From 64777ff1eba7620d4fa6b948e278573972d18d40 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 17 Jul 2024 15:22:05 +0200 Subject: [PATCH 01/80] Add EthApiTypes with error as AT and helper traits for conversion from EthApiError --- bin/reth/Cargo.toml | 1 - crates/node/builder/src/builder/mod.rs | 1 - crates/node/core/Cargo.toml | 1 - crates/optimism/node/Cargo.toml | 1 - crates/optimism/rpc/Cargo.toml | 1 - crates/optimism/rpc/src/error.rs | 58 ++++- crates/rpc/rpc-eth-api/Cargo.toml | 1 - crates/rpc/rpc-eth-api/src/core.rs | 234 +++++++++++++----- crates/rpc/rpc-eth-api/src/helpers/block.rs | 94 ++++--- .../rpc-eth-api/src/helpers/blocking_task.rs | 14 +- crates/rpc/rpc-eth-api/src/helpers/call.rs | 145 ++++++----- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 53 ++-- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 42 ++-- .../rpc-eth-api/src/helpers/pending_block.rs | 55 ++-- crates/rpc/rpc-eth-api/src/helpers/receipt.rs | 17 +- crates/rpc/rpc-eth-api/src/helpers/state.rs | 82 +++--- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 76 +++--- .../rpc-eth-api/src/helpers/transaction.rs | 131 ++++++---- crates/rpc/rpc-eth-api/src/lib.rs | 5 +- crates/rpc/rpc-eth-types/Cargo.toml | 11 - crates/rpc/rpc-eth-types/src/error.rs | 115 ++++----- crates/rpc/rpc/Cargo.toml | 1 - examples/custom-payload-builder/src/main.rs | 2 +- 23 files changed, 703 insertions(+), 438 deletions(-) diff --git a/bin/reth/Cargo.toml b/bin/reth/Cargo.toml index d67436121e7c..c41be3e25e9a 100644 --- a/bin/reth/Cargo.toml +++ b/bin/reth/Cargo.toml @@ -142,7 +142,6 @@ optimism = [ "reth-blockchain-tree/optimism", "dep:reth-node-optimism", "reth-node-core/optimism", - "reth-rpc-eth-types/optimism", ] # no-op feature flag for switching between the `optimism` and default functionality in CI matrices diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index f3c8889ea348..9b17be4dcff1 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -340,7 +340,6 @@ where self, ) -> WithLaunchContext, CB, AO>> where - CB: NodeComponentsBuilder>, AO: NodeAddOns, CB::Components>>, { WithLaunchContext { diff --git a/crates/node/core/Cargo.toml b/crates/node/core/Cargo.toml index 42673c13e0e4..2cf342bcf9c6 100644 --- a/crates/node/core/Cargo.toml +++ b/crates/node/core/Cargo.toml @@ -102,7 +102,6 @@ optimism = [ "reth-provider/optimism", "reth-rpc-types-compat/optimism", "reth-rpc-eth-api/optimism", - "reth-rpc-eth-types/optimism", ] jemalloc = ["dep:tikv-jemalloc-ctl"] diff --git a/crates/optimism/node/Cargo.toml b/crates/optimism/node/Cargo.toml index ddbc4916671c..0b163a571bfb 100644 --- a/crates/optimism/node/Cargo.toml +++ b/crates/optimism/node/Cargo.toml @@ -80,7 +80,6 @@ optimism = [ "reth-beacon-consensus/optimism", "reth-revm/optimism", "reth-auto-seal-consensus/optimism", - "reth-rpc-eth-types/optimism", "reth-optimism-rpc/optimism" ] test-utils = ["reth-node-builder/test-utils"] diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 26d1ab5779b8..8a7d6a135f37 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -59,6 +59,5 @@ optimism = [ "reth-primitives/optimism", "reth-provider/optimism", "reth-rpc-eth-api/optimism", - "reth-rpc-eth-types/optimism", "revm/optimism" ] \ No newline at end of file diff --git a/crates/optimism/rpc/src/error.rs b/crates/optimism/rpc/src/error.rs index 7b7d3bed92fa..7dd7fc5e789a 100644 --- a/crates/optimism/rpc/src/error.rs +++ b/crates/optimism/rpc/src/error.rs @@ -1,6 +1,8 @@ //! RPC errors specific to OP. use jsonrpsee::types::ErrorObject; +use reth_primitives::revm_primitives::InvalidTransaction; +use reth_rpc_eth_api::AsEthApiError; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::result::internal_rpc_err; use reth_rpc_types::ToRpcError; @@ -8,12 +10,18 @@ use reth_rpc_types::ToRpcError; /// Optimism specific errors, that extend [`EthApiError`]. #[derive(Debug, thiserror::Error)] pub enum OpEthApiError { + /// L1 ethereum error. + #[error(transparent)] + Core(#[from] EthApiError), /// Thrown when calculating L1 gas fee. #[error("failed to calculate l1 gas fee")] L1BlockFeeError, /// Thrown when calculating L1 gas used #[error("failed to calculate l1 gas used")] L1BlockGasError, + /// Wrapper for [`revm_primitives::InvalidTransaction`](InvalidTransaction). + #[error(transparent)] + InvalidTransaction(OptimismInvalidTransactionError), } impl ToRpcError for OpEthApiError { @@ -24,8 +32,52 @@ impl ToRpcError for OpEthApiError { } } -impl From for EthApiError { - fn from(err: OpEthApiError) -> Self { - Self::other(err) +impl From for OpEthApiError { + fn from(err: InvalidTransaction) -> Self { + match err { + InvalidTransaction::DepositSystemTxPostRegolith | + InvalidTransaction::HaltedDepositPostRegolith => Self::InvalidTransaction(err.into()), + _ => expect!("should cover all network specific match arms"), + } + } +} + +impl AsEthApiError for OpEthApiError { + fn as_err(&self) -> Option<&EthApiError> { + match self { + Self::Core(err) => Some(err), + _ => None, + } + } +} + +/// Optimism specific invalid transaction errors +#[derive(thiserror::Error, Debug)] +pub enum OptimismInvalidTransactionError { + /// A deposit transaction was submitted as a system transaction post-regolith. + #[error("no system transactions allowed after regolith")] + DepositSystemTxPostRegolith, + /// A deposit transaction halted post-regolith + #[error("deposit transaction halted after regolith")] + HaltedDepositPostRegolith, +} + +impl ToRpcError for OptimismInvalidTransactionError { + fn to_rpc_error(&self) -> jsonrpsee_types::error::ErrorObject<'static> { + match self { + Self::DepositSystemTxPostRegolith | Self::HaltedDepositPostRegolith => { + rpc_err(EthRpcErrorCode::TransactionRejected.code(), self.to_string(), None) + } + } + } +} + +impl From for OptimismInvalidTransactionError { + fn from(err: InvalidTransaction) -> Self { + match err { + InvalidTransaction::DepositSystemTxPostRegolith => Self::DepositSystemTxPostRegolith, + InvalidTransaction::HaltedDepositPostRegolith => Self::HaltedDepositPostRegolith, + _ => expect!("should cover all network specific match arms"), + } } } diff --git a/crates/rpc/rpc-eth-api/Cargo.toml b/crates/rpc/rpc-eth-api/Cargo.toml index b1295d69e5f6..82f13b82a897 100644 --- a/crates/rpc/rpc-eth-api/Cargo.toml +++ b/crates/rpc/rpc-eth-api/Cargo.toml @@ -53,5 +53,4 @@ optimism = [ "reth-primitives/optimism", "revm/optimism", "reth-provider/optimism", - "reth-rpc-eth-types/optimism" ] diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 3ba0a59e1000..dcfd34e1c4f4 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -3,14 +3,17 @@ use alloy_dyn_abi::TypedData; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64}; +use reth_primitives::{ + revm_primitives, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, +}; +use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; use reth_rpc_types::{ serde_helpers::JsonStorageKey, state::{EvmOverrides, StateOverride}, AccessListWithGasUsed, AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, RichBlock, - StateContext, SyncStatus, Transaction, TransactionRequest, Work, + StateContext, SyncStatus, ToRpcError, Transaction, TransactionRequest, Work, }; use tracing::trace; @@ -19,16 +22,99 @@ use crate::helpers::{ EthTransactions, FullEthApi, }; +/// Network specific `eth` API types. +pub trait EthApiTypes: Send + 'static { + /// Extension of [`EthApiError`], with network specific errors. + type Error: ToRpcError + FromEthApiError + AsEthApiError + FromEvmError; +} + +/// Helper trait to wrap core [`EthApiError`]. +pub trait FromEthApiError: From { + /// Converts from error via [`EthApiError`]. + fn from_err(err: E) -> Self + where + EthApiError: From; +} + +impl FromEthApiError for T +where + T: From, +{ + fn from_err(err: E) -> Self + where + EthApiError: From, + { + Into::::into(Into::::into(err)) + } +} + +/// Helper trait to wrap core [`EthApiError`]. +pub trait IntoEthApiError: Into { + /// Converts into error via [`EthApiError`]. + fn into_err(self) -> E + where + E: FromEthApiError; +} + +impl IntoEthApiError for T +where + T: Into, +{ + fn into_err(self) -> E + where + E: FromEthApiError, + { + Into::::into(Into::::into(self)) + } +} + +/// Helper trait to access wrapped core error. +pub trait AsEthApiError { + /// Returns reference to [`EthApiError`], if this an error variant inherited from core + /// functionality. + fn as_err(&self) -> Option<&EthApiError>; + + /// Returns `true` if error is + /// [`RpcInvalidTransactionError::GasTooHigh`](reth_rpc_eth_types::RpcInvalidTransactionError::GasTooHigh). + fn is_gas_too_high(&self) -> bool { + if let Some(err) = self.as_err() { + return err.is_gas_too_high() + } + + false + } +} + +/// Helper trait to convert from revm errors. +pub trait FromEvmError: From + From { + /// Converts from a revm error. + fn from_evm_err(err: revm_primitives::EVMError) -> Self + where + EthApiError: From, + { + match EthApiError::try_from(err) { + Ok(err) => err.into(), // error inherited from l1 + Err(err) => Self::from(err), // l2 specific error + } + } +} + /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. -pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +pub trait FullEthApiServer: + EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone +{ +} -impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +impl FullEthApiServer for EthApi where + EthApi: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone +{ +} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi { +pub trait EthApi { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; @@ -328,9 +414,10 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer for T +impl EthApiServer for T where - Self: FullEthApi, + Self: FullEthApi, + T: EthApiTypes, { /// Handler for: `eth_protocolVersion` async fn protocol_version(&self) -> RpcResult { @@ -372,7 +459,7 @@ where /// Handler for: `eth_getBlockByHash` async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); - Ok(EthBlocks::rpc_block(self, hash.into(), full).await?) + EthBlocks::rpc_block(self, hash.into(), full).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getBlockByNumber` @@ -382,13 +469,16 @@ where full: bool, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); - Ok(EthBlocks::rpc_block(self, number.into(), full).await?) + EthBlocks::rpc_block(self, number.into(), full).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getBlockTransactionCountByHash` async fn block_transaction_count_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getBlockTransactionCountByHash"); - Ok(EthBlocks::block_transaction_count(self, hash.into()).await?.map(U256::from)) + Ok(EthBlocks::block_transaction_count(self, hash.into()) + .await + .map_err(|err| err.to_rpc_error())? + .map(U256::from)) } /// Handler for: `eth_getBlockTransactionCountByNumber` @@ -397,13 +487,18 @@ where number: BlockNumberOrTag, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, "Serving eth_getBlockTransactionCountByNumber"); - Ok(EthBlocks::block_transaction_count(self, number.into()).await?.map(U256::from)) + Ok(EthBlocks::block_transaction_count(self, number.into()) + .await + .map_err(|err| err.to_rpc_error())? + .map(U256::from)) } /// Handler for: `eth_getUncleCountByBlockHash` async fn block_uncles_count_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getUncleCountByBlockHash"); - Ok(EthBlocks::ommers(self, hash.into())?.map(|ommers| U256::from(ommers.len()))) + Ok(EthBlocks::ommers(self, hash.into()) + .map_err(|err| err.to_rpc_error())? + .map(|ommers| U256::from(ommers.len()))) } /// Handler for: `eth_getUncleCountByBlockNumber` @@ -412,7 +507,9 @@ where number: BlockNumberOrTag, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, "Serving eth_getUncleCountByBlockNumber"); - Ok(EthBlocks::ommers(self, number.into())?.map(|ommers| U256::from(ommers.len()))) + Ok(EthBlocks::ommers(self, number.into()) + .map_err(|err| err.to_rpc_error())? + .map(|ommers| U256::from(ommers.len()))) } /// Handler for: `eth_getBlockReceipts` @@ -421,7 +518,7 @@ where block_id: BlockId, ) -> RpcResult>> { trace!(target: "rpc::eth", ?block_id, "Serving eth_getBlockReceipts"); - Ok(EthBlocks::block_receipts(self, block_id).await?) + EthBlocks::block_receipts(self, block_id).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getUncleByBlockHashAndIndex` @@ -431,7 +528,9 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); - Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?) + EthBlocks::ommer_by_block_and_index(self, hash.into(), index) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getUncleByBlockNumberAndIndex` @@ -441,19 +540,24 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); - Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?) + EthBlocks::ommer_by_block_and_index(self, number.into(), index) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getRawTransactionByHash` async fn raw_transaction_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getRawTransactionByHash"); - Ok(EthTransactions::raw_transaction_by_hash(self, hash).await?) + EthTransactions::raw_transaction_by_hash(self, hash).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getTransactionByHash` async fn transaction_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); - Ok(EthTransactions::transaction_by_hash(self, hash).await?.map(Into::into)) + Ok(EthTransactions::transaction_by_hash(self, hash) + .await + .map_err(|err| err.to_rpc_error())? + .map(Into::into)) } /// Handler for: `eth_getRawTransactionByBlockHashAndIndex` @@ -463,8 +567,9 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getRawTransactionByBlockHashAndIndex"); - Ok(EthTransactions::raw_transaction_by_block_and_tx_index(self, hash.into(), index.into()) - .await?) + EthTransactions::raw_transaction_by_block_and_tx_index(self, hash.into(), index.into()) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getTransactionByBlockHashAndIndex` @@ -474,8 +579,9 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); - Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) - .await?) + EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getRawTransactionByBlockNumberAndIndex` @@ -485,12 +591,9 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getRawTransactionByBlockNumberAndIndex"); - Ok(EthTransactions::raw_transaction_by_block_and_tx_index( - self, - number.into(), - index.into(), - ) - .await?) + EthTransactions::raw_transaction_by_block_and_tx_index(self, number.into(), index.into()) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getTransactionByBlockNumberAndIndex` @@ -500,20 +603,21 @@ where index: Index, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); - Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) - .await?) + EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getTransactionReceipt` async fn transaction_receipt(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionReceipt"); - Ok(EthTransactions::transaction_receipt(self, hash).await?) + EthTransactions::transaction_receipt(self, hash).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getBalance` async fn balance(&self, address: Address, block_number: Option) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getBalance"); - Ok(EthState::balance(self, address, block_number).await?) + EthState::balance(self, address, block_number).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getStorageAt` @@ -524,8 +628,9 @@ where block_number: Option, ) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getStorageAt"); - let res: B256 = EthState::storage_at(self, address, index, block_number).await?; - Ok(res) + EthState::storage_at(self, address, index, block_number) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getTransactionCount` @@ -535,25 +640,29 @@ where block_number: Option, ) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getTransactionCount"); - Ok(EthState::transaction_count(self, address, block_number).await?) + EthState::transaction_count(self, address, block_number) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getCode` async fn get_code(&self, address: Address, block_number: Option) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getCode"); - Ok(EthState::get_code(self, address, block_number).await?) + EthState::get_code(self, address, block_number).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getHeaderByNumber` async fn header_by_number(&self, block_number: BlockNumberOrTag) -> RpcResult> { trace!(target: "rpc::eth", ?block_number, "Serving eth_getHeaderByNumber"); - Ok(EthBlocks::rpc_block_header(self, block_number.into()).await?) + EthBlocks::rpc_block_header(self, block_number.into()) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getHeaderByHash` async fn header_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getHeaderByHash"); - Ok(EthBlocks::rpc_block_header(self, hash.into()).await?) + EthBlocks::rpc_block_header(self, hash.into()).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_call` @@ -565,13 +674,14 @@ where block_overrides: Option>, ) -> RpcResult { trace!(target: "rpc::eth", ?request, ?block_number, ?state_overrides, ?block_overrides, "Serving eth_call"); - Ok(EthCall::call( + EthCall::call( self, request, block_number, EvmOverrides::new(state_overrides, block_overrides), ) - .await?) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_callMany` @@ -582,7 +692,9 @@ where state_override: Option, ) -> RpcResult> { trace!(target: "rpc::eth", ?bundle, ?state_context, ?state_override, "Serving eth_callMany"); - Ok(EthCall::call_many(self, bundle, state_context, state_override).await?) + EthCall::call_many(self, bundle, state_context, state_override) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_createAccessList` @@ -592,8 +704,9 @@ where block_number: Option, ) -> RpcResult { trace!(target: "rpc::eth", ?request, ?block_number, "Serving eth_createAccessList"); - let access_list_with_gas_used = - EthCall::create_access_list_at(self, request, block_number).await?; + let access_list_with_gas_used = EthCall::create_access_list_at(self, request, block_number) + .await + .map_err(|err| err.to_rpc_error())?; Ok(access_list_with_gas_used) } @@ -606,31 +719,27 @@ where state_override: Option, ) -> RpcResult { trace!(target: "rpc::eth", ?request, ?block_number, "Serving eth_estimateGas"); - Ok(EthCall::estimate_gas_at( - self, - request, - block_number.unwrap_or_default(), - state_override, - ) - .await?) + EthCall::estimate_gas_at(self, request, block_number.unwrap_or_default(), state_override) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_gasPrice` async fn gas_price(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_gasPrice"); - return Ok(EthFees::gas_price(self).await?) + EthFees::gas_price(self).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_maxPriorityFeePerGas` async fn max_priority_fee_per_gas(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_maxPriorityFeePerGas"); - return Ok(EthFees::suggested_priority_fee(self).await?) + EthFees::suggested_priority_fee(self).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_blobBaseFee` async fn blob_base_fee(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_blobBaseFee"); - return Ok(EthFees::blob_base_fee(self).await?) + EthFees::::blob_base_fee(self).await.map_err(|err| err.to_rpc_error()) } // FeeHistory is calculated based on lazy evaluation of fees for historical blocks, and further @@ -649,9 +758,9 @@ where reward_percentiles: Option>, ) -> RpcResult { trace!(target: "rpc::eth", ?block_count, ?newest_block, ?reward_percentiles, "Serving eth_feeHistory"); - return Ok( - EthFees::fee_history(self, block_count.to(), newest_block, reward_percentiles).await? - ) + EthFees::fee_history(self, block_count.to(), newest_block, reward_percentiles) + .await + .map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_mining` @@ -687,19 +796,19 @@ where /// Handler for: `eth_sendTransaction` async fn send_transaction(&self, request: TransactionRequest) -> RpcResult { trace!(target: "rpc::eth", ?request, "Serving eth_sendTransaction"); - Ok(EthTransactions::send_transaction(self, request).await?) + EthTransactions::send_transaction(self, request).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_sendRawTransaction` async fn send_raw_transaction(&self, tx: Bytes) -> RpcResult { trace!(target: "rpc::eth", ?tx, "Serving eth_sendRawTransaction"); - Ok(EthTransactions::send_raw_transaction(self, tx).await?) + EthTransactions::send_raw_transaction(self, tx).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_sign` async fn sign(&self, address: Address, message: Bytes) -> RpcResult { trace!(target: "rpc::eth", ?address, ?message, "Serving eth_sign"); - Ok(EthTransactions::sign(self, address, message).await?) + EthTransactions::sign(self, address, message).await.map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_signTransaction` @@ -710,7 +819,7 @@ where /// Handler for: `eth_signTypedData` async fn sign_typed_data(&self, address: Address, data: TypedData) -> RpcResult { trace!(target: "rpc::eth", ?address, ?data, "Serving eth_signTypedData"); - Ok(EthTransactions::sign_typed_data(self, &data, address)?) + EthTransactions::sign_typed_data(self, &data, address).map_err(|err| err.to_rpc_error()) } /// Handler for: `eth_getProof` @@ -721,6 +830,9 @@ where block_number: Option, ) -> RpcResult { trace!(target: "rpc::eth", ?address, ?keys, ?block_number, "Serving eth_getProof"); - Ok(EthState::get_proof(self, address, keys, block_number)?.await?) + EthState::get_proof(self, address, keys, block_number) + .map_err(|err| err.to_rpc_error())? + .await + .map_err(|err| err.to_rpc_error()) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 78f1ef9da66b..0d09872849b9 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -5,15 +5,17 @@ use std::sync::Arc; use futures::Future; use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, TransactionMeta}; use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_types::{EthApiError, EthResult, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, RichBlock}; use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; +use crate::{EthApiTypes, FromEthApiError}; + use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; /// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthBlocks: LoadBlock { +pub trait EthBlocks: LoadBlock { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -23,9 +25,9 @@ pub trait EthBlocks: LoadBlock { fn rpc_block_header( &self, block_id: BlockId, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -38,9 +40,9 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { let block = match self.block_with_senders(block_id).await? { @@ -49,10 +51,11 @@ pub trait EthBlocks: LoadBlock { }; let block_hash = block.hash(); let total_difficulty = EthBlocks::provider(self) - .header_td_by_number(block.number)? + .header_td_by_number(block.number) + .map_err(T::Error::from_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = - from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash))?; + let block = from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) + .map_err(T::Error::from_err)?; Ok(Some(block.into())) } } @@ -63,19 +66,30 @@ pub trait EthBlocks: LoadBlock { fn block_transaction_count( &self, block_id: BlockId, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { if block_id.is_pending() { // Pending block can be fetched directly without need for caching - return Ok(LoadBlock::provider(self).pending_block()?.map(|block| block.body.len())) + return Ok(LoadBlock::provider(self) + .pending_block() + .map_err(T::Error::from_err)? + .map(|block| block.body.len())) } - let block_hash = match LoadBlock::provider(self).block_hash_for_id(block_id)? { + let block_hash = match LoadBlock::provider(self) + .block_hash_for_id(block_id) + .map_err(T::Error::from_err)? + { Some(block_hash) => block_hash, None => return Ok(None), }; - Ok(self.cache().get_block_transactions(block_hash).await?.map(|txs| txs.len())) + Ok(self + .cache() + .get_block_transactions(block_hash) + .await + .map_err(T::Error::from_err)? + .map(|txs| txs.len())) } } @@ -85,9 +99,9 @@ pub trait EthBlocks: LoadBlock { fn block_receipts( &self, block_id: BlockId, - ) -> impl Future>>> + Send + ) -> impl Future>, T::Error>> + Send where - Self: LoadReceipt, + Self: LoadReceipt, { async move { if let Some((block, receipts)) = self.load_block_and_receipts(block_id).await? { @@ -116,8 +130,9 @@ pub trait EthBlocks: LoadBlock { ReceiptBuilder::new(&tx, meta, receipt, &receipts) .map(|builder| builder.build()) + .map_err(T::Error::from_err) }) - .collect::>>(); + .collect::, T::Error>>(); return receipts.map(Some) } @@ -129,19 +144,25 @@ pub trait EthBlocks: LoadBlock { fn load_block_and_receipts( &self, block_id: BlockId, - ) -> impl Future>)>>> + Send + ) -> impl Future>)>, T::Error>> + Send where - Self: LoadReceipt, + Self: LoadReceipt, { async move { if block_id.is_pending() { return Ok(LoadBlock::provider(self) - .pending_block_and_receipts()? + .pending_block_and_receipts() + .map_err(T::Error::from_err)? .map(|(sb, receipts)| (sb, Arc::new(receipts)))) } - if let Some(block_hash) = LoadBlock::provider(self).block_hash_for_id(block_id)? { - return Ok(LoadReceipt::cache(self).get_block_and_receipts(block_hash).await?) + if let Some(block_hash) = + LoadBlock::provider(self).block_hash_for_id(block_id).map_err(T::Error::from_err)? + { + return LoadReceipt::cache(self) + .get_block_and_receipts(block_hash) + .await + .map_err(T::Error::from_err) } Ok(None) @@ -151,8 +172,8 @@ pub trait EthBlocks: LoadBlock { /// Returns uncle headers of given block. /// /// Returns an empty vec if there are none. - fn ommers(&self, block_id: BlockId) -> EthResult>> { - Ok(LoadBlock::provider(self).ommers_by_id(block_id)?) + fn ommers(&self, block_id: BlockId) -> Result>, T::Error> { + LoadBlock::provider(self).ommers_by_id(block_id).map_err(T::Error::from_err) } /// Returns uncle block at given index in given block. @@ -162,13 +183,16 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching - LoadBlock::provider(self).pending_block()?.map(|block| block.ommers) + LoadBlock::provider(self) + .pending_block() + .map_err(T::Error::from_err)? + .map(|block| block.ommers) } else { - LoadBlock::provider(self).ommers_by_id(block_id)? + LoadBlock::provider(self).ommers_by_id(block_id).map_err(T::Error::from_err)? } .unwrap_or_default(); @@ -183,7 +207,7 @@ pub trait EthBlocks: LoadBlock { /// Loads a block from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` blocks RPC methods. -pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { +pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { // Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -198,7 +222,7 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { fn block( &self, block_id: BlockId, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { self.block_with_senders(block_id) .await @@ -210,12 +234,13 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { fn block_with_senders( &self, block_id: BlockId, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { if block_id.is_pending() { // Pending block can be fetched directly without need for caching - let maybe_pending = - LoadPendingBlock::provider(self).pending_block_with_senders()?; + let maybe_pending = LoadPendingBlock::provider(self) + .pending_block_with_senders() + .map_err(T::Error::from_err)?; return if maybe_pending.is_some() { Ok(maybe_pending) } else { @@ -223,12 +248,15 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { } } - let block_hash = match LoadPendingBlock::provider(self).block_hash_for_id(block_id)? { + let block_hash = match LoadPendingBlock::provider(self) + .block_hash_for_id(block_id) + .map_err(T::Error::from_err)? + { Some(block_hash) => block_hash, None => return Ok(None), }; - Ok(self.cache().get_sealed_block_with_senders(block_hash).await?) + self.cache().get_sealed_block_with_senders(block_hash).await.map_err(T::Error::from_err) } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs b/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs index 4a2c81b0fdfe..82b2a2a8dbaa 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs @@ -2,12 +2,14 @@ //! are executed on the `tokio` runtime. use futures::Future; -use reth_rpc_eth_types::{EthApiError, EthResult}; +use reth_rpc_eth_types::EthApiError; use reth_tasks::{pool::BlockingTaskPool, TaskSpawner}; use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit}; +use crate::EthApiTypes; + /// Executes code on a blocking thread. -pub trait SpawnBlocking: Clone + Send + Sync + 'static { +pub trait SpawnBlocking: Clone + Send + Sync + 'static { /// Returns a handle for spawning IO heavy blocking tasks. /// /// Runtime access in default trait method implementations. @@ -33,9 +35,9 @@ pub trait SpawnBlocking: Clone + Send + Sync + 'static { /// /// Note: This is expected for futures that are dominated by blocking IO operations, for tracing /// or CPU bound operations in general use [`spawn_tracing`](Self::spawn_tracing). - fn spawn_blocking_io(&self, f: F) -> impl Future> + Send + fn spawn_blocking_io(&self, f: F) -> impl Future> + Send where - F: FnOnce(Self) -> EthResult + Send + 'static, + F: FnOnce(Self) -> Result + Send + 'static, R: Send + 'static, { let (tx, rx) = oneshot::channel(); @@ -53,9 +55,9 @@ pub trait SpawnBlocking: Clone + Send + Sync + 'static { /// Note: This is expected for futures that are predominantly CPU bound, as it uses `rayon` /// under the hood, for blocking IO futures use [`spawn_blocking`](Self::spawn_blocking_io). See /// . - fn spawn_tracing(&self, f: F) -> impl Future> + Send + fn spawn_tracing(&self, f: F) -> impl Future> + Send where - F: FnOnce(Self) -> EthResult + Send + 'static, + F: FnOnce(Self) -> Result + Send + 'static, R: Send + 'static, { let this = self.clone(); diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index a8fc6d8e2305..2e8f1fee15f7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -19,7 +19,7 @@ use reth_rpc_eth_types::{ apply_block_overrides, apply_state_overrides, caller_gas_allowance, cap_tx_gas_limit_with_caller_allowance, get_precompiles, CallFees, }, - EthApiError, EthResult, RevertError, RpcInvalidTransactionError, StateCacheDb, + EthApiError, RevertError, RpcInvalidTransactionError, StateCacheDb, }; use reth_rpc_server_types::constants::gas_oracle::{ESTIMATE_GAS_ERROR_RATIO, MIN_TRANSACTION_GAS}; use reth_rpc_types::{ @@ -31,18 +31,20 @@ use revm::{Database, DatabaseCommit}; use revm_inspectors::access_list::AccessListInspector; use tracing::trace; +use crate::{AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError}; + use super::{LoadBlock, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocking, Trace}; /// Execution related functions for the [`EthApiServer`](crate::EthApiServer) trait in /// the `eth_` namespace. -pub trait EthCall: Call + LoadPendingBlock { +pub trait EthCall: Call + LoadPendingBlock { /// Estimate gas needed for execution of the `request` at the [`BlockId`]. fn estimate_gas_at( &self, request: TransactionRequest, at: BlockId, state_override: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { Call::estimate_gas_at(self, request, at, state_override) } @@ -52,12 +54,12 @@ pub trait EthCall: Call + LoadPendingBlock { request: TransactionRequest, block_number: Option, overrides: EvmOverrides, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { let (res, _env) = self.transact_call_at(request, block_number.unwrap_or_default(), overrides).await?; - ensure_success(res.result) + ensure_success(res.result).map_err(T::Error::from_err) } } @@ -68,14 +70,16 @@ pub trait EthCall: Call + LoadPendingBlock { bundle: Bundle, state_context: Option, mut state_override: Option, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { let Bundle { transactions, block_override } = bundle; if transactions.is_empty() { - return Err(EthApiError::InvalidParams(String::from("transactions are empty."))) + return Err( + EthApiError::InvalidParams(String::from("transactions are empty.")).into() + ) } let StateContext { transaction_index, block_number } = @@ -90,7 +94,7 @@ pub trait EthCall: Call + LoadPendingBlock { self.block_with_senders(target_block) )?; - let Some(block) = block else { return Err(EthApiError::UnknownBlockNumber) }; + let Some(block) = block else { return Err(EthApiError::UnknownBlockNumber.into()) }; let gas_limit = self.call_gas_limit(); // we're essentially replaying the transactions in the block here, hence we need the @@ -136,14 +140,16 @@ pub trait EthCall: Call + LoadPendingBlock { let state_overrides = state_override.take(); let overrides = EvmOverrides::new(state_overrides, block_overrides.clone()); - let env = this.prepare_call_env( - cfg.clone(), - block_env.clone(), - tx, - gas_limit, - &mut db, - overrides, - )?; + let env = this + .prepare_call_env( + cfg.clone(), + block_env.clone(), + tx, + gas_limit, + &mut db, + overrides, + ) + .map(Into::into)?; let (res, _) = this.transact(&mut db, env)?; match ensure_success(res.result) { @@ -177,9 +183,9 @@ pub trait EthCall: Call + LoadPendingBlock { &self, request: TransactionRequest, block_number: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: Trace, + Self: Trace, { async move { let block_id = block_number.unwrap_or_default(); @@ -200,9 +206,9 @@ pub trait EthCall: Call + LoadPendingBlock { block: BlockEnv, at: BlockId, mut request: TransactionRequest, - ) -> EthResult + ) -> Result where - Self: Trace, + Self: Trace, { let state = self.state_at_block_id(at)?; @@ -228,7 +234,7 @@ pub trait EthCall: Call + LoadPendingBlock { let to = if let Some(TxKind::Call(to)) = request.to { to } else { - let nonce = db.basic_ref(from)?.unwrap_or_default().nonce; + let nonce = db.basic_ref(from).map_err(T::Error::from_err)?.unwrap_or_default().nonce; from.create(nonce) }; @@ -248,7 +254,8 @@ pub trait EthCall: Call + LoadPendingBlock { Err(RpcInvalidTransactionError::Revert(RevertError::new(output))) } ExecutionResult::Success { .. } => Ok(()), - }?; + } + .map_err(T::Error::from_err)?; let access_list = inspector.into_access_list(); @@ -265,7 +272,7 @@ pub trait EthCall: Call + LoadPendingBlock { } /// Executes code on state. -pub trait Call: LoadState + SpawnBlocking { +pub trait Call: LoadState + SpawnBlocking { /// Returns default gas limit to use for `eth_call` and tracing RPC methods. /// /// Data access in default trait method implementations. @@ -277,9 +284,9 @@ pub trait Call: LoadState + SpawnBlocking { fn evm_config(&self) -> &impl ConfigureEvm; /// Executes the closure with the state that corresponds to the given [`BlockId`]. - fn with_state_at_block(&self, at: BlockId, f: F) -> EthResult + fn with_state_at_block(&self, at: BlockId, f: F) -> Result where - F: FnOnce(StateProviderTraitObjWrapper<'_>) -> EthResult, + F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result, { let state = self.state_at_block_id(at)?; f(StateProviderTraitObjWrapper(&state)) @@ -291,13 +298,13 @@ pub trait Call: LoadState + SpawnBlocking { &self, db: DB, env: EnvWithHandlerCfg, - ) -> EthResult<(ResultAndState, EnvWithHandlerCfg)> + ) -> Result<(ResultAndState, EnvWithHandlerCfg), T::Error> where DB: Database, - ::Error: Into, + EthApiError: From, { let mut evm = self.evm_config().evm_with_env(db, env); - let res = evm.transact()?; + let res = evm.transact().map_err(T::Error::from_evm_err)?; let (_, env) = evm.into_db_and_env_with_handler_cfg(); Ok((res, env)) } @@ -308,23 +315,23 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, at: BlockId, overrides: EvmOverrides, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, + Self: LoadPendingBlock, { let this = self.clone(); self.spawn_with_call_at(request, at, overrides, move |db, env| this.transact(db, env)) } /// Executes the closure with the state that corresponds to the given [`BlockId`] on a new task - fn spawn_with_state_at_block( + fn spawn_with_state_at_block( &self, at: BlockId, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - F: FnOnce(StateProviderTraitObjWrapper<'_>) -> EthResult + Send + 'static, - T: Send + 'static, + F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result + Send + 'static, + R: Send + 'static, { self.spawn_tracing(move |this| { let state = this.state_at_block_id(at)?; @@ -343,10 +350,10 @@ pub trait Call: LoadState + SpawnBlocking { at: BlockId, overrides: EvmOverrides, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, - F: FnOnce(StateCacheDbRefMutWrapper<'_, '_>, EnvWithHandlerCfg) -> EthResult + Self: LoadPendingBlock, + F: FnOnce(StateCacheDbRefMutWrapper<'_, '_>, EnvWithHandlerCfg) -> Result + Send + 'static, R: Send + 'static, @@ -371,7 +378,7 @@ pub trait Call: LoadState + SpawnBlocking { f(StateCacheDbRefMutWrapper(&mut db), env) }) .await - .map_err(|_| EthApiError::InternalBlockingTaskError) + .map_err(|_| EthApiError::InternalBlockingTaskError.into()) } } @@ -388,10 +395,10 @@ pub trait Call: LoadState + SpawnBlocking { &self, hash: B256, f: F, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadBlock + LoadPendingBlock + LoadTransaction, - F: FnOnce(TransactionInfo, ResultAndState, StateCacheDb<'_>) -> EthResult + Self: LoadBlock + LoadPendingBlock + LoadTransaction, + F: FnOnce(TransactionInfo, ResultAndState, StateCacheDb<'_>) -> Result + Send + 'static, R: Send + 'static, @@ -451,10 +458,10 @@ pub trait Call: LoadState + SpawnBlocking { block_env: BlockEnv, transactions: impl IntoIterator, target_tx_hash: B256, - ) -> Result + ) -> Result where DB: DatabaseRef, - EthApiError: From<::Error>, + EthApiError: From, { let env = EnvWithHandlerCfg::new_with_cfg_env(cfg, block_env, Default::default()); @@ -468,7 +475,7 @@ pub trait Call: LoadState + SpawnBlocking { let sender = tx.signer(); self.evm_config().fill_tx_env(evm.tx_mut(), &tx.into_signed(), sender); - evm.transact_commit()?; + evm.transact_commit().map_err(T::Error::from_evm_err)?; index += 1; } Ok(index) @@ -480,9 +487,9 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, at: BlockId, state_override: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, + Self: LoadPendingBlock, { async move { let (cfg, block_env, at) = self.evm_env_at(at).await?; @@ -505,7 +512,7 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, state: S, state_override: Option, - ) -> EthResult + ) -> Result where S: StateProvider, { @@ -535,7 +542,7 @@ pub trait Call: LoadState + SpawnBlocking { // Apply any state overrides if specified. if let Some(state_override) = state_override { - apply_state_overrides(state_override, &mut db)?; + apply_state_overrides(state_override, &mut db).map_err(T::Error::from_err)?; } // Optimize for simple transfer transactions, potentially reducing the gas estimate. @@ -566,7 +573,8 @@ pub trait Call: LoadState + SpawnBlocking { // The caller allowance is check by doing `(account.balance - tx.value) / tx.gas_price` if env.tx.gas_price > U256::ZERO { // cap the highest gas limit by max gas caller can afford with given gas price - highest_gas_limit = highest_gas_limit.min(caller_gas_allowance(&mut db, &env.tx)?); + highest_gas_limit = highest_gas_limit + .min(caller_gas_allowance(&mut db, &env.tx).map_err(T::Error::from_err)?); } // We can now normalize the highest gas limit to a u64 @@ -584,8 +592,9 @@ pub trait Call: LoadState + SpawnBlocking { // If the gas price or gas limit was specified in the request, retry the transaction // with the block's gas limit to determine if the failure was due to // insufficient gas. - Err(EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh)) - if tx_request_gas_limit.is_some() || tx_request_gas_price.is_some() => + Err(err) + if err.is_gas_too_high() && + (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) => { return Err(self.map_out_of_gas_err(block_env_gas_limit, env, &mut db)) } @@ -598,7 +607,7 @@ pub trait Call: LoadState + SpawnBlocking { ExecutionResult::Halt { reason, gas_used } => { // here we don't check for invalid opcode because already executed with highest gas // limit - return Err(RpcInvalidTransactionError::halt(reason, gas_used).into()) + return Err(RpcInvalidTransactionError::halt(reason, gas_used).into_err()) } ExecutionResult::Revert { output, .. } => { // if price or limit was included in the request then we can execute the request @@ -607,7 +616,7 @@ pub trait Call: LoadState + SpawnBlocking { Err(self.map_out_of_gas_err(block_env_gas_limit, env, &mut db)) } else { // the transaction did revert - Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into()) + Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into_err()) } } }; @@ -669,8 +678,7 @@ pub trait Call: LoadState + SpawnBlocking { // Execute transaction and handle potential gas errors, adjusting limits accordingly. match self.transact(&mut db, env.clone()) { - // Check if the error is due to gas being too high. - Err(EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh)) => { + Err(err) if err.is_gas_too_high() => { // Increase the lowest gas limit if gas is too high lowest_gas_limit = mid_gas_limit; } @@ -707,7 +715,7 @@ pub trait Call: LoadState + SpawnBlocking { tx_gas_limit: u64, highest_gas_limit: &mut u64, lowest_gas_limit: &mut u64, - ) -> EthResult<()> { + ) -> Result<(), T::Error> { match result { ExecutionResult::Success { .. } => { // Cap the highest gas limit with the succeeding gas limit. @@ -735,7 +743,7 @@ pub trait Call: LoadState + SpawnBlocking { // These cases should be unreachable because we know the transaction // succeeds, but if they occur, treat them as an // error. - return Err(RpcInvalidTransactionError::EvmHalt(err).into()) + return Err(RpcInvalidTransactionError::EvmHalt(err).into_err()) } } } @@ -752,7 +760,7 @@ pub trait Call: LoadState + SpawnBlocking { env_gas_limit: U256, mut env: EnvWithHandlerCfg, db: &mut CacheDB>, - ) -> EthApiError + ) -> T::Error where S: StateProvider, { @@ -766,14 +774,14 @@ pub trait Call: LoadState + SpawnBlocking { ExecutionResult::Success { .. } => { // transaction succeeded by manually increasing the gas limit to // highest, which means the caller lacks funds to pay for the tx - RpcInvalidTransactionError::BasicOutOfGas(req_gas_limit).into() + RpcInvalidTransactionError::BasicOutOfGas(req_gas_limit).into_err() } ExecutionResult::Revert { output, .. } => { // reverted again after bumping the limit - RpcInvalidTransactionError::Revert(RevertError::new(output)).into() + RpcInvalidTransactionError::Revert(RevertError::new(output)).into_err() } ExecutionResult::Halt { reason, .. } => { - RpcInvalidTransactionError::EvmHalt(reason).into() + RpcInvalidTransactionError::EvmHalt(reason).into_err() } } } @@ -786,10 +794,10 @@ pub trait Call: LoadState + SpawnBlocking { &self, block_env: &BlockEnv, request: TransactionRequest, - ) -> EthResult { + ) -> Result { // Ensure that if versioned hashes are set, they're not empty if request.blob_versioned_hashes.as_ref().map_or(false, |hashes| hashes.is_empty()) { - return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()) + return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_err()) } let TransactionRequest { @@ -827,14 +835,15 @@ pub trait Call: LoadState + SpawnBlocking { let env = TxEnv { gas_limit: gas_limit .try_into() - .map_err(|_| RpcInvalidTransactionError::GasUintOverflow)?, + .map_err(|_| RpcInvalidTransactionError::GasUintOverflow) + .map_err(T::Error::from_err)?, nonce, caller: from.unwrap_or_default(), gas_price, gas_priority_fee: max_priority_fee_per_gas, transact_to: to.unwrap_or(TxKind::Create), value: value.unwrap_or_default(), - data: input.try_into_unique_input()?.unwrap_or_default(), + data: input.try_into_unique_input().map_err(T::Error::from_err)?.unwrap_or_default(), chain_id, access_list: access_list.unwrap_or_default().into(), // EIP-4844 fields @@ -857,7 +866,7 @@ pub trait Call: LoadState + SpawnBlocking { cfg: CfgEnvWithHandlerCfg, block: BlockEnv, request: TransactionRequest, - ) -> EthResult { + ) -> Result { let tx = self.create_txn_env(&block, request)?; Ok(EnvWithHandlerCfg::new_with_cfg_env(cfg, block, tx)) } @@ -879,7 +888,7 @@ pub trait Call: LoadState + SpawnBlocking { gas_limit: u64, db: &mut CacheDB, overrides: EvmOverrides, - ) -> EthResult + ) -> Result where DB: DatabaseRef, EthApiError: From<::Error>, diff --git a/crates/rpc/rpc-eth-api/src/helpers/fee.rs b/crates/rpc/rpc-eth-api/src/helpers/fee.rs index 54c577ea2504..6cd533ec7cd1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/fee.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/fee.rs @@ -4,37 +4,39 @@ use futures::Future; use reth_primitives::U256; use reth_provider::{BlockIdReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider}; use reth_rpc_eth_types::{ - fee_history::calculate_reward_percentiles_for_block, EthApiError, EthResult, EthStateCache, + fee_history::calculate_reward_percentiles_for_block, EthApiError, EthStateCache, FeeHistoryCache, FeeHistoryEntry, GasPriceOracle, RpcInvalidTransactionError, }; use reth_rpc_types::{BlockNumberOrTag, FeeHistory}; use tracing::debug; +use crate::{EthApiTypes, FromEthApiError}; + use super::LoadBlock; /// Fee related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthFees: LoadFee { +pub trait EthFees: LoadFee { /// Returns a suggestion for a gas price for legacy transactions. /// /// See also: - fn gas_price(&self) -> impl Future> + Send + fn gas_price(&self) -> impl Future> + Send where - Self: LoadBlock, + Self: LoadBlock, { LoadFee::gas_price(self) } /// Returns a suggestion for a base fee for blob transactions. - fn blob_base_fee(&self) -> impl Future> + Send + fn blob_base_fee(&self) -> impl Future> + Send where - Self: LoadBlock, + Self: LoadBlock, { LoadFee::blob_base_fee(self) } /// Returns a suggestion for the priority fee (the tip) - fn suggested_priority_fee(&self) -> impl Future> + Send + fn suggested_priority_fee(&self) -> impl Future> + Send where Self: 'static, { @@ -50,7 +52,7 @@ pub trait EthFees: LoadFee { mut block_count: u64, newest_block: BlockNumberOrTag, reward_percentiles: Option>, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { if block_count == 0 { return Ok(FeeHistory::default()) @@ -72,10 +74,11 @@ pub trait EthFees: LoadFee { block_count = max_fee_history } - let Some(end_block) = - LoadFee::provider(self).block_number_for_id(newest_block.into())? + let Some(end_block) = LoadFee::provider(self) + .block_number_for_id(newest_block.into()) + .map_err(T::Error::from_err)? else { - return Err(EthApiError::UnknownBlockNumber) + return Err(EthApiError::UnknownBlockNumber.into()) }; // need to add 1 to the end block to get the correct (inclusive) range @@ -91,7 +94,7 @@ pub trait EthFees: LoadFee { // Note: The types used ensure that the percentiles are never < 0 if let Some(percentiles) = &reward_percentiles { if percentiles.windows(2).any(|w| w[0] > w[1] || w[0] > 100.) { - return Err(EthApiError::InvalidRewardPercentiles) + return Err(EthApiError::InvalidRewardPercentiles.into()) } } @@ -116,7 +119,7 @@ pub trait EthFees: LoadFee { if let Some(fee_entries) = fee_entries { if fee_entries.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange) + return Err(EthApiError::InvalidBlockRange.into()) } for entry in &fee_entries { @@ -144,9 +147,9 @@ pub trait EthFees: LoadFee { base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default()); } else { // read the requested header range - let headers = LoadFee::provider(self).sealed_headers_range(start_block..=end_block)?; + let headers = LoadFee::provider(self).sealed_headers_range(start_block..=end_block).map_err(T::Error::from_err)?; if headers.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange) + return Err(EthApiError::InvalidBlockRange.into()) } for header in &headers { @@ -162,7 +165,7 @@ pub trait EthFees: LoadFee { if let Some(percentiles) = &reward_percentiles { let (transactions, receipts) = LoadFee::cache(self) .get_transactions_and_receipts(header.hash()) - .await? + .await.map_err(T::Error::from_err)? .ok_or(EthApiError::InvalidBlockRange)?; rewards.push( calculate_reward_percentiles_for_block( @@ -225,7 +228,7 @@ pub trait EthFees: LoadFee { /// Loads fee from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` fees RPC methods. -pub trait LoadFee: LoadBlock { +pub trait LoadFee: LoadBlock { // Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -251,7 +254,7 @@ pub trait LoadFee: LoadBlock { fn legacy_gas_price( &self, gas_price: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { match gas_price { Some(gas_price) => Ok(gas_price), @@ -271,7 +274,7 @@ pub trait LoadFee: LoadBlock { &self, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { let max_fee_per_gas = match max_fee_per_gas { Some(max_fee_per_gas) => max_fee_per_gas, @@ -303,7 +306,7 @@ pub trait LoadFee: LoadBlock { fn eip4844_blob_fee( &self, blob_fee: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { match blob_fee { Some(blob_fee) => Ok(blob_fee), @@ -315,7 +318,7 @@ pub trait LoadFee: LoadBlock { /// Returns a suggestion for a gas price for legacy transactions. /// /// See also: - fn gas_price(&self) -> impl Future> + Send { + fn gas_price(&self) -> impl Future> + Send { let header = self.block(BlockNumberOrTag::Latest.into()); let suggested_tip = self.suggested_priority_fee(); async move { @@ -326,21 +329,21 @@ pub trait LoadFee: LoadBlock { } /// Returns a suggestion for a base fee for blob transactions. - fn blob_base_fee(&self) -> impl Future> + Send { + fn blob_base_fee(&self) -> impl Future> + Send { async move { self.block(BlockNumberOrTag::Latest.into()) .await? .and_then(|h: reth_primitives::SealedBlock| h.next_block_blob_fee()) - .ok_or(EthApiError::ExcessBlobGasNotSet) + .ok_or(EthApiError::ExcessBlobGasNotSet.into()) .map(U256::from) } } /// Returns a suggestion for the priority fee (the tip) - fn suggested_priority_fee(&self) -> impl Future> + Send + fn suggested_priority_fee(&self) -> impl Future> + Send where Self: 'static, { - self.gas_oracle().suggest_tip_cap() + async move { self.gas_oracle().suggest_tip_cap().await.map_err(T::Error::from_err) } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index b82a621acaf4..cff28bdd8ac8 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -38,30 +38,44 @@ pub use state::{EthState, LoadState}; pub use trace::Trace; pub use transaction::{EthTransactions, LoadTransaction, UpdateRawTxForwarder}; +use crate::EthApiTypes; + /// Extension trait that bundles traits needed for tracing transactions. -pub trait TraceExt: - LoadTransaction + LoadBlock + LoadPendingBlock + SpawnBlocking + Trace + Call +pub trait TraceExt: + LoadTransaction + LoadBlock + LoadPendingBlock + SpawnBlocking + Trace + Call { } -impl TraceExt for T where T: LoadTransaction + LoadBlock + LoadPendingBlock + Trace + Call {} +impl TraceExt for T where + T: LoadTransaction + LoadBlock + LoadPendingBlock + Trace + Call +{ +} /// Helper trait to unify all `eth` rpc server building block traits, for simplicity. /// /// This trait is automatically implemented for any type that implements all the `Eth` traits. -pub trait FullEthApi: - EthApiSpec + EthTransactions + EthBlocks + EthState + EthCall + EthFees + Trace + LoadReceipt +pub trait FullEthApi: + EthApiSpec + + EthTransactions + + EthBlocks + + EthState + + EthCall + + EthFees + + Trace + + LoadReceipt { } -impl FullEthApi for T where - T: EthApiSpec - + EthTransactions - + EthBlocks - + EthState - + EthCall - + EthFees - + Trace - + LoadReceipt +impl FullEthApi for EthApi +where + T: EthApiTypes, + EthApi: EthApiSpec + + EthTransactions + + EthBlocks + + EthState + + EthCall + + EthFees + + Trace + + LoadReceipt, { } diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index a17fbb43f2fe..42534d83213c 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -19,27 +19,30 @@ use reth_primitives::{ EMPTY_OMMER_ROOT_HASH, U256, }; use reth_provider::{ - BlockReader, BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProviderFactory, + BlockReader, BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, ProviderError, + StateProviderFactory, }; use reth_revm::{ database::StateProviderDatabase, state_change::post_block_withdrawals_balance_increments, }; use reth_rpc_eth_types::{ - pending_block::pre_block_blockhashes_update, EthApiError, EthResult, PendingBlock, - PendingBlockEnv, PendingBlockEnvOrigin, + pending_block::pre_block_blockhashes_update, EthApiError, PendingBlock, PendingBlockEnv, + PendingBlockEnvOrigin, }; use reth_transaction_pool::{BestTransactionsAttributes, TransactionPool}; use revm::{db::states::bundle_state::BundleRetention, DatabaseCommit, State}; use tokio::sync::Mutex; use tracing::debug; +use crate::{EthApiTypes, FromEthApiError, FromEvmError}; + use super::SpawnBlocking; /// Loads a pending block from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` blocks RPC methods. #[auto_impl::auto_impl(&, Arc)] -pub trait LoadPendingBlock { +pub trait LoadPendingBlock { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -65,16 +68,19 @@ pub trait LoadPendingBlock { /// Configures the [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the pending block /// /// If no pending block is available, this will derive it from the `latest` block - fn pending_block_env_and_cfg(&self) -> EthResult { + fn pending_block_env_and_cfg(&self) -> Result { let origin: PendingBlockEnvOrigin = if let Some(pending) = - self.provider().pending_block_with_senders()? + self.provider().pending_block_with_senders().map_err(T::Error::from_err)? { PendingBlockEnvOrigin::ActualPending(pending) } else { // no pending block from the CL yet, so we use the latest block and modify the env // values that we can - let latest = - self.provider().latest_header()?.ok_or_else(|| EthApiError::UnknownBlockNumber)?; + let latest = self + .provider() + .latest_header() + .map_err(T::Error::from_err)? + .ok_or_else(|| EthApiError::UnknownBlockNumber)?; let (mut latest_header, block_hash) = latest.split(); // child block @@ -102,12 +108,14 @@ pub trait LoadPendingBlock { let mut block_env = BlockEnv::default(); // Note: for the PENDING block we assume it is past the known merge block and thus this will // not fail when looking up the total difficulty value for the blockenv. - self.provider().fill_env_with_header( - &mut cfg, - &mut block_env, - origin.header(), - self.evm_config().clone(), - )?; + self.provider() + .fill_env_with_header( + &mut cfg, + &mut block_env, + origin.header(), + self.evm_config().clone(), + ) + .map_err(T::Error::from_err)?; Ok(PendingBlockEnv::new(cfg, block_env, origin)) } @@ -115,9 +123,9 @@ pub trait LoadPendingBlock { /// Returns the locally built pending block fn local_pending_block( &self, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: SpawnBlocking, + Self: SpawnBlocking, { async move { let pending = self.pending_block_env_and_cfg()?; @@ -197,11 +205,15 @@ pub trait LoadPendingBlock { /// /// After Cancun, if the origin is the actual pending block, the block includes the EIP-4788 pre /// block contract call using the parent beacon block root received from the CL. - fn build_block(&self, env: PendingBlockEnv) -> EthResult { + fn build_block(&self, env: PendingBlockEnv) -> Result + where + EthApiError: From, + { let PendingBlockEnv { cfg, block_env, origin } = env; let parent_hash = origin.build_target_hash(); - let state_provider = self.provider().history_by_block_hash(parent_hash)?; + let state_provider = + self.provider().history_by_block_hash(parent_hash).map_err(T::Error::from_err)?; let state = StateProviderDatabase::new(state_provider); let mut db = State::builder().with_database(state).with_bundle_update().build(); @@ -316,7 +328,7 @@ pub trait LoadPendingBlock { } err => { // this is an error that we should treat as fatal for this attempt - return Err(err.into()) + return Err(T::Error::from_evm_err(err)) } } } @@ -359,7 +371,7 @@ pub trait LoadPendingBlock { ); // increment account balances for withdrawals - db.increment_balances(balance_increments)?; + db.increment_balances(balance_increments).map_err(T::Error::from_err)?; // merge all transitions into bundle state. db.merge_transitions(BundleRetention::PlainState); @@ -378,7 +390,8 @@ pub trait LoadPendingBlock { // calculate the state root let state_provider = &db.database; - let state_root = state_provider.state_root(execution_outcome.state())?; + let state_root = + state_provider.state_root(execution_outcome.state()).map_err(T::Error::from_err)?; // create the block header let transactions_root = calculate_transaction_root(&executed_txs); diff --git a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs index 5cd6c03c4d9f..03b57491fad0 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs @@ -3,14 +3,16 @@ use futures::Future; use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; -use reth_rpc_eth_types::{EthApiError, EthResult, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::AnyTransactionReceipt; +use crate::{EthApiTypes, FromEthApiError}; + /// Assembles transaction receipt data w.r.t to network. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` receipts RPC methods. #[auto_impl::auto_impl(&, Arc)] -pub trait LoadReceipt: Send + Sync { +pub trait LoadReceipt: Send + Sync { /// Returns a handle for reading data from memory. /// /// Data access in default (L1) trait method implementations. @@ -22,12 +24,17 @@ pub trait LoadReceipt: Send + Sync { tx: TransactionSigned, meta: TransactionMeta, receipt: Receipt, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { // get all receipts for the block - let all_receipts = match self.cache().get_receipts(meta.block_hash).await? { + let all_receipts = match self + .cache() + .get_receipts(meta.block_hash) + .await + .map_err(T::Error::from_err)? + { Some(recpts) => recpts, - None => return Err(EthApiError::UnknownBlockNumber), + None => return Err(EthApiError::UnknownBlockNumber.into()), }; Ok(ReceiptBuilder::new(&tx, meta, &receipt, &all_receipts)?.build()) diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index 0da2a49c3b18..db30265d6df2 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -8,19 +8,19 @@ use reth_primitives::{Address, BlockId, Bytes, Header, B256, U256}; use reth_provider::{ BlockIdReader, ChainSpecProvider, StateProvider, StateProviderBox, StateProviderFactory, }; -use reth_rpc_eth_types::{ - EthApiError, EthResult, EthStateCache, PendingBlockEnv, RpcInvalidTransactionError, -}; +use reth_rpc_eth_types::{EthApiError, EthStateCache, PendingBlockEnv, RpcInvalidTransactionError}; use reth_rpc_types::{serde_helpers::JsonStorageKey, EIP1186AccountProofResponse}; use reth_rpc_types_compat::proof::from_primitive_account_proof; use reth_transaction_pool::{PoolTransaction, TransactionPool}; use revm::db::BundleState; use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg, SpecId}; +use crate::{EthApiTypes, FromEthApiError}; + use super::{EthApiSpec, LoadPendingBlock, SpawnBlocking}; /// Helper methods for `eth_` methods relating to state (accounts). -pub trait EthState: LoadState + SpawnBlocking { +pub trait EthState: LoadState + SpawnBlocking { /// Returns the maximum number of blocks into the past for generating state proofs. fn max_proof_window(&self) -> u64; @@ -32,7 +32,7 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { LoadState::transaction_count(self, address, block_id) } @@ -41,11 +41,12 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(this .state_at_block_id_or_latest(block_id)? - .account_code(address)? + .account_code(address) + .map_err(T::Error::from_err)? .unwrap_or_default() .original_bytes()) }) @@ -56,11 +57,12 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(this .state_at_block_id_or_latest(block_id)? - .account_balance(address)? + .account_balance(address) + .map_err(T::Error::from_err)? .unwrap_or_default()) }) } @@ -71,11 +73,12 @@ pub trait EthState: LoadState + SpawnBlocking { address: Address, index: JsonStorageKey, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(B256::new( this.state_at_block_id_or_latest(block_id)? - .storage(address, index.0)? + .storage(address, index.0) + .map_err(T::Error::from_err)? .unwrap_or_default() .to_be_bytes(), )) @@ -88,21 +91,22 @@ pub trait EthState: LoadState + SpawnBlocking { address: Address, keys: Vec, block_id: Option, - ) -> EthResult> + Send> + ) -> Result> + Send, T::Error> where Self: EthApiSpec, { - let chain_info = self.chain_info()?; + let chain_info = self.chain_info().map_err(T::Error::from_err)?; let block_id = block_id.unwrap_or_default(); // Check whether the distance to the block exceeds the maximum configured window. let block_number = self .provider() - .block_number_for_id(block_id)? + .block_number_for_id(block_id) + .map_err(T::Error::from_err)? .ok_or(EthApiError::UnknownBlockNumber)?; let max_window = self.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { - return Err(EthApiError::ExceedsMaxProofWindow) + return Err(EthApiError::ExceedsMaxProofWindow.into()) } Ok(async move { @@ -113,7 +117,9 @@ pub trait EthState: LoadState + SpawnBlocking { self.spawn_blocking_io(move |this| { let state = this.state_at_block_id(block_id)?; let storage_keys = keys.iter().map(|key| key.0).collect::>(); - let proof = state.proof(&BundleState::default(), address, &storage_keys)?; + let proof = state + .proof(&BundleState::default(), address, &storage_keys) + .map_err(T::Error::from_err)?; Ok(from_primitive_account_proof(proof)) }) .await @@ -124,7 +130,7 @@ pub trait EthState: LoadState + SpawnBlocking { /// Loads state from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` state RPC methods. -pub trait LoadState { +pub trait LoadState { /// Returns a handle for reading state from database. /// /// Data access in default trait method implementations. @@ -141,21 +147,21 @@ pub trait LoadState { fn pool(&self) -> impl TransactionPool; /// Returns the state at the given block number - fn state_at_hash(&self, block_hash: B256) -> EthResult { - Ok(self.provider().history_by_block_hash(block_hash)?) + fn state_at_hash(&self, block_hash: B256) -> Result { + self.provider().history_by_block_hash(block_hash).map_err(T::Error::from_err) } /// Returns the state at the given [`BlockId`] enum. /// /// Note: if not [`BlockNumberOrTag::Pending`](reth_primitives::BlockNumberOrTag) then this /// will only return canonical state. See also - fn state_at_block_id(&self, at: BlockId) -> EthResult { - Ok(self.provider().state_by_block_id(at)?) + fn state_at_block_id(&self, at: BlockId) -> Result { + self.provider().state_by_block_id(at).map_err(T::Error::from_err) } /// Returns the _latest_ state - fn latest_state(&self) -> EthResult { - Ok(self.provider().latest()?) + fn latest_state(&self) -> Result { + self.provider().latest().map_err(T::Error::from_err) } /// Returns the state at the given [`BlockId`] enum or the latest. @@ -164,7 +170,7 @@ pub trait LoadState { fn state_at_block_id_or_latest( &self, block_id: Option, - ) -> EthResult { + ) -> Result { if let Some(block_id) = block_id { self.state_at_block_id(block_id) } else { @@ -181,9 +187,9 @@ pub trait LoadState { fn evm_env_at( &self, at: BlockId, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { if at.is_pending() { @@ -193,9 +199,11 @@ pub trait LoadState { } else { // Use cached values if there is no pending block let block_hash = LoadPendingBlock::provider(self) - .block_hash_for_id(at)? + .block_hash_for_id(at) + .map_err(T::Error::from_err)? .ok_or_else(|| EthApiError::UnknownBlockNumber)?; - let (cfg, env) = self.cache().get_evm_env(block_hash).await?; + let (cfg, env) = + self.cache().get_evm_env(block_hash).await.map_err(T::Error::from_err)?; Ok((cfg, env, block_hash.into())) } } @@ -207,9 +215,9 @@ pub trait LoadState { fn evm_env_for_raw_block( &self, header: &Header, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { // get the parent config first @@ -230,9 +238,9 @@ pub trait LoadState { &self, address: Address, block_id: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: SpawnBlocking, + Self: SpawnBlocking, { self.spawn_blocking_io(move |this| { if block_id == Some(BlockId::pending()) { @@ -240,15 +248,17 @@ pub trait LoadState { if let Some(highest_nonce) = address_txs.iter().map(|item| item.transaction.nonce()).max() { - let tx_count = highest_nonce - .checked_add(1) - .ok_or(RpcInvalidTransactionError::NonceMaxValue)?; + let tx_count = highest_nonce.checked_add(1).ok_or(T::Error::from( + EthApiError::InvalidTransaction(RpcInvalidTransactionError::NonceMaxValue), + ))?; return Ok(U256::from(tx_count)) } } let state = this.state_at_block_id_or_latest(block_id)?; - Ok(U256::from(state.account_nonce(address)?.unwrap_or_default())) + Ok(U256::from( + state.account_nonce(address).map_err(T::Error::from_err)?.unwrap_or_default(), + )) }) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index d48e566ed51d..06c6f3349288 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -6,17 +6,19 @@ use reth_primitives::B256; use reth_revm::database::StateProviderDatabase; use reth_rpc_eth_types::{ cache::db::{StateCacheDb, StateCacheDbRefMutWrapper, StateProviderTraitObjWrapper}, - EthApiError, EthResult, + EthApiError, }; use reth_rpc_types::{BlockId, TransactionInfo}; use revm::{db::CacheDB, Database, DatabaseCommit, GetInspector, Inspector}; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use revm_primitives::{EnvWithHandlerCfg, EvmState, ExecutionResult, ResultAndState}; +use crate::{EthApiTypes, FromEvmError}; + use super::{Call, LoadBlock, LoadPendingBlock, LoadState, LoadTransaction}; /// Executes CPU heavy tasks. -pub trait Trace: LoadState { +pub trait Trace: LoadState { /// Returns a handle for reading evm config. /// /// Data access in default (L1) trait method implementations. @@ -29,10 +31,10 @@ pub trait Trace: LoadState { db: DB, env: EnvWithHandlerCfg, inspector: I, - ) -> EthResult<(ResultAndState, EnvWithHandlerCfg)> + ) -> Result<(ResultAndState, EnvWithHandlerCfg), T::Error> where DB: Database, - ::Error: Into, + EthApiError: From, I: GetInspector, { self.inspect_and_return_db(db, env, inspector).map(|(res, env, _)| (res, env)) @@ -48,14 +50,14 @@ pub trait Trace: LoadState { db: DB, env: EnvWithHandlerCfg, inspector: I, - ) -> EthResult<(ResultAndState, EnvWithHandlerCfg, DB)> + ) -> Result<(ResultAndState, EnvWithHandlerCfg, DB), T::Error> where DB: Database, - ::Error: Into, + EthApiError: From, I: GetInspector, { let mut evm = self.evm_config().evm_with_env_and_inspector(db, env, inspector); - let res = evm.transact()?; + let res = evm.transact().map_err(T::Error::from_evm_err)?; let (db, env) = evm.into_db_and_env_with_handler_cfg(); Ok((res, env, db)) } @@ -73,10 +75,10 @@ pub trait Trace: LoadState { config: TracingInspectorConfig, at: BlockId, f: F, - ) -> EthResult + ) -> Result where - Self: Call, - F: FnOnce(TracingInspector, ResultAndState) -> EthResult, + Self: Call, + F: FnOnce(TracingInspector, ResultAndState) -> Result, { self.with_state_at_block(at, |state| { let mut db = CacheDB::new(StateProviderDatabase::new(state)); @@ -99,10 +101,10 @@ pub trait Trace: LoadState { config: TracingInspectorConfig, at: BlockId, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + Call, - F: FnOnce(TracingInspector, ResultAndState, StateCacheDb<'_>) -> EthResult + Self: LoadPendingBlock + Call, + F: FnOnce(TracingInspector, ResultAndState, StateCacheDb<'_>) -> Result + Send + 'static, R: Send + 'static, @@ -130,15 +132,15 @@ pub trait Trace: LoadState { hash: B256, config: TracingInspectorConfig, f: F, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadPendingBlock + LoadTransaction + Call, + Self: LoadPendingBlock + LoadTransaction + Call, F: FnOnce( TransactionInfo, TracingInspector, ResultAndState, StateCacheDb<'_>, - ) -> EthResult + ) -> Result + Send + 'static, R: Send + 'static, @@ -160,10 +162,10 @@ pub trait Trace: LoadState { hash: B256, mut inspector: Insp, f: F, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadPendingBlock + LoadTransaction + Call, - F: FnOnce(TransactionInfo, Insp, ResultAndState, StateCacheDb<'_>) -> EthResult + Self: LoadPendingBlock + LoadTransaction + Call, + F: FnOnce(TransactionInfo, Insp, ResultAndState, StateCacheDb<'_>) -> Result + Send + 'static, Insp: for<'a, 'b> Inspector> + Send + 'static, @@ -222,16 +224,16 @@ pub trait Trace: LoadState { highest_index: Option, config: TracingInspectorConfig, f: F, - ) -> impl Future>>> + Send + ) -> impl Future>, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, F: Fn( TransactionInfo, TracingInspector, ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> EthResult + ) -> Result + Send + 'static, R: Send + 'static, @@ -260,10 +262,16 @@ pub trait Trace: LoadState { highest_index: Option, mut inspector_setup: Setup, f: F, - ) -> impl Future>>> + Send + ) -> impl Future>, T::Error>> + Send where - Self: LoadBlock, - F: Fn(TransactionInfo, Insp, ExecutionResult, &EvmState, &StateCacheDb<'_>) -> EthResult + Self: LoadBlock, + F: Fn( + TransactionInfo, + Insp, + ExecutionResult, + &EvmState, + &StateCacheDb<'_>, + ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, @@ -360,9 +368,9 @@ pub trait Trace: LoadState { block_id: BlockId, config: TracingInspectorConfig, f: F, - ) -> impl Future>>> + Send + ) -> impl Future>, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, // This is the callback that's invoked for each transaction with the inspector, the result, // state and db F: Fn( @@ -371,7 +379,7 @@ pub trait Trace: LoadState { ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> EthResult + ) -> Result + Send + 'static, R: Send + 'static, @@ -398,12 +406,18 @@ pub trait Trace: LoadState { block_id: BlockId, insp_setup: Setup, f: F, - ) -> impl Future>>> + Send + ) -> impl Future>, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, // This is the callback that's invoked for each transaction with the inspector, the result, // state and db - F: Fn(TransactionInfo, Insp, ExecutionResult, &EvmState, &StateCacheDb<'_>) -> EthResult + F: Fn( + TransactionInfo, + Insp, + ExecutionResult, + &EvmState, + &StateCacheDb<'_>, + ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index fa4c9be30787..c2fe60f9eb28 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -24,9 +24,11 @@ use reth_rpc_types::{ use reth_rpc_types_compat::transaction::from_recovered_with_block_context; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; -use super::EthSigner; +use crate::{EthApiTypes, FromEthApiError, IntoEthApiError}; -use super::{Call, EthApiSpec, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking}; +use super::{ + Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking, +}; /// Transaction related functions for the [`EthApiServer`](crate::EthApiServer) trait in /// the `eth_` namespace. @@ -51,7 +53,7 @@ use super::{Call, EthApiSpec, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, /// See also /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. -pub trait EthTransactions: LoadTransaction { +pub trait EthTransactions: LoadTransaction { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -75,7 +77,7 @@ pub trait EthTransactions: LoadTransaction { fn transaction_by_hash( &self, hash: B256, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { LoadTransaction::transaction_by_hash(self, hash) } @@ -85,8 +87,8 @@ pub trait EthTransactions: LoadTransaction { fn transactions_by_block( &self, block: B256, - ) -> impl Future>>> + Send { - async move { Ok(self.cache().get_block_transactions(block).await?) } + ) -> impl Future>, T::Error>> + Send { + async move { self.cache().get_block_transactions(block).await.map_err(T::Error::from_err) } } /// Returns the EIP-2718 encoded transaction by hash. @@ -99,7 +101,7 @@ pub trait EthTransactions: LoadTransaction { fn raw_transaction_by_hash( &self, hash: B256, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { // Note: this is mostly used to fetch pooled transactions so we check the pool first if let Some(tx) = @@ -110,7 +112,8 @@ pub trait EthTransactions: LoadTransaction { self.spawn_blocking_io(move |ref this| { Ok(LoadTransaction::provider(this) - .transaction_by_hash(hash)? + .transaction_by_hash(hash) + .map_err(T::Error::from_err)? .map(|tx| tx.envelope_encoded())) }) .await @@ -121,7 +124,7 @@ pub trait EthTransactions: LoadTransaction { fn historical_transaction_by_hash_at( &self, hash: B256, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { match self.transaction_by_hash_at(hash).await? { None => Ok(None), @@ -137,9 +140,9 @@ pub trait EthTransactions: LoadTransaction { fn transaction_receipt( &self, hash: B256, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadReceipt + 'static, + Self: LoadReceipt + 'static, { async move { let result = self.load_transaction_and_receipt(hash).await?; @@ -157,19 +160,25 @@ pub trait EthTransactions: LoadTransaction { fn load_transaction_and_receipt( &self, hash: TxHash, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + + Send where Self: 'static, { let this = self.clone(); self.spawn_blocking_io(move |_| { - let (tx, meta) = - match LoadTransaction::provider(&this).transaction_by_hash_with_meta(hash)? { - Some((tx, meta)) => (tx, meta), - None => return Ok(None), - }; + let (tx, meta) = match LoadTransaction::provider(&this) + .transaction_by_hash_with_meta(hash) + .map_err(T::Error::from_err)? + { + Some((tx, meta)) => (tx, meta), + None => return Ok(None), + }; - let receipt = match EthTransactions::provider(&this).receipt_by_hash(hash)? { + let receipt = match EthTransactions::provider(&this) + .receipt_by_hash(hash) + .map_err(T::Error::from_err)? + { Some(recpt) => recpt, None => return Ok(None), }; @@ -185,9 +194,9 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { if let Some(block) = self.block_with_senders(block_id).await? { @@ -216,9 +225,9 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { if let Some(block) = self.block_with_senders(block_id).await? { @@ -234,7 +243,10 @@ pub trait EthTransactions: LoadTransaction { /// Decodes and recovers the transaction and submits it to the pool. /// /// Returns the hash of the transaction. - fn send_raw_transaction(&self, tx: Bytes) -> impl Future> + Send { + fn send_raw_transaction( + &self, + tx: Bytes, + ) -> impl Future> + Send { async move { // On optimism, transactions are forwarded directly to the sequencer to be included in // blocks that it builds. @@ -250,8 +262,11 @@ pub trait EthTransactions: LoadTransaction { ); // submit the transaction to the pool with a `Local` origin - let hash = - self.pool().add_transaction(TransactionOrigin::Local, pool_transaction).await?; + let hash = self + .pool() + .add_transaction(TransactionOrigin::Local, pool_transaction) + .await + .map_err(T::Error::from_err)?; Ok(hash) } @@ -262,18 +277,18 @@ pub trait EthTransactions: LoadTransaction { fn send_transaction( &self, mut request: TransactionRequest, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: EthApiSpec + LoadBlock + LoadPendingBlock + LoadFee + Call, + Self: EthApiSpec + LoadBlock + LoadPendingBlock + LoadFee + Call, { async move { let from = match request.from { Some(from) => from, - None => return Err(SignError::NoAccount.into()), + None => return Err(SignError::NoAccount.into_err()), }; if self.find_signer(&from).is_err() { - return Err(SignError::NoAccount.into()); + return Err(SignError::NoAccount.into_err()); } // set nonce if not already set before @@ -447,7 +462,7 @@ pub trait EthTransactions: LoadTransaction { TypedTransactionRequest::EIP4844(req) } - None => return Err(EthApiError::ConflictingFeeFieldsInRequest), + None => return Err(EthApiError::ConflictingFeeFieldsInRequest.into()), }; let signed_tx = self.sign_request(&from, transaction)?; @@ -456,14 +471,15 @@ pub trait EthTransactions: LoadTransaction { signed_tx.into_ecrecovered().ok_or(EthApiError::InvalidTransactionSignature)?; let pool_transaction = match recovered.try_into() { - Ok(converted) => <::Pool as TransactionPool>::Transaction::from_recovered_pooled_transaction(converted), - Err(_) => return Err(EthApiError::TransactionConversionError), + Ok(converted) => <>::Pool as TransactionPool>::Transaction::from_recovered_pooled_transaction(converted), + Err(_) => return Err(EthApiError::TransactionConversionError.into()), }; // submit the transaction to the pool with a `Local` origin let hash = LoadTransaction::pool(self) .add_transaction(TransactionOrigin::Local, pool_transaction) - .await?; + .await + .map_err(T::Error::from_err)?; Ok(hash) } @@ -474,16 +490,16 @@ pub trait EthTransactions: LoadTransaction { &self, from: &Address, request: TypedTransactionRequest, - ) -> EthResult { + ) -> Result { for signer in self.signers().read().iter() { if signer.is_signer_for(from) { return match signer.sign_transaction(request, from) { Ok(tx) => Ok(tx), - Err(e) => Err(e.into()), + Err(e) => Err(e.into_err()), } } } - Err(EthApiError::InvalidTransactionSignature) + Err(EthApiError::InvalidTransactionSignature.into()) } /// Signs given message. Returns the signature. @@ -491,23 +507,34 @@ pub trait EthTransactions: LoadTransaction { &self, account: Address, message: Bytes, - ) -> impl Future> + Send { - async move { Ok(self.find_signer(&account)?.sign(account, &message).await?.to_hex_bytes()) } + ) -> impl Future> + Send { + async move { + Ok(self + .find_signer(&account)? + .sign(account, &message) + .await + .map_err(T::Error::from_err)? + .to_hex_bytes()) + } } /// Encodes and signs the typed data according EIP-712. Payload must implement Eip712 trait. - fn sign_typed_data(&self, data: &TypedData, account: Address) -> EthResult { - Ok(self.find_signer(&account)?.sign_typed_data(account, data)?.to_hex_bytes()) + fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result { + Ok(self + .find_signer(&account)? + .sign_typed_data(account, data) + .map_err(T::Error::from_err)? + .to_hex_bytes()) } /// Returns the signer for the given account, if found in configured signers. - fn find_signer(&self, account: &Address) -> Result, SignError> { + fn find_signer(&self, account: &Address) -> Result, T::Error> { self.signers() .read() .iter() .find(|signer| signer.is_signer_for(account)) .map(|signer| dyn_clone::clone_box(&**signer)) - .ok_or(SignError::NoAccount) + .ok_or_else(|| SignError::NoAccount.into_err()) } } @@ -515,7 +542,7 @@ pub trait EthTransactions: LoadTransaction { /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` transactions RPC /// methods. -pub trait LoadTransaction: SpawnBlocking { +pub trait LoadTransaction: SpawnBlocking { /// Transaction pool with pending transactions. [`TransactionPool::Transaction`] is the /// supported transaction type. type Pool: TransactionPool; @@ -543,12 +570,16 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_by_hash( &self, hash: B256, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { // Try to find the transaction on disk let mut resp = self .spawn_blocking_io(move |this| { - match this.provider().transaction_by_hash_with_meta(hash)? { + match this + .provider() + .transaction_by_hash_with_meta(hash) + .map_err(T::Error::from_err)? + { None => Ok(None), Some((tx, meta)) => { // Note: we assume this transaction is valid, because it's mined (or @@ -590,7 +621,7 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_by_hash_at( &self, transaction_hash: B256, - ) -> impl Future>> + Send { + ) -> impl Future, T::Error>> + Send { async move { match self.transaction_by_hash(transaction_hash).await? { None => Ok(None), @@ -625,7 +656,7 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_and_block( &self, hash: B256, - ) -> impl Future>> + Send + ) -> impl Future, T::Error>> + Send { async move { let (transaction, at) = match self.transaction_by_hash_at(hash).await? { @@ -638,7 +669,11 @@ pub trait LoadTransaction: SpawnBlocking { BlockId::Hash(hash) => hash.block_hash, _ => return Ok(None), }; - let block = self.cache().get_block_with_senders(block_hash).await?; + let block = self + .cache() + .get_block_with_senders(block_hash) + .await + .map_err(T::Error::from_err)?; Ok(block.map(|block| (transaction, block.seal(block_hash)))) } } diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 1aed94d5cc6e..37fd050bf719 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -19,7 +19,10 @@ pub mod helpers; pub mod pubsub; pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; -pub use core::{EthApiServer, FullEthApiServer}; +pub use core::{ + AsEthApiError, EthApiServer, EthApiTypes, FromEthApiError, FromEvmError, FullEthApiServer, + IntoEthApiError, +}; pub use filter::EthFilterApiServer; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-types/Cargo.toml b/crates/rpc/rpc-eth-types/Cargo.toml index b1c307191025..3fb20836e46f 100644 --- a/crates/rpc/rpc-eth-types/Cargo.toml +++ b/crates/rpc/rpc-eth-types/Cargo.toml @@ -55,14 +55,3 @@ tracing.workspace = true [dev-dependencies] serde_json.workspace = true - -[features] -optimism = [ - "reth-primitives/optimism", - "reth-provider/optimism", - "reth-revm/optimism", - "reth-chainspec/optimism", - "reth-execution-types/optimism", - "reth-revm/optimism", - "revm/optimism" -] \ No newline at end of file diff --git a/crates/rpc/rpc-eth-types/src/error.rs b/crates/rpc/rpc-eth-types/src/error.rs index 67fd11eae2c0..9713ddce169f 100644 --- a/crates/rpc/rpc-eth-types/src/error.rs +++ b/crates/rpc/rpc-eth-types/src/error.rs @@ -137,6 +137,11 @@ impl EthApiError { pub fn other(err: E) -> Self { Self::Other(Box::new(err)) } + + /// Returns `true` if error is [`RpcInvalidTransactionError::GasTooHigh`] + pub const fn is_gas_too_high(&self) -> bool { + matches!(self, Self::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh)) + } } impl From for jsonrpsee_types::error::ErrorObject<'static> { @@ -221,18 +226,20 @@ impl From for EthApiError { } } -impl From> for EthApiError +impl TryFrom> for EthApiError where T: Into, { - fn from(err: EVMError) -> Self { + type Error = revm::primitives::InvalidTransaction; + + fn try_from(err: EVMError) -> Result { match err { - EVMError::Transaction(err) => RpcInvalidTransactionError::from(err).into(), - EVMError::Header(InvalidHeader::PrevrandaoNotSet) => Self::PrevrandaoNotSet, - EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => Self::ExcessBlobGasNotSet, - EVMError::Database(err) => err.into(), - EVMError::Custom(err) => Self::EvmCustom(err), - EVMError::Precompile(err) => Self::EvmPrecompile(err), + EVMError::Transaction(err) => Ok(RpcInvalidTransactionError::try_from(err)?.into()), + EVMError::Header(InvalidHeader::PrevrandaoNotSet) => Ok(Self::PrevrandaoNotSet), + EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => Ok(Self::ExcessBlobGasNotSet), + EVMError::Database(err) => Ok(err.into()), + EVMError::Custom(err) => Ok(Self::EvmCustom(err)), + EVMError::Precompile(err) => Ok(Self::EvmPrecompile(err)), } } } @@ -381,29 +388,6 @@ impl RpcInvalidTransactionError { } } -/// Optimism specific invalid transaction errors -#[cfg(feature = "optimism")] -#[derive(thiserror::Error, Debug)] -pub enum OptimismInvalidTransactionError { - /// A deposit transaction was submitted as a system transaction post-regolith. - #[error("no system transactions allowed after regolith")] - DepositSystemTxPostRegolith, - /// A deposit transaction halted post-regolith - #[error("deposit transaction halted after regolith")] - HaltedDepositPostRegolith, -} - -#[cfg(feature = "optimism")] -impl ToRpcError for OptimismInvalidTransactionError { - fn to_rpc_error(&self) -> jsonrpsee_types::error::ErrorObject<'static> { - match self { - Self::DepositSystemTxPostRegolith | Self::HaltedDepositPostRegolith => { - rpc_err(EthRpcErrorCode::TransactionRejected.code(), self.to_string(), None) - } - } - } -} - impl RpcInvalidTransactionError { /// Returns the rpc error code for this error. const fn error_code(&self) -> i32 { @@ -455,50 +439,47 @@ impl From for jsonrpsee_types::error::ErrorObject<'s } } -impl From for RpcInvalidTransactionError { - fn from(err: revm::primitives::InvalidTransaction) -> Self { +impl TryFrom for RpcInvalidTransactionError { + type Error = revm::primitives::InvalidTransaction; + + fn try_from(err: revm::primitives::InvalidTransaction) -> Result { use revm::primitives::InvalidTransaction; match err { - InvalidTransaction::InvalidChainId => Self::InvalidChainId, - InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap, - InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow, - InvalidTransaction::CallerGasLimitMoreThanBlock => Self::GasTooHigh, - InvalidTransaction::CallGasCostMoreThanGasLimit => Self::GasTooHigh, - InvalidTransaction::RejectCallerWithCode => Self::SenderNoEOA, - InvalidTransaction::LackOfFundForMaxFee { .. } => Self::InsufficientFunds, - InvalidTransaction::OverflowPaymentInTransaction => Self::GasUintOverflow, - InvalidTransaction::NonceOverflowInTransaction => Self::NonceMaxValue, - InvalidTransaction::CreateInitCodeSizeLimit => Self::MaxInitCodeSizeExceeded, - InvalidTransaction::NonceTooHigh { .. } => Self::NonceTooHigh, - InvalidTransaction::NonceTooLow { .. } => Self::NonceTooLow, - InvalidTransaction::AccessListNotSupported => Self::AccessListNotSupported, - InvalidTransaction::MaxFeePerBlobGasNotSupported => Self::MaxFeePerBlobGasNotSupported, + InvalidTransaction::InvalidChainId => Ok(Self::InvalidChainId), + InvalidTransaction::PriorityFeeGreaterThanMaxFee => Ok(Self::TipAboveFeeCap), + InvalidTransaction::GasPriceLessThanBasefee => Ok(Self::FeeCapTooLow), + InvalidTransaction::CallerGasLimitMoreThanBlock | + InvalidTransaction::CallGasCostMoreThanGasLimit => Ok(Self::GasTooHigh), + InvalidTransaction::RejectCallerWithCode => Ok(Self::SenderNoEOA), + InvalidTransaction::LackOfFundForMaxFee { .. } => Ok(Self::InsufficientFunds), + InvalidTransaction::OverflowPaymentInTransaction => Ok(Self::GasUintOverflow), + InvalidTransaction::NonceOverflowInTransaction => Ok(Self::NonceMaxValue), + InvalidTransaction::CreateInitCodeSizeLimit => Ok(Self::MaxInitCodeSizeExceeded), + InvalidTransaction::NonceTooHigh { .. } => Ok(Self::NonceTooHigh), + InvalidTransaction::NonceTooLow { .. } => Ok(Self::NonceTooLow), + InvalidTransaction::AccessListNotSupported => Ok(Self::AccessListNotSupported), + InvalidTransaction::MaxFeePerBlobGasNotSupported => { + Ok(Self::MaxFeePerBlobGasNotSupported) + } InvalidTransaction::BlobVersionedHashesNotSupported => { - Self::BlobVersionedHashesNotSupported + Ok(Self::BlobVersionedHashesNotSupported) + } + InvalidTransaction::BlobGasPriceGreaterThanMax => Ok(Self::BlobFeeCapTooLow), + InvalidTransaction::EmptyBlobs => Ok(Self::BlobTransactionMissingBlobHashes), + InvalidTransaction::BlobVersionNotSupported => Ok(Self::BlobHashVersionMismatch), + InvalidTransaction::TooManyBlobs { max, have } => Ok(Self::TooManyBlobs { max, have }), + InvalidTransaction::BlobCreateTransaction => Ok(Self::BlobTransactionIsCreate), + InvalidTransaction::EofCrateShouldHaveToAddress => { + Ok(Self::EofCrateShouldHaveToAddress) } - InvalidTransaction::BlobGasPriceGreaterThanMax => Self::BlobFeeCapTooLow, - InvalidTransaction::EmptyBlobs => Self::BlobTransactionMissingBlobHashes, - InvalidTransaction::BlobVersionNotSupported => Self::BlobHashVersionMismatch, - InvalidTransaction::TooManyBlobs { max, have } => Self::TooManyBlobs { max, have }, - InvalidTransaction::BlobCreateTransaction => Self::BlobTransactionIsCreate, - InvalidTransaction::EofCrateShouldHaveToAddress => Self::EofCrateShouldHaveToAddress, InvalidTransaction::AuthorizationListNotSupported => { - Self::AuthorizationListNotSupported + Ok(Self::AuthorizationListNotSupported) } InvalidTransaction::AuthorizationListInvalidFields => { - Self::AuthorizationListInvalidFields + Ok(Self::AuthorizationListInvalidFields) } - #[cfg(feature = "optimism")] - InvalidTransaction::OptimismError(err) => match err { - revm_primitives::OptimismInvalidTransaction::DepositSystemTxPostRegolith => { - Self::other(OptimismInvalidTransactionError::DepositSystemTxPostRegolith) - } - revm_primitives::OptimismInvalidTransaction::HaltedDepositPostRegolith => { - Self::Other(Box::new( - OptimismInvalidTransactionError::HaltedDepositPostRegolith, - )) - } - }, + #[allow(unreachable_patterns)] + _ => Err(err), } } } diff --git a/crates/rpc/rpc/Cargo.toml b/crates/rpc/rpc/Cargo.toml index 733f218a1a7a..add677451689 100644 --- a/crates/rpc/rpc/Cargo.toml +++ b/crates/rpc/rpc/Cargo.toml @@ -92,5 +92,4 @@ optimism = [ "reth-rpc-eth-api/optimism", "reth-revm/optimism", "jsonrpsee-types", - "reth-rpc-eth-types/optimism", ] diff --git a/examples/custom-payload-builder/src/main.rs b/examples/custom-payload-builder/src/main.rs index ca636198a839..429a90c8715e 100644 --- a/examples/custom-payload-builder/src/main.rs +++ b/examples/custom-payload-builder/src/main.rs @@ -75,7 +75,7 @@ fn main() { .with_types::() // Configure the components of the node // use default ethereum components but use our custom payload builder - .with_components( + .with_components::<_, EthereumAddOns>( EthereumNode::components().payload(CustomPayloadBuilder::default()), ) .with_add_ons::() From 2f9b4d4a38b84dff16d69e58a0c34ad83d636f36 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 18 Jul 2024 16:09:57 +0200 Subject: [PATCH 02/80] Make it possible to reference EthApiTypes via EthApiServer helper traits --- crates/rpc/rpc-eth-api/src/core.rs | 19 ++--- crates/rpc/rpc-eth-api/src/helpers/block.rs | 73 +++++++++------- .../rpc-eth-api/src/helpers/blocking_task.rs | 10 +-- crates/rpc/rpc-eth-api/src/helpers/call.rs | 85 ++++++++++--------- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 38 ++++----- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 49 +++++------ .../rpc-eth-api/src/helpers/pending_block.rs | 25 +++--- crates/rpc/rpc-eth-api/src/helpers/receipt.rs | 7 +- crates/rpc/rpc-eth-api/src/helpers/state.rs | 63 +++++++------- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 63 +++++++------- .../rpc-eth-api/src/helpers/transaction.rs | 79 +++++++++-------- 11 files changed, 260 insertions(+), 251 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index dcfd34e1c4f4..65b9a3333e27 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -101,20 +101,14 @@ pub trait FromEvmError: From + From: - EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone -{ -} +pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} -impl FullEthApiServer for EthApi where - EthApi: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone -{ -} +impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi { +pub trait EthApi { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; @@ -414,10 +408,9 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer for T +impl EthApiServer for T where - Self: FullEthApi, - T: EthApiTypes, + T: FullEthApi, { /// Handler for: `eth_protocolVersion` async fn protocol_version(&self) -> RpcResult { @@ -739,7 +732,7 @@ where /// Handler for: `eth_blobBaseFee` async fn blob_base_fee(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_blobBaseFee"); - EthFees::::blob_base_fee(self).await.map_err(|err| err.to_rpc_error()) + EthFees::blob_base_fee(self).await.map_err(|err| err.to_rpc_error()) } // FeeHistory is calculated based on lazy evaluation of fees for historical blocks, and further diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 0d09872849b9..a581fad6cbf1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -9,13 +9,13 @@ use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, RichBlock}; use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; -use crate::{EthApiTypes, FromEthApiError}; +use crate::FromEthApiError; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; /// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthBlocks: LoadBlock { +pub trait EthBlocks: LoadBlock { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -25,9 +25,9 @@ pub trait EthBlocks: LoadBlock { fn rpc_block_header( &self, block_id: BlockId, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -40,9 +40,9 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { let block = match self.block_with_senders(block_id).await? { @@ -52,10 +52,10 @@ pub trait EthBlocks: LoadBlock { let block_hash = block.hash(); let total_difficulty = EthBlocks::provider(self) .header_td_by_number(block.number) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .ok_or(EthApiError::UnknownBlockNumber)?; let block = from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(Some(block.into())) } } @@ -66,19 +66,19 @@ pub trait EthBlocks: LoadBlock { fn block_transaction_count( &self, block_id: BlockId, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { if block_id.is_pending() { // Pending block can be fetched directly without need for caching return Ok(LoadBlock::provider(self) .pending_block() - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .map(|block| block.body.len())) } let block_hash = match LoadBlock::provider(self) .block_hash_for_id(block_id) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { Some(block_hash) => block_hash, None => return Ok(None), @@ -88,7 +88,7 @@ pub trait EthBlocks: LoadBlock { .cache() .get_block_transactions(block_hash) .await - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .map(|txs| txs.len())) } } @@ -99,9 +99,9 @@ pub trait EthBlocks: LoadBlock { fn block_receipts( &self, block_id: BlockId, - ) -> impl Future>, T::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadReceipt, + Self: LoadReceipt, { async move { if let Some((block, receipts)) = self.load_block_and_receipts(block_id).await? { @@ -130,9 +130,9 @@ pub trait EthBlocks: LoadBlock { ReceiptBuilder::new(&tx, meta, receipt, &receipts) .map(|builder| builder.build()) - .map_err(T::Error::from_err) + .map_err(Self::Error::from_err) }) - .collect::, T::Error>>(); + .collect::, Self::Error>>(); return receipts.map(Some) } @@ -144,25 +144,26 @@ pub trait EthBlocks: LoadBlock { fn load_block_and_receipts( &self, block_id: BlockId, - ) -> impl Future>)>, T::Error>> + Send + ) -> impl Future>)>, Self::Error>> + Send where - Self: LoadReceipt, + Self: LoadReceipt, { async move { if block_id.is_pending() { return Ok(LoadBlock::provider(self) .pending_block_and_receipts() - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .map(|(sb, receipts)| (sb, Arc::new(receipts)))) } - if let Some(block_hash) = - LoadBlock::provider(self).block_hash_for_id(block_id).map_err(T::Error::from_err)? + if let Some(block_hash) = LoadBlock::provider(self) + .block_hash_for_id(block_id) + .map_err(Self::Error::from_err)? { return LoadReceipt::cache(self) .get_block_and_receipts(block_hash) .await - .map_err(T::Error::from_err) + .map_err(Self::Error::from_err) } Ok(None) @@ -172,8 +173,11 @@ pub trait EthBlocks: LoadBlock { /// Returns uncle headers of given block. /// /// Returns an empty vec if there are none. - fn ommers(&self, block_id: BlockId) -> Result>, T::Error> { - LoadBlock::provider(self).ommers_by_id(block_id).map_err(T::Error::from_err) + fn ommers( + &self, + block_id: BlockId, + ) -> Result>, Self::Error> { + LoadBlock::provider(self).ommers_by_id(block_id).map_err(Self::Error::from_err) } /// Returns uncle block at given index in given block. @@ -183,16 +187,16 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching LoadBlock::provider(self) .pending_block() - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .map(|block| block.ommers) } else { - LoadBlock::provider(self).ommers_by_id(block_id).map_err(T::Error::from_err)? + LoadBlock::provider(self).ommers_by_id(block_id).map_err(Self::Error::from_err)? } .unwrap_or_default(); @@ -207,7 +211,7 @@ pub trait EthBlocks: LoadBlock { /// Loads a block from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` blocks RPC methods. -pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { +pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { // Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -222,7 +226,7 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { fn block( &self, block_id: BlockId, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { self.block_with_senders(block_id) .await @@ -234,13 +238,13 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { fn block_with_senders( &self, block_id: BlockId, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { if block_id.is_pending() { // Pending block can be fetched directly without need for caching let maybe_pending = LoadPendingBlock::provider(self) .pending_block_with_senders() - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; return if maybe_pending.is_some() { Ok(maybe_pending) } else { @@ -250,13 +254,16 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking { let block_hash = match LoadPendingBlock::provider(self) .block_hash_for_id(block_id) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { Some(block_hash) => block_hash, None => return Ok(None), }; - self.cache().get_sealed_block_with_senders(block_hash).await.map_err(T::Error::from_err) + self.cache() + .get_sealed_block_with_senders(block_hash) + .await + .map_err(Self::Error::from_err) } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs b/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs index 82b2a2a8dbaa..d23453b5ed83 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/blocking_task.rs @@ -9,7 +9,7 @@ use tokio::sync::{oneshot, AcquireError, OwnedSemaphorePermit}; use crate::EthApiTypes; /// Executes code on a blocking thread. -pub trait SpawnBlocking: Clone + Send + Sync + 'static { +pub trait SpawnBlocking: EthApiTypes + Clone + Send + Sync + 'static { /// Returns a handle for spawning IO heavy blocking tasks. /// /// Runtime access in default trait method implementations. @@ -35,9 +35,9 @@ pub trait SpawnBlocking: Clone + Send + Sync + 'static { /// /// Note: This is expected for futures that are dominated by blocking IO operations, for tracing /// or CPU bound operations in general use [`spawn_tracing`](Self::spawn_tracing). - fn spawn_blocking_io(&self, f: F) -> impl Future> + Send + fn spawn_blocking_io(&self, f: F) -> impl Future> + Send where - F: FnOnce(Self) -> Result + Send + 'static, + F: FnOnce(Self) -> Result + Send + 'static, R: Send + 'static, { let (tx, rx) = oneshot::channel(); @@ -55,9 +55,9 @@ pub trait SpawnBlocking: Clone + Send + Sync + 'static { /// Note: This is expected for futures that are predominantly CPU bound, as it uses `rayon` /// under the hood, for blocking IO futures use [`spawn_blocking`](Self::spawn_blocking_io). See /// . - fn spawn_tracing(&self, f: F) -> impl Future> + Send + fn spawn_tracing(&self, f: F) -> impl Future> + Send where - F: FnOnce(Self) -> Result + Send + 'static, + F: FnOnce(Self) -> Result + Send + 'static, R: Send + 'static, { let this = self.clone(); diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 2e8f1fee15f7..55737aeb9fb1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -31,20 +31,20 @@ use revm::{Database, DatabaseCommit}; use revm_inspectors::access_list::AccessListInspector; use tracing::trace; -use crate::{AsEthApiError, EthApiTypes, FromEthApiError, FromEvmError, IntoEthApiError}; +use crate::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}; use super::{LoadBlock, LoadPendingBlock, LoadState, LoadTransaction, SpawnBlocking, Trace}; /// Execution related functions for the [`EthApiServer`](crate::EthApiServer) trait in /// the `eth_` namespace. -pub trait EthCall: Call + LoadPendingBlock { +pub trait EthCall: Call + LoadPendingBlock { /// Estimate gas needed for execution of the `request` at the [`BlockId`]. fn estimate_gas_at( &self, request: TransactionRequest, at: BlockId, state_override: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { Call::estimate_gas_at(self, request, at, state_override) } @@ -54,12 +54,12 @@ pub trait EthCall: Call + LoadPendingBlock { request: TransactionRequest, block_number: Option, overrides: EvmOverrides, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { let (res, _env) = self.transact_call_at(request, block_number.unwrap_or_default(), overrides).await?; - ensure_success(res.result).map_err(T::Error::from_err) + ensure_success(res.result).map_err(Self::Error::from_err) } } @@ -70,9 +70,9 @@ pub trait EthCall: Call + LoadPendingBlock { bundle: Bundle, state_context: Option, mut state_override: Option, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { let Bundle { transactions, block_override } = bundle; @@ -183,9 +183,9 @@ pub trait EthCall: Call + LoadPendingBlock { &self, request: TransactionRequest, block_number: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: Trace, + Self: Trace, { async move { let block_id = block_number.unwrap_or_default(); @@ -206,9 +206,9 @@ pub trait EthCall: Call + LoadPendingBlock { block: BlockEnv, at: BlockId, mut request: TransactionRequest, - ) -> Result + ) -> Result where - Self: Trace, + Self: Trace, { let state = self.state_at_block_id(at)?; @@ -234,7 +234,8 @@ pub trait EthCall: Call + LoadPendingBlock { let to = if let Some(TxKind::Call(to)) = request.to { to } else { - let nonce = db.basic_ref(from).map_err(T::Error::from_err)?.unwrap_or_default().nonce; + let nonce = + db.basic_ref(from).map_err(Self::Error::from_err)?.unwrap_or_default().nonce; from.create(nonce) }; @@ -255,7 +256,7 @@ pub trait EthCall: Call + LoadPendingBlock { } ExecutionResult::Success { .. } => Ok(()), } - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; let access_list = inspector.into_access_list(); @@ -272,7 +273,7 @@ pub trait EthCall: Call + LoadPendingBlock { } /// Executes code on state. -pub trait Call: LoadState + SpawnBlocking { +pub trait Call: LoadState + SpawnBlocking { /// Returns default gas limit to use for `eth_call` and tracing RPC methods. /// /// Data access in default trait method implementations. @@ -284,9 +285,9 @@ pub trait Call: LoadState + SpawnBlocking { fn evm_config(&self) -> &impl ConfigureEvm; /// Executes the closure with the state that corresponds to the given [`BlockId`]. - fn with_state_at_block(&self, at: BlockId, f: F) -> Result + fn with_state_at_block(&self, at: BlockId, f: F) -> Result where - F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result, + F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result, { let state = self.state_at_block_id(at)?; f(StateProviderTraitObjWrapper(&state)) @@ -298,13 +299,13 @@ pub trait Call: LoadState + SpawnBlocking { &self, db: DB, env: EnvWithHandlerCfg, - ) -> Result<(ResultAndState, EnvWithHandlerCfg), T::Error> + ) -> Result<(ResultAndState, EnvWithHandlerCfg), Self::Error> where DB: Database, EthApiError: From, { let mut evm = self.evm_config().evm_with_env(db, env); - let res = evm.transact().map_err(T::Error::from_evm_err)?; + let res = evm.transact().map_err(Self::Error::from_evm_err)?; let (_, env) = evm.into_db_and_env_with_handler_cfg(); Ok((res, env)) } @@ -315,9 +316,9 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, at: BlockId, overrides: EvmOverrides, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, + Self: LoadPendingBlock, { let this = self.clone(); self.spawn_with_call_at(request, at, overrides, move |db, env| this.transact(db, env)) @@ -328,9 +329,9 @@ pub trait Call: LoadState + SpawnBlocking { &self, at: BlockId, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result + Send + 'static, + F: FnOnce(StateProviderTraitObjWrapper<'_>) -> Result + Send + 'static, R: Send + 'static, { self.spawn_tracing(move |this| { @@ -350,10 +351,10 @@ pub trait Call: LoadState + SpawnBlocking { at: BlockId, overrides: EvmOverrides, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, - F: FnOnce(StateCacheDbRefMutWrapper<'_, '_>, EnvWithHandlerCfg) -> Result + Self: LoadPendingBlock, + F: FnOnce(StateCacheDbRefMutWrapper<'_, '_>, EnvWithHandlerCfg) -> Result + Send + 'static, R: Send + 'static, @@ -395,10 +396,10 @@ pub trait Call: LoadState + SpawnBlocking { &self, hash: B256, f: F, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadBlock + LoadPendingBlock + LoadTransaction, - F: FnOnce(TransactionInfo, ResultAndState, StateCacheDb<'_>) -> Result + Self: LoadBlock + LoadPendingBlock + LoadTransaction, + F: FnOnce(TransactionInfo, ResultAndState, StateCacheDb<'_>) -> Result + Send + 'static, R: Send + 'static, @@ -458,7 +459,7 @@ pub trait Call: LoadState + SpawnBlocking { block_env: BlockEnv, transactions: impl IntoIterator, target_tx_hash: B256, - ) -> Result + ) -> Result where DB: DatabaseRef, EthApiError: From, @@ -475,7 +476,7 @@ pub trait Call: LoadState + SpawnBlocking { let sender = tx.signer(); self.evm_config().fill_tx_env(evm.tx_mut(), &tx.into_signed(), sender); - evm.transact_commit().map_err(T::Error::from_evm_err)?; + evm.transact_commit().map_err(Self::Error::from_evm_err)?; index += 1; } Ok(index) @@ -487,9 +488,9 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, at: BlockId, state_override: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock, + Self: LoadPendingBlock, { async move { let (cfg, block_env, at) = self.evm_env_at(at).await?; @@ -512,7 +513,7 @@ pub trait Call: LoadState + SpawnBlocking { request: TransactionRequest, state: S, state_override: Option, - ) -> Result + ) -> Result where S: StateProvider, { @@ -542,7 +543,7 @@ pub trait Call: LoadState + SpawnBlocking { // Apply any state overrides if specified. if let Some(state_override) = state_override { - apply_state_overrides(state_override, &mut db).map_err(T::Error::from_err)?; + apply_state_overrides(state_override, &mut db).map_err(Self::Error::from_err)?; } // Optimize for simple transfer transactions, potentially reducing the gas estimate. @@ -574,7 +575,7 @@ pub trait Call: LoadState + SpawnBlocking { if env.tx.gas_price > U256::ZERO { // cap the highest gas limit by max gas caller can afford with given gas price highest_gas_limit = highest_gas_limit - .min(caller_gas_allowance(&mut db, &env.tx).map_err(T::Error::from_err)?); + .min(caller_gas_allowance(&mut db, &env.tx).map_err(Self::Error::from_err)?); } // We can now normalize the highest gas limit to a u64 @@ -715,7 +716,7 @@ pub trait Call: LoadState + SpawnBlocking { tx_gas_limit: u64, highest_gas_limit: &mut u64, lowest_gas_limit: &mut u64, - ) -> Result<(), T::Error> { + ) -> Result<(), Self::Error> { match result { ExecutionResult::Success { .. } => { // Cap the highest gas limit with the succeeding gas limit. @@ -760,7 +761,7 @@ pub trait Call: LoadState + SpawnBlocking { env_gas_limit: U256, mut env: EnvWithHandlerCfg, db: &mut CacheDB>, - ) -> T::Error + ) -> Self::Error where S: StateProvider, { @@ -794,7 +795,7 @@ pub trait Call: LoadState + SpawnBlocking { &self, block_env: &BlockEnv, request: TransactionRequest, - ) -> Result { + ) -> Result { // Ensure that if versioned hashes are set, they're not empty if request.blob_versioned_hashes.as_ref().map_or(false, |hashes| hashes.is_empty()) { return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_err()) @@ -836,14 +837,14 @@ pub trait Call: LoadState + SpawnBlocking { gas_limit: gas_limit .try_into() .map_err(|_| RpcInvalidTransactionError::GasUintOverflow) - .map_err(T::Error::from_err)?, + .map_err(Self::Error::from_err)?, nonce, caller: from.unwrap_or_default(), gas_price, gas_priority_fee: max_priority_fee_per_gas, transact_to: to.unwrap_or(TxKind::Create), value: value.unwrap_or_default(), - data: input.try_into_unique_input().map_err(T::Error::from_err)?.unwrap_or_default(), + data: input.try_into_unique_input().map_err(Self::Error::from_err)?.unwrap_or_default(), chain_id, access_list: access_list.unwrap_or_default().into(), // EIP-4844 fields @@ -866,7 +867,7 @@ pub trait Call: LoadState + SpawnBlocking { cfg: CfgEnvWithHandlerCfg, block: BlockEnv, request: TransactionRequest, - ) -> Result { + ) -> Result { let tx = self.create_txn_env(&block, request)?; Ok(EnvWithHandlerCfg::new_with_cfg_env(cfg, block, tx)) } @@ -888,7 +889,7 @@ pub trait Call: LoadState + SpawnBlocking { gas_limit: u64, db: &mut CacheDB, overrides: EvmOverrides, - ) -> Result + ) -> Result where DB: DatabaseRef, EthApiError: From<::Error>, diff --git a/crates/rpc/rpc-eth-api/src/helpers/fee.rs b/crates/rpc/rpc-eth-api/src/helpers/fee.rs index 6cd533ec7cd1..57420539a80c 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/fee.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/fee.rs @@ -10,33 +10,33 @@ use reth_rpc_eth_types::{ use reth_rpc_types::{BlockNumberOrTag, FeeHistory}; use tracing::debug; -use crate::{EthApiTypes, FromEthApiError}; +use crate::FromEthApiError; use super::LoadBlock; /// Fee related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthFees: LoadFee { +pub trait EthFees: LoadFee { /// Returns a suggestion for a gas price for legacy transactions. /// /// See also: - fn gas_price(&self) -> impl Future> + Send + fn gas_price(&self) -> impl Future> + Send where - Self: LoadBlock, + Self: LoadBlock, { LoadFee::gas_price(self) } /// Returns a suggestion for a base fee for blob transactions. - fn blob_base_fee(&self) -> impl Future> + Send + fn blob_base_fee(&self) -> impl Future> + Send where - Self: LoadBlock, + Self: LoadBlock, { LoadFee::blob_base_fee(self) } /// Returns a suggestion for the priority fee (the tip) - fn suggested_priority_fee(&self) -> impl Future> + Send + fn suggested_priority_fee(&self) -> impl Future> + Send where Self: 'static, { @@ -52,7 +52,7 @@ pub trait EthFees: LoadFee { mut block_count: u64, newest_block: BlockNumberOrTag, reward_percentiles: Option>, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { if block_count == 0 { return Ok(FeeHistory::default()) @@ -76,7 +76,7 @@ pub trait EthFees: LoadFee { let Some(end_block) = LoadFee::provider(self) .block_number_for_id(newest_block.into()) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? else { return Err(EthApiError::UnknownBlockNumber.into()) }; @@ -147,7 +147,7 @@ pub trait EthFees: LoadFee { base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default()); } else { // read the requested header range - let headers = LoadFee::provider(self).sealed_headers_range(start_block..=end_block).map_err(T::Error::from_err)?; + let headers = LoadFee::provider(self).sealed_headers_range(start_block..=end_block).map_err(Self::Error::from_err)?; if headers.len() != block_count as usize { return Err(EthApiError::InvalidBlockRange.into()) } @@ -165,7 +165,7 @@ pub trait EthFees: LoadFee { if let Some(percentiles) = &reward_percentiles { let (transactions, receipts) = LoadFee::cache(self) .get_transactions_and_receipts(header.hash()) - .await.map_err(T::Error::from_err)? + .await.map_err(Self::Error::from_err)? .ok_or(EthApiError::InvalidBlockRange)?; rewards.push( calculate_reward_percentiles_for_block( @@ -228,7 +228,7 @@ pub trait EthFees: LoadFee { /// Loads fee from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` fees RPC methods. -pub trait LoadFee: LoadBlock { +pub trait LoadFee: LoadBlock { // Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -254,7 +254,7 @@ pub trait LoadFee: LoadBlock { fn legacy_gas_price( &self, gas_price: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { match gas_price { Some(gas_price) => Ok(gas_price), @@ -274,7 +274,7 @@ pub trait LoadFee: LoadBlock { &self, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { let max_fee_per_gas = match max_fee_per_gas { Some(max_fee_per_gas) => max_fee_per_gas, @@ -306,7 +306,7 @@ pub trait LoadFee: LoadBlock { fn eip4844_blob_fee( &self, blob_fee: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { match blob_fee { Some(blob_fee) => Ok(blob_fee), @@ -318,7 +318,7 @@ pub trait LoadFee: LoadBlock { /// Returns a suggestion for a gas price for legacy transactions. /// /// See also: - fn gas_price(&self) -> impl Future> + Send { + fn gas_price(&self) -> impl Future> + Send { let header = self.block(BlockNumberOrTag::Latest.into()); let suggested_tip = self.suggested_priority_fee(); async move { @@ -329,7 +329,7 @@ pub trait LoadFee: LoadBlock { } /// Returns a suggestion for a base fee for blob transactions. - fn blob_base_fee(&self) -> impl Future> + Send { + fn blob_base_fee(&self) -> impl Future> + Send { async move { self.block(BlockNumberOrTag::Latest.into()) .await? @@ -340,10 +340,10 @@ pub trait LoadFee: LoadBlock { } /// Returns a suggestion for the priority fee (the tip) - fn suggested_priority_fee(&self) -> impl Future> + Send + fn suggested_priority_fee(&self) -> impl Future> + Send where Self: 'static, { - async move { self.gas_oracle().suggest_tip_cap().await.map_err(T::Error::from_err) } + async move { self.gas_oracle().suggest_tip_cap().await.map_err(Self::Error::from_err) } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index cff28bdd8ac8..1bdf622b4cba 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -41,41 +41,38 @@ pub use transaction::{EthTransactions, LoadTransaction, UpdateRawTxForwarder}; use crate::EthApiTypes; /// Extension trait that bundles traits needed for tracing transactions. -pub trait TraceExt: - LoadTransaction + LoadBlock + LoadPendingBlock + SpawnBlocking + Trace + Call +pub trait TraceExt: + LoadTransaction + LoadBlock + LoadPendingBlock + SpawnBlocking + Trace + Call { } -impl TraceExt for T where - T: LoadTransaction + LoadBlock + LoadPendingBlock + Trace + Call -{ -} +impl TraceExt for T where T: LoadTransaction + LoadBlock + LoadPendingBlock + Trace + Call {} /// Helper trait to unify all `eth` rpc server building block traits, for simplicity. /// /// This trait is automatically implemented for any type that implements all the `Eth` traits. -pub trait FullEthApi: - EthApiSpec - + EthTransactions - + EthBlocks - + EthState - + EthCall - + EthFees - + Trace - + LoadReceipt +pub trait FullEthApi: + EthApiTypes + + EthApiSpec + + EthTransactions + + EthBlocks + + EthState + + EthCall + + EthFees + + Trace + + LoadReceipt { } -impl FullEthApi for EthApi -where - T: EthApiTypes, - EthApi: EthApiSpec - + EthTransactions - + EthBlocks - + EthState - + EthCall - + EthFees - + Trace - + LoadReceipt, +impl FullEthApi for T where + T: EthApiTypes + + EthApiSpec + + EthTransactions + + EthBlocks + + EthState + + EthCall + + EthFees + + Trace + + LoadReceipt { } diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index 42534d83213c..b99a1c703fc5 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -41,8 +41,7 @@ use super::SpawnBlocking; /// Loads a pending block from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` blocks RPC methods. -#[auto_impl::auto_impl(&, Arc)] -pub trait LoadPendingBlock { +pub trait LoadPendingBlock: EthApiTypes { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -68,9 +67,9 @@ pub trait LoadPendingBlock { /// Configures the [`CfgEnvWithHandlerCfg`] and [`BlockEnv`] for the pending block /// /// If no pending block is available, this will derive it from the `latest` block - fn pending_block_env_and_cfg(&self) -> Result { + fn pending_block_env_and_cfg(&self) -> Result { let origin: PendingBlockEnvOrigin = if let Some(pending) = - self.provider().pending_block_with_senders().map_err(T::Error::from_err)? + self.provider().pending_block_with_senders().map_err(Self::Error::from_err)? { PendingBlockEnvOrigin::ActualPending(pending) } else { @@ -79,7 +78,7 @@ pub trait LoadPendingBlock { let latest = self .provider() .latest_header() - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .ok_or_else(|| EthApiError::UnknownBlockNumber)?; let (mut latest_header, block_hash) = latest.split(); @@ -115,7 +114,7 @@ pub trait LoadPendingBlock { origin.header(), self.evm_config().clone(), ) - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(PendingBlockEnv::new(cfg, block_env, origin)) } @@ -123,9 +122,9 @@ pub trait LoadPendingBlock { /// Returns the locally built pending block fn local_pending_block( &self, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: SpawnBlocking, + Self: SpawnBlocking, { async move { let pending = self.pending_block_env_and_cfg()?; @@ -205,7 +204,7 @@ pub trait LoadPendingBlock { /// /// After Cancun, if the origin is the actual pending block, the block includes the EIP-4788 pre /// block contract call using the parent beacon block root received from the CL. - fn build_block(&self, env: PendingBlockEnv) -> Result + fn build_block(&self, env: PendingBlockEnv) -> Result where EthApiError: From, { @@ -213,7 +212,7 @@ pub trait LoadPendingBlock { let parent_hash = origin.build_target_hash(); let state_provider = - self.provider().history_by_block_hash(parent_hash).map_err(T::Error::from_err)?; + self.provider().history_by_block_hash(parent_hash).map_err(Self::Error::from_err)?; let state = StateProviderDatabase::new(state_provider); let mut db = State::builder().with_database(state).with_bundle_update().build(); @@ -328,7 +327,7 @@ pub trait LoadPendingBlock { } err => { // this is an error that we should treat as fatal for this attempt - return Err(T::Error::from_evm_err(err)) + return Err(Self::Error::from_evm_err(err)) } } } @@ -371,7 +370,7 @@ pub trait LoadPendingBlock { ); // increment account balances for withdrawals - db.increment_balances(balance_increments).map_err(T::Error::from_err)?; + db.increment_balances(balance_increments).map_err(Self::Error::from_err)?; // merge all transitions into bundle state. db.merge_transitions(BundleRetention::PlainState); @@ -391,7 +390,7 @@ pub trait LoadPendingBlock { // calculate the state root let state_provider = &db.database; let state_root = - state_provider.state_root(execution_outcome.state()).map_err(T::Error::from_err)?; + state_provider.state_root(execution_outcome.state()).map_err(Self::Error::from_err)?; // create the block header let transactions_root = calculate_transaction_root(&executed_txs); diff --git a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs index 03b57491fad0..7f4a015d69d2 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs @@ -11,8 +11,7 @@ use crate::{EthApiTypes, FromEthApiError}; /// Assembles transaction receipt data w.r.t to network. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` receipts RPC methods. -#[auto_impl::auto_impl(&, Arc)] -pub trait LoadReceipt: Send + Sync { +pub trait LoadReceipt: EthApiTypes + Send + Sync { /// Returns a handle for reading data from memory. /// /// Data access in default (L1) trait method implementations. @@ -24,14 +23,14 @@ pub trait LoadReceipt: Send + Sync { tx: TransactionSigned, meta: TransactionMeta, receipt: Receipt, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { // get all receipts for the block let all_receipts = match self .cache() .get_receipts(meta.block_hash) .await - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { Some(recpts) => recpts, None => return Err(EthApiError::UnknownBlockNumber.into()), diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index db30265d6df2..a67d4c742089 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -20,7 +20,7 @@ use crate::{EthApiTypes, FromEthApiError}; use super::{EthApiSpec, LoadPendingBlock, SpawnBlocking}; /// Helper methods for `eth_` methods relating to state (accounts). -pub trait EthState: LoadState + SpawnBlocking { +pub trait EthState: LoadState + SpawnBlocking { /// Returns the maximum number of blocks into the past for generating state proofs. fn max_proof_window(&self) -> u64; @@ -32,7 +32,7 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { LoadState::transaction_count(self, address, block_id) } @@ -41,12 +41,12 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(this .state_at_block_id_or_latest(block_id)? .account_code(address) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .unwrap_or_default() .original_bytes()) }) @@ -57,12 +57,12 @@ pub trait EthState: LoadState + SpawnBlocking { &self, address: Address, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(this .state_at_block_id_or_latest(block_id)? .account_balance(address) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .unwrap_or_default()) }) } @@ -73,12 +73,12 @@ pub trait EthState: LoadState + SpawnBlocking { address: Address, index: JsonStorageKey, block_id: Option, - ) -> impl Future> + Send { + ) -> impl Future> + Send { self.spawn_blocking_io(move |this| { Ok(B256::new( this.state_at_block_id_or_latest(block_id)? .storage(address, index.0) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .unwrap_or_default() .to_be_bytes(), )) @@ -91,18 +91,21 @@ pub trait EthState: LoadState + SpawnBlocking { address: Address, keys: Vec, block_id: Option, - ) -> Result> + Send, T::Error> + ) -> Result< + impl Future> + Send, + Self::Error, + > where Self: EthApiSpec, { - let chain_info = self.chain_info().map_err(T::Error::from_err)?; + let chain_info = self.chain_info().map_err(Self::Error::from_err)?; let block_id = block_id.unwrap_or_default(); // Check whether the distance to the block exceeds the maximum configured window. let block_number = self .provider() .block_number_for_id(block_id) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .ok_or(EthApiError::UnknownBlockNumber)?; let max_window = self.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { @@ -119,7 +122,7 @@ pub trait EthState: LoadState + SpawnBlocking { let storage_keys = keys.iter().map(|key| key.0).collect::>(); let proof = state .proof(&BundleState::default(), address, &storage_keys) - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(from_primitive_account_proof(proof)) }) .await @@ -130,7 +133,7 @@ pub trait EthState: LoadState + SpawnBlocking { /// Loads state from database. /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` state RPC methods. -pub trait LoadState { +pub trait LoadState: EthApiTypes { /// Returns a handle for reading state from database. /// /// Data access in default trait method implementations. @@ -147,21 +150,21 @@ pub trait LoadState { fn pool(&self) -> impl TransactionPool; /// Returns the state at the given block number - fn state_at_hash(&self, block_hash: B256) -> Result { - self.provider().history_by_block_hash(block_hash).map_err(T::Error::from_err) + fn state_at_hash(&self, block_hash: B256) -> Result { + self.provider().history_by_block_hash(block_hash).map_err(Self::Error::from_err) } /// Returns the state at the given [`BlockId`] enum. /// /// Note: if not [`BlockNumberOrTag::Pending`](reth_primitives::BlockNumberOrTag) then this /// will only return canonical state. See also - fn state_at_block_id(&self, at: BlockId) -> Result { - self.provider().state_by_block_id(at).map_err(T::Error::from_err) + fn state_at_block_id(&self, at: BlockId) -> Result { + self.provider().state_by_block_id(at).map_err(Self::Error::from_err) } /// Returns the _latest_ state - fn latest_state(&self) -> Result { - self.provider().latest().map_err(T::Error::from_err) + fn latest_state(&self) -> Result { + self.provider().latest().map_err(Self::Error::from_err) } /// Returns the state at the given [`BlockId`] enum or the latest. @@ -170,7 +173,7 @@ pub trait LoadState { fn state_at_block_id_or_latest( &self, block_id: Option, - ) -> Result { + ) -> Result { if let Some(block_id) = block_id { self.state_at_block_id(block_id) } else { @@ -187,9 +190,9 @@ pub trait LoadState { fn evm_env_at( &self, at: BlockId, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { if at.is_pending() { @@ -200,10 +203,10 @@ pub trait LoadState { // Use cached values if there is no pending block let block_hash = LoadPendingBlock::provider(self) .block_hash_for_id(at) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .ok_or_else(|| EthApiError::UnknownBlockNumber)?; let (cfg, env) = - self.cache().get_evm_env(block_hash).await.map_err(T::Error::from_err)?; + self.cache().get_evm_env(block_hash).await.map_err(Self::Error::from_err)?; Ok((cfg, env, block_hash.into())) } } @@ -215,9 +218,9 @@ pub trait LoadState { fn evm_env_for_raw_block( &self, header: &Header, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: LoadPendingBlock + SpawnBlocking, { async move { // get the parent config first @@ -238,9 +241,9 @@ pub trait LoadState { &self, address: Address, block_id: Option, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: SpawnBlocking, + Self: SpawnBlocking, { self.spawn_blocking_io(move |this| { if block_id == Some(BlockId::pending()) { @@ -248,7 +251,7 @@ pub trait LoadState { if let Some(highest_nonce) = address_txs.iter().map(|item| item.transaction.nonce()).max() { - let tx_count = highest_nonce.checked_add(1).ok_or(T::Error::from( + let tx_count = highest_nonce.checked_add(1).ok_or(Self::Error::from( EthApiError::InvalidTransaction(RpcInvalidTransactionError::NonceMaxValue), ))?; return Ok(U256::from(tx_count)) @@ -257,7 +260,7 @@ pub trait LoadState { let state = this.state_at_block_id_or_latest(block_id)?; Ok(U256::from( - state.account_nonce(address).map_err(T::Error::from_err)?.unwrap_or_default(), + state.account_nonce(address).map_err(Self::Error::from_err)?.unwrap_or_default(), )) }) } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index 06c6f3349288..51e72dc08c7b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -13,12 +13,12 @@ use revm::{db::CacheDB, Database, DatabaseCommit, GetInspector, Inspector}; use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig}; use revm_primitives::{EnvWithHandlerCfg, EvmState, ExecutionResult, ResultAndState}; -use crate::{EthApiTypes, FromEvmError}; +use crate::FromEvmError; use super::{Call, LoadBlock, LoadPendingBlock, LoadState, LoadTransaction}; /// Executes CPU heavy tasks. -pub trait Trace: LoadState { +pub trait Trace: LoadState { /// Returns a handle for reading evm config. /// /// Data access in default (L1) trait method implementations. @@ -31,7 +31,7 @@ pub trait Trace: LoadState { db: DB, env: EnvWithHandlerCfg, inspector: I, - ) -> Result<(ResultAndState, EnvWithHandlerCfg), T::Error> + ) -> Result<(ResultAndState, EnvWithHandlerCfg), Self::Error> where DB: Database, EthApiError: From, @@ -50,14 +50,14 @@ pub trait Trace: LoadState { db: DB, env: EnvWithHandlerCfg, inspector: I, - ) -> Result<(ResultAndState, EnvWithHandlerCfg, DB), T::Error> + ) -> Result<(ResultAndState, EnvWithHandlerCfg, DB), Self::Error> where DB: Database, EthApiError: From, I: GetInspector, { let mut evm = self.evm_config().evm_with_env_and_inspector(db, env, inspector); - let res = evm.transact().map_err(T::Error::from_evm_err)?; + let res = evm.transact().map_err(Self::Error::from_evm_err)?; let (db, env) = evm.into_db_and_env_with_handler_cfg(); Ok((res, env, db)) } @@ -75,10 +75,10 @@ pub trait Trace: LoadState { config: TracingInspectorConfig, at: BlockId, f: F, - ) -> Result + ) -> Result where - Self: Call, - F: FnOnce(TracingInspector, ResultAndState) -> Result, + Self: Call, + F: FnOnce(TracingInspector, ResultAndState) -> Result, { self.with_state_at_block(at, |state| { let mut db = CacheDB::new(StateProviderDatabase::new(state)); @@ -101,10 +101,10 @@ pub trait Trace: LoadState { config: TracingInspectorConfig, at: BlockId, f: F, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: LoadPendingBlock + Call, - F: FnOnce(TracingInspector, ResultAndState, StateCacheDb<'_>) -> Result + Self: LoadPendingBlock + Call, + F: FnOnce(TracingInspector, ResultAndState, StateCacheDb<'_>) -> Result + Send + 'static, R: Send + 'static, @@ -132,15 +132,15 @@ pub trait Trace: LoadState { hash: B256, config: TracingInspectorConfig, f: F, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadPendingBlock + LoadTransaction + Call, + Self: LoadPendingBlock + LoadTransaction + Call, F: FnOnce( TransactionInfo, TracingInspector, ResultAndState, StateCacheDb<'_>, - ) -> Result + ) -> Result + Send + 'static, R: Send + 'static, @@ -162,10 +162,15 @@ pub trait Trace: LoadState { hash: B256, mut inspector: Insp, f: F, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadPendingBlock + LoadTransaction + Call, - F: FnOnce(TransactionInfo, Insp, ResultAndState, StateCacheDb<'_>) -> Result + Self: LoadPendingBlock + LoadTransaction + Call, + F: FnOnce( + TransactionInfo, + Insp, + ResultAndState, + StateCacheDb<'_>, + ) -> Result + Send + 'static, Insp: for<'a, 'b> Inspector> + Send + 'static, @@ -224,16 +229,16 @@ pub trait Trace: LoadState { highest_index: Option, config: TracingInspectorConfig, f: F, - ) -> impl Future>, T::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, F: Fn( TransactionInfo, TracingInspector, ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> Result + ) -> Result + Send + 'static, R: Send + 'static, @@ -262,16 +267,16 @@ pub trait Trace: LoadState { highest_index: Option, mut inspector_setup: Setup, f: F, - ) -> impl Future>, T::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, F: Fn( TransactionInfo, Insp, ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> Result + ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, @@ -368,9 +373,9 @@ pub trait Trace: LoadState { block_id: BlockId, config: TracingInspectorConfig, f: F, - ) -> impl Future>, T::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, // This is the callback that's invoked for each transaction with the inspector, the result, // state and db F: Fn( @@ -379,7 +384,7 @@ pub trait Trace: LoadState { ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> Result + ) -> Result + Send + 'static, R: Send + 'static, @@ -406,9 +411,9 @@ pub trait Trace: LoadState { block_id: BlockId, insp_setup: Setup, f: F, - ) -> impl Future>, T::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, // This is the callback that's invoked for each transaction with the inspector, the result, // state and db F: Fn( @@ -417,7 +422,7 @@ pub trait Trace: LoadState { ExecutionResult, &EvmState, &StateCacheDb<'_>, - ) -> Result + ) -> Result + Send + 'static, Setup: FnMut() -> Insp + Send + 'static, diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index c2fe60f9eb28..df6c2dd1e896 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -24,7 +24,7 @@ use reth_rpc_types::{ use reth_rpc_types_compat::transaction::from_recovered_with_block_context; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; -use crate::{EthApiTypes, FromEthApiError, IntoEthApiError}; +use crate::{FromEthApiError, IntoEthApiError}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking, @@ -53,7 +53,7 @@ use super::{ /// See also /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. -pub trait EthTransactions: LoadTransaction { +pub trait EthTransactions: LoadTransaction { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -77,7 +77,7 @@ pub trait EthTransactions: LoadTransaction { fn transaction_by_hash( &self, hash: B256, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { LoadTransaction::transaction_by_hash(self, hash) } @@ -87,8 +87,8 @@ pub trait EthTransactions: LoadTransaction { fn transactions_by_block( &self, block: B256, - ) -> impl Future>, T::Error>> + Send { - async move { self.cache().get_block_transactions(block).await.map_err(T::Error::from_err) } + ) -> impl Future>, Self::Error>> + Send { + async move { self.cache().get_block_transactions(block).await.map_err(Self::Error::from_err) } } /// Returns the EIP-2718 encoded transaction by hash. @@ -101,7 +101,7 @@ pub trait EthTransactions: LoadTransaction { fn raw_transaction_by_hash( &self, hash: B256, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { // Note: this is mostly used to fetch pooled transactions so we check the pool first if let Some(tx) = @@ -113,7 +113,7 @@ pub trait EthTransactions: LoadTransaction { self.spawn_blocking_io(move |ref this| { Ok(LoadTransaction::provider(this) .transaction_by_hash(hash) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .map(|tx| tx.envelope_encoded())) }) .await @@ -124,7 +124,7 @@ pub trait EthTransactions: LoadTransaction { fn historical_transaction_by_hash_at( &self, hash: B256, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { match self.transaction_by_hash_at(hash).await? { None => Ok(None), @@ -140,9 +140,9 @@ pub trait EthTransactions: LoadTransaction { fn transaction_receipt( &self, hash: B256, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadReceipt + 'static, + Self: LoadReceipt + 'static, { async move { let result = self.load_transaction_and_receipt(hash).await?; @@ -160,8 +160,9 @@ pub trait EthTransactions: LoadTransaction { fn load_transaction_and_receipt( &self, hash: TxHash, - ) -> impl Future, T::Error>> - + Send + ) -> impl Future< + Output = Result, Self::Error>, + > + Send where Self: 'static, { @@ -169,7 +170,7 @@ pub trait EthTransactions: LoadTransaction { self.spawn_blocking_io(move |_| { let (tx, meta) = match LoadTransaction::provider(&this) .transaction_by_hash_with_meta(hash) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { Some((tx, meta)) => (tx, meta), None => return Ok(None), @@ -177,7 +178,7 @@ pub trait EthTransactions: LoadTransaction { let receipt = match EthTransactions::provider(&this) .receipt_by_hash(hash) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { Some(recpt) => recpt, None => return Ok(None), @@ -194,9 +195,9 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { if let Some(block) = self.block_with_senders(block_id).await? { @@ -225,9 +226,9 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future, T::Error>> + Send + ) -> impl Future, Self::Error>> + Send where - Self: LoadBlock, + Self: LoadBlock, { async move { if let Some(block) = self.block_with_senders(block_id).await? { @@ -246,7 +247,7 @@ pub trait EthTransactions: LoadTransaction { fn send_raw_transaction( &self, tx: Bytes, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { // On optimism, transactions are forwarded directly to the sequencer to be included in // blocks that it builds. @@ -266,7 +267,7 @@ pub trait EthTransactions: LoadTransaction { .pool() .add_transaction(TransactionOrigin::Local, pool_transaction) .await - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(hash) } @@ -277,9 +278,9 @@ pub trait EthTransactions: LoadTransaction { fn send_transaction( &self, mut request: TransactionRequest, - ) -> impl Future> + Send + ) -> impl Future> + Send where - Self: EthApiSpec + LoadBlock + LoadPendingBlock + LoadFee + Call, + Self: EthApiSpec + LoadBlock + LoadPendingBlock + LoadFee + Call, { async move { let from = match request.from { @@ -471,7 +472,7 @@ pub trait EthTransactions: LoadTransaction { signed_tx.into_ecrecovered().ok_or(EthApiError::InvalidTransactionSignature)?; let pool_transaction = match recovered.try_into() { - Ok(converted) => <>::Pool as TransactionPool>::Transaction::from_recovered_pooled_transaction(converted), + Ok(converted) => <::Pool as TransactionPool>::Transaction::from_recovered_pooled_transaction(converted), Err(_) => return Err(EthApiError::TransactionConversionError.into()), }; @@ -479,7 +480,7 @@ pub trait EthTransactions: LoadTransaction { let hash = LoadTransaction::pool(self) .add_transaction(TransactionOrigin::Local, pool_transaction) .await - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(hash) } @@ -490,7 +491,7 @@ pub trait EthTransactions: LoadTransaction { &self, from: &Address, request: TypedTransactionRequest, - ) -> Result { + ) -> Result { for signer in self.signers().read().iter() { if signer.is_signer_for(from) { return match signer.sign_transaction(request, from) { @@ -507,28 +508,31 @@ pub trait EthTransactions: LoadTransaction { &self, account: Address, message: Bytes, - ) -> impl Future> + Send { + ) -> impl Future> + Send { async move { Ok(self .find_signer(&account)? .sign(account, &message) .await - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .to_hex_bytes()) } } /// Encodes and signs the typed data according EIP-712. Payload must implement Eip712 trait. - fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result { + fn sign_typed_data(&self, data: &TypedData, account: Address) -> Result { Ok(self .find_signer(&account)? .sign_typed_data(account, data) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? .to_hex_bytes()) } /// Returns the signer for the given account, if found in configured signers. - fn find_signer(&self, account: &Address) -> Result, T::Error> { + fn find_signer( + &self, + account: &Address, + ) -> Result, Self::Error> { self.signers() .read() .iter() @@ -542,7 +546,7 @@ pub trait EthTransactions: LoadTransaction { /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` transactions RPC /// methods. -pub trait LoadTransaction: SpawnBlocking { +pub trait LoadTransaction: SpawnBlocking { /// Transaction pool with pending transactions. [`TransactionPool::Transaction`] is the /// supported transaction type. type Pool: TransactionPool; @@ -570,7 +574,7 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_by_hash( &self, hash: B256, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send { async move { // Try to find the transaction on disk let mut resp = self @@ -578,7 +582,7 @@ pub trait LoadTransaction: SpawnBlocking { match this .provider() .transaction_by_hash_with_meta(hash) - .map_err(T::Error::from_err)? + .map_err(Self::Error::from_err)? { None => Ok(None), Some((tx, meta)) => { @@ -621,7 +625,8 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_by_hash_at( &self, transaction_hash: B256, - ) -> impl Future, T::Error>> + Send { + ) -> impl Future, Self::Error>> + Send + { async move { match self.transaction_by_hash(transaction_hash).await? { None => Ok(None), @@ -656,8 +661,8 @@ pub trait LoadTransaction: SpawnBlocking { fn transaction_and_block( &self, hash: B256, - ) -> impl Future, T::Error>> + Send - { + ) -> impl Future, Self::Error>> + + Send { async move { let (transaction, at) = match self.transaction_by_hash_at(hash).await? { None => return Ok(None), @@ -673,7 +678,7 @@ pub trait LoadTransaction: SpawnBlocking { .cache() .get_block_with_senders(block_hash) .await - .map_err(T::Error::from_err)?; + .map_err(Self::Error::from_err)?; Ok(block.map(|block| (transaction, block.seal(block_hash)))) } } From 494b3d9067ef0169efe6fdcf5f623bec3ba41f65 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 18 Jul 2024 16:39:33 +0200 Subject: [PATCH 03/80] Fix rpc API impls --- crates/optimism/rpc/src/error.rs | 29 ++-- crates/rpc/rpc-eth-api/src/core.rs | 108 ++++++------ crates/rpc/rpc-eth-api/src/helpers/trace.rs | 1 + crates/rpc/rpc-eth-types/src/error.rs | 82 +++++---- crates/rpc/rpc-types/src/eth/error.rs | 6 + crates/rpc/rpc-types/src/lib.rs | 2 +- crates/rpc/rpc/src/debug.rs | 135 +++++++++------ crates/rpc/rpc/src/eth/bundle.rs | 43 +++-- crates/rpc/rpc/src/eth/core.rs | 14 +- crates/rpc/rpc/src/eth/helpers/receipt.rs | 4 +- crates/rpc/rpc/src/eth/helpers/state.rs | 6 +- crates/rpc/rpc/src/eth/helpers/transaction.rs | 6 +- crates/rpc/rpc/src/otterscan.rs | 14 +- crates/rpc/rpc/src/trace.rs | 155 ++++++++++-------- 14 files changed, 352 insertions(+), 253 deletions(-) diff --git a/crates/optimism/rpc/src/error.rs b/crates/optimism/rpc/src/error.rs index 7dd7fc5e789a..bf6ab931d268 100644 --- a/crates/optimism/rpc/src/error.rs +++ b/crates/optimism/rpc/src/error.rs @@ -32,12 +32,17 @@ impl ToRpcError for OpEthApiError { } } -impl From for OpEthApiError { - fn from(err: InvalidTransaction) -> Self { +impl From> for EthApiError +where + T: Into, +{ + fn from(err: EVMError) -> Self { match err { - InvalidTransaction::DepositSystemTxPostRegolith | - InvalidTransaction::HaltedDepositPostRegolith => Self::InvalidTransaction(err.into()), - _ => expect!("should cover all network specific match arms"), + EVMError::Transaction(err) => match OptimismInvalidTransactionError::try_from(err) { + Ok(err) => Self::InvalidTransaction(err.into()), + Err(err) => Self::Core(EthApiError::InvalidTransaction(err.into())), + }, + _ => err.into_err(), } } } @@ -72,12 +77,16 @@ impl ToRpcError for OptimismInvalidTransactionError { } } -impl From for OptimismInvalidTransactionError { - fn from(err: InvalidTransaction) -> Self { +impl TryFrom for OptimismInvalidTransactionError { + type Error = InvalidTransaction; + + fn try_from(err: InvalidTransaction) -> Result { match err { - InvalidTransaction::DepositSystemTxPostRegolith => Self::DepositSystemTxPostRegolith, - InvalidTransaction::HaltedDepositPostRegolith => Self::HaltedDepositPostRegolith, - _ => expect!("should cover all network specific match arms"), + InvalidTransaction::DepositSystemTxPostRegolith => { + Ok(Self::DepositSystemTxPostRegolith) + } + InvalidTransaction::HaltedDepositPostRegolith => Ok(Self::HaltedDepositPostRegolith), + _ => Err(err), } } } diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 65b9a3333e27..804be3300252 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -4,7 +4,7 @@ use alloy_dyn_abi::TypedData; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::{ - revm_primitives, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, + revm_primitives::EVMError, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, }; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; @@ -12,8 +12,8 @@ use reth_rpc_types::{ serde_helpers::JsonStorageKey, state::{EvmOverrides, StateOverride}, AccessListWithGasUsed, AnyTransactionReceipt, BlockOverrides, Bundle, - EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, RichBlock, - StateContext, SyncStatus, ToRpcError, Transaction, TransactionRequest, Work, + EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, IntoRpcError, + RichBlock, StateContext, SyncStatus, Transaction, TransactionRequest, Work, }; use tracing::trace; @@ -23,9 +23,9 @@ use crate::helpers::{ }; /// Network specific `eth` API types. -pub trait EthApiTypes: Send + 'static { +pub trait EthApiTypes: Send + Sync { /// Extension of [`EthApiError`], with network specific errors. - type Error: ToRpcError + FromEthApiError + AsEthApiError + FromEvmError; + type Error: IntoRpcError + FromEthApiError + AsEthApiError + FromEvmError; } /// Helper trait to wrap core [`EthApiError`]. @@ -85,17 +85,29 @@ pub trait AsEthApiError { } } +impl AsEthApiError for EthApiError { + fn as_err(&self) -> Option<&EthApiError> { + Some(self) + } +} + /// Helper trait to convert from revm errors. -pub trait FromEvmError: From + From { +pub trait FromEvmError: From { /// Converts from a revm error. - fn from_evm_err(err: revm_primitives::EVMError) -> Self + fn from_evm_err(err: EVMError) -> Self + where + EthApiError: From; +} + +impl FromEvmError for T +where + T: From, +{ + fn from_evm_err(err: EVMError) -> Self where EthApiError: From, { - match EthApiError::try_from(err) { - Ok(err) => err.into(), // error inherited from l1 - Err(err) => Self::from(err), // l2 specific error - } + err.into_err() } } @@ -452,7 +464,7 @@ where /// Handler for: `eth_getBlockByHash` async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); - EthBlocks::rpc_block(self, hash.into(), full).await.map_err(|err| err.to_rpc_error()) + EthBlocks::rpc_block(self, hash.into(), full).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getBlockByNumber` @@ -462,7 +474,7 @@ where full: bool, ) -> RpcResult> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); - EthBlocks::rpc_block(self, number.into(), full).await.map_err(|err| err.to_rpc_error()) + EthBlocks::rpc_block(self, number.into(), full).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getBlockTransactionCountByHash` @@ -470,7 +482,7 @@ where trace!(target: "rpc::eth", ?hash, "Serving eth_getBlockTransactionCountByHash"); Ok(EthBlocks::block_transaction_count(self, hash.into()) .await - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .map(U256::from)) } @@ -482,7 +494,7 @@ where trace!(target: "rpc::eth", ?number, "Serving eth_getBlockTransactionCountByNumber"); Ok(EthBlocks::block_transaction_count(self, number.into()) .await - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .map(U256::from)) } @@ -490,7 +502,7 @@ where async fn block_uncles_count_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getUncleCountByBlockHash"); Ok(EthBlocks::ommers(self, hash.into()) - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .map(|ommers| U256::from(ommers.len()))) } @@ -501,7 +513,7 @@ where ) -> RpcResult> { trace!(target: "rpc::eth", ?number, "Serving eth_getUncleCountByBlockNumber"); Ok(EthBlocks::ommers(self, number.into()) - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .map(|ommers| U256::from(ommers.len()))) } @@ -511,7 +523,7 @@ where block_id: BlockId, ) -> RpcResult>> { trace!(target: "rpc::eth", ?block_id, "Serving eth_getBlockReceipts"); - EthBlocks::block_receipts(self, block_id).await.map_err(|err| err.to_rpc_error()) + EthBlocks::block_receipts(self, block_id).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getUncleByBlockHashAndIndex` @@ -523,7 +535,7 @@ where trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); EthBlocks::ommer_by_block_and_index(self, hash.into(), index) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getUncleByBlockNumberAndIndex` @@ -535,13 +547,13 @@ where trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); EthBlocks::ommer_by_block_and_index(self, number.into(), index) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getRawTransactionByHash` async fn raw_transaction_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getRawTransactionByHash"); - EthTransactions::raw_transaction_by_hash(self, hash).await.map_err(|err| err.to_rpc_error()) + EthTransactions::raw_transaction_by_hash(self, hash).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getTransactionByHash` @@ -549,7 +561,7 @@ where trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash) .await - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .map(Into::into)) } @@ -562,7 +574,7 @@ where trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getRawTransactionByBlockHashAndIndex"); EthTransactions::raw_transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getTransactionByBlockHashAndIndex` @@ -574,7 +586,7 @@ where trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getRawTransactionByBlockNumberAndIndex` @@ -586,7 +598,7 @@ where trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getRawTransactionByBlockNumberAndIndex"); EthTransactions::raw_transaction_by_block_and_tx_index(self, number.into(), index.into()) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getTransactionByBlockNumberAndIndex` @@ -598,19 +610,19 @@ where trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getTransactionReceipt` async fn transaction_receipt(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionReceipt"); - EthTransactions::transaction_receipt(self, hash).await.map_err(|err| err.to_rpc_error()) + EthTransactions::transaction_receipt(self, hash).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getBalance` async fn balance(&self, address: Address, block_number: Option) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getBalance"); - EthState::balance(self, address, block_number).await.map_err(|err| err.to_rpc_error()) + EthState::balance(self, address, block_number).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getStorageAt` @@ -623,7 +635,7 @@ where trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getStorageAt"); EthState::storage_at(self, address, index, block_number) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getTransactionCount` @@ -635,27 +647,25 @@ where trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getTransactionCount"); EthState::transaction_count(self, address, block_number) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getCode` async fn get_code(&self, address: Address, block_number: Option) -> RpcResult { trace!(target: "rpc::eth", ?address, ?block_number, "Serving eth_getCode"); - EthState::get_code(self, address, block_number).await.map_err(|err| err.to_rpc_error()) + EthState::get_code(self, address, block_number).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getHeaderByNumber` async fn header_by_number(&self, block_number: BlockNumberOrTag) -> RpcResult> { trace!(target: "rpc::eth", ?block_number, "Serving eth_getHeaderByNumber"); - EthBlocks::rpc_block_header(self, block_number.into()) - .await - .map_err(|err| err.to_rpc_error()) + EthBlocks::rpc_block_header(self, block_number.into()).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getHeaderByHash` async fn header_by_hash(&self, hash: B256) -> RpcResult> { trace!(target: "rpc::eth", ?hash, "Serving eth_getHeaderByHash"); - EthBlocks::rpc_block_header(self, hash.into()).await.map_err(|err| err.to_rpc_error()) + EthBlocks::rpc_block_header(self, hash.into()).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_call` @@ -674,7 +684,7 @@ where EvmOverrides::new(state_overrides, block_overrides), ) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_callMany` @@ -687,7 +697,7 @@ where trace!(target: "rpc::eth", ?bundle, ?state_context, ?state_override, "Serving eth_callMany"); EthCall::call_many(self, bundle, state_context, state_override) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_createAccessList` @@ -699,7 +709,7 @@ where trace!(target: "rpc::eth", ?request, ?block_number, "Serving eth_createAccessList"); let access_list_with_gas_used = EthCall::create_access_list_at(self, request, block_number) .await - .map_err(|err| err.to_rpc_error())?; + .map_err(T::Error::into_rpc_err)?; Ok(access_list_with_gas_used) } @@ -714,25 +724,25 @@ where trace!(target: "rpc::eth", ?request, ?block_number, "Serving eth_estimateGas"); EthCall::estimate_gas_at(self, request, block_number.unwrap_or_default(), state_override) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_gasPrice` async fn gas_price(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_gasPrice"); - EthFees::gas_price(self).await.map_err(|err| err.to_rpc_error()) + EthFees::gas_price(self).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_maxPriorityFeePerGas` async fn max_priority_fee_per_gas(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_maxPriorityFeePerGas"); - EthFees::suggested_priority_fee(self).await.map_err(|err| err.to_rpc_error()) + EthFees::suggested_priority_fee(self).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_blobBaseFee` async fn blob_base_fee(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_blobBaseFee"); - EthFees::blob_base_fee(self).await.map_err(|err| err.to_rpc_error()) + EthFees::blob_base_fee(self).await.map_err(T::Error::into_rpc_err) } // FeeHistory is calculated based on lazy evaluation of fees for historical blocks, and further @@ -753,7 +763,7 @@ where trace!(target: "rpc::eth", ?block_count, ?newest_block, ?reward_percentiles, "Serving eth_feeHistory"); EthFees::fee_history(self, block_count.to(), newest_block, reward_percentiles) .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } /// Handler for: `eth_mining` @@ -789,19 +799,19 @@ where /// Handler for: `eth_sendTransaction` async fn send_transaction(&self, request: TransactionRequest) -> RpcResult { trace!(target: "rpc::eth", ?request, "Serving eth_sendTransaction"); - EthTransactions::send_transaction(self, request).await.map_err(|err| err.to_rpc_error()) + EthTransactions::send_transaction(self, request).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_sendRawTransaction` async fn send_raw_transaction(&self, tx: Bytes) -> RpcResult { trace!(target: "rpc::eth", ?tx, "Serving eth_sendRawTransaction"); - EthTransactions::send_raw_transaction(self, tx).await.map_err(|err| err.to_rpc_error()) + EthTransactions::send_raw_transaction(self, tx).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_sign` async fn sign(&self, address: Address, message: Bytes) -> RpcResult { trace!(target: "rpc::eth", ?address, ?message, "Serving eth_sign"); - EthTransactions::sign(self, address, message).await.map_err(|err| err.to_rpc_error()) + EthTransactions::sign(self, address, message).await.map_err(T::Error::into_rpc_err) } /// Handler for: `eth_signTransaction` @@ -812,7 +822,7 @@ where /// Handler for: `eth_signTypedData` async fn sign_typed_data(&self, address: Address, data: TypedData) -> RpcResult { trace!(target: "rpc::eth", ?address, ?data, "Serving eth_signTypedData"); - EthTransactions::sign_typed_data(self, &data, address).map_err(|err| err.to_rpc_error()) + EthTransactions::sign_typed_data(self, &data, address).map_err(T::Error::into_rpc_err) } /// Handler for: `eth_getProof` @@ -824,8 +834,8 @@ where ) -> RpcResult { trace!(target: "rpc::eth", ?address, ?keys, ?block_number, "Serving eth_getProof"); EthState::get_proof(self, address, keys, block_number) - .map_err(|err| err.to_rpc_error())? + .map_err(T::Error::into_rpc_err)? .await - .map_err(|err| err.to_rpc_error()) + .map_err(T::Error::into_rpc_err) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index 51e72dc08c7b..09ad7f22fa21 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -54,6 +54,7 @@ pub trait Trace: LoadState { where DB: Database, EthApiError: From, + I: GetInspector, { let mut evm = self.evm_config().evm_with_env_and_inspector(db, env, inspector); diff --git a/crates/rpc/rpc-eth-types/src/error.rs b/crates/rpc/rpc-eth-types/src/error.rs index 9713ddce169f..b7e48a8017ff 100644 --- a/crates/rpc/rpc-eth-types/src/error.rs +++ b/crates/rpc/rpc-eth-types/src/error.rs @@ -9,7 +9,7 @@ use reth_rpc_server_types::result::{ internal_rpc_err, invalid_params_rpc_err, rpc_err, rpc_error_with_code, }; use reth_rpc_types::{ - error::EthRpcErrorCode, request::TransactionInputError, BlockError, ToRpcError, + error::EthRpcErrorCode, request::TransactionInputError, BlockError, IntoRpcError, ToRpcError, }; use reth_transaction_pool::error::{ Eip4844PoolTransactionError, InvalidPoolTransactionError, PoolError, PoolErrorKind, @@ -226,24 +226,28 @@ impl From for EthApiError { } } -impl TryFrom> for EthApiError +impl From> for EthApiError where T: Into, { - type Error = revm::primitives::InvalidTransaction; - - fn try_from(err: EVMError) -> Result { + fn from(err: EVMError) -> Self { match err { - EVMError::Transaction(err) => Ok(RpcInvalidTransactionError::try_from(err)?.into()), - EVMError::Header(InvalidHeader::PrevrandaoNotSet) => Ok(Self::PrevrandaoNotSet), - EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => Ok(Self::ExcessBlobGasNotSet), - EVMError::Database(err) => Ok(err.into()), - EVMError::Custom(err) => Ok(Self::EvmCustom(err)), - EVMError::Precompile(err) => Ok(Self::EvmPrecompile(err)), + EVMError::Transaction(err) => RpcInvalidTransactionError::from(err).into(), + EVMError::Header(InvalidHeader::PrevrandaoNotSet) => Self::PrevrandaoNotSet, + EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => Self::ExcessBlobGasNotSet, + EVMError::Database(err) => err.into(), + EVMError::Custom(err) => Self::EvmCustom(err), + EVMError::Precompile(err) => Self::EvmPrecompile(err), } } } +impl IntoRpcError for EthApiError { + fn into_rpc_err(self) -> jsonrpsee_types::error::ErrorObject<'static> { + self.into() + } +} + /// An error due to invalid transaction. /// /// The only reason this exists is to maintain compatibility with other clients de-facto standard @@ -439,47 +443,39 @@ impl From for jsonrpsee_types::error::ErrorObject<'s } } -impl TryFrom for RpcInvalidTransactionError { - type Error = revm::primitives::InvalidTransaction; - - fn try_from(err: revm::primitives::InvalidTransaction) -> Result { +impl From for RpcInvalidTransactionError { + fn from(err: revm::primitives::InvalidTransaction) -> Self { use revm::primitives::InvalidTransaction; match err { - InvalidTransaction::InvalidChainId => Ok(Self::InvalidChainId), - InvalidTransaction::PriorityFeeGreaterThanMaxFee => Ok(Self::TipAboveFeeCap), - InvalidTransaction::GasPriceLessThanBasefee => Ok(Self::FeeCapTooLow), + InvalidTransaction::InvalidChainId => Self::InvalidChainId, + InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap, + InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow, InvalidTransaction::CallerGasLimitMoreThanBlock | - InvalidTransaction::CallGasCostMoreThanGasLimit => Ok(Self::GasTooHigh), - InvalidTransaction::RejectCallerWithCode => Ok(Self::SenderNoEOA), - InvalidTransaction::LackOfFundForMaxFee { .. } => Ok(Self::InsufficientFunds), - InvalidTransaction::OverflowPaymentInTransaction => Ok(Self::GasUintOverflow), - InvalidTransaction::NonceOverflowInTransaction => Ok(Self::NonceMaxValue), - InvalidTransaction::CreateInitCodeSizeLimit => Ok(Self::MaxInitCodeSizeExceeded), - InvalidTransaction::NonceTooHigh { .. } => Ok(Self::NonceTooHigh), - InvalidTransaction::NonceTooLow { .. } => Ok(Self::NonceTooLow), - InvalidTransaction::AccessListNotSupported => Ok(Self::AccessListNotSupported), - InvalidTransaction::MaxFeePerBlobGasNotSupported => { - Ok(Self::MaxFeePerBlobGasNotSupported) - } + InvalidTransaction::CallGasCostMoreThanGasLimit => Self::GasTooHigh, + InvalidTransaction::RejectCallerWithCode => Self::SenderNoEOA, + InvalidTransaction::LackOfFundForMaxFee { .. } => Self::InsufficientFunds, + InvalidTransaction::OverflowPaymentInTransaction => Self::GasUintOverflow, + InvalidTransaction::NonceOverflowInTransaction => Self::NonceMaxValue, + InvalidTransaction::CreateInitCodeSizeLimit => Self::MaxInitCodeSizeExceeded, + InvalidTransaction::NonceTooHigh { .. } => Self::NonceTooHigh, + InvalidTransaction::NonceTooLow { .. } => Self::NonceTooLow, + InvalidTransaction::AccessListNotSupported => Self::AccessListNotSupported, + InvalidTransaction::MaxFeePerBlobGasNotSupported => Self::MaxFeePerBlobGasNotSupported, InvalidTransaction::BlobVersionedHashesNotSupported => { - Ok(Self::BlobVersionedHashesNotSupported) - } - InvalidTransaction::BlobGasPriceGreaterThanMax => Ok(Self::BlobFeeCapTooLow), - InvalidTransaction::EmptyBlobs => Ok(Self::BlobTransactionMissingBlobHashes), - InvalidTransaction::BlobVersionNotSupported => Ok(Self::BlobHashVersionMismatch), - InvalidTransaction::TooManyBlobs { max, have } => Ok(Self::TooManyBlobs { max, have }), - InvalidTransaction::BlobCreateTransaction => Ok(Self::BlobTransactionIsCreate), - InvalidTransaction::EofCrateShouldHaveToAddress => { - Ok(Self::EofCrateShouldHaveToAddress) + Self::BlobVersionedHashesNotSupported } + InvalidTransaction::BlobGasPriceGreaterThanMax => Self::BlobFeeCapTooLow, + InvalidTransaction::EmptyBlobs => Self::BlobTransactionMissingBlobHashes, + InvalidTransaction::BlobVersionNotSupported => Self::BlobHashVersionMismatch, + InvalidTransaction::TooManyBlobs { max, have } => Self::TooManyBlobs { max, have }, + InvalidTransaction::BlobCreateTransaction => Self::BlobTransactionIsCreate, + InvalidTransaction::EofCrateShouldHaveToAddress => Self::EofCrateShouldHaveToAddress, InvalidTransaction::AuthorizationListNotSupported => { - Ok(Self::AuthorizationListNotSupported) + Self::AuthorizationListNotSupported } InvalidTransaction::AuthorizationListInvalidFields => { - Ok(Self::AuthorizationListInvalidFields) + Self::AuthorizationListInvalidFields } - #[allow(unreachable_patterns)] - _ => Err(err), } } } diff --git a/crates/rpc/rpc-types/src/eth/error.rs b/crates/rpc/rpc-types/src/eth/error.rs index e606ee8a8f2a..44674330021e 100644 --- a/crates/rpc/rpc-types/src/eth/error.rs +++ b/crates/rpc/rpc-types/src/eth/error.rs @@ -7,3 +7,9 @@ pub trait ToRpcError: std::error::Error + Send + Sync + 'static { /// Converts the error to a JSON-RPC error object. fn to_rpc_error(&self) -> ErrorObject<'static>; } + +/// A trait to convert an error to an RPC error. +pub trait IntoRpcError: std::error::Error + Send + Sync + 'static { + /// Converts the error to a JSON-RPC error object. + fn into_rpc_err(self) -> ErrorObject<'static>; +} diff --git a/crates/rpc/rpc-types/src/lib.rs b/crates/rpc/rpc-types/src/lib.rs index 6a73c740213a..5ee0bf2d8be8 100644 --- a/crates/rpc/rpc-types/src/lib.rs +++ b/crates/rpc/rpc-types/src/lib.rs @@ -48,7 +48,7 @@ pub use eth::{ engine::{ ExecutionPayload, ExecutionPayloadV1, ExecutionPayloadV2, ExecutionPayloadV3, PayloadError, }, - error::ToRpcError, + error::{IntoRpcError, ToRpcError}, transaction::{self, TransactionRequest, TypedTransactionRequest}, }; diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 847ab6ae5a33..58a501cf0b51 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -14,8 +14,11 @@ use reth_provider::{ }; use reth_revm::database::StateProviderDatabase; use reth_rpc_api::DebugApiServer; -use reth_rpc_eth_api::helpers::{Call, EthApiSpec, EthTransactions, TraceExt}; -use reth_rpc_eth_types::{EthApiError, EthResult, StateCacheDb}; +use reth_rpc_eth_api::{ + helpers::{Call, EthApiSpec, EthTransactions, TraceExt}, + EthApiTypes, FromEthApiError, +}; +use reth_rpc_eth_types::{EthApiError, StateCacheDb}; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; use reth_rpc_types::{ state::EvmOverrides, @@ -23,7 +26,7 @@ use reth_rpc_types::{ BlockTraceResult, FourByteFrame, GethDebugBuiltInTracerType, GethDebugTracerType, GethDebugTracingCallOptions, GethDebugTracingOptions, GethTrace, NoopFrame, TraceResult, }, - BlockError, Bundle, RichBlock, StateContext, TransactionRequest, + BlockError, Bundle, IntoRpcError, RichBlock, StateContext, TransactionRequest, }; use reth_tasks::pool::BlockingTaskGuard; use revm::{ @@ -68,7 +71,7 @@ where + StateProviderFactory + EvmEnvProvider + 'static, - Eth: TraceExt + 'static, + Eth: EthApiTypes + TraceExt + 'static, { /// Acquires a permit to execute a tracing call. async fn acquire_trace_permit(&self) -> Result { @@ -83,7 +86,7 @@ where cfg: CfgEnvWithHandlerCfg, block_env: BlockEnv, opts: GethDebugTracingOptions, - ) -> EthResult> { + ) -> Result, Eth::Error> { if transactions.is_empty() { // nothing to trace return Ok(Vec::new()) @@ -141,9 +144,10 @@ where &self, rlp_block: Bytes, opts: GethDebugTracingOptions, - ) -> EthResult> { - let block = - Block::decode(&mut rlp_block.as_ref()).map_err(BlockError::RlpDecodeRawBlock)?; + ) -> Result, Eth::Error> { + let block = Block::decode(&mut rlp_block.as_ref()) + .map_err(BlockError::RlpDecodeRawBlock) + .map_err(Eth::Error::from_err)?; let (cfg, block_env) = self.eth_api().evm_env_for_raw_block(&block.header).await?; // we trace on top the block's parent block @@ -158,8 +162,9 @@ where .map(|tx| { tx.into_ecrecovered() .ok_or_else(|| EthApiError::InvalidTransactionSignature) + .map_err(Eth::Error::from_err) }) - .collect::>>()? + .collect::, Eth::Error>>()? } else { block .body @@ -167,8 +172,9 @@ where .map(|tx| { tx.into_ecrecovered_unchecked() .ok_or_else(|| EthApiError::InvalidTransactionSignature) + .map_err(Eth::Error::from_err) }) - .collect::>>()? + .collect::, Eth::Error>>()? }; self.trace_block(parent.into(), transactions, cfg, block_env, opts).await @@ -179,11 +185,12 @@ where &self, block_id: BlockId, opts: GethDebugTracingOptions, - ) -> EthResult> { + ) -> Result, Eth::Error> { let block_hash = self .inner .provider - .block_hash_for_id(block_id)? + .block_hash_for_id(block_id) + .map_err(Eth::Error::from_err)? .ok_or_else(|| EthApiError::UnknownBlockNumber)?; let ((cfg, block_env, _), block) = futures::try_join!( @@ -213,9 +220,9 @@ where &self, tx_hash: B256, opts: GethDebugTracingOptions, - ) -> EthResult { + ) -> Result { let (transaction, block) = match self.inner.eth_api.transaction_and_block(tx_hash).await? { - None => return Err(EthApiError::TransactionNotFound), + None => return Err(EthApiError::TransactionNotFound.into()), Some(res) => res, }; let (cfg, block_env, _) = self.inner.eth_api.evm_env_at(block.hash().into()).await?; @@ -277,7 +284,7 @@ where call: TransactionRequest, block_id: Option, opts: GethDebugTracingCallOptions, - ) -> EthResult { + ) -> Result { let at = block_id.unwrap_or_default(); let GethDebugTracingCallOptions { tracing_options, state_overrides, block_overrides } = opts; @@ -330,22 +337,23 @@ where TracingInspectorConfig::from_geth_prestate_config(&prestate_config), ); - let frame = - self.inner - .eth_api - .spawn_with_call_at(call, at, overrides, move |db, env| { - // wrapper is hack to get around 'higher-ranked lifetime error', - // see - let db = db.0; - - let (res, _) = - this.eth_api().inspect(&mut *db, env, &mut inspector)?; - let frame = inspector - .into_geth_builder() - .geth_prestate_traces(&res, prestate_config, db)?; - Ok(frame) - }) - .await?; + let frame = self + .inner + .eth_api + .spawn_with_call_at(call, at, overrides, move |db, env| { + // wrapper is hack to get around 'higher-ranked lifetime error', + // see + let db = db.0; + + let (res, _) = + this.eth_api().inspect(&mut *db, env, &mut inspector)?; + let frame = inspector + .into_geth_builder() + .geth_prestate_traces(&res, prestate_config, db) + .map_err(Eth::Error::from_err)?; + Ok(frame) + }) + .await?; return Ok(frame.into()) } GethDebugBuiltInTracerType::NoopTracer => Ok(NoopFrame::default().into()), @@ -354,7 +362,8 @@ where .into_mux_config() .map_err(|_| EthApiError::InvalidTracerConfig)?; - let mut inspector = MuxInspector::try_from_config(mux_config)?; + let mut inspector = MuxInspector::try_from_config(mux_config) + .map_err(Eth::Error::from_err)?; let frame = self .inner @@ -366,7 +375,9 @@ where let (res, _) = this.eth_api().inspect(&mut *db, env, &mut inspector)?; - let frame = inspector.try_into_mux_frame(&res, db)?; + let frame = inspector + .try_into_mux_frame(&res, db) + .map_err(Eth::Error::from_err)?; Ok(frame.into()) }) .await?; @@ -386,10 +397,11 @@ where // let db = db.0; - let mut inspector = JsInspector::new(code, config)?; + let mut inspector = + JsInspector::new(code, config).map_err(Eth::Error::from_err)?; let (res, _) = this.eth_api().inspect(&mut *db, env.clone(), &mut inspector)?; - Ok(inspector.json_result(res, &env, db)?) + inspector.json_result(res, &env, db).map_err(Eth::Error::from_err) }) .await?; @@ -426,9 +438,9 @@ where bundles: Vec, state_context: Option, opts: Option, - ) -> EthResult>> { + ) -> Result>, Eth::Error> { if bundles.is_empty() { - return Err(EthApiError::InvalidParams(String::from("bundles are empty."))) + return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into()) } let StateContext { transaction_index, block_number } = state_context.unwrap_or_default(); @@ -546,7 +558,7 @@ where env: EnvWithHandlerCfg, db: &mut StateCacheDb<'_>, transaction_context: Option, - ) -> EthResult<(GethTrace, revm_primitives::EvmState)> { + ) -> Result<(GethTrace, revm_primitives::EvmState), Eth::Error> { let GethDebugTracingOptions { config, tracer, tracer_config, .. } = opts; if let Some(tracer) = tracer { @@ -584,11 +596,10 @@ where ); let (res, _) = self.eth_api().inspect(&mut *db, env, &mut inspector)?; - let frame = inspector.into_geth_builder().geth_prestate_traces( - &res, - prestate_config, - db, - )?; + let frame = inspector + .into_geth_builder() + .geth_prestate_traces(&res, prestate_config, db) + .map_err(Eth::Error::from_err)?; return Ok((frame.into(), res.state)) } @@ -600,10 +611,12 @@ where .into_mux_config() .map_err(|_| EthApiError::InvalidTracerConfig)?; - let mut inspector = MuxInspector::try_from_config(mux_config)?; + let mut inspector = MuxInspector::try_from_config(mux_config) + .map_err(Eth::Error::from_err)?; let (res, _) = self.eth_api().inspect(&mut *db, env, &mut inspector)?; - let frame = inspector.try_into_mux_frame(&res, db)?; + let frame = + inspector.try_into_mux_frame(&res, db).map_err(Eth::Error::from_err)?; return Ok((frame.into(), res.state)) } }, @@ -613,11 +626,13 @@ where code, config, transaction_context.unwrap_or_default(), - )?; + ) + .map_err(Eth::Error::from_err)?; let (res, env) = self.eth_api().inspect(&mut *db, env, &mut inspector)?; let state = res.state.clone(); - let result = inspector.json_result(res, &env, db)?; + let result = + inspector.json_result(res, &env, db).map_err(Eth::Error::from_err)?; Ok((GethTrace::JS(result), state)) } } @@ -690,7 +705,7 @@ where /// /// Returns the bytes of the transaction for the given hash. async fn raw_transaction(&self, hash: B256) -> RpcResult> { - Ok(self.inner.eth_api.raw_transaction_by_hash(hash).await?) + self.inner.eth_api.raw_transaction_by_hash(hash).await.map_err(Eth::Error::into_rpc_err) } /// Handler for `debug_getRawTransactions` @@ -739,7 +754,9 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_raw_block(self, rlp_block, opts.unwrap_or_default()).await?) + Self::debug_trace_raw_block(self, rlp_block, opts.unwrap_or_default()) + .await + .map_err(Eth::Error::into_rpc_err) } /// Handler for `debug_traceBlockByHash` @@ -749,7 +766,9 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) + Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()) + .await + .map_err(Eth::Error::into_rpc_err) } /// Handler for `debug_traceBlockByNumber` @@ -759,7 +778,9 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) + Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()) + .await + .map_err(Eth::Error::into_rpc_err) } /// Handler for `debug_traceTransaction` @@ -769,7 +790,9 @@ where opts: Option, ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_transaction(self, tx_hash, opts.unwrap_or_default()).await?) + Self::debug_trace_transaction(self, tx_hash, opts.unwrap_or_default()) + .await + .map_err(Eth::Error::into_rpc_err) } /// Handler for `debug_traceCall` @@ -780,7 +803,9 @@ where opts: Option, ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_call(self, request, block_number, opts.unwrap_or_default()).await?) + Self::debug_trace_call(self, request, block_number, opts.unwrap_or_default()) + .await + .map_err(Eth::Error::into_rpc_err) } async fn debug_trace_call_many( @@ -790,7 +815,9 @@ where opts: Option, ) -> RpcResult>> { let _permit = self.acquire_trace_permit().await; - Ok(Self::debug_trace_call_many(self, bundles, state_context, opts).await?) + Self::debug_trace_call_many(self, bundles, state_context, opts) + .await + .map_err(Eth::Error::into_rpc_err) } async fn debug_backtrace_at(&self, _location: &str) -> RpcResult<()> { diff --git a/crates/rpc/rpc/src/eth/bundle.rs b/crates/rpc/rpc/src/eth/bundle.rs index d28013822ee1..61ed06d658bd 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -10,7 +10,11 @@ use reth_primitives::{ PooledTransactionsElement, U256, }; use reth_revm::database::StateProviderDatabase; -use reth_rpc_types::mev::{EthCallBundle, EthCallBundleResponse, EthCallBundleTransactionResult}; +use reth_rpc_eth_api::{FromEthApiError, FromEvmError}; +use reth_rpc_types::{ + mev::{EthCallBundle, EthCallBundleResponse, EthCallBundleTransactionResult}, + IntoRpcError, +}; use reth_tasks::pool::BlockingTaskGuard; use revm::{ db::CacheDB, @@ -23,9 +27,7 @@ use reth_rpc_eth_api::{ helpers::{Call, EthTransactions, LoadPendingBlock}, EthCallBundleApiServer, }; -use reth_rpc_eth_types::{ - utils::recover_raw_transaction, EthApiError, EthResult, RpcInvalidTransactionError, -}; +use reth_rpc_eth_types::{utils::recover_raw_transaction, EthApiError, RpcInvalidTransactionError}; /// `Eth` bundle implementation. pub struct EthBundle { @@ -48,7 +50,10 @@ where /// another (or the same) block. This can be used to simulate future blocks with the current /// state, or it can be used to simulate a past block. The sender is responsible for signing the /// transactions and using the correct nonce and ensuring validity - pub async fn call_bundle(&self, bundle: EthCallBundle) -> EthResult { + pub async fn call_bundle( + &self, + bundle: EthCallBundle, + ) -> Result { let EthCallBundle { txs, block_number, @@ -61,12 +66,14 @@ where if txs.is_empty() { return Err(EthApiError::InvalidParams( EthBundleError::EmptyBundleTransactions.to_string(), - )) + ) + .into()) } if block_number == 0 { return Err(EthApiError::InvalidParams( EthBundleError::BundleMissingBlockNumber.to_string(), - )) + ) + .into()) } let transactions = txs @@ -93,7 +100,8 @@ where { return Err(EthApiError::InvalidParams( EthBundleError::Eip4844BlobGasExceeded.to_string(), - )) + ) + .into()) } let block_id: reth_rpc_types::BlockId = state_block_number.into(); @@ -121,7 +129,8 @@ where let parent_block = block_env.number.saturating_to::(); // here we need to fetch the _next_ block's basefee based on the parent block let parent = LoadPendingBlock::provider(&self.inner.eth_api) - .header_by_number(parent_block)? + .header_by_number(parent_block) + .map_err(Eth::Error::from_err)? .ok_or_else(|| EthApiError::UnknownBlockNumber)?; if let Some(base_fee) = parent.next_block_base_fee( LoadPendingBlock::provider(&self.inner.eth_api) @@ -146,7 +155,8 @@ where let env = EnvWithHandlerCfg::new_with_cfg_env(cfg, block_env, TxEnv::default()); let db = CacheDB::new(StateProviderDatabase::new(state)); - let initial_coinbase = DatabaseRef::basic_ref(&db, coinbase)? + let initial_coinbase = DatabaseRef::basic_ref(&db, coinbase) + .map_err(Eth::Error::from_err)? .map(|acc| acc.balance) .unwrap_or_default(); let mut coinbase_balance_before_tx = initial_coinbase; @@ -164,8 +174,9 @@ where // Verify that the given blob data, commitments, and proofs are all valid for // this transaction. if let PooledTransactionsElement::BlobTransaction(ref tx) = tx { - tx.validate(EnvKzgSettings::Default.get()) - .map_err(|e| EthApiError::InvalidParams(e.to_string()))?; + tx.validate(EnvKzgSettings::Default.get()).map_err(|e| { + Eth::Error::from_err(EthApiError::InvalidParams(e.to_string())) + })?; } let tx = tx.into_transaction(); @@ -173,9 +184,11 @@ where hash_bytes.extend_from_slice(tx.hash().as_slice()); let gas_price = tx .effective_tip_per_gas(basefee) - .ok_or_else(|| RpcInvalidTransactionError::FeeCapTooLow)?; + .ok_or_else(|| RpcInvalidTransactionError::FeeCapTooLow) + .map_err(Eth::Error::from_err)?; Call::evm_config(ð_api).fill_tx_env(evm.tx_mut(), &tx, signer); - let ResultAndState { result, state } = evm.transact()?; + let ResultAndState { result, state } = + evm.transact().map_err(Eth::Error::from_evm_err)?; let gas_used = result.gas_used(); total_gas_used += gas_used; @@ -254,7 +267,7 @@ where Eth: EthTransactions + LoadPendingBlock + Call + 'static, { async fn call_bundle(&self, request: EthCallBundle) -> RpcResult { - Ok(Self::call_bundle(self, request).await?) + Self::call_bundle(self, request).await.map_err(Eth::Error::into_rpc_err) } } diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 09065dfc1a12..590d73f7f7e4 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -10,10 +10,11 @@ use reth_primitives::{BlockNumberOrTag, U256}; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; use reth_rpc_eth_api::{ helpers::{transaction::UpdateRawTxForwarder, EthSigner, SpawnBlocking}, - RawTransactionForwarder, + EthApiTypes, RawTransactionForwarder, }; use reth_rpc_eth_types::{ - EthApiBuilderCtx, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock, + EthApiBuilderCtx, EthApiError, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, + PendingBlock, }; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, @@ -114,6 +115,13 @@ where } } +impl EthApiTypes for EthApi +where + Self: Send + Sync, +{ + type Error = EthApiError; +} + impl std::fmt::Debug for EthApi { @@ -131,7 +139,7 @@ impl Clone for EthApi SpawnBlocking for EthApi where - Self: Clone + Send + Sync + 'static, + Self: EthApiTypes + Clone + Send + Sync + 'static, { #[inline] fn io_task_spawner(&self) -> impl reth_tasks::TaskSpawner { diff --git a/crates/rpc/rpc/src/eth/helpers/receipt.rs b/crates/rpc/rpc/src/eth/helpers/receipt.rs index db1fee781fd3..eb4483705f73 100644 --- a/crates/rpc/rpc/src/eth/helpers/receipt.rs +++ b/crates/rpc/rpc/src/eth/helpers/receipt.rs @@ -1,13 +1,13 @@ //! Builds an RPC receipt response w.r.t. data layout of network. -use reth_rpc_eth_api::helpers::LoadReceipt; +use reth_rpc_eth_api::{helpers::LoadReceipt, EthApiTypes}; use reth_rpc_eth_types::EthStateCache; use crate::EthApi; impl LoadReceipt for EthApi where - Self: Send + Sync, + Self: EthApiTypes, { #[inline] fn cache(&self) -> &EthStateCache { diff --git a/crates/rpc/rpc/src/eth/helpers/state.rs b/crates/rpc/rpc/src/eth/helpers/state.rs index b291eb8a2016..f76be9d88758 100644 --- a/crates/rpc/rpc/src/eth/helpers/state.rs +++ b/crates/rpc/rpc/src/eth/helpers/state.rs @@ -3,7 +3,10 @@ use reth_provider::{ChainSpecProvider, StateProviderFactory}; use reth_transaction_pool::TransactionPool; -use reth_rpc_eth_api::helpers::{EthState, LoadState, SpawnBlocking}; +use reth_rpc_eth_api::{ + helpers::{EthState, LoadState, SpawnBlocking}, + EthApiTypes, +}; use reth_rpc_eth_types::EthStateCache; use crate::EthApi; @@ -19,6 +22,7 @@ where impl LoadState for EthApi where + Self: EthApiTypes, Provider: StateProviderFactory + ChainSpecProvider, Pool: TransactionPool, { diff --git a/crates/rpc/rpc/src/eth/helpers/transaction.rs b/crates/rpc/rpc/src/eth/helpers/transaction.rs index 872af0cee451..635281c08e76 100644 --- a/crates/rpc/rpc/src/eth/helpers/transaction.rs +++ b/crates/rpc/rpc/src/eth/helpers/transaction.rs @@ -1,5 +1,7 @@ //! Contains RPC handler implementations specific to transactions +use std::sync::Arc; + use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, @@ -23,7 +25,7 @@ where } #[inline] - fn raw_tx_forwarder(&self) -> Option> { + fn raw_tx_forwarder(&self) -> Option> { self.inner.raw_tx_forwarder() } @@ -43,7 +45,7 @@ where type Pool = Pool; #[inline] - fn provider(&self) -> impl reth_provider::TransactionsProvider { + fn provider(&self) -> impl TransactionsProvider { self.inner.provider() } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 320c6856de06..055f8db16c88 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -14,7 +14,7 @@ use reth_rpc_types::{ }, parity::{Action, CreateAction, CreateOutput, TraceOutput}, }, - AnyTransactionReceipt, BlockTransactions, Header, RichBlock, + AnyTransactionReceipt, BlockTransactions, Header, IntoRpcError, RichBlock, }; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, @@ -85,7 +85,8 @@ where TransferInspector::new(false), |_tx_info, inspector, _, _| Ok(inspector.into_transfers()), ) - .await? + .await + .map_err(Eth::Error::into_rpc_err)? .map(|transfer_operations| { transfer_operations .iter() @@ -115,7 +116,8 @@ where _ => Ok(None), }) .await - .map(Option::flatten)?; + .map(Option::flatten) + .map_err(Eth::Error::into_rpc_err)?; Ok(maybe_revert) } @@ -128,7 +130,8 @@ where TracingInspectorConfig::default_parity(), move |_tx_info, inspector, _, _| Ok(inspector.into_traces().into_nodes()), ) - .await? + .await + .map_err(Eth::Error::into_rpc_err)? .map(|traces| { traces .into_iter() @@ -325,7 +328,8 @@ where Ok(inspector.into_parity_builder().into_localized_transaction_traces(tx_info)) }, ) - .await? + .await + .map_err(Eth::Error::into_rpc_err)? .map(|traces| { traces .into_iter() diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index fd0174a4e174..902033cea24e 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -1,7 +1,7 @@ use std::{collections::HashSet, sync::Arc}; use async_trait::async_trait; -use jsonrpsee::core::RpcResult as Result; +use jsonrpsee::core::RpcResult; use reth_chainspec::EthereumHardforks; use reth_consensus_common::calc::{ base_block_reward, base_block_reward_pre_merge, block_reward, ommer_reward, @@ -11,11 +11,11 @@ use reth_primitives::{BlockId, Bytes, Header, B256, U256}; use reth_provider::{BlockReader, ChainSpecProvider, EvmEnvProvider, StateProviderFactory}; use reth_revm::database::StateProviderDatabase; use reth_rpc_api::TraceApiServer; -use reth_rpc_eth_api::helpers::{Call, TraceExt}; -use reth_rpc_eth_types::{ - error::{EthApiError, EthResult}, - utils::recover_raw_transaction, +use reth_rpc_eth_api::{ + helpers::{Call, TraceExt}, + FromEthApiError, }; +use reth_rpc_eth_types::{error::EthApiError, utils::recover_raw_transaction}; use reth_rpc_types::{ state::{EvmOverrides, StateOverride}, trace::{ @@ -24,7 +24,7 @@ use reth_rpc_types::{ parity::*, tracerequest::TraceCallRequest, }, - BlockError, BlockOverrides, Index, TransactionRequest, + BlockError, BlockOverrides, Index, IntoRpcError, TransactionRequest, }; use reth_tasks::pool::BlockingTaskGuard; use revm::{ @@ -79,7 +79,10 @@ where Eth: TraceExt + 'static, { /// Executes the given call and returns a number of possible traces for it. - pub async fn trace_call(&self, trace_request: TraceCallRequest) -> EthResult { + pub async fn trace_call( + &self, + trace_request: TraceCallRequest, + ) -> Result { let at = trace_request.block_id.unwrap_or_default(); let config = TracingInspectorConfig::from_parity_config(&trace_request.trace_types); let overrides = @@ -93,11 +96,10 @@ where let db = db.0; let (res, _) = this.eth_api().inspect(&mut *db, env, &mut inspector)?; - let trace_res = inspector.into_parity_builder().into_trace_results_with_state( - &res, - &trace_request.trace_types, - &db, - )?; + let trace_res = inspector + .into_parity_builder() + .into_trace_results_with_state(&res, &trace_request.trace_types, &db) + .map_err(Eth::Error::from_err)?; Ok(trace_res) }) .await @@ -109,7 +111,7 @@ where tx: Bytes, trace_types: HashSet, block_id: Option, - ) -> EthResult { + ) -> Result { let tx = recover_raw_transaction(tx)?; let (cfg, block, at) = self.inner.eth_api.evm_env_at(block_id.unwrap_or_default()).await?; @@ -125,11 +127,10 @@ where self.inner .eth_api .spawn_trace_at_with_state(env, config, at, move |inspector, res, db| { - Ok(inspector.into_parity_builder().into_trace_results_with_state( - &res, - &trace_types, - &db, - )?) + inspector + .into_parity_builder() + .into_trace_results_with_state(&res, &trace_types, &db) + .map_err(Eth::Error::from_err) }) .await } @@ -142,7 +143,7 @@ where &self, calls: Vec<(TransactionRequest, HashSet)>, block_id: Option, - ) -> EthResult> { + ) -> Result, Eth::Error> { let at = block_id.unwrap_or(BlockId::pending()); let (cfg, block_env, at) = self.inner.eth_api.evm_env_at(at).await?; @@ -169,11 +170,10 @@ where let mut inspector = TracingInspector::new(config); let (res, _) = this.eth_api().inspect(&mut db, env, &mut inspector)?; - let trace_res = inspector.into_parity_builder().into_trace_results_with_state( - &res, - &trace_types, - &db, - )?; + let trace_res = inspector + .into_parity_builder() + .into_trace_results_with_state(&res, &trace_types, &db) + .map_err(Eth::Error::from_err)?; results.push(trace_res); @@ -196,16 +196,15 @@ where &self, hash: B256, trace_types: HashSet, - ) -> EthResult { + ) -> Result { let config = TracingInspectorConfig::from_parity_config(&trace_types); self.inner .eth_api .spawn_trace_transaction_in_block(hash, config, move |_, inspector, res, db| { - let trace_res = inspector.into_parity_builder().into_trace_results_with_state( - &res, - &trace_types, - &db, - )?; + let trace_res = inspector + .into_parity_builder() + .into_trace_results_with_state(&res, &trace_types, &db) + .map_err(Eth::Error::from_err)?; Ok(trace_res) }) .await @@ -223,7 +222,7 @@ where &self, hash: B256, indices: Vec, - ) -> EthResult> { + ) -> Result, Eth::Error> { if indices.len() != 1 { // The OG impl failed if it gets more than a single index return Ok(None) @@ -238,7 +237,7 @@ where &self, hash: B256, index: usize, - ) -> EthResult> { + ) -> Result, Eth::Error> { Ok(self.trace_transaction(hash).await?.and_then(|traces| traces.into_iter().nth(index))) } @@ -249,20 +248,21 @@ where pub async fn trace_filter( &self, filter: TraceFilter, - ) -> EthResult> { + ) -> Result, Eth::Error> { let matcher = filter.matcher(); let TraceFilter { from_block, to_block, .. } = filter; let start = from_block.unwrap_or(0); let end = if let Some(to_block) = to_block { to_block } else { - self.provider().best_block_number()? + self.provider().best_block_number().map_err(Eth::Error::from_err)? }; if start > end { return Err(EthApiError::InvalidParams( "invalid parameters: fromBlock cannot be greater than toBlock".to_string(), - )) + ) + .into()) } // ensure that the range is not too large, since we need to fetch all blocks in the range @@ -270,11 +270,12 @@ where if distance > 100 { return Err(EthApiError::InvalidParams( "Block range too large; currently limited to 100 blocks".to_string(), - )) + ) + .into()) } // fetch all blocks in that range - let blocks = self.provider().block_range(start..=end)?; + let blocks = self.provider().block_range(start..=end).map_err(Eth::Error::from_err)?; // find relevant blocks to trace let mut target_blocks = Vec::new(); @@ -282,7 +283,10 @@ where let mut transaction_indices = HashSet::new(); let mut highest_matching_index = 0; for (tx_idx, tx) in block.body.iter().enumerate() { - let from = tx.recover_signer_unchecked().ok_or(BlockError::InvalidSignature)?; + let from = tx + .recover_signer_unchecked() + .ok_or(BlockError::InvalidSignature) + .map_err(Eth::Error::from_err)?; let to = tx.to(); if matcher.matches(from, to) { let idx = tx_idx as u64; @@ -348,7 +352,7 @@ where pub async fn trace_transaction( &self, hash: B256, - ) -> EthResult>> { + ) -> Result>, Eth::Error> { self.inner .eth_api .spawn_trace_transaction_in_block( @@ -369,7 +373,7 @@ where pub async fn trace_block( &self, block_id: BlockId, - ) -> EthResult>> { + ) -> Result>, Eth::Error> { let traces = self.inner.eth_api.trace_block_with( block_id, TracingInspectorConfig::default_parity(), @@ -406,7 +410,7 @@ where &self, block_id: BlockId, trace_types: HashSet, - ) -> EthResult>> { + ) -> Result>, Eth::Error> { self.inner .eth_api .trace_block_with( @@ -419,7 +423,8 @@ where // If statediffs were requested, populate them with the account balance and // nonce from pre-state if let Some(ref mut state_diff) = full_trace.state_diff { - populate_state_diff(state_diff, db, state.iter())?; + populate_state_diff(state_diff, db, state.iter()) + .map_err(Eth::Error::from_err)?; } let trace = TraceResultsWithTransactionHash { @@ -437,7 +442,7 @@ where pub async fn trace_transaction_opcode_gas( &self, tx_hash: B256, - ) -> EthResult> { + ) -> Result, Eth::Error> { self.inner .eth_api .spawn_trace_transaction_in_block_with_inspector( @@ -461,7 +466,7 @@ where pub async fn trace_block_opcode_gas( &self, block_id: BlockId, - ) -> EthResult> { + ) -> Result, Eth::Error> { let res = self .inner .eth_api @@ -494,7 +499,7 @@ where /// - if Paris hardfork is activated, no block rewards are given /// - if Paris hardfork is not activated, calculate block rewards with block number only /// - if Paris hardfork is unknown, calculate block rewards with block number and ttd - fn calculate_base_block_reward(&self, header: &Header) -> EthResult> { + fn calculate_base_block_reward(&self, header: &Header) -> Result, Eth::Error> { let chain_spec = self.provider().chain_spec(); let is_paris_activated = chain_spec.is_paris_active_at_block(header.number); @@ -504,7 +509,11 @@ where None => { // if Paris hardfork is unknown, we need to fetch the total difficulty at the // block's height and check if it is pre-merge to calculate the base block reward - if let Some(header_td) = self.provider().header_td_by_number(header.number)? { + if let Some(header_td) = self + .provider() + .header_td_by_number(header.number) + .map_err(Eth::Error::from_err)? + { base_block_reward( chain_spec.as_ref(), header.number, @@ -570,11 +579,11 @@ where block_id: Option, state_overrides: Option, block_overrides: Option>, - ) -> Result { + ) -> RpcResult { let _permit = self.acquire_trace_permit().await; let request = TraceCallRequest { call, trace_types, block_id, state_overrides, block_overrides }; - Ok(Self::trace_call(self, request).await?) + Ok(Self::trace_call(self, request).await.map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_callMany` @@ -582,9 +591,9 @@ where &self, calls: Vec<(TransactionRequest, HashSet)>, block_id: Option, - ) -> Result> { + ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_call_many(self, calls, block_id).await?) + Ok(Self::trace_call_many(self, calls, block_id).await.map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_rawTransaction` @@ -593,9 +602,11 @@ where data: Bytes, trace_types: HashSet, block_id: Option, - ) -> Result { + ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_raw_transaction(self, data, trace_types, block_id).await?) + Ok(Self::trace_raw_transaction(self, data, trace_types, block_id) + .await + .map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_replayBlockTransactions` @@ -603,9 +614,11 @@ where &self, block_id: BlockId, trace_types: HashSet, - ) -> Result>> { + ) -> RpcResult>> { let _permit = self.acquire_trace_permit().await; - Ok(Self::replay_block_transactions(self, block_id, trace_types).await?) + Ok(Self::replay_block_transactions(self, block_id, trace_types) + .await + .map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_replayTransaction` @@ -613,18 +626,20 @@ where &self, transaction: B256, trace_types: HashSet, - ) -> Result { + ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(Self::replay_transaction(self, transaction, trace_types).await?) + Ok(Self::replay_transaction(self, transaction, trace_types) + .await + .map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_block` async fn trace_block( &self, block_id: BlockId, - ) -> Result>> { + ) -> RpcResult>> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_block(self, block_id).await?) + Ok(Self::trace_block(self, block_id).await.map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_filter` @@ -633,8 +648,8 @@ where /// /// # Limitations /// This currently requires block filter fields, since reth does not have address indices yet. - async fn trace_filter(&self, filter: TraceFilter) -> Result> { - Ok(Self::trace_filter(self, filter).await?) + async fn trace_filter(&self, filter: TraceFilter) -> RpcResult> { + Ok(Self::trace_filter(self, filter).await.map_err(Eth::Error::into_rpc_err)?) } /// Returns transaction trace at given index. @@ -643,33 +658,37 @@ where &self, hash: B256, indices: Vec, - ) -> Result> { + ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_get(self, hash, indices.into_iter().map(Into::into).collect()).await?) + Ok(Self::trace_get(self, hash, indices.into_iter().map(Into::into).collect()) + .await + .map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_transaction` async fn trace_transaction( &self, hash: B256, - ) -> Result>> { + ) -> RpcResult>> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_transaction(self, hash).await?) + Ok(Self::trace_transaction(self, hash).await.map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_transactionOpcodeGas` async fn trace_transaction_opcode_gas( &self, tx_hash: B256, - ) -> Result> { + ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_transaction_opcode_gas(self, tx_hash).await?) + Ok(Self::trace_transaction_opcode_gas(self, tx_hash) + .await + .map_err(Eth::Error::into_rpc_err)?) } /// Handler for `trace_blockOpcodeGas` - async fn trace_block_opcode_gas(&self, block_id: BlockId) -> Result> { + async fn trace_block_opcode_gas(&self, block_id: BlockId) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(Self::trace_block_opcode_gas(self, block_id).await?) + Ok(Self::trace_block_opcode_gas(self, block_id).await.map_err(Eth::Error::into_rpc_err)?) } } From 916e50924d16f4448ceddd0f21433c3a97094d82 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 18 Jul 2024 22:17:55 +0200 Subject: [PATCH 04/80] Fix OpEthApi impl --- crates/optimism/rpc/Cargo.toml | 1 + crates/optimism/rpc/src/error.rs | 43 +++++++++------------- crates/optimism/rpc/src/eth/block.rs | 19 ++++++---- crates/optimism/rpc/src/eth/call.rs | 19 +++++++--- crates/optimism/rpc/src/eth/mod.rs | 17 ++++++--- crates/optimism/rpc/src/eth/receipt.rs | 17 ++++++--- crates/optimism/rpc/src/eth/transaction.rs | 6 +-- crates/rpc/rpc-eth-api/src/core.rs | 6 +-- crates/stages/stages/src/stages/utils.rs | 2 +- 9 files changed, 74 insertions(+), 56 deletions(-) diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 8a7d6a135f37..1f0b15b6e38f 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -38,6 +38,7 @@ tokio.workspace = true # rpc jsonrpsee.workspace = true +jsonrpsee-types.workspace = true # misc thiserror.workspace = true diff --git a/crates/optimism/rpc/src/error.rs b/crates/optimism/rpc/src/error.rs index bf6ab931d268..c9bc865cfbdd 100644 --- a/crates/optimism/rpc/src/error.rs +++ b/crates/optimism/rpc/src/error.rs @@ -1,11 +1,11 @@ //! RPC errors specific to OP. use jsonrpsee::types::ErrorObject; -use reth_primitives::revm_primitives::InvalidTransaction; +use reth_primitives::revm_primitives::{InvalidTransaction, OptimismInvalidTransaction}; use reth_rpc_eth_api::AsEthApiError; use reth_rpc_eth_types::EthApiError; -use reth_rpc_server_types::result::internal_rpc_err; -use reth_rpc_types::ToRpcError; +use reth_rpc_server_types::result::{internal_rpc_err, rpc_err}; +use reth_rpc_types::{error::EthRpcErrorCode, IntoRpcError}; /// Optimism specific errors, that extend [`EthApiError`]. #[derive(Debug, thiserror::Error)] @@ -24,25 +24,12 @@ pub enum OpEthApiError { InvalidTransaction(OptimismInvalidTransactionError), } -impl ToRpcError for OpEthApiError { - fn to_rpc_error(&self) -> ErrorObject<'static> { +impl IntoRpcError for OpEthApiError { + fn into_rpc_err(self) -> ErrorObject<'static> { match self { + Self::Core(err) => err.into_rpc_err(), Self::L1BlockFeeError | Self::L1BlockGasError => internal_rpc_err(self.to_string()), - } - } -} - -impl From> for EthApiError -where - T: Into, -{ - fn from(err: EVMError) -> Self { - match err { - EVMError::Transaction(err) => match OptimismInvalidTransactionError::try_from(err) { - Ok(err) => Self::InvalidTransaction(err.into()), - Err(err) => Self::Core(EthApiError::InvalidTransaction(err.into())), - }, - _ => err.into_err(), + Self::InvalidTransaction(err) => err.into_rpc_err(), } } } @@ -67,8 +54,8 @@ pub enum OptimismInvalidTransactionError { HaltedDepositPostRegolith, } -impl ToRpcError for OptimismInvalidTransactionError { - fn to_rpc_error(&self) -> jsonrpsee_types::error::ErrorObject<'static> { +impl IntoRpcError for OptimismInvalidTransactionError { + fn into_rpc_err(self) -> jsonrpsee_types::error::ErrorObject<'static> { match self { Self::DepositSystemTxPostRegolith | Self::HaltedDepositPostRegolith => { rpc_err(EthRpcErrorCode::TransactionRejected.code(), self.to_string(), None) @@ -82,10 +69,14 @@ impl TryFrom for OptimismInvalidTransactionError { fn try_from(err: InvalidTransaction) -> Result { match err { - InvalidTransaction::DepositSystemTxPostRegolith => { - Ok(Self::DepositSystemTxPostRegolith) - } - InvalidTransaction::HaltedDepositPostRegolith => Ok(Self::HaltedDepositPostRegolith), + InvalidTransaction::OptimismError(err) => match err { + OptimismInvalidTransaction::DepositSystemTxPostRegolith => { + Ok(Self::DepositSystemTxPostRegolith) + } + OptimismInvalidTransaction::HaltedDepositPostRegolith => { + Ok(Self::HaltedDepositPostRegolith) + } + }, _ => Err(err), } } diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index c48d70907f10..c52abec753de 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -2,8 +2,11 @@ use reth_primitives::TransactionMeta; use reth_provider::{BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_api::helpers::{EthApiSpec, EthBlocks, LoadBlock, LoadReceipt, LoadTransaction}; -use reth_rpc_eth_types::{EthResult, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_api::{ + helpers::{EthApiSpec, EthBlocks, LoadBlock, LoadReceipt, LoadTransaction}, + FromEthApiError, +}; +use reth_rpc_eth_types::{EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, BlockId}; use crate::{op_receipt_fields, OpEthApi}; @@ -19,7 +22,7 @@ where async fn block_receipts( &self, block_id: BlockId, - ) -> EthResult>> + ) -> Result>, Self::Error> where Self: LoadReceipt, { @@ -52,11 +55,13 @@ where let optimism_tx_meta = self.build_op_tx_meta(tx, l1_block_info.clone(), timestamp)?; - ReceiptBuilder::new(tx, meta, receipt, &receipts).map(|builder| { - op_receipt_fields(builder, tx, receipt, optimism_tx_meta).build() - }) + ReceiptBuilder::new(tx, meta, receipt, &receipts) + .map(|builder| { + op_receipt_fields(builder, tx, receipt, optimism_tx_meta).build() + }) + .map_err(Self::Error::from_err) }) - .collect::>>(); + .collect::, Self::Error>>(); return receipts.map(Some) } diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index 03aa9a1f40a5..7285cf303fb1 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -3,13 +3,21 @@ use reth_primitives::{ revm_primitives::{BlockEnv, OptimismFields, TxEnv}, Bytes, }; -use reth_rpc_eth_api::helpers::Call; -use reth_rpc_eth_types::EthResult; +use reth_rpc_eth_api::{ + helpers::{Call, EthCall}, + EthApiTypes, FromEthApiError, +}; +use reth_rpc_eth_types::EthApiError; use reth_rpc_types::TransactionRequest; use crate::OpEthApi; -impl Call for OpEthApi { +impl EthCall for OpEthApi where EthApiError: From {} + +impl Call for OpEthApi +where + EthApiError: From, +{ fn call_gas_limit(&self) -> u64 { self.inner.call_gas_limit() } @@ -22,8 +30,9 @@ impl Call for OpEthApi { &self, block_env: &BlockEnv, request: TransactionRequest, - ) -> EthResult { - let mut env = Eth::create_txn_env(&self.inner, block_env, request)?; + ) -> Result { + let mut env = + self.inner.create_txn_env(block_env, request).map_err(Self::Error::from_err)?; env.optimism = OptimismFields { enveloped_tx: Some(Bytes::new()), ..Default::default() }; diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 1178ac1a77da..1f2b27c86e8f 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -18,10 +18,10 @@ use reth_provider::{BlockReaderIdExt, ChainSpecProvider, HeaderProvider, StatePr use reth_rpc::eth::DevSigner; use reth_rpc_eth_api::{ helpers::{ - AddDevSigners, EthApiSpec, EthCall, EthFees, EthSigner, EthState, LoadFee, LoadState, - SpawnBlocking, Trace, UpdateRawTxForwarder, + AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadFee, LoadState, SpawnBlocking, + Trace, UpdateRawTxForwarder, }, - RawTransactionForwarder, + EthApiTypes, RawTransactionForwarder, }; use reth_rpc_eth_types::EthStateCache; use reth_rpc_types::SyncStatus; @@ -29,6 +29,8 @@ use reth_tasks::{pool::BlockingTaskPool, TaskSpawner}; use reth_transaction_pool::TransactionPool; use tokio::sync::{AcquireError, OwnedSemaphorePermit}; +use crate::OpEthApiError; + /// OP-Reth `Eth` API implementation. /// /// This type provides the functionality for handling `eth_` related requests. @@ -51,6 +53,13 @@ impl OpEthApi { } } +impl EthApiTypes for OpEthApi +where + Eth: Send + Sync, +{ + type Error = OpEthApiError; +} + impl EthApiSpec for OpEthApi { fn protocol_version(&self) -> impl Future> + Send { self.inner.protocol_version() @@ -142,8 +151,6 @@ impl EthState for OpEthApi { } } -impl EthCall for OpEthApi {} - impl EthFees for OpEthApi {} impl Trace for OpEthApi { diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index f11771d615f6..50e8f90415c4 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -1,8 +1,11 @@ //! Loads and formats OP receipt RPC response. use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; -use reth_rpc_eth_api::helpers::{EthApiSpec, LoadReceipt, LoadTransaction}; -use reth_rpc_eth_types::{EthApiError, EthResult, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_api::{ + helpers::{EthApiSpec, LoadReceipt, LoadTransaction}, + FromEthApiError, +}; +use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, OptimismTransactionReceiptFields}; use crate::{OpEthApi, OptimismTxMeta}; @@ -21,17 +24,19 @@ where tx: TransactionSigned, meta: TransactionMeta, receipt: Receipt, - ) -> EthResult { + ) -> Result { let (block, receipts) = LoadReceipt::cache(self) .get_block_and_receipts(meta.block_hash) - .await? - .ok_or(EthApiError::UnknownBlockNumber)?; + .await + .map_err(Self::Error::from_err)? + .ok_or(Self::Error::from_err(EthApiError::UnknownBlockNumber))?; let block = block.unseal(); let l1_block_info = reth_evm_optimism::extract_l1_info(&block).ok(); let optimism_tx_meta = self.build_op_tx_meta(&tx, l1_block_info, block.timestamp)?; - let resp_builder = ReceiptBuilder::new(&tx, meta, &receipt, &receipts)?; + let resp_builder = + ReceiptBuilder::new(&tx, meta, &receipt, &receipts).map_err(Self::Error::from_err)?; let resp_builder = op_receipt_fields(resp_builder, &tx, &receipt, optimism_tx_meta); Ok(resp_builder.build()) diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 326c3c73d1c8..6689e230f1ce 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -7,9 +7,9 @@ use reth_primitives::TransactionSigned; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction}, - RawTransactionForwarder, + EthApiTypes, RawTransactionForwarder, }; -use reth_rpc_eth_types::{EthResult, EthStateCache}; +use reth_rpc_eth_types::EthStateCache; use revm::L1BlockInfo; use crate::{OpEthApi, OpEthApiError}; @@ -79,7 +79,7 @@ where tx: &TransactionSigned, l1_block_info: Option, block_timestamp: u64, - ) -> EthResult { + ) -> Result::Error> { let Some(l1_block_info) = l1_block_info else { return Ok(OptimismTxMeta::default()) }; let (l1_fee, l1_data_gas) = if !tx.is_deposit() { diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 804be3300252..c9faca758e69 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -44,7 +44,7 @@ where where EthApiError: From, { - Into::::into(Into::::into(err)) + T::from(EthApiError::from(err)) } } @@ -58,13 +58,13 @@ pub trait IntoEthApiError: Into { impl IntoEthApiError for T where - T: Into, + EthApiError: From, { fn into_err(self) -> E where E: FromEthApiError, { - Into::::into(Into::::into(self)) + E::from_err(self) } } diff --git a/crates/stages/stages/src/stages/utils.rs b/crates/stages/stages/src/stages/utils.rs index 3b623c358e55..15e88a284011 100644 --- a/crates/stages/stages/src/stages/utils.rs +++ b/crates/stages/stages/src/stages/utils.rs @@ -186,7 +186,7 @@ where Ok(()) } -/// Shard and insert the indice list according to [`LoadMode`] and its length. +/// Shard and insert the indices list according to [`LoadMode`] and its length. pub(crate) fn load_indices( cursor: &mut C, partial_key: P, From 20fae32fc6d3a5d4db5367a96d3d45fe0a4c6ef1 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 24 Jul 2024 18:24:21 +0200 Subject: [PATCH 05/80] Extend EthApiTypes with alloy_network::Network AT --- Cargo.lock | 4 ++++ crates/optimism/primitives/Cargo.toml | 6 +++++- crates/optimism/primitives/src/lib.rs | 1 + crates/optimism/primitives/src/types.rs | 6 ++++++ crates/rpc/rpc-eth-api/Cargo.toml | 1 + crates/rpc/rpc-eth-api/src/core.rs | 2 ++ crates/rpc/rpc/src/eth/core.rs | 2 ++ 7 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 crates/optimism/primitives/src/types.rs diff --git a/Cargo.lock b/Cargo.lock index 4277797bbc33..0a575d88a7af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7945,6 +7945,9 @@ dependencies = [ [[package]] name = "reth-optimism-primitives" version = "1.0.3" +dependencies = [ + "alloy-network", +] [[package]] name = "reth-optimism-rpc" @@ -8368,6 +8371,7 @@ name = "reth-rpc-eth-api" version = "1.0.3" dependencies = [ "alloy-dyn-abi", + "alloy-network", "async-trait", "auto_impl", "dyn-clone", diff --git a/crates/optimism/primitives/Cargo.toml b/crates/optimism/primitives/Cargo.toml index 0acd2f1ebdca..4d222bc7bf8d 100644 --- a/crates/optimism/primitives/Cargo.toml +++ b/crates/optimism/primitives/Cargo.toml @@ -9,4 +9,8 @@ repository.workspace = true description = "OP primitive types" [lints] -workspace = true \ No newline at end of file +workspace = true + +[dependencies] +# ethereum +alloy-network.workspace = true diff --git a/crates/optimism/primitives/src/lib.rs b/crates/optimism/primitives/src/lib.rs index 5cdb53def7fc..9a0528259288 100644 --- a/crates/optimism/primitives/src/lib.rs +++ b/crates/optimism/primitives/src/lib.rs @@ -8,3 +8,4 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] pub mod bedrock_import; +pub mod types; diff --git a/crates/optimism/primitives/src/types.rs b/crates/optimism/primitives/src/types.rs new file mode 100644 index 000000000000..9671955bc2be --- /dev/null +++ b/crates/optimism/primitives/src/types.rs @@ -0,0 +1,6 @@ +use alloy_network::Network; + +#[derive(Debug, Clone, Copy)] +pub struct Optimism; + +impl Network for Optimism {} diff --git a/crates/rpc/rpc-eth-api/Cargo.toml b/crates/rpc/rpc-eth-api/Cargo.toml index 82f13b82a897..20a4048ad9c5 100644 --- a/crates/rpc/rpc-eth-api/Cargo.toml +++ b/crates/rpc/rpc-eth-api/Cargo.toml @@ -32,6 +32,7 @@ reth-rpc-server-types.workspace = true # ethereum alloy-dyn-abi = { workspace = true, features = ["eip712"] } +alloy-network.workspace = true # rpc jsonrpsee = { workspace = true, features = ["server", "macros"] } diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index da7adb368a9a..4bfdeb90fdc2 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -27,6 +27,8 @@ use crate::helpers::{ pub trait EthApiTypes: Send + Sync { /// Extension of [`EthApiError`], with network specific errors. type Error: IntoRpcError + FromEthApiError + AsEthApiError + FromEvmError; + /// Blockchain data types, specific to network, e.g. block and transaction. + type Types: alloy_network::Network; } /// Helper trait to wrap core [`EthApiError`]. diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 590d73f7f7e4..689e2e392084 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -3,6 +3,7 @@ use std::sync::Arc; +use alloy_network::Ethereum; use derive_more::Deref; use futures::Future; use reth_node_api::{BuilderProvider, FullNodeComponents}; @@ -120,6 +121,7 @@ where Self: Send + Sync, { type Error = EthApiError; + type Types = Ethereum; } impl std::fmt::Debug From 83bd53bff281b76f2d7221707a59a92b1ecaf21f Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 26 Jul 2024 21:52:29 +0200 Subject: [PATCH 06/80] Import OP rpc types from op-alloy-network --- crates/optimism/rpc/src/eth/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 1f2b27c86e8f..e5127262bdcf 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -10,6 +10,7 @@ mod pending_block; use std::{future::Future, sync::Arc}; use alloy_primitives::{Address, U64}; +use op_alloy_network::Optimism; use reth_chainspec::{ChainInfo, ChainSpec}; use reth_errors::RethResult; use reth_evm::ConfigureEvm; @@ -58,6 +59,7 @@ where Eth: Send + Sync, { type Error = OpEthApiError; + type Types = Optimism; } impl EthApiSpec for OpEthApi { From ad292463f5d26b3ae8b6e666479c4d41ad7b5677 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 26 Jul 2024 22:14:57 +0200 Subject: [PATCH 07/80] Rename EthApiTypes::Types to EthApiTypes::NetworkTypes --- crates/optimism/rpc/src/eth/mod.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 2 +- crates/rpc/rpc/src/eth/core.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index e5127262bdcf..24ef40985f31 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -59,7 +59,7 @@ where Eth: Send + Sync, { type Error = OpEthApiError; - type Types = Optimism; + type NetworkTypes = Optimism; } impl EthApiSpec for OpEthApi { diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 938142086870..29d620901ee6 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -15,5 +15,5 @@ pub trait EthApiTypes: Send + Sync { + Send + Sync; /// Blockchain data types, specific to network, e.g. block and transaction. - type Types: alloy_network::Network; + type NetworkTypes: alloy_network::Network; } diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 689e2e392084..98a6ecc41727 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -121,7 +121,7 @@ where Self: Send + Sync, { type Error = EthApiError; - type Types = Ethereum; + type NetworkTypes = Ethereum; } impl std::fmt::Debug From 6bd0f6057dc8ffb6675b9adfb58da15b328169a2 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 00:04:08 +0200 Subject: [PATCH 08/80] Remove optimism feature from reth-rpc-types-compat lib --- Cargo.lock | 4 + Cargo.toml | 1 + crates/optimism/rpc/Cargo.toml | 4 +- crates/optimism/rpc/src/eth/mod.rs | 25 +++ crates/rpc/rpc-eth-api/src/core.rs | 2 +- .../rpc-eth-api/src/helpers/transaction.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 4 +- crates/rpc/rpc-types-compat/Cargo.toml | 4 + crates/rpc/rpc-types-compat/src/lib.rs | 2 + .../rpc-types-compat/src/transaction/mod.rs | 153 +++++++----------- crates/rpc/rpc/src/eth/core.rs | 63 ++++++++ 11 files changed, 166 insertions(+), 98 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a022dc34b63a..f311a13dc89b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7989,6 +7989,7 @@ name = "reth-optimism-rpc" version = "1.0.3" dependencies = [ "alloy-primitives", + "alloy-rpc-types", "jsonrpsee", "jsonrpsee-types", "op-alloy-network", @@ -8005,6 +8006,7 @@ dependencies = [ "reth-rpc-eth-types", "reth-rpc-server-types", "reth-rpc-types", + "reth-rpc-types-compat", "reth-tasks", "reth-transaction-pool", "revm", @@ -8531,8 +8533,10 @@ dependencies = [ name = "reth-rpc-types-compat" version = "1.0.3" dependencies = [ + "alloy-network", "alloy-rlp", "alloy-rpc-types", + "op-alloy-network", "reth-primitives", "reth-rpc-types", "reth-trie-common", diff --git a/Cargo.toml b/Cargo.toml index 073a26d14002..4cb23320f492 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -431,6 +431,7 @@ alloy-rpc-client = { version = "0.2", default-features = false } # op op-alloy-rpc-types = "0.1" +op-alloy-network = "0.1" # misc auto_impl = "1" diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 3446f251e23a..5b27e7313db7 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -27,10 +27,12 @@ reth-tasks = { workspace = true, features = ["rayon"] } reth-transaction-pool.workspace = true reth-rpc.workspace = true reth-node-api.workspace = true +reth-rpc-types-compat.workspace = true # ethereum alloy-primitives.workspace = true -op-alloy-network = "0.1" +alloy-rpc-types.workspace = true +op-alloy-network.workspace = true revm.workspace = true # async diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 24ef40985f31..1b19e27be5d2 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -10,6 +10,7 @@ mod pending_block; use std::{future::Future, sync::Arc}; use alloy_primitives::{Address, U64}; +use alloy_rpc_types::optimism::OptimismTransactionFields; use op_alloy_network::Optimism; use reth_chainspec::{ChainInfo, ChainSpec}; use reth_errors::RethResult; @@ -26,6 +27,7 @@ use reth_rpc_eth_api::{ }; use reth_rpc_eth_types::EthStateCache; use reth_rpc_types::SyncStatus; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::{pool::BlockingTaskPool, TaskSpawner}; use reth_transaction_pool::TransactionPool; use tokio::sync::{AcquireError, OwnedSemaphorePermit}; @@ -62,6 +64,29 @@ where type NetworkTypes = Optimism; } +impl TransactionBuilder for OpEthApi { + type Transaction = ::TransactionResponse; + + fn fill( + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let mut resp = Eth::fill(tx, block_hash, block_number, base_fee, transaction_index); + + resp.other = OptimismTransactionFields { + source_hash: signed_tx.source_hash(), + mint: signed_tx.mint(), + is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), + } + .into(); + + resp + } +} + impl EthApiSpec for OpEthApi { fn protocol_version(&self) -> impl Future> + Send { self.inner.protocol_version() diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index a86b5c956f16..c2977c477919 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -28,7 +28,7 @@ impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxF /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi { +pub trait EthApi: EthApiTypes { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index bd2b2ffd55f0..00970443511c 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -53,7 +53,7 @@ use super::{ /// See also /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. -pub trait EthTransactions: LoadTransaction { +pub trait EthTransactions: LoadTransaction + FormatTransactionResponse { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 29d620901ee6..7613756d9c8f 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -2,6 +2,8 @@ use std::error::Error; +use alloy_network::Network; + use crate::{AsEthApiError, FromEthApiError, FromEvmError}; /// Network specific `eth` API types. @@ -15,5 +17,5 @@ pub trait EthApiTypes: Send + Sync { + Send + Sync; /// Blockchain data types, specific to network, e.g. block and transaction. - type NetworkTypes: alloy_network::Network; + type NetworkTypes: Network; } diff --git a/crates/rpc/rpc-types-compat/Cargo.toml b/crates/rpc/rpc-types-compat/Cargo.toml index a589ef418c64..66d65893ec25 100644 --- a/crates/rpc/rpc-types-compat/Cargo.toml +++ b/crates/rpc/rpc-types-compat/Cargo.toml @@ -15,8 +15,12 @@ workspace = true reth-primitives.workspace = true reth-rpc-types.workspace = true reth-trie-common.workspace = true + +# ethereum +alloy-network.workspace = true alloy-rlp.workspace = true alloy-rpc-types.workspace = true +op-alloy-network.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 99eff4fa7930..9e786dbe1c8d 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -14,3 +14,5 @@ pub mod block; pub mod engine; pub mod proof; pub mod transaction; + +pub use transaction::TransactionBuilder; diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 70a01ce1b783..9369e1961500 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -1,118 +1,83 @@ //! Compatibility functions for rpc `Transaction` type. -use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; -use reth_primitives::{Address, BlockNumber, TransactionSignedEcRecovered, TxKind, TxType, B256}; -use reth_rpc_types::Transaction; -use signature::from_primitive_signature; pub use typed::*; mod signature; mod typed; +use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; +use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; + +/// Builds a RPC transaction response w.r.t. network. +pub trait TransactionBuilder { + /// RPC transaction response type. + type Transaction; + + /// Returns gas price and max fee per gas w.r.t. network specific transaction type. + fn gas_price(signed_tx: TransactionSigned, base_fee: Option) -> GasPrice { + match signed_tx.tx_type() { + TxType::Legacy | TxType::Eip2930 => { + GasPrice { gas_price: Some(signed_tx.max_fee_per_gas()), max_fee_per_gas: None } + } + TxType::Eip1559 | TxType::Eip4844 => { + // the gas price field for EIP1559 is set to `min(tip, gasFeeCap - baseFee) + + // baseFee` + let gas_price = base_fee + .and_then(|base_fee| { + signed_tx + .effective_tip_per_gas(Some(base_fee)) + .map(|tip| tip + base_fee as u128) + }) + .unwrap_or_else(|| signed_tx.max_fee_per_gas()); + + GasPrice { + gas_price: Some(gas_price), + max_fee_per_gas: Some(signed_tx.max_fee_per_gas()), + } + } + _ => GasPrice::default(), + } + } + + /// Create a new rpc transaction result for a _pending_ signed transaction, setting block + /// environment related fields to `None`. + fn fill( + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction; +} + +/// Gas price and max fee per gas for a transaction. Helper type to format transaction RPC response. +#[derive(Debug, Default)] +pub struct GasPrice { + /// Gas price for transaction. + pub gas_price: Option, + /// Max fee per gas for transaction. + pub max_fee_per_gas: Option, +} + /// Create a new rpc transaction result for a mined transaction, using the given block hash, /// number, and tx index fields to populate the corresponding fields in the rpc result. /// /// The block hash, number, and tx index fields should be from the original block where the /// transaction was mined. -pub fn from_recovered_with_block_context( +pub fn from_recovered_with_block_context( tx: TransactionSignedEcRecovered, block_hash: B256, block_number: BlockNumber, base_fee: Option, tx_index: usize, -) -> Transaction { - fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) +) -> T::Transaction { + T::fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) } /// Create a new rpc transaction result for a _pending_ signed transaction, setting block /// environment related fields to `None`. -pub fn from_recovered(tx: TransactionSignedEcRecovered) -> Transaction { - fill(tx, None, None, None, None) -} - -/// Create a new rpc transaction result for a _pending_ signed transaction, setting block -/// environment related fields to `None`. -fn fill( - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, -) -> Transaction { - let signer = tx.signer(); - let signed_tx = tx.into_signed(); - - let to: Option
= match signed_tx.kind() { - TxKind::Create => None, - TxKind::Call(to) => Some(Address(*to)), - }; - - #[allow(unreachable_patterns)] - let (gas_price, max_fee_per_gas) = match signed_tx.tx_type() { - TxType::Legacy | TxType::Eip2930 => (Some(signed_tx.max_fee_per_gas()), None), - TxType::Eip1559 | TxType::Eip4844 => { - // the gas price field for EIP1559 is set to `min(tip, gasFeeCap - baseFee) + - // baseFee` - let gas_price = base_fee - .and_then(|base_fee| { - signed_tx - .effective_tip_per_gas(Some(base_fee)) - .map(|tip| tip + base_fee as u128) - }) - .unwrap_or_else(|| signed_tx.max_fee_per_gas()); - - (Some(gas_price), Some(signed_tx.max_fee_per_gas())) - } - _ => { - // OP-deposit - (None, None) - } - }; - - // let chain_id = signed_tx.chain_id().map(U64::from); - let chain_id = signed_tx.chain_id(); - let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); - let access_list = signed_tx.access_list().cloned(); - let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); - - let signature = - from_primitive_signature(*signed_tx.signature(), signed_tx.tx_type(), signed_tx.chain_id()); - - Transaction { - hash: signed_tx.hash(), - nonce: signed_tx.nonce(), - from: signer, - to, - value: signed_tx.value(), - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), - signature: Some(signature), - gas: signed_tx.gas_limit() as u128, - input: signed_tx.input().clone(), - chain_id, - access_list, - transaction_type: Some(signed_tx.tx_type() as u8), - - // These fields are set to None because they are not stored as part of the transaction - block_hash, - block_number, - transaction_index: transaction_index.map(|idx| idx as u64), - // EIP-4844 fields - max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), - blob_versioned_hashes, - authorization_list, - // Optimism fields - #[cfg(feature = "optimism")] - other: reth_rpc_types::optimism::OptimismTransactionFields { - source_hash: signed_tx.source_hash(), - mint: signed_tx.mint(), - is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), - } - .into(), - #[cfg(not(feature = "optimism"))] - other: Default::default(), - } +pub fn from_recovered(tx: TransactionSignedEcRecovered) -> T::Transaction { + T::fill(tx, None, None, None, None) } /// Convert [`TransactionSignedEcRecovered`] to [`TransactionRequest`] diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 98a6ecc41727..e42ae6bd2d66 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -124,6 +124,69 @@ where type NetworkTypes = Ethereum; } +impl TransactionResponse + for EthApi +{ + type Transaction = ::TransactionResponse; + + fn fill( + &self, + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let signer = tx.signer(); + let signed_tx = tx.into_signed(); + + let to: Option
= match signed_tx.kind() { + TxKind::Create => None, + TxKind::Call(to) => Some(Address(*to)), + }; + + let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(signed_tx, base_fee); + + // let chain_id = signed_tx.chain_id().map(U64::from); + let chain_id = signed_tx.chain_id(); + let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); + let access_list = signed_tx.access_list().cloned(); + let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); + + let signature = from_primitive_signature( + *signed_tx.signature(), + signed_tx.tx_type(), + signed_tx.chain_id(), + ); + + Self::Transaction { + hash: signed_tx.hash(), + nonce: signed_tx.nonce(), + from: signer, + to, + value: signed_tx.value(), + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), + signature: Some(signature), + gas: signed_tx.gas_limit() as u128, + input: signed_tx.input().clone(), + chain_id, + access_list, + transaction_type: Some(signed_tx.tx_type() as u8), + // These fields are set to None because they are not stored as part of the transaction + block_hash, + block_number, + transaction_index: transaction_index.map(|idx| idx as u64), + // EIP-4844 fields + max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), + blob_versioned_hashes, + authorization_list, + other: Default::default(), + } + } +} + impl std::fmt::Debug for EthApi { From e248a65fba24e582bcdca1febfb9fe5558a9f342 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 00:49:11 +0200 Subject: [PATCH 09/80] Incorporate TransactionBuilder into EthTransactions --- crates/rpc/rpc-eth-api/src/helpers/transaction.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 00970443511c..ad201c577603 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -4,6 +4,7 @@ use std::{fmt, ops::Deref, sync::Arc}; use alloy_dyn_abi::TypedData; +use alloy_network::Network; use futures::Future; use reth_primitives::{ Address, BlockId, Bytes, FromRecoveredPooledTransaction, IntoRecoveredTransaction, Receipt, @@ -21,7 +22,7 @@ use reth_rpc_types::{ }, AnyTransactionReceipt, Transaction, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::transaction::from_recovered_with_block_context; +use reth_rpc_types_compat::{transaction::from_recovered_with_block_context, TransactionBuilder}; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; use crate::{FromEthApiError, IntoEthApiError}; @@ -53,7 +54,10 @@ use super::{ /// See also /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. -pub trait EthTransactions: LoadTransaction + FormatTransactionResponse { +pub trait EthTransactions: + LoadTransaction + + TransactionBuilder::TransactionResponse> +{ /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -197,7 +201,7 @@ pub trait EthTransactions: LoadTransaction + FormatTransactionResponse { &self, block_id: BlockId, index: usize, - ) -> impl Future, Self::Error>> + Send + ) -> impl Future, Self::Error>> + Send where Self: LoadBlock, { From 624e938f753caefe0fad6e2fc2b875af8cfb4983 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 13:12:21 +0200 Subject: [PATCH 10/80] Revert unrelated change --- crates/optimism/cli/src/commands/import_receipts.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/optimism/cli/src/commands/import_receipts.rs b/crates/optimism/cli/src/commands/import_receipts.rs index 809c63e5cd62..30d2f82c9c61 100644 --- a/crates/optimism/cli/src/commands/import_receipts.rs +++ b/crates/optimism/cli/src/commands/import_receipts.rs @@ -270,6 +270,7 @@ mod test { /// No receipts for genesis block const EMPTY_RECEIPTS_GENESIS_BLOCK: &[u8] = &hex!("c0"); + #[ignore] #[tokio::test] async fn filter_out_genesis_block_receipts() { let mut f: File = tempfile().unwrap().into(); From 91ace3a5028d56965a55777f73c42b747134562a Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 13:46:53 +0200 Subject: [PATCH 11/80] Fix conflicts from making rpc comapt generic over network for transaction --- Cargo.lock | 2 - crates/optimism/rpc/src/eth/mod.rs | 9 ++-- crates/rpc/rpc-eth-api/src/core.rs | 53 ++++++++++--------- crates/rpc/rpc-eth-api/src/filter.rs | 4 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 33 +++++++----- .../rpc-eth-api/src/helpers/transaction.rs | 12 ++--- crates/rpc/rpc-eth-api/src/helpers/types.rs | 11 ++++ crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-api/src/pubsub.rs | 4 +- crates/rpc/rpc-eth-types/src/transaction.rs | 37 +++++++------ crates/rpc/rpc-types-compat/Cargo.toml | 2 - crates/rpc/rpc-types-compat/src/block.rs | 33 ++++++------ .../rpc-types-compat/src/transaction/mod.rs | 53 ++++++++++--------- .../src/transaction/signature.rs | 6 +-- crates/rpc/rpc/src/engine.rs | 11 ++-- crates/rpc/rpc/src/eth/core.rs | 22 +++++--- crates/rpc/rpc/src/eth/filter.rs | 38 +++++++------ crates/rpc/rpc/src/eth/pubsub.rs | 16 +++--- crates/rpc/rpc/src/otterscan.rs | 2 +- crates/rpc/rpc/src/txpool.rs | 39 +++++++++----- 20 files changed, 225 insertions(+), 164 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f311a13dc89b..fd28a2a2ca92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8533,10 +8533,8 @@ dependencies = [ name = "reth-rpc-types-compat" version = "1.0.3" dependencies = [ - "alloy-network", "alloy-rlp", "alloy-rpc-types", - "op-alloy-network", "reth-primitives", "reth-rpc-types", "reth-trie-common", diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 1b19e27be5d2..8106fe8d327a 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -9,6 +9,7 @@ mod pending_block; use std::{future::Future, sync::Arc}; +use alloy_network::Network; use alloy_primitives::{Address, U64}; use alloy_rpc_types::optimism::OptimismTransactionFields; use op_alloy_network::Optimism; @@ -23,7 +24,7 @@ use reth_rpc_eth_api::{ AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadFee, LoadState, SpawnBlocking, Trace, UpdateRawTxForwarder, }, - EthApiTypes, RawTransactionForwarder, + EthApiTypes, RawTransactionForwarder, Transaction, }; use reth_rpc_eth_types::EthStateCache; use reth_rpc_types::SyncStatus; @@ -64,8 +65,10 @@ where type NetworkTypes = Optimism; } -impl TransactionBuilder for OpEthApi { - type Transaction = ::TransactionResponse; +impl>> TransactionBuilder + for OpEthApi +{ + type Transaction = Transaction; fn fill( tx: TransactionSignedEcRecovered, diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index c2977c477919..674b40e96631 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -9,26 +9,29 @@ use reth_rpc_types::{ serde_helpers::JsonStorageKey, state::{EvmOverrides, StateOverride}, AccessListWithGasUsed, AnyTransactionReceipt, BlockOverrides, Bundle, - EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, RichBlock, - StateContext, SyncStatus, Transaction, TransactionRequest, Work, + EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, + SyncStatus, TransactionRequest, Work, }; use tracing::trace; -use crate::helpers::{ - transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, - EthTransactions, FullEthApi, +use crate::{ + helpers::{ + transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, + EthTransactions, FullEthApi, + }, + Block, EthApiTypes, Transaction, }; /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. -pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} -impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi: EthApiTypes { +pub trait EthApi { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; @@ -55,7 +58,7 @@ pub trait EthApi: EthApiTypes { /// Returns information about a block by hash. #[method(name = "getBlockByHash")] - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>; + async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>>; /// Returns information about a block by number. #[method(name = "getBlockByNumber")] @@ -63,7 +66,7 @@ pub trait EthApi: EthApiTypes { &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult>; + ) -> RpcResult>>; /// Returns the number of transactions in a block from a block matching the given block hash. #[method(name = "getBlockTransactionCountByHash")] @@ -100,7 +103,7 @@ pub trait EthApi: EthApiTypes { &self, hash: B256, index: Index, - ) -> RpcResult>; + ) -> RpcResult>>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockNumberAndIndex")] @@ -108,7 +111,7 @@ pub trait EthApi: EthApiTypes { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>; + ) -> RpcResult>>; /// Returns the EIP-2718 encoded transaction if it exists. /// @@ -118,7 +121,7 @@ pub trait EthApi: EthApiTypes { /// Returns the information about a transaction requested by transaction hash. #[method(name = "getTransactionByHash")] - async fn transaction_by_hash(&self, hash: B256) -> RpcResult>; + async fn transaction_by_hash(&self, hash: B256) -> RpcResult>>; /// Returns information about a raw transaction by block hash and transaction index position. #[method(name = "getRawTransactionByBlockHashAndIndex")] @@ -134,7 +137,7 @@ pub trait EthApi: EthApiTypes { &self, hash: B256, index: Index, - ) -> RpcResult>; + ) -> RpcResult>>; /// Returns information about a raw transaction by block number and transaction index /// position. @@ -151,7 +154,7 @@ pub trait EthApi: EthApiTypes { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>; + ) -> RpcResult>>; /// Returns the receipt of a transaction by transaction hash. #[method(name = "getTransactionReceipt")] @@ -332,7 +335,7 @@ pub trait EthApi: EthApiTypes { } #[async_trait::async_trait] -impl EthApiServer for T +impl EthApiServer for T where T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, @@ -375,7 +378,7 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult> { + async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); Ok(EthBlocks::rpc_block(self, hash.into(), full).await?) } @@ -385,7 +388,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); Ok(EthBlocks::rpc_block(self, number.into(), full).await?) } @@ -434,7 +437,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?) } @@ -444,7 +447,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?) } @@ -456,9 +459,11 @@ where } /// Handler for: `eth_getTransactionByHash` - async fn transaction_by_hash(&self, hash: B256) -> RpcResult> { + async fn transaction_by_hash(&self, hash: B256) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); - Ok(EthTransactions::transaction_by_hash(self, hash).await?.map(Into::into)) + Ok(EthTransactions::transaction_by_hash(self, hash) + .await? + .map(|tx| tx.into_transaction(self))) } /// Handler for: `eth_getRawTransactionByBlockHashAndIndex` @@ -477,7 +482,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await?) @@ -503,7 +508,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) .await?) diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index da53b577eec5..ad885745460b 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -3,10 +3,12 @@ use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_rpc_types::{Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind}; +use crate::EthApiTypesCompat; + /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthFilterApi { +pub trait EthFilterApi { /// Creates anew filter and returns its id. #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult; diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 837006a970ef..3fa0eae88a70 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -6,10 +6,13 @@ use futures::Future; use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, TransactionMeta}; use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; -use reth_rpc_types::{AnyTransactionReceipt, Header, Index, RichBlock}; -use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; +use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; +use reth_rpc_types_compat::{ + block::{from_block, uncle_block_from_header}, + TransactionBuilder, +}; -use crate::FromEthApiError; +use crate::{Block, FromEthApiError, Transaction}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; @@ -27,7 +30,7 @@ pub trait EthBlocks: LoadBlock { block_id: BlockId, ) -> impl Future, Self::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: TransactionBuilder>, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -40,9 +43,9 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future, Self::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where - Self: LoadPendingBlock + SpawnBlocking, + Self: TransactionBuilder>, { async move { let block = match self.block_with_senders(block_id).await? { @@ -54,9 +57,10 @@ pub trait EthBlocks: LoadBlock { .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) - .map_err(Self::Error::from_eth_err)?; - Ok(Some(block.into())) + let block = + from_block::(block.unseal(), total_difficulty, full.into(), Some(block_hash)) + .map_err(Self::Error::from_eth_err)?; + Ok(Some(Rich { inner: block.into(), extra_info: Default::default() })) } } @@ -187,7 +191,10 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send + where + Self: TransactionBuilder>, + { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching @@ -203,8 +210,10 @@ pub trait EthBlocks: LoadBlock { .unwrap_or_default(); let index = usize::from(index); - let uncle = - uncles.into_iter().nth(index).map(|header| uncle_block_from_header(header).into()); + let uncle = uncles.into_iter().nth(index).map(|header| Rich { + inner: uncle_block_from_header(header), + extra_info: Default::default(), + }); Ok(uncle) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index ad201c577603..98174cef4dcf 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -4,7 +4,6 @@ use std::{fmt, ops::Deref, sync::Arc}; use alloy_dyn_abi::TypedData; -use alloy_network::Network; use futures::Future; use reth_primitives::{ Address, BlockId, Bytes, FromRecoveredPooledTransaction, IntoRecoveredTransaction, Receipt, @@ -20,12 +19,12 @@ use reth_rpc_types::{ EIP1559TransactionRequest, EIP2930TransactionRequest, EIP4844TransactionRequest, LegacyTransactionRequest, }, - AnyTransactionReceipt, Transaction, TransactionRequest, TypedTransactionRequest, + AnyTransactionReceipt, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::{transaction::from_recovered_with_block_context, TransactionBuilder}; +use reth_rpc_types_compat::TransactionBuilder; use reth_transaction_pool::{TransactionOrigin, TransactionPool}; -use crate::{FromEthApiError, IntoEthApiError}; +use crate::{FromEthApiError, IntoEthApiError, Transaction}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking, @@ -55,8 +54,7 @@ use super::{ /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. pub trait EthTransactions: - LoadTransaction - + TransactionBuilder::TransactionResponse> + LoadTransaction + TransactionBuilder> { /// Returns a handle for reading data from disk. /// @@ -211,7 +209,7 @@ pub trait EthTransactions: let block_number = block.number; let base_fee_per_gas = block.base_fee_per_gas; if let Some(tx) = block.into_transactions_ecrecovered().nth(index) { - return Ok(Some(from_recovered_with_block_context( + return Ok(Some(self.from_recovered_with_block_context( tx, block_hash, block_number, diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 7613756d9c8f..20c4f6c267ab 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -3,6 +3,8 @@ use std::error::Error; use alloy_network::Network; +use reth_rpc_types::Rich; +use reth_rpc_types_compat::TransactionBuilder; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -19,3 +21,12 @@ pub trait EthApiTypes: Send + Sync { /// Blockchain data types, specific to network, e.g. block and transaction. type NetworkTypes: Network; } + +/// Helper trait that unifies [`EthApiTypes`] with the necessary type conversions. +pub trait EthApiTypesCompat: EthApiTypes + TransactionBuilder {} + +/// Adapter for network specific transaction type. +pub type Transaction = <::NetworkTypes as Network>::TransactionResponse; + +/// Adapter for network specific block type. +pub type Block = Rich>>; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index c707a94eef4f..933e947d2e90 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::EthApiTypes, + types::{Block, EthApiTypes, EthApiTypesCompat, Transaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-api/src/pubsub.rs b/crates/rpc/rpc-eth-api/src/pubsub.rs index 8de125152823..4d729c883c47 100644 --- a/crates/rpc/rpc-eth-api/src/pubsub.rs +++ b/crates/rpc/rpc-eth-api/src/pubsub.rs @@ -3,9 +3,11 @@ use jsonrpsee::proc_macros::rpc; use reth_rpc_types::pubsub::{Params, SubscriptionKind}; +use crate::EthApiTypesCompat; + /// Ethereum pub-sub rpc interface. #[rpc(server, namespace = "eth")] -pub trait EthPubSubApi { +pub trait EthPubSubApi { /// Create an ethereum subscription for the given params #[subscription( name = "subscribe" => "subscription", diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index 32c81d3966f8..6e7297a2bceb 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -3,8 +3,8 @@ //! Transaction wrapper that labels transaction with its origin. use reth_primitives::{TransactionSignedEcRecovered, B256}; -use reth_rpc_types::{Transaction, TransactionInfo}; -use reth_rpc_types_compat::transaction::from_recovered_with_block_context; +use reth_rpc_types::TransactionInfo; +use reth_rpc_types_compat::TransactionBuilder; /// Represents from where a transaction was fetched. #[derive(Debug, Clone, Eq, PartialEq)] @@ -36,6 +36,22 @@ impl TransactionSource { self.into() } + /// Conversion into network specific transaction type. + pub fn into_transaction(self, tx_builder: &T) -> T::Transaction { + match self { + TransactionSource::Pool(tx) => tx_builder.from_recovered(tx), + TransactionSource::Block { transaction, index, block_hash, block_number, base_fee } => { + tx_builder.from_recovered_with_block_context( + transaction, + block_hash, + block_number, + base_fee, + index as usize, + ) + } + } + } + /// Returns the transaction and block related info, if not pending pub fn split(self) -> (TransactionSignedEcRecovered, TransactionInfo) { match self { @@ -77,20 +93,3 @@ impl From for TransactionSignedEcRecovered { } } } - -impl From for Transaction { - fn from(value: TransactionSource) -> Self { - match value { - TransactionSource::Pool(tx) => reth_rpc_types_compat::transaction::from_recovered(tx), - TransactionSource::Block { transaction, index, block_hash, block_number, base_fee } => { - from_recovered_with_block_context( - transaction, - block_hash, - block_number, - base_fee, - index as usize, - ) - } - } - } -} diff --git a/crates/rpc/rpc-types-compat/Cargo.toml b/crates/rpc/rpc-types-compat/Cargo.toml index 66d65893ec25..b6e735c3d6a5 100644 --- a/crates/rpc/rpc-types-compat/Cargo.toml +++ b/crates/rpc/rpc-types-compat/Cargo.toml @@ -17,10 +17,8 @@ reth-rpc-types.workspace = true reth-trie-common.workspace = true # ethereum -alloy-network.workspace = true alloy-rlp.workspace = true alloy-rpc-types.workspace = true -op-alloy-network.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 7cfd57e8aaf8..d80c9f27879b 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -1,27 +1,28 @@ //! Compatibility functions for rpc `Block` type. -use crate::transaction::from_recovered_with_block_context; use alloy_rlp::Encodable; use reth_primitives::{ Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, }; use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind, Header}; +use crate::{transaction::from_recovered_with_block_context, TransactionBuilder}; + /// Converts the given primitive block into a [Block] response with the given /// [`BlockTransactionsKind`] /// /// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. -pub fn from_block( +pub fn from_block( block: BlockWithSenders, total_difficulty: U256, kind: BlockTransactionsKind, block_hash: Option, -) -> Result { +) -> Result, BlockError> { match kind { BlockTransactionsKind::Hashes => { - Ok(from_block_with_tx_hashes(block, total_difficulty, block_hash)) + Ok(from_block_with_tx_hashes::(block, total_difficulty, block_hash)) } - BlockTransactionsKind::Full => from_block_full(block, total_difficulty, block_hash), + BlockTransactionsKind::Full => from_block_full::(block, total_difficulty, block_hash), } } @@ -30,15 +31,15 @@ pub fn from_block( /// /// This will populate the `transactions` field with only the hashes of the transactions in the /// block: [`BlockTransactions::Hashes`] -pub fn from_block_with_tx_hashes( +pub fn from_block_with_tx_hashes( block: BlockWithSenders, total_difficulty: U256, block_hash: Option, -) -> Block { +) -> Block { let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - from_block_with_transactions( + from_block_with_transactions::( block.length(), block_hash, block.block, @@ -52,11 +53,11 @@ pub fn from_block_with_tx_hashes( /// /// This will populate the `transactions` field with the _full_ /// [Transaction](reth_rpc_types::Transaction) objects: [`BlockTransactions::Full`] -pub fn from_block_full( +pub fn from_block_full( mut block: BlockWithSenders, total_difficulty: U256, block_hash: Option, -) -> Result { +) -> Result, BlockError> { let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); let block_number = block.block.number; let base_fee_per_gas = block.block.base_fee_per_gas; @@ -71,7 +72,7 @@ pub fn from_block_full( .map(|(idx, (tx, sender))| { let signed_tx_ec_recovered = tx.with_signer(sender); - from_recovered_with_block_context( + from_recovered_with_block_context::( signed_tx_ec_recovered, block_hash, block_number, @@ -81,7 +82,7 @@ pub fn from_block_full( }) .collect::>(); - Ok(from_block_with_transactions( + Ok(from_block_with_transactions::( block_length, block_hash, block.block, @@ -149,13 +150,13 @@ pub fn from_primitive_with_hash(primitive_header: reth_primitives::SealedHeader) } #[inline] -fn from_block_with_transactions( +fn from_block_with_transactions( block_length: usize, block_hash: B256, block: PrimitiveBlock, total_difficulty: U256, - transactions: BlockTransactions, -) -> Block { + transactions: BlockTransactions, +) -> Block { let uncles = block.ommers.into_iter().map(|h| h.hash_slow()).collect(); let mut header = from_primitive_with_hash(block.header.seal(block_hash)); header.total_difficulty = Some(total_difficulty); @@ -178,7 +179,7 @@ fn from_block_with_transactions( /// Build an RPC block response representing /// an Uncle from its header. -pub fn uncle_block_from_header(header: PrimitiveHeader) -> Block { +pub fn uncle_block_from_header(header: PrimitiveHeader) -> Block { let hash = header.hash_slow(); let rpc_header = from_primitive_with_hash(header.clone().seal(hash)); let uncle_block = PrimitiveBlock { header, ..Default::default() }; diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 9369e1961500..682d946e295e 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -1,5 +1,6 @@ //! Compatibility functions for rpc `Transaction` type. +pub use signature::*; pub use typed::*; mod signature; @@ -8,13 +9,13 @@ mod typed; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; -/// Builds a RPC transaction response w.r.t. network. -pub trait TransactionBuilder { +/// Builds RPC transaction response w.r.t. network. +pub trait TransactionBuilder: Send + Sync { /// RPC transaction response type. - type Transaction; + type Transaction: Send; /// Returns gas price and max fee per gas w.r.t. network specific transaction type. - fn gas_price(signed_tx: TransactionSigned, base_fee: Option) -> GasPrice { + fn gas_price(&self, signed_tx: &TransactionSigned, base_fee: Option) -> GasPrice { match signed_tx.tx_type() { TxType::Legacy | TxType::Eip2930 => { GasPrice { gas_price: Some(signed_tx.max_fee_per_gas()), max_fee_per_gas: None } @@ -42,12 +43,35 @@ pub trait TransactionBuilder { /// Create a new rpc transaction result for a _pending_ signed transaction, setting block /// environment related fields to `None`. fn fill( + &self, tx: TransactionSignedEcRecovered, block_hash: Option, block_number: Option, base_fee: Option, transaction_index: Option, ) -> Self::Transaction; + + /// Create a new rpc transaction result for a _pending_ signed transaction, setting block + /// environment related fields to `None`. + fn from_recovered(&self, tx: TransactionSignedEcRecovered) -> Self::Transaction { + self.fill(tx, None, None, None, None) + } + + /// Create a new rpc transaction result for a mined transaction, using the given block hash, + /// number, and tx index fields to populate the corresponding fields in the rpc result. + /// + /// The block hash, number, and tx index fields should be from the original block where the + /// transaction was mined. + fn from_recovered_with_block_context( + &self, + tx: TransactionSignedEcRecovered, + block_hash: B256, + block_number: BlockNumber, + base_fee: Option, + tx_index: usize, + ) -> Self::Transaction { + self.fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) + } } /// Gas price and max fee per gas for a transaction. Helper type to format transaction RPC response. @@ -59,27 +83,6 @@ pub struct GasPrice { pub max_fee_per_gas: Option, } -/// Create a new rpc transaction result for a mined transaction, using the given block hash, -/// number, and tx index fields to populate the corresponding fields in the rpc result. -/// -/// The block hash, number, and tx index fields should be from the original block where the -/// transaction was mined. -pub fn from_recovered_with_block_context( - tx: TransactionSignedEcRecovered, - block_hash: B256, - block_number: BlockNumber, - base_fee: Option, - tx_index: usize, -) -> T::Transaction { - T::fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) -} - -/// Create a new rpc transaction result for a _pending_ signed transaction, setting block -/// environment related fields to `None`. -pub fn from_recovered(tx: TransactionSignedEcRecovered) -> T::Transaction { - T::fill(tx, None, None, None, None) -} - /// Convert [`TransactionSignedEcRecovered`] to [`TransactionRequest`] pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> TransactionRequest { let from = tx.signer(); diff --git a/crates/rpc/rpc-types-compat/src/transaction/signature.rs b/crates/rpc/rpc-types-compat/src/transaction/signature.rs index 0e7fe5f5876a..28c51f9a9cc1 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/signature.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/signature.rs @@ -6,7 +6,7 @@ use reth_rpc_types::{Parity, Signature}; /// recovery id. /// /// If the chain id is `Some`, the recovery id is computed according to [EIP-155](https://eips.ethereum.org/EIPS/eip-155). -pub(crate) fn from_legacy_primitive_signature( +pub fn from_legacy_primitive_signature( signature: PrimitiveSignature, chain_id: Option, ) -> Signature { @@ -21,7 +21,7 @@ pub(crate) fn from_legacy_primitive_signature( /// Creates a new rpc signature from a non-legacy [primitive /// signature](reth_primitives::Signature). This sets the `v` value to `0` or `1` depending on /// the signature's `odd_y_parity`. -pub(crate) fn from_typed_primitive_signature(signature: PrimitiveSignature) -> Signature { +pub fn from_typed_primitive_signature(signature: PrimitiveSignature) -> Signature { Signature { r: signature.r, s: signature.s, @@ -39,7 +39,7 @@ pub(crate) fn from_typed_primitive_signature(signature: PrimitiveSignature) -> S /// If the transaction is a legacy transaction, it will use the `chain_id` to compute the /// signature's recovery id. If the transaction is a typed transaction, it will set the `v` /// value to `0` or `1` depending on the signature's `odd_y_parity`. -pub(crate) fn from_primitive_signature( +pub fn from_primitive_signature( signature: PrimitiveSignature, tx_type: TxType, chain_id: Option, diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 63f3bfaab4b2..8b4c6bdb29e6 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -3,8 +3,9 @@ use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64 use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; +use reth_rpc_eth_api::{Block, EthApiTypesCompat}; use reth_rpc_types::{ - state::StateOverride, BlockOverrides, Filter, Log, RichBlock, SyncStatus, TransactionRequest, + state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, Transaction, TransactionRequest, }; use tracing_futures::Instrument; @@ -32,8 +33,8 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, - EthFilter: EthFilterApiServer, + Eth: EthApiServer + EthApiTypesCompat, + EthFilter: EthFilterApiServer, { /// Handler for: `eth_syncing` fn syncing(&self) -> Result { @@ -76,7 +77,7 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> Result> { + async fn block_by_hash(&self, hash: B256, full: bool) -> Result>> { self.eth.block_by_hash(hash, full).instrument(engine_span!()).await } @@ -85,7 +86,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> Result> { + ) -> Result>> { self.eth.block_by_number(number, full).instrument(engine_span!()).await } diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index e42ae6bd2d66..7463eb3b3657 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -7,7 +7,9 @@ use alloy_network::Ethereum; use derive_more::Deref; use futures::Future; use reth_node_api::{BuilderProvider, FullNodeComponents}; -use reth_primitives::{BlockNumberOrTag, U256}; +use reth_primitives::{ + Address, BlockNumber, BlockNumberOrTag, TransactionSignedEcRecovered, TxKind, B256, U256, +}; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; use reth_rpc_eth_api::{ helpers::{transaction::UpdateRawTxForwarder, EthSigner, SpawnBlocking}, @@ -17,6 +19,10 @@ use reth_rpc_eth_types::{ EthApiBuilderCtx, EthApiError, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock, }; +use reth_rpc_types_compat::{ + transaction::{from_primitive_signature, GasPrice}, + TransactionBuilder, +}; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskExecutor, TaskSpawner, TokioTaskExecutor, @@ -124,13 +130,15 @@ where type NetworkTypes = Ethereum; } -impl TransactionResponse +impl TransactionBuilder for EthApi +where + Self: Send + Sync, { - type Transaction = ::TransactionResponse; + type Transaction = + <::NetworkTypes as alloy_network::Network>::TransactionResponse; fn fill( - &self, tx: TransactionSignedEcRecovered, block_hash: Option, block_number: Option, @@ -145,7 +153,7 @@ impl TransactionResponse TxKind::Call(to) => Some(Address(*to)), }; - let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(signed_tx, base_fee); + let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(&signed_tx, base_fee); // let chain_id = signed_tx.chain_id().map(U64::from); let chain_id = signed_tx.chain_id(); @@ -577,7 +585,7 @@ mod tests { /// Invalid block range #[tokio::test] async fn test_fee_history_empty() { - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_>>::fee_history( &build_test_eth_api(NoopProvider::default()), U64::from(1), BlockNumberOrTag::Latest, @@ -599,7 +607,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_>>::fee_history( ð_api, U64::from(newest_block + 1), newest_block.into(), diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index ef26a5781de5..50cd48504e82 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -14,7 +14,7 @@ use jsonrpsee::{core::RpcResult, server::IdProvider}; use reth_chainspec::ChainInfo; use reth_primitives::{IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockIdReader, BlockReader, EvmEnvProvider, ProviderError}; -use reth_rpc_eth_api::EthFilterApiServer; +use reth_rpc_eth_api::{EthApiTypesCompat, EthFilterApiServer}; use reth_rpc_eth_types::{ logs_utils::{self, append_matching_block_logs}, EthApiError, EthFilterConfig, EthFilterError, EthStateCache, EthSubscriptionIdProvider, @@ -22,8 +22,9 @@ use reth_rpc_eth_types::{ use reth_rpc_server_types::ToRpcResult; use reth_rpc_types::{ BlockNumHash, Filter, FilterBlockOption, FilterChanges, FilterId, FilteredParams, Log, - PendingTransactionFilterKind, + PendingTransactionFilterKind, Transaction, }; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::TaskSpawner; use reth_transaction_pool::{NewSubpoolTransactionStream, PoolTransaction, TransactionPool}; use tokio::{ @@ -219,10 +220,11 @@ where } #[async_trait] -impl EthFilterApiServer for EthFilter +impl EthFilterApiServer for EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, + Eth: EthApiTypesCompat, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { @@ -544,7 +546,7 @@ impl PendingTransactionsReceiver { } /// Returns all new pending transactions received since the last poll. - async fn drain(&self) -> FilterChanges { + async fn drain(&self) -> FilterChanges { let mut pending_txs = Vec::new(); let mut prepared_stream = self.txs_receiver.lock().await; @@ -573,12 +575,12 @@ where } /// Returns all new pending transactions received since the last poll. - async fn drain(&self) -> FilterChanges { + async fn drain(&self) -> FilterChanges { let mut pending_txs = Vec::new(); let mut prepared_stream = self.txs_stream.lock().await; while let Ok(tx) = prepared_stream.try_recv() { - pending_txs.push(reth_rpc_types_compat::transaction::from_recovered( + pending_txs.push(reth_rpc_types_compat::transaction::from_recovered::( tx.transaction.to_recovered_transaction(), )) } @@ -588,17 +590,20 @@ where /// Helper trait for [FullTransactionsReceiver] to erase the `Transaction` type. #[async_trait] -trait FullTransactionsFilter: fmt::Debug + Send + Sync + Unpin + 'static { - async fn drain(&self) -> FilterChanges; +trait FullTransactionsFilter: + fmt::Debug + Send + Sync + Unpin + 'static +{ + async fn drain(&self) -> FilterChanges; } #[async_trait] -impl FullTransactionsFilter for FullTransactionsReceiver +impl FullTransactionsFilter for FullTransactionsReceiver where T: PoolTransaction + 'static, + TxB: TransactionBuilder, { - async fn drain(&self) -> FilterChanges { - Self::drain(self).await + async fn drain(&self) -> FilterChanges { + Self::drain::(self).await } } @@ -610,13 +615,16 @@ where #[derive(Debug, Clone)] enum PendingTransactionKind { Hashes(PendingTransactionsReceiver), - FullTransaction(Arc), + FullTransaction(Arc>>), } -impl PendingTransactionKind { - async fn drain(&self) -> FilterChanges { +impl PendingTransactionKind +where + T: TransactionBuilder + 'static, +{ + async fn drain(&self) -> FilterChanges { match self { - Self::Hashes(receiver) => receiver.drain().await, + Self::Hashes(receiver) => receiver.drain::().await, Self::FullTransaction(receiver) => receiver.drain().await, } } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 426923dc4458..f72a1393a52a 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -9,7 +9,7 @@ use jsonrpsee::{ use reth_network_api::NetworkInfo; use reth_primitives::{IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider}; -use reth_rpc_eth_api::pubsub::EthPubSubApiServer; +use reth_rpc_eth_api::{pubsub::EthPubSubApiServer, EthApiTypesCompat}; use reth_rpc_eth_types::logs_utils; use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err}; use reth_rpc_types::{ @@ -17,8 +17,9 @@ use reth_rpc_types::{ Params, PubSubSyncStatus, SubscriptionKind, SubscriptionResult as EthSubscriptionResult, SyncStatusMetadata, }, - FilteredParams, Header, Log, + FilteredParams, Header, Log, Transaction, }; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::{TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{NewTransactionEvent, TransactionPool}; use serde::Serialize; @@ -68,13 +69,14 @@ impl EthPubSub } #[async_trait::async_trait] -impl EthPubSubApiServer +impl EthPubSubApiServer for EthPubSub where Provider: BlockReader + EvmEnvProvider + Clone + 'static, Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, + Eth: EthApiTypesCompat, { /// Handler for `eth_subscribe` async fn subscribe( @@ -86,7 +88,7 @@ where let sink = pending.accept().await?; let pubsub = self.inner.clone(); self.subscription_task_spawner.spawn(Box::pin(async move { - let _ = handle_accepted(pubsub, sink, kind, params).await; + let _ = handle_accepted::<_, _, _, _, Eth>(pubsub, sink, kind, params).await; })); Ok(()) @@ -94,13 +96,15 @@ where } /// The actual handler for an accepted [`EthPubSub::subscribe`] call. -async fn handle_accepted( +async fn handle_accepted( pubsub: Arc>, accepted_sink: SubscriptionSink, kind: SubscriptionKind, params: Option, ) -> Result<(), ErrorObject<'static>> where + // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction + TxB: TransactionBuilder, Provider: BlockReader + EvmEnvProvider + Clone + 'static, Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, @@ -133,7 +137,7 @@ where // full transaction objects requested let stream = pubsub.full_pending_transaction_stream().map(|tx| { EthSubscriptionResult::FullTransaction(Box::new( - reth_rpc_types_compat::transaction::from_recovered( + reth_rpc_types_compat::transaction::from_recovered::( tx.transaction.to_recovered_transaction(), ), )) diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index bf8279719fec..8915b34dd0c0 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -59,7 +59,7 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer + TraceExt + 'static, + Eth: EthApiServer + TraceExt + 'static, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 71c342225165..836eaa2f595d 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -1,3 +1,5 @@ +use std::{collections::BTreeMap, marker::PhantomData}; + use async_trait::async_trait; use jsonrpsee::core::RpcResult as Result; use reth_primitives::Address; @@ -6,39 +8,47 @@ use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, Transaction, }; +use reth_rpc_types_compat::TransactionBuilder; use reth_transaction_pool::{AllPoolTransactions, PoolTransaction, TransactionPool}; -use std::collections::BTreeMap; use tracing::trace; /// `txpool` API implementation. /// /// This type provides the functionality for handling `txpool` related requests. #[derive(Clone)] -pub struct TxPoolApi { +pub struct TxPoolApi { /// An interface to interact with the pool pool: Pool, + _phantom: PhantomData, } -impl TxPoolApi { +impl TxPoolApi { /// Creates a new instance of `TxpoolApi`. pub const fn new(pool: Pool) -> Self { - Self { pool } + Self { pool, _phantom: PhantomData } } } -impl TxPoolApi +impl TxPoolApi where Pool: TransactionPool + 'static, + // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction + TxB: TransactionBuilder, { fn content(&self) -> TxpoolContent { #[inline] - fn insert( - tx: &T, - content: &mut BTreeMap>, - ) { + fn insert( + tx: &Tx, + content: &mut BTreeMap>, + ) where + Tx: PoolTransaction, + TxRespB: TransactionBuilder, + { content.entry(tx.sender()).or_default().insert( tx.nonce().to_string(), - reth_rpc_types_compat::transaction::from_recovered(tx.to_recovered_transaction()), + reth_rpc_types_compat::transaction::from_recovered::( + tx.to_recovered_transaction(), + ), ); } @@ -46,10 +56,10 @@ where let mut content = TxpoolContent::default(); for pending in pending { - insert(&pending.transaction, &mut content.pending); + insert::<_, TxB>(&pending.transaction, &mut content.pending); } for queued in queued { - insert(&queued.transaction, &mut content.queued); + insert::<_, TxB>(&queued.transaction, &mut content.queued); } content @@ -57,9 +67,10 @@ where } #[async_trait] -impl TxPoolApiServer for TxPoolApi +impl TxPoolApiServer for TxPoolApi where Pool: TransactionPool + 'static, + TxB: TransactionBuilder + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. @@ -134,7 +145,7 @@ where } } -impl std::fmt::Debug for TxPoolApi { +impl std::fmt::Debug for TxPoolApi { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TxpoolApi").finish_non_exhaustive() } From c506e8e7075154826f1492b37c7479129aea1c02 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 18:06:28 +0200 Subject: [PATCH 12/80] Add trait for building rpc block response --- crates/rpc/rpc-eth-api/src/helpers/block.rs | 28 +--- crates/rpc/rpc-types-compat/src/block.rs | 162 ++++++++++---------- crates/rpc/rpc-types-compat/src/lib.rs | 1 + 3 files changed, 94 insertions(+), 97 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 3fa0eae88a70..1e516f76549f 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,10 +7,7 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{ - block::{from_block, uncle_block_from_header}, - TransactionBuilder, -}; +use reth_rpc_types_compat::block::{uncle_block_from_header, BlockBuilder}; use crate::{Block, FromEthApiError, Transaction}; @@ -18,7 +15,7 @@ use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; /// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthBlocks: LoadBlock { +pub trait EthBlocks: LoadBlock + BlockBuilder> { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -28,10 +25,7 @@ pub trait EthBlocks: LoadBlock { fn rpc_block_header( &self, block_id: BlockId, - ) -> impl Future, Self::Error>> + Send - where - Self: TransactionBuilder>, - { + ) -> impl Future, Self::Error>> + Send { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -43,10 +37,7 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future>, Self::Error>> + Send - where - Self: TransactionBuilder>, - { + ) -> impl Future>, Self::Error>> + Send { async move { let block = match self.block_with_senders(block_id).await? { Some(block) => block, @@ -57,9 +48,9 @@ pub trait EthBlocks: LoadBlock { .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = - from_block::(block.unseal(), total_difficulty, full.into(), Some(block_hash)) - .map_err(Self::Error::from_eth_err)?; + let block = self + .from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) + .map_err(Self::Error::from_eth_err)?; Ok(Some(Rich { inner: block.into(), extra_info: Default::default() })) } } @@ -191,10 +182,7 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future>, Self::Error>> + Send - where - Self: TransactionBuilder>, - { + ) -> impl Future>, Self::Error>> + Send { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index d80c9f27879b..41cf7b608574 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -6,89 +6,97 @@ use reth_primitives::{ }; use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind, Header}; -use crate::{transaction::from_recovered_with_block_context, TransactionBuilder}; +use crate::TransactionBuilder; -/// Converts the given primitive block into a [Block] response with the given -/// [`BlockTransactionsKind`] -/// -/// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. -pub fn from_block( - block: BlockWithSenders, - total_difficulty: U256, - kind: BlockTransactionsKind, - block_hash: Option, -) -> Result, BlockError> { - match kind { - BlockTransactionsKind::Hashes => { - Ok(from_block_with_tx_hashes::(block, total_difficulty, block_hash)) +/// Builds RPC block response w.r.t. network. +pub trait BlockBuilder: TransactionBuilder { + /// Converts the given primitive block into a [Block] response with the given + /// [`BlockTransactionsKind`] + /// + /// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. + fn from_block( + &self, + block: BlockWithSenders, + total_difficulty: U256, + kind: BlockTransactionsKind, + block_hash: Option, + ) -> Result, BlockError> { + match kind { + BlockTransactionsKind::Hashes => { + Ok(self.from_block_with_tx_hashes(block, total_difficulty, block_hash)) + } + BlockTransactionsKind::Full => { + self.from_block_full(block, total_difficulty, block_hash) + } } - BlockTransactionsKind::Full => from_block_full::(block, total_difficulty, block_hash), } -} -/// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the -/// total difficulty to populate its field in the rpc response. -/// -/// This will populate the `transactions` field with only the hashes of the transactions in the -/// block: [`BlockTransactions::Hashes`] -pub fn from_block_with_tx_hashes( - block: BlockWithSenders, - total_difficulty: U256, - block_hash: Option, -) -> Block { - let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); - let transactions = block.body.iter().map(|tx| tx.hash()).collect(); + /// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the + /// total difficulty to populate its field in the rpc response. + /// + /// This will populate the `transactions` field with the _full_ + /// [Transaction](reth_rpc_types::Transaction) objects: [`BlockTransactions::Full`] + fn from_block_full( + &self, + mut block: BlockWithSenders, + total_difficulty: U256, + block_hash: Option, + ) -> Result, BlockError> { + let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); + let block_number = block.block.number; + let base_fee_per_gas = block.block.base_fee_per_gas; - from_block_with_transactions::( - block.length(), - block_hash, - block.block, - total_difficulty, - BlockTransactions::Hashes(transactions), - ) -} + // NOTE: we can safely remove the body here because not needed to finalize the `Block` in + // `from_block_with_transactions`, however we need to compute the length before + let block_length = block.block.length(); + let body = std::mem::take(&mut block.block.body); + let transactions_with_senders = body.into_iter().zip(block.senders); + let transactions = transactions_with_senders + .enumerate() + .map(|(idx, (tx, sender))| { + let signed_tx_ec_recovered = tx.with_signer(sender); -/// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the -/// total difficulty to populate its field in the rpc response. -/// -/// This will populate the `transactions` field with the _full_ -/// [Transaction](reth_rpc_types::Transaction) objects: [`BlockTransactions::Full`] -pub fn from_block_full( - mut block: BlockWithSenders, - total_difficulty: U256, - block_hash: Option, -) -> Result, BlockError> { - let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); - let block_number = block.block.number; - let base_fee_per_gas = block.block.base_fee_per_gas; + self.from_recovered_with_block_context( + signed_tx_ec_recovered, + block_hash, + block_number, + base_fee_per_gas, + idx, + ) + }) + .collect::>(); - // NOTE: we can safely remove the body here because not needed to finalize the `Block` in - // `from_block_with_transactions`, however we need to compute the length before - let block_length = block.block.length(); - let body = std::mem::take(&mut block.block.body); - let transactions_with_senders = body.into_iter().zip(block.senders); - let transactions = transactions_with_senders - .enumerate() - .map(|(idx, (tx, sender))| { - let signed_tx_ec_recovered = tx.with_signer(sender); + Ok(from_block_with_transactions::( + block_length, + block_hash, + block.block, + total_difficulty, + BlockTransactions::Full(transactions), + )) + } - from_recovered_with_block_context::( - signed_tx_ec_recovered, - block_hash, - block_number, - base_fee_per_gas, - idx, - ) - }) - .collect::>(); + /// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the + /// total difficulty to populate its field in the rpc response. + /// + /// This will populate the `transactions` field with only the hashes of the transactions in the + /// block: [`BlockTransactions::Hashes`] + fn from_block_with_tx_hashes( + &self, + block: BlockWithSenders, + total_difficulty: U256, + block_hash: Option, + ) -> Block { + let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); + let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - Ok(from_block_with_transactions::( - block_length, - block_hash, - block.block, - total_difficulty, - BlockTransactions::Full(transactions), - )) + from_block_with_transactions::( + block.length(), + block_hash, + block.block, + total_difficulty, + BlockTransactions::Hashes(transactions), + ) + } } /// Converts from a [`reth_primitives::SealedHeader`] to a [`reth_rpc_types::Header`] @@ -150,13 +158,13 @@ pub fn from_primitive_with_hash(primitive_header: reth_primitives::SealedHeader) } #[inline] -fn from_block_with_transactions( +fn from_block_with_transactions( block_length: usize, block_hash: B256, block: PrimitiveBlock, total_difficulty: U256, - transactions: BlockTransactions, -) -> Block { + transactions: BlockTransactions, +) -> Block { let uncles = block.ommers.into_iter().map(|h| h.hash_slow()).collect(); let mut header = from_primitive_with_hash(block.header.seal(block_hash)); header.total_difficulty = Some(total_difficulty); diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 9e786dbe1c8d..1926d2bfbacd 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -15,4 +15,5 @@ pub mod engine; pub mod proof; pub mod transaction; +pub use block::BlockBuilder; pub use transaction::TransactionBuilder; From 0860e1c93fd965ef310e02bff355772bcc17c326 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 27 Jul 2024 20:43:24 +0200 Subject: [PATCH 13/80] Add adapter for network type builders to EthApi and OpEthApi --- Cargo.lock | 3 + crates/optimism/rpc/src/eth/mod.rs | 34 +------ crates/optimism/rpc/src/eth/transaction.rs | 39 ++++++++ crates/optimism/rpc/src/lib.rs | 6 +- crates/rpc/rpc-eth-api/src/filter.rs | 5 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 4 - crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-api/src/pubsub.rs | 5 +- crates/rpc/rpc-types-compat/Cargo.toml | 5 + crates/rpc/rpc-types-compat/src/adapter.rs | 44 +++++++++ crates/rpc/rpc-types-compat/src/block.rs | 29 +++++- crates/rpc/rpc-types-compat/src/lib.rs | 7 +- .../rpc-types-compat/src/transaction/mod.rs | 80 +++++++++++++++- crates/rpc/rpc/src/engine.rs | 5 +- crates/rpc/rpc/src/eth/core.rs | 92 +++---------------- crates/rpc/rpc/src/eth/filter.rs | 67 +++++++------- crates/rpc/rpc/src/eth/pubsub.rs | 41 ++++++--- crates/rpc/rpc/src/txpool.rs | 37 ++++---- 18 files changed, 303 insertions(+), 202 deletions(-) create mode 100644 crates/rpc/rpc-types-compat/src/adapter.rs diff --git a/Cargo.lock b/Cargo.lock index fd28a2a2ca92..774d3a5776d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8533,8 +8533,11 @@ dependencies = [ name = "reth-rpc-types-compat" version = "1.0.3" dependencies = [ + "alloy-network", "alloy-rlp", "alloy-rpc-types", + "auto_impl", + "derive_more", "reth-primitives", "reth-rpc-types", "reth-trie-common", diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 8106fe8d327a..b6be40e9d64c 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -24,9 +24,9 @@ use reth_rpc_eth_api::{ AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadFee, LoadState, SpawnBlocking, Trace, UpdateRawTxForwarder, }, - EthApiTypes, RawTransactionForwarder, Transaction, + EthApiTypes, RawTransactionForwarder, }; -use reth_rpc_eth_types::EthStateCache; +use reth_rpc_eth_types::{EthStateCache, Transaction}; use reth_rpc_types::SyncStatus; use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::{pool::BlockingTaskPool, TaskSpawner}; @@ -46,14 +46,15 @@ use crate::OpEthApiError; /// This type implements the [`FullEthApi`](reth_rpc_eth_api::helpers::FullEthApi) by implemented /// all the `Eth` helper traits and prerequisite traits. #[derive(Debug, Clone)] -pub struct OpEthApi { +pub struct OpEthApi { inner: Eth, + compat: NetworkTypeBuilders, EthBlockBuilder>>, } impl OpEthApi { /// Creates a new `OpEthApi` from the provided `Eth` implementation. pub const fn new(inner: Eth) -> Self { - Self { inner } + Self { inner, resp_builder: OpTxBuilder } } } @@ -65,31 +66,6 @@ where type NetworkTypes = Optimism; } -impl>> TransactionBuilder - for OpEthApi -{ - type Transaction = Transaction; - - fn fill( - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - let mut resp = Eth::fill(tx, block_hash, block_number, base_fee, transaction_index); - - resp.other = OptimismTransactionFields { - source_hash: signed_tx.source_hash(), - mint: signed_tx.mint(), - is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), - } - .into(); - - resp - } -} - impl EthApiSpec for OpEthApi { fn protocol_version(&self) -> impl Future> + Send { self.inner.protocol_version() diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 6689e230f1ce..00f87eb8c017 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use op_alloy_network::Optimism; use reth_evm_optimism::RethL1BlockInfo; use reth_primitives::TransactionSigned; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; @@ -107,3 +108,41 @@ where Ok(OptimismTxMeta::new(Some(l1_block_info), l1_fee, l1_data_gas)) } } + +#[derive(Debug, Clone, Copy)] +pub struct OpTxBuilder { + l1_resp_builder: Eth, +} + +impl> TransactionBuilder + for OpTxBuilder +{ + type Transaction = Optimism::TransactionResponse; // todo: own tx type for op, wrapper of l1 tx + + fn fill( + &self, + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let mut resp = self.l1_resp_builder.fill( + self, + tx, + block_hash, + block_number, + base_fee, + transaction_index, + ); + + resp.other = OptimismTransactionFields { + source_hash: signed_tx.source_hash(), + mint: signed_tx.mint(), + is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), + } + .into(); + + resp + } +} diff --git a/crates/optimism/rpc/src/lib.rs b/crates/optimism/rpc/src/lib.rs index a6ee9e33d01b..eef42738614c 100644 --- a/crates/optimism/rpc/src/lib.rs +++ b/crates/optimism/rpc/src/lib.rs @@ -16,4 +16,8 @@ pub mod eth; pub use api::OpEthApiServer; pub use error::OpEthApiError; -pub use eth::{receipt::op_receipt_fields, transaction::OptimismTxMeta, OpEthApi}; +pub use eth::{ + receipt::op_receipt_fields, + transaction::{OpTxBuilder, OptimismTxMeta}, + OpEthApi, +}; diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index ad885745460b..59b4da815bd5 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -2,13 +2,12 @@ use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_rpc_types::{Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind}; - -use crate::EthApiTypesCompat; +use reth_rpc_types_compat::TransactionBuilder; /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthFilterApi { +pub trait EthFilterApi { /// Creates anew filter and returns its id. #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult; diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 20c4f6c267ab..2041c73b453f 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -4,7 +4,6 @@ use std::error::Error; use alloy_network::Network; use reth_rpc_types::Rich; -use reth_rpc_types_compat::TransactionBuilder; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -22,9 +21,6 @@ pub trait EthApiTypes: Send + Sync { type NetworkTypes: Network; } -/// Helper trait that unifies [`EthApiTypes`] with the necessary type conversions. -pub trait EthApiTypesCompat: EthApiTypes + TransactionBuilder {} - /// Adapter for network specific transaction type. pub type Transaction = <::NetworkTypes as Network>::TransactionResponse; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 933e947d2e90..39bfb0d629ea 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::{Block, EthApiTypes, EthApiTypesCompat, Transaction}, + types::{Block, EthApiTypes, Transaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-api/src/pubsub.rs b/crates/rpc/rpc-eth-api/src/pubsub.rs index 4d729c883c47..760ee54e3ead 100644 --- a/crates/rpc/rpc-eth-api/src/pubsub.rs +++ b/crates/rpc/rpc-eth-api/src/pubsub.rs @@ -2,12 +2,11 @@ use jsonrpsee::proc_macros::rpc; use reth_rpc_types::pubsub::{Params, SubscriptionKind}; - -use crate::EthApiTypesCompat; +use reth_rpc_types_compat::TransactionBuilder; /// Ethereum pub-sub rpc interface. #[rpc(server, namespace = "eth")] -pub trait EthPubSubApi { +pub trait EthPubSubApi { /// Create an ethereum subscription for the given params #[subscription( name = "subscribe" => "subscription", diff --git a/crates/rpc/rpc-types-compat/Cargo.toml b/crates/rpc/rpc-types-compat/Cargo.toml index b6e735c3d6a5..1e445d9929df 100644 --- a/crates/rpc/rpc-types-compat/Cargo.toml +++ b/crates/rpc/rpc-types-compat/Cargo.toml @@ -19,6 +19,11 @@ reth-trie-common.workspace = true # ethereum alloy-rlp.workspace = true alloy-rpc-types.workspace = true +alloy-network.workspace = true + +# misc +auto_impl.workspace = true +derive_more.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/crates/rpc/rpc-types-compat/src/adapter.rs b/crates/rpc/rpc-types-compat/src/adapter.rs new file mode 100644 index 000000000000..0da8fb6716a6 --- /dev/null +++ b/crates/rpc/rpc-types-compat/src/adapter.rs @@ -0,0 +1,44 @@ +use std::{fmt, marker::PhantomData}; + +use derive_more::Constructor; +use reth_primitives::{BlockNumber, TransactionSignedEcRecovered, B256}; + +use crate::{BlockBuilder, TransactionBuilder}; + +/// Adapter for builders of network specific RPC types. +#[derive(Debug, Constructor)] +pub struct NetworkTypeBuilders { + tx_builder: T, + _phantom: PhantomData, +} + +impl TransactionBuilder for NetworkTypeBuilders +where + T: TransactionBuilder, + B: Send + Sync + Unpin + fmt::Debug, +{ + type Transaction = T::Transaction; + + fn fill( + &self, + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + self.tx_builder.fill(tx, block_hash, block_number, base_fee, transaction_index) + } +} + +impl BlockBuilder for NetworkTypeBuilders +where + T: TransactionBuilder, + B: BlockBuilder, +{ + type Transaction = B::Transaction; + + fn tx_builder(&self) -> impl TransactionBuilder { + &self.tx_builder + } +} diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 41cf7b608574..6ff4810ab0f8 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -1,6 +1,8 @@ //! Compatibility functions for rpc `Block` type. use alloy_rlp::Encodable; +use auto_impl::auto_impl; +use derive_more::Constructor; use reth_primitives::{ Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, }; @@ -8,8 +10,15 @@ use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind use crate::TransactionBuilder; -/// Builds RPC block response w.r.t. network. -pub trait BlockBuilder: TransactionBuilder { +/// Builds RPC block w.r.t. network. +#[auto_impl(&, Arc)] +pub trait BlockBuilder { + /// RPC transaction type of network. + type Transaction: Send; + + /// Returns handle to transaction builder. + fn tx_builder(&self) -> impl TransactionBuilder; + /// Converts the given primitive block into a [Block] response with the given /// [`BlockTransactionsKind`] /// @@ -56,7 +65,7 @@ pub trait BlockBuilder: TransactionBuilder { .map(|(idx, (tx, sender))| { let signed_tx_ec_recovered = tx.with_signer(sender); - self.from_recovered_with_block_context( + self.tx_builder().from_recovered_with_block_context( signed_tx_ec_recovered, block_hash, block_number, @@ -201,3 +210,17 @@ pub fn uncle_block_from_header(header: PrimitiveHeader) -> Block { other: Default::default(), } } + +/// Builds a RPC block response for l1. +#[derive(Debug, Clone, Copy, Constructor)] +pub struct EthBlockBuilder { + tx_builder: TxB, +} + +impl BlockBuilder for EthBlockBuilder { + type Transaction = TxB::Transaction; + + fn tx_builder(&self) -> impl TransactionBuilder { + &self.tx_builder + } +} diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 1926d2bfbacd..9efe99a5bb07 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -15,5 +15,8 @@ pub mod engine; pub mod proof; pub mod transaction; -pub use block::BlockBuilder; -pub use transaction::TransactionBuilder; +mod adapter; + +pub use adapter::NetworkTypeBuilders; +pub use block::{BlockBuilder, EthBlockBuilder}; +pub use transaction::{EthTxBuilder, TransactionBuilder}; diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 682d946e295e..212822baf4d8 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -6,11 +6,18 @@ pub use typed::*; mod signature; mod typed; +use std::fmt; + +use alloy_network::{Ethereum, Network}; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; -use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; +use auto_impl::auto_impl; +use reth_primitives::{ + Address, BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxKind, TxType, B256, +}; -/// Builds RPC transaction response w.r.t. network. -pub trait TransactionBuilder: Send + Sync { +/// Builds RPC transaction w.r.t. network. +#[auto_impl(&, Arc)] +pub trait TransactionBuilder: Send + Sync + Unpin + fmt::Debug { /// RPC transaction response type. type Transaction: Send; @@ -124,3 +131,70 @@ pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> Transact sidecar: None, } } + +/// Builds RPC transaction response for l1. +#[derive(Debug, Clone, Copy)] +pub struct EthTxBuilder; + +impl TransactionBuilder for EthTxBuilder +where + Self: Send + Sync, +{ + type Transaction = ::TransactionResponse; + + fn fill( + &self, + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let signer = tx.signer(); + let signed_tx = tx.into_signed(); + + let to: Option
= match signed_tx.kind() { + TxKind::Create => None, + TxKind::Call(to) => Some(Address(*to)), + }; + + let GasPrice { gas_price, max_fee_per_gas } = self.gas_price(&signed_tx, base_fee); + + let chain_id = signed_tx.chain_id(); + let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); + let access_list = signed_tx.access_list().cloned(); + let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); + + let signature = from_primitive_signature( + *signed_tx.signature(), + signed_tx.tx_type(), + signed_tx.chain_id(), + ); + + Self::Transaction { + hash: signed_tx.hash(), + nonce: signed_tx.nonce(), + from: signer, + to, + value: signed_tx.value(), + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), + signature: Some(signature), + gas: signed_tx.gas_limit() as u128, + input: signed_tx.input().clone(), + chain_id, + access_list, + transaction_type: Some(signed_tx.tx_type() as u8), + // These fields are set to None because they are not stored as part of the transaction + block_hash, + block_number, + transaction_index: transaction_index.map(|idx| idx as u64), + // EIP-4844 fields + max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), + blob_versioned_hashes, + authorization_list, + other: Default::default(), + } + } +} diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 8b4c6bdb29e6..ec121ebb4203 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -3,9 +3,8 @@ use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64 use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; -use reth_rpc_eth_api::{Block, EthApiTypesCompat}; use reth_rpc_types::{ - state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, Transaction, TransactionRequest, + state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, TransactionRequest, }; use tracing_futures::Instrument; @@ -33,7 +32,7 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer + EthApiTypesCompat, + Eth: EthApiServer, EthFilter: EthFilterApiServer, { /// Handler for: `eth_syncing` diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 7463eb3b3657..5d0ba820e9f9 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -7,9 +7,7 @@ use alloy_network::Ethereum; use derive_more::Deref; use futures::Future; use reth_node_api::{BuilderProvider, FullNodeComponents}; -use reth_primitives::{ - Address, BlockNumber, BlockNumberOrTag, TransactionSignedEcRecovered, TxKind, B256, U256, -}; +use reth_primitives::{BlockNumberOrTag, U256}; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; use reth_rpc_eth_api::{ helpers::{transaction::UpdateRawTxForwarder, EthSigner, SpawnBlocking}, @@ -19,10 +17,7 @@ use reth_rpc_eth_types::{ EthApiBuilderCtx, EthApiError, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock, }; -use reth_rpc_types_compat::{ - transaction::{from_primitive_signature, GasPrice}, - TransactionBuilder, -}; +use reth_rpc_types_compat::{EthBlockBuilder, EthTxBuilder, NetworkTypeBuilders}; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskExecutor, TaskSpawner, TokioTaskExecutor, @@ -38,10 +33,13 @@ use tokio::sync::{AcquireError, Mutex, OwnedSemaphorePermit}; /// separately in submodules. The rpc handler implementation can then delegate to the main impls. /// This way [`EthApi`] is not limited to [`jsonrpsee`] and can be used standalone or in other /// network handlers (for example ipc). -#[derive(Deref)] +#[derive(Clone, Deref)] pub struct EthApi { /// All nested fields bundled together. + #[deref] pub(super) inner: Arc>, + /// Builds network specific response types. + pub compat: NetworkTypeBuilders>, } impl EthApi @@ -80,7 +78,10 @@ where proof_permits, ); - Self { inner: Arc::new(inner) } + Self { + inner: Arc::new(inner), + compat: NetworkTypeBuilders::new(EthTxBuilder, EthBlockBuilder::new(EthTxBuilder)), + } } } @@ -118,7 +119,7 @@ where ctx.config.proof_permits, ); - Self { inner: Arc::new(inner) } + Self { inner: Arc::new(inner), compat: EthTxBuilder } } } @@ -130,71 +131,6 @@ where type NetworkTypes = Ethereum; } -impl TransactionBuilder - for EthApi -where - Self: Send + Sync, -{ - type Transaction = - <::NetworkTypes as alloy_network::Network>::TransactionResponse; - - fn fill( - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - let signer = tx.signer(); - let signed_tx = tx.into_signed(); - - let to: Option
= match signed_tx.kind() { - TxKind::Create => None, - TxKind::Call(to) => Some(Address(*to)), - }; - - let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(&signed_tx, base_fee); - - // let chain_id = signed_tx.chain_id().map(U64::from); - let chain_id = signed_tx.chain_id(); - let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); - let access_list = signed_tx.access_list().cloned(); - let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); - - let signature = from_primitive_signature( - *signed_tx.signature(), - signed_tx.tx_type(), - signed_tx.chain_id(), - ); - - Self::Transaction { - hash: signed_tx.hash(), - nonce: signed_tx.nonce(), - from: signer, - to, - value: signed_tx.value(), - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), - signature: Some(signature), - gas: signed_tx.gas_limit() as u128, - input: signed_tx.input().clone(), - chain_id, - access_list, - transaction_type: Some(signed_tx.tx_type() as u8), - // These fields are set to None because they are not stored as part of the transaction - block_hash, - block_number, - transaction_index: transaction_index.map(|idx| idx as u64), - // EIP-4844 fields - max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), - blob_versioned_hashes, - authorization_list, - other: Default::default(), - } - } -} - impl std::fmt::Debug for EthApi { @@ -203,12 +139,6 @@ impl std::fmt::Debug } } -impl Clone for EthApi { - fn clone(&self) -> Self { - Self { inner: Arc::clone(&self.inner) } - } -} - impl SpawnBlocking for EthApi where diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 50cd48504e82..09f9918354b4 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -14,7 +14,7 @@ use jsonrpsee::{core::RpcResult, server::IdProvider}; use reth_chainspec::ChainInfo; use reth_primitives::{IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockIdReader, BlockReader, EvmEnvProvider, ProviderError}; -use reth_rpc_eth_api::{EthApiTypesCompat, EthFilterApiServer}; +use reth_rpc_eth_api::EthFilterApiServer; use reth_rpc_eth_types::{ logs_utils::{self, append_matching_block_logs}, EthApiError, EthFilterConfig, EthFilterError, EthStateCache, EthSubscriptionIdProvider, @@ -37,12 +37,15 @@ use tracing::trace; const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb /// `Eth` filter RPC implementation. -pub struct EthFilter { +#[derive(Clone)] +pub struct EthFilter { /// All nested fields bundled together inner: Arc>, + /// Assembles response data w.r.t. network. + resp_builder: Arc, } -impl EthFilter +impl EthFilter where Provider: Send + Sync + 'static, Pool: Send + Sync + 'static, @@ -61,6 +64,7 @@ where eth_cache: EthStateCache, config: EthFilterConfig, task_spawner: Box, + resp_builder: Eth, ) -> Self { let EthFilterConfig { max_blocks_per_filter, max_logs_per_response, stale_filter_ttl } = config; @@ -78,7 +82,7 @@ where max_logs_per_response: max_logs_per_response.unwrap_or(usize::MAX), }; - let eth_filter = Self { inner: Arc::new(inner) }; + let eth_filter = Self { inner: Arc::new(inner), resp_builder: Arc::new(resp_builder) }; let this = eth_filter.clone(); eth_filter.inner.task_spawner.spawn_critical( @@ -123,7 +127,7 @@ where } } -impl EthFilter +impl EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, @@ -220,11 +224,11 @@ where } #[async_trait] -impl EthFilterApiServer for EthFilter +impl EthFilterApiServer for EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, - Eth: EthApiTypesCompat, + Eth: TransactionBuilder + 'static, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { @@ -253,7 +257,8 @@ where } PendingTransactionFilterKind::Full => { let stream = self.inner.pool.new_pending_pool_transactions_listener(); - let full_txs_receiver = FullTransactionsReceiver::new(stream); + let full_txs_receiver = + FullTransactionsReceiver::new(stream, self.resp_builder.clone()); FilterKind::PendingTransaction(PendingTransactionKind::FullTransaction(Arc::new( full_txs_receiver, ))) @@ -309,12 +314,6 @@ impl std::fmt::Debug for EthFilter { } } -impl Clone for EthFilter { - fn clone(&self) -> Self { - Self { inner: Arc::clone(&self.inner) } - } -} - /// Container type `EthFilter` #[derive(Debug)] struct EthFilterInner { @@ -561,28 +560,29 @@ impl PendingTransactionsReceiver { /// A structure to manage and provide access to a stream of full transaction details. #[derive(Debug, Clone)] -struct FullTransactionsReceiver { +struct FullTransactionsReceiver { txs_stream: Arc>>, + resp_builder: TxB, } -impl FullTransactionsReceiver +impl FullTransactionsReceiver where T: PoolTransaction + 'static, + TxB: TransactionBuilder, { /// Creates a new `FullTransactionsReceiver` encapsulating the provided transaction stream. - fn new(stream: NewSubpoolTransactionStream) -> Self { - Self { txs_stream: Arc::new(Mutex::new(stream)) } + fn new(stream: NewSubpoolTransactionStream, resp_builder: TxB) -> Self { + Self { txs_stream: Arc::new(Mutex::new(stream)), resp_builder } } /// Returns all new pending transactions received since the last poll. - async fn drain(&self) -> FilterChanges { + async fn drain(&self) -> FilterChanges { let mut pending_txs = Vec::new(); let mut prepared_stream = self.txs_stream.lock().await; while let Ok(tx) = prepared_stream.try_recv() { - pending_txs.push(reth_rpc_types_compat::transaction::from_recovered::( - tx.transaction.to_recovered_transaction(), - )) + pending_txs + .push(self.resp_builder.from_recovered(tx.transaction.to_recovered_transaction())) } FilterChanges::Transactions(pending_txs) } @@ -590,17 +590,15 @@ where /// Helper trait for [FullTransactionsReceiver] to erase the `Transaction` type. #[async_trait] -trait FullTransactionsFilter: - fmt::Debug + Send + Sync + Unpin + 'static -{ - async fn drain(&self) -> FilterChanges; +trait FullTransactionsFilter: fmt::Debug + Send + Sync + Unpin + 'static { + async fn drain(&self) -> FilterChanges; } #[async_trait] -impl FullTransactionsFilter for FullTransactionsReceiver +impl FullTransactionsFilter for FullTransactionsReceiver where T: PoolTransaction + 'static, - TxB: TransactionBuilder, + TxB: TransactionBuilder + 'static, { async fn drain(&self) -> FilterChanges { Self::drain::(self).await @@ -615,16 +613,15 @@ where #[derive(Debug, Clone)] enum PendingTransactionKind { Hashes(PendingTransactionsReceiver), - FullTransaction(Arc>>), + FullTransaction( + Arc>>>, + ), } -impl PendingTransactionKind -where - T: TransactionBuilder + 'static, -{ - async fn drain(&self) -> FilterChanges { +impl PendingTransactionKind { + async fn drain(&self) -> FilterChanges { match self { - Self::Hashes(receiver) => receiver.drain::().await, + Self::Hashes(receiver) => receiver.drain().await, Self::FullTransaction(receiver) => receiver.drain().await, } } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index f72a1393a52a..6cb66c0ebc0d 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -9,7 +9,7 @@ use jsonrpsee::{ use reth_network_api::NetworkInfo; use reth_primitives::{IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider}; -use reth_rpc_eth_api::{pubsub::EthPubSubApiServer, EthApiTypesCompat}; +use reth_rpc_eth_api::pubsub::EthPubSubApiServer; use reth_rpc_eth_types::logs_utils; use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err}; use reth_rpc_types::{ @@ -32,26 +32,35 @@ use tokio_stream::{ /// /// This handles `eth_subscribe` RPC calls. #[derive(Clone)] -pub struct EthPubSub { +pub struct EthPubSub { /// All nested fields bundled together. inner: Arc>, /// The type that's used to spawn subscription tasks. subscription_task_spawner: Box, + /// Assembles network specific response data. + resp_builder: Eth, } // === impl EthPubSub === -impl EthPubSub { +impl EthPubSub { /// Creates a new, shareable instance. /// /// Subscription tasks are spawned via [`tokio::task::spawn`] - pub fn new(provider: Provider, pool: Pool, chain_events: Events, network: Network) -> Self { + pub fn new( + provider: Provider, + pool: Pool, + chain_events: Events, + network: Network, + resp_builder: Eth, + ) -> Self { Self::with_spawner( provider, pool, chain_events, network, Box::::default(), + resp_builder, ) } @@ -62,21 +71,22 @@ impl EthPubSub chain_events: Events, network: Network, subscription_task_spawner: Box, + resp_builder: Eth, ) -> Self { let inner = EthPubSubInner { provider, pool, chain_events, network }; - Self { inner: Arc::new(inner), subscription_task_spawner } + Self { inner: Arc::new(inner), subscription_task_spawner, resp_builder } } } #[async_trait::async_trait] impl EthPubSubApiServer - for EthPubSub + for EthPubSub where Provider: BlockReader + EvmEnvProvider + Clone + 'static, Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, - Eth: EthApiTypesCompat, + Eth: TransactionBuilder + Clone + 'static, { /// Handler for `eth_subscribe` async fn subscribe( @@ -87,8 +97,9 @@ where ) -> jsonrpsee::core::SubscriptionResult { let sink = pending.accept().await?; let pubsub = self.inner.clone(); + let resp_builder = self.resp_builder.clone(); self.subscription_task_spawner.spawn(Box::pin(async move { - let _ = handle_accepted::<_, _, _, _, Eth>(pubsub, sink, kind, params).await; + let _ = handle_accepted(pubsub, sink, kind, params, resp_builder).await; })); Ok(()) @@ -101,14 +112,15 @@ async fn handle_accepted( accepted_sink: SubscriptionSink, kind: SubscriptionKind, params: Option, + tx_builder: TxB, ) -> Result<(), ErrorObject<'static>> where - // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction - TxB: TransactionBuilder, Provider: BlockReader + EvmEnvProvider + Clone + 'static, Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, + // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction + TxB: TransactionBuilder, { match kind { SubscriptionKind::NewHeads => { @@ -137,9 +149,8 @@ where // full transaction objects requested let stream = pubsub.full_pending_transaction_stream().map(|tx| { EthSubscriptionResult::FullTransaction(Box::new( - reth_rpc_types_compat::transaction::from_recovered::( - tx.transaction.to_recovered_transaction(), - ), + tx_builder + .from_recovered(tx.transaction.to_recovered_transaction()), )) }); return pipe_from_stream(accepted_sink, stream).await @@ -246,8 +257,8 @@ where } } -impl std::fmt::Debug - for EthPubSub +impl std::fmt::Debug + for EthPubSub { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EthPubSub").finish_non_exhaustive() diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 836eaa2f595d..8d42faa055c8 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -1,4 +1,4 @@ -use std::{collections::BTreeMap, marker::PhantomData}; +use std::collections::BTreeMap; use async_trait::async_trait; use jsonrpsee::core::RpcResult as Result; @@ -16,39 +16,38 @@ use tracing::trace; /// /// This type provides the functionality for handling `txpool` related requests. #[derive(Clone)] -pub struct TxPoolApi { +pub struct TxPoolApi { /// An interface to interact with the pool pool: Pool, - _phantom: PhantomData, + resp_builder: Eth, } -impl TxPoolApi { +impl TxPoolApi { /// Creates a new instance of `TxpoolApi`. - pub const fn new(pool: Pool) -> Self { - Self { pool, _phantom: PhantomData } + pub const fn new(pool: Pool, resp_builder: Eth) -> Self { + Self { pool, resp_builder } } } -impl TxPoolApi +impl TxPoolApi where Pool: TransactionPool + 'static, // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction - TxB: TransactionBuilder, + Eth: TransactionBuilder, { fn content(&self) -> TxpoolContent { #[inline] - fn insert( + fn insert( tx: &Tx, - content: &mut BTreeMap>, + content: &mut BTreeMap>, + resp_builder: &Eth, ) where Tx: PoolTransaction, - TxRespB: TransactionBuilder, + Eth: TransactionBuilder, { content.entry(tx.sender()).or_default().insert( tx.nonce().to_string(), - reth_rpc_types_compat::transaction::from_recovered::( - tx.to_recovered_transaction(), - ), + resp_builder.from_recovered(tx.to_recovered_transaction()), ); } @@ -56,10 +55,10 @@ where let mut content = TxpoolContent::default(); for pending in pending { - insert::<_, TxB>(&pending.transaction, &mut content.pending); + insert(&pending.transaction, &mut content.pending, &self.resp_builder); } for queued in queued { - insert::<_, TxB>(&queued.transaction, &mut content.queued); + insert(&queued.transaction, &mut content.queued, &self.resp_builder); } content @@ -67,10 +66,10 @@ where } #[async_trait] -impl TxPoolApiServer for TxPoolApi +impl TxPoolApiServer for TxPoolApi where Pool: TransactionPool + 'static, - TxB: TransactionBuilder + 'static, + Eth: TransactionBuilder + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. @@ -145,7 +144,7 @@ where } } -impl std::fmt::Debug for TxPoolApi { +impl std::fmt::Debug for TxPoolApi { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TxpoolApi").finish_non_exhaustive() } From f48038e3e3801e78020105235c604082b5297289 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 29 Jul 2024 13:23:35 +0200 Subject: [PATCH 14/80] Fix conflicts, resp ty has non-unique builder --- Cargo.lock | 4 - crates/optimism/rpc/src/eth/mod.rs | 10 +- crates/optimism/rpc/src/eth/transaction.rs | 15 +-- crates/rpc/rpc-builder/Cargo.toml | 1 - crates/rpc/rpc-builder/src/eth.rs | 46 +++++--- crates/rpc/rpc-builder/src/lib.rs | 21 ++-- crates/rpc/rpc-eth-api/src/core.rs | 2 +- crates/rpc/rpc-eth-api/src/filter.rs | 8 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 13 ++- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 10 +- .../rpc-eth-api/src/helpers/transaction.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 4 + crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-types/src/builder/ctx.rs | 30 ++++-- crates/rpc/rpc-eth-types/src/builders.rs | 82 ++++++++++++++ crates/rpc/rpc-eth-types/src/transaction.rs | 6 +- crates/rpc/rpc-types-compat/Cargo.toml | 5 - crates/rpc/rpc-types-compat/src/adapter.rs | 44 -------- crates/rpc/rpc-types-compat/src/block.rs | 47 +++----- crates/rpc/rpc-types-compat/src/builders.rs | 39 +++++++ crates/rpc/rpc-types-compat/src/lib.rs | 9 +- .../rpc-types-compat/src/transaction/mod.rs | 88 ++------------- crates/rpc/rpc/src/engine.rs | 8 +- crates/rpc/rpc/src/eth/core.rs | 50 ++++++--- crates/rpc/rpc/src/eth/filter.rs | 101 ++++++++++-------- crates/rpc/rpc/src/eth/helpers/block.rs | 9 +- crates/rpc/rpc/src/eth/helpers/mod.rs | 1 + crates/rpc/rpc/src/eth/helpers/transaction.rs | 5 +- crates/rpc/rpc/src/eth/helpers/types.rs | 85 +++++++++++++++ crates/rpc/rpc/src/eth/mod.rs | 5 +- crates/rpc/rpc/src/eth/pubsub.rs | 32 ++---- crates/rpc/rpc/src/otterscan.rs | 4 +- crates/rpc/rpc/src/txpool.rs | 21 ++-- 33 files changed, 476 insertions(+), 333 deletions(-) create mode 100644 crates/rpc/rpc-eth-types/src/builders.rs delete mode 100644 crates/rpc/rpc-types-compat/src/adapter.rs create mode 100644 crates/rpc/rpc-types-compat/src/builders.rs create mode 100644 crates/rpc/rpc/src/eth/helpers/types.rs diff --git a/Cargo.lock b/Cargo.lock index 774d3a5776d2..cf573c393e96 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8357,7 +8357,6 @@ dependencies = [ "reth-rpc-layer", "reth-rpc-server-types", "reth-rpc-types", - "reth-rpc-types-compat", "reth-tasks", "reth-tokio-util", "reth-tracing", @@ -8533,11 +8532,8 @@ dependencies = [ name = "reth-rpc-types-compat" version = "1.0.3" dependencies = [ - "alloy-network", "alloy-rlp", "alloy-rpc-types", - "auto_impl", - "derive_more", "reth-primitives", "reth-rpc-types", "reth-trie-common", diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index b6be40e9d64c..1eb814320334 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -48,13 +48,14 @@ use crate::OpEthApiError; #[derive(Debug, Clone)] pub struct OpEthApi { inner: Eth, - compat: NetworkTypeBuilders, EthBlockBuilder>>, + /// L1 RPC type builders. + _eth_ty_builders: PhantomData, } impl OpEthApi { /// Creates a new `OpEthApi` from the provided `Eth` implementation. pub const fn new(inner: Eth) -> Self { - Self { inner, resp_builder: OpTxBuilder } + Self { inner, _rpc_ty_builders: PhantomData } } } @@ -66,6 +67,11 @@ where type NetworkTypes = Optimism; } +impl EthApiTypesCompat for OpEthApi { + type TxBuilder = OpTxBuilder; + type BlockBuilder = EthBlockBuilder>; +} + impl EthApiSpec for OpEthApi { fn protocol_version(&self) -> impl Future> + Send { self.inner.protocol_version() diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 00f87eb8c017..444032f8b495 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -1,6 +1,6 @@ //! Loads and formats OP transaction RPC response. -use std::sync::Arc; +use std::{marker::PhantomData, sync::Arc}; use op_alloy_network::Optimism; use reth_evm_optimism::RethL1BlockInfo; @@ -111,13 +111,13 @@ where #[derive(Debug, Clone, Copy)] pub struct OpTxBuilder { - l1_resp_builder: Eth, + _l1_builders: PhantomData, } impl> TransactionBuilder for OpTxBuilder { - type Transaction = Optimism::TransactionResponse; // todo: own tx type for op, wrapper of l1 tx + type Transaction = Optimism::TransactionResponse; fn fill( &self, @@ -127,14 +127,7 @@ impl> Trans base_fee: Option, transaction_index: Option, ) -> Self::Transaction { - let mut resp = self.l1_resp_builder.fill( - self, - tx, - block_hash, - block_number, - base_fee, - transaction_index, - ); + let mut resp = Eth::fill(self, tx, block_hash, block_number, base_fee, transaction_index); resp.other = OptimismTransactionFields { source_hash: signed_tx.source_hash(), diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index d410268a2df2..384a7405816f 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -57,7 +57,6 @@ reth-provider = { workspace = true, features = ["test-utils"] } reth-rpc-api = { workspace = true, features = ["client"] } reth-rpc-engine-api.workspace = true reth-rpc-types.workspace = true -reth-rpc-types-compat.workspace = true reth-tracing.workspace = true reth-transaction-pool = { workspace = true, features = ["test-utils"] } reth-tokio-util.workspace = true diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index af0097c23b3c..21fd0f20a92f 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -1,29 +1,36 @@ +use std::marker::PhantomData; + use reth_evm::ConfigureEvm; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider, StateProviderFactory}; use reth_rpc::{EthFilter, EthPubSub}; +use reth_rpc_eth_api::EthApiTypesCompat; use reth_rpc_eth_types::{ cache::cache_new_blocks_task, EthApiBuilderCtx, EthConfig, EthStateCache, }; use reth_tasks::TaskSpawner; /// Alias for `eth` namespace API builder. -pub type DynEthApiBuilder = - Box) -> EthApi>; +pub type DynEthApiBuilder = Box< + dyn Fn(&EthApiBuilderCtx) -> EthApi, +>; /// Handlers for core, filter and pubsub `eth` namespace APIs. #[derive(Debug, Clone)] -pub struct EthHandlers { +pub struct EthHandlers { /// Main `eth_` request handler pub api: EthApi, /// The async caching layer used by the eth handlers pub cache: EthStateCache, /// Polling based filter handler available on all transports - pub filter: EthFilter, + pub filter: EthFilter, /// Handler for subscriptions only available for transports that support it (ws, ipc) - pub pubsub: EthPubSub, + pub pubsub: EthPubSub, } -impl EthHandlers { +impl EthHandlers +where + EthApi: EthApiTypesCompat, +{ /// Returns a new [`EthHandlers`] builder. #[allow(clippy::too_many_arguments)] pub fn builder( @@ -59,7 +66,15 @@ impl EthHandlers { +pub struct EthHandlersBuilder< + Provider, + Pool, + Network, + Tasks, + Events, + EvmConfig, + EthApi: EthApiTypesCompat, +> { provider: Provider, pool: Pool, network: Network, @@ -79,7 +94,7 @@ where Network: Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: 'static, + EthApi: EthApiTypesCompat + 'static, { /// Returns a new instance with handlers for `eth` namespace. pub fn build(self) -> EthHandlers { @@ -111,6 +126,7 @@ where executor, events, cache, + _rpc_ty_builders: PhantomData, }; let api = eth_api_builder(&ctx); @@ -129,13 +145,14 @@ pub struct EthFilterApiBuilder; impl EthFilterApiBuilder { /// Builds the [`EthFilterApiServer`](reth_rpc_eth_api::EthFilterApiServer), for given context. - pub fn build( - ctx: &EthApiBuilderCtx, - ) -> EthFilter + pub fn build( + ctx: &EthApiBuilderCtx, + ) -> EthFilter where Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, + Eth: EthApiTypesCompat + 'static, { EthFilter::new( ctx.provider.clone(), @@ -153,15 +170,16 @@ pub struct EthPubSubApiBuilder; impl EthPubSubApiBuilder { /// Builds the [`EthPubSubApiServer`](reth_rpc_eth_api::EthPubSubApiServer), for given context. - pub fn build( - ctx: &EthApiBuilderCtx, - ) -> EthPubSub + pub fn build( + ctx: &EthApiBuilderCtx, + ) -> EthPubSub where Provider: Clone, Pool: Clone, Events: Clone, Network: Clone, Tasks: TaskSpawner + Clone + 'static, + Eth: EthApiTypesCompat, { EthPubSub::with_spawner( ctx.provider.clone(), diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index d3346bcdc185..12a7a3416826 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -167,7 +167,7 @@ use reth_rpc_eth_api::{ helpers::{ Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder, }, - EthApiServer, FullEthApiServer, RawTransactionForwarder, + EthApiServer, EthApiTypes, EthApiTypesCompat, FullEthApiServer, RawTransactionForwarder, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -488,7 +488,7 @@ where eth: DynEthApiBuilder, ) -> RpcRegistryInner where - EthApi: 'static, + EthApi: EthApiTypesCompat + 'static, { let Self { provider, pool, network, executor, events, evm_config } = self; RpcRegistryInner::new(provider, pool, network, executor, events, config, evm_config, eth) @@ -608,7 +608,7 @@ impl RpcModuleConfigBuilder { /// A Helper type the holds instances of the configured modules. #[derive(Debug, Clone)] -pub struct RpcRegistryInner { +pub struct RpcRegistryInner { provider: Provider, pool: Pool, network: Network, @@ -632,7 +632,7 @@ where Network: Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: 'static, + EthApi: EthApiTypesCompat + 'static, { /// Creates a new, empty instance. #[allow(clippy::too_many_arguments)] @@ -686,6 +686,8 @@ where impl RpcRegistryInner +where + EthApi: EthApiTypesCompat, { /// Returns a reference to the installed [`EthApi`](reth_rpc::eth::EthApi). pub const fn eth_api(&self) -> &EthApi { @@ -743,7 +745,7 @@ impl impl RpcRegistryInner where - EthApi: UpdateRawTxForwarder, + EthApi: EthApiTypesCompat + UpdateRawTxForwarder, { /// Sets a forwarder for `eth_sendRawTransaction` /// @@ -758,6 +760,7 @@ impl RpcRegistryInner where Network: NetworkInfo + Clone + 'static, + EthApi: EthApiTypesCompat, { /// Instantiates `AdminApi` pub fn admin_api(&self) -> AdminApi @@ -796,7 +799,7 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: Clone, + EthApi: EthApiTypesCompat, { /// Register Eth Namespace /// @@ -805,7 +808,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_eth(&mut self) -> &mut Self where - EthApi: EthApiServer, + EthApi: EthApiTypesCompat + EthApiServer, { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); @@ -819,7 +822,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: EthApiServer + TraceExt, + EthApi: EthApiServer + TraceExt, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -919,7 +922,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn otterscan_api(&self) -> OtterscanApi where - EthApi: EthApiServer, + EthApi: EthApiServer + EthApiTypes, { let eth_api = self.eth_api().clone(); OtterscanApi::new(eth_api) diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 674b40e96631..d6f9f6c85048 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -463,7 +463,7 @@ where trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash) .await? - .map(|tx| tx.into_transaction(self))) + .map(|tx| tx.into_transaction::())) } /// Handler for: `eth_getRawTransactionByBlockHashAndIndex` diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index 59b4da815bd5..deb27e1cb8b4 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -1,13 +1,15 @@ //! `eth_` RPC API for filtering. use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_rpc_types::{Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind}; +use reth_rpc_types::{ + Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind, Transaction, +}; use reth_rpc_types_compat::TransactionBuilder; /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthFilterApi { +pub trait EthFilterApi> { /// Creates anew filter and returns its id. #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult; @@ -25,7 +27,7 @@ pub trait EthFilterApi { /// Returns all filter changes since last poll. #[method(name = "getFilterChanges")] - async fn filter_changes(&self, id: FilterId) -> RpcResult; + async fn filter_changes(&self, id: FilterId) -> RpcResult>; /// Returns all logs matching given filter (in a range 'from' - 'to'). #[method(name = "getFilterLogs")] diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 1e516f76549f..49897cf20a56 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,7 +7,7 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::block::{uncle_block_from_header, BlockBuilder}; +use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionBuilder}; use crate::{Block, FromEthApiError, Transaction}; @@ -15,7 +15,10 @@ use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; /// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthBlocks: LoadBlock + BlockBuilder> { +pub trait EthBlocks: LoadBlock + BlockBuilder +where + Self::TxBuilder: TransactionBuilder>, +{ /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -48,9 +51,9 @@ pub trait EthBlocks: LoadBlock + BlockBuilder> { .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = self - .from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) - .map_err(Self::Error::from_eth_err)?; + let block = + Self::from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) + .map_err(Self::Error::from_eth_err)?; Ok(Some(Rich { inner: block.into(), extra_info: Default::default() })) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index ecfd63388e3b..b74ecc8156fa 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -40,7 +40,7 @@ pub use state::{EthState, LoadState}; pub use trace::Trace; pub use transaction::{EthTransactions, LoadTransaction, UpdateRawTxForwarder}; -use crate::EthApiTypes; +use crate::EthApiTypesCompat; /// Extension trait that bundles traits needed for tracing transactions. pub trait TraceExt: @@ -54,10 +54,10 @@ impl TraceExt for T where T: LoadTransaction + LoadBlock + LoadPendingBlock + /// /// This trait is automatically implemented for any type that implements all the `Eth` traits. pub trait FullEthApi: - EthApiTypes + EthApiTypesCompat + EthApiSpec + EthTransactions - + EthBlocks + + EthBlocks + EthState + EthCall + EthFees @@ -67,10 +67,10 @@ pub trait FullEthApi: } impl FullEthApi for T where - T: EthApiTypes + T: EthApiTypesCompat + EthApiSpec + EthTransactions - + EthBlocks + + EthBlocks + EthState + EthCall + EthFees diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 98174cef4dcf..47db65af2451 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -209,7 +209,7 @@ pub trait EthTransactions: let block_number = block.number; let base_fee_per_gas = block.base_fee_per_gas; if let Some(tx) = block.into_transactions_ecrecovered().nth(index) { - return Ok(Some(self.from_recovered_with_block_context( + return Ok(Some(Self::from_recovered_with_block_context( tx, block_hash, block_number, diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 2041c73b453f..68a6009136e5 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -4,6 +4,7 @@ use std::error::Error; use alloy_network::Network; use reth_rpc_types::Rich; +use reth_rpc_types_compat::ResponseTypeBuilders; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -26,3 +27,6 @@ pub type Transaction = <::NetworkTypes as Network>::Transac /// Adapter for network specific block type. pub type Block = Rich>>; + +/// Helper trait that unifies [`EthApiTypes`] with type conversions. +pub trait EthApiTypesCompat: EthApiTypes + ResponseTypeBuilders {} diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 39bfb0d629ea..933e947d2e90 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::{Block, EthApiTypes, Transaction}, + types::{Block, EthApiTypes, EthApiTypesCompat, Transaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-types/src/builder/ctx.rs b/crates/rpc/rpc-eth-types/src/builder/ctx.rs index 6741f2f651bf..a21d99bc94ae 100644 --- a/crates/rpc/rpc-eth-types/src/builder/ctx.rs +++ b/crates/rpc/rpc-eth-types/src/builder/ctx.rs @@ -1,6 +1,9 @@ //! Context required for building `eth` namespace APIs. +use std::marker::PhantomData; + use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; +use reth_rpc_types_compat::{ResponseTypeBuilders, TransactionBuilder}; use reth_tasks::TaskSpawner; use crate::{ @@ -10,7 +13,15 @@ use crate::{ /// Context for building the `eth` namespace API. #[derive(Debug, Clone)] -pub struct EthApiBuilderCtx { +pub struct EthApiBuilderCtx< + Provider, + Pool, + EvmConfig, + Network, + Tasks, + Events, + Eth: TransactionBuilder, +> { /// Database handle. pub provider: Provider, /// Mempool handle. @@ -27,12 +38,15 @@ pub struct EthApiBuilderCtx { pub events: Events, /// RPC cache handle. pub cache: EthStateCache, + /// RPC type builders. + pub _rpc_ty_builders: PhantomData, } -impl - EthApiBuilderCtx +impl + EthApiBuilderCtx where Provider: BlockReaderIdExt + Clone, + Eth: ResponseTypeBuilders, { /// Returns a new [`FeeHistoryCache`] for the context. pub fn new_fee_history_cache(&self) -> FeeHistoryCache @@ -56,11 +70,12 @@ pub struct GasPriceOracleBuilder; impl GasPriceOracleBuilder { /// Builds a [`GasPriceOracle`], for given context. - pub fn build( - ctx: &EthApiBuilderCtx, + pub fn build( + ctx: &EthApiBuilderCtx, ) -> GasPriceOracle where Provider: BlockReaderIdExt + Clone, + Eth: ResponseTypeBuilders, { GasPriceOracle::new(ctx.provider.clone(), ctx.config.gas_oracle, ctx.cache.clone()) } @@ -72,13 +87,14 @@ pub struct FeeHistoryCacheBuilder; impl FeeHistoryCacheBuilder { /// Builds a [`FeeHistoryCache`], for given context. - pub fn build( - ctx: &EthApiBuilderCtx, + pub fn build( + ctx: &EthApiBuilderCtx, ) -> FeeHistoryCache where Provider: ChainSpecProvider + BlockReaderIdExt + Clone + 'static, Tasks: TaskSpawner, Events: CanonStateSubscriptions, + Eth: ResponseTypeBuilders, { let fee_history_cache = FeeHistoryCache::new(ctx.cache.clone(), ctx.config.fee_history_cache); diff --git a/crates/rpc/rpc-eth-types/src/builders.rs b/crates/rpc/rpc-eth-types/src/builders.rs new file mode 100644 index 000000000000..c02f78dc23d1 --- /dev/null +++ b/crates/rpc/rpc-eth-types/src/builders.rs @@ -0,0 +1,82 @@ +use std::marker::PhantomData; + +use alloy_network::{Ethereum, Network}; +use derive_more::Constructor; +use reth_primitives::{BlockNumber, B256, TransactionSignedEcRecovered, Address, TxKind}; +use reth_rpc_types_compat::{transaction::{from_primitive_signature, GasPrice}, BlockBuilder, TransactionBuilder}; + +/// Builds RPC transaction response for l1. +#[derive(Debug, Clone, Copy)] +pub struct EthTxBuilder; + +impl TransactionBuilder for EthTxBuilder +where + Self: Send + Sync, +{ + type Transaction = ::TransactionResponse; + + fn fill( + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let signer = tx.signer(); + let signed_tx = tx.into_signed(); + + let to: Option
= match signed_tx.kind() { + TxKind::Create => None, + TxKind::Call(to) => Some(Address(*to)), + }; + + let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(&signed_tx, base_fee); + + let chain_id = signed_tx.chain_id(); + let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); + let access_list = signed_tx.access_list().cloned(); + let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); + + let signature = from_primitive_signature( + *signed_tx.signature(), + signed_tx.tx_type(), + signed_tx.chain_id(), + ); + + Self::Transaction { + hash: signed_tx.hash(), + nonce: signed_tx.nonce(), + from: signer, + to, + value: signed_tx.value(), + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), + signature: Some(signature), + gas: signed_tx.gas_limit() as u128, + input: signed_tx.input().clone(), + chain_id, + access_list, + transaction_type: Some(signed_tx.tx_type() as u8), + // These fields are set to None because they are not stored as part of the transaction + block_hash, + block_number, + transaction_index: transaction_index.map(|idx| idx as u64), + // EIP-4844 fields + max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), + blob_versioned_hashes, + authorization_list, + other: Default::default(), + } + } +} + +/// Builds a RPC block response for l1. +#[derive(Debug, Clone, Copy, Constructor)] +pub struct EthBlockBuilder { + _tx_builder: PhantomData, +} + +impl BlockBuilder for EthBlockBuilder { + type TxBuilder = TxB; +} diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index 6e7297a2bceb..145e24bb4270 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -37,11 +37,11 @@ impl TransactionSource { } /// Conversion into network specific transaction type. - pub fn into_transaction(self, tx_builder: &T) -> T::Transaction { + pub fn into_transaction(self) -> T::Transaction { match self { - TransactionSource::Pool(tx) => tx_builder.from_recovered(tx), + TransactionSource::Pool(tx) => T::from_recovered(tx), TransactionSource::Block { transaction, index, block_hash, block_number, base_fee } => { - tx_builder.from_recovered_with_block_context( + T::from_recovered_with_block_context( transaction, block_hash, block_number, diff --git a/crates/rpc/rpc-types-compat/Cargo.toml b/crates/rpc/rpc-types-compat/Cargo.toml index 1e445d9929df..b6e735c3d6a5 100644 --- a/crates/rpc/rpc-types-compat/Cargo.toml +++ b/crates/rpc/rpc-types-compat/Cargo.toml @@ -19,11 +19,6 @@ reth-trie-common.workspace = true # ethereum alloy-rlp.workspace = true alloy-rpc-types.workspace = true -alloy-network.workspace = true - -# misc -auto_impl.workspace = true -derive_more.workspace = true [dev-dependencies] serde_json.workspace = true diff --git a/crates/rpc/rpc-types-compat/src/adapter.rs b/crates/rpc/rpc-types-compat/src/adapter.rs deleted file mode 100644 index 0da8fb6716a6..000000000000 --- a/crates/rpc/rpc-types-compat/src/adapter.rs +++ /dev/null @@ -1,44 +0,0 @@ -use std::{fmt, marker::PhantomData}; - -use derive_more::Constructor; -use reth_primitives::{BlockNumber, TransactionSignedEcRecovered, B256}; - -use crate::{BlockBuilder, TransactionBuilder}; - -/// Adapter for builders of network specific RPC types. -#[derive(Debug, Constructor)] -pub struct NetworkTypeBuilders { - tx_builder: T, - _phantom: PhantomData, -} - -impl TransactionBuilder for NetworkTypeBuilders -where - T: TransactionBuilder, - B: Send + Sync + Unpin + fmt::Debug, -{ - type Transaction = T::Transaction; - - fn fill( - &self, - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - self.tx_builder.fill(tx, block_hash, block_number, base_fee, transaction_index) - } -} - -impl BlockBuilder for NetworkTypeBuilders -where - T: TransactionBuilder, - B: BlockBuilder, -{ - type Transaction = B::Transaction; - - fn tx_builder(&self) -> impl TransactionBuilder { - &self.tx_builder - } -} diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 6ff4810ab0f8..4b22477e8c2f 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -1,8 +1,8 @@ //! Compatibility functions for rpc `Block` type. +use std::fmt; + use alloy_rlp::Encodable; -use auto_impl::auto_impl; -use derive_more::Constructor; use reth_primitives::{ Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, }; @@ -11,31 +11,26 @@ use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind use crate::TransactionBuilder; /// Builds RPC block w.r.t. network. -#[auto_impl(&, Arc)] -pub trait BlockBuilder { - /// RPC transaction type of network. - type Transaction: Send; - - /// Returns handle to transaction builder. - fn tx_builder(&self) -> impl TransactionBuilder; +pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { + /// RPC transaction type builder of network. + type TxBuilder: TransactionBuilder; /// Converts the given primitive block into a [Block] response with the given /// [`BlockTransactionsKind`] /// /// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. fn from_block( - &self, block: BlockWithSenders, total_difficulty: U256, kind: BlockTransactionsKind, block_hash: Option, - ) -> Result, BlockError> { + ) -> Result::Transaction>, BlockError> { match kind { BlockTransactionsKind::Hashes => { - Ok(self.from_block_with_tx_hashes(block, total_difficulty, block_hash)) + Ok(Self::from_block_with_tx_hashes(block, total_difficulty, block_hash)) } BlockTransactionsKind::Full => { - self.from_block_full(block, total_difficulty, block_hash) + Self::from_block_full(block, total_difficulty, block_hash) } } } @@ -46,11 +41,10 @@ pub trait BlockBuilder { /// This will populate the `transactions` field with the _full_ /// [Transaction](reth_rpc_types::Transaction) objects: [`BlockTransactions::Full`] fn from_block_full( - &self, mut block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Result, BlockError> { + ) -> Result::Transaction>, BlockError> { let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); let block_number = block.block.number; let base_fee_per_gas = block.block.base_fee_per_gas; @@ -65,7 +59,7 @@ pub trait BlockBuilder { .map(|(idx, (tx, sender))| { let signed_tx_ec_recovered = tx.with_signer(sender); - self.tx_builder().from_recovered_with_block_context( + Self::TxBuilder::from_recovered_with_block_context( signed_tx_ec_recovered, block_hash, block_number, @@ -75,7 +69,7 @@ pub trait BlockBuilder { }) .collect::>(); - Ok(from_block_with_transactions::( + Ok(from_block_with_transactions::<::Transaction>( block_length, block_hash, block.block, @@ -90,15 +84,14 @@ pub trait BlockBuilder { /// This will populate the `transactions` field with only the hashes of the transactions in the /// block: [`BlockTransactions::Hashes`] fn from_block_with_tx_hashes( - &self, block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Block { + ) -> Block<::Transaction> { let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - from_block_with_transactions::( + from_block_with_transactions::<::Transaction>( block.length(), block_hash, block.block, @@ -210,17 +203,3 @@ pub fn uncle_block_from_header(header: PrimitiveHeader) -> Block { other: Default::default(), } } - -/// Builds a RPC block response for l1. -#[derive(Debug, Clone, Copy, Constructor)] -pub struct EthBlockBuilder { - tx_builder: TxB, -} - -impl BlockBuilder for EthBlockBuilder { - type Transaction = TxB::Transaction; - - fn tx_builder(&self) -> impl TransactionBuilder { - &self.tx_builder - } -} diff --git a/crates/rpc/rpc-types-compat/src/builders.rs b/crates/rpc/rpc-types-compat/src/builders.rs new file mode 100644 index 000000000000..7162830ec740 --- /dev/null +++ b/crates/rpc/rpc-types-compat/src/builders.rs @@ -0,0 +1,39 @@ +//! Unifies network specific RPC type conversions. + +use std::fmt; + +use reth_primitives::{BlockNumber, TransactionSignedEcRecovered, B256}; + +use crate::{BlockBuilder, TransactionBuilder}; + +/// Helper trait that unifies [`EthApiTypes`] with type conversions. +pub trait ResponseTypeBuilders: Send + Sync + Unpin + Clone + fmt::Debug { + /// Builds RPC transaction response type w.r.t. network. + type TransactionBuilder: TransactionBuilder; + /// Builds RPC block response type w.r.t. network. + type BlockBuilder: BlockBuilder; +} + +impl TransactionBuilder for T +where + T: ResponseTypeBuilders, +{ + type Transaction = ::Transaction; + + fn fill( + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + T::TransactionBuilder::fill(tx, block_hash, block_number, base_fee, transaction_index) + } +} + +impl BlockBuilder for T +where + T: ResponseTypeBuilders, +{ + type TxBuilder = T::TransactionBuilder; +} diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 9efe99a5bb07..b8359b7b7407 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -11,12 +11,11 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] pub mod block; +pub mod builders; pub mod engine; pub mod proof; pub mod transaction; -mod adapter; - -pub use adapter::NetworkTypeBuilders; -pub use block::{BlockBuilder, EthBlockBuilder}; -pub use transaction::{EthTxBuilder, TransactionBuilder}; +pub use block::BlockBuilder; +pub use builders::ResponseTypeBuilders; +pub use transaction::TransactionBuilder; diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 212822baf4d8..7cbe9bcdc225 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -8,21 +8,16 @@ mod typed; use std::fmt; -use alloy_network::{Ethereum, Network}; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; -use auto_impl::auto_impl; -use reth_primitives::{ - Address, BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxKind, TxType, B256, -}; +use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; /// Builds RPC transaction w.r.t. network. -#[auto_impl(&, Arc)] -pub trait TransactionBuilder: Send + Sync + Unpin + fmt::Debug { +pub trait TransactionBuilder: Send + Sync + Unpin + Clone + fmt::Debug { /// RPC transaction response type. - type Transaction: Send; + type Transaction: Send + Clone + Default + fmt::Debug; /// Returns gas price and max fee per gas w.r.t. network specific transaction type. - fn gas_price(&self, signed_tx: &TransactionSigned, base_fee: Option) -> GasPrice { + fn gas_price(signed_tx: &TransactionSigned, base_fee: Option) -> GasPrice { match signed_tx.tx_type() { TxType::Legacy | TxType::Eip2930 => { GasPrice { gas_price: Some(signed_tx.max_fee_per_gas()), max_fee_per_gas: None } @@ -50,7 +45,6 @@ pub trait TransactionBuilder: Send + Sync + Unpin + fmt::Debug { /// Create a new rpc transaction result for a _pending_ signed transaction, setting block /// environment related fields to `None`. fn fill( - &self, tx: TransactionSignedEcRecovered, block_hash: Option, block_number: Option, @@ -60,8 +54,8 @@ pub trait TransactionBuilder: Send + Sync + Unpin + fmt::Debug { /// Create a new rpc transaction result for a _pending_ signed transaction, setting block /// environment related fields to `None`. - fn from_recovered(&self, tx: TransactionSignedEcRecovered) -> Self::Transaction { - self.fill(tx, None, None, None, None) + fn from_recovered(tx: TransactionSignedEcRecovered) -> Self::Transaction { + Self::fill(tx, None, None, None, None) } /// Create a new rpc transaction result for a mined transaction, using the given block hash, @@ -70,14 +64,13 @@ pub trait TransactionBuilder: Send + Sync + Unpin + fmt::Debug { /// The block hash, number, and tx index fields should be from the original block where the /// transaction was mined. fn from_recovered_with_block_context( - &self, tx: TransactionSignedEcRecovered, block_hash: B256, block_number: BlockNumber, base_fee: Option, tx_index: usize, ) -> Self::Transaction { - self.fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) + Self::fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) } } @@ -131,70 +124,3 @@ pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> Transact sidecar: None, } } - -/// Builds RPC transaction response for l1. -#[derive(Debug, Clone, Copy)] -pub struct EthTxBuilder; - -impl TransactionBuilder for EthTxBuilder -where - Self: Send + Sync, -{ - type Transaction = ::TransactionResponse; - - fn fill( - &self, - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - let signer = tx.signer(); - let signed_tx = tx.into_signed(); - - let to: Option
= match signed_tx.kind() { - TxKind::Create => None, - TxKind::Call(to) => Some(Address(*to)), - }; - - let GasPrice { gas_price, max_fee_per_gas } = self.gas_price(&signed_tx, base_fee); - - let chain_id = signed_tx.chain_id(); - let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); - let access_list = signed_tx.access_list().cloned(); - let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); - - let signature = from_primitive_signature( - *signed_tx.signature(), - signed_tx.tx_type(), - signed_tx.chain_id(), - ); - - Self::Transaction { - hash: signed_tx.hash(), - nonce: signed_tx.nonce(), - from: signer, - to, - value: signed_tx.value(), - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), - signature: Some(signature), - gas: signed_tx.gas_limit() as u128, - input: signed_tx.input().clone(), - chain_id, - access_list, - transaction_type: Some(signed_tx.tx_type() as u8), - // These fields are set to None because they are not stored as part of the transaction - block_hash, - block_number, - transaction_index: transaction_index.map(|idx| idx as u64), - // EIP-4844 fields - max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), - blob_versioned_hashes, - authorization_list, - other: Default::default(), - } - } -} diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index ec121ebb4203..ffa5efc48740 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -1,11 +1,14 @@ +use alloy_network::Network; use jsonrpsee::core::RpcResult as Result; use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64}; use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; +use reth_rpc_eth_api::{Block, EthApiTypes}; use reth_rpc_types::{ - state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, TransactionRequest, + state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, Transaction, TransactionRequest, }; +use reth_rpc_types_compat::TransactionBuilder; use tracing_futures::Instrument; macro_rules! engine_span { @@ -32,7 +35,8 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, + Eth: EthApiServer + EthApiTypes + TransactionBuilder, + Eth::NetworkTypes: Network, EthFilter: EthFilterApiServer, { /// Handler for: `eth_syncing` diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 5d0ba820e9f9..5fe4bda9f50f 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -17,13 +17,15 @@ use reth_rpc_eth_types::{ EthApiBuilderCtx, EthApiError, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock, }; -use reth_rpc_types_compat::{EthBlockBuilder, EthTxBuilder, NetworkTypeBuilders}; +use reth_rpc_types_compat::ResponseTypeBuilders; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskExecutor, TaskSpawner, TokioTaskExecutor, }; use tokio::sync::{AcquireError, Mutex, OwnedSemaphorePermit}; +use crate::eth::{EthBlockBuilder, EthTxBuilder}; + /// `Eth` API implementation. /// /// This type provides the functionality for handling `eth_` related requests. @@ -33,13 +35,26 @@ use tokio::sync::{AcquireError, Mutex, OwnedSemaphorePermit}; /// separately in submodules. The rpc handler implementation can then delegate to the main impls. /// This way [`EthApi`] is not limited to [`jsonrpsee`] and can be used standalone or in other /// network handlers (for example ipc). -#[derive(Clone, Deref)] +#[derive(Deref)] pub struct EthApi { /// All nested fields bundled together. #[deref] pub(super) inner: Arc>, - /// Builds network specific response types. - pub compat: NetworkTypeBuilders>, +} + +unsafe impl Send + for EthApi +{ +} +unsafe impl Sync + for EthApi +{ +} + +impl Clone for EthApi { + fn clone(&self) -> Self { + Self { inner: self.inner.clone() } + } } impl EthApi @@ -78,10 +93,7 @@ where proof_permits, ); - Self { - inner: Arc::new(inner), - compat: NetworkTypeBuilders::new(EthTxBuilder, EthBlockBuilder::new(EthTxBuilder)), - } + Self { inner: Arc::new(inner) } } } @@ -94,7 +106,7 @@ where { /// Creates a new, shareable instance. pub fn with_spawner( - ctx: &EthApiBuilderCtx, + ctx: &EthApiBuilderCtx, ) -> Self where Tasks: TaskSpawner + Clone + 'static, @@ -119,7 +131,7 @@ where ctx.config.proof_permits, ); - Self { inner: Arc::new(inner), compat: EthTxBuilder } + Self { inner: Arc::new(inner) } } } @@ -131,6 +143,13 @@ where type NetworkTypes = Ethereum; } +impl ResponseTypeBuilders + for EthApi +{ + type TransactionBuilder = EthTxBuilder; + type BlockBuilder = EthBlockBuilder; +} + impl std::fmt::Debug for EthApi { @@ -173,8 +192,15 @@ where N: FullNodeComponents, Network: Send + Sync + Clone + 'static, { - type Ctx<'a> = - &'a EthApiBuilderCtx; + type Ctx<'a> = &'a EthApiBuilderCtx< + N::Provider, + N::Pool, + N::Evm, + Network, + TaskExecutor, + N::Provider, + Self, + >; fn builder() -> Box Fn(Self::Ctx<'a>) -> Self + Send> { Box::new(|ctx| Self::with_spawner(ctx)) diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 09f9918354b4..d19f477b377a 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -4,6 +4,7 @@ use std::{ collections::HashMap, fmt, iter::StepBy, + marker::PhantomData, ops::RangeInclusive, sync::Arc, time::{Duration, Instant}, @@ -37,18 +38,27 @@ use tracing::trace; const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb /// `Eth` filter RPC implementation. -#[derive(Clone)] -pub struct EthFilter { +pub struct EthFilter { /// All nested fields bundled together - inner: Arc>, + inner: Arc>, /// Assembles response data w.r.t. network. - resp_builder: Arc, + _tx_resp_builder: PhantomData, +} + +impl Clone for EthFilter +where + Eth: TransactionBuilder, +{ + fn clone(&self) -> Self { + Self { inner: self.inner.clone(), _tx_resp_builder: PhantomData } + } } impl EthFilter where Provider: Send + Sync + 'static, Pool: Send + Sync + 'static, + Eth: TransactionBuilder + Clone + 'static, { /// Creates a new, shareable instance. /// @@ -64,7 +74,6 @@ where eth_cache: EthStateCache, config: EthFilterConfig, task_spawner: Box, - resp_builder: Eth, ) -> Self { let EthFilterConfig { max_blocks_per_filter, max_logs_per_response, stale_filter_ttl } = config; @@ -82,7 +91,7 @@ where max_logs_per_response: max_logs_per_response.unwrap_or(usize::MAX), }; - let eth_filter = Self { inner: Arc::new(inner), resp_builder: Arc::new(resp_builder) }; + let eth_filter = Self { inner: Arc::new(inner), _tx_resp_builder: PhantomData }; let this = eth_filter.clone(); eth_filter.inner.task_spawner.spawn_critical( @@ -96,7 +105,7 @@ where } /// Returns all currently active filters - pub fn active_filters(&self) -> &ActiveFilters { + pub fn active_filters(&self) -> &ActiveFilters { &self.inner.active_filters } @@ -132,9 +141,14 @@ where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, ::Transaction: 'static, + Eth: TransactionBuilder, + Eth::Transaction: Clone + 'static, { /// Returns all the filter changes for the given id, if any - pub async fn filter_changes(&self, id: FilterId) -> Result { + pub async fn filter_changes( + &self, + id: FilterId, + ) -> Result, EthFilterError> { let info = self.inner.provider.chain_info()?; let best_number = info.best_number; @@ -228,18 +242,18 @@ impl EthFilterApiServer for EthFilter + Clone + 'static, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_newFilter"); - self.inner.install_filter(FilterKind::Log(Box::new(filter))).await + self.inner.install_filter(FilterKind::::Log(Box::new(filter))).await } /// Handler for `eth_newBlockFilter` async fn new_block_filter(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_newBlockFilter"); - self.inner.install_filter(FilterKind::Block).await + self.inner.install_filter(FilterKind::::Block).await } /// Handler for `eth_newPendingTransactionFilter` @@ -257,8 +271,7 @@ where } PendingTransactionFilterKind::Full => { let stream = self.inner.pool.new_pending_pool_transactions_listener(); - let full_txs_receiver = - FullTransactionsReceiver::new(stream, self.resp_builder.clone()); + let full_txs_receiver = FullTransactionsReceiver::<_, Eth>::new(stream); FilterKind::PendingTransaction(PendingTransactionKind::FullTransaction(Arc::new( full_txs_receiver, ))) @@ -272,7 +285,7 @@ where } /// Handler for `eth_getFilterChanges` - async fn filter_changes(&self, id: FilterId) -> RpcResult { + async fn filter_changes(&self, id: FilterId) -> RpcResult> { trace!(target: "rpc::eth", "Serving eth_getFilterChanges"); Ok(Self::filter_changes(self, id).await?) } @@ -308,7 +321,10 @@ where } } -impl std::fmt::Debug for EthFilter { +impl std::fmt::Debug for EthFilter +where + Eth: TransactionBuilder, +{ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EthFilter").finish_non_exhaustive() } @@ -316,13 +332,13 @@ impl std::fmt::Debug for EthFilter { /// Container type `EthFilter` #[derive(Debug)] -struct EthFilterInner { +struct EthFilterInner { /// The transaction pool. pool: Pool, /// The provider that can interact with the chain. provider: Provider, /// All currently installed filters. - active_filters: ActiveFilters, + active_filters: ActiveFilters, /// Provides ids to identify filters id_provider: Arc, /// Maximum number of blocks that could be scanned per filter @@ -339,7 +355,7 @@ struct EthFilterInner { stale_filter_ttl: Duration, } -impl EthFilterInner +impl EthFilterInner where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, @@ -400,7 +416,7 @@ where } /// Installs a new filter and returns the new identifier. - async fn install_filter(&self, kind: FilterKind) -> RpcResult { + async fn install_filter(&self, kind: FilterKind) -> RpcResult { let last_poll_block_number = self.provider.best_block_number().to_rpc_result()?; let id = FilterId::from(self.id_provider.next_id()); let mut filters = self.active_filters.inner.lock().await; @@ -518,19 +534,19 @@ where /// All active filters #[derive(Debug, Clone, Default)] -pub struct ActiveFilters { - inner: Arc>>, +pub struct ActiveFilters { + inner: Arc>>>, } /// An installed filter #[derive(Debug)] -struct ActiveFilter { +struct ActiveFilter { /// At which block the filter was polled last. block: u64, /// Last time this filter was polled. last_poll_timestamp: Instant, /// What kind of filter it is. - kind: FilterKind, + kind: FilterKind, } /// A receiver for pending transactions that returns all new transactions since the last poll. @@ -560,29 +576,28 @@ impl PendingTransactionsReceiver { /// A structure to manage and provide access to a stream of full transaction details. #[derive(Debug, Clone)] -struct FullTransactionsReceiver { +struct FullTransactionsReceiver { txs_stream: Arc>>, - resp_builder: TxB, + _tx_resp_builder: PhantomData, } -impl FullTransactionsReceiver +impl FullTransactionsReceiver where T: PoolTransaction + 'static, - TxB: TransactionBuilder, + Eth: TransactionBuilder, { /// Creates a new `FullTransactionsReceiver` encapsulating the provided transaction stream. - fn new(stream: NewSubpoolTransactionStream, resp_builder: TxB) -> Self { - Self { txs_stream: Arc::new(Mutex::new(stream)), resp_builder } + fn new(stream: NewSubpoolTransactionStream) -> Self { + Self { txs_stream: Arc::new(Mutex::new(stream)), _tx_resp_builder: PhantomData } } /// Returns all new pending transactions received since the last poll. - async fn drain(&self) -> FilterChanges { + async fn drain(&self) -> FilterChanges { let mut pending_txs = Vec::new(); let mut prepared_stream = self.txs_stream.lock().await; while let Ok(tx) = prepared_stream.try_recv() { - pending_txs - .push(self.resp_builder.from_recovered(tx.transaction.to_recovered_transaction())) + pending_txs.push(Eth::from_recovered(tx.transaction.to_recovered_transaction())) } FilterChanges::Transactions(pending_txs) } @@ -595,13 +610,13 @@ trait FullTransactionsFilter: fmt::Debug + Send + Sync + Unpin + 'static { } #[async_trait] -impl FullTransactionsFilter for FullTransactionsReceiver +impl FullTransactionsFilter for FullTransactionsReceiver where T: PoolTransaction + 'static, - TxB: TransactionBuilder + 'static, + Eth: TransactionBuilder + 'static, { - async fn drain(&self) -> FilterChanges { - Self::drain::(self).await + async fn drain(&self) -> FilterChanges { + Self::drain(self).await } } @@ -611,15 +626,13 @@ where /// - Just the transaction hashes. /// - Full transaction details. #[derive(Debug, Clone)] -enum PendingTransactionKind { +enum PendingTransactionKind { Hashes(PendingTransactionsReceiver), - FullTransaction( - Arc>>>, - ), + FullTransaction(Arc>), } -impl PendingTransactionKind { - async fn drain(&self) -> FilterChanges { +impl PendingTransactionKind { + async fn drain(&self) -> FilterChanges { match self { Self::Hashes(receiver) => receiver.drain().await, Self::FullTransaction(receiver) => receiver.drain().await, @@ -628,10 +641,10 @@ impl PendingTransactionKind { } #[derive(Clone, Debug)] -enum FilterKind { +enum FilterKind { Log(Box), Block, - PendingTransaction(PendingTransactionKind), + PendingTransaction(PendingTransactionKind), } /// An iterator that yields _inclusive_ block ranges of a given step size diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 2ce6c7ed2e93..93b93b789de3 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -1,14 +1,19 @@ //! Contains RPC handler implementations specific to blocks. use reth_provider::{BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_api::helpers::{EthBlocks, LoadBlock, LoadPendingBlock, SpawnBlocking}; +use reth_rpc_eth_api::{ + helpers::{EthBlocks, LoadBlock, LoadPendingBlock, SpawnBlocking}, + Transaction, +}; use reth_rpc_eth_types::EthStateCache; +use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; use crate::EthApi; impl EthBlocks for EthApi where - Self: LoadBlock, + Self: LoadBlock + BlockBuilder, + Self::TxBuilder: TransactionBuilder>, Provider: HeaderProvider, { #[inline] diff --git a/crates/rpc/rpc/src/eth/helpers/mod.rs b/crates/rpc/rpc/src/eth/helpers/mod.rs index f0a0cccb5536..03e0443a15bb 100644 --- a/crates/rpc/rpc/src/eth/helpers/mod.rs +++ b/crates/rpc/rpc/src/eth/helpers/mod.rs @@ -2,6 +2,7 @@ //! files. pub mod signer; +pub mod types; mod block; mod call; diff --git a/crates/rpc/rpc/src/eth/helpers/transaction.rs b/crates/rpc/rpc/src/eth/helpers/transaction.rs index 635281c08e76..28330dec7106 100644 --- a/crates/rpc/rpc/src/eth/helpers/transaction.rs +++ b/crates/rpc/rpc/src/eth/helpers/transaction.rs @@ -5,9 +5,10 @@ use std::sync::Arc; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - RawTransactionForwarder, + RawTransactionForwarder, Transaction, }; use reth_rpc_eth_types::EthStateCache; +use reth_rpc_types_compat::TransactionBuilder; use reth_transaction_pool::TransactionPool; use crate::EthApi; @@ -15,7 +16,7 @@ use crate::EthApi; impl EthTransactions for EthApi where - Self: LoadTransaction, + Self: LoadTransaction + TransactionBuilder>, Pool: TransactionPool + 'static, Provider: BlockReaderIdExt, { diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs new file mode 100644 index 000000000000..501d2a4c9214 --- /dev/null +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -0,0 +1,85 @@ +use std::marker::PhantomData; + +use alloy_network::{Ethereum, Network}; +use derive_more::Constructor; +use reth_primitives::{Address, BlockNumber, TransactionSignedEcRecovered, TxKind, B256}; +use reth_rpc_types_compat::{ + transaction::{from_primitive_signature, GasPrice}, + BlockBuilder, TransactionBuilder, +}; + +/// Builds RPC transaction response for l1. +#[derive(Debug, Clone, Copy)] +pub struct EthTxBuilder; + +impl TransactionBuilder for EthTxBuilder +where + Self: Send + Sync, +{ + type Transaction = ::TransactionResponse; + + fn fill( + tx: TransactionSignedEcRecovered, + block_hash: Option, + block_number: Option, + base_fee: Option, + transaction_index: Option, + ) -> Self::Transaction { + let signer = tx.signer(); + let signed_tx = tx.into_signed(); + + let to: Option
= match signed_tx.kind() { + TxKind::Create => None, + TxKind::Call(to) => Some(Address(*to)), + }; + + let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(&signed_tx, base_fee); + + let chain_id = signed_tx.chain_id(); + let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); + let access_list = signed_tx.access_list().cloned(); + let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); + + let signature = from_primitive_signature( + *signed_tx.signature(), + signed_tx.tx_type(), + signed_tx.chain_id(), + ); + + Self::Transaction { + hash: signed_tx.hash(), + nonce: signed_tx.nonce(), + from: signer, + to, + value: signed_tx.value(), + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), + signature: Some(signature), + gas: signed_tx.gas_limit() as u128, + input: signed_tx.input().clone(), + chain_id, + access_list, + transaction_type: Some(signed_tx.tx_type() as u8), + // These fields are set to None because they are not stored as part of the transaction + block_hash, + block_number, + transaction_index: transaction_index.map(|idx| idx as u64), + // EIP-4844 fields + max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), + blob_versioned_hashes, + authorization_list, + other: Default::default(), + } + } +} + +/// Builds a RPC block response for l1. +#[derive(Debug, Clone, Copy, Constructor)] +pub struct EthBlockBuilder { + _tx_builder: PhantomData, +} + +impl BlockBuilder for EthBlockBuilder { + type TxBuilder = TxB; +} diff --git a/crates/rpc/rpc/src/eth/mod.rs b/crates/rpc/rpc/src/eth/mod.rs index 52b10c08c2bf..b7b3d153acd5 100644 --- a/crates/rpc/rpc/src/eth/mod.rs +++ b/crates/rpc/rpc/src/eth/mod.rs @@ -12,6 +12,9 @@ pub use core::EthApi; pub use filter::EthFilter; pub use pubsub::EthPubSub; -pub use helpers::signer::DevSigner; +pub use helpers::{ + signer::DevSigner, + types::{EthBlockBuilder, EthTxBuilder}, +}; pub use reth_rpc_eth_api::{EthApiServer, RawTransactionForwarder}; diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 6cb66c0ebc0d..189a32a1733b 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -1,6 +1,6 @@ //! `eth_` `PubSub` RPC handler implementation -use std::sync::Arc; +use std::{marker::PhantomData, sync::Arc}; use futures::StreamExt; use jsonrpsee::{ @@ -37,8 +37,7 @@ pub struct EthPubSub { inner: Arc>, /// The type that's used to spawn subscription tasks. subscription_task_spawner: Box, - /// Assembles network specific response data. - resp_builder: Eth, + _tx_resp_builder: PhantomData, } // === impl EthPubSub === @@ -47,20 +46,13 @@ impl EthPubSub Self { + pub fn new(provider: Provider, pool: Pool, chain_events: Events, network: Network) -> Self { Self::with_spawner( provider, pool, chain_events, network, Box::::default(), - resp_builder, ) } @@ -71,10 +63,9 @@ impl EthPubSub, - resp_builder: Eth, ) -> Self { let inner = EthPubSubInner { provider, pool, chain_events, network }; - Self { inner: Arc::new(inner), subscription_task_spawner, resp_builder } + Self { inner: Arc::new(inner), subscription_task_spawner, _tx_resp_builder: PhantomData } } } @@ -97,9 +88,8 @@ where ) -> jsonrpsee::core::SubscriptionResult { let sink = pending.accept().await?; let pubsub = self.inner.clone(); - let resp_builder = self.resp_builder.clone(); self.subscription_task_spawner.spawn(Box::pin(async move { - let _ = handle_accepted(pubsub, sink, kind, params, resp_builder).await; + let _ = handle_accepted::<_, _, _, _, Eth>(pubsub, sink, kind, params).await; })); Ok(()) @@ -107,12 +97,11 @@ where } /// The actual handler for an accepted [`EthPubSub::subscribe`] call. -async fn handle_accepted( +async fn handle_accepted( pubsub: Arc>, accepted_sink: SubscriptionSink, kind: SubscriptionKind, params: Option, - tx_builder: TxB, ) -> Result<(), ErrorObject<'static>> where Provider: BlockReader + EvmEnvProvider + Clone + 'static, @@ -120,7 +109,7 @@ where Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction - TxB: TransactionBuilder, + Eth: TransactionBuilder, { match kind { SubscriptionKind::NewHeads => { @@ -148,10 +137,9 @@ where Params::Bool(true) => { // full transaction objects requested let stream = pubsub.full_pending_transaction_stream().map(|tx| { - EthSubscriptionResult::FullTransaction(Box::new( - tx_builder - .from_recovered(tx.transaction.to_recovered_transaction()), - )) + EthSubscriptionResult::FullTransaction(Box::new(Eth::from_recovered( + tx.transaction.to_recovered_transaction(), + ))) }); return pipe_from_stream(accepted_sink, stream).await } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 8915b34dd0c0..1600948e8c77 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -1,3 +1,4 @@ +use alloy_network::Network; use alloy_primitives::Bytes; use async_trait::async_trait; use jsonrpsee::core::RpcResult; @@ -14,7 +15,7 @@ use reth_rpc_types::{ }, parity::{Action, CreateAction, CreateOutput, TraceOutput}, }, - AnyTransactionReceipt, BlockTransactions, Header, RichBlock, + AnyTransactionReceipt, BlockTransactions, Header, RichBlock, Transaction, }; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, @@ -60,6 +61,7 @@ impl OtterscanApi { impl OtterscanServer for OtterscanApi where Eth: EthApiServer + TraceExt + 'static, + Eth::NetworkTypes: Network, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 8d42faa055c8..b9f07140359d 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::{collections::BTreeMap, marker::PhantomData}; use async_trait::async_trait; use jsonrpsee::core::RpcResult as Result; @@ -19,13 +19,13 @@ use tracing::trace; pub struct TxPoolApi { /// An interface to interact with the pool pool: Pool, - resp_builder: Eth, + _tx_resp_builder: PhantomData, } impl TxPoolApi { /// Creates a new instance of `TxpoolApi`. - pub const fn new(pool: Pool, resp_builder: Eth) -> Self { - Self { pool, resp_builder } + pub const fn new(pool: Pool) -> Self { + Self { pool, _tx_resp_builder: PhantomData } } } @@ -40,25 +40,24 @@ where fn insert( tx: &Tx, content: &mut BTreeMap>, - resp_builder: &Eth, ) where Tx: PoolTransaction, Eth: TransactionBuilder, { - content.entry(tx.sender()).or_default().insert( - tx.nonce().to_string(), - resp_builder.from_recovered(tx.to_recovered_transaction()), - ); + content + .entry(tx.sender()) + .or_default() + .insert(tx.nonce().to_string(), Eth::from_recovered(tx.to_recovered_transaction())); } let AllPoolTransactions { pending, queued } = self.pool.all_transactions(); let mut content = TxpoolContent::default(); for pending in pending { - insert(&pending.transaction, &mut content.pending, &self.resp_builder); + insert::<_, Eth>(&pending.transaction, &mut content.pending); } for queued in queued { - insert(&queued.transaction, &mut content.queued, &self.resp_builder); + insert::<_, Eth>(&queued.transaction, &mut content.queued); } content From b0520006ed065c93358d51e815d2535691f8c464 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 1 Aug 2024 18:42:43 +0200 Subject: [PATCH 15/80] Add generics to EthApi trait that are compatible with jsonrpsee --- Cargo.lock | 1 + crates/rpc/rpc-builder/src/lib.rs | 9 +++++---- crates/rpc/rpc-eth-api/Cargo.toml | 1 + crates/rpc/rpc-eth-api/src/core.rs | 24 +++++++++++++----------- crates/rpc/rpc/src/engine.rs | 8 ++++---- crates/rpc/rpc/src/eth/core.rs | 4 ++-- crates/rpc/rpc/src/otterscan.rs | 9 +++++---- 7 files changed, 31 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b414ff67df07..2d2fd94a1ed9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8418,6 +8418,7 @@ name = "reth-rpc-eth-api" version = "1.0.3" dependencies = [ "alloy-dyn-abi", + "alloy-json-rpc", "alloy-network", "async-trait", "auto_impl", diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 12a7a3416826..a650a680d894 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -158,6 +158,7 @@ use reth_provider::{ AccountReader, BlockReader, CanonStateSubscriptions, ChainSpecProvider, ChangeSetReader, EvmEnvProvider, FullRpcProvider, StateProviderFactory, }; +use reth_rpc_eth_api::{Block, Transaction}; use reth_rpc::{ AdminApi, DebugApi, EngineEthApi, EthBundle, NetApi, OtterscanApi, RPCApi, RethApi, TraceApi, TxPoolApi, Web3Api, @@ -799,7 +800,7 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypesCompat, + EthApi: EthApiTypesCompat + EthApiServer, Block>, { /// Register Eth Namespace /// @@ -808,7 +809,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_eth(&mut self) -> &mut Self where - EthApi: EthApiTypesCompat + EthApiServer, + EthApi: EthApiTypesCompat + EthApiServer, Block>, { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); @@ -822,7 +823,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: EthApiServer + TraceExt, + EthApi: TraceExt, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -922,7 +923,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn otterscan_api(&self) -> OtterscanApi where - EthApi: EthApiServer + EthApiTypes, + EthApi: EthApiServer, Block> + EthApiTypes, { let eth_api = self.eth_api().clone(); OtterscanApi::new(eth_api) diff --git a/crates/rpc/rpc-eth-api/Cargo.toml b/crates/rpc/rpc-eth-api/Cargo.toml index 1820f3bad743..0f45e0132398 100644 --- a/crates/rpc/rpc-eth-api/Cargo.toml +++ b/crates/rpc/rpc-eth-api/Cargo.toml @@ -34,6 +34,7 @@ reth-network-api.workspace = true # ethereum alloy-dyn-abi = { workspace = true, features = ["eip712"] } alloy-network.workspace = true +alloy-json-rpc.workspace = true # rpc jsonrpsee = { workspace = true, features = ["server", "macros"] } diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 91fcb1a56eb7..d16978ec7b46 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -2,11 +2,13 @@ //! the `eth_` namespace. use alloy_dyn_abi::TypedData; +use alloy_network::Network; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::{ transaction::AccessListResult, Account, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, }; +use alloy_json_rpc::RpcObject; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; use reth_rpc_types::{ serde_helpers::JsonStorageKey, @@ -26,14 +28,14 @@ use crate::{ /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. -pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +pub trait FullEthApiServer: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone {} -impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +impl FullEthApiServer for T where T: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone {} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi { +pub trait EthApi { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; @@ -60,7 +62,7 @@ pub trait EthApi { /// Returns information about a block by hash. #[method(name = "getBlockByHash")] - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>>; + async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>; /// Returns information about a block by number. #[method(name = "getBlockByNumber")] @@ -68,7 +70,7 @@ pub trait EthApi { &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult>>; + ) -> RpcResult>; /// Returns the number of transactions in a block from a block matching the given block hash. #[method(name = "getBlockTransactionCountByHash")] @@ -105,7 +107,7 @@ pub trait EthApi { &self, hash: B256, index: Index, - ) -> RpcResult>>; + ) -> RpcResult>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockNumberAndIndex")] @@ -113,7 +115,7 @@ pub trait EthApi { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>>; + ) -> RpcResult>; /// Returns the EIP-2718 encoded transaction if it exists. /// @@ -123,7 +125,7 @@ pub trait EthApi { /// Returns the information about a transaction requested by transaction hash. #[method(name = "getTransactionByHash")] - async fn transaction_by_hash(&self, hash: B256) -> RpcResult>>; + async fn transaction_by_hash(&self, hash: B256) -> RpcResult>; /// Returns information about a raw transaction by block hash and transaction index position. #[method(name = "getRawTransactionByBlockHashAndIndex")] @@ -139,7 +141,7 @@ pub trait EthApi { &self, hash: B256, index: Index, - ) -> RpcResult>>; + ) -> RpcResult>; /// Returns information about a raw transaction by block number and transaction index /// position. @@ -156,7 +158,7 @@ pub trait EthApi { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>>; + ) -> RpcResult>; /// Returns the receipt of a transaction by transaction hash. #[method(name = "getTransactionReceipt")] @@ -337,7 +339,7 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer for T +impl EthApiServer, Block> for T where T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index ffa5efc48740..899c92e2d2c7 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -4,9 +4,9 @@ use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64 use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; -use reth_rpc_eth_api::{Block, EthApiTypes}; +use reth_rpc_eth_api::{Block, Transaction, EthApiTypes}; use reth_rpc_types::{ - state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, Transaction, TransactionRequest, + state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, TransactionRequest, }; use reth_rpc_types_compat::TransactionBuilder; use tracing_futures::Instrument; @@ -35,8 +35,8 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer + EthApiTypes + TransactionBuilder, - Eth::NetworkTypes: Network, + Eth: EthApiServer, Block> + EthApiTypes + TransactionBuilder, + Eth::NetworkTypes: Network, EthFilter: EthFilterApiServer, { /// Handler for: `eth_syncing` diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 15499886602a..767fbfae518e 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -538,7 +538,7 @@ mod tests { /// Invalid block range #[tokio::test] async fn test_fee_history_empty() { - let response = as EthApiServer<_>>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( &build_test_eth_api(NoopProvider::default()), U64::from(1), BlockNumberOrTag::Latest, @@ -560,7 +560,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer<_>>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(newest_block + 1), newest_block.into(), diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 1600948e8c77..15c04baa623a 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -4,9 +4,10 @@ use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_primitives::{Address, BlockNumberOrTag, TxHash, B256, U256}; use reth_rpc_api::{EthApiServer, OtterscanServer}; -use reth_rpc_eth_api::helpers::TraceExt; +use reth_rpc_eth_api::helpers::{LoadReceipt, TraceExt}; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::result::internal_rpc_err; +use reth_rpc_eth_api::{Transaction, Block}; use reth_rpc_types::{ trace::{ otterscan::{ @@ -15,7 +16,7 @@ use reth_rpc_types::{ }, parity::{Action, CreateAction, CreateOutput, TraceOutput}, }, - AnyTransactionReceipt, BlockTransactions, Header, RichBlock, Transaction, + AnyTransactionReceipt, BlockTransactions, Header, RichBlock, }; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, @@ -60,8 +61,8 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer + TraceExt + 'static, - Eth::NetworkTypes: Network, + Eth: EthApiServer, Block> + TraceExt + 'static, + Eth::NetworkTypes: Network, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { From 359eae70bbc6d3ff937fd1f5748e520e18d7b512 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 1 Aug 2024 19:09:26 +0200 Subject: [PATCH 16/80] Add temp constraint Network::TransactionResponse = reth_rpc_types::Transaction --- Cargo.lock | 1 + crates/rpc/rpc-builder/Cargo.toml | 4 ++++ crates/rpc/rpc-builder/src/lib.rs | 11 +++++++++-- crates/rpc/rpc-eth-api/src/core.rs | 25 ++++++++++++------------- crates/rpc/rpc/src/engine.rs | 6 ++++-- crates/rpc/rpc/src/otterscan.rs | 8 +++++--- 6 files changed, 35 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2d2fd94a1ed9..1ae9d2b44d6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8339,6 +8339,7 @@ dependencies = [ name = "reth-rpc-builder" version = "1.0.3" dependencies = [ + "alloy-network", "clap", "http 1.1.0", "jsonrpsee", diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index 384a7405816f..bf5d5c5b0489 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -27,6 +27,10 @@ reth-tasks = { workspace = true, features = ["rayon"] } reth-transaction-pool.workspace = true reth-evm.workspace = true reth-engine-primitives.workspace = true +reth-rpc-types.workspace = true + +# ethereum +alloy-network.workspace = true # rpc/net jsonrpsee = { workspace = true, features = ["server"] } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index a650a680d894..c496973b4bbb 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -158,7 +158,6 @@ use reth_provider::{ AccountReader, BlockReader, CanonStateSubscriptions, ChainSpecProvider, ChangeSetReader, EvmEnvProvider, FullRpcProvider, StateProviderFactory, }; -use reth_rpc_eth_api::{Block, Transaction}; use reth_rpc::{ AdminApi, DebugApi, EngineEthApi, EthBundle, NetApi, OtterscanApi, RPCApi, RethApi, TraceApi, TxPoolApi, Web3Api, @@ -168,7 +167,8 @@ use reth_rpc_eth_api::{ helpers::{ Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder, }, - EthApiServer, EthApiTypes, EthApiTypesCompat, FullEthApiServer, RawTransactionForwarder, + Block, EthApiServer, EthApiTypes, EthApiTypesCompat, FullEthApiServer, RawTransactionForwarder, + Transaction, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -231,6 +231,7 @@ where Events: CanonStateSubscriptions + Clone + 'static, EvmConfig: ConfigureEvm, EthApi: FullEthApiServer, + EthApi::NetworkTypes: alloy_network::Network, { let module_config = module_config.into(); server_config @@ -438,6 +439,8 @@ where EngineT: EngineTypes, EngineApi: EngineApiServer, EthApi: FullEthApiServer, + EthApi::NetworkTypes: + alloy_network::Network, { let Self { provider, pool, network, executor, events, evm_config } = self; @@ -504,6 +507,8 @@ where ) -> TransportRpcModules<()> where EthApi: FullEthApiServer, + EthApi::NetworkTypes: + alloy_network::Network, { let mut modules = TransportRpcModules::default(); @@ -801,6 +806,7 @@ where Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, EthApi: EthApiTypesCompat + EthApiServer, Block>, + EthApi::NetworkTypes: alloy_network::Network, { /// Register Eth Namespace /// @@ -970,6 +976,7 @@ where Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, EthApi: FullEthApiServer, + EthApi::NetworkTypes: alloy_network::Network, { /// Configures the auth module that includes the /// * `engine_` namespace diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index d16978ec7b46..3f8502670d9d 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -2,13 +2,13 @@ //! the `eth_` namespace. use alloy_dyn_abi::TypedData; +use alloy_json_rpc::RpcObject; use alloy_network::Network; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::{ transaction::AccessListResult, Account, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, }; -use alloy_json_rpc::RpcObject; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; use reth_rpc_types::{ serde_helpers::JsonStorageKey, @@ -28,9 +28,15 @@ use crate::{ /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. -pub trait FullEthApiServer: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone {} +pub trait FullEthApiServer: + EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone +{ +} -impl FullEthApiServer for T where T: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone {} +impl FullEthApiServer for T where + T: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone +{ +} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] @@ -66,11 +72,7 @@ pub trait EthApi { /// Returns information about a block by number. #[method(name = "getBlockByNumber")] - async fn block_by_number( - &self, - number: BlockNumberOrTag, - full: bool, - ) -> RpcResult>; + async fn block_by_number(&self, number: BlockNumberOrTag, full: bool) -> RpcResult>; /// Returns the number of transactions in a block from a block matching the given block hash. #[method(name = "getBlockTransactionCountByHash")] @@ -103,11 +105,8 @@ pub trait EthApi { /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockHashAndIndex")] - async fn uncle_by_block_hash_and_index( - &self, - hash: B256, - index: Index, - ) -> RpcResult>; + async fn uncle_by_block_hash_and_index(&self, hash: B256, index: Index) + -> RpcResult>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockNumberAndIndex")] diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 899c92e2d2c7..e13333ce9a99 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -4,7 +4,7 @@ use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64 use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; -use reth_rpc_eth_api::{Block, Transaction, EthApiTypes}; +use reth_rpc_eth_api::{Block, EthApiTypes, Transaction}; use reth_rpc_types::{ state::StateOverride, BlockOverrides, Filter, Log, SyncStatus, TransactionRequest, }; @@ -35,7 +35,9 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, Block> + EthApiTypes + TransactionBuilder, + Eth: EthApiServer, Block> + + EthApiTypes + + TransactionBuilder, Eth::NetworkTypes: Network, EthFilter: EthFilterApiServer, { diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 15c04baa623a..5e3f2a584a26 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -4,10 +4,12 @@ use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_primitives::{Address, BlockNumberOrTag, TxHash, B256, U256}; use reth_rpc_api::{EthApiServer, OtterscanServer}; -use reth_rpc_eth_api::helpers::{LoadReceipt, TraceExt}; +use reth_rpc_eth_api::{ + helpers::{LoadReceipt, TraceExt}, + Block, EthApiTypes, Transaction, +}; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::result::internal_rpc_err; -use reth_rpc_eth_api::{Transaction, Block}; use reth_rpc_types::{ trace::{ otterscan::{ @@ -61,7 +63,7 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer, Block> + TraceExt + 'static, + Eth: EthApiServer, Block> + EthApiTypes + TraceExt + 'static, Eth::NetworkTypes: Network, { /// Handler for `{ots,erigon}_getHeaderByNumber` From e12d811a80f519adf079ebaae5b61e5d115cdfa0 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 1 Aug 2024 19:21:30 +0200 Subject: [PATCH 17/80] Replace EthFilterApi and EthPubSubApi generics with jsonrpsee compatible generics --- crates/rpc/rpc-eth-api/src/filter.rs | 5 +++-- crates/rpc/rpc-eth-api/src/pubsub.rs | 3 ++- crates/rpc/rpc/src/eth/filter.rs | 2 +- crates/rpc/rpc/src/eth/pubsub.rs | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index deb27e1cb8b4..a43a040ddc39 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -1,5 +1,6 @@ //! `eth_` RPC API for filtering. +use alloy_json_rpc::RpcObject; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_rpc_types::{ Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind, Transaction, @@ -9,7 +10,7 @@ use reth_rpc_types_compat::TransactionBuilder; /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthFilterApi> { +pub trait EthFilterApi { /// Creates anew filter and returns its id. #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult; @@ -27,7 +28,7 @@ pub trait EthFilterApi> { /// Returns all filter changes since last poll. #[method(name = "getFilterChanges")] - async fn filter_changes(&self, id: FilterId) -> RpcResult>; + async fn filter_changes(&self, id: FilterId) -> RpcResult>; /// Returns all logs matching given filter (in a range 'from' - 'to'). #[method(name = "getFilterLogs")] diff --git a/crates/rpc/rpc-eth-api/src/pubsub.rs b/crates/rpc/rpc-eth-api/src/pubsub.rs index 760ee54e3ead..c4074ec12055 100644 --- a/crates/rpc/rpc-eth-api/src/pubsub.rs +++ b/crates/rpc/rpc-eth-api/src/pubsub.rs @@ -1,12 +1,13 @@ //! `eth_` RPC API for pubsub subscription. +use alloy_json_rpc::RpcObject; use jsonrpsee::proc_macros::rpc; use reth_rpc_types::pubsub::{Params, SubscriptionKind}; use reth_rpc_types_compat::TransactionBuilder; /// Ethereum pub-sub rpc interface. #[rpc(server, namespace = "eth")] -pub trait EthPubSubApi { +pub trait EthPubSubApi { /// Create an ethereum subscription for the given params #[subscription( name = "subscribe" => "subscription", diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index d19f477b377a..0203fd517497 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -238,7 +238,7 @@ where } #[async_trait] -impl EthFilterApiServer for EthFilter +impl EthFilterApiServer for EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 189a32a1733b..f76066c56a1d 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -70,7 +70,7 @@ impl EthPubSub EthPubSubApiServer +impl EthPubSubApiServer for EthPubSub where Provider: BlockReader + EvmEnvProvider + Clone + 'static, From fa58787b52e83769408a78fa38abacbd5b5c3ef9 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 1 Aug 2024 19:24:57 +0200 Subject: [PATCH 18/80] Fix lint --- crates/rpc/rpc-eth-api/src/core.rs | 3 +-- crates/rpc/rpc-eth-api/src/filter.rs | 5 +---- crates/rpc/rpc-eth-api/src/pubsub.rs | 1 - 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 3f8502670d9d..93ee0d37e833 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -3,7 +3,6 @@ use alloy_dyn_abi::TypedData; use alloy_json_rpc::RpcObject; -use alloy_network::Network; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::{ transaction::AccessListResult, Account, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, @@ -23,7 +22,7 @@ use crate::{ transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, EthTransactions, FullEthApi, }, - Block, EthApiTypes, Transaction, + Block, Transaction, }; /// Helper trait, unifies functionality that must be supported to implement all RPC methods for diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index a43a040ddc39..26c47226cfc3 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -2,10 +2,7 @@ use alloy_json_rpc::RpcObject; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_rpc_types::{ - Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind, Transaction, -}; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types::{Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind}; /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] diff --git a/crates/rpc/rpc-eth-api/src/pubsub.rs b/crates/rpc/rpc-eth-api/src/pubsub.rs index c4074ec12055..8282e6b6af64 100644 --- a/crates/rpc/rpc-eth-api/src/pubsub.rs +++ b/crates/rpc/rpc-eth-api/src/pubsub.rs @@ -3,7 +3,6 @@ use alloy_json_rpc::RpcObject; use jsonrpsee::proc_macros::rpc; use reth_rpc_types::pubsub::{Params, SubscriptionKind}; -use reth_rpc_types_compat::TransactionBuilder; /// Ethereum pub-sub rpc interface. #[rpc(server, namespace = "eth")] From 4e1d95fbd2f5c9d11a4fc6e664056a30edec5c5f Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 2 Aug 2024 19:14:58 +0200 Subject: [PATCH 19/80] Remove redundant trait bounds --- crates/node/builder/src/rpc.rs | 5 +---- crates/rpc/rpc-builder/src/eth.rs | 11 +---------- crates/rpc/rpc-eth-types/src/builder/ctx.rs | 15 ++------------- 3 files changed, 4 insertions(+), 27 deletions(-) diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 8a73b3315919..e9349af416d1 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -336,9 +336,7 @@ where } /// Provides builder for the core `eth` API type. -pub trait EthApiBuilderProvider: - BuilderProvider -{ +pub trait EthApiBuilderProvider: BuilderProvider { /// Returns the eth api builder. #[allow(clippy::type_complexity)] fn eth_api_builder() -> Box) -> Self + Send>; @@ -347,7 +345,6 @@ pub trait EthApiBuilderProvider: impl EthApiBuilderProvider for F where N: FullNodeComponents, - Eth: EthApiTypesCompat, for<'a> F: BuilderProvider = &'a EthApiBuilderCtx>, { fn eth_api_builder() -> Box) -> Self + Send> { diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index 21fd0f20a92f..23d08ef24530 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -66,15 +66,7 @@ where /// Builds [`EthHandlers`] for core, filter, and pubsub `eth_` apis. #[allow(missing_debug_implementations)] -pub struct EthHandlersBuilder< - Provider, - Pool, - Network, - Tasks, - Events, - EvmConfig, - EthApi: EthApiTypesCompat, -> { +pub struct EthHandlersBuilder { provider: Provider, pool: Pool, network: Network, @@ -179,7 +171,6 @@ impl EthPubSubApiBuilder { Events: Clone, Network: Clone, Tasks: TaskSpawner + Clone + 'static, - Eth: EthApiTypesCompat, { EthPubSub::with_spawner( ctx.provider.clone(), diff --git a/crates/rpc/rpc-eth-types/src/builder/ctx.rs b/crates/rpc/rpc-eth-types/src/builder/ctx.rs index a21d99bc94ae..883c1be63d8f 100644 --- a/crates/rpc/rpc-eth-types/src/builder/ctx.rs +++ b/crates/rpc/rpc-eth-types/src/builder/ctx.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; -use reth_rpc_types_compat::{ResponseTypeBuilders, TransactionBuilder}; +use reth_rpc_types_compat::ResponseTypeBuilders; use reth_tasks::TaskSpawner; use crate::{ @@ -13,15 +13,7 @@ use crate::{ /// Context for building the `eth` namespace API. #[derive(Debug, Clone)] -pub struct EthApiBuilderCtx< - Provider, - Pool, - EvmConfig, - Network, - Tasks, - Events, - Eth: TransactionBuilder, -> { +pub struct EthApiBuilderCtx { /// Database handle. pub provider: Provider, /// Mempool handle. @@ -46,7 +38,6 @@ impl EthApiBuilderCtx where Provider: BlockReaderIdExt + Clone, - Eth: ResponseTypeBuilders, { /// Returns a new [`FeeHistoryCache`] for the context. pub fn new_fee_history_cache(&self) -> FeeHistoryCache @@ -75,7 +66,6 @@ impl GasPriceOracleBuilder { ) -> GasPriceOracle where Provider: BlockReaderIdExt + Clone, - Eth: ResponseTypeBuilders, { GasPriceOracle::new(ctx.provider.clone(), ctx.config.gas_oracle, ctx.cache.clone()) } @@ -94,7 +84,6 @@ impl FeeHistoryCacheBuilder { Provider: ChainSpecProvider + BlockReaderIdExt + Clone + 'static, Tasks: TaskSpawner, Events: CanonStateSubscriptions, - Eth: ResponseTypeBuilders, { let fee_history_cache = FeeHistoryCache::new(ctx.cache.clone(), ctx.config.fee_history_cache); From d859c5e28b076a974213205acdc5aa8b8c9adf6f Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 2 Aug 2024 19:53:20 +0200 Subject: [PATCH 20/80] Flatten trait ResponseTypeBuilders into EthApiTypes --- Cargo.lock | 1 + crates/rpc/rpc-builder/Cargo.toml | 1 + crates/rpc/rpc-builder/src/eth.rs | 14 ++++---- crates/rpc/rpc-builder/src/lib.rs | 19 +++++----- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 6 ++-- crates/rpc/rpc-eth-api/src/helpers/types.rs | 13 +++---- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-types/src/builder/ctx.rs | 1 - crates/rpc/rpc-types-compat/src/builders.rs | 39 --------------------- crates/rpc/rpc-types-compat/src/lib.rs | 2 -- crates/rpc/rpc/src/eth/core.rs | 6 ---- 11 files changed, 29 insertions(+), 75 deletions(-) delete mode 100644 crates/rpc/rpc-types-compat/src/builders.rs diff --git a/Cargo.lock b/Cargo.lock index 12eb69380bba..569a0d6d477c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8367,6 +8367,7 @@ dependencies = [ "reth-rpc-layer", "reth-rpc-server-types", "reth-rpc-types", + "reth-rpc-types-compat", "reth-tasks", "reth-tokio-util", "reth-tracing", diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index bf5d5c5b0489..c2304b745bc6 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -28,6 +28,7 @@ reth-transaction-pool.workspace = true reth-evm.workspace = true reth-engine-primitives.workspace = true reth-rpc-types.workspace = true +reth-rpc-types-compat.workspace = true # ethereum alloy-network.workspace = true diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index 23d08ef24530..b430699d867b 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use reth_evm::ConfigureEvm; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider, StateProviderFactory}; use reth_rpc::{EthFilter, EthPubSub}; -use reth_rpc_eth_api::EthApiTypesCompat; +use reth_rpc_eth_api::EthApiTypes; use reth_rpc_eth_types::{ cache::cache_new_blocks_task, EthApiBuilderCtx, EthConfig, EthStateCache, }; @@ -16,20 +16,20 @@ pub type DynEthApiBuilder { +pub struct EthHandlers { /// Main `eth_` request handler pub api: EthApi, /// The async caching layer used by the eth handlers pub cache: EthStateCache, /// Polling based filter handler available on all transports - pub filter: EthFilter, + pub filter: EthFilter, /// Handler for subscriptions only available for transports that support it (ws, ipc) pub pubsub: EthPubSub, } impl EthHandlers where - EthApi: EthApiTypesCompat, + EthApi: EthApiTypes, { /// Returns a new [`EthHandlers`] builder. #[allow(clippy::too_many_arguments)] @@ -86,7 +86,7 @@ where Network: Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: EthApiTypesCompat + 'static, + EthApi: EthApiTypes + 'static, { /// Returns a new instance with handlers for `eth` namespace. pub fn build(self) -> EthHandlers { @@ -139,12 +139,12 @@ impl EthFilterApiBuilder { /// Builds the [`EthFilterApiServer`](reth_rpc_eth_api::EthFilterApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthFilter + ) -> EthFilter where Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - Eth: EthApiTypesCompat + 'static, + Eth: EthApiTypes + 'static, { EthFilter::new( ctx.provider.clone(), diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 70eeca3148bf..5d74c91b20be 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -167,8 +167,7 @@ use reth_rpc_eth_api::{ helpers::{ Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder, }, - Block, EthApiServer, EthApiTypes, EthApiTypesCompat, FullEthApiServer, RawTransactionForwarder, - Transaction, + Block, EthApiServer, EthApiTypes, FullEthApiServer, RawTransactionForwarder, Transaction, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -492,7 +491,7 @@ where eth: DynEthApiBuilder, ) -> RpcRegistryInner where - EthApi: EthApiTypesCompat + 'static, + EthApi: EthApiTypes + 'static, { let Self { provider, pool, network, executor, events, evm_config } = self; RpcRegistryInner::new(provider, pool, network, executor, events, config, evm_config, eth) @@ -614,7 +613,7 @@ impl RpcModuleConfigBuilder { /// A Helper type the holds instances of the configured modules. #[derive(Debug, Clone)] -pub struct RpcRegistryInner { +pub struct RpcRegistryInner { provider: Provider, pool: Pool, network: Network, @@ -638,7 +637,7 @@ where Network: Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypesCompat + 'static, + EthApi: EthApiTypes + 'static, { /// Creates a new, empty instance. #[allow(clippy::too_many_arguments)] @@ -693,7 +692,7 @@ where impl RpcRegistryInner where - EthApi: EthApiTypesCompat, + EthApi: EthApiTypes, { /// Returns a reference to the installed [`EthApi`](reth_rpc::eth::EthApi). pub const fn eth_api(&self) -> &EthApi { @@ -751,7 +750,7 @@ where impl RpcRegistryInner where - EthApi: EthApiTypesCompat + UpdateRawTxForwarder, + EthApi: EthApiTypes + UpdateRawTxForwarder, { /// Sets a forwarder for `eth_sendRawTransaction` /// @@ -766,7 +765,7 @@ impl RpcRegistryInner where Network: NetworkInfo + Clone + 'static, - EthApi: EthApiTypesCompat, + EthApi: EthApiTypes, { /// Instantiates `AdminApi` pub fn admin_api(&self) -> AdminApi @@ -805,7 +804,7 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypesCompat + EthApiServer, Block>, + EthApi: EthApiTypes + EthApiServer, Block>, EthApi::NetworkTypes: alloy_network::Network, { /// Register Eth Namespace @@ -815,7 +814,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_eth(&mut self) -> &mut Self where - EthApi: EthApiTypesCompat + EthApiServer, Block>, + EthApi: EthApiTypes + EthApiServer, Block>, { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index b74ecc8156fa..a86f44257f3a 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -40,7 +40,7 @@ pub use state::{EthState, LoadState}; pub use trace::Trace; pub use transaction::{EthTransactions, LoadTransaction, UpdateRawTxForwarder}; -use crate::EthApiTypesCompat; +use crate::EthApiTypes; /// Extension trait that bundles traits needed for tracing transactions. pub trait TraceExt: @@ -54,7 +54,7 @@ impl TraceExt for T where T: LoadTransaction + LoadBlock + LoadPendingBlock + /// /// This trait is automatically implemented for any type that implements all the `Eth` traits. pub trait FullEthApi: - EthApiTypesCompat + EthApiTypes + EthApiSpec + EthTransactions + EthBlocks @@ -67,7 +67,7 @@ pub trait FullEthApi: } impl FullEthApi for T where - T: EthApiTypesCompat + T: EthApiTypes + EthApiSpec + EthTransactions + EthBlocks diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 68a6009136e5..67667da161f4 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -4,12 +4,12 @@ use std::error::Error; use alloy_network::Network; use reth_rpc_types::Rich; -use reth_rpc_types_compat::ResponseTypeBuilders; +use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; /// Network specific `eth` API types. -pub trait EthApiTypes: Send + Sync { +pub trait EthApiTypes: Send + Sync + Clone { /// Extension of [`EthApiError`](reth_rpc_eth_types::EthApiError), with network specific errors. type Error: Into> + FromEthApiError @@ -18,8 +18,12 @@ pub trait EthApiTypes: Send + Sync { + Error + Send + Sync; - /// Blockchain data types, specific to network, e.g. block and transaction. + /// Blockchain primitive types, specific to network, e.g. block and transaction. type NetworkTypes: Network; + /// Conversion methods for transaction RPC type. + type TransactionBuilder: TransactionBuilder>; + /// Conversion methods for block RPC type. + type BlockBuilder: BlockBuilder; } /// Adapter for network specific transaction type. @@ -27,6 +31,3 @@ pub type Transaction = <::NetworkTypes as Network>::Transac /// Adapter for network specific block type. pub type Block = Rich>>; - -/// Helper trait that unifies [`EthApiTypes`] with type conversions. -pub trait EthApiTypesCompat: EthApiTypes + ResponseTypeBuilders {} diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 933e947d2e90..39bfb0d629ea 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::{Block, EthApiTypes, EthApiTypesCompat, Transaction}, + types::{Block, EthApiTypes, Transaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-types/src/builder/ctx.rs b/crates/rpc/rpc-eth-types/src/builder/ctx.rs index 883c1be63d8f..833f3e0f7022 100644 --- a/crates/rpc/rpc-eth-types/src/builder/ctx.rs +++ b/crates/rpc/rpc-eth-types/src/builder/ctx.rs @@ -3,7 +3,6 @@ use std::marker::PhantomData; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; -use reth_rpc_types_compat::ResponseTypeBuilders; use reth_tasks::TaskSpawner; use crate::{ diff --git a/crates/rpc/rpc-types-compat/src/builders.rs b/crates/rpc/rpc-types-compat/src/builders.rs deleted file mode 100644 index 7162830ec740..000000000000 --- a/crates/rpc/rpc-types-compat/src/builders.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Unifies network specific RPC type conversions. - -use std::fmt; - -use reth_primitives::{BlockNumber, TransactionSignedEcRecovered, B256}; - -use crate::{BlockBuilder, TransactionBuilder}; - -/// Helper trait that unifies [`EthApiTypes`] with type conversions. -pub trait ResponseTypeBuilders: Send + Sync + Unpin + Clone + fmt::Debug { - /// Builds RPC transaction response type w.r.t. network. - type TransactionBuilder: TransactionBuilder; - /// Builds RPC block response type w.r.t. network. - type BlockBuilder: BlockBuilder; -} - -impl TransactionBuilder for T -where - T: ResponseTypeBuilders, -{ - type Transaction = ::Transaction; - - fn fill( - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - T::TransactionBuilder::fill(tx, block_hash, block_number, base_fee, transaction_index) - } -} - -impl BlockBuilder for T -where - T: ResponseTypeBuilders, -{ - type TxBuilder = T::TransactionBuilder; -} diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index b8359b7b7407..1926d2bfbacd 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -11,11 +11,9 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] pub mod block; -pub mod builders; pub mod engine; pub mod proof; pub mod transaction; pub use block::BlockBuilder; -pub use builders::ResponseTypeBuilders; pub use transaction::TransactionBuilder; diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 767fbfae518e..2b3d2578a3e1 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -16,7 +16,6 @@ use reth_rpc_eth_types::{ EthApiBuilderCtx, EthApiError, EthStateCache, FeeHistoryCache, GasCap, GasPriceOracle, PendingBlock, }; -use reth_rpc_types_compat::ResponseTypeBuilders; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskExecutor, TaskSpawner, TokioTaskExecutor, @@ -140,11 +139,6 @@ where { type Error = EthApiError; type NetworkTypes = Ethereum; -} - -impl ResponseTypeBuilders - for EthApi -{ type TransactionBuilder = EthTxBuilder; type BlockBuilder = EthBlockBuilder; } From b733699f83b5731ecd03ebc42b9e1892a569d697 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 2 Aug 2024 20:03:13 +0200 Subject: [PATCH 21/80] Remove duplicate file --- crates/rpc/rpc-eth-types/src/builders.rs | 82 ------------------------ 1 file changed, 82 deletions(-) delete mode 100644 crates/rpc/rpc-eth-types/src/builders.rs diff --git a/crates/rpc/rpc-eth-types/src/builders.rs b/crates/rpc/rpc-eth-types/src/builders.rs deleted file mode 100644 index c02f78dc23d1..000000000000 --- a/crates/rpc/rpc-eth-types/src/builders.rs +++ /dev/null @@ -1,82 +0,0 @@ -use std::marker::PhantomData; - -use alloy_network::{Ethereum, Network}; -use derive_more::Constructor; -use reth_primitives::{BlockNumber, B256, TransactionSignedEcRecovered, Address, TxKind}; -use reth_rpc_types_compat::{transaction::{from_primitive_signature, GasPrice}, BlockBuilder, TransactionBuilder}; - -/// Builds RPC transaction response for l1. -#[derive(Debug, Clone, Copy)] -pub struct EthTxBuilder; - -impl TransactionBuilder for EthTxBuilder -where - Self: Send + Sync, -{ - type Transaction = ::TransactionResponse; - - fn fill( - tx: TransactionSignedEcRecovered, - block_hash: Option, - block_number: Option, - base_fee: Option, - transaction_index: Option, - ) -> Self::Transaction { - let signer = tx.signer(); - let signed_tx = tx.into_signed(); - - let to: Option
= match signed_tx.kind() { - TxKind::Create => None, - TxKind::Call(to) => Some(Address(*to)), - }; - - let GasPrice { gas_price, max_fee_per_gas } = Self::gas_price(&signed_tx, base_fee); - - let chain_id = signed_tx.chain_id(); - let blob_versioned_hashes = signed_tx.blob_versioned_hashes(); - let access_list = signed_tx.access_list().cloned(); - let authorization_list = signed_tx.authorization_list().map(|l| l.to_vec()); - - let signature = from_primitive_signature( - *signed_tx.signature(), - signed_tx.tx_type(), - signed_tx.chain_id(), - ); - - Self::Transaction { - hash: signed_tx.hash(), - nonce: signed_tx.nonce(), - from: signer, - to, - value: signed_tx.value(), - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), - signature: Some(signature), - gas: signed_tx.gas_limit() as u128, - input: signed_tx.input().clone(), - chain_id, - access_list, - transaction_type: Some(signed_tx.tx_type() as u8), - // These fields are set to None because they are not stored as part of the transaction - block_hash, - block_number, - transaction_index: transaction_index.map(|idx| idx as u64), - // EIP-4844 fields - max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), - blob_versioned_hashes, - authorization_list, - other: Default::default(), - } - } -} - -/// Builds a RPC block response for l1. -#[derive(Debug, Clone, Copy, Constructor)] -pub struct EthBlockBuilder { - _tx_builder: PhantomData, -} - -impl BlockBuilder for EthBlockBuilder { - type TxBuilder = TxB; -} From 179bd6b9f3e971e39f26b15b4ec12536d1fbf49a Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 2 Aug 2024 22:39:18 +0200 Subject: [PATCH 22/80] Add noop impl for EthApiTypes --- crates/rpc/rpc-builder/Cargo.toml | 1 - crates/rpc/rpc-eth-api/src/helpers/types.rs | 10 +++++++++- crates/rpc/rpc-types-compat/src/block.rs | 11 +++++++++++ .../rpc/rpc-types-compat/src/transaction/mod.rs | 17 +++++++++++++++++ 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index c2304b745bc6..bf5d5c5b0489 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -28,7 +28,6 @@ reth-transaction-pool.workspace = true reth-evm.workspace = true reth-engine-primitives.workspace = true reth-rpc-types.workspace = true -reth-rpc-types-compat.workspace = true # ethereum alloy-network.workspace = true diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 67667da161f4..1c5944d03ec8 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -2,7 +2,8 @@ use std::error::Error; -use alloy_network::Network; +use alloy_network::{AnyNetwork, Network}; +use reth_rpc_eth_types::EthApiError; use reth_rpc_types::Rich; use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; @@ -26,6 +27,13 @@ pub trait EthApiTypes: Send + Sync + Clone { type BlockBuilder: BlockBuilder; } +impl EthApiTypes for () { + type Error = EthApiError; + type NetworkTypes = AnyNetwork; + type TransactionBuilder = (); + type BlockBuilder = (); +} + /// Adapter for network specific transaction type. pub type Transaction = <::NetworkTypes as Network>::TransactionResponse; diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 4b22477e8c2f..b3b5a040b461 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -101,6 +101,17 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { } } +impl BlockBuilder for () { + type TxBuilder = (); + + fn from_block_full( + _block: BlockWithSenders, + _total_difficulty: U256, + _block_hash: Option, + ) -> Result::Transaction>, BlockError> { + Ok(Block::default()) + } +} /// Converts from a [`reth_primitives::SealedHeader`] to a [`reth_rpc_types::Header`] /// /// # Note diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 7cbe9bcdc225..036047934ff4 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -10,6 +10,7 @@ use std::fmt; use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; +use reth_rpc_types::{Transaction, WithOtherFields}; /// Builds RPC transaction w.r.t. network. pub trait TransactionBuilder: Send + Sync + Unpin + Clone + fmt::Debug { @@ -124,3 +125,19 @@ pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> Transact sidecar: None, } } + +impl TransactionBuilder for () { + // this noop impl depends on integration in `reth_rpc_eth_api::EthApiTypes` noop impl, and + // `alloy_network::AnyNetwork` + type Transaction = WithOtherFields; + + fn fill( + _tx: TransactionSignedEcRecovered, + _block_hash: Option, + _block_number: Option, + _base_fee: Option, + _transaction_index: Option, + ) -> Self::Transaction { + WithOtherFields::default() + } +} From 626c87761aebc2279aa05550e61ee44125f37ab4 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 2 Aug 2024 22:41:55 +0200 Subject: [PATCH 23/80] Add EthApiTypes trait bounds to node builder --- Cargo.lock | 4 +- crates/ethereum/node/Cargo.toml | 3 + crates/ethereum/node/src/launch.rs | 4 +- crates/node/api/Cargo.toml | 1 + crates/node/api/src/lib.rs | 2 + crates/node/api/src/node.rs | 3 +- crates/node/builder/Cargo.toml | 3 + crates/node/builder/src/builder/add_ons.rs | 4 +- crates/node/builder/src/builder/mod.rs | 11 +++- crates/node/builder/src/launch/mod.rs | 4 +- crates/node/builder/src/rpc.rs | 73 ++++++++++++++++------ crates/optimism/rpc/src/eth/mod.rs | 2 +- 12 files changed, 87 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 569a0d6d477c..ca3e5bf83e74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7660,6 +7660,7 @@ dependencies = [ "reth-payload-builder", "reth-payload-primitives", "reth-provider", + "reth-rpc-eth-api", "reth-tasks", "reth-transaction-pool", ] @@ -7668,6 +7669,7 @@ dependencies = [ name = "reth-node-builder" version = "1.0.3" dependencies = [ + "alloy-network", "aquamarine", "confy", "eyre", @@ -7771,6 +7773,7 @@ name = "reth-node-ethereum" version = "1.0.3" dependencies = [ "alloy-genesis", + "alloy-network", "alloy-primitives", "eyre", "futures", @@ -8367,7 +8370,6 @@ dependencies = [ "reth-rpc-layer", "reth-rpc-server-types", "reth-rpc-types", - "reth-rpc-types-compat", "reth-tasks", "reth-tokio-util", "reth-tracing", diff --git a/crates/ethereum/node/Cargo.toml b/crates/ethereum/node/Cargo.toml index 7b2cef39e538..346d41272c33 100644 --- a/crates/ethereum/node/Cargo.toml +++ b/crates/ethereum/node/Cargo.toml @@ -38,6 +38,9 @@ reth-exex.workspace = true reth-blockchain-tree.workspace = true reth-engine-tree.workspace = true +# ethereum +alloy-network.workspace = true + # misc eyre.workspace = true tokio = { workspace = true , features = ["sync"]} diff --git a/crates/ethereum/node/src/launch.rs b/crates/ethereum/node/src/launch.rs index d2278699e3ef..fbfbafc87065 100644 --- a/crates/ethereum/node/src/launch.rs +++ b/crates/ethereum/node/src/launch.rs @@ -11,7 +11,7 @@ use reth_ethereum_engine::service::{ChainEvent, EthService}; use reth_ethereum_engine_primitives::EthEngineTypes; use reth_exex::ExExManagerHandle; use reth_network::{BlockDownloaderProvider, NetworkEvents, NetworkSyncUpdater, SyncState}; -use reth_node_api::{FullNodeTypes, NodeAddOns}; +use reth_node_api::{EthApiTypes, FullNodeTypes, NodeAddOns}; use reth_node_builder::{ hooks::NodeHooks, rpc::{launch_rpc_servers, EthApiBuilderProvider}, @@ -59,6 +59,8 @@ where AO: NodeAddOns>, AO::EthApi: EthApiBuilderProvider> + FullEthApiServer + AddDevSigners, + ::NetworkTypes: + alloy_network::Network, { type Node = NodeHandle, AO>; diff --git a/crates/node/api/Cargo.toml b/crates/node/api/Cargo.toml index 2ae8f52c9ae6..c3b7ee9bef6f 100644 --- a/crates/node/api/Cargo.toml +++ b/crates/node/api/Cargo.toml @@ -21,3 +21,4 @@ reth-network.workspace = true reth-payload-builder.workspace = true reth-payload-primitives.workspace = true reth-tasks.workspace = true +reth-rpc-eth-api.workspace = true diff --git a/crates/node/api/src/lib.rs b/crates/node/api/src/lib.rs index b01a2def0bde..8748fc79d94e 100644 --- a/crates/node/api/src/lib.rs +++ b/crates/node/api/src/lib.rs @@ -26,3 +26,5 @@ pub use node::*; // re-export for convenience pub use reth_provider::FullProvider; + +pub use reth_rpc_eth_api::EthApiTypes; diff --git a/crates/node/api/src/node.rs b/crates/node/api/src/node.rs index da4115ec9ce5..e20dfc4171c7 100644 --- a/crates/node/api/src/node.rs +++ b/crates/node/api/src/node.rs @@ -10,6 +10,7 @@ use reth_evm::execute::BlockExecutorProvider; use reth_network::FullNetwork; use reth_payload_builder::PayloadBuilderHandle; use reth_provider::FullProvider; +use reth_rpc_eth_api::EthApiTypes; use reth_tasks::TaskExecutor; use reth_transaction_pool::TransactionPool; @@ -155,7 +156,7 @@ pub trait FullNodeComponents: FullNodeTypes + Clone + 'static { pub trait NodeAddOns: Send + Sync + Unpin + Clone + 'static { /// The core `eth` namespace API type to install on the RPC server (see /// `reth_rpc_eth_api::EthApiServer`). - type EthApi: Send + Clone; + type EthApi: EthApiTypes + Send + Clone; } impl NodeAddOns for () { diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index c10b15615e45..235d57a27b96 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -50,6 +50,9 @@ reth-engine-util.workspace = true reth-cli-util.workspace = true reth-rpc-eth-types.workspace = true +## ethereum +alloy-network.workspace = true + ## async futures.workspace = true tokio = { workspace = true, features = [ diff --git a/crates/node/builder/src/builder/add_ons.rs b/crates/node/builder/src/builder/add_ons.rs index 54a776fd69aa..e8eb3b49dc7b 100644 --- a/crates/node/builder/src/builder/add_ons.rs +++ b/crates/node/builder/src/builder/add_ons.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; -use reth_node_api::{FullNodeComponents, NodeAddOns}; +use reth_node_api::{EthApiTypes, FullNodeComponents, NodeAddOns}; use crate::{exex::BoxedLaunchExEx, hooks::NodeHooks, rpc::RpcHooks}; @@ -21,7 +21,7 @@ pub struct AddOns> { /// Captures node specific addons that can be installed on top of the type configured node and are /// required for launching the node, such as RPC. #[derive(Default)] -pub struct RpcAddOns { +pub struct RpcAddOns { /// Core `eth` API type to install on the RPC server, configured w.r.t. network. pub _eth_api: PhantomData, /// Additional RPC hooks. diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 9c146be0827a..287f1d28370f 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -20,7 +20,7 @@ use reth_exex::ExExContext; use reth_network::{ NetworkBuilder, NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, }; -use reth_node_api::{FullNodeTypes, FullNodeTypesAdapter, NodeAddOns, NodeTypes}; +use reth_node_api::{EthApiTypes, FullNodeTypes, FullNodeTypesAdapter, NodeAddOns, NodeTypes}; use reth_node_core::{ cli::config::{PayloadBuilderConfig, RethTransactionPoolConfig}, dirs::{ChainPath, DataDirPath}, @@ -328,6 +328,13 @@ where >>::Components, >, > + FullEthApiServer + AddDevSigners, + <, + >>::Components, + >, + >>::EthApi as EthApiTypes>::NetworkTypes: + alloy_network::Network, { self.node(node).launch().await } @@ -473,6 +480,8 @@ where AO::EthApi: EthApiBuilderProvider, CB::Components>> + FullEthApiServer + AddDevSigners, + ::NetworkTypes: + alloy_network::Network, { /// Launches the node with the [`DefaultNodeLauncher`] that sets up engine API consensus and rpc pub async fn launch( diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index daef8047223d..165aa9a720d8 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -20,7 +20,7 @@ use reth_node_api::{FullNodeComponents, FullNodeTypes, NodeAddOns}; use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, - rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, + rpc::eth::{helpers::AddDevSigners, EthApiTypes, FullEthApiServer}, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; @@ -104,6 +104,8 @@ where AO: NodeAddOns>, AO::EthApi: EthApiBuilderProvider> + FullEthApiServer + AddDevSigners, + ::NetworkTypes: + alloy_network::Network, { type Node = NodeHandle, AO>; diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index e9349af416d1..4edc3658cb02 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -11,7 +11,7 @@ use reth_node_core::{ node_config::NodeConfig, rpc::{ api::EngineApiServer, - eth::{EthApiTypesCompat, FullEthApiServer}, + eth::{EthApiTypes, FullEthApiServer}, }, }; use reth_payload_builder::PayloadBuilderHandle; @@ -45,13 +45,21 @@ pub struct RpcHooks { pub extend_rpc_modules: Box>, } -impl Default for RpcHooks { +impl Default for RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn default() -> Self { Self { on_rpc_started: Box::<()>::default(), extend_rpc_modules: Box::<()>::default() } } } -impl RpcHooks { +impl RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ /// Sets the hook that is run once the rpc server is started. pub(crate) fn set_on_rpc_started(&mut self, hook: F) -> &mut Self where @@ -91,7 +99,11 @@ impl RpcHooks { } } -impl fmt::Debug for RpcHooks { +impl fmt::Debug for RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RpcHooks") .field("on_rpc_started", &"...") @@ -101,7 +113,7 @@ impl fmt::Debug for RpcHooks { } /// Event hook that is called once the rpc server is started. -pub trait OnRpcStarted: Send { +pub trait OnRpcStarted: Send { /// The hook that is called once the rpc server is started. fn on_rpc_started( self: Box, @@ -114,6 +126,7 @@ impl OnRpcStarted for F where F: FnOnce(RpcContext<'_, Node, EthApi>, RethRpcServerHandles) -> eyre::Result<()> + Send, Node: FullNodeComponents, + EthApi: EthApiTypes, { fn on_rpc_started( self: Box, @@ -124,7 +137,11 @@ where } } -impl OnRpcStarted for () { +impl OnRpcStarted for () +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn on_rpc_started( self: Box, _: RpcContext<'_, Node, EthApi>, @@ -135,7 +152,7 @@ impl OnRpcStarted for () { } /// Event hook that is called when the rpc server is started. -pub trait ExtendRpcModules: Send { +pub trait ExtendRpcModules: Send { /// The hook that is called once the rpc server is started. fn extend_rpc_modules(self: Box, ctx: RpcContext<'_, Node, EthApi>) -> eyre::Result<()>; } @@ -144,13 +161,18 @@ impl ExtendRpcModules for F where F: FnOnce(RpcContext<'_, Node, EthApi>) -> eyre::Result<()> + Send, Node: FullNodeComponents, + EthApi: EthApiTypes, { fn extend_rpc_modules(self: Box, ctx: RpcContext<'_, Node, EthApi>) -> eyre::Result<()> { (*self)(ctx) } } -impl ExtendRpcModules for () { +impl ExtendRpcModules for () +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn extend_rpc_modules(self: Box, _: RpcContext<'_, Node, EthApi>) -> eyre::Result<()> { Ok(()) } @@ -159,7 +181,7 @@ impl ExtendRpcModules for () { /// Helper wrapper type to encapsulate the [`RpcRegistryInner`] over components trait. #[derive(Debug, Clone)] #[allow(clippy::type_complexity)] -pub struct RpcRegistry { +pub struct RpcRegistry { pub(crate) registry: RpcRegistryInner< Node::Provider, Node::Pool, @@ -170,7 +192,11 @@ pub struct RpcRegistry { >, } -impl Deref for RpcRegistry { +impl Deref for RpcRegistry +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ type Target = RpcRegistryInner< Node::Provider, Node::Pool, @@ -185,7 +211,11 @@ impl Deref for RpcRegistry { } } -impl DerefMut for RpcRegistry { +impl DerefMut for RpcRegistry +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.registry } @@ -199,7 +229,7 @@ impl DerefMut for RpcRegistry { /// transport modules [`TransportRpcModules`] as well as configured authenticated methods /// [`AuthRpcModule`]. #[allow(missing_debug_implementations)] -pub struct RpcContext<'a, Node: FullNodeComponents, EthApi> { +pub struct RpcContext<'a, Node: FullNodeComponents, EthApi: EthApiTypes> { /// The node components. pub(crate) node: Node, @@ -221,7 +251,11 @@ pub struct RpcContext<'a, Node: FullNodeComponents, EthApi> { pub auth_module: &'a mut AuthRpcModule, } -impl<'a, Node: FullNodeComponents, EthApi> RpcContext<'a, Node, EthApi> { +impl<'a, Node, EthApi> RpcContext<'a, Node, EthApi> +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ /// Returns the config of the node. pub const fn config(&self) -> &NodeConfig { self.config @@ -262,9 +296,10 @@ pub async fn launch_rpc_servers( add_ons: RpcAddOns, ) -> eyre::Result<(RethRpcServerHandles, RpcRegistry)> where - EthApi: EthApiBuilderProvider + FullEthApiServer, Node: FullNodeComponents + Clone, Engine: EngineApiServer, + EthApi: EthApiBuilderProvider + FullEthApiServer, + EthApi::NetworkTypes: alloy_network::Network, { let auth_config = config.rpc.auth_server_config(jwt_secret)?; let module_config = config.rpc.transport_rpc_module_config(); @@ -336,18 +371,18 @@ where } /// Provides builder for the core `eth` API type. -pub trait EthApiBuilderProvider: BuilderProvider { +pub trait EthApiBuilderProvider: BuilderProvider + EthApiTypes { /// Returns the eth api builder. #[allow(clippy::type_complexity)] - fn eth_api_builder() -> Box) -> Self + Send>; + fn eth_api_builder() -> Box) -> Self + Send>; } -impl EthApiBuilderProvider for F +impl EthApiBuilderProvider for F where N: FullNodeComponents, - for<'a> F: BuilderProvider = &'a EthApiBuilderCtx>, + for<'a> F: BuilderProvider = &'a EthApiBuilderCtx> + EthApiTypes, { - fn eth_api_builder() -> Box) -> Self + Send> { + fn eth_api_builder() -> Box) -> Self + Send> { F::builder() } } diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index d6b5fe1e312b..b6f90c220c69 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -104,7 +104,7 @@ where type NetworkTypes = Optimism; } -impl EthApiTypesCompat for OpEthApi { +impl EthApiTypes for OpEthApi { type TxBuilder = OpTxBuilder; type BlockBuilder = EthBlockBuilder>; } From f24dee58ee2cb9706ba08a620e11d2f0d55cd76a Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 00:03:17 +0200 Subject: [PATCH 24/80] fixup! Flatten trait ResponseTypeBuilders into EthApiTypes --- crates/rpc/rpc-builder/src/eth.rs | 5 +-- crates/rpc/rpc-builder/src/lib.rs | 17 ++++----- crates/rpc/rpc-eth-api/src/core.rs | 35 +++++++++++++------ crates/rpc/rpc-eth-api/src/helpers/block.rs | 23 ++++++------ crates/rpc/rpc-eth-api/src/helpers/mod.rs | 4 +-- .../rpc-eth-api/src/helpers/transaction.rs | 8 ++--- crates/rpc/rpc-eth-api/src/helpers/types.rs | 4 +-- crates/rpc/rpc-eth-api/src/lib.rs | 2 ++ crates/rpc/rpc-testing-util/src/debug.rs | 3 +- crates/rpc/rpc/src/engine.rs | 14 ++++---- crates/rpc/rpc/src/eth/core.rs | 4 +-- crates/rpc/rpc/src/eth/helpers/block.rs | 11 ++---- crates/rpc/rpc/src/eth/helpers/transaction.rs | 5 ++- crates/rpc/rpc/src/otterscan.rs | 5 ++- 14 files changed, 75 insertions(+), 65 deletions(-) diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index b430699d867b..f28148fb2508 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -24,7 +24,7 @@ pub struct EthHandlers { /// Polling based filter handler available on all transports pub filter: EthFilter, /// Handler for subscriptions only available for transports that support it (ws, ipc) - pub pubsub: EthPubSub, + pub pubsub: EthPubSub, } impl EthHandlers @@ -164,13 +164,14 @@ impl EthPubSubApiBuilder { /// Builds the [`EthPubSubApiServer`](reth_rpc_eth_api::EthPubSubApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthPubSub + ) -> EthPubSub where Provider: Clone, Pool: Clone, Events: Clone, Network: Clone, Tasks: TaskSpawner + Clone + 'static, + Eth: EthApiTypes + 'static, { EthPubSub::with_spawner( ctx.provider.clone(), diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 5d74c91b20be..4015458f3f47 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -804,7 +804,8 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypes + EthApiServer, Block>, + EthApi: + EthApiServer, Block> + EthApiTypes, EthApi::NetworkTypes: alloy_network::Network, { /// Register Eth Namespace @@ -812,10 +813,7 @@ where /// # Panics /// /// If called outside of the tokio runtime. See also [`Self::eth_api`] - pub fn register_eth(&mut self) -> &mut Self - where - EthApi: EthApiTypes + EthApiServer, Block>, - { + pub fn register_eth(&mut self) -> &mut Self { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); self @@ -926,10 +924,7 @@ where /// # Panics /// /// If called outside of the tokio runtime. See also [`Self::eth_api`] - pub fn otterscan_api(&self) -> OtterscanApi - where - EthApi: EthApiServer, Block> + EthApiTypes, - { + pub fn otterscan_api(&self) -> OtterscanApi { let eth_api = self.eth_api().clone(); OtterscanApi::new(eth_api) } @@ -1091,7 +1086,9 @@ where .into(), RethRpcModule::Web3 => Web3Api::new(self.network.clone()).into_rpc().into(), RethRpcModule::Txpool => { - TxPoolApi::<_, EthApi>::new(self.pool.clone()).into_rpc().into() + TxPoolApi::<_, EthApi::TransactionBuilder>::new(self.pool.clone()) + .into_rpc() + .into() } RethRpcModule::Rpc => RPCApi::new( namespaces diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 54142ab277af..90f9bb7c7a7b 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -27,12 +27,18 @@ use crate::{ /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. pub trait FullEthApiServer: - EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone + EthApiServer, Block> + + FullEthApi + + UpdateRawTxForwarder + + Clone { } impl FullEthApiServer for T where - T: EthApiServer, Block> + FullEthApi + UpdateRawTxForwarder + Clone + T: EthApiServer, Block> + + FullEthApi + + UpdateRawTxForwarder + + Clone { } @@ -340,7 +346,7 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer, Block> for T +impl EthApiServer, Block> for T where T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, @@ -383,7 +389,11 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>> { + async fn block_by_hash( + &self, + hash: B256, + full: bool, + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); Ok(EthBlocks::rpc_block(self, hash.into(), full).await?) } @@ -393,7 +403,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); Ok(EthBlocks::rpc_block(self, number.into(), full).await?) } @@ -442,7 +452,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?) } @@ -452,7 +462,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?) } @@ -464,11 +474,14 @@ where } /// Handler for: `eth_getTransactionByHash` - async fn transaction_by_hash(&self, hash: B256) -> RpcResult>> { + async fn transaction_by_hash( + &self, + hash: B256, + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash) .await? - .map(|tx| tx.into_transaction::())) + .map(|tx| tx.into_transaction::())) } /// Handler for: `eth_getRawTransactionByBlockHashAndIndex` @@ -487,7 +500,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await?) @@ -513,7 +526,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) .await?) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index d65f86a84d54..86354c656ef8 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,18 +7,15 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionBuilder}; +use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder}; -use crate::{Block, FromEthApiError, Transaction}; +use crate::{Block, FromEthApiError}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; /// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the /// `eth_` namespace. -pub trait EthBlocks: LoadBlock + BlockBuilder -where - Self::TxBuilder: TransactionBuilder>, -{ +pub trait EthBlocks: LoadBlock { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -40,7 +37,7 @@ where &self, block_id: BlockId, full: bool, - ) -> impl Future>, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send { async move { let block = match self.block_with_senders(block_id).await? { Some(block) => block, @@ -51,9 +48,13 @@ where .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = - Self::from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) - .map_err(Self::Error::from_eth_err)?; + let block = Self::BlockBuilder::from_block( + block.unseal(), + total_difficulty, + full.into(), + Some(block_hash), + ) + .map_err(Self::Error::from_eth_err)?; Ok(Some(Rich { inner: block, extra_info: Default::default() })) } } @@ -185,7 +186,7 @@ where &self, block_id: BlockId, index: Index, - ) -> impl Future>, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index a86f44257f3a..ecfd63388e3b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -57,7 +57,7 @@ pub trait FullEthApi: EthApiTypes + EthApiSpec + EthTransactions - + EthBlocks + + EthBlocks + EthState + EthCall + EthFees @@ -70,7 +70,7 @@ impl FullEthApi for T where T: EthApiTypes + EthApiSpec + EthTransactions - + EthBlocks + + EthBlocks + EthState + EthCall + EthFees diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 9a85bfbe0bed..b19c3170e4c0 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -53,9 +53,7 @@ use super::{ /// See also /// /// This implementation follows the behaviour of Geth and disables the basefee check for tracing. -pub trait EthTransactions: - LoadTransaction + TransactionBuilder> -{ +pub trait EthTransactions: LoadTransaction { /// Returns a handle for reading data from disk. /// /// Data access in default (L1) trait method implementations. @@ -197,7 +195,7 @@ pub trait EthTransactions: &self, block_id: BlockId, index: usize, - ) -> impl Future, Self::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, { @@ -207,7 +205,7 @@ pub trait EthTransactions: let block_number = block.number; let base_fee_per_gas = block.base_fee_per_gas; if let Some(tx) = block.into_transactions_ecrecovered().nth(index) { - return Ok(Some(Self::from_recovered_with_block_context( + return Ok(Some(Self::TransactionBuilder::from_recovered_with_block_context( tx, block_hash, block_number, diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 1c5944d03ec8..30dff21ee3cd 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -22,7 +22,7 @@ pub trait EthApiTypes: Send + Sync + Clone { /// Blockchain primitive types, specific to network, e.g. block and transaction. type NetworkTypes: Network; /// Conversion methods for transaction RPC type. - type TransactionBuilder: TransactionBuilder>; + type TransactionBuilder: TransactionBuilder>; /// Conversion methods for block RPC type. type BlockBuilder: BlockBuilder; } @@ -35,7 +35,7 @@ impl EthApiTypes for () { } /// Adapter for network specific transaction type. -pub type Transaction = <::NetworkTypes as Network>::TransactionResponse; +pub type Transaction = ::TransactionResponse; /// Adapter for network specific block type. pub type Block = Rich>>; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 39bfb0d629ea..f71f2d05f7f2 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -18,6 +18,8 @@ pub mod filter; pub mod helpers; pub mod pubsub; +pub use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; + pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; diff --git a/crates/rpc/rpc-testing-util/src/debug.rs b/crates/rpc/rpc-testing-util/src/debug.rs index 58fc1cf916b6..c0151e2d1be2 100644 --- a/crates/rpc/rpc-testing-util/src/debug.rs +++ b/crates/rpc/rpc-testing-util/src/debug.rs @@ -4,7 +4,6 @@ use futures::{Stream, StreamExt}; use jsonrpsee::core::client::Error as RpcError; use reth_primitives::{BlockId, TxHash, B256}; use reth_rpc_api::{clients::DebugApiClient, EthApiClient}; -use reth_rpc_eth_api::{Block, EthApiTypes, Transaction}; use reth_rpc_types::{ trace::{ common::TraceResult, @@ -77,7 +76,7 @@ pub trait DebugApiExt { impl DebugApiExt for T where - T: EthApiClient, Block> + EthApiTypes + DebugApiClient + Sync, + T: EthApiClient + DebugApiClient + Sync, { type Provider = T; diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 3a926d4694a2..f95600f0b6ab 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -36,11 +36,9 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, Block> - + EthApiTypes - + TransactionBuilder, + Eth: EthApiServer, Block> + EthApiTypes, Eth::NetworkTypes: Network, - EthFilter: EthFilterApiServer>, + EthFilter: EthFilterApiServer<::Transaction>, { /// Handler for: `eth_syncing` fn syncing(&self) -> Result { @@ -83,7 +81,11 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> Result>> { + async fn block_by_hash( + &self, + hash: B256, + full: bool, + ) -> Result>> { self.eth.block_by_hash(hash, full).instrument(engine_span!()).await } @@ -92,7 +94,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> Result>> { + ) -> Result>> { self.eth.block_by_number(number, full).instrument(engine_span!()).await } diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 2b3d2578a3e1..824e143832aa 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -577,7 +577,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(1), (newest_block + 1000).into(), @@ -600,7 +600,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(0), newest_block.into(), diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 93b93b789de3..92f8d5e0344d 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -1,23 +1,18 @@ //! Contains RPC handler implementations specific to blocks. use reth_provider::{BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_api::{ - helpers::{EthBlocks, LoadBlock, LoadPendingBlock, SpawnBlocking}, - Transaction, -}; +use reth_rpc_eth_api::helpers::{EthBlocks, LoadBlock, LoadPendingBlock, SpawnBlocking}; use reth_rpc_eth_types::EthStateCache; -use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; use crate::EthApi; impl EthBlocks for EthApi where - Self: LoadBlock + BlockBuilder, - Self::TxBuilder: TransactionBuilder>, + Self: LoadBlock, Provider: HeaderProvider, { #[inline] - fn provider(&self) -> impl reth_provider::HeaderProvider { + fn provider(&self) -> impl HeaderProvider { self.inner.provider() } } diff --git a/crates/rpc/rpc/src/eth/helpers/transaction.rs b/crates/rpc/rpc/src/eth/helpers/transaction.rs index 28330dec7106..635281c08e76 100644 --- a/crates/rpc/rpc/src/eth/helpers/transaction.rs +++ b/crates/rpc/rpc/src/eth/helpers/transaction.rs @@ -5,10 +5,9 @@ use std::sync::Arc; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - RawTransactionForwarder, Transaction, + RawTransactionForwarder, }; use reth_rpc_eth_types::EthStateCache; -use reth_rpc_types_compat::TransactionBuilder; use reth_transaction_pool::TransactionPool; use crate::EthApi; @@ -16,7 +15,7 @@ use crate::EthApi; impl EthTransactions for EthApi where - Self: LoadTransaction + TransactionBuilder>, + Self: LoadTransaction, Pool: TransactionPool + 'static, Provider: BlockReaderIdExt, { diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 39dfc349f5bf..3b13165b091f 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -60,7 +60,10 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer, Block> + EthApiTypes + TraceExt + 'static, + Eth: EthApiServer, Block> + + EthApiTypes + + TraceExt + + 'static, Eth::NetworkTypes: Network, { /// Handler for `{ots,erigon}_getHeaderByNumber` From 34c56e6c5c7139cad95442cd771fb6c80becfa85 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 00:43:37 +0200 Subject: [PATCH 25/80] Fix tests --- Cargo.lock | 4 + crates/e2e-test-utils/Cargo.toml | 2 + crates/e2e-test-utils/src/lib.rs | 7 +- crates/e2e-test-utils/src/node.rs | 5 +- crates/e2e-test-utils/src/rpc.rs | 9 +- crates/rpc/rpc-builder/Cargo.toml | 1 + crates/rpc/rpc-builder/src/lib.rs | 28 ++- crates/rpc/rpc-builder/tests/it/http.rs | 173 +++++++++++++----- crates/rpc/rpc-builder/tests/it/middleware.rs | 3 +- crates/rpc/rpc-testing-util/Cargo.toml | 2 +- crates/rpc/rpc-testing-util/src/debug.rs | 15 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 16 +- 12 files changed, 189 insertions(+), 76 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ca3e5bf83e74..bec52916d9e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6936,6 +6936,7 @@ dependencies = [ "eyre", "futures-util", "jsonrpsee", + "jsonrpsee-types", "reth", "reth-chainspec", "reth-db", @@ -6947,6 +6948,7 @@ dependencies = [ "reth-provider", "reth-rpc", "reth-rpc-layer", + "reth-rpc-types", "reth-stages-types", "reth-tokio-util", "reth-tracing", @@ -8328,6 +8330,7 @@ version = "1.0.3" dependencies = [ "futures", "jsonrpsee", + "jsonrpsee-http-client", "reth-primitives", "reth-rpc-api", "reth-rpc-eth-api", @@ -8370,6 +8373,7 @@ dependencies = [ "reth-rpc-layer", "reth-rpc-server-types", "reth-rpc-types", + "reth-rpc-types-compat", "reth-tasks", "reth-tokio-util", "reth-tracing", diff --git a/crates/e2e-test-utils/Cargo.toml b/crates/e2e-test-utils/Cargo.toml index 7bdbfd885e55..112f5d25509e 100644 --- a/crates/e2e-test-utils/Cargo.toml +++ b/crates/e2e-test-utils/Cargo.toml @@ -25,6 +25,8 @@ reth-tokio-util.workspace = true reth-stages-types.workspace = true reth-network-peers.workspace = true reth-node-ethereum.workspace = true +reth-rpc-types.workspace = true +jsonrpsee-types.workspace = true jsonrpsee.workspace = true diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index 132bc36c1579..994f71f033e7 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use alloy_network::Network; use node::NodeTestContext; use reth::{ args::{DiscoveryArgs, NetworkArgs, RpcServerArgs}, @@ -13,8 +14,8 @@ use reth::{ use reth_chainspec::ChainSpec; use reth_db::{test_utils::TempDatabase, DatabaseEnv}; use reth_node_builder::{ - components::NodeComponentsBuilder, rpc::EthApiBuilderProvider, FullNodeTypesAdapter, Node, - NodeAdapter, NodeAddOns, NodeComponents, RethFullAdapter, + components::NodeComponentsBuilder, rpc::EthApiBuilderProvider, EthApiTypes, + FullNodeTypesAdapter, Node, NodeAdapter, NodeAddOns, NodeComponents, RethFullAdapter, }; use reth_provider::providers::BlockchainProvider; use tracing::{span, Level}; @@ -54,6 +55,8 @@ where <>>::Components as NodeComponents>>::Network: PeersHandleProvider, >>::EthApi: FullEthApiServer + AddDevSigners + EthApiBuilderProvider>, + <>>::EthApi as EthApiTypes>::NetworkTypes: Network, + { let tasks = TaskManager::current(); let exec = tasks.executor(); diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 19f387c7b8b6..681a3bbd176a 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -1,5 +1,6 @@ use std::{marker::PhantomData, pin::Pin}; +use alloy_network::Network; use alloy_rpc_types::BlockNumberOrTag; use eyre::Ok; use futures_util::Future; @@ -14,7 +15,7 @@ use reth::{ types::engine::PayloadStatusEnum, }, }; -use reth_node_builder::{NodeAddOns, NodeTypes}; +use reth_node_builder::{EthApiTypes, NodeAddOns, NodeTypes}; use reth_primitives::{BlockHash, BlockNumber, Bytes, B256}; use reth_stages_types::StageId; use tokio_stream::StreamExt; @@ -92,6 +93,8 @@ where ::ExecutionPayloadV3: From<::BuiltPayload> + PayloadEnvelopeExt, AddOns::EthApi: EthApiSpec + EthTransactions + TraceExt, + ::NetworkTypes: + Network, { let mut chain = Vec::with_capacity(length as usize); for i in 0..length { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index b301889507a9..085e46c00640 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -1,5 +1,5 @@ use alloy_consensus::TxEnvelope; -use alloy_network::eip2718::Decodable2718; +use alloy_network::{eip2718::Decodable2718, Network}; use reth::{ builder::{rpc::RpcRegistry, FullNodeComponents}, rpc::api::{ @@ -7,16 +7,19 @@ use reth::{ DebugApiServer, }, }; +use reth_node_builder::EthApiTypes; use reth_primitives::{Bytes, B256}; #[allow(missing_debug_implementations)] -pub struct RpcTestContext { +pub struct RpcTestContext { pub inner: RpcRegistry, } -impl RpcTestContext +impl RpcTestContext where + Node: FullNodeComponents, EthApi: EthApiSpec + EthTransactions + TraceExt, + EthApi::NetworkTypes: Network, { /// Injects a raw transaction into the node tx pool via RPC server pub async fn inject_tx(&self, raw_tx: Bytes) -> Result { diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index bf5d5c5b0489..74485ee8f32b 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -65,6 +65,7 @@ reth-tracing.workspace = true reth-transaction-pool = { workspace = true, features = ["test-utils"] } reth-tokio-util.workspace = true reth-node-api.workspace = true +reth-rpc-types-compat.workspace = true tokio = { workspace = true, features = ["rt", "rt-multi-thread"] } serde_json.workspace = true diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 4015458f3f47..57a12140b5a5 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -804,8 +804,7 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: - EthApiServer, Block> + EthApiTypes, + EthApi: EthApiTypes, EthApi::NetworkTypes: alloy_network::Network, { /// Register Eth Namespace @@ -813,7 +812,10 @@ where /// # Panics /// /// If called outside of the tokio runtime. See also [`Self::eth_api`] - pub fn register_eth(&mut self) -> &mut Self { + pub fn register_eth(&mut self) -> &mut Self + where + EthApi: EthApiServer, Block>, + { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); self @@ -826,7 +828,8 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: TraceExt, + EthApi: + EthApiServer, Block> + TraceExt, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -840,7 +843,10 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_debug(&mut self) -> &mut Self where - EthApi: EthApiSpec + EthTransactions + TraceExt, + EthApi: EthApiServer, Block> + + EthApiSpec + + EthTransactions + + TraceExt, { let debug_api = self.debug_api(); self.modules.insert(RethRpcModule::Debug, debug_api.into_rpc().into()); @@ -854,7 +860,8 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_trace(&mut self) -> &mut Self where - EthApi: TraceExt, + EthApi: + EthApiServer, Block> + TraceExt, { let trace_api = self.trace_api(); self.modules.insert(RethRpcModule::Trace, trace_api.into_rpc().into()); @@ -870,7 +877,9 @@ where /// If called outside of the tokio runtime. pub fn register_net(&mut self) -> &mut Self where - EthApi: EthApiSpec + 'static, + EthApi: EthApiServer, Block> + + EthApiSpec + + 'static, { let netapi = self.net_api(); self.modules.insert(RethRpcModule::Net, netapi.into_rpc().into()); @@ -884,7 +893,10 @@ where /// # Panics /// /// If called outside of the tokio runtime. - pub fn register_reth(&mut self) -> &mut Self { + pub fn register_reth(&mut self) -> &mut Self + where + EthApi: EthApiServer, Block>, + { let rethapi = self.reth_api(); self.modules.insert(RethRpcModule::Reth, rethapi.into_rpc().into()); self diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index fa4ade38ef68..9aa69a4abd30 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -116,20 +116,21 @@ async fn test_filter_calls(client: &C) where C: ClientT + SubscriptionClientT + Sync, { - EthFilterApiClient::new_filter(client, Filter::default()).await.unwrap(); - EthFilterApiClient::new_pending_transaction_filter(client, None).await.unwrap(); - EthFilterApiClient::new_pending_transaction_filter( + EthFilterApiClient::::new_filter(client, Filter::default()).await.unwrap(); + EthFilterApiClient::::new_pending_transaction_filter(client, None).await.unwrap(); + EthFilterApiClient::::new_pending_transaction_filter( client, Some(PendingTransactionFilterKind::Full), ) .await .unwrap(); - let id = EthFilterApiClient::new_block_filter(client).await.unwrap(); - EthFilterApiClient::filter_changes(client, id.clone()).await.unwrap(); - EthFilterApiClient::logs(client, Filter::default()).await.unwrap(); - let id = EthFilterApiClient::new_filter(client, Filter::default()).await.unwrap(); - EthFilterApiClient::filter_logs(client, id.clone()).await.unwrap(); - EthFilterApiClient::uninstall_filter(client, id).await.unwrap(); + let id = EthFilterApiClient::::new_block_filter(client).await.unwrap(); + EthFilterApiClient::::filter_changes(client, id.clone()).await.unwrap(); + EthFilterApiClient::::logs(client, Filter::default()).await.unwrap(); + let id = + EthFilterApiClient::::new_filter(client, Filter::default()).await.unwrap(); + EthFilterApiClient::::filter_logs(client, id.clone()).await.unwrap(); + EthFilterApiClient::::uninstall_filter(client, id).await.unwrap(); } async fn test_basic_admin_calls(client: &C) @@ -172,59 +173,133 @@ where .unwrap(); // Implemented - EthApiClient::protocol_version(client).await.unwrap(); - EthApiClient::chain_id(client).await.unwrap(); - EthApiClient::accounts(client).await.unwrap(); - EthApiClient::block_number(client).await.unwrap(); - EthApiClient::get_code(client, address, None).await.unwrap(); - EthApiClient::send_raw_transaction(client, tx).await.unwrap(); - EthApiClient::fee_history(client, U64::from(0), block_number, None).await.unwrap(); - EthApiClient::balance(client, address, None).await.unwrap(); - EthApiClient::transaction_count(client, address, None).await.unwrap(); - EthApiClient::storage_at(client, address, U256::default().into(), None).await.unwrap(); - EthApiClient::block_by_hash(client, hash, false).await.unwrap(); - EthApiClient::block_by_number(client, block_number, false).await.unwrap(); - EthApiClient::block_transaction_count_by_number(client, block_number).await.unwrap(); - EthApiClient::block_transaction_count_by_hash(client, hash).await.unwrap(); - EthApiClient::block_uncles_count_by_hash(client, hash).await.unwrap(); - EthApiClient::block_uncles_count_by_number(client, block_number).await.unwrap(); - EthApiClient::uncle_by_block_hash_and_index(client, hash, index).await.unwrap(); - EthApiClient::uncle_by_block_number_and_index(client, block_number, index).await.unwrap(); - EthApiClient::sign(client, address, bytes.clone()).await.unwrap_err(); - EthApiClient::sign_typed_data(client, address, typed_data).await.unwrap_err(); - EthApiClient::transaction_by_hash(client, tx_hash).await.unwrap(); - EthApiClient::transaction_by_block_hash_and_index(client, hash, index).await.unwrap(); - EthApiClient::transaction_by_block_number_and_index(client, block_number, index).await.unwrap(); - EthApiClient::create_access_list(client, call_request.clone(), Some(block_number.into())) + EthApiClient::::protocol_version(client).await.unwrap(); + EthApiClient::::chain_id(client).await.unwrap(); + EthApiClient::::accounts(client).await.unwrap(); + EthApiClient::::block_number(client).await.unwrap(); + EthApiClient::::get_code(client, address, None).await.unwrap(); + EthApiClient::::send_raw_transaction(client, tx).await.unwrap(); + EthApiClient::::fee_history(client, U64::from(0), block_number, None) .await .unwrap(); - EthApiClient::estimate_gas(client, call_request.clone(), Some(block_number.into()), None) + EthApiClient::::balance(client, address, None).await.unwrap(); + EthApiClient::::transaction_count(client, address, None).await.unwrap(); + EthApiClient::::storage_at( + client, + address, + U256::default().into(), + None, + ) + .await + .unwrap(); + EthApiClient::::block_by_hash(client, hash, false).await.unwrap(); + EthApiClient::::block_by_number(client, block_number, false) + .await + .unwrap(); + EthApiClient::::block_transaction_count_by_number(client, block_number) + .await + .unwrap(); + EthApiClient::::block_transaction_count_by_hash(client, hash) + .await + .unwrap(); + EthApiClient::::block_uncles_count_by_hash(client, hash).await.unwrap(); + EthApiClient::::block_uncles_count_by_number(client, block_number) .await .unwrap(); - EthApiClient::call(client, call_request.clone(), Some(block_number.into()), None, None) + EthApiClient::::uncle_by_block_hash_and_index(client, hash, index) .await .unwrap(); - EthApiClient::syncing(client).await.unwrap(); - EthApiClient::send_transaction(client, transaction_request).await.unwrap_err(); - EthApiClient::hashrate(client).await.unwrap(); - EthApiClient::submit_hashrate(client, U256::default(), B256::default()).await.unwrap(); - EthApiClient::gas_price(client).await.unwrap_err(); - EthApiClient::max_priority_fee_per_gas(client).await.unwrap_err(); - EthApiClient::get_proof(client, address, vec![], None).await.unwrap(); + EthApiClient::::uncle_by_block_number_and_index( + client, + block_number, + index, + ) + .await + .unwrap(); + EthApiClient::::sign(client, address, bytes.clone()).await.unwrap_err(); + EthApiClient::::sign_typed_data(client, address, typed_data) + .await + .unwrap_err(); + EthApiClient::::transaction_by_hash(client, tx_hash).await.unwrap(); + EthApiClient::::transaction_by_block_hash_and_index( + client, hash, index, + ) + .await + .unwrap(); + EthApiClient::::transaction_by_block_number_and_index( + client, + block_number, + index, + ) + .await + .unwrap(); + EthApiClient::::create_access_list( + client, + call_request.clone(), + Some(block_number.into()), + ) + .await + .unwrap(); + EthApiClient::::estimate_gas( + client, + call_request.clone(), + Some(block_number.into()), + None, + ) + .await + .unwrap(); + EthApiClient::::call( + client, + call_request.clone(), + Some(block_number.into()), + None, + None, + ) + .await + .unwrap(); + EthApiClient::::syncing(client).await.unwrap(); + EthApiClient::::send_transaction(client, transaction_request) + .await + .unwrap_err(); + EthApiClient::::hashrate(client).await.unwrap(); + EthApiClient::::submit_hashrate( + client, + U256::default(), + B256::default(), + ) + .await + .unwrap(); + EthApiClient::::gas_price(client).await.unwrap_err(); + EthApiClient::::max_priority_fee_per_gas(client).await.unwrap_err(); + EthApiClient::::get_proof(client, address, vec![], None).await.unwrap(); // Unimplemented - assert!(is_unimplemented(EthApiClient::author(client).await.err().unwrap())); - assert!(is_unimplemented(EthApiClient::is_mining(client).await.err().unwrap())); - assert!(is_unimplemented(EthApiClient::get_work(client).await.err().unwrap())); assert!(is_unimplemented( - EthApiClient::submit_work(client, B64::default(), B256::default(), B256::default()) + EthApiClient::::author(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::is_mining(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::get_work(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::submit_work( + client, + B64::default(), + B256::default(), + B256::default() + ) + .await + .err() + .unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::sign_transaction(client, call_request.clone()) .await .err() .unwrap() )); - assert!(is_unimplemented( - EthApiClient::sign_transaction(client, call_request.clone()).await.err().unwrap() - )); } async fn test_basic_debug_calls(client: &C) diff --git a/crates/rpc/rpc-builder/tests/it/middleware.rs b/crates/rpc/rpc-builder/tests/it/middleware.rs index 59cc86d4dc86..6641157e9f35 100644 --- a/crates/rpc/rpc-builder/tests/it/middleware.rs +++ b/crates/rpc/rpc-builder/tests/it/middleware.rs @@ -8,6 +8,7 @@ use reth_rpc::EthApi; use reth_rpc_builder::{RpcServerConfig, TransportRpcModuleConfig}; use reth_rpc_eth_api::EthApiClient; use reth_rpc_server_types::RpcModuleSelection; +use reth_rpc_types::{RichBlock, Transaction}; use std::{ future::Future, pin::Pin, @@ -74,7 +75,7 @@ async fn test_rpc_middleware() { .unwrap(); let client = handle.http_client().unwrap(); - EthApiClient::protocol_version(&client).await.unwrap(); + EthApiClient::::protocol_version(&client).await.unwrap(); let count = mylayer.count.load(Ordering::Relaxed); assert_eq!(count, 1); } diff --git a/crates/rpc/rpc-testing-util/Cargo.toml b/crates/rpc/rpc-testing-util/Cargo.toml index 79edce652709..19cef0b02de8 100644 --- a/crates/rpc/rpc-testing-util/Cargo.toml +++ b/crates/rpc/rpc-testing-util/Cargo.toml @@ -16,7 +16,6 @@ workspace = true reth-primitives.workspace = true reth-rpc-types.workspace = true reth-rpc-api = { workspace = true, features = ["client"] } -reth-rpc-eth-api.workspace = true # async futures.workspace = true @@ -31,3 +30,4 @@ similar-asserts.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["rt-multi-thread", "macros", "rt"] } reth-rpc-eth-api.workspace = true +jsonrpsee-http-client.workspace = true diff --git a/crates/rpc/rpc-testing-util/src/debug.rs b/crates/rpc/rpc-testing-util/src/debug.rs index c0151e2d1be2..532e9555f8ba 100644 --- a/crates/rpc/rpc-testing-util/src/debug.rs +++ b/crates/rpc/rpc-testing-util/src/debug.rs @@ -1,5 +1,11 @@ //! Helpers for testing debug trace calls. +use std::{ + future::Future, + pin::Pin, + task::{Context, Poll}, +}; + use futures::{Stream, StreamExt}; use jsonrpsee::core::client::Error as RpcError; use reth_primitives::{BlockId, TxHash, B256}; @@ -9,12 +15,7 @@ use reth_rpc_types::{ common::TraceResult, geth::{GethDebugTracerType, GethDebugTracingOptions, GethTrace}, }, - TransactionRequest, -}; -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, + RichBlock, Transaction, TransactionRequest, }; const NOOP_TRACER: &str = include_str!("../assets/noop-tracer.js"); @@ -76,7 +77,7 @@ pub trait DebugApiExt { impl DebugApiExt for T where - T: EthApiClient + DebugApiClient + Sync, + T: EthApiClient + DebugApiClient + Sync, { type Provider = T; diff --git a/crates/rpc/rpc-testing-util/tests/it/trace.rs b/crates/rpc/rpc-testing-util/tests/it/trace.rs index 029e9fbbc8b5..4d1234e1ae26 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -1,11 +1,14 @@ +use std::{collections::HashSet, time::Instant}; + use futures::StreamExt; use jsonrpsee::http_client::HttpClientBuilder; +use jsonrpsee_http_client::HttpClient; use reth_rpc_api_testing_util::{debug::DebugApiExt, trace::TraceApiExt, utils::parse_env_url}; use reth_rpc_eth_api::EthApiClient; -use reth_rpc_types::trace::{ - filter::TraceFilter, parity::TraceType, tracerequest::TraceCallRequest, +use reth_rpc_types::{ + trace::{filter::TraceFilter, parity::TraceType, tracerequest::TraceCallRequest}, + RichBlock, Transaction, }; -use std::{collections::HashSet, time::Instant}; /// This is intended to be run locally against a running node. /// @@ -106,7 +109,12 @@ async fn debug_trace_block_entire_chain() { let url = url.unwrap(); let client = HttpClientBuilder::default().build(url).unwrap(); - let current_block: u64 = client.block_number().await.unwrap().try_into().unwrap(); + let current_block: u64 = + >::block_number(&client) + .await + .unwrap() + .try_into() + .unwrap(); let range = 0..=current_block; let mut stream = client.debug_trace_block_buffered_unordered(range, None, 20); let now = Instant::now(); From fe0297f7419207cc3e4fc87a591977c234586a77 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 01:14:44 +0200 Subject: [PATCH 26/80] Fix optimism crates --- crates/optimism/node/src/node.rs | 3 +- crates/optimism/rpc/Cargo.toml | 2 +- crates/optimism/rpc/src/eth/block.rs | 4 +- crates/optimism/rpc/src/eth/call.rs | 4 +- crates/optimism/rpc/src/eth/mod.rs | 64 ++++++++++---------- crates/optimism/rpc/src/eth/pending_block.rs | 2 +- crates/optimism/rpc/src/eth/receipt.rs | 2 +- crates/optimism/rpc/src/eth/transaction.rs | 25 ++++---- 8 files changed, 55 insertions(+), 51 deletions(-) diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 9fc1f9b85a03..4b30940c6e39 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -19,6 +19,7 @@ use reth_optimism_consensus::OptimismBeaconConsensus; use reth_optimism_rpc::OpEthApi; use reth_payload_builder::{PayloadBuilderHandle, PayloadBuilderService}; use reth_provider::CanonStateSubscriptions; +use reth_rpc::eth::EthTxBuilder; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::{ blobstore::DiskFileBlobStore, CoinbaseTipOrdering, TransactionPool, @@ -107,7 +108,7 @@ impl NodeTypes for OptimismNode { pub struct OptimismAddOns; impl NodeAddOns for OptimismAddOns { - type EthApi = OpEthApi; + type EthApi = OpEthApi; } /// A regular optimism evm and executor builder. diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 3c360fdd76d3..453674543416 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -63,5 +63,5 @@ optimism = [ "reth-primitives/optimism", "reth-provider/optimism", "reth-rpc-eth-api/optimism", - "revm/optimism" + "revm/optimism", ] \ No newline at end of file diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index c7a7b45ab4ab..19cd8eb265ac 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -15,7 +15,7 @@ use reth_rpc_types::{AnyTransactionReceipt, BlockId}; use crate::{op_receipt_fields, OpEthApi, OpEthApiError}; -impl EthBlocks for OpEthApi +impl EthBlocks for OpEthApi where Self: LoadBlock + EthApiSpec + LoadTransaction, Self::Error: From, @@ -76,7 +76,7 @@ where } } -impl LoadBlock for OpEthApi +impl LoadBlock for OpEthApi where Self: LoadPendingBlock + SpawnBlocking, N: FullNodeComponents, diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index 3f25b0182a47..45d97f7dfa75 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -13,14 +13,14 @@ use reth_rpc_types::TransactionRequest; use crate::{OpEthApi, OpEthApiError}; -impl EthCall for OpEthApi +impl EthCall for OpEthApi where Self: Call, N: FullNodeComponents, { } -impl Call for OpEthApi +impl Call for OpEthApi where Self: LoadState + SpawnBlocking, Self::Error: From, diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index b6f90c220c69..9a0f14672c4b 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -7,15 +7,11 @@ mod block; mod call; mod pending_block; -use std::{fmt, sync::Arc}; +use std::{fmt, marker::PhantomData, sync::Arc}; -use alloy_network::Network; -use alloy_primitives::{Address, U256, U64}; -use alloy_rpc_types::optimism::OptimismTransactionFields; +use alloy_primitives::U256; use derive_more::Deref; -use op_alloy_network::Optimism; -use reth_chainspec::{ChainInfo, ChainSpec}; -use reth_errors::RethResult; +use op_alloy_network::{Network, Optimism}; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; use reth_node_api::{BuilderProvider, FullNodeComponents, FullNodeTypes}; @@ -24,7 +20,7 @@ use reth_provider::{ BlockIdReader, BlockNumReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider, StateProviderFactory, }; -use reth_rpc::eth::{core::EthApiInner, DevSigner}; +use reth_rpc::eth::{core::EthApiInner, DevSigner, EthBlockBuilder}; use reth_rpc_eth_api::{ helpers::{ AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadBlock, LoadFee, LoadState, @@ -32,16 +28,15 @@ use reth_rpc_eth_api::{ }, EthApiTypes, }; -use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle, Transaction}; -use reth_rpc_types::SyncStatus; +use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle}; use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, - TaskExecutor, TaskSpawner, + TaskSpawner, }; use reth_transaction_pool::TransactionPool; -use crate::OpEthApiError; +use crate::{OpEthApiError, OpTxBuilder}; /// Adapter for [`EthApiInner`], which holds all the data required to serve core `eth_` API. pub type EthApiNodeBackend = EthApiInner< @@ -62,16 +57,17 @@ pub type EthApiNodeBackend = EthApiInner< /// This type implements the [`FullEthApi`](reth_rpc_eth_api::helpers::FullEthApi) by implemented /// all the `Eth` helper traits and prerequisite traits. #[derive(Clone, Deref)] -pub struct OpEthApi { +pub struct OpEthApi { + #[deref] inner: Arc>, /// L1 RPC type builders. _eth_ty_builders: PhantomData, } -impl OpEthApi { +impl OpEthApi { /// Creates a new instance for given context. #[allow(clippy::type_complexity)] - pub fn with_spawner(ctx: &EthApiBuilderCtx) -> Self { + pub fn with_spawner(ctx: &EthApiBuilderCtx) -> Self { let blocking_task_pool = BlockingTaskPool::build().expect("failed to build blocking task pool"); @@ -91,26 +87,26 @@ impl OpEthApi { ctx.config.proof_permits, ); - Self { _eth_ty_builders: PhantomData, inner: Arc::new(inner) } + Self { inner: Arc::new(inner), _eth_ty_builders: PhantomData } } } -impl EthApiTypes for OpEthApi +impl EthApiTypes for OpEthApi where Self: Send + Sync, N: FullNodeComponents, + // todo: replace constraint when op and l1 don't use same tx type in alloy + Eth: TransactionBuilder::TransactionResponse>, { type Error = OpEthApiError; type NetworkTypes = Optimism; -} - -impl EthApiTypes for OpEthApi { - type TxBuilder = OpTxBuilder; + type TransactionBuilder = OpTxBuilder; type BlockBuilder = EthBlockBuilder>; } -impl EthApiSpec for OpEthApi +impl EthApiSpec for OpEthApi where + Self: Send + Sync, N: FullNodeComponents, { #[inline] @@ -134,10 +130,11 @@ where } } -impl SpawnBlocking for OpEthApi +impl SpawnBlocking for OpEthApi where Self: Send + Sync + Clone + 'static, N: FullNodeComponents, + Eth: TransactionBuilder::TransactionResponse>, { #[inline] fn io_task_spawner(&self) -> impl TaskSpawner { @@ -155,7 +152,7 @@ where } } -impl LoadFee for OpEthApi +impl LoadFee for OpEthApi where Self: LoadBlock, N: FullNodeComponents, @@ -181,10 +178,11 @@ where } } -impl LoadState for OpEthApi +impl LoadState for OpEthApi where Self: Send + Sync, N: FullNodeComponents, + Eth: TransactionBuilder::TransactionResponse>, { #[inline] fn provider(&self) -> impl StateProviderFactory + ChainSpecProvider { @@ -202,7 +200,7 @@ where } } -impl EthState for OpEthApi +impl EthState for OpEthApi where Self: LoadState + SpawnBlocking, N: FullNodeComponents, @@ -213,14 +211,14 @@ where } } -impl EthFees for OpEthApi +impl EthFees for OpEthApi where Self: LoadFee, N: FullNodeComponents, { } -impl Trace for OpEthApi +impl Trace for OpEthApi where Self: LoadState, N: FullNodeComponents, @@ -231,24 +229,26 @@ where } } -impl AddDevSigners for OpEthApi { +impl AddDevSigners for OpEthApi { fn with_dev_accounts(&self) { *self.signers().write() = DevSigner::random_signers(20) } } -impl BuilderProvider for OpEthApi +impl BuilderProvider for OpEthApi where + Self: Send, N: FullNodeComponents, + Eth: TransactionBuilder::TransactionResponse> + 'static, { - type Ctx<'a> = &'a EthApiBuilderCtx; + type Ctx<'a> = &'a EthApiBuilderCtx; fn builder() -> Box Fn(Self::Ctx<'a>) -> Self + Send> { Box::new(|ctx| Self::with_spawner(ctx)) } } -impl fmt::Debug for OpEthApi { +impl fmt::Debug for OpEthApi { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OpEthApi").finish_non_exhaustive() } diff --git a/crates/optimism/rpc/src/eth/pending_block.rs b/crates/optimism/rpc/src/eth/pending_block.rs index c64c83cc0618..94bc62572115 100644 --- a/crates/optimism/rpc/src/eth/pending_block.rs +++ b/crates/optimism/rpc/src/eth/pending_block.rs @@ -12,7 +12,7 @@ use reth_transaction_pool::TransactionPool; use crate::OpEthApi; -impl LoadPendingBlock for OpEthApi +impl LoadPendingBlock for OpEthApi where Self: SpawnBlocking, N: FullNodeComponents, diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index 5aa1b172acec..560aa86cd75a 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -11,7 +11,7 @@ use reth_rpc_types::{AnyTransactionReceipt, OptimismTransactionReceiptFields}; use crate::{OpEthApi, OpEthApiError, OptimismTxMeta}; -impl LoadReceipt for OpEthApi +impl LoadReceipt for OpEthApi where Self: EthApiSpec + LoadTransaction, Self::Error: From, diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index e821a571ad15..81536d29c402 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -2,21 +2,22 @@ use std::{marker::PhantomData, sync::Arc}; -use op_alloy_network::Optimism; +use alloy_rpc_types::optimism::OptimismTransactionFields; +use op_alloy_network::{Network, Optimism}; use reth_evm_optimism::RethL1BlockInfo; use reth_node_api::FullNodeComponents; -use reth_primitives::TransactionSigned; +use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, B256}; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, RawTransactionForwarder, + EthApiTypes, RawTransactionForwarder, TransactionBuilder, }; use reth_rpc_eth_types::EthStateCache; use revm::L1BlockInfo; use crate::{OpEthApi, OpEthApiError}; -impl EthTransactions for OpEthApi +impl EthTransactions for OpEthApi where Self: LoadTransaction, N: FullNodeComponents, @@ -34,7 +35,7 @@ where } } -impl LoadTransaction for OpEthApi +impl LoadTransaction for OpEthApi where Self: SpawnBlocking, N: FullNodeComponents, @@ -76,7 +77,7 @@ impl OptimismTxMeta { } } -impl OpEthApi +impl OpEthApi where Self: EthApiSpec + LoadTransaction, ::Error: From, @@ -115,25 +116,27 @@ where } } +/// Builds OP transaction response type. #[derive(Debug, Clone, Copy)] pub struct OpTxBuilder { _l1_builders: PhantomData, } -impl> TransactionBuilder - for OpTxBuilder +impl::TransactionResponse>> + TransactionBuilder for OpTxBuilder { - type Transaction = Optimism::TransactionResponse; + type Transaction = ::TransactionResponse; fn fill( - &self, tx: TransactionSignedEcRecovered, block_hash: Option, block_number: Option, base_fee: Option, transaction_index: Option, ) -> Self::Transaction { - let mut resp = Eth::fill(self, tx, block_hash, block_number, base_fee, transaction_index); + let signed_tx = tx.clone().into_signed(); + + let mut resp = Eth::fill(tx, block_hash, block_number, base_fee, transaction_index); resp.other = OptimismTransactionFields { source_hash: signed_tx.source_hash(), From f7c7206b0f2690358e518ec5d444e2ada8885096 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 01:29:10 +0200 Subject: [PATCH 27/80] Set explicit Ethereum network for reth_e2e_test_utils::TransactionTestContext --- Cargo.lock | 1 + crates/e2e-test-utils/Cargo.toml | 4 +++- crates/e2e-test-utils/src/transaction.rs | 24 +++++++++++++++--------- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bec52916d9e2..8e977c9bf46e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6949,6 +6949,7 @@ dependencies = [ "reth-rpc", "reth-rpc-layer", "reth-rpc-types", + "reth-rpc-types-compat", "reth-stages-types", "reth-tokio-util", "reth-tracing", diff --git a/crates/e2e-test-utils/Cargo.toml b/crates/e2e-test-utils/Cargo.toml index 112f5d25509e..1111d44d7067 100644 --- a/crates/e2e-test-utils/Cargo.toml +++ b/crates/e2e-test-utils/Cargo.toml @@ -26,8 +26,10 @@ reth-stages-types.workspace = true reth-network-peers.workspace = true reth-node-ethereum.workspace = true reth-rpc-types.workspace = true -jsonrpsee-types.workspace = true +reth-rpc-types-compat.workspace = true +# rpc +jsonrpsee-types.workspace = true jsonrpsee.workspace = true futures-util.workspace = true diff --git a/crates/e2e-test-utils/src/transaction.rs b/crates/e2e-test-utils/src/transaction.rs index e2c6a019b3ac..736e11f0a19c 100644 --- a/crates/e2e-test-utils/src/transaction.rs +++ b/crates/e2e-test-utils/src/transaction.rs @@ -2,13 +2,11 @@ use alloy_consensus::{ BlobTransactionSidecar, EnvKzgSettings, SidecarBuilder, SimpleCoder, TxEip4844Variant, TxEnvelope, }; -use alloy_network::{eip2718::Encodable2718, EthereumWallet, TransactionBuilder}; +use alloy_network::{eip2718::Encodable2718, Ethereum, EthereumWallet, TransactionBuilder}; use alloy_rpc_types::{TransactionInput, TransactionRequest}; use alloy_signer_local::PrivateKeySigner; use eyre::Ok; -use reth_primitives::{hex, Address, Bytes, U256}; - -use reth_primitives::B256; +use reth_primitives::{hex, Address, Bytes, TxKind, B256, U256}; /// Helper for transaction operations #[derive(Debug)] @@ -38,8 +36,10 @@ impl TransactionTestContext { builder.ingest(b"dummy blob"); let sidecar: BlobTransactionSidecar = builder.build()?; - tx.set_blob_sidecar(sidecar); - tx.set_max_fee_per_blob_gas(15e9 as u128); + >::set_blob_sidecar( + &mut tx, sidecar, + ); + >::set_max_fee_per_blob_gas(&mut tx, 15e9 as u128); let signed = Self::sign_tx(wallet, tx).await; Ok(signed) @@ -48,7 +48,9 @@ impl TransactionTestContext { /// Signs an arbitrary [`TransactionRequest`] using the provided wallet pub async fn sign_tx(wallet: PrivateKeySigner, tx: TransactionRequest) -> TxEnvelope { let signer = EthereumWallet::from(wallet); - tx.build(&signer).await.unwrap() + >::build(tx, &signer) + .await + .unwrap() } /// Creates a tx with blob sidecar and sign it, returning bytes @@ -70,7 +72,11 @@ impl TransactionTestContext { let l1_block_info = Bytes::from_static(&hex!("7ef9015aa044bae9d41b8380d781187b426c6fe43df5fb2fb57bd4466ef6a701e1f01e015694deaddeaddeaddeaddeaddeaddeaddeaddead000194420000000000000000000000000000000000001580808408f0d18001b90104015d8eb900000000000000000000000000000000000000000000000000000000008057650000000000000000000000000000000000000000000000000000000063d96d10000000000000000000000000000000000000000000000000000000000009f35273d89754a1e0387b89520d989d3be9c37c1f32495a88faf1ea05c61121ab0d1900000000000000000000000000000000000000000000000000000000000000010000000000000000000000002d679b567db6187c0c8323fa982cfb88b74dbcc7000000000000000000000000000000000000000000000000000000000000083400000000000000000000000000000000000000000000000000000000000f4240")); let tx = tx(chain_id, Some(l1_block_info), nonce); let signer = EthereumWallet::from(wallet); - tx.build(&signer).await.unwrap().encoded_2718().into() + >::build(tx, &signer) + .await + .unwrap() + .encoded_2718() + .into() } /// Validates the sidecar of a given tx envelope and returns the versioned hashes @@ -95,7 +101,7 @@ fn tx(chain_id: u64, data: Option, nonce: u64) -> TransactionRequest { TransactionRequest { nonce: Some(nonce), value: Some(U256::from(100)), - to: Some(reth_primitives::TxKind::Call(Address::random())), + to: Some(TxKind::Call(Address::random())), gas: Some(210000), max_fee_per_gas: Some(20e9 as u128), max_priority_fee_per_gas: Some(20e9 as u128), From 75ff7da85c67e65105cc9aea4497d338591ac878 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 01:31:33 +0200 Subject: [PATCH 28/80] Fix docs --- crates/e2e-test-utils/src/transaction.rs | 11 +++++------ crates/rpc/rpc-eth-api/src/helpers/types.rs | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/e2e-test-utils/src/transaction.rs b/crates/e2e-test-utils/src/transaction.rs index 736e11f0a19c..041ba40d6eb2 100644 --- a/crates/e2e-test-utils/src/transaction.rs +++ b/crates/e2e-test-utils/src/transaction.rs @@ -36,10 +36,11 @@ impl TransactionTestContext { builder.ingest(b"dummy blob"); let sidecar: BlobTransactionSidecar = builder.build()?; - >::set_blob_sidecar( - &mut tx, sidecar, + >::set_blob_sidecar(&mut tx, sidecar); + >::set_max_fee_per_blob_gas( + &mut tx, + 15e9 as u128, ); - >::set_max_fee_per_blob_gas(&mut tx, 15e9 as u128); let signed = Self::sign_tx(wallet, tx).await; Ok(signed) @@ -48,9 +49,7 @@ impl TransactionTestContext { /// Signs an arbitrary [`TransactionRequest`] using the provided wallet pub async fn sign_tx(wallet: PrivateKeySigner, tx: TransactionRequest) -> TxEnvelope { let signer = EthereumWallet::from(wallet); - >::build(tx, &signer) - .await - .unwrap() + >::build(tx, &signer).await.unwrap() } /// Creates a tx with blob sidecar and sign it, returning bytes diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 30dff21ee3cd..56434f4e0ed1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -11,7 +11,7 @@ use crate::{AsEthApiError, FromEthApiError, FromEvmError}; /// Network specific `eth` API types. pub trait EthApiTypes: Send + Sync + Clone { - /// Extension of [`EthApiError`](reth_rpc_eth_types::EthApiError), with network specific errors. + /// Extension of [`EthApiError`], with network specific errors. type Error: Into> + FromEthApiError + AsEthApiError From 43f6808a47f811f087131ceec79f25ce8bc85c35 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 16:14:18 +0200 Subject: [PATCH 29/80] Remove redundant autotrait impls for EthApi --- crates/rpc/rpc/src/eth/core.rs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 824e143832aa..498061658b92 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -40,15 +40,6 @@ pub struct EthApi { pub(super) inner: Arc>, } -unsafe impl Send - for EthApi -{ -} -unsafe impl Sync - for EthApi -{ -} - impl Clone for EthApi { fn clone(&self) -> Self { Self { inner: self.inner.clone() } From 57995debbbd3d1489481cc6c7b4808bceba58127 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 16:19:54 +0200 Subject: [PATCH 30/80] Remove redundant attribute --- crates/rpc/rpc/src/eth/core.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 498061658b92..45932e07164c 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -36,7 +36,6 @@ use crate::eth::{EthBlockBuilder, EthTxBuilder}; #[derive(Deref)] pub struct EthApi { /// All nested fields bundled together. - #[deref] pub(super) inner: Arc>, } From b62ec379e2f12d5d8cd42b6f3f796d5b1f756093 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sat, 3 Aug 2024 16:20:29 +0200 Subject: [PATCH 31/80] Make generic naming unfiorm --- crates/optimism/rpc/src/eth/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 74b1b407698b..23e963aeef82 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -57,11 +57,11 @@ pub type EthApiNodeBackend = EthApiInner< /// This type implements the [`FullEthApi`](reth_rpc_eth_api::helpers::FullEthApi) by implemented /// all the `Eth` helper traits and prerequisite traits. #[derive(Clone, Deref)] -pub struct OpEthApi { +pub struct OpEthApi { #[deref] inner: Arc>, /// L1 RPC type builders. - _eth_ty_builders: PhantomData, + _eth_ty_builders: PhantomData, } impl OpEthApi { From 1b8197f655b9e43df4c0a51fe627714b65bdda0e Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 15 Aug 2024 10:59:16 -0700 Subject: [PATCH 32/80] Remove trait bound TransactionBuilder on EthApiTypes::TransationBuilder --- Cargo.lock | 1 + crates/node/builder/Cargo.toml | 1 + crates/node/builder/src/launch/engine.rs | 27 ++++++------------ crates/node/builder/src/rpc.rs | 8 ++++-- crates/rpc/rpc-builder/src/lib.rs | 27 +++++++++++------- crates/rpc/rpc-eth-api/src/core.rs | 2 ++ crates/rpc/rpc-eth-api/src/helpers/block.rs | 14 +++++++--- .../rpc-eth-api/src/helpers/transaction.rs | 1 + crates/rpc/rpc-eth-api/src/helpers/types.rs | 6 ++-- crates/rpc/rpc/src/engine.rs | 1 + crates/rpc/rpc/src/eth/filter.rs | 28 +++++++++---------- 11 files changed, 65 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 80fafb545bf5..defcd75e1a84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7729,6 +7729,7 @@ dependencies = [ "reth-rpc-eth-types", "reth-rpc-layer", "reth-rpc-types", + "reth-rpc-types-compat", "reth-stages", "reth-static-file", "reth-tasks", diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index febdcee21310..fa77f2d3c171 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -54,6 +54,7 @@ reth-payload-validator.workspace = true reth-engine-service.workspace = true reth-tokio-util.workspace = true reth-engine-tree.workspace = true +reth-rpc-types-compat.workspace = true ## ethereum alloy-network.workspace = true diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index aaf769dfd0eb..d320b01617ef 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -1,14 +1,5 @@ //! Engine node related functionality. -use crate::{ - components::NodeComponents, - hooks::NodeHooks, - launch::{LaunchContext, LaunchNode}, - rpc::{launch_rpc_servers, EthApiBuilderProvider}, - setup::build_networked_pipeline, - AddOns, ExExLauncher, FullNode, NodeAdapter, NodeBuilderWithComponents, NodeComponentsBuilder, - NodeHandle, NodeTypesAdapter, -}; use futures::{future::Either, stream, stream_select, StreamExt}; use reth_beacon_consensus::{ hooks::{EngineHooks, StaticFileHook}, @@ -22,17 +13,9 @@ use reth_engine_tree::{ }; use reth_engine_util::EngineMessageStreamExt; use reth_exex::ExExManagerHandle; -use reth_network::{ - BlockDownloaderProvider, NetworkEventListenerProvider, NetworkSyncUpdater, SyncState, -}; +use reth_network::{NetworkSyncUpdater, SyncState}; use reth_network_api::{BlockDownloaderProvider, NetworkEventListenerProvider}; use reth_node_api::{BuiltPayload, EthApiTypes, FullNodeTypes, NodeAddOns}; -use reth_node_builder::{ - hooks::NodeHooks, - rpc::{launch_rpc_servers, EthApiBuilderProvider}, - AddOns, ExExLauncher, FullNode, LaunchContext, LaunchNode, NodeAdapter, - NodeBuilderWithComponents, NodeComponents, NodeComponentsBuilder, NodeHandle, NodeTypesAdapter, -}; use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, @@ -50,6 +33,14 @@ use reth_tracing::tracing::{debug, error, info}; use tokio::sync::{mpsc::unbounded_channel, oneshot}; use tokio_stream::wrappers::UnboundedReceiverStream; +use crate::{ + hooks::NodeHooks, + rpc::{launch_rpc_servers, EthApiBuilderProvider}, + setup::build_networked_pipeline, + AddOns, ExExLauncher, FullNode, LaunchContext, LaunchNode, NodeAdapter, + NodeBuilderWithComponents, NodeComponents, NodeComponentsBuilder, NodeHandle, NodeTypesAdapter, +}; + /// The engine node launcher. #[derive(Debug)] pub struct EngineNodeLauncher { diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 4edc3658cb02..4aae1138cb09 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -21,6 +21,7 @@ use reth_rpc_builder::{ RpcModuleBuilder, RpcRegistryInner, RpcServerHandle, TransportRpcModules, }; use reth_rpc_layer::JwtSecret; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; @@ -298,8 +299,11 @@ pub async fn launch_rpc_servers( where Node: FullNodeComponents + Clone, Engine: EngineApiServer, - EthApi: EthApiBuilderProvider + FullEthApiServer, - EthApi::NetworkTypes: alloy_network::Network, + EthApi: EthApiBuilderProvider + + FullEthApiServer< + NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, + >, { let auth_config = config.rpc.auth_server_config(jwt_secret)?; let module_config = config.rpc.transport_rpc_module_config(); diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 57a12140b5a5..a0cb488ae07d 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -168,6 +168,7 @@ use reth_rpc_eth_api::{ Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder, }, Block, EthApiServer, EthApiTypes, FullEthApiServer, RawTransactionForwarder, Transaction, + TransactionBuilder, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -229,8 +230,10 @@ where Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, EvmConfig: ConfigureEvm, - EthApi: FullEthApiServer, - EthApi::NetworkTypes: alloy_network::Network, + EthApi: FullEthApiServer< + NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, + >, { let module_config = module_config.into(); server_config @@ -437,9 +440,10 @@ where where EngineT: EngineTypes, EngineApi: EngineApiServer, - EthApi: FullEthApiServer, - EthApi::NetworkTypes: - alloy_network::Network, + EthApi: FullEthApiServer< + NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, + >, { let Self { provider, pool, network, executor, events, evm_config } = self; @@ -505,9 +509,10 @@ where eth: DynEthApiBuilder, ) -> TransportRpcModules<()> where - EthApi: FullEthApiServer, - EthApi::NetworkTypes: - alloy_network::Network, + EthApi: FullEthApiServer< + NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, + >, { let mut modules = TransportRpcModules::default(); @@ -981,8 +986,10 @@ where Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: FullEthApiServer, - EthApi::NetworkTypes: alloy_network::Network, + EthApi: FullEthApiServer< + NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, + >, { /// Configures the auth module that includes the /// * `engine_` namespace diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 3baaf8bf66c0..fccfb1977285 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -15,6 +15,7 @@ use reth_rpc_types::{ AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; +use reth_rpc_types_compat::TransactionBuilder; use tracing::trace; use crate::{ @@ -359,6 +360,7 @@ pub trait EthApi { impl EthApiServer, Block> for T where T: FullEthApi, + T::TransactionBuilder: TransactionBuilder>, jsonrpsee_types::error::ErrorObject<'static>: From, { /// Handler for: `eth_protocolVersion` diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 86354c656ef8..c77ee1c52547 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,9 +7,9 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder}; +use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionBuilder}; -use crate::{Block, FromEthApiError}; +use crate::{Block, FromEthApiError, Transaction}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; @@ -25,7 +25,10 @@ pub trait EthBlocks: LoadBlock { fn rpc_block_header( &self, block_id: BlockId, - ) -> impl Future, Self::Error>> + Send { + ) -> impl Future, Self::Error>> + Send + where + Self::TransactionBuilder: TransactionBuilder>, + { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -37,7 +40,10 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future>, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send + where + Self::TransactionBuilder: TransactionBuilder>, + { async move { let block = match self.block_with_senders(block_id).await? { Some(block) => block, diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index a90760f5e1bb..78245bf6d4b4 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -198,6 +198,7 @@ pub trait EthTransactions: LoadTransaction { ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, + Self::TransactionBuilder: TransactionBuilder>, { async move { if let Some(block) = self.block_with_senders(block_id).await? { diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 56434f4e0ed1..f5bae747e791 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -1,11 +1,11 @@ //! Trait for specifying `eth` API types that may be network dependent. -use std::error::Error; +use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; use reth_rpc_types::Rich; -use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; +use reth_rpc_types_compat::BlockBuilder; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -22,7 +22,7 @@ pub trait EthApiTypes: Send + Sync + Clone { /// Blockchain primitive types, specific to network, e.g. block and transaction. type NetworkTypes: Network; /// Conversion methods for transaction RPC type. - type TransactionBuilder: TransactionBuilder>; + type TransactionBuilder: Send + Sync + Clone + fmt::Debug; /// Conversion methods for block RPC type. type BlockBuilder: BlockBuilder; } diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index f95600f0b6ab..89107bff5e92 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -38,6 +38,7 @@ impl EngineEthApiServer for EngineEthApi where Eth: EthApiServer, Block> + EthApiTypes, Eth::NetworkTypes: Network, + Eth::TransactionBuilder: TransactionBuilder>, EthFilter: EthFilterApiServer<::Transaction>, { /// Handler for: `eth_syncing` diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 0203fd517497..65ab90614e62 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -38,17 +38,15 @@ use tracing::trace; const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb /// `Eth` filter RPC implementation. -pub struct EthFilter { + +pub struct EthFilter { /// All nested fields bundled together - inner: Arc>, + inner: Arc>, /// Assembles response data w.r.t. network. _tx_resp_builder: PhantomData, } -impl Clone for EthFilter -where - Eth: TransactionBuilder, -{ +impl Clone for EthFilter { fn clone(&self) -> Self { Self { inner: self.inner.clone(), _tx_resp_builder: PhantomData } } @@ -58,7 +56,7 @@ impl EthFilter where Provider: Send + Sync + 'static, Pool: Send + Sync + 'static, - Eth: TransactionBuilder + Clone + 'static, + Eth: Send + Sync + 'static, { /// Creates a new, shareable instance. /// @@ -103,9 +101,15 @@ where eth_filter } +} +impl EthFilter +where + Provider: Send + Sync + 'static, + Pool: Send + Sync + 'static, +{ /// Returns all currently active filters - pub fn active_filters(&self) -> &ActiveFilters { + pub fn active_filters(&self) -> &ActiveFilters { &self.inner.active_filters } @@ -141,8 +145,7 @@ where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, ::Transaction: 'static, - Eth: TransactionBuilder, - Eth::Transaction: Clone + 'static, + Eth: TransactionBuilder, { /// Returns all the filter changes for the given id, if any pub async fn filter_changes( @@ -321,10 +324,7 @@ where } } -impl std::fmt::Debug for EthFilter -where - Eth: TransactionBuilder, -{ +impl std::fmt::Debug for EthFilter { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EthFilter").finish_non_exhaustive() } From a1868673203ffa58aa245cbde99e165a1664bc3e Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Tue, 20 Aug 2024 21:38:52 +0200 Subject: [PATCH 33/80] fixup! Remove trait bound TransactionBuilder on EthApiTypes::TransationBuilder --- Cargo.lock | 1 - crates/ethereum/node/Cargo.toml | 3 --- crates/net/network/src/transactions/mod.rs | 2 ++ crates/node/builder/src/builder/mod.rs | 6 ++++-- crates/node/builder/src/launch/engine.rs | 4 +++- crates/node/builder/src/launch/mod.rs | 4 +++- crates/rpc/rpc-eth-api/src/helpers/block.rs | 9 +++++---- 7 files changed, 17 insertions(+), 12 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d01c653b5657..33f4f361ae4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7798,7 +7798,6 @@ name = "reth-node-ethereum" version = "1.0.5" dependencies = [ "alloy-genesis", - "alloy-network", "alloy-primitives", "eyre", "futures", diff --git a/crates/ethereum/node/Cargo.toml b/crates/ethereum/node/Cargo.toml index d3081a969a81..fba683a2a45f 100644 --- a/crates/ethereum/node/Cargo.toml +++ b/crates/ethereum/node/Cargo.toml @@ -28,9 +28,6 @@ reth-beacon-consensus.workspace = true reth-rpc.workspace = true reth-node-api.workspace = true -# ethereum -alloy-network.workspace = true - # misc eyre.workspace = true diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index 9e6bd4efcf61..d180b92e7a3d 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -2380,9 +2380,11 @@ mod tests { assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash())); assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash())); peer.seen_transactions.contains(eip4844_tx.transaction.hash()); + println!("{:?}", propagated.0); // propagate again let propagated = tx_manager.propagate_transactions(propagate); + println!("{:?}", propagated.0); assert!(propagated.0.is_empty()); } } diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index a5a1ce1882ec..b4855dc71bb5 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -20,7 +20,7 @@ use reth_exex::ExExContext; use reth_network::{ NetworkBuilder, NetworkConfig, NetworkConfigBuilder, NetworkHandle, NetworkManager, }; -use reth_node_api::{EthApiTypes, FullNodeTypes, FullNodeTypesAdapter, NodeAddOns, NodeTypes}; +use reth_node_api::{FullNodeTypes, FullNodeTypesAdapter, NodeAddOns, NodeTypes}; use reth_node_core::{ cli::config::{PayloadBuilderConfig, RethTransactionPoolConfig}, dirs::{ChainPath, DataDirPath}, @@ -30,6 +30,7 @@ use reth_node_core::{ }; use reth_primitives::revm_primitives::EnvKzgSettings; use reth_provider::{providers::BlockchainProvider, ChainSpecProvider, FullProvider}; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::TaskExecutor; use reth_transaction_pool::{PoolConfig, TransactionPool}; use secp256k1::SecretKey; @@ -331,7 +332,7 @@ where + FullEthApiServer< NetworkTypes: alloy_network::Network< TransactionResponse = reth_rpc_types::Transaction - > + >, TransactionBuilder: TransactionBuilder > + AddDevSigners >, @@ -480,6 +481,7 @@ where EthApi: EthApiBuilderProvider, CB::Components>> + FullEthApiServer< NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index c436b8e6f726..f625daacab2a 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -15,7 +15,7 @@ use reth_engine_util::EngineMessageStreamExt; use reth_exex::ExExManagerHandle; use reth_network::{NetworkSyncUpdater, SyncState}; use reth_network_api::{BlockDownloaderProvider, NetworkEventListenerProvider}; -use reth_node_api::{BuiltPayload, EthApiTypes, FullNodeTypes, NodeAddOns}; +use reth_node_api::{BuiltPayload, FullNodeTypes, NodeAddOns}; use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, @@ -27,6 +27,7 @@ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_provider::providers::BlockchainProvider2; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; use reth_tracing::tracing::{debug, error, info}; @@ -64,6 +65,7 @@ where EthApi: EthApiBuilderProvider> + FullEthApiServer< NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index c68000294c0d..fbfc91543998 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -24,7 +24,7 @@ use reth_node_api::{FullNodeComponents, FullNodeTypes, NodeAddOns}; use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, - rpc::eth::{helpers::AddDevSigners, EthApiTypes, FullEthApiServer}, + rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; @@ -32,6 +32,7 @@ use reth_primitives::format_ether; use reth_provider::providers::BlockchainProvider; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; +use reth_rpc_types_compat::TransactionBuilder; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::TransactionPool; @@ -109,6 +110,7 @@ where EthApi: EthApiBuilderProvider> + FullEthApiServer< NetworkTypes: alloy_network::Network, + TransactionBuilder: TransactionBuilder, > + AddDevSigners, >, { diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 92bb123da755..c77ee1c52547 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -207,10 +207,11 @@ pub trait EthBlocks: LoadBlock { } .unwrap_or_default(); - let uncle = uncles - .into_iter() - .nth(index.into()) - .map(|header| uncle_block_from_header(header).into()); + let index = usize::from(index); + let uncle = uncles.into_iter().nth(index).map(|header| Rich { + inner: uncle_block_from_header(header), + extra_info: Default::default(), + }); Ok(uncle) } } From a784b7a68b7faffdb4d64c1bcedf840817d8e18d Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Tue, 20 Aug 2024 21:43:09 +0200 Subject: [PATCH 34/80] Fix lint --- crates/rpc/rpc/src/eth/filter.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 65ab90614e62..4d88bbb0f25f 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -38,7 +38,6 @@ use tracing::trace; const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb /// `Eth` filter RPC implementation. - pub struct EthFilter { /// All nested fields bundled together inner: Arc>, From 856f37e2e7893dd3e6bc73a315246580f991a0fb Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Tue, 20 Aug 2024 21:45:53 +0200 Subject: [PATCH 35/80] Rename TransactionBuilder to TransactionCompat --- crates/node/builder/src/builder/mod.rs | 6 +++--- crates/node/builder/src/launch/engine.rs | 4 ++-- crates/node/builder/src/launch/mod.rs | 4 ++-- crates/node/builder/src/rpc.rs | 4 ++-- crates/rpc/rpc-builder/src/eth.rs | 8 ++++---- crates/rpc/rpc-builder/src/lib.rs | 12 ++++++------ crates/rpc/rpc-eth-api/src/core.rs | 6 +++--- crates/rpc/rpc-eth-api/src/helpers/block.rs | 6 +++--- .../rpc/rpc-eth-api/src/helpers/transaction.rs | 6 +++--- crates/rpc/rpc-eth-api/src/helpers/types.rs | 6 +++--- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-types/src/transaction.rs | 4 ++-- crates/rpc/rpc-types-compat/src/block.rs | 16 ++++++++-------- crates/rpc/rpc-types-compat/src/lib.rs | 2 +- .../rpc/rpc-types-compat/src/transaction/mod.rs | 4 ++-- crates/rpc/rpc/src/engine.rs | 6 +++--- crates/rpc/rpc/src/eth/core.rs | 2 +- crates/rpc/rpc/src/eth/filter.rs | 10 +++++----- crates/rpc/rpc/src/eth/helpers/types.rs | 6 +++--- crates/rpc/rpc/src/eth/pubsub.rs | 6 +++--- crates/rpc/rpc/src/txpool.rs | 8 ++++---- 21 files changed, 64 insertions(+), 64 deletions(-) diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index b4855dc71bb5..3d0b80137ab5 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -30,7 +30,7 @@ use reth_node_core::{ }; use reth_primitives::revm_primitives::EnvKzgSettings; use reth_provider::{providers::BlockchainProvider, ChainSpecProvider, FullProvider}; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_transaction_pool::{PoolConfig, TransactionPool}; use secp256k1::SecretKey; @@ -332,7 +332,7 @@ where + FullEthApiServer< NetworkTypes: alloy_network::Network< TransactionResponse = reth_rpc_types::Transaction - >, TransactionBuilder: TransactionBuilder + >, TransactionCompat: TransactionCompat > + AddDevSigners >, @@ -481,7 +481,7 @@ where EthApi: EthApiBuilderProvider, CB::Components>> + FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index f625daacab2a..b8a21b5a33e3 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -27,7 +27,7 @@ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_provider::providers::BlockchainProvider2; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; use reth_tracing::tracing::{debug, error, info}; @@ -65,7 +65,7 @@ where EthApi: EthApiBuilderProvider> + FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index fbfc91543998..9f75c3f69c81 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -32,7 +32,7 @@ use reth_primitives::format_ether; use reth_provider::providers::BlockchainProvider; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::TransactionPool; @@ -110,7 +110,7 @@ where EthApi: EthApiBuilderProvider> + FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 4aae1138cb09..45e774e3191b 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -21,7 +21,7 @@ use reth_rpc_builder::{ RpcModuleBuilder, RpcRegistryInner, RpcServerHandle, TransportRpcModules, }; use reth_rpc_layer::JwtSecret; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; @@ -302,7 +302,7 @@ where EthApi: EthApiBuilderProvider + FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, >, { let auth_config = config.rpc.auth_server_config(jwt_secret)?; diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index f28148fb2508..52eef4870a8f 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -22,9 +22,9 @@ pub struct EthHandlers { /// The async caching layer used by the eth handlers pub cache: EthStateCache, /// Polling based filter handler available on all transports - pub filter: EthFilter, + pub filter: EthFilter, /// Handler for subscriptions only available for transports that support it (ws, ipc) - pub pubsub: EthPubSub, + pub pubsub: EthPubSub, } impl EthHandlers @@ -139,7 +139,7 @@ impl EthFilterApiBuilder { /// Builds the [`EthFilterApiServer`](reth_rpc_eth_api::EthFilterApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthFilter + ) -> EthFilter where Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, @@ -164,7 +164,7 @@ impl EthPubSubApiBuilder { /// Builds the [`EthPubSubApiServer`](reth_rpc_eth_api::EthPubSubApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthPubSub + ) -> EthPubSub where Provider: Clone, Pool: Clone, diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index a0cb488ae07d..00c1dfedde7d 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -168,7 +168,7 @@ use reth_rpc_eth_api::{ Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, UpdateRawTxForwarder, }, Block, EthApiServer, EthApiTypes, FullEthApiServer, RawTransactionForwarder, Transaction, - TransactionBuilder, + TransactionCompat, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -232,7 +232,7 @@ where EvmConfig: ConfigureEvm, EthApi: FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, >, { let module_config = module_config.into(); @@ -442,7 +442,7 @@ where EngineApi: EngineApiServer, EthApi: FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, >, { let Self { provider, pool, network, executor, events, evm_config } = self; @@ -511,7 +511,7 @@ where where EthApi: FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, >, { let mut modules = TransportRpcModules::default(); @@ -988,7 +988,7 @@ where Events: CanonStateSubscriptions + Clone + 'static, EthApi: FullEthApiServer< NetworkTypes: alloy_network::Network, - TransactionBuilder: TransactionBuilder, + TransactionCompat: TransactionCompat, >, { /// Configures the auth module that includes the @@ -1105,7 +1105,7 @@ where .into(), RethRpcModule::Web3 => Web3Api::new(self.network.clone()).into_rpc().into(), RethRpcModule::Txpool => { - TxPoolApi::<_, EthApi::TransactionBuilder>::new(self.pool.clone()) + TxPoolApi::<_, EthApi::TransactionCompat>::new(self.pool.clone()) .into_rpc() .into() } diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 1eee45c406f0..93768e1a5e7b 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -15,7 +15,7 @@ use reth_rpc_types::{ AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use tracing::trace; use crate::{ @@ -360,7 +360,7 @@ pub trait EthApi { impl EthApiServer, Block> for T where T: FullEthApi, - T::TransactionBuilder: TransactionBuilder>, + T::TransactionCompat: TransactionCompat>, jsonrpsee_types::error::ErrorObject<'static>: From, { /// Handler for: `eth_protocolVersion` @@ -493,7 +493,7 @@ where trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash) .await? - .map(|tx| tx.into_transaction::())) + .map(|tx| tx.into_transaction::())) } /// Handler for: `eth_getRawTransactionByBlockHashAndIndex` diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index c77ee1c52547..23556a047804 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,7 +7,7 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionBuilder}; +use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionCompat}; use crate::{Block, FromEthApiError, Transaction}; @@ -27,7 +27,7 @@ pub trait EthBlocks: LoadBlock { block_id: BlockId, ) -> impl Future, Self::Error>> + Send where - Self::TransactionBuilder: TransactionBuilder>, + Self::TransactionCompat: TransactionCompat>, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -42,7 +42,7 @@ pub trait EthBlocks: LoadBlock { full: bool, ) -> impl Future>, Self::Error>> + Send where - Self::TransactionBuilder: TransactionBuilder>, + Self::TransactionCompat: TransactionCompat>, { async move { let block = match self.block_with_senders(block_id).await? { diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 78245bf6d4b4..7977d7e54613 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -21,7 +21,7 @@ use reth_rpc_types::{ }, AnyTransactionReceipt, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; use crate::{FromEthApiError, IntoEthApiError, Transaction}; @@ -198,7 +198,7 @@ pub trait EthTransactions: LoadTransaction { ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, - Self::TransactionBuilder: TransactionBuilder>, + Self::TransactionCompat: TransactionCompat>, { async move { if let Some(block) = self.block_with_senders(block_id).await? { @@ -206,7 +206,7 @@ pub trait EthTransactions: LoadTransaction { let block_number = block.number; let base_fee_per_gas = block.base_fee_per_gas; if let Some(tx) = block.into_transactions_ecrecovered().nth(index) { - return Ok(Some(Self::TransactionBuilder::from_recovered_with_block_context( + return Ok(Some(Self::TransactionCompat::from_recovered_with_block_context( tx, block_hash, block_number, diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index f5bae747e791..45192009273e 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -22,15 +22,15 @@ pub trait EthApiTypes: Send + Sync + Clone { /// Blockchain primitive types, specific to network, e.g. block and transaction. type NetworkTypes: Network; /// Conversion methods for transaction RPC type. - type TransactionBuilder: Send + Sync + Clone + fmt::Debug; + type TransactionCompat: Send + Sync + Clone + fmt::Debug; /// Conversion methods for block RPC type. - type BlockBuilder: BlockBuilder; + type BlockBuilder: BlockBuilder; } impl EthApiTypes for () { type Error = EthApiError; type NetworkTypes = AnyNetwork; - type TransactionBuilder = (); + type TransactionCompat = (); type BlockBuilder = (); } diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index f71f2d05f7f2..6529f1f5eb29 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -18,7 +18,7 @@ pub mod filter; pub mod helpers; pub mod pubsub; -pub use reth_rpc_types_compat::{BlockBuilder, TransactionBuilder}; +pub use reth_rpc_types_compat::{BlockBuilder, TransactionCompat}; pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; pub use core::{EthApiServer, FullEthApiServer}; diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index 78f483b2c942..08fd42966683 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -4,7 +4,7 @@ use reth_primitives::{TransactionSignedEcRecovered, B256}; use reth_rpc_types::TransactionInfo; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; /// Represents from where a transaction was fetched. #[derive(Debug, Clone, Eq, PartialEq)] @@ -37,7 +37,7 @@ impl TransactionSource { } /// Conversion into network specific transaction type. - pub fn into_transaction(self) -> T::Transaction { + pub fn into_transaction(self) -> T::Transaction { match self { Self::Pool(tx) => T::from_recovered(tx), Self::Block { transaction, index, block_hash, block_number, base_fee } => { diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index b3b5a040b461..046202879d96 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -8,12 +8,12 @@ use reth_primitives::{ }; use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind, Header}; -use crate::TransactionBuilder; +use crate::TransactionCompat; /// Builds RPC block w.r.t. network. pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { /// RPC transaction type builder of network. - type TxBuilder: TransactionBuilder; + type TxBuilder: TransactionCompat; /// Converts the given primitive block into a [Block] response with the given /// [`BlockTransactionsKind`] @@ -24,7 +24,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { total_difficulty: U256, kind: BlockTransactionsKind, block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { match kind { BlockTransactionsKind::Hashes => { Ok(Self::from_block_with_tx_hashes(block, total_difficulty, block_hash)) @@ -44,7 +44,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { mut block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); let block_number = block.block.number; let base_fee_per_gas = block.block.base_fee_per_gas; @@ -69,7 +69,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { }) .collect::>(); - Ok(from_block_with_transactions::<::Transaction>( + Ok(from_block_with_transactions::<::Transaction>( block_length, block_hash, block.block, @@ -87,11 +87,11 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Block<::Transaction> { + ) -> Block<::Transaction> { let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - from_block_with_transactions::<::Transaction>( + from_block_with_transactions::<::Transaction>( block.length(), block_hash, block.block, @@ -108,7 +108,7 @@ impl BlockBuilder for () { _block: BlockWithSenders, _total_difficulty: U256, _block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { Ok(Block::default()) } } diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 1926d2bfbacd..5c3f1f5a7085 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -16,4 +16,4 @@ pub mod proof; pub mod transaction; pub use block::BlockBuilder; -pub use transaction::TransactionBuilder; +pub use transaction::TransactionCompat; diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 036047934ff4..ecd2ce12d1f4 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -13,7 +13,7 @@ use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecover use reth_rpc_types::{Transaction, WithOtherFields}; /// Builds RPC transaction w.r.t. network. -pub trait TransactionBuilder: Send + Sync + Unpin + Clone + fmt::Debug { +pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { /// RPC transaction response type. type Transaction: Send + Clone + Default + fmt::Debug; @@ -126,7 +126,7 @@ pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> Transact } } -impl TransactionBuilder for () { +impl TransactionCompat for () { // this noop impl depends on integration in `reth_rpc_eth_api::EthApiTypes` noop impl, and // `alloy_network::AnyNetwork` type Transaction = WithOtherFields; diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 89107bff5e92..3772e4255e49 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -9,7 +9,7 @@ use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, SyncStatus, TransactionRequest, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use tracing_futures::Instrument; macro_rules! engine_span { @@ -38,8 +38,8 @@ impl EngineEthApiServer for EngineEthApi where Eth: EthApiServer, Block> + EthApiTypes, Eth::NetworkTypes: Network, - Eth::TransactionBuilder: TransactionBuilder>, - EthFilter: EthFilterApiServer<::Transaction>, + Eth::TransactionCompat: TransactionCompat>, + EthFilter: EthFilterApiServer<::Transaction>, { /// Handler for: `eth_syncing` fn syncing(&self) -> Result { diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 45932e07164c..dc3466471e16 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -129,7 +129,7 @@ where { type Error = EthApiError; type NetworkTypes = Ethereum; - type TransactionBuilder = EthTxBuilder; + type TransactionCompat = EthTxBuilder; type BlockBuilder = EthBlockBuilder; } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 4d88bbb0f25f..9648ffac425c 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -25,7 +25,7 @@ use reth_rpc_types::{ BlockNumHash, Filter, FilterBlockOption, FilterChanges, FilterId, FilteredParams, Log, PendingTransactionFilterKind, Transaction, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskSpawner; use reth_transaction_pool::{NewSubpoolTransactionStream, PoolTransaction, TransactionPool}; use tokio::{ @@ -144,7 +144,7 @@ where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, ::Transaction: 'static, - Eth: TransactionBuilder, + Eth: TransactionCompat, { /// Returns all the filter changes for the given id, if any pub async fn filter_changes( @@ -244,7 +244,7 @@ impl EthFilterApiServer for EthFilter + Clone + 'static, + Eth: TransactionCompat + Clone + 'static, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { @@ -583,7 +583,7 @@ struct FullTransactionsReceiver { impl FullTransactionsReceiver where T: PoolTransaction + 'static, - Eth: TransactionBuilder, + Eth: TransactionCompat, { /// Creates a new `FullTransactionsReceiver` encapsulating the provided transaction stream. fn new(stream: NewSubpoolTransactionStream) -> Self { @@ -612,7 +612,7 @@ trait FullTransactionsFilter: fmt::Debug + Send + Sync + Unpin + 'static { impl FullTransactionsFilter for FullTransactionsReceiver where T: PoolTransaction + 'static, - Eth: TransactionBuilder + 'static, + Eth: TransactionCompat + 'static, { async fn drain(&self) -> FilterChanges { Self::drain(self).await diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index 7a18555fcb89..c8f3bbe9c086 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -7,14 +7,14 @@ use derive_more::Constructor; use reth_primitives::{Address, BlockNumber, TransactionSignedEcRecovered, TxKind, B256}; use reth_rpc_types_compat::{ transaction::{from_primitive_signature, GasPrice}, - BlockBuilder, TransactionBuilder, + BlockBuilder, TransactionCompat, }; /// Builds RPC transaction response for l1. #[derive(Debug, Clone, Copy)] pub struct EthTxBuilder; -impl TransactionBuilder for EthTxBuilder +impl TransactionCompat for EthTxBuilder where Self: Send + Sync, { @@ -82,6 +82,6 @@ pub struct EthBlockBuilder { _tx_builder: PhantomData, } -impl BlockBuilder for EthBlockBuilder { +impl BlockBuilder for EthBlockBuilder { type TxBuilder = TxB; } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index f76066c56a1d..b4dc1b385b70 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -19,7 +19,7 @@ use reth_rpc_types::{ }, FilteredParams, Header, Log, Transaction, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::{TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{NewTransactionEvent, TransactionPool}; use serde::Serialize; @@ -77,7 +77,7 @@ where Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, - Eth: TransactionBuilder + Clone + 'static, + Eth: TransactionCompat + Clone + 'static, { /// Handler for `eth_subscribe` async fn subscribe( @@ -109,7 +109,7 @@ where Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction - Eth: TransactionBuilder, + Eth: TransactionCompat, { match kind { SubscriptionKind::NewHeads => { diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index b12080aaf80a..70f9e4862533 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -8,7 +8,7 @@ use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, Transaction, }; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_transaction_pool::{AllPoolTransactions, PoolTransaction, TransactionPool}; use tracing::trace; @@ -33,7 +33,7 @@ impl TxPoolApi where Pool: TransactionPool + 'static, // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction - Eth: TransactionBuilder, + Eth: TransactionCompat, { fn content(&self) -> TxpoolContent { #[inline] @@ -42,7 +42,7 @@ where content: &mut BTreeMap>, ) where Tx: PoolTransaction, - Eth: TransactionBuilder, + Eth: TransactionCompat, { content .entry(tx.sender()) @@ -68,7 +68,7 @@ where impl TxPoolApiServer for TxPoolApi where Pool: TransactionPool + 'static, - Eth: TransactionBuilder + 'static, + Eth: TransactionCompat + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. From 9d911bbe49d6f31f2cf035ba51461e0afe9f008d Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 11:46:05 +0200 Subject: [PATCH 36/80] Rename BlockBuilder to BlockCompat --- crates/rpc/rpc-eth-api/src/helpers/block.rs | 4 ++-- crates/rpc/rpc-eth-api/src/helpers/types.rs | 6 +++--- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-types-compat/src/block.rs | 24 ++++++++++----------- crates/rpc/rpc-types-compat/src/lib.rs | 2 +- crates/rpc/rpc/src/eth/core.rs | 2 +- crates/rpc/rpc/src/eth/helpers/types.rs | 6 +++--- 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 23556a047804..bf80aafa65f3 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,7 +7,7 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{block::uncle_block_from_header, BlockBuilder, TransactionCompat}; +use reth_rpc_types_compat::{block::uncle_block_from_header, BlockCompat, TransactionCompat}; use crate::{Block, FromEthApiError, Transaction}; @@ -54,7 +54,7 @@ pub trait EthBlocks: LoadBlock { .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = Self::BlockBuilder::from_block( + let block = Self::BlockCompat::from_block( block.unseal(), total_difficulty, full.into(), diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 45192009273e..a609cddcdc4b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -5,7 +5,7 @@ use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; use reth_rpc_types::Rich; -use reth_rpc_types_compat::BlockBuilder; +use reth_rpc_types_compat::BlockCompat; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -24,14 +24,14 @@ pub trait EthApiTypes: Send + Sync + Clone { /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; /// Conversion methods for block RPC type. - type BlockBuilder: BlockBuilder; + type BlockCompat: BlockCompat; } impl EthApiTypes for () { type Error = EthApiError; type NetworkTypes = AnyNetwork; type TransactionCompat = (); - type BlockBuilder = (); + type BlockCompat = (); } /// Adapter for network specific transaction type. diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 6529f1f5eb29..9a29e2382875 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -18,7 +18,7 @@ pub mod filter; pub mod helpers; pub mod pubsub; -pub use reth_rpc_types_compat::{BlockBuilder, TransactionCompat}; +pub use reth_rpc_types_compat::{BlockCompat, TransactionCompat}; pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; pub use core::{EthApiServer, FullEthApiServer}; diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 046202879d96..264a0f9057c0 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -11,9 +11,9 @@ use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind use crate::TransactionCompat; /// Builds RPC block w.r.t. network. -pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { - /// RPC transaction type builder of network. - type TxBuilder: TransactionCompat; +pub trait BlockCompat: Send + Sync + Unpin + fmt::Debug { + /// RPC transaction type conversions w.r.t. network. + type TxCompat: TransactionCompat; /// Converts the given primitive block into a [Block] response with the given /// [`BlockTransactionsKind`] @@ -24,7 +24,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { total_difficulty: U256, kind: BlockTransactionsKind, block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { match kind { BlockTransactionsKind::Hashes => { Ok(Self::from_block_with_tx_hashes(block, total_difficulty, block_hash)) @@ -44,7 +44,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { mut block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); let block_number = block.block.number; let base_fee_per_gas = block.block.base_fee_per_gas; @@ -59,7 +59,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { .map(|(idx, (tx, sender))| { let signed_tx_ec_recovered = tx.with_signer(sender); - Self::TxBuilder::from_recovered_with_block_context( + Self::TxCompat::from_recovered_with_block_context( signed_tx_ec_recovered, block_hash, block_number, @@ -69,7 +69,7 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { }) .collect::>(); - Ok(from_block_with_transactions::<::Transaction>( + Ok(from_block_with_transactions::<::Transaction>( block_length, block_hash, block.block, @@ -87,11 +87,11 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { block: BlockWithSenders, total_difficulty: U256, block_hash: Option, - ) -> Block<::Transaction> { + ) -> Block<::Transaction> { let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - from_block_with_transactions::<::Transaction>( + from_block_with_transactions::<::Transaction>( block.length(), block_hash, block.block, @@ -101,14 +101,14 @@ pub trait BlockBuilder: Send + Sync + Unpin + fmt::Debug { } } -impl BlockBuilder for () { - type TxBuilder = (); +impl BlockCompat for () { + type TxCompat = (); fn from_block_full( _block: BlockWithSenders, _total_difficulty: U256, _block_hash: Option, - ) -> Result::Transaction>, BlockError> { + ) -> Result::Transaction>, BlockError> { Ok(Block::default()) } } diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 5c3f1f5a7085..1b19459e76a1 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -15,5 +15,5 @@ pub mod engine; pub mod proof; pub mod transaction; -pub use block::BlockBuilder; +pub use block::BlockCompat; pub use transaction::TransactionCompat; diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index dc3466471e16..11e8c02346c4 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -130,7 +130,7 @@ where type Error = EthApiError; type NetworkTypes = Ethereum; type TransactionCompat = EthTxBuilder; - type BlockBuilder = EthBlockBuilder; + type BlockCompat = EthBlockBuilder; } impl std::fmt::Debug diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index c8f3bbe9c086..92cf670c631d 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -7,7 +7,7 @@ use derive_more::Constructor; use reth_primitives::{Address, BlockNumber, TransactionSignedEcRecovered, TxKind, B256}; use reth_rpc_types_compat::{ transaction::{from_primitive_signature, GasPrice}, - BlockBuilder, TransactionCompat, + BlockCompat, TransactionCompat, }; /// Builds RPC transaction response for l1. @@ -82,6 +82,6 @@ pub struct EthBlockBuilder { _tx_builder: PhantomData, } -impl BlockBuilder for EthBlockBuilder { - type TxBuilder = TxB; +impl BlockCompat for EthBlockBuilder { + type TxCompat = TxB; } From 2bb8a75f22ed4dd1ea066058ccde3bec5294db0b Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 11:52:22 +0200 Subject: [PATCH 37/80] Delay trait bound for EthApiTypes::BlockCompat --- crates/rpc/rpc-eth-api/src/core.rs | 8 +++++--- crates/rpc/rpc-eth-api/src/helpers/block.rs | 2 ++ crates/rpc/rpc-eth-api/src/helpers/types.rs | 3 +-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 93768e1a5e7b..5ba557ee6395 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -15,7 +15,7 @@ use reth_rpc_types::{ AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{BlockCompat, TransactionCompat}; use tracing::trace; use crate::{ @@ -359,8 +359,10 @@ pub trait EthApi { #[async_trait::async_trait] impl EthApiServer, Block> for T where - T: FullEthApi, - T::TransactionCompat: TransactionCompat>, + T: FullEthApi< + TransactionCompat: TransactionCompat>, + BlockCompat: BlockCompat, + >, jsonrpsee_types::error::ErrorObject<'static>: From, { /// Handler for: `eth_protocolVersion` diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index bf80aafa65f3..80afadaec726 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -28,6 +28,7 @@ pub trait EthBlocks: LoadBlock { ) -> impl Future, Self::Error>> + Send where Self::TransactionCompat: TransactionCompat>, + Self::BlockCompat: BlockCompat, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -43,6 +44,7 @@ pub trait EthBlocks: LoadBlock { ) -> impl Future>, Self::Error>> + Send where Self::TransactionCompat: TransactionCompat>, + Self::BlockCompat: BlockCompat, { async move { let block = match self.block_with_senders(block_id).await? { diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index a609cddcdc4b..cfa9e3e24d42 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -5,7 +5,6 @@ use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; use reth_rpc_types::Rich; -use reth_rpc_types_compat::BlockCompat; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -24,7 +23,7 @@ pub trait EthApiTypes: Send + Sync + Clone { /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; /// Conversion methods for block RPC type. - type BlockCompat: BlockCompat; + type BlockCompat; } impl EthApiTypes for () { From b6a2cc9944ad7d41ccab9b6f8cc10a7b809577c3 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 12:06:40 +0200 Subject: [PATCH 38/80] Remove EthApiTypes::BlockCompat --- crates/optimism/rpc/src/eth/mod.rs | 3 +- crates/rpc/rpc-eth-api/src/core.rs | 7 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 9 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 3 - crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-types-compat/src/block.rs | 175 +++++++++----------- crates/rpc/rpc-types-compat/src/lib.rs | 1 - crates/rpc/rpc/src/eth/core.rs | 3 +- crates/rpc/rpc/src/eth/helpers/types.rs | 15 +- crates/rpc/rpc/src/eth/mod.rs | 5 +- 10 files changed, 89 insertions(+), 134 deletions(-) diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 23e963aeef82..7af11e3ea788 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -20,7 +20,7 @@ use reth_provider::{ BlockIdReader, BlockNumReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider, StageCheckpointReader, StateProviderFactory, }; -use reth_rpc::eth::{core::EthApiInner, DevSigner, EthBlockBuilder}; +use reth_rpc::eth::{core::EthApiInner, DevSigner}; use reth_rpc_eth_api::{ helpers::{ AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadBlock, LoadFee, LoadState, @@ -101,7 +101,6 @@ where type Error = OpEthApiError; type NetworkTypes = Optimism; type TransactionBuilder = OpTxBuilder; - type BlockBuilder = EthBlockBuilder>; } impl EthApiSpec for OpEthApi diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 44cb32bf3bff..499d8c368518 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -15,7 +15,7 @@ use reth_rpc_types::{ AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; -use reth_rpc_types_compat::{BlockCompat, TransactionCompat}; +use reth_rpc_types_compat::TransactionCompat; use tracing::trace; use crate::{ @@ -359,10 +359,7 @@ pub trait EthApi { #[async_trait::async_trait] impl EthApiServer, Block> for T where - T: FullEthApi< - TransactionCompat: TransactionCompat>, - BlockCompat: BlockCompat, - >, + T: FullEthApi>>, jsonrpsee_types::error::ErrorObject<'static>: From, { /// Handler for: `eth_protocolVersion` diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 80afadaec726..a1e6b1949366 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,7 +7,10 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, Tra use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; -use reth_rpc_types_compat::{block::uncle_block_from_header, BlockCompat, TransactionCompat}; +use reth_rpc_types_compat::{ + block::{from_block, uncle_block_from_header}, + TransactionCompat, +}; use crate::{Block, FromEthApiError, Transaction}; @@ -28,7 +31,6 @@ pub trait EthBlocks: LoadBlock { ) -> impl Future, Self::Error>> + Send where Self::TransactionCompat: TransactionCompat>, - Self::BlockCompat: BlockCompat, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -44,7 +46,6 @@ pub trait EthBlocks: LoadBlock { ) -> impl Future>, Self::Error>> + Send where Self::TransactionCompat: TransactionCompat>, - Self::BlockCompat: BlockCompat, { async move { let block = match self.block_with_senders(block_id).await? { @@ -56,7 +57,7 @@ pub trait EthBlocks: LoadBlock { .header_td_by_number(block.number) .map_err(Self::Error::from_eth_err)? .ok_or(EthApiError::UnknownBlockNumber)?; - let block = Self::BlockCompat::from_block( + let block = from_block::( block.unseal(), total_difficulty, full.into(), diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index cfa9e3e24d42..8d18897fe387 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -22,15 +22,12 @@ pub trait EthApiTypes: Send + Sync + Clone { type NetworkTypes: Network; /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; - /// Conversion methods for block RPC type. - type BlockCompat; } impl EthApiTypes for () { type Error = EthApiError; type NetworkTypes = AnyNetwork; type TransactionCompat = (); - type BlockCompat = (); } /// Adapter for network specific transaction type. diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 9a29e2382875..11af6aa8e0fe 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -18,7 +18,7 @@ pub mod filter; pub mod helpers; pub mod pubsub; -pub use reth_rpc_types_compat::{BlockCompat, TransactionCompat}; +pub use reth_rpc_types_compat::TransactionCompat; pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; pub use core::{EthApiServer, FullEthApiServer}; diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 264a0f9057c0..48552e0e3156 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -1,7 +1,5 @@ //! Compatibility functions for rpc `Block` type. -use std::fmt; - use alloy_rlp::Encodable; use reth_primitives::{ Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, @@ -10,108 +8,89 @@ use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind use crate::TransactionCompat; -/// Builds RPC block w.r.t. network. -pub trait BlockCompat: Send + Sync + Unpin + fmt::Debug { - /// RPC transaction type conversions w.r.t. network. - type TxCompat: TransactionCompat; - - /// Converts the given primitive block into a [Block] response with the given - /// [`BlockTransactionsKind`] - /// - /// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. - fn from_block( - block: BlockWithSenders, - total_difficulty: U256, - kind: BlockTransactionsKind, - block_hash: Option, - ) -> Result::Transaction>, BlockError> { - match kind { - BlockTransactionsKind::Hashes => { - Ok(Self::from_block_with_tx_hashes(block, total_difficulty, block_hash)) - } - BlockTransactionsKind::Full => { - Self::from_block_full(block, total_difficulty, block_hash) - } +/// Converts the given primitive block into a [`Block`] response with the given +/// [`BlockTransactionsKind`] +/// +/// If a `block_hash` is provided, then this is used, otherwise the block hash is computed. +pub fn from_block( + block: BlockWithSenders, + total_difficulty: U256, + kind: BlockTransactionsKind, + block_hash: Option, +) -> Result, BlockError> { + match kind { + BlockTransactionsKind::Hashes => { + Ok(from_block_with_tx_hashes::(block, total_difficulty, block_hash)) } - } - - /// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the - /// total difficulty to populate its field in the rpc response. - /// - /// This will populate the `transactions` field with the _full_ - /// [Transaction](reth_rpc_types::Transaction) objects: [`BlockTransactions::Full`] - fn from_block_full( - mut block: BlockWithSenders, - total_difficulty: U256, - block_hash: Option, - ) -> Result::Transaction>, BlockError> { - let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); - let block_number = block.block.number; - let base_fee_per_gas = block.block.base_fee_per_gas; - - // NOTE: we can safely remove the body here because not needed to finalize the `Block` in - // `from_block_with_transactions`, however we need to compute the length before - let block_length = block.block.length(); - let body = std::mem::take(&mut block.block.body); - let transactions_with_senders = body.into_iter().zip(block.senders); - let transactions = transactions_with_senders - .enumerate() - .map(|(idx, (tx, sender))| { - let signed_tx_ec_recovered = tx.with_signer(sender); - - Self::TxCompat::from_recovered_with_block_context( - signed_tx_ec_recovered, - block_hash, - block_number, - base_fee_per_gas, - idx, - ) - }) - .collect::>(); - - Ok(from_block_with_transactions::<::Transaction>( - block_length, - block_hash, - block.block, - total_difficulty, - BlockTransactions::Full(transactions), - )) - } - - /// Create a new [Block] response from a [primitive block](reth_primitives::Block), using the - /// total difficulty to populate its field in the rpc response. - /// - /// This will populate the `transactions` field with only the hashes of the transactions in the - /// block: [`BlockTransactions::Hashes`] - fn from_block_with_tx_hashes( - block: BlockWithSenders, - total_difficulty: U256, - block_hash: Option, - ) -> Block<::Transaction> { - let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); - let transactions = block.body.iter().map(|tx| tx.hash()).collect(); - - from_block_with_transactions::<::Transaction>( - block.length(), - block_hash, - block.block, - total_difficulty, - BlockTransactions::Hashes(transactions), - ) + BlockTransactionsKind::Full => from_block_full::(block, total_difficulty, block_hash), } } -impl BlockCompat for () { - type TxCompat = (); +/// Create a new [`Block`] response from a [primitive block](reth_primitives::Block), using the +/// total difficulty to populate its field in the rpc response. +/// +/// This will populate the `transactions` field with only the hashes of the transactions in the +/// block: [`BlockTransactions::Hashes`] +pub fn from_block_with_tx_hashes( + block: BlockWithSenders, + total_difficulty: U256, + block_hash: Option, +) -> Block { + let block_hash = block_hash.unwrap_or_else(|| block.header.hash_slow()); + let transactions = block.body.iter().map(|tx| tx.hash()).collect(); + + from_block_with_transactions( + block.length(), + block_hash, + block.block, + total_difficulty, + BlockTransactions::Hashes(transactions), + ) +} - fn from_block_full( - _block: BlockWithSenders, - _total_difficulty: U256, - _block_hash: Option, - ) -> Result::Transaction>, BlockError> { - Ok(Block::default()) - } +/// Create a new [`Block`] response from a [primitive block](reth_primitives::Block), using the +/// total difficulty to populate its field in the rpc response. +/// +/// This will populate the `transactions` field with the _full_ +/// [`Transaction`] objects: [`BlockTransactions::Full`] +pub fn from_block_full( + mut block: BlockWithSenders, + total_difficulty: U256, + block_hash: Option, +) -> Result, BlockError> { + let block_hash = block_hash.unwrap_or_else(|| block.block.header.hash_slow()); + let block_number = block.block.number; + let base_fee_per_gas = block.block.base_fee_per_gas; + + // NOTE: we can safely remove the body here because not needed to finalize the `Block` in + // `from_block_with_transactions`, however we need to compute the length before + let block_length = block.block.length(); + let body = std::mem::take(&mut block.block.body); + let transactions_with_senders = body.into_iter().zip(block.senders); + let transactions = transactions_with_senders + .enumerate() + .map(|(idx, (tx, sender))| { + let signed_tx_ec_recovered = tx.with_signer(sender); + + T::from_recovered_with_block_context( + signed_tx_ec_recovered, + block_hash, + block_number, + base_fee_per_gas, + idx, + ) + }) + .collect::>(); + + Ok(from_block_with_transactions( + block_length, + block_hash, + block.block, + total_difficulty, + BlockTransactions::Full(transactions), + )) } + /// Converts from a [`reth_primitives::SealedHeader`] to a [`reth_rpc_types::Header`] /// /// # Note diff --git a/crates/rpc/rpc-types-compat/src/lib.rs b/crates/rpc/rpc-types-compat/src/lib.rs index 1b19459e76a1..c324eebc8723 100644 --- a/crates/rpc/rpc-types-compat/src/lib.rs +++ b/crates/rpc/rpc-types-compat/src/lib.rs @@ -15,5 +15,4 @@ pub mod engine; pub mod proof; pub mod transaction; -pub use block::BlockCompat; pub use transaction::TransactionCompat; diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 11e8c02346c4..a2a72ba14772 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -22,7 +22,7 @@ use reth_tasks::{ }; use tokio::sync::Mutex; -use crate::eth::{EthBlockBuilder, EthTxBuilder}; +use crate::eth::EthTxBuilder; /// `Eth` API implementation. /// @@ -130,7 +130,6 @@ where type Error = EthApiError; type NetworkTypes = Ethereum; type TransactionCompat = EthTxBuilder; - type BlockCompat = EthBlockBuilder; } impl std::fmt::Debug diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index 92cf670c631d..435d021b02b3 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -1,13 +1,10 @@ //! L1 `eth` API types. -use std::marker::PhantomData; - use alloy_network::{Ethereum, Network}; -use derive_more::Constructor; use reth_primitives::{Address, BlockNumber, TransactionSignedEcRecovered, TxKind, B256}; use reth_rpc_types_compat::{ transaction::{from_primitive_signature, GasPrice}, - BlockCompat, TransactionCompat, + TransactionCompat, }; /// Builds RPC transaction response for l1. @@ -75,13 +72,3 @@ where } } } - -/// Builds a RPC block response for l1. -#[derive(Debug, Clone, Copy, Constructor)] -pub struct EthBlockBuilder { - _tx_builder: PhantomData, -} - -impl BlockCompat for EthBlockBuilder { - type TxCompat = TxB; -} diff --git a/crates/rpc/rpc/src/eth/mod.rs b/crates/rpc/rpc/src/eth/mod.rs index b7b3d153acd5..a932ac62d0a2 100644 --- a/crates/rpc/rpc/src/eth/mod.rs +++ b/crates/rpc/rpc/src/eth/mod.rs @@ -12,9 +12,6 @@ pub use core::EthApi; pub use filter::EthFilter; pub use pubsub::EthPubSub; -pub use helpers::{ - signer::DevSigner, - types::{EthBlockBuilder, EthTxBuilder}, -}; +pub use helpers::{signer::DevSigner, types::EthTxBuilder}; pub use reth_rpc_eth_api::{EthApiServer, RawTransactionForwarder}; From 97051001efee3a93b9133dfc261c899f14e0e73c Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 12:16:06 +0200 Subject: [PATCH 39/80] Fix lint --- crates/ethereum/evm/src/lib.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ethereum/evm/src/lib.rs b/crates/ethereum/evm/src/lib.rs index ec22b9f0894b..636e0f740846 100644 --- a/crates/ethereum/evm/src/lib.rs +++ b/crates/ethereum/evm/src/lib.rs @@ -177,6 +177,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_configure() { // Create a default `EthEvmConfig` let evm_config = EthEvmConfig::default(); @@ -218,6 +219,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_default_spec() { let evm_config = EthEvmConfig::default(); @@ -238,6 +240,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_custom_cfg() { let evm_config = EthEvmConfig::default(); @@ -268,6 +271,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_custom_block_and_tx() { let evm_config = EthEvmConfig::default(); @@ -324,6 +328,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_inspector() { let evm_config = EthEvmConfig::default(); @@ -368,6 +373,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_and_default_inspector() { let evm_config = EthEvmConfig::default(); let db = CacheDB::>::default(); @@ -387,6 +393,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_inspector_and_custom_cfg() { let evm_config = EthEvmConfig::default(); let db = CacheDB::>::default(); @@ -411,6 +418,7 @@ mod tests { } #[test] + #[allow(clippy::needless_update)] fn test_evm_with_env_inspector_and_custom_block_tx() { let evm_config = EthEvmConfig::default(); let db = CacheDB::>::default(); From a5d95bd9b9244ae0711a43b8f632d5fb4348c380 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 12:31:09 +0200 Subject: [PATCH 40/80] Fix lint --- Cargo.lock | 1 + crates/e2e-test-utils/src/lib.rs | 21 +++++++++++++++------ crates/optimism/node/Cargo.toml | 1 + crates/optimism/rpc/src/eth/mod.rs | 12 ++++++------ crates/optimism/rpc/src/eth/transaction.rs | 6 +++--- 5 files changed, 26 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7ae427c694d1..7af53f04ae50 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7932,6 +7932,7 @@ dependencies = [ "reth-primitives", "reth-provider", "reth-revm", + "reth-rpc", "reth-rpc-eth-api", "reth-rpc-eth-types", "reth-rpc-types", diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index 994f71f033e7..00e79305af79 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -14,10 +14,11 @@ use reth::{ use reth_chainspec::ChainSpec; use reth_db::{test_utils::TempDatabase, DatabaseEnv}; use reth_node_builder::{ - components::NodeComponentsBuilder, rpc::EthApiBuilderProvider, EthApiTypes, - FullNodeTypesAdapter, Node, NodeAdapter, NodeAddOns, NodeComponents, RethFullAdapter, + components::NodeComponentsBuilder, rpc::EthApiBuilderProvider, FullNodeTypesAdapter, Node, + NodeAdapter, NodeAddOns, NodeComponents, RethFullAdapter, }; use reth_provider::providers::BlockchainProvider; +use reth_rpc_types_compat::TransactionCompat; use tracing::{span, Level}; use wallet::Wallet; @@ -52,11 +53,19 @@ pub async fn setup( ) -> eyre::Result<(Vec>, TaskManager, Wallet)> where N: Default + Node>, - <>>::Components as NodeComponents>>::Network: PeersHandleProvider, - >>::EthApi: - FullEthApiServer + AddDevSigners + EthApiBuilderProvider>, - <>>::EthApi as EthApiTypes>::NetworkTypes: Network, + N::ComponentsBuilder: NodeComponentsBuilder< + TmpNodeAdapter, + Components: NodeComponents, Network: PeersHandleProvider>, + >, + N::AddOns: NodeAddOns< + Adapter, + EthApi: FullEthApiServer< + NetworkTypes: Network, + TransactionCompat: TransactionCompat, + > + AddDevSigners + + EthApiBuilderProvider>, + >, { let tasks = TaskManager::current(); let exec = tasks.executor(); diff --git a/crates/optimism/node/Cargo.toml b/crates/optimism/node/Cargo.toml index 52b622e22eca..52c436ecb16c 100644 --- a/crates/optimism/node/Cargo.toml +++ b/crates/optimism/node/Cargo.toml @@ -36,6 +36,7 @@ reth-discv5.workspace = true reth-rpc-eth-types.workspace = true reth-rpc-eth-api.workspace = true reth-optimism-rpc.workspace = true +reth-rpc.workspace = true # async async-trait.workspace = true diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 7af11e3ea788..1f8a018bcfed 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -29,7 +29,7 @@ use reth_rpc_eth_api::{ EthApiTypes, }; use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle}; -use reth_rpc_types_compat::TransactionBuilder; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskSpawner, @@ -96,11 +96,11 @@ where Self: Send + Sync, N: FullNodeComponents, // todo: replace constraint when op and l1 don't use same tx type in alloy - Eth: TransactionBuilder::TransactionResponse>, + Eth: TransactionCompat::TransactionResponse>, { type Error = OpEthApiError; type NetworkTypes = Optimism; - type TransactionBuilder = OpTxBuilder; + type TransactionCompat = OpTxBuilder; } impl EthApiSpec for OpEthApi @@ -133,7 +133,7 @@ impl SpawnBlocking for OpEthApi where Self: Send + Sync + Clone + 'static, N: FullNodeComponents, - Eth: TransactionBuilder::TransactionResponse>, + Eth: TransactionCompat::TransactionResponse>, { #[inline] fn io_task_spawner(&self) -> impl TaskSpawner { @@ -181,7 +181,7 @@ impl LoadState for OpEthApi where Self: Send + Sync, N: FullNodeComponents, - Eth: TransactionBuilder::TransactionResponse>, + Eth: TransactionCompat::TransactionResponse>, { #[inline] fn provider(&self) -> impl StateProviderFactory + ChainSpecProvider { @@ -238,7 +238,7 @@ impl BuilderProvider for OpEthApi where Self: Send, N: FullNodeComponents, - Eth: TransactionBuilder::TransactionResponse> + 'static, + Eth: TransactionCompat::TransactionResponse> + 'static, { type Ctx<'a> = &'a EthApiBuilderCtx; diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 81536d29c402..96c7c5864558 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -10,7 +10,7 @@ use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecover use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, RawTransactionForwarder, TransactionBuilder, + EthApiTypes, RawTransactionForwarder, TransactionCompat, }; use reth_rpc_eth_types::EthStateCache; use revm::L1BlockInfo; @@ -122,8 +122,8 @@ pub struct OpTxBuilder { _l1_builders: PhantomData, } -impl::TransactionResponse>> - TransactionBuilder for OpTxBuilder +impl::TransactionResponse>> + TransactionCompat for OpTxBuilder { type Transaction = ::TransactionResponse; From 16cc68ed96ff1e3a7aaf6ccaa8c49550104c21a9 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 12:45:39 +0200 Subject: [PATCH 41/80] Fix docs --- crates/rpc/rpc-types-compat/src/block.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 48552e0e3156..cc504a31ae14 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -52,7 +52,7 @@ pub fn from_block_with_tx_hashes( /// total difficulty to populate its field in the rpc response. /// /// This will populate the `transactions` field with the _full_ -/// [`Transaction`] objects: [`BlockTransactions::Full`] +/// [`TransactionCompat::Transaction`] objects: [`BlockTransactions::Full`] pub fn from_block_full( mut block: BlockWithSenders, total_difficulty: U256, From a0a2f357b1241e258d8f03ff90162cc0f46cfc6f Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 14:54:38 +0200 Subject: [PATCH 42/80] Checkout EthApiTypes::NetworkTypes from emhane/ethapi-types --- Cargo.lock | 126 ++++++------- Cargo.toml | 1 + crates/e2e-test-utils/Cargo.toml | 4 + crates/e2e-test-utils/src/lib.rs | 16 +- crates/e2e-test-utils/src/node.rs | 5 +- crates/e2e-test-utils/src/rpc.rs | 9 +- crates/e2e-test-utils/src/transaction.rs | 23 ++- crates/node/api/Cargo.toml | 1 + crates/node/api/src/lib.rs | 2 + crates/node/api/src/node.rs | 3 +- crates/node/builder/Cargo.toml | 3 + crates/node/builder/src/builder/add_ons.rs | 4 +- crates/node/builder/src/builder/mod.rs | 11 +- crates/node/builder/src/launch/engine.rs | 11 +- crates/node/builder/src/launch/mod.rs | 5 +- crates/node/builder/src/rpc.rs | 72 +++++-- crates/optimism/node/Cargo.toml | 1 + crates/optimism/primitives/Cargo.toml | 2 +- crates/optimism/rpc/Cargo.toml | 4 +- crates/optimism/rpc/src/eth/mod.rs | 26 ++- crates/optimism/rpc/src/eth/pending_block.rs | 3 +- crates/rpc/rpc-builder/Cargo.toml | 1 + crates/rpc/rpc-builder/src/lib.rs | 6 +- crates/rpc/rpc-builder/tests/it/http.rs | 177 +++++++++++++----- crates/rpc/rpc-builder/tests/it/middleware.rs | 3 +- crates/rpc/rpc-eth-api/Cargo.toml | 2 + crates/rpc/rpc-eth-api/src/core.rs | 80 ++++---- crates/rpc/rpc-eth-api/src/filter.rs | 5 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 27 ++- .../rpc-eth-api/src/helpers/transaction.rs | 6 +- crates/rpc/rpc-eth-api/src/helpers/types.rs | 21 ++- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-api/src/pubsub.rs | 3 +- crates/rpc/rpc-testing-util/Cargo.toml | 1 + crates/rpc/rpc-testing-util/src/debug.rs | 15 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 16 +- crates/rpc/rpc/Cargo.toml | 1 + crates/rpc/rpc/src/engine.rs | 17 +- crates/rpc/rpc/src/eth/core.rs | 22 ++- crates/rpc/rpc/src/eth/filter.rs | 2 +- crates/rpc/rpc/src/eth/helpers/block.rs | 2 +- crates/rpc/rpc/src/eth/pubsub.rs | 2 +- crates/rpc/rpc/src/otterscan.rs | 9 +- 43 files changed, 477 insertions(+), 275 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b1bcf4a81549..3b6c1dc1813c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,12 +17,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" - [[package]] name = "aead" version = "0.4.3" @@ -1113,7 +1107,7 @@ dependencies = [ "cc", "cfg-if", "libc", - "miniz_oxide 0.7.4", + "miniz_oxide", "object", "rustc-demangle", ] @@ -1558,9 +1552,9 @@ dependencies = [ [[package]] name = "camino" -version = "1.1.9" +version = "1.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "3054fea8a20d8ff3968d5b22cc27501d2b08dc4decdb31b184323f00c5ef23bb" dependencies = [ "serde", ] @@ -3131,12 +3125,12 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.32" +version = "1.0.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c0596c1eac1f9e04ed902702e9878208b336edc9d6fddc8a48387349bab3666" +checksum = "7f211bbe8e69bbd0cfdea405084f128ae8b4aaa6b0b522fc8f2b009084797920" dependencies = [ "crc32fast", - "miniz_oxide 0.8.0", + "miniz_oxide", ] [[package]] @@ -3403,9 +3397,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.6" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" dependencies = [ "atomic-waker", "bytes", @@ -4082,7 +4076,7 @@ dependencies = [ "socket2 0.5.7", "widestring", "windows-sys 0.48.0", - "winreg", + "winreg 0.50.0", ] [[package]] @@ -4455,9 +4449,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.158" +version = "0.2.156" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" +checksum = "a5f43f184355eefb8d17fc948dbecf6c13be3c141f20d834ae842193a448c72a" [[package]] name = "libloading" @@ -4885,15 +4879,6 @@ dependencies = [ "adler", ] -[[package]] -name = "miniz_oxide" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" -dependencies = [ - "adler2", -] - [[package]] name = "mio" version = "0.8.11" @@ -5256,6 +5241,20 @@ dependencies = [ "serde", ] +[[package]] +name = "op-alloy-network" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3cbfa664a74fe4577a78d1c4bce18fa93be56756730782283df8ff3241c7118" +dependencies = [ + "alloy-consensus", + "alloy-network", + "alloy-primitives", + "alloy-rpc-types-eth", + "op-alloy-consensus", + "op-alloy-rpc-types", +] + [[package]] name = "op-alloy-rpc-types" version = "0.1.5" @@ -6116,9 +6115,9 @@ dependencies = [ [[package]] name = "redox_users" -version = "0.4.6" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" dependencies = [ "getrandom 0.2.15", "libredox", @@ -6181,9 +6180,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.12.7" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8f4955649ef5c38cc7f9e8aa41761d48fb9677197daea9984dc54f56aad5e63" +checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" dependencies = [ "base64 0.22.1", "bytes", @@ -6221,7 +6220,7 @@ dependencies = [ "wasm-streams", "web-sys", "webpki-roots", - "windows-registry", + "winreg 0.52.0", ] [[package]] @@ -6962,6 +6961,7 @@ dependencies = [ "eyre", "futures-util", "jsonrpsee", + "jsonrpsee-types", "reth", "reth-chainspec", "reth-db", @@ -6973,6 +6973,8 @@ dependencies = [ "reth-provider", "reth-rpc", "reth-rpc-layer", + "reth-rpc-types", + "reth-rpc-types-compat", "reth-stages-types", "reth-tokio-util", "reth-tracing", @@ -7697,6 +7699,7 @@ dependencies = [ "reth-payload-builder", "reth-payload-primitives", "reth-provider", + "reth-rpc-eth-api", "reth-tasks", "reth-transaction-pool", ] @@ -7705,6 +7708,7 @@ dependencies = [ name = "reth-node-builder" version = "1.0.5" dependencies = [ + "alloy-network", "aquamarine", "eyre", "fdlimit", @@ -7927,6 +7931,7 @@ dependencies = [ "reth-primitives", "reth-provider", "reth-revm", + "reth-rpc", "reth-rpc-eth-api", "reth-rpc-eth-types", "reth-rpc-types", @@ -8030,11 +8035,13 @@ dependencies = [ "derive_more 1.0.0", "jsonrpsee", "jsonrpsee-types", + "op-alloy-network", "parking_lot 0.12.3", "reth-evm", "reth-evm-optimism", "reth-network-api", "reth-node-api", + "reth-node-builder", "reth-primitives", "reth-provider", "reth-rpc", @@ -8278,6 +8285,7 @@ version = "1.0.5" dependencies = [ "alloy-dyn-abi", "alloy-genesis", + "alloy-network", "alloy-primitives", "alloy-rlp", "async-trait", @@ -8348,6 +8356,7 @@ version = "1.0.5" dependencies = [ "futures", "jsonrpsee", + "jsonrpsee-http-client", "reth-primitives", "reth-rpc-api", "reth-rpc-eth-api", @@ -8441,6 +8450,8 @@ name = "reth-rpc-eth-api" version = "1.0.5" dependencies = [ "alloy-dyn-abi", + "alloy-json-rpc", + "alloy-network", "async-trait", "auto_impl", "dyn-clone", @@ -9214,9 +9225,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.7.2" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04182dffc9091a404e0fc069ea5cd60e5b866c3adf881eff99a32d048242dffa" +checksum = "a88d6d420651b496bdd98684116959239430022a115c1240e6c3993be0b15fba" dependencies = [ "openssl-probe", "rustls-pemfile", @@ -10002,9 +10013,6 @@ name = "sync_wrapper" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" -dependencies = [ - "futures-core", -] [[package]] name = "synstructure" @@ -10784,9 +10792,9 @@ checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" [[package]] name = "unicode-xid" -version = "0.2.5" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" [[package]] name = "universal-hash" @@ -11128,7 +11136,7 @@ checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" dependencies = [ "windows-implement", "windows-interface", - "windows-result 0.1.2", + "windows-result", "windows-targets 0.52.6", ] @@ -11154,17 +11162,6 @@ dependencies = [ "syn 2.0.75", ] -[[package]] -name = "windows-registry" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" -dependencies = [ - "windows-result 0.2.0", - "windows-strings", - "windows-targets 0.52.6", -] - [[package]] name = "windows-result" version = "0.1.2" @@ -11174,25 +11171,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-result" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-strings" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" -dependencies = [ - "windows-result 0.2.0", - "windows-targets 0.52.6", -] - [[package]] name = "windows-sys" version = "0.48.0" @@ -11369,6 +11347,16 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "winreg" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" +dependencies = [ + "cfg-if", + "windows-sys 0.48.0", +] + [[package]] name = "write16" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index 0278ae35ccc7..9b525ff4e4aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -428,6 +428,7 @@ alloy-transport-ws = { version = "0.2.1", default-features = false } # op op-alloy-rpc-types = "0.1" +op-alloy-network = "0.1" # misc aquamarine = "0.5" diff --git a/crates/e2e-test-utils/Cargo.toml b/crates/e2e-test-utils/Cargo.toml index 7bdbfd885e55..1111d44d7067 100644 --- a/crates/e2e-test-utils/Cargo.toml +++ b/crates/e2e-test-utils/Cargo.toml @@ -25,7 +25,11 @@ reth-tokio-util.workspace = true reth-stages-types.workspace = true reth-network-peers.workspace = true reth-node-ethereum.workspace = true +reth-rpc-types.workspace = true +reth-rpc-types-compat.workspace = true +# rpc +jsonrpsee-types.workspace = true jsonrpsee.workspace = true futures-util.workspace = true diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index 132bc36c1579..c351aa06e476 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -2,6 +2,7 @@ use std::sync::Arc; +use alloy_network::Network; use node::NodeTestContext; use reth::{ args::{DiscoveryArgs, NetworkArgs, RpcServerArgs}, @@ -51,9 +52,18 @@ pub async fn setup( ) -> eyre::Result<(Vec>, TaskManager, Wallet)> where N: Default + Node>, - <>>::Components as NodeComponents>>::Network: PeersHandleProvider, - >>::EthApi: - FullEthApiServer + AddDevSigners + EthApiBuilderProvider>, + + N::ComponentsBuilder: NodeComponentsBuilder< + TmpNodeAdapter, + Components: NodeComponents, Network: PeersHandleProvider>, + >, + N::AddOns: NodeAddOns< + Adapter, + EthApi: FullEthApiServer< + NetworkTypes: Network, + > + AddDevSigners + + EthApiBuilderProvider>, + >, { let tasks = TaskManager::current(); let exec = tasks.executor(); diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 19f387c7b8b6..681a3bbd176a 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -1,5 +1,6 @@ use std::{marker::PhantomData, pin::Pin}; +use alloy_network::Network; use alloy_rpc_types::BlockNumberOrTag; use eyre::Ok; use futures_util::Future; @@ -14,7 +15,7 @@ use reth::{ types::engine::PayloadStatusEnum, }, }; -use reth_node_builder::{NodeAddOns, NodeTypes}; +use reth_node_builder::{EthApiTypes, NodeAddOns, NodeTypes}; use reth_primitives::{BlockHash, BlockNumber, Bytes, B256}; use reth_stages_types::StageId; use tokio_stream::StreamExt; @@ -92,6 +93,8 @@ where ::ExecutionPayloadV3: From<::BuiltPayload> + PayloadEnvelopeExt, AddOns::EthApi: EthApiSpec + EthTransactions + TraceExt, + ::NetworkTypes: + Network, { let mut chain = Vec::with_capacity(length as usize); for i in 0..length { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index b301889507a9..085e46c00640 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -1,5 +1,5 @@ use alloy_consensus::TxEnvelope; -use alloy_network::eip2718::Decodable2718; +use alloy_network::{eip2718::Decodable2718, Network}; use reth::{ builder::{rpc::RpcRegistry, FullNodeComponents}, rpc::api::{ @@ -7,16 +7,19 @@ use reth::{ DebugApiServer, }, }; +use reth_node_builder::EthApiTypes; use reth_primitives::{Bytes, B256}; #[allow(missing_debug_implementations)] -pub struct RpcTestContext { +pub struct RpcTestContext { pub inner: RpcRegistry, } -impl RpcTestContext +impl RpcTestContext where + Node: FullNodeComponents, EthApi: EthApiSpec + EthTransactions + TraceExt, + EthApi::NetworkTypes: Network, { /// Injects a raw transaction into the node tx pool via RPC server pub async fn inject_tx(&self, raw_tx: Bytes) -> Result { diff --git a/crates/e2e-test-utils/src/transaction.rs b/crates/e2e-test-utils/src/transaction.rs index e2c6a019b3ac..041ba40d6eb2 100644 --- a/crates/e2e-test-utils/src/transaction.rs +++ b/crates/e2e-test-utils/src/transaction.rs @@ -2,13 +2,11 @@ use alloy_consensus::{ BlobTransactionSidecar, EnvKzgSettings, SidecarBuilder, SimpleCoder, TxEip4844Variant, TxEnvelope, }; -use alloy_network::{eip2718::Encodable2718, EthereumWallet, TransactionBuilder}; +use alloy_network::{eip2718::Encodable2718, Ethereum, EthereumWallet, TransactionBuilder}; use alloy_rpc_types::{TransactionInput, TransactionRequest}; use alloy_signer_local::PrivateKeySigner; use eyre::Ok; -use reth_primitives::{hex, Address, Bytes, U256}; - -use reth_primitives::B256; +use reth_primitives::{hex, Address, Bytes, TxKind, B256, U256}; /// Helper for transaction operations #[derive(Debug)] @@ -38,8 +36,11 @@ impl TransactionTestContext { builder.ingest(b"dummy blob"); let sidecar: BlobTransactionSidecar = builder.build()?; - tx.set_blob_sidecar(sidecar); - tx.set_max_fee_per_blob_gas(15e9 as u128); + >::set_blob_sidecar(&mut tx, sidecar); + >::set_max_fee_per_blob_gas( + &mut tx, + 15e9 as u128, + ); let signed = Self::sign_tx(wallet, tx).await; Ok(signed) @@ -48,7 +49,7 @@ impl TransactionTestContext { /// Signs an arbitrary [`TransactionRequest`] using the provided wallet pub async fn sign_tx(wallet: PrivateKeySigner, tx: TransactionRequest) -> TxEnvelope { let signer = EthereumWallet::from(wallet); - tx.build(&signer).await.unwrap() + >::build(tx, &signer).await.unwrap() } /// Creates a tx with blob sidecar and sign it, returning bytes @@ -70,7 +71,11 @@ impl TransactionTestContext { let l1_block_info = Bytes::from_static(&hex!("7ef9015aa044bae9d41b8380d781187b426c6fe43df5fb2fb57bd4466ef6a701e1f01e015694deaddeaddeaddeaddeaddeaddeaddeaddead000194420000000000000000000000000000000000001580808408f0d18001b90104015d8eb900000000000000000000000000000000000000000000000000000000008057650000000000000000000000000000000000000000000000000000000063d96d10000000000000000000000000000000000000000000000000000000000009f35273d89754a1e0387b89520d989d3be9c37c1f32495a88faf1ea05c61121ab0d1900000000000000000000000000000000000000000000000000000000000000010000000000000000000000002d679b567db6187c0c8323fa982cfb88b74dbcc7000000000000000000000000000000000000000000000000000000000000083400000000000000000000000000000000000000000000000000000000000f4240")); let tx = tx(chain_id, Some(l1_block_info), nonce); let signer = EthereumWallet::from(wallet); - tx.build(&signer).await.unwrap().encoded_2718().into() + >::build(tx, &signer) + .await + .unwrap() + .encoded_2718() + .into() } /// Validates the sidecar of a given tx envelope and returns the versioned hashes @@ -95,7 +100,7 @@ fn tx(chain_id: u64, data: Option, nonce: u64) -> TransactionRequest { TransactionRequest { nonce: Some(nonce), value: Some(U256::from(100)), - to: Some(reth_primitives::TxKind::Call(Address::random())), + to: Some(TxKind::Call(Address::random())), gas: Some(210000), max_fee_per_gas: Some(20e9 as u128), max_priority_fee_per_gas: Some(20e9 as u128), diff --git a/crates/node/api/Cargo.toml b/crates/node/api/Cargo.toml index 46ff6139600f..2b3ce2fa09e3 100644 --- a/crates/node/api/Cargo.toml +++ b/crates/node/api/Cargo.toml @@ -20,4 +20,5 @@ reth-transaction-pool.workspace = true reth-payload-builder.workspace = true reth-payload-primitives.workspace = true reth-tasks.workspace = true +reth-rpc-eth-api.workspace = true reth-network-api.workspace = true diff --git a/crates/node/api/src/lib.rs b/crates/node/api/src/lib.rs index b01a2def0bde..8748fc79d94e 100644 --- a/crates/node/api/src/lib.rs +++ b/crates/node/api/src/lib.rs @@ -26,3 +26,5 @@ pub use node::*; // re-export for convenience pub use reth_provider::FullProvider; + +pub use reth_rpc_eth_api::EthApiTypes; diff --git a/crates/node/api/src/node.rs b/crates/node/api/src/node.rs index 8cd72e91ece0..da6003b120ae 100644 --- a/crates/node/api/src/node.rs +++ b/crates/node/api/src/node.rs @@ -10,6 +10,7 @@ use reth_evm::execute::BlockExecutorProvider; use reth_network_api::FullNetwork; use reth_payload_builder::PayloadBuilderHandle; use reth_provider::FullProvider; +use reth_rpc_eth_api::EthApiTypes; use reth_tasks::TaskExecutor; use reth_transaction_pool::TransactionPool; @@ -155,7 +156,7 @@ pub trait FullNodeComponents: FullNodeTypes + Clone + 'static { pub trait NodeAddOns: Send + Sync + Unpin + Clone + 'static { /// The core `eth` namespace API type to install on the RPC server (see /// `reth_rpc_eth_api::EthApiServer`). - type EthApi: Send + Clone; + type EthApi: EthApiTypes + Send + Clone; } impl NodeAddOns for () { diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index 106337d17b1a..e5290233b8eb 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -55,6 +55,9 @@ reth-engine-service.workspace = true reth-tokio-util.workspace = true reth-engine-tree.workspace = true +## ethereum +alloy-network.workspace = true + ## async futures.workspace = true tokio = { workspace = true, features = [ diff --git a/crates/node/builder/src/builder/add_ons.rs b/crates/node/builder/src/builder/add_ons.rs index 54a776fd69aa..e8eb3b49dc7b 100644 --- a/crates/node/builder/src/builder/add_ons.rs +++ b/crates/node/builder/src/builder/add_ons.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; -use reth_node_api::{FullNodeComponents, NodeAddOns}; +use reth_node_api::{EthApiTypes, FullNodeComponents, NodeAddOns}; use crate::{exex::BoxedLaunchExEx, hooks::NodeHooks, rpc::RpcHooks}; @@ -21,7 +21,7 @@ pub struct AddOns> { /// Captures node specific addons that can be installed on top of the type configured node and are /// required for launching the node, such as RPC. #[derive(Default)] -pub struct RpcAddOns { +pub struct RpcAddOns { /// Core `eth` API type to install on the RPC server, configured w.r.t. network. pub _eth_api: PhantomData, /// Additional RPC hooks. diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index f63f0c3a6705..09867f9bf84c 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -328,7 +328,11 @@ where >>::Components, > > - + FullEthApiServer + + FullEthApiServer< + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::Transaction + >, + > + AddDevSigners >, { @@ -474,8 +478,9 @@ where AO: NodeAddOns< NodeAdapter, CB::Components>, EthApi: EthApiBuilderProvider, CB::Components>> - + FullEthApiServer - + AddDevSigners, + + FullEthApiServer< + NetworkTypes: alloy_network::Network, + > + AddDevSigners, >, { /// Launches the node with the [`DefaultNodeLauncher`] that sets up engine API consensus and rpc diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index 4d2ed714c2b5..39b0ee3c318a 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -34,13 +34,11 @@ use tokio::sync::{mpsc::unbounded_channel, oneshot}; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::{ - components::NodeComponents, hooks::NodeHooks, - launch::{LaunchContext, LaunchNode}, rpc::{launch_rpc_servers, EthApiBuilderProvider}, setup::build_networked_pipeline, - AddOns, ExExLauncher, FullNode, NodeAdapter, NodeBuilderWithComponents, NodeComponentsBuilder, - NodeHandle, NodeTypesAdapter, + AddOns, ExExLauncher, FullNode, LaunchContext, LaunchNode, NodeAdapter, + NodeBuilderWithComponents, NodeComponents, NodeComponentsBuilder, NodeHandle, NodeTypesAdapter, }; /// The engine node launcher. @@ -64,8 +62,9 @@ where AO: NodeAddOns< NodeAdapter, EthApi: EthApiBuilderProvider> - + FullEthApiServer - + AddDevSigners, + + FullEthApiServer< + NetworkTypes: alloy_network::Network, + > + AddDevSigners, >, { type Node = NodeHandle, AO>; diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 60b7dc6d795b..4e201db17d49 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -106,8 +106,9 @@ where AO: NodeAddOns< NodeAdapter, EthApi: EthApiBuilderProvider> - + FullEthApiServer - + AddDevSigners, + + FullEthApiServer< + NetworkTypes: alloy_network::Network, + > + AddDevSigners, >, { type Node = NodeHandle, AO>; diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 920882703a84..123eae88e727 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -9,7 +9,10 @@ use futures::TryFutureExt; use reth_node_api::{BuilderProvider, FullNodeComponents}; use reth_node_core::{ node_config::NodeConfig, - rpc::{api::EngineApiServer, eth::FullEthApiServer}, + rpc::{ + api::EngineApiServer, + eth::{EthApiTypes, FullEthApiServer}, + }, }; use reth_payload_builder::PayloadBuilderHandle; use reth_rpc_builder::{ @@ -42,13 +45,21 @@ pub struct RpcHooks { pub extend_rpc_modules: Box>, } -impl Default for RpcHooks { +impl Default for RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn default() -> Self { Self { on_rpc_started: Box::<()>::default(), extend_rpc_modules: Box::<()>::default() } } } -impl RpcHooks { +impl RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ /// Sets the hook that is run once the rpc server is started. pub(crate) fn set_on_rpc_started(&mut self, hook: F) -> &mut Self where @@ -88,7 +99,11 @@ impl RpcHooks { } } -impl fmt::Debug for RpcHooks { +impl fmt::Debug for RpcHooks +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RpcHooks") .field("on_rpc_started", &"...") @@ -98,7 +113,7 @@ impl fmt::Debug for RpcHooks { } /// Event hook that is called once the rpc server is started. -pub trait OnRpcStarted: Send { +pub trait OnRpcStarted: Send { /// The hook that is called once the rpc server is started. fn on_rpc_started( self: Box, @@ -111,6 +126,7 @@ impl OnRpcStarted for F where F: FnOnce(RpcContext<'_, Node, EthApi>, RethRpcServerHandles) -> eyre::Result<()> + Send, Node: FullNodeComponents, + EthApi: EthApiTypes, { fn on_rpc_started( self: Box, @@ -121,7 +137,11 @@ where } } -impl OnRpcStarted for () { +impl OnRpcStarted for () +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn on_rpc_started( self: Box, _: RpcContext<'_, Node, EthApi>, @@ -132,7 +152,7 @@ impl OnRpcStarted for () { } /// Event hook that is called when the rpc server is started. -pub trait ExtendRpcModules: Send { +pub trait ExtendRpcModules: Send { /// The hook that is called once the rpc server is started. fn extend_rpc_modules(self: Box, ctx: RpcContext<'_, Node, EthApi>) -> eyre::Result<()>; } @@ -141,13 +161,18 @@ impl ExtendRpcModules for F where F: FnOnce(RpcContext<'_, Node, EthApi>) -> eyre::Result<()> + Send, Node: FullNodeComponents, + EthApi: EthApiTypes, { fn extend_rpc_modules(self: Box, ctx: RpcContext<'_, Node, EthApi>) -> eyre::Result<()> { (*self)(ctx) } } -impl ExtendRpcModules for () { +impl ExtendRpcModules for () +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn extend_rpc_modules(self: Box, _: RpcContext<'_, Node, EthApi>) -> eyre::Result<()> { Ok(()) } @@ -156,7 +181,7 @@ impl ExtendRpcModules for () { /// Helper wrapper type to encapsulate the [`RpcRegistryInner`] over components trait. #[derive(Debug, Clone)] #[allow(clippy::type_complexity)] -pub struct RpcRegistry { +pub struct RpcRegistry { pub(crate) registry: RpcRegistryInner< Node::Provider, Node::Pool, @@ -167,7 +192,11 @@ pub struct RpcRegistry { >, } -impl Deref for RpcRegistry { +impl Deref for RpcRegistry +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ type Target = RpcRegistryInner< Node::Provider, Node::Pool, @@ -182,7 +211,11 @@ impl Deref for RpcRegistry { } } -impl DerefMut for RpcRegistry { +impl DerefMut for RpcRegistry +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ fn deref_mut(&mut self) -> &mut Self::Target { &mut self.registry } @@ -196,7 +229,7 @@ impl DerefMut for RpcRegistry { /// transport modules [`TransportRpcModules`] as well as configured authenticated methods /// [`AuthRpcModule`]. #[allow(missing_debug_implementations)] -pub struct RpcContext<'a, Node: FullNodeComponents, EthApi> { +pub struct RpcContext<'a, Node: FullNodeComponents, EthApi: EthApiTypes> { /// The node components. pub(crate) node: Node, @@ -218,7 +251,11 @@ pub struct RpcContext<'a, Node: FullNodeComponents, EthApi> { pub auth_module: &'a mut AuthRpcModule, } -impl<'a, Node: FullNodeComponents, EthApi> RpcContext<'a, Node, EthApi> { +impl<'a, Node, EthApi> RpcContext<'a, Node, EthApi> +where + Node: FullNodeComponents, + EthApi: EthApiTypes, +{ /// Returns the config of the node. pub const fn config(&self) -> &NodeConfig { self.config @@ -259,9 +296,12 @@ pub async fn launch_rpc_servers( add_ons: RpcAddOns, ) -> eyre::Result<(RethRpcServerHandles, RpcRegistry)> where - EthApi: EthApiBuilderProvider + FullEthApiServer, Node: FullNodeComponents + Clone, Engine: EngineApiServer, + EthApi: EthApiBuilderProvider + + FullEthApiServer< + NetworkTypes: alloy_network::Network, + >, { let auth_config = config.rpc.auth_server_config(jwt_secret)?; let module_config = config.rpc.transport_rpc_module_config(); @@ -333,7 +373,7 @@ where } /// Provides builder for the core `eth` API type. -pub trait EthApiBuilderProvider: BuilderProvider { +pub trait EthApiBuilderProvider: BuilderProvider + EthApiTypes { /// Returns the eth api builder. #[allow(clippy::type_complexity)] fn eth_api_builder() -> Box) -> Self + Send>; @@ -342,7 +382,7 @@ pub trait EthApiBuilderProvider: BuilderProvider { impl EthApiBuilderProvider for F where N: FullNodeComponents, - for<'a> F: BuilderProvider = &'a EthApiBuilderCtx>, + for<'a> F: BuilderProvider = &'a EthApiBuilderCtx> + EthApiTypes, { fn eth_api_builder() -> Box) -> Self + Send> { F::builder() diff --git a/crates/optimism/node/Cargo.toml b/crates/optimism/node/Cargo.toml index 52b622e22eca..52c436ecb16c 100644 --- a/crates/optimism/node/Cargo.toml +++ b/crates/optimism/node/Cargo.toml @@ -36,6 +36,7 @@ reth-discv5.workspace = true reth-rpc-eth-types.workspace = true reth-rpc-eth-api.workspace = true reth-optimism-rpc.workspace = true +reth-rpc.workspace = true # async async-trait.workspace = true diff --git a/crates/optimism/primitives/Cargo.toml b/crates/optimism/primitives/Cargo.toml index 0acd2f1ebdca..262cb5881504 100644 --- a/crates/optimism/primitives/Cargo.toml +++ b/crates/optimism/primitives/Cargo.toml @@ -9,4 +9,4 @@ repository.workspace = true description = "OP primitive types" [lints] -workspace = true \ No newline at end of file +workspace = true diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index e5c2bede42dd..2223bac0b9bb 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -26,9 +26,11 @@ reth-transaction-pool.workspace = true reth-rpc.workspace = true reth-node-api.workspace = true reth-network-api.workspace = true +reth-node-builder.workspace = true # ethereum alloy-primitives.workspace = true +op-alloy-network.workspace = true revm.workspace = true # async @@ -59,5 +61,5 @@ optimism = [ "reth-primitives/optimism", "reth-provider/optimism", "reth-rpc-eth-api/optimism", - "revm/optimism" + "revm/optimism", ] \ No newline at end of file diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index d36f9a3b8cfc..ebe64cd532a3 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -11,9 +11,11 @@ use std::{fmt, sync::Arc}; use alloy_primitives::U256; use derive_more::Deref; +use op_alloy_network::Optimism; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; use reth_node_api::{BuilderProvider, FullNodeComponents, FullNodeTypes}; +use reth_node_builder::EthApiBuilderCtx; use reth_provider::{ BlockIdReader, BlockNumReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider, StageCheckpointReader, StateProviderFactory, @@ -21,15 +23,15 @@ use reth_provider::{ use reth_rpc::eth::{core::EthApiInner, DevSigner}; use reth_rpc_eth_api::{ helpers::{ - AddDevSigners, EthApiSpec, EthFees, EthState, LoadBlock, LoadFee, LoadState, SpawnBlocking, - Trace, + AddDevSigners, EthApiSpec, EthFees, EthSigner, EthState, LoadBlock, LoadFee, LoadState, + SpawnBlocking, Trace, }, EthApiTypes, }; use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle}; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, - TaskExecutor, TaskSpawner, + TaskSpawner, }; use reth_transaction_pool::TransactionPool; @@ -43,16 +45,6 @@ pub type EthApiNodeBackend = EthApiInner< ::Evm, >; -/// Adapter for [`EthApiBuilderCtx`]. -pub type EthApiBuilderCtx = reth_rpc_eth_types::EthApiBuilderCtx< - ::Provider, - ::Pool, - ::Evm, - ::Network, - TaskExecutor, - ::Provider, ->; - /// OP-Reth `Eth` API implementation. /// /// This type provides the functionality for handling `eth_` related requests. @@ -65,6 +57,7 @@ pub type EthApiBuilderCtx = reth_rpc_eth_types::EthApiBuilderCtx< /// all the `Eth` helper traits and prerequisite traits. #[derive(Clone, Deref)] pub struct OpEthApi { + #[deref] inner: Arc>, } @@ -101,10 +94,12 @@ where N: FullNodeComponents, { type Error = OpEthApiError; + type NetworkTypes = Optimism; } impl EthApiSpec for OpEthApi where + Self: Send + Sync, N: FullNodeComponents, { #[inline] @@ -123,7 +118,7 @@ where } #[inline] - fn signers(&self) -> &parking_lot::RwLock>> { + fn signers(&self) -> &parking_lot::RwLock>> { self.inner.signers() } } @@ -233,6 +228,7 @@ impl AddDevSigners for OpEthApi { impl BuilderProvider for OpEthApi where + Self: Send, N: FullNodeComponents, { type Ctx<'a> = &'a EthApiBuilderCtx; @@ -243,7 +239,7 @@ where } impl fmt::Debug for OpEthApi { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OpEthApi").finish_non_exhaustive() } } diff --git a/crates/optimism/rpc/src/eth/pending_block.rs b/crates/optimism/rpc/src/eth/pending_block.rs index 0a66fb6230fa..6b345e9698cf 100644 --- a/crates/optimism/rpc/src/eth/pending_block.rs +++ b/crates/optimism/rpc/src/eth/pending_block.rs @@ -1,6 +1,5 @@ //! Loads OP pending block for a RPC response. -use crate::OpEthApi; use reth_evm::ConfigureEvm; use reth_node_api::FullNodeComponents; use reth_primitives::{ @@ -17,6 +16,8 @@ use reth_rpc_eth_api::{ use reth_rpc_eth_types::{EthApiError, PendingBlock}; use reth_transaction_pool::TransactionPool; +use crate::OpEthApi; + impl LoadPendingBlock for OpEthApi where Self: SpawnBlocking, diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index d410268a2df2..e1b7c182353f 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -27,6 +27,7 @@ reth-tasks = { workspace = true, features = ["rayon"] } reth-transaction-pool.workspace = true reth-evm.workspace = true reth-engine-primitives.workspace = true +reth-rpc-types.workspace = true # rpc/net jsonrpsee = { workspace = true, features = ["server"] } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index d3346bcdc185..a3c9edbc7965 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -805,7 +805,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_eth(&mut self) -> &mut Self where - EthApi: EthApiServer, + EthApi: EthApiServer, { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); @@ -819,7 +819,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: EthApiServer + TraceExt, + EthApi: EthApiServer + TraceExt, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -919,7 +919,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn otterscan_api(&self) -> OtterscanApi where - EthApi: EthApiServer, + EthApi: EthApiServer, { let eth_api = self.eth_api().clone(); OtterscanApi::new(eth_api) diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index 9a858d5a4751..2b65bc19a8db 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -116,20 +116,21 @@ async fn test_filter_calls(client: &C) where C: ClientT + SubscriptionClientT + Sync, { - EthFilterApiClient::new_filter(client, Filter::default()).await.unwrap(); - EthFilterApiClient::new_pending_transaction_filter(client, None).await.unwrap(); - EthFilterApiClient::new_pending_transaction_filter( + EthFilterApiClient::::new_filter(client, Filter::default()).await.unwrap(); + EthFilterApiClient::::new_pending_transaction_filter(client, None).await.unwrap(); + EthFilterApiClient::::new_pending_transaction_filter( client, Some(PendingTransactionFilterKind::Full), ) .await .unwrap(); - let id = EthFilterApiClient::new_block_filter(client).await.unwrap(); - EthFilterApiClient::filter_changes(client, id.clone()).await.unwrap(); - EthFilterApiClient::logs(client, Filter::default()).await.unwrap(); - let id = EthFilterApiClient::new_filter(client, Filter::default()).await.unwrap(); - EthFilterApiClient::filter_logs(client, id.clone()).await.unwrap(); - EthFilterApiClient::uninstall_filter(client, id).await.unwrap(); + let id = EthFilterApiClient::::new_block_filter(client).await.unwrap(); + EthFilterApiClient::::filter_changes(client, id.clone()).await.unwrap(); + EthFilterApiClient::::logs(client, Filter::default()).await.unwrap(); + let id = + EthFilterApiClient::::new_filter(client, Filter::default()).await.unwrap(); + EthFilterApiClient::::filter_logs(client, id.clone()).await.unwrap(); + EthFilterApiClient::::uninstall_filter(client, id).await.unwrap(); } async fn test_basic_admin_calls(client: &C) @@ -172,60 +173,136 @@ where .unwrap(); // Implemented - EthApiClient::protocol_version(client).await.unwrap(); - EthApiClient::chain_id(client).await.unwrap(); - EthApiClient::accounts(client).await.unwrap(); - EthApiClient::get_account(client, address, block_number.into()).await.unwrap(); - EthApiClient::block_number(client).await.unwrap(); - EthApiClient::get_code(client, address, None).await.unwrap(); - EthApiClient::send_raw_transaction(client, tx).await.unwrap(); - EthApiClient::fee_history(client, U64::from(0), block_number, None).await.unwrap(); - EthApiClient::balance(client, address, None).await.unwrap(); - EthApiClient::transaction_count(client, address, None).await.unwrap(); - EthApiClient::storage_at(client, address, U256::default().into(), None).await.unwrap(); - EthApiClient::block_by_hash(client, hash, false).await.unwrap(); - EthApiClient::block_by_number(client, block_number, false).await.unwrap(); - EthApiClient::block_transaction_count_by_number(client, block_number).await.unwrap(); - EthApiClient::block_transaction_count_by_hash(client, hash).await.unwrap(); - EthApiClient::block_uncles_count_by_hash(client, hash).await.unwrap(); - EthApiClient::block_uncles_count_by_number(client, block_number).await.unwrap(); - EthApiClient::uncle_by_block_hash_and_index(client, hash, index).await.unwrap(); - EthApiClient::uncle_by_block_number_and_index(client, block_number, index).await.unwrap(); - EthApiClient::sign(client, address, bytes.clone()).await.unwrap_err(); - EthApiClient::sign_typed_data(client, address, typed_data).await.unwrap_err(); - EthApiClient::transaction_by_hash(client, tx_hash).await.unwrap(); - EthApiClient::transaction_by_block_hash_and_index(client, hash, index).await.unwrap(); - EthApiClient::transaction_by_block_number_and_index(client, block_number, index).await.unwrap(); - EthApiClient::create_access_list(client, call_request.clone(), Some(block_number.into())) + EthApiClient::::protocol_version(client).await.unwrap(); + EthApiClient::::chain_id(client).await.unwrap(); + EthApiClient::::accounts(client).await.unwrap(); + EthApiClient::::get_account(client, address, block_number.into()) .await .unwrap(); - EthApiClient::estimate_gas(client, call_request.clone(), Some(block_number.into()), None) + EthApiClient::::block_number(client).await.unwrap(); + EthApiClient::::get_code(client, address, None).await.unwrap(); + EthApiClient::::send_raw_transaction(client, tx).await.unwrap(); + EthApiClient::::fee_history(client, U64::from(0), block_number, None) .await .unwrap(); - EthApiClient::call(client, call_request.clone(), Some(block_number.into()), None, None) + EthApiClient::::balance(client, address, None).await.unwrap(); + EthApiClient::::transaction_count(client, address, None).await.unwrap(); + EthApiClient::::storage_at( + client, + address, + U256::default().into(), + None, + ) + .await + .unwrap(); + EthApiClient::::block_by_hash(client, hash, false).await.unwrap(); + EthApiClient::::block_by_number(client, block_number, false) + .await + .unwrap(); + EthApiClient::::block_transaction_count_by_number(client, block_number) + .await + .unwrap(); + EthApiClient::::block_transaction_count_by_hash(client, hash) + .await + .unwrap(); + EthApiClient::::block_uncles_count_by_hash(client, hash).await.unwrap(); + EthApiClient::::block_uncles_count_by_number(client, block_number) .await .unwrap(); - EthApiClient::syncing(client).await.unwrap(); - EthApiClient::send_transaction(client, transaction_request).await.unwrap_err(); - EthApiClient::hashrate(client).await.unwrap(); - EthApiClient::submit_hashrate(client, U256::default(), B256::default()).await.unwrap(); - EthApiClient::gas_price(client).await.unwrap_err(); - EthApiClient::max_priority_fee_per_gas(client).await.unwrap_err(); - EthApiClient::get_proof(client, address, vec![], None).await.unwrap(); + EthApiClient::::uncle_by_block_hash_and_index(client, hash, index) + .await + .unwrap(); + EthApiClient::::uncle_by_block_number_and_index( + client, + block_number, + index, + ) + .await + .unwrap(); + EthApiClient::::sign(client, address, bytes.clone()).await.unwrap_err(); + EthApiClient::::sign_typed_data(client, address, typed_data) + .await + .unwrap_err(); + EthApiClient::::transaction_by_hash(client, tx_hash).await.unwrap(); + EthApiClient::::transaction_by_block_hash_and_index( + client, hash, index, + ) + .await + .unwrap(); + EthApiClient::::transaction_by_block_number_and_index( + client, + block_number, + index, + ) + .await + .unwrap(); + EthApiClient::::create_access_list( + client, + call_request.clone(), + Some(block_number.into()), + ) + .await + .unwrap(); + EthApiClient::::estimate_gas( + client, + call_request.clone(), + Some(block_number.into()), + None, + ) + .await + .unwrap(); + EthApiClient::::call( + client, + call_request.clone(), + Some(block_number.into()), + None, + None, + ) + .await + .unwrap(); + EthApiClient::::syncing(client).await.unwrap(); + EthApiClient::::send_transaction(client, transaction_request) + .await + .unwrap_err(); + EthApiClient::::hashrate(client).await.unwrap(); + EthApiClient::::submit_hashrate( + client, + U256::default(), + B256::default(), + ) + .await + .unwrap(); + EthApiClient::::gas_price(client).await.unwrap_err(); + EthApiClient::::max_priority_fee_per_gas(client).await.unwrap_err(); + EthApiClient::::get_proof(client, address, vec![], None).await.unwrap(); // Unimplemented - assert!(is_unimplemented(EthApiClient::author(client).await.err().unwrap())); - assert!(is_unimplemented(EthApiClient::is_mining(client).await.err().unwrap())); - assert!(is_unimplemented(EthApiClient::get_work(client).await.err().unwrap())); assert!(is_unimplemented( - EthApiClient::submit_work(client, B64::default(), B256::default(), B256::default()) + EthApiClient::::author(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::is_mining(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::get_work(client).await.err().unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::submit_work( + client, + B64::default(), + B256::default(), + B256::default() + ) + .await + .err() + .unwrap() + )); + assert!(is_unimplemented( + EthApiClient::::sign_transaction(client, call_request.clone()) .await .err() .unwrap() )); - assert!(is_unimplemented( - EthApiClient::sign_transaction(client, call_request.clone()).await.err().unwrap() - )); } async fn test_basic_debug_calls(client: &C) diff --git a/crates/rpc/rpc-builder/tests/it/middleware.rs b/crates/rpc/rpc-builder/tests/it/middleware.rs index 59cc86d4dc86..6641157e9f35 100644 --- a/crates/rpc/rpc-builder/tests/it/middleware.rs +++ b/crates/rpc/rpc-builder/tests/it/middleware.rs @@ -8,6 +8,7 @@ use reth_rpc::EthApi; use reth_rpc_builder::{RpcServerConfig, TransportRpcModuleConfig}; use reth_rpc_eth_api::EthApiClient; use reth_rpc_server_types::RpcModuleSelection; +use reth_rpc_types::{RichBlock, Transaction}; use std::{ future::Future, pin::Pin, @@ -74,7 +75,7 @@ async fn test_rpc_middleware() { .unwrap(); let client = handle.http_client().unwrap(); - EthApiClient::protocol_version(&client).await.unwrap(); + EthApiClient::::protocol_version(&client).await.unwrap(); let count = mylayer.count.load(Ordering::Relaxed); assert_eq!(count, 1); } diff --git a/crates/rpc/rpc-eth-api/Cargo.toml b/crates/rpc/rpc-eth-api/Cargo.toml index 5cd79c27c6fc..bcb6bcf7baac 100644 --- a/crates/rpc/rpc-eth-api/Cargo.toml +++ b/crates/rpc/rpc-eth-api/Cargo.toml @@ -33,6 +33,8 @@ reth-network-api.workspace = true # ethereum alloy-dyn-abi = { workspace = true, features = ["eip712"] } +alloy-network.workspace = true +alloy-json-rpc.workspace = true # rpc jsonrpsee = { workspace = true, features = ["server", "macros"] } diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 1a1e914850f7..828756ad391c 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -1,11 +1,8 @@ //! Implementation of the [`jsonrpsee`] generated [`EthApiServer`] trait. Handles RPC requests for //! the `eth_` namespace. -use crate::helpers::{ - transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, - EthTransactions, FullEthApi, -}; use alloy_dyn_abi::TypedData; +use alloy_json_rpc::RpcObject; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::{ transaction::AccessListResult, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, @@ -16,21 +13,40 @@ use reth_rpc_types::{ simulate::{SimBlock, SimulatedBlock}, state::{EvmOverrides, StateOverride}, AnyTransactionReceipt, BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, - FeeHistory, Header, Index, RichBlock, StateContext, SyncStatus, Transaction, - TransactionRequest, Work, + FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; use tracing::trace; +use crate::{ + helpers::{ + transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, + EthTransactions, FullEthApi, + }, + Block, Transaction, +}; + /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. -pub trait FullEthApiServer: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +pub trait FullEthApiServer: + EthApiServer, Block> + + FullEthApi + + UpdateRawTxForwarder + + Clone +{ +} -impl FullEthApiServer for T where T: EthApiServer + FullEthApi + UpdateRawTxForwarder + Clone {} +impl FullEthApiServer for T where + T: EthApiServer, Block> + + FullEthApi + + UpdateRawTxForwarder + + Clone +{ +} /// Eth rpc interface: #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthApi { +pub trait EthApi { /// Returns the protocol version encoded as a string. #[method(name = "protocolVersion")] async fn protocol_version(&self) -> RpcResult; @@ -57,15 +73,11 @@ pub trait EthApi { /// Returns information about a block by hash. #[method(name = "getBlockByHash")] - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>; + async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult>; /// Returns information about a block by number. #[method(name = "getBlockByNumber")] - async fn block_by_number( - &self, - number: BlockNumberOrTag, - full: bool, - ) -> RpcResult>; + async fn block_by_number(&self, number: BlockNumberOrTag, full: bool) -> RpcResult>; /// Returns the number of transactions in a block from a block matching the given block hash. #[method(name = "getBlockTransactionCountByHash")] @@ -98,11 +110,8 @@ pub trait EthApi { /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockHashAndIndex")] - async fn uncle_by_block_hash_and_index( - &self, - hash: B256, - index: Index, - ) -> RpcResult>; + async fn uncle_by_block_hash_and_index(&self, hash: B256, index: Index) + -> RpcResult>; /// Returns an uncle block of the given block and index. #[method(name = "getUncleByBlockNumberAndIndex")] @@ -110,7 +119,7 @@ pub trait EthApi { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>; + ) -> RpcResult>; /// Returns the EIP-2718 encoded transaction if it exists. /// @@ -120,7 +129,7 @@ pub trait EthApi { /// Returns the information about a transaction requested by transaction hash. #[method(name = "getTransactionByHash")] - async fn transaction_by_hash(&self, hash: B256) -> RpcResult>; + async fn transaction_by_hash(&self, hash: B256) -> RpcResult>; /// Returns information about a raw transaction by block hash and transaction index position. #[method(name = "getRawTransactionByBlockHashAndIndex")] @@ -136,7 +145,7 @@ pub trait EthApi { &self, hash: B256, index: Index, - ) -> RpcResult>; + ) -> RpcResult>; /// Returns information about a raw transaction by block number and transaction index /// position. @@ -153,7 +162,7 @@ pub trait EthApi { &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>; + ) -> RpcResult>; /// Returns the receipt of a transaction by transaction hash. #[method(name = "getTransactionReceipt")] @@ -347,7 +356,7 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer for T +impl EthApiServer, Block> for T where T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, @@ -390,7 +399,11 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> RpcResult> { + async fn block_by_hash( + &self, + hash: B256, + full: bool, + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); Ok(EthBlocks::rpc_block(self, hash.into(), full).await?) } @@ -400,7 +413,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); Ok(EthBlocks::rpc_block(self, number.into(), full).await?) } @@ -449,7 +462,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?) } @@ -459,7 +472,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?) } @@ -471,7 +484,10 @@ where } /// Handler for: `eth_getTransactionByHash` - async fn transaction_by_hash(&self, hash: B256) -> RpcResult> { + async fn transaction_by_hash( + &self, + hash: B256, + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash).await?.map(Into::into)) } @@ -492,7 +508,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await?) @@ -518,7 +534,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) .await?) diff --git a/crates/rpc/rpc-eth-api/src/filter.rs b/crates/rpc/rpc-eth-api/src/filter.rs index da53b577eec5..26c47226cfc3 100644 --- a/crates/rpc/rpc-eth-api/src/filter.rs +++ b/crates/rpc/rpc-eth-api/src/filter.rs @@ -1,12 +1,13 @@ //! `eth_` RPC API for filtering. +use alloy_json_rpc::RpcObject; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_rpc_types::{Filter, FilterChanges, FilterId, Log, PendingTransactionFilterKind}; /// Rpc Interface for poll-based ethereum filter API. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "eth"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "eth"))] -pub trait EthFilterApi { +pub trait EthFilterApi { /// Creates anew filter and returns its id. #[method(name = "newFilter")] async fn new_filter(&self, filter: Filter) -> RpcResult; @@ -24,7 +25,7 @@ pub trait EthFilterApi { /// Returns all filter changes since last poll. #[method(name = "getFilterChanges")] - async fn filter_changes(&self, id: FilterId) -> RpcResult; + async fn filter_changes(&self, id: FilterId) -> RpcResult>; /// Returns all logs matching given filter (in a range 'from' - 'to'). #[method(name = "getFilterLogs")] diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 0058ca021cfc..63eb6e6027ac 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -6,10 +6,10 @@ use futures::Future; use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, TransactionMeta}; use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; -use reth_rpc_types::{AnyTransactionReceipt, Header, Index, RichBlock}; +use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; -use crate::FromEthApiError; +use crate::{Block, FromEthApiError}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; @@ -25,10 +25,7 @@ pub trait EthBlocks: LoadBlock { fn rpc_block_header( &self, block_id: BlockId, - ) -> impl Future, Self::Error>> + Send - where - Self: LoadPendingBlock + SpawnBlocking, - { + ) -> impl Future, Self::Error>> + Send { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.inner.header)) } } @@ -40,10 +37,7 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future, Self::Error>> + Send - where - Self: LoadPendingBlock + SpawnBlocking, - { + ) -> impl Future>, Self::Error>> + Send { async move { let block = match self.block_with_senders(block_id).await? { Some(block) => block, @@ -56,7 +50,7 @@ pub trait EthBlocks: LoadBlock { .ok_or(EthApiError::UnknownBlockNumber)?; let block = from_block(block.unseal(), total_difficulty, full.into(), Some(block_hash)) .map_err(Self::Error::from_eth_err)?; - Ok(Some(block.into())) + Ok(Some(Rich { inner: block, extra_info: Default::default() })) } } @@ -187,7 +181,7 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching @@ -202,10 +196,11 @@ pub trait EthBlocks: LoadBlock { } .unwrap_or_default(); - let uncle = uncles - .into_iter() - .nth(index.into()) - .map(|header| uncle_block_from_header(header).into()); + let index = usize::from(index); + let uncle = uncles.into_iter().nth(index).map(|header| Rich { + inner: uncle_block_from_header(header), + extra_info: Default::default(), + }); Ok(uncle) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index c4387a25537d..38174732aee0 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -19,12 +19,12 @@ use reth_rpc_types::{ EIP1559TransactionRequest, EIP2930TransactionRequest, EIP4844TransactionRequest, LegacyTransactionRequest, }, - AnyTransactionReceipt, Transaction, TransactionRequest, TypedTransactionRequest, + AnyTransactionReceipt, TransactionRequest, TypedTransactionRequest, }; use reth_rpc_types_compat::transaction::from_recovered_with_block_context; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use crate::{FromEthApiError, IntoEthApiError}; +use crate::{FromEthApiError, IntoEthApiError, Transaction}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking, @@ -195,7 +195,7 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future, Self::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, { diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 088f9d9b69e9..2030ea0cf481 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -2,11 +2,15 @@ use std::error::Error; +use alloy_network::{Ethereum, Network}; +use reth_rpc_eth_types::EthApiError; +use reth_rpc_types::Rich; + use crate::{AsEthApiError, FromEthApiError, FromEvmError}; /// Network specific `eth` API types. -pub trait EthApiTypes: Send + Sync { - /// Extension of [`EthApiError`](reth_rpc_eth_types::EthApiError), with network specific errors. +pub trait EthApiTypes: Send + Sync + Clone { + /// Extension of [`EthApiError`], with network specific errors. type Error: Into> + FromEthApiError + AsEthApiError @@ -14,4 +18,17 @@ pub trait EthApiTypes: Send + Sync { + Error + Send + Sync; + /// Blockchain primitive types, specific to network, e.g. block and transaction. + type NetworkTypes: Network; +} + +impl EthApiTypes for () { + type Error = EthApiError; + type NetworkTypes = Ethereum; } + +/// Adapter for network specific transaction type. +pub type Transaction = ::TransactionResponse; + +/// Adapter for network specific block type. +pub type Block = Rich>>; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index c707a94eef4f..39bfb0d629ea 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::EthApiTypes, + types::{Block, EthApiTypes, Transaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc-eth-api/src/pubsub.rs b/crates/rpc/rpc-eth-api/src/pubsub.rs index 8de125152823..8282e6b6af64 100644 --- a/crates/rpc/rpc-eth-api/src/pubsub.rs +++ b/crates/rpc/rpc-eth-api/src/pubsub.rs @@ -1,11 +1,12 @@ //! `eth_` RPC API for pubsub subscription. +use alloy_json_rpc::RpcObject; use jsonrpsee::proc_macros::rpc; use reth_rpc_types::pubsub::{Params, SubscriptionKind}; /// Ethereum pub-sub rpc interface. #[rpc(server, namespace = "eth")] -pub trait EthPubSubApi { +pub trait EthPubSubApi { /// Create an ethereum subscription for the given params #[subscription( name = "subscribe" => "subscription", diff --git a/crates/rpc/rpc-testing-util/Cargo.toml b/crates/rpc/rpc-testing-util/Cargo.toml index 8ab37d1b18d0..19cef0b02de8 100644 --- a/crates/rpc/rpc-testing-util/Cargo.toml +++ b/crates/rpc/rpc-testing-util/Cargo.toml @@ -30,3 +30,4 @@ similar-asserts.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["rt-multi-thread", "macros", "rt"] } reth-rpc-eth-api.workspace = true +jsonrpsee-http-client.workspace = true diff --git a/crates/rpc/rpc-testing-util/src/debug.rs b/crates/rpc/rpc-testing-util/src/debug.rs index c0151e2d1be2..532e9555f8ba 100644 --- a/crates/rpc/rpc-testing-util/src/debug.rs +++ b/crates/rpc/rpc-testing-util/src/debug.rs @@ -1,5 +1,11 @@ //! Helpers for testing debug trace calls. +use std::{ + future::Future, + pin::Pin, + task::{Context, Poll}, +}; + use futures::{Stream, StreamExt}; use jsonrpsee::core::client::Error as RpcError; use reth_primitives::{BlockId, TxHash, B256}; @@ -9,12 +15,7 @@ use reth_rpc_types::{ common::TraceResult, geth::{GethDebugTracerType, GethDebugTracingOptions, GethTrace}, }, - TransactionRequest, -}; -use std::{ - future::Future, - pin::Pin, - task::{Context, Poll}, + RichBlock, Transaction, TransactionRequest, }; const NOOP_TRACER: &str = include_str!("../assets/noop-tracer.js"); @@ -76,7 +77,7 @@ pub trait DebugApiExt { impl DebugApiExt for T where - T: EthApiClient + DebugApiClient + Sync, + T: EthApiClient + DebugApiClient + Sync, { type Provider = T; diff --git a/crates/rpc/rpc-testing-util/tests/it/trace.rs b/crates/rpc/rpc-testing-util/tests/it/trace.rs index 029e9fbbc8b5..4d1234e1ae26 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -1,11 +1,14 @@ +use std::{collections::HashSet, time::Instant}; + use futures::StreamExt; use jsonrpsee::http_client::HttpClientBuilder; +use jsonrpsee_http_client::HttpClient; use reth_rpc_api_testing_util::{debug::DebugApiExt, trace::TraceApiExt, utils::parse_env_url}; use reth_rpc_eth_api::EthApiClient; -use reth_rpc_types::trace::{ - filter::TraceFilter, parity::TraceType, tracerequest::TraceCallRequest, +use reth_rpc_types::{ + trace::{filter::TraceFilter, parity::TraceType, tracerequest::TraceCallRequest}, + RichBlock, Transaction, }; -use std::{collections::HashSet, time::Instant}; /// This is intended to be run locally against a running node. /// @@ -106,7 +109,12 @@ async fn debug_trace_block_entire_chain() { let url = url.unwrap(); let client = HttpClientBuilder::default().build(url).unwrap(); - let current_block: u64 = client.block_number().await.unwrap().try_into().unwrap(); + let current_block: u64 = + >::block_number(&client) + .await + .unwrap() + .try_into() + .unwrap(); let range = 0..=current_block; let mut stream = client.debug_trace_block_buffered_unordered(range, None, 20); let now = Instant::now(); diff --git a/crates/rpc/rpc/Cargo.toml b/crates/rpc/rpc/Cargo.toml index 5661c1f724f2..5c0b1c68657e 100644 --- a/crates/rpc/rpc/Cargo.toml +++ b/crates/rpc/rpc/Cargo.toml @@ -41,6 +41,7 @@ alloy-dyn-abi.workspace = true alloy-rlp.workspace = true alloy-primitives.workspace = true alloy-genesis.workspace = true +alloy-network.workspace = true revm = { workspace = true, features = [ "optional_block_gas_limit", "optional_eip3607", diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 71d4ff94130e..4839f7f83976 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -1,11 +1,13 @@ +use alloy_network::Network; use jsonrpsee::core::RpcResult as Result; use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64}; use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; +use reth_rpc_eth_api::{Block, EthApiTypes, Transaction}; use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, - RichBlock, SyncStatus, TransactionRequest, + SyncStatus, TransactionRequest, }; use tracing_futures::Instrument; @@ -33,8 +35,9 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, - EthFilter: EthFilterApiServer, + Eth: EthApiServer, Block> + EthApiTypes, + Eth::NetworkTypes: Network, + EthFilter: EthFilterApiServer, { /// Handler for: `eth_syncing` fn syncing(&self) -> Result { @@ -77,7 +80,11 @@ where } /// Handler for: `eth_getBlockByHash` - async fn block_by_hash(&self, hash: B256, full: bool) -> Result> { + async fn block_by_hash( + &self, + hash: B256, + full: bool, + ) -> Result>> { self.eth.block_by_hash(hash, full).instrument(engine_span!()).await } @@ -86,7 +93,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> Result> { + ) -> Result>> { self.eth.block_by_number(number, full).instrument(engine_span!()).await } diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 231b6a72dbfd..75a6785e76ba 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -3,6 +3,7 @@ use std::sync::Arc; +use alloy_network::Ethereum; use derive_more::Deref; use reth_node_api::{BuilderProvider, FullNodeComponents}; use reth_primitives::{BlockNumberOrTag, U256}; @@ -36,6 +37,12 @@ pub struct EthApi { pub(super) inner: Arc>, } +impl Clone for EthApi { + fn clone(&self) -> Self { + Self { inner: self.inner.clone() } + } +} + impl EthApi where Provider: BlockReaderIdExt, @@ -119,6 +126,7 @@ where Self: Send + Sync, { type Error = EthApiError; + type NetworkTypes = Ethereum; } impl std::fmt::Debug @@ -129,12 +137,6 @@ impl std::fmt::Debug } } -impl Clone for EthApi { - fn clone(&self) -> Self { - Self { inner: Arc::clone(&self.inner) } - } -} - impl SpawnBlocking for EthApi where @@ -509,7 +511,7 @@ mod tests { /// Invalid block range #[tokio::test] async fn test_fee_history_empty() { - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( &build_test_eth_api(NoopProvider::default()), U64::from(1), BlockNumberOrTag::Latest, @@ -531,7 +533,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(newest_block + 1), newest_block.into(), @@ -554,7 +556,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(1), (newest_block + 1000).into(), @@ -577,7 +579,7 @@ mod tests { let (eth_api, _, _) = prepare_eth_api(newest_block, oldest_block, block_count, MockEthProvider::default()); - let response = as EthApiServer>::fee_history( + let response = as EthApiServer<_, _>>::fee_history( ð_api, U64::from(0), newest_block.into(), diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index ef26a5781de5..a809f76aea39 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -219,7 +219,7 @@ where } #[async_trait] -impl EthFilterApiServer for EthFilter +impl EthFilterApiServer for EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 2ce6c7ed2e93..92f8d5e0344d 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -12,7 +12,7 @@ where Provider: HeaderProvider, { #[inline] - fn provider(&self) -> impl reth_provider::HeaderProvider { + fn provider(&self) -> impl HeaderProvider { self.inner.provider() } } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 426923dc4458..5509f3e933a3 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -68,7 +68,7 @@ impl EthPubSub } #[async_trait::async_trait] -impl EthPubSubApiServer +impl EthPubSubApiServer for EthPubSub where Provider: BlockReader + EvmEnvProvider + Clone + 'static, diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index bf8279719fec..3b13165b091f 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -1,9 +1,10 @@ +use alloy_network::Network; use alloy_primitives::Bytes; use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_primitives::{Address, BlockNumberOrTag, TxHash, B256, U256}; use reth_rpc_api::{EthApiServer, OtterscanServer}; -use reth_rpc_eth_api::helpers::TraceExt; +use reth_rpc_eth_api::{helpers::TraceExt, Block, EthApiTypes, Transaction}; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::result::internal_rpc_err; use reth_rpc_types::{ @@ -59,7 +60,11 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer + TraceExt + 'static, + Eth: EthApiServer, Block> + + EthApiTypes + + TraceExt + + 'static, + Eth::NetworkTypes: Network, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { From 2d6d70266f5dc64af2bdcdf907357cd09af08261 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 21 Aug 2024 20:14:39 +0200 Subject: [PATCH 43/80] Shrink scope of TransactionCompat trait --- .../rpc-eth-api/src/helpers/transaction.rs | 4 +- crates/rpc/rpc-eth-types/src/transaction.rs | 9 ++- crates/rpc/rpc-types-compat/src/block.rs | 4 +- .../rpc-types-compat/src/transaction/mod.rs | 66 +++++++++---------- crates/rpc/rpc/src/eth/filter.rs | 4 +- crates/rpc/rpc/src/eth/pubsub.rs | 4 +- crates/rpc/rpc/src/txpool.rs | 4 +- 7 files changed, 49 insertions(+), 46 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 7977d7e54613..74bc702e1079 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -21,7 +21,7 @@ use reth_rpc_types::{ }, AnyTransactionReceipt, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{transaction::from_recovered_with_block_context, TransactionCompat}; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; use crate::{FromEthApiError, IntoEthApiError, Transaction}; @@ -206,7 +206,7 @@ pub trait EthTransactions: LoadTransaction { let block_number = block.number; let base_fee_per_gas = block.base_fee_per_gas; if let Some(tx) = block.into_transactions_ecrecovered().nth(index) { - return Ok(Some(Self::TransactionCompat::from_recovered_with_block_context( + return Ok(Some(from_recovered_with_block_context::( tx, block_hash, block_number, diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index 08fd42966683..a0883d9165d3 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -4,7 +4,10 @@ use reth_primitives::{TransactionSignedEcRecovered, B256}; use reth_rpc_types::TransactionInfo; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{ + transaction::{from_recovered, from_recovered_with_block_context}, + TransactionCompat, +}; /// Represents from where a transaction was fetched. #[derive(Debug, Clone, Eq, PartialEq)] @@ -39,9 +42,9 @@ impl TransactionSource { /// Conversion into network specific transaction type. pub fn into_transaction(self) -> T::Transaction { match self { - Self::Pool(tx) => T::from_recovered(tx), + Self::Pool(tx) => from_recovered::(tx), Self::Block { transaction, index, block_hash, block_number, base_fee } => { - T::from_recovered_with_block_context( + from_recovered_with_block_context::( transaction, block_hash, block_number, diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index cc504a31ae14..700d7ad3944f 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -6,7 +6,7 @@ use reth_primitives::{ }; use reth_rpc_types::{Block, BlockError, BlockTransactions, BlockTransactionsKind, Header}; -use crate::TransactionCompat; +use crate::{transaction::from_recovered_with_block_context, TransactionCompat}; /// Converts the given primitive block into a [`Block`] response with the given /// [`BlockTransactionsKind`] @@ -72,7 +72,7 @@ pub fn from_block_full( .map(|(idx, (tx, sender))| { let signed_tx_ec_recovered = tx.with_signer(sender); - T::from_recovered_with_block_context( + from_recovered_with_block_context::( signed_tx_ec_recovered, block_hash, block_number, diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index ecd2ce12d1f4..43403f8c4cac 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -12,6 +12,27 @@ use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; use reth_primitives::{BlockNumber, TransactionSigned, TransactionSignedEcRecovered, TxType, B256}; use reth_rpc_types::{Transaction, WithOtherFields}; +/// Create a new rpc transaction result for a mined transaction, using the given block hash, +/// number, and tx index fields to populate the corresponding fields in the rpc result. +/// +/// The block hash, number, and tx index fields should be from the original block where the +/// transaction was mined. +pub fn from_recovered_with_block_context( + tx: TransactionSignedEcRecovered, + block_hash: B256, + block_number: BlockNumber, + base_fee: Option, + tx_index: usize, +) -> T::Transaction { + T::fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) +} + +/// Create a new rpc transaction result for a _pending_ signed transaction, setting block +/// environment related fields to `None`. +pub fn from_recovered(tx: TransactionSignedEcRecovered) -> T::Transaction { + T::fill(tx, None, None, None, None) +} + /// Builds RPC transaction w.r.t. network. pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { /// RPC transaction response type. @@ -52,26 +73,21 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { base_fee: Option, transaction_index: Option, ) -> Self::Transaction; +} - /// Create a new rpc transaction result for a _pending_ signed transaction, setting block - /// environment related fields to `None`. - fn from_recovered(tx: TransactionSignedEcRecovered) -> Self::Transaction { - Self::fill(tx, None, None, None, None) - } +impl TransactionCompat for () { + // this noop impl depends on integration in `reth_rpc_eth_api::EthApiTypes` noop impl, and + // `alloy_network::AnyNetwork` + type Transaction = WithOtherFields; - /// Create a new rpc transaction result for a mined transaction, using the given block hash, - /// number, and tx index fields to populate the corresponding fields in the rpc result. - /// - /// The block hash, number, and tx index fields should be from the original block where the - /// transaction was mined. - fn from_recovered_with_block_context( - tx: TransactionSignedEcRecovered, - block_hash: B256, - block_number: BlockNumber, - base_fee: Option, - tx_index: usize, + fn fill( + _tx: TransactionSignedEcRecovered, + _block_hash: Option, + _block_number: Option, + _base_fee: Option, + _transaction_index: Option, ) -> Self::Transaction { - Self::fill(tx, Some(block_hash), Some(block_number), base_fee, Some(tx_index)) + WithOtherFields::default() } } @@ -125,19 +141,3 @@ pub fn transaction_to_call_request(tx: TransactionSignedEcRecovered) -> Transact sidecar: None, } } - -impl TransactionCompat for () { - // this noop impl depends on integration in `reth_rpc_eth_api::EthApiTypes` noop impl, and - // `alloy_network::AnyNetwork` - type Transaction = WithOtherFields; - - fn fill( - _tx: TransactionSignedEcRecovered, - _block_hash: Option, - _block_number: Option, - _base_fee: Option, - _transaction_index: Option, - ) -> Self::Transaction { - WithOtherFields::default() - } -} diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 9648ffac425c..41a5fc249d75 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -25,7 +25,7 @@ use reth_rpc_types::{ BlockNumHash, Filter, FilterBlockOption, FilterChanges, FilterId, FilteredParams, Log, PendingTransactionFilterKind, Transaction, }; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; use reth_tasks::TaskSpawner; use reth_transaction_pool::{NewSubpoolTransactionStream, PoolTransaction, TransactionPool}; use tokio::{ @@ -596,7 +596,7 @@ where let mut prepared_stream = self.txs_stream.lock().await; while let Ok(tx) = prepared_stream.try_recv() { - pending_txs.push(Eth::from_recovered(tx.transaction.to_recovered_transaction())) + pending_txs.push(from_recovered::(tx.transaction.to_recovered_transaction())) } FilterChanges::Transactions(pending_txs) } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index b4dc1b385b70..d3b57fde3493 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -19,7 +19,7 @@ use reth_rpc_types::{ }, FilteredParams, Header, Log, Transaction, }; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; use reth_tasks::{TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{NewTransactionEvent, TransactionPool}; use serde::Serialize; @@ -137,7 +137,7 @@ where Params::Bool(true) => { // full transaction objects requested let stream = pubsub.full_pending_transaction_stream().map(|tx| { - EthSubscriptionResult::FullTransaction(Box::new(Eth::from_recovered( + EthSubscriptionResult::FullTransaction(Box::new(from_recovered::( tx.transaction.to_recovered_transaction(), ))) }); diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 70f9e4862533..b2e518b9028d 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -8,7 +8,7 @@ use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, Transaction, }; -use reth_rpc_types_compat::TransactionCompat; +use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; use reth_transaction_pool::{AllPoolTransactions, PoolTransaction, TransactionPool}; use tracing::trace; @@ -47,7 +47,7 @@ where content .entry(tx.sender()) .or_default() - .insert(tx.nonce().to_string(), Eth::from_recovered(tx.clone().into())); + .insert(tx.nonce().to_string(), from_recovered::(tx.clone().into())); } let AllPoolTransactions { pending, queued } = self.pool.all_transactions(); From 443e9b247542de7412d963a778b7bae2a544f7bc Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 14:47:43 +0200 Subject: [PATCH 44/80] Rename reth_rpc_eth_api::Transaction to RpcTransaction --- crates/rpc/rpc-eth-api/src/core.rs | 22 +++++++++---------- crates/rpc/rpc-eth-api/src/helpers/block.rs | 8 ++++--- .../rpc-eth-api/src/helpers/transaction.rs | 4 ++-- crates/rpc/rpc-eth-api/src/helpers/types.rs | 8 +++---- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc/src/engine.rs | 8 +++---- crates/rpc/rpc/src/otterscan.rs | 4 ++-- 7 files changed, 29 insertions(+), 27 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 828756ad391c..d66bc91597de 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -22,13 +22,13 @@ use crate::{ transaction::UpdateRawTxForwarder, EthApiSpec, EthBlocks, EthCall, EthFees, EthState, EthTransactions, FullEthApi, }, - Block, Transaction, + RpcBlock, RpcTransaction, }; /// Helper trait, unifies functionality that must be supported to implement all RPC methods for /// server. pub trait FullEthApiServer: - EthApiServer, Block> + EthApiServer, RpcBlock> + FullEthApi + UpdateRawTxForwarder + Clone @@ -36,7 +36,7 @@ pub trait FullEthApiServer: } impl FullEthApiServer for T where - T: EthApiServer, Block> + T: EthApiServer, RpcBlock> + FullEthApi + UpdateRawTxForwarder + Clone @@ -356,7 +356,7 @@ pub trait EthApi { } #[async_trait::async_trait] -impl EthApiServer, Block> for T +impl EthApiServer, RpcBlock> for T where T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, @@ -403,7 +403,7 @@ where &self, hash: B256, full: bool, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); Ok(EthBlocks::rpc_block(self, hash.into(), full).await?) } @@ -413,7 +413,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); Ok(EthBlocks::rpc_block(self, number.into(), full).await?) } @@ -462,7 +462,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, hash.into(), index).await?) } @@ -472,7 +472,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); Ok(EthBlocks::ommer_by_block_and_index(self, number.into(), index).await?) } @@ -487,7 +487,7 @@ where async fn transaction_by_hash( &self, hash: B256, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, "Serving eth_getTransactionByHash"); Ok(EthTransactions::transaction_by_hash(self, hash).await?.map(Into::into)) } @@ -508,7 +508,7 @@ where &self, hash: B256, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, hash.into(), index.into()) .await?) @@ -534,7 +534,7 @@ where &self, number: BlockNumberOrTag, index: Index, - ) -> RpcResult>> { + ) -> RpcResult>> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); Ok(EthTransactions::transaction_by_block_and_tx_index(self, number.into(), index.into()) .await?) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 63eb6e6027ac..9bffb2125b97 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -9,7 +9,7 @@ use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index, Rich}; use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; -use crate::{Block, FromEthApiError}; +use crate::{FromEthApiError, RpcBlock}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; @@ -37,7 +37,8 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, full: bool, - ) -> impl Future>, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send + { async move { let block = match self.block_with_senders(block_id).await? { Some(block) => block, @@ -181,7 +182,8 @@ pub trait EthBlocks: LoadBlock { &self, block_id: BlockId, index: Index, - ) -> impl Future>, Self::Error>> + Send { + ) -> impl Future>, Self::Error>> + Send + { async move { let uncles = if block_id.is_pending() { // Pending block can be fetched directly without need for caching diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 38174732aee0..a52db4658d92 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -24,7 +24,7 @@ use reth_rpc_types::{ use reth_rpc_types_compat::transaction::from_recovered_with_block_context; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use crate::{FromEthApiError, IntoEthApiError, Transaction}; +use crate::{FromEthApiError, IntoEthApiError, RpcTransaction}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, SpawnBlocking, @@ -195,7 +195,7 @@ pub trait EthTransactions: LoadTransaction { &self, block_id: BlockId, index: usize, - ) -> impl Future>, Self::Error>> + Send + ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, { diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/helpers/types.rs index 2030ea0cf481..c04375f54efe 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/types.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/types.rs @@ -4,7 +4,7 @@ use std::error::Error; use alloy_network::{Ethereum, Network}; use reth_rpc_eth_types::EthApiError; -use reth_rpc_types::Rich; +use reth_rpc_types::{Block, Rich, Transaction}; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -19,7 +19,7 @@ pub trait EthApiTypes: Send + Sync + Clone { + Send + Sync; /// Blockchain primitive types, specific to network, e.g. block and transaction. - type NetworkTypes: Network; + type NetworkTypes: Network; } impl EthApiTypes for () { @@ -28,7 +28,7 @@ impl EthApiTypes for () { } /// Adapter for network specific transaction type. -pub type Transaction = ::TransactionResponse; +pub type RpcTransaction = ::TransactionResponse; /// Adapter for network specific block type. -pub type Block = Rich>>; +pub type RpcBlock = Rich>>; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 39bfb0d629ea..4da463091763 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -23,7 +23,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::{Block, EthApiTypes, Transaction}, + types::{EthApiTypes, RpcBlock, RpcTransaction}, }; pub use pubsub::EthPubSubApiServer; diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 4839f7f83976..cbf74e24fbcb 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -4,7 +4,7 @@ use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64 use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; -use reth_rpc_eth_api::{Block, EthApiTypes, Transaction}; +use reth_rpc_eth_api::{EthApiTypes, RpcBlock, RpcTransaction}; use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, SyncStatus, TransactionRequest, @@ -35,7 +35,7 @@ impl EngineEthApi { #[async_trait::async_trait] impl EngineEthApiServer for EngineEthApi where - Eth: EthApiServer, Block> + EthApiTypes, + Eth: EthApiServer, RpcBlock> + EthApiTypes, Eth::NetworkTypes: Network, EthFilter: EthFilterApiServer, { @@ -84,7 +84,7 @@ where &self, hash: B256, full: bool, - ) -> Result>> { + ) -> Result>> { self.eth.block_by_hash(hash, full).instrument(engine_span!()).await } @@ -93,7 +93,7 @@ where &self, number: BlockNumberOrTag, full: bool, - ) -> Result>> { + ) -> Result>> { self.eth.block_by_number(number, full).instrument(engine_span!()).await } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 3b13165b091f..672b32cd7ede 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -4,7 +4,7 @@ use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_primitives::{Address, BlockNumberOrTag, TxHash, B256, U256}; use reth_rpc_api::{EthApiServer, OtterscanServer}; -use reth_rpc_eth_api::{helpers::TraceExt, Block, EthApiTypes, Transaction}; +use reth_rpc_eth_api::{helpers::TraceExt, EthApiTypes, RpcBlock, RpcTransaction}; use reth_rpc_eth_types::EthApiError; use reth_rpc_server_types::result::internal_rpc_err; use reth_rpc_types::{ @@ -60,7 +60,7 @@ impl OtterscanApi { #[async_trait] impl OtterscanServer for OtterscanApi where - Eth: EthApiServer, Block> + Eth: EthApiServer, RpcBlock> + EthApiTypes + TraceExt + 'static, From fe2bf752aae2fc9383f2e6dc5fe89bf293e610c6 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 14:50:22 +0200 Subject: [PATCH 45/80] Move crates/rpc/rpc-eth-api/src/helpers/types.rs up one dir --- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 1 - crates/rpc/rpc-eth-api/src/lib.rs | 6 +++--- crates/rpc/rpc-eth-api/src/{helpers => }/types.rs | 0 3 files changed, 3 insertions(+), 4 deletions(-) rename crates/rpc/rpc-eth-api/src/{helpers => }/types.rs (100%) diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index ecfd63388e3b..4f12b7dac861 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -26,7 +26,6 @@ pub mod spec; pub mod state; pub mod trace; pub mod transaction; -pub mod types; pub use block::{EthBlocks, LoadBlock}; pub use blocking_task::SpawnBlocking; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 4da463091763..c3ea0746a119 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -17,17 +17,17 @@ pub mod core; pub mod filter; pub mod helpers; pub mod pubsub; +pub mod types; pub use bundle::{EthBundleApiServer, EthCallBundleApiServer}; pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::{ error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}, - types::{EthApiTypes, RpcBlock, RpcTransaction}, + transaction::RawTransactionForwarder, }; pub use pubsub::EthPubSubApiServer; - -pub use helpers::transaction::RawTransactionForwarder; +pub use types::{EthApiTypes, RpcBlock, RpcTransaction}; #[cfg(feature = "client")] pub use bundle::{EthBundleApiClient, EthCallBundleApiClient}; diff --git a/crates/rpc/rpc-eth-api/src/helpers/types.rs b/crates/rpc/rpc-eth-api/src/types.rs similarity index 100% rename from crates/rpc/rpc-eth-api/src/helpers/types.rs rename to crates/rpc/rpc-eth-api/src/types.rs From 02b38c7df8954eb374d8b98f70712eb74579f06a Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 14:52:31 +0200 Subject: [PATCH 46/80] Update docs --- crates/rpc/rpc-eth-api/src/types.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index c04375f54efe..b668678d267e 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -1,4 +1,4 @@ -//! Trait for specifying `eth` API types that may be network dependent. +//! Trait for specifying `eth` network dependent API types. use std::error::Error; @@ -19,6 +19,7 @@ pub trait EthApiTypes: Send + Sync + Clone { + Send + Sync; /// Blockchain primitive types, specific to network, e.g. block and transaction. + // todo: remove restriction `reth_rpc_types::Transaction` type NetworkTypes: Network; } From 46bad2e4a40281c60df0cb39ef4511df2d77bedb Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 16:23:56 +0200 Subject: [PATCH 47/80] Fix lint --- crates/optimism/rpc/src/eth/call.rs | 1 - crates/rpc/rpc-eth-api/src/helpers/transaction.rs | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index db7d0589cf22..5018ab129a53 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -1,4 +1,3 @@ -use reth_chainspec::ChainSpec; use reth_evm::ConfigureEvm; use reth_node_api::FullNodeComponents; use reth_primitives::{ diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index a52db4658d92..124da5f31d5b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -188,7 +188,7 @@ pub trait EthTransactions: LoadTransaction { }) } - /// Get [`Transaction`] by [`BlockId`] and index of transaction within that block. + /// Get transaction by [`BlockId`] and index of transaction within that block. /// /// Returns `Ok(None)` if the block does not exist, or index is out of range. fn transaction_by_block_and_tx_index( From 5e0901107cc1d151668a64489cda5d8118385bc1 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 17:24:24 +0200 Subject: [PATCH 48/80] Revert unrelated change --- crates/chainspec/src/api.rs | 3 +-- crates/chainspec/src/constants.rs | 3 +-- crates/chainspec/src/lib.rs | 1 - 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/chainspec/src/api.rs b/crates/chainspec/src/api.rs index acc7ebce8a77..f31b0918e87d 100644 --- a/crates/chainspec/src/api.rs +++ b/crates/chainspec/src/api.rs @@ -1,8 +1,7 @@ +use crate::ChainSpec; use alloy_chains::Chain; use reth_ethereum_forks::{EthereumHardfork, ForkCondition}; -use crate::ChainSpec; - /// Trait representing type configuring a chain spec. pub trait EthChainSpec: Send + Sync + Unpin + 'static { /// Enumw with chain hardforks. diff --git a/crates/chainspec/src/constants.rs b/crates/chainspec/src/constants.rs index f53dc80deb60..c5c6096951c2 100644 --- a/crates/chainspec/src/constants.rs +++ b/crates/chainspec/src/constants.rs @@ -1,6 +1,5 @@ -use alloy_primitives::{address, b256}; - use crate::spec::DepositContract; +use alloy_primitives::{address, b256}; /// Deposit contract address: `0x00000000219ab540356cbb839cbe05303d7705fa` pub(crate) const MAINNET_DEPOSIT_CONTRACT: DepositContract = DepositContract::new( diff --git a/crates/chainspec/src/lib.rs b/crates/chainspec/src/lib.rs index 7e508538d971..26e15edc87dd 100644 --- a/crates/chainspec/src/lib.rs +++ b/crates/chainspec/src/lib.rs @@ -10,7 +10,6 @@ #![cfg_attr(not(feature = "std"), no_std)] pub use alloy_chains::{Chain, ChainKind, NamedChain}; - pub use info::ChainInfo; pub use spec::{ BaseFeeParams, BaseFeeParamsKind, ChainSpec, ChainSpecBuilder, ChainSpecProvider, From 148d4e3533692114a53657b6b68b9bc89f8d8a6e Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 22 Aug 2024 17:24:59 +0200 Subject: [PATCH 49/80] Fix lint --- crates/net/network/src/transactions/mod.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index d180b92e7a3d..9e6bd4efcf61 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -2380,11 +2380,9 @@ mod tests { assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash())); assert!(peer.seen_transactions.contains(eip1559_tx.transaction.hash())); peer.seen_transactions.contains(eip4844_tx.transaction.hash()); - println!("{:?}", propagated.0); // propagate again let propagated = tx_manager.propagate_transactions(propagate); - println!("{:?}", propagated.0); assert!(propagated.0.is_empty()); } } From 07f2e9ff9d655fe754faede2d6c50a4afb74ec89 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 6 Sep 2024 21:10:08 +0200 Subject: [PATCH 50/80] Fix merge conflicts --- Cargo.lock | 2 + crates/node/builder/Cargo.toml | 1 - crates/node/builder/src/builder/mod.rs | 4 +- crates/node/builder/src/launch/engine.rs | 6 +- crates/node/builder/src/launch/mod.rs | 6 +- crates/node/builder/src/rpc.rs | 2 +- crates/rpc/ipc/src/server/connection.rs | 12 +- crates/rpc/ipc/src/server/ipc.rs | 4 +- crates/rpc/ipc/src/stream_codec.rs | 2 +- crates/rpc/rpc-builder/src/auth.rs | 2 +- crates/rpc/rpc-builder/src/cors.rs | 2 +- crates/rpc/rpc-builder/src/error.rs | 2 +- crates/rpc/rpc-builder/src/eth.rs | 14 ++- crates/rpc/rpc-builder/src/lib.rs | 98 ++++++++-------- crates/rpc/rpc-engine-api/src/engine_api.rs | 10 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 6 +- crates/rpc/rpc-eth-api/src/helpers/call.rs | 20 ++-- crates/rpc/rpc-eth-api/src/helpers/error.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 110 +++++++++--------- .../rpc-eth-api/src/helpers/pending_block.rs | 16 +-- crates/rpc/rpc-eth-api/src/helpers/state.rs | 4 +- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 2 +- .../rpc-eth-api/src/helpers/transaction.rs | 29 +++-- crates/rpc/rpc-eth-api/src/types.rs | 6 +- crates/rpc/rpc-eth-types/src/cache/mod.rs | 8 +- crates/rpc/rpc-eth-types/src/fee_history.rs | 6 +- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 10 +- crates/rpc/rpc-eth-types/src/id_provider.rs | 2 +- crates/rpc/rpc-eth-types/src/logs_utils.rs | 2 +- crates/rpc/rpc-eth-types/src/revm_utils.rs | 6 +- crates/rpc/rpc-eth-types/src/transaction.rs | 2 +- crates/rpc/rpc-eth-types/src/utils.rs | 2 +- crates/rpc/rpc-server-types/src/module.rs | 2 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 4 +- crates/rpc/rpc-types-compat/src/block.rs | 2 +- .../rpc-types-compat/src/engine/payload.rs | 6 +- crates/rpc/rpc/src/debug.rs | 24 ++-- crates/rpc/rpc/src/engine.rs | 9 +- crates/rpc/rpc/src/eth/bundle.rs | 6 +- crates/rpc/rpc/src/eth/core.rs | 3 +- crates/rpc/rpc/src/eth/filter.rs | 37 +++--- crates/rpc/rpc/src/eth/helpers/types.rs | 1 - crates/rpc/rpc/src/eth/pubsub.rs | 11 +- crates/rpc/rpc/src/otterscan.rs | 4 +- crates/rpc/rpc/src/reth.rs | 2 +- crates/rpc/rpc/src/trace.rs | 8 +- crates/rpc/rpc/src/txpool.rs | 16 ++- 47 files changed, 291 insertions(+), 244 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6d6c5cff01cb..8b5d7de8b316 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7598,6 +7598,7 @@ dependencies = [ name = "reth-node-builder" version = "1.0.6" dependencies = [ + "alloy-network", "aquamarine", "eyre", "fdlimit", @@ -7959,6 +7960,7 @@ name = "reth-optimism-rpc" version = "1.0.6" dependencies = [ "alloy-primitives", + "alloy-rpc-types", "jsonrpsee-types", "op-alloy-network", "op-alloy-rpc-types", diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index 2638f266629c..01ecfaed5337 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -54,7 +54,6 @@ reth-stages.workspace = true reth-static-file.workspace = true reth-tasks.workspace = true reth-tokio-util.workspace = true -reth-engine-tree.workspace = true reth-rpc-types-compat.workspace = true reth-tracing.workspace = true reth-transaction-pool.workspace = true diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 7f2bba136347..747b0a0df46c 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -488,7 +488,9 @@ where NodeAdapter, CB::Components>, EthApi: EthApiBuilderProvider, CB::Components>> + FullEthApiServer< - TransactionCompat: TransactionCompat>, + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index 7a3967f359a3..aa1f670e73f2 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -30,8 +30,8 @@ use reth_node_core::{ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_provider::providers::BlockchainProvider2; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; -use reth_rpc_types_compat::TransactionCompat; use reth_rpc_types::{engine::ClientVersionV1, WithOtherFields}; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; use reth_tracing::tracing::{debug, error, info}; @@ -70,7 +70,9 @@ where NodeAdapter, EthApi: EthApiBuilderProvider> + FullEthApiServer< - TransactionCompat: TransactionCompat>, + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 56e9aa5b4121..d5b549e99827 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -34,8 +34,8 @@ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_primitives::format_ether; use reth_provider::providers::BlockchainProvider; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; -use reth_rpc_types_compat::TransactionCompat; use reth_rpc_types::{engine::ClientVersionV1, WithOtherFields}; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::TransactionPool; @@ -113,7 +113,9 @@ where NodeAdapter, EthApi: EthApiBuilderProvider> + FullEthApiServer< - TransactionCompat: TransactionCompat>, + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, > + AddDevSigners, >, { diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 2b093e2d953a..332ed2c126f0 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -22,8 +22,8 @@ use reth_rpc_builder::{ RpcModuleBuilder, RpcRegistryInner, RpcServerHandle, TransportRpcModules, }; use reth_rpc_layer::JwtSecret; -use reth_rpc_types_compat::TransactionCompat; use reth_rpc_types::WithOtherFields; +use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; diff --git a/crates/rpc/ipc/src/server/connection.rs b/crates/rpc/ipc/src/server/connection.rs index 5e7497cb9e59..f1f4290d5fa2 100644 --- a/crates/rpc/ipc/src/server/connection.rs +++ b/crates/rpc/ipc/src/server/connection.rs @@ -102,7 +102,7 @@ where if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } // write all responses to the sink @@ -110,10 +110,10 @@ where if let Some(item) = this.items.pop_front() { if let Err(err) = this.conn.as_mut().start_send(item) { tracing::warn!("IPC response failed: {:?}", err); - return Poll::Ready(()) + return Poll::Ready(()); } } else { - break + break; } } @@ -147,7 +147,7 @@ where Err(err) => err.into().to_string(), }; this.items.push_back(item); - continue 'outer + continue 'outer; } Poll::Pending => { this.pending_calls.push(call); @@ -157,14 +157,14 @@ where Some(Err(err)) => { // this can happen if the client closes the connection tracing::debug!("IPC request failed: {:?}", err); - return Poll::Ready(()) + return Poll::Ready(()); } None => return Poll::Ready(()), }, Poll::Pending => { if drained || this.pending_calls.is_empty() { // at this point all things are pending - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/rpc/ipc/src/server/ipc.rs b/crates/rpc/ipc/src/server/ipc.rs index 33ed8d2d5531..9bdd55c44984 100644 --- a/crates/rpc/ipc/src/server/ipc.rs +++ b/crates/rpc/ipc/src/server/ipc.rs @@ -70,7 +70,7 @@ where while let Some(response) = pending_calls.next().await { if let Err(too_large) = batch_response.append(&response) { - return Some(too_large.to_result()) + return Some(too_large.to_result()); } } @@ -151,7 +151,7 @@ where return Some(batch_response_error( Id::Null, reject_too_big_request(max_request_body_size as u32), - )) + )); } // Single request or notification diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index e6e035f1d512..1f2a0e791cc1 100644 --- a/crates/rpc/ipc/src/stream_codec.rs +++ b/crates/rpc/ipc/src/stream_codec.rs @@ -117,7 +117,7 @@ impl tokio_util::codec::Decoder for StreamCodec { return match String::from_utf8(bts.into()) { Ok(val) => Ok(Some(val)), Err(_) => Ok(None), - } + }; } } Ok(None) diff --git a/crates/rpc/rpc-builder/src/auth.rs b/crates/rpc/rpc-builder/src/auth.rs index 25626e4f12d3..849349aa2688 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -304,7 +304,7 @@ impl AuthServerHandle { .build(ipc_endpoint) .await .expect("Failed to create ipc client"), - ) + ); } None } diff --git a/crates/rpc/rpc-builder/src/cors.rs b/crates/rpc/rpc-builder/src/cors.rs index c68cf84942c0..18098a7d1632 100644 --- a/crates/rpc/rpc-builder/src/cors.rs +++ b/crates/rpc/rpc-builder/src/cors.rs @@ -31,7 +31,7 @@ pub(crate) fn create_cors_layer(http_cors_domains: &str) -> Result Self { if io_error.kind() == ErrorKind::AddrInUse { - return Self::AddressAlreadyInUse { kind, error: io_error } + return Self::AddressAlreadyInUse { kind, error: io_error }; } Self::ServerError { kind, error: io_error } } diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index 52eef4870a8f..b07cc3f28116 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use reth_evm::ConfigureEvm; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider, StateProviderFactory}; use reth_rpc::{EthFilter, EthPubSub}; -use reth_rpc_eth_api::EthApiTypes; +use reth_rpc_eth_api::{EthApiTypes, TransactionCompat}; use reth_rpc_eth_types::{ cache::cache_new_blocks_task, EthApiBuilderCtx, EthConfig, EthStateCache, }; @@ -86,7 +86,11 @@ where Network: Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: EthApiTypes + 'static, + EthApi: EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, + > + 'static, { /// Returns a new instance with handlers for `eth` namespace. pub fn build(self) -> EthHandlers { @@ -144,7 +148,11 @@ impl EthFilterApiBuilder { Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - Eth: EthApiTypes + 'static, + Eth: EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, + > + 'static, { EthFilter::new( ctx.provider.clone(), diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 37dab320973f..a56e3a2de276 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -164,15 +164,13 @@ use reth_rpc::{ }; use reth_rpc_api::servers::*; use reth_rpc_eth_api::{ - helpers::{ - Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt, - }, - EthApiServer, EthApiTypes, FullEthApiServer, RawTransactionForwarder, RpcBlock, RpcTransaction, + helpers::{Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt}, + EthApiServer, EthApiTypes, FullEthApiServer, RpcBlock, RpcReceipt, RpcTransaction, TransactionCompat, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; -use reth_rpc_types::WithOtherFields; +use reth_rpc_types::{optimism::Transaction, WithOtherFields}; use reth_tasks::{pool::BlockingTaskGuard, TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{noop::NoopTransactionPool, TransactionPool}; use serde::{Deserialize, Serialize}; @@ -496,7 +494,11 @@ where eth: DynEthApiBuilder, ) -> RpcRegistryInner where - EthApi: EthApiTypes + 'static, + EthApi: EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, + > + 'static, { let Self { provider, pool, network, executor, events, evm_config } = self; RpcRegistryInner::new(provider, pool, network, executor, events, config, evm_config, eth) @@ -644,7 +646,11 @@ where Network: Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypes + 'static, + EthApi: EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, + > + 'static, { /// Creates a new, empty instance. #[allow(clippy::too_many_arguments)] @@ -798,17 +804,22 @@ where Provider: FullRpcProvider + AccountReader + ChangeSetReader, Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypes, + EthApi: EthApiServer< + RpcTransaction, + RpcBlock, + RpcReceipt, + > + EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, + >, { /// Register Eth Namespace /// /// # Panics /// /// If called outside of the tokio runtime. See also [`Self::eth_api`] - pub fn register_eth(&mut self) -> &mut Self - where - EthApi: EthApiServer, RpcBlock, reth_rpc_types::AnyTransactionReceipt>, - { + pub fn register_eth(&mut self) -> &mut Self { let eth_api = self.eth_api().clone(); self.modules.insert(RethRpcModule::Eth, eth_api.into_rpc().into()); self @@ -821,8 +832,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: EthApiServer, RpcBlock, reth_rpc_types::AnyTransactionReceipt> - + TraceExt, + EthApi: TraceExt + EthTransactions, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -836,10 +846,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_debug(&mut self) -> &mut Self where - EthApi: EthApiServer, RpcBlock> - + EthApiSpec - + EthTransactions - + TraceExt, + EthApi: EthApiSpec + EthTransactions + TraceExt, { let debug_api = self.debug_api(); self.modules.insert(RethRpcModule::Debug, debug_api.into_rpc().into()); @@ -853,8 +860,7 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_trace(&mut self) -> &mut Self where - EthApi: EthApiServer, RpcBlock> - + TraceExt, + EthApi: TraceExt, { let trace_api = self.trace_api(); self.modules.insert(RethRpcModule::Trace, trace_api.into_rpc().into()); @@ -870,9 +876,7 @@ where /// If called outside of the tokio runtime. pub fn register_net(&mut self) -> &mut Self where - EthApi: EthApiServer, RpcBlock> - + EthApiSpec - + 'static, + EthApi: EthApiSpec + 'static, { let netapi = self.net_api(); self.modules.insert(RethRpcModule::Net, netapi.into_rpc().into()); @@ -886,15 +890,31 @@ where /// # Panics /// /// If called outside of the tokio runtime. - pub fn register_reth(&mut self) -> &mut Self - where - EthApi: EthApiServer, RpcBlock>, - { + pub fn register_reth(&mut self) -> &mut Self { let rethapi = self.reth_api(); self.modules.insert(RethRpcModule::Reth, rethapi.into_rpc().into()); self } + /// Instantiates `OtterscanApi` + /// + /// # Panics + /// + /// If called outside of the tokio runtime. See also [`Self::eth_api`] + pub fn otterscan_api(&self) -> OtterscanApi { + let eth_api = self.eth_api().clone(); + OtterscanApi::new(eth_api) + } +} + +impl + RpcRegistryInner +where + Provider: FullRpcProvider + AccountReader + ChangeSetReader, + Network: NetworkInfo + Peers + Clone + 'static, + Tasks: TaskSpawner + Clone + 'static, + EthApi: EthApiTypes, +{ /// Instantiates `TraceApi` /// /// # Panics @@ -924,24 +944,6 @@ where EthBundle::new(eth_api, self.blocking_pool_guard.clone()) } - /// Instantiates `OtterscanApi` - /// - /// # Panics - /// - /// If called outside of the tokio runtime. See also [`Self::eth_api`] - pub fn otterscan_api(&self) -> OtterscanApi - where - EthApi: EthApiServer< - WithOtherFields, - reth_rpc_types::Block>, - reth_rpc_types::AnyTransactionReceipt, - > + TraceExt - + EthTransactions, - { - let eth_api = self.eth_api().clone(); - OtterscanApi::new(eth_api) - } - /// Instantiates `DebugApi` /// /// # Panics @@ -1686,7 +1688,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no http transport is configured. pub fn merge_http(&mut self, other: impl Into) -> Result { if let Some(ref mut http) = self.http { - return http.merge(other.into()).map(|_| true) + return http.merge(other.into()).map(|_| true); } Ok(false) } @@ -1698,7 +1700,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no ws transport is configured. pub fn merge_ws(&mut self, other: impl Into) -> Result { if let Some(ref mut ws) = self.ws { - return ws.merge(other.into()).map(|_| true) + return ws.merge(other.into()).map(|_| true); } Ok(false) } @@ -1710,7 +1712,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no ipc transport is configured. pub fn merge_ipc(&mut self, other: impl Into) -> Result { if let Some(ref mut ipc) = self.ipc { - return ipc.merge(other.into()).map(|_| true) + return ipc.merge(other.into()).map(|_| true); } Ok(false) } diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index d22590a3aa08..10c965f451fe 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -465,7 +465,7 @@ where { let len = hashes.len() as u64; if len > MAX_PAYLOAD_BODIES_LIMIT { - return Err(EngineApiError::PayloadRequestTooLarge { len }) + return Err(EngineApiError::PayloadRequestTooLarge { len }); } let mut result = Vec::with_capacity(hashes.len()); @@ -523,7 +523,7 @@ where return Err(EngineApiError::TerminalTD { execution: merge_terminal_td, consensus: terminal_total_difficulty, - }) + }); } self.inner.beacon_consensus.transition_configuration_exchanged(); @@ -533,7 +533,7 @@ where return Ok(TransitionConfiguration { terminal_total_difficulty: merge_terminal_td, ..Default::default() - }) + }); } // Attempt to look up terminal block hash @@ -598,9 +598,9 @@ where // TODO: decide if we want this branch - the FCU INVALID response might be more // useful than the payload attributes INVALID response if fcu_res.is_invalid() { - return Ok(fcu_res) + return Ok(fcu_res); } - return Err(err.into()) + return Err(err.into()); } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 659b7715408f..b0773c32f566 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -84,7 +84,7 @@ pub trait EthBlocks: LoadBlock { return Ok(LoadBlock::provider(self) .pending_block() .map_err(Self::Error::from_eth_err)? - .map(|block| block.body.len())) + .map(|block| block.body.len())); } let block_hash = match LoadBlock::provider(self) @@ -144,7 +144,7 @@ pub trait EthBlocks: LoadBlock { .map_err(Self::Error::from_eth_err) }) .collect::, Self::Error>>(); - return receipts.map(Some) + return receipts.map(Some); } Ok(None) @@ -183,7 +183,7 @@ pub trait EthBlocks: LoadBlock { return LoadReceipt::cache(self) .get_block_and_receipts(block_hash) .await - .map_err(Self::Error::from_eth_err) + .map_err(Self::Error::from_eth_err); } Ok(None) diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 0d309e6e0863..8f37b11d87e7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -93,7 +93,7 @@ pub trait EthCall: Call + LoadPendingBlock { if transactions.is_empty() { return Err( EthApiError::InvalidParams(String::from("transactions are empty.")).into() - ) + ); } let StateContext { transaction_index, block_number } = @@ -266,11 +266,11 @@ pub trait EthCall: Call + LoadPendingBlock { ExecutionResult::Halt { reason, gas_used } => { let error = Some(RpcInvalidTransactionError::halt(reason, env.tx.gas_limit).to_string()); - return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }) + return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }); } ExecutionResult::Revert { output, gas_used } => { let error = Some(RevertError::new(output).to_string()); - return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }) + return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }); } ExecutionResult::Success { .. } => {} }; @@ -494,7 +494,7 @@ pub trait Call: LoadState + SpawnBlocking { for tx in transactions { if tx.hash() == target_tx_hash { // reached the target transaction - break + break; } let sender = tx.signer(); @@ -595,7 +595,7 @@ pub trait Call: LoadState + SpawnBlocking { env.tx.gas_limit = MIN_TRANSACTION_GAS; if let Ok((res, _)) = self.transact(&mut db, env) { if res.result.is_success() { - return Ok(U256::from(MIN_TRANSACTION_GAS)) + return Ok(U256::from(MIN_TRANSACTION_GAS)); } } } @@ -642,7 +642,7 @@ pub trait Call: LoadState + SpawnBlocking { ExecutionResult::Halt { reason, gas_used } => { // here we don't check for invalid opcode because already executed with highest gas // limit - return Err(RpcInvalidTransactionError::halt(reason, gas_used).into_eth_err()) + return Err(RpcInvalidTransactionError::halt(reason, gas_used).into_eth_err()); } ExecutionResult::Revert { output, .. } => { // if price or limit was included in the request then we can execute the request @@ -652,7 +652,7 @@ pub trait Call: LoadState + SpawnBlocking { } else { // the transaction did revert Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into_eth_err()) - } + }; } }; @@ -710,7 +710,7 @@ pub trait Call: LoadState + SpawnBlocking { if (highest_gas_limit - lowest_gas_limit) as f64 / (highest_gas_limit as f64) < ESTIMATE_GAS_ERROR_RATIO { - break + break; }; env.tx.gas_limit = mid_gas_limit; @@ -782,7 +782,7 @@ pub trait Call: LoadState + SpawnBlocking { // These cases should be unreachable because we know the transaction // succeeds, but if they occur, treat them as an // error. - return Err(RpcInvalidTransactionError::EvmHalt(err).into_eth_err()) + return Err(RpcInvalidTransactionError::EvmHalt(err).into_eth_err()); } } } @@ -836,7 +836,7 @@ pub trait Call: LoadState + SpawnBlocking { ) -> Result { // Ensure that if versioned hashes are set, they're not empty if request.blob_versioned_hashes.as_ref().map_or(false, |hashes| hashes.is_empty()) { - return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_eth_err()) + return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_eth_err()); } let TransactionRequest { diff --git a/crates/rpc/rpc-eth-api/src/helpers/error.rs b/crates/rpc/rpc-eth-api/src/helpers/error.rs index 041a019052bd..5417e24b34a2 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/error.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/error.rs @@ -54,7 +54,7 @@ pub trait AsEthApiError { /// [`RpcInvalidTransactionError::GasTooHigh`](reth_rpc_eth_types::RpcInvalidTransactionError::GasTooHigh). fn is_gas_too_high(&self) -> bool { if let Some(err) = self.as_err() { - return err.is_gas_too_high() + return err.is_gas_too_high(); } false diff --git a/crates/rpc/rpc-eth-api/src/helpers/fee.rs b/crates/rpc/rpc-eth-api/src/helpers/fee.rs index a8fbc7e7fa73..ec81f8f2d3c7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/fee.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/fee.rs @@ -56,7 +56,7 @@ pub trait EthFees: LoadFee { ) -> impl Future> + Send { async move { if block_count == 0 { - return Ok(FeeHistory::default()) + return Ok(FeeHistory::default()); } // See https://github.com/ethereum/go-ethereum/blob/2754b197c935ee63101cbbca2752338246384fec/eth/gasprice/feehistory.go#L218C8-L225 @@ -86,7 +86,7 @@ pub trait EthFees: LoadFee { .block_number_for_id(newest_block.into()) .map_err(Self::Error::from_eth_err)? else { - return Err(EthApiError::UnknownBlockNumber.into()) + return Err(EthApiError::UnknownBlockNumber.into()); }; // need to add 1 to the end block to get the correct (inclusive) range @@ -102,7 +102,7 @@ pub trait EthFees: LoadFee { // Note: The types used ensure that the percentiles are never < 0 if let Some(percentiles) = &reward_percentiles { if percentiles.windows(2).any(|w| w[0] > w[1] || w[0] > 100.) { - return Err(EthApiError::InvalidRewardPercentiles.into()) + return Err(EthApiError::InvalidRewardPercentiles.into()); } } @@ -127,7 +127,7 @@ pub trait EthFees: LoadFee { if let Some(fee_entries) = fee_entries { if fee_entries.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange.into()) + return Err(EthApiError::InvalidBlockRange.into()); } for entry in &fee_entries { @@ -154,58 +154,64 @@ pub trait EthFees: LoadFee { base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default()); } else { - // read the requested header range - let headers = LoadFee::provider(self).sealed_headers_range(start_block..=end_block).map_err(Self::Error::from_eth_err)?; - if headers.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange.into()) - } - - for header in &headers { - base_fee_per_gas.push(header.base_fee_per_gas.unwrap_or_default() as u128); - gas_used_ratio.push(header.gas_used as f64 / header.gas_limit as f64); - base_fee_per_blob_gas.push(header.blob_fee().unwrap_or_default()); - blob_gas_used_ratio.push( - header.blob_gas_used.unwrap_or_default() as f64 / - reth_primitives::constants::eip4844::MAX_DATA_GAS_PER_BLOCK as f64, - ); + // read the requested header range + let headers = LoadFee::provider(self) + .sealed_headers_range(start_block..=end_block) + .map_err(Self::Error::from_eth_err)?; + if headers.len() != block_count as usize { + return Err(EthApiError::InvalidBlockRange.into()); + } - // Percentiles were specified, so we need to collect reward percentile ino - if let Some(percentiles) = &reward_percentiles { - let (transactions, receipts) = LoadFee::cache(self) - .get_transactions_and_receipts(header.hash()) - .await.map_err(Self::Error::from_eth_err)? - .ok_or(EthApiError::InvalidBlockRange)?; - rewards.push( - calculate_reward_percentiles_for_block( - percentiles, - header.gas_used, - header.base_fee_per_gas.unwrap_or_default(), - &transactions, - &receipts, - ) - .unwrap_or_default(), + for header in &headers { + base_fee_per_gas.push(header.base_fee_per_gas.unwrap_or_default() as u128); + gas_used_ratio.push(header.gas_used as f64 / header.gas_limit as f64); + base_fee_per_blob_gas.push(header.blob_fee().unwrap_or_default()); + blob_gas_used_ratio.push( + header.blob_gas_used.unwrap_or_default() as f64 + / reth_primitives::constants::eip4844::MAX_DATA_GAS_PER_BLOCK as f64, ); + + // Percentiles were specified, so we need to collect reward percentile ino + if let Some(percentiles) = &reward_percentiles { + let (transactions, receipts) = LoadFee::cache(self) + .get_transactions_and_receipts(header.hash()) + .await + .map_err(Self::Error::from_eth_err)? + .ok_or(EthApiError::InvalidBlockRange)?; + rewards.push( + calculate_reward_percentiles_for_block( + percentiles, + header.gas_used, + header.base_fee_per_gas.unwrap_or_default(), + &transactions, + &receipts, + ) + .unwrap_or_default(), + ); + } } - } - // The spec states that `base_fee_per_gas` "[..] includes the next block after the - // newest of the returned range, because this value can be derived from the - // newest block" - // - // The unwrap is safe since we checked earlier that we got at least 1 header. - let last_header = headers.last().expect("is present"); - base_fee_per_gas.push( - LoadFee::provider(self).chain_spec().base_fee_params_at_timestamp(last_header.timestamp).next_block_base_fee( - last_header.gas_used as u128, - last_header.gas_limit as u128, - last_header.base_fee_per_gas.unwrap_or_default() as u128, - )); - - // Same goes for the `base_fee_per_blob_gas`: - // > "[..] includes the next block after the newest of the returned range, because this value can be derived from the newest block. - base_fee_per_blob_gas - .push(last_header.next_block_blob_fee().unwrap_or_default()); - }; + // The spec states that `base_fee_per_gas` "[..] includes the next block after the + // newest of the returned range, because this value can be derived from the + // newest block" + // + // The unwrap is safe since we checked earlier that we got at least 1 header. + let last_header = headers.last().expect("is present"); + base_fee_per_gas.push( + LoadFee::provider(self) + .chain_spec() + .base_fee_params_at_timestamp(last_header.timestamp) + .next_block_base_fee( + last_header.gas_used as u128, + last_header.gas_limit as u128, + last_header.base_fee_per_gas.unwrap_or_default() as u128, + ), + ); + + // Same goes for the `base_fee_per_blob_gas`: + // > "[..] includes the next block after the newest of the returned range, because this value can be derived from the newest block. + base_fee_per_blob_gas.push(last_header.next_block_blob_fee().unwrap_or_default()); + }; Ok(FeeHistory { base_fee_per_gas, diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index bcbbf576a763..d05e34bd985e 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -139,7 +139,7 @@ pub trait LoadPendingBlock: EthApiTypes { .receipts_by_block(block.hash().into()) .map_err(Self::Error::from_eth_err)? { - return Ok(Some((block, receipts))) + return Ok(Some((block, receipts))); } } } @@ -156,7 +156,7 @@ pub trait LoadPendingBlock: EthApiTypes { pending.origin.header().hash() == pending_block.block.parent_hash && now <= pending_block.expires_at { - return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))) + return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))); } } @@ -171,7 +171,7 @@ pub trait LoadPendingBlock: EthApiTypes { Ok(block) => block, Err(err) => { debug!(target: "rpc", "Failed to build pending block: {:?}", err); - return Ok(None) + return Ok(None); } }; @@ -296,7 +296,7 @@ pub trait LoadPendingBlock: EthApiTypes { // which also removes all dependent transaction from the iterator before we can // continue best_txs.mark_invalid(&pool_tx); - continue + continue; } if pool_tx.origin.is_private() { @@ -304,7 +304,7 @@ pub trait LoadPendingBlock: EthApiTypes { // them as invalid here which removes all dependent transactions from the iterator // before we can continue best_txs.mark_invalid(&pool_tx); - continue + continue; } // convert tx to a signed transaction @@ -320,7 +320,7 @@ pub trait LoadPendingBlock: EthApiTypes { // the iterator. This is similar to the gas limit condition // for regular transactions above. best_txs.mark_invalid(&pool_tx); - continue + continue; } } @@ -345,11 +345,11 @@ pub trait LoadPendingBlock: EthApiTypes { // descendants best_txs.mark_invalid(&pool_tx); } - continue + continue; } err => { // this is an error that we should treat as fatal for this attempt - return Err(Self::Error::from_evm_err(err)) + return Err(Self::Error::from_evm_err(err)); } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index 06c3f9b5b8b1..3382f6c2522d 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -101,7 +101,7 @@ pub trait EthState: LoadState + SpawnBlocking { .ok_or(EthApiError::UnknownBlockNumber)?; let max_window = self.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { - return Err(EthApiError::ExceedsMaxProofWindow.into()) + return Err(EthApiError::ExceedsMaxProofWindow.into()); } Ok(async move { @@ -275,7 +275,7 @@ pub trait LoadState: EthApiTypes { let tx_count = highest_nonce.checked_add(1).ok_or(Self::Error::from( EthApiError::InvalidTransaction(RpcInvalidTransactionError::NonceMaxValue), ))?; - return Ok(U256::from(tx_count)) + return Ok(U256::from(tx_count)); } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index 09ad7f22fa21..e5a2b24ba0c1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -292,7 +292,7 @@ pub trait Trace: LoadState { if block.body.is_empty() { // nothing to trace - return Ok(Some(Vec::new())) + return Ok(Some(Vec::new())); } // replay all transactions of the block diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 62e20c79c04f..c1d46c413df1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -19,10 +19,13 @@ use reth_rpc_types::{ }, AnyTransactionReceipt, TransactionInfo, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::{transaction::from_recovered_with_block_context, TransactionCompat}; +use reth_rpc_types_compat::{ + transaction::{from_recovered, from_recovered_with_block_context}, + TransactionCompat, +}; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use crate::{FromEthApiError, IntoEthApiError, RpcTransaction}; +use crate::{EthApiTypes, FromEthApiError, IntoEthApiError, RpcTransaction}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, LoadState, @@ -103,7 +106,7 @@ pub trait EthTransactions: LoadTransaction { if let Some(tx) = self.pool().get_pooled_transaction_element(hash).map(|tx| tx.envelope_encoded()) { - return Ok(Some(tx)) + return Ok(Some(tx)); } self.spawn_blocking_io(move |ref this| { @@ -211,7 +214,7 @@ pub trait EthTransactions: LoadTransaction { return Ok(Some(from_recovered_with_block_context::( tx, tx_info, - ))) + ))); } } @@ -227,7 +230,13 @@ pub trait EthTransactions: LoadTransaction { include_pending: bool, ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock + LoadState, + Self: LoadBlock + + LoadState + + EthApiTypes< + TransactionCompat: TransactionCompat< + Transaction = RpcTransaction, + >, + >, { async move { // Check the pool first @@ -236,7 +245,7 @@ pub trait EthTransactions: LoadTransaction { LoadState::pool(self).get_transaction_by_sender_and_nonce(sender, nonce) { let transaction = tx.transaction.clone().into_consensus(); - return Ok(Some(from_recovered(transaction))); + return Ok(Some(from_recovered::(transaction))); } } @@ -286,7 +295,9 @@ pub trait EthTransactions: LoadTransaction { base_fee: base_fee_per_gas.map(u128::from), index: Some(index as u64), }; - from_recovered_with_block_context(tx, tx_info) + from_recovered_with_block_context::( + tx, tx_info, + ) }) }) .ok_or(EthApiError::UnknownBlockNumber.into()) @@ -308,7 +319,7 @@ pub trait EthTransactions: LoadTransaction { async move { if let Some(block) = self.block_with_senders(block_id).await? { if let Some(tx) = block.transactions().nth(index) { - return Ok(Some(tx.envelope_encoded())) + return Ok(Some(tx.envelope_encoded())); } } @@ -559,7 +570,7 @@ pub trait EthTransactions: LoadTransaction { return match signer.sign_transaction(request, from) { Ok(tx) => Ok(tx), Err(e) => Err(e.into_eth_err()), - } + }; } } Err(EthApiError::InvalidTransactionSignature.into()) diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 7013d18699c3..74862099bc3b 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -26,13 +26,13 @@ pub trait EthApiTypes: Send + Sync + Clone { HeaderResponse = reth_rpc_types::Header, ReceiptResponse = AnyTransactionReceipt, >; - /// Conversion methods for transaction RPC type. - type TransactionCompat: Send + Sync + Clone + fmt::Debug; + /// Conversion methods for transaction RPC type. + type TransactionCompat: Send + Sync + Clone + fmt::Debug; } impl EthApiTypes for () { type Error = EthApiError; - type NetworkTypes = Ethereum; + type NetworkTypes = AnyNetwork; type TransactionCompat = (); } diff --git a/crates/rpc/rpc-eth-types/src/cache/mod.rs b/crates/rpc/rpc-eth-types/src/cache/mod.rs index 63daa641b474..9a8059494415 100644 --- a/crates/rpc/rpc-eth-types/src/cache/mod.rs +++ b/crates/rpc/rpc-eth-types/src/cache/mod.rs @@ -419,7 +419,7 @@ where CacheAction::GetBlockWithSenders { block_hash, response_tx } => { if let Some(block) = this.full_block_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(Some(block))); - continue + continue; } // block is not in the cache, request it if this is the first consumer @@ -447,7 +447,7 @@ where // check if block is cached if let Some(block) = this.full_block_cache.get(&block_hash) { let _ = response_tx.send(Ok(Some(block.body.clone()))); - continue + continue; } // block is not in the cache, request it if this is the first consumer @@ -475,7 +475,7 @@ where // check if block is cached if let Some(receipts) = this.receipts_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(Some(receipts))); - continue + continue; } // block is not in the cache, request it if this is the first consumer @@ -499,7 +499,7 @@ where // check if env data is cached if let Some(env) = this.evm_env_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(env)); - continue + continue; } // env data is not in the cache, request it if this is the first diff --git a/crates/rpc/rpc-eth-types/src/fee_history.rs b/crates/rpc/rpc-eth-types/src/fee_history.rs index 94e52eb959db..bab993b68fab 100644 --- a/crates/rpc/rpc-eth-types/src/fee_history.rs +++ b/crates/rpc/rpc-eth-types/src/fee_history.rs @@ -103,7 +103,7 @@ impl FeeHistoryCache { if entries.len() == 0 { self.inner.upper_bound.store(0, SeqCst); self.inner.lower_bound.store(0, SeqCst); - return + return; } let upper_bound = *entries.last_entry().expect("Contains at least one entry").key(); @@ -150,7 +150,7 @@ impl FeeHistoryCache { .collect::>(); if result.is_empty() { - return None + return None; } Some(result) @@ -308,7 +308,7 @@ pub fn calculate_reward_percentiles_for_block( // Empty blocks should return in a zero row if transactions.is_empty() { rewards_in_block.push(0); - continue + continue; } let threshold = (gas_used as f64 * percentile / 100.) as u64; diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 5075a6d4a719..577b4e947a2c 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -124,7 +124,7 @@ where // if we have stored a last price, then we check whether or not it was for the same head if inner.last_price.block_hash == header.hash() { - return Ok(inner.last_price.price) + return Ok(inner.last_price.price); } // if all responses are empty, then we can return a maximum of 2*check_block blocks' worth @@ -169,7 +169,7 @@ where // break when we have enough populated blocks if populated_blocks >= self.oracle_config.blocks { - break + break; } current_hash = parent_hash; @@ -230,14 +230,14 @@ where let tip = tx.effective_tip_per_gas(base_fee_per_gas); effective_gas_tip = Some(tip); if tip < Some(ignore_under) { - continue + continue; } } // check if the sender was the coinbase, if so, ignore if let Some(sender) = tx.recover_signer() { if sender == block.beneficiary { - continue + continue; } } @@ -251,7 +251,7 @@ where // we have enough entries if prices.len() >= limit { - break + break; } } diff --git a/crates/rpc/rpc-eth-types/src/id_provider.rs b/crates/rpc/rpc-eth-types/src/id_provider.rs index 642d87578f81..97375624ca62 100644 --- a/crates/rpc/rpc-eth-types/src/id_provider.rs +++ b/crates/rpc/rpc-eth-types/src/id_provider.rs @@ -29,7 +29,7 @@ fn to_quantity(val: u128) -> SubscriptionId<'static> { let non_zero = b.iter().take_while(|b| **b == 0).count(); let b = &b[non_zero..]; if b.is_empty() { - return SubscriptionId::Str("0x0".into()) + return SubscriptionId::Str("0x0".into()); } let mut id = String::with_capacity(2 * b.len() + 2); diff --git a/crates/rpc/rpc-eth-types/src/logs_utils.rs b/crates/rpc/rpc-eth-types/src/logs_utils.rs index a08db4ce483f..ab93398fa4bc 100644 --- a/crates/rpc/rpc-eth-types/src/logs_utils.rs +++ b/crates/rpc/rpc-eth-types/src/logs_utils.rs @@ -176,7 +176,7 @@ pub fn log_matches_filter( !params.filter_address(&log.address) || !params.filter_topics(log.topics())) { - return false + return false; } true } diff --git a/crates/rpc/rpc-eth-types/src/revm_utils.rs b/crates/rpc/rpc-eth-types/src/revm_utils.rs index 52ae7ee0a167..55ec3f15fdac 100644 --- a/crates/rpc/rpc-eth-types/src/revm_utils.rs +++ b/crates/rpc/rpc-eth-types/src/revm_utils.rs @@ -125,13 +125,13 @@ impl CallFees { max_fee < block_base_fee { // `base_fee_per_gas` is greater than the `max_fee_per_gas` - return Err(RpcInvalidTransactionError::FeeCapTooLow.into()) + return Err(RpcInvalidTransactionError::FeeCapTooLow.into()); } if max_fee < max_priority_fee_per_gas { return Err( // `max_priority_fee_per_gas` is greater than the `max_fee_per_gas` RpcInvalidTransactionError::TipAboveFeeCap.into(), - ) + ); } Ok(min( max_fee, @@ -185,7 +185,7 @@ impl CallFees { // Ensure blob_hashes are present if !has_blob_hashes { // Blob transaction but no blob hashes - return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()) + return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()); } Ok(Self { diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index d4b083920fde..007671ca7b01 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -2,7 +2,7 @@ //! //! Transaction wrapper that labels transaction with its origin. use reth_primitives::{TransactionSignedEcRecovered, B256}; -use reth_rpc_types::{Transaction, TransactionInfo, WithOtherFields}; +use reth_rpc_types::TransactionInfo; use reth_rpc_types_compat::{ transaction::{from_recovered, from_recovered_with_block_context}, TransactionCompat, diff --git a/crates/rpc/rpc-eth-types/src/utils.rs b/crates/rpc/rpc-eth-types/src/utils.rs index ca2901ba8679..2c93d52fc6de 100644 --- a/crates/rpc/rpc-eth-types/src/utils.rs +++ b/crates/rpc/rpc-eth-types/src/utils.rs @@ -10,7 +10,7 @@ use super::{EthApiError, EthResult}; /// See [`PooledTransactionsElement::decode_enveloped`] pub fn recover_raw_transaction(data: Bytes) -> EthResult { if data.is_empty() { - return Err(EthApiError::EmptyRawTransactionData) + return Err(EthApiError::EmptyRawTransactionData); } let transaction = PooledTransactionsElement::decode_enveloped(&mut data.as_ref()) diff --git a/crates/rpc/rpc-server-types/src/module.rs b/crates/rpc/rpc-server-types/src/module.rs index 72a5e7c85833..63f283213b7e 100644 --- a/crates/rpc/rpc-server-types/src/module.rs +++ b/crates/rpc/rpc-server-types/src/module.rs @@ -195,7 +195,7 @@ impl FromStr for RpcModuleSelection { fn from_str(s: &str) -> Result { if s.is_empty() { - return Ok(Self::Selection(Default::default())) + return Ok(Self::Selection(Default::default())); } let mut modules = s.split(',').map(str::trim).peekable(); let first = modules.peek().copied().ok_or(ParseError::VariantNotFound)?; diff --git a/crates/rpc/rpc-testing-util/tests/it/trace.rs b/crates/rpc/rpc-testing-util/tests/it/trace.rs index 46d17e40b2ee..409b2f4a7af0 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -18,7 +18,7 @@ use reth_rpc_types::{ async fn trace_many_blocks() { let url = parse_env_url("RETH_RPC_TEST_NODE_URL"); if url.is_err() { - return + return; } let url = url.unwrap(); @@ -105,7 +105,7 @@ async fn trace_call() { async fn debug_trace_block_entire_chain() { let url = parse_env_url("RETH_RPC_TEST_NODE_URL"); if url.is_err() { - return + return; } let url = url.unwrap(); diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index 5056bf08af37..d30fccd8bff0 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -5,7 +5,7 @@ use reth_primitives::{ Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, }; use reth_rpc_types::{ - Block, BlockError, BlockTransactions, BlockTransactionsKind, Header, TransactionInfo, WithOtherFields, + Block, BlockError, BlockTransactions, BlockTransactionsKind, Header, TransactionInfo, }; use crate::{transaction::from_recovered_with_block_context, TransactionCompat}; diff --git a/crates/rpc/rpc-types-compat/src/engine/payload.rs b/crates/rpc/rpc-types-compat/src/engine/payload.rs index 933beb985561..c2d263300d26 100644 --- a/crates/rpc/rpc-types-compat/src/engine/payload.rs +++ b/crates/rpc/rpc-types-compat/src/engine/payload.rs @@ -15,11 +15,11 @@ use reth_rpc_types::engine::{ /// Converts [`ExecutionPayloadV1`] to [`Block`] pub fn try_payload_v1_to_block(payload: ExecutionPayloadV1) -> Result { if payload.extra_data.len() > MAXIMUM_EXTRA_DATA_SIZE { - return Err(PayloadError::ExtraData(payload.extra_data)) + return Err(PayloadError::ExtraData(payload.extra_data)); } if payload.base_fee_per_gas.is_zero() { - return Err(PayloadError::BaseFee(payload.base_fee_per_gas)) + return Err(PayloadError::BaseFee(payload.base_fee_per_gas)); } let transactions = payload @@ -355,7 +355,7 @@ pub fn validate_block_hash( return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_block_hash, - }) + }); } Ok(sealed_block) diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 20e70ae0bbe0..e754a6199b4f 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -94,7 +94,7 @@ where ) -> Result, Eth::Error> { if transactions.is_empty() { // nothing to trace - return Ok(Vec::new()) + return Ok(Vec::new()); } // replay all transactions of the block @@ -310,7 +310,7 @@ where Ok(inspector) }) .await?; - return Ok(FourByteFrame::from(inspector).into()) + return Ok(FourByteFrame::from(inspector).into()); } GethDebugBuiltInTracerType::CallTracer => { let call_config = tracer_config @@ -333,7 +333,7 @@ where Ok(frame.into()) }) .await?; - return Ok(frame) + return Ok(frame); } GethDebugBuiltInTracerType::PreStateTracer => { let prestate_config = tracer_config @@ -361,7 +361,7 @@ where Ok(frame) }) .await?; - return Ok(frame.into()) + return Ok(frame.into()); } GethDebugBuiltInTracerType::NoopTracer => Ok(NoopFrame::default().into()), GethDebugBuiltInTracerType::MuxTracer => { @@ -388,7 +388,7 @@ where Ok(frame.into()) }) .await?; - return Ok(frame) + return Ok(frame); } }, #[cfg(not(feature = "js-tracer"))] @@ -420,7 +420,7 @@ where Ok(GethTrace::JS(res)) } - } + }; } // default structlog tracer @@ -456,7 +456,7 @@ where opts: Option, ) -> Result>, Eth::Error> { if bundles.is_empty() { - return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into()) + return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into()); } let StateContext { transaction_index, block_number } = state_context.unwrap_or_default(); @@ -706,7 +706,7 @@ where GethDebugBuiltInTracerType::FourByteTracer => { let mut inspector = FourByteInspector::default(); let (res, _) = self.eth_api().inspect(db, env, &mut inspector)?; - return Ok((FourByteFrame::from(inspector).into(), res.state)) + return Ok((FourByteFrame::from(inspector).into(), res.state)); } GethDebugBuiltInTracerType::CallTracer => { let call_config = tracer_config @@ -724,7 +724,7 @@ where .into_geth_builder() .geth_call_traces(call_config, res.result.gas_used()); - return Ok((frame.into(), res.state)) + return Ok((frame.into(), res.state)); } GethDebugBuiltInTracerType::PreStateTracer => { let prestate_config = tracer_config @@ -742,7 +742,7 @@ where .geth_prestate_traces(&res, prestate_config, db) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)) + return Ok((frame.into(), res.state)); } GethDebugBuiltInTracerType::NoopTracer => { Ok((NoopFrame::default().into(), Default::default())) @@ -759,7 +759,7 @@ where let frame = inspector .try_into_mux_frame(&res, db) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)) + return Ok((frame.into(), res.state)); } }, #[cfg(not(feature = "js-tracer"))] @@ -783,7 +783,7 @@ where inspector.json_result(res, &env, db).map_err(Eth::Error::from_eth_err)?; Ok((GethTrace::JS(result), state)) } - } + }; } // default structlog tracer diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index a98cf3aef622..d634f09aba65 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -6,7 +6,7 @@ pub use reth_rpc_engine_api::EngineApi; use reth_rpc_eth_api::{EthApiTypes, RpcBlock, RpcReceipt, RpcTransaction}; use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, - SyncStatus, TransactionRequest, WithOtherFields, + SyncStatus, TransactionRequest, }; use reth_rpc_types_compat::TransactionCompat; use tracing_futures::Instrument; @@ -36,8 +36,11 @@ impl EngineEthApi { impl EngineEthApiServer> for EngineEthApi where - Eth: EthApiServer, RpcBlock> - + EthApiTypes< + Eth: EthApiServer< + RpcTransaction, + RpcBlock, + RpcReceipt, + > + EthApiTypes< TransactionCompat: TransactionCompat>, >, EthFilter: EthFilterApiServer<::Transaction>, diff --git a/crates/rpc/rpc/src/eth/bundle.rs b/crates/rpc/rpc/src/eth/bundle.rs index 4731de20d035..649c5c334af5 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -64,13 +64,13 @@ where return Err(EthApiError::InvalidParams( EthBundleError::EmptyBundleTransactions.to_string(), ) - .into()) + .into()); } if block_number == 0 { return Err(EthApiError::InvalidParams( EthBundleError::BundleMissingBlockNumber.to_string(), ) - .into()) + .into()); } let transactions = txs @@ -98,7 +98,7 @@ where return Err(EthApiError::InvalidParams( EthBundleError::Eip4844BlobGasExceeded.to_string(), ) - .into()) + .into()); } let block_id: reth_rpc_types::BlockId = state_block_number.into(); diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 7a5ccf69dd70..bf6800184e01 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -125,7 +125,8 @@ where Self: Send + Sync, { type Error = EthApiError; - type NetworkTypes = Ethereum; + // todo: replace with alloy_network::Ethereum + type NetworkTypes = AnyNetwork; type TransactionCompat = EthTxBuilder; } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index d8f106d6963e..bfe1541d2695 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -40,7 +40,7 @@ const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500k /// `Eth` filter RPC implementation. pub struct EthFilter { /// All nested fields bundled together - inner: Arc>, + inner: Arc>>, /// Assembles response data w.r.t. network. _tx_resp_builder: PhantomData, } @@ -55,7 +55,9 @@ impl EthFilter where Provider: Send + Sync + 'static, Pool: Send + Sync + 'static, - Eth: Send + Sync + 'static, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + > + 'static, { /// Creates a new, shareable instance. /// @@ -100,15 +102,9 @@ where eth_filter } -} -impl EthFilter -where - Provider: Send + Sync + 'static, - Pool: Send + Sync + 'static, -{ /// Returns all currently active filters - pub fn active_filters(&self) -> &ActiveFilters { + pub fn active_filters(&self) -> &ActiveFilters { &self.inner.active_filters } @@ -147,7 +143,9 @@ where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, ::Transaction: 'static, - Eth: TransactionCompat>, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, { /// Returns all the filter changes for the given id, if any pub async fn filter_changes( @@ -165,7 +163,7 @@ where if filter.block > best_number { // no new blocks since the last poll - return Ok(FilterChanges::Empty) + return Ok(FilterChanges::Empty); } // update filter @@ -234,7 +232,7 @@ where *filter.clone() } else { // Not a log filter - return Err(EthFilterError::FilterNotFound(id)) + return Err(EthFilterError::FilterNotFound(id)); } }; @@ -247,7 +245,10 @@ impl EthFilterApiServer for EthFilter> + Clone + 'static, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + > + Clone + + 'static, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { @@ -449,11 +450,11 @@ where let best_number = chain_info.best_number; if to_block < from_block { - return Err(EthFilterError::InvalidBlockRangeParams) + return Err(EthFilterError::InvalidBlockRangeParams); } if to_block - from_block > self.max_blocks_per_filter { - return Err(EthFilterError::QueryExceedsMaxBlocks(self.max_blocks_per_filter)) + return Err(EthFilterError::QueryExceedsMaxBlocks(self.max_blocks_per_filter)); } let mut all_logs = Vec::new(); @@ -477,7 +478,7 @@ where block.header.timestamp, )?; } - return Ok(all_logs) + return Ok(all_logs); } // derive bloom filters from filter input, so we can check headers for matching logs @@ -523,7 +524,7 @@ where if is_multi_block_range && all_logs.len() > self.max_logs_per_response { return Err(EthFilterError::QueryExceedsMaxResults( self.max_logs_per_response, - )) + )); } } } @@ -673,7 +674,7 @@ impl Iterator for BlockRangeInclusiveIter { let start = self.iter.next()?; let end = (start + self.step).min(self.end); if start > end { - return None + return None; } Some((start, end)) } diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index 3eabf5d30385..d77f64df8e06 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -68,7 +68,6 @@ where max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), blob_versioned_hashes, authorization_list, - other: Default::default(), } } } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index c8798017012c..0670319edb68 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -77,7 +77,10 @@ where Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, - Eth: TransactionCompat + Clone + 'static, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + > + Clone + + 'static, { /// Handler for `eth_subscribe` async fn subscribe( @@ -144,7 +147,7 @@ where tx.transaction.to_recovered_transaction(), ))) }); - return pipe_from_stream(accepted_sink, stream).await + return pipe_from_stream(accepted_sink, stream).await; } Params::Bool(false) | Params::None => { // only hashes requested @@ -174,7 +177,7 @@ where let msg = SubscriptionMessage::from_json(¤t_sub_res) .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - return Ok(()) + return Ok(()); } while canon_state.next().await.is_some() { @@ -189,7 +192,7 @@ where let msg = SubscriptionMessage::from_json(&sync_status) .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - break + break; } } } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index d151f783f8c5..39c3dee5474a 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -20,6 +20,7 @@ use reth_rpc_types::{ }, AnyTransactionReceipt, BlockTransactions, Header, Transaction, WithOtherFields, }; +use reth_rpc_types_compat::TransactionCompat; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, transfer::{TransferInspector, TransferKind}, @@ -77,6 +78,7 @@ where NetworkTypes: Network< TransactionResponse = WithOtherFields, >, + TransactionCompat: TransactionCompat>, > + TraceExt + EthTransactions + 'static, @@ -211,7 +213,7 @@ where if tx_len != receipts.len() { return Err(internal_rpc_err( "the number of transactions does not match the number of receipts", - )) + )); } // make sure the block is full diff --git a/crates/rpc/rpc/src/reth.rs b/crates/rpc/rpc/src/reth.rs index 33dc74920406..bfb56075f182 100644 --- a/crates/rpc/rpc/src/reth.rs +++ b/crates/rpc/rpc/src/reth.rs @@ -64,7 +64,7 @@ where fn try_balance_changes_in_block(&self, block_id: BlockId) -> EthResult> { let Some(block_number) = self.provider().block_number_for_id(block_id)? else { - return Err(EthApiError::UnknownBlockNumber) + return Err(EthApiError::UnknownBlockNumber); }; let state = self.provider().state_by_block_id(block_id)?; diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index cb9f0ab269bd..70c636cb403c 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -229,7 +229,7 @@ where ) -> Result, Eth::Error> { if indices.len() != 1 { // The OG impl failed if it gets more than a single index - return Ok(None) + return Ok(None); } self.trace_get_index(hash, indices[0]).await } @@ -266,7 +266,7 @@ where return Err(EthApiError::InvalidParams( "invalid parameters: fromBlock cannot be greater than toBlock".to_string(), ) - .into()) + .into()); } // ensure that the range is not too large, since we need to fetch all blocks in the range @@ -275,7 +275,7 @@ where return Err(EthApiError::InvalidParams( "Block range too large; currently limited to 100 blocks".to_string(), ) - .into()) + .into()); } // fetch all blocks in that range @@ -316,7 +316,7 @@ where } else { // no block reward, means we're past the Paris hardfork and don't expect any rewards // because the blocks in ascending order - break + break; } } diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index e40a665e29cb..4040ae00e700 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -33,16 +33,20 @@ impl TxPoolApi where Pool: TransactionPool + 'static, // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction - Eth: TransactionCompat, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, { - fn content(&self) -> TxpoolContent> { + fn content(&self) -> TxpoolContent { #[inline] fn insert( tx: &Tx, content: &mut BTreeMap>, ) where Tx: PoolTransaction, - Eth: TransactionCompat, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, { content .entry(tx.sender()) @@ -52,7 +56,7 @@ where let AllPoolTransactions { pending, queued } = self.pool.all_transactions(); - let mut content = TxpoolContent::default(); + let mut content = TxpoolContent::>::default(); for pending in pending { insert::<_, Eth>(&pending.transaction, &mut content.pending); } @@ -68,7 +72,7 @@ where impl TxPoolApiServer for TxPoolApi where Pool: TransactionPool + 'static, - Eth: TransactionCompat + 'static, + Eth: TransactionCompat> + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. @@ -130,7 +134,7 @@ where async fn txpool_content_from( &self, from: Address, - ) -> Result>> { + ) -> Result> { trace!(target: "rpc::eth", ?from, "Serving txpool_contentFrom"); Ok(self.content().remove_from(&from)) } From 2dff25add2f9c20c6593b4921abe6ddd3a374ef4 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Sun, 8 Sep 2024 21:54:23 +0200 Subject: [PATCH 51/80] Fix merge conflicts --- Cargo.lock | 3 +- crates/node/builder/Cargo.toml | 3 -- crates/node/builder/src/builder/mod.rs | 1 - crates/node/builder/src/launch/engine.rs | 2 +- crates/node/builder/src/launch/mod.rs | 2 +- crates/node/builder/src/rpc.rs | 1 - crates/optimism/rpc/Cargo.toml | 2 +- crates/optimism/rpc/src/eth/mod.rs | 5 +- crates/optimism/rpc/src/eth/receipt.rs | 2 +- crates/optimism/rpc/src/eth/transaction.rs | 9 ++-- crates/rpc/rpc-builder/src/lib.rs | 1 - crates/rpc/rpc-eth-api/src/types.rs | 3 +- crates/rpc/rpc/src/eth/helpers/types.rs | 56 ++++++++++++---------- crates/rpc/rpc/src/eth/pubsub.rs | 4 +- 14 files changed, 46 insertions(+), 48 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fefcf95a4a08..e9c79dd96a05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7602,7 +7602,6 @@ dependencies = [ name = "reth-node-builder" version = "1.0.6" dependencies = [ - "alloy-network", "aquamarine", "eyre", "fdlimit", @@ -7964,7 +7963,7 @@ name = "reth-optimism-rpc" version = "1.0.6" dependencies = [ "alloy-primitives", - "alloy-rpc-types", + "derive_more 1.0.0", "jsonrpsee-types", "op-alloy-network", "op-alloy-rpc-types", diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index 01ecfaed5337..807612204471 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -58,9 +58,6 @@ reth-rpc-types-compat.workspace = true reth-tracing.workspace = true reth-transaction-pool.workspace = true -## ethereum -alloy-network.workspace = true - ## async futures.workspace = true tokio = { workspace = true, features = [ diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 747b0a0df46c..689e6b752fcf 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -5,7 +5,6 @@ pub mod add_ons; mod states; -use reth_rpc_types::WithOtherFields; pub use states::*; use std::sync::Arc; diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index aa1f670e73f2..1238d0c19d4e 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -30,7 +30,7 @@ use reth_node_core::{ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_provider::providers::BlockchainProvider2; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; -use reth_rpc_types::{engine::ClientVersionV1, WithOtherFields}; +use reth_rpc_types::engine::ClientVersionV1; use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index d5b549e99827..6ec92a66365a 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -34,7 +34,7 @@ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_primitives::format_ether; use reth_provider::providers::BlockchainProvider; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; -use reth_rpc_types::{engine::ClientVersionV1, WithOtherFields}; +use reth_rpc_types::engine::ClientVersionV1; use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 332ed2c126f0..77850487726d 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -22,7 +22,6 @@ use reth_rpc_builder::{ RpcModuleBuilder, RpcRegistryInner, RpcServerHandle, TransportRpcModules, }; use reth_rpc_layer::JwtSecret; -use reth_rpc_types::WithOtherFields; use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 381c6daa554b..dde9f7081f40 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -32,7 +32,6 @@ reth-chainspec.workspace = true # ethereum alloy-primitives.workspace = true -alloy-rpc-types.workspace = true op-alloy-network.workspace = true revm.workspace = true op-alloy-rpc-types.workspace = true @@ -49,6 +48,7 @@ serde_json.workspace = true # misc thiserror.workspace = true tracing.workspace = true +derive_more = { workspace = true, default-features = false, features = ["deref"] } [dev-dependencies] reth-optimism-chainspec.workspace = true diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index cd49fe6a6816..506c6039e941 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -19,8 +19,8 @@ use reth_network_api::NetworkInfo; use reth_node_api::{BuilderProvider, FullNodeComponents, FullNodeTypes, NodeTypes}; use reth_node_builder::EthApiBuilderCtx; use reth_provider::{ - BlockIdReader, BlockNumReader, BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider, - HeaderProvider, StageCheckpointReader, StateProviderFactory, + BlockIdReader, BlockNumReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider, + StageCheckpointReader, StateProviderFactory, }; use reth_rpc::eth::{core::EthApiInner, DevSigner}; use reth_rpc_eth_api::{ @@ -101,7 +101,6 @@ impl EthApiTypes for OpEthApi where Self: Send + Sync, N: FullNodeComponents, - // todo: replace constraint when op and l1 don't use same tx type in alloy Eth: TransactionCompat::TransactionResponse>, { type Error = OpEthApiError; diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index a9d91cc5ea68..53e3785f49a6 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -56,7 +56,7 @@ where } } -impl OpEthApi +impl OpEthApi where N: FullNodeComponents>, { diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 351a79511875..0a027cc39cce 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -1,16 +1,17 @@ //! Loads and formats OP transaction RPC response. -use std::{marker::PhantomData, sync::Arc}; +use std::marker::PhantomData; -use alloy_rpc_types::optimism::OptimismTransactionFields; +use alloy_primitives::{Bytes, B256}; use op_alloy_network::{Network, Optimism}; +use op_alloy_rpc_types::OptimismTransactionFields; use reth_evm_optimism::RethL1BlockInfo; use reth_node_api::FullNodeComponents; -use reth_primitives::{TransactionSigned, TransactionSignedEcRecovered}; +use reth_primitives::TransactionSignedEcRecovered; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; use reth_rpc_eth_api::{ helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, FromEthApiError, RawTransactionForwarder, TransactionCompat, + FromEthApiError, TransactionCompat, }; use reth_rpc_eth_types::{utils::recover_raw_transaction, EthStateCache}; use reth_rpc_types::TransactionInfo; diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index a56e3a2de276..9401dce6e0d4 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -170,7 +170,6 @@ use reth_rpc_eth_api::{ }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; -use reth_rpc_types::{optimism::Transaction, WithOtherFields}; use reth_tasks::{pool::BlockingTaskGuard, TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{noop::NoopTransactionPool, TransactionPool}; use serde::{Deserialize, Serialize}; diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 74862099bc3b..90c7035f385f 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -4,7 +4,7 @@ use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; -use reth_rpc_types::{AnyTransactionReceipt, Block, Transaction, WithOtherFields}; +use reth_rpc_types::{Block, Transaction, WithOtherFields}; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -24,7 +24,6 @@ pub trait EthApiTypes: Send + Sync + Clone { type NetworkTypes: Network< TransactionResponse = WithOtherFields, HeaderResponse = reth_rpc_types::Header, - ReceiptResponse = AnyTransactionReceipt, >; /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index d77f64df8e06..0469a6908a9b 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -1,8 +1,8 @@ //! L1 `eth` API types. -use alloy_network::{Ethereum, Network}; +use alloy_network::{AnyNetwork, Network}; use reth_primitives::{Address, TransactionSignedEcRecovered, TxKind}; -use reth_rpc_types::TransactionInfo; +use reth_rpc_types::{Transaction, TransactionInfo, WithOtherFields}; use reth_rpc_types_compat::{ transaction::{from_primitive_signature, GasPrice}, TransactionCompat, @@ -16,7 +16,7 @@ impl TransactionCompat for EthTxBuilder where Self: Send + Sync, { - type Transaction = ::TransactionResponse; + type Transaction = ::TransactionResponse; fn fill(tx: TransactionSignedEcRecovered, tx_info: TransactionInfo) -> Self::Transaction { let signer = tx.signer(); @@ -45,29 +45,33 @@ where signed_tx.chain_id(), ); - Self::Transaction { - hash: signed_tx.hash(), - nonce: signed_tx.nonce(), - from: signer, - to, - value: signed_tx.value(), - gas_price, - max_fee_per_gas, - max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), - signature: Some(signature), - gas: signed_tx.gas_limit() as u128, - input: signed_tx.input().clone(), - chain_id, - access_list, - transaction_type: Some(signed_tx.tx_type() as u8), - // These fields are set to None because they are not stored as part of the transaction - block_hash, - block_number, - transaction_index, - // EIP-4844 fields - max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), - blob_versioned_hashes, - authorization_list, + WithOtherFields { + inner: Transaction { + hash: signed_tx.hash(), + nonce: signed_tx.nonce(), + from: signer, + to, + value: signed_tx.value(), + gas_price, + max_fee_per_gas, + max_priority_fee_per_gas: signed_tx.max_priority_fee_per_gas(), + signature: Some(signature), + gas: signed_tx.gas_limit() as u128, + input: signed_tx.input().clone(), + chain_id, + access_list, + transaction_type: Some(signed_tx.tx_type() as u8), + // These fields are set to None because they are not stored as part of the + // transaction + block_hash, + block_number, + transaction_index, + // EIP-4844 fields + max_fee_per_blob_gas: signed_tx.max_fee_per_blob_gas(), + blob_versioned_hashes, + authorization_list, + }, + ..Default::default() } } } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 0670319edb68..906553ab0299 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -112,7 +112,9 @@ where Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction - Eth: TransactionCompat, + Eth: TransactionCompat< + Transaction = reth_rpc_types::WithOtherFields, + >, { match kind { SubscriptionKind::NewHeads => { From 963dab3d4224246612f713c9d54b8f3cde2e9bf2 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 9 Sep 2024 14:39:30 +0200 Subject: [PATCH 52/80] Define type reth_optimism_rpc::OpReceiptBuilder --- Cargo.lock | 1 + crates/optimism/rpc/Cargo.toml | 1 + crates/optimism/rpc/src/eth/mod.rs | 4 +- crates/optimism/rpc/src/eth/receipt.rs | 114 +++++++++++++++++++++++- crates/rpc/rpc-eth-types/src/receipt.rs | 4 +- 5 files changed, 118 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5f9de84f078e..b7e1b0397443 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7964,6 +7964,7 @@ version = "1.0.6" dependencies = [ "alloy-primitives", "jsonrpsee-types", + "op-alloy-consensus", "op-alloy-network", "op-alloy-rpc-types", "parking_lot 0.12.3", diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index f82483590bbd..05d5364f1b18 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -34,6 +34,7 @@ alloy-primitives.workspace = true op-alloy-network.workspace = true revm.workspace = true op-alloy-rpc-types.workspace = true +op-alloy-consensus.workspace = true # async parking_lot.workspace = true diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 13078e456bbd..9f42c50371e4 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -1,12 +1,14 @@ //! OP-Reth `eth_` endpoint implementation. pub mod receipt; +pub mod rpc; pub mod transaction; mod block; mod call; mod pending_block; -pub mod rpc; + +pub use receipt::{OpReceiptBuilder, OpReceiptFieldsBuilder}; use std::{fmt, sync::Arc}; diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index b68ccd15ab09..e7e8770cb7f8 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -1,17 +1,20 @@ //! Loads and formats OP receipt RPC response. -use op_alloy_rpc_types::{receipt::L1BlockInfo, OptimismTransactionReceiptFields}; +use op_alloy_consensus::{OpDepositReceipt, OpDepositReceiptWithBloom, OpReceiptEnvelope}; +use op_alloy_rpc_types::{ + receipt::L1BlockInfo, OpTransactionReceipt, OptimismTransactionReceiptFields, +}; use reth_chainspec::{ChainSpec, OptimismHardforks}; use reth_evm_optimism::RethL1BlockInfo; use reth_node_api::{FullNodeComponents, NodeTypes}; -use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; +use reth_primitives::{Receipt, TransactionMeta, TransactionSigned, TxType}; use reth_provider::ChainSpecProvider; use reth_rpc_eth_api::{ helpers::{EthApiSpec, LoadReceipt, LoadTransaction}, FromEthApiError, }; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; -use reth_rpc_types::AnyTransactionReceipt; +use reth_rpc_types::{AnyReceiptEnvelope, AnyTransactionReceipt, Log, TransactionReceipt}; use crate::{OpEthApi, OpEthApiError}; @@ -191,6 +194,111 @@ impl OpReceiptFieldsBuilder { } } +/// Builds an [`OpTransactionReceipt`]. +#[derive(Debug)] +pub struct OpReceiptBuilder { + /// Core receipt, has all the fields of an L1 receipt and is the basis for the OP receipt. + pub core_receipt: TransactionReceipt>, + /// Transaction type. + pub tx_type: TxType, + /// Additional OP receipt fields. + pub op_receipt_fields: OptimismTransactionReceiptFields, +} + +impl OpReceiptBuilder { + /// Returns a new builder. + pub fn new( + chain_spec: &ChainSpec, + transaction: &TransactionSigned, + meta: TransactionMeta, + receipt: &Receipt, + all_receipts: &[Receipt], + l1_block_info: revm::L1BlockInfo, + ) -> Result { + let ReceiptBuilder { base: core_receipt, .. } = + ReceiptBuilder::new(transaction, meta, receipt, all_receipts) + .map_err(OpEthApiError::Eth)?; + + let tx_type = transaction.tx_type(); + + let op_receipt_fields = OpReceiptFieldsBuilder::default() + .l1_block_info(chain_spec, transaction, l1_block_info)? + .deposit_nonce(receipt.deposit_nonce) + .deposit_version(receipt.deposit_receipt_version) + .build(); + + Ok(Self { core_receipt, tx_type, op_receipt_fields }) + } + + /// Builds [`OpTransactionReceipt`] by combing core (l1) receipt fields and additional OP + /// receipt fields. + pub fn build(self) -> OpTransactionReceipt { + let Self { core_receipt, tx_type, op_receipt_fields } = self; + + let OptimismTransactionReceiptFields { + l1_block_info, + deposit_nonce, + deposit_receipt_version, + } = op_receipt_fields; + + let TransactionReceipt { + inner: AnyReceiptEnvelope { inner: receipt_with_bloom, .. }, + transaction_hash, + transaction_index, + block_hash, + block_number, + gas_used, + effective_gas_price, + blob_gas_used, + blob_gas_price, + from, + to, + contract_address, + state_root, + authorization_list, + } = core_receipt; + + let inner = match tx_type { + TxType::Legacy => OpReceiptEnvelope::::Legacy(receipt_with_bloom), + TxType::Eip2930 => OpReceiptEnvelope::::Eip2930(receipt_with_bloom), + TxType::Eip1559 => OpReceiptEnvelope::::Eip1559(receipt_with_bloom), + TxType::Eip4844 => OpReceiptEnvelope::::Eip4844(receipt_with_bloom), + TxType::Eip7702 => { + unimplemented!("not implemented yet for OpReceiptEnvelope") + } + TxType::Deposit => { + OpReceiptEnvelope::::Deposit(OpDepositReceiptWithBloom:: { + receipt: OpDepositReceipt:: { + inner: receipt_with_bloom.receipt, + deposit_nonce, + deposit_receipt_version, + }, + logs_bloom: receipt_with_bloom.logs_bloom, + }) + } + }; + + let inner = TransactionReceipt::> { + inner, + transaction_hash, + transaction_index, + block_hash, + block_number, + gas_used, + effective_gas_price, + blob_gas_used, + blob_gas_price, + from, + to, + contract_address, + state_root, + authorization_list, + }; + + OpTransactionReceipt { inner, l1_block_info } + } +} + #[cfg(test)] mod test { use alloy_primitives::hex; diff --git a/crates/rpc/rpc-eth-types/src/receipt.rs b/crates/rpc/rpc-eth-types/src/receipt.rs index 34b10fd1c23c..db0b91fb75d8 100644 --- a/crates/rpc/rpc-eth-types/src/receipt.rs +++ b/crates/rpc/rpc-eth-types/src/receipt.rs @@ -13,9 +13,9 @@ use super::{EthApiError, EthResult}; #[derive(Debug)] pub struct ReceiptBuilder { /// The base response body, contains L1 fields. - base: TransactionReceipt>, + pub base: TransactionReceipt>, /// Additional L2 fields. - other: OtherFields, + pub other: OtherFields, } impl ReceiptBuilder { From ecddc971fb39053a872c338a7d044b236f0f1cc4 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 9 Sep 2024 15:47:54 +0200 Subject: [PATCH 53/80] Move EthBlocks::block_receipts default impl to impl for EthApi --- crates/rpc/rpc-eth-api/src/helpers/block.rs | 43 ++--------------- crates/rpc/rpc/src/eth/helpers/block.rs | 51 ++++++++++++++++++++- 2 files changed, 52 insertions(+), 42 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 3f1d4eff31b9..877822394765 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -3,9 +3,9 @@ use std::sync::Arc; use futures::Future; -use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders, TransactionMeta}; +use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders}; use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_types::{EthApiError, EthStateCache}; use reth_rpc_types::{AnyTransactionReceipt, Header, Index}; use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; @@ -93,44 +93,7 @@ pub trait EthBlocks: LoadBlock { block_id: BlockId, ) -> impl Future>, Self::Error>> + Send where - Self: LoadReceipt, - { - async move { - if let Some((block, receipts)) = self.load_block_and_receipts(block_id).await? { - let block_number = block.number; - let base_fee = block.base_fee_per_gas; - let block_hash = block.hash(); - let excess_blob_gas = block.excess_blob_gas; - let timestamp = block.timestamp; - let block = block.unseal(); - - let receipts = block - .body - .into_iter() - .zip(receipts.iter()) - .enumerate() - .map(|(idx, (tx, receipt))| { - let meta = TransactionMeta { - tx_hash: tx.hash, - index: idx as u64, - block_hash, - block_number, - base_fee, - excess_blob_gas, - timestamp, - }; - - ReceiptBuilder::new(&tx, meta, receipt, &receipts) - .map(|builder| builder.build()) - .map_err(Self::Error::from_eth_err) - }) - .collect::, Self::Error>>(); - return receipts.map(Some) - } - - Ok(None) - } - } + Self: LoadReceipt; /// Helper method that loads a bock and all its receipts. fn load_block_and_receipts( diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 92f8d5e0344d..5e16ce64d819 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -1,8 +1,13 @@ //! Contains RPC handler implementations specific to blocks. +use reth_primitives::{BlockId, TransactionMeta}; use reth_provider::{BlockReaderIdExt, HeaderProvider}; -use reth_rpc_eth_api::helpers::{EthBlocks, LoadBlock, LoadPendingBlock, SpawnBlocking}; -use reth_rpc_eth_types::EthStateCache; +use reth_rpc_eth_api::{ + helpers::{EthBlocks, LoadBlock, LoadPendingBlock, LoadReceipt, SpawnBlocking}, + FromEthApiError, +}; +use reth_rpc_eth_types::{EthStateCache, ReceiptBuilder}; +use reth_rpc_types::AnyTransactionReceipt; use crate::EthApi; @@ -15,6 +20,48 @@ where fn provider(&self) -> impl HeaderProvider { self.inner.provider() } + + async fn block_receipts( + &self, + block_id: BlockId, + ) -> Result>, Self::Error> + where + Self: LoadReceipt, + { + if let Some((block, receipts)) = self.load_block_and_receipts(block_id).await? { + let block_number = block.number; + let base_fee = block.base_fee_per_gas; + let block_hash = block.hash(); + let excess_blob_gas = block.excess_blob_gas; + let timestamp = block.timestamp; + let block = block.unseal(); + + let receipts = block + .body + .into_iter() + .zip(receipts.iter()) + .enumerate() + .map(|(idx, (tx, receipt))| { + let meta = TransactionMeta { + tx_hash: tx.hash, + index: idx as u64, + block_hash, + block_number, + base_fee, + excess_blob_gas, + timestamp, + }; + + ReceiptBuilder::new(&tx, meta, receipt, &receipts) + .map(|builder| builder.build()) + .map_err(Self::Error::from_eth_err) + }) + .collect::, Self::Error>>(); + return receipts.map(Some) + } + + Ok(None) + } } impl LoadBlock for EthApi From a0b5cfdf282923f6367e82d3b7bf3aed82de2193 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 9 Sep 2024 16:07:00 +0200 Subject: [PATCH 54/80] Move LoadReceipt::build_transaction_receipt default impl to impl for EthApi --- crates/rpc/rpc-eth-api/src/helpers/receipt.rs | 19 +++------------ crates/rpc/rpc/src/eth/helpers/receipt.rs | 24 +++++++++++++++++-- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs index c5b549295299..fbd81e6fd7bb 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/receipt.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/receipt.rs @@ -3,10 +3,10 @@ use futures::Future; use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; -use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; +use reth_rpc_eth_types::EthStateCache; use reth_rpc_types::AnyTransactionReceipt; -use crate::{EthApiTypes, FromEthApiError}; +use crate::EthApiTypes; /// Assembles transaction receipt data w.r.t to network. /// @@ -23,18 +23,5 @@ pub trait LoadReceipt: EthApiTypes + Send + Sync { tx: TransactionSigned, meta: TransactionMeta, receipt: Receipt, - ) -> impl Future> + Send { - async move { - let hash = meta.block_hash; - // get all receipts for the block - let all_receipts = self - .cache() - .get_receipts(hash) - .await - .map_err(Self::Error::from_eth_err)? - .ok_or(EthApiError::HeaderNotFound(hash.into()))?; - - Ok(ReceiptBuilder::new(&tx, meta, &receipt, &all_receipts)?.build()) - } - } + ) -> impl Future> + Send; } diff --git a/crates/rpc/rpc/src/eth/helpers/receipt.rs b/crates/rpc/rpc/src/eth/helpers/receipt.rs index db1fee781fd3..77a4058240e7 100644 --- a/crates/rpc/rpc/src/eth/helpers/receipt.rs +++ b/crates/rpc/rpc/src/eth/helpers/receipt.rs @@ -1,7 +1,9 @@ //! Builds an RPC receipt response w.r.t. data layout of network. -use reth_rpc_eth_api::helpers::LoadReceipt; -use reth_rpc_eth_types::EthStateCache; +use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; +use reth_rpc_eth_api::{helpers::LoadReceipt, FromEthApiError}; +use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; +use reth_rpc_types::AnyTransactionReceipt; use crate::EthApi; @@ -13,4 +15,22 @@ where fn cache(&self) -> &EthStateCache { self.inner.cache() } + + async fn build_transaction_receipt( + &self, + tx: TransactionSigned, + meta: TransactionMeta, + receipt: Receipt, + ) -> Result { + let hash = meta.block_hash; + // get all receipts for the block + let all_receipts = self + .cache() + .get_receipts(hash) + .await + .map_err(Self::Error::from_eth_err)? + .ok_or(EthApiError::HeaderNotFound(hash.into()))?; + + Ok(ReceiptBuilder::new(&tx, meta, &receipt, &all_receipts)?.build()) + } } From b6ad11644e5e120010f0e328f7daf07996abc133 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 13:08:53 +0200 Subject: [PATCH 55/80] Merge branch 'main' into emhane/ethapi-types --- .github/assets/hive/expected_failures.yaml | 2 - .../hive/expected_failures_experimental.yaml | 2 - .github/workflows/dependencies.yml | 2 +- .github/workflows/lint.yml | 5 +- Cargo.lock | 284 ++++++++++-------- Cargo.toml | 62 ++-- bin/reth/src/cli/mod.rs | 2 +- bin/reth/src/commands/debug_cmd/execution.rs | 2 +- bin/reth/src/lib.rs | 3 - book/run/optimism.md | 25 -- crates/blockchain-tree/Cargo.toml | 3 + crates/blockchain-tree/src/block_buffer.rs | 6 +- crates/blockchain-tree/src/block_indices.rs | 8 +- crates/blockchain-tree/src/blockchain_tree.rs | 49 +-- crates/blockchain-tree/src/bundle.rs | 5 +- crates/blockchain-tree/src/canonical_chain.rs | 3 +- crates/blockchain-tree/src/chain.rs | 5 +- crates/blockchain-tree/src/externals.rs | 3 +- crates/blockchain-tree/src/noop.rs | 6 +- crates/blockchain-tree/src/shareable.rs | 6 +- crates/blockchain-tree/src/state.rs | 3 +- crates/cli/cli/src/chainspec.rs | 2 +- crates/cli/commands/src/common.rs | 2 +- crates/cli/commands/src/dump_genesis.rs | 2 +- crates/cli/commands/src/import.rs | 2 +- crates/cli/commands/src/node.rs | 2 +- crates/cli/commands/src/p2p/mod.rs | 2 +- crates/cli/commands/src/stage/run.rs | 2 + .../beacon/src/engine/hooks/static_file.rs | 31 +- crates/e2e-test-utils/src/lib.rs | 5 +- crates/e2e-test-utils/src/node.rs | 19 +- crates/e2e-test-utils/src/rpc.rs | 10 +- crates/engine/service/Cargo.toml | 3 - crates/engine/service/src/service.rs | 8 +- crates/engine/tree/src/download.rs | 5 +- crates/engine/tree/src/persistence.rs | 23 +- .../ethereum/engine-primitives/src/payload.rs | 15 +- crates/ethereum/payload/src/lib.rs | 200 ++---------- crates/net/discv5/src/lib.rs | 6 +- crates/net/network/src/network.rs | 4 +- crates/net/peers/src/node_record.rs | 9 + crates/node/builder/Cargo.toml | 4 + crates/node/builder/src/builder/mod.rs | 5 +- crates/node/builder/src/launch/common.rs | 9 +- crates/node/builder/src/launch/engine.rs | 7 +- crates/node/builder/src/launch/mod.rs | 6 +- crates/node/builder/src/setup.rs | 4 +- crates/node/core/Cargo.toml | 10 +- crates/node/core/src/args/debug.rs | 2 +- crates/node/core/src/args/pruning.rs | 2 +- crates/node/core/src/args/txpool.rs | 2 +- crates/node/core/src/cli/config.rs | 2 +- crates/node/core/src/node_config.rs | 27 +- crates/node/core/src/version.rs | 2 +- crates/node/events/Cargo.toml | 6 +- crates/node/events/src/node.rs | 3 +- crates/node/metrics/src/chain.rs | 19 ++ crates/node/metrics/src/lib.rs | 1 + crates/node/metrics/src/server.rs | 13 +- crates/optimism/bin/src/main.rs | 94 +++--- crates/optimism/cli/Cargo.toml | 10 +- .../cli/src/commands/build_pipeline.rs | 2 +- .../cli/src/commands/import_receipts.rs | 2 +- crates/optimism/cli/src/lib.rs | 19 +- crates/optimism/cli/src/receipt_file_codec.rs | 6 +- crates/optimism/consensus/Cargo.toml | 6 +- crates/optimism/consensus/src/lib.rs | 5 +- crates/optimism/consensus/src/proof.rs | 3 +- crates/optimism/consensus/src/validation.rs | 5 +- crates/optimism/evm/Cargo.toml | 3 + crates/optimism/evm/src/error.rs | 2 +- crates/optimism/evm/src/execute.rs | 7 +- crates/optimism/evm/src/l1.rs | 6 +- crates/optimism/evm/src/lib.rs | 6 +- crates/optimism/node/Cargo.toml | 3 + crates/optimism/node/src/txpool.rs | 10 +- crates/optimism/node/tests/e2e/utils.rs | 2 +- crates/optimism/payload/Cargo.toml | 1 + crates/optimism/payload/src/builder.rs | 157 ++-------- crates/optimism/payload/src/error.rs | 2 +- crates/optimism/payload/src/payload.rs | 26 +- crates/optimism/rpc/Cargo.toml | 6 +- crates/optimism/rpc/src/eth/call.rs | 6 +- crates/optimism/rpc/src/eth/pending_block.rs | 3 +- crates/optimism/rpc/src/eth/rpc.rs | 2 +- crates/payload/basic/src/lib.rs | 39 +++ crates/payload/builder/src/lib.rs | 2 +- crates/payload/builder/src/test_utils.rs | 1 - crates/payload/primitives/src/traits.rs | 5 +- crates/primitives-traits/src/constants/mod.rs | 2 - crates/primitives/src/transaction/compat.rs | 2 +- crates/primitives/src/transaction/mod.rs | 7 +- crates/rpc/rpc-api/Cargo.toml | 1 + crates/rpc/rpc-api/src/anvil.rs | 2 +- crates/rpc/rpc-api/src/debug.rs | 3 +- crates/rpc/rpc-api/src/engine.rs | 14 +- crates/rpc/rpc-api/src/ganache.rs | 2 +- crates/rpc/rpc-api/src/hardhat.rs | 2 +- crates/rpc/rpc-api/src/net.rs | 2 +- crates/rpc/rpc-api/src/otterscan.rs | 3 +- crates/rpc/rpc-api/src/reth.rs | 3 +- crates/rpc/rpc-api/src/trace.rs | 3 +- crates/rpc/rpc-api/src/txpool.rs | 2 +- crates/rpc/rpc-api/src/web3.rs | 2 +- crates/rpc/rpc-builder/Cargo.toml | 5 + crates/rpc/rpc-builder/src/lib.rs | 1 + crates/rpc/rpc-builder/tests/it/auth.rs | 3 +- crates/rpc/rpc-builder/tests/it/http.rs | 6 +- crates/rpc/rpc-builder/tests/it/serde.rs | 2 +- crates/rpc/rpc-builder/tests/it/utils.rs | 6 +- crates/rpc/rpc-engine-api/Cargo.toml | 4 + crates/rpc/rpc-engine-api/src/capabilities.rs | 1 + crates/rpc/rpc-engine-api/src/engine_api.rs | 69 +++-- crates/rpc/rpc-engine-api/src/error.rs | 11 +- crates/rpc/rpc-engine-api/tests/it/payload.rs | 3 +- crates/rpc/rpc-eth-api/Cargo.toml | 5 +- crates/rpc/rpc-eth-api/src/bundle.rs | 2 +- crates/rpc/rpc-eth-api/src/core.rs | 5 +- crates/rpc/rpc-eth-api/src/helpers/call.rs | 3 +- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 2 +- .../rpc-eth-api/src/helpers/pending_block.rs | 6 +- crates/rpc/rpc-eth-api/src/helpers/signer.rs | 3 +- crates/rpc/rpc-eth-api/src/helpers/spec.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/state.rs | 3 +- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 2 +- .../rpc-eth-api/src/helpers/transaction.rs | 4 +- crates/rpc/rpc-eth-api/src/types.rs | 1 - crates/rpc/rpc-eth-types/Cargo.toml | 2 + crates/rpc/rpc-eth-types/src/cache/db.rs | 14 +- crates/rpc/rpc-eth-types/src/cache/mod.rs | 3 +- crates/rpc/rpc-eth-types/src/error.rs | 3 +- crates/rpc/rpc-eth-types/src/fee_history.rs | 3 +- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 3 +- crates/rpc/rpc-eth-types/src/id_provider.rs | 2 +- crates/rpc/rpc-eth-types/src/logs_utils.rs | 5 +- crates/rpc/rpc-eth-types/src/pending_block.rs | 5 +- crates/rpc/rpc-eth-types/src/receipt.rs | 3 +- crates/rpc/rpc-eth-types/src/revm_utils.rs | 2 +- crates/rpc/rpc-eth-types/src/transaction.rs | 6 +- crates/rpc/rpc-eth-types/src/utils.rs | 3 +- crates/rpc/rpc-server-types/Cargo.toml | 1 - crates/rpc/rpc-server-types/src/result.rs | 2 +- crates/rpc/rpc-testing-util/Cargo.toml | 3 + crates/rpc/rpc-testing-util/src/debug.rs | 3 +- crates/rpc/rpc-testing-util/src/trace.rs | 3 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 3 +- crates/rpc/rpc-types-compat/Cargo.toml | 2 + crates/rpc/rpc-types-compat/src/block.rs | 3 +- .../rpc-types-compat/src/engine/payload.rs | 5 +- .../rpc-types-compat/src/transaction/mod.rs | 13 +- .../src/transaction/signature.rs | 3 +- crates/rpc/rpc-types/Cargo.toml | 2 + crates/rpc/rpc-types/src/lib.rs | 12 + crates/rpc/rpc/Cargo.toml | 2 +- crates/rpc/rpc/src/debug.rs | 13 +- crates/rpc/rpc/src/engine.rs | 3 +- crates/rpc/rpc/src/eth/bundle.rs | 4 +- crates/rpc/rpc/src/eth/core.rs | 10 +- crates/rpc/rpc/src/eth/filter.rs | 3 +- crates/rpc/rpc/src/eth/helpers/signer.rs | 7 +- crates/rpc/rpc/src/eth/helpers/spec.rs | 2 +- crates/rpc/rpc/src/eth/helpers/state.rs | 5 +- crates/rpc/rpc/src/eth/helpers/transaction.rs | 3 +- crates/rpc/rpc/src/eth/pubsub.rs | 3 +- crates/rpc/rpc/src/net.rs | 2 +- crates/rpc/rpc/src/otterscan.rs | 7 +- crates/rpc/rpc/src/reth.rs | 3 +- crates/rpc/rpc/src/trace.rs | 3 +- crates/rpc/rpc/src/txpool.rs | 3 +- crates/rpc/rpc/src/web3.rs | 2 +- crates/stages/api/src/pipeline/builder.rs | 2 +- crates/stages/api/src/pipeline/mod.rs | 2 +- .../static-file/src/segments/headers.rs | 8 +- .../static-file/src/segments/mod.rs | 7 +- .../static-file/src/segments/receipts.rs | 8 +- .../static-file/src/segments/transactions.rs | 8 +- .../static-file/src/static_file_producer.rs | 62 ++-- .../codecs/src/alloy/transaction/eip7702.rs | 4 +- crates/storage/db-api/Cargo.toml | 11 - crates/storage/db-api/src/models/blocks.rs | 11 +- crates/storage/db-api/src/models/mod.rs | 6 +- crates/storage/db-models/src/blocks.rs | 11 +- .../src}/client_version.rs | 0 crates/storage/db-models/src/lib.rs | 6 +- .../storage/db/src/implementation/mdbx/mod.rs | 2 +- crates/storage/db/src/lib.rs | 1 + crates/storage/db/src/tables/mod.rs | 4 +- .../src/providers/blockchain_provider.rs | 7 +- .../provider/src/providers/consistent_view.rs | 25 +- .../provider/src/providers/database/mod.rs | 7 +- .../src/providers/database/provider.rs | 14 +- crates/storage/provider/src/providers/mod.rs | 7 +- .../provider/src/traits/database_provider.rs | 9 - crates/storage/provider/src/traits/full.rs | 4 +- crates/storage/provider/src/traits/mod.rs | 3 - crates/storage/storage-api/Cargo.toml | 1 + .../storage-api/src/database_provider.rs | 36 +++ crates/storage/storage-api/src/lib.rs | 3 + crates/transaction-pool/Cargo.toml | 1 + crates/transaction-pool/src/blobstore/disk.rs | 26 ++ crates/transaction-pool/src/blobstore/mem.rs | 26 ++ crates/transaction-pool/src/blobstore/mod.rs | 7 + crates/transaction-pool/src/blobstore/noop.rs | 8 + crates/transaction-pool/src/lib.rs | 10 +- crates/transaction-pool/src/noop.rs | 18 +- crates/transaction-pool/src/traits.rs | 7 + crates/trie/common/Cargo.toml | 2 - crates/trie/common/src/account.rs | 111 +++++++ crates/trie/db/Cargo.toml | 1 - crates/trie/parallel/src/async_root.rs | 18 +- crates/trie/parallel/src/parallel_root.rs | 18 +- crates/trie/trie/Cargo.toml | 3 - etc/grafana/dashboards/overview.json | 82 ++++- examples/rpc-db/Cargo.toml | 1 - examples/rpc-db/src/main.rs | 3 +- 215 files changed, 1345 insertions(+), 1052 deletions(-) create mode 100644 crates/node/metrics/src/chain.rs rename crates/storage/{db-api/src/models => db-models/src}/client_version.rs (100%) delete mode 100644 crates/storage/provider/src/traits/database_provider.rs create mode 100644 crates/storage/storage-api/src/database_provider.rs diff --git a/.github/assets/hive/expected_failures.yaml b/.github/assets/hive/expected_failures.yaml index b82c9d131ebf..678ed8cf2806 100644 --- a/.github/assets/hive/expected_failures.yaml +++ b/.github/assets/hive/expected_failures.yaml @@ -63,8 +63,6 @@ engine-cancun: - Invalid Missing Ancestor Syncing ReOrg, StateRoot, EmptyTxs=False, CanonicalReOrg=True, Invalid P9 (Cancun) (reth) - Invalid PayloadAttributes, Missing BeaconRoot, Syncing=True (Cancun) (reth) - Invalid NewPayload, ParentBeaconBlockRoot, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - - Invalid NewPayload, BlobGasUsed, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - - Invalid NewPayload, Blob Count on BlobGasUsed, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - Invalid NewPayload, ExcessBlobGas, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) # https://github.com/paradigmxyz/reth/issues/8579 diff --git a/.github/assets/hive/expected_failures_experimental.yaml b/.github/assets/hive/expected_failures_experimental.yaml index 50686a9bcb78..8e92564adedb 100644 --- a/.github/assets/hive/expected_failures_experimental.yaml +++ b/.github/assets/hive/expected_failures_experimental.yaml @@ -50,8 +50,6 @@ engine-api: engine-cancun: - Blob Transaction Ordering, Multiple Clients (Cancun) (reth) - Invalid PayloadAttributes, Missing BeaconRoot, Syncing=True (Cancun) (reth) - - Invalid NewPayload, BlobGasUsed, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - - Invalid NewPayload, Blob Count on BlobGasUsed, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - Invalid NewPayload, ExcessBlobGas, Syncing=True, EmptyTxs=False, DynFeeTxs=False (Cancun) (reth) - Invalid Missing Ancestor ReOrg, StateRoot, EmptyTxs=False, Invalid P9 (Cancun) (reth) - Invalid Missing Ancestor ReOrg, StateRoot, EmptyTxs=True, Invalid P9 (Cancun) (reth) diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index 336004eded9f..4716486e688b 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -52,7 +52,7 @@ jobs: echo "EOF" >> $GITHUB_OUTPUT - name: Create Pull Request - uses: peter-evans/create-pull-request@v6 + uses: peter-evans/create-pull-request@v7 with: add-paths: ./Cargo.lock commit-message: ${{ steps.msg.outputs.commit_message }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 6f6042f0cd41..0eef396640a2 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -37,7 +37,10 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@clippy + - uses: dtolnay/rust-toolchain@nightly + with: + toolchain: nightly-2024-09-09 + components: clippy - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true diff --git a/Cargo.lock b/Cargo.lock index c6ea4064373d..7d011fe3b058 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,13 +4,19 @@ version = 3 [[package]] name = "addr2line" -version = "0.24.1" +version = "0.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" +checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" dependencies = [ "gimli", ] +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + [[package]] name = "adler2" version = "2.0.0" @@ -111,9 +117,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4177d135789e282e925092be8939d421b701c6d92c0a16679faa659d9166289d" +checksum = "1468e3128e07c7afe4ff13c17e8170c330d12c322f8924b8bf6986a27e0aad3d" dependencies = [ "alloy-eips", "alloy-primitives", @@ -171,9 +177,9 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "499ee14d296a133d142efd215eb36bf96124829fe91cf8f5d4e5ccdd381eae00" +checksum = "0c35df7b972b06f1b2f4e8b7a53328522fa788054a9d3e556faf2411c5a51d5a" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -190,9 +196,9 @@ dependencies = [ [[package]] name = "alloy-genesis" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b85dfc693e4a1193f0372a8f789df12ab51fcbe7be0733baa04939a86dd813b" +checksum = "0b7210f9206c0fa2a83c824cf8cb6c962126bc9fdc4f41ade1932f14150ef5f6" dependencies = [ "alloy-primitives", "alloy-serde", @@ -213,9 +219,9 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4207166c79cfdf7f3bed24bbc84f5c7c5d4db1970f8c82e3fcc76257f16d2166" +checksum = "8866562186d237f1dfeaf989ef941a24764f764bf5c33311e37ead3519c6a429" dependencies = [ "alloy-primitives", "alloy-sol-types", @@ -227,9 +233,9 @@ dependencies = [ [[package]] name = "alloy-network" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe2802d5b8c632f18d68c352073378f02a3407c1b6a4487194e7d21ab0f002" +checksum = "abe714e233f9eaf410de95a9af6bcd05d3a7f8c8de7a0817221e95a6b642a080" dependencies = [ "alloy-consensus", "alloy-eips", @@ -248,10 +254,11 @@ dependencies = [ [[package]] name = "alloy-network-primitives" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396c07726030fa0f9dab5da8c71ccd69d5eb74a7fe1072b7ae453a67e4fe553e" +checksum = "8c5a38117974c5776a45e140226745a0b664f79736aa900995d8e4121558e064" dependencies = [ + "alloy-eips", "alloy-primitives", "alloy-serde", "serde", @@ -259,9 +266,9 @@ dependencies = [ [[package]] name = "alloy-node-bindings" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c847311cc7386684ef38ab404069d795bee07da945f63d884265436870a17276" +checksum = "d149d4f3147b3494e1b1db8704e9fdb579e8c666c3deb7d070ebd5f38c2abb15" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -301,9 +308,9 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1376948df782ffee83a54cac4b2aba14134edd997229a3db97da0a606586eb5c" +checksum = "c65633d6ef83c3626913c004eaf166a6dd50406f724772ea8567135efd6dc5d3" dependencies = [ "alloy-chains", "alloy-consensus", @@ -339,9 +346,9 @@ dependencies = [ [[package]] name = "alloy-pubsub" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa73f976e7b6341f3f8a404241cf04f883d40212cd4f2633c66d99de472e262c" +checksum = "949db89abae6193b44cc90ebf2eeb74eb8d2a474383c5e62b45bdcd362e84f8f" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -352,7 +359,7 @@ dependencies = [ "serde_json", "tokio", "tokio-stream", - "tower", + "tower 0.5.1", "tracing", ] @@ -380,9 +387,9 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02378418a429f8a14a0ad8ffaa15b2d25ff34914fc4a1e366513c6a3800e03b3" +checksum = "d5fc328bb5d440599ba1b5aa44c0b9ab0625fbc3a403bb5ee94ed4a01ba23e07" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -397,29 +404,28 @@ dependencies = [ "serde_json", "tokio", "tokio-stream", - "tower", + "tower 0.5.1", "tracing", "url", ] [[package]] name = "alloy-rpc-types" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9ae4c4fbd37d9996f501fbc7176405aab97ae3a5772789be06ef0e7c4dad6dd" +checksum = "8f8ff679f94c497a8383f2cd09e2a099266e5f3d5e574bc82b4b379865707dbb" dependencies = [ "alloy-rpc-types-engine", "alloy-rpc-types-eth", - "alloy-rpc-types-trace", "alloy-serde", "serde", ] [[package]] name = "alloy-rpc-types-admin" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "594b7cb723759c7b438c95a3bbd2e391760c03ee857443070758aaf2593ae84e" +checksum = "cfeb75bc4dad84037f6ebd9385b8fe85833aac70c384e99855bc2f38cc35ab91" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -429,9 +435,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-anvil" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "140b079c6fda14d9586432bf988b46ac0e04871ca313c9e00aa85cc808105e8a" +checksum = "1d430bf98148565e67b2c08f033dd5fb27ce901c3481018941ce1524b9ad4fba" dependencies = [ "alloy-primitives", "alloy-serde", @@ -440,9 +446,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-beacon" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abbd9b6764423821bd6874477791ca68cfd0e946958d611319b57b006edf0113" +checksum = "b016035bb76144d04c071004383370d39def54d1a857171277f618112086b70e" dependencies = [ "alloy-eips", "alloy-primitives", @@ -454,9 +460,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-debug" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd56b9d938e458b8d4498b276bd3aaf0e8f0b58e86fe04fef2c71fed4b4c96de" +checksum = "1c037ac74c2aff58a6f8f82179b7f05c6b02b762b661abff9d8fe32056bc4a41" dependencies = [ "alloy-primitives", "serde", @@ -464,9 +470,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d79cadb52e32d40afa04847647eb50a332559d7870e66e46a0c32c33bf1c801d" +checksum = "b66bb45f4c5efe227bcb51d89c97221225169976e18097671a0bd4393d8248a4" dependencies = [ "alloy-consensus", "alloy-eips", @@ -483,9 +489,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bb3506ab1cf415d4752778c93e102050399fb8de97b7da405a5bf3e31f5f3b" +checksum = "9a59b1d7c86e0a653e7f3d29954f6de5a2878d8cfd1f010ff93be5c2c48cd3b1" dependencies = [ "alloy-consensus", "alloy-eips", @@ -504,9 +510,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-mev" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e8cb848b66617f7d58b576bfc416854c4e9ae8d35e14f5077c0c779048f280" +checksum = "456a942b962e140d574d09b52241bc9f4277203fb80bddb1f49de57ca3ce4e00" dependencies = [ "alloy-eips", "alloy-primitives", @@ -517,9 +523,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-trace" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16cca915e0aab3b2657b4f9efe02eb88e5483905fb6d244749652aae14e5f92e" +checksum = "c54375e5a34ec5a2cf607f9ce98c0ece30dc76ad623afeb25d3953a8d7d30f20" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -531,9 +537,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-txpool" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68eede4bd722bb872222efbbfbccc8f9b86e597143934b8ce556d3e0487bb662" +checksum = "65ae88491edfc8bbd55ba2b22b2ff24d4c522bacd8808461c4a232715fee3d22" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -543,9 +549,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae417978015f573b4a8c02af17f88558fb22e3fccd12e8a910cf6a2ff331cfcb" +checksum = "51db8a6428a2159e01b7a43ec7aac801edd0c4db1d4de06f310c288940f16fd3" dependencies = [ "alloy-primitives", "arbitrary", @@ -555,9 +561,9 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b750c9b61ac0646f8f4a61231c2732a337b2c829866fc9a191b96b7eedf80ffe" +checksum = "bebc1760c13592b7ba3fcd964abba546b8d6a9f10d15e8d92a8263731be33f36" dependencies = [ "alloy-primitives", "async-trait", @@ -569,9 +575,9 @@ dependencies = [ [[package]] name = "alloy-signer-local" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c640f9343e8f741f837c345c5ea30239ba77938b3691b884c736834853bd16c" +checksum = "3bfb3508485aa798efb5725322e414313239274d3780079b7f8c6746b8ee6e1b" dependencies = [ "alloy-consensus", "alloy-network", @@ -657,9 +663,9 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2799749ca692ae145f54968778877afd7c95e788488f176cfdfcf2a8abeb2062" +checksum = "fd5dc4e902f1860d54952446d246ac05386311ad61030a2b906ae865416d36e0" dependencies = [ "alloy-json-rpc", "base64 0.22.1", @@ -669,31 +675,31 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tower", + "tower 0.5.1", "tracing", "url", ] [[package]] name = "alloy-transport-http" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc10c4dd932f66e0db6cc5735241e0c17a6a18564b430bbc1839f7db18587a93" +checksum = "1742b94bb814f1ca6b322a6f9dd38a0252ff45a3119e40e888fb7029afa500ce" dependencies = [ "alloy-json-rpc", "alloy-transport", "reqwest", "serde_json", - "tower", + "tower 0.5.1", "tracing", "url", ] [[package]] name = "alloy-transport-ipc" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38f39f88798c3282914079a3eda3ea8b9fbf21e383a0ce85958b4f1c170d222f" +checksum = "be321aac6f06d86855d41d4ce9ff9feb877fe7e9fe1cafce7380b981c12398c7" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -710,9 +716,9 @@ dependencies = [ [[package]] name = "alloy-transport-ws" -version = "0.3.1" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65e732028930aa17b7edd464a9711365417635e984028fcc7176393ccea22c00" +checksum = "e8ed861e7030001364c8ffa2db63541f7bae275a6e636de7616c20f2fd3dc0c3" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -1125,17 +1131,17 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.74" +version = "0.3.73" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" dependencies = [ "addr2line", + "cc", "cfg-if", "libc", - "miniz_oxide", + "miniz_oxide 0.7.4", "object", "rustc-demangle", - "windows-targets 0.52.6", ] [[package]] @@ -2902,7 +2908,6 @@ dependencies = [ "reth", "reth-chainspec", "reth-db", - "reth-db-api", "reth-node-ethereum", "reth-provider", "tokio", @@ -3047,7 +3052,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "324a1be68054ef05ad64b861cc9eaf1d623d2d8cb25b4bf2cb9cdd902b4bf253" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.8.0", ] [[package]] @@ -3253,9 +3258,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.31.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" [[package]] name = "glob" @@ -3623,9 +3628,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.8" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da62f120a8a37763efb0cf8fdf264b884c7b8b9ac8660b900c8661030c00e6ba" +checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9" dependencies = [ "bytes", "futures-channel", @@ -3636,7 +3641,7 @@ dependencies = [ "pin-project-lite", "socket2 0.5.7", "tokio", - "tower", + "tower 0.4.13", "tower-service", "tracing", ] @@ -3987,9 +3992,9 @@ dependencies = [ [[package]] name = "intrusive-collections" -version = "0.9.7" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" +checksum = "b694dc9f70c3bda874626d2aed13b780f137aab435f4e9814121955cf706122e" dependencies = [ "memoffset", ] @@ -4200,7 +4205,7 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tower", + "tower 0.4.13", "tracing", "url", ] @@ -4241,7 +4246,7 @@ dependencies = [ "tokio", "tokio-stream", "tokio-util", - "tower", + "tower 0.4.13", "tracing", ] @@ -4705,6 +4710,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +dependencies = [ + "adler", +] + [[package]] name = "miniz_oxide" version = "0.8.0" @@ -5067,9 +5081,9 @@ checksum = "b410bbe7e14ab526a0e86877eb47c6996a2bd7746f027ba551028c925390e4e9" [[package]] name = "op-alloy-consensus" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b7fbb0f5c3754c22c6ea30e100dca6aea73b747e693e27763e23ca92fb02f2f" +checksum = "ad134a77fdfebac469526756b207c7889593657eeaca374200332ec89175e27a" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5084,9 +5098,9 @@ dependencies = [ [[package]] name = "op-alloy-network" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff4d24313531c4a988f590da377491accd4a108711b44243ccd6615a3afb9c3f" +checksum = "f4234322a67d2c0be701ea61381ac7c78984bda2fae0be3d8e0d1e055c583b2f" dependencies = [ "alloy-consensus", "alloy-eips", @@ -5099,10 +5113,11 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1fbb93dcb71aba9cd555784375011efce1fdaaea67e01972a0a9bc9eb90c626" +checksum = "f9fbd440cd8a5ccfa7c4c085b29fd0f0a1574fb53e1572f8e070cc105039e42b" dependencies = [ + "alloy-eips", "alloy-network", "alloy-primitives", "alloy-rpc-types-eth", @@ -5114,9 +5129,9 @@ dependencies = [ [[package]] name = "op-alloy-rpc-types-engine" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14716d1b1e82ca710de448f16efb62e29b2ed999f0ea0060801fd037666fabc7" +checksum = "b8b14dba2261a5d54e4502d41dcee03079b5d2d13d47a07b8ec2c67722af10c7" dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", @@ -5428,9 +5443,9 @@ dependencies = [ [[package]] name = "plotters" -version = "0.3.7" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" +checksum = "a15b6eccb8484002195a3e44fe65a4ce8e93a625797a063735536fd59cb01cf3" dependencies = [ "num-traits", "plotters-backend", @@ -5441,15 +5456,15 @@ dependencies = [ [[package]] name = "plotters-backend" -version = "0.3.7" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" +checksum = "414cec62c6634ae900ea1c56128dfe87cf63e7caece0852ec76aba307cebadb7" [[package]] name = "plotters-svg" -version = "0.3.7" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" +checksum = "81b30686a7d9c3e010b84284bdd26a29f2138574f52f5eb6f794fc0ad924e705" dependencies = [ "plotters-backend", ] @@ -6074,7 +6089,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper", + "sync_wrapper 1.0.1", "tokio", "tokio-rustls", "tokio-util", @@ -6306,7 +6321,7 @@ dependencies = [ "tikv-jemallocator", "tokio", "tokio-util", - "tower", + "tower 0.4.13", "tracing", ] @@ -6315,6 +6330,7 @@ name = "reth-blockchain-tree" version = "1.0.6" dependencies = [ "alloy-genesis", + "alloy-primitives", "aquamarine", "assert_matches", "linked_hash_set", @@ -6631,15 +6647,11 @@ name = "reth-db-api" version = "1.0.6" dependencies = [ "arbitrary", - "assert_matches", "bytes", - "criterion", "derive_more", - "iai-callgrind", "metrics", "modular-bitfield", "parity-scale-codec", - "pprof", "proptest", "proptest-arbitrary-interop", "rand 0.8.5", @@ -6895,7 +6907,6 @@ dependencies = [ "futures", "pin-project", "reth-beacon-consensus", - "reth-blockchain-tree", "reth-chainspec", "reth-consensus", "reth-engine-tree", @@ -6910,7 +6921,6 @@ dependencies = [ "reth-primitives", "reth-provider", "reth-prune", - "reth-prune-types", "reth-stages-api", "reth-tasks", "thiserror", @@ -7192,6 +7202,7 @@ dependencies = [ name = "reth-evm-optimism" version = "1.0.6" dependencies = [ + "alloy-primitives", "reth-chainspec", "reth-ethereum-forks", "reth-evm", @@ -7356,7 +7367,7 @@ dependencies = [ "tokio", "tokio-stream", "tokio-util", - "tower", + "tower 0.4.13", "tracing", ] @@ -7595,6 +7606,8 @@ dependencies = [ name = "reth-node-builder" version = "1.0.6" dependencies = [ + "alloy-network", + "alloy-primitives", "aquamarine", "eyre", "fdlimit", @@ -7656,6 +7669,7 @@ name = "reth-node-core" version = "1.0.6" dependencies = [ "alloy-genesis", + "alloy-primitives", "alloy-rpc-types-engine", "clap", "const_format", @@ -7672,7 +7686,6 @@ dependencies = [ "reth-config", "reth-consensus-common", "reth-db", - "reth-db-api", "reth-discv4", "reth-discv5", "reth-fs-util", @@ -7680,10 +7693,8 @@ dependencies = [ "reth-network", "reth-network-p2p", "reth-network-peers", - "reth-node-types", "reth-optimism-chainspec", "reth-primitives", - "reth-provider", "reth-prune-types", "reth-rpc-api", "reth-rpc-eth-api", @@ -7692,6 +7703,7 @@ dependencies = [ "reth-rpc-types", "reth-rpc-types-compat", "reth-stages-types", + "reth-storage-api", "reth-storage-errors", "reth-tracing", "reth-transaction-pool", @@ -7747,6 +7759,7 @@ dependencies = [ name = "reth-node-events" version = "1.0.6" dependencies = [ + "alloy-primitives", "alloy-rpc-types-engine", "futures", "humantime", @@ -7785,7 +7798,7 @@ dependencies = [ "socket2 0.4.10", "tikv-jemalloc-ctl", "tokio", - "tower", + "tower 0.4.13", "tracing", "vergen", ] @@ -7925,6 +7938,7 @@ dependencies = [ name = "reth-optimism-payload-builder" version = "1.0.6" dependencies = [ + "alloy-primitives", "alloy-rlp", "reth-basic-payload-builder", "reth-chain-state", @@ -8267,7 +8281,7 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", - "tower", + "tower 0.4.13", "tracing", "tracing-futures", ] @@ -8277,6 +8291,7 @@ name = "reth-rpc-api" version = "1.0.6" dependencies = [ "alloy-json-rpc", + "alloy-primitives", "jsonrpsee", "reth-engine-primitives", "reth-network-peers", @@ -8290,6 +8305,7 @@ dependencies = [ name = "reth-rpc-api-testing-util" version = "1.0.6" dependencies = [ + "alloy-primitives", "futures", "jsonrpsee", "jsonrpsee-http-client", @@ -8306,6 +8322,8 @@ dependencies = [ name = "reth-rpc-builder" version = "1.0.6" dependencies = [ + "alloy-network", + "alloy-primitives", "clap", "http", "jsonrpsee", @@ -8343,7 +8361,7 @@ dependencies = [ "serde_json", "thiserror", "tokio", - "tower", + "tower 0.4.13", "tower-http", "tracing", ] @@ -8352,6 +8370,7 @@ dependencies = [ name = "reth-rpc-engine-api" version = "1.0.6" dependencies = [ + "alloy-primitives", "alloy-rlp", "assert_matches", "async-trait", @@ -8375,6 +8394,7 @@ dependencies = [ "reth-tasks", "reth-testing-utils", "reth-tokio-util", + "reth-transaction-pool", "serde", "thiserror", "tokio", @@ -8388,6 +8408,7 @@ dependencies = [ "alloy-dyn-abi", "alloy-json-rpc", "alloy-network", + "alloy-primitives", "async-trait", "auto_impl", "dyn-clone", @@ -8421,6 +8442,8 @@ dependencies = [ name = "reth-rpc-eth-types" version = "1.0.6" dependencies = [ + "alloy-primitives", + "alloy-rpc-types", "alloy-sol-types", "derive_more", "futures", @@ -8467,7 +8490,7 @@ dependencies = [ "pin-project", "reqwest", "tokio", - "tower", + "tower 0.4.13", "tracing", ] @@ -8490,6 +8513,7 @@ dependencies = [ name = "reth-rpc-types" version = "1.0.6" dependencies = [ + "alloy-eips", "alloy-primitives", "alloy-rpc-types", "alloy-rpc-types-admin", @@ -8506,12 +8530,14 @@ dependencies = [ "op-alloy-rpc-types", "op-alloy-rpc-types-engine", "rand 0.8.5", + "serde", ] [[package]] name = "reth-rpc-types-compat" version = "1.0.6" dependencies = [ + "alloy-primitives", "alloy-rlp", "alloy-rpc-types", "reth-primitives", @@ -8658,6 +8684,7 @@ dependencies = [ "alloy-primitives", "auto_impl", "reth-chainspec", + "reth-db-api", "reth-db-models", "reth-execution-types", "reth-primitives", @@ -8757,6 +8784,7 @@ dependencies = [ "reth-metrics", "reth-primitives", "reth-provider", + "reth-rpc-types", "reth-storage-api", "reth-tasks", "reth-tracing", @@ -8791,16 +8819,13 @@ dependencies = [ "reth-execution-errors", "reth-metrics", "reth-primitives", - "reth-provider", "reth-stages-types", "reth-storage-errors", "reth-trie-common", "revm", "serde", "serde_json", - "similar-asserts", "tokio", - "tokio-stream", "tracing", "triehash", ] @@ -8827,8 +8852,6 @@ dependencies = [ "reth-primitives-traits", "revm-primitives", "serde", - "test-fuzz", - "toml", ] [[package]] @@ -8837,7 +8860,6 @@ version = "1.0.6" dependencies = [ "alloy-rlp", "auto_impl", - "criterion", "derive_more", "itertools 0.13.0", "metrics", @@ -8910,17 +8932,19 @@ dependencies = [ [[package]] name = "revm-inspectors" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48184032103bb23788e42e42c7c85207f5b0b8a248b09ea8f5233077f35ab56e" +checksum = "5d37cf496100c6ff1fb7de04a0e05318b7f36b36aec54054bdeeb3346fb2abeb" dependencies = [ "alloy-primitives", - "alloy-rpc-types", + "alloy-rpc-types-eth", + "alloy-rpc-types-trace", "alloy-sol-types", "anstyle", "boa_engine", "boa_gc", "colorchoice", + "intrusive-collections", "revm", "serde_json", "thiserror", @@ -9291,9 +9315,9 @@ dependencies = [ [[package]] name = "scc" -version = "2.1.17" +version = "2.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c947adb109a8afce5fc9c7bf951f87f146e9147b3a6a58413105628fb1d1e66" +checksum = "aeb7ac86243095b70a7920639507b71d51a63390d1ba26c4f60a552fbb914a37" dependencies = [ "sdd", ] @@ -9326,9 +9350,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sdd" -version = "3.0.3" +version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a7b59a5d9b0099720b417b6325d91a52cbf5b3dcb5041d864be53eefa58abc" +checksum = "0495e4577c672de8254beb68d01a9b62d0e8a13c099edecdbedccce3223cd29f" [[package]] name = "sec1" @@ -9928,6 +9952,12 @@ dependencies = [ "syn 2.0.77", ] +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + [[package]] name = "sync_wrapper" version = "1.0.1" @@ -10359,6 +10389,20 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper 0.1.2", + "tower-layer", + "tower-service", +] + [[package]] name = "tower-http" version = "0.5.2" @@ -10383,7 +10427,7 @@ dependencies = [ "pin-project-lite", "tokio", "tokio-util", - "tower", + "tower 0.4.13", "tower-layer", "tower-service", "tracing", diff --git a/Cargo.toml b/Cargo.toml index f304b66a4638..636cb6c3879b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -410,7 +410,7 @@ revm = { version = "14.0.0", features = [ "secp256k1", "blst", ], default-features = false } -revm-inspectors = "0.6" +revm-inspectors = "0.7" revm-primitives = { version = "9.0.0", features = [ "std", ], default-features = false } @@ -423,45 +423,45 @@ alloy-rlp = "0.3.4" alloy-sol-types = "0.8.0" alloy-trie = { version = "0.5", default-features = false } -alloy-consensus = { version = "0.3.1", default-features = false } -alloy-eips = { version = "0.3.1", default-features = false } -alloy-genesis = { version = "0.3.1", default-features = false } -alloy-json-rpc = { version = "0.3.1", default-features = false } -alloy-network = { version = "0.3.1", default-features = false } -alloy-node-bindings = { version = "0.3.1", default-features = false } -alloy-provider = { version = "0.3.1", features = [ +alloy-consensus = { version = "0.3.3", default-features = false } +alloy-eips = { version = "0.3.3", default-features = false } +alloy-genesis = { version = "0.3.3", default-features = false } +alloy-json-rpc = { version = "0.3.3", default-features = false } +alloy-network = { version = "0.3.3", default-features = false } +alloy-node-bindings = { version = "0.3.3", default-features = false } +alloy-provider = { version = "0.3.3", features = [ "reqwest", ], default-features = false } -alloy-pubsub = { version = "0.3.1", default-features = false } -alloy-rpc-client = { version = "0.3.1", default-features = false } -alloy-rpc-types = { version = "0.3.1", features = [ +alloy-pubsub = { version = "0.3.3", default-features = false } +alloy-rpc-client = { version = "0.3.3", default-features = false } +alloy-rpc-types = { version = "0.3.3", features = [ "eth", ], default-features = false } -alloy-rpc-types-admin = { version = "0.3.1", default-features = false } -alloy-rpc-types-anvil = { version = "0.3.1", default-features = false } -alloy-rpc-types-beacon = { version = "0.3.1", default-features = false } -alloy-rpc-types-debug = { version = "0.3.1", default-features = false } -alloy-rpc-types-engine = { version = "0.3.1", default-features = false } -alloy-rpc-types-eth = { version = "0.3.1", default-features = false } -alloy-rpc-types-mev = { version = "0.3.1", default-features = false } -alloy-rpc-types-trace = { version = "0.3.1", default-features = false } -alloy-rpc-types-txpool = { version = "0.3.1", default-features = false } -alloy-serde = { version = "0.3.1", default-features = false } -alloy-signer = { version = "0.3.1", default-features = false } -alloy-signer-local = { version = "0.3.1", default-features = false } -alloy-transport = { version = "0.3.1" } -alloy-transport-http = { version = "0.3.1", features = [ +alloy-rpc-types-admin = { version = "0.3.3", default-features = false } +alloy-rpc-types-anvil = { version = "0.3.3", default-features = false } +alloy-rpc-types-beacon = { version = "0.3.3", default-features = false } +alloy-rpc-types-debug = { version = "0.3.3", default-features = false } +alloy-rpc-types-engine = { version = "0.3.3", default-features = false } +alloy-rpc-types-eth = { version = "0.3.3", default-features = false } +alloy-rpc-types-mev = { version = "0.3.3", default-features = false } +alloy-rpc-types-trace = { version = "0.3.3", default-features = false } +alloy-rpc-types-txpool = { version = "0.3.3", default-features = false } +alloy-serde = { version = "0.3.3", default-features = false } +alloy-signer = { version = "0.3.3", default-features = false } +alloy-signer-local = { version = "0.3.3", default-features = false } +alloy-transport = { version = "0.3.3" } +alloy-transport-http = { version = "0.3.3", features = [ "reqwest-rustls-tls", ], default-features = false } -alloy-transport-ipc = { version = "0.3.1", default-features = false } -alloy-transport-ws = { version = "0.3.1", default-features = false } +alloy-transport-ipc = { version = "0.3.3", default-features = false } +alloy-transport-ws = { version = "0.3.3", default-features = false } alloy-network-primitives = { version = "0.3.1", default-features = false } # op -op-alloy-rpc-types = "0.2.8" -op-alloy-rpc-types-engine = "0.2.8" -op-alloy-network = "0.2.8" -op-alloy-consensus = "0.2.8" +op-alloy-rpc-types = "0.2.9" +op-alloy-rpc-types-engine = "0.2.9" +op-alloy-network = "0.2.9" +op-alloy-consensus = "0.2.9" # misc aquamarine = "0.5" diff --git a/bin/reth/src/cli/mod.rs b/bin/reth/src/cli/mod.rs index 8c1f5c246d52..665dbcba2bd5 100644 --- a/bin/reth/src/cli/mod.rs +++ b/bin/reth/src/cli/mod.rs @@ -45,7 +45,7 @@ pub struct Cli> Command { consensus: Arc, provider_factory: ProviderFactory, task_executor: &TaskExecutor, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, ) -> eyre::Result> where Client: BlockClient + 'static, diff --git a/bin/reth/src/lib.rs b/bin/reth/src/lib.rs index 452d10a23d60..f1a4d2467608 100644 --- a/bin/reth/src/lib.rs +++ b/bin/reth/src/lib.rs @@ -18,9 +18,6 @@ //! calls to the logging component is made. //! - `min-debug-logs`: Disables all logs below `debug` level. //! - `min-trace-logs`: Disables all logs below `trace` level. -//! - `optimism`: Enables [OP-Stack](https://stack.optimism.io/) support for the node. Note that -//! this breaks compatibility with the Ethereum mainnet as a new deposit transaction type is -//! introduced as well as gas cost changes. #![doc( html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png", diff --git a/book/run/optimism.md b/book/run/optimism.md index 4c2f09ef1954..ed71d1e0d9bc 100644 --- a/book/run/optimism.md +++ b/book/run/optimism.md @@ -42,20 +42,6 @@ Next, you'll need to install a [Rollup Node][rollup-node-spec], which is the equ For the sake of this tutorial, we'll use the reference implementation of the Rollup Node maintained by OP Labs, the `op-node`. The `op-node` can be built from source, or pulled from a [Docker image available on Google Cloud][op-node-docker]. -**`rethdb` build tag** -The `op-node` also comes with an experimental `rethdb` build tag, which allows it to read receipts directly from an L1 `reth` database during [derivation][derivation-spec]. This can speed up sync times, but it is not required if you do not -have access to the L1 archive node on the same machine as your L2 node. - -To build the `op-node` with the `rethdb` build tag enabled: -```sh -git clone https://github.com/ethereum-optimism/optimism.git && \ - (cd optimism/op-service/rethdb-reader && cargo build --release) && \ - cd optimism/op-node && \ - go build -v -tags rethdb -o ./bin/op-node ./cmd/main.go && \ - mv bin/op-node /usr/bin/op-node -``` -This will build the `rethdb-reader` dylib and instruct the `op-node` build to statically link this dylib into the binary. The `op-node` binary will be installed to `/usr/bin/op-node`. - ### Running `op-reth` The `optimism` feature flag in `op-reth` adds several new CLI flags to the `reth` binary: @@ -91,17 +77,6 @@ op-node \ Consider adding the `--l1.trustrpc` flag to improve performance, if the connection to l1 is over localhost. -If you opted to build the `op-node` with the `rethdb` build tag, this feature can be enabled by appending one extra flag to the `op-node` invocation: - -> Note, the `reth_db_path` is the path to the `db` folder inside of the reth datadir, not the `mdbx.dat` file itself. This can be fetched from `op-reth db path [--chain ]`, or if you are using a custom datadir location via the `--datadir` flag, -> by appending `/db` to the end of the path. - -```sh -op-node \ - # ... - --l1.rethdb= -``` - [l1-el-spec]: https://github.com/ethereum/execution-specs [rollup-node-spec]: https://github.com/ethereum-optimism/specs/blob/main/specs/protocol/rollup-node.md [op-geth-forkdiff]: https://op-geth.optimism.io diff --git a/crates/blockchain-tree/Cargo.toml b/crates/blockchain-tree/Cargo.toml index aa44282ae7d7..7d5f36008335 100644 --- a/crates/blockchain-tree/Cargo.toml +++ b/crates/blockchain-tree/Cargo.toml @@ -31,6 +31,9 @@ reth-network.workspace = true reth-consensus.workspace = true reth-node-types.workspace = true +# ethereum +alloy-primitives.workspace = true + # common parking_lot.workspace = true tracing.workspace = true diff --git a/crates/blockchain-tree/src/block_buffer.rs b/crates/blockchain-tree/src/block_buffer.rs index dd1b00eb9067..99729af0fae5 100644 --- a/crates/blockchain-tree/src/block_buffer.rs +++ b/crates/blockchain-tree/src/block_buffer.rs @@ -1,6 +1,7 @@ use crate::metrics::BlockBufferMetrics; +use alloy_primitives::{BlockHash, BlockNumber}; use reth_network::cache::LruCache; -use reth_primitives::{BlockHash, BlockNumber, SealedBlockWithSenders}; +use reth_primitives::SealedBlockWithSenders; use std::collections::{btree_map, hash_map, BTreeMap, HashMap, HashSet}; /// Contains the tree of pending blocks that cannot be executed due to missing parent. @@ -182,7 +183,8 @@ impl BlockBuffer { #[cfg(test)] mod tests { use crate::BlockBuffer; - use reth_primitives::{BlockHash, BlockNumHash, SealedBlockWithSenders}; + use alloy_primitives::BlockHash; + use reth_primitives::{BlockNumHash, SealedBlockWithSenders}; use reth_testing_utils::generators::{self, random_block, BlockParams, Rng}; use std::collections::HashMap; diff --git a/crates/blockchain-tree/src/block_indices.rs b/crates/blockchain-tree/src/block_indices.rs index 42e37ad94171..fb132bdedc4c 100644 --- a/crates/blockchain-tree/src/block_indices.rs +++ b/crates/blockchain-tree/src/block_indices.rs @@ -2,9 +2,10 @@ use super::state::SidechainId; use crate::canonical_chain::CanonicalChain; +use alloy_primitives::{BlockHash, BlockNumber}; use linked_hash_set::LinkedHashSet; use reth_execution_types::Chain; -use reth_primitives::{BlockHash, BlockNumHash, BlockNumber, SealedBlockWithSenders}; +use reth_primitives::{BlockNumHash, SealedBlockWithSenders}; use std::collections::{btree_map, hash_map, BTreeMap, BTreeSet, HashMap, HashSet}; /// Internal indices of the blocks and chains. @@ -178,7 +179,7 @@ impl BlockIndices { if new_block_value.1 != old_block_value.1 { // remove block hash as it is different removed.push(old_block_value); - added.push(new_block_value.into()); + added.push(new_block_value.into()) } new_hash = new_hashes.next(); old_hash = old_hashes.next(); @@ -375,7 +376,8 @@ impl BlockIndices { #[cfg(test)] mod tests { use super::*; - use reth_primitives::{Header, SealedBlock, SealedHeader, B256}; + use alloy_primitives::B256; + use reth_primitives::{Header, SealedBlock, SealedHeader}; #[test] fn pending_block_num_hash_returns_none_if_no_fork() { diff --git a/crates/blockchain-tree/src/blockchain_tree.rs b/crates/blockchain-tree/src/blockchain_tree.rs index a48d03a98775..23896ac50668 100644 --- a/crates/blockchain-tree/src/blockchain_tree.rs +++ b/crates/blockchain-tree/src/blockchain_tree.rs @@ -5,6 +5,7 @@ use crate::{ state::{SidechainId, TreeState}, AppendableChain, BlockIndices, BlockchainTreeConfig, ExecutionData, TreeExternals, }; +use alloy_primitives::{BlockHash, BlockNumber, B256, U256}; use reth_blockchain_tree_api::{ error::{BlockchainTreeError, CanonicalError, InsertBlockError, InsertBlockErrorKind}, BlockAttachment, BlockStatus, BlockValidationKind, CanonicalOutcome, InsertPayloadOk, @@ -15,8 +16,8 @@ use reth_execution_errors::{BlockExecutionError, BlockValidationError}; use reth_execution_types::{Chain, ExecutionOutcome}; use reth_node_types::NodeTypesWithDB; use reth_primitives::{ - BlockHash, BlockNumHash, BlockNumber, EthereumHardfork, ForkBlock, GotExpected, Receipt, - SealedBlock, SealedBlockWithSenders, SealedHeader, StaticFileSegment, B256, U256, + BlockNumHash, EthereumHardfork, ForkBlock, GotExpected, Receipt, SealedBlock, + SealedBlockWithSenders, SealedHeader, StaticFileSegment, }; use reth_provider::{ providers::ProviderNodeTypes, BlockExecutionWriter, BlockNumReader, BlockWriter, @@ -187,7 +188,7 @@ where ) -> Result, InsertBlockErrorKind> { // check if block is canonical if self.is_block_hash_canonical(&block.hash)? { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); } let last_finalized_block = self.block_indices().last_finalized_block(); @@ -195,7 +196,7 @@ where if block.number <= last_finalized_block { // check if block is inside database if self.externals.provider_factory.provider()?.block_number(block.hash)?.is_some() { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); } return Err(BlockchainTreeError::PendingBlockIsFinalized { @@ -206,7 +207,7 @@ where // is block inside chain if let Some(attachment) = self.is_block_inside_sidechain(&block) { - return Ok(Some(BlockStatus::Valid(attachment))) + return Ok(Some(BlockStatus::Valid(attachment))); } // check if block is disconnected @@ -290,7 +291,7 @@ where let Some((first_pending_block_number, _)) = parent_block_hashes.first_key_value() else { debug!(target: "blockchain_tree", ?chain_id, "No block hashes stored"); - return None + return None; }; let canonical_chain = canonical_chain .iter() @@ -300,7 +301,7 @@ where // get canonical fork. let canonical_fork = self.canonical_fork(chain_id)?; - return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }) + return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }); } // check if there is canonical block @@ -310,7 +311,7 @@ where canonical_fork: ForkBlock { number: canonical_number, hash: block_hash }, execution_outcome: ExecutionOutcome::default(), parent_block_hashes: canonical_chain.inner().clone(), - }) + }); } None @@ -333,12 +334,12 @@ where // check if block parent can be found in any side chain. if let Some(chain_id) = self.block_indices().get_side_chain_id(&parent.hash) { // found parent in side tree, try to insert there - return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind) + return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind); } // if not found, check if the parent can be found inside canonical chain. if self.is_block_hash_canonical(&parent.hash)? { - return self.try_append_canonical_chain(block.clone(), block_validation_kind) + return self.try_append_canonical_chain(block.clone(), block_validation_kind); } // this is another check to ensure that if the block points to a canonical block its block @@ -689,7 +690,7 @@ where pub fn buffer_block(&mut self, block: SealedBlockWithSenders) -> Result<(), InsertBlockError> { // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)) + return Err(InsertBlockError::consensus_error(err, block.block)); } self.state.buffered_blocks.insert_block(block); @@ -707,17 +708,17 @@ where "Failed to validate total difficulty for block {}: {e}", block.header.hash() ); - return Err(e) + return Err(e); } if let Err(e) = self.externals.consensus.validate_header(block) { error!(?block, "Failed to validate header {}: {e}", block.header.hash()); - return Err(e) + return Err(e); } if let Err(e) = self.externals.consensus.validate_block_pre_execution(block) { error!(?block, "Failed to validate block {}: {e}", block.header.hash()); - return Err(e) + return Err(e); } Ok(()) @@ -742,7 +743,7 @@ where Some(BlockAttachment::Canonical) } else { Some(BlockAttachment::HistoricalFork) - } + }; } None } @@ -783,7 +784,7 @@ where // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)) + return Err(InsertBlockError::consensus_error(err, block.block)); } let status = self @@ -1057,7 +1058,7 @@ where } let head = self.state.block_indices.canonical_tip(); - return Ok(CanonicalOutcome::AlreadyCanonical { header, head }) + return Ok(CanonicalOutcome::AlreadyCanonical { header, head }); } let Some(chain_id) = self.block_indices().get_side_chain_id(&block_hash) else { @@ -1072,7 +1073,7 @@ where debug!(target: "blockchain_tree", ?block_hash, ?chain_id, "Chain not present"); return Err(CanonicalError::from(BlockchainTreeError::BlockSideChainIdConsistency { chain_id: chain_id.into(), - })); + })) }; trace!(target: "blockchain_tree", chain = ?canonical, "Found chain to make canonical"); durations_recorder.record_relative(MakeCanonicalAction::SplitChain); @@ -1102,7 +1103,7 @@ where debug!(target: "blockchain_tree", "No blocks in the chain to make canonical"); return Err(CanonicalError::from(BlockchainTreeError::BlockHashNotFoundInChain { block_hash: fork_block.hash, - })); + })) }; trace!(target: "blockchain_tree", ?new_canon_chain, "Merging chains"); let mut chain_appended = false; @@ -1283,7 +1284,7 @@ where pub fn unwind(&mut self, unwind_to: BlockNumber) -> Result<(), CanonicalError> { // nothing to be done if unwind_to is higher then the tip if self.block_indices().canonical_tip().number <= unwind_to { - return Ok(()) + return Ok(()); } // revert `N` blocks from current canonical chain and put them inside BlockchainTree let old_canon_chain = self.revert_canonical_from_database(unwind_to)?; @@ -1325,7 +1326,7 @@ where "Reverting optimistic canonical chain to block {}", revert_until ); - return Err(CanonicalError::OptimisticTargetRevert(revert_until)) + return Err(CanonicalError::OptimisticTargetRevert(revert_until)); } // read data that is needed for new sidechain @@ -1379,6 +1380,7 @@ where mod tests { use super::*; use alloy_genesis::{Genesis, GenesisAccount}; + use alloy_primitives::{keccak256, Address, B256}; use assert_matches::assert_matches; use linked_hash_set::LinkedHashSet; use reth_chainspec::{ChainSpecBuilder, MAINNET}; @@ -1389,11 +1391,10 @@ mod tests { use reth_evm_ethereum::execute::EthExecutorProvider; use reth_primitives::{ constants::{EIP1559_INITIAL_BASE_FEE, EMPTY_ROOT_HASH}, - keccak256, proofs::{calculate_receipt_root, calculate_transaction_root}, revm_primitives::AccountInfo, - Account, Address, Header, Signature, Transaction, TransactionSigned, - TransactionSignedEcRecovered, TxEip1559, Withdrawals, B256, + Account, Header, Signature, Transaction, TransactionSigned, TransactionSignedEcRecovered, + TxEip1559, Withdrawals, }; use reth_provider::{ test_utils::{ diff --git a/crates/blockchain-tree/src/bundle.rs b/crates/blockchain-tree/src/bundle.rs index e10adecdcac1..226afd8fab59 100644 --- a/crates/blockchain-tree/src/bundle.rs +++ b/crates/blockchain-tree/src/bundle.rs @@ -1,6 +1,7 @@ //! [`ExecutionDataProvider`] implementations used by the tree. -use reth_primitives::{BlockHash, BlockNumber, ForkBlock}; +use alloy_primitives::{BlockHash, BlockNumber}; +use reth_primitives::ForkBlock; use reth_provider::{BlockExecutionForkProvider, ExecutionDataProvider, ExecutionOutcome}; use std::collections::BTreeMap; @@ -25,7 +26,7 @@ impl<'a> ExecutionDataProvider for BundleStateDataRef<'a> { fn block_hash(&self, block_number: BlockNumber) -> Option { let block_hash = self.sidechain_block_hashes.get(&block_number).copied(); if block_hash.is_some() { - return block_hash + return block_hash; } self.canonical_block_hashes.get(&block_number).copied() diff --git a/crates/blockchain-tree/src/canonical_chain.rs b/crates/blockchain-tree/src/canonical_chain.rs index e01e52dcb02f..e3dc596ba0e7 100644 --- a/crates/blockchain-tree/src/canonical_chain.rs +++ b/crates/blockchain-tree/src/canonical_chain.rs @@ -1,4 +1,5 @@ -use reth_primitives::{BlockHash, BlockNumHash, BlockNumber}; +use alloy_primitives::{BlockHash, BlockNumber}; +use reth_primitives::BlockNumHash; use std::collections::BTreeMap; /// This keeps track of (non-finalized) blocks of the canonical chain. diff --git a/crates/blockchain-tree/src/chain.rs b/crates/blockchain-tree/src/chain.rs index df20a142a312..b54e8730433c 100644 --- a/crates/blockchain-tree/src/chain.rs +++ b/crates/blockchain-tree/src/chain.rs @@ -5,6 +5,7 @@ use super::externals::TreeExternals; use crate::BundleStateDataRef; +use alloy_primitives::{BlockHash, BlockNumber, U256}; use reth_blockchain_tree_api::{ error::{BlockchainTreeError, InsertBlockErrorKind}, BlockAttachment, BlockValidationKind, @@ -13,9 +14,7 @@ use reth_consensus::{Consensus, ConsensusError, PostExecutionInput}; use reth_evm::execute::{BlockExecutorProvider, Executor}; use reth_execution_errors::BlockExecutionError; use reth_execution_types::{Chain, ExecutionOutcome}; -use reth_primitives::{ - BlockHash, BlockNumber, ForkBlock, GotExpected, SealedBlockWithSenders, SealedHeader, U256, -}; +use reth_primitives::{ForkBlock, GotExpected, SealedBlockWithSenders, SealedHeader}; use reth_provider::{ providers::{BundleStateProvider, ConsistentDbView, ProviderNodeTypes}, FullExecutionDataProvider, ProviderError, StateRootProvider, diff --git a/crates/blockchain-tree/src/externals.rs b/crates/blockchain-tree/src/externals.rs index 5991e55324d0..a4f72f6d33d7 100644 --- a/crates/blockchain-tree/src/externals.rs +++ b/crates/blockchain-tree/src/externals.rs @@ -1,10 +1,11 @@ //! Blockchain tree externals. +use alloy_primitives::{BlockHash, BlockNumber}; use reth_consensus::Consensus; use reth_db::{static_file::HeaderMask, tables}; use reth_db_api::{cursor::DbCursorRO, transaction::DbTx}; use reth_node_types::NodeTypesWithDB; -use reth_primitives::{BlockHash, BlockNumber, StaticFileSegment}; +use reth_primitives::StaticFileSegment; use reth_provider::{ providers::ProviderNodeTypes, FinalizedBlockReader, FinalizedBlockWriter, ProviderFactory, StaticFileProviderFactory, StatsReader, diff --git a/crates/blockchain-tree/src/noop.rs b/crates/blockchain-tree/src/noop.rs index d92131dc8ac2..76e59a47792f 100644 --- a/crates/blockchain-tree/src/noop.rs +++ b/crates/blockchain-tree/src/noop.rs @@ -1,13 +1,11 @@ +use alloy_primitives::{BlockHash, BlockNumber}; use reth_blockchain_tree_api::{ self, error::{BlockchainTreeError, CanonicalError, InsertBlockError, ProviderError}, BlockValidationKind, BlockchainTreeEngine, BlockchainTreeViewer, CanonicalOutcome, InsertPayloadOk, }; -use reth_primitives::{ - BlockHash, BlockNumHash, BlockNumber, Receipt, SealedBlock, SealedBlockWithSenders, - SealedHeader, -}; +use reth_primitives::{BlockNumHash, Receipt, SealedBlock, SealedBlockWithSenders, SealedHeader}; use reth_provider::{ BlockchainTreePendingStateProvider, CanonStateNotificationSender, CanonStateNotifications, CanonStateSubscriptions, FullExecutionDataProvider, diff --git a/crates/blockchain-tree/src/shareable.rs b/crates/blockchain-tree/src/shareable.rs index 3cfabe1cdbd3..333527b83ef7 100644 --- a/crates/blockchain-tree/src/shareable.rs +++ b/crates/blockchain-tree/src/shareable.rs @@ -1,6 +1,7 @@ //! Wrapper around `BlockchainTree` that allows for it to be shared. use super::BlockchainTree; +use alloy_primitives::{BlockHash, BlockNumber}; use parking_lot::RwLock; use reth_blockchain_tree_api::{ error::{CanonicalError, InsertBlockError}, @@ -9,10 +10,7 @@ use reth_blockchain_tree_api::{ }; use reth_evm::execute::BlockExecutorProvider; use reth_node_types::NodeTypesWithDB; -use reth_primitives::{ - BlockHash, BlockNumHash, BlockNumber, Receipt, SealedBlock, SealedBlockWithSenders, - SealedHeader, -}; +use reth_primitives::{BlockNumHash, Receipt, SealedBlock, SealedBlockWithSenders, SealedHeader}; use reth_provider::{ providers::ProviderNodeTypes, BlockchainTreePendingStateProvider, CanonStateSubscriptions, FullExecutionDataProvider, ProviderError, diff --git a/crates/blockchain-tree/src/state.rs b/crates/blockchain-tree/src/state.rs index dcf91d8bbddb..b76db9e6a9ce 100644 --- a/crates/blockchain-tree/src/state.rs +++ b/crates/blockchain-tree/src/state.rs @@ -1,7 +1,8 @@ //! Blockchain tree state. use crate::{AppendableChain, BlockBuffer, BlockIndices}; -use reth_primitives::{BlockHash, BlockNumber, Receipt, SealedBlock, SealedBlockWithSenders}; +use alloy_primitives::{BlockHash, BlockNumber}; +use reth_primitives::{Receipt, SealedBlock, SealedBlockWithSenders}; use std::collections::{BTreeMap, HashMap}; /// Container to hold the state of the blockchain tree. diff --git a/crates/cli/cli/src/chainspec.rs b/crates/cli/cli/src/chainspec.rs index 5eb9c820b93d..63705bd28f4a 100644 --- a/crates/cli/cli/src/chainspec.rs +++ b/crates/cli/cli/src/chainspec.rs @@ -57,7 +57,7 @@ pub trait ChainSpecParser: Clone + Send + Sync + 'static { } /// Produces a help message for the chain spec argument. - fn help_messge() -> String { + fn help_message() -> String { format!("The chain this node is running.\nPossible values are either a built-in chain or the path to a chain specification file.\n\nBuilt-in chains:\n {}", Self::SUPPORTED_CHAINS.join(", ")) } } diff --git a/crates/cli/commands/src/common.rs b/crates/cli/commands/src/common.rs index 3b86417e5db3..2f24dbca2983 100644 --- a/crates/cli/commands/src/common.rs +++ b/crates/cli/commands/src/common.rs @@ -39,7 +39,7 @@ pub struct EnvironmentArgs { #[arg( long, value_name = "CHAIN_OR_PATH", - long_help = C::help_messge(), + long_help = C::help_message(), default_value = C::SUPPORTED_CHAINS[0], value_parser = C::parser() )] diff --git a/crates/cli/commands/src/dump_genesis.rs b/crates/cli/commands/src/dump_genesis.rs index a12c9d80c169..30d3bc9651df 100644 --- a/crates/cli/commands/src/dump_genesis.rs +++ b/crates/cli/commands/src/dump_genesis.rs @@ -14,7 +14,7 @@ pub struct DumpGenesisCommand { #[arg( long, value_name = "CHAIN_OR_PATH", - long_help = C::help_messge(), + long_help = C::help_message(), default_value = C::SUPPORTED_CHAINS[0], value_parser = C::parser() )] diff --git a/crates/cli/commands/src/import.rs b/crates/cli/commands/src/import.rs index 2ab1287328bd..5b35e8aa1c7b 100644 --- a/crates/cli/commands/src/import.rs +++ b/crates/cli/commands/src/import.rs @@ -163,7 +163,7 @@ pub fn build_import_pipeline( provider_factory: ProviderFactory, consensus: &Arc, file_client: Arc, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, disable_exec: bool, executor: E, ) -> eyre::Result<(Pipeline, impl Stream)> diff --git a/crates/cli/commands/src/node.rs b/crates/cli/commands/src/node.rs index 704e931a3aa6..f92a0cdbaf6d 100644 --- a/crates/cli/commands/src/node.rs +++ b/crates/cli/commands/src/node.rs @@ -34,7 +34,7 @@ pub struct NodeCommand< #[arg( long, value_name = "CHAIN_OR_PATH", - long_help = C::help_messge(), + long_help = C::help_message(), default_value = C::SUPPORTED_CHAINS[0], default_value_if("dev", "true", "dev"), value_parser = C::parser(), diff --git a/crates/cli/commands/src/p2p/mod.rs b/crates/cli/commands/src/p2p/mod.rs index 326fdb23585a..4622c638b0c3 100644 --- a/crates/cli/commands/src/p2p/mod.rs +++ b/crates/cli/commands/src/p2p/mod.rs @@ -31,7 +31,7 @@ pub struct Command { #[arg( long, value_name = "CHAIN_OR_PATH", - long_help = C::help_messge(), + long_help = C::help_message(), default_value = C::SUPPORTED_CHAINS[0], value_parser = C::parser() )] diff --git a/crates/cli/commands/src/stage/run.rs b/crates/cli/commands/src/stage/run.rs index e0c2898eca53..b80c2724c4df 100644 --- a/crates/cli/commands/src/stage/run.rs +++ b/crates/cli/commands/src/stage/run.rs @@ -28,6 +28,7 @@ use reth_node_core::{ }, }; use reth_node_metrics::{ + chain::ChainSpecInfo, hooks::Hooks, server::{MetricServer, MetricServerConfig}, version::VersionInfo, @@ -130,6 +131,7 @@ impl> Command { target_triple: VERGEN_CARGO_TARGET_TRIPLE, build_profile: BUILD_PROFILE_NAME, }, + ChainSpecInfo { name: provider_factory.chain_spec().chain.to_string() }, ctx.task_executor, Hooks::new( provider_factory.db_ref().clone(), diff --git a/crates/consensus/beacon/src/engine/hooks/static_file.rs b/crates/consensus/beacon/src/engine/hooks/static_file.rs index fbadb5e5cfd3..8a5a28f95741 100644 --- a/crates/consensus/beacon/src/engine/hooks/static_file.rs +++ b/crates/consensus/beacon/src/engine/hooks/static_file.rs @@ -7,9 +7,10 @@ use crate::{ use alloy_primitives::BlockNumber; use futures::FutureExt; use reth_errors::RethResult; -use reth_node_types::NodeTypesWithDB; use reth_primitives::static_file::HighestStaticFiles; -use reth_provider::providers::ProviderNodeTypes; +use reth_provider::{ + BlockReader, DatabaseProviderFactory, StageCheckpointReader, StaticFileProviderFactory, +}; use reth_static_file::{StaticFileProducer, StaticFileProducerWithResult}; use reth_tasks::TaskSpawner; use std::task::{ready, Context, Poll}; @@ -20,17 +21,22 @@ use tracing::trace; /// /// This type controls the [`StaticFileProducer`]. #[derive(Debug)] -pub struct StaticFileHook { +pub struct StaticFileHook { /// The current state of the `static_file_producer`. - state: StaticFileProducerState, + state: StaticFileProducerState, /// The type that can spawn the `static_file_producer` task. task_spawner: Box, } -impl StaticFileHook { +impl StaticFileHook +where + Provider: StaticFileProviderFactory + + DatabaseProviderFactory + + 'static, +{ /// Create a new instance pub fn new( - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer, task_spawner: Box, ) -> Self { Self { state: StaticFileProducerState::Idle(Some(static_file_producer)), task_spawner } @@ -128,7 +134,12 @@ impl StaticFileHook { } } -impl EngineHook for StaticFileHook { +impl EngineHook for StaticFileHook +where + Provider: StaticFileProviderFactory + + DatabaseProviderFactory + + 'static, +{ fn name(&self) -> &'static str { "StaticFile" } @@ -164,9 +175,9 @@ impl EngineHook for StaticFileHook { /// [`StaticFileProducerState::Idle`] means that the static file producer is currently idle. /// [`StaticFileProducerState::Running`] means that the static file producer is currently running. #[derive(Debug)] -enum StaticFileProducerState { +enum StaticFileProducerState { /// [`StaticFileProducer`] is idle. - Idle(Option>), + Idle(Option>), /// [`StaticFileProducer`] is running and waiting for a response - Running(oneshot::Receiver>), + Running(oneshot::Receiver>), } diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index adf50107222c..45a9ebd1a1d7 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -7,7 +7,10 @@ use reth::{ args::{DiscoveryArgs, NetworkArgs, RpcServerArgs}, builder::{NodeBuilder, NodeConfig, NodeHandle}, network::PeersHandleProvider, - rpc::api::eth::{helpers::AddDevSigners, FullEthApiServer}, + rpc::{ + api::eth::{helpers::AddDevSigners, FullEthApiServer}, + types::AnyTransactionReceipt, + }, tasks::TaskManager, }; use reth_chainspec::ChainSpec; diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 0eb141bc159e..d1c241216542 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -11,7 +11,7 @@ use reth::{ providers::{BlockReader, BlockReaderIdExt, CanonStateSubscriptions, StageCheckpointReader}, rpc::{ api::eth::helpers::{EthApiSpec, EthTransactions, TraceExt}, - types::engine::PayloadStatusEnum, + types::{engine::PayloadStatusEnum, AnyTransactionReceipt}, }, }; use reth_chainspec::ChainSpec; @@ -87,11 +87,18 @@ where attributes_generator: impl Fn(u64) -> Engine::PayloadBuilderAttributes + Copy, ) -> eyre::Result> where - ::ExecutionPayloadV3: - From + PayloadEnvelopeExt, - AddOns::EthApi: EthApiSpec + EthTransactions + TraceExt, - ::NetworkTypes: - Network>, + Engine::ExecutionPayloadV3: From + PayloadEnvelopeExt, + AddOns::EthApi: EthApiSpec + + EthTransactions + + TraceExt + + EthApiTypes< + NetworkTypes: Network< + TransactionResponse = WithOtherFields, + TransactionCompat: TransactionCompat< + Transaction = RpcTransaction<::NetworkTypes>, + >, + >, + >, { let mut chain = Vec::with_capacity(length as usize); for i in 0..length { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index a7d3030f1286..3289e619f106 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -3,14 +3,17 @@ use alloy_network::{eip2718::Decodable2718, Network}; use reth::{ builder::{rpc::RpcRegistry, FullNodeComponents}, rpc::api::{ - eth::helpers::{EthApiSpec, EthTransactions, TraceExt}, + eth::{ + helpers::{EthApiSpec, EthTransactions, TraceExt}, + RpcTransaction, + }, DebugApiServer, }, }; use reth_chainspec::ChainSpec; use reth_node_builder::{EthApiTypes, NodeTypes}; use reth_primitives::{Bytes, B256}; -use reth_rpc_types::WithOtherFields; +use reth_rpc_types::{AnyTransactionReceipt, WithOtherFields}; #[allow(missing_debug_implementations)] pub struct RpcTestContext { @@ -25,6 +28,9 @@ where NetworkTypes: Network< TransactionResponse = WithOtherFields, >, + TransactionCompat: TransactionCompat< + Transaction = RpcTransaction, + >, > + TraceExt, { /// Injects a raw transaction into the node tx pool via RPC server diff --git a/crates/engine/service/Cargo.toml b/crates/engine/service/Cargo.toml index 1cee7506ac6f..63d5f1fb9766 100644 --- a/crates/engine/service/Cargo.toml +++ b/crates/engine/service/Cargo.toml @@ -33,14 +33,11 @@ pin-project.workspace = true thiserror.workspace = true [dev-dependencies] -reth-blockchain-tree.workspace = true -reth-consensus.workspace = true reth-engine-tree = { workspace = true, features = ["test-utils"] } reth-ethereum-engine-primitives.workspace = true reth-evm-ethereum.workspace = true reth-exex-types.workspace = true reth-primitives.workspace = true -reth-prune-types.workspace = true reth-chainspec.workspace = true tokio = { workspace = true, features = ["sync"] } diff --git a/crates/engine/service/src/service.rs b/crates/engine/service/src/service.rs index 9ce2086e4e5a..2be1bcca8643 100644 --- a/crates/engine/service/src/service.rs +++ b/crates/engine/service/src/service.rs @@ -20,7 +20,7 @@ use reth_payload_builder::PayloadBuilderHandle; use reth_payload_validator::ExecutionPayloadValidator; use reth_provider::{providers::BlockchainProvider2, ProviderFactory}; use reth_prune::Pruner; -use reth_stages_api::Pipeline; +use reth_stages_api::{MetricEventsSender, Pipeline}; use reth_tasks::TaskSpawner; use std::{ marker::PhantomData, @@ -77,10 +77,12 @@ where payload_builder: PayloadBuilderHandle, tree_config: TreeConfig, invalid_block_hook: Box, + sync_metrics_tx: MetricEventsSender, ) -> Self { let downloader = BasicBlockDownloader::new(client, consensus.clone()); - let persistence_handle = PersistenceHandle::spawn_service(provider, pruner); + let persistence_handle = + PersistenceHandle::spawn_service(provider, pruner, sync_metrics_tx); let payload_validator = ExecutionPayloadValidator::new(chain_spec); let canonical_in_memory_state = blockchain_db.canonical_in_memory_state(); @@ -179,6 +181,7 @@ mod tests { let pruner = Pruner::<_, ProviderFactory<_>>::new(provider_factory.clone(), vec![], 0, 0, None, rx); + let (sync_metrics_tx, _sync_metrics_rx) = unbounded_channel(); let (tx, _rx) = unbounded_channel(); let _eth_service = EngineService::new( consensus, @@ -194,6 +197,7 @@ mod tests { PayloadBuilderHandle::new(tx), TreeConfig::default(), Box::new(NoopInvalidBlockHook::default()), + sync_metrics_tx, ); } } diff --git a/crates/engine/tree/src/download.rs b/crates/engine/tree/src/download.rs index ec173e227a4b..04c94f144688 100644 --- a/crates/engine/tree/src/download.rs +++ b/crates/engine/tree/src/download.rs @@ -163,8 +163,9 @@ where /// Sets the metrics for the active downloads fn update_block_download_metrics(&self) { - self.metrics.active_block_downloads.set(self.inflight_full_block_requests.len() as f64); - // TODO: full block range metrics + let blocks = self.inflight_full_block_requests.len() + + self.inflight_block_range_requests.iter().map(|r| r.count() as usize).sum::(); + self.metrics.active_block_downloads.set(blocks as f64); } /// Adds a pending event to the FIFO queue. diff --git a/crates/engine/tree/src/persistence.rs b/crates/engine/tree/src/persistence.rs index bc2bc32489d9..63a480fed1e8 100644 --- a/crates/engine/tree/src/persistence.rs +++ b/crates/engine/tree/src/persistence.rs @@ -8,6 +8,7 @@ use reth_provider::{ StaticFileProviderFactory, }; use reth_prune::{Pruner, PrunerError, PrunerOutput}; +use reth_stages_api::{MetricEvent, MetricEventsSender}; use std::{ sync::mpsc::{Receiver, SendError, Sender}, time::Instant, @@ -33,6 +34,8 @@ pub struct PersistenceService { pruner: Pruner>, /// metrics metrics: PersistenceMetrics, + /// Sender for sync metrics - we only submit sync metrics for persisted blocks + sync_metrics_tx: MetricEventsSender, } impl PersistenceService { @@ -41,8 +44,9 @@ impl PersistenceService { provider: ProviderFactory, incoming: Receiver, pruner: Pruner>, + sync_metrics_tx: MetricEventsSender, ) -> Self { - Self { provider, incoming, pruner, metrics: PersistenceMetrics::default() } + Self { provider, incoming, pruner, metrics: PersistenceMetrics::default(), sync_metrics_tx } } /// Prunes block data before the given block hash according to the configured prune @@ -66,11 +70,20 @@ impl PersistenceService { match action { PersistenceAction::RemoveBlocksAbove(new_tip_num, sender) => { let result = self.on_remove_blocks_above(new_tip_num)?; + // send new sync metrics based on removed blocks + let _ = + self.sync_metrics_tx.send(MetricEvent::SyncHeight { height: new_tip_num }); // we ignore the error because the caller may or may not care about the result let _ = sender.send(result); } PersistenceAction::SaveBlocks(blocks, sender) => { let result = self.on_save_blocks(blocks)?; + if let Some(ref num_hash) = result { + // send new sync metrics based on saved blocks + let _ = self + .sync_metrics_tx + .send(MetricEvent::SyncHeight { height: num_hash.number }); + } // we ignore the error because the caller may or may not care about the result let _ = sender.send(result); } @@ -175,6 +188,7 @@ impl PersistenceHandle { pub fn spawn_service( provider_factory: ProviderFactory, pruner: Pruner>, + sync_metrics_tx: MetricEventsSender, ) -> Self { // create the initial channels let (db_service_tx, db_service_rx) = std::sync::mpsc::channel(); @@ -183,7 +197,8 @@ impl PersistenceHandle { let persistence_handle = Self::new(db_service_tx); // spawn the persistence service - let db_service = PersistenceService::new(provider_factory, db_service_rx, pruner); + let db_service = + PersistenceService::new(provider_factory, db_service_rx, pruner, sync_metrics_tx); std::thread::Builder::new() .name("Persistence Service".to_string()) .spawn(|| { @@ -255,6 +270,7 @@ mod tests { use reth_primitives::B256; use reth_provider::{test_utils::create_test_provider_factory, ProviderFactory}; use reth_prune::Pruner; + use tokio::sync::mpsc::unbounded_channel; fn default_persistence_handle() -> PersistenceHandle { let provider = create_test_provider_factory(); @@ -271,7 +287,8 @@ mod tests { finished_exex_height_rx, ); - PersistenceHandle::spawn_service(provider, pruner) + let (sync_metrics_tx, _sync_metrics_rx) = unbounded_channel(); + PersistenceHandle::spawn_service(provider, pruner, sync_metrics_tx) } #[tokio::test] diff --git a/crates/ethereum/engine-primitives/src/payload.rs b/crates/ethereum/engine-primitives/src/payload.rs index 724e11b9087e..0bb4da1c2e8b 100644 --- a/crates/ethereum/engine-primitives/src/payload.rs +++ b/crates/ethereum/engine-primitives/src/payload.rs @@ -7,7 +7,7 @@ use reth_evm_ethereum::revm_spec_by_timestamp_after_merge; use reth_payload_primitives::{BuiltPayload, PayloadBuilderAttributes}; use reth_primitives::{ constants::EIP1559_INITIAL_BASE_FEE, Address, BlobTransactionSidecar, EthereumHardfork, Header, - Receipt, SealedBlock, Withdrawals, B256, U256, + SealedBlock, Withdrawals, B256, U256, }; use reth_rpc_types::engine::{ ExecutionPayloadEnvelopeV2, ExecutionPayloadEnvelopeV3, ExecutionPayloadEnvelopeV4, @@ -38,8 +38,6 @@ pub struct EthBuiltPayload { /// The blobs, proofs, and commitments in the block. If the block is pre-cancun, this will be /// empty. pub(crate) sidecars: Vec, - /// The receipts of the block - pub(crate) receipts: Vec, } // === impl BuiltPayload === @@ -50,10 +48,9 @@ impl EthBuiltPayload { id: PayloadId, block: SealedBlock, fees: U256, - receipts: Vec, executed_block: Option, ) -> Self { - Self { id, block, executed_block, fees, sidecars: Vec::new(), receipts } + Self { id, block, executed_block, fees, sidecars: Vec::new() } } /// Returns the identifier of the payload. @@ -94,10 +91,6 @@ impl BuiltPayload for EthBuiltPayload { fn executed_block(&self) -> Option { self.executed_block.clone() } - - fn receipts(&self) -> &[Receipt] { - &self.receipts - } } impl<'a> BuiltPayload for &'a EthBuiltPayload { @@ -112,10 +105,6 @@ impl<'a> BuiltPayload for &'a EthBuiltPayload { fn executed_block(&self) -> Option { self.executed_block.clone() } - - fn receipts(&self) -> &[Receipt] { - &self.receipts - } } // V1 engine_getPayloadV1 response diff --git a/crates/ethereum/payload/src/lib.rs b/crates/ethereum/payload/src/lib.rs index 87e0715096bb..baebd19fa973 100644 --- a/crates/ethereum/payload/src/lib.rs +++ b/crates/ethereum/payload/src/lib.rs @@ -29,9 +29,7 @@ use reth_payload_builder::{ error::PayloadBuilderError, EthBuiltPayload, EthPayloadBuilderAttributes, }; use reth_primitives::{ - constants::{ - eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE, EMPTY_RECEIPTS, EMPTY_TRANSACTIONS, - }, + constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE}, eip4844::calculate_excess_blob_gas, proofs::{self, calculate_requests_root}, Block, EthereumHardforks, Header, IntoRecoveredTransaction, Receipt, EMPTY_OMMER_ROOT_HASH, @@ -39,7 +37,9 @@ use reth_primitives::{ }; use reth_provider::StateProviderFactory; use reth_revm::database::StateProviderDatabase; -use reth_transaction_pool::{BestTransactionsAttributes, TransactionPool}; +use reth_transaction_pool::{ + noop::NoopTransactionPool, BestTransactionsAttributes, TransactionPool, +}; use reth_trie::HashedPostState; use revm::{ db::states::bundle_state::BundleRetention, @@ -83,7 +83,7 @@ where &self, args: BuildArguments, ) -> Result, PayloadBuilderError> { - default_ethereum_payload_builder(self.evm_config.clone(), args) + default_ethereum_payload(self.evm_config.clone(), args) } fn build_empty_payload( @@ -91,179 +91,18 @@ where client: &Client, config: PayloadConfig, ) -> Result { - let extra_data = config.extra_data(); - let PayloadConfig { - initialized_block_env, - parent_block, - attributes, - chain_spec, - initialized_cfg, - .. - } = config; - - debug!(target: "payload_builder", parent_hash = ?parent_block.hash(), parent_number = parent_block.number, "building empty payload"); - - let state = client.state_by_block_hash(parent_block.hash()).map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to get state for empty payload" - ); - err - })?; - - let mut db = State::builder() - .with_database(StateProviderDatabase::new(state)) - .with_bundle_update() - .build(); - - let base_fee = initialized_block_env.basefee.to::(); - let block_gas_limit = - initialized_block_env.gas_limit.try_into().unwrap_or(chain_spec.max_gas_limit); - - // apply eip-4788 pre block contract call - pre_block_beacon_root_contract_call( - &mut db, - &self.evm_config, - &chain_spec, - &initialized_cfg, - &initialized_block_env, - attributes.parent_beacon_block_root, - ) - .map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to apply beacon root contract call for empty payload" - ); - PayloadBuilderError::Internal(err.into()) - })?; - - // apply eip-2935 blockhashes update - pre_block_blockhashes_contract_call( - &mut db, - &self.evm_config, - &chain_spec, - &initialized_cfg, - &initialized_block_env, - parent_block.hash(), - ) - .map_err(|err| { - warn!(target: "payload_builder", parent_hash=%parent_block.hash(), %err, "failed to update blockhashes for empty payload"); - PayloadBuilderError::Internal(err.into()) - })?; - - let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals( - &mut db, - &chain_spec, - attributes.timestamp, - attributes.withdrawals.clone(), - ) - .map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to commit withdrawals for empty payload" - ); - err - })?; - - // merge all transitions into bundle state, this would apply the withdrawal balance - // changes and 4788 contract call - db.merge_transitions(BundleRetention::PlainState); - - // calculate the state root - let bundle_state = db.take_bundle(); - let state_root = db - .database - .state_root(HashedPostState::from_bundle_state(&bundle_state.state)) - .map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to calculate state root for empty payload" - ); - err - })?; - - let mut excess_blob_gas = None; - let mut blob_gas_used = None; - - if chain_spec.is_cancun_active_at_timestamp(attributes.timestamp) { - excess_blob_gas = if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) { - let parent_excess_blob_gas = parent_block.excess_blob_gas.unwrap_or_default(); - let parent_blob_gas_used = parent_block.blob_gas_used.unwrap_or_default(); - Some(calculate_excess_blob_gas(parent_excess_blob_gas, parent_blob_gas_used)) - } else { - // for the first post-fork block, both parent.blob_gas_used and - // parent.excess_blob_gas are evaluated as 0 - Some(calculate_excess_blob_gas(0, 0)) - }; - - blob_gas_used = Some(0); - } - - // Calculate the requests and the requests root. - let (requests, requests_root) = - if chain_spec.is_prague_active_at_timestamp(attributes.timestamp) { - // We do not calculate the EIP-6110 deposit requests because there are no - // transactions in an empty payload. - let withdrawal_requests = post_block_withdrawal_requests_contract_call( - &self.evm_config, - &mut db, - &initialized_cfg, - &initialized_block_env, - ) - .map_err(|err| PayloadBuilderError::Internal(err.into()))?; - let consolidation_requests = post_block_consolidation_requests_contract_call( - &self.evm_config, - &mut db, - &initialized_cfg, - &initialized_block_env, - ) - .map_err(|err| PayloadBuilderError::Internal(err.into()))?; - - let requests = [withdrawal_requests, consolidation_requests].concat(); - let requests_root = calculate_requests_root(&requests); - (Some(requests.into()), Some(requests_root)) - } else { - (None, None) - }; - - let header = Header { - parent_hash: parent_block.hash(), - ommers_hash: EMPTY_OMMER_ROOT_HASH, - beneficiary: initialized_block_env.coinbase, - state_root, - transactions_root: EMPTY_TRANSACTIONS, - withdrawals_root, - receipts_root: EMPTY_RECEIPTS, - logs_bloom: Default::default(), - timestamp: attributes.timestamp, - mix_hash: attributes.prev_randao, - nonce: BEACON_NONCE, - base_fee_per_gas: Some(base_fee), - number: parent_block.number + 1, - gas_limit: block_gas_limit, - difficulty: U256::ZERO, - gas_used: 0, - extra_data, - blob_gas_used, - excess_blob_gas, - parent_beacon_block_root: attributes.parent_beacon_block_root, - requests_root, + let args = BuildArguments { + client, + config, + // we use defaults here because for the empty payload we don't need to execute anything + pool: NoopTransactionPool::default(), + cached_reads: Default::default(), + cancel: Default::default(), + best_payload: None, }; - - let block = Block { header, body: vec![], ommers: vec![], withdrawals, requests }; - let sealed_block = block.seal_slow(); - - Ok(EthBuiltPayload::new( - attributes.payload_id(), - sealed_block, - U256::ZERO, - Vec::new(), - None, - )) + default_ethereum_payload(self.evm_config.clone(), args)? + .into_payload() + .ok_or_else(|| PayloadBuilderError::MissingPayload) } } @@ -273,7 +112,7 @@ where /// and configuration, this function creates a transaction payload. Returns /// a result indicating success with the payload or an error in case of failure. #[inline] -pub fn default_ethereum_payload_builder( +pub fn default_ethereum_payload( evm_config: EvmConfig, args: BuildArguments, ) -> Result, PayloadBuilderError> @@ -580,8 +419,6 @@ where let sealed_block = block.seal_slow(); debug!(target: "payload_builder", ?sealed_block, "sealed built block"); - let receipts_pay: Vec = receipts.into_iter().flatten().collect(); - // create the executed block data let executed = ExecutedBlock { block: Arc::new(sealed_block.clone()), @@ -591,8 +428,7 @@ where trie: Arc::new(trie_output), }; - let mut payload = - EthBuiltPayload::new(attributes.id, sealed_block, total_fees, receipts_pay, Some(executed)); + let mut payload = EthBuiltPayload::new(attributes.id, sealed_block, total_fees, Some(executed)); // extend the payload with the blob sidecars from the executed txs payload.extend_sidecars(blob_sidecars); diff --git a/crates/net/discv5/src/lib.rs b/crates/net/discv5/src/lib.rs index 5b0044a721f5..f231603f40ee 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -148,9 +148,11 @@ impl Discv5 { /// Returns the [`NodeRecord`] of the local node. /// /// This includes the currently tracked external IP address of the node. - pub fn node_record(&self) -> NodeRecord { + /// + /// Returns `None` if the local ENR does not contain the required fields. + pub fn node_record(&self) -> Option { let enr: Enr<_> = EnrCombinedKeyWrapper(self.discv5.local_enr()).into(); - (&enr).try_into().unwrap() + enr.try_into().ok() } /// Spawns [`discv5::Discv5`]. Returns [`discv5::Discv5`] handle in reth compatible wrapper type diff --git a/crates/net/network/src/network.rs b/crates/net/network/src/network.rs index 0c20c636c3b9..94c2ef92dd5b 100644 --- a/crates/net/network/src/network.rs +++ b/crates/net/network/src/network.rs @@ -212,8 +212,8 @@ impl PeersInfo for NetworkHandle { fn local_node_record(&self) -> NodeRecord { if let Some(discv4) = &self.inner.discv4 { discv4.node_record() - } else if let Some(discv5) = &self.inner.discv5 { - discv5.node_record() + } else if let Some(record) = self.inner.discv5.as_ref().and_then(|d| d.node_record()) { + record } else { let id = *self.peer_id(); let mut socket_addr = *self.inner.listener_address.lock(); diff --git a/crates/net/peers/src/node_record.rs b/crates/net/peers/src/node_record.rs index cd29e12d4cd8..d6836d88193c 100644 --- a/crates/net/peers/src/node_record.rs +++ b/crates/net/peers/src/node_record.rs @@ -196,6 +196,15 @@ impl FromStr for NodeRecord { } } +#[cfg(feature = "secp256k1")] +impl TryFrom> for NodeRecord { + type Error = NodeRecordParseError; + + fn try_from(enr: Enr) -> Result { + (&enr).try_into() + } +} + #[cfg(feature = "secp256k1")] impl TryFrom<&Enr> for NodeRecord { type Error = NodeRecordParseError; diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index 807612204471..0adaed2c2eb0 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -58,6 +58,10 @@ reth-rpc-types-compat.workspace = true reth-tracing.workspace = true reth-transaction-pool.workspace = true +## ethereum +alloy-network.workspace = true +alloy-primitives.workspace = true + ## async futures.workspace = true tokio = { workspace = true, features = [ diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 689e6b752fcf..4f0cffb33e2a 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -29,7 +29,10 @@ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, node_config::NodeConfig, primitives::Head, - rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, + rpc::{ + eth::{helpers::AddDevSigners, FullEthApiServer}, + types::AnyTransactionReceipt, + }, }; use reth_primitives::revm_primitives::EnvKzgSettings; use reth_provider::{providers::BlockchainProvider, ChainSpecProvider, FullProvider}; diff --git a/crates/node/builder/src/launch/common.rs b/crates/node/builder/src/launch/common.rs index 34a187426275..e15a852e7d62 100644 --- a/crates/node/builder/src/launch/common.rs +++ b/crates/node/builder/src/launch/common.rs @@ -2,6 +2,7 @@ use std::{sync::Arc, thread::available_parallelism}; +use alloy_primitives::{BlockNumber, B256}; use eyre::Context; use rayon::ThreadPoolBuilder; use reth_auto_seal_consensus::MiningMode; @@ -30,11 +31,12 @@ use reth_node_core::{ }, }; use reth_node_metrics::{ + chain::ChainSpecInfo, hooks::Hooks, server::{MetricServer, MetricServerConfig}, version::VersionInfo, }; -use reth_primitives::{BlockNumber, Head, B256}; +use reth_primitives::Head; use reth_provider::{ providers::{BlockchainProvider, BlockchainProvider2, StaticFileProvider}, BlockHashReader, CanonStateNotificationSender, ChainSpecProvider, ProviderFactory, @@ -507,6 +509,7 @@ where target_triple: VERGEN_CARGO_TARGET_TRIPLE, build_profile: BUILD_PROFILE_NAME, }, + ChainSpecInfo { name: self.left().config.chain.chain.to_string() }, self.task_executor().clone(), Hooks::new(self.database().clone(), self.static_file_provider()), ); @@ -617,7 +620,7 @@ where /// If the database is empty, returns the genesis block. pub fn lookup_head(&self) -> eyre::Result { self.node_config() - .lookup_head(self.provider_factory().clone()) + .lookup_head(self.provider_factory()) .wrap_err("the head block is missing") } @@ -741,7 +744,7 @@ where } /// Creates a new [`StaticFileProducer`] with the attached database. - pub fn static_file_producer(&self) -> StaticFileProducer { + pub fn static_file_producer(&self) -> StaticFileProducer> { StaticFileProducer::new(self.provider_factory().clone(), self.prune_modes()) } diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index 1238d0c19d4e..e4b700b239e0 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -24,7 +24,10 @@ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, primitives::Head, - rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, + rpc::{ + eth::{helpers::AddDevSigners, FullEthApiServer}, + types::AnyTransactionReceipt, + }, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; @@ -220,6 +223,7 @@ where ctx.components().payload_builder().clone(), TreeConfig::default(), ctx.invalid_block_hook()?, + ctx.sync_metrics_tx(), ); let event_sender = EventSender::default(); @@ -264,6 +268,7 @@ where ctx.chain_spec(), beacon_engine_handle, ctx.components().payload_builder().clone().into(), + ctx.components().pool().clone(), Box::new(ctx.task_executor().clone()), client, EngineCapabilities::default(), diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 6ec92a66365a..6300a3986471 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -27,7 +27,10 @@ use reth_node_api::{ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, - rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, + rpc::{ + eth::{helpers::AddDevSigners, FullEthApiServer}, + types::AnyTransactionReceipt, + }, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; @@ -350,6 +353,7 @@ where ctx.chain_spec(), beacon_engine_handle, ctx.components().payload_builder().clone().into(), + ctx.components().pool().clone(), Box::new(ctx.task_executor().clone()), client, EngineCapabilities::default(), diff --git a/crates/node/builder/src/setup.rs b/crates/node/builder/src/setup.rs index 69972a5a2067..10144d8699de 100644 --- a/crates/node/builder/src/setup.rs +++ b/crates/node/builder/src/setup.rs @@ -32,7 +32,7 @@ pub fn build_networked_pipeline( metrics_tx: reth_stages::MetricEventsSender, prune_config: Option, max_block: Option, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, executor: Executor, exex_manager_handle: ExExManagerHandle, ) -> eyre::Result> @@ -78,7 +78,7 @@ pub fn build_pipeline( max_block: Option, metrics_tx: reth_stages::MetricEventsSender, prune_config: Option, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, executor: Executor, exex_manager_handle: ExExManagerHandle, ) -> eyre::Result> diff --git a/crates/node/core/Cargo.toml b/crates/node/core/Cargo.toml index 0d507853d770..1cd4264ccc22 100644 --- a/crates/node/core/Cargo.toml +++ b/crates/node/core/Cargo.toml @@ -18,9 +18,8 @@ reth-cli.workspace = true reth-cli-util.workspace = true reth-fs-util.workspace = true reth-db = { workspace = true, features = ["mdbx"] } -reth-db-api.workspace = true reth-storage-errors.workspace = true -reth-provider.workspace = true +reth-storage-api.workspace = true reth-network = { workspace = true, features = ["serde"] } reth-network-p2p.workspace = true reth-rpc-eth-types.workspace = true @@ -40,13 +39,12 @@ reth-consensus-common.workspace = true reth-prune-types.workspace = true reth-stages-types.workspace = true reth-optimism-chainspec = { workspace = true, optional = true } -reth-node-types.workspace = true # ethereum alloy-genesis.workspace = true +alloy-primitives.workspace = true alloy-rpc-types-engine.workspace = true - # misc eyre.workspace = true clap = { workspace = true, features = ["derive"] } @@ -64,8 +62,6 @@ dirs-next = "2.0.0" shellexpand.workspace = true serde_json.workspace = true - - # tracing tracing.workspace = true @@ -79,7 +75,6 @@ secp256k1 = { workspace = true, features = [ # async futures.workspace = true - [dev-dependencies] # test vectors generation proptest.workspace = true @@ -89,7 +84,6 @@ tempfile.workspace = true [features] optimism = [ "reth-primitives/optimism", - "reth-provider/optimism", "reth-rpc-types-compat/optimism", "reth-rpc-eth-api/optimism", "dep:reth-optimism-chainspec", diff --git a/crates/node/core/src/args/debug.rs b/crates/node/core/src/args/debug.rs index d706604429a4..175e2e235d7f 100644 --- a/crates/node/core/src/args/debug.rs +++ b/crates/node/core/src/args/debug.rs @@ -1,10 +1,10 @@ //! clap [Args](clap::Args) for debugging purposes +use alloy_primitives::B256; use clap::{ builder::{PossibleValue, TypedValueParser}, Arg, Args, Command, }; -use reth_primitives::B256; use std::{collections::HashSet, ffi::OsStr, fmt, path::PathBuf, str::FromStr}; use strum::{AsRefStr, EnumIter, IntoStaticStr, ParseError, VariantArray, VariantNames}; diff --git a/crates/node/core/src/args/pruning.rs b/crates/node/core/src/args/pruning.rs index acef58a09bc9..ac4ea8f73851 100644 --- a/crates/node/core/src/args/pruning.rs +++ b/crates/node/core/src/args/pruning.rs @@ -1,10 +1,10 @@ //! Pruning and full node arguments use crate::args::error::ReceiptsLogError; +use alloy_primitives::{Address, BlockNumber}; use clap::Args; use reth_chainspec::ChainSpec; use reth_config::config::PruneConfig; -use reth_primitives::{Address, BlockNumber}; use reth_prune_types::{PruneMode, PruneModes, ReceiptsLogPruneConfig, MINIMUM_PRUNING_DISTANCE}; use std::collections::BTreeMap; diff --git a/crates/node/core/src/args/txpool.rs b/crates/node/core/src/args/txpool.rs index a27b1fa806cf..57780430a34c 100644 --- a/crates/node/core/src/args/txpool.rs +++ b/crates/node/core/src/args/txpool.rs @@ -1,8 +1,8 @@ //! Transaction pool arguments use crate::cli::config::RethTransactionPoolConfig; +use alloy_primitives::Address; use clap::Args; -use reth_primitives::Address; use reth_transaction_pool::{ blobstore::disk::DEFAULT_MAX_CACHED_BLOBS, pool::{NEW_TX_LISTENER_BUFFER_SIZE, PENDING_TX_LISTENER_BUFFER_SIZE}, diff --git a/crates/node/core/src/cli/config.rs b/crates/node/core/src/cli/config.rs index f40d4287f406..73ada50fcd2e 100644 --- a/crates/node/core/src/cli/config.rs +++ b/crates/node/core/src/cli/config.rs @@ -1,7 +1,7 @@ //! Config traits for various node components. +use alloy_primitives::Bytes; use reth_network::protocol::IntoRlpxSubProtocol; -use reth_primitives::Bytes; use reth_transaction_pool::PoolConfig; use std::{borrow::Cow, time::Duration}; diff --git a/crates/node/core/src/node_config.rs b/crates/node/core/src/node_config.rs index b99c13dc6c4a..d4cdd2f88c6c 100644 --- a/crates/node/core/src/node_config.rs +++ b/crates/node/core/src/node_config.rs @@ -15,12 +15,12 @@ use reth_network_p2p::headers::client::HeadersClient; use serde::{de::DeserializeOwned, Serialize}; use std::{fs, path::Path}; -use reth_node_types::NodeTypesWithDB; -use reth_primitives::{ - revm_primitives::EnvKzgSettings, BlockHashOrNumber, BlockNumber, Head, SealedHeader, B256, -}; -use reth_provider::{BlockHashReader, HeaderProvider, ProviderFactory, StageCheckpointReader}; +use alloy_primitives::{BlockNumber, B256}; +use reth_primitives::{BlockHashOrNumber, Head, SealedHeader}; use reth_stages_types::StageId; +use reth_storage_api::{ + BlockHashReader, DatabaseProviderFactory, HeaderProvider, StageCheckpointReader, +}; use reth_storage_errors::provider::ProviderResult; use std::{net::SocketAddr, path::PathBuf, sync::Arc}; use tracing::*; @@ -261,19 +261,16 @@ impl NodeConfig { Ok(max_block) } - /// Loads '`EnvKzgSettings::Default`' - pub const fn kzg_settings(&self) -> eyre::Result { - Ok(EnvKzgSettings::Default) - } - /// Fetches the head block from the database. /// /// If the database is empty, returns the genesis block. - pub fn lookup_head>( - &self, - factory: ProviderFactory, - ) -> ProviderResult { - let provider = factory.provider()?; + pub fn lookup_head(&self, factory: &Factory) -> ProviderResult + where + Factory: DatabaseProviderFactory< + Provider: HeaderProvider + StageCheckpointReader + BlockHashReader, + >, + { + let provider = factory.database_provider_ro()?; let head = provider.get_stage_checkpoint(StageId::Finish)?.unwrap_or_default().block_number; diff --git a/crates/node/core/src/version.rs b/crates/node/core/src/version.rs index 78dbcfbcf5e9..683c30564265 100644 --- a/crates/node/core/src/version.rs +++ b/crates/node/core/src/version.rs @@ -1,5 +1,5 @@ //! Version information for reth. -use reth_db_api::models::ClientVersion; +use reth_db::ClientVersion; use reth_rpc_types::engine::ClientCode; /// The client code for Reth diff --git a/crates/node/events/Cargo.toml b/crates/node/events/Cargo.toml index a4970677ac3a..9c56c2da9b88 100644 --- a/crates/node/events/Cargo.toml +++ b/crates/node/events/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true workspace = true [dependencies] +# reth reth-provider.workspace = true reth-beacon-consensus.workspace = true reth-network = { workspace = true, features = ["serde"] } @@ -21,7 +22,8 @@ reth-static-file.workspace = true reth-primitives.workspace = true reth-primitives-traits.workspace = true -# alloy +# ethereum +alloy-primitives.workspace = true alloy-rpc-types-engine.workspace = true # async @@ -32,6 +34,6 @@ futures.workspace = true tracing.workspace = true -#misc +# misc pin-project.workspace = true humantime.workspace = true diff --git a/crates/node/events/src/node.rs b/crates/node/events/src/node.rs index 24d5465fb2a0..9c554478ae58 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -1,6 +1,7 @@ //! Support for handling events emitted by node components. use crate::cl::ConsensusLayerHealthEvent; +use alloy_primitives::{BlockNumber, B256}; use alloy_rpc_types_engine::ForkchoiceState; use futures::Stream; use reth_beacon_consensus::{ @@ -8,7 +9,7 @@ use reth_beacon_consensus::{ }; use reth_network::NetworkEvent; use reth_network_api::PeersInfo; -use reth_primitives::{constants, BlockNumber, B256}; +use reth_primitives::constants; use reth_primitives_traits::{format_gas, format_gas_throughput}; use reth_prune::PrunerEvent; use reth_stages::{EntitiesCheckpoint, ExecOutput, PipelineEvent, StageCheckpoint, StageId}; diff --git a/crates/node/metrics/src/chain.rs b/crates/node/metrics/src/chain.rs new file mode 100644 index 000000000000..191aae992394 --- /dev/null +++ b/crates/node/metrics/src/chain.rs @@ -0,0 +1,19 @@ +//! This exposes reth's chain information over prometheus. +use metrics::{describe_gauge, gauge}; + +/// Contains chain information for the application. +#[derive(Debug, Clone)] +pub struct ChainSpecInfo { + /// The name of the chain. + pub name: String, +} + +impl ChainSpecInfo { + /// This exposes reth's chain information over prometheus. + pub fn register_chain_spec_metrics(&self) { + let labels: [(&str, String); 1] = [("name", self.name.clone())]; + + describe_gauge!("chain_spec", "Information about the chain"); + let _gauge = gauge!("chain_spec", &labels); + } +} diff --git a/crates/node/metrics/src/lib.rs b/crates/node/metrics/src/lib.rs index 4abc39a32dc3..d74a8aeffba0 100644 --- a/crates/node/metrics/src/lib.rs +++ b/crates/node/metrics/src/lib.rs @@ -7,6 +7,7 @@ #![cfg_attr(not(test), warn(unused_crate_dependencies))] #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] +pub mod chain; /// The metrics hooks for prometheus. pub mod hooks; pub mod recorder; diff --git a/crates/node/metrics/src/server.rs b/crates/node/metrics/src/server.rs index d22df4eab610..06bb490a4365 100644 --- a/crates/node/metrics/src/server.rs +++ b/crates/node/metrics/src/server.rs @@ -1,4 +1,5 @@ use crate::{ + chain::ChainSpecInfo, hooks::{Hook, Hooks}, recorder::install_prometheus_recorder, version::VersionInfo, @@ -17,6 +18,7 @@ use tracing::info; pub struct MetricServerConfig { listen_addr: SocketAddr, version_info: VersionInfo, + chain_spec_info: ChainSpecInfo, task_executor: TaskExecutor, hooks: Hooks, } @@ -26,10 +28,11 @@ impl MetricServerConfig { pub const fn new( listen_addr: SocketAddr, version_info: VersionInfo, + chain_spec_info: ChainSpecInfo, task_executor: TaskExecutor, hooks: Hooks, ) -> Self { - Self { listen_addr, hooks, task_executor, version_info } + Self { listen_addr, hooks, task_executor, version_info, chain_spec_info } } } @@ -47,7 +50,8 @@ impl MetricServer { /// Spawns the metrics server pub async fn serve(&self) -> eyre::Result<()> { - let MetricServerConfig { listen_addr, hooks, task_executor, version_info } = &self.config; + let MetricServerConfig { listen_addr, hooks, task_executor, version_info, chain_spec_info } = + &self.config; info!(target: "reth::cli", addr = %listen_addr, "Starting metrics endpoint"); @@ -68,6 +72,7 @@ impl MetricServer { describe_io_stats(); version_info.register_version_metrics(); + chain_spec_info.register_chain_spec_metrics(); Ok(()) } @@ -221,6 +226,7 @@ mod tests { #[tokio::test] async fn test_metrics_endpoint() { + let chain_spec_info = ChainSpecInfo { name: "test".to_string() }; let version_info = VersionInfo { version: "test", build_timestamp: "test", @@ -237,7 +243,8 @@ mod tests { let hooks = Hooks::new(factory.db_ref().clone(), factory.static_file_provider()); let listen_addr = get_random_available_addr(); - let config = MetricServerConfig::new(listen_addr, version_info, executor, hooks); + let config = + MetricServerConfig::new(listen_addr, version_info, chain_spec_info, executor, hooks); MetricServer::new(config).serve().await.unwrap(); diff --git a/crates/optimism/bin/src/main.rs b/crates/optimism/bin/src/main.rs index 7b91bca6a51c..3f66a38510e0 100644 --- a/crates/optimism/bin/src/main.rs +++ b/crates/optimism/bin/src/main.rs @@ -6,7 +6,7 @@ use clap::Parser; use reth_node_builder::EngineNodeLauncher; use reth_node_optimism::{args::RollupArgs, node::OptimismAddOns, OptimismNode}; -use reth_optimism_cli::Cli; +use reth_optimism_cli::{chainspec::OpChainSpecParser, Cli}; use reth_optimism_rpc::eth::rpc::SequencerClient; use reth_provider::providers::BlockchainProvider2; @@ -23,56 +23,58 @@ fn main() { std::env::set_var("RUST_BACKTRACE", "1"); } - if let Err(err) = Cli::::parse().run(|builder, rollup_args| async move { - let enable_engine2 = rollup_args.experimental; - let sequencer_http_arg = rollup_args.sequencer_http.clone(); - match enable_engine2 { - true => { - let handle = builder - .with_types_and_provider::>() - .with_components(OptimismNode::components(rollup_args)) - .with_add_ons::() - .extend_rpc_modules(move |ctx| { - // register sequencer tx forwarder - if let Some(sequencer_http) = sequencer_http_arg { - ctx.registry - .eth_api() - .set_sequencer_client(SequencerClient::new(sequencer_http)); - } + if let Err(err) = + Cli::::parse().run(|builder, rollup_args| async move { + let enable_engine2 = rollup_args.experimental; + let sequencer_http_arg = rollup_args.sequencer_http.clone(); + match enable_engine2 { + true => { + let handle = builder + .with_types_and_provider::>() + .with_components(OptimismNode::components(rollup_args)) + .with_add_ons::() + .extend_rpc_modules(move |ctx| { + // register sequencer tx forwarder + if let Some(sequencer_http) = sequencer_http_arg { + ctx.registry + .eth_api() + .set_sequencer_client(SequencerClient::new(sequencer_http)); + } - Ok(()) - }) - .launch_with_fn(|builder| { - let launcher = EngineNodeLauncher::new( - builder.task_executor().clone(), - builder.config().datadir(), - ); - builder.launch_with(launcher) - }) - .await?; + Ok(()) + }) + .launch_with_fn(|builder| { + let launcher = EngineNodeLauncher::new( + builder.task_executor().clone(), + builder.config().datadir(), + ); + builder.launch_with(launcher) + }) + .await?; - handle.node_exit_future.await - } - false => { - let handle = builder - .node(OptimismNode::new(rollup_args.clone())) - .extend_rpc_modules(move |ctx| { - // register sequencer tx forwarder - if let Some(sequencer_http) = sequencer_http_arg { - ctx.registry - .eth_api() - .set_sequencer_client(SequencerClient::new(sequencer_http)); - } + handle.node_exit_future.await + } + false => { + let handle = builder + .node(OptimismNode::new(rollup_args.clone())) + .extend_rpc_modules(move |ctx| { + // register sequencer tx forwarder + if let Some(sequencer_http) = sequencer_http_arg { + ctx.registry + .eth_api() + .set_sequencer_client(SequencerClient::new(sequencer_http)); + } - Ok(()) - }) - .launch() - .await?; + Ok(()) + }) + .launch() + .await?; - handle.node_exit_future.await + handle.node_exit_future.await + } } - } - }) { + }) + { eprintln!("Error: {err:?}"); std::process::exit(1); } diff --git a/crates/optimism/cli/Cargo.toml b/crates/optimism/cli/Cargo.toml index 41135d4a2117..00b19ad8f060 100644 --- a/crates/optimism/cli/Cargo.toml +++ b/crates/optimism/cli/Cargo.toml @@ -26,7 +26,7 @@ reth-node-core.workspace = true reth-node-optimism.workspace = true reth-primitives.workspace = true -## optimisim +## optimism reth-optimism-primitives.workspace = true reth-optimism-chainspec.workspace = true @@ -42,12 +42,10 @@ reth-cli-runner.workspace = true reth-node-builder.workspace = true reth-tracing.workspace = true - # eth alloy-primitives.workspace = true alloy-rlp.workspace = true - # misc futures-util.workspace = true clap = { workspace = true, features = ["derive", "env"] } @@ -68,10 +66,10 @@ tempfile.workspace = true reth-stages = { workspace = true, features = ["test-utils"] } reth-db-common.workspace = true -[features] - optimism = [ +[features] + optimism = [ "reth-primitives/optimism", "reth-evm-optimism/optimism", "reth-provider/optimism", "reth-node-optimism/optimism", - ] + ] diff --git a/crates/optimism/cli/src/commands/build_pipeline.rs b/crates/optimism/cli/src/commands/build_pipeline.rs index 20f01cc172c5..b546a1a515a2 100644 --- a/crates/optimism/cli/src/commands/build_pipeline.rs +++ b/crates/optimism/cli/src/commands/build_pipeline.rs @@ -32,7 +32,7 @@ pub(crate) async fn build_import_pipeline( provider_factory: ProviderFactory, consensus: &Arc, file_client: Arc, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, disable_exec: bool, ) -> eyre::Result<(Pipeline, impl Stream)> where diff --git a/crates/optimism/cli/src/commands/import_receipts.rs b/crates/optimism/cli/src/commands/import_receipts.rs index efc815dc4d03..d84296d84648 100644 --- a/crates/optimism/cli/src/commands/import_receipts.rs +++ b/crates/optimism/cli/src/commands/import_receipts.rs @@ -252,8 +252,8 @@ pub struct ImportReceiptsResult { #[cfg(test)] mod test { + use alloy_primitives::hex; use reth_db_common::init::init_genesis; - use reth_primitives::hex; use reth_stages::test_utils::TestStageDB; use tempfile::tempfile; use tokio::{ diff --git a/crates/optimism/cli/src/lib.rs b/crates/optimism/cli/src/lib.rs index b83d08db5b8e..06c04bf55fe4 100644 --- a/crates/optimism/cli/src/lib.rs +++ b/crates/optimism/cli/src/lib.rs @@ -55,7 +55,10 @@ use tracing::info; /// This is the entrypoint to the executable. #[derive(Debug, Parser)] #[command(author, version = SHORT_VERSION, long_version = LONG_VERSION, about = "Reth", long_about = None)] -pub struct Cli { +pub struct Cli< + Spec: ChainSpecParser = OpChainSpecParser, + Ext: clap::Args + fmt::Debug = NoArgs, +> { /// The command to run #[command(subcommand)] command: Commands, @@ -66,12 +69,12 @@ pub struct Cli { #[arg( long, value_name = "CHAIN_OR_PATH", - long_help = OpChainSpecParser::help_messge(), - default_value = OpChainSpecParser::SUPPORTED_CHAINS[0], - value_parser = OpChainSpecParser::parser(), + long_help = Spec::help_message(), + default_value = Spec::SUPPORTED_CHAINS[0], + value_parser = Spec::parser(), global = true, )] - chain: Arc, + chain: Arc, /// Add a new instance of a node. /// @@ -109,7 +112,11 @@ impl Cli { } } -impl Cli { +impl Cli +where + Spec: ChainSpecParser, + Ext: clap::Args + fmt::Debug, +{ /// Execute the configured cli command. /// /// This accepts a closure that is used to launch the node via the diff --git a/crates/optimism/cli/src/receipt_file_codec.rs b/crates/optimism/cli/src/receipt_file_codec.rs index b2643b84005d..c86bfa12a6bd 100644 --- a/crates/optimism/cli/src/receipt_file_codec.rs +++ b/crates/optimism/cli/src/receipt_file_codec.rs @@ -1,9 +1,10 @@ //! Codec for reading raw receipts from a file. +use alloy_primitives::B256; use alloy_rlp::{Decodable, RlpDecodable}; use reth_primitives::{ bytes::{Buf, BytesMut}, - Address, Bloom, Bytes, Log, Receipt, TxType, B256, + Address, Bloom, Bytes, Log, Receipt, TxType, }; use tokio_util::codec::Decoder; @@ -94,7 +95,8 @@ impl TryFrom for ReceiptWithBlockNumber { #[cfg(test)] pub(crate) mod test { - use reth_primitives::{alloy_primitives::LogData, hex}; + use alloy_primitives::hex; + use reth_primitives::alloy_primitives::LogData; use super::*; diff --git a/crates/optimism/consensus/Cargo.toml b/crates/optimism/consensus/Cargo.toml index cf522bfb8512..a77a50cadd0a 100644 --- a/crates/optimism/consensus/Cargo.toml +++ b/crates/optimism/consensus/Cargo.toml @@ -19,12 +19,14 @@ reth-consensus.workspace = true reth-primitives.workspace = true reth-trie-common.workspace = true +# ethereum +alloy-primitives.workspace = true + tracing.workspace = true [dev-dependencies] alloy-primitives.workspace = true reth-optimism-chainspec.workspace = true - [features] -optimism = ["reth-primitives/optimism"] \ No newline at end of file +optimism = ["reth-primitives/optimism"] diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index abf5d8599e7e..e603f1d91fb6 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -9,6 +9,7 @@ // The `optimism` feature must be enabled to use this crate. #![cfg(feature = "optimism")] +use alloy_primitives::U256; use reth_chainspec::{ChainSpec, EthereumHardforks, OptimismHardforks}; use reth_consensus::{Consensus, ConsensusError, PostExecutionInput}; use reth_consensus_common::validation::{ @@ -17,9 +18,7 @@ use reth_consensus_common::validation::{ validate_block_pre_execution, validate_header_base_fee, validate_header_extradata, validate_header_gas, }; -use reth_primitives::{ - BlockWithSenders, Header, SealedBlock, SealedHeader, EMPTY_OMMER_ROOT_HASH, U256, -}; +use reth_primitives::{BlockWithSenders, Header, SealedBlock, SealedHeader, EMPTY_OMMER_ROOT_HASH}; use std::{sync::Arc, time::SystemTime}; mod proof; diff --git a/crates/optimism/consensus/src/proof.rs b/crates/optimism/consensus/src/proof.rs index 8f9b83866fbb..d11244293994 100644 --- a/crates/optimism/consensus/src/proof.rs +++ b/crates/optimism/consensus/src/proof.rs @@ -1,7 +1,8 @@ //! Helper function for Receipt root calculation for Optimism hardforks. +use alloy_primitives::B256; use reth_chainspec::{ChainSpec, OptimismHardfork}; -use reth_primitives::{ReceiptWithBloom, B256}; +use reth_primitives::ReceiptWithBloom; use reth_trie_common::root::ordered_trie_root_with_encoder; /// Calculates the receipt root for a header. diff --git a/crates/optimism/consensus/src/validation.rs b/crates/optimism/consensus/src/validation.rs index a3cd1627ecb9..3a76ec138547 100644 --- a/crates/optimism/consensus/src/validation.rs +++ b/crates/optimism/consensus/src/validation.rs @@ -1,9 +1,8 @@ use crate::proof::calculate_receipt_root_optimism; +use alloy_primitives::{Bloom, B256}; use reth_chainspec::{ChainSpec, EthereumHardforks}; use reth_consensus::ConsensusError; -use reth_primitives::{ - gas_spent_by_transactions, BlockWithSenders, Bloom, GotExpected, Receipt, B256, -}; +use reth_primitives::{gas_spent_by_transactions, BlockWithSenders, GotExpected, Receipt}; /// Validate a block with regard to execution results: /// diff --git a/crates/optimism/evm/Cargo.toml b/crates/optimism/evm/Cargo.toml index 6e06a280afc7..48282cdafc43 100644 --- a/crates/optimism/evm/Cargo.toml +++ b/crates/optimism/evm/Cargo.toml @@ -21,6 +21,9 @@ reth-execution-errors.workspace = true reth-execution-types.workspace = true reth-prune-types.workspace = true +# ethereum +alloy-primitives.workspace = true + # Optimism reth-optimism-consensus.workspace = true diff --git a/crates/optimism/evm/src/error.rs b/crates/optimism/evm/src/error.rs index 57958b5ec52a..c5c6a0a4a3d3 100644 --- a/crates/optimism/evm/src/error.rs +++ b/crates/optimism/evm/src/error.rs @@ -19,7 +19,7 @@ pub enum OptimismBlockExecutionError { BlobTransactionRejected, /// Thrown when a database account could not be loaded. #[error("failed to load account {0}")] - AccountLoadFailed(reth_primitives::Address), + AccountLoadFailed(alloy_primitives::Address), } impl From for BlockExecutionError { diff --git a/crates/optimism/evm/src/execute.rs b/crates/optimism/evm/src/execute.rs index 3b18f43897b0..659d7128c93b 100644 --- a/crates/optimism/evm/src/execute.rs +++ b/crates/optimism/evm/src/execute.rs @@ -1,6 +1,7 @@ //! Optimism block executor. use crate::{l1::ensure_create2_deployer, OptimismBlockExecutionError, OptimismEvmConfig}; +use alloy_primitives::{BlockNumber, U256}; use reth_chainspec::{ChainSpec, EthereumHardforks, OptimismHardfork}; use reth_evm::{ execute::{ @@ -12,7 +13,7 @@ use reth_evm::{ }; use reth_execution_types::ExecutionOutcome; use reth_optimism_consensus::validate_block_post_execution; -use reth_primitives::{BlockNumber, BlockWithSenders, Header, Receipt, Receipts, TxType, U256}; +use reth_primitives::{BlockWithSenders, Header, Receipt, Receipts, TxType}; use reth_prune_types::PruneModes; use reth_revm::{ batch::BlockBatchRecord, db::states::bundle_state::BundleRetention, @@ -441,10 +442,10 @@ where #[cfg(test)] mod tests { use super::*; + use alloy_primitives::{b256, Address, StorageKey, StorageValue}; use reth_chainspec::ChainSpecBuilder; use reth_primitives::{ - b256, Account, Address, Block, Signature, StorageKey, StorageValue, Transaction, - TransactionSigned, TxEip1559, BASE_MAINNET, + Account, Block, Signature, Transaction, TransactionSigned, TxEip1559, BASE_MAINNET, }; use reth_revm::{ database::StateProviderDatabase, test_utils::StateProviderTest, L1_BLOCK_CONTRACT, diff --git a/crates/optimism/evm/src/l1.rs b/crates/optimism/evm/src/l1.rs index f9f952788f4c..20d1ec854c4b 100644 --- a/crates/optimism/evm/src/l1.rs +++ b/crates/optimism/evm/src/l1.rs @@ -1,9 +1,10 @@ //! Optimism-specific implementation and utilities for the executor use crate::OptimismBlockExecutionError; +use alloy_primitives::{address, b256, hex, Address, Bytes, B256, U256}; use reth_chainspec::{ChainSpec, OptimismHardfork}; use reth_execution_errors::BlockExecutionError; -use reth_primitives::{address, b256, hex, Address, Block, Bytes, B256, U256}; +use reth_primitives::Block; use revm::{ primitives::{Bytecode, HashMap, SpecId}, DatabaseCommit, L1BlockInfo, @@ -303,7 +304,8 @@ mod tests { #[test] fn sanity_l1_block() { - use reth_primitives::{hex_literal::hex, Bytes, Header, TransactionSigned}; + use alloy_primitives::{hex_literal::hex, Bytes}; + use reth_primitives::{Header, TransactionSigned}; let bytes = Bytes::from_static(&hex!("7ef9015aa044bae9d41b8380d781187b426c6fe43df5fb2fb57bd4466ef6a701e1f01e015694deaddeaddeaddeaddeaddeaddeaddeaddead000194420000000000000000000000000000000000001580808408f0d18001b90104015d8eb900000000000000000000000000000000000000000000000000000000008057650000000000000000000000000000000000000000000000000000000063d96d10000000000000000000000000000000000000000000000000000000000009f35273d89754a1e0387b89520d989d3be9c37c1f32495a88faf1ea05c61121ab0d1900000000000000000000000000000000000000000000000000000000000000010000000000000000000000002d679b567db6187c0c8323fa982cfb88b74dbcc7000000000000000000000000000000000000000000000000000000000000083400000000000000000000000000000000000000000000000000000000000f4240")); let l1_info_tx = TransactionSigned::decode_enveloped(&mut bytes.as_ref()).unwrap(); diff --git a/crates/optimism/evm/src/lib.rs b/crates/optimism/evm/src/lib.rs index f55616df269f..0e46e346481d 100644 --- a/crates/optimism/evm/src/lib.rs +++ b/crates/optimism/evm/src/lib.rs @@ -9,12 +9,13 @@ // The `optimism` feature must be enabled to use this crate. #![cfg(feature = "optimism")] +use alloy_primitives::{Address, U256}; use reth_chainspec::ChainSpec; use reth_evm::{ConfigureEvm, ConfigureEvmEnv}; use reth_primitives::{ revm_primitives::{AnalysisKind, CfgEnvWithHandlerCfg, TxEnv}, transaction::FillTxEnv, - Address, Head, Header, TransactionSigned, U256, + Head, Header, TransactionSigned, }; use reth_revm::{inspector_handle_register, Database, Evm, EvmBuilder, GetInspector}; @@ -136,11 +137,12 @@ impl ConfigureEvm for OptimismEvmConfig { #[cfg(test)] mod tests { use super::*; + use alloy_primitives::{B256, U256}; use reth_chainspec::{Chain, ChainSpec}; use reth_evm::execute::ProviderError; use reth_primitives::{ revm_primitives::{BlockEnv, CfgEnv, SpecId}, - Genesis, Header, B256, KECCAK_EMPTY, U256, + Genesis, Header, KECCAK_EMPTY, }; use reth_revm::{ db::{CacheDB, EmptyDBTyped}, diff --git a/crates/optimism/node/Cargo.toml b/crates/optimism/node/Cargo.toml index 3e963a238ee0..3d23740a6579 100644 --- a/crates/optimism/node/Cargo.toml +++ b/crates/optimism/node/Cargo.toml @@ -39,6 +39,9 @@ reth-optimism-rpc.workspace = true reth-rpc.workspace = true reth-optimism-chainspec.workspace = true +# ethereum +alloy-primitives.workspace = true + # async async-trait.workspace = true reqwest = { workspace = true, features = ["rustls-tls-native-roots"] } diff --git a/crates/optimism/node/src/txpool.rs b/crates/optimism/node/src/txpool.rs index f4849d2d4890..ad71c18ec6b7 100644 --- a/crates/optimism/node/src/txpool.rs +++ b/crates/optimism/node/src/txpool.rs @@ -41,6 +41,11 @@ impl OpTransactionValidator { self.inner.chain_spec() } + /// Returns the configured client + pub fn client(&self) -> &Client { + self.inner.client() + } + /// Returns the current block timestamp. fn block_timestamp(&self) -> u64 { self.block_info.timestamp.load(Ordering::Relaxed) @@ -224,10 +229,11 @@ pub struct OpL1BlockInfo { #[cfg(test)] mod tests { use crate::txpool::OpTransactionValidator; + use alloy_primitives::{TxKind, U256}; + use reth::primitives::Signature; use reth_chainspec::MAINNET; use reth_primitives::{ - Signature, Transaction, TransactionSigned, TransactionSignedEcRecovered, TxDeposit, TxKind, - U256, + Transaction, TransactionSigned, TransactionSignedEcRecovered, TxDeposit, }; use reth_provider::test_utils::MockEthProvider; use reth_transaction_pool::{ diff --git a/crates/optimism/node/tests/e2e/utils.rs b/crates/optimism/node/tests/e2e/utils.rs index 89933af63d43..6b8e07a42e38 100644 --- a/crates/optimism/node/tests/e2e/utils.rs +++ b/crates/optimism/node/tests/e2e/utils.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use alloy_genesis::Genesis; +use alloy_primitives::{Address, B256}; use reth::{rpc::types::engine::PayloadAttributes, tasks::TaskManager}; use reth_chainspec::ChainSpecBuilder; use reth_e2e_test_utils::{transaction::TransactionTestContext, wallet::Wallet, NodeHelperType}; @@ -9,7 +10,6 @@ use reth_node_optimism::{ }; use reth_optimism_chainspec::BASE_MAINNET; use reth_payload_builder::EthPayloadBuilderAttributes; -use reth_primitives::{Address, B256}; use tokio::sync::Mutex; /// Optimism Node Helper type diff --git a/crates/optimism/payload/Cargo.toml b/crates/optimism/payload/Cargo.toml index 23900295e551..39cf8263f736 100644 --- a/crates/optimism/payload/Cargo.toml +++ b/crates/optimism/payload/Cargo.toml @@ -31,6 +31,7 @@ reth-chain-state.workspace = true # ethereum revm.workspace = true +alloy-primitives.workspace = true alloy-rlp.workspace = true # misc diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index c985ae845354..702b8a98ca98 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -4,6 +4,7 @@ use crate::{ error::OptimismPayloadBuilderError, payload::{OptimismBuiltPayload, OptimismPayloadBuilderAttributes}, }; +use alloy_primitives::U256; use reth_basic_payload_builder::*; use reth_chain_state::ExecutedBlock; use reth_chainspec::{EthereumHardforks, OptimismHardfork}; @@ -11,13 +12,14 @@ use reth_evm::{system_calls::pre_block_beacon_root_contract_call, ConfigureEvm}; use reth_execution_types::ExecutionOutcome; use reth_payload_builder::error::PayloadBuilderError; use reth_primitives::{ - constants::{BEACON_NONCE, EMPTY_RECEIPTS, EMPTY_TRANSACTIONS}, - eip4844::calculate_excess_blob_gas, - proofs, Block, Header, IntoRecoveredTransaction, Receipt, TxType, EMPTY_OMMER_ROOT_HASH, U256, + constants::BEACON_NONCE, eip4844::calculate_excess_blob_gas, proofs, Block, Header, + IntoRecoveredTransaction, Receipt, TxType, EMPTY_OMMER_ROOT_HASH, }; use reth_provider::StateProviderFactory; use reth_revm::database::StateProviderDatabase; -use reth_transaction_pool::{BestTransactionsAttributes, TransactionPool}; +use reth_transaction_pool::{ + noop::NoopTransactionPool, BestTransactionsAttributes, TransactionPool, +}; use reth_trie::HashedPostState; use revm::{ db::states::bundle_state::BundleRetention, @@ -74,7 +76,7 @@ where &self, args: BuildArguments, ) -> Result, PayloadBuilderError> { - optimism_payload_builder(self.evm_config.clone(), args, self.compute_pending_block) + optimism_payload(self.evm_config.clone(), args, self.compute_pending_block) } fn on_missing_payload( @@ -86,140 +88,25 @@ where MissingPayloadBehaviour::AwaitInProgress } + // NOTE: this should only be used for testing purposes because this doesn't have access to L1 + // system txs, hence on_missing_payload we return [MissingPayloadBehaviour::AwaitInProgress]. fn build_empty_payload( &self, client: &Client, config: PayloadConfig, ) -> Result { - let extra_data = config.extra_data(); - let PayloadConfig { - initialized_block_env, - parent_block, - attributes, - chain_spec, - initialized_cfg, - .. - } = config; - - debug!(target: "payload_builder", parent_hash = ?parent_block.hash(), parent_number = parent_block.number, "building empty payload"); - - let state = client.state_by_block_hash(parent_block.hash()).map_err(|err| { - warn!(target: "payload_builder", parent_hash=%parent_block.hash(), %err, "failed to get state for empty payload"); - err - })?; - let mut db = State::builder() - .with_database(StateProviderDatabase::new(state)) - .with_bundle_update() - .build(); - - let base_fee = initialized_block_env.basefee.to::(); - let block_gas_limit: u64 = - initialized_block_env.gas_limit.try_into().unwrap_or(chain_spec.max_gas_limit); - - // apply eip-4788 pre block contract call - pre_block_beacon_root_contract_call( - &mut db, - &self.evm_config, - &chain_spec, - &initialized_cfg, - &initialized_block_env, - attributes.payload_attributes.parent_beacon_block_root, - ) - .map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to apply beacon root contract call for empty payload" - ); - PayloadBuilderError::Internal(err.into()) - })?; - - let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals( - &mut db, - &chain_spec, - attributes.payload_attributes.timestamp, - attributes.payload_attributes.withdrawals.clone(), - ) - .map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to commit withdrawals for empty payload" - ); - err - })?; - - // merge all transitions into bundle state, this would apply the withdrawal balance - // changes and 4788 contract call - db.merge_transitions(BundleRetention::PlainState); - - // calculate the state root - let bundle_state = db.take_bundle(); - let hashed_state = HashedPostState::from_bundle_state(&bundle_state.state); - let state_root = db.database.state_root(hashed_state).map_err(|err| { - warn!(target: "payload_builder", - parent_hash=%parent_block.hash(), - %err, - "failed to calculate state root for empty payload" - ); - err - })?; - - let mut excess_blob_gas = None; - let mut blob_gas_used = None; - - if chain_spec.is_cancun_active_at_timestamp(attributes.payload_attributes.timestamp) { - excess_blob_gas = if chain_spec.is_cancun_active_at_timestamp(parent_block.timestamp) { - let parent_excess_blob_gas = parent_block.excess_blob_gas.unwrap_or_default(); - let parent_blob_gas_used = parent_block.blob_gas_used.unwrap_or_default(); - Some(calculate_excess_blob_gas(parent_excess_blob_gas, parent_blob_gas_used)) - } else { - // for the first post-fork block, both parent.blob_gas_used and - // parent.excess_blob_gas are evaluated as 0 - Some(calculate_excess_blob_gas(0, 0)) - }; - - blob_gas_used = Some(0); - } - - let header = Header { - parent_hash: parent_block.hash(), - ommers_hash: EMPTY_OMMER_ROOT_HASH, - beneficiary: initialized_block_env.coinbase, - state_root, - transactions_root: EMPTY_TRANSACTIONS, - withdrawals_root, - receipts_root: EMPTY_RECEIPTS, - logs_bloom: Default::default(), - timestamp: attributes.payload_attributes.timestamp, - mix_hash: attributes.payload_attributes.prev_randao, - nonce: BEACON_NONCE, - base_fee_per_gas: Some(base_fee), - number: parent_block.number + 1, - gas_limit: block_gas_limit, - difficulty: U256::ZERO, - gas_used: 0, - extra_data, - blob_gas_used, - excess_blob_gas, - parent_beacon_block_root: attributes.payload_attributes.parent_beacon_block_root, - requests_root: None, + let args = BuildArguments { + client, + config, + // we use defaults here because for the empty payload we don't need to execute anything + pool: NoopTransactionPool::default(), + cached_reads: Default::default(), + cancel: Default::default(), + best_payload: None, }; - - let block = Block { header, body: vec![], ommers: vec![], withdrawals, requests: None }; - let sealed_block = block.seal_slow(); - - let receipts = Vec::new(); - - Ok(OptimismBuiltPayload::new( - attributes.payload_attributes.payload_id(), - sealed_block, - U256::ZERO, - chain_spec, - attributes, - None, - receipts, - )) + optimism_payload(self.evm_config.clone(), args, false)? + .into_payload() + .ok_or_else(|| PayloadBuilderError::MissingPayload) } } @@ -232,7 +119,7 @@ where /// and configuration, this function creates a transaction payload. Returns /// a result indicating success with the payload or an error in case of failure. #[inline] -pub(crate) fn optimism_payload_builder( +pub(crate) fn optimism_payload( evm_config: EvmConfig, args: BuildArguments, _compute_pending_block: bool, @@ -608,7 +495,6 @@ where trie: Arc::new(trie_output), }; - let receipts_pay: Vec = receipts.into_iter().flatten().collect(); let mut payload = OptimismBuiltPayload::new( attributes.payload_attributes.id, sealed_block, @@ -616,7 +502,6 @@ where chain_spec, attributes, Some(executed), - receipts_pay, ); // extend the payload with the blob sidecars from the executed txs diff --git a/crates/optimism/payload/src/error.rs b/crates/optimism/payload/src/error.rs index 38f5bb10b7c2..2016fdc6dd93 100644 --- a/crates/optimism/payload/src/error.rs +++ b/crates/optimism/payload/src/error.rs @@ -13,7 +13,7 @@ pub enum OptimismPayloadBuilderError { L1BlockInfoParseFailed, /// Thrown when a database account could not be loaded. #[error("failed to load account {0}")] - AccountLoadFailed(reth_primitives::Address), + AccountLoadFailed(alloy_primitives::Address), /// Thrown when force deploy of create2deployer code fails. #[error("failed to force create2deployer account code")] ForceCreate2DeployerFail, diff --git a/crates/optimism/payload/src/payload.rs b/crates/optimism/payload/src/payload.rs index df38c60ea9fc..62c559b32283 100644 --- a/crates/optimism/payload/src/payload.rs +++ b/crates/optimism/payload/src/payload.rs @@ -2,6 +2,7 @@ //! Optimism builder support +use alloy_primitives::{Address, B256, U256}; use alloy_rlp::Encodable; use reth_chain_state::ExecutedBlock; use reth_chainspec::{ChainSpec, EthereumHardforks}; @@ -11,8 +12,7 @@ use reth_payload_primitives::{BuiltPayload, PayloadBuilderAttributes}; use reth_primitives::{ revm_primitives::{BlobExcessGasAndPrice, BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, SpecId}, transaction::WithEncoded, - Address, BlobTransactionSidecar, Header, Receipt, SealedBlock, TransactionSigned, Withdrawals, - B256, U256, + BlobTransactionSidecar, Header, SealedBlock, TransactionSigned, Withdrawals, }; /// Re-export for use in downstream arguments. pub use reth_rpc_types::optimism::OptimismPayloadAttributes; @@ -179,8 +179,6 @@ pub struct OptimismBuiltPayload { pub(crate) chain_spec: Arc, /// The payload attributes. pub(crate) attributes: OptimismPayloadBuilderAttributes, - /// The receipts of the block - pub(crate) receipts: Vec, } // === impl BuiltPayload === @@ -194,18 +192,8 @@ impl OptimismBuiltPayload { chain_spec: Arc, attributes: OptimismPayloadBuilderAttributes, executed_block: Option, - receipts: Vec, ) -> Self { - Self { - id, - block, - executed_block, - fees, - sidecars: Vec::new(), - chain_spec, - attributes, - receipts, - } + Self { id, block, executed_block, fees, sidecars: Vec::new(), chain_spec, attributes } } /// Returns the identifier of the payload. @@ -241,10 +229,6 @@ impl BuiltPayload for OptimismBuiltPayload { fn executed_block(&self) -> Option { self.executed_block.clone() } - - fn receipts(&self) -> &[Receipt] { - &self.receipts - } } impl<'a> BuiltPayload for &'a OptimismBuiltPayload { @@ -259,10 +243,6 @@ impl<'a> BuiltPayload for &'a OptimismBuiltPayload { fn executed_block(&self) -> Option { self.executed_block.clone() } - - fn receipts(&self) -> &[Receipt] { - &self.receipts - } } // V1 engine_getPayloadV1 response diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 2383518895bd..15f911f52611 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -33,9 +33,9 @@ reth-chainspec.workspace = true # ethereum alloy-primitives.workspace = true op-alloy-network.workspace = true -revm.workspace = true op-alloy-rpc-types.workspace = true op-alloy-consensus.workspace = true +revm.workspace = true # async parking_lot.workspace = true @@ -49,7 +49,7 @@ serde_json.workspace = true # misc thiserror.workspace = true tracing.workspace = true -derive_more = { workspace = true, default-features = false, features = ["deref"] } +derive_more.workspace = true [dev-dependencies] reth-optimism-chainspec.workspace = true @@ -61,4 +61,4 @@ optimism = [ "reth-provider/optimism", "reth-rpc-eth-api/optimism", "revm/optimism", -] \ No newline at end of file +] diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index af3fe67221b3..1da1129a62e2 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -1,10 +1,8 @@ +use alloy_primitives::{Bytes, TxKind, U256}; use reth_chainspec::ChainSpec; use reth_evm::ConfigureEvm; use reth_node_api::{FullNodeComponents, NodeTypes}; -use reth_primitives::{ - revm_primitives::{BlockEnv, OptimismFields, TxEnv}, - Bytes, TxKind, U256, -}; +use reth_primitives::revm_primitives::{BlockEnv, OptimismFields, TxEnv}; use reth_rpc_eth_api::{ helpers::{Call, EthCall, LoadState, SpawnBlocking}, FromEthApiError, IntoEthApiError, diff --git a/crates/optimism/rpc/src/eth/pending_block.rs b/crates/optimism/rpc/src/eth/pending_block.rs index dfba808d356d..95c6d72cb23f 100644 --- a/crates/optimism/rpc/src/eth/pending_block.rs +++ b/crates/optimism/rpc/src/eth/pending_block.rs @@ -1,10 +1,11 @@ //! Loads OP pending block for a RPC response. +use alloy_primitives::{BlockNumber, B256}; use reth_chainspec::ChainSpec; use reth_evm::ConfigureEvm; use reth_node_api::{FullNodeComponents, NodeTypes}; use reth_primitives::{ - revm_primitives::BlockEnv, BlockNumber, BlockNumberOrTag, Receipt, SealedBlockWithSenders, B256, + revm_primitives::BlockEnv, BlockNumberOrTag, Receipt, SealedBlockWithSenders, }; use reth_provider::{ BlockReader, BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, ExecutionOutcome, diff --git a/crates/optimism/rpc/src/eth/rpc.rs b/crates/optimism/rpc/src/eth/rpc.rs index 02f227cbe9ae..747e36a3cf5f 100644 --- a/crates/optimism/rpc/src/eth/rpc.rs +++ b/crates/optimism/rpc/src/eth/rpc.rs @@ -73,7 +73,7 @@ impl SequencerClient { let body = serde_json::to_string(&serde_json::json!({ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", - "params": [format!("0x{}", reth_primitives::hex::encode(tx))], + "params": [format!("0x{}", alloy_primitives::hex::encode(tx))], "id": self.next_request_id() })) .map_err(|_| { diff --git a/crates/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 5df63fe4b71e..3847d46a5d99 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -746,6 +746,31 @@ pub enum BuildOutcome { Cancelled, } +impl BuildOutcome { + /// Consumes the type and returns the payload if the outcome is `Better`. + pub fn into_payload(self) -> Option { + match self { + Self::Better { payload, .. } => Some(payload), + _ => None, + } + } + + /// Returns true if the outcome is `Better`. + pub const fn is_better(&self) -> bool { + matches!(self, Self::Better { .. }) + } + + /// Returns true if the outcome is `Aborted`. + pub const fn is_aborted(&self) -> bool { + matches!(self, Self::Aborted { .. }) + } + + /// Returns true if the outcome is `Cancelled`. + pub const fn is_cancelled(&self) -> bool { + matches!(self, Self::Cancelled) + } +} + /// A collection of arguments used for building payloads. /// /// This struct encapsulates the essential components and configuration required for the payload @@ -756,6 +781,8 @@ pub struct BuildArguments { /// How to interact with the chain. pub client: Client, /// The transaction pool. + /// + /// Or the type that provides the transactions to build the payload. pub pool: Pool, /// Previously cached disk reads pub cached_reads: CachedReads, @@ -779,6 +806,18 @@ impl BuildArguments Self { Self { client, pool, cached_reads, config, cancel, best_payload } } + + /// Maps the transaction pool to a new type. + pub fn with_pool

(self, pool: P) -> BuildArguments { + BuildArguments { + client: self.client, + pool, + cached_reads: self.cached_reads, + config: self.config, + cancel: self.cancel, + best_payload: self.best_payload, + } + } } /// A trait for building payloads that encapsulate Ethereum transactions. diff --git a/crates/payload/builder/src/lib.rs b/crates/payload/builder/src/lib.rs index 56c9d1ab494f..fa78e912cfcd 100644 --- a/crates/payload/builder/src/lib.rs +++ b/crates/payload/builder/src/lib.rs @@ -65,7 +65,7 @@ //! }, //! ..Default::default() //! }; -//! let payload = EthBuiltPayload::new(self.attributes.id, payload.seal_slow(), U256::ZERO, Vec::new(), None); +//! let payload = EthBuiltPayload::new(self.attributes.id, payload.seal_slow(), U256::ZERO, None); //! Ok(payload) //! } //! diff --git a/crates/payload/builder/src/test_utils.rs b/crates/payload/builder/src/test_utils.rs index 23e484344ba3..e4083d3ab386 100644 --- a/crates/payload/builder/src/test_utils.rs +++ b/crates/payload/builder/src/test_utils.rs @@ -86,7 +86,6 @@ impl PayloadJob for TestPayloadJob { self.attr.payload_id(), Block::default().seal_slow(), U256::ZERO, - Vec::new(), None, )) } diff --git a/crates/payload/primitives/src/traits.rs b/crates/payload/primitives/src/traits.rs index c3d011f7ef8c..80ae38127e8a 100644 --- a/crates/payload/primitives/src/traits.rs +++ b/crates/payload/primitives/src/traits.rs @@ -2,7 +2,7 @@ use reth_chain_state::ExecutedBlock; use reth_chainspec::ChainSpec; use reth_primitives::{ revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg}, - Address, Header, Receipt, SealedBlock, Withdrawals, B256, U256, + Address, Header, SealedBlock, Withdrawals, B256, U256, }; use reth_rpc_types::{ engine::{PayloadAttributes as EthPayloadAttributes, PayloadId}, @@ -23,9 +23,6 @@ pub trait BuiltPayload: Send + Sync + std::fmt::Debug { /// Returns the fees collected for the built block fn fees(&self) -> U256; - /// Returns the Receipts - fn receipts(&self) -> &[Receipt]; - /// Returns the entire execution data for the built block, if available. fn executed_block(&self) -> Option { None diff --git a/crates/primitives-traits/src/constants/mod.rs b/crates/primitives-traits/src/constants/mod.rs index 8da0bd331ee6..ed5c893dd6c2 100644 --- a/crates/primitives-traits/src/constants/mod.rs +++ b/crates/primitives-traits/src/constants/mod.rs @@ -32,8 +32,6 @@ pub const EPOCH_DURATION: Duration = Duration::from_secs(12 * EPOCH_SLOTS); pub const BEACON_NONCE: u64 = 0u64; /// The default Ethereum block gas limit. -// TODO: This should be a chain spec parameter. -/// See . pub const ETHEREUM_BLOCK_GAS_LIMIT: u64 = 30_000_000; /// The minimum tx fee below which the txpool will reject the transaction. diff --git a/crates/primitives/src/transaction/compat.rs b/crates/primitives/src/transaction/compat.rs index 410d6f7c8fe0..be51d0e4bb04 100644 --- a/crates/primitives/src/transaction/compat.rs +++ b/crates/primitives/src/transaction/compat.rs @@ -81,7 +81,7 @@ impl FillTxEnv for TransactionSigned { tx_env.gas_limit = tx.gas_limit as u64; tx_env.gas_price = U256::from(tx.max_fee_per_gas); tx_env.gas_priority_fee = Some(U256::from(tx.max_priority_fee_per_gas)); - tx_env.transact_to = tx.to; + tx_env.transact_to = tx.to.into(); tx_env.value = tx.value; tx_env.data = tx.input.clone(); tx_env.chain_id = Some(tx.chain_id); diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 4e00d0139466..012e64954e26 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -218,9 +218,10 @@ impl Transaction { match self { Self::Legacy(TxLegacy { to, .. }) | Self::Eip2930(TxEip2930 { to, .. }) | - Self::Eip1559(TxEip1559 { to, .. }) | - Self::Eip7702(TxEip7702 { to, .. }) => *to, - Self::Eip4844(TxEip4844 { to, .. }) => TxKind::Call(*to), + Self::Eip1559(TxEip1559 { to, .. }) => *to, + Self::Eip4844(TxEip4844 { to, .. }) | Self::Eip7702(TxEip7702 { to, .. }) => { + TxKind::Call(*to) + } #[cfg(feature = "optimism")] Self::Deposit(TxDeposit { to, .. }) => *to, } diff --git a/crates/rpc/rpc-api/Cargo.toml b/crates/rpc/rpc-api/Cargo.toml index 3bfb2e9a7662..399dfe9cc33b 100644 --- a/crates/rpc/rpc-api/Cargo.toml +++ b/crates/rpc/rpc-api/Cargo.toml @@ -21,6 +21,7 @@ reth-network-peers.workspace = true # ethereum alloy-json-rpc.workspace = true +alloy-primitives.workspace = true # misc jsonrpsee = { workspace = true, features = ["server", "macros"] } diff --git a/crates/rpc/rpc-api/src/anvil.rs b/crates/rpc/rpc-api/src/anvil.rs index 56416d094136..e916fa8c232c 100644 --- a/crates/rpc/rpc-api/src/anvil.rs +++ b/crates/rpc/rpc-api/src/anvil.rs @@ -1,6 +1,6 @@ use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, Bytes, B256, U256}; +use alloy_primitives::{Address, Bytes, B256, U256}; use reth_rpc_types::{ anvil::{Forking, Metadata, MineOptions, NodeInfo}, Block, diff --git a/crates/rpc/rpc-api/src/debug.rs b/crates/rpc/rpc-api/src/debug.rs index 705ccc6ed1a5..0876b464cf74 100644 --- a/crates/rpc/rpc-api/src/debug.rs +++ b/crates/rpc/rpc-api/src/debug.rs @@ -1,5 +1,6 @@ +use alloy_primitives::{Address, Bytes, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256}; +use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_types::{ debug::ExecutionWitness, trace::geth::{ diff --git a/crates/rpc/rpc-api/src/engine.rs b/crates/rpc/rpc-api/src/engine.rs index 23537b5271c3..09993dd2f60d 100644 --- a/crates/rpc/rpc-api/src/engine.rs +++ b/crates/rpc/rpc-api/src/engine.rs @@ -4,9 +4,10 @@ //! the consensus client. use alloy_json_rpc::RpcObject; +use alloy_primitives::{Address, BlockHash, Bytes, B256, U256, U64}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_engine_primitives::EngineTypes; -use reth_primitives::{Address, BlockHash, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64}; +use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_types::{ engine::{ ClientVersionV1, ExecutionPayloadBodiesV1, ExecutionPayloadBodiesV2, @@ -14,8 +15,8 @@ use reth_rpc_types::{ ForkchoiceState, ForkchoiceUpdated, PayloadId, PayloadStatus, TransitionConfiguration, }, state::StateOverride, - BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, SyncStatus, - TransactionRequest, + BlobAndProofV1, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, + SyncStatus, TransactionRequest, }; // NOTE: We can't use associated types in the `EngineApi` trait because of jsonrpsee, so we use a // generic here. It would be nice if the rpc macro would understand which types need to have serde. @@ -213,6 +214,13 @@ pub trait EngineApi { /// See also #[method(name = "exchangeCapabilities")] async fn exchange_capabilities(&self, capabilities: Vec) -> RpcResult>; + + /// Fetch blobs for the consensus layer from the in-memory blob cache. + #[method(name = "getBlobsV1")] + async fn get_blobs_v1( + &self, + transaction_ids: Vec, + ) -> RpcResult>>; } /// A subset of the ETH rpc interface: diff --git a/crates/rpc/rpc-api/src/ganache.rs b/crates/rpc/rpc-api/src/ganache.rs index 338c914980eb..99a50c0fae42 100644 --- a/crates/rpc/rpc-api/src/ganache.rs +++ b/crates/rpc/rpc-api/src/ganache.rs @@ -1,5 +1,5 @@ +use alloy_primitives::U256; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::U256; use reth_rpc_types::anvil::MineOptions; /// Ganache rpc interface. diff --git a/crates/rpc/rpc-api/src/hardhat.rs b/crates/rpc/rpc-api/src/hardhat.rs index 1620bdb59671..c34991fd3a4f 100644 --- a/crates/rpc/rpc-api/src/hardhat.rs +++ b/crates/rpc/rpc-api/src/hardhat.rs @@ -1,5 +1,5 @@ +use alloy_primitives::{Address, Bytes, B256, U256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, Bytes, B256, U256}; use reth_rpc_types::anvil::{Forking, Metadata}; /// Hardhat rpc interface. diff --git a/crates/rpc/rpc-api/src/net.rs b/crates/rpc/rpc-api/src/net.rs index 98aa65bd0924..5535f123c18c 100644 --- a/crates/rpc/rpc-api/src/net.rs +++ b/crates/rpc/rpc-api/src/net.rs @@ -1,5 +1,5 @@ +use alloy_primitives::U64; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::U64; /// Net rpc interface. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "net"))] diff --git a/crates/rpc/rpc-api/src/otterscan.rs b/crates/rpc/rpc-api/src/otterscan.rs index 1da4def25227..c025087ff53e 100644 --- a/crates/rpc/rpc-api/src/otterscan.rs +++ b/crates/rpc/rpc-api/src/otterscan.rs @@ -1,5 +1,6 @@ +use alloy_primitives::{Address, Bytes, TxHash, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, BlockId, Bytes, TxHash, B256}; +use reth_primitives::BlockId; use reth_rpc_types::{ trace::otterscan::{ BlockDetails, ContractCreator, InternalOperation, OtsBlockTransactions, TraceEntry, diff --git a/crates/rpc/rpc-api/src/reth.rs b/crates/rpc/rpc-api/src/reth.rs index 1e9c4314ab14..98c31b78f9a4 100644 --- a/crates/rpc/rpc-api/src/reth.rs +++ b/crates/rpc/rpc-api/src/reth.rs @@ -1,5 +1,6 @@ +use alloy_primitives::{Address, U256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Address, BlockId, U256}; +use reth_primitives::BlockId; use std::collections::HashMap; /// Reth API namespace for reth-specific methods diff --git a/crates/rpc/rpc-api/src/trace.rs b/crates/rpc/rpc-api/src/trace.rs index aa2a5693a865..13518c73d10b 100644 --- a/crates/rpc/rpc-api/src/trace.rs +++ b/crates/rpc/rpc-api/src/trace.rs @@ -1,5 +1,6 @@ +use alloy_primitives::{Bytes, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{BlockId, Bytes, B256}; +use reth_primitives::BlockId; use reth_rpc_types::{ state::StateOverride, trace::{ diff --git a/crates/rpc/rpc-api/src/txpool.rs b/crates/rpc/rpc-api/src/txpool.rs index 844bcceaab5d..34591aa6d4d5 100644 --- a/crates/rpc/rpc-api/src/txpool.rs +++ b/crates/rpc/rpc-api/src/txpool.rs @@ -1,5 +1,5 @@ +use alloy_primitives::Address; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::Address; use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolStatus}, Transaction, WithOtherFields, diff --git a/crates/rpc/rpc-api/src/web3.rs b/crates/rpc/rpc-api/src/web3.rs index cf3887cbc825..c4017e03f2df 100644 --- a/crates/rpc/rpc-api/src/web3.rs +++ b/crates/rpc/rpc-api/src/web3.rs @@ -1,5 +1,5 @@ +use alloy_primitives::{Bytes, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{Bytes, B256}; /// Web3 rpc interface. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "web3"))] diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index 03d0f1eb2c26..593d5f9efe10 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -30,6 +30,9 @@ reth-evm.workspace = true reth-engine-primitives.workspace = true reth-rpc-types.workspace = true +# ethereum +alloy-network.workspace = true + # rpc/net jsonrpsee = { workspace = true, features = ["server"] } tower-http = { workspace = true, features = ["full"] } @@ -65,6 +68,8 @@ reth-tokio-util.workspace = true reth-node-api.workspace = true reth-rpc-types-compat.workspace = true +alloy-primitives.workspace = true + tokio = { workspace = true, features = ["rt", "rt-multi-thread"] } serde_json.workspace = true clap = { workspace = true, features = ["derive"] } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 9401dce6e0d4..9d99204981fd 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -207,6 +207,7 @@ pub use eth::EthHandlers; // Rpc server metrics mod metrics; pub use metrics::{MeteredRequestFuture, RpcRequestMetricsService}; +use reth_node_core::rpc::types::AnyTransactionReceipt; /// Convenience function for starting a server in one step. #[allow(clippy::too_many_arguments)] diff --git a/crates/rpc/rpc-builder/tests/it/auth.rs b/crates/rpc/rpc-builder/tests/it/auth.rs index 631ea813578d..79a42d121c0b 100644 --- a/crates/rpc/rpc-builder/tests/it/auth.rs +++ b/crates/rpc/rpc-builder/tests/it/auth.rs @@ -1,9 +1,10 @@ //! Auth server tests use crate::utils::launch_auth; +use alloy_primitives::U64; use jsonrpsee::core::client::{ClientT, SubscriptionClientT}; use reth_ethereum_engine_primitives::EthEngineTypes; -use reth_primitives::{Block, U64}; +use reth_primitives::Block; use reth_rpc_api::clients::EngineApiClient; use reth_rpc_layer::JwtSecret; use reth_rpc_types::engine::{ForkchoiceState, PayloadId, TransitionConfiguration}; diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index c6a4975a04aa..500631427cb2 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -2,6 +2,7 @@ //! Standalone http tests use crate::utils::{launch_http, launch_http_ws, launch_ws}; +use alloy_primitives::{hex_literal::hex, Address, Bytes, TxHash, B256, B64, U256, U64}; use jsonrpsee::{ core::{ client::{ClientT, SubscriptionClientT}, @@ -12,10 +13,7 @@ use jsonrpsee::{ types::error::ErrorCode, }; use reth_network_peers::NodeRecord; -use reth_primitives::{ - hex_literal::hex, Address, BlockId, BlockNumberOrTag, Bytes, Receipt, TxHash, B256, B64, U256, - U64, -}; +use reth_primitives::{BlockId, BlockNumberOrTag, Receipt}; use reth_rpc_api::{ clients::{AdminApiClient, EthApiClient}, DebugApiClient, EthFilterApiClient, NetApiClient, OtterscanClient, TraceApiClient, diff --git a/crates/rpc/rpc-builder/tests/it/serde.rs b/crates/rpc/rpc-builder/tests/it/serde.rs index 5df41b2d19b7..e8d60f4c3bdb 100644 --- a/crates/rpc/rpc-builder/tests/it/serde.rs +++ b/crates/rpc/rpc-builder/tests/it/serde.rs @@ -1,11 +1,11 @@ //! various serde test use crate::utils::launch_http; +use alloy_primitives::U256; use jsonrpsee::{ core::{client::ClientT, traits::ToRpcParams}, types::Request, }; -use reth_primitives::U256; use reth_rpc_server_types::RethRpcModule; use serde_json::value::RawValue; diff --git a/crates/rpc/rpc-builder/tests/it/utils.rs b/crates/rpc/rpc-builder/tests/it/utils.rs index 85d81ea39f09..14104492000c 100644 --- a/crates/rpc/rpc-builder/tests/it/utils.rs +++ b/crates/rpc/rpc-builder/tests/it/utils.rs @@ -17,7 +17,10 @@ use reth_rpc_layer::JwtSecret; use reth_rpc_server_types::RpcModuleSelection; use reth_rpc_types::engine::{ClientCode, ClientVersionV1}; use reth_tasks::TokioTaskExecutor; -use reth_transaction_pool::test_utils::{TestPool, TestPoolBuilder}; +use reth_transaction_pool::{ + noop::NoopTransactionPool, + test_utils::{TestPool, TestPoolBuilder}, +}; use tokio::sync::mpsc::unbounded_channel; /// Localhost with port 0 so a free port is used. @@ -43,6 +46,7 @@ pub async fn launch_auth(secret: JwtSecret) -> AuthServerHandle { MAINNET.clone(), beacon_engine_handle, spawn_test_payload_service().into(), + NoopTransactionPool::default(), Box::::default(), client, EngineCapabilities::default(), diff --git a/crates/rpc/rpc-engine-api/Cargo.toml b/crates/rpc/rpc-engine-api/Cargo.toml index d067515f6c2a..228e0a1fc6cb 100644 --- a/crates/rpc/rpc-engine-api/Cargo.toml +++ b/crates/rpc/rpc-engine-api/Cargo.toml @@ -25,6 +25,10 @@ reth-tasks.workspace = true reth-rpc-types-compat.workspace = true reth-engine-primitives.workspace = true reth-evm.workspace = true +reth-transaction-pool.workspace = true + +# ethereum +alloy-primitives.workspace = true # async tokio = { workspace = true, features = ["sync"] } diff --git a/crates/rpc/rpc-engine-api/src/capabilities.rs b/crates/rpc/rpc-engine-api/src/capabilities.rs index eb796aebcd0c..de4d96231538 100644 --- a/crates/rpc/rpc-engine-api/src/capabilities.rs +++ b/crates/rpc/rpc-engine-api/src/capabilities.rs @@ -19,6 +19,7 @@ pub const CAPABILITIES: &[&str] = &[ "engine_getPayloadBodiesByRangeV1", "engine_getPayloadBodiesByHashV2", "engine_getPayloadBodiesByRangeV2", + "engine_getBlobsV1", ]; // The list of all supported Engine capabilities available over the engine endpoint. diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index 10c965f451fe..95a172a11334 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -1,6 +1,7 @@ use crate::{ capabilities::EngineCapabilities, metrics::EngineApiMetrics, EngineApiError, EngineApiResult, }; +use alloy_primitives::{BlockHash, BlockNumber, B256, U64}; use async_trait::async_trait; use jsonrpsee_core::RpcResult; use reth_beacon_consensus::BeaconConsensusEngineHandle; @@ -12,21 +13,23 @@ use reth_payload_primitives::{ validate_payload_timestamp, EngineApiMessageVersion, PayloadAttributes, PayloadBuilderAttributes, PayloadOrAttributes, }; -use reth_primitives::{ - Block, BlockHash, BlockHashOrNumber, BlockNumber, EthereumHardfork, B256, U64, -}; +use reth_primitives::{Block, BlockHashOrNumber, EthereumHardfork}; use reth_rpc_api::EngineApiServer; -use reth_rpc_types::engine::{ - CancunPayloadFields, ClientVersionV1, ExecutionPayload, ExecutionPayloadBodiesV1, - ExecutionPayloadBodiesV2, ExecutionPayloadInputV2, ExecutionPayloadV1, ExecutionPayloadV3, - ExecutionPayloadV4, ForkchoiceState, ForkchoiceUpdated, PayloadId, PayloadStatus, - TransitionConfiguration, +use reth_rpc_types::{ + engine::{ + CancunPayloadFields, ClientVersionV1, ExecutionPayload, ExecutionPayloadBodiesV1, + ExecutionPayloadBodiesV2, ExecutionPayloadInputV2, ExecutionPayloadV1, ExecutionPayloadV3, + ExecutionPayloadV4, ForkchoiceState, ForkchoiceUpdated, PayloadId, PayloadStatus, + TransitionConfiguration, + }, + BlobAndProofV1, }; use reth_rpc_types_compat::engine::payload::{ convert_payload_input_v2_to_payload, convert_to_payload_body_v1, convert_to_payload_body_v2, }; use reth_storage_api::{BlockReader, HeaderProvider, StateProviderFactory}; use reth_tasks::TaskSpawner; +use reth_transaction_pool::TransactionPool; use std::{sync::Arc, time::Instant}; use tokio::sync::oneshot; use tracing::{trace, warn}; @@ -37,13 +40,16 @@ pub type EngineApiSender = oneshot::Sender>; /// The upper limit for payload bodies request. const MAX_PAYLOAD_BODIES_LIMIT: u64 = 1024; +/// The upper limit blobs `eth_getBlobs`. +const MAX_BLOB_LIMIT: usize = 128; + /// The Engine API implementation that grants the Consensus layer access to data and /// functions in the Execution layer that are crucial for the consensus process. -pub struct EngineApi { - inner: Arc>, +pub struct EngineApi { + inner: Arc>, } -struct EngineApiInner { +struct EngineApiInner { /// The provider to interact with the chain. provider: Provider, /// Consensus configuration @@ -60,19 +66,24 @@ struct EngineApiInner { client: ClientVersionV1, /// The list of all supported Engine capabilities available over the engine endpoint. capabilities: EngineCapabilities, + /// Transaction pool. + tx_pool: Pool, } -impl EngineApi +impl EngineApi where Provider: HeaderProvider + BlockReader + StateProviderFactory + EvmEnvProvider + 'static, EngineT: EngineTypes, + Pool: TransactionPool + 'static, { /// Create new instance of [`EngineApi`]. + #[allow(clippy::too_many_arguments)] pub fn new( provider: Provider, chain_spec: Arc, beacon_consensus: BeaconConsensusEngineHandle, payload_store: PayloadStore, + tx_pool: Pool, task_spawner: Box, client: ClientVersionV1, capabilities: EngineCapabilities, @@ -86,6 +97,7 @@ where metrics: EngineApiMetrics::default(), client, capabilities, + tx_pool, }); Self { inner } } @@ -609,10 +621,11 @@ where } #[async_trait] -impl EngineApiServer for EngineApi +impl EngineApiServer for EngineApi where Provider: HeaderProvider + BlockReader + StateProviderFactory + EvmEnvProvider + 'static, EngineT: EngineTypes, + Pool: TransactionPool + 'static, { /// Handler for `engine_newPayloadV1` /// See also @@ -904,9 +917,25 @@ where async fn exchange_capabilities(&self, _capabilities: Vec) -> RpcResult> { Ok(self.inner.capabilities.list()) } + + async fn get_blobs_v1( + &self, + versioned_hashes: Vec, + ) -> RpcResult>> { + trace!(target: "rpc::engine", "Serving engine_getBlobsV1"); + if versioned_hashes.len() > MAX_BLOB_LIMIT { + return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }.into()) + } + + Ok(self + .inner + .tx_pool + .get_blobs_for_versioned_hashes(&versioned_hashes) + .map_err(|err| EngineApiError::Internal(Box::new(err)))?) + } } -impl std::fmt::Debug for EngineApi +impl std::fmt::Debug for EngineApi where EngineT: EngineTypes, { @@ -920,20 +949,21 @@ mod tests { use super::*; use assert_matches::assert_matches; use reth_beacon_consensus::{BeaconConsensusEngineEvent, BeaconEngineMessage}; - use reth_ethereum_engine_primitives::EthEngineTypes; - use reth_testing_utils::generators::random_block; - use reth_chainspec::MAINNET; + use reth_ethereum_engine_primitives::EthEngineTypes; use reth_payload_builder::test_utils::spawn_test_payload_service; use reth_primitives::SealedBlock; use reth_provider::test_utils::MockEthProvider; use reth_rpc_types::engine::{ClientCode, ClientVersionV1}; use reth_rpc_types_compat::engine::payload::execution_payload_from_sealed_block; use reth_tasks::TokioTaskExecutor; + use reth_testing_utils::generators::random_block; use reth_tokio_util::EventSender; + use reth_transaction_pool::noop::NoopTransactionPool; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver}; - fn setup_engine_api() -> (EngineApiTestHandle, EngineApi, EthEngineTypes>) + fn setup_engine_api( + ) -> (EngineApiTestHandle, EngineApi, EthEngineTypes, NoopTransactionPool>) { let client = ClientVersionV1 { code: ClientCode::RH, @@ -953,6 +983,7 @@ mod tests { chain_spec.clone(), BeaconConsensusEngineHandle::new(to_engine, event_sender), payload_store.into(), + NoopTransactionPool::default(), task_executor, client, EngineCapabilities::default(), @@ -1115,7 +1146,7 @@ mod tests { // https://github.com/ethereum/execution-apis/blob/main/src/engine/paris.md#specification-3 mod exchange_transition_configuration { use super::*; - use reth_primitives::U256; + use alloy_primitives::U256; use reth_testing_utils::generators::{self, BlockParams}; #[tokio::test] diff --git a/crates/rpc/rpc-engine-api/src/error.rs b/crates/rpc/rpc-engine-api/src/error.rs index a1e4dc328995..7fd5a112a1c6 100644 --- a/crates/rpc/rpc-engine-api/src/error.rs +++ b/crates/rpc/rpc-engine-api/src/error.rs @@ -1,10 +1,10 @@ +use alloy_primitives::{B256, U256}; use jsonrpsee_types::error::{ INTERNAL_ERROR_CODE, INVALID_PARAMS_CODE, INVALID_PARAMS_MSG, SERVER_ERROR_MSG, }; use reth_beacon_consensus::{BeaconForkChoiceUpdateError, BeaconOnNewPayloadError}; use reth_payload_builder::error::PayloadBuilderError; use reth_payload_primitives::EngineObjectValidationError; -use reth_primitives::{B256, U256}; use reth_rpc_types::ToRpcError; use thiserror::Error; @@ -42,6 +42,12 @@ pub enum EngineApiError { /// The length that was requested. len: u64, }, + /// Too many requested versioned hashes for blobs request + #[error("requested blob count too large: {len}")] + BlobRequestTooLarge { + /// The length that was requested. + len: usize, + }, /// Thrown if `engine_getPayloadBodiesByRangeV1` contains an invalid range #[error("invalid start ({start}) or count ({count})")] InvalidBodiesRange { @@ -145,7 +151,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { error.to_string(), None::<()>, ), - EngineApiError::PayloadRequestTooLarge { .. } => { + EngineApiError::PayloadRequestTooLarge { .. } | + EngineApiError::BlobRequestTooLarge { .. } => { jsonrpsee_types::error::ErrorObject::owned( REQUEST_TOO_LARGE_CODE, REQUEST_TOO_LARGE_MESSAGE, diff --git a/crates/rpc/rpc-engine-api/tests/it/payload.rs b/crates/rpc/rpc-engine-api/tests/it/payload.rs index c57beb21001c..0587de68498a 100644 --- a/crates/rpc/rpc-engine-api/tests/it/payload.rs +++ b/crates/rpc/rpc-engine-api/tests/it/payload.rs @@ -1,8 +1,9 @@ //! Some payload tests +use alloy_primitives::{Bytes, U256}; use alloy_rlp::{Decodable, Error as RlpError}; use assert_matches::assert_matches; -use reth_primitives::{proofs, Block, Bytes, SealedBlock, TransactionSigned, Withdrawals, U256}; +use reth_primitives::{proofs, Block, SealedBlock, TransactionSigned, Withdrawals}; use reth_rpc_types::engine::{ ExecutionPayload, ExecutionPayloadBodyV1, ExecutionPayloadV1, PayloadError, }; diff --git a/crates/rpc/rpc-eth-api/Cargo.toml b/crates/rpc/rpc-eth-api/Cargo.toml index 5c18bfef46ce..60762ba865bf 100644 --- a/crates/rpc/rpc-eth-api/Cargo.toml +++ b/crates/rpc/rpc-eth-api/Cargo.toml @@ -34,8 +34,9 @@ reth-trie.workspace = true # ethereum alloy-dyn-abi = { workspace = true, features = ["eip712"] } -alloy-network.workspace = true alloy-json-rpc.workspace = true +alloy-network.workspace = true +alloy-primitives.workspace = true # rpc jsonrpsee = { workspace = true, features = ["server", "macros"] } @@ -59,4 +60,4 @@ optimism = [ "reth-primitives/optimism", "revm/optimism", "reth-provider/optimism", -] \ No newline at end of file +] diff --git a/crates/rpc/rpc-eth-api/src/bundle.rs b/crates/rpc/rpc-eth-api/src/bundle.rs index bf3a623df2f1..563e6ff75459 100644 --- a/crates/rpc/rpc-eth-api/src/bundle.rs +++ b/crates/rpc/rpc-eth-api/src/bundle.rs @@ -2,8 +2,8 @@ //! //! See also +use alloy_primitives::{Bytes, B256}; use jsonrpsee::proc_macros::rpc; -use reth_primitives::{Bytes, B256}; use reth_rpc_types::mev::{ CancelBundleRequest, CancelPrivateTransactionRequest, EthBundleHash, EthCallBundle, EthCallBundleResponse, EthSendBundle, PrivateTransactionRequest, diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index f4c879ff0c55..573e5c9f9275 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -3,10 +3,9 @@ use alloy_dyn_abi::TypedData; use alloy_json_rpc::RpcObject; +use alloy_primitives::{Address, Bytes, B256, B64, U256, U64}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_primitives::{ - transaction::AccessListResult, Address, BlockId, BlockNumberOrTag, Bytes, B256, B64, U256, U64, -}; +use reth_primitives::{transaction::AccessListResult, BlockId, BlockNumberOrTag}; use reth_rpc_server_types::{result::internal_rpc_err, ToRpcResult}; use reth_rpc_types::{ serde_helpers::JsonStorageKey, diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 3ae9dcb4509e..81780a62d138 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -2,6 +2,7 @@ //! methods. use crate::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}; +use alloy_primitives::{Bytes, TxKind, B256, U256}; use futures::Future; use reth_evm::{ConfigureEvm, ConfigureEvmEnv}; use reth_primitives::{ @@ -10,7 +11,7 @@ use reth_primitives::{ ResultAndState, TransactTo, TxEnv, }, transaction::AccessListResult, - Bytes, TransactionSignedEcRecovered, TxKind, B256, U256, + TransactionSignedEcRecovered, }; use reth_provider::{ChainSpecProvider, StateProvider}; use reth_revm::{database::StateProviderDatabase, db::CacheDB, DatabaseRef}; diff --git a/crates/rpc/rpc-eth-api/src/helpers/fee.rs b/crates/rpc/rpc-eth-api/src/helpers/fee.rs index 5488eb642160..ac0c7cd9d495 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/fee.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/fee.rs @@ -1,8 +1,8 @@ //! Loads fee history from database. Helper trait for `eth_` fee and transaction RPC methods. +use alloy_primitives::U256; use futures::Future; use reth_chainspec::ChainSpec; -use reth_primitives::U256; use reth_provider::{BlockIdReader, BlockReaderIdExt, ChainSpecProvider, HeaderProvider}; use reth_rpc_eth_types::{ fee_history::calculate_reward_percentiles_for_block, EthApiError, EthStateCache, diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index 7109f41d4cd9..f46dc62387ba 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -4,6 +4,7 @@ use std::time::{Duration, Instant}; use crate::{EthApiTypes, FromEthApiError, FromEvmError}; +use alloy_primitives::{BlockNumber, B256, U256}; use futures::Future; use reth_chainspec::{ChainSpec, EthereumHardforks}; use reth_evm::{ @@ -18,9 +19,8 @@ use reth_primitives::{ BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, EVMError, Env, ExecutionResult, InvalidTransaction, ResultAndState, SpecId, }, - Block, BlockNumber, Header, IntoRecoveredTransaction, Receipt, Requests, - SealedBlockWithSenders, SealedHeader, TransactionSignedEcRecovered, B256, - EMPTY_OMMER_ROOT_HASH, U256, + Block, Header, IntoRecoveredTransaction, Receipt, Requests, SealedBlockWithSenders, + SealedHeader, TransactionSignedEcRecovered, EMPTY_OMMER_ROOT_HASH, }; use reth_provider::{ BlockReader, BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, ProviderError, diff --git a/crates/rpc/rpc-eth-api/src/helpers/signer.rs b/crates/rpc/rpc-eth-api/src/helpers/signer.rs index 5b71761431eb..3580410b6d29 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/signer.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/signer.rs @@ -3,8 +3,9 @@ use std::result; use alloy_dyn_abi::TypedData; +use alloy_primitives::Address; use dyn_clone::DynClone; -use reth_primitives::{Address, Signature, TransactionSigned}; +use reth_primitives::{Signature, TransactionSigned}; use reth_rpc_eth_types::SignError; use reth_rpc_types::TypedTransactionRequest; diff --git a/crates/rpc/rpc-eth-api/src/helpers/spec.rs b/crates/rpc/rpc-eth-api/src/helpers/spec.rs index f8f257fdbba3..f404ec7db147 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/spec.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/spec.rs @@ -2,11 +2,11 @@ use std::sync::Arc; +use alloy_primitives::{Address, U256, U64}; use futures::Future; use reth_chainspec::{ChainInfo, ChainSpec}; use reth_errors::{RethError, RethResult}; use reth_network_api::NetworkInfo; -use reth_primitives::{Address, U256, U64}; use reth_provider::{BlockNumReader, ChainSpecProvider, StageCheckpointReader}; use reth_rpc_types::{Stage, SyncInfo, SyncStatus}; diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index d991d1e27500..65bf128c754a 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -1,11 +1,12 @@ //! Loads a pending block from database. Helper trait for `eth_` block, transaction, call and trace //! RPC methods. +use alloy_primitives::{Address, Bytes, B256, U256}; use futures::Future; use reth_chainspec::ChainSpec; use reth_errors::RethError; use reth_evm::ConfigureEvmEnv; -use reth_primitives::{Address, BlockId, Bytes, Header, B256, KECCAK_EMPTY, U256}; +use reth_primitives::{BlockId, Header, KECCAK_EMPTY}; use reth_provider::{ BlockIdReader, ChainSpecProvider, StateProvider, StateProviderBox, StateProviderFactory, }; diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index e5a2b24ba0c1..b90af06cc3c3 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -1,8 +1,8 @@ //! Loads a pending block from database. Helper trait for `eth_` call and trace RPC methods. +use alloy_primitives::B256; use futures::Future; use reth_evm::{ConfigureEvm, ConfigureEvmEnv}; -use reth_primitives::B256; use reth_revm::database::StateProviderDatabase; use reth_rpc_eth_types::{ cache::db::{StateCacheDb, StateCacheDbRefMutWrapper, StateProviderTraitObjWrapper}, diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index be447e11d974..dbe1150c9475 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -2,10 +2,10 @@ //! network. use alloy_dyn_abi::TypedData; +use alloy_primitives::{Address, Bytes, TxHash, TxKind, B256, U256}; use futures::Future; use reth_primitives::{ - Address, BlockId, Bytes, Receipt, SealedBlockWithSenders, TransactionMeta, TransactionSigned, - TxHash, TxKind, B256, U256, + BlockId, Receipt, SealedBlockWithSenders, TransactionMeta, TransactionSigned, }; use reth_provider::{BlockNumReader, BlockReaderIdExt, ReceiptProvider, TransactionsProvider}; use reth_rpc_eth_types::{ diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 90c7035f385f..1c533ab5d89c 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -20,7 +20,6 @@ pub trait EthApiTypes: Send + Sync + Clone { + Sync; /// Blockchain primitive types, specific to network, e.g. block and transaction. // todo: remove restriction [`reth_rpc_types::Transaction`] - // todo: remove restriction [`reth_rpc_types::AnyTransactionReceipt`] type NetworkTypes: Network< TransactionResponse = WithOtherFields, HeaderResponse = reth_rpc_types::Header, diff --git a/crates/rpc/rpc-eth-types/Cargo.toml b/crates/rpc/rpc-eth-types/Cargo.toml index 2d2330107d92..0e3a56db746b 100644 --- a/crates/rpc/rpc-eth-types/Cargo.toml +++ b/crates/rpc/rpc-eth-types/Cargo.toml @@ -30,10 +30,12 @@ reth-trie.workspace = true reth-provider.workspace = true # ethereum +alloy-primitives.workspace = true alloy-sol-types.workspace = true revm.workspace = true revm-inspectors.workspace = true revm-primitives = { workspace = true, features = ["dev"] } +alloy-rpc-types.workspace = true # rpc jsonrpsee-core.workspace = true diff --git a/crates/rpc/rpc-eth-types/src/cache/db.rs b/crates/rpc/rpc-eth-types/src/cache/db.rs index 2437f99864a6..60b895c47bae 100644 --- a/crates/rpc/rpc-eth-types/src/cache/db.rs +++ b/crates/rpc/rpc-eth-types/src/cache/db.rs @@ -2,8 +2,8 @@ //! in default implementation of //! `reth_rpc_eth_api::helpers::Call`. +use alloy_primitives::{Address, B256, U256}; use reth_errors::ProviderResult; -use reth_primitives::{Address, B256, U256}; use reth_revm::{database::StateProviderDatabase, db::CacheDB, DatabaseRef}; use reth_storage_api::StateProvider; use reth_trie::HashedStorage; @@ -75,7 +75,7 @@ impl<'a> reth_storage_api::StateProofProvider for StateProviderTraitObjWrapper<' &self, overlay: reth_trie::HashedPostState, target: reth_trie::HashedPostState, - ) -> reth_errors::ProviderResult> { + ) -> reth_errors::ProviderResult> { self.0.witness(overlay, target) } } @@ -92,15 +92,15 @@ impl<'a> reth_storage_api::AccountReader for StateProviderTraitObjWrapper<'a> { impl<'a> reth_storage_api::BlockHashReader for StateProviderTraitObjWrapper<'a> { fn block_hash( &self, - block_number: reth_primitives::BlockNumber, + block_number: alloy_primitives::BlockNumber, ) -> reth_errors::ProviderResult> { self.0.block_hash(block_number) } fn canonical_hashes_range( &self, - start: reth_primitives::BlockNumber, - end: reth_primitives::BlockNumber, + start: alloy_primitives::BlockNumber, + end: alloy_primitives::BlockNumber, ) -> reth_errors::ProviderResult> { self.0.canonical_hashes_range(start, end) } @@ -145,8 +145,8 @@ impl<'a> StateProvider for StateProviderTraitObjWrapper<'a> { fn storage( &self, account: revm_primitives::Address, - storage_key: reth_primitives::StorageKey, - ) -> reth_errors::ProviderResult> { + storage_key: alloy_primitives::StorageKey, + ) -> reth_errors::ProviderResult> { self.0.storage(account, storage_key) } } diff --git a/crates/rpc/rpc-eth-types/src/cache/mod.rs b/crates/rpc/rpc-eth-types/src/cache/mod.rs index 9a8059494415..a2cc29ecbb60 100644 --- a/crates/rpc/rpc-eth-types/src/cache/mod.rs +++ b/crates/rpc/rpc-eth-types/src/cache/mod.rs @@ -1,5 +1,6 @@ //! Async caching support for eth RPC +use alloy_primitives::B256; use futures::{future::Either, Stream, StreamExt}; use reth_chain_state::CanonStateNotification; use reth_errors::{ProviderError, ProviderResult}; @@ -7,7 +8,7 @@ use reth_evm::{provider::EvmEnvProvider, ConfigureEvm}; use reth_execution_types::Chain; use reth_primitives::{ Block, BlockHashOrNumber, BlockWithSenders, Receipt, SealedBlock, SealedBlockWithSenders, - TransactionSigned, TransactionSignedEcRecovered, B256, + TransactionSigned, TransactionSignedEcRecovered, }; use reth_storage_api::{BlockReader, StateProviderFactory, TransactionVariant}; use reth_tasks::{TaskSpawner, TokioTaskExecutor}; diff --git a/crates/rpc/rpc-eth-types/src/error.rs b/crates/rpc/rpc-eth-types/src/error.rs index fc0dd3362948..1630da0a0676 100644 --- a/crates/rpc/rpc-eth-types/src/error.rs +++ b/crates/rpc/rpc-eth-types/src/error.rs @@ -2,9 +2,10 @@ use std::time::Duration; +use alloy_primitives::{Address, Bytes}; use alloy_sol_types::decode_revert_reason; use reth_errors::RethError; -use reth_primitives::{revm_primitives::InvalidHeader, Address, BlockId, Bytes}; +use reth_primitives::{revm_primitives::InvalidHeader, BlockId}; use reth_rpc_server_types::result::{ block_id_to_str, internal_rpc_err, invalid_params_rpc_err, rpc_err, rpc_error_with_code, }; diff --git a/crates/rpc/rpc-eth-types/src/fee_history.rs b/crates/rpc/rpc-eth-types/src/fee_history.rs index bab993b68fab..23c2348798b5 100644 --- a/crates/rpc/rpc-eth-types/src/fee_history.rs +++ b/crates/rpc/rpc-eth-types/src/fee_history.rs @@ -6,6 +6,7 @@ use std::{ sync::{atomic::Ordering::SeqCst, Arc}, }; +use alloy_primitives::B256; use futures::{ future::{Fuse, FusedFuture}, FutureExt, Stream, StreamExt, @@ -16,7 +17,7 @@ use reth_chainspec::{ChainSpec, ChainSpecProvider}; use reth_primitives::{ basefee::calc_next_block_base_fee, eip4844::{calc_blob_gasprice, calculate_excess_blob_gas}, - Receipt, SealedBlock, TransactionSigned, B256, + Receipt, SealedBlock, TransactionSigned, }; use reth_rpc_types::TxGasAndReward; use reth_storage_api::BlockReaderIdExt; diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 62a43cb4e67d..b92f363d444c 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -3,8 +3,9 @@ use std::fmt::{self, Debug, Formatter}; +use alloy_primitives::{B256, U256}; use derive_more::{Deref, DerefMut, From, Into}; -use reth_primitives::{constants::GWEI_TO_WEI, BlockNumberOrTag, B256, U256}; +use reth_primitives::{constants::GWEI_TO_WEI, BlockNumberOrTag}; use reth_rpc_server_types::constants; use reth_rpc_types::BlockId; use reth_storage_api::BlockReaderIdExt; diff --git a/crates/rpc/rpc-eth-types/src/id_provider.rs b/crates/rpc/rpc-eth-types/src/id_provider.rs index 97375624ca62..1c4efa7707c0 100644 --- a/crates/rpc/rpc-eth-types/src/id_provider.rs +++ b/crates/rpc/rpc-eth-types/src/id_provider.rs @@ -46,7 +46,7 @@ fn to_quantity(val: u128) -> SubscriptionId<'static> { #[cfg(test)] mod tests { use super::*; - use reth_primitives::U128; + use alloy_primitives::U128; #[test] fn test_id_provider_quantity() { diff --git a/crates/rpc/rpc-eth-types/src/logs_utils.rs b/crates/rpc/rpc-eth-types/src/logs_utils.rs index ab93398fa4bc..ae49685aaf2b 100644 --- a/crates/rpc/rpc-eth-types/src/logs_utils.rs +++ b/crates/rpc/rpc-eth-types/src/logs_utils.rs @@ -2,9 +2,10 @@ //! //! Log parsing for building filter. +use alloy_primitives::TxHash; use reth_chainspec::ChainInfo; use reth_errors::ProviderError; -use reth_primitives::{BlockNumHash, Receipt, TxHash}; +use reth_primitives::{BlockNumHash, Receipt}; use reth_rpc_server_types::result::rpc_error_with_code; use reth_rpc_types::{FilterId, FilteredParams, Log}; use reth_storage_api::BlockReader; @@ -167,7 +168,7 @@ pub fn append_matching_block_logs( /// Returns true if the log matches the filter and should be included pub fn log_matches_filter( block: BlockNumHash, - log: &reth_primitives::Log, + log: &alloy_primitives::Log, params: &FilteredParams, ) -> bool { if params.filter.is_some() && diff --git a/crates/rpc/rpc-eth-types/src/pending_block.rs b/crates/rpc/rpc-eth-types/src/pending_block.rs index 8a9503d81e81..949e205dcf88 100644 --- a/crates/rpc/rpc-eth-types/src/pending_block.rs +++ b/crates/rpc/rpc-eth-types/src/pending_block.rs @@ -4,10 +4,9 @@ use std::time::Instant; +use alloy_primitives::B256; use derive_more::Constructor; -use reth_primitives::{ - BlockId, BlockNumberOrTag, Receipt, SealedBlockWithSenders, SealedHeader, B256, -}; +use reth_primitives::{BlockId, BlockNumberOrTag, Receipt, SealedBlockWithSenders, SealedHeader}; use revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg}; /// Configured [`BlockEnv`] and [`CfgEnvWithHandlerCfg`] for a pending block. diff --git a/crates/rpc/rpc-eth-types/src/receipt.rs b/crates/rpc/rpc-eth-types/src/receipt.rs index db0b91fb75d8..63d148d44161 100644 --- a/crates/rpc/rpc-eth-types/src/receipt.rs +++ b/crates/rpc/rpc-eth-types/src/receipt.rs @@ -1,6 +1,7 @@ //! RPC receipt response builder, extends a layer one receipt with layer two data. -use reth_primitives::{Address, Receipt, TransactionMeta, TransactionSigned, TxKind}; +use alloy_primitives::{Address, TxKind}; +use reth_primitives::{Receipt, TransactionMeta, TransactionSigned}; use reth_rpc_types::{ AnyReceiptEnvelope, AnyTransactionReceipt, Log, OtherFields, ReceiptWithBloom, TransactionReceipt, WithOtherFields, diff --git a/crates/rpc/rpc-eth-types/src/revm_utils.rs b/crates/rpc/rpc-eth-types/src/revm_utils.rs index 1a5edfe44d1f..b9b48e2b4a87 100644 --- a/crates/rpc/rpc-eth-types/src/revm_utils.rs +++ b/crates/rpc/rpc-eth-types/src/revm_utils.rs @@ -1,6 +1,6 @@ //! utilities for working with revm -use reth_primitives::{Address, B256, U256}; +use alloy_primitives::{Address, B256, U256}; use reth_rpc_types::{ state::{AccountOverride, StateOverride}, BlockOverrides, diff --git a/crates/rpc/rpc-eth-types/src/transaction.rs b/crates/rpc/rpc-eth-types/src/transaction.rs index 007671ca7b01..c3ca1b503aef 100644 --- a/crates/rpc/rpc-eth-types/src/transaction.rs +++ b/crates/rpc/rpc-eth-types/src/transaction.rs @@ -1,8 +1,10 @@ //! Helper types for `reth_rpc_eth_api::EthApiServer` implementation. //! //! Transaction wrapper that labels transaction with its origin. -use reth_primitives::{TransactionSignedEcRecovered, B256}; -use reth_rpc_types::TransactionInfo; + +use alloy_primitives::B256; +use alloy_rpc_types::TransactionInfo; +use reth_primitives::TransactionSignedEcRecovered; use reth_rpc_types_compat::{ transaction::{from_recovered, from_recovered_with_block_context}, TransactionCompat, diff --git a/crates/rpc/rpc-eth-types/src/utils.rs b/crates/rpc/rpc-eth-types/src/utils.rs index 2c93d52fc6de..4f6e91575d15 100644 --- a/crates/rpc/rpc-eth-types/src/utils.rs +++ b/crates/rpc/rpc-eth-types/src/utils.rs @@ -1,6 +1,7 @@ //! Commonly used code snippets -use reth_primitives::{Bytes, PooledTransactionsElement, PooledTransactionsElementEcRecovered}; +use alloy_primitives::Bytes; +use reth_primitives::{PooledTransactionsElement, PooledTransactionsElementEcRecovered}; use std::future::Future; use super::{EthApiError, EthResult}; diff --git a/crates/rpc/rpc-server-types/Cargo.toml b/crates/rpc/rpc-server-types/Cargo.toml index 628654ebaf98..e908af0af75a 100644 --- a/crates/rpc/rpc-server-types/Cargo.toml +++ b/crates/rpc/rpc-server-types/Cargo.toml @@ -17,7 +17,6 @@ reth-network-api.workspace = true reth-primitives.workspace = true reth-rpc-types.workspace = true - # ethereum alloy-primitives.workspace = true diff --git a/crates/rpc/rpc-server-types/src/result.rs b/crates/rpc/rpc-server-types/src/result.rs index e0397d485ef7..3dc76f0d8f4b 100644 --- a/crates/rpc/rpc-server-types/src/result.rs +++ b/crates/rpc/rpc-server-types/src/result.rs @@ -144,7 +144,7 @@ pub fn rpc_err( code, msg.into(), data.map(|data| { - jsonrpsee_core::to_json_raw_value(&reth_primitives::hex::encode_prefixed(data)) + jsonrpsee_core::to_json_raw_value(&alloy_primitives::hex::encode_prefixed(data)) .expect("serializing String can't fail") }), ) diff --git a/crates/rpc/rpc-testing-util/Cargo.toml b/crates/rpc/rpc-testing-util/Cargo.toml index 19cef0b02de8..59672595d50a 100644 --- a/crates/rpc/rpc-testing-util/Cargo.toml +++ b/crates/rpc/rpc-testing-util/Cargo.toml @@ -17,6 +17,9 @@ reth-primitives.workspace = true reth-rpc-types.workspace = true reth-rpc-api = { workspace = true, features = ["client"] } +# ethereum +alloy-primitives.workspace = true + # async futures.workspace = true diff --git a/crates/rpc/rpc-testing-util/src/debug.rs b/crates/rpc/rpc-testing-util/src/debug.rs index 9bbccaa2a43d..0ec5311fe9f2 100644 --- a/crates/rpc/rpc-testing-util/src/debug.rs +++ b/crates/rpc/rpc-testing-util/src/debug.rs @@ -6,9 +6,10 @@ use std::{ task::{Context, Poll}, }; +use alloy_primitives::{TxHash, B256}; use futures::{Stream, StreamExt}; use jsonrpsee::core::client::Error as RpcError; -use reth_primitives::{BlockId, Receipt, TxHash, B256}; +use reth_primitives::{BlockId, Receipt}; use reth_rpc_api::{clients::DebugApiClient, EthApiClient}; use reth_rpc_types::{ trace::{ diff --git a/crates/rpc/rpc-testing-util/src/trace.rs b/crates/rpc/rpc-testing-util/src/trace.rs index 862ecb432392..5a1843935e44 100644 --- a/crates/rpc/rpc-testing-util/src/trace.rs +++ b/crates/rpc/rpc-testing-util/src/trace.rs @@ -1,8 +1,9 @@ //! Helpers for testing trace calls. +use alloy_primitives::{Bytes, TxHash, B256}; use futures::{Stream, StreamExt}; use jsonrpsee::core::client::Error as RpcError; -use reth_primitives::{BlockId, Bytes, TxHash, B256}; +use reth_primitives::BlockId; use reth_rpc_api::clients::TraceApiClient; use reth_rpc_types::{ trace::{ diff --git a/crates/rpc/rpc-testing-util/tests/it/trace.rs b/crates/rpc/rpc-testing-util/tests/it/trace.rs index 409b2f4a7af0..62e2a67f4a2c 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -1,4 +1,4 @@ -use std::{collections::HashSet, time::Instant}; +//! Integration tests for the trace API. use futures::StreamExt; use jsonrpsee::http_client::HttpClientBuilder; @@ -10,6 +10,7 @@ use reth_rpc_types::{ trace::{filter::TraceFilter, parity::TraceType, tracerequest::TraceCallRequest}, Block, Transaction, }; +use std::{collections::HashSet, time::Instant}; /// This is intended to be run locally against a running node. /// diff --git a/crates/rpc/rpc-types-compat/Cargo.toml b/crates/rpc/rpc-types-compat/Cargo.toml index b6e735c3d6a5..23304c51bdba 100644 --- a/crates/rpc/rpc-types-compat/Cargo.toml +++ b/crates/rpc/rpc-types-compat/Cargo.toml @@ -12,11 +12,13 @@ description = "Compatibility layer for reth-primitives and ethereum RPC types" workspace = true [dependencies] +# reth reth-primitives.workspace = true reth-rpc-types.workspace = true reth-trie-common.workspace = true # ethereum +alloy-primitives.workspace = true alloy-rlp.workspace = true alloy-rpc-types.workspace = true diff --git a/crates/rpc/rpc-types-compat/src/block.rs b/crates/rpc/rpc-types-compat/src/block.rs index d30fccd8bff0..bf500a2090f4 100644 --- a/crates/rpc/rpc-types-compat/src/block.rs +++ b/crates/rpc/rpc-types-compat/src/block.rs @@ -1,8 +1,9 @@ //! Compatibility functions for rpc `Block` type. +use alloy_primitives::{B256, U256}; use alloy_rlp::Encodable; use reth_primitives::{ - Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, B256, U256, + Block as PrimitiveBlock, BlockWithSenders, Header as PrimitiveHeader, Withdrawals, }; use reth_rpc_types::{ Block, BlockError, BlockTransactions, BlockTransactionsKind, Header, TransactionInfo, diff --git a/crates/rpc/rpc-types-compat/src/engine/payload.rs b/crates/rpc/rpc-types-compat/src/engine/payload.rs index c2d263300d26..89ebd52a5d17 100644 --- a/crates/rpc/rpc-types-compat/src/engine/payload.rs +++ b/crates/rpc/rpc-types-compat/src/engine/payload.rs @@ -1,10 +1,11 @@ //! Standalone Conversion Functions for Handling Different Versions of Execution Payloads in //! Ethereum's Engine +use alloy_primitives::{B256, U256}; use reth_primitives::{ constants::{EMPTY_OMMER_ROOT_HASH, MAXIMUM_EXTRA_DATA_SIZE}, proofs::{self}, - Block, Header, Request, SealedBlock, TransactionSigned, UintTryTo, Withdrawals, B256, U256, + Block, Header, Request, SealedBlock, TransactionSigned, UintTryTo, Withdrawals, }; use reth_rpc_types::engine::{ payload::{ExecutionPayloadBodyV1, ExecutionPayloadFieldV2, ExecutionPayloadInputV2}, @@ -447,7 +448,7 @@ mod tests { block_to_payload_v3, try_into_block, try_payload_v3_to_block, try_payload_v4_to_block, validate_block_hash, }; - use reth_primitives::{b256, hex, Bytes, U256}; + use alloy_primitives::{b256, hex, Bytes, U256}; use reth_rpc_types::{ engine::{CancunPayloadFields, ExecutionPayloadV3, ExecutionPayloadV4}, ExecutionPayload, ExecutionPayloadV1, ExecutionPayloadV2, diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index addcfe79a01a..28046457146d 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -1,16 +1,19 @@ //! Compatibility functions for rpc `Transaction` type. -pub use signature::*; -pub use typed::*; - mod signature; mod typed; +pub use signature::*; +pub use typed::*; + use std::fmt; -use alloy_rpc_types::request::{TransactionInput, TransactionRequest}; +use alloy_rpc_types::{ + request::{TransactionInput, TransactionRequest}, + TransactionInfo, +}; use reth_primitives::{TransactionSigned, TransactionSignedEcRecovered, TxType}; -use reth_rpc_types::{Transaction, TransactionInfo, WithOtherFields}; +use reth_rpc_types::{Transaction, WithOtherFields}; /// Create a new rpc transaction result for a mined transaction, using the given block hash, /// number, and tx index fields to populate the corresponding fields in the rpc result. diff --git a/crates/rpc/rpc-types-compat/src/transaction/signature.rs b/crates/rpc/rpc-types-compat/src/transaction/signature.rs index b3fc4609476f..34866677d501 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/signature.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/signature.rs @@ -1,4 +1,5 @@ -use reth_primitives::{Signature as PrimitiveSignature, TxType, U256}; +use alloy_primitives::U256; +use reth_primitives::{Signature as PrimitiveSignature, TxType}; use reth_rpc_types::{Parity, Signature}; /// Creates a new rpc signature from a legacy [primitive diff --git a/crates/rpc/rpc-types/Cargo.toml b/crates/rpc/rpc-types/Cargo.toml index 32362cc3007c..8d3973a56b97 100644 --- a/crates/rpc/rpc-types/Cargo.toml +++ b/crates/rpc/rpc-types/Cargo.toml @@ -14,6 +14,7 @@ workspace = true [dependencies] # ethereum +alloy-eips.workspace = true alloy-primitives = { workspace = true, features = ["rand", "rlp", "serde"] } alloy-rpc-types.workspace = true alloy-rpc-types-admin.workspace = true @@ -32,6 +33,7 @@ op-alloy-rpc-types-engine.workspace = true # misc jsonrpsee-types = { workspace = true, optional = true } +serde.workspace = true [dev-dependencies] # misc diff --git a/crates/rpc/rpc-types/src/lib.rs b/crates/rpc/rpc-types/src/lib.rs index dc0eb3dec5c9..03c681a8b8a4 100644 --- a/crates/rpc/rpc-types/src/lib.rs +++ b/crates/rpc/rpc-types/src/lib.rs @@ -61,6 +61,18 @@ pub use eth::{ }, }; +use alloy_eips::eip4844::{Blob, Bytes48}; +use serde::{Deserialize, Serialize}; + +/// Blob type returned in responses to `engine_getBlobsV1`: +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct BlobAndProofV1 { + /// The blob data. + pub blob: Box, + /// The KZG proof for the blob. + pub proof: Bytes48, +} + /// Optimism specific rpc types. pub mod optimism { pub use op_alloy_rpc_types::*; diff --git a/crates/rpc/rpc/Cargo.toml b/crates/rpc/rpc/Cargo.toml index 20b596681b40..b825fa8c5c1a 100644 --- a/crates/rpc/rpc/Cargo.toml +++ b/crates/rpc/rpc/Cargo.toml @@ -36,7 +36,7 @@ reth-node-api.workspace = true reth-network-types.workspace = true reth-trie.workspace = true -# eth +# ethereum alloy-dyn-abi.workspace = true alloy-rlp.workspace = true alloy-primitives.workspace = true diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index dc3ac8de55d9..4d7378f201d8 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -1,3 +1,4 @@ +use alloy_primitives::{Address, Bytes, B256, U256}; use alloy_rlp::{Decodable, Encodable}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; @@ -6,9 +7,7 @@ use reth_evm::{ system_calls::{pre_block_beacon_root_contract_call, pre_block_blockhashes_contract_call}, ConfigureEvmEnv, }; -use reth_primitives::{ - Address, Block, BlockId, BlockNumberOrTag, Bytes, TransactionSignedEcRecovered, B256, U256, -}; +use reth_primitives::{Block, BlockId, BlockNumberOrTag, TransactionSignedEcRecovered}; use reth_provider::{ BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, HeaderProvider, StateProofProvider, StateProviderFactory, TransactionVariant, @@ -310,7 +309,7 @@ where Ok(inspector) }) .await?; - return Ok(FourByteFrame::from(inspector).into()); + return Ok(FourByteFrame::from(&inspector).into()) } GethDebugBuiltInTracerType::CallTracer => { let call_config = tracer_config @@ -356,7 +355,7 @@ where let frame = inspector .with_transaction_gas_limit(env.tx.gas_limit) .into_geth_builder() - .geth_prestate_traces(&res, prestate_config, db) + .geth_prestate_traces(&res, &prestate_config, db) .map_err(Eth::Error::from_eth_err)?; Ok(frame) }) @@ -706,7 +705,7 @@ where GethDebugBuiltInTracerType::FourByteTracer => { let mut inspector = FourByteInspector::default(); let (res, _) = self.eth_api().inspect(db, env, &mut inspector)?; - return Ok((FourByteFrame::from(inspector).into(), res.state)); + return Ok((FourByteFrame::from(&inspector).into(), res.state)) } GethDebugBuiltInTracerType::CallTracer => { let call_config = tracer_config @@ -739,7 +738,7 @@ where let frame = inspector .with_transaction_gas_limit(env.tx.gas_limit) .into_geth_builder() - .geth_prestate_traces(&res, prestate_config, db) + .geth_prestate_traces(&res, &prestate_config, db) .map_err(Eth::Error::from_eth_err)?; return Ok((frame.into(), res.state)); diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index c5c90167221d..066fd9c1b108 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -1,5 +1,6 @@ +use alloy_primitives::{Address, Bytes, B256, U256, U64}; use jsonrpsee::core::RpcResult as Result; -use reth_primitives::{Address, BlockId, BlockNumberOrTag, Bytes, B256, U256, U64}; +use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; diff --git a/crates/rpc/rpc/src/eth/bundle.rs b/crates/rpc/rpc/src/eth/bundle.rs index 339ce47dedf5..ff060d60504d 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -2,12 +2,12 @@ use std::sync::Arc; +use alloy_primitives::{keccak256, U256}; use jsonrpsee::core::RpcResult; use reth_evm::{ConfigureEvm, ConfigureEvmEnv}; use reth_primitives::{ - keccak256, revm_primitives::db::{DatabaseCommit, DatabaseRef}, - PooledTransactionsElement, U256, + PooledTransactionsElement, }; use reth_revm::database::StateProviderDatabase; use reth_rpc_eth_api::{FromEthApiError, FromEvmError}; diff --git a/crates/rpc/rpc/src/eth/core.rs b/crates/rpc/rpc/src/eth/core.rs index 6b6d512ca3ba..c1896b3cdab0 100644 --- a/crates/rpc/rpc/src/eth/core.rs +++ b/crates/rpc/rpc/src/eth/core.rs @@ -3,10 +3,11 @@ use std::sync::Arc; -use alloy_network::{AnyNetwork, Ethereum, Network}; +use alloy_network::AnyNetwork; +use alloy_primitives::U256; use derive_more::Deref; use reth_node_api::{BuilderProvider, FullNodeComponents}; -use reth_primitives::{BlockNumberOrTag, U256}; +use reth_primitives::BlockNumberOrTag; use reth_provider::{BlockReaderIdExt, CanonStateSubscriptions, ChainSpecProvider}; use reth_rpc_eth_api::{ helpers::{EthSigner, SpawnBlocking}, @@ -126,7 +127,7 @@ where { type Error = EthApiError; // todo: replace with alloy_network::Ethereum - type NetworkTypes = Ethereum; + type NetworkTypes = AnyNetwork; type TransactionCompat = EthTxBuilder; } @@ -360,11 +361,12 @@ impl EthApiInner OtterscanApi where Eth: EthApiTypes< NetworkTypes: Network>, + TransactionCompat: TransactionCompat>, >, { /// Constructs a `BlockDetails` from a block and its receipts. diff --git a/crates/rpc/rpc/src/reth.rs b/crates/rpc/rpc/src/reth.rs index 49cc1f1384bc..3e8e842aeda3 100644 --- a/crates/rpc/rpc/src/reth.rs +++ b/crates/rpc/rpc/src/reth.rs @@ -1,9 +1,10 @@ use std::{collections::HashMap, future::Future, sync::Arc}; +use alloy_primitives::{Address, U256}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_errors::RethResult; -use reth_primitives::{Address, BlockId, U256}; +use reth_primitives::BlockId; use reth_provider::{BlockReaderIdExt, ChangeSetReader, StateProviderFactory}; use reth_rpc_api::RethApiServer; use reth_rpc_eth_types::{EthApiError, EthResult}; diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index 8e7592623445..36f42d3a918b 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -1,5 +1,6 @@ use std::{collections::HashSet, sync::Arc}; +use alloy_primitives::{Bytes, B256, U256}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_chainspec::{ChainSpec, EthereumHardforks}; @@ -7,7 +8,7 @@ use reth_consensus_common::calc::{ base_block_reward, base_block_reward_pre_merge, block_reward, ommer_reward, }; use reth_evm::ConfigureEvmEnv; -use reth_primitives::{BlockId, Bytes, Header, B256, U256}; +use reth_primitives::{BlockId, Header}; use reth_provider::{BlockReader, ChainSpecProvider, EvmEnvProvider, StateProviderFactory}; use reth_revm::database::StateProviderDatabase; use reth_rpc_api::TraceApiServer; diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 4040ae00e700..cfb7667fa966 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -1,8 +1,9 @@ use std::{collections::BTreeMap, marker::PhantomData}; +use alloy_primitives::Address; use async_trait::async_trait; use jsonrpsee::core::RpcResult as Result; -use reth_primitives::{Address, TransactionSignedEcRecovered}; +use reth_primitives::TransactionSignedEcRecovered; use reth_rpc_api::TxPoolApiServer; use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, diff --git a/crates/rpc/rpc/src/web3.rs b/crates/rpc/rpc/src/web3.rs index 787604e25e23..8a890efbe7c0 100644 --- a/crates/rpc/rpc/src/web3.rs +++ b/crates/rpc/rpc/src/web3.rs @@ -1,7 +1,7 @@ +use alloy_primitives::{keccak256, Bytes, B256}; use async_trait::async_trait; use jsonrpsee::core::RpcResult; use reth_network_api::NetworkInfo; -use reth_primitives::{keccak256, Bytes, B256}; use reth_rpc_api::Web3ApiServer; use reth_rpc_server_types::ToRpcResult; diff --git a/crates/stages/api/src/pipeline/builder.rs b/crates/stages/api/src/pipeline/builder.rs index c5c585cfc5b9..8493504939f3 100644 --- a/crates/stages/api/src/pipeline/builder.rs +++ b/crates/stages/api/src/pipeline/builder.rs @@ -72,7 +72,7 @@ where pub fn build>( self, provider_factory: ProviderFactory, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, ) -> Pipeline { let Self { stages, max_block, tip_tx, metrics_tx } = self; Pipeline { diff --git a/crates/stages/api/src/pipeline/mod.rs b/crates/stages/api/src/pipeline/mod.rs index 470adf228cc9..a94112396af5 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -71,7 +71,7 @@ pub struct Pipeline { stages: Vec>, /// The maximum block number to sync to. max_block: Option, - static_file_producer: StaticFileProducer, + static_file_producer: StaticFileProducer>, /// Sender for events the pipeline emits. event_sender: EventSender, /// Keeps track of the progress of the pipeline. diff --git a/crates/static-file/static-file/src/segments/headers.rs b/crates/static-file/static-file/src/segments/headers.rs index 3212c0cd8894..54d5bee65cfd 100644 --- a/crates/static-file/static-file/src/segments/headers.rs +++ b/crates/static-file/static-file/src/segments/headers.rs @@ -1,10 +1,10 @@ use crate::segments::Segment; use alloy_primitives::BlockNumber; use reth_db::tables; -use reth_db_api::{cursor::DbCursorRO, database::Database, transaction::DbTx}; +use reth_db_api::{cursor::DbCursorRO, transaction::DbTx}; use reth_provider::{ providers::{StaticFileProvider, StaticFileWriter}, - DatabaseProviderRO, + DBProvider, }; use reth_static_file_types::StaticFileSegment; use reth_storage_errors::provider::ProviderResult; @@ -14,14 +14,14 @@ use std::ops::RangeInclusive; #[derive(Debug, Default)] pub struct Headers; -impl Segment for Headers { +impl Segment for Headers { fn segment(&self) -> StaticFileSegment { StaticFileSegment::Headers } fn copy_to_static_files( &self, - provider: DatabaseProviderRO, + provider: Provider, static_file_provider: StaticFileProvider, block_range: RangeInclusive, ) -> ProviderResult<()> { diff --git a/crates/static-file/static-file/src/segments/mod.rs b/crates/static-file/static-file/src/segments/mod.rs index 1125b2085d99..3d961c7b1197 100644 --- a/crates/static-file/static-file/src/segments/mod.rs +++ b/crates/static-file/static-file/src/segments/mod.rs @@ -10,14 +10,13 @@ mod receipts; pub use receipts::Receipts; use alloy_primitives::BlockNumber; -use reth_db_api::database::Database; -use reth_provider::{providers::StaticFileProvider, DatabaseProviderRO}; +use reth_provider::providers::StaticFileProvider; use reth_static_file_types::StaticFileSegment; use reth_storage_errors::provider::ProviderResult; use std::ops::RangeInclusive; /// A segment represents moving some portion of the data to static files. -pub trait Segment: Send + Sync { +pub trait Segment: Send + Sync { /// Returns the [`StaticFileSegment`]. fn segment(&self) -> StaticFileSegment; @@ -25,7 +24,7 @@ pub trait Segment: Send + Sync { /// the management of and writing to files. fn copy_to_static_files( &self, - provider: DatabaseProviderRO, + provider: Provider, static_file_provider: StaticFileProvider, block_range: RangeInclusive, ) -> ProviderResult<()>; diff --git a/crates/static-file/static-file/src/segments/receipts.rs b/crates/static-file/static-file/src/segments/receipts.rs index b63d083a0645..4e2185a598a8 100644 --- a/crates/static-file/static-file/src/segments/receipts.rs +++ b/crates/static-file/static-file/src/segments/receipts.rs @@ -1,10 +1,10 @@ use crate::segments::Segment; use alloy_primitives::BlockNumber; use reth_db::tables; -use reth_db_api::{cursor::DbCursorRO, database::Database, transaction::DbTx}; +use reth_db_api::{cursor::DbCursorRO, transaction::DbTx}; use reth_provider::{ providers::{StaticFileProvider, StaticFileWriter}, - BlockReader, DatabaseProviderRO, + BlockReader, DBProvider, }; use reth_static_file_types::StaticFileSegment; use reth_storage_errors::provider::{ProviderError, ProviderResult}; @@ -14,14 +14,14 @@ use std::ops::RangeInclusive; #[derive(Debug, Default)] pub struct Receipts; -impl Segment for Receipts { +impl Segment for Receipts { fn segment(&self) -> StaticFileSegment { StaticFileSegment::Receipts } fn copy_to_static_files( &self, - provider: DatabaseProviderRO, + provider: Provider, static_file_provider: StaticFileProvider, block_range: RangeInclusive, ) -> ProviderResult<()> { diff --git a/crates/static-file/static-file/src/segments/transactions.rs b/crates/static-file/static-file/src/segments/transactions.rs index ac690def4b40..52e0ca8b575f 100644 --- a/crates/static-file/static-file/src/segments/transactions.rs +++ b/crates/static-file/static-file/src/segments/transactions.rs @@ -1,10 +1,10 @@ use crate::segments::Segment; use alloy_primitives::BlockNumber; use reth_db::tables; -use reth_db_api::{cursor::DbCursorRO, database::Database, transaction::DbTx}; +use reth_db_api::{cursor::DbCursorRO, transaction::DbTx}; use reth_provider::{ providers::{StaticFileProvider, StaticFileWriter}, - BlockReader, DatabaseProviderRO, + BlockReader, DBProvider, }; use reth_static_file_types::StaticFileSegment; use reth_storage_errors::provider::{ProviderError, ProviderResult}; @@ -14,7 +14,7 @@ use std::ops::RangeInclusive; #[derive(Debug, Default)] pub struct Transactions; -impl Segment for Transactions { +impl Segment for Transactions { fn segment(&self) -> StaticFileSegment { StaticFileSegment::Transactions } @@ -23,7 +23,7 @@ impl Segment for Transactions { /// [`StaticFileSegment::Transactions`] for the provided block range. fn copy_to_static_files( &self, - provider: DatabaseProviderRO, + provider: Provider, static_file_provider: StaticFileProvider, block_range: RangeInclusive, ) -> ProviderResult<()> { diff --git a/crates/static-file/static-file/src/static_file_producer.rs b/crates/static-file/static-file/src/static_file_producer.rs index fd2c48bbff81..eca59e1e74d5 100644 --- a/crates/static-file/static-file/src/static_file_producer.rs +++ b/crates/static-file/static-file/src/static_file_producer.rs @@ -4,11 +4,9 @@ use crate::{segments, segments::Segment, StaticFileProducerEvent}; use alloy_primitives::BlockNumber; use parking_lot::Mutex; use rayon::prelude::*; -use reth_chainspec::ChainSpec; -use reth_node_types::NodeTypesWithDB; use reth_provider::{ - providers::StaticFileWriter, ProviderFactory, StageCheckpointReader as _, - StaticFileProviderFactory, + providers::StaticFileWriter, BlockReader, DBProvider, DatabaseProviderFactory, + StageCheckpointReader, StaticFileProviderFactory, }; use reth_prune_types::PruneModes; use reth_stages_types::StageId; @@ -26,28 +24,29 @@ use tracing::{debug, trace}; pub type StaticFileProducerResult = ProviderResult; /// The [`StaticFileProducer`] instance itself with the result of [`StaticFileProducerInner::run`] -pub type StaticFileProducerWithResult = (StaticFileProducer, StaticFileProducerResult); +pub type StaticFileProducerWithResult = + (StaticFileProducer, StaticFileProducerResult); /// Static File producer. It's a wrapper around [`StaticFileProducer`] that allows to share it /// between threads. #[derive(Debug)] -pub struct StaticFileProducer(Arc>>); +pub struct StaticFileProducer(Arc>>); -impl StaticFileProducer { +impl StaticFileProducer { /// Creates a new [`StaticFileProducer`]. - pub fn new(provider_factory: ProviderFactory, prune_modes: PruneModes) -> Self { - Self(Arc::new(Mutex::new(StaticFileProducerInner::new(provider_factory, prune_modes)))) + pub fn new(provider: Provider, prune_modes: PruneModes) -> Self { + Self(Arc::new(Mutex::new(StaticFileProducerInner::new(provider, prune_modes)))) } } -impl Clone for StaticFileProducer { +impl Clone for StaticFileProducer { fn clone(&self) -> Self { Self(self.0.clone()) } } -impl Deref for StaticFileProducer { - type Target = Arc>>; +impl Deref for StaticFileProducer { + type Target = Arc>>; fn deref(&self) -> &Self::Target { &self.0 @@ -57,9 +56,9 @@ impl Deref for StaticFileProducer { /// Static File producer routine. See [`StaticFileProducerInner::run`] for more detailed /// description. #[derive(Debug)] -pub struct StaticFileProducerInner { +pub struct StaticFileProducerInner { /// Provider factory - provider_factory: ProviderFactory, + provider: Provider, /// Pruning configuration for every part of the data that can be pruned. Set by user, and /// needed in [`StaticFileProducerInner`] to prevent attempting to move prunable data to static /// files. See [`StaticFileProducerInner::get_static_file_targets`]. @@ -101,13 +100,17 @@ impl StaticFileTargets { } } -impl StaticFileProducerInner { - fn new(provider_factory: ProviderFactory, prune_modes: PruneModes) -> Self { - Self { provider_factory, prune_modes, event_sender: Default::default() } +impl StaticFileProducerInner { + fn new(provider: Provider, prune_modes: PruneModes) -> Self { + Self { provider, prune_modes, event_sender: Default::default() } } } -impl> StaticFileProducerInner { +impl StaticFileProducerInner +where + Provider: StaticFileProviderFactory + + DatabaseProviderFactory, +{ /// Listen for events on the `static_file_producer`. pub fn events(&self) -> EventStream { self.event_sender.new_listener() @@ -117,8 +120,8 @@ impl> StaticFileProducerInner { /// /// For each [Some] target in [`StaticFileTargets`], initializes a corresponding [Segment] and /// runs it with the provided block range using [`reth_provider::providers::StaticFileProvider`] - /// and a read-only database transaction from [`ProviderFactory`]. All segments are run in - /// parallel. + /// and a read-only database transaction from [`DatabaseProviderFactory`]. All segments are run + /// in parallel. /// /// NOTE: it doesn't delete the data from database, and the actual deleting (aka pruning) logic /// lives in the `prune` crate. @@ -129,7 +132,7 @@ impl> StaticFileProducerInner { } debug_assert!(targets.is_contiguous_to_highest_static_files( - self.provider_factory.static_file_provider().get_highest_static_files() + self.provider.static_file_provider().get_highest_static_files() )); self.event_sender.notify(StaticFileProducerEvent::Started { targets: targets.clone() }); @@ -137,7 +140,8 @@ impl> StaticFileProducerInner { debug!(target: "static_file", ?targets, "StaticFileProducer started"); let start = Instant::now(); - let mut segments = Vec::<(Box>, RangeInclusive)>::new(); + let mut segments = + Vec::<(Box>, RangeInclusive)>::new(); if let Some(block_range) = targets.transactions.clone() { segments.push((Box::new(segments::Transactions), block_range)); @@ -155,8 +159,9 @@ impl> StaticFileProducerInner { // Create a new database transaction on every segment to prevent long-lived read-only // transactions - let provider = self.provider_factory.provider()?.disable_long_read_transaction_safety(); - segment.copy_to_static_files(provider, self.provider_factory.static_file_provider(), block_range.clone())?; + let mut provider = self.provider.database_provider_ro()?; + provider.disable_long_read_transaction_safety(); + segment.copy_to_static_files(provider, self.provider.static_file_provider(), block_range.clone())?; let elapsed = start.elapsed(); // TODO(alexey): track in metrics debug!(target: "static_file", segment = %segment.segment(), ?block_range, ?elapsed, "Finished StaticFileProducer segment"); @@ -164,9 +169,9 @@ impl> StaticFileProducerInner { Ok(()) })?; - self.provider_factory.static_file_provider().commit()?; + self.provider.static_file_provider().commit()?; for (segment, block_range) in segments { - self.provider_factory + self.provider .static_file_provider() .update_index(segment.segment(), Some(*block_range.end()))?; } @@ -185,7 +190,7 @@ impl> StaticFileProducerInner { /// /// Returns highest block numbers for all static file segments. pub fn copy_to_static_files(&self) -> ProviderResult { - let provider = self.provider_factory.provider()?; + let provider = self.provider.database_provider_ro()?; let stages_checkpoints = [StageId::Headers, StageId::Execution, StageId::Bodies] .into_iter() .map(|stage| provider.get_stage_checkpoint(stage).map(|c| c.map(|c| c.block_number))) @@ -209,8 +214,7 @@ impl> StaticFileProducerInner { &self, finalized_block_numbers: HighestStaticFiles, ) -> ProviderResult { - let highest_static_files = - self.provider_factory.static_file_provider().get_highest_static_files(); + let highest_static_files = self.provider.static_file_provider().get_highest_static_files(); let targets = StaticFileTargets { headers: finalized_block_numbers.headers.and_then(|finalized_block_number| { diff --git a/crates/storage/codecs/src/alloy/transaction/eip7702.rs b/crates/storage/codecs/src/alloy/transaction/eip7702.rs index 69f65d5227a5..ecb7d66a00c5 100644 --- a/crates/storage/codecs/src/alloy/transaction/eip7702.rs +++ b/crates/storage/codecs/src/alloy/transaction/eip7702.rs @@ -1,7 +1,7 @@ use crate::Compact; use alloy_consensus::transaction::TxEip7702 as AlloyTxEip7702; use alloy_eips::{eip2930::AccessList, eip7702::SignedAuthorization}; -use alloy_primitives::{Bytes, ChainId, TxKind, U256}; +use alloy_primitives::{Address, Bytes, ChainId, U256}; use reth_codecs_derive::add_arbitrary_tests; use serde::{Deserialize, Serialize}; @@ -25,7 +25,7 @@ pub(crate) struct TxEip7702 { gas_limit: u64, max_fee_per_gas: u128, max_priority_fee_per_gas: u128, - to: TxKind, + to: Address, value: U256, access_list: AccessList, authorization_list: Vec, diff --git a/crates/storage/db-api/Cargo.toml b/crates/storage/db-api/Cargo.toml index 7cab50fdf64f..5bdad1500f5f 100644 --- a/crates/storage/db-api/Cargo.toml +++ b/crates/storage/db-api/Cargo.toml @@ -47,21 +47,10 @@ rand.workspace = true test-fuzz.workspace = true -pprof = { workspace = true, features = [ - "flamegraph", - "frame-pointer", - "criterion", -] } -criterion.workspace = true -iai-callgrind.workspace = true - arbitrary = { workspace = true, features = ["derive"] } proptest.workspace = true proptest-arbitrary-interop.workspace = true - -assert_matches.workspace = true - [features] test-utils = ["arbitrary"] arbitrary = [ diff --git a/crates/storage/db-api/src/models/blocks.rs b/crates/storage/db-api/src/models/blocks.rs index 052254be784b..0da35da6b5f4 100644 --- a/crates/storage/db-api/src/models/blocks.rs +++ b/crates/storage/db-api/src/models/blocks.rs @@ -1,7 +1,7 @@ //! Block related models and types. use reth_codecs::{add_arbitrary_tests, Compact}; -use reth_primitives::{Header, Withdrawals, B256}; +use reth_primitives::{Header, B256}; use serde::{Deserialize, Serialize}; /// The storage representation of a block's ommers. @@ -15,15 +15,6 @@ pub struct StoredBlockOmmers { pub ommers: Vec

, } -/// The storage representation of block withdrawals. -#[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize, Compact)] -#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))] -#[add_arbitrary_tests(compact)] -pub struct StoredBlockWithdrawals { - /// The block withdrawals. - pub withdrawals: Withdrawals, -} - /// Hash of the block header. pub type HeaderHash = B256; diff --git a/crates/storage/db-api/src/models/mod.rs b/crates/storage/db-api/src/models/mod.rs index 07f69402ef5c..5061876fb9ff 100644 --- a/crates/storage/db-api/src/models/mod.rs +++ b/crates/storage/db-api/src/models/mod.rs @@ -13,15 +13,15 @@ use serde::{Deserialize, Serialize}; pub mod accounts; pub mod blocks; -pub mod client_version; pub mod integer_list; pub mod sharded_key; pub mod storage_sharded_key; pub use accounts::*; pub use blocks::*; -pub use client_version::ClientVersion; -pub use reth_db_models::{AccountBeforeTx, StoredBlockBodyIndices}; +pub use reth_db_models::{ + AccountBeforeTx, ClientVersion, StoredBlockBodyIndices, StoredBlockWithdrawals, +}; pub use sharded_key::ShardedKey; /// Macro that implements [`Encode`] and [`Decode`] for uint types. diff --git a/crates/storage/db-models/src/blocks.rs b/crates/storage/db-models/src/blocks.rs index c993e58dad6d..72ff433f83de 100644 --- a/crates/storage/db-models/src/blocks.rs +++ b/crates/storage/db-models/src/blocks.rs @@ -1,7 +1,7 @@ use std::ops::Range; use reth_codecs::{add_arbitrary_tests, Compact}; -use reth_primitives::TxNumber; +use reth_primitives::{TxNumber, Withdrawals}; use serde::{Deserialize, Serialize}; /// Total number of transactions. @@ -66,6 +66,15 @@ impl StoredBlockBodyIndices { } } +/// The storage representation of block withdrawals. +#[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize, Compact)] +#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))] +#[add_arbitrary_tests(compact)] +pub struct StoredBlockWithdrawals { + /// The block withdrawals. + pub withdrawals: Withdrawals, +} + #[cfg(test)] mod tests { use crate::StoredBlockBodyIndices; diff --git a/crates/storage/db-api/src/models/client_version.rs b/crates/storage/db-models/src/client_version.rs similarity index 100% rename from crates/storage/db-api/src/models/client_version.rs rename to crates/storage/db-models/src/client_version.rs diff --git a/crates/storage/db-models/src/lib.rs b/crates/storage/db-models/src/lib.rs index 55a210269caa..b8595362afc3 100644 --- a/crates/storage/db-models/src/lib.rs +++ b/crates/storage/db-models/src/lib.rs @@ -6,4 +6,8 @@ pub use accounts::AccountBeforeTx; /// Blocks pub mod blocks; -pub use blocks::StoredBlockBodyIndices; +pub use blocks::{StoredBlockBodyIndices, StoredBlockWithdrawals}; + +/// Client Version +pub mod client_version; +pub use client_version::ClientVersion; diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index aff1da56d68a..e53fbfbe3ac3 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -13,7 +13,7 @@ use reth_db_api::{ cursor::{DbCursorRO, DbCursorRW}, database::Database, database_metrics::{DatabaseMetadata, DatabaseMetadataValue, DatabaseMetrics}, - models::client_version::ClientVersion, + models::ClientVersion, transaction::{DbTx, DbTxMut}, }; use reth_libmdbx::{ diff --git a/crates/storage/db/src/lib.rs b/crates/storage/db/src/lib.rs index c16f2b73c4e9..a9f073d7b546 100644 --- a/crates/storage/db/src/lib.rs +++ b/crates/storage/db/src/lib.rs @@ -36,6 +36,7 @@ pub use utils::is_database_empty; #[cfg(feature = "mdbx")] pub use mdbx::{create_db, init_db, open_db, open_db_read_only, DatabaseEnv, DatabaseEnvKind}; +pub use models::ClientVersion; pub use reth_db_api::*; /// Collection of database test utilities diff --git a/crates/storage/db/src/tables/mod.rs b/crates/storage/db/src/tables/mod.rs index cff4b8009044..090c22e97aad 100644 --- a/crates/storage/db/src/tables/mod.rs +++ b/crates/storage/db/src/tables/mod.rs @@ -23,9 +23,9 @@ use reth_db_api::{ models::{ accounts::BlockNumberAddress, blocks::{HeaderHash, StoredBlockOmmers}, - client_version::ClientVersion, storage_sharded_key::StorageShardedKey, - AccountBeforeTx, CompactU256, ShardedKey, StoredBlockBodyIndices, StoredBlockWithdrawals, + AccountBeforeTx, ClientVersion, CompactU256, ShardedKey, StoredBlockBodyIndices, + StoredBlockWithdrawals, }, table::{Decode, DupSort, Encode, Table}, }; diff --git a/crates/storage/provider/src/providers/blockchain_provider.rs b/crates/storage/provider/src/providers/blockchain_provider.rs index 91a4b306b470..adf73bd70ad9 100644 --- a/crates/storage/provider/src/providers/blockchain_provider.rs +++ b/crates/storage/provider/src/providers/blockchain_provider.rs @@ -261,8 +261,11 @@ impl BlockchainProvider2 { } } -impl DatabaseProviderFactory for BlockchainProvider2 { - fn database_provider_ro(&self) -> ProviderResult> { +impl DatabaseProviderFactory for BlockchainProvider2 { + type DB = N::DB; + type Provider = DatabaseProviderRO; + + fn database_provider_ro(&self) -> ProviderResult { self.database.provider() } } diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index fe9b65941107..c5d98a238448 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -1,8 +1,7 @@ -use crate::{BlockNumReader, DatabaseProviderFactory, DatabaseProviderRO, HeaderProvider}; -use reth_db_api::database::Database; +use crate::{BlockNumReader, DatabaseProviderFactory, HeaderProvider}; use reth_primitives::{GotExpected, B256}; +use reth_storage_api::BlockReader; use reth_storage_errors::provider::ProviderResult; -use std::marker::PhantomData; pub use reth_storage_errors::provider::ConsistentViewError; @@ -22,24 +21,22 @@ pub use reth_storage_errors::provider::ConsistentViewError; /// appropriately. /// 2) be sure that the state does not change. #[derive(Clone, Debug)] -pub struct ConsistentDbView { - database: PhantomData, - provider: Provider, +pub struct ConsistentDbView { + factory: Factory, tip: Option, } -impl ConsistentDbView +impl ConsistentDbView where - DB: Database, - Provider: DatabaseProviderFactory, + Factory: DatabaseProviderFactory, { /// Creates new consistent database view. - pub const fn new(provider: Provider, tip: Option) -> Self { - Self { database: PhantomData, provider, tip } + pub const fn new(factory: Factory, tip: Option) -> Self { + Self { factory, tip } } /// Creates new consistent database view with latest tip. - pub fn new_with_latest_tip(provider: Provider) -> ProviderResult { + pub fn new_with_latest_tip(provider: Factory) -> ProviderResult { let provider_ro = provider.database_provider_ro()?; let last_num = provider_ro.last_block_number()?; let tip = provider_ro.sealed_header(last_num)?.map(|h| h.hash()); @@ -47,9 +44,9 @@ where } /// Creates new read-only provider and performs consistency checks on the current tip. - pub fn provider_ro(&self) -> ProviderResult> { + pub fn provider_ro(&self) -> ProviderResult { // Create a new provider. - let provider_ro = self.provider.database_provider_ro()?; + let provider_ro = self.factory.database_provider_ro()?; // Check that the latest stored header number matches the number // that consistent view was initialized with. diff --git a/crates/storage/provider/src/providers/database/mod.rs b/crates/storage/provider/src/providers/database/mod.rs index 249d1f116734..2c79134ca908 100644 --- a/crates/storage/provider/src/providers/database/mod.rs +++ b/crates/storage/provider/src/providers/database/mod.rs @@ -182,8 +182,11 @@ impl ProviderFactory { } } -impl DatabaseProviderFactory for ProviderFactory { - fn database_provider_ro(&self) -> ProviderResult> { +impl DatabaseProviderFactory for ProviderFactory { + type DB = N::DB; + type Provider = DatabaseProviderRO; + + fn database_provider_ro(&self) -> ProviderResult { self.provider() } } diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index 643b2359e234..666edb148d20 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -7,7 +7,7 @@ use crate::{ }, writer::UnifiedStorageWriter, AccountReader, BlockExecutionReader, BlockExecutionWriter, BlockHashReader, BlockNumReader, - BlockReader, BlockWriter, BundleStateInit, EvmEnvProvider, FinalizedBlockReader, + BlockReader, BlockWriter, BundleStateInit, DBProvider, EvmEnvProvider, FinalizedBlockReader, FinalizedBlockWriter, HashingWriter, HeaderProvider, HeaderSyncGap, HeaderSyncGapProvider, HistoricalStateProvider, HistoryWriter, LatestStateProvider, OriginalValuesKnown, ProviderError, PruneCheckpointReader, PruneCheckpointWriter, RequestsProvider, RevertsInit, @@ -3700,6 +3700,18 @@ impl FinalizedBlockWriter for DatabaseProvider { } } +impl DBProvider for DatabaseProvider { + type Tx = TX; + + fn tx_ref(&self) -> &Self::Tx { + &self.tx + } + + fn tx_mut(&mut self) -> &mut Self::Tx { + &mut self.tx + } +} + /// Helper method to recover senders for any blocks in the db which do not have senders. This /// compares the length of the input senders [`Vec`], with the length of given transactions [`Vec`], /// and will add to the input senders vec if there are more transactions. diff --git a/crates/storage/provider/src/providers/mod.rs b/crates/storage/provider/src/providers/mod.rs index 246bd426f507..652d275f3a47 100644 --- a/crates/storage/provider/src/providers/mod.rs +++ b/crates/storage/provider/src/providers/mod.rs @@ -169,8 +169,11 @@ where } } -impl DatabaseProviderFactory for BlockchainProvider { - fn database_provider_ro(&self) -> ProviderResult> { +impl DatabaseProviderFactory for BlockchainProvider { + type DB = N::DB; + type Provider = DatabaseProviderRO; + + fn database_provider_ro(&self) -> ProviderResult { self.database.provider() } } diff --git a/crates/storage/provider/src/traits/database_provider.rs b/crates/storage/provider/src/traits/database_provider.rs deleted file mode 100644 index fab60fe2e704..000000000000 --- a/crates/storage/provider/src/traits/database_provider.rs +++ /dev/null @@ -1,9 +0,0 @@ -use crate::DatabaseProviderRO; -use reth_db_api::database::Database; -use reth_storage_errors::provider::ProviderResult; - -/// Database provider factory. -pub trait DatabaseProviderFactory { - /// Create new read-only database provider. - fn database_provider_ro(&self) -> ProviderResult>; -} diff --git a/crates/storage/provider/src/traits/full.rs b/crates/storage/provider/src/traits/full.rs index 52346257a223..1022184d6883 100644 --- a/crates/storage/provider/src/traits/full.rs +++ b/crates/storage/provider/src/traits/full.rs @@ -11,7 +11,7 @@ use reth_node_types::NodeTypesWithDB; /// Helper trait to unify all provider traits for simplicity. pub trait FullProvider: - DatabaseProviderFactory + DatabaseProviderFactory + StaticFileProviderFactory + BlockReaderIdExt + AccountReader @@ -29,7 +29,7 @@ pub trait FullProvider: } impl FullProvider for T where - T: DatabaseProviderFactory + T: DatabaseProviderFactory + StaticFileProviderFactory + BlockReaderIdExt + AccountReader diff --git a/crates/storage/provider/src/traits/mod.rs b/crates/storage/provider/src/traits/mod.rs index 3e692b7ed905..8bae4f67ae85 100644 --- a/crates/storage/provider/src/traits/mod.rs +++ b/crates/storage/provider/src/traits/mod.rs @@ -29,9 +29,6 @@ pub use trie::{StorageTrieWriter, TrieWriter}; mod history; pub use history::HistoryWriter; -mod database_provider; -pub use database_provider::DatabaseProviderFactory; - mod static_file_provider; pub use static_file_provider::StaticFileProviderFactory; diff --git a/crates/storage/storage-api/Cargo.toml b/crates/storage/storage-api/Cargo.toml index e469cd6dcfc5..ce043213c9c1 100644 --- a/crates/storage/storage-api/Cargo.toml +++ b/crates/storage/storage-api/Cargo.toml @@ -15,6 +15,7 @@ workspace = true # reth reth-chainspec.workspace = true reth-db-models.workspace = true +reth-db-api.workspace = true reth-execution-types.workspace = true reth-primitives.workspace = true reth-prune-types.workspace = true diff --git a/crates/storage/storage-api/src/database_provider.rs b/crates/storage/storage-api/src/database_provider.rs new file mode 100644 index 000000000000..fd15411d7c20 --- /dev/null +++ b/crates/storage/storage-api/src/database_provider.rs @@ -0,0 +1,36 @@ +use reth_db_api::{database::Database, transaction::DbTx}; +use reth_storage_errors::provider::ProviderResult; + +/// Database provider. +pub trait DBProvider: Send + Sync { + /// Underlying database transaction held by the provider. + type Tx: DbTx; + + /// Returns a reference to the underlying transaction. + fn tx_ref(&self) -> &Self::Tx; + + /// Returns a mutable reference to the underlying transaction. + fn tx_mut(&mut self) -> &mut Self::Tx; + + /// Disables long-lived read transaction safety guarantees for leaks prevention and + /// observability improvements. + /// + /// CAUTION: In most of the cases, you want the safety guarantees for long read transactions + /// enabled. Use this only if you're sure that no write transaction is open in parallel, meaning + /// that Reth as a node is offline and not progressing. + fn disable_long_read_transaction_safety(&mut self) { + self.tx_mut().disable_long_read_transaction_safety(); + } +} + +/// Database provider factory. +pub trait DatabaseProviderFactory: Send + Sync { + /// Database this factory produces providers for. + type DB: Database; + + /// Provider type returned by the factory. + type Provider: DBProvider::TX>; + + /// Create new read-only database provider. + fn database_provider_ro(&self) -> ProviderResult; +} diff --git a/crates/storage/storage-api/src/lib.rs b/crates/storage/storage-api/src/lib.rs index 440c27d37dcc..3f93bbbde2f1 100644 --- a/crates/storage/storage-api/src/lib.rs +++ b/crates/storage/storage-api/src/lib.rs @@ -52,4 +52,7 @@ pub use trie::*; mod withdrawals; pub use withdrawals::*; +mod database_provider; +pub use database_provider::*; + pub mod noop; diff --git a/crates/transaction-pool/Cargo.toml b/crates/transaction-pool/Cargo.toml index 95ebea623364..1daa6b4b2149 100644 --- a/crates/transaction-pool/Cargo.toml +++ b/crates/transaction-pool/Cargo.toml @@ -18,6 +18,7 @@ reth-chainspec.workspace = true reth-eth-wire-types.workspace = true reth-primitives = { workspace = true, features = ["c-kzg", "secp256k1"] } reth-execution-types.workspace = true +reth-rpc-types.workspace = true reth-fs-util.workspace = true reth-storage-api.workspace = true reth-tasks.workspace = true diff --git a/crates/transaction-pool/src/blobstore/disk.rs b/crates/transaction-pool/src/blobstore/disk.rs index c43d4565080a..94b200590f55 100644 --- a/crates/transaction-pool/src/blobstore/disk.rs +++ b/crates/transaction-pool/src/blobstore/disk.rs @@ -5,6 +5,7 @@ use alloy_primitives::{TxHash, B256}; use alloy_rlp::{Decodable, Encodable}; use parking_lot::{Mutex, RwLock}; use reth_primitives::BlobTransactionSidecar; +use reth_rpc_types::BlobAndProofV1; use schnellru::{ByLength, LruMap}; use std::{collections::HashSet, fmt, fs, io, path::PathBuf, sync::Arc}; use tracing::{debug, trace}; @@ -128,6 +129,31 @@ impl BlobStore for DiskFileBlobStore { self.inner.get_exact(txs) } + fn get_by_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError> { + let mut result = vec![None; versioned_hashes.len()]; + for (_tx_hash, blob_sidecar) in self.inner.blob_cache.lock().iter() { + for (i, blob_versioned_hash) in blob_sidecar.versioned_hashes().enumerate() { + for (j, target_versioned_hash) in versioned_hashes.iter().enumerate() { + if blob_versioned_hash == *target_versioned_hash { + result[j].get_or_insert_with(|| BlobAndProofV1 { + blob: Box::new(blob_sidecar.blobs[i]), + proof: blob_sidecar.proofs[i], + }); + } + } + } + + // Return early if all blobs are found. + if result.iter().all(|blob| blob.is_some()) { + break; + } + } + Ok(result) + } + fn data_size_hint(&self) -> Option { Some(self.inner.size_tracker.data_size()) } diff --git a/crates/transaction-pool/src/blobstore/mem.rs b/crates/transaction-pool/src/blobstore/mem.rs index 0d8cbda35970..ebde21fb4dab 100644 --- a/crates/transaction-pool/src/blobstore/mem.rs +++ b/crates/transaction-pool/src/blobstore/mem.rs @@ -3,6 +3,7 @@ use crate::blobstore::{ }; use alloy_primitives::B256; use parking_lot::RwLock; +use reth_rpc_types::BlobAndProofV1; use std::{collections::HashMap, sync::Arc}; /// An in-memory blob store. @@ -113,6 +114,31 @@ impl BlobStore for InMemoryBlobStore { Ok(items) } + fn get_by_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError> { + let mut result = vec![None; versioned_hashes.len()]; + for (_tx_hash, blob_sidecar) in self.inner.store.read().iter() { + for (i, blob_versioned_hash) in blob_sidecar.versioned_hashes().enumerate() { + for (j, target_versioned_hash) in versioned_hashes.iter().enumerate() { + if blob_versioned_hash == *target_versioned_hash { + result[j].get_or_insert_with(|| BlobAndProofV1 { + blob: Box::new(blob_sidecar.blobs[i]), + proof: blob_sidecar.proofs[i], + }); + } + } + } + + // Return early if all blobs are found. + if result.iter().all(|blob| blob.is_some()) { + break; + } + } + Ok(result) + } + fn data_size_hint(&self) -> Option { Some(self.inner.size_tracker.data_size()) } diff --git a/crates/transaction-pool/src/blobstore/mod.rs b/crates/transaction-pool/src/blobstore/mod.rs index ea973003bfa1..3f38b41f4cb0 100644 --- a/crates/transaction-pool/src/blobstore/mod.rs +++ b/crates/transaction-pool/src/blobstore/mod.rs @@ -5,6 +5,7 @@ pub use disk::{DiskFileBlobStore, DiskFileBlobStoreConfig, OpenDiskFileBlobStore pub use mem::InMemoryBlobStore; pub use noop::NoopBlobStore; use reth_primitives::BlobTransactionSidecar; +use reth_rpc_types::BlobAndProofV1; use std::{ fmt, sync::atomic::{AtomicUsize, Ordering}, @@ -65,6 +66,12 @@ pub trait BlobStore: fmt::Debug + Send + Sync + 'static { /// Returns an error if any of the blobs are not found in the blob store. fn get_exact(&self, txs: Vec) -> Result, BlobStoreError>; + /// Return the [`BlobTransactionSidecar`]s for a list of blob versioned hashes. + fn get_by_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError>; + /// Data size of all transactions in the blob store. fn data_size_hint(&self) -> Option; diff --git a/crates/transaction-pool/src/blobstore/noop.rs b/crates/transaction-pool/src/blobstore/noop.rs index 975e97c111b4..e8d2931730ca 100644 --- a/crates/transaction-pool/src/blobstore/noop.rs +++ b/crates/transaction-pool/src/blobstore/noop.rs @@ -1,5 +1,6 @@ use crate::blobstore::{BlobStore, BlobStoreCleanupStat, BlobStoreError, BlobTransactionSidecar}; use alloy_primitives::B256; +use reth_rpc_types::BlobAndProofV1; /// A blobstore implementation that does nothing #[derive(Clone, Copy, Debug, PartialOrd, PartialEq, Eq, Default)] @@ -49,6 +50,13 @@ impl BlobStore for NoopBlobStore { Err(BlobStoreError::MissingSidecar(txs[0])) } + fn get_by_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError> { + Ok(vec![None; versioned_hashes.len()]) + } + fn data_size_hint(&self) -> Option { Some(0) } diff --git a/crates/transaction-pool/src/lib.rs b/crates/transaction-pool/src/lib.rs index 75b1324ba5c4..bd734e18b31a 100644 --- a/crates/transaction-pool/src/lib.rs +++ b/crates/transaction-pool/src/lib.rs @@ -151,11 +151,12 @@ #![cfg_attr(not(test), warn(unused_crate_dependencies))] use crate::{identifier::TransactionId, pool::PoolInner}; -use alloy_primitives::{Address, TxHash, U256}; +use alloy_primitives::{Address, TxHash, B256, U256}; use aquamarine as _; use reth_eth_wire_types::HandleMempoolData; use reth_execution_types::ChangedAccount; use reth_primitives::{BlobTransactionSidecar, PooledTransactionsElement}; +use reth_rpc_types::BlobAndProofV1; use reth_storage_api::StateProviderFactory; use std::{collections::HashSet, sync::Arc}; use tokio::sync::mpsc::Receiver; @@ -526,6 +527,13 @@ where self.pool.blob_store().get_exact(tx_hashes) } + fn get_blobs_for_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError> { + self.pool.blob_store().get_by_versioned_hashes(versioned_hashes) + } + /// Returns all pending transactions filtered by [`TransactionOrigin`] fn get_pending_transactions_by_origin( &self, diff --git a/crates/transaction-pool/src/noop.rs b/crates/transaction-pool/src/noop.rs index 7a6939d31885..e4055bd5225b 100644 --- a/crates/transaction-pool/src/noop.rs +++ b/crates/transaction-pool/src/noop.rs @@ -16,9 +16,10 @@ use crate::{ PooledTransactionsElement, PropagatedTransactions, TransactionEvents, TransactionOrigin, TransactionPool, TransactionValidationOutcome, TransactionValidator, ValidPoolTransaction, }; -use alloy_primitives::{Address, TxHash, U256}; +use alloy_primitives::{Address, TxHash, B256, U256}; use reth_eth_wire_types::HandleMempoolData; use reth_primitives::BlobTransactionSidecar; +use reth_rpc_types::BlobAndProofV1; use std::{collections::HashSet, marker::PhantomData, sync::Arc}; use tokio::sync::{mpsc, mpsc::Receiver}; @@ -219,6 +220,13 @@ impl TransactionPool for NoopTransactionPool { vec![] } + fn get_pending_transactions_by_origin( + &self, + _origin: TransactionOrigin, + ) -> Vec>> { + vec![] + } + fn unique_senders(&self) -> HashSet
{ Default::default() } @@ -244,11 +252,11 @@ impl TransactionPool for NoopTransactionPool { Err(BlobStoreError::MissingSidecar(tx_hashes[0])) } - fn get_pending_transactions_by_origin( + fn get_blobs_for_versioned_hashes( &self, - _origin: TransactionOrigin, - ) -> Vec>> { - vec![] + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError> { + Ok(vec![None; versioned_hashes.len()]) } } diff --git a/crates/transaction-pool/src/traits.rs b/crates/transaction-pool/src/traits.rs index cd96c30c0f17..c0e5fae154a0 100644 --- a/crates/transaction-pool/src/traits.rs +++ b/crates/transaction-pool/src/traits.rs @@ -17,6 +17,7 @@ use reth_primitives::{ PooledTransactionsElementEcRecovered, SealedBlock, Transaction, TransactionSignedEcRecovered, EIP1559_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID, }; +use reth_rpc_types::BlobAndProofV1; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use std::{ @@ -414,6 +415,12 @@ pub trait TransactionPool: Send + Sync + Clone { &self, tx_hashes: Vec, ) -> Result, BlobStoreError>; + + /// Return the [`BlobTransactionSidecar`]s for a list of blob versioned hashes. + fn get_blobs_for_versioned_hashes( + &self, + versioned_hashes: &[B256], + ) -> Result>, BlobStoreError>; } /// Extension for [TransactionPool] trait that allows to set the current block info. diff --git a/crates/trie/common/Cargo.toml b/crates/trie/common/Cargo.toml index 1d11d335d1ca..0bd28140f447 100644 --- a/crates/trie/common/Cargo.toml +++ b/crates/trie/common/Cargo.toml @@ -37,8 +37,6 @@ arbitrary = { workspace = true, features = ["derive"], optional = true } arbitrary = { workspace = true, features = ["derive"] } proptest.workspace = true proptest-arbitrary-interop.workspace = true -test-fuzz.workspace = true -toml.workspace = true hash-db = "=0.15.2" plain_hasher = "0.2" diff --git a/crates/trie/common/src/account.rs b/crates/trie/common/src/account.rs index 269202601182..0808837063cf 100644 --- a/crates/trie/common/src/account.rs +++ b/crates/trie/common/src/account.rs @@ -71,3 +71,114 @@ impl From<(AccountInfo, B256)> for TrieAccount { } } } + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::Bytes; + use std::collections::BTreeMap; + + #[test] + fn test_from_genesis_account_with_default_values() { + let genesis_account = GenesisAccount::default(); + + // Convert the GenesisAccount to a TrieAccount + let trie_account: TrieAccount = genesis_account.into(); + + // Check the fields are properly set. + assert_eq!(trie_account.nonce, 0); + assert_eq!(trie_account.balance, U256::default()); + assert_eq!(trie_account.storage_root(), EMPTY_ROOT_HASH); + assert_eq!(trie_account.code_hash, KECCAK_EMPTY); + + // Check that the default Account converts to the same TrieAccount + assert_eq!(Into::::into((Account::default(), EMPTY_ROOT_HASH)), trie_account); + + // Check that the default AccountInfo converts to the same TrieAccount + assert_eq!( + Into::::into((AccountInfo::default(), EMPTY_ROOT_HASH)), + trie_account + ); + } + + #[test] + fn test_from_genesis_account_with_values() { + // Create a GenesisAccount with specific values + let mut storage = BTreeMap::new(); + storage.insert(B256::from([0x01; 32]), B256::from([0x02; 32])); + + let genesis_account = GenesisAccount { + nonce: Some(10), + balance: U256::from(1000), + code: Some(Bytes::from(vec![0x60, 0x61])), + storage: Some(storage), + private_key: None, + }; + + // Convert the GenesisAccount to a TrieAccount + let trie_account: TrieAccount = genesis_account.into(); + + let expected_storage_root = storage_root_unhashed(BTreeMap::from([( + B256::from([0x01; 32]), + U256::from_be_bytes(*B256::from([0x02; 32])), + )])); + + // Check that the fields are properly set. + assert_eq!(trie_account.nonce, 10); + assert_eq!(trie_account.balance, U256::from(1000)); + assert_eq!(trie_account.storage_root(), expected_storage_root); + assert_eq!(trie_account.code_hash, keccak256([0x60, 0x61])); + + // Check that the Account converts to the same TrieAccount + assert_eq!( + Into::::into(( + Account { + nonce: 10, + balance: U256::from(1000), + bytecode_hash: Some(keccak256([0x60, 0x61])) + }, + expected_storage_root + )), + trie_account + ); + + // Check that the AccountInfo converts to the same TrieAccount + assert_eq!( + Into::::into(( + AccountInfo { + nonce: 10, + balance: U256::from(1000), + code_hash: keccak256([0x60, 0x61]), + ..Default::default() + }, + expected_storage_root + )), + trie_account + ); + } + + #[test] + fn test_from_genesis_account_with_zeroed_storage_values() { + // Create a GenesisAccount with storage containing zero values + let storage = BTreeMap::from([(B256::from([0x01; 32]), B256::from([0x00; 32]))]); + + let genesis_account = GenesisAccount { + nonce: Some(3), + balance: U256::from(300), + code: None, + storage: Some(storage), + private_key: None, + }; + + // Convert the GenesisAccount to a TrieAccount + let trie_account: TrieAccount = genesis_account.into(); + + // Check the fields are properly set. + assert_eq!(trie_account.nonce, 3); + assert_eq!(trie_account.balance, U256::from(300)); + // Zero values in storage should result in EMPTY_ROOT_HASH + assert_eq!(trie_account.storage_root(), EMPTY_ROOT_HASH); + // No code provided, so code hash should be KECCAK_EMPTY + assert_eq!(trie_account.code_hash, KECCAK_EMPTY); + } +} diff --git a/crates/trie/db/Cargo.toml b/crates/trie/db/Cargo.toml index f42046656da5..d05d350110d3 100644 --- a/crates/trie/db/Cargo.toml +++ b/crates/trie/db/Cargo.toml @@ -71,7 +71,6 @@ tokio = { workspace = true, default-features = false, features = [ tokio-stream.workspace = true serde_json.workspace = true similar-asserts.workspace = true -criterion.workspace = true [features] metrics = ["reth-metrics", "reth-trie/metrics", "dep:metrics"] diff --git a/crates/trie/parallel/src/async_root.rs b/crates/trie/parallel/src/async_root.rs index ef206064ffe7..179c7dabadc2 100644 --- a/crates/trie/parallel/src/async_root.rs +++ b/crates/trie/parallel/src/async_root.rs @@ -3,10 +3,11 @@ use crate::metrics::ParallelStateRootMetrics; use crate::{stats::ParallelTrieTracker, storage_root_targets::StorageRootTargets}; use alloy_rlp::{BufMut, Encodable}; use itertools::Itertools; -use reth_db_api::database::Database; use reth_execution_errors::StorageRootError; use reth_primitives::B256; -use reth_provider::{providers::ConsistentDbView, DatabaseProviderFactory, ProviderError}; +use reth_provider::{ + providers::ConsistentDbView, BlockReader, DBProvider, DatabaseProviderFactory, ProviderError, +}; use reth_tasks::pool::BlockingTaskPool; use reth_trie::{ hashed_cursor::{HashedCursorFactory, HashedPostStateCursorFactory}, @@ -35,9 +36,9 @@ use tracing::*; /// /// For sync usage, take a look at `ParallelStateRoot`. #[derive(Debug)] -pub struct AsyncStateRoot { +pub struct AsyncStateRoot { /// Consistent view of the database. - view: ConsistentDbView, + view: ConsistentDbView, /// Blocking task pool. blocking_pool: BlockingTaskPool, /// Changed hashed state. @@ -47,10 +48,10 @@ pub struct AsyncStateRoot { metrics: ParallelStateRootMetrics, } -impl AsyncStateRoot { +impl AsyncStateRoot { /// Create new async state root calculator. pub fn new( - view: ConsistentDbView, + view: ConsistentDbView, blocking_pool: BlockingTaskPool, hashed_state: HashedPostState, ) -> Self { @@ -64,10 +65,9 @@ impl AsyncStateRoot { } } -impl AsyncStateRoot +impl AsyncStateRoot where - DB: Database + Clone + 'static, - Provider: DatabaseProviderFactory + Clone + Send + Sync + 'static, + Factory: DatabaseProviderFactory + Clone + Send + Sync + 'static, { /// Calculate incremental state root asynchronously. pub async fn incremental_root(self) -> Result { diff --git a/crates/trie/parallel/src/parallel_root.rs b/crates/trie/parallel/src/parallel_root.rs index 015d41677d21..b41d9319cbdc 100644 --- a/crates/trie/parallel/src/parallel_root.rs +++ b/crates/trie/parallel/src/parallel_root.rs @@ -3,10 +3,11 @@ use crate::metrics::ParallelStateRootMetrics; use crate::{stats::ParallelTrieTracker, storage_root_targets::StorageRootTargets}; use alloy_rlp::{BufMut, Encodable}; use rayon::prelude::*; -use reth_db_api::database::Database; use reth_execution_errors::StorageRootError; use reth_primitives::B256; -use reth_provider::{providers::ConsistentDbView, DatabaseProviderFactory, ProviderError}; +use reth_provider::{ + providers::ConsistentDbView, BlockReader, DBProvider, DatabaseProviderFactory, ProviderError, +}; use reth_trie::{ hashed_cursor::{HashedCursorFactory, HashedPostStateCursorFactory}, node_iter::{TrieElement, TrieNodeIter}, @@ -33,9 +34,9 @@ use tracing::*; /// /// If possible, use more optimized `AsyncStateRoot` instead. #[derive(Debug)] -pub struct ParallelStateRoot { +pub struct ParallelStateRoot { /// Consistent view of the database. - view: ConsistentDbView, + view: ConsistentDbView, /// Changed hashed state. hashed_state: HashedPostState, /// Parallel state root metrics. @@ -43,9 +44,9 @@ pub struct ParallelStateRoot { metrics: ParallelStateRootMetrics, } -impl ParallelStateRoot { +impl ParallelStateRoot { /// Create new parallel state root calculator. - pub fn new(view: ConsistentDbView, hashed_state: HashedPostState) -> Self { + pub fn new(view: ConsistentDbView, hashed_state: HashedPostState) -> Self { Self { view, hashed_state, @@ -55,10 +56,9 @@ impl ParallelStateRoot { } } -impl ParallelStateRoot +impl ParallelStateRoot where - DB: Database, - Provider: DatabaseProviderFactory + Send + Sync, + Factory: DatabaseProviderFactory + Send + Sync, { /// Calculate incremental state root in parallel. pub fn incremental_root(self) -> Result { diff --git a/crates/trie/trie/Cargo.toml b/crates/trie/trie/Cargo.toml index eef6cfe5461b..12cf9ac1cb7b 100644 --- a/crates/trie/trie/Cargo.toml +++ b/crates/trie/trie/Cargo.toml @@ -48,7 +48,6 @@ serde = { workspace = true, optional = true } # reth reth-chainspec.workspace = true reth-primitives = { workspace = true, features = ["test-utils", "arbitrary"] } -reth-provider = { workspace = true, features = ["test-utils"] } reth-trie-common = { workspace = true, features = ["test-utils", "arbitrary"] } # trie @@ -62,9 +61,7 @@ tokio = { workspace = true, default-features = false, features = [ "rt", "macros", ] } -tokio-stream.workspace = true serde_json.workspace = true -similar-asserts.workspace = true criterion.workspace = true [features] diff --git a/etc/grafana/dashboards/overview.json b/etc/grafana/dashboards/overview.json index d03feca6a29b..380f6d3dd3ff 100644 --- a/etc/grafana/dashboards/overview.json +++ b/etc/grafana/dashboards/overview.json @@ -147,7 +147,79 @@ "orientation": "auto", "percentChangeColorMode": "standard", "reduceOptions": { - "calcs": ["lastNotNull"], + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "showPercentChange": false, + "text": { + "valueSize": 20 + }, + "textMode": "name", + "wideLayout": true + }, + "pluginVersion": "11.1.0", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "editorMode": "builder", + "exemplar": false, + "expr": "reth_chain_spec{instance=~\"$instance\"}", + "instant": true, + "legendFormat": "{{name}}", + "range": false, + "refId": "A" + } + ], + "title": "Chain", + "transparent": true, + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "${DS_PROMETHEUS}" + }, + "fieldConfig": { + "defaults": { + "color": { + "mode": "thresholds" + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 3, + "w": 2, + "x": 3, + "y": 1 + }, + "id": 240, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "percentChangeColorMode": "standard", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], "fields": "", "values": false }, @@ -203,8 +275,8 @@ }, "gridPos": { "h": 3, - "w": 6, - "x": 3, + "w": 5, + "x": 5, "y": 1 }, "id": 192, @@ -271,8 +343,8 @@ }, "gridPos": { "h": 3, - "w": 3, - "x": 9, + "w": 2, + "x": 10, "y": 1 }, "id": 193, diff --git a/examples/rpc-db/Cargo.toml b/examples/rpc-db/Cargo.toml index 007a488b8174..262b3df8babc 100644 --- a/examples/rpc-db/Cargo.toml +++ b/examples/rpc-db/Cargo.toml @@ -11,7 +11,6 @@ jsonrpsee.workspace = true reth.workspace = true reth-chainspec.workspace = true reth-db.workspace = true -reth-db-api.workspace = true reth-node-ethereum.workspace = true reth-provider = { workspace = true, features = ["test-utils"] } tokio = { workspace = true, features = ["full"] } diff --git a/examples/rpc-db/src/main.rs b/examples/rpc-db/src/main.rs index ccf81acdd05a..7c978cf085d5 100644 --- a/examples/rpc-db/src/main.rs +++ b/examples/rpc-db/src/main.rs @@ -24,8 +24,7 @@ use reth::{ utils::open_db_read_only, }; use reth_chainspec::ChainSpecBuilder; -use reth_db::{mdbx::DatabaseArguments, DatabaseEnv}; -use reth_db_api::models::ClientVersion; +use reth_db::{mdbx::DatabaseArguments, ClientVersion, DatabaseEnv}; // Bringing up the RPC use reth::rpc::builder::{ From 30bd98ec327846d00303eb43beb304e7019d24dd Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 14:24:46 +0200 Subject: [PATCH 56/80] Fix merge conflicts --- crates/rpc/rpc/src/eth/helpers/block.rs | 12 ++++--- crates/rpc/rpc/src/otterscan.rs | 43 ++++++++++++++++++------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 29f361e992d7..af239b0f1b8c 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -4,16 +4,19 @@ use reth_primitives::TransactionMeta; use reth_provider::{BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_api::{ helpers::{EthBlocks, LoadBlock, LoadPendingBlock, LoadReceipt, SpawnBlocking}, - FromEthApiError, RpcReceipt, + RpcReceipt, }; -use reth_rpc_eth_types::{EthStateCache, ReceiptBuilder}; -use reth_rpc_types::BlockId; +use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; +use reth_rpc_types::{AnyTransactionReceipt, BlockId}; use crate::EthApi; impl EthBlocks for EthApi where - Self: LoadBlock, + Self: LoadBlock< + Error = EthApiError, + NetworkTypes: alloy_network::Network, + >, Provider: HeaderProvider, { #[inline] @@ -54,7 +57,6 @@ where ReceiptBuilder::new(&tx, meta, receipt, &receipts) .map(|builder| builder.build()) - .map_err(Self::Error::from_eth_err) }) .collect::, Self::Error>>(); return receipts.map(Some) diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index e5696d3a2aa9..1775e3eef8f4 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -18,14 +18,14 @@ use reth_rpc_types::{ }, parity::{Action, CreateAction, CreateOutput, TraceOutput}, }, - BlockTransactions, Header, Transaction, WithOtherFields, + BlockTransactions, Header, Transaction, TransactionReceipt, WithOtherFields, }; use reth_rpc_types_compat::TransactionCompat; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, transfer::{TransferInspector, TransferKind}, }; -use revm_primitives::ExecutionResult; +use revm_primitives::{ExecutionResult, SignedAuthorization}; const API_LEVEL: u64 = 8; @@ -247,17 +247,38 @@ where let timestamp = Some(block.header.timestamp); let receipts = receipts .drain(page_start..page_end) - .map(|receipt| { - let receipt = receipt.map_inner(|receipt| OtsReceipt { - status: receipt - .status() - .as_eip658() - .expect("ETH API returned pre-EIP-658 status"), - cumulative_gas_used: receipt.cumulative_gas_used() as u64, + .zip(transactions.iter().map(|tx| tx.inner.transaction_type.unwrap_or(0))) + .map(|(receipt, tx_ty)| { + let status = receipt.status(); + let cumulative_gas_used = receipt.cumulative_gas_used() as u64; + let r#type = receipt.transaction_type(); + + let inner = OtsReceipt { + status: receipt.status(), + cumulative_gas_used, logs: None, logs_bloom: None, - r#type: receipt.r#type, - }); + r#type: tx_ty, + }; + + let receipt = TransactionReceipt { + inner, + transaction_hash: receipt.transaction_hash(), + transaction_index: receipt.transaction_index(), + block_hash: receipt.block_hash(), + block_number: receipt.block_number(), + gas_used: receipt.gas_used(), + effective_gas_price: receipt.effective_gas_price(), + blob_gas_used: receipt.blob_gas_used(), + blob_gas_price: receipt.blob_gas_price(), + from: receipt.from(), + to: receipt.to(), + contract_address: receipt.contract_address(), + state_root: receipt.state_root(), + authorization_list: receipt + .authorization_list() + .map(<[SignedAuthorization]>::to_vec), + }; OtsTransactionReceipt { receipt, timestamp } }) From 79de341e1f53ce3bda08093d4e8c7d07af04b850 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 14:59:56 +0200 Subject: [PATCH 57/80] Revert formatting changes --- crates/rpc/ipc/src/server/connection.rs | 12 +++++------ crates/rpc/ipc/src/server/ipc.rs | 4 ++-- crates/rpc/ipc/src/stream_codec.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/block.rs | 6 +++--- crates/rpc/rpc-eth-api/src/helpers/call.rs | 20 +++++++++---------- crates/rpc/rpc-eth-api/src/helpers/error.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 8 ++++---- .../rpc-eth-api/src/helpers/pending_block.rs | 16 +++++++-------- crates/rpc/rpc-eth-api/src/helpers/state.rs | 4 ++-- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 2 +- .../rpc-eth-api/src/helpers/transaction.rs | 14 ++++++------- crates/rpc/rpc-eth-types/src/cache/mod.rs | 8 ++++---- crates/rpc/rpc-eth-types/src/fee_history.rs | 6 +++--- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 10 +++++----- crates/rpc/rpc-eth-types/src/id_provider.rs | 2 +- crates/rpc/rpc-eth-types/src/logs_utils.rs | 2 +- crates/rpc/rpc-eth-types/src/revm_utils.rs | 6 +++--- crates/rpc/rpc-eth-types/src/utils.rs | 2 +- crates/rpc/rpc-server-types/src/module.rs | 2 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 4 ++-- .../rpc-types-compat/src/engine/payload.rs | 6 +++--- crates/rpc/rpc/src/debug.rs | 20 +++++++++---------- crates/rpc/rpc/src/eth/bundle.rs | 6 +++--- crates/rpc/rpc/src/eth/filter.rs | 14 ++++++------- crates/rpc/rpc/src/eth/pubsub.rs | 4 ++-- crates/rpc/rpc/src/trace.rs | 8 ++++---- 26 files changed, 95 insertions(+), 95 deletions(-) diff --git a/crates/rpc/ipc/src/server/connection.rs b/crates/rpc/ipc/src/server/connection.rs index f1f4290d5fa2..5e7497cb9e59 100644 --- a/crates/rpc/ipc/src/server/connection.rs +++ b/crates/rpc/ipc/src/server/connection.rs @@ -102,7 +102,7 @@ where if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } // write all responses to the sink @@ -110,10 +110,10 @@ where if let Some(item) = this.items.pop_front() { if let Err(err) = this.conn.as_mut().start_send(item) { tracing::warn!("IPC response failed: {:?}", err); - return Poll::Ready(()); + return Poll::Ready(()) } } else { - break; + break } } @@ -147,7 +147,7 @@ where Err(err) => err.into().to_string(), }; this.items.push_back(item); - continue 'outer; + continue 'outer } Poll::Pending => { this.pending_calls.push(call); @@ -157,14 +157,14 @@ where Some(Err(err)) => { // this can happen if the client closes the connection tracing::debug!("IPC request failed: {:?}", err); - return Poll::Ready(()); + return Poll::Ready(()) } None => return Poll::Ready(()), }, Poll::Pending => { if drained || this.pending_calls.is_empty() { // at this point all things are pending - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/rpc/ipc/src/server/ipc.rs b/crates/rpc/ipc/src/server/ipc.rs index 9bdd55c44984..33ed8d2d5531 100644 --- a/crates/rpc/ipc/src/server/ipc.rs +++ b/crates/rpc/ipc/src/server/ipc.rs @@ -70,7 +70,7 @@ where while let Some(response) = pending_calls.next().await { if let Err(too_large) = batch_response.append(&response) { - return Some(too_large.to_result()); + return Some(too_large.to_result()) } } @@ -151,7 +151,7 @@ where return Some(batch_response_error( Id::Null, reject_too_big_request(max_request_body_size as u32), - )); + )) } // Single request or notification diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index 1f2a0e791cc1..e6e035f1d512 100644 --- a/crates/rpc/ipc/src/stream_codec.rs +++ b/crates/rpc/ipc/src/stream_codec.rs @@ -117,7 +117,7 @@ impl tokio_util::codec::Decoder for StreamCodec { return match String::from_utf8(bts.into()) { Ok(val) => Ok(Some(val)), Err(_) => Ok(None), - }; + } } } Ok(None) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index ae76b79f47f1..4e0c08e24654 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -126,12 +126,12 @@ pub trait EthBlocks: LoadBlock { .pending_block_and_receipts() .map_err(Self::Error::from_eth_err)? { - return Ok(Some((block, Arc::new(receipts)))); + return Ok(Some((block, Arc::new(receipts)))) } // If no pending block from provider, build the pending block locally. if let Some((block, receipts)) = self.local_pending_block().await? { - return Ok(Some((block.block, Arc::new(receipts)))); + return Ok(Some((block.block, Arc::new(receipts)))) } } @@ -142,7 +142,7 @@ pub trait EthBlocks: LoadBlock { return LoadReceipt::cache(self) .get_block_and_receipts(block_hash) .await - .map_err(Self::Error::from_eth_err); + .map_err(Self::Error::from_eth_err) } Ok(None) diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 81780a62d138..d32f0104b33f 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -94,7 +94,7 @@ pub trait EthCall: Call + LoadPendingBlock { if transactions.is_empty() { return Err( EthApiError::InvalidParams(String::from("transactions are empty.")).into() - ); + ) } let StateContext { transaction_index, block_number } = @@ -267,11 +267,11 @@ pub trait EthCall: Call + LoadPendingBlock { ExecutionResult::Halt { reason, gas_used } => { let error = Some(RpcInvalidTransactionError::halt(reason, env.tx.gas_limit).to_string()); - return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }); + return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }) } ExecutionResult::Revert { output, gas_used } => { let error = Some(RevertError::new(output).to_string()); - return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }); + return Ok(AccessListResult { access_list, gas_used: U256::from(gas_used), error }) } ExecutionResult::Success { .. } => {} }; @@ -495,7 +495,7 @@ pub trait Call: LoadState + SpawnBlocking { for tx in transactions { if tx.hash() == target_tx_hash { // reached the target transaction - break; + break } let sender = tx.signer(); @@ -596,7 +596,7 @@ pub trait Call: LoadState + SpawnBlocking { env.tx.gas_limit = MIN_TRANSACTION_GAS; if let Ok((res, _)) = self.transact(&mut db, env) { if res.result.is_success() { - return Ok(U256::from(MIN_TRANSACTION_GAS)); + return Ok(U256::from(MIN_TRANSACTION_GAS)) } } } @@ -643,7 +643,7 @@ pub trait Call: LoadState + SpawnBlocking { ExecutionResult::Halt { reason, gas_used } => { // here we don't check for invalid opcode because already executed with highest gas // limit - return Err(RpcInvalidTransactionError::halt(reason, gas_used).into_eth_err()); + return Err(RpcInvalidTransactionError::halt(reason, gas_used).into_eth_err()) } ExecutionResult::Revert { output, .. } => { // if price or limit was included in the request then we can execute the request @@ -653,7 +653,7 @@ pub trait Call: LoadState + SpawnBlocking { } else { // the transaction did revert Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into_eth_err()) - }; + } } }; @@ -711,7 +711,7 @@ pub trait Call: LoadState + SpawnBlocking { if (highest_gas_limit - lowest_gas_limit) as f64 / (highest_gas_limit as f64) < ESTIMATE_GAS_ERROR_RATIO { - break; + break }; env.tx.gas_limit = mid_gas_limit; @@ -783,7 +783,7 @@ pub trait Call: LoadState + SpawnBlocking { // These cases should be unreachable because we know the transaction // succeeds, but if they occur, treat them as an // error. - return Err(RpcInvalidTransactionError::EvmHalt(err).into_eth_err()); + return Err(RpcInvalidTransactionError::EvmHalt(err).into_eth_err()) } } } @@ -837,7 +837,7 @@ pub trait Call: LoadState + SpawnBlocking { ) -> Result { // Ensure that if versioned hashes are set, they're not empty if request.blob_versioned_hashes.as_ref().map_or(false, |hashes| hashes.is_empty()) { - return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_eth_err()); + return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into_eth_err()) } let TransactionRequest { diff --git a/crates/rpc/rpc-eth-api/src/helpers/error.rs b/crates/rpc/rpc-eth-api/src/helpers/error.rs index 5417e24b34a2..041a019052bd 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/error.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/error.rs @@ -54,7 +54,7 @@ pub trait AsEthApiError { /// [`RpcInvalidTransactionError::GasTooHigh`](reth_rpc_eth_types::RpcInvalidTransactionError::GasTooHigh). fn is_gas_too_high(&self) -> bool { if let Some(err) = self.as_err() { - return err.is_gas_too_high(); + return err.is_gas_too_high() } false diff --git a/crates/rpc/rpc-eth-api/src/helpers/fee.rs b/crates/rpc/rpc-eth-api/src/helpers/fee.rs index ac0c7cd9d495..43f202a7d009 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/fee.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/fee.rs @@ -56,7 +56,7 @@ pub trait EthFees: LoadFee { ) -> impl Future> + Send { async move { if block_count == 0 { - return Ok(FeeHistory::default()); + return Ok(FeeHistory::default()) } // See https://github.com/ethereum/go-ethereum/blob/2754b197c935ee63101cbbca2752338246384fec/eth/gasprice/feehistory.go#L218C8-L225 @@ -100,7 +100,7 @@ pub trait EthFees: LoadFee { // Note: The types used ensure that the percentiles are never < 0 if let Some(percentiles) = &reward_percentiles { if percentiles.windows(2).any(|w| w[0] > w[1] || w[0] > 100.) { - return Err(EthApiError::InvalidRewardPercentiles.into()); + return Err(EthApiError::InvalidRewardPercentiles.into()) } } @@ -125,7 +125,7 @@ pub trait EthFees: LoadFee { if let Some(fee_entries) = fee_entries { if fee_entries.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange.into()); + return Err(EthApiError::InvalidBlockRange.into()) } for entry in &fee_entries { @@ -157,7 +157,7 @@ pub trait EthFees: LoadFee { .sealed_headers_range(start_block..=end_block) .map_err(Self::Error::from_eth_err)?; if headers.len() != block_count as usize { - return Err(EthApiError::InvalidBlockRange.into()); + return Err(EthApiError::InvalidBlockRange.into()) } for header in &headers { diff --git a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs index f46dc62387ba..3c811acebae3 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -140,7 +140,7 @@ pub trait LoadPendingBlock: EthApiTypes { .receipts_by_block(block.hash().into()) .map_err(Self::Error::from_eth_err)? { - return Ok(Some((block, receipts))); + return Ok(Some((block, receipts))) } } } @@ -157,7 +157,7 @@ pub trait LoadPendingBlock: EthApiTypes { pending.origin.header().hash() == pending_block.block.parent_hash && now <= pending_block.expires_at { - return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))); + return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))) } } @@ -172,7 +172,7 @@ pub trait LoadPendingBlock: EthApiTypes { Ok(block) => block, Err(err) => { debug!(target: "rpc", "Failed to build pending block: {:?}", err); - return Ok(None); + return Ok(None) } }; @@ -297,7 +297,7 @@ pub trait LoadPendingBlock: EthApiTypes { // which also removes all dependent transaction from the iterator before we can // continue best_txs.mark_invalid(&pool_tx); - continue; + continue } if pool_tx.origin.is_private() { @@ -305,7 +305,7 @@ pub trait LoadPendingBlock: EthApiTypes { // them as invalid here which removes all dependent transactions from the iterator // before we can continue best_txs.mark_invalid(&pool_tx); - continue; + continue } // convert tx to a signed transaction @@ -321,7 +321,7 @@ pub trait LoadPendingBlock: EthApiTypes { // the iterator. This is similar to the gas limit condition // for regular transactions above. best_txs.mark_invalid(&pool_tx); - continue; + continue } } @@ -346,11 +346,11 @@ pub trait LoadPendingBlock: EthApiTypes { // descendants best_txs.mark_invalid(&pool_tx); } - continue; + continue } err => { // this is an error that we should treat as fatal for this attempt - return Err(Self::Error::from_evm_err(err)); + return Err(Self::Error::from_evm_err(err)) } } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index 65bf128c754a..7ecd9e979762 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -102,7 +102,7 @@ pub trait EthState: LoadState + SpawnBlocking { .ok_or(EthApiError::HeaderNotFound(block_id))?; let max_window = self.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { - return Err(EthApiError::ExceedsMaxProofWindow.into()); + return Err(EthApiError::ExceedsMaxProofWindow.into()) } Ok(async move { @@ -277,7 +277,7 @@ pub trait LoadState: EthApiTypes { let tx_count = highest_nonce.checked_add(1).ok_or(Self::Error::from( EthApiError::InvalidTransaction(RpcInvalidTransactionError::NonceMaxValue), ))?; - return Ok(U256::from(tx_count)); + return Ok(U256::from(tx_count)) } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index b90af06cc3c3..896d28bab2a0 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -292,7 +292,7 @@ pub trait Trace: LoadState { if block.body.is_empty() { // nothing to trace - return Ok(Some(Vec::new())); + return Ok(Some(Vec::new())) } // replay all transactions of the block diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index dbe1150c9475..f9a4ace3f025 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -106,7 +106,7 @@ pub trait EthTransactions: LoadTransaction { if let Some(tx) = self.pool().get_pooled_transaction_element(hash).map(|tx| tx.envelope_encoded()) { - return Ok(Some(tx)); + return Ok(Some(tx)) } self.spawn_blocking_io(move |ref this| { @@ -214,7 +214,7 @@ pub trait EthTransactions: LoadTransaction { return Ok(Some(from_recovered_with_block_context::( tx, tx_info, - ))); + ))) } } @@ -251,7 +251,7 @@ pub trait EthTransactions: LoadTransaction { // Check if the sender is a contract if self.get_code(sender, None).await?.len() > 0 { - return Ok(None); + return Ok(None) } let highest = self.transaction_count(sender, None).await?.saturating_to::(); @@ -259,11 +259,11 @@ pub trait EthTransactions: LoadTransaction { // If the nonce is higher or equal to the highest nonce, the transaction is pending or // not exists. if nonce >= highest { - return Ok(None); + return Ok(None) } let Ok(high) = LoadBlock::provider(self).best_block_number() else { - return Err(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()).into()); + return Err(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()).into()) }; // Perform a binary search over the block range to find the block in which the sender's @@ -320,7 +320,7 @@ pub trait EthTransactions: LoadTransaction { async move { if let Some(block) = self.block_with_senders(block_id).await? { if let Some(tx) = block.transactions().nth(index) { - return Ok(Some(tx.envelope_encoded())); + return Ok(Some(tx.envelope_encoded())) } } @@ -367,7 +367,7 @@ pub trait EthTransactions: LoadTransaction { }; if self.find_signer(&from).is_err() { - return Err(SignError::NoAccount.into_eth_err()); + return Err(SignError::NoAccount.into_eth_err()) } // set nonce if not already set before diff --git a/crates/rpc/rpc-eth-types/src/cache/mod.rs b/crates/rpc/rpc-eth-types/src/cache/mod.rs index a2cc29ecbb60..b224d36c2399 100644 --- a/crates/rpc/rpc-eth-types/src/cache/mod.rs +++ b/crates/rpc/rpc-eth-types/src/cache/mod.rs @@ -420,7 +420,7 @@ where CacheAction::GetBlockWithSenders { block_hash, response_tx } => { if let Some(block) = this.full_block_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(Some(block))); - continue; + continue } // block is not in the cache, request it if this is the first consumer @@ -448,7 +448,7 @@ where // check if block is cached if let Some(block) = this.full_block_cache.get(&block_hash) { let _ = response_tx.send(Ok(Some(block.body.clone()))); - continue; + continue } // block is not in the cache, request it if this is the first consumer @@ -476,7 +476,7 @@ where // check if block is cached if let Some(receipts) = this.receipts_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(Some(receipts))); - continue; + continue } // block is not in the cache, request it if this is the first consumer @@ -500,7 +500,7 @@ where // check if env data is cached if let Some(env) = this.evm_env_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(env)); - continue; + continue } // env data is not in the cache, request it if this is the first diff --git a/crates/rpc/rpc-eth-types/src/fee_history.rs b/crates/rpc/rpc-eth-types/src/fee_history.rs index 23c2348798b5..17e1fea8aa97 100644 --- a/crates/rpc/rpc-eth-types/src/fee_history.rs +++ b/crates/rpc/rpc-eth-types/src/fee_history.rs @@ -104,7 +104,7 @@ impl FeeHistoryCache { if entries.len() == 0 { self.inner.upper_bound.store(0, SeqCst); self.inner.lower_bound.store(0, SeqCst); - return; + return } let upper_bound = *entries.last_entry().expect("Contains at least one entry").key(); @@ -151,7 +151,7 @@ impl FeeHistoryCache { .collect::>(); if result.is_empty() { - return None; + return None } Some(result) @@ -309,7 +309,7 @@ pub fn calculate_reward_percentiles_for_block( // Empty blocks should return in a zero row if transactions.is_empty() { rewards_in_block.push(0); - continue; + continue } let threshold = (gas_used as f64 * percentile / 100.) as u64; diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index b92f363d444c..b5f9ca58d091 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -126,7 +126,7 @@ where // if we have stored a last price, then we check whether or not it was for the same head if inner.last_price.block_hash == header.hash() { - return Ok(inner.last_price.price); + return Ok(inner.last_price.price) } // if all responses are empty, then we can return a maximum of 2*check_block blocks' worth @@ -171,7 +171,7 @@ where // break when we have enough populated blocks if populated_blocks >= self.oracle_config.blocks { - break; + break } current_hash = parent_hash; @@ -232,14 +232,14 @@ where let tip = tx.effective_tip_per_gas(base_fee_per_gas); effective_gas_tip = Some(tip); if tip < Some(ignore_under) { - continue; + continue } } // check if the sender was the coinbase, if so, ignore if let Some(sender) = tx.recover_signer() { if sender == block.beneficiary { - continue; + continue } } @@ -253,7 +253,7 @@ where // we have enough entries if prices.len() >= limit { - break; + break } } diff --git a/crates/rpc/rpc-eth-types/src/id_provider.rs b/crates/rpc/rpc-eth-types/src/id_provider.rs index 1c4efa7707c0..a2020d0b2199 100644 --- a/crates/rpc/rpc-eth-types/src/id_provider.rs +++ b/crates/rpc/rpc-eth-types/src/id_provider.rs @@ -29,7 +29,7 @@ fn to_quantity(val: u128) -> SubscriptionId<'static> { let non_zero = b.iter().take_while(|b| **b == 0).count(); let b = &b[non_zero..]; if b.is_empty() { - return SubscriptionId::Str("0x0".into()); + return SubscriptionId::Str("0x0".into()) } let mut id = String::with_capacity(2 * b.len() + 2); diff --git a/crates/rpc/rpc-eth-types/src/logs_utils.rs b/crates/rpc/rpc-eth-types/src/logs_utils.rs index ae49685aaf2b..d332a044592e 100644 --- a/crates/rpc/rpc-eth-types/src/logs_utils.rs +++ b/crates/rpc/rpc-eth-types/src/logs_utils.rs @@ -177,7 +177,7 @@ pub fn log_matches_filter( !params.filter_address(&log.address) || !params.filter_topics(log.topics())) { - return false; + return false } true } diff --git a/crates/rpc/rpc-eth-types/src/revm_utils.rs b/crates/rpc/rpc-eth-types/src/revm_utils.rs index b9b48e2b4a87..bfcc2bf42062 100644 --- a/crates/rpc/rpc-eth-types/src/revm_utils.rs +++ b/crates/rpc/rpc-eth-types/src/revm_utils.rs @@ -125,13 +125,13 @@ impl CallFees { max_fee < block_base_fee { // `base_fee_per_gas` is greater than the `max_fee_per_gas` - return Err(RpcInvalidTransactionError::FeeCapTooLow.into()); + return Err(RpcInvalidTransactionError::FeeCapTooLow.into()) } if max_fee < max_priority_fee_per_gas { return Err( // `max_priority_fee_per_gas` is greater than the `max_fee_per_gas` RpcInvalidTransactionError::TipAboveFeeCap.into(), - ); + ) } Ok(min( max_fee, @@ -185,7 +185,7 @@ impl CallFees { // Ensure blob_hashes are present if !has_blob_hashes { // Blob transaction but no blob hashes - return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()); + return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()) } Ok(Self { diff --git a/crates/rpc/rpc-eth-types/src/utils.rs b/crates/rpc/rpc-eth-types/src/utils.rs index 4f6e91575d15..bb7c3d64846e 100644 --- a/crates/rpc/rpc-eth-types/src/utils.rs +++ b/crates/rpc/rpc-eth-types/src/utils.rs @@ -11,7 +11,7 @@ use super::{EthApiError, EthResult}; /// See [`PooledTransactionsElement::decode_enveloped`] pub fn recover_raw_transaction(data: Bytes) -> EthResult { if data.is_empty() { - return Err(EthApiError::EmptyRawTransactionData); + return Err(EthApiError::EmptyRawTransactionData) } let transaction = PooledTransactionsElement::decode_enveloped(&mut data.as_ref()) diff --git a/crates/rpc/rpc-server-types/src/module.rs b/crates/rpc/rpc-server-types/src/module.rs index 63f283213b7e..72a5e7c85833 100644 --- a/crates/rpc/rpc-server-types/src/module.rs +++ b/crates/rpc/rpc-server-types/src/module.rs @@ -195,7 +195,7 @@ impl FromStr for RpcModuleSelection { fn from_str(s: &str) -> Result { if s.is_empty() { - return Ok(Self::Selection(Default::default())); + return Ok(Self::Selection(Default::default())) } let mut modules = s.split(',').map(str::trim).peekable(); let first = modules.peek().copied().ok_or(ParseError::VariantNotFound)?; diff --git a/crates/rpc/rpc-testing-util/tests/it/trace.rs b/crates/rpc/rpc-testing-util/tests/it/trace.rs index 62e2a67f4a2c..184fc0f3e780 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -19,7 +19,7 @@ use std::{collections::HashSet, time::Instant}; async fn trace_many_blocks() { let url = parse_env_url("RETH_RPC_TEST_NODE_URL"); if url.is_err() { - return; + return } let url = url.unwrap(); @@ -106,7 +106,7 @@ async fn trace_call() { async fn debug_trace_block_entire_chain() { let url = parse_env_url("RETH_RPC_TEST_NODE_URL"); if url.is_err() { - return; + return } let url = url.unwrap(); diff --git a/crates/rpc/rpc-types-compat/src/engine/payload.rs b/crates/rpc/rpc-types-compat/src/engine/payload.rs index 89ebd52a5d17..bd2401b96ac8 100644 --- a/crates/rpc/rpc-types-compat/src/engine/payload.rs +++ b/crates/rpc/rpc-types-compat/src/engine/payload.rs @@ -16,11 +16,11 @@ use reth_rpc_types::engine::{ /// Converts [`ExecutionPayloadV1`] to [`Block`] pub fn try_payload_v1_to_block(payload: ExecutionPayloadV1) -> Result { if payload.extra_data.len() > MAXIMUM_EXTRA_DATA_SIZE { - return Err(PayloadError::ExtraData(payload.extra_data)); + return Err(PayloadError::ExtraData(payload.extra_data)) } if payload.base_fee_per_gas.is_zero() { - return Err(PayloadError::BaseFee(payload.base_fee_per_gas)); + return Err(PayloadError::BaseFee(payload.base_fee_per_gas)) } let transactions = payload @@ -356,7 +356,7 @@ pub fn validate_block_hash( return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_block_hash, - }); + }) } Ok(sealed_block) diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 4d7378f201d8..95af81a7bd86 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -93,7 +93,7 @@ where ) -> Result, Eth::Error> { if transactions.is_empty() { // nothing to trace - return Ok(Vec::new()); + return Ok(Vec::new()) } // replay all transactions of the block @@ -332,7 +332,7 @@ where Ok(frame.into()) }) .await?; - return Ok(frame); + return Ok(frame) } GethDebugBuiltInTracerType::PreStateTracer => { let prestate_config = tracer_config @@ -360,7 +360,7 @@ where Ok(frame) }) .await?; - return Ok(frame.into()); + return Ok(frame.into()) } GethDebugBuiltInTracerType::NoopTracer => Ok(NoopFrame::default().into()), GethDebugBuiltInTracerType::MuxTracer => { @@ -387,7 +387,7 @@ where Ok(frame.into()) }) .await?; - return Ok(frame); + return Ok(frame) } }, #[cfg(not(feature = "js-tracer"))] @@ -419,7 +419,7 @@ where Ok(GethTrace::JS(res)) } - }; + } } // default structlog tracer @@ -455,7 +455,7 @@ where opts: Option, ) -> Result>, Eth::Error> { if bundles.is_empty() { - return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into()); + return Err(EthApiError::InvalidParams(String::from("bundles are empty.")).into()) } let StateContext { transaction_index, block_number } = state_context.unwrap_or_default(); @@ -723,7 +723,7 @@ where .into_geth_builder() .geth_call_traces(call_config, res.result.gas_used()); - return Ok((frame.into(), res.state)); + return Ok((frame.into(), res.state)) } GethDebugBuiltInTracerType::PreStateTracer => { let prestate_config = tracer_config @@ -741,7 +741,7 @@ where .geth_prestate_traces(&res, &prestate_config, db) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)); + return Ok((frame.into(), res.state)) } GethDebugBuiltInTracerType::NoopTracer => { Ok((NoopFrame::default().into(), Default::default())) @@ -758,7 +758,7 @@ where let frame = inspector .try_into_mux_frame(&res, db) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)); + return Ok((frame.into(), res.state)) } }, #[cfg(not(feature = "js-tracer"))] @@ -782,7 +782,7 @@ where inspector.json_result(res, &env, db).map_err(Eth::Error::from_eth_err)?; Ok((GethTrace::JS(result), state)) } - }; + } } // default structlog tracer diff --git a/crates/rpc/rpc/src/eth/bundle.rs b/crates/rpc/rpc/src/eth/bundle.rs index ff060d60504d..484b8dfe8633 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -64,13 +64,13 @@ where return Err(EthApiError::InvalidParams( EthBundleError::EmptyBundleTransactions.to_string(), ) - .into()); + .into()) } if block_number == 0 { return Err(EthApiError::InvalidParams( EthBundleError::BundleMissingBlockNumber.to_string(), ) - .into()); + .into()) } let transactions = txs @@ -98,7 +98,7 @@ where return Err(EthApiError::InvalidParams( EthBundleError::Eip4844BlobGasExceeded.to_string(), ) - .into()); + .into()) } let block_id: reth_rpc_types::BlockId = state_block_number.into(); diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 55390c00a0ad..77344702b5ae 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -164,7 +164,7 @@ where if filter.block > best_number { // no new blocks since the last poll - return Ok(FilterChanges::Empty); + return Ok(FilterChanges::Empty) } // update filter @@ -232,7 +232,7 @@ where *filter.clone() } else { // Not a log filter - return Err(EthFilterError::FilterNotFound(id)); + return Err(EthFilterError::FilterNotFound(id)) } }; @@ -450,11 +450,11 @@ where let best_number = chain_info.best_number; if to_block < from_block { - return Err(EthFilterError::InvalidBlockRangeParams); + return Err(EthFilterError::InvalidBlockRangeParams) } if to_block - from_block > self.max_blocks_per_filter { - return Err(EthFilterError::QueryExceedsMaxBlocks(self.max_blocks_per_filter)); + return Err(EthFilterError::QueryExceedsMaxBlocks(self.max_blocks_per_filter)) } let mut all_logs = Vec::new(); @@ -478,7 +478,7 @@ where block.header.timestamp, )?; } - return Ok(all_logs); + return Ok(all_logs) } // derive bloom filters from filter input, so we can check headers for matching logs @@ -524,7 +524,7 @@ where if is_multi_block_range && all_logs.len() > self.max_logs_per_response { return Err(EthFilterError::QueryExceedsMaxResults( self.max_logs_per_response, - )); + )) } } } @@ -674,7 +674,7 @@ impl Iterator for BlockRangeInclusiveIter { let start = self.iter.next()?; let end = (start + self.step).min(self.end); if start > end { - return None; + return None } Some((start, end)) } diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 61a33ea5ad75..f62be16f10af 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -150,7 +150,7 @@ where tx.transaction.to_recovered_transaction(), ))) }); - return pipe_from_stream(accepted_sink, stream).await; + return pipe_from_stream(accepted_sink, stream).await } Params::Bool(false) | Params::None => { // only hashes requested @@ -180,7 +180,7 @@ where let msg = SubscriptionMessage::from_json(¤t_sub_res) .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - return Ok(()); + return Ok(()) } while canon_state.next().await.is_some() { diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index 36f42d3a918b..83e41d9a9266 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -230,7 +230,7 @@ where ) -> Result, Eth::Error> { if indices.len() != 1 { // The OG impl failed if it gets more than a single index - return Ok(None); + return Ok(None) } self.trace_get_index(hash, indices[0]).await } @@ -267,7 +267,7 @@ where return Err(EthApiError::InvalidParams( "invalid parameters: fromBlock cannot be greater than toBlock".to_string(), ) - .into()); + .into()) } // ensure that the range is not too large, since we need to fetch all blocks in the range @@ -276,7 +276,7 @@ where return Err(EthApiError::InvalidParams( "Block range too large; currently limited to 100 blocks".to_string(), ) - .into()); + .into()) } // fetch all blocks in that range @@ -317,7 +317,7 @@ where } else { // no block reward, means we're past the Paris hardfork and don't expect any rewards // because the blocks in ascending order - break; + break } } From 604df148406f7400ea500d687b9306e25e0d6553 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 15:18:51 +0200 Subject: [PATCH 58/80] Add helper trait FullEthApiTypes linking EthApiTypes::NetworkTypes to EthApiTypes::TransactionCompat --- crates/e2e-test-utils/src/lib.rs | 5 ++-- crates/e2e-test-utils/src/node.rs | 7 ++--- crates/e2e-test-utils/src/rpc.rs | 5 +--- crates/node/builder/src/builder/mod.rs | 8 ++--- crates/node/builder/src/launch/engine.rs | 5 ++-- crates/node/builder/src/launch/mod.rs | 5 ++-- crates/node/builder/src/rpc.rs | 5 ++-- crates/optimism/rpc/src/eth/mod.rs | 1 - crates/rpc/rpc-builder/src/eth.rs | 10 ++++--- crates/rpc/rpc-builder/src/lib.rs | 30 +++++++++++-------- crates/rpc/rpc-eth-api/src/core.rs | 5 ++-- .../rpc-eth-api/src/helpers/transaction.rs | 12 +++++--- crates/rpc/rpc-eth-api/src/lib.rs | 2 +- crates/rpc/rpc-eth-api/src/types.rs | 14 +++++++++ crates/rpc/rpc/src/engine.rs | 7 +++-- crates/rpc/rpc/src/eth/helpers/transaction.rs | 7 +++-- crates/rpc/rpc/src/otterscan.rs | 3 -- 17 files changed, 74 insertions(+), 57 deletions(-) diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index 45a9ebd1a1d7..d8f1e78a02b0 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -21,7 +21,6 @@ use reth_node_builder::{ RethFullAdapter, }; use reth_provider::providers::BlockchainProvider; -use reth_rpc_types_compat::TransactionCompat; use tracing::{span, Level}; use wallet::Wallet; @@ -63,8 +62,8 @@ where N::AddOns: NodeAddOns< Adapter, EthApi: FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + AddDevSigners + EthApiBuilderProvider>, diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index d1c241216542..b4851de8d9b8 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -91,12 +91,9 @@ where AddOns::EthApi: EthApiSpec + EthTransactions + TraceExt - + EthApiTypes< - NetworkTypes: Network< + + FullEthApiTypes< + NetworkTypes: alloy_network::Network< TransactionResponse = WithOtherFields, - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction<::NetworkTypes>, - >, >, >, { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index 6ebb2521c7ae..b1a9707435e9 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -25,13 +25,10 @@ where Node: FullNodeComponents>, EthApi: EthApiSpec + EthTransactions< - NetworkTypes: Network< + NetworkTypes: alloy_network::Network< TransactionResponse = WithOtherFields, ReceiptResponse = AnyTransactionReceipt, >, - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction, - >, > + TraceExt, { /// Injects a raw transaction into the node tx pool via RPC server diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 4f0cffb33e2a..8b49fead86b6 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -5,6 +5,7 @@ pub mod add_ons; mod states; +use alloy_network::Network; pub use states::*; use std::sync::Arc; @@ -36,7 +37,6 @@ use reth_node_core::{ }; use reth_primitives::revm_primitives::EnvKzgSettings; use reth_provider::{providers::BlockchainProvider, ChainSpecProvider, FullProvider}; -use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_transaction_pool::{PoolConfig, TransactionPool}; use secp256k1::SecretKey; @@ -342,7 +342,7 @@ where > > + FullEthApiServer< - TransactionCompat: TransactionCompat> + NetworkTypes: Network> > + AddDevSigners >, @@ -490,8 +490,8 @@ where NodeAdapter, CB::Components>, EthApi: EthApiBuilderProvider, CB::Components>> + FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + AddDevSigners, >, diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index e4b700b239e0..874bb4eaf0ba 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -34,7 +34,6 @@ use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; use reth_provider::providers::BlockchainProvider2; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; -use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tokio_util::EventSender; use reth_tracing::tracing::{debug, error, info}; @@ -73,8 +72,8 @@ where NodeAdapter, EthApi: EthApiBuilderProvider> + FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + AddDevSigners, >, diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 6300a3986471..9f4c8dafcc51 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -38,7 +38,6 @@ use reth_primitives::format_ether; use reth_provider::providers::BlockchainProvider; use reth_rpc_engine_api::{capabilities::EngineCapabilities, EngineApi}; use reth_rpc_types::engine::ClientVersionV1; -use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::TransactionPool; @@ -116,8 +115,8 @@ where NodeAdapter, EthApi: EthApiBuilderProvider> + FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + AddDevSigners, >, diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 77850487726d..a8e2e9e91dc3 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -22,7 +22,6 @@ use reth_rpc_builder::{ RpcModuleBuilder, RpcRegistryInner, RpcServerHandle, TransportRpcModules, }; use reth_rpc_layer::JwtSecret; -use reth_rpc_types_compat::TransactionCompat; use reth_tasks::TaskExecutor; use reth_tracing::tracing::{debug, info}; @@ -304,8 +303,8 @@ where Engine: EngineApiServer<::Engine>, EthApi: EthApiBuilderProvider + FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, >, { diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index ddc522ec2956..a835d2050a93 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -33,7 +33,6 @@ use reth_rpc_eth_api::{ EthApiTypes, }; use reth_rpc_eth_types::{EthStateCache, FeeHistoryCache, GasPriceOracle}; -use reth_rpc_types_compat::TransactionCompat; use reth_tasks::{ pool::{BlockingTaskGuard, BlockingTaskPool}, TaskSpawner, diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index b07cc3f28116..8067f5eda874 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -87,8 +87,8 @@ where Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, EthApi: EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + 'static, { @@ -149,8 +149,10 @@ impl EthFilterApiBuilder { Pool: Send + Sync + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Eth: EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields< + reth_rpc_types::Transaction, + >, >, > + 'static, { diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 9d99204981fd..4822784d3358 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -230,7 +230,9 @@ where Events: CanonStateSubscriptions + Clone + 'static, EvmConfig: ConfigureEvm, EthApi: FullEthApiServer< - TransactionCompat: TransactionCompat>, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, + >, >, { let module_config = module_config.into(); @@ -439,8 +441,8 @@ where EngineT: EngineTypes, EngineApi: EngineApiServer, EthApi: FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, >, { @@ -495,8 +497,10 @@ where ) -> RpcRegistryInner where EthApi: EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields< + reth_rpc_types::Transaction, + >, >, > + 'static, { @@ -513,8 +517,8 @@ where ) -> TransportRpcModules<()> where EthApi: FullEthApiServer< - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, >, { @@ -647,8 +651,8 @@ where Events: CanonStateSubscriptions + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, EthApi: EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, > + 'static, { @@ -809,8 +813,8 @@ where RpcBlock, RpcReceipt, > + EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, >, >, { @@ -985,7 +989,9 @@ where Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, EthApi: FullEthApiServer< - TransactionCompat: TransactionCompat>, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, + >, >, { /// Configures the auth module that includes the diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 62dbc31e85b2..487ebfcc1683 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -13,7 +13,6 @@ use reth_rpc_types::{ BlockOverrides, Bundle, EIP1186AccountProofResponse, EthCallResponse, FeeHistory, Header, Index, StateContext, SyncStatus, TransactionRequest, Work, }; -use reth_rpc_types_compat::TransactionCompat; use tracing::trace; use crate::{ @@ -369,7 +368,9 @@ impl > for T where T: FullEthApi< - TransactionCompat: TransactionCompat>, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, + >, >, jsonrpsee_types::error::ErrorObject<'static>: From, { diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index f9a4ace3f025..2d31c18836e7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -25,7 +25,9 @@ use reth_rpc_types_compat::{ }; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use crate::{EthApiTypes, FromEthApiError, IntoEthApiError, RpcReceipt, RpcTransaction}; +use crate::{ + EthApiTypes, FromEthApiError, FullEthApiTypes, IntoEthApiError, RpcReceipt, RpcTransaction, +}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, LoadState, @@ -233,8 +235,10 @@ pub trait EthTransactions: LoadTransaction { Self: LoadBlock + LoadState + EthApiTypes< - TransactionCompat: TransactionCompat< - Transaction = RpcTransaction, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields< + reth_rpc_types::Transaction, + >, >, >, { @@ -620,7 +624,7 @@ pub trait EthTransactions: LoadTransaction { /// /// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` transactions RPC /// methods. -pub trait LoadTransaction: SpawnBlocking { +pub trait LoadTransaction: SpawnBlocking + FullEthApiTypes { /// Transaction pool with pending transactions. [`TransactionPool::Transaction`] is the /// supported transaction type. type Pool: TransactionPool; diff --git a/crates/rpc/rpc-eth-api/src/lib.rs b/crates/rpc/rpc-eth-api/src/lib.rs index 80b97bc0a823..849c8e2e4c8f 100644 --- a/crates/rpc/rpc-eth-api/src/lib.rs +++ b/crates/rpc/rpc-eth-api/src/lib.rs @@ -26,7 +26,7 @@ pub use core::{EthApiServer, FullEthApiServer}; pub use filter::EthFilterApiServer; pub use helpers::error::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}; pub use pubsub::EthPubSubApiServer; -pub use types::{EthApiTypes, RpcBlock, RpcReceipt, RpcTransaction}; +pub use types::{EthApiTypes, FullEthApiTypes, RpcBlock, RpcReceipt, RpcTransaction}; #[cfg(feature = "client")] pub use bundle::{EthBundleApiClient, EthCallBundleApiClient}; diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 1c533ab5d89c..70e4d41ad8e6 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -5,6 +5,7 @@ use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; use reth_rpc_types::{Block, Transaction, WithOtherFields}; +use reth_rpc_types_compat::TransactionCompat; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -42,3 +43,16 @@ pub type RpcBlock = Block, ::HeaderResponse>; /// Adapter for network specific receipt type. pub type RpcReceipt = ::ReceiptResponse; + +/// Helper trait holds necessary trait bounds on [`EthApiTypes`] to implement `eth` API. +pub trait FullEthApiTypes: + EthApiTypes>> +{ +} + +impl FullEthApiTypes for T where + T: EthApiTypes< + TransactionCompat: TransactionCompat>, + > +{ +} diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 066fd9c1b108..6821ba4a4f73 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -9,7 +9,6 @@ use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, SyncStatus, TransactionRequest, }; -use reth_rpc_types_compat::TransactionCompat; use tracing_futures::Instrument; macro_rules! engine_span { @@ -42,9 +41,11 @@ where RpcBlock, RpcReceipt, > + EthApiTypes< - TransactionCompat: TransactionCompat>, + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, + >, >, - EthFilter: EthFilterApiServer<::Transaction>, + EthFilter: EthFilterApiServer>, { /// Handler for: `eth_syncing` fn syncing(&self) -> Result { diff --git a/crates/rpc/rpc/src/eth/helpers/transaction.rs b/crates/rpc/rpc/src/eth/helpers/transaction.rs index 2bf64536b452..4a8d95169bf5 100644 --- a/crates/rpc/rpc/src/eth/helpers/transaction.rs +++ b/crates/rpc/rpc/src/eth/helpers/transaction.rs @@ -1,7 +1,10 @@ //! Contains RPC handler implementations specific to transactions use reth_provider::{BlockReaderIdExt, TransactionsProvider}; -use reth_rpc_eth_api::helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}; +use reth_rpc_eth_api::{ + helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, + FullEthApiTypes, +}; use reth_rpc_eth_types::EthStateCache; use reth_transaction_pool::TransactionPool; @@ -28,7 +31,7 @@ where impl LoadTransaction for EthApi where - Self: SpawnBlocking, + Self: SpawnBlocking + FullEthApiTypes, Provider: TransactionsProvider, Pool: TransactionPool, { diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 992b400aa4fc..faf5b6bf3fcb 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -20,7 +20,6 @@ use reth_rpc_types::{ }, BlockTransactions, Header, Transaction, TransactionReceipt, WithOtherFields, }; -use reth_rpc_types_compat::TransactionCompat; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, transfer::{TransferInspector, TransferKind}, @@ -46,7 +45,6 @@ impl OtterscanApi where Eth: EthApiTypes< NetworkTypes: Network>, - TransactionCompat: TransactionCompat>, >, { /// Constructs a `BlockDetails` from a block and its receipts. @@ -76,7 +74,6 @@ where NetworkTypes: Network< TransactionResponse = WithOtherFields, >, - TransactionCompat: TransactionCompat>, > + TraceExt + EthTransactions + 'static, From 68d5c9aca7089a27169ec81a6b4b304013ce9462 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 15:40:46 +0200 Subject: [PATCH 59/80] Fix merge conflicts --- crates/optimism/rpc/src/eth/transaction.rs | 22 ---------------------- 1 file changed, 22 deletions(-) diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 0a027cc39cce..a9c3cbf187f0 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -80,28 +80,6 @@ where } } -/// L1 fee and data gas for a transaction, along with the L1 block info. -#[derive(Debug, Default, Clone)] -pub struct OptimismTxMeta { - /// The L1 block info. - pub l1_block_info: Option, - /// The L1 fee for the block. - pub l1_fee: Option, - /// The L1 data gas for the block. - pub l1_data_gas: Option, -} - -impl OptimismTxMeta { - /// Creates a new [`OptimismTxMeta`]. - pub const fn new( - l1_block_info: Option, - l1_fee: Option, - l1_data_gas: Option, - ) -> Self { - Self { l1_block_info, l1_fee, l1_data_gas } - } -} - impl OpEthApi where N: FullNodeComponents, From 384145014fcf21d3cd2be7f8d594f959e91a6fee Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 15:43:38 +0200 Subject: [PATCH 60/80] Revert formatting changes --- crates/rpc/rpc-builder/src/auth.rs | 2 +- crates/rpc/rpc-builder/src/cors.rs | 2 +- crates/rpc/rpc-builder/src/error.rs | 2 +- crates/rpc/rpc-builder/src/lib.rs | 10 +++++----- crates/rpc/rpc-engine-api/src/engine_api.rs | 10 +++++----- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/rpc/rpc-builder/src/auth.rs b/crates/rpc/rpc-builder/src/auth.rs index 849349aa2688..25626e4f12d3 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -304,7 +304,7 @@ impl AuthServerHandle { .build(ipc_endpoint) .await .expect("Failed to create ipc client"), - ); + ) } None } diff --git a/crates/rpc/rpc-builder/src/cors.rs b/crates/rpc/rpc-builder/src/cors.rs index 18098a7d1632..c68cf84942c0 100644 --- a/crates/rpc/rpc-builder/src/cors.rs +++ b/crates/rpc/rpc-builder/src/cors.rs @@ -31,7 +31,7 @@ pub(crate) fn create_cors_layer(http_cors_domains: &str) -> Result Self { if io_error.kind() == ErrorKind::AddrInUse { - return Self::AddressAlreadyInUse { kind, error: io_error }; + return Self::AddressAlreadyInUse { kind, error: io_error } } Self::ServerError { kind, error: io_error } } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 4822784d3358..0d19689865e4 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -1410,7 +1410,7 @@ impl RpcServerConfig { http_cors_domains: Some(http_cors.clone()), ws_cors_domains: Some(ws_cors.clone()), } - .into()); + .into()) } Some(ws_cors) } @@ -1459,7 +1459,7 @@ impl RpcServerConfig { ipc_endpoint: self.ipc_endpoint.clone(), ipc: ipc_handle, jwt_secret: self.jwt_secret, - }); + }) } } @@ -1694,7 +1694,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no http transport is configured. pub fn merge_http(&mut self, other: impl Into) -> Result { if let Some(ref mut http) = self.http { - return http.merge(other.into()).map(|_| true); + return http.merge(other.into()).map(|_| true) } Ok(false) } @@ -1706,7 +1706,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no ws transport is configured. pub fn merge_ws(&mut self, other: impl Into) -> Result { if let Some(ref mut ws) = self.ws { - return ws.merge(other.into()).map(|_| true); + return ws.merge(other.into()).map(|_| true) } Ok(false) } @@ -1718,7 +1718,7 @@ impl TransportRpcModules { /// Returns [Ok(false)] if no ipc transport is configured. pub fn merge_ipc(&mut self, other: impl Into) -> Result { if let Some(ref mut ipc) = self.ipc { - return ipc.merge(other.into()).map(|_| true); + return ipc.merge(other.into()).map(|_| true) } Ok(false) } diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index 95a172a11334..b2f95fea5f74 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -477,7 +477,7 @@ where { let len = hashes.len() as u64; if len > MAX_PAYLOAD_BODIES_LIMIT { - return Err(EngineApiError::PayloadRequestTooLarge { len }); + return Err(EngineApiError::PayloadRequestTooLarge { len }) } let mut result = Vec::with_capacity(hashes.len()); @@ -535,7 +535,7 @@ where return Err(EngineApiError::TerminalTD { execution: merge_terminal_td, consensus: terminal_total_difficulty, - }); + }) } self.inner.beacon_consensus.transition_configuration_exchanged(); @@ -545,7 +545,7 @@ where return Ok(TransitionConfiguration { terminal_total_difficulty: merge_terminal_td, ..Default::default() - }); + }) } // Attempt to look up terminal block hash @@ -610,9 +610,9 @@ where // TODO: decide if we want this branch - the FCU INVALID response might be more // useful than the payload attributes INVALID response if fcu_res.is_invalid() { - return Ok(fcu_res); + return Ok(fcu_res) } - return Err(err.into()); + return Err(err.into()) } } From 1756510fa397ded028d1647f3926cc65d5432e13 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 15:47:13 +0200 Subject: [PATCH 61/80] Revert formatting changes --- crates/rpc/rpc-builder/src/lib.rs | 4 ++-- crates/rpc/rpc-eth-api/src/helpers/block.rs | 4 ++-- crates/rpc/rpc-eth-api/src/helpers/transaction.rs | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 0d19689865e4..d45b60c9258d 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -1410,7 +1410,7 @@ impl RpcServerConfig { http_cors_domains: Some(http_cors.clone()), ws_cors_domains: Some(ws_cors.clone()), } - .into()) + .into()); } Some(ws_cors) } @@ -1459,7 +1459,7 @@ impl RpcServerConfig { ipc_endpoint: self.ipc_endpoint.clone(), ipc: ipc_handle, jwt_secret: self.jwt_secret, - }) + }); } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 4e0c08e24654..d5e37fd2b074 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -126,12 +126,12 @@ pub trait EthBlocks: LoadBlock { .pending_block_and_receipts() .map_err(Self::Error::from_eth_err)? { - return Ok(Some((block, Arc::new(receipts)))) + return Ok(Some((block, Arc::new(receipts)))); } // If no pending block from provider, build the pending block locally. if let Some((block, receipts)) = self.local_pending_block().await? { - return Ok(Some((block.block, Arc::new(receipts)))) + return Ok(Some((block.block, Arc::new(receipts)))); } } diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 2d31c18836e7..7b852716f66a 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -255,7 +255,7 @@ pub trait EthTransactions: LoadTransaction { // Check if the sender is a contract if self.get_code(sender, None).await?.len() > 0 { - return Ok(None) + return Ok(None); } let highest = self.transaction_count(sender, None).await?.saturating_to::(); @@ -263,11 +263,11 @@ pub trait EthTransactions: LoadTransaction { // If the nonce is higher or equal to the highest nonce, the transaction is pending or // not exists. if nonce >= highest { - return Ok(None) + return Ok(None); } let Ok(high) = LoadBlock::provider(self).best_block_number() else { - return Err(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()).into()) + return Err(EthApiError::HeaderNotFound(BlockNumberOrTag::Latest.into()).into()); }; // Perform a binary search over the block range to find the block in which the sender's @@ -575,7 +575,7 @@ pub trait EthTransactions: LoadTransaction { return match signer.sign_transaction(request, from) { Ok(tx) => Ok(tx), Err(e) => Err(e.into_eth_err()), - }; + } } } Err(EthApiError::InvalidTransactionSignature.into()) From 3c1b2cd4d136342fa9654e657a3226cad6ce5293 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 15:49:31 +0200 Subject: [PATCH 62/80] Revert bad formatting changes --- crates/rpc/rpc/src/eth/pubsub.rs | 2 +- crates/rpc/rpc/src/otterscan.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index f62be16f10af..7d36b5220e55 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -195,7 +195,7 @@ where let msg = SubscriptionMessage::from_json(&sync_status) .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - break; + break } } } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index faf5b6bf3fcb..0d64ff2500b2 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -217,7 +217,7 @@ where if tx_len != receipts.len() { return Err(internal_rpc_err( "the number of transactions does not match the number of receipts", - )); + )) } // make sure the block is full From 472a338723ce6beb280b15df74935327c1254185 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Wed, 11 Sep 2024 16:04:03 +0200 Subject: [PATCH 63/80] Remove redundant trait bound on RPC transaction response type --- crates/e2e-test-utils/src/lib.rs | 7 +-- crates/e2e-test-utils/src/node.rs | 9 +--- crates/e2e-test-utils/src/rpc.rs | 8 +--- crates/node/builder/src/builder/mod.rs | 11 ++--- crates/node/builder/src/launch/engine.rs | 7 +-- crates/node/builder/src/launch/mod.rs | 7 +-- crates/node/builder/src/rpc.rs | 7 +-- crates/rpc/rpc-builder/src/eth.rs | 14 +----- crates/rpc/rpc-builder/src/lib.rs | 44 +++---------------- crates/rpc/rpc-eth-api/src/core.rs | 6 +-- .../rpc-eth-api/src/helpers/transaction.rs | 14 +----- crates/rpc/rpc-eth-api/src/types.rs | 7 +-- crates/rpc/rpc/src/engine.rs | 8 +--- crates/rpc/rpc/src/otterscan.rs | 19 ++++---- 14 files changed, 35 insertions(+), 133 deletions(-) diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index d8f1e78a02b0..c4f1315e220b 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -61,12 +61,7 @@ where >, N::AddOns: NodeAddOns< Adapter, - EthApi: FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + AddDevSigners - + EthApiBuilderProvider>, + EthApi: FullEthApiServer + AddDevSigners + EthApiBuilderProvider>, >, { let tasks = TaskManager::current(); diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index b4851de8d9b8..2d370db262d3 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -88,14 +88,7 @@ where ) -> eyre::Result> where Engine::ExecutionPayloadV3: From + PayloadEnvelopeExt, - AddOns::EthApi: EthApiSpec - + EthTransactions - + TraceExt - + FullEthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = WithOtherFields, - >, - >, + AddOns::EthApi: EthApiSpec + EthTransactions + TraceExt + FullEthApiTypes, { let mut chain = Vec::with_capacity(length as usize); for i in 0..length { diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index b1a9707435e9..3c613b055df4 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -23,13 +23,7 @@ pub struct RpcTestContext { impl RpcTestContext where Node: FullNodeComponents>, - EthApi: EthApiSpec - + EthTransactions< - NetworkTypes: alloy_network::Network< - TransactionResponse = WithOtherFields, - ReceiptResponse = AnyTransactionReceipt, - >, - > + TraceExt, + EthApi: EthApiSpec + EthTransactions + TraceExt, { /// Injects a raw transaction into the node tx pool via RPC server pub async fn inject_tx(&self, raw_tx: Bytes) -> Result { diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 8b49fead86b6..c2e4dce7a913 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -341,9 +341,7 @@ where >>::Components, > > - + FullEthApiServer< - NetworkTypes: Network> - > + + FullEthApiServer + AddDevSigners >, { @@ -489,11 +487,8 @@ where AO: NodeAddOns< NodeAdapter, CB::Components>, EthApi: EthApiBuilderProvider, CB::Components>> - + FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + AddDevSigners, + + FullEthApiServer + + AddDevSigners, >, { /// Launches the node with the [`DefaultNodeLauncher`] that sets up engine API consensus and rpc diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index 874bb4eaf0ba..f56c43218ba3 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -71,11 +71,8 @@ where AO: NodeAddOns< NodeAdapter, EthApi: EthApiBuilderProvider> - + FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + AddDevSigners, + + FullEthApiServer + + AddDevSigners, >, { type Node = NodeHandle, AO>; diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 9f4c8dafcc51..2f20c2467eab 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -114,11 +114,8 @@ where AO: NodeAddOns< NodeAdapter, EthApi: EthApiBuilderProvider> - + FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + AddDevSigners, + + FullEthApiServer + + AddDevSigners, >, { type Node = NodeHandle, AO>; diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index a8e2e9e91dc3..4f2cbf1d3cbe 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -301,12 +301,7 @@ pub async fn launch_rpc_servers( where Node: FullNodeComponents> + Clone, Engine: EngineApiServer<::Engine>, - EthApi: EthApiBuilderProvider - + FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + EthApi: EthApiBuilderProvider + FullEthApiServer, { let auth_config = config.rpc.auth_server_config(jwt_secret)?; let module_config = config.rpc.transport_rpc_module_config(); diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index 8067f5eda874..b0aa12a5de43 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -86,11 +86,7 @@ where Network: Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + 'static, + EthApi: EthApiTypes + 'static, { /// Returns a new instance with handlers for `eth` namespace. pub fn build(self) -> EthHandlers { @@ -148,13 +144,7 @@ impl EthFilterApiBuilder { Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - Eth: EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields< - reth_rpc_types::Transaction, - >, - >, - > + 'static, + Eth: EthApiTypes + 'static, { EthFilter::new( ctx.provider.clone(), diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index d45b60c9258d..64049bcc461c 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -229,11 +229,7 @@ where Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, EvmConfig: ConfigureEvm, - EthApi: FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + EthApi: FullEthApiServer, { let module_config = module_config.into(); server_config @@ -440,11 +436,7 @@ where where EngineT: EngineTypes, EngineApi: EngineApiServer, - EthApi: FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + EthApi: FullEthApiServer, { let Self { provider, pool, network, executor, events, evm_config } = self; @@ -496,13 +488,7 @@ where eth: DynEthApiBuilder, ) -> RpcRegistryInner where - EthApi: EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields< - reth_rpc_types::Transaction, - >, - >, - > + 'static, + EthApi: EthApiTypes + 'static, { let Self { provider, pool, network, executor, events, evm_config } = self; RpcRegistryInner::new(provider, pool, network, executor, events, config, evm_config, eth) @@ -516,11 +502,7 @@ where eth: DynEthApiBuilder, ) -> TransportRpcModules<()> where - EthApi: FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + EthApi: FullEthApiServer, { let mut modules = TransportRpcModules::default(); @@ -650,11 +632,7 @@ where Network: Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, - EthApi: EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + 'static, + EthApi: EthApiTypes + 'static, { /// Creates a new, empty instance. #[allow(clippy::too_many_arguments)] @@ -812,11 +790,7 @@ where RpcTransaction, RpcBlock, RpcReceipt, - > + EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + > + EthApiTypes, { /// Register Eth Namespace /// @@ -988,11 +962,7 @@ where Network: NetworkInfo + Peers + Clone + 'static, Tasks: TaskSpawner + Clone + 'static, Events: CanonStateSubscriptions + Clone + 'static, - EthApi: FullEthApiServer< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + EthApi: FullEthApiServer, { /// Configures the auth module that includes the /// * `engine_` namespace diff --git a/crates/rpc/rpc-eth-api/src/core.rs b/crates/rpc/rpc-eth-api/src/core.rs index 487ebfcc1683..92d562991aaf 100644 --- a/crates/rpc/rpc-eth-api/src/core.rs +++ b/crates/rpc/rpc-eth-api/src/core.rs @@ -367,11 +367,7 @@ impl RpcReceipt, > for T where - T: FullEthApi< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + T: FullEthApi, jsonrpsee_types::error::ErrorObject<'static>: From, { /// Handler for: `eth_protocolVersion` diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 7b852716f66a..9776a9eb2bea 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -25,9 +25,7 @@ use reth_rpc_types_compat::{ }; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use crate::{ - EthApiTypes, FromEthApiError, FullEthApiTypes, IntoEthApiError, RpcReceipt, RpcTransaction, -}; +use crate::{FromEthApiError, FullEthApiTypes, IntoEthApiError, RpcReceipt, RpcTransaction}; use super::{ Call, EthApiSpec, EthSigner, LoadBlock, LoadFee, LoadPendingBlock, LoadReceipt, LoadState, @@ -232,15 +230,7 @@ pub trait EthTransactions: LoadTransaction { include_pending: bool, ) -> impl Future>, Self::Error>> + Send where - Self: LoadBlock - + LoadState - + EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields< - reth_rpc_types::Transaction, - >, - >, - >, + Self: LoadBlock + LoadState + FullEthApiTypes, { async move { // Check the pool first diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 70e4d41ad8e6..5636dfe9f051 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -4,7 +4,7 @@ use std::{error::Error, fmt}; use alloy_network::{AnyNetwork, Network}; use reth_rpc_eth_types::EthApiError; -use reth_rpc_types::{Block, Transaction, WithOtherFields}; +use reth_rpc_types::Block; use reth_rpc_types_compat::TransactionCompat; use crate::{AsEthApiError, FromEthApiError, FromEvmError}; @@ -21,10 +21,7 @@ pub trait EthApiTypes: Send + Sync + Clone { + Sync; /// Blockchain primitive types, specific to network, e.g. block and transaction. // todo: remove restriction [`reth_rpc_types::Transaction`] - type NetworkTypes: Network< - TransactionResponse = WithOtherFields, - HeaderResponse = reth_rpc_types::Header, - >; + type NetworkTypes: Network; /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; } diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 6821ba4a4f73..c646d6809c40 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -4,7 +4,7 @@ use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_api::{EngineEthApiServer, EthApiServer, EthFilterApiServer}; /// Re-export for convenience pub use reth_rpc_engine_api::EngineApi; -use reth_rpc_eth_api::{EthApiTypes, RpcBlock, RpcReceipt, RpcTransaction}; +use reth_rpc_eth_api::{FullEthApiTypes, RpcBlock, RpcReceipt, RpcTransaction}; use reth_rpc_types::{ state::StateOverride, BlockOverrides, EIP1186AccountProofResponse, Filter, JsonStorageKey, Log, SyncStatus, TransactionRequest, @@ -40,11 +40,7 @@ where RpcTransaction, RpcBlock, RpcReceipt, - > + EthApiTypes< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - >, + > + FullEthApiTypes, EthFilter: EthFilterApiServer>, { /// Handler for: `eth_syncing` diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 0d64ff2500b2..dbe5d130e9f4 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -1,4 +1,4 @@ -use alloy_network::{Network, ReceiptResponse}; +use alloy_network::ReceiptResponse; use alloy_primitives::{Address, Bytes, TxHash, B256, U256}; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, types::ErrorObjectOwned}; @@ -6,7 +6,7 @@ use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_api::{EthApiServer, OtterscanServer}; use reth_rpc_eth_api::{ helpers::{EthTransactions, TraceExt}, - EthApiTypes, RpcBlock, RpcReceipt, RpcTransaction, + FullEthApiTypes, RpcBlock, RpcReceipt, RpcTransaction, }; use reth_rpc_eth_types::{utils::binary_search, EthApiError}; use reth_rpc_server_types::result::internal_rpc_err; @@ -43,9 +43,7 @@ impl OtterscanApi { impl OtterscanApi where - Eth: EthApiTypes< - NetworkTypes: Network>, - >, + Eth: FullEthApiTypes, { /// Constructs a `BlockDetails` from a block and its receipts. fn block_details( @@ -70,13 +68,12 @@ where RpcTransaction, RpcBlock, RpcReceipt, - > + EthApiTypes< - NetworkTypes: Network< - TransactionResponse = WithOtherFields, - >, > + TraceExt - + EthTransactions - + 'static, + + EthTransactions< + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields, + >, + > + 'static, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { From 509939f5ae4af3142f9a8630a8420fa3af98fe88 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 13 Sep 2024 19:03:21 +0200 Subject: [PATCH 64/80] Bump deps --- Cargo.lock | 243 ++++++++++++++++++++++++----------------------------- 1 file changed, 111 insertions(+), 132 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7059fbf00747..ac9b2f463cd3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,19 +4,13 @@ version = 3 [[package]] name = "addr2line" -version = "0.22.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" +checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" dependencies = [ "gimli", ] -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - [[package]] name = "adler2" version = "2.0.0" @@ -103,9 +97,9 @@ checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" [[package]] name = "alloy-chains" -version = "0.1.30" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b4f201b0ac8f81315fbdc55269965a8ddadbc04ab47fa65a1a468f9a40f7a5f" +checksum = "b68b94c159bcc2ca5f758b8663d7b00fc7c5e40569984595ddf2221b0f7f7f6e" dependencies = [ "alloy-rlp", "arbitrary", @@ -132,9 +126,9 @@ dependencies = [ [[package]] name = "alloy-dyn-abi" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b03f58cfae4d41b624effe1f11624ee40499449174b20a6d6505fd72ef0d547d" +checksum = "4004925bff5ba0a11739ae84dbb6601a981ea692f3bd45b626935ee90a6b8471" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -207,9 +201,9 @@ dependencies = [ [[package]] name = "alloy-json-abi" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28ecae8b5315daecd0075084eb47f4374b3037777346ca52fc8d9c327693f02" +checksum = "9996daf962fd0a90d3c93b388033228865953b92de7bb1959b891d78750a4091" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -283,9 +277,9 @@ dependencies = [ [[package]] name = "alloy-primitives" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccb865df835f851b367ae439d6c82b117ded971628c8888b24fed411a290e38a" +checksum = "411aff151f2a73124ee473708e82ed51b2535f68928b6a1caa8bc1246ae6f7cd" dependencies = [ "alloy-rlp", "arbitrary", @@ -595,9 +589,9 @@ dependencies = [ [[package]] name = "alloy-sol-macro" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2dc5201ca0018afb7a3e0cd8bd15f7ca6aca924333b5f3bb87463b41d0c4ef2" +checksum = "0458ccb02a564228fcd76efb8eb5a520521a8347becde37b402afec9a1b83859" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", @@ -609,13 +603,13 @@ dependencies = [ [[package]] name = "alloy-sol-macro-expander" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "155f63dc6945885aa4532601800201fddfaa3b20901fda8e8c2570327242fe0e" +checksum = "2bc65475025fc1e84bf86fc840f04f63fcccdcf3cf12053c99918e4054dfbc69" dependencies = [ "alloy-sol-macro-input", "const-hex", - "heck 0.5.0", + "heck", "indexmap 2.5.0", "proc-macro-error2", "proc-macro2", @@ -627,13 +621,13 @@ dependencies = [ [[package]] name = "alloy-sol-macro-input" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "847700aa9cb59d3c7b290b2d05976cd8d76b64d73bb63116a9533132d995586b" +checksum = "6ed10f0715a0b69fde3236ff3b9ae5f6f7c97db5a387747100070d3016b9266b" dependencies = [ "const-hex", "dunce", - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn 2.0.77", @@ -642,9 +636,9 @@ dependencies = [ [[package]] name = "alloy-sol-type-parser" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a6b5d462d4520bd9ed70d8364c6280aeff13baa46ea26be1ddd33538dbbe6ac" +checksum = "3edae8ea1de519ccba896b6834dec874230f72fe695ff3c9c118e90ec7cff783" dependencies = [ "serde", "winnow", @@ -652,9 +646,9 @@ dependencies = [ [[package]] name = "alloy-sol-types" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83665e5607725a7a1aab3cb0dea708f4a05e70776954ec7f0a9461439175c957" +checksum = "1eb88e4da0a1b697ed6a9f811fdba223cf4d5c21410804fd1707836af73a462b" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -826,9 +820,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.87" +version = "1.0.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f00e1f6e58a40e807377c75c6a7f97bf9044fab57816f2414e6f5f4499d7b8" +checksum = "4e1496f8fb1fbf272686b8d37f523dab3e4a7443300055e74cdaa449f3114356" [[package]] name = "aquamarine" @@ -1133,17 +1127,17 @@ dependencies = [ [[package]] name = "backtrace" -version = "0.3.73" +version = "0.3.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" +checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" dependencies = [ "addr2line", - "cc", "cfg-if", "libc", - "miniz_oxide 0.7.4", + "miniz_oxide", "object", "rustc-demangle", + "windows-targets 0.52.6", ] [[package]] @@ -1308,9 +1302,9 @@ dependencies = [ [[package]] name = "boa_ast" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b49637e7ecb7c541c46c3e885d4c49326ad8076dbfb88bef2cf3165d8ea7df2b" +checksum = "3a69ee3a749ea36d4e56d92941e7b25076b493d4917c3d155b6cf369e23547d9" dependencies = [ "bitflags 2.6.0", "boa_interner", @@ -1322,9 +1316,9 @@ dependencies = [ [[package]] name = "boa_engine" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411558b4cbc7d0303012e26721815e612fed78179313888fd5dd8d6c50d70099" +checksum = "06e4559b35b80ceb2e6328481c0eca9a24506663ea33ee1e279be6b5b618b25c" dependencies = [ "arrayvec", "bitflags 2.6.0", @@ -1367,9 +1361,9 @@ dependencies = [ [[package]] name = "boa_gc" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eff345a85a39cf9b8ed863198947d61e6df2b1d774002b57341158b0ce2c525" +checksum = "716406f57d67bc3ac7fd227d5513b42df401dff14a3be22cbd8ee29817225363" dependencies = [ "boa_macros", "boa_profiler", @@ -1380,9 +1374,9 @@ dependencies = [ [[package]] name = "boa_interner" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b779280420804c70da9043d152c84eb96e2f7c9e7d1ec3262decf59f9349df" +checksum = "4e18df2272616e1ba0322a69333d37dbb78797f1aa0595aad9dc41e8ecd06ad9" dependencies = [ "boa_gc", "boa_macros", @@ -1396,9 +1390,9 @@ dependencies = [ [[package]] name = "boa_macros" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e0097fa69cde4c95f9869654004340fbbe2bcf3ce9189ba2a31a65ac40e0a1" +checksum = "240f4126219a83519bad05c9a40bfc0303921eeb571fc2d7e44c17ffac99d3f1" dependencies = [ "proc-macro2", "quote", @@ -1408,9 +1402,9 @@ dependencies = [ [[package]] name = "boa_parser" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd63fe8faf62561fc8c50f9402687e8cfde720b57d292fb3b4ac17c821878ac1" +checksum = "62b59dc05bf1dc019b11478a92986f590cff43fced4d20e866eefb913493e91c" dependencies = [ "bitflags 2.6.0", "boa_ast", @@ -1427,15 +1421,15 @@ dependencies = [ [[package]] name = "boa_profiler" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd9da895f0df9e2a97b36c1f98e0c5d2ab963abc8679d80f2a66f7bcb211ce90" +checksum = "00ee0645509b3b91abd724f25072649d9e8e65653a78ff0b6e592788a58dd838" [[package]] name = "boa_string" -version = "0.19.0" +version = "0.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9ca6668df83fcd3c2903f6f296b7180421908c5b478ebe0d1c468be9fd60e1c" +checksum = "ae85205289bab1f2c7c8a30ddf0541cf89ba2ff7dbd144feef50bbfa664288d4" dependencies = [ "fast-float", "paste", @@ -1733,7 +1727,7 @@ version = "4.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "syn 2.0.77", @@ -2608,11 +2602,11 @@ dependencies = [ [[package]] name = "enum-as-inner" -version = "0.6.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ffccbb6966c05b32ef8fbac435df276c4ae4d3dc55a8cd0eb9745e6c12f546a" +checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" dependencies = [ - "heck 0.4.1", + "heck", "proc-macro2", "quote", "syn 2.0.77", @@ -3054,7 +3048,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "324a1be68054ef05ad64b861cc9eaf1d623d2d8cb25b4bf2cb9cdd902b4bf253" dependencies = [ "crc32fast", - "miniz_oxide 0.8.0", + "miniz_oxide", ] [[package]] @@ -3273,9 +3267,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.29.0" +version = "0.31.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" +checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" [[package]] name = "glob" @@ -3417,12 +3411,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - [[package]] name = "heck" version = "0.5.0" @@ -3643,9 +3631,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cde7055719c54e36e95e8719f95883f22072a48ede39db7fc17a4e1d5281e9b9" +checksum = "da62f120a8a37763efb0cf8fdf264b884c7b8b9ac8660b900c8661030c00e6ba" dependencies = [ "bytes", "futures-channel", @@ -4044,9 +4032,9 @@ checksum = "187674a687eed5fe42285b40c6291f9a01517d415fad1c3cbc6a9f778af7fcd4" [[package]] name = "iri-string" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f5f6c2df22c009ac44f6f1499308e7a3ac7ba42cd2378475cc691510e1eef1b" +checksum = "3e0f755bd3806e06ad4f366f92639415d99a339a2c7ecf8c26ccea2097c11cb6" dependencies = [ "memchr", "serde", @@ -4142,9 +4130,9 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ec465b607a36dc5dd45d48b7689bc83f679f66a3ac6b6b21cc787a11e0f8685" +checksum = "8fd1ead9fb95614e8dc5556d12a8681c2f6d352d0c1d3efc8708c7ccbba47bc6" dependencies = [ "jsonrpsee-client-transport", "jsonrpsee-core", @@ -4160,9 +4148,9 @@ dependencies = [ [[package]] name = "jsonrpsee-client-transport" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f0977f9c15694371b8024c35ab58ca043dbbf4b51ccb03db8858a021241df1" +checksum = "89841d4f03a14c055eb41d4f41901819573ef948e8ee0d5c86466fd286b2ce7f" dependencies = [ "base64 0.22.1", "futures-channel", @@ -4185,9 +4173,9 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e942c55635fbf5dc421938b8558a8141c7e773720640f4f1dbe1f4164ca4e221" +checksum = "ff79651479f69ada7bda604ef2acf3f1aa50755d97cc36d25ff04c2664f9d96f" dependencies = [ "async-trait", "bytes", @@ -4212,9 +4200,9 @@ dependencies = [ [[package]] name = "jsonrpsee-http-client" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33774602df12b68a2310b38a535733c477ca4a498751739f89fe8dbbb62ec4c" +checksum = "68ed8b301b19f4dad8ddc66ed956a70fc227def5c19b3898e0a29ce8f0edee06" dependencies = [ "async-trait", "base64 0.22.1", @@ -4237,11 +4225,11 @@ dependencies = [ [[package]] name = "jsonrpsee-proc-macros" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b07a2daf52077ab1b197aea69a5c990c060143835bf04c77070e98903791715" +checksum = "a0d4c6bec4909c966f59f52db3655c0e9d4685faae8b49185973d9d7389bb884" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro-crate", "proc-macro2", "quote", @@ -4250,9 +4238,9 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038fb697a709bec7134e9ccbdbecfea0e2d15183f7140254afef7c5610a3f488" +checksum = "ebe2198e5fd96cf2153ecc123364f699b6e2151317ea09c7bf799c43c2fe1415" dependencies = [ "futures-util", "http", @@ -4277,9 +4265,9 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b67d6e008164f027afbc2e7bb79662650158d26df200040282d2aa1cbb093b" +checksum = "531e386460425e49679587871a056f2895a47dade21457324ad1262cd78ef6d9" dependencies = [ "http", "serde", @@ -4289,9 +4277,9 @@ dependencies = [ [[package]] name = "jsonrpsee-wasm-client" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0470d0ae043ffcb0cd323797a631e637fb4b55fe3eaa6002934819458bba62a7" +checksum = "5a2d2206c8f04c6b79a11bd1d92d6726b6f7fd3dec57c91e07fa53e867268bbb" dependencies = [ "jsonrpsee-client-transport", "jsonrpsee-core", @@ -4300,9 +4288,9 @@ dependencies = [ [[package]] name = "jsonrpsee-ws-client" -version = "0.24.3" +version = "0.24.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "992bf67d1132f88edf4a4f8cff474cf01abb2be203004a2b8e11c2b20795b99e" +checksum = "87bc869e143d430e748988261d19b630e8f1692074e68f1a7f0eb4c521d2fc58" dependencies = [ "http", "jsonrpsee-client-transport", @@ -4351,9 +4339,9 @@ dependencies = [ [[package]] name = "keccak-asm" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "422fbc7ff2f2f5bdffeb07718e5a5324dca72b0c9293d50df4026652385e3314" +checksum = "505d1856a39b200489082f90d897c3f07c455563880bc5952e38eabf731c83b6" dependencies = [ "digest 0.10.7", "sha3-asm", @@ -4422,7 +4410,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" dependencies = [ "cfg-if", - "windows-targets 0.48.5", + "windows-targets 0.52.6", ] [[package]] @@ -4469,7 +4457,7 @@ checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags 2.6.0", "libc", - "redox_syscall 0.5.3", + "redox_syscall 0.5.4", ] [[package]] @@ -4632,9 +4620,9 @@ checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memmap2" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe751422e4a8caa417e13c3ea66452215d7d63e19e604f4980461212f3ae1322" +checksum = "fd3f7eed9d3848f8b98834af67102b720745c4ec028fcd0aa0239277e7de374f" dependencies = [ "libc", ] @@ -4748,15 +4736,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" -dependencies = [ - "adler", -] - [[package]] name = "miniz_oxide" version = "0.8.0" @@ -5321,7 +5300,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall 0.5.3", + "redox_syscall 0.5.4", "smallvec", "windows-targets 0.52.6", ] @@ -5480,9 +5459,9 @@ dependencies = [ [[package]] name = "plotters" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a15b6eccb8484002195a3e44fe65a4ce8e93a625797a063735536fd59cb01cf3" +checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" dependencies = [ "num-traits", "plotters-backend", @@ -5493,15 +5472,15 @@ dependencies = [ [[package]] name = "plotters-backend" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414cec62c6634ae900ea1c56128dfe87cf63e7caece0852ec76aba307cebadb7" +checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" [[package]] name = "plotters-svg" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81b30686a7d9c3e010b84284bdd26a29f2138574f52f5eb6f794fc0ad924e705" +checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" dependencies = [ "plotters-backend", ] @@ -6023,9 +6002,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +checksum = "0884ad60e090bf1345b93da0a5de8923c93884cd03f40dfcfddd3b4bee661853" dependencies = [ "bitflags 2.6.0", ] @@ -8963,9 +8942,9 @@ dependencies = [ [[package]] name = "revm-inspectors" -version = "0.7.0" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d37cf496100c6ff1fb7de04a0e05318b7f36b36aec54054bdeeb3346fb2abeb" +checksum = "02b2198350ddee1744cc99812fb39175daf6960af26c1dcfb26ec853c1937d9e" dependencies = [ "alloy-primitives", "alloy-rpc-types-eth", @@ -9199,9 +9178,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.36" +version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f55e80d50763938498dd5ebb18647174e0c76dc38c5505294bb224624f30f36" +checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ "bitflags 2.6.0", "errno", @@ -9212,9 +9191,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.12" +version = "0.23.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c58f8c84392efc0a126acce10fa59ff7b3d2ac06ab451a33f2741989b806b044" +checksum = "f2dabaac7466917e566adb06783a81ca48944c6898a1b08b9374106dd671f4c8" dependencies = [ "log", "once_cell", @@ -9296,9 +9275,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.102.7" +version = "0.102.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84678086bd54edf2b415183ed7a94d0efb049f1b646a33e22a36f3794be6ae56" +checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" dependencies = [ "ring", "rustls-pki-types", @@ -9346,9 +9325,9 @@ dependencies = [ [[package]] name = "scc" -version = "2.1.16" +version = "2.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aeb7ac86243095b70a7920639507b71d51a63390d1ba26c4f60a552fbb914a37" +checksum = "0c947adb109a8afce5fc9c7bf951f87f146e9147b3a6a58413105628fb1d1e66" dependencies = [ "sdd", ] @@ -9387,9 +9366,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sdd" -version = "3.0.2" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0495e4577c672de8254beb68d01a9b62d0e8a13c099edecdbedccce3223cd29f" +checksum = "60a7b59a5d9b0099720b417b6325d91a52cbf5b3dcb5041d864be53eefa58abc" [[package]] name = "sec1" @@ -9418,9 +9397,9 @@ dependencies = [ [[package]] name = "secp256k1-sys" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1433bd67156263443f14d603720b082dd3121779323fce20cba2aa07b874bc1b" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" dependencies = [ "cc", ] @@ -9655,9 +9634,9 @@ dependencies = [ [[package]] name = "sha3-asm" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57d79b758b7cb2085612b11a235055e485605a5103faccdd633f35bd7aee69dd" +checksum = "c28efc5e327c837aa837c59eae585fc250715ef939ac32881bcc11677cd02d46" dependencies = [ "cc", "cfg-if", @@ -9906,7 +9885,7 @@ version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" dependencies = [ - "heck 0.5.0", + "heck", "proc-macro2", "quote", "rustversion", @@ -9979,9 +9958,9 @@ dependencies = [ [[package]] name = "syn-solidity" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1e1355d44af21638c8e05d45097db6cb5ec2aa3e970c51cb2901605cf3344fa" +checksum = "4b95156f8b577cb59dc0b1df15c6f29a10afc5f8a7ac9786b0b5c68c19149278" dependencies = [ "paste", "proc-macro2", @@ -10767,9 +10746,9 @@ checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "unicode-normalization" @@ -11075,7 +11054,7 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] From dd61e57e3f336c93787dbbd1bda7725229b2d921 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Fri, 13 Sep 2024 19:12:29 +0200 Subject: [PATCH 65/80] Fix lint --- crates/rpc/ipc/src/server/mod.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/rpc/ipc/src/server/mod.rs b/crates/rpc/ipc/src/server/mod.rs index 28c0f6e8cb4f..11384da50c4c 100644 --- a/crates/rpc/ipc/src/server/mod.rs +++ b/crates/rpc/ipc/src/server/mod.rs @@ -789,6 +789,7 @@ impl Builder { } } +/// Returns a random name for the IPC endpoint. #[cfg(test)] pub fn dummy_name() -> String { let num: u64 = rand::Rng::gen(&mut rand::thread_rng()); From 237a78aa329e7928b4b84e629eb9401a4fc1ca94 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 20:40:31 +0200 Subject: [PATCH 66/80] Fix conflicts eth filter API --- crates/rpc/rpc/src/eth/filter.rs | 84 +++++++++++++++++++------------- 1 file changed, 50 insertions(+), 34 deletions(-) diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 77344702b5ae..728401ea56fa 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -10,13 +10,15 @@ use std::{ time::{Duration, Instant}, }; +use alloy_network::Network; use alloy_primitives::TxHash; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, server::IdProvider}; use reth_chainspec::ChainInfo; +use reth_node_api::EthApiTypes; use reth_primitives::{IntoRecoveredTransaction, TransactionSignedEcRecovered}; use reth_provider::{BlockIdReader, BlockReader, EvmEnvProvider, ProviderError}; -use reth_rpc_eth_api::EthFilterApiServer; +use reth_rpc_eth_api::{EthFilterApiServer, FullEthApiTypes, RpcTransaction, TransactionCompat}; use reth_rpc_eth_types::{ logs_utils::{self, append_matching_block_logs}, EthApiError, EthFilterConfig, EthFilterError, EthStateCache, EthSubscriptionIdProvider, @@ -24,9 +26,9 @@ use reth_rpc_eth_types::{ use reth_rpc_server_types::ToRpcResult; use reth_rpc_types::{ BlockNumHash, Filter, FilterBlockOption, FilterChanges, FilterId, FilteredParams, Log, - PendingTransactionFilterKind, Transaction, WithOtherFields, + PendingTransactionFilterKind, }; -use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; +use reth_rpc_types_compat::transaction::from_recovered; use reth_tasks::TaskSpawner; use reth_transaction_pool::{NewSubpoolTransactionStream, PoolTransaction, TransactionPool}; use tokio::{ @@ -39,14 +41,17 @@ use tracing::trace; const MAX_HEADERS_RANGE: u64 = 1_000; // with ~530bytes per header this is ~500kb /// `Eth` filter RPC implementation. -pub struct EthFilter { +pub struct EthFilter { /// All nested fields bundled together - inner: Arc>>, + inner: Arc>>, /// Assembles response data w.r.t. network. _tx_resp_builder: PhantomData, } -impl Clone for EthFilter { +impl Clone for EthFilter +where + Eth: EthApiTypes, +{ fn clone(&self) -> Self { Self { inner: self.inner.clone(), _tx_resp_builder: PhantomData } } @@ -56,9 +61,7 @@ impl EthFilter where Provider: Send + Sync + 'static, Pool: Send + Sync + 'static, - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - > + 'static, + Eth: EthApiTypes + 'static, { /// Creates a new, shareable instance. /// @@ -79,7 +82,7 @@ where config; let inner = EthFilterInner { provider, - active_filters: Default::default(), + active_filters: ActiveFilters::new(), pool, id_provider: Arc::new(EthSubscriptionIdProvider::default()), eth_cache, @@ -105,7 +108,7 @@ where } /// Returns all currently active filters - pub fn active_filters(&self) -> &ActiveFilters { + pub fn active_filters(&self) -> &ActiveFilters> { &self.inner.active_filters } @@ -144,15 +147,13 @@ where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, ::Transaction: 'static, - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - >, + Eth: FullEthApiTypes, { /// Returns all the filter changes for the given id, if any pub async fn filter_changes( &self, id: FilterId, - ) -> Result, EthFilterError> { + ) -> Result>, EthFilterError> { let info = self.inner.provider.chain_info()?; let best_number = info.best_number; @@ -241,25 +242,25 @@ where } #[async_trait] -impl EthFilterApiServer for EthFilter +impl EthFilterApiServer> + for EthFilter where Provider: BlockReader + BlockIdReader + EvmEnvProvider + 'static, Pool: TransactionPool + 'static, - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - > + Clone - + 'static, + Eth: FullEthApiTypes + 'static, { /// Handler for `eth_newFilter` async fn new_filter(&self, filter: Filter) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_newFilter"); - self.inner.install_filter(FilterKind::::Log(Box::new(filter))).await + self.inner + .install_filter(FilterKind::>::Log(Box::new(filter))) + .await } /// Handler for `eth_newBlockFilter` async fn new_block_filter(&self) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_newBlockFilter"); - self.inner.install_filter(FilterKind::::Block).await + self.inner.install_filter(FilterKind::>::Block).await } /// Handler for `eth_newPendingTransactionFilter` @@ -277,7 +278,8 @@ where } PendingTransactionFilterKind::Full => { let stream = self.inner.pool.new_pending_pool_transactions_listener(); - let full_txs_receiver = FullTransactionsReceiver::<_, Eth>::new(stream); + let full_txs_receiver = + FullTransactionsReceiver::<_, Eth::TransactionCompat>::new(stream); FilterKind::PendingTransaction(PendingTransactionKind::FullTransaction(Arc::new( full_txs_receiver, ))) @@ -291,7 +293,10 @@ where } /// Handler for `eth_getFilterChanges` - async fn filter_changes(&self, id: FilterId) -> RpcResult> { + async fn filter_changes( + &self, + id: FilterId, + ) -> RpcResult>> { trace!(target: "rpc::eth", "Serving eth_getFilterChanges"); Ok(Self::filter_changes(self, id).await?) } @@ -327,7 +332,10 @@ where } } -impl std::fmt::Debug for EthFilter { +impl std::fmt::Debug for EthFilter +where + Eth: EthApiTypes, +{ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EthFilter").finish_non_exhaustive() } @@ -541,6 +549,13 @@ pub struct ActiveFilters { inner: Arc>>>, } +impl ActiveFilters { + /// Returns an empty instance. + pub fn new() -> Self { + Self { inner: Arc::new(Mutex::new(HashMap::new())) } + } +} + /// An installed filter #[derive(Debug)] struct ActiveFilter { @@ -579,15 +594,15 @@ impl PendingTransactionsReceiver { /// A structure to manage and provide access to a stream of full transaction details. #[derive(Debug, Clone)] -struct FullTransactionsReceiver { +struct FullTransactionsReceiver { txs_stream: Arc>>, - _tx_resp_builder: PhantomData, + _tx_resp_builder: PhantomData, } -impl FullTransactionsReceiver +impl FullTransactionsReceiver where T: PoolTransaction + 'static, - Eth: TransactionCompat, + TxCompat: TransactionCompat, { /// Creates a new `FullTransactionsReceiver` encapsulating the provided transaction stream. fn new(stream: NewSubpoolTransactionStream) -> Self { @@ -595,7 +610,7 @@ where } /// Returns all new pending transactions received since the last poll. - async fn drain(&self) -> FilterChanges + async fn drain(&self) -> FilterChanges where T: PoolTransaction, { @@ -603,7 +618,7 @@ where let mut prepared_stream = self.txs_stream.lock().await; while let Ok(tx) = prepared_stream.try_recv() { - pending_txs.push(from_recovered::(tx.transaction.to_recovered_transaction())) + pending_txs.push(from_recovered::(tx.transaction.to_recovered_transaction())) } FilterChanges::Transactions(pending_txs) } @@ -616,12 +631,13 @@ trait FullTransactionsFilter: fmt::Debug + Send + Sync + Unpin + 'static { } #[async_trait] -impl FullTransactionsFilter for FullTransactionsReceiver +impl FullTransactionsFilter + for FullTransactionsReceiver where T: PoolTransaction + 'static, - Eth: TransactionCompat + 'static, + TxCompat: TransactionCompat + 'static, { - async fn drain(&self) -> FilterChanges { + async fn drain(&self) -> FilterChanges { Self::drain(self).await } } From 461e7a735ad0c4d06877ea903ce4d765ad56de23 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 20:41:10 +0200 Subject: [PATCH 67/80] Fix conflicts eth pubsub API --- crates/rpc/rpc/src/eth/pubsub.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 7d36b5220e55..5a2b7dcd14c6 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -10,7 +10,7 @@ use jsonrpsee::{ use reth_network_api::NetworkInfo; use reth_primitives::IntoRecoveredTransaction; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider}; -use reth_rpc_eth_api::pubsub::EthPubSubApiServer; +use reth_rpc_eth_api::{pubsub::EthPubSubApiServer, FullEthApiTypes, RpcTransaction}; use reth_rpc_eth_types::logs_utils; use reth_rpc_server_types::result::{internal_rpc_err, invalid_params_rpc_err}; use reth_rpc_types::{ @@ -71,17 +71,14 @@ impl EthPubSub EthPubSubApiServer +impl EthPubSubApiServer> for EthPubSub where Provider: BlockReader + EvmEnvProvider + Clone + 'static, Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - > + Clone - + 'static, + Eth: FullEthApiTypes + 'static, { /// Handler for `eth_subscribe` async fn subscribe( @@ -113,9 +110,7 @@ where Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - >, + Eth: FullEthApiTypes, { match kind { SubscriptionKind::NewHeads => { @@ -146,7 +141,9 @@ where Params::Bool(true) => { // full transaction objects requested let stream = pubsub.full_pending_transaction_stream().map(|tx| { - EthSubscriptionResult::FullTransaction(Box::new(from_recovered::( + EthSubscriptionResult::FullTransaction(Box::new(from_recovered::< + Eth::TransactionCompat, + >( tx.transaction.to_recovered_transaction(), ))) }); From 89ba917f9c5706fce08c7760c318f095877b3204 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 20:42:15 +0200 Subject: [PATCH 68/80] Fix conflicts rpc builder --- crates/rpc/rpc-builder/src/eth.rs | 8 ++++---- crates/rpc/rpc-builder/src/lib.rs | 13 +++++++++---- crates/rpc/rpc-eth-api/src/helpers/mod.rs | 6 +++--- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index b0aa12a5de43..64314b50754c 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -22,9 +22,9 @@ pub struct EthHandlers { /// The async caching layer used by the eth handlers pub cache: EthStateCache, /// Polling based filter handler available on all transports - pub filter: EthFilter, + pub filter: EthFilter, /// Handler for subscriptions only available for transports that support it (ws, ipc) - pub pubsub: EthPubSub, + pub pubsub: EthPubSub, } impl EthHandlers @@ -139,7 +139,7 @@ impl EthFilterApiBuilder { /// Builds the [`EthFilterApiServer`](reth_rpc_eth_api::EthFilterApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthFilter + ) -> EthFilter where Provider: Send + Sync + Clone + 'static, Pool: Send + Sync + Clone + 'static, @@ -164,7 +164,7 @@ impl EthPubSubApiBuilder { /// Builds the [`EthPubSubApiServer`](reth_rpc_eth_api::EthPubSubApiServer), for given context. pub fn build( ctx: &EthApiBuilderCtx, - ) -> EthPubSub + ) -> EthPubSub where Provider: Clone, Pool: Clone, diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index 64049bcc461c..f7bd0c9bc68a 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -810,7 +810,14 @@ where /// If called outside of the tokio runtime. See also [`Self::eth_api`] pub fn register_ots(&mut self) -> &mut Self where - EthApi: TraceExt + EthTransactions, + EthApi: TraceExt + + EthTransactions< + NetworkTypes: alloy_network::Network< + TransactionResponse = reth_rpc_types::WithOtherFields< + reth_rpc_types::Transaction, + >, + >, + >, { let otterscan_api = self.otterscan_api(); self.modules.insert(RethRpcModule::Ots, otterscan_api.into_rpc().into()); @@ -1087,9 +1094,7 @@ where .into(), RethRpcModule::Web3 => Web3Api::new(self.network.clone()).into_rpc().into(), RethRpcModule::Txpool => { - TxPoolApi::<_, EthApi::TransactionCompat>::new(self.pool.clone()) - .into_rpc() - .into() + TxPoolApi::<_, EthApi>::new(self.pool.clone()).into_rpc().into() } RethRpcModule::Rpc => RPCApi::new( namespaces diff --git a/crates/rpc/rpc-eth-api/src/helpers/mod.rs b/crates/rpc/rpc-eth-api/src/helpers/mod.rs index 73a64078da54..8adb0e281e71 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/mod.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/mod.rs @@ -39,7 +39,7 @@ pub use state::{EthState, LoadState}; pub use trace::Trace; pub use transaction::{EthTransactions, LoadTransaction}; -use crate::EthApiTypes; +use crate::FullEthApiTypes; /// Extension trait that bundles traits needed for tracing transactions. pub trait TraceExt: @@ -53,7 +53,7 @@ impl TraceExt for T where T: LoadTransaction + LoadBlock + LoadPendingBlock + /// /// This trait is automatically implemented for any type that implements all the `Eth` traits. pub trait FullEthApi: - EthApiTypes + FullEthApiTypes + EthApiSpec + EthTransactions + EthBlocks @@ -66,7 +66,7 @@ pub trait FullEthApi: } impl FullEthApi for T where - T: EthApiTypes + T: FullEthApiTypes + EthApiSpec + EthTransactions + EthBlocks From 011b80b653ac47ffef79aa2ce558dfe8044eeb83 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 20:45:32 +0200 Subject: [PATCH 69/80] Fix conflicts tx pool API --- crates/rpc/rpc-api/src/txpool.rs | 15 +++++-------- crates/rpc/rpc/src/txpool.rs | 38 +++++++++++++++----------------- 2 files changed, 23 insertions(+), 30 deletions(-) diff --git a/crates/rpc/rpc-api/src/txpool.rs b/crates/rpc/rpc-api/src/txpool.rs index 34591aa6d4d5..9ad21cf9c95e 100644 --- a/crates/rpc/rpc-api/src/txpool.rs +++ b/crates/rpc/rpc-api/src/txpool.rs @@ -1,14 +1,12 @@ +use alloy_json_rpc::RpcObject; use alloy_primitives::Address; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_rpc_types::{ - txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolStatus}, - Transaction, WithOtherFields, -}; +use reth_rpc_types::txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolStatus}; /// Txpool rpc interface. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "txpool"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "txpool"))] -pub trait TxPoolApi { +pub trait TxPoolApi { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. /// @@ -28,15 +26,12 @@ pub trait TxPoolApi { /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_contentFrom) for more details #[method(name = "contentFrom")] - async fn txpool_content_from( - &self, - from: Address, - ) -> RpcResult>>; + async fn txpool_content_from(&self, from: Address) -> RpcResult>; /// Returns the details of all transactions currently pending for inclusion in the next /// block(s), as well as the ones that are being scheduled for future execution only. /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content) for more details #[method(name = "content")] - async fn txpool_content(&self) -> RpcResult>>; + async fn txpool_content(&self) -> RpcResult>; } diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index cfb7667fa966..576318e99628 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -5,12 +5,14 @@ use async_trait::async_trait; use jsonrpsee::core::RpcResult as Result; use reth_primitives::TransactionSignedEcRecovered; use reth_rpc_api::TxPoolApiServer; +use reth_rpc_eth_api::{FullEthApiTypes, RpcTransaction}; use reth_rpc_types::{ txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, Transaction, WithOtherFields, }; use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; use reth_transaction_pool::{AllPoolTransactions, PoolTransaction, TransactionPool}; +use revm_primitives::TransactTo; use tracing::trace; /// `txpool` API implementation. @@ -34,35 +36,31 @@ impl TxPoolApi where Pool: TransactionPool + 'static, // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - >, + Eth: FullEthApiTypes, { - fn content(&self) -> TxpoolContent { + fn content(&self) -> TxpoolContent> { #[inline] - fn insert( + fn insert( tx: &Tx, - content: &mut BTreeMap>, + content: &mut BTreeMap>, ) where Tx: PoolTransaction, - Eth: TransactionCompat< - Transaction = reth_rpc_types::WithOtherFields, - >, + RpcTxB: TransactionCompat, { - content - .entry(tx.sender()) - .or_default() - .insert(tx.nonce().to_string(), from_recovered::(tx.clone().into_consensus())); + content.entry(tx.sender()).or_default().insert( + tx.nonce().to_string(), + from_recovered::(tx.clone().into_consensus()), + ); } let AllPoolTransactions { pending, queued } = self.pool.all_transactions(); - let mut content = TxpoolContent::>::default(); + let mut content = TxpoolContent { pending: BTreeMap::new(), queued: BTreeMap::new() }; for pending in pending { - insert::<_, Eth>(&pending.transaction, &mut content.pending); + insert::<_, Eth::TransactionCompat>(&pending.transaction, &mut content.pending); } for queued in queued { - insert::<_, Eth>(&queued.transaction, &mut content.queued); + insert::<_, Eth::TransactionCompat>(&queued.transaction, &mut content.queued); } content @@ -70,10 +68,10 @@ where } #[async_trait] -impl TxPoolApiServer for TxPoolApi +impl TxPoolApiServer> for TxPoolApi where Pool: TransactionPool + 'static, - Eth: TransactionCompat> + 'static, + Eth: FullEthApiTypes + 'static, { /// Returns the number of transactions currently pending for inclusion in the next block(s), as /// well as the ones that are being scheduled for future execution only. @@ -135,7 +133,7 @@ where async fn txpool_content_from( &self, from: Address, - ) -> Result> { + ) -> Result>> { trace!(target: "rpc::eth", ?from, "Serving txpool_contentFrom"); Ok(self.content().remove_from(&from)) } @@ -145,7 +143,7 @@ where /// /// See [here](https://geth.ethereum.org/docs/rpc/ns-txpool#txpool_content) for more details /// Handler for `txpool_content` - async fn txpool_content(&self) -> Result>> { + async fn txpool_content(&self) -> Result>> { trace!(target: "rpc::eth", "Serving txpool_content"); Ok(self.content()) } From 87f8f510a811f43f794f74145076b3c35d602a2d Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 21:20:16 +0200 Subject: [PATCH 70/80] Fix conflicts otterscan API --- crates/rpc/rpc-api/src/otterscan.rs | 5 +- crates/rpc/rpc-builder/tests/it/http.rs | 72 ++++++++++++------- .../rpc-types-compat/src/transaction/mod.rs | 10 +++ crates/rpc/rpc/src/eth/helpers/types.rs | 8 +++ crates/rpc/rpc/src/otterscan.rs | 31 ++++---- 5 files changed, 83 insertions(+), 43 deletions(-) diff --git a/crates/rpc/rpc-api/src/otterscan.rs b/crates/rpc/rpc-api/src/otterscan.rs index c025087ff53e..9001299830a4 100644 --- a/crates/rpc/rpc-api/src/otterscan.rs +++ b/crates/rpc/rpc-api/src/otterscan.rs @@ -1,3 +1,4 @@ +use alloy_json_rpc::RpcObject; use alloy_primitives::{Address, Bytes, TxHash, B256}; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; use reth_primitives::BlockId; @@ -12,7 +13,7 @@ use reth_rpc_types::{ /// Otterscan rpc interface. #[cfg_attr(not(feature = "client"), rpc(server, namespace = "ots"))] #[cfg_attr(feature = "client", rpc(server, client, namespace = "ots"))] -pub trait Otterscan { +pub trait Otterscan { /// Get the block header by block number, required by otterscan. /// Otterscan currently requires this endpoint, used as: /// @@ -62,7 +63,7 @@ pub trait Otterscan { block_number: u64, page_number: usize, page_size: usize, - ) -> RpcResult>>; + ) -> RpcResult>; /// Gets paginated inbound/outbound transaction calls for a certain address. #[method(name = "searchTransactionsBefore")] diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index 500631427cb2..d7289d217432 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -398,45 +398,69 @@ where let nonce = 1; let block_hash = B256::default(); - OtterscanClient::get_header_by_number(client, block_number).await.unwrap(); + OtterscanClient::::get_header_by_number(client, block_number).await.unwrap(); - OtterscanClient::has_code(client, address, None).await.unwrap(); - OtterscanClient::has_code(client, address, Some(block_number.into())).await.unwrap(); - - OtterscanClient::get_api_level(client).await.unwrap(); + OtterscanClient::::has_code(client, address, None).await.unwrap(); + OtterscanClient::::has_code(client, address, Some(block_number.into())) + .await + .unwrap(); - OtterscanClient::get_internal_operations(client, tx_hash).await.unwrap(); + OtterscanClient::::get_api_level(client).await.unwrap(); - OtterscanClient::get_transaction_error(client, tx_hash).await.unwrap(); + OtterscanClient::::get_internal_operations(client, tx_hash).await.unwrap(); - OtterscanClient::trace_transaction(client, tx_hash).await.unwrap(); + OtterscanClient::::get_transaction_error(client, tx_hash).await.unwrap(); - OtterscanClient::get_block_details(client, block_number).await.unwrap_err(); + OtterscanClient::::trace_transaction(client, tx_hash).await.unwrap(); - OtterscanClient::get_block_details_by_hash(client, block_hash).await.unwrap_err(); + OtterscanClient::::get_block_details(client, block_number).await.unwrap_err(); - OtterscanClient::get_block_transactions(client, block_number, page_number, page_size) + OtterscanClient::::get_block_details_by_hash(client, block_hash) .await - .err() - .unwrap(); + .unwrap_err(); + + OtterscanClient::::get_block_transactions( + client, + block_number, + page_number, + page_size, + ) + .await + .err() + .unwrap(); assert!(is_unimplemented( - OtterscanClient::search_transactions_before(client, address, block_number, page_size,) - .await - .err() - .unwrap() + OtterscanClient::::search_transactions_before( + client, + address, + block_number, + page_size, + ) + .await + .err() + .unwrap() )); assert!(is_unimplemented( - OtterscanClient::search_transactions_after(client, address, block_number, page_size,) - .await - .err() - .unwrap() - )); - assert!(OtterscanClient::get_transaction_by_sender_and_nonce(client, sender, nonce) + OtterscanClient::::search_transactions_after( + client, + address, + block_number, + page_size, + ) .await .err() + .unwrap() + )); + assert!(OtterscanClient::::get_transaction_by_sender_and_nonce( + client, sender, nonce + ) + .await + .err() + .is_none()); + assert!(OtterscanClient::::get_contract_creator(client, address) + .await + .unwrap() .is_none()); - assert!(OtterscanClient::get_contract_creator(client, address).await.unwrap().is_none()); } #[tokio::test(flavor = "multi_thread")] diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 28046457146d..ea307439b597 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -67,6 +67,10 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { /// Create a new rpc transaction result for a _pending_ signed transaction, setting block /// environment related fields to `None`. fn fill(tx: TransactionSignedEcRecovered, tx_inf: TransactionInfo) -> Self::Transaction; + + fn otterscan_api_truncate_input(tx: &mut Self::Transaction); + + fn tx_type(tx: &Self::Transaction) -> u8; } impl TransactionCompat for () { @@ -77,6 +81,12 @@ impl TransactionCompat for () { fn fill(_tx: TransactionSignedEcRecovered, _tx_info: TransactionInfo) -> Self::Transaction { WithOtherFields::default() } + + fn otterscan_api_truncate_input(_tx: &mut Self::Transaction) {} + + fn tx_type(tx: &Self::Transaction) -> u8 { + 0 + } } /// Gas price and max fee per gas for a transaction. Helper type to format transaction RPC response. diff --git a/crates/rpc/rpc/src/eth/helpers/types.rs b/crates/rpc/rpc/src/eth/helpers/types.rs index 0469a6908a9b..0047f3636386 100644 --- a/crates/rpc/rpc/src/eth/helpers/types.rs +++ b/crates/rpc/rpc/src/eth/helpers/types.rs @@ -74,4 +74,12 @@ where ..Default::default() } } + + fn otterscan_api_truncate_input(tx: &mut Self::Transaction) { + tx.inner.input = tx.inner.input.slice(..4); + } + + fn tx_type(tx: &Self::Transaction) -> u8 { + tx.inner.transaction_type.unwrap_or(0) + } } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 3d0cdae15fac..21b26eeacaa5 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -1,12 +1,12 @@ -use alloy_network::ReceiptResponse; +use alloy_network::{ReceiptResponse, TransactionResponse}; use alloy_primitives::{Address, Bytes, TxHash, B256, U256}; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, types::ErrorObjectOwned}; -use reth_primitives::{BlockId, BlockNumberOrTag}; +use reth_primitives::{BlockId, BlockNumberOrTag, Transaction}; use reth_rpc_api::{EthApiServer, OtterscanServer}; use reth_rpc_eth_api::{ helpers::{EthTransactions, TraceExt}, - FullEthApiTypes, RpcBlock, RpcReceipt, RpcTransaction, + FullEthApiTypes, RpcBlock, RpcReceipt, RpcTransaction, TransactionCompat, }; use reth_rpc_eth_types::{utils::binary_search, EthApiError}; use reth_rpc_server_types::result::internal_rpc_err; @@ -18,7 +18,7 @@ use reth_rpc_types::{ }, parity::{Action, CreateAction, CreateOutput, TraceOutput}, }, - BlockTransactions, Header, Transaction, TransactionReceipt, WithOtherFields, + BlockTransactions, Header, TransactionReceipt, }; use revm_inspectors::{ tracing::{types::CallTraceNode, TracingInspectorConfig}, @@ -62,18 +62,15 @@ where } #[async_trait] -impl OtterscanServer for OtterscanApi +impl OtterscanServer> for OtterscanApi where Eth: EthApiServer< RpcTransaction, RpcBlock, RpcReceipt, - > + TraceExt - + EthTransactions< - NetworkTypes: alloy_network::Network< - TransactionResponse = reth_rpc_types::WithOtherFields, - >, - > + 'static, + > + EthTransactions + + TraceExt + + 'static, { /// Handler for `{ots,erigon}_getHeaderByNumber` async fn get_header_by_number(&self, block_number: u64) -> RpcResult> { @@ -200,7 +197,7 @@ where block_number: u64, page_number: usize, page_size: usize, - ) -> RpcResult>> { + ) -> RpcResult>> { let block_id = block_number.into(); // retrieve full block and its receipts let block = self.eth.block_by_number(block_id, true); @@ -233,9 +230,9 @@ where // The input field returns only the 4 bytes method selector instead of the entire // calldata byte blob. - for tx in transactions { - if tx.input.len() > 4 { - tx.input = tx.input.slice(..4); + for tx in transactions.iter_mut() { + if tx.input().len() > 4 { + Eth::TransactionCompat::otterscan_api_truncate_input(tx); } } @@ -243,7 +240,7 @@ where let timestamp = Some(block.header.timestamp); let receipts = receipts .drain(page_start..page_end) - .zip(transactions.iter().map(|tx| tx.inner.transaction_type.unwrap_or(0))) + .zip(transactions.iter().map(|tx| Eth::TransactionCompat::tx_type(tx))) .map(|(receipt, tx_ty)| { let inner = OtsReceipt { status: receipt.status(), @@ -313,7 +310,7 @@ where .get_transaction_by_sender_and_nonce(sender, nonce, false) .await .map_err(Into::into)? - .map(|tx| tx.hash)) + .map(|tx| tx.tx_hash())) } /// Handler for `getContractCreator` From 15112eb32e74078231c1615615611aebd8dfbf93 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 21:30:18 +0200 Subject: [PATCH 71/80] Fix conflicts optimism --- Cargo.lock | 3 -- crates/optimism/node/src/node.rs | 3 +- crates/optimism/rpc/Cargo.toml | 1 - crates/optimism/rpc/src/eth/block.rs | 34 ++++++------- crates/optimism/rpc/src/eth/call.rs | 4 +- crates/optimism/rpc/src/eth/mod.rs | 46 +++++++----------- crates/optimism/rpc/src/eth/pending_block.rs | 2 +- crates/optimism/rpc/src/eth/receipt.rs | 35 ++++++-------- crates/optimism/rpc/src/eth/transaction.rs | 50 ++++++++++---------- crates/optimism/rpc/src/lib.rs | 2 +- 10 files changed, 81 insertions(+), 99 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 53c6b1c06135..9fe6abeff858 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7640,7 +7640,6 @@ dependencies = [ name = "reth-node-builder" version = "1.0.6" dependencies = [ - "alloy-network", "alloy-primitives", "aquamarine", "eyre", @@ -7686,7 +7685,6 @@ dependencies = [ "reth-rpc-eth-types", "reth-rpc-layer", "reth-rpc-types", - "reth-rpc-types-compat", "reth-stages", "reth-static-file", "reth-tasks", @@ -8027,7 +8025,6 @@ dependencies = [ "reth-rpc-eth-types", "reth-rpc-server-types", "reth-rpc-types", - "reth-rpc-types-compat", "reth-tasks", "reth-transaction-pool", "revm", diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index c55ac5f76d39..d4fabdbf1144 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -21,7 +21,6 @@ use reth_optimism_consensus::OptimismBeaconConsensus; use reth_optimism_rpc::OpEthApi; use reth_payload_builder::{PayloadBuilderHandle, PayloadBuilderService}; use reth_provider::CanonStateSubscriptions; -use reth_rpc::eth::EthTxBuilder; use reth_tracing::tracing::{debug, info}; use reth_transaction_pool::{ blobstore::DiskFileBlobStore, CoinbaseTipOrdering, TransactionPool, @@ -115,7 +114,7 @@ impl NodeTypesWithEngine for OptimismNode { pub struct OptimismAddOns; impl NodeAddOns for OptimismAddOns { - type EthApi = OpEthApi; + type EthApi = OpEthApi; } /// A regular optimism evm and executor builder. diff --git a/crates/optimism/rpc/Cargo.toml b/crates/optimism/rpc/Cargo.toml index 15f911f52611..0f4b87d5302a 100644 --- a/crates/optimism/rpc/Cargo.toml +++ b/crates/optimism/rpc/Cargo.toml @@ -25,7 +25,6 @@ reth-tasks = { workspace = true, features = ["rayon"] } reth-transaction-pool.workspace = true reth-rpc.workspace = true reth-node-api.workspace = true -reth-rpc-types-compat.workspace = true reth-network-api.workspace = true reth-node-builder.workspace = true reth-chainspec.workspace = true diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index 180373697328..ac1a060f53a4 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -1,24 +1,26 @@ //! Loads and formats OP block RPC response. -use reth_chainspec::ChainSpec; +use op_alloy_network::Network; +use op_alloy_rpc_types::OpTransactionReceipt; +use reth_chainspec::{ChainSpec, ChainSpecProvider}; use reth_node_api::{FullNodeComponents, NodeTypes}; use reth_primitives::TransactionMeta; use reth_provider::{BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_api::{ - helpers::{ - EthApiSpec, EthBlocks, LoadBlock, LoadPendingBlock, LoadReceipt, LoadTransaction, - SpawnBlocking, - }, - FromEthApiError, + helpers::{EthBlocks, LoadBlock, LoadPendingBlock, LoadReceipt, SpawnBlocking}, + RpcReceipt, }; -use reth_rpc_eth_types::{EthStateCache, ReceiptBuilder}; -use reth_rpc_types::{AnyTransactionReceipt, BlockId}; +use reth_rpc_eth_types::EthStateCache; +use reth_rpc_types::BlockId; -use crate::{OpEthApi, OpEthApiError}; +use crate::{OpEthApi, OpEthApiError, OpReceiptBuilder}; -impl EthBlocks for OpEthApi +impl EthBlocks for OpEthApi where - Self: EthApiSpec + LoadBlock + LoadTransaction, + Self: LoadBlock< + Error = OpEthApiError, + NetworkTypes: Network, + >, N: FullNodeComponents>, { #[inline] @@ -44,7 +46,7 @@ where let l1_block_info = reth_evm_optimism::extract_l1_info(&block).map_err(OpEthApiError::from)?; - let receipts = block + return block .body .into_iter() .zip(receipts.iter()) @@ -61,7 +63,7 @@ where }; Ok(OpReceiptBuilder::new( - self.provider().chain_spec(), + &self.inner.provider().chain_spec(), tx, meta, receipt, @@ -70,15 +72,15 @@ where )? .build()) }) - .collect::, Self::Error>>(); - return receipts.map(Some) + .collect::, Self::Error>>() + .map(Some) } Ok(None) } } -impl LoadBlock for OpEthApi +impl LoadBlock for OpEthApi where Self: LoadPendingBlock + SpawnBlocking, N: FullNodeComponents, diff --git a/crates/optimism/rpc/src/eth/call.rs b/crates/optimism/rpc/src/eth/call.rs index 1da1129a62e2..40e7a6aa2049 100644 --- a/crates/optimism/rpc/src/eth/call.rs +++ b/crates/optimism/rpc/src/eth/call.rs @@ -12,14 +12,14 @@ use reth_rpc_types::TransactionRequest; use crate::{OpEthApi, OpEthApiError}; -impl EthCall for OpEthApi +impl EthCall for OpEthApi where Self: Call, N: FullNodeComponents>, { } -impl Call for OpEthApi +impl Call for OpEthApi where Self: LoadState + SpawnBlocking, Self::Error: From, diff --git a/crates/optimism/rpc/src/eth/mod.rs b/crates/optimism/rpc/src/eth/mod.rs index 6e384a45c73e..76da8c6c7941 100644 --- a/crates/optimism/rpc/src/eth/mod.rs +++ b/crates/optimism/rpc/src/eth/mod.rs @@ -9,11 +9,11 @@ mod pending_block; pub use receipt::{OpReceiptBuilder, OpReceiptFieldsBuilder}; -use std::{fmt, marker::PhantomData, sync::Arc}; +use std::{fmt, sync::Arc}; use alloy_primitives::U256; use derive_more::Deref; -use op_alloy_network::{Network, Optimism}; +use op_alloy_network::Optimism; use reth_chainspec::ChainSpec; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; @@ -60,18 +60,16 @@ pub type EthApiNodeBackend = EthApiInner< /// This type implements the [`FullEthApi`](reth_rpc_eth_api::helpers::FullEthApi) by implemented /// all the `Eth` helper traits and prerequisite traits. #[derive(Clone, Deref)] -pub struct OpEthApi { +pub struct OpEthApi { /// Gateway to node's core components. #[deref] inner: Arc>, /// Sequencer client, configured to forward submitted transactions to sequencer of given OP /// network. sequencer_client: OnceCell, - /// L1 RPC type builders. - _eth_ty_builders: PhantomData, } -impl OpEthApi { +impl OpEthApi { /// Creates a new instance for given context. #[allow(clippy::type_complexity)] pub fn with_spawner(ctx: &EthApiBuilderCtx) -> Self { @@ -93,26 +91,21 @@ impl OpEthApi { ctx.config.proof_permits, ); - Self { - inner: Arc::new(inner), - sequencer_client: OnceCell::new(), - _eth_ty_builders: PhantomData, - } + Self { inner: Arc::new(inner), sequencer_client: OnceCell::new() } } } -impl EthApiTypes for OpEthApi +impl EthApiTypes for OpEthApi where Self: Send + Sync, N: FullNodeComponents, - Eth: TransactionCompat::TransactionResponse>, { type Error = OpEthApiError; type NetworkTypes = Optimism; - type TransactionCompat = OpTxBuilder; + type TransactionCompat = OpTxBuilder; } -impl EthApiSpec for OpEthApi +impl EthApiSpec for OpEthApi where Self: Send + Sync, N: FullNodeComponents>, @@ -141,11 +134,10 @@ where } } -impl SpawnBlocking for OpEthApi +impl SpawnBlocking for OpEthApi where Self: Send + Sync + Clone + 'static, N: FullNodeComponents, - Eth: TransactionCompat::TransactionResponse>, { #[inline] fn io_task_spawner(&self) -> impl TaskSpawner { @@ -163,7 +155,7 @@ where } } -impl LoadFee for OpEthApi +impl LoadFee for OpEthApi where Self: LoadBlock, N: FullNodeComponents>, @@ -191,11 +183,10 @@ where } } -impl LoadState for OpEthApi +impl LoadState for OpEthApi where - Self: Send + Sync, + Self: Send + Sync + Clone, N: FullNodeComponents>, - Eth: TransactionCompat::TransactionResponse>, { #[inline] fn provider(&self) -> impl StateProviderFactory + ChainSpecProvider { @@ -213,7 +204,7 @@ where } } -impl EthState for OpEthApi +impl EthState for OpEthApi where Self: LoadState + SpawnBlocking, N: FullNodeComponents, @@ -224,14 +215,14 @@ where } } -impl EthFees for OpEthApi +impl EthFees for OpEthApi where Self: LoadFee, N: FullNodeComponents, { } -impl Trace for OpEthApi +impl Trace for OpEthApi where Self: LoadState, N: FullNodeComponents, @@ -242,7 +233,7 @@ where } } -impl AddDevSigners for OpEthApi +impl AddDevSigners for OpEthApi where N: FullNodeComponents>, { @@ -251,11 +242,10 @@ where } } -impl BuilderProvider for OpEthApi +impl BuilderProvider for OpEthApi where Self: Send, N: FullNodeComponents, - Eth: TransactionCompat::TransactionResponse> + 'static, { type Ctx<'a> = &'a EthApiBuilderCtx; @@ -264,7 +254,7 @@ where } } -impl fmt::Debug for OpEthApi { +impl fmt::Debug for OpEthApi { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("OpEthApi").finish_non_exhaustive() } diff --git a/crates/optimism/rpc/src/eth/pending_block.rs b/crates/optimism/rpc/src/eth/pending_block.rs index 95c6d72cb23f..3b9fe2e20554 100644 --- a/crates/optimism/rpc/src/eth/pending_block.rs +++ b/crates/optimism/rpc/src/eth/pending_block.rs @@ -20,7 +20,7 @@ use reth_transaction_pool::TransactionPool; use crate::OpEthApi; -impl LoadPendingBlock for OpEthApi +impl LoadPendingBlock for OpEthApi where Self: SpawnBlocking, N: FullNodeComponents>, diff --git a/crates/optimism/rpc/src/eth/receipt.rs b/crates/optimism/rpc/src/eth/receipt.rs index 2e64512ef43c..782ebb15ab6b 100644 --- a/crates/optimism/rpc/src/eth/receipt.rs +++ b/crates/optimism/rpc/src/eth/receipt.rs @@ -9,18 +9,15 @@ use reth_evm_optimism::RethL1BlockInfo; use reth_node_api::{FullNodeComponents, NodeTypes}; use reth_primitives::{Receipt, TransactionMeta, TransactionSigned, TxType}; use reth_provider::ChainSpecProvider; -use reth_rpc_eth_api::{ - helpers::{EthApiSpec, LoadReceipt, LoadTransaction}, - FromEthApiError, -}; +use reth_rpc_eth_api::{helpers::LoadReceipt, FromEthApiError, RpcReceipt}; use reth_rpc_eth_types::{EthApiError, EthStateCache, ReceiptBuilder}; -use reth_rpc_types::{AnyReceiptEnvelope, AnyTransactionReceipt, Log, TransactionReceipt}; +use reth_rpc_types::{AnyReceiptEnvelope, Log, TransactionReceipt}; use crate::{OpEthApi, OpEthApiError}; -impl LoadReceipt for OpEthApi +impl LoadReceipt for OpEthApi where - Self: EthApiSpec + LoadTransaction, + Self: Send + Sync, N: FullNodeComponents>, { #[inline] @@ -46,23 +43,19 @@ where let l1_block_info = reth_evm_optimism::extract_l1_info(&block).map_err(OpEthApiError::from)?; - let op_receipt_meta = self - .build_op_receipt_meta( - self.provider().chain_spec(), - &tx, - l1_block_info, - &receipt, - l1_block_info, - ) - .map_err(OpEthApiError::from)?; - - let receipt_resp = OpReceiptBuilder::new(&tx, meta, &receipt, &receipts)?.build(); - - Ok(receipt_resp) + Ok(OpReceiptBuilder::new( + &self.inner.provider().chain_spec(), + &tx, + meta, + &receipt, + &receipts, + l1_block_info, + )? + .build()) } } -impl OpEthApi +impl OpEthApi where N: FullNodeComponents>, { diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index d59365db6006..21923c21aa1b 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -1,26 +1,22 @@ //! Loads and formats OP transaction RPC response. -use std::marker::PhantomData; - use alloy_primitives::{Bytes, B256}; -use op_alloy_network::{Network, Optimism}; -use op_alloy_rpc_types::OptimismTransactionFields; -use reth_evm_optimism::RethL1BlockInfo; +use op_alloy_rpc_types::Transaction; use reth_node_api::FullNodeComponents; use reth_primitives::TransactionSignedEcRecovered; use reth_provider::{BlockReaderIdExt, TransactionsProvider}; +use reth_rpc::eth::EthTxBuilder; use reth_rpc_eth_api::{ - helpers::{EthApiSpec, EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - FromEthApiError, TransactionCompat, + helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, + FromEthApiError, FullEthApiTypes, TransactionCompat, }; use reth_rpc_eth_types::{utils::recover_raw_transaction, EthStateCache}; use reth_rpc_types::TransactionInfo; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; -use revm::L1BlockInfo; use crate::{OpEthApi, SequencerClient}; -impl EthTransactions for OpEthApi +impl EthTransactions for OpEthApi where Self: LoadTransaction, N: FullNodeComponents, @@ -60,9 +56,9 @@ where } } -impl LoadTransaction for OpEthApi +impl LoadTransaction for OpEthApi where - Self: SpawnBlocking, + Self: SpawnBlocking + FullEthApiTypes, N: FullNodeComponents, { type Pool = N::Pool; @@ -80,7 +76,7 @@ where } } -impl OpEthApi +impl OpEthApi where N: FullNodeComponents, { @@ -99,28 +95,34 @@ where } /// Builds OP transaction response type. -#[derive(Debug, Clone, Copy)] -pub struct OpTxBuilder { - _l1_builders: PhantomData, -} +#[derive(Clone, Debug, Copy)] +pub struct OpTxBuilder; -impl::TransactionResponse>> - TransactionCompat for OpTxBuilder -{ - type Transaction = ::TransactionResponse; +impl TransactionCompat for OpTxBuilder { + type Transaction = Transaction; fn fill(tx: TransactionSignedEcRecovered, tx_info: TransactionInfo) -> Self::Transaction { let signed_tx = tx.clone().into_signed(); - let mut resp = Eth::fill(tx, tx_info); + let inner = EthTxBuilder::fill(tx, tx_info).inner; - resp.other = OptimismTransactionFields { + Transaction { + inner, source_hash: signed_tx.source_hash(), mint: signed_tx.mint(), is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), + deposit_receipt_version: None, // todo: how to fill this field? } - .into(); + } + + /// Truncates the input of a transaction to only the first 4 bytes. + fn otterscan_api_truncate_input(tx: &mut Self::Transaction) { + tx.inner.input = tx.inner.input.slice(..4); + } - resp + /// Returns the transaction type. + // todo: remove when alloy TransactionResponse trait it updated. + fn tx_type(tx: &Self::Transaction) -> u8 { + tx.inner.transaction_type.unwrap_or_default() } } diff --git a/crates/optimism/rpc/src/lib.rs b/crates/optimism/rpc/src/lib.rs index 7ab2843f9643..e3fef7adb5b7 100644 --- a/crates/optimism/rpc/src/lib.rs +++ b/crates/optimism/rpc/src/lib.rs @@ -15,5 +15,5 @@ pub mod eth; pub mod sequencer; pub use error::{OpEthApiError, OptimismInvalidTransactionError, SequencerClientError}; -pub use eth::{transaction::OpTxBuilder, OpEthApi}; +pub use eth::{transaction::OpTxBuilder, OpEthApi, OpReceiptBuilder}; pub use sequencer::SequencerClient; From 4794fd483f073d91533f3728de2e744c17824f15 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 22:26:03 +0200 Subject: [PATCH 72/80] Fix lint --- crates/e2e-test-utils/src/lib.rs | 5 +---- crates/e2e-test-utils/src/node.rs | 11 ++++++----- crates/e2e-test-utils/src/rpc.rs | 8 ++------ crates/node/builder/Cargo.toml | 2 -- crates/node/builder/src/builder/mod.rs | 6 +----- crates/node/builder/src/launch/engine.rs | 5 +---- crates/node/builder/src/launch/mod.rs | 5 +---- crates/node/builder/src/rpc.rs | 2 +- crates/rpc/rpc-api/src/otterscan.rs | 2 +- crates/rpc/rpc-builder/src/eth.rs | 2 +- crates/rpc/rpc-builder/src/lib.rs | 2 -- crates/rpc/rpc/src/eth/filter.rs | 1 - crates/rpc/rpc/src/eth/helpers/block.rs | 6 +++--- crates/rpc/rpc/src/eth/pubsub.rs | 2 +- crates/rpc/rpc/src/otterscan.rs | 4 ++-- crates/rpc/rpc/src/txpool.rs | 6 ++---- 16 files changed, 23 insertions(+), 46 deletions(-) diff --git a/crates/e2e-test-utils/src/lib.rs b/crates/e2e-test-utils/src/lib.rs index c4f1315e220b..3d2961cf8cd9 100644 --- a/crates/e2e-test-utils/src/lib.rs +++ b/crates/e2e-test-utils/src/lib.rs @@ -7,10 +7,7 @@ use reth::{ args::{DiscoveryArgs, NetworkArgs, RpcServerArgs}, builder::{NodeBuilder, NodeConfig, NodeHandle}, network::PeersHandleProvider, - rpc::{ - api::eth::{helpers::AddDevSigners, FullEthApiServer}, - types::AnyTransactionReceipt, - }, + rpc::api::eth::{helpers::AddDevSigners, FullEthApiServer}, tasks::TaskManager, }; use reth_chainspec::ChainSpec; diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 2d370db262d3..21d8c97b0422 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -1,6 +1,5 @@ use std::{marker::PhantomData, pin::Pin}; -use alloy_network::Network; use alloy_rpc_types::BlockNumberOrTag; use eyre::Ok; use futures_util::Future; @@ -10,14 +9,16 @@ use reth::{ network::PeersHandleProvider, providers::{BlockReader, BlockReaderIdExt, CanonStateSubscriptions, StageCheckpointReader}, rpc::{ - api::eth::helpers::{EthApiSpec, EthTransactions, TraceExt}, - types::{engine::PayloadStatusEnum, AnyTransactionReceipt}, + api::eth::{ + helpers::{EthApiSpec, EthTransactions, TraceExt}, + FullEthApiTypes, + }, + types::engine::PayloadStatusEnum, }, }; use reth_chainspec::ChainSpec; -use reth_node_builder::{EthApiTypes, NodeAddOns, NodeTypesWithEngine}; +use reth_node_builder::{NodeAddOns, NodeTypesWithEngine}; use reth_primitives::{BlockHash, BlockNumber, Bytes, B256}; -use reth_rpc_types::WithOtherFields; use reth_stages_types::StageId; use tokio_stream::StreamExt; diff --git a/crates/e2e-test-utils/src/rpc.rs b/crates/e2e-test-utils/src/rpc.rs index 3c613b055df4..d0a0d55f0681 100644 --- a/crates/e2e-test-utils/src/rpc.rs +++ b/crates/e2e-test-utils/src/rpc.rs @@ -1,19 +1,15 @@ use alloy_consensus::TxEnvelope; -use alloy_network::{eip2718::Decodable2718, Network}; +use alloy_network::eip2718::Decodable2718; use reth::{ builder::{rpc::RpcRegistry, FullNodeComponents}, rpc::api::{ - eth::{ - helpers::{EthApiSpec, EthTransactions, TraceExt}, - RpcTransaction, - }, + eth::helpers::{EthApiSpec, EthTransactions, TraceExt}, DebugApiServer, }, }; use reth_chainspec::ChainSpec; use reth_node_builder::{EthApiTypes, NodeTypes}; use reth_primitives::{Bytes, B256}; -use reth_rpc_types::{AnyTransactionReceipt, WithOtherFields}; #[allow(missing_debug_implementations)] pub struct RpcTestContext { diff --git a/crates/node/builder/Cargo.toml b/crates/node/builder/Cargo.toml index 4f897ed646bf..cd4b4a7b9278 100644 --- a/crates/node/builder/Cargo.toml +++ b/crates/node/builder/Cargo.toml @@ -55,12 +55,10 @@ reth-stages.workspace = true reth-static-file.workspace = true reth-tasks.workspace = true reth-tokio-util.workspace = true -reth-rpc-types-compat.workspace = true reth-tracing.workspace = true reth-transaction-pool.workspace = true ## ethereum -alloy-network.workspace = true alloy-primitives.workspace = true ## async diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index c2e4dce7a913..3dc8b12ee3d9 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -5,7 +5,6 @@ pub mod add_ons; mod states; -use alloy_network::Network; pub use states::*; use std::sync::Arc; @@ -30,10 +29,7 @@ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, node_config::NodeConfig, primitives::Head, - rpc::{ - eth::{helpers::AddDevSigners, FullEthApiServer}, - types::AnyTransactionReceipt, - }, + rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, }; use reth_primitives::revm_primitives::EnvKzgSettings; use reth_provider::{providers::BlockchainProvider, ChainSpecProvider, FullProvider}; diff --git a/crates/node/builder/src/launch/engine.rs b/crates/node/builder/src/launch/engine.rs index f56c43218ba3..c82f5278aaf9 100644 --- a/crates/node/builder/src/launch/engine.rs +++ b/crates/node/builder/src/launch/engine.rs @@ -24,10 +24,7 @@ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, primitives::Head, - rpc::{ - eth::{helpers::AddDevSigners, FullEthApiServer}, - types::AnyTransactionReceipt, - }, + rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index 2f20c2467eab..1c2764fdbf6d 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -27,10 +27,7 @@ use reth_node_api::{ use reth_node_core::{ dirs::{ChainPath, DataDirPath}, exit::NodeExitFuture, - rpc::{ - eth::{helpers::AddDevSigners, FullEthApiServer}, - types::AnyTransactionReceipt, - }, + rpc::eth::{helpers::AddDevSigners, FullEthApiServer}, version::{CARGO_PKG_VERSION, CLIENT_CODE, NAME_CLIENT, VERGEN_GIT_SHA}, }; use reth_node_events::{cl::ConsensusLayerHealthEvents, node}; diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 4f2cbf1d3cbe..00d10a8f5d92 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -12,7 +12,7 @@ use reth_node_core::{ node_config::NodeConfig, rpc::{ api::EngineApiServer, - eth::{EthApiTypes, FullEthApiServer, RpcTransaction}, + eth::{EthApiTypes, FullEthApiServer}, }, }; use reth_payload_builder::PayloadBuilderHandle; diff --git a/crates/rpc/rpc-api/src/otterscan.rs b/crates/rpc/rpc-api/src/otterscan.rs index 9001299830a4..3fc4cd2b386f 100644 --- a/crates/rpc/rpc-api/src/otterscan.rs +++ b/crates/rpc/rpc-api/src/otterscan.rs @@ -7,7 +7,7 @@ use reth_rpc_types::{ BlockDetails, ContractCreator, InternalOperation, OtsBlockTransactions, TraceEntry, TransactionsWithReceipts, }, - Header, Transaction, WithOtherFields, + Header, }; /// Otterscan rpc interface. diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index 64314b50754c..5b13214e7129 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -3,7 +3,7 @@ use std::marker::PhantomData; use reth_evm::ConfigureEvm; use reth_provider::{BlockReader, CanonStateSubscriptions, EvmEnvProvider, StateProviderFactory}; use reth_rpc::{EthFilter, EthPubSub}; -use reth_rpc_eth_api::{EthApiTypes, TransactionCompat}; +use reth_rpc_eth_api::EthApiTypes; use reth_rpc_eth_types::{ cache::cache_new_blocks_task, EthApiBuilderCtx, EthConfig, EthStateCache, }; diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index f7bd0c9bc68a..a856afa39a22 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -166,7 +166,6 @@ use reth_rpc_api::servers::*; use reth_rpc_eth_api::{ helpers::{Call, EthApiSpec, EthTransactions, LoadPendingBlock, TraceExt}, EthApiServer, EthApiTypes, FullEthApiServer, RpcBlock, RpcReceipt, RpcTransaction, - TransactionCompat, }; use reth_rpc_eth_types::{EthConfig, EthStateCache, EthSubscriptionIdProvider}; use reth_rpc_layer::{AuthLayer, Claims, JwtAuthValidator, JwtSecret}; @@ -207,7 +206,6 @@ pub use eth::EthHandlers; // Rpc server metrics mod metrics; pub use metrics::{MeteredRequestFuture, RpcRequestMetricsService}; -use reth_node_core::rpc::types::AnyTransactionReceipt; /// Convenience function for starting a server in one step. #[allow(clippy::too_many_arguments)] diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 728401ea56fa..2b6a7f79796b 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -10,7 +10,6 @@ use std::{ time::{Duration, Instant}, }; -use alloy_network::Network; use alloy_primitives::TxHash; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, server::IdProvider}; diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index af239b0f1b8c..3cc12c443d4a 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -39,7 +39,7 @@ where let timestamp = block.timestamp; let block = block.unseal(); - let receipts = block + return block .body .into_iter() .zip(receipts.iter()) @@ -58,8 +58,8 @@ where ReceiptBuilder::new(&tx, meta, receipt, &receipts) .map(|builder| builder.build()) }) - .collect::, Self::Error>>(); - return receipts.map(Some) + .collect::, Self::Error>>() + .map(Some) } Ok(None) diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 5a2b7dcd14c6..950489880b4d 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -20,7 +20,7 @@ use reth_rpc_types::{ }, FilteredParams, Header, Log, Transaction, WithOtherFields, }; -use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; +use reth_rpc_types_compat::transaction::from_recovered; use reth_tasks::{TaskSpawner, TokioTaskExecutor}; use reth_transaction_pool::{NewTransactionEvent, TransactionPool}; use serde::Serialize; diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 21b26eeacaa5..d88ec7a85322 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -2,7 +2,7 @@ use alloy_network::{ReceiptResponse, TransactionResponse}; use alloy_primitives::{Address, Bytes, TxHash, B256, U256}; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, types::ErrorObjectOwned}; -use reth_primitives::{BlockId, BlockNumberOrTag, Transaction}; +use reth_primitives::{BlockId, BlockNumberOrTag}; use reth_rpc_api::{EthApiServer, OtterscanServer}; use reth_rpc_eth_api::{ helpers::{EthTransactions, TraceExt}, @@ -240,7 +240,7 @@ where let timestamp = Some(block.header.timestamp); let receipts = receipts .drain(page_start..page_end) - .zip(transactions.iter().map(|tx| Eth::TransactionCompat::tx_type(tx))) + .zip(transactions.iter().map(Eth::TransactionCompat::tx_type)) .map(|(receipt, tx_ty)| { let inner = OtsReceipt { status: receipt.status(), diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 576318e99628..eb2ad8bbca77 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -6,13 +6,11 @@ use jsonrpsee::core::RpcResult as Result; use reth_primitives::TransactionSignedEcRecovered; use reth_rpc_api::TxPoolApiServer; use reth_rpc_eth_api::{FullEthApiTypes, RpcTransaction}; -use reth_rpc_types::{ - txpool::{TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus}, - Transaction, WithOtherFields, +use reth_rpc_types::txpool::{ + TxpoolContent, TxpoolContentFrom, TxpoolInspect, TxpoolInspectSummary, TxpoolStatus, }; use reth_rpc_types_compat::{transaction::from_recovered, TransactionCompat}; use reth_transaction_pool::{AllPoolTransactions, PoolTransaction, TransactionPool}; -use revm_primitives::TransactTo; use tracing::trace; /// `txpool` API implementation. From a430d619fb1a976b6a083f74482a1b94061df9a1 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 22:29:11 +0200 Subject: [PATCH 73/80] Fix lint --- crates/optimism/rpc/src/eth/transaction.rs | 3 --- crates/rpc/rpc-types-compat/src/transaction/mod.rs | 5 ++++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 21923c21aa1b..4beac98141f3 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -115,13 +115,10 @@ impl TransactionCompat for OpTxBuilder { } } - /// Truncates the input of a transaction to only the first 4 bytes. fn otterscan_api_truncate_input(tx: &mut Self::Transaction) { tx.inner.input = tx.inner.input.slice(..4); } - /// Returns the transaction type. - // todo: remove when alloy TransactionResponse trait it updated. fn tx_type(tx: &Self::Transaction) -> u8 { tx.inner.transaction_type.unwrap_or_default() } diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index ea307439b597..5b0bcad7e33e 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -68,8 +68,11 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { /// environment related fields to `None`. fn fill(tx: TransactionSignedEcRecovered, tx_inf: TransactionInfo) -> Self::Transaction; + /// Truncates the input of a transaction to only the first 4 bytes. fn otterscan_api_truncate_input(tx: &mut Self::Transaction); + /// Returns the transaction type. + // todo: remove when alloy TransactionResponse trait it updated. fn tx_type(tx: &Self::Transaction) -> u8; } @@ -84,7 +87,7 @@ impl TransactionCompat for () { fn otterscan_api_truncate_input(_tx: &mut Self::Transaction) {} - fn tx_type(tx: &Self::Transaction) -> u8 { + fn tx_type(_tx: &Self::Transaction) -> u8 { 0 } } From e51f52ae2a018ead5f2c8b65cc0ebb9e04a1b783 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 22:34:00 +0200 Subject: [PATCH 74/80] Remove completed todos --- crates/rpc/rpc-eth-api/src/types.rs | 1 - crates/rpc/rpc/src/eth/pubsub.rs | 1 - crates/rpc/rpc/src/txpool.rs | 1 - 3 files changed, 3 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/types.rs b/crates/rpc/rpc-eth-api/src/types.rs index 5636dfe9f051..900817964546 100644 --- a/crates/rpc/rpc-eth-api/src/types.rs +++ b/crates/rpc/rpc-eth-api/src/types.rs @@ -20,7 +20,6 @@ pub trait EthApiTypes: Send + Sync + Clone { + Send + Sync; /// Blockchain primitive types, specific to network, e.g. block and transaction. - // todo: remove restriction [`reth_rpc_types::Transaction`] type NetworkTypes: Network; /// Conversion methods for transaction RPC type. type TransactionCompat: Send + Sync + Clone + fmt::Debug; diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 950489880b4d..e1ad6e853ae7 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -109,7 +109,6 @@ where Pool: TransactionPool + 'static, Events: CanonStateSubscriptions + Clone + 'static, Network: NetworkInfo + Clone + 'static, - // todo: make alloy_rpc_types_eth::SubscriptionResult generic over transaction Eth: FullEthApiTypes, { match kind { diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index eb2ad8bbca77..4b1e43766a8a 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -33,7 +33,6 @@ impl TxPoolApi { impl TxPoolApi where Pool: TransactionPool + 'static, - // todo: make alloy_rpc_types_txpool::TxpoolContent generic over transaction Eth: FullEthApiTypes, { fn content(&self) -> TxpoolContent> { From 67d4ba85329ac9b76d23e5d7440e69dade33fc48 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Mon, 16 Sep 2024 22:50:52 +0200 Subject: [PATCH 75/80] Revert unrelated changes --- crates/rpc/ipc/src/server/mod.rs | 1 - crates/rpc/rpc-api/Cargo.toml | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/rpc/ipc/src/server/mod.rs b/crates/rpc/ipc/src/server/mod.rs index 11384da50c4c..28c0f6e8cb4f 100644 --- a/crates/rpc/ipc/src/server/mod.rs +++ b/crates/rpc/ipc/src/server/mod.rs @@ -789,7 +789,6 @@ impl Builder { } } -/// Returns a random name for the IPC endpoint. #[cfg(test)] pub fn dummy_name() -> String { let num: u64 = rand::Rng::gen(&mut rand::thread_rng()); diff --git a/crates/rpc/rpc-api/Cargo.toml b/crates/rpc/rpc-api/Cargo.toml index e6a5cd61ee90..480d06f997ed 100644 --- a/crates/rpc/rpc-api/Cargo.toml +++ b/crates/rpc/rpc-api/Cargo.toml @@ -21,8 +21,8 @@ reth-network-peers.workspace = true # ethereum alloy-json-rpc.workspace = true -alloy-primitives.workspace = true alloy-eips.workspace = true +alloy-primitives.workspace = true # misc jsonrpsee = { workspace = true, features = ["server", "macros"] } From 9ccf619da84ef090af70e37730eeeec860723f33 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 19 Sep 2024 18:29:05 +0200 Subject: [PATCH 76/80] Update docs --- crates/rpc/rpc-types-compat/src/transaction/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index 5b0bcad7e33e..b37f60e8102d 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -38,7 +38,8 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { /// RPC transaction response type. type Transaction: Send + Clone + Default + fmt::Debug; - /// Returns gas price and max fee per gas w.r.t. network specific transaction type. + /// Formats gas price and max fee per gas for RPC transaction response w.r.t. network specific + /// transaction type. fn gas_price(signed_tx: &TransactionSigned, base_fee: Option) -> GasPrice { match signed_tx.tx_type() { TxType::Legacy | TxType::Eip2930 => { From dc7d4d1850d7a934fc8f3b59f3d1aa6ec3e6acff Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 19 Sep 2024 18:31:53 +0200 Subject: [PATCH 77/80] Add lost code comment --- crates/optimism/rpc/src/eth/transaction.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 4beac98141f3..20809d6b00c2 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -110,6 +110,7 @@ impl TransactionCompat for OpTxBuilder { inner, source_hash: signed_tx.source_hash(), mint: signed_tx.mint(), + // only include is_system_tx if true: is_system_tx: signed_tx.is_deposit().then_some(signed_tx.is_system_transaction()), deposit_receipt_version: None, // todo: how to fill this field? } From a6253121ca790b16521f31e3eb534a8f75d47f89 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 19 Sep 2024 18:33:26 +0200 Subject: [PATCH 78/80] Add todo --- crates/rpc/rpc-types-compat/src/transaction/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/rpc/rpc-types-compat/src/transaction/mod.rs b/crates/rpc/rpc-types-compat/src/transaction/mod.rs index b37f60e8102d..8fd4860e1597 100644 --- a/crates/rpc/rpc-types-compat/src/transaction/mod.rs +++ b/crates/rpc/rpc-types-compat/src/transaction/mod.rs @@ -70,6 +70,8 @@ pub trait TransactionCompat: Send + Sync + Unpin + Clone + fmt::Debug { fn fill(tx: TransactionSignedEcRecovered, tx_inf: TransactionInfo) -> Self::Transaction; /// Truncates the input of a transaction to only the first 4 bytes. + // todo: remove in favour of using constructor on `TransactionResponse` or similar + // . fn otterscan_api_truncate_input(tx: &mut Self::Transaction); /// Returns the transaction type. From 614cb7f07ff8657b78b157e0ffa548ed6abe0643 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 19 Sep 2024 19:01:07 +0200 Subject: [PATCH 79/80] Fix merge conflicts --- crates/rpc/rpc-eth-api/src/helpers/call.rs | 24 +++++++++------------- crates/rpc/rpc-eth-types/src/simulate.rs | 10 ++++----- 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/call.rs b/crates/rpc/rpc-eth-api/src/helpers/call.rs index 3bfcd5bd18ef..ee9dad9b6c34 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -1,7 +1,9 @@ //! Loads a pending block from database. Helper trait for `eth_` transaction, call and trace RPC //! methods. -use crate::{AsEthApiError, FromEthApiError, FromEvmError, IntoEthApiError}; +use crate::{ + AsEthApiError, FromEthApiError, FromEvmError, FullEthApiTypes, IntoEthApiError, RpcBlock, +}; use alloy_primitives::{Bytes, TxKind, B256, U256}; use futures::Future; use reth_chainspec::MIN_TRANSACTION_GAS; @@ -31,8 +33,7 @@ use reth_rpc_server_types::constants::gas_oracle::{CALL_STIPEND_GAS, ESTIMATE_GA use reth_rpc_types::{ simulate::{SimBlock, SimulatePayload, SimulatedBlock}, state::{EvmOverrides, StateOverride}, - Block, BlockId, Bundle, EthCallResponse, StateContext, TransactionInfo, TransactionRequest, - WithOtherFields, + BlockId, Bundle, EthCallResponse, StateContext, TransactionInfo, TransactionRequest, }; use revm::{Database, DatabaseCommit, GetInspector}; use revm_inspectors::{access_list::AccessListInspector, transfer::TransferInspector}; @@ -61,14 +62,10 @@ pub trait EthCall: Call + LoadPendingBlock { &self, payload: SimulatePayload, block: Option, - ) -> impl Future< - Output = Result< - Vec>>>, - Self::Error, - >, - > + Send + ) -> impl Future>>, Self::Error>> + + Send where - Self: LoadBlock, + Self: LoadBlock + FullEthApiTypes, { async move { if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { @@ -108,9 +105,8 @@ pub trait EthCall: Call + LoadPendingBlock { let this = self.clone(); self.spawn_with_state_at_block(block, move |state| { let mut db = CacheDB::new(StateProviderDatabase::new(state)); - let mut blocks: Vec< - SimulatedBlock>>, - > = Vec::with_capacity(block_state_calls.len()); + let mut blocks: Vec>> = + Vec::with_capacity(block_state_calls.len()); let mut gas_used = 0; for block in block_state_calls { // Increase number and timestamp for every new block @@ -191,7 +187,7 @@ pub trait EthCall: Call + LoadPendingBlock { results.push((env.tx.caller, res.result)); } - let block = simulate::build_block( + let block = simulate::build_block::( results, transactions, &block_env, diff --git a/crates/rpc/rpc-eth-types/src/simulate.rs b/crates/rpc/rpc-eth-types/src/simulate.rs index c36f77599aa6..5160982ea313 100644 --- a/crates/rpc/rpc-eth-types/src/simulate.rs +++ b/crates/rpc/rpc-eth-types/src/simulate.rs @@ -11,9 +11,9 @@ use reth_revm::database::StateProviderDatabase; use reth_rpc_server_types::result::rpc_err; use reth_rpc_types::{ simulate::{SimCallResult, SimulateError, SimulatedBlock}, - Block, BlockTransactionsKind, ToRpcError, TransactionRequest, WithOtherFields, + Block, BlockTransactionsKind, ToRpcError, TransactionRequest, }; -use reth_rpc_types_compat::block::from_block; +use reth_rpc_types_compat::{block::from_block, TransactionCompat}; use reth_storage_api::StateRootProvider; use reth_trie::{HashedPostState, HashedStorage}; use revm::{db::CacheDB, Database}; @@ -168,7 +168,7 @@ where } /// Handles outputs of the calls execution and builds a [`SimulatedBlock`]. -pub fn build_block( +pub fn build_block( results: Vec<(Address, ExecutionResult)>, transactions: Vec, block_env: &BlockEnv, @@ -176,7 +176,7 @@ pub fn build_block( total_difficulty: U256, full_transactions: bool, db: &CacheDB>>, -) -> Result>>, EthApiError> { +) -> Result>, EthApiError> { let mut calls: Vec = Vec::with_capacity(results.len()); let mut senders = Vec::with_capacity(results.len()); let mut receipts = Vec::new(); @@ -297,6 +297,6 @@ pub fn build_block( let txs_kind = if full_transactions { BlockTransactionsKind::Full } else { BlockTransactionsKind::Hashes }; - let block = from_block(block, total_difficulty, txs_kind, None)?; + let block = from_block::(block, total_difficulty, txs_kind, None)?; Ok(SimulatedBlock { inner: block, calls }) } From 2c6bb1ded39b5731a68efa7fcb6b1beaa93af690 Mon Sep 17 00:00:00 2001 From: Emilia Hane Date: Thu, 19 Sep 2024 19:17:37 +0200 Subject: [PATCH 80/80] Fix merge conflicts --- crates/rpc/rpc-eth-api/src/helpers/block.rs | 13 ++++--------- crates/rpc/rpc-eth-api/src/helpers/transaction.rs | 7 +------ 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index d5e37fd2b074..19e81e2703d4 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -7,12 +7,9 @@ use reth_primitives::{BlockId, Receipt, SealedBlock, SealedBlockWithSenders}; use reth_provider::{BlockIdReader, BlockReader, BlockReaderIdExt, HeaderProvider}; use reth_rpc_eth_types::{EthApiError, EthStateCache}; use reth_rpc_types::{Header, Index}; -use reth_rpc_types_compat::{ - block::{from_block, uncle_block_from_header}, - TransactionCompat, -}; +use reth_rpc_types_compat::block::{from_block, uncle_block_from_header}; -use crate::{FromEthApiError, RpcBlock, RpcReceipt, RpcTransaction}; +use crate::{FromEthApiError, FullEthApiTypes, RpcBlock, RpcReceipt}; use super::{LoadPendingBlock, LoadReceipt, SpawnBlocking}; @@ -30,8 +27,7 @@ pub trait EthBlocks: LoadBlock { block_id: BlockId, ) -> impl Future, Self::Error>> + Send where - Self::TransactionCompat: - TransactionCompat>, + Self: FullEthApiTypes, { async move { Ok(self.rpc_block(block_id, false).await?.map(|block| block.header)) } } @@ -46,8 +42,7 @@ pub trait EthBlocks: LoadBlock { full: bool, ) -> impl Future>, Self::Error>> + Send where - Self::TransactionCompat: - TransactionCompat>, + Self: FullEthApiTypes, { async move { let Some(block) = self.block_with_senders(block_id).await? else { return Ok(None) }; diff --git a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs index 9776a9eb2bea..a12ef7012eb7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -19,10 +19,7 @@ use reth_rpc_types::{ }, BlockNumberOrTag, TransactionInfo, TransactionRequest, TypedTransactionRequest, }; -use reth_rpc_types_compat::{ - transaction::{from_recovered, from_recovered_with_block_context}, - TransactionCompat, -}; +use reth_rpc_types_compat::transaction::{from_recovered, from_recovered_with_block_context}; use reth_transaction_pool::{PoolTransaction, TransactionOrigin, TransactionPool}; use crate::{FromEthApiError, FullEthApiTypes, IntoEthApiError, RpcReceipt, RpcTransaction}; @@ -195,8 +192,6 @@ pub trait EthTransactions: LoadTransaction { ) -> impl Future>, Self::Error>> + Send where Self: LoadBlock, - Self::TransactionCompat: - TransactionCompat>, { async move { if let Some(block) = self.block_with_senders(block_id).await? {