From 5c149a5faf490b84687e993b13dacf31b550deda Mon Sep 17 00:00:00 2001 From: Morty Date: Sat, 28 Jun 2025 05:15:45 +0800 Subject: [PATCH 01/18] feat: support forward transaction to sequencer --- Cargo.lock | 7 + bin/reth/Cargo.toml | 1 + crates/scroll/rpc/Cargo.toml | 10 + crates/scroll/rpc/src/error.rs | 23 +++ crates/scroll/rpc/src/eth/mod.rs | 47 ++++- crates/scroll/rpc/src/eth/transaction.rs | 21 +- crates/scroll/rpc/src/lib.rs | 4 +- crates/scroll/rpc/src/sequencer.rs | 232 +++++++++++++++++++++++ 8 files changed, 338 insertions(+), 7 deletions(-) create mode 100644 crates/scroll/rpc/src/sequencer.rs diff --git a/Cargo.lock b/Cargo.lock index cf4bed5a88..5dcc79f181 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7195,6 +7195,7 @@ name = "reth" version = "1.4.8" dependencies = [ "alloy-rpc-types", + "alloy-transport", "aquamarine", "backon", "clap", @@ -10393,11 +10394,16 @@ name = "reth-scroll-rpc" version = "1.4.8" dependencies = [ "alloy-consensus", + "alloy-json-rpc", "alloy-primitives", + "alloy-rpc-client", "alloy-rpc-types-eth", + "alloy-transport", + "alloy-transport-http", "eyre", "jsonrpsee-types", "parking_lot", + "reqwest", "reth-chainspec", "reth-evm", "reth-network-api", @@ -10422,6 +10428,7 @@ dependencies = [ "scroll-alloy-rpc-types", "thiserror 2.0.12", "tokio", + "tracing", ] [[package]] diff --git a/bin/reth/Cargo.toml b/bin/reth/Cargo.toml index 4d93ca5d73..0c758f71c7 100644 --- a/bin/reth/Cargo.toml +++ b/bin/reth/Cargo.toml @@ -61,6 +61,7 @@ tokio = { workspace = true, features = ["sync", "macros", "time", "rt-multi-thre aquamarine.workspace = true clap = { workspace = true, features = ["derive", "env"] } eyre.workspace = true +alloy-transport.workspace = true [dev-dependencies] backon.workspace = true diff --git a/crates/scroll/rpc/Cargo.toml b/crates/scroll/rpc/Cargo.toml index f1fbbc9289..e43bfba133 100644 --- a/crates/scroll/rpc/Cargo.toml +++ b/crates/scroll/rpc/Cargo.toml @@ -42,6 +42,16 @@ alloy-primitives.workspace = true alloy-rpc-types-eth.workspace = true alloy-consensus.workspace = true revm.workspace = true +alloy-transport.workspace = true +alloy-json-rpc.workspace = true +alloy-rpc-client.workspace = true +alloy-transport-http.workspace = true + +# reqwest +reqwest = { workspace = true, default-features = false, features = ["rustls-tls-native-roots"] } + +# tracing +tracing.workspace = true # async parking_lot.workspace = true diff --git a/crates/scroll/rpc/src/error.rs b/crates/scroll/rpc/src/error.rs index 6357053166..a517ffb4fa 100644 --- a/crates/scroll/rpc/src/error.rs +++ b/crates/scroll/rpc/src/error.rs @@ -1,6 +1,8 @@ //! RPC errors specific to Scroll. use alloy_rpc_types_eth::BlockError; +use alloy_transport::{RpcError, TransportErrorKind}; +use jsonrpsee_types::error::{INTERNAL_ERROR_CODE}; use reth_evm::execute::ProviderError; use reth_rpc_eth_api::{AsEthApiError, TransactionConversionError}; use reth_rpc_eth_types::{error::api::FromEvmHalt, EthApiError}; @@ -62,3 +64,24 @@ impl From for ScrollEthApiError { Self::Eth(EthApiError::from(value)) } } + +/// Error type when interacting with the Sequencer +#[derive(Debug, thiserror::Error)] +pub enum SequencerClientError { + /// Wrapper around an [`RpcError`]. + #[error(transparent)] + HttpError(#[from] RpcError), + /// Thrown when serializing transaction to forward to sequencer + #[error("invalid sequencer transaction")] + InvalidSequencerTransaction, +} + +impl From for jsonrpsee_types::error::ErrorObject<'static> { + fn from(err: SequencerClientError) -> Self { + jsonrpsee_types::error::ErrorObject::owned( + INTERNAL_ERROR_CODE, + err.to_string(), + None::, + ) + } +} \ No newline at end of file diff --git a/crates/scroll/rpc/src/eth/mod.rs b/crates/scroll/rpc/src/eth/mod.rs index c89c1509fb..c8bbf000f4 100644 --- a/crates/scroll/rpc/src/eth/mod.rs +++ b/crates/scroll/rpc/src/eth/mod.rs @@ -1,6 +1,7 @@ //! Scroll-Reth `eth_` endpoint implementation. use alloy_primitives::U256; +use eyre::WrapErr; use reth_chainspec::{EthChainSpec, EthereumHardforks}; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; @@ -40,6 +41,8 @@ mod pending_block; pub mod receipt; pub mod transaction; +use crate::SequencerClient; + /// Adapter for [`EthApiInner`], which holds all the data required to serve core `eth_` API. pub type EthApiNodeBackend = EthApiInner< ::Provider, @@ -74,8 +77,8 @@ pub struct ScrollEthApi { impl ScrollEthApi { /// Creates a new [`ScrollEthApi`]. - pub fn new(eth_api: EthApiNodeBackend) -> Self { - let inner = Arc::new(ScrollEthApiInner { eth_api }); + pub fn new(eth_api: EthApiNodeBackend, sequencer_client: Option) -> Self { + let inner = Arc::new(ScrollEthApiInner { eth_api, sequencer_client }); Self { inner: inner.clone(), _nt: PhantomData, @@ -99,6 +102,11 @@ where self.inner.eth_api() } + /// Returns the configured sequencer client, if any. + pub fn sequencer_client(&self) -> Option<&SequencerClient> { + self.inner.sequencer_client() + } + /// Return a builder for the [`ScrollEthApi`]. pub const fn builder() -> ScrollEthApiBuilder { ScrollEthApiBuilder::new() @@ -302,6 +310,9 @@ impl fmt::Debug for ScrollEthApi { pub struct ScrollEthApiInner { /// Gateway to node's core components. pub eth_api: EthApiNodeBackend, + /// Sequencer client, configured to forward submitted transactions to sequencer of given Scroll + /// network. + sequencer_client: Option, } impl ScrollEthApiInner { @@ -309,16 +320,31 @@ impl ScrollEthApiInner { const fn eth_api(&self) -> &EthApiNodeBackend { &self.eth_api } + + /// Returns the configured sequencer client, if any. + const fn sequencer_client(&self) -> Option<&SequencerClient> { + self.sequencer_client.as_ref() + } } /// A type that knows how to build a [`ScrollEthApi`]. #[derive(Debug, Default)] -pub struct ScrollEthApiBuilder {} +pub struct ScrollEthApiBuilder { + /// Sequencer client, configured to forward submitted transactions to sequencer of given Scroll + /// network. + sequencer_url: Option, +} impl ScrollEthApiBuilder { /// Creates a [`ScrollEthApiBuilder`] instance. pub const fn new() -> Self { - Self {} + Self { sequencer_url: None } + } + + /// With a [`SequencerClient`]. + pub fn with_sequencer(mut self, sequencer_url: Option) -> Self { + self.sequencer_url = sequencer_url; + self } } @@ -330,6 +356,7 @@ where type EthApi = ScrollEthApi; async fn build_eth_api(self, ctx: EthApiCtx<'_, N>) -> eyre::Result { + let Self { sequencer_url } = self; let eth_api = reth_rpc::EthApiBuilder::new( ctx.components.provider().clone(), ctx.components.pool().clone(), @@ -345,6 +372,16 @@ where .proof_permits(ctx.config.proof_permits) .build_inner(); - Ok(ScrollEthApi::new(eth_api)) + let sequencer_client = if let Some(url) = sequencer_url { + Some( + SequencerClient::new(&url) + .await + .wrap_err_with(|| "Failed to init sequencer client with: {url}")?, + ) + } else { + None + }; + + Ok(ScrollEthApi::new(eth_api, sequencer_client)) } } diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index d044b1c7d3..b3e7b0fcd7 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -2,7 +2,7 @@ use crate::{ eth::{ScrollEthApiInner, ScrollNodeCore}, - ScrollEthApi, + ScrollEthApi, SequencerClient, }; use alloy_consensus::transaction::TransactionInfo; use alloy_primitives::{Bytes, B256}; @@ -41,6 +41,15 @@ where let recovered = recover_raw_transaction(&tx)?; let pool_transaction = ::Transaction::from_pooled(recovered); + // On scroll, transactions are forwarded directly to the sequencer to be included in + // blocks that it builds. + if let Some(client) = self.raw_tx_forwarder().as_ref() { + tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); + let _ = client.forward_raw_transaction(&tx).await.inspect_err(|err| { + tracing::debug!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction"); + }); + } + // submit the transaction to the pool with a `Local` origin let hash = self .pool() @@ -60,6 +69,16 @@ where { } +impl ScrollEthApi +where + N: ScrollNodeCore, +{ + /// Returns the [`SequencerClient`] if one is set. + pub fn raw_tx_forwarder(&self) -> Option { + self.inner.sequencer_client.clone() + } +} + /// Scroll implementation of [`TxInfoMapper`]. /// /// Receipt is fetched to extract the `l1_fee` for all transactions but L1 messages. diff --git a/crates/scroll/rpc/src/lib.rs b/crates/scroll/rpc/src/lib.rs index a3058ffee0..116bc181c8 100644 --- a/crates/scroll/rpc/src/lib.rs +++ b/crates/scroll/rpc/src/lib.rs @@ -10,6 +10,8 @@ pub mod error; pub mod eth; +pub mod sequencer; -pub use error::ScrollEthApiError; +pub use error::{ScrollEthApiError, SequencerClientError}; pub use eth::{ScrollEthApi, ScrollReceiptBuilder}; +pub use sequencer::SequencerClient; \ No newline at end of file diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs new file mode 100644 index 0000000000..d5a581a8c6 --- /dev/null +++ b/crates/scroll/rpc/src/sequencer.rs @@ -0,0 +1,232 @@ +//! Helpers for scroll specific RPC implementations. + +use crate::SequencerClientError; +use alloy_json_rpc::{RpcRecv, RpcSend}; +use alloy_primitives::{hex, B256}; +use alloy_rpc_client::{BuiltInConnectionString, ClientBuilder, RpcClient as Client}; +use alloy_rpc_types_eth::erc4337::TransactionConditional; +use alloy_transport_http::Http; +use std::{str::FromStr, sync::Arc}; +use thiserror::Error; +use tracing::warn; + +/// Sequencer client error +#[derive(Error, Debug)] +pub enum Error { + /// Invalid scheme + #[error("Invalid scheme of sequencer url: {0}")] + InvalidScheme(String), + /// Invalid url + #[error("Invalid sequencer url: {0}")] + InvalidUrl(String), + /// Establishing a connection to the sequencer endpoint resulted in an error. + #[error("Failed to connect to sequencer: {0}")] + TransportError( + #[from] + #[source] + alloy_transport::TransportError, + ), + /// Reqwest failed to init client + #[error("Failed to init reqwest client for sequencer: {0}")] + ReqwestError( + #[from] + #[source] + reqwest::Error, + ), +} + +/// A client to interact with a Sequencer +#[derive(Debug, Clone)] +pub struct SequencerClient { + inner: Arc, +} + +impl SequencerClient { + /// Creates a new [`SequencerClient`] for the given URL. + /// + /// If the URL is a websocket endpoint we connect a websocket instance. + pub async fn new(sequencer_endpoint: impl Into) -> Result { + let sequencer_endpoint = sequencer_endpoint.into(); + let endpoint = BuiltInConnectionString::from_str(&sequencer_endpoint)?; + if let BuiltInConnectionString::Http(url) = endpoint { + let client = reqwest::Client::builder() + // we force use tls to prevent native issues + .use_rustls_tls() + .build()?; + Self::with_http_client(url, client) + } else { + let client = ClientBuilder::default().connect_with(endpoint).await?; + let inner = SequencerClientInner { sequencer_endpoint, client }; + Ok(Self { inner: Arc::new(inner) }) + } + } + + /// Creates a new [`SequencerClient`] with http transport with the given http client. + pub fn with_http_client( + sequencer_endpoint: impl Into, + client: reqwest::Client, + ) -> Result { + let sequencer_endpoint: String = sequencer_endpoint.into(); + let url = sequencer_endpoint + .parse() + .map_err(|_| Error::InvalidUrl(sequencer_endpoint.clone()))?; + + let http_client = Http::with_client(client, url); + let is_local = http_client.guess_local(); + let client = ClientBuilder::default().transport(http_client, is_local); + + let inner = SequencerClientInner { sequencer_endpoint, client }; + Ok(Self { inner: Arc::new(inner) }) + } + + /// Returns the network of the client + pub fn endpoint(&self) -> &str { + &self.inner.sequencer_endpoint + } + + /// Returns the client + pub fn client(&self) -> &Client { + &self.inner.client + } + + /// Sends a [`alloy_rpc_client::RpcCall`] request to the sequencer endpoint. + async fn send_rpc_call( + &self, + method: &str, + params: Params, + ) -> Result { + let resp = + self.client().request::(method.to_string(), params).await.inspect_err( + |err| { + warn!( + target: "rpc::sequencer", + %err, + "HTTP request to sequencer failed", + ); + }, + )?; + Ok(resp) + } + + /// Forwards a transaction to the sequencer endpoint. + pub async fn forward_raw_transaction(&self, tx: &[u8]) -> Result { + let rlp_hex = hex::encode_prefixed(tx); + let tx_hash = + self.send_rpc_call("eth_sendRawTransaction", (rlp_hex,)).await.inspect_err(|err| { + warn!( + target: "rpc::eth", + %err, + "Failed to forward transaction to sequencer", + ); + })?; + + Ok(tx_hash) + } + + /// Forwards a transaction conditional to the sequencer endpoint. + pub async fn forward_raw_transaction_conditional( + &self, + tx: &[u8], + condition: TransactionConditional, + ) -> Result { + let rlp_hex = hex::encode_prefixed(tx); + let tx_hash = self + .send_rpc_call("eth_sendRawTransactionConditional", (rlp_hex, condition)) + .await + .inspect_err(|err| { + warn!( + target: "rpc::eth", + %err, + "Failed to forward transaction conditional for sequencer", + ); + })?; + Ok(tx_hash) + } +} + +#[derive(Debug)] +struct SequencerClientInner { + /// The endpoint of the sequencer + sequencer_endpoint: String, + /// The client + client: Client, +} + +#[cfg(test)] +mod tests { + use super::*; + use alloy_primitives::U64; + + #[tokio::test] + async fn test_http_body_str() { + let client = SequencerClient::new("http://localhost:8545").await.unwrap(); + + let request = client + .client() + .make_request("eth_getBlockByNumber", (U64::from(10),)) + .serialize() + .unwrap() + .take_request(); + let body = request.get(); + + assert_eq!( + body, + r#"{"method":"eth_getBlockByNumber","params":["0xa"],"id":0,"jsonrpc":"2.0"}"# + ); + + let condition = TransactionConditional::default(); + + let request = client + .client() + .make_request( + "eth_sendRawTransactionConditional", + (format!("0x{}", hex::encode("abcd")), condition), + ) + .serialize() + .unwrap() + .take_request(); + let body = request.get(); + + assert_eq!( + body, + r#"{"method":"eth_sendRawTransactionConditional","params":["0x61626364",{"knownAccounts":{}}],"id":1,"jsonrpc":"2.0"}"# + ); + } + + #[tokio::test] + #[ignore = "Start if WS is reachable at ws://localhost:8546"] + async fn test_ws_body_str() { + let client = SequencerClient::new("ws://localhost:8546").await.unwrap(); + + let request = client + .client() + .make_request("eth_getBlockByNumber", (U64::from(10),)) + .serialize() + .unwrap() + .take_request(); + let body = request.get(); + + assert_eq!( + body, + r#"{"method":"eth_getBlockByNumber","params":["0xa"],"id":0,"jsonrpc":"2.0"}"# + ); + + let condition = TransactionConditional::default(); + + let request = client + .client() + .make_request( + "eth_sendRawTransactionConditional", + (format!("0x{}", hex::encode("abcd")), condition), + ) + .serialize() + .unwrap() + .take_request(); + let body = request.get(); + + assert_eq!( + body, + r#"{"method":"eth_sendRawTransactionConditional","params":["0x61626364",{"knownAccounts":{}}],"id":1,"jsonrpc":"2.0"}"# + ); + } +} From d7aeddb6909a66fbd0dc4cbd0165926161872bff Mon Sep 17 00:00:00 2001 From: Morty Date: Sat, 28 Jun 2025 05:39:08 +0800 Subject: [PATCH 02/18] remove unused code --- crates/scroll/rpc/src/sequencer.rs | 37 +++++------------------------- 1 file changed, 6 insertions(+), 31 deletions(-) diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs index d5a581a8c6..5c7c5e610c 100644 --- a/crates/scroll/rpc/src/sequencer.rs +++ b/crates/scroll/rpc/src/sequencer.rs @@ -4,7 +4,6 @@ use crate::SequencerClientError; use alloy_json_rpc::{RpcRecv, RpcSend}; use alloy_primitives::{hex, B256}; use alloy_rpc_client::{BuiltInConnectionString, ClientBuilder, RpcClient as Client}; -use alloy_rpc_types_eth::erc4337::TransactionConditional; use alloy_transport_http::Http; use std::{str::FromStr, sync::Arc}; use thiserror::Error; @@ -122,26 +121,6 @@ impl SequencerClient { Ok(tx_hash) } - - /// Forwards a transaction conditional to the sequencer endpoint. - pub async fn forward_raw_transaction_conditional( - &self, - tx: &[u8], - condition: TransactionConditional, - ) -> Result { - let rlp_hex = hex::encode_prefixed(tx); - let tx_hash = self - .send_rpc_call("eth_sendRawTransactionConditional", (rlp_hex, condition)) - .await - .inspect_err(|err| { - warn!( - target: "rpc::eth", - %err, - "Failed to forward transaction conditional for sequencer", - ); - })?; - Ok(tx_hash) - } } #[derive(Debug)] @@ -174,13 +153,11 @@ mod tests { r#"{"method":"eth_getBlockByNumber","params":["0xa"],"id":0,"jsonrpc":"2.0"}"# ); - let condition = TransactionConditional::default(); - let request = client .client() .make_request( - "eth_sendRawTransactionConditional", - (format!("0x{}", hex::encode("abcd")), condition), + "eth_sendRawTransaction", + format!("0x{}", hex::encode("abcd")), ) .serialize() .unwrap() @@ -189,7 +166,7 @@ mod tests { assert_eq!( body, - r#"{"method":"eth_sendRawTransactionConditional","params":["0x61626364",{"knownAccounts":{}}],"id":1,"jsonrpc":"2.0"}"# + r#"{"method":"eth_sendRawTransaction","params":"0x61626364","id":1,"jsonrpc":"2.0"}"# ); } @@ -211,13 +188,11 @@ mod tests { r#"{"method":"eth_getBlockByNumber","params":["0xa"],"id":0,"jsonrpc":"2.0"}"# ); - let condition = TransactionConditional::default(); - let request = client .client() .make_request( - "eth_sendRawTransactionConditional", - (format!("0x{}", hex::encode("abcd")), condition), + "eth_sendRawTransaction", + format!("0x{}", hex::encode("abcd")), ) .serialize() .unwrap() @@ -226,7 +201,7 @@ mod tests { assert_eq!( body, - r#"{"method":"eth_sendRawTransactionConditional","params":["0x61626364",{"knownAccounts":{}}],"id":1,"jsonrpc":"2.0"}"# + r#"{"method":"eth_sendRawTransaction","params":"0x61626364","id":1,"jsonrpc":"2.0"}"# ); } } From 762e208cb3548346956c065f085635ca24a2cbab Mon Sep 17 00:00:00 2001 From: Morty Date: Mon, 7 Jul 2025 01:33:08 +0800 Subject: [PATCH 03/18] fix: transaction already know --- crates/scroll/rpc/src/error.rs | 25 +++++++++++++----- crates/scroll/rpc/src/eth/transaction.rs | 33 +++++++++++++++++++----- 2 files changed, 46 insertions(+), 12 deletions(-) diff --git a/crates/scroll/rpc/src/error.rs b/crates/scroll/rpc/src/error.rs index a517ffb4fa..a9f9a09227 100644 --- a/crates/scroll/rpc/src/error.rs +++ b/crates/scroll/rpc/src/error.rs @@ -1,5 +1,6 @@ //! RPC errors specific to Scroll. +use alloy_json_rpc::ErrorPayload; use alloy_rpc_types_eth::BlockError; use alloy_transport::{RpcError, TransportErrorKind}; use jsonrpsee_types::error::{INTERNAL_ERROR_CODE}; @@ -14,12 +15,16 @@ pub enum ScrollEthApiError { /// L1 ethereum error. #[error(transparent)] Eth(#[from] EthApiError), + /// Sequencer client error. + #[error(transparent)] + Sequencer(#[from] SequencerClientError), } impl AsEthApiError for ScrollEthApiError { fn as_err(&self) -> Option<&EthApiError> { match self { Self::Eth(err) => Some(err), + _ => None, } } } @@ -28,6 +33,7 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(err: ScrollEthApiError) -> Self { match err { ScrollEthApiError::Eth(err) => err.into(), + ScrollEthApiError::Sequencer(err) => err.into(), } } } @@ -78,10 +84,17 @@ pub enum SequencerClientError { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(err: SequencerClientError) -> Self { - jsonrpsee_types::error::ErrorObject::owned( - INTERNAL_ERROR_CODE, - err.to_string(), - None::, - ) + match err { + SequencerClientError::HttpError(RpcError::ErrorResp(ErrorPayload { + code, + message, + data, + })) => jsonrpsee_types::error::ErrorObject::owned(code as i32, message, data), + err => jsonrpsee_types::error::ErrorObject::owned( + INTERNAL_ERROR_CODE, + err.to_string(), + None::, + ), + } } -} \ No newline at end of file +} diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index b3e7b0fcd7..5e492ea095 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -2,7 +2,7 @@ use crate::{ eth::{ScrollEthApiInner, ScrollNodeCore}, - ScrollEthApi, SequencerClient, + ScrollEthApi, ScrollEthApiError, SequencerClient, }; use alloy_consensus::transaction::TransactionInfo; use alloy_primitives::{Bytes, B256}; @@ -13,7 +13,7 @@ use reth_provider::{ }; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - try_into_scroll_tx_info, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, + try_into_scroll_tx_info, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; @@ -27,7 +27,7 @@ use std::{ impl EthTransactions for ScrollEthApi where - Self: LoadTransaction, + Self: LoadTransaction + EthApiTypes, N: ScrollNodeCore>>, { fn signers(&self) -> &parking_lot::RwLock>>>> { @@ -45,9 +45,30 @@ where // blocks that it builds. if let Some(client) = self.raw_tx_forwarder().as_ref() { tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); - let _ = client.forward_raw_transaction(&tx).await.inspect_err(|err| { - tracing::debug!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction"); - }); + + match client.forward_raw_transaction(&tx).await { + Ok(hash) => { + // Sequencer succeeded, try to add to local pool too + let _ = self + .pool() + .add_transaction(TransactionOrigin::Local, pool_transaction) + .await.inspect_err(|err| { + tracing::debug!(target: "rpc::eth", %err, %hash, "successfully sent tx to sequencer, but failed to persist in local tx pool"); + }); + return Ok(hash); + } + Err(err) => { + tracing::warn!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction to sequencer"); + // Sequencer failed, try local pool instead + let hash = self + .pool() + .add_transaction(TransactionOrigin::Local, pool_transaction) + .await + .map_err(Self::Error::from_eth_err)?; + tracing::debug!(target: "rpc::eth", %hash, "failed to forward tx to sequencer, but successfully added to local tx pool"); + return Ok(hash); + } + } } // submit the transaction to the pool with a `Local` origin From 053c929ee05cf99c3e404c70e76242bf7491ae23 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 03:05:23 +0800 Subject: [PATCH 04/18] update logic to keep it same as l2geth --- crates/scroll/rpc/src/eth/transaction.rs | 33 +++++++++++------------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 4f036b496f..2d5b719f95 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -47,29 +47,26 @@ where if let Some(client) = self.raw_tx_forwarder().as_ref() { tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); + // Retain tx in local tx pool before forwarding to sequencer rpc, for local RPC usage. + let hash = self + .pool() + .add_transaction(TransactionOrigin::Local, pool_transaction.clone()) + .await + .map_err(Self::Error::from_eth_err)?; + + tracing::debug!(target: "rpc::eth", %hash, "successfully added transaction to local tx pool"); + + // Forward to remote sequencer RPC. match client.forward_raw_transaction(&tx).await { - Ok(hash) => { - // Sequencer succeeded, try to add to local pool too - let _ = self - .pool() - .add_transaction(TransactionOrigin::Local, pool_transaction) - .await.inspect_err(|err| { - tracing::debug!(target: "rpc::eth", %err, %hash, "successfully sent tx to sequencer, but failed to persist in local tx pool"); - }); - return Ok(hash); + Ok(sequencer_hash) => { + tracing::debug!(target: "rpc::eth", local_hash=%hash, sequencer_hash=%sequencer_hash, "successfully forwarded transaction to sequencer"); } Err(err) => { - tracing::warn!(target: "rpc::eth", %err, hash=% *pool_transaction.hash(), "failed to forward raw transaction to sequencer"); - // Sequencer failed, try local pool instead - let hash = self - .pool() - .add_transaction(TransactionOrigin::Local, pool_transaction) - .await - .map_err(Self::Error::from_eth_err)?; - tracing::debug!(target: "rpc::eth", %hash, "failed to forward tx to sequencer, but successfully added to local tx pool"); - return Ok(hash); + tracing::warn!(target: "rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); } } + + return Ok(hash); } // submit the transaction to the pool with a `Local` origin From c82a2df91f6ca3170afa2b331a1836ea4c1b3a3a Mon Sep 17 00:00:00 2001 From: Gregory Edison Date: Mon, 14 Jul 2025 12:51:04 +0200 Subject: [PATCH 05/18] fix: make clippy happy Signed-off-by: Gregory Edison --- crates/engine/tree/src/tree/mod.rs | 26 ++++++++++----------- crates/net/network/src/manager.rs | 8 +++---- crates/rpc/rpc-builder/src/auth.rs | 9 +++---- crates/rpc/rpc-eth-api/src/helpers/state.rs | 8 +++---- crates/storage/db-models/src/accounts.rs | 5 +--- crates/transaction-pool/src/pool/txpool.rs | 12 +++++----- crates/trie/common/benches/prefix_set.rs | 1 + 7 files changed, 32 insertions(+), 37 deletions(-) diff --git a/crates/engine/tree/src/tree/mod.rs b/crates/engine/tree/src/tree/mod.rs index fd214e8878..a88c109787 100644 --- a/crates/engine/tree/src/tree/mod.rs +++ b/crates/engine/tree/src/tree/mod.rs @@ -1207,18 +1207,18 @@ where debug!(target: "engine::tree", "received backfill sync finished event"); self.backfill_sync_state = BackfillSyncState::Idle; - // backfill height is the block number that the backfill finished at - let mut backfill_height = ctrl.block_number(); - // Pipeline unwound, memorize the invalid block and wait for CL for next sync target. - if let ControlFlow::Unwind { bad_block, target } = &ctrl { + let backfill_height = if let ControlFlow::Unwind { bad_block, target } = &ctrl { warn!(target: "engine::tree", invalid_block=?bad_block, "Bad block detected in unwind"); // update the `invalid_headers` cache with the new invalid header self.state.invalid_headers.insert(**bad_block); // if this was an unwind then the target is the new height - backfill_height = Some(*target); - } + Some(*target) + } else { + // backfill height is the block number that the backfill finished at + ctrl.block_number() + }; // backfill height is the block number that the backfill finished at let Some(backfill_height) = backfill_height else { return Ok(()) }; @@ -1780,20 +1780,18 @@ where ) -> Option { let sync_target_state = self.state.forkchoice_state_tracker.sync_target_state(); - // check if the distance exceeds the threshold for backfill sync - let mut exceeds_backfill_threshold = - self.exceeds_backfill_run_threshold(canonical_tip_num, target_block_number); - // check if the downloaded block is the tracked finalized block - if let Some(buffered_finalized) = sync_target_state + let mut exceeds_backfill_threshold = if let Some(buffered_finalized) = sync_target_state .as_ref() .and_then(|state| self.state.buffer.block(&state.finalized_block_hash)) { // if we have buffered the finalized block, we should check how far // we're off - exceeds_backfill_threshold = - self.exceeds_backfill_run_threshold(canonical_tip_num, buffered_finalized.number()); - } + self.exceeds_backfill_run_threshold(canonical_tip_num, buffered_finalized.number()) + } else { + // check if the distance exceeds the threshold for backfill sync + self.exceeds_backfill_run_threshold(canonical_tip_num, target_block_number) + }; // If this is invoked after we downloaded a block we can check if this block is the // finalized block diff --git a/crates/net/network/src/manager.rs b/crates/net/network/src/manager.rs index c4dbbf75d1..aee8218382 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -842,8 +842,7 @@ impl NetworkManager { "Session disconnected" ); - let mut reason = None; - if let Some(ref err) = error { + let reason = if let Some(ref err) = error { // If the connection was closed due to an error, we report // the peer self.swarm.state_mut().peers_mut().on_active_session_dropped( @@ -851,11 +850,12 @@ impl NetworkManager { &peer_id, err, ); - reason = err.as_disconnected(); + err.as_disconnected() } else { // Gracefully disconnected self.swarm.state_mut().peers_mut().on_active_session_gracefully_closed(peer_id); - } + None + }; self.metrics.closed_sessions.increment(1); self.update_active_connection_metrics(); diff --git a/crates/rpc/rpc-builder/src/auth.rs b/crates/rpc/rpc-builder/src/auth.rs index ca96adec8e..b1a4f4166b 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -68,16 +68,17 @@ impl AuthServerConfig { .map_err(|err| RpcError::server_error(err, ServerKind::Auth(socket_addr)))?; let handle = server.start(module.inner.clone()); - let mut ipc_handle: Option = None; - if let Some(ipc_server_config) = ipc_server_config { + let ipc_handle = if let Some(ipc_server_config) = ipc_server_config { let ipc_endpoint_str = ipc_endpoint .clone() .unwrap_or_else(|| constants::DEFAULT_ENGINE_API_IPC_ENDPOINT.to_string()); let ipc_server = ipc_server_config.build(ipc_endpoint_str); let res = ipc_server.start(module.inner).await?; - ipc_handle = Some(res); - } + Some(res) + } else { + None + }; Ok(AuthServerHandle { handle: Some(handle), local_addr, secret, ipc_endpoint, ipc_handle }) } diff --git a/crates/rpc/rpc-eth-api/src/helpers/state.rs b/crates/rpc/rpc-eth-api/src/helpers/state.rs index 008b78ced4..4fa4edee8b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -277,17 +277,15 @@ pub trait LoadState: { self.spawn_blocking_io(move |this| { // first fetch the on chain nonce of the account - let on_chain_account_nonce = this + let mut next_nonce = this .latest_state()? .account_nonce(&address) .map_err(Self::Error::from_eth_err)? .unwrap_or_default(); - let mut next_nonce = on_chain_account_nonce; // Retrieve the highest consecutive transaction for the sender from the transaction pool - if let Some(highest_tx) = this - .pool() - .get_highest_consecutive_transaction_by_sender(address, on_chain_account_nonce) + if let Some(highest_tx) = + this.pool().get_highest_consecutive_transaction_by_sender(address, next_nonce) { // Return the nonce of the highest consecutive transaction + 1 next_nonce = highest_tx.nonce().checked_add(1).ok_or_else(|| { diff --git a/crates/storage/db-models/src/accounts.rs b/crates/storage/db-models/src/accounts.rs index 477c18f1c0..cbae5d84aa 100644 --- a/crates/storage/db-models/src/accounts.rs +++ b/crates/storage/db-models/src/accounts.rs @@ -27,10 +27,7 @@ impl reth_codecs::Compact for AccountBeforeTx { // for now put full bytes and later compress it. buf.put_slice(self.address.as_slice()); - let mut acc_len = 0; - if let Some(account) = self.info { - acc_len = account.to_compact(buf); - } + let acc_len = if let Some(account) = self.info { account.to_compact(buf) } else { 0 }; acc_len + 20 } diff --git a/crates/transaction-pool/src/pool/txpool.rs b/crates/transaction-pool/src/pool/txpool.rs index 3c84bea80b..66ba5368f0 100644 --- a/crates/transaction-pool/src/pool/txpool.rs +++ b/crates/transaction-pool/src/pool/txpool.rs @@ -1354,11 +1354,9 @@ impl AllTransactions { } }; } - // tracks the balance if the sender was changed in the block - let mut changed_balance = None; - + // track the balance if the sender was changed in the block // check if this is a changed account - if let Some(info) = changed_accounts.get(&id.sender) { + let changed_balance = if let Some(info) = changed_accounts.get(&id.sender) { // discard all transactions with a nonce lower than the current state nonce if id.nonce < info.state_nonce { updates.push(PoolUpdate { @@ -1384,8 +1382,10 @@ impl AllTransactions { } } - changed_balance = Some(&info.balance); - } + Some(&info.balance) + } else { + None + }; // If there's a nonce gap, we can shortcircuit, because there's nothing to update yet. if tx.state.has_nonce_gap() { diff --git a/crates/trie/common/benches/prefix_set.rs b/crates/trie/common/benches/prefix_set.rs index 1448e41502..bc2a8dc259 100644 --- a/crates/trie/common/benches/prefix_set.rs +++ b/crates/trie/common/benches/prefix_set.rs @@ -292,6 +292,7 @@ mod implementations { } #[derive(Default)] + #[allow(dead_code)] pub struct VecBinarySearchWithLastFoundPrefixSet { keys: Vec, last_found_idx: usize, From 7c16480f89d030918d36b3f2d3ff95562d75a1c3 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:08:27 +0800 Subject: [PATCH 06/18] fix: ci --- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 2 +- crates/scroll/rpc/src/eth/transaction.rs | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 795363f3df..798a146e61 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -128,7 +128,7 @@ where /// Suggests a gas price estimate based on recent blocks, using the configured percentile. pub async fn suggest_tip_cap(&self) -> EthResult { - let header = self + let header: reth_primitives_traits::SealedHeader<::Header> = self .provider .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 2d5b719f95..07a7fbb569 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -11,10 +11,9 @@ use reth_node_api::FullNodeComponents; use reth_provider::{ BlockReader, BlockReaderIdExt, ProviderTx, ReceiptProvider, TransactionsProvider, }; -use reth_rpc_convert::try_into_scroll_tx_info; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - try_into_scroll_tx_info, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, + EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; From 27bd9da703694f5b2b41c7b28bc6e1cfc3889070 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:16:11 +0800 Subject: [PATCH 07/18] fix: ci run cargo fmt --all --- bin/reth-bench/src/valid_payload.rs | 8 +- crates/alloy-provider/src/lib.rs | 12 +- crates/chain-state/src/chain_info.rs | 4 +- crates/chain-state/src/in_memory.rs | 6 +- crates/chain-state/src/notifications.rs | 4 +- crates/chain-state/src/test_utils.rs | 4 +- crates/chainspec/src/spec.rs | 16 +- crates/cli/cli/src/chainspec.rs | 2 +- crates/cli/commands/src/common.rs | 2 +- crates/cli/commands/src/db/checksum.rs | 2 +- crates/cli/commands/src/db/diff.rs | 4 +- crates/cli/commands/src/db/list.rs | 2 +- crates/cli/commands/src/db/mod.rs | 2 +- crates/cli/commands/src/db/stats.rs | 8 +- crates/cli/commands/src/db/tui.rs | 2 +- crates/cli/commands/src/import.rs | 4 +- crates/cli/commands/src/import_era.rs | 4 +- .../commands/src/init_state/without_evm.rs | 2 +- .../src/stage/dump/hashing_account.rs | 2 +- .../src/stage/dump/hashing_storage.rs | 2 +- crates/cli/commands/src/stage/dump/merkle.rs | 2 +- crates/cli/commands/src/stage/run.rs | 8 +- .../cli/commands/src/test_vectors/compact.rs | 2 +- .../cli/commands/src/test_vectors/tables.rs | 2 +- crates/cli/util/src/parsers.rs | 8 +- crates/cli/util/src/sigsegv_handler.rs | 4 +- crates/consensus/common/src/validation.rs | 34 ++-- crates/consensus/consensus/src/lib.rs | 2 +- .../debug-client/src/providers/etherscan.rs | 2 +- crates/e2e-test-utils/src/network.rs | 6 +- crates/e2e-test-utils/src/node.rs | 6 +- crates/e2e-test-utils/src/payload.rs | 2 +- .../src/testsuite/actions/produce_blocks.rs | 4 +- crates/engine/local/src/miner.rs | 4 +- crates/engine/tree/src/backfill.rs | 6 +- crates/engine/tree/src/chain.rs | 6 +- crates/engine/tree/src/download.rs | 8 +- crates/engine/tree/src/engine.rs | 10 +- crates/engine/tree/src/tree/block_buffer.rs | 2 +- crates/engine/tree/src/tree/cached_state.rs | 10 +- .../engine/tree/src/tree/invalid_headers.rs | 2 +- crates/engine/tree/src/tree/mod.rs | 172 +++++++++--------- .../src/tree/payload_processor/multiproof.rs | 14 +- .../src/tree/payload_processor/prewarm.rs | 18 +- .../engine/tree/src/tree/precompile_cache.rs | 2 +- crates/engine/tree/src/tree/state.rs | 14 +- crates/engine/tree/src/tree/tests.rs | 4 +- crates/engine/tree/src/tree/trie_updates.rs | 22 +-- crates/engine/util/src/reorg.rs | 14 +- crates/engine/util/src/skip_fcu.rs | 4 +- crates/engine/util/src/skip_new_payload.rs | 4 +- crates/era-downloader/tests/it/checksums.rs | 18 +- crates/era-downloader/tests/it/main.rs | 18 +- crates/era/src/era1_file.rs | 26 ++- crates/era/tests/it/main.rs | 4 +- .../ethereum/cli/src/debug_cmd/execution.rs | 4 +- .../cli/src/debug_cmd/in_memory_merkle.rs | 6 +- crates/ethereum/cli/src/debug_cmd/merkle.rs | 20 +- crates/ethereum/consensus/src/lib.rs | 45 ++--- crates/ethereum/consensus/src/validation.rs | 12 +- crates/ethereum/node/tests/e2e/rpc.rs | 4 +- crates/ethereum/payload/src/lib.rs | 14 +- crates/ethereum/payload/src/validator.rs | 2 +- crates/ethereum/primitives/src/receipt.rs | 22 +-- crates/ethereum/primitives/src/transaction.rs | 6 +- crates/etl/src/lib.rs | 2 +- crates/evm/evm/src/metrics.rs | 6 +- crates/evm/execution-errors/src/trie.rs | 4 +- crates/evm/execution-types/src/chain.rs | 6 +- .../execution-types/src/execution_outcome.rs | 6 +- crates/exex/exex/src/backfill/job.rs | 4 +- crates/exex/exex/src/backfill/stream.rs | 2 +- crates/exex/exex/src/manager.rs | 8 +- crates/exex/exex/src/notifications.rs | 18 +- crates/exex/exex/src/wal/cache.rs | 2 +- crates/exex/exex/src/wal/mod.rs | 6 +- crates/net/banlist/src/lib.rs | 6 +- crates/net/discv4/src/lib.rs | 78 ++++---- crates/net/discv4/src/proto.rs | 24 +-- crates/net/discv4/src/test_utils.rs | 4 +- crates/net/discv5/src/config.rs | 14 +- crates/net/discv5/src/enr.rs | 2 +- crates/net/discv5/src/filter.rs | 4 +- crates/net/discv5/src/lib.rs | 8 +- crates/net/discv5/src/network_stack_id.rs | 4 +- crates/net/dns/src/lib.rs | 6 +- crates/net/dns/src/query.rs | 8 +- crates/net/dns/src/sync.rs | 12 +- crates/net/dns/src/tree.rs | 2 +- crates/net/downloaders/src/bodies/bodies.rs | 60 +++--- crates/net/downloaders/src/bodies/request.rs | 10 +- crates/net/downloaders/src/bodies/task.rs | 8 +- crates/net/downloaders/src/file_client.rs | 12 +- crates/net/downloaders/src/file_codec.rs | 2 +- .../src/headers/reverse_headers.rs | 54 +++--- crates/net/downloaders/src/headers/task.rs | 6 +- .../downloaders/src/receipt_file_client.rs | 6 +- .../src/test_utils/bodies_client.rs | 2 +- crates/net/ecies/src/algorithm.rs | 16 +- crates/net/ecies/src/codec.rs | 22 +-- crates/net/eth-wire-types/src/broadcast.rs | 10 +- .../eth-wire-types/src/disconnect_reason.rs | 8 +- crates/net/eth-wire-types/src/message.rs | 30 +-- crates/net/eth-wire/src/capability.rs | 10 +- crates/net/eth-wire/src/errors/eth.rs | 2 +- crates/net/eth-wire/src/errors/p2p.rs | 4 +- crates/net/eth-wire/src/eth_snap_stream.rs | 10 +- crates/net/eth-wire/src/ethstream.rs | 2 +- crates/net/eth-wire/src/multiplex.rs | 51 +++--- crates/net/eth-wire/src/p2pstream.rs | 38 ++-- crates/net/eth-wire/src/pinger.rs | 6 +- crates/net/eth-wire/src/test_utils.rs | 2 +- crates/net/nat/src/lib.rs | 2 +- crates/net/network-types/src/peers/mod.rs | 6 +- crates/net/network/src/discovery.rs | 6 +- crates/net/network/src/error.rs | 124 ++++++------- crates/net/network/src/eth_requests.rs | 18 +- crates/net/network/src/fetch/mod.rs | 18 +- crates/net/network/src/manager.rs | 4 +- crates/net/network/src/network.rs | 2 +- crates/net/network/src/peers.rs | 72 ++++---- crates/net/network/src/session/active.rs | 46 ++--- crates/net/network/src/session/counter.rs | 2 +- crates/net/network/src/session/mod.rs | 8 +- crates/net/network/src/state.rs | 14 +- crates/net/network/src/swarm.rs | 22 +-- crates/net/network/src/test_utils/init.rs | 2 +- crates/net/network/src/test_utils/testnet.rs | 8 +- .../net/network/src/transactions/constants.rs | 12 +- .../net/network/src/transactions/fetcher.rs | 72 ++++---- crates/net/network/src/transactions/mod.rs | 92 +++++----- crates/net/network/tests/it/connect.rs | 4 +- crates/net/network/tests/it/multiplex.rs | 16 +- crates/net/network/tests/it/txgossip.rs | 4 +- crates/net/p2p/src/error.rs | 10 +- crates/net/p2p/src/full_block.rs | 28 +-- crates/net/p2p/src/test_utils/headers.rs | 10 +- crates/net/peers/src/lib.rs | 8 +- crates/net/peers/src/node_record.rs | 8 +- crates/node/builder/src/launch/common.rs | 10 +- crates/node/builder/src/launch/exex.rs | 2 +- crates/node/core/src/args/debug.rs | 2 +- crates/node/core/src/args/network.rs | 6 +- crates/node/core/src/args/payload_builder.rs | 2 +- crates/node/core/src/node_config.rs | 4 +- crates/node/events/src/cl.rs | 6 +- crates/node/events/src/node.rs | 14 +- crates/node/metrics/src/hooks.rs | 6 +- .../chainspec/src/superchain/configs.rs | 4 +- crates/optimism/cli/src/commands/import.rs | 6 +- .../cli/src/commands/import_receipts.rs | 2 +- .../optimism/cli/src/commands/init_state.rs | 2 +- crates/optimism/cli/src/receipt_file_codec.rs | 2 +- crates/optimism/consensus/src/lib.rs | 12 +- crates/optimism/consensus/src/proof.rs | 12 +- .../consensus/src/validation/canyon.rs | 2 +- .../consensus/src/validation/isthmus.rs | 4 +- .../optimism/consensus/src/validation/mod.rs | 16 +- crates/optimism/node/src/engine.rs | 10 +- crates/optimism/node/src/node.rs | 8 +- crates/optimism/payload/src/builder.rs | 22 +-- crates/optimism/payload/src/validator.rs | 2 +- crates/optimism/primitives/src/bedrock.rs | 4 +- crates/optimism/primitives/src/receipt.rs | 78 ++++---- .../primitives/src/transaction/signed.rs | 10 +- crates/optimism/rpc/src/error.rs | 10 +- crates/optimism/rpc/src/eth/block.rs | 2 +- crates/optimism/rpc/src/eth/ext.rs | 4 +- crates/optimism/rpc/src/eth/transaction.rs | 2 +- crates/optimism/rpc/src/historical.rs | 12 +- .../optimism/txpool/src/supervisor/client.rs | 2 +- crates/optimism/txpool/src/transaction.rs | 2 +- crates/optimism/txpool/src/validator.rs | 10 +- crates/payload/basic/src/lib.rs | 8 +- .../payload/builder-primitives/src/events.rs | 12 +- crates/payload/builder/src/noop.rs | 2 +- crates/payload/builder/src/service.rs | 2 +- crates/payload/primitives/src/lib.rs | 32 ++-- crates/payload/util/src/traits.rs | 4 +- crates/payload/validator/src/cancun.rs | 20 +- crates/payload/validator/src/prague.rs | 4 +- crates/payload/validator/src/shanghai.rs | 4 +- crates/primitives-traits/src/account.rs | 6 +- crates/primitives-traits/src/block/mod.rs | 4 +- .../primitives-traits/src/block/recovered.rs | 6 +- crates/primitives-traits/src/block/sealed.rs | 2 +- crates/primitives-traits/src/size.rs | 23 +-- crates/primitives-traits/src/withdrawal.rs | 8 +- crates/prune/prune/src/db_ext.rs | 6 +- crates/prune/prune/src/pruner.rs | 12 +- crates/prune/prune/src/segments/mod.rs | 6 +- crates/prune/prune/src/segments/receipts.rs | 6 +- crates/prune/prune/src/segments/set.rs | 2 +- .../prune/src/segments/static_file/headers.rs | 16 +- .../src/segments/static_file/transactions.rs | 6 +- .../src/segments/user/account_history.rs | 8 +- .../prune/prune/src/segments/user/history.rs | 4 +- .../src/segments/user/receipts_by_logs.rs | 21 ++- .../src/segments/user/sender_recovery.rs | 6 +- .../src/segments/user/storage_history.rs | 8 +- .../src/segments/user/transaction_lookup.rs | 12 +- crates/prune/types/src/lib.rs | 4 +- crates/prune/types/src/mode.rs | 2 +- crates/ress/protocol/src/connection.rs | 4 +- crates/ress/protocol/src/provider.rs | 12 +- crates/ress/protocol/tests/it/e2e.rs | 4 +- crates/ress/provider/src/lib.rs | 6 +- crates/ress/provider/src/pending_state.rs | 10 +- crates/revm/src/cached.rs | 18 +- 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/lib.rs | 22 +-- crates/rpc/rpc-builder/tests/it/http.rs | 4 +- crates/rpc/rpc-convert/src/fees.rs | 10 +- crates/rpc/rpc-convert/src/transaction.rs | 2 +- crates/rpc/rpc-engine-api/src/engine_api.rs | 16 +- crates/rpc/rpc-engine-api/src/error.rs | 34 ++-- crates/rpc/rpc-eth-api/src/helpers/block.rs | 4 +- crates/rpc/rpc-eth-api/src/helpers/call.rs | 20 +- .../rpc/rpc-eth-api/src/helpers/estimate.rs | 18 +- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 27 +-- .../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 | 4 +- .../rpc-eth-api/src/helpers/transaction.rs | 8 +- crates/rpc/rpc-eth-types/src/cache/mod.rs | 8 +- crates/rpc/rpc-eth-types/src/error/api.rs | 4 +- crates/rpc/rpc-eth-types/src/error/mod.rs | 104 +++++------ crates/rpc/rpc-eth-types/src/fee_history.rs | 12 +- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 22 +-- crates/rpc/rpc-eth-types/src/id_provider.rs | 2 +- crates/rpc/rpc-eth-types/src/utils.rs | 2 +- crates/rpc/rpc-layer/src/auth_client_layer.rs | 4 +- crates/rpc/rpc-server-types/src/module.rs | 2 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 6 +- crates/rpc/rpc/src/debug.rs | 14 +- crates/rpc/rpc/src/eth/bundle.rs | 15 +- crates/rpc/rpc/src/eth/filter.rs | 16 +- crates/rpc/rpc/src/eth/helpers/block.rs | 2 +- crates/rpc/rpc/src/eth/pubsub.rs | 6 +- crates/rpc/rpc/src/eth/sim_bundle.rs | 10 +- crates/rpc/rpc/src/otterscan.rs | 2 +- crates/rpc/rpc/src/reth.rs | 2 +- crates/rpc/rpc/src/trace.rs | 12 +- crates/rpc/rpc/src/validation.rs | 66 +++---- .../alloy/consensus/src/receipt/envelope.rs | 40 ++-- .../consensus/src/transaction/l1_message.rs | 12 +- crates/scroll/alloy/evm/src/block/feynman.rs | 2 +- crates/scroll/alloy/evm/src/block/mod.rs | 16 +- crates/scroll/alloy/evm/src/system_caller.rs | 4 +- crates/scroll/alloy/evm/src/tx/compression.rs | 2 +- .../alloy/rpc-types-engine/src/attributes.rs | 10 +- crates/scroll/chainspec/src/lib.rs | 10 +- crates/scroll/consensus/src/validation.rs | 20 +- crates/scroll/evm/src/lib.rs | 8 +- crates/scroll/payload/src/builder.rs | 18 +- crates/scroll/payload/src/config.rs | 4 +- crates/scroll/primitives/src/receipt.rs | 66 +++---- crates/scroll/rpc/src/error.rs | 2 +- crates/scroll/rpc/src/eth/block.rs | 2 +- crates/scroll/rpc/src/eth/transaction.rs | 11 +- crates/scroll/rpc/src/lib.rs | 2 +- crates/scroll/rpc/src/sequencer.rs | 10 +- crates/scroll/txpool/src/validator.rs | 8 +- crates/stages/api/src/error.rs | 18 +- crates/stages/api/src/metrics/listener.rs | 2 +- crates/stages/api/src/pipeline/mod.rs | 35 ++-- crates/stages/api/src/pipeline/set.rs | 4 +- crates/stages/api/src/stage.rs | 2 +- crates/stages/stages/src/stages/bodies.rs | 14 +- crates/stages/stages/src/stages/era.rs | 4 +- crates/stages/stages/src/stages/execution.rs | 30 +-- crates/stages/stages/src/stages/finish.rs | 2 +- .../stages/src/stages/hashing_account.rs | 4 +- .../stages/src/stages/hashing_storage.rs | 10 +- crates/stages/stages/src/stages/headers.rs | 18 +- .../src/stages/index_account_history.rs | 4 +- .../src/stages/index_storage_history.rs | 4 +- crates/stages/stages/src/stages/merkle.rs | 24 +-- crates/stages/stages/src/stages/prune.rs | 2 +- .../stages/src/stages/s3/downloader/fetch.rs | 8 +- .../stages/src/stages/s3/downloader/meta.rs | 2 +- crates/stages/stages/src/stages/s3/mod.rs | 16 +- .../stages/src/stages/sender_recovery.rs | 12 +- crates/stages/stages/src/stages/tx_lookup.rs | 6 +- crates/stages/stages/src/stages/utils.rs | 4 +- .../stages/stages/src/test_utils/test_db.rs | 4 +- crates/stages/types/src/checkpoints.rs | 24 +-- crates/stages/types/src/execution.rs | 8 +- crates/stateless/src/trie.rs | 8 +- .../static-file/src/static_file_producer.rs | 6 +- crates/static-file/types/src/lib.rs | 15 +- crates/static-file/types/src/segment.rs | 6 +- .../codecs/derive/src/compact/flags.rs | 4 +- .../codecs/derive/src/compact/generator.rs | 2 +- .../storage/codecs/derive/src/compact/mod.rs | 11 +- .../codecs/derive/src/compact/structs.rs | 2 +- crates/storage/codecs/derive/src/lib.rs | 6 +- crates/storage/codecs/src/lib.rs | 10 +- crates/storage/codecs/src/test_utils.rs | 2 +- crates/storage/db-api/src/cursor.rs | 6 +- .../db-api/src/models/storage_sharded_key.rs | 2 +- crates/storage/db-api/src/unwind.rs | 2 +- crates/storage/db-common/src/db_tool/mod.rs | 16 +- crates/storage/db-common/src/init.rs | 20 +- .../storage/db/src/implementation/mdbx/mod.rs | 4 +- .../storage/db/src/implementation/mdbx/tx.rs | 6 +- crates/storage/db/src/lockfile.rs | 2 +- crates/storage/db/src/static_file/cursor.rs | 4 +- crates/storage/db/src/version.rs | 2 +- crates/storage/libmdbx-rs/mdbx-sys/build.rs | 76 ++++---- crates/storage/libmdbx-rs/src/codec.rs | 6 +- crates/storage/libmdbx-rs/src/cursor.rs | 6 +- crates/storage/libmdbx-rs/src/environment.rs | 8 +- crates/storage/libmdbx-rs/src/error.rs | 6 +- crates/storage/libmdbx-rs/src/transaction.rs | 4 +- .../storage/nippy-jar/src/compression/lz4.rs | 2 +- .../storage/nippy-jar/src/compression/zstd.rs | 14 +- crates/storage/nippy-jar/src/consistency.rs | 16 +- crates/storage/nippy-jar/src/cursor.rs | 4 +- crates/storage/nippy-jar/src/lib.rs | 10 +- crates/storage/nippy-jar/src/writer.rs | 6 +- .../provider/src/providers/consistent.rs | 44 ++--- .../provider/src/providers/consistent_view.rs | 2 +- .../src/providers/database/provider.rs | 69 +++---- .../src/providers/state/historical.rs | 18 +- .../provider/src/providers/state/latest.rs | 2 +- .../provider/src/providers/static_file/jar.rs | 4 +- .../src/providers/static_file/manager.rs | 74 ++++---- .../src/providers/static_file/writer.rs | 10 +- .../storage/provider/src/test_utils/mock.rs | 4 +- crates/storage/provider/src/writer/mod.rs | 4 +- crates/storage/storage-api/src/receipts.rs | 2 +- crates/storage/storage-api/src/state.rs | 4 +- crates/storage/zstd-compressors/src/lib.rs | 2 +- crates/tasks/src/lib.rs | 2 +- crates/tokio-util/src/ratelimit.rs | 2 +- crates/transaction-pool/src/blobstore/disk.rs | 18 +- crates/transaction-pool/src/blobstore/mem.rs | 4 +- crates/transaction-pool/src/blobstore/mod.rs | 4 +- crates/transaction-pool/src/blobstore/noop.rs | 2 +- .../transaction-pool/src/blobstore/tracker.rs | 2 +- crates/transaction-pool/src/config.rs | 12 +- crates/transaction-pool/src/error.rs | 38 ++-- crates/transaction-pool/src/lib.rs | 2 +- crates/transaction-pool/src/maintain.rs | 14 +- crates/transaction-pool/src/noop.rs | 2 +- crates/transaction-pool/src/pool/best.rs | 19 +- crates/transaction-pool/src/pool/blob.rs | 18 +- crates/transaction-pool/src/pool/mod.rs | 26 +-- crates/transaction-pool/src/pool/parked.rs | 8 +- crates/transaction-pool/src/pool/pending.rs | 18 +- crates/transaction-pool/src/pool/state.rs | 8 +- crates/transaction-pool/src/pool/txpool.rs | 56 +++--- .../transaction-pool/src/test_utils/mock.rs | 132 +++++++------- crates/transaction-pool/src/traits.rs | 4 +- crates/transaction-pool/src/validate/eth.rs | 64 +++---- crates/transaction-pool/src/validate/mod.rs | 18 +- crates/trie/common/benches/prefix_set.rs | 8 +- crates/trie/common/src/hashed_state.rs | 4 +- crates/trie/common/src/prefix_set.rs | 12 +- crates/trie/common/src/proofs.rs | 32 ++-- crates/trie/common/src/updates.rs | 6 +- crates/trie/db/tests/witness.rs | 16 +- crates/trie/parallel/src/proof.rs | 61 +++---- crates/trie/parallel/src/proof_task.rs | 2 +- crates/trie/sparse-parallel/src/trie.rs | 61 ++++--- crates/trie/sparse/src/state.rs | 20 +- crates/trie/sparse/src/trie.rs | 69 +++---- .../trie/trie/src/hashed_cursor/post_state.rs | 6 +- crates/trie/trie/src/node_iter.rs | 14 +- crates/trie/trie/src/proof/mod.rs | 2 +- crates/trie/trie/src/trie.rs | 10 +- crates/trie/trie/src/trie_cursor/in_memory.rs | 6 +- crates/trie/trie/src/walker.rs | 16 +- crates/trie/trie/src/witness.rs | 4 +- .../src/mined_sidecar.rs | 6 +- examples/custom-engine-types/src/main.rs | 2 +- examples/custom-node/src/engine.rs | 2 +- .../custom-node/src/primitives/tx_custom.rs | 14 +- .../src/subprotocol/connection/mod.rs | 10 +- .../src/subprotocol/protocol/proto.rs | 6 +- examples/manual-p2p/src/main.rs | 6 +- examples/node-custom-rpc/src/main.rs | 2 +- examples/precompile-cache/src/main.rs | 2 +- testing/ef-tests/src/cases/blockchain_test.rs | 16 +- testing/ef-tests/src/models.rs | 20 +- testing/testing-utils/src/generators.rs | 2 +- 392 files changed, 2504 insertions(+), 2489 deletions(-) diff --git a/bin/reth-bench/src/valid_payload.rs b/bin/reth-bench/src/valid_payload.rs index e2f83a0ec2..abcb32e747 100644 --- a/bin/reth-bench/src/valid_payload.rs +++ b/bin/reth-bench/src/valid_payload.rs @@ -133,7 +133,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )) + )); } status = self .new_payload_v3(payload.clone(), versioned_hashes.clone(), parent_beacon_block_root) @@ -178,7 +178,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )) + )); } status = self .client() @@ -217,7 +217,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )) + )); } status = self.fork_choice_updated_v1(fork_choice_state, payload_attributes.clone()).await?; @@ -247,7 +247,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )) + )); } status = self.fork_choice_updated_v2(fork_choice_state, payload_attributes.clone()).await?; diff --git a/crates/alloy-provider/src/lib.rs b/crates/alloy-provider/src/lib.rs index ba4767006a..0978808c12 100644 --- a/crates/alloy-provider/src/lib.rs +++ b/crates/alloy-provider/src/lib.rs @@ -828,9 +828,9 @@ impl AlloyRethStateProvider { .map_err(ProviderError::other)?; // Only return account if it exists (has balance, nonce, or code) - if account_info.balance.is_zero() && - account_info.nonce == 0 && - account_info.code.is_empty() + if account_info.balance.is_zero() + && account_info.nonce == 0 + && account_info.code.is_empty() { Ok(None) } else { @@ -1711,9 +1711,9 @@ where .map_err(ProviderError::other)?; // Only return account if it exists - if account_info.balance.is_zero() && - account_info.nonce == 0 && - account_info.code.is_empty() + if account_info.balance.is_zero() + && account_info.nonce == 0 + && account_info.code.is_empty() { Ok(None) } else { diff --git a/crates/chain-state/src/chain_info.rs b/crates/chain-state/src/chain_info.rs index a8a0843056..191e7765ba 100644 --- a/crates/chain-state/src/chain_info.rs +++ b/crates/chain-state/src/chain_info.rs @@ -111,7 +111,7 @@ where self.inner.safe_block.send_if_modified(|current_header| { if current_header.as_ref().map(SealedHeader::hash) != Some(header.hash()) { let _ = current_header.replace(header); - return true + return true; } false @@ -123,7 +123,7 @@ where self.inner.finalized_block.send_if_modified(|current_header| { if current_header.as_ref().map(SealedHeader::hash) != Some(header.hash()) { let _ = current_header.replace(header); - return true + return true; } false diff --git a/crates/chain-state/src/in_memory.rs b/crates/chain-state/src/in_memory.rs index 20f2a2a4c2..4fdb7b1cde 100644 --- a/crates/chain-state/src/in_memory.rs +++ b/crates/chain-state/src/in_memory.rs @@ -316,7 +316,7 @@ impl CanonicalInMemoryState { { if self.inner.in_memory_state.blocks.read().get(&persisted_num_hash.hash).is_none() { // do nothing - return + return; } } @@ -540,7 +540,7 @@ impl CanonicalInMemoryState { if let Some(tx) = block_state.block_ref().recovered_block().body().transaction_by_hash(&hash) { - return Some(tx.clone()) + return Some(tx.clone()); } } None @@ -570,7 +570,7 @@ impl CanonicalInMemoryState { timestamp: block_state.block_ref().recovered_block().timestamp(), excess_blob_gas: block_state.block_ref().recovered_block().excess_blob_gas(), }; - return Some((tx.clone(), meta)) + return Some((tx.clone(), meta)); } } None diff --git a/crates/chain-state/src/notifications.rs b/crates/chain-state/src/notifications.rs index abf2405c87..134e201de4 100644 --- a/crates/chain-state/src/notifications.rs +++ b/crates/chain-state/src/notifications.rs @@ -68,10 +68,10 @@ impl Stream for CanonStateNotificationStream { Some(Ok(notification)) => Poll::Ready(Some(notification)), Some(Err(err)) => { debug!(%err, "canonical state notification stream lagging behind"); - continue + continue; } None => Poll::Ready(None), - } + }; } } } diff --git a/crates/chain-state/src/test_utils.rs b/crates/chain-state/src/test_utils.rs index 499a47de59..334bd4fea1 100644 --- a/crates/chain-state/src/test_utils.rs +++ b/crates/chain-state/src/test_utils.rs @@ -163,8 +163,8 @@ impl TestBlockBuilder { .into_trie_account(EMPTY_ROOT_HASH), )])), // use the number as the timestamp so it is monotonically increasing - timestamp: number + - EthereumHardfork::Cancun.activation_timestamp(self.chain_spec.chain).unwrap(), + timestamp: number + + EthereumHardfork::Cancun.activation_timestamp(self.chain_spec.chain).unwrap(), withdrawals_root: Some(calculate_withdrawals_root(&[])), blob_gas_used: Some(0), excess_blob_gas: Some(0), diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index 7accf96fa3..62090d3230 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -384,7 +384,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.hardforks.is_fork_active_at_timestamp(fork.clone(), timestamp) { - return *params + return *params; } } @@ -403,7 +403,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.hardforks.is_fork_active_at_block(fork.clone(), block_number) { - return *params + return *params; } } @@ -477,8 +477,8 @@ impl ChainSpec { // We filter out TTD-based forks w/o a pre-known block since those do not show up in the // fork filter. Some(match condition { - ForkCondition::Block(block) | - ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), + ForkCondition::Block(block) + | ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), ForkCondition::Timestamp(time) => ForkFilterKey::Time(time), _ => return None, }) @@ -505,8 +505,8 @@ impl ChainSpec { for (_, cond) in self.hardforks.forks_iter() { // handle block based forks and the sepolia merge netsplit block edge case (TTD // ForkCondition with Some(block)) - if let ForkCondition::Block(block) | - ForkCondition::TTD { fork_block: Some(block), .. } = cond + if let ForkCondition::Block(block) + | ForkCondition::TTD { fork_block: Some(block), .. } = cond { if head.number >= block { // skip duplicated hardforks: hardforks enabled at genesis block @@ -517,7 +517,7 @@ impl ChainSpec { } else { // we can return here because this block fork is not active, so we set the // `next` value - return ForkId { hash: forkhash, next: block } + return ForkId { hash: forkhash, next: block }; } } } @@ -539,7 +539,7 @@ impl ChainSpec { // can safely return here because we have already handled all block forks and // have handled all active timestamp forks, and set the next value to the // timestamp that is known but not active yet - return ForkId { hash: forkhash, next: timestamp } + return ForkId { hash: forkhash, next: timestamp }; } } diff --git a/crates/cli/cli/src/chainspec.rs b/crates/cli/cli/src/chainspec.rs index b70430a910..00a6363323 100644 --- a/crates/cli/cli/src/chainspec.rs +++ b/crates/cli/cli/src/chainspec.rs @@ -75,7 +75,7 @@ pub fn parse_genesis(s: &str) -> eyre::Result { if s.contains('{') { s.to_string() } else { - return Err(io_err.into()) // assume invalid path + return Err(io_err.into()); // assume invalid path } } }; diff --git a/crates/cli/commands/src/common.rs b/crates/cli/commands/src/common.rs index be3bcec5a1..9b56da6742 100644 --- a/crates/cli/commands/src/common.rs +++ b/crates/cli/commands/src/common.rs @@ -143,7 +143,7 @@ impl EnvironmentArgs { { if factory.db_ref().is_read_only()? { warn!(target: "reth::cli", ?unwind_target, "Inconsistent storage. Restart node to heal."); - return Ok(factory) + return Ok(factory); } // Highly unlikely to happen, and given its destructive nature, it's better to panic diff --git a/crates/cli/commands/src/db/checksum.rs b/crates/cli/commands/src/db/checksum.rs index 40f0d22f6d..73142314db 100644 --- a/crates/cli/commands/src/db/checksum.rs +++ b/crates/cli/commands/src/db/checksum.rs @@ -125,7 +125,7 @@ impl TableViewer<(u64, Duration)> for ChecksumViewer<'_, N total = index + 1; if total >= limit { - break + break; } } diff --git a/crates/cli/commands/src/db/diff.rs b/crates/cli/commands/src/db/diff.rs index b22930302f..95f1b324c6 100644 --- a/crates/cli/commands/src/db/diff.rs +++ b/crates/cli/commands/src/db/diff.rs @@ -309,12 +309,12 @@ where ) { // do not bother comparing if the key is already in the discrepancies map if self.discrepancies.contains_key(&key) { - return + return; } // do not bother comparing if the key is already in the extra elements map if self.extra_elements.contains_key(&key) { - return + return; } match (first, second) { diff --git a/crates/cli/commands/src/db/list.rs b/crates/cli/commands/src/db/list.rs index 9288a56a86..bf8b705412 100644 --- a/crates/cli/commands/src/db/list.rs +++ b/crates/cli/commands/src/db/list.rs @@ -67,7 +67,7 @@ impl Command { .as_ref() .map(|search| { if let Some(search) = search.strip_prefix("0x") { - return hex::decode(search).unwrap() + return hex::decode(search).unwrap(); } search.as_bytes().to_vec() }) diff --git a/crates/cli/commands/src/db/mod.rs b/crates/cli/commands/src/db/mod.rs index 67b060f7e9..ddc3886c40 100644 --- a/crates/cli/commands/src/db/mod.rs +++ b/crates/cli/commands/src/db/mod.rs @@ -123,7 +123,7 @@ impl> Command if !input.trim().eq_ignore_ascii_case("y") { println!("Database drop aborted!"); - return Ok(()) + return Ok(()); } } diff --git a/crates/cli/commands/src/db/stats.rs b/crates/cli/commands/src/db/stats.rs index c8398d795c..df25c07624 100644 --- a/crates/cli/commands/src/db/stats.rs +++ b/crates/cli/commands/src/db/stats.rs @@ -291,10 +291,10 @@ impl Command { .add_cell(Cell::new(human_bytes(segment_config_size as f64))); } row.add_cell(Cell::new(human_bytes( - (segment_data_size + - segment_index_size + - segment_offsets_size + - segment_config_size) as f64, + (segment_data_size + + segment_index_size + + segment_offsets_size + + segment_config_size) as f64, ))); table.add_row(row); } diff --git a/crates/cli/commands/src/db/tui.rs b/crates/cli/commands/src/db/tui.rs index 800c17b8ef..213ffa0c35 100644 --- a/crates/cli/commands/src/db/tui.rs +++ b/crates/cli/commands/src/db/tui.rs @@ -291,7 +291,7 @@ where } } - return Ok(false) + return Ok(false); } match event { diff --git a/crates/cli/commands/src/import.rs b/crates/cli/commands/src/import.rs index eef6711706..193369e768 100644 --- a/crates/cli/commands/src/import.rs +++ b/crates/cli/commands/src/import.rs @@ -143,8 +143,8 @@ impl> ImportComm let total_imported_blocks = provider.tx_ref().entries::()?; let total_imported_txns = provider.tx_ref().entries::()?; - if total_decoded_blocks != total_imported_blocks || - total_decoded_txns != total_imported_txns + if total_decoded_blocks != total_imported_blocks + || total_decoded_txns != total_imported_txns { error!(target: "reth::cli", total_decoded_blocks, diff --git a/crates/cli/commands/src/import_era.rs b/crates/cli/commands/src/import_era.rs index 7920fda313..ebb569cdba 100644 --- a/crates/cli/commands/src/import_era.rs +++ b/crates/cli/commands/src/import_era.rs @@ -77,8 +77,8 @@ impl> ImportEraC let next_block = provider_factory .static_file_provider() .get_highest_static_file_block(StaticFileSegment::Headers) - .unwrap_or_default() + - 1; + .unwrap_or_default() + + 1; if let Some(path) = self.import.path { let stream = read_dir(path, next_block)?; diff --git a/crates/cli/commands/src/init_state/without_evm.rs b/crates/cli/commands/src/init_state/without_evm.rs index c839aaf268..7dad0b64c3 100644 --- a/crates/cli/commands/src/init_state/without_evm.rs +++ b/crates/cli/commands/src/init_state/without_evm.rs @@ -148,7 +148,7 @@ where while let Ok(append_result) = rx.recv() { if let Err(err) = append_result { tracing::error!(target: "reth::cli", "Error appending dummy chain: {err}"); - return Err(err) + return Err(err); } } diff --git a/crates/cli/commands/src/stage/dump/hashing_account.rs b/crates/cli/commands/src/stage/dump/hashing_account.rs index 8b9ba5e937..8d2ac1a554 100644 --- a/crates/cli/commands/src/stage/dump/hashing_account.rs +++ b/crates/cli/commands/src/stage/dump/hashing_account.rs @@ -93,7 +93,7 @@ fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/crates/cli/commands/src/stage/dump/hashing_storage.rs b/crates/cli/commands/src/stage/dump/hashing_storage.rs index 265048354b..7f520f1103 100644 --- a/crates/cli/commands/src/stage/dump/hashing_storage.rs +++ b/crates/cli/commands/src/stage/dump/hashing_storage.rs @@ -88,7 +88,7 @@ fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/crates/cli/commands/src/stage/dump/merkle.rs b/crates/cli/commands/src/stage/dump/merkle.rs index cc21c0fc29..357522541d 100644 --- a/crates/cli/commands/src/stage/dump/merkle.rs +++ b/crates/cli/commands/src/stage/dump/merkle.rs @@ -172,7 +172,7 @@ where checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/crates/cli/commands/src/stage/run.rs b/crates/cli/commands/src/stage/run.rs index bba9858f21..ae792528fe 100644 --- a/crates/cli/commands/src/stage/run.rs +++ b/crates/cli/commands/src/stage/run.rs @@ -188,7 +188,7 @@ impl match fetch_client.get_header(BlockHashOrNumber::Number(self.to)).await { Ok(header) => { if let Some(header) = header.into_data() { - break header + break header; } } Err(error) if error.is_retryable() => { @@ -246,8 +246,8 @@ impl config.stages.bodies.downloader_max_buffered_blocks_size_bytes, ) .with_concurrent_requests_range( - config.stages.bodies.downloader_min_concurrent_requests..= - config.stages.bodies.downloader_max_concurrent_requests, + config.stages.bodies.downloader_min_concurrent_requests + ..=config.stages.bodies.downloader_max_concurrent_requests, ) .build(fetch_client, consensus.clone(), provider_factory.clone()), ); @@ -377,7 +377,7 @@ impl } if done { - break + break; } } info!(target: "reth::cli", stage = %self.stage, time = ?start.elapsed(), "Finished stage"); diff --git a/crates/cli/commands/src/test_vectors/compact.rs b/crates/cli/commands/src/test_vectors/compact.rs index abd3635e4f..d38911ef48 100644 --- a/crates/cli/commands/src/test_vectors/compact.rs +++ b/crates/cli/commands/src/test_vectors/compact.rs @@ -215,7 +215,7 @@ where tries += 1; bytes.extend(std::iter::repeat_n(0u8, 256)); } else { - return Err(err)? + return Err(err)?; } } } diff --git a/crates/cli/commands/src/test_vectors/tables.rs b/crates/cli/commands/src/test_vectors/tables.rs index 1bbd2604f9..e30286b965 100644 --- a/crates/cli/commands/src/test_vectors/tables.rs +++ b/crates/cli/commands/src/test_vectors/tables.rs @@ -133,7 +133,7 @@ where let key: T::Key = start_keys.new_tree(runner).map_err(|e| eyre::eyre!("{e}"))?.current(); if !seen_keys.insert(key.clone()) { - continue + continue; } let mut values: Vec = diff --git a/crates/cli/util/src/parsers.rs b/crates/cli/util/src/parsers.rs index ddb120452e..2c7868b3ad 100644 --- a/crates/cli/util/src/parsers.rs +++ b/crates/cli/util/src/parsers.rs @@ -68,15 +68,15 @@ pub enum SocketAddressParsingError { /// An error is returned if the value is empty. pub fn parse_socket_address(value: &str) -> eyre::Result { if value.is_empty() { - return Err(SocketAddressParsingError::Empty) + return Err(SocketAddressParsingError::Empty); } if let Some(port) = value.strip_prefix(':').or_else(|| value.strip_prefix("localhost:")) { let port: u16 = port.parse()?; - return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)) + return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)); } if let Ok(port) = value.parse() { - return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)) + return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)); } value .to_socket_addrs()? @@ -100,7 +100,7 @@ pub fn read_json_from_file(path: &str) -> Result pub fn parse_ether_value(value: &str) -> eyre::Result { let eth = value.parse::()?; if eth.is_sign_negative() { - return Err(eyre::eyre!("Ether value cannot be negative")) + return Err(eyre::eyre!("Ether value cannot be negative")); } let wei = eth * 1e18; Ok(wei as u128) diff --git a/crates/cli/util/src/sigsegv_handler.rs b/crates/cli/util/src/sigsegv_handler.rs index b0a195391f..606478649f 100644 --- a/crates/cli/util/src/sigsegv_handler.rs +++ b/crates/cli/util/src/sigsegv_handler.rs @@ -49,7 +49,7 @@ extern "C" fn print_stack_trace(_: libc::c_int) { // Collect return addresses let depth = libc::backtrace(stack_trace.as_mut_ptr(), MAX_FRAMES as i32); if depth == 0 { - return + return; } &stack_trace[0..depth as usize] }; @@ -67,7 +67,7 @@ extern "C" fn print_stack_trace(_: libc::c_int) { let period = period.saturating_add(1); // avoid "what if wrapped?" branches let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else { // impossible. - return + return; }; // Count matching trace slices, else we could miscount "biphasic cycles" diff --git a/crates/consensus/common/src/validation.rs b/crates/consensus/common/src/validation.rs index a682bc2f91..0a1556e242 100644 --- a/crates/consensus/common/src/validation.rs +++ b/crates/consensus/common/src/validation.rs @@ -18,11 +18,11 @@ pub fn validate_header_gas(header: &H) -> Result<(), ConsensusEr return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { gas_used: header.gas_used(), gas_limit: header.gas_limit(), - }) + }); } // Check that the gas limit is below the maximum allowed gas limit if header.gas_limit() > MAXIMUM_GAS_LIMIT_BLOCK { - return Err(ConsensusError::HeaderGasLimitExceedsMax { gas_limit: header.gas_limit() }) + return Err(ConsensusError::HeaderGasLimitExceedsMax { gas_limit: header.gas_limit() }); } Ok(()) } @@ -35,7 +35,7 @@ pub fn validate_header_base_fee( ) -> Result<(), ConsensusError> { if chain_spec.is_london_active_at_block(header.number()) && header.base_fee_per_gas().is_none() { - return Err(ConsensusError::BaseFeeMissing) + return Err(ConsensusError::BaseFeeMissing); } Ok(()) } @@ -100,14 +100,14 @@ where expected: header.ommers_hash(), } .into(), - )) + )); } let tx_root = body.calculate_tx_root(); if header.transactions_root() != tx_root { return Err(ConsensusError::BodyTransactionRootDiff( GotExpected { got: tx_root, expected: header.transactions_root() }.into(), - )) + )); } match (header.withdrawals_root(), body.calculate_withdrawals_root()) { @@ -115,7 +115,7 @@ where if withdrawals_root != header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root }.into(), - )) + )); } } (None, None) => { @@ -150,12 +150,12 @@ where expected: block.ommers_hash(), } .into(), - )) + )); } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())) + return Err(ConsensusError::BodyTransactionRootDiff(error.into())); } // EIP-4895: Beacon chain push withdrawals as operations @@ -187,21 +187,21 @@ pub fn validate_4844_header_standalone( let blob_gas_used = header.blob_gas_used().ok_or(ConsensusError::BlobGasUsedMissing)?; if header.parent_beacon_block_root().is_none() { - return Err(ConsensusError::ParentBeaconBlockRootMissing) + return Err(ConsensusError::ParentBeaconBlockRootMissing); } if blob_gas_used % DATA_GAS_PER_BLOB != 0 { return Err(ConsensusError::BlobGasUsedNotMultipleOfBlobGasPerBlob { blob_gas_used, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }) + }); } if blob_gas_used > blob_params.max_blob_gas_per_block() { return Err(ConsensusError::BlobGasUsedExceedsMaxBlobGasPerBlock { blob_gas_used, max_blob_gas_per_block: blob_params.max_blob_gas_per_block(), - }) + }); } Ok(()) @@ -235,13 +235,13 @@ pub fn validate_against_parent_hash_number( return Err(ConsensusError::ParentBlockNumberMismatch { parent_block_number: parent.number(), block_number: header.number(), - }) + }); } if parent.hash() != header.parent_hash() { return Err(ConsensusError::ParentHashMismatch( GotExpected { got: header.parent_hash(), expected: parent.hash() }.into(), - )) + )); } Ok(()) @@ -271,7 +271,7 @@ pub fn validate_against_parent_eip1559_base_fee( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp(), timestamp: header.timestamp(), - }) + }); } Ok(()) } @@ -312,7 +312,7 @@ pub fn validate_against_parent_4844( let parent_excess_blob_gas = parent.excess_blob_gas().unwrap_or(0); if header.blob_gas_used().is_none() { - return Err(ConsensusError::BlobGasUsedMissing) + return Err(ConsensusError::BlobGasUsedMissing); } let excess_blob_gas = header.excess_blob_gas().ok_or(ConsensusError::ExcessBlobGasMissing)?; @@ -323,7 +323,7 @@ pub fn validate_against_parent_4844( diff: GotExpected { got: excess_blob_gas, expected: expected_excess_blob_gas }, parent_excess_blob_gas, parent_blob_gas_used, - }) + }); } Ok(()) diff --git a/crates/consensus/consensus/src/lib.rs b/crates/consensus/consensus/src/lib.rs index 951c2c0ef5..d0a71aca2a 100644 --- a/crates/consensus/consensus/src/lib.rs +++ b/crates/consensus/consensus/src/lib.rs @@ -133,7 +133,7 @@ pub fn validate_state_root(header: &H, root: B256) -> Result<(), if header.state_root() != root { return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: root, expected: header.state_root() }.into(), - )) + )); } Ok(()) diff --git a/crates/consensus/debug-client/src/providers/etherscan.rs b/crates/consensus/debug-client/src/providers/etherscan.rs index c52ee609d2..4c09250806 100644 --- a/crates/consensus/debug-client/src/providers/etherscan.rs +++ b/crates/consensus/debug-client/src/providers/etherscan.rs @@ -99,7 +99,7 @@ where %err, "Failed to fetch a block from Etherscan", ); - continue + continue; } }; let block_number = block.header().number(); diff --git a/crates/e2e-test-utils/src/network.rs b/crates/e2e-test-utils/src/network.rs index dd703b312e..126736c9f5 100644 --- a/crates/e2e-test-utils/src/network.rs +++ b/crates/e2e-test-utils/src/network.rs @@ -43,11 +43,11 @@ where pub async fn next_session_established(&mut self) -> Option { while let Some(ev) = self.network_events.next().await { match ev { - NetworkEvent::ActivePeerSession { info, .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { let peer_id = info.peer_id; info!("Session established with peer: {:?}", peer_id); - return Some(peer_id) + return Some(peer_id); } _ => {} } diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 0261978a66..688390abb7 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -168,7 +168,7 @@ where if check { if let Some(latest_block) = self.inner.provider.block_by_number(number)? { assert_eq!(latest_block.header().hash_slow(), expected_block_hash); - break + break; } assert!( !wait_finish_checkpoint, @@ -185,7 +185,7 @@ where tokio::time::sleep(std::time::Duration::from_millis(10)).await; if let Some(checkpoint) = self.inner.provider.get_stage_checkpoint(StageId::Headers)? { if checkpoint.block_number == number { - break + break; } } } @@ -218,7 +218,7 @@ where // make sure the block hash we submitted via FCU engine api is the new latest // block using an RPC call assert_eq!(latest_block.header().hash_slow(), block_hash); - break + break; } } } diff --git a/crates/e2e-test-utils/src/payload.rs b/crates/e2e-test-utils/src/payload.rs index b3f9b027fb..545850f899 100644 --- a/crates/e2e-test-utils/src/payload.rs +++ b/crates/e2e-test-utils/src/payload.rs @@ -60,7 +60,7 @@ impl PayloadTestContext { let payload = self.payload_builder.best_payload(payload_id).await.unwrap().unwrap(); if payload.block().body().transactions().is_empty() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; - continue + continue; } // Resolve payload once its built self.payload_builder diff --git a/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs b/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs index c20b79d9ae..4215c1d855 100644 --- a/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs +++ b/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs @@ -256,8 +256,8 @@ where debug!("No payload ID returned, generating fresh payload attributes for forking"); let fresh_payload_attributes = PayloadAttributes { - timestamp: env.active_node_state()?.latest_header_time + - env.block_timestamp_increment, + timestamp: env.active_node_state()?.latest_header_time + + env.block_timestamp_increment, prev_randao: B256::random(), suggested_fee_recipient: alloy_primitives::Address::random(), withdrawals: Some(vec![]), diff --git a/crates/engine/local/src/miner.rs b/crates/engine/local/src/miner.rs index a3318f1f5c..30a9745785 100644 --- a/crates/engine/local/src/miner.rs +++ b/crates/engine/local/src/miner.rs @@ -55,13 +55,13 @@ impl Future for MiningMode { Self::Instant(rx) => { // drain all transactions notifications if let Poll::Ready(Some(_)) = rx.poll_next_unpin(cx) { - return Poll::Ready(()) + return Poll::Ready(()); } Poll::Pending } Self::Interval(interval) => { if interval.poll_tick(cx).is_ready() { - return Poll::Ready(()) + return Poll::Ready(()); } Poll::Pending } diff --git a/crates/engine/tree/src/backfill.rs b/crates/engine/tree/src/backfill.rs index 9dad8c32a5..4038bf02d1 100644 --- a/crates/engine/tree/src/backfill.rs +++ b/crates/engine/tree/src/backfill.rs @@ -124,7 +124,7 @@ impl PipelineSync { "Pipeline target cannot be zero hash." ); // precaution to never sync to the zero hash - return + return; } self.pending_pipeline_target = Some(target); } @@ -187,14 +187,14 @@ impl BackfillSync for PipelineSync { fn poll(&mut self, cx: &mut Context<'_>) -> Poll { // try to spawn a pipeline if a target is set if let Some(event) = self.try_spawn_pipeline() { - return Poll::Ready(event) + return Poll::Ready(event); } // make sure we poll the pipeline if it's active, and return any ready pipeline events if self.is_pipeline_active() { // advance the pipeline if let Poll::Ready(event) = self.poll_pipeline(cx) { - return Poll::Ready(event) + return Poll::Ready(event); } } diff --git a/crates/engine/tree/src/chain.rs b/crates/engine/tree/src/chain.rs index e2893bb976..2850097074 100644 --- a/crates/engine/tree/src/chain.rs +++ b/crates/engine/tree/src/chain.rs @@ -100,7 +100,7 @@ where tracing::error!( %err, "backfill sync failed"); Poll::Ready(ChainEvent::FatalError) } - } + }; } BackfillEvent::TaskDropped(err) => { tracing::error!( %err, "backfill sync task dropped"); @@ -124,13 +124,13 @@ where } HandlerEvent::FatalError => { error!(target: "engine::tree", "Fatal error"); - return Poll::Ready(ChainEvent::FatalError) + return Poll::Ready(ChainEvent::FatalError); } } } Poll::Pending => { // no more events to process - break 'outer + break 'outer; } } } diff --git a/crates/engine/tree/src/download.rs b/crates/engine/tree/src/download.rs index 5d7d52af84..afea7790be 100644 --- a/crates/engine/tree/src/download.rs +++ b/crates/engine/tree/src/download.rs @@ -144,7 +144,7 @@ where /// given hash. fn download_full_block(&mut self, hash: B256) -> bool { if self.is_inflight_request(hash) { - return false + return false; } self.push_pending_event(DownloadOutcome::NewDownloadStarted { remaining_blocks: 1, @@ -172,8 +172,8 @@ where /// Sets the metrics for the active downloads fn update_block_download_metrics(&self) { - let blocks = self.inflight_full_block_requests.len() + - self.inflight_block_range_requests.iter().map(|r| r.count() as usize).sum::(); + 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); } @@ -256,7 +256,7 @@ where if peek.0 .0.hash() == block.0 .0.hash() { PeekMut::pop(peek); } else { - break + break; } } downloaded_blocks.push(block.0.into()); diff --git a/crates/engine/tree/src/engine.rs b/crates/engine/tree/src/engine.rs index 16ba103439..572f515ebb 100644 --- a/crates/engine/tree/src/engine.rs +++ b/crates/engine/tree/src/engine.rs @@ -96,7 +96,7 @@ where Poll::Ready(HandlerEvent::Event(ev)) } HandlerEvent::FatalError => Poll::Ready(HandlerEvent::FatalError), - } + }; } RequestHandlerEvent::Download(req) => { // delegate download request to the downloader @@ -110,7 +110,7 @@ where // and delegate the request to the handler self.handler.on_event(FromEngine::Request(req.into())); // skip downloading in this iteration to allow the handler to process the request - continue + continue; } // advance the downloader @@ -119,10 +119,10 @@ where // delegate the downloaded blocks to the handler self.handler.on_event(FromEngine::DownloadedBlocks(blocks)); } - continue + continue; } - return Poll::Pending + return Poll::Pending; } } } @@ -202,7 +202,7 @@ where fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { let Some(ev) = ready!(self.from_tree.poll_recv(cx)) else { - return Poll::Ready(RequestHandlerEvent::HandlerEvent(HandlerEvent::FatalError)) + return Poll::Ready(RequestHandlerEvent::HandlerEvent(HandlerEvent::FatalError)); }; let ev = match ev { diff --git a/crates/engine/tree/src/tree/block_buffer.rs b/crates/engine/tree/src/tree/block_buffer.rs index 6da92818e2..3e842c7084 100644 --- a/crates/engine/tree/src/tree/block_buffer.rs +++ b/crates/engine/tree/src/tree/block_buffer.rs @@ -109,7 +109,7 @@ impl BlockBuffer { // discard all blocks that are before the finalized number. while let Some(entry) = self.earliest_blocks.first_entry() { if *entry.key() > block_number { - break + break; } let block_hashes = entry.remove(); block_hashes_to_remove.extend(block_hashes); diff --git a/crates/engine/tree/src/tree/cached_state.rs b/crates/engine/tree/src/tree/cached_state.rs index bce9949564..bfdb849cea 100644 --- a/crates/engine/tree/src/tree/cached_state.rs +++ b/crates/engine/tree/src/tree/cached_state.rs @@ -117,7 +117,7 @@ impl AccountReader for CachedStateProvider { fn basic_account(&self, address: &Address) -> ProviderResult> { if let Some(res) = self.caches.account_cache.get(address) { self.metrics.account_cache_hits.increment(1); - return Ok(res) + return Ok(res); } self.metrics.account_cache_misses.increment(1); @@ -168,7 +168,7 @@ impl BytecodeReader for CachedStateProvider { fn bytecode_by_hash(&self, code_hash: &B256) -> ProviderResult> { if let Some(res) = self.caches.code_cache.get(code_hash) { self.metrics.code_cache_hits.increment(1); - return Ok(res) + return Ok(res); } self.metrics.code_cache_misses.increment(1); @@ -352,7 +352,7 @@ impl ProviderCaches { // If the account was not modified, as in not changed and not destroyed, then we have // nothing to do w.r.t. this particular account and can move on if account.status.is_not_modified() { - continue + continue; } // If the account was destroyed, invalidate from the account / storage caches @@ -361,7 +361,7 @@ impl ProviderCaches { self.account_cache.invalidate(addr); self.invalidate_account_storage(addr); - continue + continue; } // If we have an account that was modified, but it has a `None` account info, some wild @@ -369,7 +369,7 @@ impl ProviderCaches { // `None` current info, should be destroyed. let Some(ref account_info) = account.info else { trace!(target: "engine::caching", ?account, "Account with None account info found in state updates"); - return Err(()) + return Err(()); }; // Now we iterate over all storage and make updates to the cached storage values diff --git a/crates/engine/tree/src/tree/invalid_headers.rs b/crates/engine/tree/src/tree/invalid_headers.rs index d349901a19..2fec318fb7 100644 --- a/crates/engine/tree/src/tree/invalid_headers.rs +++ b/crates/engine/tree/src/tree/invalid_headers.rs @@ -42,7 +42,7 @@ impl InvalidHeaderCache { let entry = self.headers.get(hash)?; entry.hit_count += 1; if entry.hit_count < INVALID_HEADER_HIT_EVICTION_THRESHOLD { - return Some(entry.header) + return Some(entry.header); } } // if we get here, the entry has been hit too many times, so we evict it diff --git a/crates/engine/tree/src/tree/mod.rs b/crates/engine/tree/src/tree/mod.rs index a88c109787..1e79c467d6 100644 --- a/crates/engine/tree/src/tree/mod.rs +++ b/crates/engine/tree/src/tree/mod.rs @@ -452,7 +452,7 @@ where debug!(target: "engine::tree", %msg, "received new engine message"); if let Err(fatal) = self.on_engine_message(msg) { error!(target: "engine::tree", %fatal, "insert block fatal error"); - return + return; } } Ok(None) => { @@ -460,13 +460,13 @@ where } Err(_err) => { error!(target: "engine::tree", "Engine channel disconnected"); - return + return; } } if let Err(err) = self.advance_persistence() { error!(target: "engine::tree", %err, "Advancing persistence failed"); - return + return; } } } @@ -482,7 +482,7 @@ where ) -> Result, InsertBlockFatalError> { if blocks.is_empty() { // nothing to execute - return Ok(None) + return Ok(None); } trace!(target: "engine::tree", block_count = %blocks.len(), "received downloaded blocks"); @@ -493,7 +493,7 @@ where self.on_tree_event(event)?; if needs_backfill { // can exit early if backfill is needed - return Ok(None) + return Ok(None); } } } @@ -571,7 +571,7 @@ where }; let status = PayloadStatusEnum::from(error); - return Ok(TreeOutcome::new(PayloadStatus::new(status, latest_valid_hash))) + return Ok(TreeOutcome::new(PayloadStatus::new(status, latest_valid_hash))); } }; @@ -589,7 +589,7 @@ where if let Some(status) = self.check_invalid_ancestor_with_head(lowest_buffered_ancestor, &block)? { - return Ok(TreeOutcome::new(status)) + return Ok(TreeOutcome::new(status)); } let status = if self.backfill_sync_state.is_idle() { @@ -607,8 +607,8 @@ where latest_valid_hash = Some(block_hash); PayloadStatusEnum::Valid } - InsertPayloadOk::Inserted(BlockStatus::Disconnected { .. }) | - InsertPayloadOk::AlreadySeen(BlockStatus::Disconnected { .. }) => { + InsertPayloadOk::Inserted(BlockStatus::Disconnected { .. }) + | InsertPayloadOk::AlreadySeen(BlockStatus::Disconnected { .. }) => { // not known to be invalid, but we don't know anything else PayloadStatusEnum::Syncing } @@ -648,7 +648,7 @@ where // get the executed new head block let Some(new_head_block) = self.state.tree_state.blocks_by_hash.get(&new_head) else { debug!(target: "engine::tree", new_head=?new_head, "New head block not found in inmemory tree state"); - return Ok(None) + return Ok(None); }; let new_head_number = new_head_block.recovered_block().number(); @@ -751,11 +751,11 @@ where let mut current_block = Cow::Borrowed(target_header); loop { if current_block.hash() == canonical_head.hash { - return Ok(false) + return Ok(false); } // We already passed the canonical head if current_block.number() <= canonical_head.number { - break + break; } current_hash = current_block.parent_hash(); @@ -765,12 +765,12 @@ where // verify that the given hash is not already part of canonical chain stored in memory if self.canonical_in_memory_state.header_by_hash(target_hash).is_some() { - return Ok(false) + return Ok(false); } // verify that the given hash is not already part of persisted canonical chain if self.provider.block_number(target_hash)?.is_some() { - return Ok(false) + return Ok(false); } Ok(true) @@ -800,17 +800,17 @@ where fn persisting_kind_for(&self, block: &N::BlockHeader) -> PersistingKind { // Check that we're currently persisting. let Some(action) = self.persistence_state.current_action() else { - return PersistingKind::NotPersisting + return PersistingKind::NotPersisting; }; // Check that the persistince action is saving blocks, not removing them. let CurrentPersistenceAction::SavingBlocks { highest } = action else { - return PersistingKind::PersistingNotDescendant + return PersistingKind::PersistingNotDescendant; }; // The block being validated can only be a descendant if its number is higher than // the highest block persisting. Otherwise, it's likely a fork of a lower block. if block.number() > highest.number && self.state.tree_state.is_descendant(*highest, block) { - return PersistingKind::PersistingDescendant + return PersistingKind::PersistingDescendant; } // In all other cases, the block is not a descendant. @@ -837,7 +837,7 @@ where self.canonical_in_memory_state.on_forkchoice_update_received(); if let Some(on_updated) = self.pre_validate_forkchoice_update(state)? { - return Ok(TreeOutcome::new(on_updated)) + return Ok(TreeOutcome::new(on_updated)); } let valid_outcome = |head| { @@ -868,7 +868,7 @@ where // update the safe and finalized blocks and ensure their values are valid if let Err(outcome) = self.ensure_consistent_forkchoice_state(state) { // safe or finalized hashes are invalid - return Ok(TreeOutcome::new(outcome)) + return Ok(TreeOutcome::new(outcome)); } // we still need to process payload attributes if the head is already canonical @@ -881,11 +881,11 @@ where ProviderError::HeaderNotFound(state.head_block_hash.into()) })?; let updated = self.process_payload_attributes(attr, tip.header(), state, version); - return Ok(TreeOutcome::new(updated)) + return Ok(TreeOutcome::new(updated)); } // the head block is already canonical - return Ok(valid_outcome(state.head_block_hash)) + return Ok(valid_outcome(state.head_block_hash)); } // 2. check if the head is already part of the canonical chain @@ -895,14 +895,14 @@ where // For OpStack the proposers are allowed to reorg their own chain at will, so we need to // always trigger a new payload job if requested. // Also allow forcing this behavior via a config flag. - if self.engine_kind.is_opstack() || - self.config.always_process_payload_attributes_on_canonical_head() + if self.engine_kind.is_opstack() + || self.config.always_process_payload_attributes_on_canonical_head() { if let Some(attr) = attrs { debug!(target: "engine::tree", head = canonical_header.number(), "handling payload attributes for canonical head"); let updated = self.process_payload_attributes(attr, &canonical_header, state, version); - return Ok(TreeOutcome::new(updated)) + return Ok(TreeOutcome::new(updated)); } } @@ -915,7 +915,7 @@ where // the head block is already canonical, so we're not triggering a payload job and can // return right away - return Ok(valid_outcome(state.head_block_hash)) + return Ok(valid_outcome(state.head_block_hash)); } // 3. ensure we can apply a new chain update for the head block @@ -926,15 +926,15 @@ where // update the safe and finalized blocks and ensure their values are valid if let Err(outcome) = self.ensure_consistent_forkchoice_state(state) { // safe or finalized hashes are invalid - return Ok(TreeOutcome::new(outcome)) + return Ok(TreeOutcome::new(outcome)); } if let Some(attr) = attrs { let updated = self.process_payload_attributes(attr, &tip, state, version); - return Ok(TreeOutcome::new(updated)) + return Ok(TreeOutcome::new(updated)); } - return Ok(valid_outcome(state.head_block_hash)) + return Ok(valid_outcome(state.head_block_hash)); } // 4. we don't have the block to perform the update @@ -1006,7 +1006,7 @@ where fn persist_blocks(&mut self, blocks_to_persist: Vec>) { if blocks_to_persist.is_empty() { debug!(target: "engine::tree", "Returned empty set of blocks to persist"); - return + return; } // NOTE: checked non-empty above @@ -1046,7 +1046,7 @@ where // if this happened, then we persisted no blocks because we sent an // empty vec of blocks warn!(target: "engine::tree", "Persistence task completed but did not persist any blocks"); - return Ok(()) + return Ok(()); }; debug!(target: "engine::tree", ?last_persisted_block_hash, ?last_persisted_block_number, "Finished persisting, calling finish"); @@ -1094,7 +1094,7 @@ where let block_num_hash = block.recovered_block().num_hash(); if block_num_hash.number <= self.state.tree_state.canonical_block_number() { // outdated block that can be skipped - return Ok(()) + return Ok(()); } debug!(target: "engine::tree", block=?block_num_hash, "inserting already executed block"); @@ -1102,8 +1102,8 @@ where // if the parent is the canonical head, we can insert the block as the // pending block - if self.state.tree_state.canonical_block_hash() == - block.recovered_block().parent_hash() + if self.state.tree_state.canonical_block_hash() + == block.recovered_block().parent_hash() { debug!(target: "engine::tree", pending=?block_num_hash, "updating pending block"); self.canonical_in_memory_state.set_pending_block(block.clone()); @@ -1234,7 +1234,7 @@ where .map(|hash| BlockNumHash { hash, number: backfill_height }) else { debug!(target: "engine::tree", ?ctrl, "Backfill block not found"); - return Ok(()) + return Ok(()); }; if ctrl.is_unwind() { @@ -1272,11 +1272,11 @@ where // the backfill height let Some(sync_target_state) = self.state.forkchoice_state_tracker.sync_target_state() else { - return Ok(()) + return Ok(()); }; if sync_target_state.finalized_block_hash.is_zero() { // no finalized block, can't check distance - return Ok(()) + return Ok(()); } // get the block number of the finalized block, if we have it let newest_finalized = self @@ -1301,7 +1301,7 @@ where self.emit_event(EngineApiEvent::BackfillAction(BackfillAction::Start( backfill_target.into(), ))); - return Ok(()) + return Ok(()); }; // try to close the gap by executing buffered blocks that are child blocks of the new head @@ -1364,7 +1364,7 @@ where // backfill sync and persisting data are mutually exclusive, so we can't start // backfill while we're still persisting debug!(target: "engine::tree", "skipping backfill file while persistence task is active"); - return + return; } self.backfill_sync_state = BackfillSyncState::Pending; @@ -1383,12 +1383,12 @@ where pub const fn should_persist(&self) -> bool { if !self.backfill_sync_state.is_idle() { // can't persist if backfill is running - return false + return false; } let min_block = self.persistence_state.last_persisted_block.number; - self.state.tree_state.canonical_block_number().saturating_sub(min_block) > - self.config.persistence_threshold() + self.state.tree_state.canonical_block_number().saturating_sub(min_block) + > self.config.persistence_threshold() } /// Returns a batch of consecutive canonical blocks to persist in the range @@ -1434,7 +1434,7 @@ where // Calculate missing trie updates for block in &mut blocks_to_persist { if block.trie.is_present() { - continue + continue; } debug!( @@ -1487,7 +1487,7 @@ where // state. if let Some(remove_above) = self.find_disk_reorg()? { self.remove_blocks(remove_above); - return Ok(()) + return Ok(()); } let finalized = self.state.forkchoice_state_tracker.last_valid_finalized(); @@ -1510,7 +1510,7 @@ where trace!(target: "engine::tree", ?hash, "Fetching executed block by hash"); // check memory first if let Some(block) = self.state.tree_state.executed_block_by_hash(hash) { - return Ok(Some(block.block.clone())) + return Ok(Some(block.block.clone())); } let (block, senders) = self @@ -1597,7 +1597,7 @@ where ) -> ProviderResult> { // Check if parent exists in side chain or in canonical chain. if self.block_by_hash(parent_hash)?.is_some() { - return Ok(Some(parent_hash)) + return Ok(Some(parent_hash)); } // iterate over ancestors in the invalid cache @@ -1611,7 +1611,7 @@ where // If current_header is None, then the current_hash does not have an invalid // ancestor in the cache, check its presence in blockchain tree if current_block.is_none() && self.block_by_hash(current_hash)?.is_some() { - return Ok(Some(current_hash)) + return Ok(Some(current_hash)); } } Ok(None) @@ -1641,7 +1641,7 @@ where /// See [`ForkchoiceStateTracker::sync_target_state`] fn is_sync_target_head(&self, block_hash: B256) -> bool { if let Some(target) = self.state.forkchoice_state_tracker.sync_target_state() { - return target.head_block_hash == block_hash + return target.head_block_hash == block_hash; } false } @@ -1683,12 +1683,12 @@ where fn validate_block(&self, block: &RecoveredBlock) -> Result<(), ConsensusError> { if let Err(e) = self.consensus.validate_header(block.sealed_header()) { error!(target: "engine::tree", ?block, "Failed to validate header {}: {e}", block.hash()); - return Err(e) + return Err(e); } if let Err(e) = self.consensus.validate_block_pre_execution(block.sealed_block()) { error!(target: "engine::tree", ?block, "Failed to validate block {}: {e}", block.hash()); - return Err(e) + return Err(e); } Ok(()) @@ -1704,7 +1704,7 @@ where if blocks.is_empty() { // nothing to append - return Ok(()) + return Ok(()); } let now = Instant::now(); @@ -1714,8 +1714,8 @@ where match self.insert_block(child) { Ok(res) => { debug!(target: "engine::tree", child =?child_num_hash, ?res, "connected buffered block"); - if self.is_sync_target_head(child_num_hash.hash) && - matches!(res, InsertPayloadOk::Inserted(BlockStatus::Valid)) + if self.is_sync_target_head(child_num_hash.hash) + && matches!(res, InsertPayloadOk::Inserted(BlockStatus::Valid)) { self.make_canonical(child_num_hash.hash)?; } @@ -1724,7 +1724,7 @@ where debug!(target: "engine::tree", ?err, "failed to connect buffered block to tree"); if let Err(fatal) = self.on_insert_block_error(err) { warn!(target: "engine::tree", %fatal, "fatal error occurred while connecting buffered blocks"); - return Err(fatal) + return Err(fatal); } } } @@ -1740,7 +1740,7 @@ where block: RecoveredBlock, ) -> Result<(), InsertBlockError> { if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.into_sealed_block())) + return Err(InsertBlockError::consensus_error(err, block.into_sealed_block())); } self.state.buffer.insert_block(block); Ok(()) @@ -1816,7 +1816,7 @@ where if !state.finalized_block_hash.is_zero() { // we don't have the block yet and the distance exceeds the allowed // threshold - return Some(state.finalized_block_hash) + return Some(state.finalized_block_hash); } // OPTIMISTIC SYNCING @@ -1832,7 +1832,7 @@ where // However, optimism chains will do this. The risk of a reorg is however // low. debug!(target: "engine::tree", hash=?state.head_block_hash, "Setting head hash as an optimistic backfill target."); - return Some(state.head_block_hash) + return Some(state.head_block_hash); } Ok(Some(_)) => { // we're fully synced to the finalized block @@ -2043,11 +2043,11 @@ where .check_invalid_ancestor_with_head(lowest_buffered_ancestor, block.sealed_block())? .is_some() { - return Ok(None) + return Ok(None); } if !self.backfill_sync_state.is_idle() { - return Ok(None) + return Ok(None); } // try to append the block @@ -2060,7 +2060,7 @@ where // canonical return Ok(Some(TreeEvent::TreeAction(TreeAction::MakeCanonical { sync_target_head: block_num_hash.hash, - }))) + }))); } trace!(target: "engine::tree", "appended downloaded block"); self.try_connect_buffered_blocks(block_num_hash)?; @@ -2072,7 +2072,7 @@ where block_num_hash, missing_ancestor, head, - )) + )); } Ok(InsertPayloadOk::AlreadySeen(_)) => { trace!(target: "engine::tree", "downloaded block already executed"); @@ -2081,7 +2081,7 @@ where debug!(target: "engine::tree", err=%err.kind(), "failed to insert downloaded block"); if let Err(fatal) = self.on_insert_block_error(err) { warn!(target: "engine::tree", %fatal, "fatal error occurred while inserting downloaded block"); - return Err(fatal) + return Err(fatal); } } } @@ -2116,7 +2116,7 @@ where debug!(target: "engine::tree", block=?block_num_hash, parent = ?block.parent_hash(), state_root = ?block.state_root(), "Inserting new block into tree"); if ensure_ok!(self.block_by_hash(block.hash())).is_some() { - return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid)) + return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid)); } let start = Instant::now(); @@ -2143,7 +2143,7 @@ where return Ok(InsertPayloadOk::Inserted(BlockStatus::Disconnected { head: self.state.tree_state.current_canonical_head, missing_ancestor, - })) + })); }; // now validate against the parent @@ -2153,14 +2153,14 @@ where block.parent_hash().into(), )), block, - )) + )); }; if let Err(e) = self.consensus.validate_header_against_parent(block.sealed_header(), &parent_block) { warn!(target: "engine::tree", ?block, "Failed to validate header {} against parent: {e}", block.hash()); - return Err((e.into(), block)) + return Err((e.into(), block)); } let state_provider = ensure_ok!(provider_builder.build()); @@ -2188,9 +2188,9 @@ where // accounting for the prefix sets. let has_ancestors_with_missing_trie_updates = self.has_ancestors_with_missing_trie_updates(block.sealed_header()); - let mut use_state_root_task = run_parallel_state_root && - self.config.use_state_root_task() && - !has_ancestors_with_missing_trie_updates; + let mut use_state_root_task = run_parallel_state_root + && self.config.use_state_root_task() + && !has_ancestors_with_missing_trie_updates; debug!( target: "engine::tree", @@ -2274,7 +2274,7 @@ where if let Err(err) = self.consensus.validate_block_post_execution(&block, &output) { // call post-block hook self.on_invalid_block(&parent_block, &block, &output, None); - return Err((err.into(), block)) + return Err((err.into(), block)); } let hashed_state = self.provider.hashed_post_state(&output.state); @@ -2285,7 +2285,7 @@ where { // call post-block hook self.on_invalid_block(&parent_block, &block, &output, None); - return Err((err.into(), block)) + return Err((err.into(), block)); } debug!(target: "engine::tree", block=?block_num_hash, "Calculating block state root"); @@ -2341,7 +2341,9 @@ where Err(ParallelStateRootError::Provider(ProviderError::ConsistentView(error))) => { debug!(target: "engine::tree", %error, "Parallel state root computation failed consistency check, falling back"); } - Err(error) => return Err((InsertBlockErrorKind::Other(Box::new(error)), block)), + Err(error) => { + return Err((InsertBlockErrorKind::Other(Box::new(error)), block)) + } } } } @@ -2377,7 +2379,7 @@ where ) .into(), block, - )) + )); } // terminate prewarming task with good state output @@ -2535,7 +2537,7 @@ where } else { // If the block is higher than the best block number, stop filtering, as it's // the first block that's not in the database. - break + break; } } @@ -2649,18 +2651,18 @@ where finalized_block_hash: B256, ) -> Result<(), OnForkChoiceUpdated> { if finalized_block_hash.is_zero() { - return Ok(()) + return Ok(()); } match self.find_canonical_header(finalized_block_hash) { Ok(None) => { debug!(target: "engine::tree", "Finalized block not found in canonical chain"); // if the finalized block is not known, we can't update the finalized block - return Err(OnForkChoiceUpdated::invalid_state()) + return Err(OnForkChoiceUpdated::invalid_state()); } Ok(Some(finalized)) => { - if Some(finalized.num_hash()) != - self.canonical_in_memory_state.get_finalized_num_hash() + if Some(finalized.num_hash()) + != self.canonical_in_memory_state.get_finalized_num_hash() { // we're also persisting the finalized block on disk so we can reload it on // restart this is required by optimism which queries the finalized block: @@ -2679,14 +2681,14 @@ where /// Updates the tracked safe block if we have it fn update_safe_block(&self, safe_block_hash: B256) -> Result<(), OnForkChoiceUpdated> { if safe_block_hash.is_zero() { - return Ok(()) + return Ok(()); } match self.find_canonical_header(safe_block_hash) { Ok(None) => { debug!(target: "engine::tree", "Safe block not found in canonical chain"); // if the safe block is not known, we can't update the safe block - return Err(OnForkChoiceUpdated::invalid_state()) + return Err(OnForkChoiceUpdated::invalid_state()); } Ok(Some(safe)) => { if Some(safe.num_hash()) != self.canonical_in_memory_state.get_safe_num_hash() { @@ -2740,21 +2742,21 @@ where state: ForkchoiceState, ) -> ProviderResult> { if state.head_block_hash.is_zero() { - return Ok(Some(OnForkChoiceUpdated::invalid_state())) + return Ok(Some(OnForkChoiceUpdated::invalid_state())); } // check if the new head hash is connected to any ancestor that we previously marked as // invalid let lowest_buffered_ancestor_fcu = self.lowest_buffered_ancestor_or(state.head_block_hash); if let Some(status) = self.check_invalid_ancestor(lowest_buffered_ancestor_fcu)? { - return Ok(Some(OnForkChoiceUpdated::with_invalid(status))) + return Ok(Some(OnForkChoiceUpdated::with_invalid(status))); } if !self.backfill_sync_state.is_idle() { // We can only process new forkchoice updates if the pipeline is idle, since it requires // exclusive access to the database trace!(target: "engine::tree", "Pipeline is syncing, skipping forkchoice update"); - return Ok(Some(OnForkChoiceUpdated::syncing())) + return Ok(Some(OnForkChoiceUpdated::syncing())); } Ok(None) @@ -2775,7 +2777,7 @@ where self.payload_validator.validate_payload_attributes_against_header(&attrs, head) { warn!(target: "engine::tree", %err, ?head, "Invalid payload attributes"); - return OnForkChoiceUpdated::invalid_payload_attributes() + return OnForkChoiceUpdated::invalid_payload_attributes(); } // 8. Client software MUST begin a payload build process building on top of @@ -2857,7 +2859,7 @@ where self.provider.clone(), historical, Some(blocks), - ))) + ))); } // Check if the block is persisted @@ -2865,7 +2867,7 @@ where debug!(target: "engine::tree", %hash, number = %header.number(), "found canonical state for block in database, creating provider builder"); // For persisted blocks, we create a builder that will fetch state directly from the // database - return Ok(Some(StateProviderBuilder::new(self.provider.clone(), hash, None))) + return Ok(Some(StateProviderBuilder::new(self.provider.clone(), hash, None))); } debug!(target: "engine::tree", %hash, "no canonical state found for block"); diff --git a/crates/engine/tree/src/tree/payload_processor/multiproof.rs b/crates/engine/tree/src/tree/payload_processor/multiproof.rs index 0b62bc73ea..ac0a8972d1 100644 --- a/crates/engine/tree/src/tree/payload_processor/multiproof.rs +++ b/crates/engine/tree/src/tree/payload_processor/multiproof.rs @@ -162,7 +162,7 @@ impl ProofSequencer { // return early if we don't have the next expected proof if !self.pending_proofs.contains_key(&self.next_to_deliver) { - return Vec::new() + return Vec::new(); } let mut consecutive_proofs = Vec::with_capacity(self.pending_proofs.len()); @@ -385,7 +385,7 @@ where "No proof targets, sending empty multiproof back immediately" ); input.send_empty_proof(); - return + return; } if self.inflight >= self.max_concurrent { @@ -760,7 +760,7 @@ where let Some(fetched_storage) = self.fetched_proof_targets.get(hashed_address) else { // this means the account has not been fetched yet, so we must fetch everything // associated with this account - continue + continue; }; let prev_target_storage_len = target_storage.len(); @@ -966,7 +966,7 @@ where target: "engine::root", "State updates finished and all proofs processed, ending calculation" ); - break + break; } } MultiProofMessage::EmptyProof { sequence_number, state } => { @@ -991,7 +991,7 @@ where target: "engine::root", "State updates finished and all proofs processed, ending calculation" ); - break + break; } } MultiProofMessage::ProofCalculated(proof_calculated) => { @@ -1030,7 +1030,7 @@ where debug!( target: "engine::root", "State updates finished and all proofs processed, ending calculation"); - break + break; } } MultiProofMessage::ProofCalculationError(err) => { @@ -1039,7 +1039,7 @@ where ?err, "proof calculation error" ); - return + return; } }, Err(_) => { diff --git a/crates/engine/tree/src/tree/payload_processor/prewarm.rs b/crates/engine/tree/src/tree/payload_processor/prewarm.rs index 85e9e80330..57d0611821 100644 --- a/crates/engine/tree/src/tree/payload_processor/prewarm.rs +++ b/crates/engine/tree/src/tree/payload_processor/prewarm.rs @@ -124,7 +124,7 @@ where self.ctx.cache_metrics.clone(), ); if cache.cache().insert_state(&state).is_err() { - return + return; } cache.update_metrics(); @@ -177,7 +177,7 @@ where if self.prewarm_outcomes_left == 0 && final_block_output.is_some() { // all tasks are done, and we have the block output, we can exit - break + break; } } PrewarmTaskEvent::Terminate { block_output } => { @@ -185,7 +185,7 @@ where if self.prewarm_outcomes_left == 0 { // all tasks are done, we can exit, which will save caches and exit - break + break; } } } @@ -249,7 +249,7 @@ where %err, "Failed to build state provider in prewarm thread" ); - return None + return None; } }; @@ -292,7 +292,7 @@ where /// executed sequentially. fn transact_batch(self, txs: &[Recovered], sender: Sender) { let Some((mut evm, evm_config, metrics, terminate_execution)) = self.evm_for_ctx() else { - return + return; }; for tx in txs { @@ -300,7 +300,7 @@ where // and exit. if terminate_execution.load(Ordering::Relaxed) { let _ = sender.send(PrewarmTaskEvent::Outcome { proof_targets: None }); - return + return; } // create the tx env @@ -316,7 +316,7 @@ where sender=%tx.signer(), "Error when executing prewarm transaction", ); - return + return; } }; metrics.execution_duration.record(start.elapsed()); @@ -344,7 +344,7 @@ fn multiproof_targets_from_state(state: EvmState) -> (MultiProofTargets, usize) // // See: https://eips.ethereum.org/EIPS/eip-6780 if !account.is_touched() || account.is_selfdestructed() { - continue + continue; } let mut storage_set = @@ -352,7 +352,7 @@ fn multiproof_targets_from_state(state: EvmState) -> (MultiProofTargets, usize) for (key, slot) in account.storage { // do nothing if unchanged if !slot.is_changed() { - continue + continue; } storage_set.insert(keccak256(B256::new(key.to_be_bytes()))); diff --git a/crates/engine/tree/src/tree/precompile_cache.rs b/crates/engine/tree/src/tree/precompile_cache.rs index a3eb3a5ba2..d21d6de17f 100644 --- a/crates/engine/tree/src/tree/precompile_cache.rs +++ b/crates/engine/tree/src/tree/precompile_cache.rs @@ -187,7 +187,7 @@ where if let Some(entry) = &self.cache.get(&key) { self.increment_by_one_precompile_cache_hits(); if input.gas >= entry.gas_used() { - return entry.to_precompile_result() + return entry.to_precompile_result(); } } diff --git a/crates/engine/tree/src/tree/state.rs b/crates/engine/tree/src/tree/state.rs index 7bc443db93..74c9d08146 100644 --- a/crates/engine/tree/src/tree/state.rs +++ b/crates/engine/tree/src/tree/state.rs @@ -176,13 +176,13 @@ impl TreeState { pub(crate) fn is_canonical(&self, hash: B256) -> bool { let mut current_block = self.current_canonical_head.hash; if current_block == hash { - return true + return true; } while let Some(executed) = self.blocks_by_hash.get(¤t_block) { current_block = executed.recovered_block().parent_hash(); if current_block == hash { - return true + return true; } } @@ -201,7 +201,7 @@ impl TreeState { // If the last persisted hash is not canonical, then we don't want to remove any canonical // blocks yet. if !self.is_canonical(last_persisted_hash) { - return + return; } // First, let's walk back the canonical chain and remove canonical blocks lower than the @@ -352,25 +352,25 @@ impl TreeState { // If the second block's parent is the first block's hash, then it is a direct descendant // and we can return early. if second.parent_hash() == first.hash { - return true + return true; } // If the second block is lower than, or has the same block number, they are not // descendants. if second.number() <= first.number { - return false + return false; } // iterate through parents of the second until we reach the number let Some(mut current_block) = self.block_by_hash(second.parent_hash()) else { // If we can't find its parent in the tree, we can't continue, so return false - return false + return false; }; while current_block.number() > first.number + 1 { let Some(block) = self.block_by_hash(current_block.header().parent_hash()) else { // If we can't find its parent in the tree, we can't continue, so return false - return false + return false; }; current_block = block; diff --git a/crates/engine/tree/src/tree/tests.rs b/crates/engine/tree/src/tree/tests.rs index 9922d29ff1..5ebccf8619 100644 --- a/crates/engine/tree/src/tree/tests.rs +++ b/crates/engine/tree/src/tree/tests.rs @@ -714,8 +714,8 @@ async fn test_get_canonical_blocks_to_persist() { assert!(!blocks_to_persist.iter().any(|b| b.recovered_block().hash() == fork_block_hash)); // check that the original block 4 is still included - assert!(blocks_to_persist.iter().any(|b| b.recovered_block().number == 4 && - b.recovered_block().hash() == blocks[4].recovered_block().hash())); + assert!(blocks_to_persist.iter().any(|b| b.recovered_block().number == 4 + && b.recovered_block().hash() == blocks[4].recovered_block().hash())); // check that if we advance persistence, the persistence action is the correct value test_harness.tree.advance_persistence().expect("advancing persistence should succeed"); diff --git a/crates/engine/tree/src/tree/trie_updates.rs b/crates/engine/tree/src/tree/trie_updates.rs index ba8f7fc16a..a01cb7f1c6 100644 --- a/crates/engine/tree/src/tree/trie_updates.rs +++ b/crates/engine/tree/src/tree/trie_updates.rs @@ -24,9 +24,9 @@ struct TrieUpdatesDiff { impl TrieUpdatesDiff { fn has_differences(&self) -> bool { - !self.account_nodes.is_empty() || - !self.removed_nodes.is_empty() || - !self.storage_tries.is_empty() + !self.account_nodes.is_empty() + || !self.removed_nodes.is_empty() + || !self.storage_tries.is_empty() } pub(super) fn log_differences(mut self) { @@ -63,9 +63,9 @@ struct StorageTrieUpdatesDiff { impl StorageTrieUpdatesDiff { fn has_differences(&self) -> bool { - self.is_deleted.is_some() || - !self.storage_nodes.is_empty() || - !self.removed_nodes.is_empty() + self.is_deleted.is_some() + || !self.storage_nodes.is_empty() + || !self.removed_nodes.is_empty() } fn log_differences(&self, address: B256) { @@ -287,11 +287,11 @@ fn branch_nodes_equal( ) -> Result { Ok(match (task, regular) { (Some(task), Some(regular)) => { - task.state_mask == regular.state_mask && - task.tree_mask == regular.tree_mask && - task.hash_mask == regular.hash_mask && - task.hashes == regular.hashes && - task.root_hash == regular.root_hash + task.state_mask == regular.state_mask + && task.tree_mask == regular.tree_mask + && task.hash_mask == regular.hash_mask + && task.hashes == regular.hashes + && task.root_hash == regular.root_hash } (None, None) => true, _ => { diff --git a/crates/engine/util/src/reorg.rs b/crates/engine/util/src/reorg.rs index 050a384c44..4dce37cf88 100644 --- a/crates/engine/util/src/reorg.rs +++ b/crates/engine/util/src/reorg.rs @@ -127,7 +127,7 @@ where } Err(_) => {} }; - continue + continue; } if let EngineReorgState::Reorg { queue } = &mut this.state { @@ -173,7 +173,7 @@ where return Poll::Ready(Some(BeaconEngineMessage::NewPayload { payload, tx, - })) + })); } }; let reorg_forkchoice_state = ForkchoiceState { @@ -206,7 +206,7 @@ where }, ]); *this.state = EngineReorgState::Reorg { queue }; - continue + continue; } ( Some(BeaconEngineMessage::ForkchoiceUpdated { @@ -231,7 +231,7 @@ where } (item, _) => item, }; - return Poll::Ready(item) + return Poll::Ready(item); } } } @@ -263,7 +263,7 @@ where .block_by_hash(previous_hash)? .ok_or_else(|| ProviderError::HeaderNotFound(previous_hash.into()))?; if depth == 0 { - break 'target reorg_target.seal_slow() + break 'target reorg_target.seal_slow(); } depth -= 1; @@ -294,7 +294,7 @@ where for tx in candidate_transactions { // ensure we still have capacity for this transaction if cumulative_gas_used + tx.gas_limit() > reorg_target.gas_limit() { - continue + continue; } let tx_recovered = @@ -306,7 +306,7 @@ where error, })) => { trace!(target: "engine::stream::reorg", hash = %hash, ?error, "Error executing transaction from next block"); - continue + continue; } // Treat error as fatal Err(error) => return Err(RethError::Execution(error)), diff --git a/crates/engine/util/src/skip_fcu.rs b/crates/engine/util/src/skip_fcu.rs index a4712c2e0b..0c724de080 100644 --- a/crates/engine/util/src/skip_fcu.rs +++ b/crates/engine/util/src/skip_fcu.rs @@ -55,7 +55,7 @@ where *this.skipped += 1; tracing::warn!(target: "engine::stream::skip_fcu", ?state, ?payload_attrs, threshold=this.threshold, skipped=this.skipped, "Skipping FCU"); let _ = tx.send(Ok(OnForkChoiceUpdated::syncing())); - continue + continue; } *this.skipped = 0; Some(BeaconEngineMessage::ForkchoiceUpdated { @@ -67,7 +67,7 @@ where } next => next, }; - return Poll::Ready(item) + return Poll::Ready(item); } } } diff --git a/crates/engine/util/src/skip_new_payload.rs b/crates/engine/util/src/skip_new_payload.rs index fa818f5453..26d47fa36a 100644 --- a/crates/engine/util/src/skip_new_payload.rs +++ b/crates/engine/util/src/skip_new_payload.rs @@ -53,14 +53,14 @@ where skipped=this.skipped, "Skipping new payload" ); let _ = tx.send(Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing))); - continue + continue; } *this.skipped = 0; Some(BeaconEngineMessage::NewPayload { payload, tx }) } next => next, }; - return Poll::Ready(item) + return Poll::Ready(item); } } } diff --git a/crates/era-downloader/tests/it/checksums.rs b/crates/era-downloader/tests/it/checksums.rs index 630cbece5d..09faa01710 100644 --- a/crates/era-downloader/tests/it/checksums.rs +++ b/crates/era-downloader/tests/it/checksums.rs @@ -64,17 +64,17 @@ impl HttpClient for FailingClient { "https://mainnet.era1.nimbus.team/" => Bytes::from_static(crate::NIMBUS), "https://era1.ethportal.net/" => Bytes::from_static(crate::ETH_PORTAL), "https://era.ithaca.xyz/era1/index.html" => Bytes::from_static(crate::ITHACA), - "https://mainnet.era1.nimbus.team/checksums.txt" | - "https://era1.ethportal.net/checksums.txt" | - "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), - "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" | - "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" | - "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { + "https://mainnet.era1.nimbus.team/checksums.txt" + | "https://era1.ethportal.net/checksums.txt" + | "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), + "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" + | "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" + | "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { Bytes::from_static(crate::MAINNET_0) } - "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" | - "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" | - "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { + "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" + | "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" + | "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { Bytes::from_static(crate::MAINNET_1) } v => unimplemented!("Unexpected URL \"{v}\""), diff --git a/crates/era-downloader/tests/it/main.rs b/crates/era-downloader/tests/it/main.rs index 526d3885bf..cc5839755d 100644 --- a/crates/era-downloader/tests/it/main.rs +++ b/crates/era-downloader/tests/it/main.rs @@ -36,17 +36,17 @@ impl HttpClient for StubClient { "https://mainnet.era1.nimbus.team/" => Bytes::from_static(NIMBUS), "https://era1.ethportal.net/" => Bytes::from_static(ETH_PORTAL), "https://era.ithaca.xyz/era1/index.html" => Bytes::from_static(ITHACA), - "https://mainnet.era1.nimbus.team/checksums.txt" | - "https://era1.ethportal.net/checksums.txt" | - "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), - "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" | - "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" | - "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { + "https://mainnet.era1.nimbus.team/checksums.txt" + | "https://era1.ethportal.net/checksums.txt" + | "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), + "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" + | "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" + | "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { Bytes::from_static(MAINNET_0) } - "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" | - "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" | - "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { + "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" + | "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" + | "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { Bytes::from_static(MAINNET_1) } v => unimplemented!("Unexpected URL \"{v}\""), diff --git a/crates/era/src/era1_file.rs b/crates/era/src/era1_file.rs index 547d770f06..8b8b507c69 100644 --- a/crates/era/src/era1_file.rs +++ b/crates/era/src/era1_file.rs @@ -123,13 +123,17 @@ impl BlockTupleIterator { } execution_types::ACCUMULATOR => { if self.accumulator.is_some() { - return Err(E2sError::Ssz("Multiple accumulator entries found".to_string())); + return Err(E2sError::Ssz( + "Multiple accumulator entries found".to_string(), + )); } self.accumulator = Some(Accumulator::from_entry(&entry)?); } BLOCK_INDEX => { if self.block_index.is_some() { - return Err(E2sError::Ssz("Multiple block index entries found".to_string())); + return Err(E2sError::Ssz( + "Multiple block index entries found".to_string(), + )); } self.block_index = Some(BlockIndex::from_entry(&entry)?); } @@ -138,10 +142,10 @@ impl BlockTupleIterator { } } - if !self.headers.is_empty() && - !self.bodies.is_empty() && - !self.receipts.is_empty() && - !self.difficulties.is_empty() + if !self.headers.is_empty() + && !self.bodies.is_empty() + && !self.receipts.is_empty() + && !self.difficulties.is_empty() { let header = self.headers.pop_front().unwrap(); let body = self.bodies.pop_front().unwrap(); @@ -190,9 +194,9 @@ impl Era1Reader { } = iter; // Ensure we have matching counts for block components - if headers.len() != bodies.len() || - headers.len() != receipts.len() || - headers.len() != difficulties.len() + if headers.len() != bodies.len() + || headers.len() != receipts.len() + || headers.len() != difficulties.len() { return Err(E2sError::Ssz(format!( "Mismatched block component counts: headers={}, bodies={}, receipts={}, difficulties={}", @@ -275,7 +279,9 @@ impl Era1Writer { // Ensure blocks are written before other entries if era1_file.group.blocks.len() > MAX_BLOCKS_PER_ERA1 { - return Err(E2sError::Ssz("Era1 file cannot contain more than 8192 blocks".to_string())); + return Err(E2sError::Ssz( + "Era1 file cannot contain more than 8192 blocks".to_string(), + )); } // Write all blocks diff --git a/crates/era/tests/it/main.rs b/crates/era/tests/it/main.rs index fa93981918..84fffff063 100644 --- a/crates/era/tests/it/main.rs +++ b/crates/era/tests/it/main.rs @@ -90,8 +90,8 @@ impl Era1TestDownloader { } // check if the filename is supported - if !ERA1_MAINNET_FILES_NAMES.contains(&filename) && - !ERA1_SEPOLIA_FILES_NAMES.contains(&filename) + if !ERA1_MAINNET_FILES_NAMES.contains(&filename) + && !ERA1_SEPOLIA_FILES_NAMES.contains(&filename) { return Err(eyre!( "Unknown file: {}. Only the following files are supported: {:?} or {:?}", diff --git a/crates/ethereum/cli/src/debug_cmd/execution.rs b/crates/ethereum/cli/src/debug_cmd/execution.rs index 63a9cc3a80..a68fa2a523 100644 --- a/crates/ethereum/cli/src/debug_cmd/execution.rs +++ b/crates/ethereum/cli/src/debug_cmd/execution.rs @@ -156,7 +156,7 @@ impl> Command { match get_single_header(&client, BlockHashOrNumber::Number(block)).await { Ok(tip_header) => { info!(target: "reth::cli", ?block, "Successfully fetched block"); - return Ok(tip_header.hash()) + return Ok(tip_header.hash()); } Err(error) => { error!(target: "reth::cli", ?block, %error, "Failed to fetch the block. Retrying..."); @@ -209,7 +209,7 @@ impl> Command { provider.get_stage_checkpoint(StageId::Finish)?.map(|ch| ch.block_number); if latest_block_number.unwrap_or_default() >= self.to { info!(target: "reth::cli", latest = latest_block_number, "Nothing to run"); - return Ok(()) + return Ok(()); } ctx.task_executor.spawn_critical( diff --git a/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs b/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs index b45e712da2..86662e2842 100644 --- a/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs +++ b/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs @@ -159,7 +159,7 @@ impl> Command { if in_memory_state_root == block.state_root() { info!(target: "reth::cli", state_root = ?in_memory_state_root, "Computed in-memory state root matches"); - return Ok(()) + return Ok(()); } let provider_rw = provider_factory.database_provider_rw()?; @@ -203,8 +203,8 @@ impl> Command { match (in_mem_updates_iter.next(), incremental_updates_iter.next()) { (Some(in_mem), Some(incr)) => { similar_asserts::assert_eq!(in_mem.0, incr.0, "Nibbles don't match"); - if in_mem.1 != incr.1 && - in_mem.0.len() > self.skip_node_depth.unwrap_or_default() + if in_mem.1 != incr.1 + && in_mem.0.len() > self.skip_node_depth.unwrap_or_default() { in_mem_mismatched.push(in_mem); incremental_mismatched.push(incr); diff --git a/crates/ethereum/cli/src/debug_cmd/merkle.rs b/crates/ethereum/cli/src/debug_cmd/merkle.rs index 09c435b6f3..27d0876af7 100644 --- a/crates/ethereum/cli/src/debug_cmd/merkle.rs +++ b/crates/ethereum/cli/src/debug_cmd/merkle.rs @@ -192,7 +192,7 @@ impl> Command { if incremental_result.is_ok() { debug!(target: "reth::cli", block_number, "Successfully computed incremental root"); - continue + continue; } warn!(target: "reth::cli", block_number, "Incremental calculation failed, retrying from scratch"); @@ -235,14 +235,14 @@ impl> Command { let mut clean_account_mismatched = Vec::new(); let mut incremental_account_trie_iter = incremental_account_trie.into_iter().peekable(); let mut clean_account_trie_iter = clean_account_trie.into_iter().peekable(); - while incremental_account_trie_iter.peek().is_some() || - clean_account_trie_iter.peek().is_some() + while incremental_account_trie_iter.peek().is_some() + || clean_account_trie_iter.peek().is_some() { match (incremental_account_trie_iter.next(), clean_account_trie_iter.next()) { (Some(incremental), Some(clean)) => { similar_asserts::assert_eq!(incremental.0, clean.0, "Nibbles don't match"); - if incremental.1 != clean.1 && - clean.0 .0.len() > self.skip_node_depth.unwrap_or_default() + if incremental.1 != clean.1 + && clean.0 .0.len() > self.skip_node_depth.unwrap_or_default() { incremental_account_mismatched.push(incremental); clean_account_mismatched.push(clean); @@ -264,16 +264,16 @@ impl> Command { let mut first_mismatched_storage = None; let mut incremental_storage_trie_iter = incremental_storage_trie.into_iter().peekable(); let mut clean_storage_trie_iter = clean_storage_trie.into_iter().peekable(); - while incremental_storage_trie_iter.peek().is_some() || - clean_storage_trie_iter.peek().is_some() + while incremental_storage_trie_iter.peek().is_some() + || clean_storage_trie_iter.peek().is_some() { match (incremental_storage_trie_iter.next(), clean_storage_trie_iter.next()) { (Some(incremental), Some(clean)) => { - if incremental != clean && - clean.1.nibbles.len() > self.skip_node_depth.unwrap_or_default() + if incremental != clean + && clean.1.nibbles.len() > self.skip_node_depth.unwrap_or_default() { first_mismatched_storage = Some((incremental, clean)); - break + break; } } (Some(incremental), None) => { diff --git a/crates/ethereum/consensus/src/lib.rs b/crates/ethereum/consensus/src/lib.rs index 82a37b2386..bb7d4d860b 100644 --- a/crates/ethereum/consensus/src/lib.rs +++ b/crates/ethereum/consensus/src/lib.rs @@ -56,11 +56,12 @@ impl EthBeaconConsensus parent: &SealedHeader, ) -> Result<(), ConsensusError> { // Determine the parent gas limit, considering elasticity multiplier on the London fork. - let parent_gas_limit = if !self.chain_spec.is_london_active_at_block(parent.number()) && - self.chain_spec.is_london_active_at_block(header.number()) + let parent_gas_limit = if !self.chain_spec.is_london_active_at_block(parent.number()) + && self.chain_spec.is_london_active_at_block(header.number()) { - parent.gas_limit() * - self.chain_spec + parent.gas_limit() + * self + .chain_spec .base_fee_params_at_timestamp(header.timestamp()) .elasticity_multiplier as u64 } else { @@ -73,23 +74,23 @@ impl EthBeaconConsensus return Err(ConsensusError::GasLimitInvalidIncrease { parent_gas_limit, child_gas_limit: header.gas_limit(), - }) + }); } } // Check for a decrease in gas limit beyond the allowed threshold. - else if parent_gas_limit - header.gas_limit() >= - parent_gas_limit / GAS_LIMIT_BOUND_DIVISOR + else if parent_gas_limit - header.gas_limit() + >= parent_gas_limit / GAS_LIMIT_BOUND_DIVISOR { return Err(ConsensusError::GasLimitInvalidDecrease { parent_gas_limit, child_gas_limit: header.gas_limit(), - }) + }); } // Check if the self gas limit is below the minimum required limit. else if header.gas_limit() < MINIMUM_GAS_LIMIT { return Err(ConsensusError::GasLimitInvalidMinimum { child_gas_limit: header.gas_limit(), - }) + }); } Ok(()) @@ -159,8 +160,8 @@ where .unwrap() .as_secs(); - if header.timestamp() > - present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS + if header.timestamp() + > present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp(), @@ -174,14 +175,14 @@ where validate_header_base_fee(header, &self.chain_spec)?; // EIP-4895: Beacon chain push withdrawals as operations - if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) && - header.withdrawals_root().is_none() + if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) + && header.withdrawals_root().is_none() { - return Err(ConsensusError::WithdrawalsRootMissing) - } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) && - header.withdrawals_root().is_some() + return Err(ConsensusError::WithdrawalsRootMissing); + } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) + && header.withdrawals_root().is_some() { - return Err(ConsensusError::WithdrawalsRootUnexpected) + return Err(ConsensusError::WithdrawalsRootUnexpected); } // Ensures that EIP-4844 fields are valid once cancun is active. @@ -193,19 +194,19 @@ where .unwrap_or_else(BlobParams::cancun), )?; } else if header.blob_gas_used().is_some() { - return Err(ConsensusError::BlobGasUsedUnexpected) + return Err(ConsensusError::BlobGasUsedUnexpected); } else if header.excess_blob_gas().is_some() { - return Err(ConsensusError::ExcessBlobGasUnexpected) + return Err(ConsensusError::ExcessBlobGasUnexpected); } else if header.parent_beacon_block_root().is_some() { - return Err(ConsensusError::ParentBeaconBlockRootUnexpected) + return Err(ConsensusError::ParentBeaconBlockRootUnexpected); } if self.chain_spec.is_prague_active_at_timestamp(header.timestamp()) { if header.requests_hash().is_none() { - return Err(ConsensusError::RequestsHashMissing) + return Err(ConsensusError::RequestsHashMissing); } } else if header.requests_hash().is_some() { - return Err(ConsensusError::RequestsHashUnexpected) + return Err(ConsensusError::RequestsHashUnexpected); } Ok(()) diff --git a/crates/ethereum/consensus/src/validation.rs b/crates/ethereum/consensus/src/validation.rs index 186403d865..01eb6d06fc 100644 --- a/crates/ethereum/consensus/src/validation.rs +++ b/crates/ethereum/consensus/src/validation.rs @@ -30,7 +30,7 @@ where return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.header().gas_used() }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }) + }); } // Before Byzantium, receipts contained state root that would mean that expensive @@ -42,20 +42,20 @@ where verify_receipts(block.header().receipts_root(), block.header().logs_bloom(), receipts) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error) + return Err(error); } } // Validate that the header requests hash matches the calculated requests hash if chain_spec.is_prague_active_at_timestamp(block.header().timestamp()) { let Some(header_requests_hash) = block.header().requests_hash() else { - return Err(ConsensusError::RequestsHashMissing) + return Err(ConsensusError::RequestsHashMissing); }; let requests_hash = requests.requests_hash(); if requests_hash != header_requests_hash { return Err(ConsensusError::BodyRequestsHashDiff( GotExpected::new(requests_hash, header_requests_hash).into(), - )) + )); } } @@ -97,13 +97,13 @@ fn compare_receipts_root_and_logs_bloom( if calculated_receipts_root != expected_receipts_root { return Err(ConsensusError::BodyReceiptRootDiff( GotExpected { got: calculated_receipts_root, expected: expected_receipts_root }.into(), - )) + )); } if calculated_logs_bloom != expected_logs_bloom { return Err(ConsensusError::BodyBloomLogDiff( GotExpected { got: calculated_logs_bloom, expected: expected_logs_bloom }.into(), - )) + )); } Ok(()) diff --git a/crates/ethereum/node/tests/e2e/rpc.rs b/crates/ethereum/node/tests/e2e/rpc.rs index ea49d8b3c8..60a3991c0f 100644 --- a/crates/ethereum/node/tests/e2e/rpc.rs +++ b/crates/ethereum/node/tests/e2e/rpc.rs @@ -61,8 +61,8 @@ async fn test_fee_history() -> eyre::Result<()> { let fee_history = provider.get_fee_history(10, 0_u64.into(), &[]).await?; let genesis_base_fee = chain_spec.initial_base_fee().unwrap() as u128; - let expected_first_base_fee = genesis_base_fee - - genesis_base_fee / chain_spec.base_fee_params_at_block(0).max_change_denominator; + let expected_first_base_fee = genesis_base_fee + - genesis_base_fee / chain_spec.base_fee_params_at_block(0).max_change_denominator; assert_eq!(fee_history.base_fee_per_gas[0], genesis_base_fee); assert_eq!(fee_history.base_fee_per_gas[1], expected_first_base_fee,); diff --git a/crates/ethereum/payload/src/lib.rs b/crates/ethereum/payload/src/lib.rs index 603e7ab74e..848c900ac7 100644 --- a/crates/ethereum/payload/src/lib.rs +++ b/crates/ethereum/payload/src/lib.rs @@ -208,12 +208,12 @@ where &pool_tx, InvalidPoolTransactionError::ExceedsGasLimit(pool_tx.gas_limit(), block_gas_limit), ); - continue + continue; } // check if the job was cancelled, if so we can exit early if cancel.is_cancelled() { - return Ok(BuildOutcome::Cancelled) + return Ok(BuildOutcome::Cancelled); } // convert tx to a signed transaction @@ -240,14 +240,14 @@ where }, ), ); - continue + continue; } let blob_sidecar_result = 'sidecar: { let Some(sidecar) = pool.get_blob(*tx.hash()).map_err(PayloadBuilderError::other)? else { - break 'sidecar Err(Eip4844PoolTransactionError::MissingEip4844BlobSidecar) + break 'sidecar Err(Eip4844PoolTransactionError::MissingEip4844BlobSidecar); }; if chain_spec.is_osaka_active_at_timestamp(attributes.timestamp) { @@ -267,7 +267,7 @@ where Ok(sidecar) => Some(sidecar), Err(error) => { best_txs.mark_invalid(&pool_tx, InvalidPoolTransactionError::Eip4844(error)); - continue + continue; } }; } @@ -291,7 +291,7 @@ where ), ); } - continue + continue; } // this is an error that we should treat as fatal for this attempt Err(err) => return Err(PayloadBuilderError::evm(err)), @@ -324,7 +324,7 @@ where // Release db drop(builder); // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); } let BlockBuilderOutcome { execution_result, block, .. } = builder.finish(&state_provider)?; diff --git a/crates/ethereum/payload/src/validator.rs b/crates/ethereum/payload/src/validator.rs index 75f4b1f474..0fac37fe30 100644 --- a/crates/ethereum/payload/src/validator.rs +++ b/crates/ethereum/payload/src/validator.rs @@ -85,7 +85,7 @@ impl EthereumExecutionPayloadValidator return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - }) + }); } shanghai::ensure_well_formed_fields( diff --git a/crates/ethereum/primitives/src/receipt.rs b/crates/ethereum/primitives/src/receipt.rs index ffc06c7fc8..735decd620 100644 --- a/crates/ethereum/primitives/src/receipt.rs +++ b/crates/ethereum/primitives/src/receipt.rs @@ -38,10 +38,10 @@ pub struct Receipt { impl Receipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { - self.success.length() + - self.cumulative_gas_used.length() + - bloom.length() + - self.logs.length() + self.success.length() + + self.cumulative_gas_used.length() + + bloom.length() + + self.logs.length() } /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. @@ -178,7 +178,7 @@ impl RlpDecodableReceipt for Receipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, TxType::Legacy) + return Self::rlp_decode_inner(buf, TxType::Legacy); } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -198,8 +198,8 @@ impl RlpDecodableReceipt for Receipt { impl Encodable2718 for Receipt { fn encode_2718_len(&self) -> usize { - (!self.tx_type.is_legacy() as usize) + - self.rlp_header_inner_without_bloom().length_with_payload() + (!self.tx_type.is_legacy() as usize) + + self.rlp_header_inner_without_bloom().length_with_payload() } // encode the header @@ -276,10 +276,10 @@ impl IsTyped2718 for Receipt { impl InMemorySize for Receipt { fn size(&self) -> usize { - self.tx_type.size() + - core::mem::size_of::() + - core::mem::size_of::() + - self.logs.capacity() * core::mem::size_of::() + self.tx_type.size() + + core::mem::size_of::() + + core::mem::size_of::() + + self.logs.capacity() * core::mem::size_of::() } } diff --git a/crates/ethereum/primitives/src/transaction.rs b/crates/ethereum/primitives/src/transaction.rs index 07191142e7..9da37fe078 100644 --- a/crates/ethereum/primitives/src/transaction.rs +++ b/crates/ethereum/primitives/src/transaction.rs @@ -333,9 +333,9 @@ impl Hash for TransactionSigned { impl PartialEq for TransactionSigned { fn eq(&self, other: &Self) -> bool { - self.signature == other.signature && - self.transaction == other.transaction && - self.tx_hash() == other.tx_hash() + self.signature == other.signature + && self.transaction == other.transaction + && self.tx_hash() == other.tx_hash() } } diff --git a/crates/etl/src/lib.rs b/crates/etl/src/lib.rs index 46d41d704d..fdf4a2ec37 100644 --- a/crates/etl/src/lib.rs +++ b/crates/etl/src/lib.rs @@ -256,7 +256,7 @@ impl EtlFile { /// Can return error if it reaches EOF before filling the internal buffers. pub(crate) fn read_next(&mut self) -> std::io::Result, Vec)>> { if self.len == 0 { - return Ok(None) + return Ok(None); } let mut buffer_key_length = [0; KV_LEN]; diff --git a/crates/evm/evm/src/metrics.rs b/crates/evm/evm/src/metrics.rs index 586c1c154d..46f74e7aae 100644 --- a/crates/evm/evm/src/metrics.rs +++ b/crates/evm/evm/src/metrics.rs @@ -303,9 +303,9 @@ mod tests { for metric in snapshot { let metric_name = metric.0.key().name(); - if metric_name == "sync.execution.accounts_loaded_histogram" || - metric_name == "sync.execution.storage_slots_loaded_histogram" || - metric_name == "sync.execution.bytecodes_loaded_histogram" + if metric_name == "sync.execution.accounts_loaded_histogram" + || metric_name == "sync.execution.storage_slots_loaded_histogram" + || metric_name == "sync.execution.bytecodes_loaded_histogram" { if let DebugValue::Histogram(vs) = metric.3 { assert!( diff --git a/crates/evm/execution-errors/src/trie.rs b/crates/evm/execution-errors/src/trie.rs index 7c5ad72b1c..8578b7443c 100644 --- a/crates/evm/execution-errors/src/trie.rs +++ b/crates/evm/execution-errors/src/trie.rs @@ -20,8 +20,8 @@ pub enum StateRootError { impl From for DatabaseError { fn from(err: StateRootError) -> Self { match err { - StateRootError::Database(err) | - StateRootError::StorageRootError(StorageRootError::Database(err)) => err, + StateRootError::Database(err) + | StateRootError::StorageRootError(StorageRootError::Database(err)) => err, } } } diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index dc7218631f..bf5671c040 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -140,13 +140,13 @@ impl Chain { block_number: BlockNumber, ) -> Option> { if self.tip().number() == block_number { - return Some(self.execution_outcome.clone()) + return Some(self.execution_outcome.clone()); } if self.blocks.contains_key(&block_number) { let mut execution_outcome = self.execution_outcome.clone(); execution_outcome.revert_to(block_number); - return Some(execution_outcome) + return Some(execution_outcome); } None } @@ -286,7 +286,7 @@ impl Chain { let chain_tip = self.tip(); let other_fork_block = other.fork_block(); if chain_tip.hash() != other_fork_block.hash { - return Err(other) + return Err(other); } // Insert blocks from other chain diff --git a/crates/evm/execution-types/src/execution_outcome.rs b/crates/evm/execution-types/src/execution_outcome.rs index b198713a2e..61d21b6b1a 100644 --- a/crates/evm/execution-types/src/execution_outcome.rs +++ b/crates/evm/execution-types/src/execution_outcome.rs @@ -203,11 +203,11 @@ impl ExecutionOutcome { /// Transform block number to the index of block. pub fn block_number_to_index(&self, block_number: BlockNumber) -> Option { if self.first_block > block_number { - return None + return None; } let index = block_number - self.first_block; if index >= self.receipts.len() as u64 { - return None + return None; } Some(index as usize) } @@ -296,7 +296,7 @@ impl ExecutionOutcome { T: Clone, { if at == self.first_block { - return (None, self) + return (None, self); } let (mut lower_state, mut higher_state) = (self.clone(), self); diff --git a/crates/exex/exex/src/backfill/job.rs b/crates/exex/exex/src/backfill/job.rs index bbfd6c2a89..c73a22e4f4 100644 --- a/crates/exex/exex/src/backfill/job.rs +++ b/crates/exex/exex/src/backfill/job.rs @@ -46,7 +46,7 @@ where fn next(&mut self) -> Option { if self.range.is_empty() { - return None + return None; } Some(self.execute_range()) @@ -129,7 +129,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break + break; } } diff --git a/crates/exex/exex/src/backfill/stream.rs b/crates/exex/exex/src/backfill/stream.rs index 2525f80422..1f0fef798a 100644 --- a/crates/exex/exex/src/backfill/stream.rs +++ b/crates/exex/exex/src/backfill/stream.rs @@ -108,7 +108,7 @@ where // next. self.push_front(job); - return Poll::Ready(Some(job_result)) + return Poll::Ready(Some(job_result)); }; } diff --git a/crates/exex/exex/src/manager.rs b/crates/exex/exex/src/manager.rs index d5006dd9f1..7300eb4e28 100644 --- a/crates/exex/exex/src/manager.rs +++ b/crates/exex/exex/src/manager.rs @@ -146,7 +146,7 @@ impl ExExHandle { ); self.next_notification_id = notification_id + 1; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } // Do not handle [ExExNotification::ChainReorged] and @@ -482,9 +482,9 @@ where } this.push_notification(notification); - continue + continue; } - break + break; } // Update capacity @@ -504,7 +504,7 @@ where if let Some(notification) = this.buffer.get(notification_index) { if let Poll::Ready(Err(err)) = exex.send(cx, notification) { // The channel was closed, which is irrecoverable for the manager - return Poll::Ready(Err(err.into())) + return Poll::Ready(Err(err.into())); } } min_id = min_id.min(exex.next_notification_id); diff --git a/crates/exex/exex/src/notifications.rs b/crates/exex/exex/src/notifications.rs index 651bd7d5b2..f13d0693d5 100644 --- a/crates/exex/exex/src/notifications.rs +++ b/crates/exex/exex/src/notifications.rs @@ -308,12 +308,12 @@ where /// we're not on the canonical chain and we need to revert the notification with the ExEx /// head block. fn check_canonical(&mut self) -> eyre::Result>> { - if self.provider.is_known(&self.initial_exex_head.block.hash)? && - self.initial_exex_head.block.number <= self.initial_local_head.number + if self.provider.is_known(&self.initial_exex_head.block.hash)? + && self.initial_exex_head.block.number <= self.initial_local_head.number { // we have the targeted block and that block is below the current head debug!(target: "exex::notifications", "ExEx head is on the canonical chain"); - return Ok(None) + return Ok(None); } // If the head block is not found in the database, it means we're not on the canonical @@ -333,7 +333,7 @@ where return Err(eyre::eyre!( "Could not find notification for block hash {:?} in the WAL", self.initial_exex_head.block.hash - )) + )); }; // Update the head block hash to the parent hash of the first committed block. @@ -397,7 +397,7 @@ where // 1. Check once whether we need to retrieve a notification gap from the WAL. if this.pending_check_canonical { if let Some(canonical_notification) = this.check_canonical()? { - return Poll::Ready(Some(Ok(canonical_notification))) + return Poll::Ready(Some(Ok(canonical_notification))); } // ExEx head is on the canonical chain, we no longer need to check it @@ -417,7 +417,7 @@ where debug!(target: "exex::notifications", range = ?chain.range(), "Backfill job returned a chain"); return Poll::Ready(Some(Ok(ExExNotification::ChainCommitted { new: Arc::new(chain), - }))) + }))); } // Backfill job is done, remove it @@ -427,18 +427,18 @@ where // 4. Otherwise advance the regular event stream loop { let Some(notification) = ready!(this.notifications.poll_recv(cx)) else { - return Poll::Ready(None) + return Poll::Ready(None); }; // 5. In case the exex is ahead of the new tip, we must skip it if let Some(committed) = notification.committed_chain() { // inclusive check because we should start with `exex.head + 1` if this.initial_exex_head.block.number >= committed.tip().number() { - continue + continue; } } - return Poll::Ready(Some(Ok(notification))) + return Poll::Ready(Some(Ok(notification))); } } } diff --git a/crates/exex/exex/src/wal/cache.rs b/crates/exex/exex/src/wal/cache.rs index b5e0f2034e..75506082a9 100644 --- a/crates/exex/exex/src/wal/cache.rs +++ b/crates/exex/exex/src/wal/cache.rs @@ -59,7 +59,7 @@ impl BlockCache { debug_assert_eq!(popped_block, block); file_ids.insert(file_id); } else { - break + break; } } diff --git a/crates/exex/exex/src/wal/mod.rs b/crates/exex/exex/src/wal/mod.rs index b5537aa88f..77048d17f2 100644 --- a/crates/exex/exex/src/wal/mod.rs +++ b/crates/exex/exex/src/wal/mod.rs @@ -169,7 +169,7 @@ where // Remove notifications from the storage. if file_ids.is_empty() { debug!(target: "exex::wal", "No notifications were finalized from the storage"); - return Ok(()) + return Ok(()); } let (removed_notifications, removed_size) = self.storage.remove_notifications(file_ids)?; @@ -199,7 +199,7 @@ where &self, ) -> WalResult>> + '_>> { let Some(range) = self.storage.files_range()? else { - return Ok(Box::new(std::iter::empty())) + return Ok(Box::new(std::iter::empty())); }; Ok(Box::new(self.storage.iter_notifications(range).map(|entry| Ok(entry?.2)))) @@ -223,7 +223,7 @@ where ) -> WalResult>> { let Some(file_id) = self.wal.block_cache().get_file_id_by_committed_block_hash(block_hash) else { - return Ok(None) + return Ok(None); }; self.wal diff --git a/crates/net/banlist/src/lib.rs b/crates/net/banlist/src/lib.rs index 29cf8eb76a..bc7d347195 100644 --- a/crates/net/banlist/src/lib.rs +++ b/crates/net/banlist/src/lib.rs @@ -16,7 +16,7 @@ use std::{collections::HashMap, net::IpAddr, time::Instant}; /// Should be replaced with [`IpAddr::is_global`](std::net::IpAddr::is_global) once it is stable. pub const fn is_global(ip: &IpAddr) -> bool { if ip.is_unspecified() || ip.is_loopback() { - return false + return false; } match ip { @@ -62,7 +62,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false + return false; } } true @@ -77,7 +77,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false + return false; } } true diff --git a/crates/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index 976ade1728..2599af9384 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -772,8 +772,8 @@ impl Discv4Service { self.kbuckets .closest_values(&target_key) .filter(|node| { - node.value.has_endpoint_proof && - !self.pending_find_nodes.contains_key(&node.key.preimage().0) + node.value.has_endpoint_proof + && !self.pending_find_nodes.contains_key(&node.key.preimage().0) }) .take(MAX_NODES_PER_BUCKET) .map(|n| (target_key.distance(&n.key), n.value.record)), @@ -789,7 +789,7 @@ impl Discv4Service { // (e.g. connectivity problems over a long period of time, or issues during initial // bootstrapping) so we attempt to bootstrap again self.bootstrap(); - return + return; } trace!(target: "discv4", ?target, num = closest.len(), "Start lookup closest nodes"); @@ -883,7 +883,7 @@ impl Discv4Service { let Some(bucket) = self.kbuckets.get_bucket(&key) else { return false }; if bucket.num_entries() < MAX_NODES_PER_BUCKET / 2 { // skip half empty bucket - return false + return false; } self.remove_key(node_id, key) } @@ -906,7 +906,7 @@ impl Discv4Service { fn has_bond(&self, remote_id: PeerId, remote_ip: IpAddr) -> bool { if let Some(timestamp) = self.received_pongs.last_pong(remote_id, remote_ip) { if timestamp.elapsed() < self.config.bond_expiration { - return true + return true; } } false @@ -933,7 +933,7 @@ impl Discv4Service { /// a followup request to retrieve the updated ENR fn update_on_reping(&mut self, record: NodeRecord, mut last_enr_seq: Option) { if record.id == self.local_node_record.id { - return + return; } // If EIP868 extension is disabled then we want to ignore this @@ -968,7 +968,7 @@ impl Discv4Service { /// Callback invoked when we receive a pong from the peer. fn update_on_pong(&mut self, record: NodeRecord, mut last_enr_seq: Option) { if record.id == *self.local_peer_id() { - return + return; } // If EIP868 extension is disabled then we want to ignore this @@ -1077,7 +1077,7 @@ impl Discv4Service { fn on_ping(&mut self, ping: Ping, remote_addr: SocketAddr, remote_id: PeerId, hash: B256) { if self.is_expired(ping.expire) { // ping's expiration timestamp is in the past - return + return; } // create the record @@ -1209,17 +1209,17 @@ impl Discv4Service { fn try_ping(&mut self, node: NodeRecord, reason: PingReason) { if node.id == *self.local_peer_id() { // don't ping ourselves - return + return; } - if self.pending_pings.contains_key(&node.id) || - self.pending_find_nodes.contains_key(&node.id) + if self.pending_pings.contains_key(&node.id) + || self.pending_find_nodes.contains_key(&node.id) { - return + return; } if self.queued_pings.iter().any(|(n, _)| n.id == node.id) { - return + return; } if self.pending_pings.len() < MAX_NODES_PING { @@ -1254,7 +1254,7 @@ impl Discv4Service { /// Returns the echo hash of the ping message. pub(crate) fn send_enr_request(&mut self, node: NodeRecord) { if !self.config.enable_eip868 { - return + return; } let remote_addr = node.udp_addr(); let enr_request = EnrRequest { expire: self.enr_request_expiration() }; @@ -1269,7 +1269,7 @@ impl Discv4Service { /// Message handler for an incoming `Pong`. fn on_pong(&mut self, pong: Pong, remote_addr: SocketAddr, remote_id: PeerId) { if self.is_expired(pong.expire) { - return + return; } let PingRequest { node, reason, .. } = match self.pending_pings.entry(remote_id) { @@ -1278,7 +1278,7 @@ impl Discv4Service { let request = entry.get(); if request.echo_hash != pong.echo { trace!(target: "discv4", from=?remote_addr, expected=?request.echo_hash, echo_hash=?pong.echo,"Got unexpected Pong"); - return + return; } } entry.remove() @@ -1315,11 +1315,11 @@ impl Discv4Service { fn on_find_node(&mut self, msg: FindNode, remote_addr: SocketAddr, node_id: PeerId) { if self.is_expired(msg.expire) { // expiration timestamp is in the past - return + return; } if node_id == *self.local_peer_id() { // ignore find node requests to ourselves - return + return; } if self.has_bond(node_id, remote_addr.ip()) { @@ -1334,7 +1334,7 @@ impl Discv4Service { // ensure the ENR's public key matches the expected node id let enr_id = pk2id(&msg.enr.public_key()); if id != enr_id { - return + return; } if resp.echo_hash == msg.request_hash { @@ -1373,7 +1373,7 @@ impl Discv4Service { request_hash: B256, ) { if !self.config.enable_eip868 || self.is_expired(msg.expire) { - return + return; } if self.has_bond(id, remote_addr.ip()) { @@ -1392,7 +1392,7 @@ impl Discv4Service { fn on_neighbours(&mut self, msg: Neighbours, remote_addr: SocketAddr, node_id: PeerId) { if self.is_expired(msg.expire) { // response is expired - return + return; } // check if this request was expected let ctx = match self.pending_find_nodes.entry(node_id) { @@ -1408,7 +1408,7 @@ impl Discv4Service { request.response_count = total; } else { trace!(target: "discv4", total, from=?remote_addr, "Received neighbors packet entries exceeds max nodes per bucket"); - return + return; } }; @@ -1424,7 +1424,7 @@ impl Discv4Service { Entry::Vacant(_) => { // received neighbours response without requesting it trace!(target: "discv4", from=?remote_addr, "Received unsolicited Neighbours"); - return + return; } }; @@ -1444,7 +1444,7 @@ impl Discv4Service { // prevent banned peers from being added to the context if self.config.ban_list.is_banned(&node.id, &node.address) { trace!(target: "discv4", peer_id=?node.id, ip=?node.address, "ignoring banned record"); - continue + continue; } ctx.add_node(node); @@ -1540,7 +1540,7 @@ impl Discv4Service { self.pending_pings.retain(|node_id, ping_request| { if now.duration_since(ping_request.sent_at) > self.config.ping_expiration { failed_pings.push(*node_id); - return false + return false; } true }); @@ -1557,7 +1557,7 @@ impl Discv4Service { self.pending_lookup.retain(|node_id, (lookup_sent_at, _)| { if now.duration_since(*lookup_sent_at) > self.config.request_timeout { failed_lookups.push(*node_id); - return false + return false; } true }); @@ -1583,13 +1583,13 @@ impl Discv4Service { // treat this as an hard error since it responded. failed_find_nodes.push(*node_id); } - return false + return false; } true }); if failed_find_nodes.is_empty() { - return + return; } trace!(target: "discv4", num=%failed_find_nodes.len(), "processing failed find nodes"); @@ -1656,7 +1656,7 @@ impl Discv4Service { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); if self.config.enforce_expiration_timestamps && timestamp < now { trace!(target: "discv4", "Expired packet"); - return Err(()) + return Err(()); } Ok(()) } @@ -1700,7 +1700,7 @@ impl Discv4Service { loop { // drain buffered events first if let Some(event) = self.queued_events.pop_front() { - return Poll::Ready(event) + return Poll::Ready(event); } // trigger self lookup @@ -1825,7 +1825,7 @@ impl Discv4Service { // this will make sure we're woken up again cx.waker().wake_by_ref(); } - break + break; } } @@ -1843,7 +1843,7 @@ impl Discv4Service { } if self.queued_events.is_empty() { - return Poll::Pending + return Poll::Pending; } } } @@ -1950,7 +1950,7 @@ pub(crate) async fn receive_loop(udp: Arc, tx: IngressSender, local_i // rate limit incoming packets by IP if cache.inc_ip(remote_addr.ip()) > MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP { trace!(target: "discv4", ?remote_addr, "Too many incoming packets from IP."); - continue + continue; } let packet = &buf[..read]; @@ -1959,13 +1959,13 @@ pub(crate) async fn receive_loop(udp: Arc, tx: IngressSender, local_i if packet.node_id == local_id { // received our own message debug!(target: "discv4", ?remote_addr, "Received own packet."); - continue + continue; } // skip if we've already received the same packet if cache.contains_packet(packet.hash) { debug!(target: "discv4", ?remote_addr, "Received duplicate packet."); - continue + continue; } send(IngressEvent::Packet(remote_addr, packet)).await; @@ -2114,7 +2114,7 @@ impl LookupTargetRotator { self.counter += 1; self.counter %= self.interval; if self.counter == 0 { - return *local + return *local; } PeerId::random() } @@ -2488,7 +2488,7 @@ mod tests { assert!(service.pending_pings.contains_key(&node.id)); assert_eq!(service.pending_pings.len(), num_inserted); if num_inserted == MAX_NODES_PING { - break + break; } } } @@ -2668,8 +2668,8 @@ mod tests { }) .await; - let expiry = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() + - 10000000000000; + let expiry = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() + + 10000000000000; let msg = Neighbours { nodes: vec![service2.local_node_record], expire: expiry }; service.on_neighbours(msg, record.tcp_addr(), id); // wait for the processed ping diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 2aabd45d99..25d3f94b58 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -141,7 +141,7 @@ impl Message { /// Returns the decoded message and the public key of the sender. pub fn decode(packet: &[u8]) -> Result { if packet.len() < MIN_PACKET_SIZE { - return Err(DecodePacketError::PacketTooShort) + return Err(DecodePacketError::PacketTooShort); } // parses the wire-protocol, every packet starts with a header: @@ -152,7 +152,7 @@ impl Message { let header_hash = keccak256(&packet[32..]); let data_hash = B256::from_slice(&packet[..32]); if data_hash != header_hash { - return Err(DecodePacketError::HashMismatch) + return Err(DecodePacketError::HashMismatch); } let signature = &packet[32..96]; @@ -282,7 +282,7 @@ impl Decodable for FindNode { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } let started_len = b.len(); @@ -296,7 +296,7 @@ impl Decodable for FindNode { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -324,7 +324,7 @@ impl Decodable for Neighbours { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } let started_len = b.len(); @@ -338,7 +338,7 @@ impl Decodable for Neighbours { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -367,7 +367,7 @@ impl Decodable for EnrRequest { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } let started_len = b.len(); @@ -381,7 +381,7 @@ impl Decodable for EnrRequest { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -475,7 +475,7 @@ impl Decodable for Ping { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } let started_len = b.len(); @@ -499,7 +499,7 @@ impl Decodable for Ping { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; b.advance(rem); @@ -554,7 +554,7 @@ impl Decodable for Pong { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } let started_len = b.len(); let mut this = Self { @@ -574,7 +574,7 @@ impl Decodable for Pong { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; b.advance(rem); diff --git a/crates/net/discv4/src/test_utils.rs b/crates/net/discv4/src/test_utils.rs index 15311dd9c0..a75a322e77 100644 --- a/crates/net/discv4/src/test_utils.rs +++ b/crates/net/discv4/src/test_utils.rs @@ -167,7 +167,7 @@ impl Stream for MockDiscovery { ping, pong, to: remote_addr, - })) + })); } } Message::Pong(_) | Message::Neighbours(_) => {} @@ -181,7 +181,7 @@ impl Stream for MockDiscovery { return Poll::Ready(Some(MockEvent::Neighbours { nodes, to: remote_addr, - })) + })); } } Message::EnrRequest(_) | Message::EnrResponse(_) => todo!(), diff --git a/crates/net/discv5/src/config.rs b/crates/net/discv5/src/config.rs index ef89e72da5..7d3ba6973c 100644 --- a/crates/net/discv5/src/config.rs +++ b/crates/net/discv5/src/config.rs @@ -350,8 +350,8 @@ impl Config { /// Returns the IPv4 discovery socket if one is configured. pub const fn ipv4(listen_config: &ListenConfig) -> Option { match listen_config { - ListenConfig::Ipv4 { ip, port } | - ListenConfig::DualStack { ipv4: ip, ipv4_port: port, .. } => { + ListenConfig::Ipv4 { ip, port } + | ListenConfig::DualStack { ipv4: ip, ipv4_port: port, .. } => { Some(SocketAddrV4::new(*ip, *port)) } ListenConfig::Ipv6 { .. } => None, @@ -362,8 +362,8 @@ pub const fn ipv4(listen_config: &ListenConfig) -> Option { pub const fn ipv6(listen_config: &ListenConfig) -> Option { match listen_config { ListenConfig::Ipv4 { .. } => None, - ListenConfig::Ipv6 { ip, port } | - ListenConfig::DualStack { ipv6: ip, ipv6_port: port, .. } => { + ListenConfig::Ipv6 { ip, port } + | ListenConfig::DualStack { ipv6: ip, ipv6_port: port, .. } => { Some(SocketAddrV6::new(*ip, *port, 0, 0)) } } @@ -511,9 +511,9 @@ mod test { for node in config.bootstrap_nodes { let BootNode::Enr(node) = node else { panic!() }; assert!( - socket_1 == node.udp4_socket().unwrap() && socket_1 == node.tcp4_socket().unwrap() || - socket_2 == node.udp4_socket().unwrap() && - socket_2 == node.tcp4_socket().unwrap() + socket_1 == node.udp4_socket().unwrap() && socket_1 == node.tcp4_socket().unwrap() + || socket_2 == node.udp4_socket().unwrap() + && socket_2 == node.tcp4_socket().unwrap() ); assert_eq!("84b4940500", hex::encode(node.get_raw_rlp("opstack").unwrap())); } diff --git a/crates/net/discv5/src/enr.rs b/crates/net/discv5/src/enr.rs index 02c5ec389b..80bdfb0b3e 100644 --- a/crates/net/discv5/src/enr.rs +++ b/crates/net/discv5/src/enr.rs @@ -11,7 +11,7 @@ use secp256k1::{PublicKey, SecretKey}; pub fn enr_to_discv4_id(enr: &discv5::Enr) -> Option { let pk = enr.public_key(); if !matches!(pk, CombinedPublicKey::Secp256k1(_)) { - return None + return None; } let pk = PublicKey::from_slice(&pk.encode()).unwrap(); diff --git a/crates/net/discv5/src/filter.rs b/crates/net/discv5/src/filter.rs index a83345a9a5..fe6bac9220 100644 --- a/crates/net/discv5/src/filter.rs +++ b/crates/net/discv5/src/filter.rs @@ -37,7 +37,7 @@ impl MustIncludeKey { if enr.get_raw_rlp(self.key).is_none() { return FilterOutcome::Ignore { reason: format!("{} fork required", String::from_utf8_lossy(self.key)), - } + }; } FilterOutcome::Ok } @@ -72,7 +72,7 @@ impl MustNotIncludeKeys { "{} forks not allowed", self.keys.iter().map(|key| String::from_utf8_lossy(key.key)).format(",") ), - } + }; } } diff --git a/crates/net/discv5/src/lib.rs b/crates/net/discv5/src/lib.rs index 17fa68754e..1bc3f1b6cd 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -100,7 +100,7 @@ impl Discv5 { err="key not utf-8", "failed to update local enr" ); - return + return; }; if let Err(err) = self.discv5.enr_insert(key_str, &rlp) { error!(target: "net::discv5", @@ -305,7 +305,7 @@ impl Discv5 { self.metrics.discovered_peers.increment_established_sessions_unreachable_enr(1); - return None + return None; } }; if let FilterOutcome::Ignore { reason } = self.filter_discovered_peer(enr) { @@ -317,7 +317,7 @@ impl Discv5 { self.metrics.discovered_peers.increment_established_sessions_filtered(1); - return None + return None; } // todo: extend for all network stacks in reth-network rlpx logic @@ -517,7 +517,7 @@ pub async fn bootstrap( match node { BootNode::Enr(node) => { if let Err(err) = discv5.add_enr(node) { - return Err(Error::AddNodeFailed(err)) + return Err(Error::AddNodeFailed(err)); } } BootNode::Enode(enode) => { diff --git a/crates/net/discv5/src/network_stack_id.rs b/crates/net/discv5/src/network_stack_id.rs index a7b6944f35..e2125f3d4c 100644 --- a/crates/net/discv5/src/network_stack_id.rs +++ b/crates/net/discv5/src/network_stack_id.rs @@ -23,9 +23,9 @@ impl NetworkStackId { /// Returns the [`NetworkStackId`] that matches the given chain spec. pub fn id(chain: impl EthChainSpec) -> Option<&'static [u8]> { if chain.is_optimism() { - return Some(Self::OPEL) + return Some(Self::OPEL); } else if chain.is_ethereum() { - return Some(Self::ETH) + return Some(Self::ETH); } None diff --git a/crates/net/dns/src/lib.rs b/crates/net/dns/src/lib.rs index 14a78ab7cc..9ba887aaf7 100644 --- a/crates/net/dns/src/lib.rs +++ b/crates/net/dns/src/lib.rs @@ -220,7 +220,7 @@ impl DnsDiscoveryService { // already resolved let cached = ResolveEntryResult { entry: Some(Ok(entry)), link, hash, kind }; self.on_resolved_entry(cached); - return + return; } self.queries.resolve_entry(link, hash, kind) } @@ -298,7 +298,7 @@ impl DnsDiscoveryService { loop { // drain buffered events first if let Some(event) = self.queued_events.pop_front() { - return Poll::Ready(event) + return Poll::Ready(event); } // process all incoming commands @@ -351,7 +351,7 @@ impl DnsDiscoveryService { } if !progress && self.queued_events.is_empty() { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/dns/src/query.rs b/crates/net/dns/src/query.rs index edf387ec5c..aee2196ecb 100644 --- a/crates/net/dns/src/query.rs +++ b/crates/net/dns/src/query.rs @@ -75,7 +75,7 @@ impl QueryPool { loop { // drain buffered events first if let Some(event) = self.queued_outcomes.pop_front() { - return Poll::Ready(event) + return Poll::Ready(event); } // queue in new queries if we have capacity @@ -84,10 +84,10 @@ impl QueryPool { if let Some(query) = self.queued_queries.pop_front() { self.rate_limit.tick(); self.active_queries.push(query); - continue 'queries + continue 'queries; } } - break + break; } // advance all queries @@ -102,7 +102,7 @@ impl QueryPool { } if self.queued_outcomes.is_empty() { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/dns/src/sync.rs b/crates/net/dns/src/sync.rs index 5b9453959d..06de925d03 100644 --- a/crates/net/dns/src/sync.rs +++ b/crates/net/dns/src/sync.rs @@ -73,27 +73,27 @@ impl SyncTree { match self.sync_state { SyncState::Pending => { self.sync_state = SyncState::Enr; - return Some(SyncAction::Link(self.root.link_root.clone())) + return Some(SyncAction::Link(self.root.link_root.clone())); } SyncState::Enr => { self.sync_state = SyncState::Active; - return Some(SyncAction::Enr(self.root.enr_root.clone())) + return Some(SyncAction::Enr(self.root.enr_root.clone())); } SyncState::Link => { self.sync_state = SyncState::Active; - return Some(SyncAction::Link(self.root.link_root.clone())) + return Some(SyncAction::Link(self.root.link_root.clone())); } SyncState::Active => { if now > self.root_updated + update_timeout { self.sync_state = SyncState::RootUpdate; - return Some(SyncAction::UpdateRoot) + return Some(SyncAction::UpdateRoot); } } SyncState::RootUpdate => return None, } if let Some(link) = self.unresolved_links.pop_front() { - return Some(SyncAction::Link(link)) + return Some(SyncAction::Link(link)); } let enr = self.unresolved_nodes.pop_front()?; @@ -124,7 +124,7 @@ impl SyncTree { } _ => { // unchanged - return + return; } }; self.sync_state = state; diff --git a/crates/net/dns/src/tree.rs b/crates/net/dns/src/tree.rs index 822eec327c..036725ca6f 100644 --- a/crates/net/dns/src/tree.rs +++ b/crates/net/dns/src/tree.rs @@ -205,7 +205,7 @@ impl BranchEntry { let decoded_len = base32_no_padding_decoded_len(hash.len()); if !(12..=32).contains(&decoded_len) || hash.chars().any(|c| c.is_whitespace()) { - return Err(ParseDnsEntryError::InvalidChildHash(hash.to_string())) + return Err(ParseDnsEntryError::InvalidChildHash(hash.to_string())); } Ok(hash.to_string()) } diff --git a/crates/net/downloaders/src/bodies/bodies.rs b/crates/net/downloaders/src/bodies/bodies.rs index a6e454b041..5fea0b0883 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -103,7 +103,7 @@ where max_non_empty: u64, ) -> DownloadResult>>> { if range.is_empty() || max_non_empty == 0 { - return Ok(None) + return Ok(None); } // Collect headers while @@ -114,9 +114,9 @@ where let mut collected = 0; let mut non_empty_headers = 0; let headers = self.provider.sealed_headers_while(range.clone(), |header| { - let should_take = range.contains(&header.number()) && - non_empty_headers < max_non_empty && - collected < self.stream_batch_size; + let should_take = range.contains(&header.number()) + && non_empty_headers < max_non_empty + && collected < self.stream_batch_size; if should_take { collected += 1; @@ -152,7 +152,7 @@ where // if we're only connected to a few peers, we keep it low if num_peers < *self.concurrent_requests_range.start() { - return max_requests + return max_requests; } max_requests.min(*self.concurrent_requests_range.end()) @@ -171,10 +171,10 @@ where self.in_progress_queue .last_requested_block_number.is_some_and(|last| last == *self.download_range.end()); - nothing_to_request && - self.in_progress_queue.is_empty() && - self.buffered_responses.is_empty() && - self.queued_bodies.is_empty() + nothing_to_request + && self.in_progress_queue.is_empty() + && self.buffered_responses.is_empty() + && self.queued_bodies.is_empty() } /// Clear all download related data. @@ -216,8 +216,8 @@ where /// Adds a new response to the internal buffer fn buffer_bodies_response(&mut self, response: Vec>) { // take into account capacity - let size = response.iter().map(BlockResponse::size).sum::() + - response.capacity() * mem::size_of::>(); + let size = response.iter().map(BlockResponse::size).sum::() + + response.capacity() * mem::size_of::>(); let response = OrderedBodiesResponse { resp: response, size }; let response_len = response.len(); @@ -244,7 +244,7 @@ where .skip_while(|b| b.block_number() < expected) .take_while(|b| self.download_range.contains(&b.block_number())) .collect() - }) + }); } // Drop buffered response since we passed that range @@ -263,7 +263,7 @@ where self.queued_bodies.shrink_to_fit(); self.metrics.total_flushed.increment(next_batch.len() as u64); self.metrics.queued_blocks.set(self.queued_bodies.len() as f64); - return Some(next_batch) + return Some(next_batch); } None } @@ -276,9 +276,9 @@ where // requests are issued in order but not necessarily finished in order, so the queued bodies // can grow large if a certain request is slow, so we limit the followup requests if the // queued bodies grew too large - self.queued_bodies.len() < 4 * self.stream_batch_size && - self.has_buffer_capacity() && - self.in_progress_queue.len() < self.concurrent_request_limit() + self.queued_bodies.len() < 4 * self.stream_batch_size + && self.has_buffer_capacity() + && self.in_progress_queue.len() < self.concurrent_request_limit() } } @@ -320,16 +320,16 @@ where // Check if the range is valid. if range.is_empty() { tracing::error!(target: "downloaders::bodies", ?range, "Bodies download range is invalid (empty)"); - return Err(DownloadError::InvalidBodyRange { range }) + return Err(DownloadError::InvalidBodyRange { range }); } // Check if the provided range is the subset of the existing range. - let is_current_range_subset = self.download_range.contains(range.start()) && - *range.end() == *self.download_range.end(); + let is_current_range_subset = self.download_range.contains(range.start()) + && *range.end() == *self.download_range.end(); if is_current_range_subset { tracing::trace!(target: "downloaders::bodies", ?range, "Download range already in progress"); // The current range already includes requested. - return Ok(()) + return Ok(()); } // Check if the provided range is the next expected range. @@ -340,7 +340,7 @@ where tracing::trace!(target: "downloaders::bodies", ?range, "New download range set"); info!(target: "downloaders::bodies", count, ?range, "Downloading bodies"); self.download_range = range; - return Ok(()) + return Ok(()); } // The block range is reset. This can happen either after unwind or after the bodies were @@ -364,13 +364,13 @@ where fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if this.is_terminated() { - return Poll::Ready(None) + return Poll::Ready(None); } // Submit new requests and poll any in progress loop { // Yield next batch if ready if let Some(next_batch) = this.try_split_next_batch() { - return Poll::Ready(Some(Ok(next_batch))) + return Poll::Ready(Some(Ok(next_batch))); } // Poll requests @@ -383,7 +383,7 @@ where Err(error) => { tracing::debug!(target: "downloaders::bodies", %error, "Request failed"); this.clear(); - return Poll::Ready(Some(Err(error))) + return Poll::Ready(Some(Err(error))); } }; } @@ -406,7 +406,7 @@ where Err(error) => { tracing::error!(target: "downloaders::bodies", %error, "Failed to download from next request"); this.clear(); - return Poll::Ready(Some(Err(error))) + return Poll::Ready(Some(Err(error))); } }; } @@ -419,21 +419,21 @@ where this.buffered_responses.shrink_to_fit(); if !new_request_submitted { - break + break; } } // All requests are handled, stream is finished if this.in_progress_queue.is_empty() { if this.queued_bodies.is_empty() { - return Poll::Ready(None) + return Poll::Ready(None); } let batch_size = this.stream_batch_size.min(this.queued_bodies.len()); let next_batch = this.queued_bodies.drain(..batch_size).collect::>(); this.queued_bodies.shrink_to_fit(); this.metrics.total_flushed.increment(next_batch.len() as u64); this.metrics.queued_blocks.set(this.queued_bodies.len() as f64); - return Poll::Ready(Some(Ok(next_batch))) + return Poll::Ready(Some(Ok(next_batch))); } Poll::Pending @@ -522,8 +522,8 @@ impl BodiesDownloaderBuilder { .with_request_limit(config.downloader_request_limit) .with_max_buffered_blocks_size_bytes(config.downloader_max_buffered_blocks_size_bytes) .with_concurrent_requests_range( - config.downloader_min_concurrent_requests..= - config.downloader_max_concurrent_requests, + config.downloader_min_concurrent_requests + ..=config.downloader_max_concurrent_requests, ) } } diff --git a/crates/net/downloaders/src/bodies/request.rs b/crates/net/downloaders/src/bodies/request.rs index aa10db382a..d06672566b 100644 --- a/crates/net/downloaders/src/bodies/request.rs +++ b/crates/net/downloaders/src/bodies/request.rs @@ -134,14 +134,14 @@ where // next one exceed the soft response limit, if not then peer either does not have the next // block or deliberately sent a single block. if bodies.is_empty() { - return Err(DownloadError::EmptyResponse) + return Err(DownloadError::EmptyResponse); } if response_len > request_len { return Err(DownloadError::TooManyBodies(GotExpected { got: response_len, expected: request_len, - })) + })); } // Buffer block responses @@ -198,7 +198,7 @@ where hash, number, error: Box::new(error), - }) + }); } self.buffer.push(BlockResponse::Full(block)); @@ -225,7 +225,7 @@ where loop { if this.pending_headers.is_empty() { - return Poll::Ready(Ok(std::mem::take(&mut this.buffer))) + return Poll::Ready(Ok(std::mem::take(&mut this.buffer))); } // Check if there is a pending requests. It might not exist if all @@ -240,7 +240,7 @@ where } Err(error) => { if error.is_channel_closed() { - return Poll::Ready(Err(error.into())) + return Poll::Ready(Err(error.into())); } this.on_error(error.into(), None); diff --git a/crates/net/downloaders/src/bodies/task.rs b/crates/net/downloaders/src/bodies/task.rs index df1d5540db..cf75814377 100644 --- a/crates/net/downloaders/src/bodies/task.rs +++ b/crates/net/downloaders/src/bodies/task.rs @@ -136,13 +136,13 @@ impl Future for SpawnedDownloader { if forward_error_result.is_err() { // channel closed, this means [TaskDownloader] was dropped, // so we can also exit - return Poll::Ready(()) + return Poll::Ready(()); } } } else { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()) + return Poll::Ready(()); } } @@ -152,7 +152,7 @@ impl Future for SpawnedDownloader { if this.bodies_tx.send_item(bodies).is_err() { // channel closed, this means [TaskDownloader] was dropped, so we can // also exit - return Poll::Ready(()) + return Poll::Ready(()); } } None => return Poll::Pending, @@ -160,7 +160,7 @@ impl Future for SpawnedDownloader { Err(_) => { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()) + return Poll::Ready(()); } } } diff --git a/crates/net/downloaders/src/file_client.rs b/crates/net/downloaders/src/file_client.rs index a0b83d72d4..aaa3cc8d88 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -135,7 +135,7 @@ impl FileClient { /// Returns true if all blocks are canonical (no gaps) pub fn has_canonical_blocks(&self) -> bool { if self.headers.is_empty() { - return true + return true; } let mut nums = self.headers.keys().copied().collect::>(); nums.sort_unstable(); @@ -143,7 +143,7 @@ impl FileClient { let mut lowest = iter.next().expect("not empty"); for next in iter { if next != lowest + 1 { - return false + return false; } lowest = next; } @@ -247,7 +247,7 @@ impl> FromReader "partial block returned from decoding chunk" ); remaining_bytes = bytes; - break + break; } Err(err) => return Err(err), }; @@ -317,7 +317,7 @@ impl HeadersClient for FileClient { Some(num) => *num, None => { warn!(%hash, "Could not find starting block number for requested header hash"); - return Box::pin(async move { Err(RequestError::BadResponse) }) + return Box::pin(async move { Err(RequestError::BadResponse) }); } }, BlockHashOrNumber::Number(num) => num, @@ -341,7 +341,7 @@ impl HeadersClient for FileClient { Some(header) => headers.push(header), None => { warn!(number=%block_number, "Could not find header"); - return Box::pin(async move { Err(RequestError::BadResponse) }) + return Box::pin(async move { Err(RequestError::BadResponse) }); } } } @@ -454,7 +454,7 @@ impl ChunkedFileReader { async fn read_next_chunk(&mut self) -> Result, io::Error> { if self.file_byte_len == 0 && self.chunk.is_empty() { // eof - return Ok(None) + return Ok(None); } let chunk_target_len = self.chunk_len(); diff --git a/crates/net/downloaders/src/file_codec.rs b/crates/net/downloaders/src/file_codec.rs index 57a15b6c88..c9ccb2cee9 100644 --- a/crates/net/downloaders/src/file_codec.rs +++ b/crates/net/downloaders/src/file_codec.rs @@ -32,7 +32,7 @@ impl Decoder for BlockFileCodec { fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None) + return Ok(None); } let buf_slice = &mut src.as_ref(); diff --git a/crates/net/downloaders/src/headers/reverse_headers.rs b/crates/net/downloaders/src/headers/reverse_headers.rs index 5f27467cf8..bda6d5a70b 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -160,7 +160,7 @@ where // If only a few peers are connected we keep it low if num_peers < self.min_concurrent_requests { - return max_dynamic + return max_dynamic; } max_dynamic.min(self.max_concurrent_requests) @@ -183,7 +183,7 @@ where // headers so follow-up requests will use that as start. self.next_request_block_number -= request.limit; - return Some(request) + return Some(request); } } @@ -272,7 +272,7 @@ where trace!(target: "downloaders::headers", %error ,"Failed to validate header"); return Err( HeadersResponseError { request, peer_id: Some(peer_id), error }.into() - ) + ); } } else { self.validate_sync_target(&parent, request.clone(), peer_id)?; @@ -299,7 +299,7 @@ where error: Box::new(error), }, } - .into()) + .into()); } // If the header is valid on its own, but not against its parent, we return it as @@ -324,7 +324,7 @@ where header: Box::new(last_header.clone()), error: Box::new(error), } - .into()) + .into()); } } @@ -397,7 +397,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()) + .into()); } let header = headers.swap_remove(0); @@ -413,7 +413,7 @@ where GotExpected { got: target.hash(), expected: hash }.into(), ), } - .into()) + .into()); } } SyncTargetBlock::Number(number) => { @@ -426,7 +426,7 @@ where expected: number, }), } - .into()) + .into()); } } } @@ -475,7 +475,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()) + .into()); } if (headers.len() as u64) != request.limit { @@ -487,7 +487,7 @@ where }), request, } - .into()) + .into()); } // sort headers from highest to lowest block number @@ -507,7 +507,7 @@ where expected: requested_block_number, }), } - .into()) + .into()); } // check if the response is the next expected @@ -578,7 +578,7 @@ where self.metrics.buffered_responses.decrement(1.); if let Err(err) = self.process_next_headers(request, headers, peer_id) { - return Some(err) + return Some(err); } } Ordering::Greater => { @@ -729,7 +729,7 @@ where .map(|h| h.number()) { self.sync_target = Some(new_sync_target.with_number(target_number)); - return + return; } trace!(target: "downloaders::headers", new=?target, "Request new sync target"); @@ -796,7 +796,7 @@ where sync_target=?this.sync_target, "The downloader sync boundaries have not been set" ); - return Poll::Pending + return Poll::Pending; } // If we have a new tip request we need to complete that first before we send batched @@ -810,7 +810,7 @@ where trace!(target: "downloaders::headers", %error, "invalid sync target response"); if error.is_channel_closed() { // download channel closed which means the network was dropped - return Poll::Ready(None) + return Poll::Ready(None); } this.penalize_peer(error.peer_id, &error.error); @@ -820,13 +820,13 @@ where } Err(ReverseHeadersDownloaderError::Downloader(error)) => { this.clear(); - return Poll::Ready(Some(Err(error))) + return Poll::Ready(Some(Err(error))); } }; } Poll::Pending => { this.sync_target_request = Some(req); - return Poll::Pending + return Poll::Pending; } } } @@ -852,13 +852,13 @@ where Err(ReverseHeadersDownloaderError::Response(error)) => { if error.is_channel_closed() { // download channel closed which means the network was dropped - return Poll::Ready(None) + return Poll::Ready(None); } this.on_headers_error(error); } Err(ReverseHeadersDownloaderError::Downloader(error)) => { this.clear(); - return Poll::Ready(Some(Err(error))) + return Poll::Ready(Some(Err(error))); } }; } @@ -871,8 +871,8 @@ where let concurrent_request_limit = this.concurrent_request_limit(); // populate requests - while this.in_progress_queue.len() < concurrent_request_limit && - this.buffered_responses.len() < this.max_buffered_responses + while this.in_progress_queue.len() < concurrent_request_limit + && this.buffered_responses.len() < this.max_buffered_responses { if let Some(request) = this.next_request() { trace!( @@ -883,7 +883,7 @@ where this.submit_request(request, Priority::Normal); } else { // no more requests - break + break; } } @@ -900,11 +900,11 @@ where trace!(target: "downloaders::headers", batch=%next_batch.len(), "Returning validated batch"); this.metrics.total_flushed.increment(next_batch.len() as u64); - return Poll::Ready(Some(Ok(next_batch))) + return Poll::Ready(Some(Ok(next_batch))); } if !progress { - break + break; } } @@ -913,10 +913,10 @@ where let next_batch = this.split_next_batch(); if next_batch.is_empty() { this.clear(); - return Poll::Ready(None) + return Poll::Ready(None); } this.metrics.total_flushed.increment(next_batch.len() as u64); - return Poll::Ready(Some(Ok(next_batch))) + return Poll::Ready(Some(Ok(next_batch))); } Poll::Pending @@ -1009,7 +1009,7 @@ impl HeadersResponseError { /// Returns true if the error was caused by a closed channel to the network. const fn is_channel_closed(&self) -> bool { if let DownloadError::RequestError(ref err) = self.error { - return err.is_channel_closed() + return err.is_channel_closed(); } false } diff --git a/crates/net/downloaders/src/headers/task.rs b/crates/net/downloaders/src/headers/task.rs index 38eb1429a8..8a3649cc56 100644 --- a/crates/net/downloaders/src/headers/task.rs +++ b/crates/net/downloaders/src/headers/task.rs @@ -133,7 +133,7 @@ impl Future for SpawnedDownloader { Poll::Ready(None) => { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()) + return Poll::Ready(()); } Poll::Ready(Some(update)) => match update { DownloaderUpdates::UpdateSyncGap(head, target) => { @@ -159,7 +159,7 @@ impl Future for SpawnedDownloader { if this.headers_tx.send_item(headers).is_err() { // channel closed, this means [TaskDownloader] was dropped, so we // can also exit - return Poll::Ready(()) + return Poll::Ready(()); } } None => return Poll::Pending, @@ -168,7 +168,7 @@ impl Future for SpawnedDownloader { Err(_) => { // channel closed, this means [TaskDownloader] was dropped, so // we can also exit - return Poll::Ready(()) + return Poll::Ready(()); } } } diff --git a/crates/net/downloaders/src/receipt_file_client.rs b/crates/net/downloaders/src/receipt_file_client.rs index 60af1e7027..cdf774a900 100644 --- a/crates/net/downloaders/src/receipt_file_client.rs +++ b/crates/net/downloaders/src/receipt_file_client.rs @@ -100,7 +100,7 @@ where remaining_bytes = bytes; - break + break; } Err(err) => return Err(err), }; @@ -109,7 +109,7 @@ where Some(ReceiptWithBlockNumber { receipt, number }) => { if block_number > number { warn!(target: "downloaders::file", previous_block_number = block_number, "skipping receipt from a lower block: {number}"); - continue + continue; } total_receipts += 1; @@ -266,7 +266,7 @@ mod test { fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None) + return Ok(None); } let buf_slice = &mut src.as_ref(); diff --git a/crates/net/downloaders/src/test_utils/bodies_client.rs b/crates/net/downloaders/src/test_utils/bodies_client.rs index 6b0c65a38a..452a6707ac 100644 --- a/crates/net/downloaders/src/test_utils/bodies_client.rs +++ b/crates/net/downloaders/src/test_utils/bodies_client.rs @@ -97,7 +97,7 @@ impl BodiesClient for TestBodiesClient { Box::pin(async move { if should_respond_empty { - return Ok((PeerId::default(), vec![]).into()) + return Ok((PeerId::default(), vec![]).into()); } if should_delay { diff --git a/crates/net/ecies/src/algorithm.rs b/crates/net/ecies/src/algorithm.rs index 350cd3f7ed..0881665f2b 100644 --- a/crates/net/ecies/src/algorithm.rs +++ b/crates/net/ecies/src/algorithm.rs @@ -99,7 +99,7 @@ impl core::fmt::Debug for ECIES { fn split_at_mut(arr: &mut [T], idx: usize) -> Result<(&mut [T], &mut [T]), ECIESError> { if idx > arr.len() { - return Err(ECIESErrorImpl::OutOfBounds { idx, len: arr.len() }.into()) + return Err(ECIESErrorImpl::OutOfBounds { idx, len: arr.len() }.into()); } Ok(arr.split_at_mut(idx)) } @@ -138,7 +138,7 @@ impl<'a> EncryptedMessage<'a> { pub fn parse(data: &mut [u8]) -> Result, ECIESError> { // Auth data is 2 bytes, public key is 65 bytes if data.len() < 65 + 2 { - return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()) + return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()); } let (auth_data, encrypted) = data.split_at_mut(2); @@ -164,7 +164,7 @@ impl<'a> EncryptedMessage<'a> { // now we can check if the encrypted data is long enough to contain the IV if data_iv.len() < 16 { - return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()) + return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()); } let (iv, encrypted_data) = data_iv.split_at_mut(16); @@ -234,7 +234,7 @@ impl<'a> EncryptedMessage<'a> { &self.auth_data, ); if check_tag != self.tag { - return Err(ECIESErrorImpl::TagCheckDecryptFailed.into()) + return Err(ECIESErrorImpl::TagCheckDecryptFailed.into()); } Ok(()) @@ -656,7 +656,7 @@ impl ECIES { // // The header is 16 bytes, and the mac is 16 bytes, so the data must be at least 32 bytes if data.len() < 32 { - return Err(ECIESErrorImpl::InvalidHeader.into()) + return Err(ECIESErrorImpl::InvalidHeader.into()); } let (header_bytes, mac_bytes) = split_at_mut(data, 16)?; @@ -666,12 +666,12 @@ impl ECIES { self.ingress_mac.as_mut().unwrap().update_header(header); let check_mac = self.ingress_mac.as_mut().unwrap().digest(); if check_mac != mac { - return Err(ECIESErrorImpl::TagCheckHeaderFailed.into()) + return Err(ECIESErrorImpl::TagCheckHeaderFailed.into()); } self.ingress_aes.as_mut().unwrap().apply_keystream(header); if header.as_slice().len() < 3 { - return Err(ECIESErrorImpl::InvalidHeader.into()) + return Err(ECIESErrorImpl::InvalidHeader.into()); } let body_size = usize::try_from(header.as_slice().read_uint::(3)?)?; @@ -722,7 +722,7 @@ impl ECIES { self.ingress_mac.as_mut().unwrap().update_body(body); let check_mac = self.ingress_mac.as_mut().unwrap().digest(); if check_mac != mac { - return Err(ECIESErrorImpl::TagCheckBodyFailed.into()) + return Err(ECIESErrorImpl::TagCheckBodyFailed.into()); } let size = self.body_size.unwrap(); diff --git a/crates/net/ecies/src/codec.rs b/crates/net/ecies/src/codec.rs index b5a10284cf..99c054906f 100644 --- a/crates/net/ecies/src/codec.rs +++ b/crates/net/ecies/src/codec.rs @@ -65,7 +65,7 @@ impl Decoder for ECIESCodec { ECIESState::Auth => { trace!("parsing auth"); if buf.len() < 2 { - return Ok(None) + return Ok(None); } let payload_size = u16::from_be_bytes([buf[0], buf[1]]) as usize; @@ -73,18 +73,18 @@ impl Decoder for ECIESCodec { if buf.len() < total_size { trace!("current len {}, need {}", buf.len(), total_size); - return Ok(None) + return Ok(None); } self.ecies.read_auth(&mut buf.split_to(total_size))?; self.state = ECIESState::InitialHeader; - return Ok(Some(IngressECIESValue::AuthReceive(self.ecies.remote_id()))) + return Ok(Some(IngressECIESValue::AuthReceive(self.ecies.remote_id()))); } ECIESState::Ack => { trace!("parsing ack with len {}", buf.len()); if buf.len() < 2 { - return Ok(None) + return Ok(None); } let payload_size = u16::from_be_bytes([buf[0], buf[1]]) as usize; @@ -92,18 +92,18 @@ impl Decoder for ECIESCodec { if buf.len() < total_size { trace!("current len {}, need {}", buf.len(), total_size); - return Ok(None) + return Ok(None); } self.ecies.read_ack(&mut buf.split_to(total_size))?; self.state = ECIESState::InitialHeader; - return Ok(Some(IngressECIESValue::Ack)) + return Ok(Some(IngressECIESValue::Ack)); } ECIESState::InitialHeader => { if buf.len() < ECIES::header_len() { trace!("current len {}, need {}", buf.len(), ECIES::header_len()); - return Ok(None) + return Ok(None); } let body_size = @@ -115,7 +115,7 @@ impl Decoder for ECIESCodec { body_size, max_body_size: MAX_INITIAL_HANDSHAKE_SIZE, } - .into()) + .into()); } self.state = ECIESState::Body; @@ -123,7 +123,7 @@ impl Decoder for ECIESCodec { ECIESState::Header => { if buf.len() < ECIES::header_len() { trace!("current len {}, need {}", buf.len(), ECIES::header_len()); - return Ok(None) + return Ok(None); } self.ecies.read_header(&mut buf.split_to(ECIES::header_len()))?; @@ -132,7 +132,7 @@ impl Decoder for ECIESCodec { } ECIESState::Body => { if buf.len() < self.ecies.body_len() { - return Ok(None) + return Ok(None); } let mut data = buf.split_to(self.ecies.body_len()); @@ -140,7 +140,7 @@ impl Decoder for ECIESCodec { ret.extend_from_slice(self.ecies.read_body(&mut data)?); self.state = ECIESState::Header; - return Ok(Some(IngressECIESValue::Message(ret))) + return Ok(Some(IngressECIESValue::Message(ret))); } } } diff --git a/crates/net/eth-wire-types/src/broadcast.rs b/crates/net/eth-wire-types/src/broadcast.rs index c877b673c7..c963636e57 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -33,7 +33,7 @@ impl NewBlockHashes { pub fn latest(&self) -> Option<&BlockHashNumber> { self.0.iter().fold(None, |latest, block| { if let Some(latest) = latest { - return if latest.number > block.number { Some(latest) } else { Some(block) } + return if latest.number > block.number { Some(latest) } else { Some(block) }; } Some(block) }) @@ -480,13 +480,13 @@ impl Decodable for NewPooledTransactionHashes68 { return Err(alloy_rlp::Error::ListLengthMismatch { expected: msg.hashes.len(), got: msg.types.len(), - }) + }); } if msg.hashes.len() != msg.sizes.len() { return Err(alloy_rlp::Error::ListLengthMismatch { expected: msg.hashes.len(), got: msg.sizes.len(), - }) + }); } Ok(msg) @@ -759,7 +759,7 @@ impl RequestTxHashes { pub fn retain_count(&mut self, count: usize) -> Self { let rest_capacity = self.hashes.len().saturating_sub(count); if rest_capacity == 0 { - return Self::empty() + return Self::empty(); } let mut rest = Self::with_capacity(rest_capacity); @@ -767,7 +767,7 @@ impl RequestTxHashes { self.hashes.retain(|hash| { if i >= count { rest.insert(*hash); - return false + return false; } i += 1; diff --git a/crates/net/eth-wire-types/src/disconnect_reason.rs b/crates/net/eth-wire-types/src/disconnect_reason.rs index 5efa9e571c..c877e1d4c0 100644 --- a/crates/net/eth-wire-types/src/disconnect_reason.rs +++ b/crates/net/eth-wire-types/src/disconnect_reason.rs @@ -96,9 +96,9 @@ impl Decodable for DisconnectReason { /// reason encoded a single byte or a RLP list containing the disconnect reason. fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { if buf.is_empty() { - return Err(alloy_rlp::Error::InputTooShort) + return Err(alloy_rlp::Error::InputTooShort); } else if buf.len() > 2 { - return Err(alloy_rlp::Error::Overflow) + return Err(alloy_rlp::Error::Overflow); } if buf.len() > 1 { @@ -107,14 +107,14 @@ impl Decodable for DisconnectReason { let header = Header::decode(buf)?; if !header.list { - return Err(alloy_rlp::Error::UnexpectedString) + return Err(alloy_rlp::Error::UnexpectedString); } if header.payload_length != 1 { return Err(alloy_rlp::Error::ListLengthMismatch { expected: 1, got: header.payload_length, - }) + }); } } diff --git a/crates/net/eth-wire-types/src/message.rs b/crates/net/eth-wire-types/src/message.rs index 0e54b86222..29e3cea740 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -101,13 +101,13 @@ impl ProtocolMessage { } EthMessageID::GetNodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); } EthMessage::GetNodeData(RequestPair::decode(buf)?) } EthMessageID::NodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); } EthMessage::NodeData(RequestPair::decode(buf)?) } @@ -122,7 +122,7 @@ impl ProtocolMessage { } EthMessageID::BlockRangeUpdate => { if version < EthVersion::Eth69 { - return Err(MessageError::Invalid(version, EthMessageID::BlockRangeUpdate)) + return Err(MessageError::Invalid(version, EthMessageID::BlockRangeUpdate)); } EthMessage::BlockRangeUpdate(BlockRangeUpdate::decode(buf)?) } @@ -311,11 +311,11 @@ impl EthMessage { pub const fn is_request(&self) -> bool { matches!( self, - Self::GetBlockBodies(_) | - Self::GetBlockHeaders(_) | - Self::GetReceipts(_) | - Self::GetPooledTransactions(_) | - Self::GetNodeData(_) + Self::GetBlockBodies(_) + | Self::GetBlockHeaders(_) + | Self::GetReceipts(_) + | Self::GetPooledTransactions(_) + | Self::GetNodeData(_) ) } @@ -323,12 +323,12 @@ impl EthMessage { pub const fn is_response(&self) -> bool { matches!( self, - Self::PooledTransactions(_) | - Self::Receipts(_) | - Self::Receipts69(_) | - Self::BlockHeaders(_) | - Self::BlockBodies(_) | - Self::NodeData(_) + Self::PooledTransactions(_) + | Self::Receipts(_) + | Self::Receipts69(_) + | Self::BlockHeaders(_) + | Self::BlockBodies(_) + | Self::NodeData(_) ) } } @@ -627,7 +627,7 @@ where // RequestPair let consumed_len = initial_length - buf.len(); if consumed_len != header.payload_length { - return Err(alloy_rlp::Error::UnexpectedLength) + return Err(alloy_rlp::Error::UnexpectedLength); } Ok(Self { request_id, message }) diff --git a/crates/net/eth-wire/src/capability.rs b/crates/net/eth-wire/src/capability.rs index 97e15dbe1f..775715d178 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -58,7 +58,7 @@ impl SharedCapability { messages: u8, ) -> Result { if offset <= MAX_RESERVED_MESSAGE_ID { - return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)) + return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)); } match name { @@ -214,12 +214,12 @@ impl SharedCapabilities { let mut cap = iter.next()?; if offset < cap.message_id_offset() { // reserved message id space - return None + return None; } for next in iter { if offset < next.message_id_offset() { - return Some(cap) + return Some(cap); } cap = next } @@ -303,7 +303,7 @@ pub fn shared_capability_offsets( // disconnect if we don't share any capabilities if shared_capabilities.is_empty() { - return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)) + return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)); } // order versions based on capability name (alphabetical) and select offsets based on @@ -327,7 +327,7 @@ pub fn shared_capability_offsets( } if shared_with_offsets.is_empty() { - return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)) + return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)); } Ok(shared_with_offsets) diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index 5e3cbbdb9a..32ecace3ce 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -66,7 +66,7 @@ impl EthStreamError { /// Returns the [`io::Error`] if it was caused by IO pub const fn as_io(&self) -> Option<&io::Error> { if let Self::P2PStreamError(P2PStreamError::Io(io)) = self { - return Some(io) + return Some(io); } None } diff --git a/crates/net/eth-wire/src/errors/p2p.rs b/crates/net/eth-wire/src/errors/p2p.rs index c77816b48b..f6b98c2776 100644 --- a/crates/net/eth-wire/src/errors/p2p.rs +++ b/crates/net/eth-wire/src/errors/p2p.rs @@ -82,8 +82,8 @@ impl P2PStreamError { /// Returns the [`DisconnectReason`] if it is the `Disconnected` variant. pub const fn as_disconnected(&self) -> Option { let reason = match self { - Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) | - Self::Disconnected(reason) => reason, + Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) + | Self::Disconnected(reason) => reason, _ => return None, }; diff --git a/crates/net/eth-wire/src/eth_snap_stream.rs b/crates/net/eth-wire/src/eth_snap_stream.rs index 000e161510..384779843b 100644 --- a/crates/net/eth-wire/src/eth_snap_stream.rs +++ b/crates/net/eth-wire/src/eth_snap_stream.rs @@ -236,9 +236,9 @@ where Err(EthSnapStreamError::InvalidMessage(self.eth_version, err.to_string())) } } - } else if message_id > EthMessageID::max(self.eth_version) && - message_id <= - EthMessageID::max(self.eth_version) + 1 + SnapMessageId::TrieNodes as u8 + } else if message_id > EthMessageID::max(self.eth_version) + && message_id + <= EthMessageID::max(self.eth_version) + 1 + SnapMessageId::TrieNodes as u8 { // Checks for multiplexed snap message IDs : // - message_id > EthMessageID::max() : ensures it's not an eth message @@ -405,8 +405,8 @@ mod tests { // This should be decoded as eth message let eth_boundary_result = inner.decode_message(eth_boundary_bytes); assert!( - eth_boundary_result.is_err() || - matches!(eth_boundary_result, Ok(EthSnapMessage::Eth(_))) + eth_boundary_result.is_err() + || matches!(eth_boundary_result, Ok(EthSnapMessage::Eth(_))) ); // Create a bytes buffer with message ID just above eth max, it should be snap min diff --git a/crates/net/eth-wire/src/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index 415603c8c2..20ee7fd640 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -289,7 +289,7 @@ where // allowing for its start_disconnect method to be called. // // self.project().inner.start_disconnect(DisconnectReason::ProtocolBreach); - return Err(EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake)) + return Err(EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake)); } self.project() diff --git a/crates/net/eth-wire/src/multiplex.rs b/crates/net/eth-wire/src/multiplex.rs index d44f5ea7eb..6616d85f97 100644 --- a/crates/net/eth-wire/src/multiplex.rs +++ b/crates/net/eth-wire/src/multiplex.rs @@ -81,7 +81,7 @@ impl RlpxProtocolMultiplexer { { let Ok(shared_cap) = self.shared_capabilities().ensure_matching_capability(cap).cloned() else { - return Err(P2PStreamError::CapabilityNotShared) + return Err(P2PStreamError::CapabilityNotShared); }; let (to_primary, from_wire) = mpsc::unbounded_channel(); @@ -149,7 +149,7 @@ impl RlpxProtocolMultiplexer { { let Ok(shared_cap) = self.shared_capabilities().ensure_matching_capability(cap).cloned() else { - return Err(P2PStreamError::CapabilityNotShared.into()) + return Err(P2PStreamError::CapabilityNotShared.into()); }; let (to_primary, from_wire) = mpsc::unbounded_channel(); @@ -245,7 +245,7 @@ impl MultiplexInner { for proto in &self.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - return true + return true; } } false @@ -301,7 +301,7 @@ impl ProtocolProxy { fn try_send(&self, msg: Bytes) -> Result<(), io::Error> { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()) + return Err(io::ErrorKind::InvalidInput.into()); } self.to_wire.send(self.mask_msg_id(msg)?).map_err(|_| io::ErrorKind::BrokenPipe.into()) } @@ -311,7 +311,7 @@ impl ProtocolProxy { fn mask_msg_id(&self, msg: Bytes) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()) + return Err(io::ErrorKind::InvalidInput.into()); } let offset = self.shared_cap.relative_message_id_offset(); @@ -329,7 +329,7 @@ impl ProtocolProxy { fn unmask_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()) + return Err(io::ErrorKind::InvalidInput.into()); } msg[0] = msg[0] .checked_sub(self.shared_cap.relative_message_id_offset()) @@ -463,7 +463,7 @@ where loop { // first drain the primary stream if let Poll::Ready(Some(msg)) = this.primary.st.try_poll_next_unpin(cx) { - return Poll::Ready(Some(msg)) + return Poll::Ready(Some(msg)); } let mut conn_ready = true; @@ -472,23 +472,23 @@ where Poll::Ready(Ok(())) => { if let Some(msg) = this.inner.out_buffer.pop_front() { if let Err(err) = this.inner.conn.start_send_unpin(msg) { - return Poll::Ready(Some(Err(err.into()))) + return Poll::Ready(Some(Err(err.into()))); } } else { - break + break; } } Poll::Ready(Err(err)) => { if let Err(disconnect_err) = this.inner.conn.start_disconnect(DisconnectReason::DisconnectRequested) { - return Poll::Ready(Some(Err(disconnect_err.into()))) + return Poll::Ready(Some(Err(disconnect_err.into()))); } - return Poll::Ready(Some(Err(err.into()))) + return Poll::Ready(Some(Err(err.into()))); } Poll::Pending => { conn_ready = false; - break + break; } } } @@ -501,7 +501,7 @@ where } Poll::Ready(None) => { // primary closed - return Poll::Ready(None) + return Poll::Ready(None); } Poll::Pending => break, } @@ -521,7 +521,7 @@ where Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => { this.inner.protocols.push(proto); - break + break; } } } @@ -536,7 +536,7 @@ where let Some(offset) = msg.first().copied() else { return Poll::Ready(Some(Err( P2PStreamError::EmptyProtocolMessage.into() - ))) + ))); }; // delegate the multiplexed message to the correct protocol if let Some(cap) = @@ -550,28 +550,27 @@ where for proto in &this.inner.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - break + break; } } } } else { - return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId( - offset, - ) - .into()))) + return Poll::Ready(Some(Err( + P2PStreamError::UnknownReservedMessageId(offset).into(), + ))); } } Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err.into()))), Poll::Ready(None) => { // connection closed - return Poll::Ready(None) + return Poll::Ready(None); } Poll::Pending => break, } } if !conn_ready || (!delegated && this.inner.out_buffer.is_empty()) { - return Poll::Pending + return Poll::Pending; } } } @@ -588,10 +587,10 @@ where fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Err(err) = ready!(this.inner.conn.poll_ready_unpin(cx)) { - return Poll::Ready(Err(err.into())) + return Poll::Ready(Err(err.into())); } if let Err(err) = ready!(this.primary.st.poll_ready_unpin(cx)) { - return Poll::Ready(Err(err)) + return Poll::Ready(Err(err)); } Poll::Ready(Ok(())) } @@ -623,7 +622,7 @@ impl ProtocolStream { fn mask_msg_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()) + return Err(io::ErrorKind::InvalidInput.into()); } msg[0] = msg[0] .checked_add(self.shared_cap.relative_message_id_offset()) @@ -636,7 +635,7 @@ impl ProtocolStream { fn unmask_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()) + return Err(io::ErrorKind::InvalidInput.into()); } msg[0] = msg[0] .checked_sub(self.shared_cap.relative_message_id_offset()) diff --git a/crates/net/eth-wire/src/p2pstream.rs b/crates/net/eth-wire/src/p2pstream.rs index e794795b1c..cde7d30912 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -107,7 +107,7 @@ where return Err(P2PStreamError::MessageTooBig { message_size: first_message_bytes.len(), max_size: MAX_PAYLOAD_SIZE, - }) + }); } // The first message sent MUST be a hello OR disconnect message @@ -149,7 +149,7 @@ where return Err(P2PStreamError::MismatchedProtocolVersion(GotExpected { got: their_hello.protocol_version, expected: hello.protocol_version, - })) + })); } // determine shared capabilities (currently returns only one capability) @@ -394,7 +394,7 @@ where if this.disconnecting { // if disconnecting, stop reading messages - return Poll::Ready(None) + return Poll::Ready(None); } // we should loop here to ensure we don't return Poll::Pending if we have a message to @@ -408,7 +408,7 @@ where if bytes.is_empty() { // empty messages are not allowed - return Poll::Ready(Some(Err(P2PStreamError::EmptyProtocolMessage))) + return Poll::Ready(Some(Err(P2PStreamError::EmptyProtocolMessage))); } // first decode disconnect reasons, because they can be encoded in a variety of forms @@ -429,7 +429,7 @@ where // message is snappy compressed. Failure handling in that step is the primary point // where an error is returned if the disconnect reason is malformed. if let Ok(reason) = DisconnectReason::decode(&mut &bytes[1..]) { - return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))) + return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))); } } @@ -440,7 +440,7 @@ where return Poll::Ready(Some(Err(P2PStreamError::MessageTooBig { message_size: decompressed_len, max_size: MAX_PAYLOAD_SIZE, - }))) + }))); } // create a buffer to hold the decompressed message, adding a byte to the length for @@ -471,7 +471,7 @@ where // an error return Poll::Ready(Some(Err(P2PStreamError::HandshakeError( P2PHandshakeError::HelloNotInHandshake, - )))) + )))); } _ if id == P2PMessageID::Pong as u8 => { // if we were waiting for a pong, this will reset the pinger state @@ -488,11 +488,11 @@ where %err, msg=%hex::encode(&decompress_buf[1..]), "Failed to decode disconnect message from peer" ); })?; - return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))) + return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))); } _ if id > MAX_P2P_MESSAGE_ID && id <= MAX_RESERVED_MESSAGE_ID => { // we have received an unknown reserved message - return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId(id)))) + return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId(id)))); } _ => { // we have received a message that is outside the `p2p` reserved message space, @@ -520,7 +520,7 @@ where // decompress_buf[0] = bytes[0] - MAX_RESERVED_MESSAGE_ID - 1; - return Poll::Ready(Some(Ok(decompress_buf))) + return Poll::Ready(Some(Ok(decompress_buf))); } } } @@ -549,7 +549,7 @@ where this.start_disconnect(DisconnectReason::PingTimeout)?; // End the stream after ping related error - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } @@ -559,7 +559,7 @@ where Poll::Ready(Ok(())) => { let flushed = this.poll_flush(cx); if flushed.is_ready() { - return flushed + return flushed; } } } @@ -577,17 +577,17 @@ where return Err(P2PStreamError::MessageTooBig { message_size: item.len(), max_size: MAX_PAYLOAD_SIZE, - }) + }); } if item.is_empty() { // empty messages are not allowed - return Err(P2PStreamError::EmptyProtocolMessage) + return Err(P2PStreamError::EmptyProtocolMessage); } // ensure we have free capacity if !self.has_outgoing_capacity() { - return Err(P2PStreamError::SendBufferFull) + return Err(P2PStreamError::SendBufferFull); } let this = self.project(); @@ -624,10 +624,10 @@ where Poll::Ready(Err(err)) => break Poll::Ready(Err(err.into())), Poll::Ready(Ok(())) => { let Some(message) = this.outgoing_messages.pop_front() else { - break Poll::Ready(Ok(())) + break Poll::Ready(Ok(())); }; if let Err(err) = this.inner.as_mut().start_send(message) { - break Poll::Ready(Err(err.into())) + break Poll::Ready(Err(err.into())); } } } @@ -725,10 +725,10 @@ impl Decodable for P2PMessage { /// Removes the snappy prefix from the Ping/Pong buffer fn advance_snappy_ping_pong_payload(buf: &mut &[u8]) -> alloy_rlp::Result<()> { if buf.len() < 3 { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } if buf[..3] != [0x01, 0x00, EMPTY_LIST_CODE] { - return Err(RlpError::Custom("expected snappy payload")) + return Err(RlpError::Custom("expected snappy payload")); } buf.advance(3); Ok(()) diff --git a/crates/net/eth-wire/src/pinger.rs b/crates/net/eth-wire/src/pinger.rs index d93404c5f9..90ac45831d 100644 --- a/crates/net/eth-wire/src/pinger.rs +++ b/crates/net/eth-wire/src/pinger.rs @@ -73,19 +73,19 @@ impl Pinger { if self.ping_interval.poll_tick(cx).is_ready() { self.timeout_timer.as_mut().reset(Instant::now() + self.timeout); self.state = PingState::WaitingForPong; - return Poll::Ready(Ok(PingerEvent::Ping)) + return Poll::Ready(Ok(PingerEvent::Ping)); } } PingState::WaitingForPong => { if self.timeout_timer.is_elapsed() { self.state = PingState::TimedOut; - return Poll::Ready(Ok(PingerEvent::Timeout)) + return Poll::Ready(Ok(PingerEvent::Timeout)); } } PingState::TimedOut => { // we treat continuous calls while in timeout as pending, since the connection is // not yet terminated - return Poll::Pending + return Poll::Pending; } }; Poll::Pending diff --git a/crates/net/eth-wire/src/test_utils.rs b/crates/net/eth-wire/src/test_utils.rs index 0cf96484f1..e539900372 100644 --- a/crates/net/eth-wire/src/test_utils.rs +++ b/crates/net/eth-wire/src/test_utils.rs @@ -142,7 +142,7 @@ pub mod proto { /// Decodes a `TestProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None + return None; } let id = buf[0]; buf.advance(1); diff --git a/crates/net/nat/src/lib.rs b/crates/net/nat/src/lib.rs index c7466b4401..24db5c0003 100644 --- a/crates/net/nat/src/lib.rs +++ b/crates/net/nat/src/lib.rs @@ -109,7 +109,7 @@ impl FromStr for NatResolver { let Some(ip) = s.strip_prefix("extip:") else { return Err(ParseNatResolverError::UnknownVariant(format!( "Unknown Nat Resolver: {s}" - ))) + ))); }; Self::ExternalIp(ip.parse()?) } diff --git a/crates/net/network-types/src/peers/mod.rs b/crates/net/network-types/src/peers/mod.rs index f352987501..4afd0e83be 100644 --- a/crates/net/network-types/src/peers/mod.rs +++ b/crates/net/network-types/src/peers/mod.rs @@ -96,15 +96,15 @@ impl Peer { if self.state.is_connected() && self.is_banned() { self.state.disconnect(); - return ReputationChangeOutcome::DisconnectAndBan + return ReputationChangeOutcome::DisconnectAndBan; } if self.is_banned() && !is_banned_reputation(previous) { - return ReputationChangeOutcome::Ban + return ReputationChangeOutcome::Ban; } if !self.is_banned() && is_banned_reputation(previous) { - return ReputationChangeOutcome::Unban + return ReputationChangeOutcome::Unban; } ReputationChangeOutcome::None diff --git a/crates/net/network/src/discovery.rs b/crates/net/network/src/discovery.rs index 5809380aa8..70b364e49d 100644 --- a/crates/net/network/src/discovery.rs +++ b/crates/net/network/src/discovery.rs @@ -215,7 +215,7 @@ impl Discovery { let tcp_addr = record.tcp_addr(); if tcp_addr.port() == 0 { // useless peer for p2p - return + return; } let udp_addr = record.udp_addr(); let addr = PeerAddr::new(tcp_addr, Some(udp_addr)); @@ -253,7 +253,7 @@ impl Discovery { // Drain all buffered events first if let Some(event) = self.queued_events.pop_front() { self.notify_listeners(&event); - return Poll::Ready(event) + return Poll::Ready(event); } // drain the discv4 update stream @@ -291,7 +291,7 @@ impl Discovery { } if self.queued_events.is_empty() { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/network/src/error.rs b/crates/net/network/src/error.rs index 96ba2ff85e..8698ac5e93 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -72,7 +72,7 @@ impl NetworkError { ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err }, _ => { if let ServiceKind::Discovery(address) = kind { - return Self::Discovery(address, err) + return Self::Discovery(address, err); } Self::Io(err) } @@ -110,8 +110,8 @@ impl SessionError for EthStreamError { fn merits_discovery_ban(&self) -> bool { match self { Self::P2PStreamError(P2PStreamError::HandshakeError( - P2PHandshakeError::HelloNotInHandshake | - P2PHandshakeError::NonHelloMessageInHandshake, + P2PHandshakeError::HelloNotInHandshake + | P2PHandshakeError::NonHelloMessageInHandshake, )) => true, Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), _ => false, @@ -124,24 +124,24 @@ impl SessionError for EthStreamError { matches!( err, P2PStreamError::HandshakeError( - P2PHandshakeError::NoSharedCapabilities | - P2PHandshakeError::HelloNotInHandshake | - P2PHandshakeError::NonHelloMessageInHandshake | - P2PHandshakeError::Disconnected( - DisconnectReason::UselessPeer | - DisconnectReason::IncompatibleP2PProtocolVersion | - DisconnectReason::ProtocolBreach + P2PHandshakeError::NoSharedCapabilities + | P2PHandshakeError::HelloNotInHandshake + | P2PHandshakeError::NonHelloMessageInHandshake + | P2PHandshakeError::Disconnected( + DisconnectReason::UselessPeer + | DisconnectReason::IncompatibleP2PProtocolVersion + | DisconnectReason::ProtocolBreach ) - ) | P2PStreamError::UnknownReservedMessageId(_) | - P2PStreamError::EmptyProtocolMessage | - P2PStreamError::ParseSharedCapability(_) | - P2PStreamError::CapabilityNotShared | - P2PStreamError::Disconnected( - DisconnectReason::UselessPeer | - DisconnectReason::IncompatibleP2PProtocolVersion | - DisconnectReason::ProtocolBreach - ) | - P2PStreamError::MismatchedProtocolVersion { .. } + ) | P2PStreamError::UnknownReservedMessageId(_) + | P2PStreamError::EmptyProtocolMessage + | P2PStreamError::ParseSharedCapability(_) + | P2PStreamError::CapabilityNotShared + | P2PStreamError::Disconnected( + DisconnectReason::UselessPeer + | DisconnectReason::IncompatibleP2PProtocolVersion + | DisconnectReason::ProtocolBreach + ) + | P2PStreamError::MismatchedProtocolVersion { .. } ) } Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), @@ -151,50 +151,50 @@ impl SessionError for EthStreamError { fn should_backoff(&self) -> Option { if let Some(err) = self.as_io() { - return err.should_backoff() + return err.should_backoff(); } if let Some(err) = self.as_disconnected() { return match err { - DisconnectReason::TooManyPeers | - DisconnectReason::AlreadyConnected | - DisconnectReason::PingTimeout | - DisconnectReason::DisconnectRequested | - DisconnectReason::TcpSubsystemError => Some(BackoffKind::Low), + DisconnectReason::TooManyPeers + | DisconnectReason::AlreadyConnected + | DisconnectReason::PingTimeout + | DisconnectReason::DisconnectRequested + | DisconnectReason::TcpSubsystemError => Some(BackoffKind::Low), - DisconnectReason::ProtocolBreach | - DisconnectReason::UselessPeer | - DisconnectReason::IncompatibleP2PProtocolVersion | - DisconnectReason::NullNodeIdentity | - DisconnectReason::ClientQuitting | - DisconnectReason::UnexpectedHandshakeIdentity | - DisconnectReason::ConnectedToSelf | - DisconnectReason::SubprotocolSpecific => { + DisconnectReason::ProtocolBreach + | DisconnectReason::UselessPeer + | DisconnectReason::IncompatibleP2PProtocolVersion + | DisconnectReason::NullNodeIdentity + | DisconnectReason::ClientQuitting + | DisconnectReason::UnexpectedHandshakeIdentity + | DisconnectReason::ConnectedToSelf + | DisconnectReason::SubprotocolSpecific => { // These are considered fatal, and are handled by the // [`SessionError::is_fatal_protocol_error`] Some(BackoffKind::High) } - } + }; } // This only checks for a subset of error variants, the counterpart of // [`SessionError::is_fatal_protocol_error`] match self { // timeouts - Self::EthHandshakeError(EthHandshakeError::NoResponse) | - Self::P2PStreamError( - P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse) | - P2PStreamError::PingTimeout, + Self::EthHandshakeError(EthHandshakeError::NoResponse) + | Self::P2PStreamError( + P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse) + | P2PStreamError::PingTimeout, ) => Some(BackoffKind::Low), // malformed messages Self::P2PStreamError( - P2PStreamError::Rlp(_) | - P2PStreamError::UnknownReservedMessageId(_) | - P2PStreamError::UnknownDisconnectReason(_) | - P2PStreamError::MessageTooBig { .. } | - P2PStreamError::EmptyProtocolMessage | - P2PStreamError::PingerError(_) | - P2PStreamError::Snap(_), + P2PStreamError::Rlp(_) + | P2PStreamError::UnknownReservedMessageId(_) + | P2PStreamError::UnknownDisconnectReason(_) + | P2PStreamError::MessageTooBig { .. } + | P2PStreamError::EmptyProtocolMessage + | P2PStreamError::PingerError(_) + | P2PStreamError::Snap(_), ) => Some(BackoffKind::Medium), _ => None, } @@ -207,14 +207,14 @@ impl SessionError for PendingSessionHandshakeError { Self::Eth(eth) => eth.merits_discovery_ban(), Self::Ecies(err) => matches!( err.inner(), - ECIESErrorImpl::TagCheckDecryptFailed | - ECIESErrorImpl::TagCheckHeaderFailed | - ECIESErrorImpl::TagCheckBodyFailed | - ECIESErrorImpl::InvalidAuthData | - ECIESErrorImpl::InvalidAckData | - ECIESErrorImpl::InvalidHeader | - ECIESErrorImpl::Secp256k1(_) | - ECIESErrorImpl::InvalidHandshake { .. } + ECIESErrorImpl::TagCheckDecryptFailed + | ECIESErrorImpl::TagCheckHeaderFailed + | ECIESErrorImpl::TagCheckBodyFailed + | ECIESErrorImpl::InvalidAuthData + | ECIESErrorImpl::InvalidAckData + | ECIESErrorImpl::InvalidHeader + | ECIESErrorImpl::Secp256k1(_) + | ECIESErrorImpl::InvalidHandshake { .. } ), Self::Timeout | Self::UnsupportedExtraCapability => false, } @@ -225,14 +225,14 @@ impl SessionError for PendingSessionHandshakeError { Self::Eth(eth) => eth.is_fatal_protocol_error(), Self::Ecies(err) => matches!( err.inner(), - ECIESErrorImpl::TagCheckDecryptFailed | - ECIESErrorImpl::TagCheckHeaderFailed | - ECIESErrorImpl::TagCheckBodyFailed | - ECIESErrorImpl::InvalidAuthData | - ECIESErrorImpl::InvalidAckData | - ECIESErrorImpl::InvalidHeader | - ECIESErrorImpl::Secp256k1(_) | - ECIESErrorImpl::InvalidHandshake { .. } + ECIESErrorImpl::TagCheckDecryptFailed + | ECIESErrorImpl::TagCheckHeaderFailed + | ECIESErrorImpl::TagCheckBodyFailed + | ECIESErrorImpl::InvalidAuthData + | ECIESErrorImpl::InvalidAckData + | ECIESErrorImpl::InvalidHeader + | ECIESErrorImpl::Secp256k1(_) + | ECIESErrorImpl::InvalidHandshake { .. } ), Self::Timeout => false, Self::UnsupportedExtraCapability => true, diff --git a/crates/net/network/src/eth_requests.rs b/crates/net/network/src/eth_requests.rs index 39e485318b..64aa5b2da7 100644 --- a/crates/net/network/src/eth_requests.rs +++ b/crates/net/network/src/eth_requests.rs @@ -93,7 +93,7 @@ where BlockHashOrNumber::Hash(start) => start.into(), BlockHashOrNumber::Number(num) => { let Some(hash) = self.client.block_hash(num).unwrap_or_default() else { - return headers + return headers; }; hash.into() } @@ -109,7 +109,7 @@ where if let Some(next) = (header.number() + 1).checked_add(skip) { block = next.into() } else { - break + break; } } HeadersDirection::Falling => { @@ -121,7 +121,7 @@ where { block = next.into() } else { - break + break; } } else { block = header.parent_hash().into() @@ -133,10 +133,10 @@ where headers.push(header); if headers.len() >= MAX_HEADERS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } @@ -172,10 +172,10 @@ where bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } @@ -231,10 +231,10 @@ where receipts.push(transformed_receipts); if receipts.len() >= MAX_RECEIPTS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index 794c184e69..82a74f9fe6 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -127,7 +127,7 @@ impl StateFetcher { if number > peer.best_number { peer.best_hash = hash; peer.best_number = number; - return true + return true; } } false @@ -152,12 +152,12 @@ impl StateFetcher { // replace best peer if our current best peer sent us a bad response last time if best_peer.1.last_response_likely_bad && !maybe_better.1.last_response_likely_bad { best_peer = maybe_better; - continue + continue; } // replace best peer if this peer has better rtt - if maybe_better.1.timeout() < best_peer.1.timeout() && - !maybe_better.1.last_response_likely_bad + if maybe_better.1.timeout() < best_peer.1.timeout() + && !maybe_better.1.last_response_likely_bad { best_peer = maybe_better; } @@ -170,7 +170,7 @@ impl StateFetcher { fn poll_action(&mut self) -> PollAction { // we only check and not pop here since we don't know yet whether a peer is available. if self.queued_requests.is_empty() { - return PollAction::NoRequests + return PollAction::NoRequests; } let Some(peer_id) = self.next_best_peer() else { return PollAction::NoPeersAvailable }; @@ -217,7 +217,7 @@ impl StateFetcher { } if self.queued_requests.is_empty() || no_peers_available { - return Poll::Pending + return Poll::Pending; } } } @@ -292,7 +292,7 @@ impl StateFetcher { // If the peer is still ready to accept new requests, we try to send a followup // request immediately. if peer.state.on_request_finished() && !is_error && !is_likely_bad_response { - return self.followup_request(peer_id) + return self.followup_request(peer_id); } } @@ -318,7 +318,7 @@ impl StateFetcher { peer.last_response_likely_bad = is_likely_bad_response; if peer.state.on_request_finished() && !is_likely_bad_response { - return self.followup_request(peer_id) + return self.followup_request(peer_id); } } None @@ -399,7 +399,7 @@ impl PeerState { const fn on_request_finished(&mut self) -> bool { if !matches!(self, Self::Closing) { *self = Self::Idle; - return true + return true; } false } diff --git a/crates/net/network/src/manager.rs b/crates/net/network/src/manager.rs index aee8218382..1ff8b06886 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -650,7 +650,7 @@ impl NetworkManager { if self.handle.mode().is_stake() { // See [EIP-3675](https://eips.ethereum.org/EIPS/eip-3675#devp2p) warn!(target: "net", "Peer performed block propagation, but it is not supported in proof of stake (EIP-3675)"); - return + return; } let msg = NewBlockMessage { hash, block: Arc::new(block) }; self.swarm.state_mut().announce_new_block(msg); @@ -1142,7 +1142,7 @@ impl Future for NetworkManager { if maybe_more_handle_messages || maybe_more_swarm_events { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } this.update_poll_metrics(start, poll_durations); diff --git a/crates/net/network/src/network.rs b/crates/net/network/src/network.rs index ffe8bf1531..f60a025684 100644 --- a/crates/net/network/src/network.rs +++ b/crates/net/network/src/network.rs @@ -413,7 +413,7 @@ impl SyncStateProvider for NetworkHandle { // used to guard the txpool fn is_initially_syncing(&self) -> bool { if self.inner.initial_sync_done.load(Ordering::Relaxed) { - return false + return false; } self.inner.is_syncing.load(Ordering::Relaxed) } diff --git a/crates/net/network/src/peers.rs b/crates/net/network/src/peers.rs index c0694023ce..715648cfd4 100644 --- a/crates/net/network/src/peers.rs +++ b/crates/net/network/src/peers.rs @@ -244,7 +244,7 @@ impl PeersManager { addr: IpAddr, ) -> Result<(), InboundConnectionError> { if self.ban_list.is_banned_ip(&addr) { - return Err(InboundConnectionError::IpBanned) + return Err(InboundConnectionError::IpBanned); } // check if we even have slots for a new incoming connection @@ -252,7 +252,7 @@ impl PeersManager { if self.trusted_peer_ids.is_empty() { // if we don't have any incoming slots and no trusted peers, we don't accept any new // connections - return Err(InboundConnectionError::ExceedsCapacity) + return Err(InboundConnectionError::ExceedsCapacity); } // there's an edge case here where no incoming connections besides from trusted peers @@ -265,17 +265,17 @@ impl PeersManager { self.trusted_peer_ids.len().max(self.connection_info.config.max_inbound); if self.connection_info.num_pending_in < max_inbound { self.connection_info.inc_pending_in(); - return Ok(()) + return Ok(()); } } // all trusted peers are either connected or connecting - return Err(InboundConnectionError::ExceedsCapacity) + return Err(InboundConnectionError::ExceedsCapacity); } // also cap the incoming connections we can process at once if !self.connection_info.has_in_pending_capacity() { - return Err(InboundConnectionError::ExceedsCapacity) + return Err(InboundConnectionError::ExceedsCapacity); } // apply the rate limit @@ -327,14 +327,14 @@ impl PeersManager { // on_incoming_pending_session. We also check if the peer is in the backoff list here. if self.ban_list.is_banned_peer(&peer_id) { self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id }); - return + return; } // check if the peer is trustable or not let mut is_trusted = self.trusted_peer_ids.contains(&peer_id); if self.trusted_nodes_only && !is_trusted { self.queued_actions.push_back(PeerAction::DisconnectUntrustedIncoming { peer_id }); - return + return; } // start a new tick, so the peer is not immediately rewarded for the time since last tick @@ -345,7 +345,7 @@ impl PeersManager { let peer = entry.get_mut(); if peer.is_banned() { self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id }); - return + return; } // it might be the case that we're also trying to connect to this peer at the same // time, so we need to adjust the state here @@ -466,12 +466,12 @@ impl PeersManager { // exempt trusted and static peers from reputation slashing for if matches!( rep, - ReputationChangeKind::Dropped | - ReputationChangeKind::BadAnnouncement | - ReputationChangeKind::Timeout | - ReputationChangeKind::AlreadySeenTransaction + ReputationChangeKind::Dropped + | ReputationChangeKind::BadAnnouncement + | ReputationChangeKind::Timeout + | ReputationChangeKind::AlreadySeenTransaction ) { - return + return; } // also be less strict with the reputation slashing for trusted peers @@ -483,7 +483,7 @@ impl PeersManager { peer.apply_reputation(reputation_change, rep) } } else { - return + return; }; match outcome { @@ -537,7 +537,7 @@ impl PeersManager { // session to that peer entry.get_mut().severe_backoff_counter = 0; entry.get_mut().state = PeerConnectionState::Idle; - return + return; } } Entry::Vacant(_) => return, @@ -582,7 +582,7 @@ impl PeersManager { if let Some(peer) = self.peers.get(peer_id) { if peer.state.is_incoming() { // we already have an active connection to the peer, so we can ignore this error - return + return; } if peer.is_trusted() && is_connection_failed_reputation(peer.reputation) { @@ -663,9 +663,9 @@ impl PeersManager { self.connection_info.decr_state(peer.state); peer.state = PeerConnectionState::Idle; - if peer.severe_backoff_counter > self.max_backoff_count && - !peer.is_trusted() && - !peer.is_static() + if peer.severe_backoff_counter > self.max_backoff_count + && !peer.is_trusted() + && !peer.is_static() { // mark peer for removal if it has been backoff too many times and is _not_ // trusted or static @@ -746,7 +746,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.tcp().ip()) { - return + return; } match self.peers.entry(peer_id) { @@ -781,7 +781,7 @@ impl PeersManager { pub(crate) fn remove_peer(&mut self, peer_id: PeerId) { let Entry::Occupied(entry) = self.peers.entry(peer_id) else { return }; if entry.get().is_trusted() { - return + return; } let mut peer = entry.remove(); @@ -827,7 +827,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.tcp().ip()) { - return + return; } match self.peers.entry(peer_id) { @@ -866,7 +866,7 @@ impl PeersManager { pub(crate) fn remove_peer_from_trusted_set(&mut self, peer_id: PeerId) { let Entry::Occupied(mut entry) = self.peers.entry(peer_id) else { return }; if !entry.get().is_trusted() { - return + return; } let peer = entry.get_mut(); @@ -886,23 +886,23 @@ impl PeersManager { /// Returns `None` if no peer is available. fn best_unconnected(&mut self) -> Option<(PeerId, &mut Peer)> { let mut unconnected = self.peers.iter_mut().filter(|(_, peer)| { - !peer.is_backed_off() && - !peer.is_banned() && - peer.state.is_unconnected() && - (!self.trusted_nodes_only || peer.is_trusted()) + !peer.is_backed_off() + && !peer.is_banned() + && peer.state.is_unconnected() + && (!self.trusted_nodes_only || peer.is_trusted()) }); // keep track of the best peer, if there's one let mut best_peer = unconnected.next()?; if best_peer.1.is_trusted() || best_peer.1.is_static() { - return Some((*best_peer.0, best_peer.1)) + return Some((*best_peer.0, best_peer.1)); } for maybe_better in unconnected { // if the peer is trusted or static, return it immediately if maybe_better.1.is_trusted() || maybe_better.1.is_static() { - return Some((*maybe_better.0, maybe_better.1)) + return Some((*maybe_better.0, maybe_better.1)); } // otherwise we keep track of the best peer using the reputation @@ -923,7 +923,7 @@ impl PeersManager { if !self.net_connection_state.is_active() { // nothing to fill - return + return; } // as long as there are slots available fill them with the best peers @@ -984,7 +984,7 @@ impl PeersManager { loop { // drain buffered actions if let Some(action) = self.queued_actions.pop_front() { - return Poll::Ready(action) + return Poll::Ready(action); } while let Poll::Ready(Some(cmd)) = self.handle_rx.poll_next_unpin(cx) { @@ -1023,7 +1023,7 @@ impl PeersManager { if let Some(peer) = self.peers.get_mut(peer_id) { peer.backed_off = false; } - return false + return false; } true }) @@ -1038,7 +1038,7 @@ impl PeersManager { } if self.queued_actions.is_empty() { - return Poll::Pending + return Poll::Pending; } } } @@ -1075,8 +1075,8 @@ impl ConnectionInfo { /// Returns `true` if there's still capacity to perform an outgoing connection. const fn has_out_capacity(&self) -> bool { - self.num_pending_out < self.config.max_concurrent_outbound_dials && - self.num_outbound < self.config.max_outbound + self.num_pending_out < self.config.max_concurrent_outbound_dials + && self.num_outbound < self.config.max_outbound } /// Returns `true` if there's still capacity to accept a new incoming connection. @@ -2038,7 +2038,7 @@ mod tests { let p = peers.peers.get(&peer).unwrap(); if p.is_banned() { - break + break; } } diff --git a/crates/net/network/src/session/active.rs b/crates/net/network/src/session/active.rs index 827c4bfb19..54102e8d93 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -238,7 +238,7 @@ impl ActiveSession { sizes_len: msg.sizes.len(), }, message: EthMessage::NewPooledTransactionHashes68(msg), - } + }; } self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into() } @@ -353,8 +353,8 @@ impl ActiveSession { /// Returns the deadline timestamp at which the request times out fn request_deadline(&self) -> Instant { - Instant::now() + - Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed)) + Instant::now() + + Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed)) } /// Handle a Response to the peer @@ -499,7 +499,7 @@ impl ActiveSession { debug!(target: "net::session", ?id, remote_peer_id=?self.remote_peer_id, "timed out outgoing request"); req.timeout(); } else if now - req.timestamp > self.protocol_breach_request_timeout { - return true + return true; } } } @@ -523,7 +523,7 @@ impl ActiveSession { match tx.poll_reserve(cx) { Poll::Pending => { self.terminate_message = Some((tx, msg)); - return Some(Poll::Pending) + return Some(Poll::Pending); } Poll::Ready(Ok(())) => { let _ = tx.send_item(msg); @@ -545,11 +545,11 @@ impl Future for ActiveSession { // if the session is terminate we have to send the termination message before we can close if let Some(terminate) = this.poll_terminate_message(cx) { - return terminate + return terminate; } if this.is_disconnecting() { - return this.poll_disconnect(cx) + return this.poll_disconnect(cx); } // The receive loop can be CPU intensive since it involves message decoding which could take @@ -570,7 +570,7 @@ impl Future for ActiveSession { Poll::Ready(None) => { // this is only possible when the manager was dropped, in which case we also // terminate this session - return Poll::Ready(()) + return Poll::Ready(()); } Poll::Ready(Some(cmd)) => { progress = true; @@ -585,7 +585,7 @@ impl Future for ActiveSession { let reason = reason.unwrap_or(DisconnectReason::DisconnectRequested); - return this.try_disconnect(reason, cx) + return this.try_disconnect(reason, cx); } SessionCommand::Message(msg) => { this.on_internal_peer_message(msg); @@ -629,11 +629,11 @@ impl Future for ActiveSession { if let Err(err) = res { debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message"); // notify the manager - return this.close_on_error(err, cx) + return this.close_on_error(err, cx); } } else { // no more messages to send over the wire - break + break; } } @@ -644,7 +644,7 @@ impl Future for ActiveSession { if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - break 'main + break 'main; } // try to resend the pending message that we could not send because the channel was @@ -658,7 +658,7 @@ impl Future for ActiveSession { Poll::Ready(Err(_)) => return Poll::Ready(()), Poll::Pending => { this.pending_message_to_session = Some(msg); - break 'receive + break 'receive; } }; } @@ -670,12 +670,12 @@ impl Future for ActiveSession { // // Note: we don't need to register the waker here because we polled the requests // above - break 'receive + break 'receive; } // we also need to check if we have multiple responses queued up - if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES && - this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES + if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES + && this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES { // if we've queued up more responses than allowed, we don't poll for new // messages and break the receive loop early @@ -683,17 +683,17 @@ impl Future for ActiveSession { // Note: we don't need to register the waker here because we still have // queued messages and the sink impl registered the waker because we've // already advanced it to `Pending` earlier - break 'receive + break 'receive; } match this.conn.poll_next_unpin(cx) { Poll::Pending => break, Poll::Ready(None) => { if this.is_disconnecting() { - break + break; } debug!(target: "net::session", remote_peer_id=?this.remote_peer_id, "eth stream completed"); - return this.emit_disconnect(cx) + return this.emit_disconnect(cx); } Poll::Ready(Some(res)) => { match res { @@ -707,7 +707,7 @@ impl Future for ActiveSession { } OnIncomingMessageOutcome::BadMessage { error, message } => { debug!(target: "net::session", %error, msg=?message, remote_peer_id=?this.remote_peer_id, "received invalid protocol message"); - return this.close_on_error(error, cx) + return this.close_on_error(error, cx); } OnIncomingMessageOutcome::NoCapacity(msg) => { // failed to send due to lack of capacity @@ -717,7 +717,7 @@ impl Future for ActiveSession { } Err(err) => { debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to receive message"); - return this.close_on_error(err, cx) + return this.close_on_error(err, cx); } } } @@ -725,7 +725,7 @@ impl Future for ActiveSession { } if !progress { - break 'main + break 'main; } } @@ -1262,7 +1262,7 @@ mod tests { .try_send(ActiveSessionMessage::ProtocolBreach { peer_id: PeerId::random() }) .is_err() { - break + break; } num_fill_messages += 1; } diff --git a/crates/net/network/src/session/counter.rs b/crates/net/network/src/session/counter.rs index 215c7279d1..f8fd73c678 100644 --- a/crates/net/network/src/session/counter.rs +++ b/crates/net/network/src/session/counter.rs @@ -82,7 +82,7 @@ impl SessionCounter { const fn ensure(current: u32, limit: Option) -> Result<(), ExceedsSessionLimit> { if let Some(limit) = limit { if current >= limit { - return Err(ExceedsSessionLimit(limit)) + return Err(ExceedsSessionLimit(limit)); } } Ok(()) diff --git a/crates/net/network/src/session/mod.rs b/crates/net/network/src/session/mod.rs index 5aad90cbb6..2d6df058a5 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -409,7 +409,7 @@ impl SessionManager { ) { if !self.disconnections_counter.has_capacity() { // drop the connection if we don't have capacity for gracefully disconnecting - return + return; } let guard = self.disconnections_counter.clone(); @@ -517,7 +517,7 @@ impl SessionManager { peer_id, remote_addr, direction, - }) + }); } let (commands_to_session, commands_rx) = mpsc::channel(self.session_command_buffer); @@ -930,7 +930,7 @@ async fn start_pending_outbound_session( error, }) .await; - return + return; } }; authenticate( @@ -978,7 +978,7 @@ async fn authenticate( direction, }) .await; - return + return; } }; diff --git a/crates/net/network/src/state.rs b/crates/net/network/src/state.rs index 89ad4874cc..8146fb3fa8 100644 --- a/crates/net/network/src/state.rs +++ b/crates/net/network/src/state.rs @@ -211,7 +211,7 @@ impl NetworkState { for (peer_id, peer) in peers { if peer.blocks.contains(&msg.hash) { // skip peers which already reported the block - continue + continue; } // Queue a `NewBlock` message for the peer @@ -231,7 +231,7 @@ impl NetworkState { } if count >= num_propagate { - break + break; } } } @@ -244,7 +244,7 @@ impl NetworkState { for (peer_id, peer) in &mut self.active_peers { if peer.blocks.contains(&msg.hash) { // skip peers which already reported the block - continue + continue; } if self.state_fetcher.update_peer_block(peer_id, msg.hash, number) { @@ -351,8 +351,8 @@ impl NetworkState { self.state_fetcher.on_pending_disconnect(&peer_id); self.queued_messages.push_back(StateAction::Disconnect { peer_id, reason }); } - PeerAction::DisconnectBannedIncoming { peer_id } | - PeerAction::DisconnectUntrustedIncoming { peer_id } => { + PeerAction::DisconnectBannedIncoming { peer_id } + | PeerAction::DisconnectUntrustedIncoming { peer_id } => { self.state_fetcher.on_pending_disconnect(&peer_id); self.queued_messages.push_back(StateAction::Disconnect { peer_id, reason: None }); } @@ -433,7 +433,7 @@ impl NetworkState { loop { // drain buffered messages if let Some(message) = self.queued_messages.pop_front() { - return Poll::Ready(message) + return Poll::Ready(message); } while let Poll::Ready(discovery) = self.discovery.poll(cx) { @@ -503,7 +503,7 @@ impl NetworkState { // We need to poll again tn case we have received any responses because they may have // triggered follow-up requests. if self.queued_messages.is_empty() { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/network/src/swarm.rs b/crates/net/network/src/swarm.rs index fbb7b0bf94..8f3526cb4c 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -187,7 +187,7 @@ impl Swarm { ListenerEvent::Incoming { stream, remote_addr } => { // Reject incoming connection if node is shutting down. if self.is_shutting_down() { - return None + return None; } // ensure we can handle an incoming connection from this address if let Err(err) = @@ -205,13 +205,13 @@ impl Swarm { ); } } - return None + return None; } match self.sessions.on_incoming(stream, remote_addr) { Ok(session_id) => { trace!(target: "net", ?remote_addr, "Incoming connection"); - return Some(SwarmEvent::IncomingTcpConnection { session_id, remote_addr }) + return Some(SwarmEvent::IncomingTcpConnection { session_id, remote_addr }); } Err(err) => { trace!(target: "net", %err, "Incoming connection rejected, capacity already reached."); @@ -230,7 +230,7 @@ impl Swarm { match event { StateAction::Connect { remote_addr, peer_id } => { self.dial_outbound(remote_addr, peer_id); - return Some(SwarmEvent::OutgoingTcpConnection { remote_addr, peer_id }) + return Some(SwarmEvent::OutgoingTcpConnection { remote_addr, peer_id }); } StateAction::Disconnect { peer_id, reason } => { self.sessions.disconnect(peer_id, reason); @@ -248,7 +248,7 @@ impl Swarm { StateAction::DiscoveredNode { peer_id, addr, fork_id } => { // Don't try to connect to peer if node is shutting down if self.is_shutting_down() { - return None + return None; } // Insert peer only if no fork id or a valid fork id if fork_id.map_or_else(|| true, |f| self.sessions.is_valid_fork_id(f)) { @@ -302,7 +302,7 @@ impl Stream for Swarm { loop { while let Poll::Ready(action) = this.state.poll(cx) { if let Some(event) = this.on_state_action(action) { - return Poll::Ready(Some(event)) + return Poll::Ready(Some(event)); } } @@ -311,9 +311,9 @@ impl Stream for Swarm { Poll::Pending => {} Poll::Ready(event) => { if let Some(event) = this.on_session_event(event) { - return Poll::Ready(Some(event)) + return Poll::Ready(Some(event)); } - continue + continue; } } @@ -322,13 +322,13 @@ impl Stream for Swarm { Poll::Pending => {} Poll::Ready(event) => { if let Some(event) = this.on_connection(event) { - return Poll::Ready(Some(event)) + return Poll::Ready(Some(event)); } - continue + continue; } } - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/network/src/test_utils/init.rs b/crates/net/network/src/test_utils/init.rs index 51537f37d8..7adad9c5fa 100644 --- a/crates/net/network/src/test_utils/init.rs +++ b/crates/net/network/src/test_utils/init.rs @@ -42,7 +42,7 @@ pub fn unused_tcp_and_udp_port() -> u16 { loop { let port = unused_port(); if std::net::UdpSocket::bind(format!("127.0.0.1:{port}")).is_ok() { - return port + return port; } } } diff --git a/crates/net/network/src/test_utils/testnet.rs b/crates/net/network/src/test_utils/testnet.rs index d064ed7eda..b1bece61ac 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -367,7 +367,7 @@ impl TestnetHandle { /// Returns once all sessions are established. pub async fn connect_peers(&self) { if self.peers.len() < 2 { - return + return; } // add an event stream for _each_ peer @@ -750,7 +750,7 @@ impl NetworkEventStream { pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> { while let Some(ev) = self.inner.next().await { if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev { - return Some((peer_id, reason)) + return Some((peer_id, reason)); } } None @@ -760,8 +760,8 @@ impl NetworkEventStream { pub async fn next_session_established(&mut self) -> Option { while let Some(ev) = self.inner.next().await { match ev { - NetworkEvent::ActivePeerSession { info, .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { return Some(info.peer_id) } _ => {} diff --git a/crates/net/network/src/transactions/constants.rs b/crates/net/network/src/transactions/constants.rs index 905c5931e9..7f43a2c2bf 100644 --- a/crates/net/network/src/transactions/constants.rs +++ b/crates/net/network/src/transactions/constants.rs @@ -137,8 +137,8 @@ pub mod tx_fetcher { /// [`DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES`], which is 25600 hashes and /// 65 requests, so it is 25665 hashes. pub const DEFAULT_MAX_CAPACITY_CACHE_INFLIGHT_AND_PENDING_FETCH: u32 = - DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH + - DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES as u32; + DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH + + DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES as u32; /// Default maximum number of hashes pending fetch to tolerate at any time. /// @@ -189,8 +189,8 @@ pub mod tx_fetcher { /// which defaults to 128 KiB, so 64 KiB. pub const DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES: usize = - DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ / - 2; + DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ + / 2; /// Default max inflight request when fetching pending hashes. /// @@ -239,8 +239,8 @@ pub mod tx_fetcher { /// divided by [`SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE`], which /// is spec'd at 4096 hashes, so 521 bytes. pub const AVERAGE_BYTE_SIZE_TX_ENCODED: usize = - SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE / - SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE; + SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE + / SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE; /// Median observed size in bytes of a small encoded legacy transaction. /// diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index 2656840128..1de3675ecb 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -162,7 +162,7 @@ impl TransactionFetcher { if let Some(inflight_count) = self.active_peers.get(peer_id) { *inflight_count = inflight_count.saturating_sub(1); if *inflight_count == 0 { - return true + return true; } } false @@ -178,7 +178,7 @@ impl TransactionFetcher { pub fn is_idle(&self, peer_id: &PeerId) -> bool { let Some(inflight_count) = self.active_peers.peek(peer_id) else { return true }; if *inflight_count < self.info.max_inflight_requests_per_peer { - return true + return true; } false } @@ -190,7 +190,7 @@ impl TransactionFetcher { for peer_id in fallback_peers.iter() { if self.is_idle(peer_id) { - return Some(peer_id) + return Some(peer_id); } } @@ -216,13 +216,13 @@ impl TransactionFetcher { if idle_peer.is_some() { hashes_to_request.insert(hash); - break idle_peer.copied() + break idle_peer.copied(); } if let Some(ref mut bud) = budget { *bud = bud.saturating_sub(1); if *bud == 0 { - return None + return None; } } }; @@ -245,7 +245,7 @@ impl TransactionFetcher { hashes_from_announcement: ValidAnnouncementData, ) -> RequestTxHashes { if hashes_from_announcement.msg_version().is_eth68() { - return self.pack_request_eth68(hashes_to_request, hashes_from_announcement) + return self.pack_request_eth68(hashes_to_request, hashes_from_announcement); } self.pack_request_eth66(hashes_to_request, hashes_from_announcement) } @@ -275,7 +275,7 @@ impl TransactionFetcher { // tx is really big, pack request with single tx if size >= self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request { - return hashes_from_announcement_iter.collect() + return hashes_from_announcement_iter.collect(); } acc_size_response = size; } @@ -293,8 +293,8 @@ impl TransactionFetcher { let next_acc_size = acc_size_response + size; - if next_acc_size <= - self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request + if next_acc_size + <= self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request { // only update accumulated size of tx response if tx will fit in without exceeding // soft limit @@ -305,11 +305,11 @@ impl TransactionFetcher { } let free_space = - self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request - - acc_size_response; + self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request + - acc_size_response; if free_space < MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED { - break + break; } } @@ -356,7 +356,7 @@ impl TransactionFetcher { hashes.retain(|hash| { if let Some(entry) = self.hashes_fetch_inflight_and_pending_fetch.get(hash) { entry.fallback_peers_mut().remove(peer_failed_to_serve); - return true + return true; } // tx has been seen over broadcast in the time it took for the request to resolve false @@ -383,13 +383,13 @@ impl TransactionFetcher { for hash in hashes { // hash could have been evicted from bounded lru map if self.hashes_fetch_inflight_and_pending_fetch.peek(&hash).is_none() { - continue + continue; } let Some(TxFetchMetadata { retries, fallback_peers, .. }) = self.hashes_fetch_inflight_and_pending_fetch.get(&hash) else { - return + return; }; if let Some(peer_id) = fallback_peer { @@ -405,7 +405,7 @@ impl TransactionFetcher { self.hashes_fetch_inflight_and_pending_fetch.remove(&hash); self.hashes_pending_fetch.remove(&hash); - continue + continue; } *retries += 1; } @@ -443,7 +443,7 @@ impl TransactionFetcher { budget_find_idle_fallback_peer, ) else { // no peers are idle or budget is depleted - return + return; }; peer_id @@ -601,7 +601,7 @@ impl TransactionFetcher { max_inflight_transaction_requests=self.info.max_inflight_requests, "limit for concurrent `GetPooledTransactions` requests reached, dropping request for hashes to peer" ); - return Some(new_announced_hashes) + return Some(new_announced_hashes); } let Some(inflight_count) = self.active_peers.get_or_insert(peer_id, || 0) else { @@ -611,7 +611,7 @@ impl TransactionFetcher { conn_eth_version=%conn_eth_version, "failed to cache active peer in schnellru::LruMap, dropping request to peer" ); - return Some(new_announced_hashes) + return Some(new_announced_hashes); }; if *inflight_count >= self.info.max_inflight_requests_per_peer { @@ -622,7 +622,7 @@ impl TransactionFetcher { max_concurrent_tx_reqs_per_peer=self.info.max_inflight_requests_per_peer, "limit for concurrent `GetPooledTransactions` requests per peer reached" ); - return Some(new_announced_hashes) + return Some(new_announced_hashes); } #[cfg(debug_assertions)] @@ -655,7 +655,7 @@ impl TransactionFetcher { self.metrics.egress_peer_channel_full.increment(1); Some(new_announced_hashes) } - } + }; } *inflight_count += 1; @@ -699,10 +699,10 @@ impl TransactionFetcher { .unwrap_or(AVERAGE_BYTE_SIZE_TX_ENCODED); // if request full enough already, we're satisfied, send request for single tx - if acc_size_response >= - DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES + if acc_size_response + >= DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES { - return + return; } // try to fill request by checking if any other hashes pending fetch (in lru order) are @@ -710,7 +710,7 @@ impl TransactionFetcher { for hash in self.hashes_pending_fetch.iter() { // 1. Check if a hash pending fetch is seen by peer. if !seen_hashes.contains(hash) { - continue + continue; }; // 2. Optimistically include the hash in the request. @@ -739,7 +739,7 @@ impl TransactionFetcher { if let Some(ref mut bud) = budget_fill_request { *bud -= 1; if *bud == 0 { - break + break; } } } @@ -775,8 +775,8 @@ impl TransactionFetcher { let info = &self.info; let tx_fetcher_has_capacity = self.has_capacity( - info.max_inflight_requests / - DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_IDLE_PEER, + info.max_inflight_requests + / DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_IDLE_PEER, ); let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports( DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_IDLE_PEER, @@ -814,8 +814,8 @@ impl TransactionFetcher { let info = &self.info; let tx_fetcher_has_capacity = self.has_capacity( - info.max_inflight_requests / - DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_INTERSECTION, + info.max_inflight_requests + / DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_INTERSECTION, ); let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports( DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_INTERSECTION, @@ -866,7 +866,7 @@ impl TransactionFetcher { "received empty `PooledTransactions` response from peer, peer failed to serve hashes it announced" ); - return FetchEvent::EmptyResponse { peer_id } + return FetchEvent::EmptyResponse { peer_id }; } // @@ -897,7 +897,7 @@ impl TransactionFetcher { // peer has only sent hashes that we didn't request if verified_payload.is_empty() { - return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse } + return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse }; } // @@ -933,7 +933,7 @@ impl TransactionFetcher { if valid_payload.contains_key(requested_hash) { // hash is now known, stop tracking fetched.push(*requested_hash); - return false + return false; } true }); @@ -979,11 +979,11 @@ impl Stream for TransactionFetcher { // `FuturesUnordered` doesn't close when `None` is returned. so just return pending. // if self.inflight_requests.is_empty() { - return Poll::Pending + return Poll::Pending; } if let Some(resp) = ready!(self.inflight_requests.poll_next_unpin(cx)) { - return Poll::Ready(Some(self.on_resolved_get_pooled_transactions_request_fut(resp))) + return Poll::Ready(Some(self.on_resolved_get_pooled_transactions_request_fut(resp))); } Poll::Pending @@ -1190,7 +1190,7 @@ impl VerifyPooledTransactionsResponse for UnverifiedPooled tx_hashes_not_requested_count += 1; } - return false + return false; } true }); diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index 18233700e2..ab4ea570d8 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -131,7 +131,7 @@ impl TransactionsHandle { pub fn propagate_hashes_to(&self, hash: impl IntoIterator, peer: PeerId) { let hashes = hash.into_iter().collect::>(); if hashes.is_empty() { - return + return; } self.send(TransactionsCommand::PropagateHashesTo(hashes, peer)) } @@ -148,7 +148,7 @@ impl TransactionsHandle { /// Do nothing if transactions are empty. pub fn propagate_transactions_to(&self, transactions: Vec, peer: PeerId) { if transactions.is_empty() { - return + return; } self.send(TransactionsCommand::PropagateTransactionsTo(transactions, peer)) } @@ -159,7 +159,7 @@ impl TransactionsHandle { /// full. pub fn propagate_transactions(&self, transactions: Vec) { if transactions.is_empty() { - return + return; } self.send(TransactionsCommand::PropagateTransactions(transactions)) } @@ -175,7 +175,7 @@ impl TransactionsHandle { let transactions = transactions.into_iter().map(PropagateTransaction::new).collect::>(); if transactions.is_empty() { - return + return; } self.send(TransactionsCommand::BroadcastTransactions(transactions)) } @@ -186,7 +186,7 @@ impl TransactionsHandle { peers: Vec, ) -> Result>, RecvError> { if peers.is_empty() { - return Ok(Default::default()) + return Ok(Default::default()); } let (tx, rx) = oneshot::channel(); self.send(TransactionsCommand::GetTransactionHashes { peers, tx }); @@ -440,8 +440,8 @@ impl /// `false` if [`TransactionsManager`] is operating close to full capacity. fn has_capacity_for_fetching_pending_hashes(&self) -> bool { self.pending_pool_imports_info - .has_capacity(self.pending_pool_imports_info.max_pending_pool_imports) && - self.transaction_fetcher.has_capacity_for_fetching_pending_hashes() + .has_capacity(self.pending_pool_imports_info.max_pending_pool_imports) + && self.transaction_fetcher.has_capacity_for_fetching_pending_hashes() } fn report_peer_bad_transactions(&self, peer_id: PeerId) { @@ -492,7 +492,7 @@ impl // if we're _currently_ syncing, we ignore a bad transaction if !err.is_bad_transaction() || self.network.is_syncing() { - return + return; } // otherwise we penalize the peer that sent the bad transaction, with the assumption that // the peer should have known that this transaction is bad (e.g. violating consensus rules) @@ -523,7 +523,7 @@ impl RequestError::Timeout => ReputationChangeKind::Timeout, RequestError::ChannelClosed | RequestError::ConnectionDropped => { // peer is already disconnected - return + return; } RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id), }; @@ -582,10 +582,10 @@ impl ) { // If the node is initially syncing, ignore transactions if self.network.is_initially_syncing() { - return + return; } if self.network.tx_gossip_disabled() { - return + return; } // get handle to peer's session, if the session is still active @@ -596,7 +596,7 @@ impl "discarding announcement from inactive peer" ); - return + return; }; let client = peer.client_version.clone(); @@ -662,7 +662,7 @@ impl if partially_valid_msg.is_empty() { // nothing to request - return + return; } // 4. filter out invalid entries (spam) @@ -732,7 +732,7 @@ impl if valid_announcement_data.is_empty() { // no valid announcement data - return + return; } // 5. filter out already seen unknown hashes @@ -751,7 +751,7 @@ impl if valid_announcement_data.is_empty() { // nothing to request - return + return; } trace!(target: "net::tx::propagation", @@ -780,7 +780,7 @@ impl self.transaction_fetcher.buffer_hashes(hashes, Some(peer_id)); - return + return; } let mut hashes_to_request = @@ -854,10 +854,10 @@ where fn on_new_pending_transactions(&mut self, hashes: Vec) { // Nothing to propagate while initially syncing if self.network.is_initially_syncing() { - return + return; } if self.network.tx_gossip_disabled() { - return + return; } trace!(target: "net::tx", num_hashes=?hashes.len(), "Start propagating transactions"); @@ -900,7 +900,7 @@ where if full_transactions.is_empty() { // nothing to propagate - return None + return None; } let PropagateTransactions { pooled, full } = full_transactions.build(); @@ -951,7 +951,7 @@ where let propagated = { let Some(peer) = self.peers.get_mut(&peer_id) else { // no such peer - return + return; }; let to_propagate = self @@ -981,7 +981,7 @@ where if new_pooled_hashes.is_empty() { // nothing to propagate - return + return; } for hash in new_pooled_hashes.iter_hashes().copied() { @@ -1016,7 +1016,7 @@ where ) -> PropagatedTransactions { let mut propagated = PropagatedTransactions::default(); if self.network.tx_gossip_disabled() { - return propagated + return propagated; } // send full transactions to a set of the connected peers based on the configured mode @@ -1026,7 +1026,7 @@ where for (peer_idx, (peer_id, peer)) in self.peers.iter_mut().enumerate() { if !self.policies.propagation_policy().can_propagate(peer) { // skip peers we should not propagate to - continue + continue; } // determine whether to send full tx objects or hashes. let mut builder = if peer_idx > max_num_full { @@ -1052,7 +1052,7 @@ where if builder.is_empty() { trace!(target: "net::tx", ?peer_id, "Nothing to propagate to peer; has seen all transactions"); - continue + continue; } let PropagateTransactions { pooled, full } = builder.build(); @@ -1125,7 +1125,7 @@ where if let Some(peer) = self.peers.get_mut(&peer_id) { if self.network.tx_gossip_disabled() { let _ = response.send(Ok(PooledTransactions::default())); - return + return; } let transactions = self.pool.get_pooled_transaction_elements( request.0, @@ -1221,7 +1221,7 @@ where // transactions in the pool. if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() { trace!(target: "net::tx", ?peer_id, "Skipping transaction broadcast: node syncing or gossip disabled"); - return + return; } // Get transactions to broadcast @@ -1321,10 +1321,10 @@ where ) { // If the node is pipeline syncing, ignore transactions if self.network.is_initially_syncing() { - return + return; } if self.network.tx_gossip_disabled() { - return + return; } let Some(peer) = self.peers.get_mut(&peer_id) else { return }; @@ -1373,7 +1373,7 @@ where "failed ecrecovery for transaction" ); has_bad_transactions = true; - continue + continue; } }; @@ -1626,16 +1626,16 @@ where this.transaction_fetcher.update_metrics(); // all channels are fully drained and import futures pending - if maybe_more_network_events || - maybe_more_commands || - maybe_more_tx_events || - maybe_more_tx_fetch_events || - maybe_more_pool_imports || - maybe_more_pending_txns + if maybe_more_network_events + || maybe_more_commands + || maybe_more_tx_events + || maybe_more_tx_fetch_events + || maybe_more_pool_imports + || maybe_more_pending_txns { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } this.update_poll_metrics(start, poll_durations); @@ -1825,16 +1825,16 @@ impl FullTransactionsBuilder { // From: if !transaction.transaction.is_broadcastable_in_full() { self.pooled.push(transaction); - return + return; } let new_size = self.total_size + transaction.size; - if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE && - self.total_size > 0 + if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE + && self.total_size > 0 { // transaction does not fit into the message self.pooled.push(transaction); - return + return; } self.total_size = new_size; @@ -2233,8 +2233,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { // to insert a new peer in transactions peerset transactions.on_network_event(ev); } @@ -2402,8 +2402,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { // to insert a new peer in transactions peerset transactions.on_network_event(ev); } @@ -2480,8 +2480,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { transactions.on_network_event(ev); } NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {} diff --git a/crates/net/network/tests/it/connect.rs b/crates/net/network/tests/it/connect.rs index f4c4aa159b..7e86b7de0c 100644 --- a/crates/net/network/tests/it/connect.rs +++ b/crates/net/network/tests/it/connect.rs @@ -63,8 +63,8 @@ async fn test_establish_connections() { NetworkEvent::Peer(PeerEvent::SessionClosed { .. } | PeerEvent::PeerRemoved(_)) => { panic!("unexpected event") } - NetworkEvent::ActivePeerSession { info, .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { let SessionInfo { peer_id, .. } = info; assert!(expected_connections.remove(&peer_id)); } diff --git a/crates/net/network/tests/it/multiplex.rs b/crates/net/network/tests/it/multiplex.rs index d081100681..f0ba867c9e 100644 --- a/crates/net/network/tests/it/multiplex.rs +++ b/crates/net/network/tests/it/multiplex.rs @@ -103,8 +103,8 @@ mod proto { buf.put_u8(self.message_type as u8); match &self.message { PingPongProtoMessageKind::Ping | PingPongProtoMessageKind::Pong => {} - PingPongProtoMessageKind::PingMessage(msg) | - PingPongProtoMessageKind::PongMessage(msg) => { + PingPongProtoMessageKind::PingMessage(msg) + | PingPongProtoMessageKind::PongMessage(msg) => { buf.put(msg.as_bytes()); } } @@ -114,7 +114,7 @@ mod proto { /// Decodes a `TestProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None + return None; } let id = buf[0]; buf.advance(1); @@ -238,7 +238,7 @@ impl Stream for PingPongProtoConnection { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Some(initial_ping) = this.initial_ping.take() { - return Poll::Ready(Some(initial_ping.encoded())) + return Poll::Ready(Some(initial_ping.encoded())); } loop { @@ -248,12 +248,12 @@ impl Stream for PingPongProtoConnection { this.pending_pong = Some(response); Poll::Ready(Some(PingPongProtoMessage::ping_message(msg).encoded())) } - } + }; } let Some(msg) = ready!(this.conn.poll_next_unpin(cx)) else { return Poll::Ready(None) }; let Some(msg) = PingPongProtoMessage::decode_message(&mut &msg[..]) else { - return Poll::Ready(None) + return Poll::Ready(None); }; match msg.message { @@ -268,11 +268,11 @@ impl Stream for PingPongProtoConnection { if let Some(sender) = this.pending_pong.take() { sender.send(msg).ok(); } - continue + continue; } } - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/net/network/tests/it/txgossip.rs b/crates/net/network/tests/it/txgossip.rs index 4014f41bfc..f577ec5e41 100644 --- a/crates/net/network/tests/it/txgossip.rs +++ b/crates/net/network/tests/it/txgossip.rs @@ -212,8 +212,8 @@ async fn test_sending_invalid_transactions() { NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, .. }) => { assert_eq!(peer_id, *peer0.peer_id()); } - NetworkEvent::ActivePeerSession { .. } | - NetworkEvent::Peer(PeerEvent::SessionEstablished { .. }) => { + NetworkEvent::ActivePeerSession { .. } + | NetworkEvent::Peer(PeerEvent::SessionEstablished { .. }) => { panic!("unexpected SessionEstablished event") } NetworkEvent::Peer(PeerEvent::PeerAdded(_)) => { diff --git a/crates/net/p2p/src/error.rs b/crates/net/p2p/src/error.rs index d650763b4e..5664f92764 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -34,7 +34,7 @@ impl EthResponseValidator for RequestResult> { let request_length = headers.len() as u64; if request_length <= 1 && request.limit != request_length { - return true + return true; } match request.start { @@ -62,10 +62,10 @@ impl EthResponseValidator for RequestResult> { fn reputation_change_err(&self) -> Option { if let Err(err) = self { match err { - RequestError::ChannelClosed | - RequestError::ConnectionDropped | - RequestError::UnsupportedCapability | - RequestError::BadResponse => None, + RequestError::ChannelClosed + | RequestError::ConnectionDropped + | RequestError::UnsupportedCapability + | RequestError::BadResponse => None, RequestError::Timeout => Some(ReputationChangeKind::Timeout), } } else { diff --git a/crates/net/p2p/src/full_block.rs b/crates/net/p2p/src/full_block.rs index aa48f6c610..d77b7c2188 100644 --- a/crates/net/p2p/src/full_block.rs +++ b/crates/net/p2p/src/full_block.rs @@ -146,7 +146,7 @@ where /// Returns the [`SealedBlock`] if the request is complete and valid. fn take_block(&mut self) -> Option> { if self.header.is_none() || self.body.is_none() { - return None + return None; } let header = self.header.take().unwrap(); @@ -161,7 +161,7 @@ where self.client.report_bad_message(resp.peer_id()); self.header = Some(header); self.request.body = Some(self.client.get_block_body(self.hash)); - return None + return None; } Some(SealedBlock::from_sealed_parts(header, resp.into_data())) } @@ -173,10 +173,10 @@ where if let Err(err) = self.consensus.validate_body_against_header(resp.data(), header) { debug!(target: "downloaders", %err, hash=?header.hash(), "Received wrong body"); self.client.report_bad_message(resp.peer_id()); - return + return; } self.body = Some(BodyResponse::Validated(resp.into_data())); - return + return; } self.body = Some(BodyResponse::PendingValidation(resp)); } @@ -240,7 +240,7 @@ where } if let Some(res) = this.take_block() { - return Poll::Ready(res) + return Poll::Ready(res); } // ensure we still have enough budget for another iteration @@ -248,7 +248,7 @@ where if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } } } @@ -283,14 +283,14 @@ where if let Some(fut) = Pin::new(&mut self.header).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.header = None; - return Poll::Ready(ResponseResult::Header(res)) + return Poll::Ready(ResponseResult::Header(res)); } } if let Some(fut) = Pin::new(&mut self.body).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.body = None; - return Poll::Ready(ResponseResult::Body(res)) + return Poll::Ready(ResponseResult::Body(res)); } } @@ -395,7 +395,7 @@ where fn take_blocks(&mut self) -> Option>> { if !self.is_bodies_complete() { // not done with bodies yet - return None + return None; } let headers = self.headers.take()?; @@ -418,7 +418,7 @@ where // get body that doesn't match, put back into vecdeque, and retry it self.pending_headers.push_back(header.clone()); needs_retry = true; - continue + continue; } resp.into_data() @@ -444,7 +444,7 @@ where // create response for failing bodies let hashes = self.remaining_bodies_hashes(); self.request.bodies = Some(self.client.get_block_bodies(hashes)); - return None + return None; } Some(valid_responses) @@ -596,7 +596,7 @@ where } if let Some(res) = this.take_blocks() { - return Poll::Ready(res) + return Poll::Ready(res); } } } @@ -624,14 +624,14 @@ where if let Some(fut) = Pin::new(&mut self.headers).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.headers = None; - return Poll::Ready(RangeResponseResult::Header(res)) + return Poll::Ready(RangeResponseResult::Header(res)); } } if let Some(fut) = Pin::new(&mut self.bodies).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.bodies = None; - return Poll::Ready(RangeResponseResult::Body(res)) + return Poll::Ready(RangeResponseResult::Body(res)); } } diff --git a/crates/net/p2p/src/test_utils/headers.rs b/crates/net/p2p/src/test_utils/headers.rs index b19b29d58d..53cd747bdf 100644 --- a/crates/net/p2p/src/test_utils/headers.rs +++ b/crates/net/p2p/src/test_utils/headers.rs @@ -72,7 +72,7 @@ impl Stream for TestHeaderDownloader { let this = self.get_mut(); loop { if this.queued_headers.len() == this.batch_size { - return Poll::Ready(Some(Ok(std::mem::take(&mut this.queued_headers)))) + return Poll::Ready(Some(Ok(std::mem::take(&mut this.queued_headers)))); } if this.download.is_none() { this.download = Some(this.create_download()); @@ -130,9 +130,9 @@ impl Stream for TestDownload { loop { if let Some(header) = this.buffer.pop() { - return Poll::Ready(Some(Ok(header))) + return Poll::Ready(Some(Ok(header))); } else if this.done { - return Poll::Ready(None) + return Poll::Ready(None); } match ready!(this.get_or_init_fut().poll_unpin(cx)) { @@ -151,7 +151,7 @@ impl Stream for TestDownload { return Poll::Ready(Some(Err(match err { RequestError::Timeout => DownloadError::Timeout, _ => DownloadError::RequestError(err), - }))) + }))); } } } @@ -217,7 +217,7 @@ impl HeadersClient for TestHeadersClient { Box::pin(async move { if let Some(err) = &mut *error.lock().await { - return Err(err.clone()) + return Err(err.clone()); } let mut lock = responses.lock().await; diff --git a/crates/net/peers/src/lib.rs b/crates/net/peers/src/lib.rs index bfca16a82f..477ee40fb4 100644 --- a/crates/net/peers/src/lib.rs +++ b/crates/net/peers/src/lib.rs @@ -178,17 +178,17 @@ impl FromStr for AnyNode { fn from_str(s: &str) -> Result { if let Some(rem) = s.strip_prefix("enode://") { if let Ok(record) = NodeRecord::from_str(s) { - return Ok(Self::NodeRecord(record)) + return Ok(Self::NodeRecord(record)); } // incomplete enode if let Ok(peer_id) = PeerId::from_str(rem) { - return Ok(Self::PeerId(peer_id)) + return Ok(Self::PeerId(peer_id)); } - return Err(format!("invalid public key: {rem}")) + return Err(format!("invalid public key: {rem}")); } #[cfg(feature = "secp256k1")] if s.starts_with("enr:") { - return Enr::from_str(s).map(AnyNode::Enr) + return Enr::from_str(s).map(AnyNode::Enr); } Err("missing 'enr:' prefix for base64-encoded record".to_string()) } diff --git a/crates/net/peers/src/node_record.rs b/crates/net/peers/src/node_record.rs index d9f10ebdbe..c74b80542d 100644 --- a/crates/net/peers/src/node_record.rs +++ b/crates/net/peers/src/node_record.rs @@ -66,7 +66,7 @@ impl NodeRecord { if let IpAddr::V6(v6) = self.address { if let Some(v4) = v6.to_ipv4_mapped() { self.address = v4.into(); - return true + return true; } } false @@ -215,15 +215,15 @@ impl TryFrom<&Enr> for NodeRecord { fn try_from(enr: &Enr) -> Result { let Some(address) = enr.ip4().map(IpAddr::from).or_else(|| enr.ip6().map(IpAddr::from)) else { - return Err(NodeRecordParseError::InvalidUrl("ip missing".to_string())) + return Err(NodeRecordParseError::InvalidUrl("ip missing".to_string())); }; let Some(udp_port) = enr.udp4().or_else(|| enr.udp6()) else { - return Err(NodeRecordParseError::InvalidUrl("udp port missing".to_string())) + return Err(NodeRecordParseError::InvalidUrl("udp port missing".to_string())); }; let Some(tcp_port) = enr.tcp4().or_else(|| enr.tcp6()) else { - return Err(NodeRecordParseError::InvalidUrl("tcp port missing".to_string())) + return Err(NodeRecordParseError::InvalidUrl("tcp port missing".to_string())); }; let id = crate::pk2id(&enr.public_key()); diff --git a/crates/node/builder/src/launch/common.rs b/crates/node/builder/src/launch/common.rs index f7696799e9..02d96c24a4 100644 --- a/crates/node/builder/src/launch/common.rs +++ b/crates/node/builder/src/launch/common.rs @@ -835,9 +835,9 @@ where /// This checks for OP-Mainnet and ensures we have all the necessary data to progress (past /// bedrock height) fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> { - if self.chain_spec().is_optimism() && - !self.is_dev() && - self.chain_id() == Chain::optimism_mainnet() + if self.chain_spec().is_optimism() + && !self.is_dev() + && self.chain_id() == Chain::optimism_mainnet() { let latest = self.blockchain_db().last_block_number()?; // bedrock height @@ -845,7 +845,7 @@ where error!( "Op-mainnet has been launched without importing the pre-Bedrock state. The chain can't progress without this. See also https://reth.rs/run/sync-op-mainnet.html?minimal-bootstrap-recommended" ); - return Err(ProviderError::BestBlockNotFound) + return Err(ProviderError::BestBlockNotFound); } } @@ -1016,7 +1016,7 @@ where &self, ) -> eyre::Result::Primitives>>> { let Some(ref hook) = self.node_config().debug.invalid_block_hook else { - return Ok(Box::new(NoopInvalidBlockHook::default())) + return Ok(Box::new(NoopInvalidBlockHook::default())); }; let healthy_node_rpc_client = self.get_healthy_node_client().await?; diff --git a/crates/node/builder/src/launch/exex.rs b/crates/node/builder/src/launch/exex.rs index b40c9c8b61..8fe44ce836 100644 --- a/crates/node/builder/src/launch/exex.rs +++ b/crates/node/builder/src/launch/exex.rs @@ -47,7 +47,7 @@ impl ExExLauncher { if extensions.is_empty() { // nothing to launch - return Ok(None) + return Ok(None); } info!(target: "reth::cli", "Loading ExEx Write-Ahead Log..."); diff --git a/crates/node/core/src/args/debug.rs b/crates/node/core/src/args/debug.rs index d8b6d57038..97c69c07ca 100644 --- a/crates/node/core/src/args/debug.rs +++ b/crates/node/core/src/args/debug.rs @@ -218,7 +218,7 @@ impl FromStr for InvalidBlockSelection { fn from_str(s: &str) -> Result { if s.is_empty() { - return Ok(Self(Default::default())) + return Ok(Self(Default::default())); } let hooks = s.split(',').map(str::trim).peekable(); Self::try_from_selection(hooks) diff --git a/crates/node/core/src/args/network.rs b/crates/node/core/src/args/network.rs index 2f5908aaf4..18835a1e76 100644 --- a/crates/node/core/src/args/network.rs +++ b/crates/node/core/src/args/network.rs @@ -496,9 +496,9 @@ impl DiscoveryArgs { return false; } - self.enable_discv5_discovery || - self.discv5_addr.is_some() || - self.discv5_addr_ipv6.is_some() + self.enable_discv5_discovery + || self.discv5_addr.is_some() + || self.discv5_addr_ipv6.is_some() } /// Set the discovery port to zero, to allow the OS to assign a random unused port when diff --git a/crates/node/core/src/args/payload_builder.rs b/crates/node/core/src/args/payload_builder.rs index d658241c21..5c304ba25b 100644 --- a/crates/node/core/src/args/payload_builder.rs +++ b/crates/node/core/src/args/payload_builder.rs @@ -92,7 +92,7 @@ impl TypedValueParser for ExtraDataValueParser { format!( "Payload builder extradata size exceeds {MAXIMUM_EXTRA_DATA_SIZE}-byte limit" ), - )) + )); } Ok(val.to_string()) } diff --git a/crates/node/core/src/node_config.rs b/crates/node/core/src/node_config.rs index b1998110a3..e434b2d726 100644 --- a/crates/node/core/src/node_config.rs +++ b/crates/node/core/src/node_config.rs @@ -372,7 +372,7 @@ impl NodeConfig { // try to look up the header in the database if let Some(header) = header { info!(target: "reth::cli", ?tip, "Successfully looked up tip block in the database"); - return Ok(header.number()) + return Ok(header.number()); } Ok(self.fetch_tip_from_network(client, tip.into()).await.number()) @@ -395,7 +395,7 @@ impl NodeConfig { match get_single_header(&client, tip).await { Ok(tip_header) => { info!(target: "reth::cli", ?tip, "Successfully fetched tip"); - return tip_header + return tip_header; } Err(error) => { fetch_failures += 1; diff --git a/crates/node/events/src/cl.rs b/crates/node/events/src/cl.rs index bdced7c97d..ca974b49e2 100644 --- a/crates/node/events/src/cl.rs +++ b/crates/node/events/src/cl.rs @@ -51,18 +51,18 @@ impl Stream for ConsensusLayerHealthEvents { if let Some(fork_choice) = this.canon_chain.last_received_update_timestamp() { if fork_choice.elapsed() <= NO_FORKCHOICE_UPDATE_RECEIVED_PERIOD { // We had an FCU, and it's recent. CL is healthy. - continue + continue; } // We had an FCU, but it's too old. return Poll::Ready(Some( ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile( fork_choice.elapsed(), ), - )) + )); } // We never had both FCU and transition config exchange. - return Poll::Ready(Some(ConsensusLayerHealthEvent::NeverSeen)) + return Poll::Ready(Some(ConsensusLayerHealthEvent::NeverSeen)); } } } diff --git a/crates/node/events/src/node.rs b/crates/node/events/src/node.rs index bd583c45e4..00530bdb02 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -220,8 +220,8 @@ impl NodeState { BeaconConsensusEngineEvent::ForkchoiceUpdated(state, status) => { let ForkchoiceState { head_block_hash, safe_block_hash, finalized_block_hash } = state; - if self.safe_block_hash != Some(safe_block_hash) && - self.finalized_block_hash != Some(finalized_block_hash) + if self.safe_block_hash != Some(safe_block_hash) + && self.finalized_block_hash != Some(finalized_block_hash) { let msg = match status { ForkchoiceStatus::Valid => "Forkchoice updated", @@ -556,7 +556,7 @@ impl Eta { else { self.eta = None; debug!(target: "reth::cli", %stage, ?current, ?self.last_checkpoint, "Failed to calculate the ETA: processed entities is less than the last checkpoint"); - return + return; }; let elapsed = last_checkpoint_time.elapsed(); let per_second = processed_since_last as f64 / elapsed.as_secs_f64(); @@ -564,7 +564,7 @@ impl Eta { let Some(remaining) = current.total.checked_sub(current.processed) else { self.eta = None; debug!(target: "reth::cli", %stage, ?current, "Failed to calculate the ETA: total entities is less than processed entities"); - return + return; }; self.eta = Duration::try_from_secs_f64(remaining as f64 / per_second).ok(); @@ -585,8 +585,8 @@ impl Eta { /// It's not the case for network-dependent ([`StageId::Headers`] and [`StageId::Bodies`]) and /// [`StageId::Execution`] stages. fn fmt_for_stage(&self, stage: StageId) -> Option { - if !self.is_available() || - matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution) + if !self.is_available() + || matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution) { None } else { @@ -605,7 +605,7 @@ impl Display for Eta { f, "{}", humantime::format_duration(Duration::from_secs(remaining.as_secs())) - ) + ); } } diff --git a/crates/node/metrics/src/hooks.rs b/crates/node/metrics/src/hooks.rs index d8ddce0a4d..9d7ee076da 100644 --- a/crates/node/metrics/src/hooks.rs +++ b/crates/node/metrics/src/hooks.rs @@ -93,7 +93,7 @@ fn collect_memory_stats() { if epoch::advance().map_err(|error| error!(%error, "Failed to advance jemalloc epoch")).is_err() { - return + return; } if let Ok(value) = stats::active::read() @@ -144,13 +144,13 @@ fn collect_io_stats() { let Ok(process) = procfs::process::Process::myself() .map_err(|error| error!(%error, "Failed to get currently running process")) else { - return + return; }; let Ok(io) = process.io().map_err( |error| error!(%error, "Failed to get IO stats for the currently running process"), ) else { - return + return; }; counter!("io.rchar").absolute(io.rchar); diff --git a/crates/optimism/chainspec/src/superchain/configs.rs b/crates/optimism/chainspec/src/superchain/configs.rs index 428f197a04..456df1ff6e 100644 --- a/crates/optimism/chainspec/src/superchain/configs.rs +++ b/crates/optimism/chainspec/src/superchain/configs.rs @@ -78,7 +78,7 @@ fn read_file( ) -> Result, SuperchainConfigError> { for entry in archive.entries() { if entry.filename().as_str()? == file_path { - return Ok(entry.data().to_vec()) + return Ok(entry.data().to_vec()); } } Err(SuperchainConfigError::FileNotFound(file_path.to_string())) @@ -127,7 +127,7 @@ mod tests { .map(|s| s.to_string()) .collect::>(); if filename.first().unwrap().ne(&"genesis") { - continue + continue; } read_superchain_metadata( &filename.get(2).unwrap().replace(".json.zz", ""), diff --git a/crates/optimism/cli/src/commands/import.rs b/crates/optimism/cli/src/commands/import.rs index 2fd0c56758..4803bf0089 100644 --- a/crates/optimism/cli/src/commands/import.rs +++ b/crates/optimism/cli/src/commands/import.rs @@ -89,7 +89,7 @@ impl> ImportOpCommand { body.transactions.retain(|_| { if is_dup_tx(block_number) { total_filtered_out_dup_txns += 1; - return false + return false; } true }) @@ -132,8 +132,8 @@ impl> ImportOpCommand { let total_imported_blocks = provider.tx_ref().entries::()?; let total_imported_txns = provider.tx_ref().entries::()?; - if total_decoded_blocks != total_imported_blocks || - total_decoded_txns != total_imported_txns + total_filtered_out_dup_txns + if total_decoded_blocks != total_imported_blocks + || total_decoded_txns != total_imported_txns + total_filtered_out_dup_txns { error!(target: "reth::cli", total_decoded_blocks, diff --git a/crates/optimism/cli/src/commands/import_receipts.rs b/crates/optimism/cli/src/commands/import_receipts.rs index 38503bc2d3..0a49bc4275 100644 --- a/crates/optimism/cli/src/commands/import_receipts.rs +++ b/crates/optimism/cli/src/commands/import_receipts.rs @@ -175,7 +175,7 @@ where { if highest_block_receipts == highest_block_transactions { warn!(target: "reth::cli", highest_block_receipts, highest_block_transactions, "Ignoring all other blocks in the file since we have reached the desired height"); - break + break; } // create a new file client from chunk read from file diff --git a/crates/optimism/cli/src/commands/init_state.rs b/crates/optimism/cli/src/commands/init_state.rs index da574239d5..5151334584 100644 --- a/crates/optimism/cli/src/commands/init_state.rs +++ b/crates/optimism/cli/src/commands/init_state.rs @@ -71,7 +71,7 @@ impl> InitStateCommandOp { } else if last_block_number > 0 && last_block_number < BEDROCK_HEADER.number { return Err(eyre::eyre!( "Data directory should be empty when calling init-state with --without-ovm." - )) + )); } } diff --git a/crates/optimism/cli/src/receipt_file_codec.rs b/crates/optimism/cli/src/receipt_file_codec.rs index f5b6b48b26..bd479c21f8 100644 --- a/crates/optimism/cli/src/receipt_file_codec.rs +++ b/crates/optimism/cli/src/receipt_file_codec.rs @@ -43,7 +43,7 @@ where fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None) + return Ok(None); } let buf_slice = &mut src.as_ref(); diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index 3e4201dc73..d147b46db3 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -96,12 +96,12 @@ where expected: block.ommers_hash(), } .into(), - )) + )); } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())) + return Err(ConsensusError::BodyTransactionRootDiff(error.into())); } // Check empty shanghai-withdrawals @@ -110,7 +110,7 @@ where ConsensusError::Other(format!("failed to verify block {}: {err}", block.number())) })? } else { - return Ok(()) + return Ok(()); } if self.chain_spec.is_ecotone_active_at_timestamp(block.timestamp()) { @@ -146,11 +146,11 @@ where ); if header.nonce() != Some(B64::ZERO) { - return Err(ConsensusError::TheMergeNonceIsNotZero) + return Err(ConsensusError::TheMergeNonceIsNotZero); } if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty) + return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); } // Post-merge, the consensus layer is expected to perform checks such that the block @@ -192,7 +192,7 @@ where return Err(ConsensusError::BaseFeeDiff(GotExpected { expected: expected_base_fee, got: header_base_fee, - })) + })); } } else { validate_against_parent_eip1559_base_fee( diff --git a/crates/optimism/consensus/src/proof.rs b/crates/optimism/consensus/src/proof.rs index 86f7b2ecbe..4d87638091 100644 --- a/crates/optimism/consensus/src/proof.rs +++ b/crates/optimism/consensus/src/proof.rs @@ -19,8 +19,8 @@ pub(crate) fn calculate_receipt_root_optimism( // encoding. In the Regolith Hardfork, we must strip the deposit nonce from the // receipts before calculating the receipt root. This was corrected in the Canyon // hardfork. - if chain_spec.is_regolith_active_at_timestamp(timestamp) && - !chain_spec.is_canyon_active_at_timestamp(timestamp) + if chain_spec.is_regolith_active_at_timestamp(timestamp) + && !chain_spec.is_canyon_active_at_timestamp(timestamp) { let receipts = receipts .iter() @@ -33,7 +33,7 @@ pub(crate) fn calculate_receipt_root_optimism( }) .collect::>(); - return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| r.encode_2718(buf)) + return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| r.encode_2718(buf)); } ordered_trie_root_with_encoder(receipts, |r, buf| r.encode_2718(buf)) @@ -52,8 +52,8 @@ pub fn calculate_receipt_root_no_memo_optimism( // encoding. In the Regolith Hardfork, we must strip the deposit nonce from the // receipts before calculating the receipt root. This was corrected in the Canyon // hardfork. - if chain_spec.is_regolith_active_at_timestamp(timestamp) && - !chain_spec.is_canyon_active_at_timestamp(timestamp) + if chain_spec.is_regolith_active_at_timestamp(timestamp) + && !chain_spec.is_canyon_active_at_timestamp(timestamp) { let receipts = receipts .iter() @@ -68,7 +68,7 @@ pub fn calculate_receipt_root_no_memo_optimism( return ordered_trie_root_with_encoder(&receipts, |r, buf| { r.with_bloom_ref().encode_2718(buf); - }) + }); } ordered_trie_root_with_encoder(receipts, |r, buf| { diff --git a/crates/optimism/consensus/src/validation/canyon.rs b/crates/optimism/consensus/src/validation/canyon.rs index 886f53bb20..432b121a48 100644 --- a/crates/optimism/consensus/src/validation/canyon.rs +++ b/crates/optimism/consensus/src/validation/canyon.rs @@ -34,7 +34,7 @@ pub fn ensure_empty_shanghai_withdrawals(body: &T) -> Result<(), O // Canyon rule if !withdrawals.as_ref().is_empty() { - return Err(OpConsensusError::WithdrawalsNonEmpty) + return Err(OpConsensusError::WithdrawalsNonEmpty); } Ok(()) diff --git a/crates/optimism/consensus/src/validation/isthmus.rs b/crates/optimism/consensus/src/validation/isthmus.rs index 64d45eae5c..cdaf382661 100644 --- a/crates/optimism/consensus/src/validation/isthmus.rs +++ b/crates/optimism/consensus/src/validation/isthmus.rs @@ -90,7 +90,7 @@ where return Err(OpConsensusError::L2WithdrawalsRootMismatch { header: header_storage_root, exec_res: storage_root, - }) + }); } Ok(()) @@ -122,7 +122,7 @@ where return Err(OpConsensusError::L2WithdrawalsRootMismatch { header: header_storage_root, exec_res: storage_root, - }) + }); } Ok(()) diff --git a/crates/optimism/consensus/src/validation/mod.rs b/crates/optimism/consensus/src/validation/mod.rs index 4977647d89..bd69c664d9 100644 --- a/crates/optimism/consensus/src/validation/mod.rs +++ b/crates/optimism/consensus/src/validation/mod.rs @@ -38,14 +38,14 @@ where expected: header.ommers_hash(), } .into(), - )) + )); } let tx_root = body.calculate_tx_root(); if header.transactions_root() != tx_root { return Err(ConsensusError::BodyTransactionRootDiff( GotExpected { got: tx_root, expected: header.transactions_root() }.into(), - )) + )); } match (header.withdrawals_root(), body.calculate_withdrawals_root()) { @@ -57,7 +57,7 @@ where if withdrawals_root != EMPTY_ROOT_HASH { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: EMPTY_ROOT_HASH }.into(), - )) + )); } } else { // before isthmus we ensure that the header root matches the body @@ -65,7 +65,7 @@ where return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root } .into(), - )) + )); } } } @@ -100,7 +100,7 @@ pub fn validate_block_post_execution( header.timestamp(), ) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error) + return Err(error); } } @@ -111,7 +111,7 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: header.gas_used() }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }) + }); } Ok(()) @@ -154,13 +154,13 @@ fn compare_receipts_root_and_logs_bloom( if calculated_receipts_root != expected_receipts_root { return Err(ConsensusError::BodyReceiptRootDiff( GotExpected { got: calculated_receipts_root, expected: expected_receipts_root }.into(), - )) + )); } if calculated_logs_bloom != expected_logs_bloom { return Err(ConsensusError::BodyBloomLogDiff( GotExpected { got: calculated_logs_bloom, expected: expected_logs_bloom }.into(), - )) + )); } Ok(()) diff --git a/crates/optimism/node/src/engine.rs b/crates/optimism/node/src/engine.rs index bba734ae8f..670d9c2674 100644 --- a/crates/optimism/node/src/engine.rs +++ b/crates/optimism/node/src/engine.rs @@ -140,7 +140,7 @@ where // FIXME: we don't necessarily have access to the parent block here because the // parent block isn't necessarily part of the canonical chain yet. Instead this // function should receive the list of in memory blocks as input - return Ok(()) + return Ok(()); }; let predeploy_storage_updates = state_updates .storages @@ -264,10 +264,10 @@ pub fn validate_withdrawals_presence( .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); } } - EngineApiMessageVersion::V2 | - EngineApiMessageVersion::V3 | - EngineApiMessageVersion::V4 | - EngineApiMessageVersion::V5 => { + EngineApiMessageVersion::V2 + | EngineApiMessageVersion::V3 + | EngineApiMessageVersion::V4 + | EngineApiMessageVersion::V5 => { if is_shanghai && !has_withdrawals { return Err(message_validation_kind .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 2d33f05f4a..4d9416976a 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -786,8 +786,8 @@ where let Self { pool_config_overrides, .. } = self; // supervisor used for interop - if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) && - self.supervisor_http == DEFAULT_SUPERVISOR_URL + if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) + && self.supervisor_http == DEFAULT_SUPERVISOR_URL { info!(target: "reth::cli", url=%DEFAULT_SUPERVISOR_URL, @@ -830,8 +830,8 @@ where debug!(target: "reth::cli", "Spawned txpool maintenance task"); // The Op txpool maintenance task is only spawned when interop is active - if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) && - self.supervisor_http == DEFAULT_SUPERVISOR_URL + if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) + && self.supervisor_http == DEFAULT_SUPERVISOR_URL { // spawn the Op txpool maintenance task let chain_events = ctx.provider().canonical_state_stream(); diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index d5a3260420..f450fd7d9d 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -311,13 +311,13 @@ impl OpBuilder<'_, Txs> { if !ctx.attributes().no_tx_pool { let best_txs = best(ctx.best_transaction_attributes(builder.evm_mut().block())); if ctx.execute_best_transactions(&mut info, &mut builder, best_txs)?.is_some() { - return Ok(BuildOutcomeKind::Cancelled) + return Ok(BuildOutcomeKind::Cancelled); } // check if the new payload is even more valuable if !ctx.is_better_payload(info.total_fees) { // can skip building the block - return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }) + return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }); } } @@ -593,7 +593,7 @@ where if sequencer_tx.value().is_eip4844() { return Err(PayloadBuilderError::other( OpPayloadBuilderError::BlobTransactionRejected, - )) + )); } // Convert the transaction to a [RecoveredTx]. This is @@ -611,11 +611,11 @@ where .. })) => { trace!(target: "payload_builder", %error, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue + continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; @@ -657,13 +657,13 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue + continue; } // A sequencer's block should never contain blob or deposit transactions from the pool. if tx.is_eip4844() || tx.is_deposit() { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue + continue; } // We skip invalid cross chain txs, they would be removed on the next block update in @@ -671,12 +671,12 @@ where if let Some(interop) = interop { if !is_valid_interop(interop, self.config.attributes.timestamp()) { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue + continue; } } // check if the job was cancelled, if so we can exit early if self.cancel.is_cancelled() { - return Ok(Some(())) + return Ok(Some(())); } let gas_used = match builder.execute_transaction(tx.clone()) { @@ -694,11 +694,11 @@ where trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid(tx.signer(), tx.nonce()); } - continue + continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; diff --git a/crates/optimism/payload/src/validator.rs b/crates/optimism/payload/src/validator.rs index b287c55398..ba808f0057 100644 --- a/crates/optimism/payload/src/validator.rs +++ b/crates/optimism/payload/src/validator.rs @@ -60,7 +60,7 @@ where return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - })? + })?; } shanghai::ensure_well_formed_fields( diff --git a/crates/optimism/primitives/src/bedrock.rs b/crates/optimism/primitives/src/bedrock.rs index 5ab72cf0d7..6c2e062f76 100644 --- a/crates/optimism/primitives/src/bedrock.rs +++ b/crates/optimism/primitives/src/bedrock.rs @@ -43,12 +43,12 @@ pub const BLOCK_NUMS_REPLAYED_TX: [u64; 6] = [ /// with replayed transaction happen to only contain the single transaction. pub fn is_dup_tx(block_number: u64) -> bool { if block_number > BLOCK_NUMS_REPLAYED_TX[5] { - return false + return false; } // these blocks just have one transaction! if BLOCK_NUMS_REPLAYED_TX.contains(&block_number) { - return true + return true; } false diff --git a/crates/optimism/primitives/src/receipt.rs b/crates/optimism/primitives/src/receipt.rs index e0ef631808..c253a754b6 100644 --- a/crates/optimism/primitives/src/receipt.rs +++ b/crates/optimism/primitives/src/receipt.rs @@ -45,10 +45,10 @@ impl OpReceipt { /// Returns inner [`Receipt`], pub const fn as_receipt(&self) -> &Receipt { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => &receipt.inner, } } @@ -56,10 +56,10 @@ impl OpReceipt { /// Returns a mutable reference to the inner [`Receipt`], pub const fn as_receipt_mut(&mut self) -> &mut Receipt { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => &mut receipt.inner, } } @@ -67,10 +67,10 @@ impl OpReceipt { /// Consumes this and returns the inner [`Receipt`]. pub fn into_receipt(self) -> Receipt { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => receipt.inner, } } @@ -78,10 +78,10 @@ impl OpReceipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), Self::Deposit(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), } } @@ -89,10 +89,10 @@ impl OpReceipt { /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encode_fields(&self, bloom: &Bloom, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), Self::Deposit(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), } } @@ -145,10 +145,10 @@ impl OpReceipt { /// RLP-encodes receipt fields without an RLP header. pub fn rlp_encode_fields_without_bloom(&self, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => { + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => { receipt.status.encode(out); receipt.cumulative_gas_used.encode(out); receipt.logs.encode(out); @@ -170,20 +170,20 @@ impl OpReceipt { /// Returns length of RLP-encoded receipt fields without an RLP header. pub fn rlp_encoded_fields_length_without_bloom(&self) -> usize { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => { - receipt.status.length() + - receipt.cumulative_gas_used.length() + - receipt.logs.length() + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => { + receipt.status.length() + + receipt.cumulative_gas_used.length() + + receipt.logs.length() } Self::Deposit(receipt) => { - receipt.inner.status.length() + - receipt.inner.cumulative_gas_used.length() + - receipt.inner.logs.length() + - receipt.deposit_nonce.map_or(0, |nonce| nonce.length()) + - receipt.deposit_receipt_version.map_or(0, |version| version.length()) + receipt.inner.status.length() + + receipt.inner.cumulative_gas_used.length() + + receipt.inner.logs.length() + + receipt.deposit_nonce.map_or(0, |nonce| nonce.length()) + + receipt.deposit_receipt_version.map_or(0, |version| version.length()) } } } @@ -276,7 +276,7 @@ impl RlpDecodableReceipt for OpReceipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, OpTxType::Legacy) + return Self::rlp_decode_inner(buf, OpTxType::Legacy); } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -296,8 +296,8 @@ impl RlpDecodableReceipt for OpReceipt { impl Encodable2718 for OpReceipt { fn encode_2718_len(&self) -> usize { - !self.tx_type().is_legacy() as usize + - self.rlp_header_inner_without_bloom().length_with_payload() + !self.tx_type().is_legacy() as usize + + self.rlp_header_inner_without_bloom().length_with_payload() } fn encode_2718(&self, out: &mut dyn BufMut) { diff --git a/crates/optimism/primitives/src/transaction/signed.rs b/crates/optimism/primitives/src/transaction/signed.rs index 2a345229a6..164b6167ed 100644 --- a/crates/optimism/primitives/src/transaction/signed.rs +++ b/crates/optimism/primitives/src/transaction/signed.rs @@ -108,7 +108,7 @@ impl SignerRecoverable for OpTransactionSigned { // Optimism's Deposit transaction does not have a signature. Directly return the // `from` address. if let OpTypedTransaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Ok(from) + return Ok(from); } let Self { transaction, signature, .. } = self; @@ -120,7 +120,7 @@ impl SignerRecoverable for OpTransactionSigned { // Optimism's Deposit transaction does not have a signature. Directly return the // `from` address. if let OpTypedTransaction::Deposit(TxDeposit { from, .. }) = &self.transaction { - return Ok(*from) + return Ok(*from); } let Self { transaction, signature, .. } = self; @@ -396,9 +396,9 @@ impl Typed2718 for OpTransactionSigned { impl PartialEq for OpTransactionSigned { fn eq(&self, other: &Self) -> bool { - self.signature == other.signature && - self.transaction == other.transaction && - self.tx_hash() == other.tx_hash() + self.signature == other.signature + && self.transaction == other.transaction + && self.tx_hash() == other.tx_hash() } } diff --git a/crates/optimism/rpc/src/error.rs b/crates/optimism/rpc/src/error.rs index f544586349..8defe79ffd 100644 --- a/crates/optimism/rpc/src/error.rs +++ b/crates/optimism/rpc/src/error.rs @@ -50,9 +50,9 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { match err { OpEthApiError::Eth(err) => err.into(), OpEthApiError::InvalidTransaction(err) => err.into(), - OpEthApiError::Evm(_) | - OpEthApiError::L1BlockFeeError | - OpEthApiError::L1BlockGasError => internal_rpc_err(err.to_string()), + OpEthApiError::Evm(_) + | OpEthApiError::L1BlockFeeError + | OpEthApiError::L1BlockGasError => internal_rpc_err(err.to_string()), OpEthApiError::Sequencer(err) => err.into(), } } @@ -75,8 +75,8 @@ pub enum OpInvalidTransactionError { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(err: OpInvalidTransactionError) -> Self { match err { - OpInvalidTransactionError::DepositSystemTxPostRegolith | - OpInvalidTransactionError::HaltedDepositPostRegolith => { + OpInvalidTransactionError::DepositSystemTxPostRegolith + | OpInvalidTransactionError::HaltedDepositPostRegolith => { rpc_err(EthRpcErrorCode::TransactionRejected.code(), err.to_string(), None) } OpInvalidTransactionError::TxConditionalErr(_) => err.into(), diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index 34ce4081b2..b74e69f47a 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -85,7 +85,7 @@ where .build()) }) .collect::, Self::Error>>() - .map(Some) + .map(Some); } Ok(None) diff --git a/crates/optimism/rpc/src/eth/ext.rs b/crates/optimism/rpc/src/eth/ext.rs index 46008d0608..6227aa123d 100644 --- a/crates/optimism/rpc/src/eth/ext.rs +++ b/crates/optimism/rpc/src/eth/ext.rs @@ -138,8 +138,8 @@ where .ok_or_else(header_not_found)?; // Ensure that the condition can still be met by checking the max bounds - if condition.has_exceeded_block_number(header.header().number()) || - condition.has_exceeded_timestamp(header.header().timestamp()) + if condition.has_exceeded_block_number(header.header().number()) + || condition.has_exceeded_timestamp(header.header().timestamp()) { return Err(TxConditionalErr::InvalidCondition.into()); } diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 30422316ad..3d72493559 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -57,7 +57,7 @@ where tracing::warn!(target: "rpc::eth", %err, %hash, "successfully sent tx to sequencer, but failed to persist in local tx pool"); }); - return Ok(hash) + return Ok(hash); } // submit the transaction to the pool with a `Local` origin diff --git a/crates/optimism/rpc/src/historical.rs b/crates/optimism/rpc/src/historical.rs index 0f8824882b..136e089d87 100644 --- a/crates/optimism/rpc/src/historical.rs +++ b/crates/optimism/rpc/src/historical.rs @@ -139,12 +139,12 @@ where "eth_getBlockByNumber" | "eth_getBlockByHash" => { parse_block_id_from_params(&req.params(), 0) } - "eth_getBalance" | - "eth_getCode" | - "eth_getTransactionCount" | - "eth_call" | - "eth_estimateGas" | - "eth_createAccessList" => parse_block_id_from_params(&req.params(), 1), + "eth_getBalance" + | "eth_getCode" + | "eth_getTransactionCount" + | "eth_call" + | "eth_estimateGas" + | "eth_createAccessList" => parse_block_id_from_params(&req.params(), 1), "eth_getStorageAt" | "eth_getProof" => parse_block_id_from_params(&req.params(), 2), _ => None, }; diff --git a/crates/optimism/txpool/src/supervisor/client.rs b/crates/optimism/txpool/src/supervisor/client.rs index 4cc67685b5..6829c94ae8 100644 --- a/crates/optimism/txpool/src/supervisor/client.rs +++ b/crates/optimism/txpool/src/supervisor/client.rs @@ -103,7 +103,7 @@ impl SupervisorClient { // Interop check if !is_interop_active { // No cross chain tx allowed before interop - return Some(Err(InvalidCrossTx::CrossChainTxPreInterop)) + return Some(Err(InvalidCrossTx::CrossChainTxPreInterop)); } if let Err(err) = self diff --git a/crates/optimism/txpool/src/transaction.rs b/crates/optimism/txpool/src/transaction.rs index 6cbc645fe5..9358d78589 100644 --- a/crates/optimism/txpool/src/transaction.rs +++ b/crates/optimism/txpool/src/transaction.rs @@ -109,7 +109,7 @@ impl MaybeInteropTransaction for OpPooledTransaction fn interop_deadline(&self) -> Option { let interop = self.interop.load(Ordering::Relaxed); if interop > NO_INTEROP_TX { - return Some(interop) + return Some(interop); } None } diff --git a/crates/optimism/txpool/src/validator.rs b/crates/optimism/txpool/src/validator.rs index 6c986e9498..45c3e03ba5 100644 --- a/crates/optimism/txpool/src/validator.rs +++ b/crates/optimism/txpool/src/validator.rs @@ -187,7 +187,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ) + ); } // Interop cross tx validation @@ -199,7 +199,7 @@ where } err => InvalidPoolTransactionError::Other(Box::new(err)), }; - return TransactionValidationOutcome::Invalid(transaction, err) + return TransactionValidationOutcome::Invalid(transaction, err); } Some(Ok(_)) => { // valid interop tx @@ -222,7 +222,7 @@ where ) -> TransactionValidationOutcome { if !self.requires_l1_data_gas_fee() { // no need to check L1 gas fee - return outcome + return outcome; } // ensure that the account has enough balance to cover the L1 gas cost if let TransactionValidationOutcome::Valid { @@ -259,7 +259,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ) + ); } return TransactionValidationOutcome::Valid { @@ -269,7 +269,7 @@ where propagate, bytecode_hash, authorities, - } + }; } outcome } diff --git a/crates/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 470e34bee3..06c7895cf9 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -377,7 +377,7 @@ where // check if the deadline is reached if this.deadline.as_mut().poll(cx).is_ready() { trace!(target: "payload_builder", "payload building deadline reached"); - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } // check if the interval is reached @@ -597,7 +597,7 @@ where if let Some(best) = this.best_payload.take() { debug!(target: "payload_builder", "resolving best payload"); - return Poll::Ready(Ok(best)) + return Poll::Ready(Ok(best)); } if let Some(fut) = Pin::new(&mut this.empty_payload).as_pin_mut() { @@ -613,12 +613,12 @@ where Poll::Ready(res) } Err(err) => Poll::Ready(Err(err.into())), - } + }; } } if this.is_empty() { - return Poll::Ready(Err(PayloadBuilderError::MissingPayload)) + return Poll::Ready(Err(PayloadBuilderError::MissingPayload)); } Poll::Pending diff --git a/crates/payload/builder-primitives/src/events.rs b/crates/payload/builder-primitives/src/events.rs index d14d967500..ee6f09723e 100644 --- a/crates/payload/builder-primitives/src/events.rs +++ b/crates/payload/builder-primitives/src/events.rs @@ -69,14 +69,14 @@ impl Stream for BuiltPayloadStream { Some(Ok(Events::BuiltPayload(payload))) => Poll::Ready(Some(payload)), Some(Ok(Events::Attributes(_))) => { // ignoring attributes - continue + continue; } Some(Err(err)) => { debug!(%err, "payload event stream lagging behind"); - continue + continue; } None => Poll::Ready(None), - } + }; } } } @@ -99,14 +99,14 @@ impl Stream for PayloadAttributeStream { Some(Ok(Events::Attributes(attr))) => Poll::Ready(Some(attr)), Some(Ok(Events::BuiltPayload(_))) => { // ignoring payloads - continue + continue; } Some(Err(err)) => { debug!(%err, "payload event stream lagging behind"); - continue + continue; } None => Poll::Ready(None), - } + }; } } } diff --git a/crates/payload/builder/src/noop.rs b/crates/payload/builder/src/noop.rs index 6047bffa8b..54b64cd522 100644 --- a/crates/payload/builder/src/noop.rs +++ b/crates/payload/builder/src/noop.rs @@ -42,7 +42,7 @@ where let this = self.get_mut(); loop { let Some(cmd) = ready!(this.command_rx.poll_next_unpin(cx)) else { - return Poll::Ready(()) + return Poll::Ready(()); }; match cmd { PayloadServiceCommand::BuildNewPayload(attr, tx) => { diff --git a/crates/payload/builder/src/service.rs b/crates/payload/builder/src/service.rs index 3c4daf2555..05866f6871 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -440,7 +440,7 @@ where } if !new_job { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/payload/primitives/src/lib.rs b/crates/payload/primitives/src/lib.rs index fb78cae16c..dc21a9fa56 100644 --- a/crates/payload/primitives/src/lib.rs +++ b/crates/payload/primitives/src/lib.rs @@ -96,7 +96,7 @@ pub fn validate_payload_timestamp( // // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // payload or payloadAttributes is greater or equal to the Cancun activation timestamp. - return Err(EngineObjectValidationError::UnsupportedFork) + return Err(EngineObjectValidationError::UnsupportedFork); } if version.is_v3() && !is_cancun { @@ -118,7 +118,7 @@ pub fn validate_payload_timestamp( // // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // the payload does not fall within the time frame of the Cancun fork. - return Err(EngineObjectValidationError::UnsupportedFork) + return Err(EngineObjectValidationError::UnsupportedFork); } let is_prague = chain_spec.is_prague_active_at_timestamp(timestamp); @@ -141,7 +141,7 @@ pub fn validate_payload_timestamp( // // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // the payload does not fall within the time frame of the Prague fork. - return Err(EngineObjectValidationError::UnsupportedFork) + return Err(EngineObjectValidationError::UnsupportedFork); } let is_osaka = chain_spec.is_osaka_active_at_timestamp(timestamp); @@ -153,7 +153,7 @@ pub fn validate_payload_timestamp( // // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the // built payload does not fall within the time frame of the Osaka fork. - return Err(EngineObjectValidationError::UnsupportedFork) + return Err(EngineObjectValidationError::UnsupportedFork); } Ok(()) @@ -175,20 +175,20 @@ pub fn validate_withdrawals_presence( EngineApiMessageVersion::V1 => { if has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)) + .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)); } } - EngineApiMessageVersion::V2 | - EngineApiMessageVersion::V3 | - EngineApiMessageVersion::V4 | - EngineApiMessageVersion::V5 => { + EngineApiMessageVersion::V2 + | EngineApiMessageVersion::V3 + | EngineApiMessageVersion::V4 + | EngineApiMessageVersion::V5 => { if is_shanghai_active && !has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); } if !is_shanghai_active && has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)) + .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)); } } }; @@ -279,13 +279,13 @@ pub fn validate_parent_beacon_block_root_presence( if has_parent_beacon_block_root { return Err(validation_kind.to_error( VersionSpecificValidationError::ParentBeaconBlockRootNotSupportedBeforeV3, - )) + )); } } EngineApiMessageVersion::V3 | EngineApiMessageVersion::V4 | EngineApiMessageVersion::V5 => { if !has_parent_beacon_block_root { return Err(validation_kind - .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)) + .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)); } } }; @@ -452,20 +452,20 @@ pub fn validate_execution_requests(requests: &[Bytes]) -> Result<(), EngineObjec if request.len() <= 1 { return Err(EngineObjectValidationError::InvalidParams( "EmptyExecutionRequest".to_string().into(), - )) + )); } let request_type = request[0]; if Some(request_type) < last_request_type { return Err(EngineObjectValidationError::InvalidParams( "OutOfOrderExecutionRequest".to_string().into(), - )) + )); } if Some(request_type) == last_request_type { return Err(EngineObjectValidationError::InvalidParams( "DuplicatedExecutionRequestType".to_string().into(), - )) + )); } last_request_type = Some(request_type); diff --git a/crates/payload/util/src/traits.rs b/crates/payload/util/src/traits.rs index 7d076d3687..2c9954fa3c 100644 --- a/crates/payload/util/src/traits.rs +++ b/crates/payload/util/src/traits.rs @@ -78,9 +78,9 @@ where loop { let tx = self.best.next()?; if self.invalid.contains(tx.sender_ref()) { - continue + continue; } - return Some(tx.transaction.clone()) + return Some(tx.transaction.clone()); } } diff --git a/crates/payload/validator/src/cancun.rs b/crates/payload/validator/src/cancun.rs index 5a4deb139f..0427bcdcfd 100644 --- a/crates/payload/validator/src/cancun.rs +++ b/crates/payload/validator/src/cancun.rs @@ -38,28 +38,28 @@ pub fn ensure_well_formed_header_and_sidecar_fields( if is_cancun_active { if block.blob_gas_used().is_none() { // cancun active but blob gas used not present - return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed) + return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed); } if block.excess_blob_gas().is_none() { // cancun active but excess blob gas not present - return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas) + return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas); } if cancun_sidecar_fields.is_none() { // cancun active but cancun fields not present - return Err(PayloadError::PostCancunWithoutCancunFields) + return Err(PayloadError::PostCancunWithoutCancunFields); } } else { if block.blob_gas_used().is_some() { // cancun not active but blob gas used present - return Err(PayloadError::PreCancunBlockWithBlobGasUsed) + return Err(PayloadError::PreCancunBlockWithBlobGasUsed); } if block.excess_blob_gas().is_some() { // cancun not active but excess blob gas present - return Err(PayloadError::PreCancunBlockWithExcessBlobGas) + return Err(PayloadError::PreCancunBlockWithExcessBlobGas); } if cancun_sidecar_fields.is_some() { // cancun not active but cancun fields present - return Err(PayloadError::PreCancunWithCancunFields) + return Err(PayloadError::PreCancunWithCancunFields); } } @@ -80,7 +80,7 @@ pub fn ensure_well_formed_transactions_field_with_sidecar( if let Some(versioned_hashes) = cancun_sidecar_fields.map(|fields| &fields.versioned_hashes) { if num_blob_versioned_hashes != versioned_hashes.len() { // Number of blob versioned hashes does not match - return Err(PayloadError::InvalidVersionedHashes) + return Err(PayloadError::InvalidVersionedHashes); } // we can use `zip` safely here because we already compared their length for (payload_versioned_hash, block_versioned_hash) in versioned_hashes.iter().zip(block_body.blob_versioned_hashes_iter()) { if payload_versioned_hash != block_versioned_hash { - return Err(PayloadError::InvalidVersionedHashes) + return Err(PayloadError::InvalidVersionedHashes); } } } else { // No Cancun fields, if block includes any blobs, this is an error if num_blob_versioned_hashes > 0 { - return Err(PayloadError::InvalidVersionedHashes) + return Err(PayloadError::InvalidVersionedHashes); } } diff --git a/crates/payload/validator/src/prague.rs b/crates/payload/validator/src/prague.rs index d663469a82..cbd6e7333a 100644 --- a/crates/payload/validator/src/prague.rs +++ b/crates/payload/validator/src/prague.rs @@ -27,7 +27,7 @@ pub const fn ensure_well_formed_sidecar_fields( ) -> Result<(), PayloadError> { if !is_prague_active && prague_fields.is_some() { // prague _not_ active but prague fields present - return Err(PayloadError::PrePragueBlockRequests) + return Err(PayloadError::PrePragueBlockRequests); } Ok(()) @@ -41,7 +41,7 @@ pub fn ensure_well_formed_transactions_field( is_prague_active: bool, ) -> Result<(), PayloadError> { if !is_prague_active && block_body.has_eip7702_transactions() { - return Err(PayloadError::PrePragueBlockWithEip7702Transactions) + return Err(PayloadError::PrePragueBlockWithEip7702Transactions); } Ok(()) diff --git a/crates/payload/validator/src/shanghai.rs b/crates/payload/validator/src/shanghai.rs index 743c96fa1b..f88c4c45c0 100644 --- a/crates/payload/validator/src/shanghai.rs +++ b/crates/payload/validator/src/shanghai.rs @@ -12,11 +12,11 @@ pub fn ensure_well_formed_fields( if is_shanghai_active { if block_body.withdrawals().is_none() { // shanghai active but no withdrawals present - return Err(PayloadError::PostShanghaiBlockWithoutWithdrawals) + return Err(PayloadError::PostShanghaiBlockWithoutWithdrawals); } } else if block_body.withdrawals().is_some() { // shanghai not active but withdrawals present - return Err(PayloadError::PreShanghaiBlockWithWithdrawals) + return Err(PayloadError::PreShanghaiBlockWithWithdrawals); } Ok(()) diff --git a/crates/primitives-traits/src/account.rs b/crates/primitives-traits/src/account.rs index 34a533fc4a..ee4b3be980 100644 --- a/crates/primitives-traits/src/account.rs +++ b/crates/primitives-traits/src/account.rs @@ -46,9 +46,9 @@ impl Account { /// After `SpuriousDragon` empty account is defined as account with nonce == 0 && balance == 0 /// && bytecode = None (or hash is [`KECCAK_EMPTY`]). pub fn is_empty(&self) -> bool { - self.nonce == 0 && - self.balance.is_zero() && - self.bytecode_hash.is_none_or(|hash| hash == KECCAK_EMPTY) + self.nonce == 0 + && self.balance.is_zero() + && self.bytecode_hash.is_none_or(|hash| hash == KECCAK_EMPTY) } /// Returns an account bytecode's hash. diff --git a/crates/primitives-traits/src/block/mod.rs b/crates/primitives-traits/src/block/mod.rs index 35ecb17144..11ce3fc78e 100644 --- a/crates/primitives-traits/src/block/mod.rs +++ b/crates/primitives-traits/src/block/mod.rs @@ -169,7 +169,7 @@ pub trait Block: } else { // Fall back to recovery if lengths don't match let Ok(senders) = self.body().recover_signers_unchecked() else { - return Err(BlockRecoveryError::new(self)) + return Err(BlockRecoveryError::new(self)); }; senders }; @@ -195,7 +195,7 @@ pub trait Block: ::Transaction: SignedTransaction, { let Ok(signers) = self.body().recover_signers() else { - return Err(BlockRecoveryError::new(self)) + return Err(BlockRecoveryError::new(self)); }; Ok(RecoveredBlock::new_unhashed(self, signers)) } diff --git a/crates/primitives-traits/src/block/recovered.rs b/crates/primitives-traits/src/block/recovered.rs index 7da2bcf373..ee4faa8dfd 100644 --- a/crates/primitives-traits/src/block/recovered.rs +++ b/crates/primitives-traits/src/block/recovered.rs @@ -445,9 +445,9 @@ impl Eq for RecoveredBlock {} impl PartialEq for RecoveredBlock { fn eq(&self, other: &Self) -> bool { - self.hash_ref().eq(other.hash_ref()) && - self.block.eq(&other.block) && - self.senders.eq(&other.senders) + self.hash_ref().eq(other.hash_ref()) + && self.block.eq(&other.block) + && self.senders.eq(&other.senders) } } diff --git a/crates/primitives-traits/src/block/sealed.rs b/crates/primitives-traits/src/block/sealed.rs index dd0bc0b665..61663dcb6f 100644 --- a/crates/primitives-traits/src/block/sealed.rs +++ b/crates/primitives-traits/src/block/sealed.rs @@ -266,7 +266,7 @@ impl SealedBlock { return Err(GotExpected { got: calculated_root, expected: self.header().transactions_root(), - }) + }); } Ok(()) diff --git a/crates/primitives-traits/src/size.rs b/crates/primitives-traits/src/size.rs index 21b192b6bc..24ba3bb200 100644 --- a/crates/primitives-traits/src/size.rs +++ b/crates/primitives-traits/src/size.rs @@ -72,9 +72,9 @@ impl_in_mem_size_size_of!(op_alloy_consensus::OpTxType); impl InMemorySize for alloy_consensus::Receipt { fn size(&self) -> usize { let Self { status, cumulative_gas_used, logs } = self; - core::mem::size_of_val(status) + - core::mem::size_of_val(cumulative_gas_used) + - logs.capacity() * core::mem::size_of::() + core::mem::size_of_val(status) + + core::mem::size_of_val(cumulative_gas_used) + + logs.capacity() * core::mem::size_of::() } } @@ -94,11 +94,12 @@ impl InMemorySize for alloy_consensus::BlockBo /// Calculates a heuristic for the in-memory size of the block body #[inline] fn size(&self) -> usize { - self.transactions.iter().map(T::size).sum::() + - self.transactions.capacity() * core::mem::size_of::() + - self.ommers.iter().map(H::size).sum::() + - self.ommers.capacity() * core::mem::size_of::
() + - self.withdrawals + self.transactions.iter().map(T::size).sum::() + + self.transactions.capacity() * core::mem::size_of::() + + self.ommers.iter().map(H::size).sum::() + + self.ommers.capacity() * core::mem::size_of::
() + + self + .withdrawals .as_ref() .map_or(core::mem::size_of::>(), Withdrawals::total_size) } @@ -132,9 +133,9 @@ mod op { impl InMemorySize for op_alloy_consensus::OpDepositReceipt { fn size(&self) -> usize { let Self { inner, deposit_nonce, deposit_receipt_version } = self; - inner.size() + - core::mem::size_of_val(deposit_nonce) + - core::mem::size_of_val(deposit_receipt_version) + inner.size() + + core::mem::size_of_val(deposit_nonce) + + core::mem::size_of_val(deposit_receipt_version) } } diff --git a/crates/primitives-traits/src/withdrawal.rs b/crates/primitives-traits/src/withdrawal.rs index 0849ab6202..8c436c0090 100644 --- a/crates/primitives-traits/src/withdrawal.rs +++ b/crates/primitives-traits/src/withdrawal.rs @@ -40,10 +40,10 @@ mod tests { impl PartialEq for RethWithdrawal { fn eq(&self, other: &Withdrawal) -> bool { - self.index == other.index && - self.validator_index == other.validator_index && - self.address == other.address && - self.amount == other.amount + self.index == other.index + && self.validator_index == other.validator_index + && self.address == other.address + && self.amount == other.amount } } diff --git a/crates/prune/prune/src/db_ext.rs b/crates/prune/prune/src/db_ext.rs index 63ab87c446..7c7e05c1fb 100644 --- a/crates/prune/prune/src/db_ext.rs +++ b/crates/prune/prune/src/db_ext.rs @@ -33,7 +33,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { table = %T::NAME, "Pruning limit reached" ); - break + break; } let row = cursor.seek_exact(key)?; @@ -76,7 +76,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { table = %T::NAME, "Pruning limit reached" ); - break false + break false; } let done = self.prune_table_with_range_step( @@ -87,7 +87,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { )?; if done { - break true + break true; } deleted_entries += 1; }; diff --git a/crates/prune/prune/src/pruner.rs b/crates/prune/prune/src/pruner.rs index 60fa7a8b5c..f357aba7cf 100644 --- a/crates/prune/prune/src/pruner.rs +++ b/crates/prune/prune/src/pruner.rs @@ -120,13 +120,13 @@ where let Some(tip_block_number) = self.adjust_tip_block_number_to_finished_exex_height(tip_block_number) else { - return Ok(PruneProgress::Finished.into()) + return Ok(PruneProgress::Finished.into()); }; if tip_block_number == 0 { self.previous_tip_block_number = Some(tip_block_number); debug!(target: "pruner", %tip_block_number, "Nothing to prune yet"); - return Ok(PruneProgress::Finished.into()) + return Ok(PruneProgress::Finished.into()); } self.event_sender.notify(PrunerEvent::Started { tip_block_number }); @@ -189,7 +189,7 @@ where for segment in &self.segments { if limiter.is_limit_reached() { - break + break; } if let Some((to_block, prune_mode)) = segment @@ -270,14 +270,14 @@ where let Some(tip_block_number) = self.adjust_tip_block_number_to_finished_exex_height(tip_block_number) else { - return false + return false; }; // Saturating subtraction is needed for the case when the chain was reverted, meaning // current block number might be less than the previous tip block number. // If that's the case, no pruning is needed as outdated data is also reverted. - if tip_block_number.saturating_sub(self.previous_tip_block_number.unwrap_or_default()) >= - self.min_block_interval as u64 + if tip_block_number.saturating_sub(self.previous_tip_block_number.unwrap_or_default()) + >= self.min_block_interval as u64 { debug!( target: "pruner", diff --git a/crates/prune/prune/src/segments/mod.rs b/crates/prune/prune/src/segments/mod.rs index c34e3a322a..c2bfaaa2b9 100644 --- a/crates/prune/prune/src/segments/mod.rs +++ b/crates/prune/prune/src/segments/mod.rs @@ -95,7 +95,7 @@ impl PruneInput { // Prevents a scenario where the pruner correctly starts at a finalized block, // but the first transaction (tx_num = 0) only appears on a non-finalized one. // Should only happen on a test/hive scenario. - return Ok(None) + return Ok(None); } last_tx } @@ -104,7 +104,7 @@ impl PruneInput { let range = from_tx_number..=to_tx_number; if range.is_empty() { - return Ok(None) + return Ok(None); } Ok(Some(range)) @@ -122,7 +122,7 @@ impl PruneInput { let from_block = self.get_start_next_block_range(); let range = from_block..=self.to_block; if range.is_empty() { - return None + return None; } Some(range) diff --git a/crates/prune/prune/src/segments/receipts.rs b/crates/prune/prune/src/segments/receipts.rs index 2c94b5e4a8..2cfe72eddb 100644 --- a/crates/prune/prune/src/segments/receipts.rs +++ b/crates/prune/prune/src/segments/receipts.rs @@ -29,7 +29,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No receipts to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; let tx_range_end = *tx_range.end(); @@ -161,8 +161,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize + - input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/set.rs b/crates/prune/prune/src/segments/set.rs index 52e6ee7544..3fd9bf466c 100644 --- a/crates/prune/prune/src/segments/set.rs +++ b/crates/prune/prune/src/segments/set.rs @@ -34,7 +34,7 @@ impl SegmentSet { /// Adds new [Segment] to collection if it's [Some]. pub fn segment_opt + 'static>(self, segment: Option) -> Self { if let Some(segment) = segment { - return self.segment(segment) + return self.segment(segment); } self } diff --git a/crates/prune/prune/src/segments/static_file/headers.rs b/crates/prune/prune/src/segments/static_file/headers.rs index be4e50fe48..1c80850898 100644 --- a/crates/prune/prune/src/segments/static_file/headers.rs +++ b/crates/prune/prune/src/segments/static_file/headers.rs @@ -54,7 +54,7 @@ impl> Segment (*range.start(), *range.end()), None => { trace!(target: "pruner", "No headers to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; @@ -144,7 +144,7 @@ where type Item = Result; fn next(&mut self) -> Option { if self.limiter.is_limit_reached() { - return None + return None; } let mut pruned_block_headers = None; @@ -157,7 +157,7 @@ where &mut |_| false, &mut |row| pruned_block_headers = Some(row.0), ) { - return Some(Err(err.into())) + return Some(Err(err.into())); } if let Err(err) = self.provider.tx_ref().prune_table_with_range_step( @@ -166,7 +166,7 @@ where &mut |_| false, &mut |row| pruned_block_td = Some(row.0), ) { - return Some(Err(err.into())) + return Some(Err(err.into())); } if let Err(err) = self.provider.tx_ref().prune_table_with_range_step( @@ -175,13 +175,13 @@ where &mut |_| false, &mut |row| pruned_block_canonical = Some(row.0), ) { - return Some(Err(err.into())) + return Some(Err(err.into())); } if ![pruned_block_headers, pruned_block_td, pruned_block_canonical].iter().all_equal() { return Some(Err(PrunerError::InconsistentData( "All headers-related tables should be pruned up to the same height", - ))) + ))); } pruned_block_headers.map(move |block| { @@ -278,8 +278,8 @@ mod tests { provider.commit().expect("commit"); let last_pruned_block_number = to_block.min( - next_block_number_to_prune + - (input.limiter.deleted_entries_limit().unwrap() / HEADER_TABLES_TO_PRUNE - 1) + next_block_number_to_prune + + (input.limiter.deleted_entries_limit().unwrap() / HEADER_TABLES_TO_PRUNE - 1) as u64, ); diff --git a/crates/prune/prune/src/segments/static_file/transactions.rs b/crates/prune/prune/src/segments/static_file/transactions.rs index 409e7f9b3d..21b4f9b262 100644 --- a/crates/prune/prune/src/segments/static_file/transactions.rs +++ b/crates/prune/prune/src/segments/static_file/transactions.rs @@ -53,7 +53,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transactions to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; @@ -178,8 +178,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize + - input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/user/account_history.rs b/crates/prune/prune/src/segments/user/account_history.rs index 7780a9e07e..75ab52518b 100644 --- a/crates/prune/prune/src/segments/user/account_history.rs +++ b/crates/prune/prune/src/segments/user/account_history.rs @@ -51,7 +51,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No account history to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; let range_end = *range.end(); @@ -65,7 +65,7 @@ where return Ok(SegmentOutput::not_done( limiter.interrupt_reason(), input.previous_checkpoint.map(SegmentOutputCheckpoint::from_prune_checkpoint), - )) + )); } let mut last_changeset_pruned_block = None; @@ -232,8 +232,8 @@ mod tests { .iter() .enumerate() .skip_while(|(i, (block_number, _))| { - *i < deleted_entries_limit / ACCOUNT_HISTORY_TABLES_TO_PRUNE * run && - *block_number <= to_block as usize + *i < deleted_entries_limit / ACCOUNT_HISTORY_TABLES_TO_PRUNE * run + && *block_number <= to_block as usize }) .next() .map(|(i, _)| i) diff --git a/crates/prune/prune/src/segments/user/history.rs b/crates/prune/prune/src/segments/user/history.rs index 9d95b2fd3b..91f825370f 100644 --- a/crates/prune/prune/src/segments/user/history.rs +++ b/crates/prune/prune/src/segments/user/history.rs @@ -49,7 +49,7 @@ where let Some((key, block_nums)) = shard.map(|(k, v)| Result::<_, DatabaseError>::Ok((k.key()?, v))).transpose()? else { - break + break; }; if key_matches(&key, &sharded_key) { @@ -60,7 +60,7 @@ where } } else { // If such shard doesn't exist, skip to the next sharded key - break 'shard + break 'shard; } shard = cursor.next()?; diff --git a/crates/prune/prune/src/segments/user/receipts_by_logs.rs b/crates/prune/prune/src/segments/user/receipts_by_logs.rs index b413a70394..5e4510f737 100644 --- a/crates/prune/prune/src/segments/user/receipts_by_logs.rs +++ b/crates/prune/prune/src/segments/user/receipts_by_logs.rs @@ -141,7 +141,7 @@ where ?block_range, "No receipts to prune." ); - continue + continue; } }; let tx_range = from_tx_number..=tx_range_end; @@ -155,10 +155,11 @@ where tx_range, &mut limiter, |(tx_num, receipt)| { - let skip = num_addresses > 0 && - receipt.logs().iter().any(|log| { - filtered_addresses[..num_addresses].contains(&&log.address) - }); + let skip = num_addresses > 0 + && receipt + .logs() + .iter() + .any(|log| filtered_addresses[..num_addresses].contains(&&log.address)); if skip { last_skipped_transaction = *tx_num; @@ -190,7 +191,7 @@ where if limiter.is_limit_reached() { done &= end_block == to_block; - break + break; } from_tx_number = last_pruned_transaction + 1; @@ -336,8 +337,8 @@ mod tests { assert_eq!( db.table::().unwrap().len(), - blocks.iter().map(|block| block.transaction_count()).sum::() - - ((pruned_tx + 1) - unprunable) as usize + blocks.iter().map(|block| block.transaction_count()).sum::() + - ((pruned_tx + 1) - unprunable) as usize ); output.progress.is_finished() @@ -354,8 +355,8 @@ mod tests { // Either we only find our contract, or the receipt is part of the unprunable receipts // set by tip - 128 assert!( - receipt.logs.iter().any(|l| l.address == deposit_contract_addr) || - provider.transaction_block(tx_num).unwrap().unwrap() > tip - 128, + receipt.logs.iter().any(|l| l.address == deposit_contract_addr) + || provider.transaction_block(tx_num).unwrap().unwrap() > tip - 128, ); } } diff --git a/crates/prune/prune/src/segments/user/sender_recovery.rs b/crates/prune/prune/src/segments/user/sender_recovery.rs index f379fb9951..99f2656d8e 100644 --- a/crates/prune/prune/src/segments/user/sender_recovery.rs +++ b/crates/prune/prune/src/segments/user/sender_recovery.rs @@ -43,7 +43,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transaction senders to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; let tx_range_end = *tx_range.end(); @@ -162,8 +162,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize + - input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/user/storage_history.rs b/crates/prune/prune/src/segments/user/storage_history.rs index aa9cb84644..21de15a17b 100644 --- a/crates/prune/prune/src/segments/user/storage_history.rs +++ b/crates/prune/prune/src/segments/user/storage_history.rs @@ -53,7 +53,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No storage history to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } }; let range_end = *range.end(); @@ -67,7 +67,7 @@ where return Ok(SegmentOutput::not_done( limiter.interrupt_reason(), input.previous_checkpoint.map(SegmentOutputCheckpoint::from_prune_checkpoint), - )) + )); } let mut last_changeset_pruned_block = None; @@ -240,8 +240,8 @@ mod tests { .iter() .enumerate() .skip_while(|(i, (block_number, _, _))| { - *i < deleted_entries_limit / STORAGE_HISTORY_TABLES_TO_PRUNE * run && - *block_number <= to_block as usize + *i < deleted_entries_limit / STORAGE_HISTORY_TABLES_TO_PRUNE * run + && *block_number <= to_block as usize }) .next() .map(|(i, _)| i) diff --git a/crates/prune/prune/src/segments/user/transaction_lookup.rs b/crates/prune/prune/src/segments/user/transaction_lookup.rs index 92a69dfd12..ed7e92cebb 100644 --- a/crates/prune/prune/src/segments/user/transaction_lookup.rs +++ b/crates/prune/prune/src/segments/user/transaction_lookup.rs @@ -43,12 +43,12 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transaction lookup entries to prune"); - return Ok(SegmentOutput::done()) + return Ok(SegmentOutput::done()); } } .into_inner(); - let tx_range = start..= - Some(end) + let tx_range = start + ..=Some(end) .min(input.limiter.deleted_entries_limit_left().map(|left| start + left as u64 - 1)) .unwrap(); let tx_range_end = *tx_range.end(); @@ -65,7 +65,7 @@ where if hashes.len() != tx_count { return Err(PrunerError::InconsistentData( "Unexpected number of transaction hashes retrieved by transaction number range", - )) + )); } let mut limiter = input.limiter; @@ -187,8 +187,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize + - input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/types/src/lib.rs b/crates/prune/types/src/lib.rs index c1d268a0fb..761e5c3a00 100644 --- a/crates/prune/types/src/lib.rs +++ b/crates/prune/types/src/lib.rs @@ -77,8 +77,8 @@ impl ReceiptsLogPruneConfig { let block = base_block.max( mode.prune_target_block(tip, PruneSegment::ContractLogs, PrunePurpose::User)? .map(|(block, _)| block) - .unwrap_or_default() + - 1, + .unwrap_or_default() + + 1, ); map.entry(block).or_insert_with(Vec::new).push(address) diff --git a/crates/prune/types/src/mode.rs b/crates/prune/types/src/mode.rs index 42d34b30cc..78e2b80023 100644 --- a/crates/prune/types/src/mode.rs +++ b/crates/prune/types/src/mode.rs @@ -62,7 +62,7 @@ impl PruneMode { Self::Full => true, Self::Distance(distance) => { if *distance > tip { - return false + return false; } block < tip - *distance } diff --git a/crates/ress/protocol/src/connection.rs b/crates/ress/protocol/src/connection.rs index e97c4a0e90..e9a8fce59a 100644 --- a/crates/ress/protocol/src/connection.rs +++ b/crates/ress/protocol/src/connection.rs @@ -264,12 +264,12 @@ where let this = self.get_mut(); if this.terminated { - return Poll::Ready(None) + return Poll::Ready(None); } if !this.node_type_sent { this.node_type_sent = true; - return Poll::Ready(Some(RessProtocolMessage::node_type(this.node_type).encoded())) + return Poll::Ready(Some(RessProtocolMessage::node_type(this.node_type).encoded())); } 'conn: loop { diff --git a/crates/ress/protocol/src/provider.rs b/crates/ress/protocol/src/provider.rs index bac8b1f5f0..1e3709e082 100644 --- a/crates/ress/protocol/src/provider.rs +++ b/crates/ress/protocol/src/provider.rs @@ -21,11 +21,11 @@ pub trait RessProtocolProvider: Send + Sync { block_hash = header.parent_hash; total_bytes += header.length(); headers.push(header); - if headers.len() >= request.limit as usize || - headers.len() >= MAX_HEADERS_SERVE || - total_bytes > SOFT_RESPONSE_LIMIT + if headers.len() >= request.limit as usize + || headers.len() >= MAX_HEADERS_SERVE + || total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } Ok(headers) @@ -43,10 +43,10 @@ pub trait RessProtocolProvider: Send + Sync { total_bytes += body.length(); bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } Ok(bodies) diff --git a/crates/ress/protocol/tests/it/e2e.rs b/crates/ress/protocol/tests/it/e2e.rs index 5259e763a5..00b5648f8c 100644 --- a/crates/ress/protocol/tests/it/e2e.rs +++ b/crates/ress/protocol/tests/it/e2e.rs @@ -66,7 +66,7 @@ async fn disconnect_on_stateful_pair() { peer0_event_listener.next().await.unwrap() { assert_eq!(peer_id, *handle.peers()[1].peer_id()); - break + break; } } @@ -76,7 +76,7 @@ async fn disconnect_on_stateful_pair() { peer1_event_listener.next().await.unwrap() { assert_eq!(peer_id, *handle.peers()[0].peer_id()); - break + break; } } } diff --git a/crates/ress/provider/src/lib.rs b/crates/ress/provider/src/lib.rs index 41318ebaaf..30f7c8ed1d 100644 --- a/crates/ress/provider/src/lib.rs +++ b/crates/ress/provider/src/lib.rs @@ -97,7 +97,7 @@ where /// Generate state witness pub fn generate_witness(&self, block_hash: B256) -> ProviderResult> { if let Some(witness) = self.witness_cache.lock().get(&block_hash).cloned() { - return Ok(witness.as_ref().clone()) + return Ok(witness.as_ref().clone()); } let block = @@ -107,7 +107,7 @@ where if best_block_number.saturating_sub(block.number()) > self.max_witness_window { return Err(ProviderError::TrieWitnessError( "witness target block exceeds maximum witness window".to_owned(), - )) + )); } let mut executed_ancestors = Vec::new(); @@ -136,7 +136,7 @@ where } let Some(executed) = executed else { - return Err(ProviderError::StateForHashNotFound(ancestor_hash)) + return Err(ProviderError::StateForHashNotFound(ancestor_hash)); }; ancestor_hash = executed.sealed_block().parent_hash(); executed_ancestors.push(executed); diff --git a/crates/ress/provider/src/pending_state.rs b/crates/ress/provider/src/pending_state.rs index 1c4c81e29e..bebf73b4e3 100644 --- a/crates/ress/provider/src/pending_state.rs +++ b/crates/ress/provider/src/pending_state.rs @@ -101,8 +101,8 @@ pub async fn maintain_pending_state

( { while let Some(event) = events.next().await { match event { - BeaconConsensusEngineEvent::CanonicalBlockAdded(block, _) | - BeaconConsensusEngineEvent::ForkBlockAdded(block, _) => { + BeaconConsensusEngineEvent::CanonicalBlockAdded(block, _) + | BeaconConsensusEngineEvent::ForkBlockAdded(block, _) => { trace!(target: "reth::ress_provider", block = ? block.recovered_block().num_hash(), "Insert block into pending state"); pending_state.insert_block(block); } @@ -122,9 +122,9 @@ pub async fn maintain_pending_state

( } } // ignore - BeaconConsensusEngineEvent::CanonicalChainCommitted(_, _) | - BeaconConsensusEngineEvent::BlockReceived(_) | - BeaconConsensusEngineEvent::LiveSyncProgress(_) => (), + BeaconConsensusEngineEvent::CanonicalChainCommitted(_, _) + | BeaconConsensusEngineEvent::BlockReceived(_) + | BeaconConsensusEngineEvent::LiveSyncProgress(_) => (), } } } diff --git a/crates/revm/src/cached.rs b/crates/revm/src/cached.rs index bf4bd6d5d1..cbc17fa969 100644 --- a/crates/revm/src/cached.rs +++ b/crates/revm/src/cached.rs @@ -235,20 +235,20 @@ mod tests { // Verify the combined state assert!( - primary.accounts.len() == 2 && - primary.contracts.len() == 2 && - primary.block_hashes.len() == 2, + primary.accounts.len() == 2 + && primary.contracts.len() == 2 + && primary.block_hashes.len() == 2, "All maps should contain 2 entries" ); // Verify specific entries assert!( - primary.accounts.contains_key(&address1) && - primary.accounts.contains_key(&address2) && - primary.contracts.contains_key(&hash1) && - primary.contracts.contains_key(&hash2) && - primary.block_hashes.get(&1) == Some(&hash1) && - primary.block_hashes.get(&2) == Some(&hash2), + primary.accounts.contains_key(&address1) + && primary.accounts.contains_key(&address2) + && primary.contracts.contains_key(&hash1) + && primary.contracts.contains_key(&hash2) + && primary.block_hashes.get(&1) == Some(&hash1) + && primary.block_hashes.get(&2) == Some(&hash2), "All expected entries should be present" ); } diff --git a/crates/rpc/ipc/src/server/connection.rs b/crates/rpc/ipc/src/server/connection.rs index 0734296b98..63582769af 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 19992ead49..b64c5be785 100644 --- a/crates/rpc/ipc/src/server/ipc.rs +++ b/crates/rpc/ipc/src/server/ipc.rs @@ -66,7 +66,7 @@ where while let Some(response) = pending_calls.next().await { if let Err(too_large) = batch_response.append(response) { - return Some(too_large.to_json().to_string()) + return Some(too_large.to_json().to_string()); } } @@ -138,7 +138,7 @@ where return Some( batch_response_error(Id::Null, reject_too_big_request(max_request_body_size as u32)) .to_string(), - ) + ); } // Single request or notification diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index 4205081e3d..46a60abb09 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 b1a4f4166b..b08db390ae 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -337,7 +337,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 c68cf84942..18098a7d16 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 4dcce346c0..343173e14d 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -1192,9 +1192,9 @@ impl RpcServerConfig { /// /// If no server is configured, no server will be launched on [`RpcServerConfig::start`]. pub const fn has_server(&self) -> bool { - self.http_server_config.is_some() || - self.ws_server_config.is_some() || - self.ipc_server_config.is_some() + self.http_server_config.is_some() + || self.ws_server_config.is_some() + || self.ipc_server_config.is_some() } /// Returns the [`SocketAddr`] of the http server @@ -1267,9 +1267,9 @@ impl RpcServerConfig { } // If both are configured on the same port, we combine them into one server. - if self.http_addr == self.ws_addr && - self.http_server_config.is_some() && - self.ws_server_config.is_some() + if self.http_addr == self.ws_addr + && self.http_server_config.is_some() + && self.ws_server_config.is_some() { let cors = match (self.ws_cors_domains.as_ref(), self.http_cors_domains.as_ref()) { (Some(ws_cors), Some(http_cors)) => { @@ -1642,7 +1642,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) } @@ -1654,7 +1654,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) } @@ -1666,7 +1666,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) } @@ -1982,8 +1982,8 @@ impl RpcServerHandle { "Bearer {}", secret .encode(&Claims { - iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + - Duration::from_secs(60)) + iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + + Duration::from_secs(60)) .as_secs(), exp: None, }) diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index d21d6f915a..1047b534a9 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -33,8 +33,8 @@ use std::collections::HashSet; fn is_unimplemented(err: jsonrpsee::core::client::Error) -> bool { match err { jsonrpsee::core::client::Error::Call(error_obj) => { - error_obj.code() == ErrorCode::InternalError.code() && - error_obj.message() == "unimplemented" + error_obj.code() == ErrorCode::InternalError.code() + && error_obj.message() == "unimplemented" } _ => false, } diff --git a/crates/rpc/rpc-convert/src/fees.rs b/crates/rpc/rpc-convert/src/fees.rs index 46f8fc8c20..e19a68d402 100644 --- a/crates/rpc/rpc-convert/src/fees.rs +++ b/crates/rpc/rpc-convert/src/fees.rs @@ -60,17 +60,17 @@ impl CallFees { let max_priority_fee_per_gas = max_priority_fee_per_gas.unwrap_or(U256::ZERO); // only enforce the fee cap if provided input is not zero - if !(max_fee.is_zero() && max_priority_fee_per_gas.is_zero()) && - max_fee < block_base_fee + if !(max_fee.is_zero() && max_priority_fee_per_gas.is_zero()) + && max_fee < block_base_fee { // `base_fee_per_gas` is greater than the `max_fee_per_gas` - return Err(CallFeesError::FeeCapTooLow) + return Err(CallFeesError::FeeCapTooLow); } if max_fee < max_priority_fee_per_gas { return Err( // `max_priority_fee_per_gas` is greater than the `max_fee_per_gas` CallFeesError::TipAboveFeeCap, - ) + ); } // ref Ok(min( @@ -125,7 +125,7 @@ impl CallFees { // Ensure blob_hashes are present if !has_blob_hashes { // Blob transaction but no blob hashes - return Err(CallFeesError::BlobTransactionMissingBlobHashes) + return Err(CallFeesError::BlobTransactionMissingBlobHashes); } Ok(Self { diff --git a/crates/rpc/rpc-convert/src/transaction.rs b/crates/rpc/rpc-convert/src/transaction.rs index 68dc1a2974..93592bab70 100644 --- a/crates/rpc/rpc-convert/src/transaction.rs +++ b/crates/rpc/rpc-convert/src/transaction.rs @@ -224,7 +224,7 @@ impl TryIntoTxEnv for TransactionRequest { ) -> Result { // Ensure that if versioned hashes are set, they're not empty if self.blob_versioned_hashes.as_ref().is_some_and(|hashes| hashes.is_empty()) { - return Err(CallFeesError::BlobTransactionMissingBlobHashes.into()) + return Err(CallFeesError::BlobTransactionMissingBlobHashes.into()); } let tx_type = self.minimal_tx_type() as u8; diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index 3066b440a4..681a53a9f7 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -726,9 +726,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()); } } @@ -745,7 +745,7 @@ where versioned_hashes: Vec, ) -> EngineApiResult>> { if versioned_hashes.len() > MAX_BLOB_LIMIT { - return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }) + return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }); } self.inner @@ -779,7 +779,7 @@ where versioned_hashes: Vec, ) -> EngineApiResult>> { if versioned_hashes.len() > MAX_BLOB_LIMIT { - return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }) + return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }); } self.inner @@ -1341,8 +1341,8 @@ mod tests { blocks .iter() .filter(|b| { - !first_missing_range.contains(&b.number) && - !second_missing_range.contains(&b.number) + !first_missing_range.contains(&b.number) + && !second_missing_range.contains(&b.number) }) .map(|b| (b.hash(), b.clone().into_block())), ); @@ -1371,8 +1371,8 @@ mod tests { // ensure we still return trailing `None`s here because by-hash will not be aware // of the missing block's number, and cannot compare it to the current best block .map(|b| { - if first_missing_range.contains(&b.number) || - second_missing_range.contains(&b.number) + if first_missing_range.contains(&b.number) + || second_missing_range.contains(&b.number) { None } else { diff --git a/crates/rpc/rpc-engine-api/src/error.rs b/crates/rpc/rpc-engine-api/src/error.rs index 2578b2f44e..3d41c9d2ad 100644 --- a/crates/rpc/rpc-engine-api/src/error.rs +++ b/crates/rpc/rpc-engine-api/src/error.rs @@ -128,12 +128,12 @@ impl ErrorData { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(error: EngineApiError) -> Self { match error { - EngineApiError::InvalidBodiesRange { .. } | - EngineApiError::EngineObjectValidationError( - EngineObjectValidationError::Payload(_) | - EngineObjectValidationError::InvalidParams(_), - ) | - EngineApiError::UnexpectedRequestsHash => { + EngineApiError::InvalidBodiesRange { .. } + | EngineApiError::EngineObjectValidationError( + EngineObjectValidationError::Payload(_) + | EngineObjectValidationError::InvalidParams(_), + ) + | EngineApiError::UnexpectedRequestsHash => { // Note: the data field is not required by the spec, but is also included by other // clients jsonrpsee_types::error::ErrorObject::owned( @@ -158,8 +158,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { error.to_string(), None::<()>, ), - EngineApiError::PayloadRequestTooLarge { .. } | - EngineApiError::BlobRequestTooLarge { .. } => { + EngineApiError::PayloadRequestTooLarge { .. } + | EngineApiError::BlobRequestTooLarge { .. } => { jsonrpsee_types::error::ErrorObject::owned( REQUEST_TOO_LARGE_CODE, REQUEST_TOO_LARGE_MESSAGE, @@ -183,8 +183,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { None::<()>, ) } - ForkchoiceUpdateError::InvalidState | - ForkchoiceUpdateError::UnknownFinalBlock => { + ForkchoiceUpdateError::InvalidState + | ForkchoiceUpdateError::UnknownFinalBlock => { jsonrpsee_types::error::ErrorObject::owned( INVALID_FORK_CHOICE_STATE_ERROR, INVALID_FORK_CHOICE_STATE_ERROR_MSG, @@ -192,8 +192,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { ) } }, - BeaconForkChoiceUpdateError::EngineUnavailable | - BeaconForkChoiceUpdateError::Internal(_) => { + BeaconForkChoiceUpdateError::EngineUnavailable + | BeaconForkChoiceUpdateError::Internal(_) => { jsonrpsee_types::error::ErrorObject::owned( INTERNAL_ERROR_CODE, SERVER_ERROR_MSG, @@ -202,11 +202,11 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { } }, // Any other server error - EngineApiError::TerminalTD { .. } | - EngineApiError::TerminalBlockHash { .. } | - EngineApiError::NewPayload(_) | - EngineApiError::Internal(_) | - EngineApiError::GetPayloadError(_) => jsonrpsee_types::error::ErrorObject::owned( + EngineApiError::TerminalTD { .. } + | EngineApiError::TerminalBlockHash { .. } + | EngineApiError::NewPayload(_) + | EngineApiError::Internal(_) + | EngineApiError::GetPayloadError(_) => jsonrpsee_types::error::ErrorObject::owned( INTERNAL_ERROR_CODE, SERVER_ERROR_MSG, Some(ErrorData::new(error)), diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index 91a6739b8b..c407a32887 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -80,7 +80,7 @@ pub trait EthBlocks: LoadBlock { .provider() .pending_block() .map_err(Self::Error::from_eth_err)? - .map(|block| block.body().transactions().len())) + .map(|block| block.body().transactions().len())); } let block_hash = match self @@ -147,7 +147,7 @@ pub trait EthBlocks: LoadBlock { .get_block_and_receipts(block_hash) .await .map_err(Self::Error::from_eth_err) - .map(|b| b.map(|(b, r)| (b.clone_sealed_block(), r))) + .map(|b| b.map(|(b, r)| (b.clone_sealed_block(), r))); } 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 12d63243f1..6607e96444 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -76,7 +76,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA ) -> impl Future> + Send { async move { if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { - return Err(EthApiError::InvalidParams("too many blocks.".to_string()).into()) + return Err(EthApiError::InvalidParams("too many blocks.".to_string()).into()); } let block = block.unwrap_or_default(); @@ -89,7 +89,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA } = payload; if block_state_calls.is_empty() { - return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()) + return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); } let base_block = @@ -124,12 +124,12 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA if let Some(block_overrides) = block_overrides { // ensure we don't allow uncapped gas limit per block if let Some(gas_limit_override) = block_overrides.gas_limit { - if gas_limit_override > evm_env.block_env.gas_limit && - gas_limit_override > this.call_gas_limit() + if gas_limit_override > evm_env.block_env.gas_limit + && gas_limit_override > this.call_gas_limit() { return Err( EthApiError::other(EthSimulateError::GasLimitReached).into() - ) + ); } } apply_block_overrides(block_overrides, &mut db, &mut evm_env.block_env); @@ -151,7 +151,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA return Err(EthApiError::Other(Box::new( EthSimulateError::BlockGasLimitExceeded, )) - .into()) + .into()); } if txs_without_gas_limit > 0 { @@ -421,11 +421,11 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA ExecutionResult::Halt { reason, gas_used } => { let error = Some(Self::Error::from_evm_halt(reason, tx_env.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 { .. } => {} }; @@ -683,7 +683,7 @@ pub trait Call: for tx in transactions { if *tx.tx_hash() == target_tx_hash { // reached the target transaction - break + break; } let tx_env = self.evm_config().tx_env(tx); @@ -744,7 +744,7 @@ pub trait Call: // configured gas exceeds limit return Err( EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into() - ) + ); } // apply configured gas cap diff --git a/crates/rpc/rpc-eth-api/src/helpers/estimate.rs b/crates/rpc/rpc-eth-api/src/helpers/estimate.rs index 91af2c37e4..1e91c06ed0 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/estimate.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/estimate.rs @@ -119,7 +119,7 @@ pub trait EstimateCall: Call { // Reuse the same EVM instance if let Ok(res) = evm.transact(min_tx_env).map_err(Self::Error::from_evm_err) { if res.result.is_success() { - return Ok(U256::from(MIN_TRANSACTION_GAS)) + return Ok(U256::from(MIN_TRANSACTION_GAS)); } } } @@ -133,8 +133,8 @@ pub trait EstimateCall: Call { // retry the transaction with the block's gas limit to determine if // the failure was due to insufficient gas. Err(err) - if err.is_gas_too_high() && - (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) => + if err.is_gas_too_high() + && (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) => { return Self::map_out_of_gas_err(&mut evm, tx_env, block_env_gas_limit); } @@ -146,7 +146,7 @@ pub trait EstimateCall: Call { return Err(RpcInvalidTransactionError::GasRequiredExceedsAllowance { gas_limit: tx_env.gas_limit(), } - .into_eth_err()) + .into_eth_err()); } // Propagate other results (successful or other errors). ethres => ethres?, @@ -157,7 +157,7 @@ pub trait EstimateCall: Call { ExecutionResult::Halt { reason, .. } => { // here we don't check for invalid opcode because already executed with highest gas // limit - return Err(Self::Error::from_evm_halt(reason, tx_env.gas_limit())) + return Err(Self::Error::from_evm_halt(reason, tx_env.gas_limit())); } ExecutionResult::Revert { output, .. } => { // if price or limit was included in the request then we can execute the request @@ -167,7 +167,7 @@ pub trait EstimateCall: Call { } else { // the transaction did revert Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into_eth_err()) - } + }; } }; @@ -225,10 +225,10 @@ pub trait EstimateCall: Call { // An estimation error is allowed once the current gas limit range used in the binary // search is small enough (less than 1.5% of the highest gas limit) // impl Future> + Send { async move { if block_count == 0 { - return Ok(FeeHistory::default()) + return Ok(FeeHistory::default()); } // ensure the given reward percentiles aren't excessive - if reward_percentiles.as_ref().map(|perc| perc.len() as u64) > - Some(self.gas_oracle().config().max_reward_percentile_count) + if reward_percentiles.as_ref().map(|perc| perc.len() as u64) + > Some(self.gas_oracle().config().max_reward_percentile_count) { - return Err(EthApiError::InvalidRewardPercentiles.into()) + return Err(EthApiError::InvalidRewardPercentiles.into()); } // See https://github.com/ethereum/go-ethereum/blob/2754b197c935ee63101cbbca2752338246384fec/eth/gasprice/feehistory.go#L218C8-L225 @@ -111,7 +111,7 @@ pub trait EthFees: // 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()); } } @@ -136,7 +136,7 @@ pub trait EthFees: 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 { @@ -168,11 +168,12 @@ pub trait EthFees: base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default()); } else { // read the requested header range - let headers = self.provider() + let headers = self + .provider() .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()); } let chain_spec = self.provider().chain_spec(); @@ -192,7 +193,8 @@ pub trait EthFees: // Percentiles were specified, so we need to collect reward percentile info if let Some(percentiles) = &reward_percentiles { - let (block, receipts) = self.cache() + let (block, receipts) = self + .cache() .get_block_and_receipts(header.hash()) .await .map_err(Self::Error::from_eth_err)? @@ -225,9 +227,10 @@ pub trait EthFees: // > "[..] 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 - .maybe_next_block_blob_fee( - chain_spec.blob_params_at_timestamp(last_header.timestamp()) - ).unwrap_or_default() + .maybe_next_block_blob_fee( + chain_spec.blob_params_at_timestamp(last_header.timestamp()), + ) + .unwrap_or_default(), ); }; 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 272f3c18f1..55b8236f5f 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -155,9 +155,9 @@ pub trait LoadPendingBlock: // check if the block is still good if let Some(pending_block) = lock.as_ref() { // this is guaranteed to be the `latest` header - if pending.evm_env.block_env.number == U256::from(pending_block.block.number()) && - parent.hash() == pending_block.block.parent_hash() && - now <= pending_block.expires_at + if pending.evm_env.block_env.number == U256::from(pending_block.block.number()) + && parent.hash() == pending_block.block.parent_hash() + && now <= pending_block.expires_at { return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))); } @@ -174,7 +174,7 @@ pub trait LoadPendingBlock: Ok(block) => block, Err(err) => { debug!(target: "rpc", "Failed to build pending block: {:?}", err); - return Ok(None) + return Ok(None); } }; @@ -253,7 +253,7 @@ pub trait LoadPendingBlock: block_gas_limit, ), ); - continue + continue; } if pool_tx.origin.is_private() { @@ -266,7 +266,7 @@ pub trait LoadPendingBlock: InvalidTransactionError::TxTypeNotSupported, ), ); - continue + continue; } // convert tx to a signed transaction @@ -287,7 +287,7 @@ pub trait LoadPendingBlock: blob_params.max_blob_gas_per_block(), ), ); - continue + continue; } } @@ -309,7 +309,7 @@ pub trait LoadPendingBlock: ), ); } - continue + continue; } // this is an error that we should treat as fatal for this attempt Err(err) => return Err(Self::Error::from_eth_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 4fa4edee8b..8f8c96c399 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -107,7 +107,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()); } self.spawn_blocking_io(move |this| { @@ -142,7 +142,7 @@ pub trait EthState: LoadState + SpawnBlocking { .ok_or(EthApiError::HeaderNotFound(block_id))?; let max_window = this.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { - return Err(EthApiError::ExceedsMaxProofWindow.into()) + return Err(EthApiError::ExceedsMaxProofWindow.into()); } let balance = account.balance; diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index 31085bdc08..db31a1afb7 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -294,7 +294,7 @@ pub trait Trace: async move { let block = async { if block.is_some() { - return Ok(block) + return Ok(block); } self.recovered_block(block_id).await }; @@ -305,7 +305,7 @@ pub trait Trace: if block.body().transactions().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 c0c759d400..1d5fc19cf4 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -158,7 +158,7 @@ pub trait EthTransactions: LoadTransaction { if let Some(tx) = self.pool().get_pooled_transaction_element(hash).map(|tx| tx.encoded_2718().into()) { - return Ok(Some(tx)) + return Ok(Some(tx)); } self.spawn_blocking_io(move |ref this| { @@ -269,7 +269,7 @@ pub trait EthTransactions: LoadTransaction { return Ok(Some( self.tx_resp_builder().fill(tx.clone().with_signer(*signer), tx_info)?, - )) + )); } } @@ -367,7 +367,7 @@ pub trait EthTransactions: LoadTransaction { async move { if let Some(block) = self.recovered_block(block_id).await? { if let Some(tx) = block.body().transactions().get(index) { - return Ok(Some(tx.encoded_2718().into())) + return Ok(Some(tx.encoded_2718().into())); } } @@ -391,7 +391,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 a055acac58..9dc84af42f 100644 --- a/crates/rpc/rpc-eth-types/src/cache/mod.rs +++ b/crates/rpc/rpc-eth-types/src/cache/mod.rs @@ -459,7 +459,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 @@ -488,7 +488,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 @@ -513,13 +513,13 @@ where // check if the header is cached if let Some(header) = this.headers_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(header)); - continue + continue; } // it's possible we have the entire block cached if let Some(block) = this.full_block_cache.get(&block_hash) { let _ = response_tx.send(Ok(block.clone_header())); - continue + continue; } // header is not in the cache, request it if this is the first diff --git a/crates/rpc/rpc-eth-types/src/error/api.rs b/crates/rpc/rpc-eth-types/src/error/api.rs index 03641d067e..f70f03e199 100644 --- a/crates/rpc/rpc-eth-types/src/error/api.rs +++ b/crates/rpc/rpc-eth-types/src/error/api.rs @@ -58,7 +58,7 @@ pub trait AsEthApiError { /// [`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 @@ -68,7 +68,7 @@ pub trait AsEthApiError { /// [`RpcInvalidTransactionError::GasTooLow`]. fn is_gas_too_low(&self) -> bool { if let Some(err) = self.as_err() { - return err.is_gas_too_low() + return err.is_gas_too_low(); } false diff --git a/crates/rpc/rpc-eth-types/src/error/mod.rs b/crates/rpc/rpc-eth-types/src/error/mod.rs index 96adc4e67b..04dc0093de 100644 --- a/crates/rpc/rpc-eth-types/src/error/mod.rs +++ b/crates/rpc/rpc-eth-types/src/error/mod.rs @@ -207,25 +207,25 @@ impl EthApiError { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(error: EthApiError) -> Self { match error { - EthApiError::FailedToDecodeSignedTransaction | - EthApiError::InvalidTransactionSignature | - EthApiError::EmptyRawTransactionData | - EthApiError::InvalidBlockRange | - EthApiError::ExceedsMaxProofWindow | - EthApiError::ConflictingFeeFieldsInRequest | - EthApiError::Signing(_) | - EthApiError::BothStateAndStateDiffInOverride(_) | - EthApiError::InvalidTracerConfig | - EthApiError::TransactionConversionError | - EthApiError::InvalidRewardPercentiles | - EthApiError::InvalidBytecode(_) => invalid_params_rpc_err(error.to_string()), + EthApiError::FailedToDecodeSignedTransaction + | EthApiError::InvalidTransactionSignature + | EthApiError::EmptyRawTransactionData + | EthApiError::InvalidBlockRange + | EthApiError::ExceedsMaxProofWindow + | EthApiError::ConflictingFeeFieldsInRequest + | EthApiError::Signing(_) + | EthApiError::BothStateAndStateDiffInOverride(_) + | EthApiError::InvalidTracerConfig + | EthApiError::TransactionConversionError + | EthApiError::InvalidRewardPercentiles + | EthApiError::InvalidBytecode(_) => invalid_params_rpc_err(error.to_string()), EthApiError::InvalidTransaction(err) => err.into(), EthApiError::PoolError(err) => err.into(), - EthApiError::PrevrandaoNotSet | - EthApiError::ExcessBlobGasNotSet | - EthApiError::InvalidBlockData(_) | - EthApiError::Internal(_) | - EthApiError::EvmCustom(_) => internal_rpc_err(error.to_string()), + EthApiError::PrevrandaoNotSet + | EthApiError::ExcessBlobGasNotSet + | EthApiError::InvalidBlockData(_) + | EthApiError::Internal(_) + | EthApiError::EvmCustom(_) => internal_rpc_err(error.to_string()), EthApiError::UnknownBlockOrTxIndex | EthApiError::TransactionNotFound => { rpc_error_with_code(EthRpcErrorCode::ResourceNotFound.code(), error.to_string()) } @@ -586,14 +586,14 @@ impl RpcInvalidTransactionError { /// Returns the rpc error code for this error. pub const fn error_code(&self) -> i32 { match self { - Self::InvalidChainId | - Self::GasTooLow | - Self::GasTooHigh | - Self::GasRequiredExceedsAllowance { .. } | - Self::NonceTooLow { .. } | - Self::NonceTooHigh { .. } | - Self::FeeCapTooLow | - Self::FeeCapVeryHigh => EthRpcErrorCode::InvalidInput.code(), + Self::InvalidChainId + | Self::GasTooLow + | Self::GasTooHigh + | Self::GasRequiredExceedsAllowance { .. } + | Self::NonceTooLow { .. } + | Self::NonceTooHigh { .. } + | Self::FeeCapTooLow + | Self::FeeCapVeryHigh => EthRpcErrorCode::InvalidInput.code(), Self::Revert(_) => EthRpcErrorCode::ExecutionError.code(), _ => EthRpcErrorCode::TransactionRejected.code(), } @@ -648,8 +648,8 @@ impl From for RpcInvalidTransactionError { } InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap, InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow, - InvalidTransaction::CallerGasLimitMoreThanBlock | - InvalidTransaction::TxGasLimitGreaterThanCap { .. } => { + InvalidTransaction::CallerGasLimitMoreThanBlock + | InvalidTransaction::TxGasLimitGreaterThanCap { .. } => { // tx.gas > block.gas_limit Self::GasTooHigh } @@ -686,13 +686,13 @@ impl From for RpcInvalidTransactionError { InvalidTransaction::AuthorizationListNotSupported => { Self::AuthorizationListNotSupported } - InvalidTransaction::AuthorizationListInvalidFields | - InvalidTransaction::EmptyAuthorizationList => Self::AuthorizationListInvalidFields, - InvalidTransaction::Eip2930NotSupported | - InvalidTransaction::Eip1559NotSupported | - InvalidTransaction::Eip4844NotSupported | - InvalidTransaction::Eip7702NotSupported | - InvalidTransaction::Eip7873NotSupported => Self::TxTypeNotSupported, + InvalidTransaction::AuthorizationListInvalidFields + | InvalidTransaction::EmptyAuthorizationList => Self::AuthorizationListInvalidFields, + InvalidTransaction::Eip2930NotSupported + | InvalidTransaction::Eip1559NotSupported + | InvalidTransaction::Eip4844NotSupported + | InvalidTransaction::Eip7702NotSupported + | InvalidTransaction::Eip7873NotSupported => Self::TxTypeNotSupported, InvalidTransaction::Eip7873MissingTarget => { Self::other(internal_rpc_err(err.to_string())) } @@ -717,11 +717,11 @@ impl From for RpcInvalidTransactionError { Self::OldLegacyChainId } InvalidTransactionError::ChainIdMismatch => Self::InvalidChainId, - InvalidTransactionError::Eip2930Disabled | - InvalidTransactionError::Eip1559Disabled | - InvalidTransactionError::Eip4844Disabled | - InvalidTransactionError::Eip7702Disabled | - InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported, + InvalidTransactionError::Eip2930Disabled + | InvalidTransactionError::Eip1559Disabled + | InvalidTransactionError::Eip4844Disabled + | InvalidTransactionError::Eip7702Disabled + | InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported, InvalidTransactionError::GasUintOverflow => Self::GasUintOverflow, InvalidTransactionError::GasTooLow => Self::GasTooLow, InvalidTransactionError::GasTooHigh => Self::GasTooHigh, @@ -849,19 +849,19 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { RpcPoolError::TxPoolOverflow => { rpc_error_with_code(EthRpcErrorCode::TransactionRejected.code(), error.to_string()) } - RpcPoolError::AlreadyKnown | - RpcPoolError::InvalidSender | - RpcPoolError::Underpriced | - RpcPoolError::ReplaceUnderpriced | - RpcPoolError::ExceedsGasLimit | - RpcPoolError::ExceedsFeeCap { .. } | - RpcPoolError::NegativeValue | - RpcPoolError::OversizedData | - RpcPoolError::ExceedsMaxInitCodeSize | - RpcPoolError::PoolTransactionError(_) | - RpcPoolError::Eip4844(_) | - RpcPoolError::Eip7702(_) | - RpcPoolError::AddressAlreadyReserved => { + RpcPoolError::AlreadyKnown + | RpcPoolError::InvalidSender + | RpcPoolError::Underpriced + | RpcPoolError::ReplaceUnderpriced + | RpcPoolError::ExceedsGasLimit + | RpcPoolError::ExceedsFeeCap { .. } + | RpcPoolError::NegativeValue + | RpcPoolError::OversizedData + | RpcPoolError::ExceedsMaxInitCodeSize + | RpcPoolError::PoolTransactionError(_) + | RpcPoolError::Eip4844(_) + | RpcPoolError::Eip7702(_) + | RpcPoolError::AddressAlreadyReserved => { rpc_error_with_code(EthRpcErrorCode::InvalidInput.code(), error.to_string()) } RpcPoolError::Other(other) => internal_rpc_err(other.to_string()), diff --git a/crates/rpc/rpc-eth-types/src/fee_history.rs b/crates/rpc/rpc-eth-types/src/fee_history.rs index 7262c1c44c..3574ac94ab 100644 --- a/crates/rpc/rpc-eth-types/src/fee_history.rs +++ b/crates/rpc/rpc-eth-types/src/fee_history.rs @@ -109,7 +109,7 @@ where if entries.is_empty() { 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(); @@ -148,7 +148,7 @@ where ) -> Option>> { if end_block < start_block { // invalid range, return None - return None + return None; } let lower_bound = self.lower_bound(); let upper_bound = self.upper_bound(); @@ -160,7 +160,7 @@ where .collect::>(); if result.is_empty() { - return None + return None; } Some(result) @@ -324,7 +324,7 @@ where // 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; @@ -377,8 +377,8 @@ where base_fee_per_blob_gas: header .excess_blob_gas() .and_then(|excess_blob_gas| Some(blob_params?.calc_blob_fee(excess_blob_gas))), - blob_gas_used_ratio: block.body().blob_gas_used() as f64 / - blob_params + blob_gas_used_ratio: block.body().blob_gas_used() as f64 + / blob_params .as_ref() .map(|params| params.max_blob_gas_per_block()) .unwrap_or(alloy_eips::eip4844::MAX_DATA_GAS_PER_BLOCK_DENCUN) diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 798a146e61..065a2f5c2c 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -128,16 +128,16 @@ where /// Suggests a gas price estimate based on recent blocks, using the configured percentile. pub async fn suggest_tip_cap(&self) -> EthResult { - let header: reth_primitives_traits::SealedHeader<::Header> = self - .provider - .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? - .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; + let header: reth_primitives_traits::SealedHeader<::Header> = + self.provider + .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? + .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; let mut inner = self.inner.lock().await; // 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 @@ -182,7 +182,7 @@ where // break when we have enough populated blocks if populated_blocks >= self.oracle_config.blocks { - break + break; } current_hash = parent_hash; @@ -224,7 +224,7 @@ where ) -> EthResult)>> { // check the cache (this will hit the disk if the block is not cached) let Some(block) = self.cache.get_recovered_block(block_hash).await? else { - return Ok(None) + return Ok(None); }; let base_fee_per_gas = block.base_fee_per_gas(); @@ -251,13 +251,13 @@ where // ignore transactions with a tip under the configured threshold if let Some(ignore_under) = self.ignore_price { if effective_tip < Some(ignore_under) { - continue + continue; } } // check if the sender was the coinbase, if so, ignore if tx.signer() == block.beneficiary() { - continue + continue; } // a `None` effective_gas_tip represents a transaction where the max_fee_per_gas is @@ -266,7 +266,7 @@ where // we have enough entries if prices.len() >= limit { - break + break; } } @@ -352,7 +352,7 @@ where pub async fn get_block_median_tip(&self, block_hash: B256) -> EthResult> { // check the cache (this will hit the disk if the block is not cached) let Some(block) = self.cache.get_recovered_block(block_hash).await? else { - return Ok(None) + return Ok(None); }; let base_fee_per_gas = block.base_fee_per_gas(); diff --git a/crates/rpc/rpc-eth-types/src/id_provider.rs b/crates/rpc/rpc-eth-types/src/id_provider.rs index a2020d0b21..1c4efa7707 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/utils.rs b/crates/rpc/rpc-eth-types/src/utils.rs index d3bb655be1..d2d8ac00ce 100644 --- a/crates/rpc/rpc-eth-types/src/utils.rs +++ b/crates/rpc/rpc-eth-types/src/utils.rs @@ -12,7 +12,7 @@ use std::future::Future; /// See [`alloy_eips::eip2718::Decodable2718::decode_2718`] pub fn recover_raw_transaction(mut data: &[u8]) -> EthResult> { if data.is_empty() { - return Err(EthApiError::EmptyRawTransactionData) + return Err(EthApiError::EmptyRawTransactionData); } let transaction = diff --git a/crates/rpc/rpc-layer/src/auth_client_layer.rs b/crates/rpc/rpc-layer/src/auth_client_layer.rs index 5eda04aa0f..c5899b0696 100644 --- a/crates/rpc/rpc-layer/src/auth_client_layer.rs +++ b/crates/rpc/rpc-layer/src/auth_client_layer.rs @@ -66,8 +66,8 @@ pub fn secret_to_bearer_header(secret: &JwtSecret) -> HeaderValue { "Bearer {}", secret .encode(&Claims { - iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + - Duration::from_secs(60)) + iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + + Duration::from_secs(60)) .as_secs(), exp: None, }) diff --git a/crates/rpc/rpc-server-types/src/module.rs b/crates/rpc/rpc-server-types/src/module.rs index fdca41cc19..64bad737d6 100644 --- a/crates/rpc/rpc-server-types/src/module.rs +++ b/crates/rpc/rpc-server-types/src/module.rs @@ -204,7 +204,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 301d65a820..564a9e123a 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -20,7 +20,7 @@ use std::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(); @@ -107,7 +107,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(); @@ -141,7 +141,7 @@ async fn debug_trace_block_opcodes_entire_chain() { let opcodes7702 = ["EXTCODESIZE", "EXTCODECOPY", "EXTCODEHASH"]; 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/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 1e2f107398..2363243096 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -445,7 +445,7 @@ where Ok(GethTrace::JS(res)) } - } + }; } // default structlog tracer @@ -481,7 +481,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(); @@ -739,7 +739,7 @@ where let mut inspector = FourByteInspector::default(); let (res, _) = self.eth_api().inspect(db, evm_env, tx_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 @@ -762,7 +762,7 @@ where .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 @@ -784,7 +784,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())) @@ -803,7 +803,7 @@ where let frame = inspector .try_into_mux_frame(&res, db, tx_info) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)) + return Ok((frame.into(), res.state)); } GethDebugBuiltInTracerType::FlatCallTracer => { let flat_call_config = tracer_config @@ -848,7 +848,7 @@ where .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 8a0683b763..4ebfa98681 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -68,13 +68,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 @@ -113,14 +113,14 @@ where .chain_spec() .blob_params_at_timestamp(evm_env.block_env.timestamp.saturating_to()) .unwrap_or_else(BlobParams::cancun); - if transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::() > - blob_params.max_blob_gas_per_block() + if transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::() + > blob_params.max_blob_gas_per_block() { return Err(EthApiError::InvalidParams( EthBundleError::Eip4844BlobGasExceeded(blob_params.max_blob_gas_per_block()) .to_string(), ) - .into()) + .into()); } } @@ -128,9 +128,10 @@ where evm_env.block_env.gas_limit = self.inner.eth_api.call_gas_limit(); if let Some(gas_limit) = gas_limit { if gas_limit > evm_env.block_env.gas_limit { - return Err( - EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into() + return Err(EthApiError::InvalidTransaction( + RpcInvalidTransactionError::GasTooHigh, ) + .into()); } evm_env.block_env.gas_limit = gas_limit; } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index d672fd10f6..d9b81bdb59 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -199,7 +199,7 @@ where if filter.block > best_number { // no new blocks since the last poll - return Ok(FilterChanges::Empty) + return Ok(FilterChanges::Empty); } // update filter @@ -273,7 +273,7 @@ where *filter.clone() } else { // Not a log filter - return Err(EthFilterError::FilterNotFound(id)) + return Err(EthFilterError::FilterNotFound(id)); } }; @@ -534,13 +534,13 @@ where // perform boundary checks first if to_block < from_block { - return Err(EthFilterError::InvalidBlockRangeParams) + return Err(EthFilterError::InvalidBlockRangeParams); } if let Some(max_blocks_per_filter) = limits.max_blocks_per_filter.filter(|limit| to_block - from_block > *limit) { - return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter)) + return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter)); } let (tx, rx) = oneshot::channel(); @@ -780,7 +780,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)) } @@ -827,9 +827,9 @@ impl From for jsonrpsee::types::error::ErrorObject<'static> { rpc_error_with_code(jsonrpsee::types::error::INTERNAL_ERROR_CODE, err.to_string()) } EthFilterError::EthAPIError(err) => err.into(), - err @ (EthFilterError::InvalidBlockRangeParams | - EthFilterError::QueryExceedsMaxBlocks(_) | - EthFilterError::QueryExceedsMaxResults { .. }) => { + err @ (EthFilterError::InvalidBlockRangeParams + | EthFilterError::QueryExceedsMaxBlocks(_) + | EthFilterError::QueryExceedsMaxResults { .. }) => { rpc_error_with_code(jsonrpsee::types::error::INVALID_PARAMS_CODE, err.to_string()) } } diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 724b3a5c96..0b086ae481 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -65,7 +65,7 @@ where .map(|builder| builder.build()) }) .collect::, Self::Error>>() - .map(Some) + .map(Some); } Ok(None) diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index 1c7982f80f..e3e9ddfae8 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -139,7 +139,7 @@ where }; std::future::ready(tx_value) }); - return pipe_from_stream(accepted_sink, stream).await + return pipe_from_stream(accepted_sink, stream).await; } Params::Bool(false) | Params::None => { // only hashes requested @@ -172,7 +172,7 @@ where .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - return Ok(()) + return Ok(()); } while canon_state.next().await.is_some() { @@ -192,7 +192,7 @@ where .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - break + break; } } } diff --git a/crates/rpc/rpc/src/eth/sim_bundle.rs b/crates/rpc/rpc/src/eth/sim_bundle.rs index 6221f6821c..98045d1f77 100644 --- a/crates/rpc/rpc/src/eth/sim_bundle.rs +++ b/crates/rpc/rpc/src/eth/sim_bundle.rs @@ -270,8 +270,8 @@ where let max_block_number = item.inclusion.max_block_number().unwrap_or(block_number); - if current_block_number < block_number || - current_block_number > max_block_number + if current_block_number < block_number + || current_block_number > max_block_number { return Err(EthApiError::InvalidParams( EthSimBundleError::InvalidInclusion.to_string(), @@ -349,9 +349,9 @@ where }); // Calculate payout transaction fee - let payout_tx_fee = U256::from(basefee) * - U256::from(SBUNDLE_PAYOUT_MAX_COST) * - U256::from(refund_configs.len() as u64); + let payout_tx_fee = U256::from(basefee) + * U256::from(SBUNDLE_PAYOUT_MAX_COST) + * U256::from(refund_configs.len() as u64); // Add gas used for payout transactions total_gas_used += SBUNDLE_PAYOUT_MAX_COST * refund_configs.len() as u64; diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index bafbf0730b..691251db2e 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -227,7 +227,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 3aaa1ebc5e..6e9669c820 100644 --- a/crates/rpc/rpc/src/reth.rs +++ b/crates/rpc/rpc/src/reth.rs @@ -71,7 +71,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::HeaderNotFound(block_id)) + return Err(EthApiError::HeaderNotFound(block_id)); }; 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 73d461bf22..94f84160fc 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -224,7 +224,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 } @@ -298,7 +298,7 @@ where }; if is_paris_activated { - return Ok(None) + return Ok(None); } Ok(Some(base_block_reward_pre_merge(&chain_spec, header.number()))) @@ -373,7 +373,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 @@ -382,7 +382,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 @@ -437,7 +437,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; } } @@ -448,7 +448,7 @@ where if after < all_traces.len() { all_traces.drain(..after); } else { - return Ok(vec![]) + return Ok(vec![]); } } diff --git a/crates/rpc/rpc/src/validation.rs b/crates/rpc/rpc/src/validation.rs index bd75a8045a..e96410ae09 100644 --- a/crates/rpc/rpc/src/validation.rs +++ b/crates/rpc/rpc/src/validation.rs @@ -133,18 +133,18 @@ where if !self.disallow.is_empty() { if self.disallow.contains(&block.beneficiary()) { - return Err(ValidationApiError::Blacklist(block.beneficiary())) + return Err(ValidationApiError::Blacklist(block.beneficiary())); } if self.disallow.contains(&message.proposer_fee_recipient) { - return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient)) + return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient)); } for (sender, tx) in block.senders_iter().zip(block.body().transactions()) { if self.disallow.contains(sender) { - return Err(ValidationApiError::Blacklist(*sender)) + return Err(ValidationApiError::Blacklist(*sender)); } if let Some(to) = tx.to() { if self.disallow.contains(&to) { - return Err(ValidationApiError::Blacklist(to)) + return Err(ValidationApiError::Blacklist(to)); } } } @@ -162,10 +162,10 @@ where .sealed_header_by_hash(block.parent_hash())? .ok_or_else(|| ValidationApiError::MissingParentBlock)?; - if latest_header.number().saturating_sub(parent_header.number()) > - self.validation_window + if latest_header.number().saturating_sub(parent_header.number()) + > self.validation_window { - return Err(ValidationApiError::BlockTooOld) + return Err(ValidationApiError::BlockTooOld); } parent_header }; @@ -194,7 +194,7 @@ where })?; if let Some(account) = accessed_blacklisted { - return Err(ValidationApiError::Blacklist(account)) + return Err(ValidationApiError::Blacklist(account)); } // update the cached reads @@ -211,7 +211,7 @@ where return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: state_root, expected: block.header().state_root() }.into(), ) - .into()) + .into()); } Ok(()) @@ -270,7 +270,7 @@ where return Err(ValidationApiError::GasLimitMismatch(GotExpected { got: header.gas_limit(), expected: best_gas_limit, - })) + })); } Ok(()) @@ -308,7 +308,7 @@ where } if balance_after >= balance_before + message.value { - return Ok(()) + return Ok(()); } let (receipt, tx) = output @@ -318,24 +318,24 @@ where .ok_or(ValidationApiError::ProposerPayment)?; if !receipt.status() { - return Err(ValidationApiError::ProposerPayment) + return Err(ValidationApiError::ProposerPayment); } if tx.to() != Some(message.proposer_fee_recipient) { - return Err(ValidationApiError::ProposerPayment) + return Err(ValidationApiError::ProposerPayment); } if tx.value() != message.value { - return Err(ValidationApiError::ProposerPayment) + return Err(ValidationApiError::ProposerPayment); } if !tx.input().is_empty() { - return Err(ValidationApiError::ProposerPayment) + return Err(ValidationApiError::ProposerPayment); } if let Some(block_base_fee) = block.header().base_fee_per_gas() { if tx.effective_tip_per_gas(block_base_fee).unwrap_or_default() != 0 { - return Err(ValidationApiError::ProposerPayment) + return Err(ValidationApiError::ProposerPayment); } } @@ -347,10 +347,10 @@ where &self, mut blobs_bundle: BlobsBundleV1, ) -> Result, ValidationApiError> { - if blobs_bundle.commitments.len() != blobs_bundle.proofs.len() || - blobs_bundle.commitments.len() != blobs_bundle.blobs.len() + if blobs_bundle.commitments.len() != blobs_bundle.proofs.len() + || blobs_bundle.commitments.len() != blobs_bundle.blobs.len() { - return Err(ValidationApiError::InvalidBlobsBundle) + return Err(ValidationApiError::InvalidBlobsBundle); } let versioned_hashes = blobs_bundle @@ -588,20 +588,20 @@ pub enum ValidationApiError { impl From for ErrorObject<'static> { fn from(error: ValidationApiError) -> Self { match error { - ValidationApiError::GasLimitMismatch(_) | - ValidationApiError::GasUsedMismatch(_) | - ValidationApiError::ParentHashMismatch(_) | - ValidationApiError::BlockHashMismatch(_) | - ValidationApiError::Blacklist(_) | - ValidationApiError::ProposerPayment | - ValidationApiError::InvalidBlobsBundle | - ValidationApiError::Blob(_) => invalid_params_rpc_err(error.to_string()), - - ValidationApiError::MissingLatestBlock | - ValidationApiError::MissingParentBlock | - ValidationApiError::BlockTooOld | - ValidationApiError::Consensus(_) | - ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()), + ValidationApiError::GasLimitMismatch(_) + | ValidationApiError::GasUsedMismatch(_) + | ValidationApiError::ParentHashMismatch(_) + | ValidationApiError::BlockHashMismatch(_) + | ValidationApiError::Blacklist(_) + | ValidationApiError::ProposerPayment + | ValidationApiError::InvalidBlobsBundle + | ValidationApiError::Blob(_) => invalid_params_rpc_err(error.to_string()), + + ValidationApiError::MissingLatestBlock + | ValidationApiError::MissingParentBlock + | ValidationApiError::BlockTooOld + | ValidationApiError::Consensus(_) + | ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()), ValidationApiError::Execution(err) => match err { error @ BlockExecutionError::Validation(_) => { invalid_params_rpc_err(error.to_string()) diff --git a/crates/scroll/alloy/consensus/src/receipt/envelope.rs b/crates/scroll/alloy/consensus/src/receipt/envelope.rs index 2ba0afdd84..0a0bf60abf 100644 --- a/crates/scroll/alloy/consensus/src/receipt/envelope.rs +++ b/crates/scroll/alloy/consensus/src/receipt/envelope.rs @@ -116,11 +116,11 @@ impl ScrollReceiptEnvelope { /// Return the receipt's bloom. pub const fn logs_bloom(&self) -> &Bloom { match self { - Self::Legacy(t) | - Self::Eip2930(t) | - Self::Eip1559(t) | - Self::Eip7702(t) | - Self::L1Message(t) => &t.logs_bloom, + Self::Legacy(t) + | Self::Eip2930(t) + | Self::Eip1559(t) + | Self::Eip7702(t) + | Self::L1Message(t) => &t.logs_bloom, } } @@ -144,11 +144,11 @@ impl ScrollReceiptEnvelope { /// receipt types may be added. pub const fn as_receipt(&self) -> Option<&Receipt> { match self { - Self::Legacy(t) | - Self::Eip2930(t) | - Self::Eip1559(t) | - Self::Eip7702(t) | - Self::L1Message(t) => Some(&t.receipt), + Self::Legacy(t) + | Self::Eip2930(t) + | Self::Eip1559(t) + | Self::Eip7702(t) + | Self::L1Message(t) => Some(&t.receipt), } } } @@ -157,11 +157,11 @@ impl ScrollReceiptEnvelope { /// Get the length of the inner receipt in the 2718 encoding. pub fn inner_length(&self) -> usize { match self { - Self::Legacy(t) | - Self::Eip2930(t) | - Self::Eip1559(t) | - Self::Eip7702(t) | - Self::L1Message(t) => t.length(), + Self::Legacy(t) + | Self::Eip2930(t) + | Self::Eip1559(t) + | Self::Eip7702(t) + | Self::L1Message(t) => t.length(), } } @@ -251,11 +251,11 @@ impl Encodable2718 for ScrollReceiptEnvelope { Some(ty) => out.put_u8(ty), } match self { - Self::Legacy(t) | - Self::Eip2930(t) | - Self::Eip1559(t) | - Self::Eip7702(t) | - Self::L1Message(t) => t.encode(out), + Self::Legacy(t) + | Self::Eip2930(t) + | Self::Eip1559(t) + | Self::Eip7702(t) + | Self::L1Message(t) => t.encode(out), } } } diff --git a/crates/scroll/alloy/consensus/src/transaction/l1_message.rs b/crates/scroll/alloy/consensus/src/transaction/l1_message.rs index 0c200904fb..2f18e24bbc 100644 --- a/crates/scroll/alloy/consensus/src/transaction/l1_message.rs +++ b/crates/scroll/alloy/consensus/src/transaction/l1_message.rs @@ -102,12 +102,12 @@ impl TxL1Message { /// Outputs the length of the transaction's fields, without a RLP header. pub fn rlp_encoded_fields_length(&self) -> usize { - self.queue_index.length() + - self.gas_limit.length() + - self.to.length() + - self.value.length() + - self.input.0.length() + - self.sender.length() + self.queue_index.length() + + self.gas_limit.length() + + self.to.length() + + self.value.length() + + self.input.0.length() + + self.sender.length() } /// Encode the fields of the transaction without a RLP header. diff --git a/crates/scroll/alloy/evm/src/block/feynman.rs b/crates/scroll/alloy/evm/src/block/feynman.rs index e815f87cc5..6e443bac87 100644 --- a/crates/scroll/alloy/evm/src/block/feynman.rs +++ b/crates/scroll/alloy/evm/src/block/feynman.rs @@ -50,7 +50,7 @@ pub(super) fn apply_feynman_hard_fork( // other reliable way to apply the change only at the transition block, since // `ScrollBlockExecutor` does not have access to the parent timestamp. if matches!(oracle.storage_slot(IS_FEYNMAN_SLOT), Some(val) if val == IS_FEYNMAN) { - return Ok(()) + return Ok(()); } // compute the code hash diff --git a/crates/scroll/alloy/evm/src/block/mod.rs b/crates/scroll/alloy/evm/src/block/mod.rs index 054b5a5b96..ac696cfa5d 100644 --- a/crates/scroll/alloy/evm/src/block/mod.rs +++ b/crates/scroll/alloy/evm/src/block/mod.rs @@ -207,7 +207,7 @@ where transaction_gas_limit: tx.tx().gas_limit(), block_available_gas, } - .into()) + .into()); } let hash = tx.tx().trie_hash(); @@ -219,30 +219,30 @@ where hash, error: Box::new(InvalidTransaction::Eip2930NotSupported), } - .into()) + .into()); } if tx.tx().is_eip1559() && !chain_spec.is_curie_active_at_block(block.number.to()) { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip1559NotSupported), } - .into()) + .into()); } if tx.tx().is_eip4844() { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip4844NotSupported), } - .into()) + .into()); } - if tx.tx().is_eip7702() && - !chain_spec.is_euclid_v2_active_at_timestamp(block.timestamp.to()) + if tx.tx().is_eip7702() + && !chain_spec.is_euclid_v2_active_at_timestamp(block.timestamp.to()) { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip7702NotSupported), } - .into()) + .into()); } // disable the base fee and nonce checks for l1 messages. @@ -254,7 +254,7 @@ where self.evm.transact(tx).map_err(move |err| BlockExecutionError::evm(err, hash))?; if !f(&result).should_commit() { - return Ok(None) + return Ok(None); }; let l1_fee = if is_l1_message { diff --git a/crates/scroll/alloy/evm/src/system_caller.rs b/crates/scroll/alloy/evm/src/system_caller.rs index 83cd003374..77e21b1b70 100644 --- a/crates/scroll/alloy/evm/src/system_caller.rs +++ b/crates/scroll/alloy/evm/src/system_caller.rs @@ -79,7 +79,9 @@ fn transact_blockhashes_contract_call( ) { Ok(res) => res, Err(e) => { - return Err(BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) + return Err( + BlockValidationError::BlockHashContractCall { message: e.to_string() }.into() + ) } }; diff --git a/crates/scroll/alloy/evm/src/tx/compression.rs b/crates/scroll/alloy/evm/src/tx/compression.rs index f8f151df77..4080d523ab 100644 --- a/crates/scroll/alloy/evm/src/tx/compression.rs +++ b/crates/scroll/alloy/evm/src/tx/compression.rs @@ -49,7 +49,7 @@ mod zstd_compression { pub fn compute_compression_ratio>(bytes: &T) -> U256 { // By definition, the compression ratio of empty data is infinity if bytes.as_ref().is_empty() { - return U256::MAX + return U256::MAX; } // Instantiate the compressor diff --git a/crates/scroll/alloy/rpc-types-engine/src/attributes.rs b/crates/scroll/alloy/rpc-types-engine/src/attributes.rs index 25b522ac03..4e2343059f 100644 --- a/crates/scroll/alloy/rpc-types-engine/src/attributes.rs +++ b/crates/scroll/alloy/rpc-types-engine/src/attributes.rs @@ -47,11 +47,11 @@ impl BlockDataHint { /// Returns `true` if the [`BlockDataHint`] is empty. pub const fn is_empty(&self) -> bool { - self.extra_data.is_none() && - self.state_root.is_none() && - self.coinbase.is_none() && - self.nonce.is_none() && - self.difficulty.is_none() + self.extra_data.is_none() + && self.state_root.is_none() + && self.coinbase.is_none() + && self.nonce.is_none() + && self.difficulty.is_none() } } diff --git a/crates/scroll/chainspec/src/lib.rs b/crates/scroll/chainspec/src/lib.rs index 776b6b6cde..efcd944bba 100644 --- a/crates/scroll/chainspec/src/lib.rs +++ b/crates/scroll/chainspec/src/lib.rs @@ -309,8 +309,8 @@ impl Hardforks for ScrollChainSpec { for (_, cond) in self.hardforks.forks_iter() { // handle block based forks and the sepolia merge netsplit block edge case (TTD // ForkCondition with Some(block)) - if let ForkCondition::Block(block) | - ForkCondition::TTD { fork_block: Some(block), .. } = cond + if let ForkCondition::Block(block) + | ForkCondition::TTD { fork_block: Some(block), .. } = cond { if head.number >= block { // skip duplicated hardforks: hardforks enabled at genesis block @@ -321,7 +321,7 @@ impl Hardforks for ScrollChainSpec { } else { // we can return here because this block fork is not active, so we set the // `next` value - return ForkId { hash: forkhash, next: block } + return ForkId { hash: forkhash, next: block }; } } } @@ -337,8 +337,8 @@ impl Hardforks for ScrollChainSpec { // We filter out TTD-based forks w/o a pre-known block since those do not show up in the // fork filter. Some(match condition { - ForkCondition::Block(block) | - ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), + ForkCondition::Block(block) + | ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), _ => return None, }) }); diff --git a/crates/scroll/consensus/src/validation.rs b/crates/scroll/consensus/src/validation.rs index adcd2706f8..701bb258a9 100644 --- a/crates/scroll/consensus/src/validation.rs +++ b/crates/scroll/consensus/src/validation.rs @@ -98,17 +98,19 @@ impl Consensus expected: block.ommers_hash(), } .into(), - )) + )); } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())) + return Err(ConsensusError::BodyTransactionRootDiff(error.into())); } // Check withdrawals are empty if block.body().withdrawals().is_some() { - return Err(ConsensusError::Other(ScrollConsensusError::WithdrawalsNonEmpty.to_string())) + return Err(ConsensusError::Other( + ScrollConsensusError::WithdrawalsNonEmpty.to_string(), + )); } Ok(()) @@ -120,7 +122,7 @@ impl HeaderValidator< { fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty) + return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); } validate_header_gas(header.header())?; @@ -143,7 +145,7 @@ impl HeaderValidator< if self.chain_spec.blob_params_at_timestamp(header.timestamp()).is_some() { return Err(ConsensusError::Other( ScrollConsensusError::UnexpectedBlobParams.to_string(), - )) + )); } Ok(()) @@ -164,10 +166,10 @@ fn validate_header_base_fee( header: &H, chain_spec: &ChainSpec, ) -> Result<(), ConsensusError> { - if chain_spec.scroll_fork_activation(ScrollHardfork::Curie).active_at_block(header.number()) && - header.base_fee_per_gas().is_none() + if chain_spec.scroll_fork_activation(ScrollHardfork::Curie).active_at_block(header.number()) + && header.base_fee_per_gas().is_none() { - return Err(ConsensusError::BaseFeeMissing) + return Err(ConsensusError::BaseFeeMissing); } Ok(()) } @@ -185,7 +187,7 @@ fn validate_against_parent_timestamp( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp(), timestamp: header.timestamp(), - }) + }); } Ok(()) } diff --git a/crates/scroll/evm/src/lib.rs b/crates/scroll/evm/src/lib.rs index 84b1afca19..dad40b3e1e 100644 --- a/crates/scroll/evm/src/lib.rs +++ b/crates/scroll/evm/src/lib.rs @@ -116,11 +116,11 @@ pub fn spec_id_at_timestamp_and_number( ScrollSpecId::EUCLID } else if chain_spec .scroll_fork_activation(ScrollHardfork::Euclid) - .active_at_timestamp_or_number(timestamp, number) || - chain_spec + .active_at_timestamp_or_number(timestamp, number) + || chain_spec .scroll_fork_activation(ScrollHardfork::DarwinV2) - .active_at_timestamp_or_number(timestamp, number) || - chain_spec + .active_at_timestamp_or_number(timestamp, number) + || chain_spec .scroll_fork_activation(ScrollHardfork::Darwin) .active_at_timestamp_or_number(timestamp, number) { diff --git a/crates/scroll/payload/src/builder.rs b/crates/scroll/payload/src/builder.rs index c69d2bd7e1..71fe3810d0 100644 --- a/crates/scroll/payload/src/builder.rs +++ b/crates/scroll/payload/src/builder.rs @@ -255,7 +255,7 @@ impl ScrollBuilder<'_, Txs> { // check if the new payload is even more valuable if !ctx.is_better_payload(info.total_fees) { // can skip building the block - return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }) + return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }); } } @@ -424,7 +424,7 @@ where if sequencer_tx.value().is_eip4844() { return Err(PayloadBuilderError::other( ScrollPayloadBuilderError::BlobTransactionRejected, - )) + )); } // Convert the transaction to a [RecoveredTx]. This is @@ -442,11 +442,11 @@ where .. })) => { tracing::trace!(target: "payload_builder", %error, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue + continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; @@ -479,18 +479,18 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue + continue; } // A sequencer's block should never contain blob or deposit transactions from the pool. if tx.is_eip4844() || tx.is_l1_message() { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue + continue; } // check if the job was cancelled, if so we can exit early if self.cancel.is_cancelled() { - return Ok(Some(())) + return Ok(Some(())); } // check if the execution needs to be halted. @@ -514,11 +514,11 @@ where tracing::trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid(tx.signer(), tx.nonce()); } - continue + continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; diff --git a/crates/scroll/payload/src/config.rs b/crates/scroll/payload/src/config.rs index d51c59bf1d..fc81719790 100644 --- a/crates/scroll/payload/src/config.rs +++ b/crates/scroll/payload/src/config.rs @@ -41,8 +41,8 @@ impl PayloadBuildingBreaker { /// Returns whether the payload building should stop. pub(super) fn should_break(&self, cumulative_gas_used: u64) -> bool { - self.start.elapsed() >= self.time_limit || - cumulative_gas_used > self.gas_limit.saturating_sub(MIN_TRANSACTION_GAS) + self.start.elapsed() >= self.time_limit + || cumulative_gas_used > self.gas_limit.saturating_sub(MIN_TRANSACTION_GAS) } } diff --git a/crates/scroll/primitives/src/receipt.rs b/crates/scroll/primitives/src/receipt.rs index 6e214b3108..d57b6248af 100644 --- a/crates/scroll/primitives/src/receipt.rs +++ b/crates/scroll/primitives/src/receipt.rs @@ -44,10 +44,10 @@ impl ScrollReceipt { /// Returns inner [`Receipt`], pub const fn as_receipt(&self) -> &Receipt { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => &receipt.inner, + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => &receipt.inner, Self::L1Message(receipt) => receipt, } } @@ -55,10 +55,10 @@ impl ScrollReceipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), Self::L1Message(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), } } @@ -66,10 +66,10 @@ impl ScrollReceipt { /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encode_fields(&self, bloom: &Bloom, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), Self::L1Message(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), } } @@ -122,10 +122,10 @@ impl ScrollReceipt { /// RLP-encodes receipt fields without an RLP header. pub fn rlp_encode_fields_without_bloom(&self, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => { + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => { receipt.inner.status.encode(out); receipt.inner.cumulative_gas_used.encode(out); receipt.inner.logs.encode(out); @@ -141,18 +141,18 @@ impl ScrollReceipt { /// Returns length of RLP-encoded receipt fields without an RLP header. pub fn rlp_encoded_fields_length_without_bloom(&self) -> usize { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => { - receipt.inner.status.length() + - receipt.inner.cumulative_gas_used.length() + - receipt.inner.logs.length() + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => { + receipt.inner.status.length() + + receipt.inner.cumulative_gas_used.length() + + receipt.inner.logs.length() } Self::L1Message(receipt) => { - receipt.status.length() + - receipt.cumulative_gas_used.length() + - receipt.logs.length() + receipt.status.length() + + receipt.cumulative_gas_used.length() + + receipt.logs.length() } } } @@ -198,10 +198,10 @@ impl ScrollReceipt { /// Returns the l1 fee for the transaction receipt. pub const fn l1_fee(&self) -> U256 { match self { - Self::Legacy(receipt) | - Self::Eip2930(receipt) | - Self::Eip1559(receipt) | - Self::Eip7702(receipt) => receipt.l1_fee, + Self::Legacy(receipt) + | Self::Eip2930(receipt) + | Self::Eip1559(receipt) + | Self::Eip7702(receipt) => receipt.l1_fee, Self::L1Message(_) => U256::ZERO, } } @@ -258,7 +258,7 @@ impl RlpDecodableReceipt for ScrollReceipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, ScrollTxType::Legacy) + return Self::rlp_decode_inner(buf, ScrollTxType::Legacy); } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -278,8 +278,8 @@ impl RlpDecodableReceipt for ScrollReceipt { impl Encodable2718 for ScrollReceipt { fn encode_2718_len(&self) -> usize { - !self.tx_type().is_legacy() as usize + - self.rlp_header_inner_without_bloom().length_with_payload() + !self.tx_type().is_legacy() as usize + + self.rlp_header_inner_without_bloom().length_with_payload() } fn encode_2718(&self, out: &mut dyn BufMut) { diff --git a/crates/scroll/rpc/src/error.rs b/crates/scroll/rpc/src/error.rs index 23ad2a9466..5471ccf1c8 100644 --- a/crates/scroll/rpc/src/error.rs +++ b/crates/scroll/rpc/src/error.rs @@ -3,7 +3,7 @@ use alloy_json_rpc::ErrorPayload; use alloy_rpc_types_eth::BlockError; use alloy_transport::{RpcError, TransportErrorKind}; -use jsonrpsee_types::error::{INTERNAL_ERROR_CODE}; +use jsonrpsee_types::error::INTERNAL_ERROR_CODE; use reth_evm::execute::ProviderError; use reth_rpc_convert::transaction::EthTxEnvError; use reth_rpc_eth_api::{AsEthApiError, TransactionConversionError}; diff --git a/crates/scroll/rpc/src/eth/block.rs b/crates/scroll/rpc/src/eth/block.rs index 49bcd5b29e..f3205cafe3 100644 --- a/crates/scroll/rpc/src/eth/block.rs +++ b/crates/scroll/rpc/src/eth/block.rs @@ -62,7 +62,7 @@ where .map(|builder| builder.build()) }) .collect::, Self::Error>>() - .map(Some) + .map(Some); } Ok(None) diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 07a7fbb569..11888567f0 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -13,8 +13,7 @@ use reth_provider::{ }; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, - TxInfoMapper, + EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; use reth_scroll_primitives::ScrollReceipt; @@ -45,16 +44,16 @@ where // blocks that it builds. if let Some(client) = self.raw_tx_forwarder().as_ref() { tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); - + // Retain tx in local tx pool before forwarding to sequencer rpc, for local RPC usage. let hash = self .pool() .add_transaction(TransactionOrigin::Local, pool_transaction.clone()) .await .map_err(Self::Error::from_eth_err)?; - + tracing::debug!(target: "rpc::eth", %hash, "successfully added transaction to local tx pool"); - + // Forward to remote sequencer RPC. match client.forward_raw_transaction(&tx).await { Ok(sequencer_hash) => { @@ -64,7 +63,7 @@ where tracing::warn!(target: "rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); } } - + return Ok(hash); } diff --git a/crates/scroll/rpc/src/lib.rs b/crates/scroll/rpc/src/lib.rs index 116bc181c8..76ecfbec7b 100644 --- a/crates/scroll/rpc/src/lib.rs +++ b/crates/scroll/rpc/src/lib.rs @@ -14,4 +14,4 @@ pub mod sequencer; pub use error::{ScrollEthApiError, SequencerClientError}; pub use eth::{ScrollEthApi, ScrollReceiptBuilder}; -pub use sequencer::SequencerClient; \ No newline at end of file +pub use sequencer::SequencerClient; diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs index 5c7c5e610c..094840f99e 100644 --- a/crates/scroll/rpc/src/sequencer.rs +++ b/crates/scroll/rpc/src/sequencer.rs @@ -155,10 +155,7 @@ mod tests { let request = client .client() - .make_request( - "eth_sendRawTransaction", - format!("0x{}", hex::encode("abcd")), - ) + .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) .serialize() .unwrap() .take_request(); @@ -190,10 +187,7 @@ mod tests { let request = client .client() - .make_request( - "eth_sendRawTransaction", - format!("0x{}", hex::encode("abcd")), - ) + .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) .serialize() .unwrap() .take_request(); diff --git a/crates/scroll/txpool/src/validator.rs b/crates/scroll/txpool/src/validator.rs index 3b6ae3aac4..450d0db323 100644 --- a/crates/scroll/txpool/src/validator.rs +++ b/crates/scroll/txpool/src/validator.rs @@ -141,14 +141,14 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ) + ); } let outcome = self.inner.validate_one(origin, transaction); if !self.requires_l1_data_gas_fee() { // no need to check L1 gas fee - return outcome + return outcome; } // ensure that the account has enough balance to cover the L1 gas cost @@ -191,7 +191,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ) + ); } return TransactionValidationOutcome::Valid { @@ -201,7 +201,7 @@ where transaction: valid_tx, propagate, authorities, - } + }; } outcome diff --git a/crates/stages/api/src/error.rs b/crates/stages/api/src/error.rs index b4bbf390e2..c11ff05c61 100644 --- a/crates/stages/api/src/error.rs +++ b/crates/stages/api/src/error.rs @@ -123,15 +123,15 @@ impl StageError { pub const fn is_fatal(&self) -> bool { matches!( self, - Self::Database(_) | - Self::Download(_) | - Self::DatabaseIntegrity(_) | - Self::StageCheckpoint(_) | - Self::MissingDownloadBuffer | - Self::MissingSyncGap | - Self::ChannelClosed | - Self::Internal(_) | - Self::Fatal(_) + Self::Database(_) + | Self::Download(_) + | Self::DatabaseIntegrity(_) + | Self::StageCheckpoint(_) + | Self::MissingDownloadBuffer + | Self::MissingSyncGap + | Self::ChannelClosed + | Self::Internal(_) + | Self::Fatal(_) ) } } diff --git a/crates/stages/api/src/metrics/listener.rs b/crates/stages/api/src/metrics/listener.rs index aba001a92f..b8df526c0f 100644 --- a/crates/stages/api/src/metrics/listener.rs +++ b/crates/stages/api/src/metrics/listener.rs @@ -90,7 +90,7 @@ impl Future for MetricsListener { loop { let Some(event) = ready!(this.events_rx.poll_recv(cx)) else { // Channel has closed - return Poll::Ready(()) + return Poll::Ready(()); }; this.handle_event(event); diff --git a/crates/stages/api/src/pipeline/mod.rs b/crates/stages/api/src/pipeline/mod.rs index b8d41e9e55..214fc61ba3 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -155,14 +155,14 @@ impl Pipeline { PipelineTarget::Sync(tip) => self.set_tip(tip), PipelineTarget::Unwind(target) => { if let Err(err) = self.move_to_static_files() { - return (self, Err(err.into())) + return (self, Err(err.into())); } if let Err(err) = self.unwind(target, None) { - return (self, Err(err)) + return (self, Err(err)); } self.progress.update(target); - return (self, Ok(ControlFlow::Continue { block_number: target })) + return (self, Ok(ControlFlow::Continue { block_number: target })); } } } @@ -182,13 +182,14 @@ impl Pipeline { let next_action = self.run_loop().await?; if next_action.is_unwind() && self.fail_on_unwind { - return Err(PipelineError::UnexpectedUnwind) + return Err(PipelineError::UnexpectedUnwind); } // Terminate the loop early if it's reached the maximum user // configured block. - if next_action.should_continue() && - self.progress + if next_action.should_continue() + && self + .progress .minimum_block_number .zip(self.max_block) .is_some_and(|(progress, target)| progress >= target) @@ -200,7 +201,7 @@ impl Pipeline { max_block = ?self.max_block, "Terminating pipeline." ); - return Ok(()) + return Ok(()); } } } @@ -238,7 +239,7 @@ impl Pipeline { ControlFlow::Continue { block_number } => self.progress.update(block_number), ControlFlow::Unwind { target, bad_block } => { self.unwind(target, Some(bad_block.block.number))?; - return Ok(ControlFlow::Unwind { target, bad_block }) + return Ok(ControlFlow::Unwind { target, bad_block }); } } @@ -327,7 +328,7 @@ impl Pipeline { ); self.event_sender.notify(PipelineEvent::Skipped { stage_id }); - continue + continue; } info!( @@ -373,8 +374,8 @@ impl Pipeline { // If None, that means the finalized block is not written so we should // always save in that case - if last_saved_finalized_block_number.is_none() || - Some(checkpoint.block_number) < last_saved_finalized_block_number + if last_saved_finalized_block_number.is_none() + || Some(checkpoint.block_number) < last_saved_finalized_block_number { provider_rw.save_finalized_block_number(BlockNumber::from( checkpoint.block_number, @@ -390,7 +391,7 @@ impl Pipeline { Err(err) => { self.event_sender.notify(PipelineEvent::Error { stage_id }); - return Err(PipelineError::Stage(StageError::Fatal(Box::new(err)))) + return Err(PipelineError::Stage(StageError::Fatal(Box::new(err)))); } } } @@ -429,7 +430,7 @@ impl Pipeline { // We reached the maximum block, so we skip the stage return Ok(ControlFlow::NoProgress { block_number: prev_checkpoint.map(|progress| progress.block_number), - }) + }); } let exec_input = ExecInput { target, checkpoint: prev_checkpoint }; @@ -497,7 +498,7 @@ impl Pipeline { ControlFlow::Continue { block_number } } else { ControlFlow::NoProgress { block_number: Some(block_number) } - }) + }); } } Err(err) => { @@ -505,7 +506,7 @@ impl Pipeline { self.event_sender.notify(PipelineEvent::Error { stage_id }); if let Some(ctrl) = self.on_stage_error(stage_id, prev_checkpoint, err)? { - return Ok(ctrl) + return Ok(ctrl); } } } @@ -522,8 +523,8 @@ impl Pipeline { warn!(target: "sync::pipeline", stage = %stage_id, ?local_head, ?header, %error, "Stage encountered detached head"); if let Some(last_detached_head_unwind_target) = self.last_detached_head_unwind_target { - if local_head.block.hash == last_detached_head_unwind_target && - header.block.number == local_head.block.number + 1 + if local_head.block.hash == last_detached_head_unwind_target + && header.block.number == local_head.block.number + 1 { self.detached_head_attempts += 1; } else { diff --git a/crates/stages/api/src/pipeline/set.rs b/crates/stages/api/src/pipeline/set.rs index 8aea87ba03..5ab4e390f5 100644 --- a/crates/stages/api/src/pipeline/set.rs +++ b/crates/stages/api/src/pipeline/set.rs @@ -241,7 +241,7 @@ impl StageSetBuilder { F: FnOnce() -> bool, { if f() { - return self.disable(stage_id) + return self.disable(stage_id); } self } @@ -255,7 +255,7 @@ impl StageSetBuilder { F: FnOnce() -> bool, { if f() { - return self.disable_all(stages) + return self.disable_all(stages); } self } diff --git a/crates/stages/api/src/stage.rs b/crates/stages/api/src/stage.rs index e390f02e15..f251c3e40e 100644 --- a/crates/stages/api/src/stage.rs +++ b/crates/stages/api/src/stage.rs @@ -95,7 +95,7 @@ impl ExecInput { if all_tx_cnt == 0 { // if there is no more transaction return back. - return Ok((first_tx_num..first_tx_num, start_block..=target_block, true)) + return Ok((first_tx_num..first_tx_num, start_block..=target_block, true)); } // get block of this tx diff --git a/crates/stages/stages/src/stages/bodies.rs b/crates/stages/stages/src/stages/bodies.rs index e503d8b5d5..321085d2e7 100644 --- a/crates/stages/stages/src/stages/bodies.rs +++ b/crates/stages/stages/src/stages/bodies.rs @@ -125,7 +125,7 @@ where &static_file_provider, provider, StaticFileSegment::Transactions, - )?) + )?); } } else { return Err(missing_static_data_error( @@ -133,7 +133,7 @@ where &static_file_provider, provider, StaticFileSegment::Transactions, - )?) + )?); } } Ordering::Equal => {} @@ -162,7 +162,7 @@ where input: ExecInput, ) -> Poll> { if input.target_reached() || self.buffer.is_some() { - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } // Update the header range on the downloader @@ -188,7 +188,7 @@ where /// header, limited by the stage's batch size. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -789,7 +789,7 @@ mod tests { let this = self.get_mut(); if this.headers.is_empty() { - return Poll::Ready(None) + return Poll::Ready(None); } let mut response = @@ -806,12 +806,12 @@ mod tests { } if response.len() as u64 >= this.batch_size { - break + break; } } if !response.is_empty() { - return Poll::Ready(Some(Ok(response))) + return Poll::Ready(Some(Ok(response))); } panic!("requested bodies without setting headers") diff --git a/crates/stages/stages/src/stages/era.rs b/crates/stages/stages/src/stages/era.rs index 38b7f0c0db..b67cc96c5d 100644 --- a/crates/stages/stages/src/stages/era.rs +++ b/crates/stages/stages/src/stages/era.rs @@ -446,8 +446,8 @@ mod tests { .header_td_by_number(initial_checkpoint.saturating_sub(1))? .unwrap_or_default(); - for block_num in initial_checkpoint.. - output + for block_num in initial_checkpoint + ..output .checkpoint .block_number .min(self.responses.as_ref().map(|v| v.len()).unwrap_or_default() diff --git a/crates/stages/stages/src/stages/execution.rs b/crates/stages/stages/src/stages/execution.rs index e5592cd8de..adf0f0a88d 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -167,8 +167,8 @@ where ) -> Result { // We can only prune changesets if we're not executing MerkleStage from scratch (by // threshold or first-sync) - Ok(max_block - start_block > self.external_clean_threshold || - provider.count_entries::()?.is_zero()) + Ok(max_block - start_block > self.external_clean_threshold + || provider.count_entries::()?.is_zero()) } /// Performs consistency check on static files. @@ -191,7 +191,7 @@ where // If there's any receipts pruning configured, receipts are written directly to database and // inconsistencies are expected. if provider.prune_modes_ref().has_receipts_pruning() { - return Ok(()) + return Ok(()); } // Get next expected receipt number @@ -232,7 +232,7 @@ where if next_receipt_num_after_unwind > next_static_file_receipt_num { // This means we need a deeper unwind. } else { - return Ok(()) + return Ok(()); } } @@ -241,7 +241,7 @@ where &static_file_provider, provider, StaticFileSegment::Receipts, - )?) + )?); } } @@ -280,7 +280,7 @@ where /// Execute the stage fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let start_block = input.next_block(); @@ -348,7 +348,7 @@ where return Err(StageError::Block { block: Box::new(block.block_with_parent()), error: BlockErrorKind::Validation(err), - }) + }); } results.push(result); @@ -385,7 +385,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break + break; } } @@ -420,7 +420,7 @@ where // means that we didn't send the notification to ExExes return Err(StageError::PostExecuteCommit( "Previous post execute commit input wasn't processed", - )) + )); } } @@ -434,15 +434,15 @@ where let Some(reverts) = state.bundle.reverts.get_mut((block_number - start_block) as usize) else { - break + break; }; // If both account history and storage history pruning is configured, clear reverts // for this block. if prune_modes .account_history - .is_some_and(|m| m.should_prune(block_number, max_block)) && - prune_modes + .is_some_and(|m| m.should_prune(block_number, max_block)) + && prune_modes .storage_history .is_some_and(|m| m.should_prune(block_number, max_block)) { @@ -496,7 +496,7 @@ where if range.is_empty() { return Ok(UnwindOutput { checkpoint: input.checkpoint.with_block_number(input.unwind_to), - }) + }); } self.ensure_consistency(provider, input.checkpoint.block_number, Some(unwind_to))?; @@ -619,8 +619,8 @@ fn execution_checkpoint( block_range: CheckpointBlockRange { from: start_block, to: max_block }, progress: EntitiesCheckpoint { processed, - total: processed + - calculate_gas_used_from_headers(provider, start_block..=max_block)?, + total: processed + + calculate_gas_used_from_headers(provider, start_block..=max_block)?, }, } } diff --git a/crates/stages/stages/src/stages/finish.rs b/crates/stages/stages/src/stages/finish.rs index 1b9e624b41..a0498b994e 100644 --- a/crates/stages/stages/src/stages/finish.rs +++ b/crates/stages/stages/src/stages/finish.rs @@ -78,7 +78,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()) + return Ok(Vec::default()); } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/hashing_account.rs b/crates/stages/stages/src/stages/hashing_account.rs index 726f9e8218..227a3eada1 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -144,7 +144,7 @@ where /// Execute the stage. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -469,7 +469,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } } self.check_hashed_accounts() diff --git a/crates/stages/stages/src/stages/hashing_storage.rs b/crates/stages/stages/src/stages/hashing_storage.rs index af811828fb..a64d4e7fea 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -75,7 +75,7 @@ where fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { let tx = provider.tx_ref(); if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -270,7 +270,7 @@ mod tests { // Continue from checkpoint input.checkpoint = Some(checkpoint); - continue + continue; } assert_eq!(checkpoint.block_number, previous_stage); assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint { @@ -288,7 +288,7 @@ mod tests { "execution validation" ); - break + break; } panic!("Failed execution"); } @@ -422,7 +422,7 @@ mod tests { let start_block = input.checkpoint().block_number + 1; let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } } self.check_hashed_storage() @@ -523,7 +523,7 @@ mod tests { while let Some((bn_address, entry)) = rev_changeset_walker.next().transpose()? { if bn_address.block_number() < target_block { - break + break; } if storage_cursor diff --git a/crates/stages/stages/src/stages/headers.rs b/crates/stages/stages/src/stages/headers.rs index c622e743c1..47c6956a16 100644 --- a/crates/stages/stages/src/stages/headers.rs +++ b/crates/stages/stages/src/stages/headers.rs @@ -130,7 +130,7 @@ where let (header, header_hash) = sealed_header.split_ref(); if header.number() == 0 { - continue + continue; } last_header_number = header.number(); @@ -206,7 +206,7 @@ where // Return if stage has already completed the gap on the ETL files if self.is_etl_ready { - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } // Lookup the head and tip of the sync range @@ -225,7 +225,7 @@ where ); self.is_etl_ready = true; self.sync_gap = Some(gap); - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } debug!(target: "sync::stages::headers", ?tip, head = ?gap.local_head.hash(), "Commencing sync"); @@ -260,7 +260,7 @@ where // filled the gap. if header_number == local_head_number + 1 { self.is_etl_ready = true; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } } @@ -271,11 +271,11 @@ where local_head: Box::new(local_head.block_with_parent()), header: Box::new(header.block_with_parent()), error, - })) + })); } None => { self.sync_gap = None; - return Poll::Ready(Err(StageError::ChannelClosed)) + return Poll::Ready(Err(StageError::ChannelClosed)); } } } @@ -288,12 +288,12 @@ where if self.sync_gap.take().ok_or(StageError::MissingSyncGap)?.is_closed() { self.is_etl_ready = false; - return Ok(ExecOutput::done(current_checkpoint)) + return Ok(ExecOutput::done(current_checkpoint)); } // We should be here only after we have downloaded all headers into the disk buffer (ETL). if !self.is_etl_ready { - return Err(StageError::MissingDownloadBuffer) + return Err(StageError::MissingDownloadBuffer); } // Reset flag @@ -480,7 +480,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()) + return Ok(Vec::default()); } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/index_account_history.rs b/crates/stages/stages/src/stages/index_account_history.rs index 37db4f5f9f..2d705d4db9 100644 --- a/crates/stages/stages/src/stages/index_account_history.rs +++ b/crates/stages/stages/src/stages/index_account_history.rs @@ -88,7 +88,7 @@ where } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let mut range = input.next_block_range(); @@ -568,7 +568,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } assert_eq!( diff --git a/crates/stages/stages/src/stages/index_storage_history.rs b/crates/stages/stages/src/stages/index_storage_history.rs index 09c9030cb3..2711b0701e 100644 --- a/crates/stages/stages/src/stages/index_storage_history.rs +++ b/crates/stages/stages/src/stages/index_storage_history.rs @@ -91,7 +91,7 @@ where } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let mut range = input.next_block_range(); @@ -591,7 +591,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } assert_eq!( diff --git a/crates/stages/stages/src/stages/merkle.rs b/crates/stages/stages/src/stages/merkle.rs index 7d5dd69d2b..f5defa5df8 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -158,7 +158,7 @@ where provider.get_stage_checkpoint_progress(StageId::MerkleExecute)?.unwrap_or_default(); if buf.is_empty() { - return Ok(None) + return Ok(None); } let (checkpoint, _) = MerkleCheckpoint::from_compact(&buf, buf.len()); @@ -264,8 +264,8 @@ where } .unwrap_or(EntitiesCheckpoint { processed: 0, - total: (provider.count_entries::()? + - provider.count_entries::()?) + total: (provider.count_entries::()? + + provider.count_entries::()?) as u64, }); @@ -296,7 +296,7 @@ where .checkpoint() .with_entities_stage_checkpoint(entities_checkpoint), done: false, - }) + }); } StateRootProgress::Complete(root, hashed_entries_walked, updates) => { provider.write_trie_updates(&updates)?; @@ -335,8 +335,8 @@ where "Incremental merkle hashing did not produce a final root".into(), ))?; - let total_hashed_entries = (provider.count_entries::()? + - provider.count_entries::()?) + let total_hashed_entries = (provider.count_entries::()? + + provider.count_entries::()?) as u64; let entities_checkpoint = EntitiesCheckpoint { @@ -378,14 +378,14 @@ where let range = input.unwind_block_range(); if matches!(self, Self::Execution { .. }) { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); - return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) }) + return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) }); } let mut entities_checkpoint = input.checkpoint.entities_stage_checkpoint().unwrap_or(EntitiesCheckpoint { processed: 0, - total: (tx.entries::()? + - tx.entries::()?) as u64, + total: (tx.entries::()? + + tx.entries::()?) as u64, }); if input.unwind_to == 0 { @@ -397,7 +397,7 @@ where return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) .with_entities_stage_checkpoint(entities_checkpoint), - }) + }); } // Unwind trie only if there are transitions @@ -789,7 +789,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if bn_address.block_number() < target_block { - break + break; } tree.entry(keccak256(bn_address.address())) @@ -820,7 +820,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if block_number < target_block { - break + break; } if let Some(acc) = account_before_tx.info { diff --git a/crates/stages/stages/src/stages/prune.rs b/crates/stages/stages/src/stages/prune.rs index 6671c4a413..4fa4313f49 100644 --- a/crates/stages/stages/src/stages/prune.rs +++ b/crates/stages/stages/src/stages/prune.rs @@ -233,7 +233,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } let provider = self.db.factory.provider()?; diff --git a/crates/stages/stages/src/stages/s3/downloader/fetch.rs b/crates/stages/stages/src/stages/s3/downloader/fetch.rs index 7f82552bda..efac05c255 100644 --- a/crates/stages/stages/src/stages/s3/downloader/fetch.rs +++ b/crates/stages/stages/src/stages/s3/downloader/fetch.rs @@ -47,7 +47,7 @@ pub async fn fetch( let data_file = download_dir.join(filename); let mut metadata = metadata(&data_file, url).await?; if metadata.is_done() { - return Ok(()) + return Ok(()); } // Ensure the file is preallocated so we can download it concurrently @@ -95,7 +95,7 @@ pub async fn fetch( } WorkerResponse::Err { worker_id, error } => { error!(target: "sync::stages::s3::downloader", ?worker_id, "Worker found an error: {:?}", error); - return Err(error) + return Err(error); } }; @@ -133,7 +133,7 @@ pub async fn fetch( async fn metadata(data_file: &Path, url: &str) -> Result { if Metadata::file_path(data_file).exists() { debug!(target: "sync::stages::s3::downloader", ?data_file, "Loading metadata "); - return Metadata::load(data_file) + return Metadata::load(data_file); } let client = Client::new(); @@ -158,7 +158,7 @@ fn check_file_hash(path: &Path, expected: &B256) -> Result<(), DownloaderError> let file_hash = hasher.finalize(); if file_hash.as_bytes() != expected { - return Err(DownloaderError::InvalidFileHash(file_hash.as_bytes().into(), *expected)) + return Err(DownloaderError::InvalidFileHash(file_hash.as_bytes().into(), *expected)); } Ok(()) diff --git a/crates/stages/stages/src/stages/s3/downloader/meta.rs b/crates/stages/stages/src/stages/s3/downloader/meta.rs index 7ff4213fff..d44b06ad12 100644 --- a/crates/stages/stages/src/stages/s3/downloader/meta.rs +++ b/crates/stages/stages/src/stages/s3/downloader/meta.rs @@ -62,7 +62,7 @@ impl Metadata { let num_chunks = self.chunks.len(); if index >= self.chunks.len() { - return Err(DownloaderError::InvalidChunk(index, num_chunks)) + return Err(DownloaderError::InvalidChunk(index, num_chunks)); } // Update chunk with downloaded range diff --git a/crates/stages/stages/src/stages/s3/mod.rs b/crates/stages/stages/src/stages/s3/mod.rs index b5904f1c2c..486453df09 100644 --- a/crates/stages/stages/src/stages/s3/mod.rs +++ b/crates/stages/stages/src/stages/s3/mod.rs @@ -71,7 +71,7 @@ where self.fetch_rx = None; } - return Poll::Ready(response) + return Poll::Ready(response); } // Spawns the downloader task if there are any missing files @@ -79,11 +79,11 @@ where self.fetch_rx = Some(fetch_rx); // Polls fetch_rx & registers waker - continue + continue; } // No files to be downloaded - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } @@ -147,7 +147,7 @@ impl S3Stage { StaticFileSegment::parse_filename(block_range_files[0].0).expect("qed"); if block_range.end() <= checkpoint.block_number { - continue + continue; } let mut block_range_requests = vec![]; @@ -156,7 +156,7 @@ impl S3Stage { // run. if self.static_file_directory.join(filename).exists() { // TODO: check hash if the file already exists - continue + continue; } block_range_requests.push((filename, file_hash)); @@ -167,7 +167,7 @@ impl S3Stage { // Return None, if we have downloaded all the files that are required. if requests.is_empty() { - return None + return None; } let static_file_directory = self.static_file_directory.clone(); @@ -190,7 +190,7 @@ impl S3Stage { .await { let _ = fetch_tx.send(Err(err)); - return + return; } } @@ -254,7 +254,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()) + return Ok(Vec::default()); } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/sender_recovery.rs b/crates/stages/stages/src/stages/sender_recovery.rs index e6bdb92cf2..771893239a 100644 --- a/crates/stages/stages/src/stages/sender_recovery.rs +++ b/crates/stages/stages/src/stages/sender_recovery.rs @@ -77,7 +77,7 @@ where /// entries in the [`TransactionSenders`][reth_db_api::tables::TransactionSenders] table. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let (tx_range, block_range, is_final_range) = @@ -91,7 +91,7 @@ where checkpoint: StageCheckpoint::new(end_block) .with_entities_stage_checkpoint(stage_checkpoint(provider)?), done: is_final_range, - }) + }); } // Acquire the cursor for inserting elements @@ -206,7 +206,7 @@ where .into(), )) } - } + }; } }; senders_cursor.append(tx_id, &sender)?; @@ -271,7 +271,7 @@ where // We exit early since we could not process this chunk. let _ = recovered_senders_tx .send(Err(Box::new(SenderRecoveryStageError::StageError(err.into())))); - break + break; } }; @@ -294,7 +294,7 @@ where // Finish early if is_err { - break + break; } } }); @@ -663,7 +663,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } let mut body_cursor = diff --git a/crates/stages/stages/src/stages/tx_lookup.rs b/crates/stages/stages/src/stages/tx_lookup.rs index 2010e5e355..688aa05af1 100644 --- a/crates/stages/stages/src/stages/tx_lookup.rs +++ b/crates/stages/stages/src/stages/tx_lookup.rs @@ -242,8 +242,8 @@ where // If `TransactionHashNumbers` table was pruned, we will have a number of entries in it not // matching the actual number of processed transactions. To fix that, we add the // number of pruned `TransactionHashNumbers` entries. - processed: provider.count_entries::()? as u64 + - pruned_entries, + processed: provider.count_entries::()? as u64 + + pruned_entries, // Count only static files entries. If we count the database entries too, we may have // duplicates. We're sure that the static files have all entries that database has, // because we run the `StaticFileProducer` before starting the pipeline. @@ -548,7 +548,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()) + return Ok(()); } let mut body_cursor = diff --git a/crates/stages/stages/src/stages/utils.rs b/crates/stages/stages/src/stages/utils.rs index 2198b2db60..9659174806 100644 --- a/crates/stages/stages/src/stages/utils.rs +++ b/crates/stages/stages/src/stages/utils.rs @@ -267,11 +267,11 @@ where loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= last_tx_num { - break + break; } } if last_block == 0 { - break + break; } last_block -= 1; } diff --git a/crates/stages/stages/src/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index f3e29c1fa6..559f9b3f37 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -277,8 +277,8 @@ impl TestStageDB { // Backfill: some tests start at a forward block number, but static files // require no gaps. let segment_header = txs_writer.user_header(); - if segment_header.block_end().is_none() && - segment_header.expected_block_start() == 0 + if segment_header.block_end().is_none() + && segment_header.expected_block_start() == 0 { for block in 0..block.number { txs_writer.increment_block(block)?; diff --git a/crates/stages/types/src/checkpoints.rs b/crates/stages/types/src/checkpoints.rs index 587d0508a2..48f1a86cf6 100644 --- a/crates/stages/types/src/checkpoints.rs +++ b/crates/stages/types/src/checkpoints.rs @@ -163,7 +163,7 @@ impl EntitiesCheckpoint { /// Return [None] if `total == 0`. pub fn fmt_percentage(&self) -> Option { if self.total == 0 { - return None + return None; } // Calculate percentage with 2 decimal places. @@ -257,14 +257,14 @@ impl StageCheckpoint { match stage_checkpoint { StageUnitCheckpoint::Account(AccountHashingCheckpoint { progress: entities, .. - }) | - StageUnitCheckpoint::Storage(StorageHashingCheckpoint { + }) + | StageUnitCheckpoint::Storage(StorageHashingCheckpoint { progress: entities, .. - }) | - StageUnitCheckpoint::Entities(entities) | - StageUnitCheckpoint::Execution(ExecutionCheckpoint { progress: entities, .. }) | - StageUnitCheckpoint::Headers(HeadersCheckpoint { progress: entities, .. }) | - StageUnitCheckpoint::IndexHistory(IndexHistoryCheckpoint { + }) + | StageUnitCheckpoint::Entities(entities) + | StageUnitCheckpoint::Execution(ExecutionCheckpoint { progress: entities, .. }) + | StageUnitCheckpoint::Headers(HeadersCheckpoint { progress: entities, .. }) + | StageUnitCheckpoint::IndexHistory(IndexHistoryCheckpoint { progress: entities, .. }) => Some(entities), @@ -300,10 +300,10 @@ impl StageUnitCheckpoint { /// range. pub const fn set_block_range(&mut self, from: u64, to: u64) -> Option { match self { - Self::Account(AccountHashingCheckpoint { block_range, .. }) | - Self::Storage(StorageHashingCheckpoint { block_range, .. }) | - Self::Execution(ExecutionCheckpoint { block_range, .. }) | - Self::IndexHistory(IndexHistoryCheckpoint { block_range, .. }) => { + Self::Account(AccountHashingCheckpoint { block_range, .. }) + | Self::Storage(StorageHashingCheckpoint { block_range, .. }) + | Self::Execution(ExecutionCheckpoint { block_range, .. }) + | Self::IndexHistory(IndexHistoryCheckpoint { block_range, .. }) => { let old_range = *block_range; *block_range = CheckpointBlockRange { from, to }; diff --git a/crates/stages/types/src/execution.rs b/crates/stages/types/src/execution.rs index a334951abe..bdfbaf01cb 100644 --- a/crates/stages/types/src/execution.rs +++ b/crates/stages/types/src/execution.rs @@ -42,9 +42,9 @@ impl ExecutionStageThresholds { cumulative_gas_used: u64, elapsed: Duration, ) -> bool { - blocks_processed >= self.max_blocks.unwrap_or(u64::MAX) || - changes_processed >= self.max_changes.unwrap_or(u64::MAX) || - cumulative_gas_used >= self.max_cumulative_gas.unwrap_or(u64::MAX) || - elapsed >= self.max_duration.unwrap_or(Duration::MAX) + blocks_processed >= self.max_blocks.unwrap_or(u64::MAX) + || changes_processed >= self.max_changes.unwrap_or(u64::MAX) + || cumulative_gas_used >= self.max_cumulative_gas.unwrap_or(u64::MAX) + || elapsed >= self.max_duration.unwrap_or(Duration::MAX) } } diff --git a/crates/stateless/src/trie.rs b/crates/stateless/src/trie.rs index 5a35e52a7f..cb00d2d580 100644 --- a/crates/stateless/src/trie.rs +++ b/crates/stateless/src/trie.rs @@ -70,7 +70,7 @@ impl StatelessSparseTrie { if let Some(bytes) = self.inner.get_account_value(&hashed_address) { let account = TrieAccount::decode(&mut bytes.as_slice())?; - return Ok(Some(account)) + return Ok(Some(account)); } if !self.inner.check_valid_account_witness(hashed_address) { @@ -91,7 +91,7 @@ impl StatelessSparseTrie { let hashed_slot = keccak256(B256::from(slot)); if let Some(raw) = self.inner.get_storage_slot_value(&hashed_address, &hashed_slot) { - return Ok(U256::decode(&mut raw.as_slice())?) + return Ok(U256::decode(&mut raw.as_slice())?); } // Storage slot value is not present in the trie, validate that the witness is complete. @@ -100,8 +100,8 @@ impl StatelessSparseTrie { // ...check that its storage is either empty or the storage trie was sufficiently // revealed... let account = TrieAccount::decode(&mut bytes.as_slice())?; - if account.storage_root != EMPTY_ROOT_HASH && - !self.inner.check_valid_storage_witness(hashed_address, hashed_slot) + if account.storage_root != EMPTY_ROOT_HASH + && !self.inner.check_valid_storage_witness(hashed_address, hashed_slot) { return Err(ProviderError::TrieWitnessError(format!( "incomplete storage witness: prover must supply exclusion proof for slot {hashed_slot:?} in account {hashed_address:?}" 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 491419ef4b..9ddf89f6da 100644 --- a/crates/static-file/static-file/src/static_file_producer.rs +++ b/crates/static-file/static-file/src/static_file_producer.rs @@ -116,7 +116,7 @@ where pub fn run(&self, targets: StaticFileTargets) -> StaticFileProducerResult { // If there are no targets, do not produce any static files and return early if !targets.any() { - return Ok(targets) + return Ok(targets); } debug_assert!(targets.is_contiguous_to_highest_static_files( @@ -209,8 +209,8 @@ where self.get_static_file_target(highest_static_files.headers, finalized_block_number) }), // StaticFile receipts only if they're not pruned according to the user configuration - receipts: if self.prune_modes.receipts.is_none() && - self.prune_modes.receipts_log_filter.is_empty() + receipts: if self.prune_modes.receipts.is_none() + && self.prune_modes.receipts_log_filter.is_empty() { finalized_block_numbers.receipts.and_then(|finalized_block_number| { self.get_static_file_target( diff --git a/crates/static-file/types/src/lib.rs b/crates/static-file/types/src/lib.rs index 5d63849364..f9d4645811 100644 --- a/crates/static-file/types/src/lib.rs +++ b/crates/static-file/types/src/lib.rs @@ -94,10 +94,10 @@ pub struct StaticFileTargets { impl StaticFileTargets { /// Returns `true` if any of the targets are [Some]. pub const fn any(&self) -> bool { - self.headers.is_some() || - self.receipts.is_some() || - self.transactions.is_some() || - self.block_meta.is_some() + self.headers.is_some() + || self.receipts.is_some() + || self.transactions.is_some() + || self.block_meta.is_some() } /// Returns `true` if all targets are either [`None`] or has beginning of the range equal to the @@ -112,10 +112,9 @@ impl StaticFileTargets { .iter() .all(|(target_block_range, highest_static_fileted_block)| { target_block_range.is_none_or(|target_block_range| { - *target_block_range.start() == - highest_static_fileted_block.map_or(0, |highest_static_fileted_block| { - highest_static_fileted_block + 1 - }) + *target_block_range.start() + == highest_static_fileted_block + .map_or(0, |highest_static_fileted_block| highest_static_fileted_block + 1) }) }) } diff --git a/crates/static-file/types/src/segment.rs b/crates/static-file/types/src/segment.rs index 185eff18ea..9ad44dc1e5 100644 --- a/crates/static-file/types/src/segment.rs +++ b/crates/static-file/types/src/segment.rs @@ -115,14 +115,14 @@ impl StaticFileSegment { pub fn parse_filename(name: &str) -> Option<(Self, SegmentRangeInclusive)> { let mut parts = name.split('_'); if !(parts.next() == Some("static") && parts.next() == Some("file")) { - return None + return None; } let segment = Self::from_str(parts.next()?).ok()?; let (block_start, block_end) = (parts.next()?.parse().ok()?, parts.next()?.parse().ok()?); if block_start > block_end { - return None + return None; } Some((segment, SegmentRangeInclusive::new(block_start, block_end))) @@ -303,7 +303,7 @@ impl SegmentHeader { /// Returns the row offset which depends on whether the segment is block or transaction based. pub fn start(&self) -> Option { if self.segment.is_block_based() { - return self.block_start() + return self.block_start(); } self.tx_start() } diff --git a/crates/storage/codecs/derive/src/compact/flags.rs b/crates/storage/codecs/derive/src/compact/flags.rs index b6bad46291..67102c5266 100644 --- a/crates/storage/codecs/derive/src/compact/flags.rs +++ b/crates/storage/codecs/derive/src/compact/flags.rs @@ -30,7 +30,7 @@ pub(crate) fn generate_flag_struct( .iter() .filter_map(|f| { if let FieldTypes::StructField(f) = f { - return Some(f) + return Some(f); } None }) @@ -41,7 +41,7 @@ pub(crate) fn generate_flag_struct( }; if total_bits == 0 { - return placeholder_flag_struct(ident, &flags_ident) + return placeholder_flag_struct(ident, &flags_ident); } let (total_bytes, unused_bits) = pad_flag_struct(total_bits, &mut field_flags); diff --git a/crates/storage/codecs/derive/src/compact/generator.rs b/crates/storage/codecs/derive/src/compact/generator.rs index e6c06f44ad..85b7186fe8 100644 --- a/crates/storage/codecs/derive/src/compact/generator.rs +++ b/crates/storage/codecs/derive/src/compact/generator.rs @@ -144,7 +144,7 @@ fn generate_from_compact( let ident = format_ident!("{}", field.name); return Some(quote! { #ident: #ident, - }) + }); } None }); diff --git a/crates/storage/codecs/derive/src/compact/mod.rs b/crates/storage/codecs/derive/src/compact/mod.rs index 0e795e7a94..56d03ea5bc 100644 --- a/crates/storage/codecs/derive/src/compact/mod.rs +++ b/crates/storage/codecs/derive/src/compact/mod.rs @@ -150,10 +150,11 @@ fn load_field_from_segments( if is_enum { fields.push(FieldTypes::EnumUnnamedField((ftype, use_alt_impl))); } else { - let should_compact = is_flag_type(&ftype) || - field.attrs.iter().any(|attr| { - attr.path().segments.iter().any(|path| path.ident == "maybe_zero") - }); + let should_compact = is_flag_type(&ftype) + || field + .attrs + .iter() + .any(|attr| attr.path().segments.iter().any(|path| path.ident == "maybe_zero")); fields.push(FieldTypes::StructField(StructFieldDescriptor { name: field.ident.as_ref().map(|i| i.to_string()).unwrap_or_default(), @@ -188,7 +189,7 @@ fn should_use_alt_impl(ftype: &str, segment: &syn::PathSegment) -> bool { ] .contains(&path.ident.to_string().as_str()) { - return true + return true; } } } diff --git a/crates/storage/codecs/derive/src/compact/structs.rs b/crates/storage/codecs/derive/src/compact/structs.rs index f8ebda3349..469f89a00b 100644 --- a/crates/storage/codecs/derive/src/compact/structs.rs +++ b/crates/storage/codecs/derive/src/compact/structs.rs @@ -67,7 +67,7 @@ impl<'a> StructHandler<'a> { }) } - return + return; } let name = format_ident!("{name}"); diff --git a/crates/storage/codecs/derive/src/lib.rs b/crates/storage/codecs/derive/src/lib.rs index a835e8fab3..54ad3d25ca 100644 --- a/crates/storage/codecs/derive/src/lib.rs +++ b/crates/storage/codecs/derive/src/lib.rs @@ -80,11 +80,11 @@ pub fn derive_zstd(input: TokenStream) -> TokenStream { let path: syn::Path = value.parse()?; decompressor = Some(path); } else { - return Err(meta.error("unsupported attribute")) + return Err(meta.error("unsupported attribute")); } Ok(()) }) { - return err.to_compile_error().into() + return err.to_compile_error().into(); } } } @@ -93,7 +93,7 @@ pub fn derive_zstd(input: TokenStream) -> TokenStream { return quote! { compile_error!("missing compressor or decompressor attribute"); } - .into() + .into(); }; compact::derive(input, Some(ZstdConfig { compressor, decompressor })) diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index a9cb7f2fcd..fe5ab44d80 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -309,7 +309,7 @@ where #[inline] fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (None, buf) + return (None, buf); } let (len, mut buf) = decode_varuint(buf); @@ -338,7 +338,7 @@ where #[inline] fn specialized_from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (None, buf) + return (None, buf); } let (element, buf) = T::from_compact(buf, len); @@ -387,7 +387,7 @@ impl Compact for U256 { #[inline] fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (Self::ZERO, buf) + return (Self::ZERO, buf); } let mut arr = [0; 32]; @@ -427,7 +427,7 @@ impl Compact for [u8; N] { #[inline] fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return ([0; N], buf) + return ([0; N], buf); } let v = buf[..N].try_into().unwrap(); @@ -512,7 +512,7 @@ fn decode_varuint(buf: &[u8]) -> (usize, &[u8]) { let byte = buf[i]; value |= usize::from(byte & 0x7F) << (i * 7); if byte < 0x80 { - return (value, &buf[i + 1..]) + return (value, &buf[i + 1..]); } } diff --git a/crates/storage/codecs/src/test_utils.rs b/crates/storage/codecs/src/test_utils.rs index b845645cb1..12a8780722 100644 --- a/crates/storage/codecs/src/test_utils.rs +++ b/crates/storage/codecs/src/test_utils.rs @@ -32,7 +32,7 @@ /// validate_bitflag_backwards_compat!(TExtension, UnusedBits::NotZero); /// } /// ``` -/// +/// /// ### 2. `Zero` -> `NotZero` /// If it becomes `NotZero`, it would break backwards compatibility, so there is not an action item, /// and should be handled with care in a case by case scenario. diff --git a/crates/storage/db-api/src/cursor.rs b/crates/storage/db-api/src/cursor.rs index 3aeee949ea..81520d1c20 100644 --- a/crates/storage/db-api/src/cursor.rs +++ b/crates/storage/db-api/src/cursor.rs @@ -225,7 +225,7 @@ impl> Iterator for ReverseWalker<'_, T, CURSOR> fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start + return start; } self.cursor.prev().transpose() @@ -265,7 +265,7 @@ impl> Iterator for RangeWalker<'_, T, CURSOR> { fn next(&mut self) -> Option { if self.is_done { - return None + return None; } let next_item = self.start.take().or_else(|| self.cursor.next().transpose()); @@ -356,7 +356,7 @@ impl> Iterator for DupWalker<'_, T, CURSOR> fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start + return start; } self.cursor.next_dup().transpose() } diff --git a/crates/storage/db-api/src/models/storage_sharded_key.rs b/crates/storage/db-api/src/models/storage_sharded_key.rs index a7a1ffb71b..eee429247d 100644 --- a/crates/storage/db-api/src/models/storage_sharded_key.rs +++ b/crates/storage/db-api/src/models/storage_sharded_key.rs @@ -68,7 +68,7 @@ impl Encode for StorageShardedKey { impl Decode for StorageShardedKey { fn decode(value: &[u8]) -> Result { if value.len() != STORAGE_SHARD_KEY_BYTES_SIZE { - return Err(DatabaseError::Decode) + return Err(DatabaseError::Decode); } let tx_num_index = value.len() - 8; diff --git a/crates/storage/db-api/src/unwind.rs b/crates/storage/db-api/src/unwind.rs index 79cf585a62..c553914f0c 100644 --- a/crates/storage/db-api/src/unwind.rs +++ b/crates/storage/db-api/src/unwind.rs @@ -31,7 +31,7 @@ pub trait DbTxUnwindExt: DbTxMut { while let Some(Ok((entry_key, _))) = reverse_walker.next() { if selector(entry_key.clone()) <= key { - break + break; } reverse_walker.delete_current()?; deleted += 1; diff --git a/crates/storage/db-common/src/db_tool/mod.rs b/crates/storage/db-common/src/db_tool/mod.rs index 5866ad8ae2..b48ef3ab16 100644 --- a/crates/storage/db-common/src/db_tool/mod.rs +++ b/crates/storage/db-common/src/db_tool/mod.rs @@ -50,18 +50,18 @@ impl DbTool { let (key, value) = (k.into_key(), v.into_value()); if key.len() + value.len() < filter.min_row_size { - return None + return None; } if key.len() < filter.min_key_size { - return None + return None; } if value.len() < filter.min_value_size { - return None + return None; } let result = || { if filter.only_count { - return None + return None; } Some(( ::Key::decode(&key).unwrap(), @@ -71,16 +71,16 @@ impl DbTool { match &*bmb { Some(searcher) => { - if searcher.find_first_in(&value).is_some() || - searcher.find_first_in(&key).is_some() + if searcher.find_first_in(&value).is_some() + || searcher.find_first_in(&key).is_some() { hits += 1; - return result() + return result(); } } None => { hits += 1; - return result() + return result(); } } } diff --git a/crates/storage/db-common/src/init.rs b/crates/storage/db-common/src/init.rs index a29d02a42c..81756a648c 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -106,17 +106,17 @@ where // make sure that our database has been written to, and throw error if it's empty. if factory.get_stage_checkpoint(StageId::Headers)?.is_none() { error!(target: "reth::storage", "Genesis header found on static files, but database is uninitialized."); - return Err(InitStorageError::UninitializedDatabase) + return Err(InitStorageError::UninitializedDatabase); } debug!("Genesis already written, skipping."); - return Ok(hash) + return Ok(hash); } return Err(InitStorageError::GenesisHashMismatch { chainspec_hash: hash, storage_hash: block_hash, - }) + }); } Err(e) => { debug!(?e); @@ -381,7 +381,7 @@ where + AsRef, { if etl_config.file_size == 0 { - return Err(eyre::eyre!("ETL file size cannot be zero")) + return Err(eyre::eyre!("ETL file size cannot be zero")); } let block = provider_rw.last_block_number()?; @@ -403,7 +403,7 @@ where got: dump_state_root, expected: expected_state_root, }) - .into()) + .into()); } debug!(target: "reth::cli", @@ -436,7 +436,7 @@ where got: computed_state_root, expected: expected_state_root, }) - .into()) + .into()); } // insert sync stages for stages that require state @@ -470,7 +470,7 @@ fn parse_accounts( while let Ok(n) = reader.read_line(&mut line) { if n == 0 { - break + break; } let GenesisAccountWithAddress { genesis_account, address } = serde_json::from_str(&line)?; @@ -515,8 +515,8 @@ where accounts.push((address, account)); - if (index > 0 && index % AVERAGE_COUNT_ACCOUNTS_PER_GB_STATE_DUMP == 0) || - index == accounts_len - 1 + if (index > 0 && index % AVERAGE_COUNT_ACCOUNTS_PER_GB_STATE_DUMP == 0) + || index == accounts_len - 1 { total_inserted_accounts += accounts.len(); @@ -598,7 +598,7 @@ where "State root has been computed" ); - return Ok(root) + return Ok(root); } } } diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index d536e69a27..6be3ce7d83 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -417,7 +417,7 @@ impl DatabaseEnv { LogLevel::Extra => 7, }); } else { - return Err(DatabaseError::LogLevelUnavailable(log_level)) + return Err(DatabaseError::LogLevelUnavailable(log_level)); } } @@ -465,7 +465,7 @@ impl DatabaseEnv { /// Records version that accesses the database with write privileges. pub fn record_client_version(&self, version: ClientVersion) -> Result<(), DatabaseError> { if version.is_empty() { - return Ok(()) + return Ok(()); } let tx = self.tx_mut()?; diff --git a/crates/storage/db/src/implementation/mdbx/tx.rs b/crates/storage/db/src/implementation/mdbx/tx.rs index d2b20f5ae3..e860e9e253 100644 --- a/crates/storage/db/src/implementation/mdbx/tx.rs +++ b/crates/storage/db/src/implementation/mdbx/tx.rs @@ -231,9 +231,9 @@ impl MetricsHandler { /// NOTE: Backtrace is recorded using [`Backtrace::force_capture`], so `RUST_BACKTRACE` env var /// is not needed. fn log_backtrace_on_long_read_transaction(&self) { - if self.record_backtrace && - !self.backtrace_recorded.load(Ordering::Relaxed) && - self.transaction_mode().is_read_only() + if self.record_backtrace + && !self.backtrace_recorded.load(Ordering::Relaxed) + && self.transaction_mode().is_read_only() { let open_duration = self.start.elapsed(); if open_duration >= self.long_transaction_duration { diff --git a/crates/storage/db/src/lockfile.rs b/crates/storage/db/src/lockfile.rs index a1a9946b57..13cf09283c 100644 --- a/crates/storage/db/src/lockfile.rs +++ b/crates/storage/db/src/lockfile.rs @@ -53,7 +53,7 @@ impl StorageLock { start_time = process_lock.start_time, "Storage lock already taken." ); - return Err(StorageLockError::Taken(process_lock.pid)) + return Err(StorageLockError::Taken(process_lock.pid)); } } diff --git a/crates/storage/db/src/static_file/cursor.rs b/crates/storage/db/src/static_file/cursor.rs index 7721acc1a8..716bd44ea3 100644 --- a/crates/storage/db/src/static_file/cursor.rs +++ b/crates/storage/db/src/static_file/cursor.rs @@ -33,7 +33,7 @@ impl<'a> StaticFileCursor<'a> { mask: usize, ) -> ProviderResult>> { if self.jar().rows() == 0 { - return Ok(None) + return Ok(None); } let row = match key_or_num { @@ -41,7 +41,7 @@ impl<'a> StaticFileCursor<'a> { KeyOrNumber::Number(n) => match self.jar().user_header().start() { Some(offset) => { if offset > n { - return Ok(None) + return Ok(None); } self.row_by_number_with_cols((n - offset) as usize, mask) } diff --git a/crates/storage/db/src/version.rs b/crates/storage/db/src/version.rs index 09c1f94678..424d543606 100644 --- a/crates/storage/db/src/version.rs +++ b/crates/storage/db/src/version.rs @@ -48,7 +48,7 @@ pub enum DatabaseVersionError { pub fn check_db_version_file>(db_path: P) -> Result<(), DatabaseVersionError> { let version = get_db_version(db_path)?; if version != DB_VERSION { - return Err(DatabaseVersionError::VersionMismatch { version }) + return Err(DatabaseVersionError::VersionMismatch { version }); } Ok(()) diff --git a/crates/storage/libmdbx-rs/mdbx-sys/build.rs b/crates/storage/libmdbx-rs/mdbx-sys/build.rs index c265d02e23..6a4d5caa1d 100644 --- a/crates/storage/libmdbx-rs/mdbx-sys/build.rs +++ b/crates/storage/libmdbx-rs/mdbx-sys/build.rs @@ -32,8 +32,8 @@ fn main() { // Propagate `-C target-cpu=native` let rustflags = env::var("CARGO_ENCODED_RUSTFLAGS").unwrap(); - if rustflags.contains("target-cpu=native") && - env::var("CARGO_CFG_TARGET_ENV").unwrap() != "msvc" + if rustflags.contains("target-cpu=native") + && env::var("CARGO_CFG_TARGET_ENV").unwrap() != "msvc" { cc.flag("-march=native"); } @@ -53,42 +53,42 @@ fn generate_bindings(mdbx: &Path, out_file: &Path) { impl ParseCallbacks for Callbacks { fn int_macro(&self, name: &str, _value: i64) -> Option { match name { - "MDBX_SUCCESS" | - "MDBX_KEYEXIST" | - "MDBX_NOTFOUND" | - "MDBX_PAGE_NOTFOUND" | - "MDBX_CORRUPTED" | - "MDBX_PANIC" | - "MDBX_VERSION_MISMATCH" | - "MDBX_INVALID" | - "MDBX_MAP_FULL" | - "MDBX_DBS_FULL" | - "MDBX_READERS_FULL" | - "MDBX_TLS_FULL" | - "MDBX_TXN_FULL" | - "MDBX_CURSOR_FULL" | - "MDBX_PAGE_FULL" | - "MDBX_MAP_RESIZED" | - "MDBX_INCOMPATIBLE" | - "MDBX_BAD_RSLOT" | - "MDBX_BAD_TXN" | - "MDBX_BAD_VALSIZE" | - "MDBX_BAD_DBI" | - "MDBX_LOG_DONTCHANGE" | - "MDBX_DBG_DONTCHANGE" | - "MDBX_RESULT_TRUE" | - "MDBX_UNABLE_EXTEND_MAPSIZE" | - "MDBX_PROBLEM" | - "MDBX_LAST_LMDB_ERRCODE" | - "MDBX_BUSY" | - "MDBX_EMULTIVAL" | - "MDBX_EBADSIGN" | - "MDBX_WANNA_RECOVERY" | - "MDBX_EKEYMISMATCH" | - "MDBX_TOO_LARGE" | - "MDBX_THREAD_MISMATCH" | - "MDBX_TXN_OVERLAPPING" | - "MDBX_LAST_ERRCODE" => Some(IntKind::Int), + "MDBX_SUCCESS" + | "MDBX_KEYEXIST" + | "MDBX_NOTFOUND" + | "MDBX_PAGE_NOTFOUND" + | "MDBX_CORRUPTED" + | "MDBX_PANIC" + | "MDBX_VERSION_MISMATCH" + | "MDBX_INVALID" + | "MDBX_MAP_FULL" + | "MDBX_DBS_FULL" + | "MDBX_READERS_FULL" + | "MDBX_TLS_FULL" + | "MDBX_TXN_FULL" + | "MDBX_CURSOR_FULL" + | "MDBX_PAGE_FULL" + | "MDBX_MAP_RESIZED" + | "MDBX_INCOMPATIBLE" + | "MDBX_BAD_RSLOT" + | "MDBX_BAD_TXN" + | "MDBX_BAD_VALSIZE" + | "MDBX_BAD_DBI" + | "MDBX_LOG_DONTCHANGE" + | "MDBX_DBG_DONTCHANGE" + | "MDBX_RESULT_TRUE" + | "MDBX_UNABLE_EXTEND_MAPSIZE" + | "MDBX_PROBLEM" + | "MDBX_LAST_LMDB_ERRCODE" + | "MDBX_BUSY" + | "MDBX_EMULTIVAL" + | "MDBX_EBADSIGN" + | "MDBX_WANNA_RECOVERY" + | "MDBX_EKEYMISMATCH" + | "MDBX_TOO_LARGE" + | "MDBX_THREAD_MISMATCH" + | "MDBX_TXN_OVERLAPPING" + | "MDBX_LAST_ERRCODE" => Some(IntKind::Int), _ => Some(IntKind::UInt), } } diff --git a/crates/storage/libmdbx-rs/src/codec.rs b/crates/storage/libmdbx-rs/src/codec.rs index c78f79db9f..c67d74c510 100644 --- a/crates/storage/libmdbx-rs/src/codec.rs +++ b/crates/storage/libmdbx-rs/src/codec.rs @@ -41,8 +41,8 @@ impl TableObject for Cow<'_, [u8]> { #[cfg(not(feature = "return-borrowed"))] { - let is_dirty = (!K::IS_READ_ONLY) && - crate::error::mdbx_result(ffi::mdbx_is_dirty(_txn, data_val.iov_base))?; + let is_dirty = (!K::IS_READ_ONLY) + && crate::error::mdbx_result(ffi::mdbx_is_dirty(_txn, data_val.iov_base))?; Ok(if is_dirty { Cow::Owned(s.to_vec()) } else { Cow::Borrowed(s) }) } @@ -81,7 +81,7 @@ impl TableObject for ObjectLength { impl TableObject for [u8; LEN] { fn decode(data_val: &[u8]) -> Result { if data_val.len() != LEN { - return Err(Error::DecodeErrorLenDiff) + return Err(Error::DecodeErrorLenDiff); } let mut a = [0; LEN]; a[..].copy_from_slice(data_val); diff --git a/crates/storage/libmdbx-rs/src/cursor.rs b/crates/storage/libmdbx-rs/src/cursor.rs index 8f7a4b5cd4..13ae2f7ad5 100644 --- a/crates/storage/libmdbx-rs/src/cursor.rs +++ b/crates/storage/libmdbx-rs/src/cursor.rs @@ -371,7 +371,7 @@ where { let res: Result> = self.set_range(key); if let Err(error) = res { - return Iter::Err(Some(error)) + return Iter::Err(Some(error)); }; Iter::new(self, ffi::MDBX_GET_CURRENT, ffi::MDBX_NEXT) } @@ -406,7 +406,7 @@ where { let res: Result> = self.set_range(key); if let Err(error) = res { - return IterDup::Err(Some(error)) + return IterDup::Err(Some(error)); }; IterDup::new(self, ffi::MDBX_GET_CURRENT) } @@ -422,7 +422,7 @@ where Ok(Some(_)) => (), Ok(None) => { let _: Result> = self.last(); - return Iter::new(self, ffi::MDBX_NEXT, ffi::MDBX_NEXT) + return Iter::new(self, ffi::MDBX_NEXT, ffi::MDBX_NEXT); } Err(error) => return Iter::Err(Some(error)), }; diff --git a/crates/storage/libmdbx-rs/src/environment.rs b/crates/storage/libmdbx-rs/src/environment.rs index 9be857796f..6c3e332627 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -121,10 +121,10 @@ impl Environment { warn!(target: "libmdbx", "Process stalled, awaiting read-write transaction lock."); } sleep(Duration::from_millis(250)); - continue + continue; } - break res + break res; }?; Ok(Transaction::new_from_ptr(self.clone(), txn.0)) } @@ -220,7 +220,7 @@ impl Environment { for result in cursor.iter_slices() { let (_key, value) = result?; if value.len() < size_of::() { - return Err(Error::Corrupted) + return Err(Error::Corrupted); } let s = &value[..size_of::()]; @@ -732,7 +732,7 @@ impl EnvironmentBuilder { })() { ffi::mdbx_env_close_ex(env, false); - return Err(e) + return Err(e); } } diff --git a/crates/storage/libmdbx-rs/src/error.rs b/crates/storage/libmdbx-rs/src/error.rs index 2f852c3dc7..da11540083 100644 --- a/crates/storage/libmdbx-rs/src/error.rs +++ b/crates/storage/libmdbx-rs/src/error.rs @@ -200,9 +200,9 @@ impl Error { Self::DecodeErrorLenDiff | Self::DecodeError => ffi::MDBX_EINVAL, Self::TooLarge => ffi::MDBX_TOO_LARGE, Self::BadSignature => ffi::MDBX_EBADSIGN, - Self::Access | - Self::WriteTransactionUnsupportedInReadOnlyMode | - Self::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, + Self::Access + | Self::WriteTransactionUnsupportedInReadOnlyMode + | Self::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, Self::ReadTransactionTimeout => -96000, // Custom non-MDBX error code Self::Permission => ffi::MDBX_EPERM, Self::Other(err_code) => *err_code, diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index 677a33474b..38203d50ee 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -530,7 +530,7 @@ impl Transaction { /// Begins a new nested transaction inside of this transaction. pub fn begin_nested_txn(&mut self) -> Result { if self.inner.env.is_write_map() { - return Err(Error::NestedTransactionsUnsupportedWithWriteMap) + return Err(Error::NestedTransactionsUnsupportedWithWriteMap); } self.txn_execute(|txn| { let (tx, rx) = sync_channel(0); @@ -614,7 +614,7 @@ impl TransactionPtr { // to the `mdbx_txn_reset`. #[cfg(feature = "read-tx-timeouts")] if self.is_timed_out() { - return Err(Error::ReadTransactionTimeout) + return Err(Error::ReadTransactionTimeout); } Ok((f)(self.txn)) diff --git a/crates/storage/nippy-jar/src/compression/lz4.rs b/crates/storage/nippy-jar/src/compression/lz4.rs index cdffd91529..5bf96d3372 100644 --- a/crates/storage/nippy-jar/src/compression/lz4.rs +++ b/crates/storage/nippy-jar/src/compression/lz4.rs @@ -42,7 +42,7 @@ impl Compression for Lz4 { Err(err) => { multiplier *= 2; if multiplier == 16 { - return Err(NippyJarError::Custom(err.to_string())) + return Err(NippyJarError::Custom(err.to_string())); } } } diff --git a/crates/storage/nippy-jar/src/compression/zstd.rs b/crates/storage/nippy-jar/src/compression/zstd.rs index 5f2888d041..36560a3d5d 100644 --- a/crates/storage/nippy-jar/src/compression/zstd.rs +++ b/crates/storage/nippy-jar/src/compression/zstd.rs @@ -64,7 +64,7 @@ impl Zstd { pub fn decompressors(&self) -> Result>, NippyJarError> { if let Some(dictionaries) = &self.dictionaries { debug_assert!(dictionaries.len() == self.columns); - return dictionaries.decompressors() + return dictionaries.decompressors(); } Ok(vec![]) @@ -76,12 +76,12 @@ impl Zstd { ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady), ZstdState::Ready => { if !self.use_dict { - return Ok(None) + return Ok(None); } if let Some(dictionaries) = &self.dictionaries { debug!(target: "nippy-jar", count=?dictionaries.len(), "Generating ZSTD compressor dictionaries."); - return Ok(Some(dictionaries.compressors()?)) + return Ok(Some(dictionaries.compressors()?)); } Ok(None) } @@ -106,7 +106,7 @@ impl Zstd { buffer.reserve(column_value.len() * multiplier); multiplier += 1; if multiplier == 5 { - return Err(NippyJarError::Disconnect(err)) + return Err(NippyJarError::Disconnect(err)); } } @@ -196,7 +196,7 @@ impl Compression for Zstd { columns: Vec>>, ) -> Result<(), NippyJarError> { if !self.use_dict { - return Ok(()) + return Ok(()); } // There's a per 2GB hard limit on each column data set for training @@ -210,7 +210,7 @@ impl Compression for Zstd { // ``` if columns.len() != self.columns { - return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())) + return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())); } let mut dictionaries = Vec::with_capacity(columns.len()); @@ -369,7 +369,7 @@ impl Serialize for ZstdDictionary<'_> { impl PartialEq for ZstdDictionary<'_> { fn eq(&self, other: &Self) -> bool { if let (Self::Raw(a), Self::Raw(b)) = (self, &other) { - return a == b + return a == b; } unimplemented!( "`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value." diff --git a/crates/storage/nippy-jar/src/consistency.rs b/crates/storage/nippy-jar/src/consistency.rs index 0abe118a4b..2fd4aba1ac 100644 --- a/crates/storage/nippy-jar/src/consistency.rs +++ b/crates/storage/nippy-jar/src/consistency.rs @@ -56,7 +56,7 @@ impl NippyJarChecker { // When an offset size is smaller than the initial (8), we are dealing with immutable // data. if reader.offset_size() != OFFSET_SIZE_BYTES { - return Err(NippyJarError::FrozenJar) + return Err(NippyJarError::FrozenJar); } let expected_offsets_file_size: u64 = (1 + // first byte is the size of one offset @@ -64,10 +64,10 @@ impl NippyJarChecker { OFFSET_SIZE_BYTES as usize) as u64; // expected size of the data file let actual_offsets_file_size = self.offsets_file().get_ref().metadata()?.len(); - if mode.should_err() && - expected_offsets_file_size.cmp(&actual_offsets_file_size) != Ordering::Equal + if mode.should_err() + && expected_offsets_file_size.cmp(&actual_offsets_file_size) != Ordering::Equal { - return Err(NippyJarError::InconsistentState) + return Err(NippyJarError::InconsistentState); } // Offsets configuration wasn't properly committed @@ -89,8 +89,8 @@ impl NippyJarChecker { self.jar.rows = ((actual_offsets_file_size. saturating_sub(1). // first byte is the size of one offset saturating_sub(OFFSET_SIZE_BYTES as u64) / // expected size of the data file - (self.jar.columns as u64)) / - OFFSET_SIZE_BYTES as u64) as usize; + (self.jar.columns as u64)) + / OFFSET_SIZE_BYTES as u64) as usize; // Freeze row count changed self.jar.freeze_config()?; @@ -103,7 +103,7 @@ impl NippyJarChecker { let data_file_len = self.data_file().get_ref().metadata()?.len(); if mode.should_err() && last_offset.cmp(&data_file_len) != Ordering::Equal { - return Err(NippyJarError::InconsistentState) + return Err(NippyJarError::InconsistentState); } // Offset list wasn't properly committed @@ -138,7 +138,7 @@ impl NippyJarChecker { // Since we decrease the offset list, we need to check the consistency of // `self.jar.rows` again self.handle_consistency(ConsistencyFailStrategy::Heal)?; - break + break; } } } diff --git a/crates/storage/nippy-jar/src/cursor.rs b/crates/storage/nippy-jar/src/cursor.rs index 505a00260b..3861a8fe1e 100644 --- a/crates/storage/nippy-jar/src/cursor.rs +++ b/crates/storage/nippy-jar/src/cursor.rs @@ -80,7 +80,7 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { if self.row as usize >= self.jar.rows { // Has reached the end - return Ok(None) + return Ok(None); } let mut row = Vec::with_capacity(self.jar.columns); @@ -120,7 +120,7 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { if self.row as usize >= self.jar.rows { // Has reached the end - return Ok(None) + return Ok(None); } let columns = self.jar.columns; diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index daa272fdd1..0cc8b79868 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -306,12 +306,12 @@ impl NippyJar { columns: &[impl IntoIterator>>], ) -> Result<(), NippyJarError> { if columns.len() != self.columns { - return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())) + return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())); } if let Some(compression) = &self.compressor { if !compression.is_ready() { - return Err(NippyJarError::CompressorNotReady) + return Err(NippyJarError::CompressorNotReady); } } @@ -353,9 +353,9 @@ impl DataReader { // Ensure that the size of an offset is at most 8 bytes. if offset_size > 8 { - return Err(NippyJarError::OffsetSizeTooBig { offset_size }) + return Err(NippyJarError::OffsetSizeTooBig { offset_size }); } else if offset_size == 0 { - return Err(NippyJarError::OffsetSizeTooSmall { offset_size }) + return Err(NippyJarError::OffsetSizeTooSmall { offset_size }); } Ok(Self { data_file, data_mmap, offset_file, offset_size, offset_mmap }) @@ -395,7 +395,7 @@ impl DataReader { let offset_end = index.saturating_add(self.offset_size as usize); if offset_end > self.offset_mmap.len() { - return Err(NippyJarError::OffsetOutOfBounds { index }) + return Err(NippyJarError::OffsetOutOfBounds { index }); } buffer[..self.offset_size as usize].copy_from_slice(&self.offset_mmap[index..offset_end]); diff --git a/crates/storage/nippy-jar/src/writer.rs b/crates/storage/nippy-jar/src/writer.rs index b20d9d6507..0a4738db39 100644 --- a/crates/storage/nippy-jar/src/writer.rs +++ b/crates/storage/nippy-jar/src/writer.rs @@ -284,7 +284,7 @@ impl NippyJarWriter { return Err(NippyJarError::InvalidPruning( num_offsets, remaining_to_prune as u64, - )) + )); } let new_num_offsets = num_offsets.saturating_sub(remaining_to_prune as u64); @@ -310,7 +310,7 @@ impl NippyJarWriter { self.data_file.get_mut().set_len(last_offset)?; } } else { - return Err(NippyJarError::InvalidPruning(0, remaining_to_prune as u64)) + return Err(NippyJarError::InvalidPruning(0, remaining_to_prune as u64)); } } @@ -406,7 +406,7 @@ impl NippyJarWriter { for offset in self.offsets.drain(..) { if let Some(last_offset_ondisk) = last_offset_ondisk.take() { if last_offset_ondisk == offset { - continue + continue; } } self.offsets_file.write_all(&offset.to_le_bytes())?; diff --git a/crates/storage/provider/src/providers/consistent.rs b/crates/storage/provider/src/providers/consistent.rs index 3922e286c2..b0e32f2744 100644 --- a/crates/storage/provider/src/providers/consistent.rs +++ b/crates/storage/provider/src/providers/consistent.rs @@ -148,7 +148,7 @@ impl ConsistentProvider { range: RangeInclusive, ) -> ProviderResult>>> { if range.is_empty() { - return Ok(None) + return Ok(None); } let start_block_number = *range.start(); let end_block_number = *range.end(); @@ -165,10 +165,10 @@ impl ConsistentProvider { // get transaction receipts let Some(from_transaction_num) = block_bodies.first().map(|body| body.1.first_tx_num()) else { - return Ok(None) + return Ok(None); }; let Some(to_transaction_num) = block_bodies.last().map(|body| body.1.last_tx_num()) else { - return Ok(None) + return Ok(None); }; let mut account_changeset = Vec::new(); @@ -327,7 +327,7 @@ impl ConsistentProvider { }); if start > end { - return Ok(vec![]) + return Ok(vec![]); } // Split range into storage_range and in-memory range. If the in-memory range is not @@ -375,7 +375,7 @@ impl ConsistentProvider { // The predicate was not met, if the number of items differs from the expected. So, we // return what we have. if items.len() as u64 != storage_range.end() - storage_range.start() + 1 { - return Ok(items) + return Ok(items); } } @@ -385,7 +385,7 @@ impl ConsistentProvider { if let Some(item) = map_block_state_item(block, &mut predicate) { items.push(item); } else { - break + break; } } } @@ -443,12 +443,12 @@ impl ConsistentProvider { in_mem_chain .iter() .map(|b| b.block_ref().recovered_block().body().transactions().len() as u64) - .sum::() + - last_block_body_index.last_tx_num() + .sum::() + + last_block_body_index.last_tx_num() }); if start > end { - return Ok(vec![]) + return Ok(vec![]); } let mut tx_range = start..=end; @@ -482,7 +482,7 @@ impl ConsistentProvider { // transaction, advance if *tx_range.start() >= in_memory_tx_num + block_tx_count as u64 { in_memory_tx_num += block_tx_count as u64; - continue + continue; } // This should only be more than 0 once, in case of a partial range inside a block. @@ -497,7 +497,7 @@ impl ConsistentProvider { // Break if the range has been fully processed if in_memory_tx_num > *tx_range.end() { - break + break; } // Set updated range @@ -540,7 +540,7 @@ impl ConsistentProvider { // database lookup if let HashOrNumber::Number(id) = id { if id < in_memory_tx_num { - return fetch_from_db(provider) + return fetch_from_db(provider); } } @@ -553,12 +553,12 @@ impl ConsistentProvider { match id { HashOrNumber::Hash(tx_hash) => { if tx_hash == block.body().transactions()[tx_index].trie_hash() { - return fetch_from_block_state(tx_index, in_memory_tx_num, block_state) + return fetch_from_block_state(tx_index, in_memory_tx_num, block_state); } } HashOrNumber::Number(id) => { if id == in_memory_tx_num { - return fetch_from_block_state(tx_index, in_memory_tx_num, block_state) + return fetch_from_block_state(tx_index, in_memory_tx_num, block_state); } } } @@ -569,7 +569,7 @@ impl ConsistentProvider { // Not found in-memory, so check database. if let HashOrNumber::Hash(_) = id { - return fetch_from_db(provider) + return fetch_from_db(provider); } Ok(None) @@ -587,7 +587,7 @@ impl ConsistentProvider { M: Fn(&BlockState) -> ProviderResult, { if let Some(Some(block_state)) = self.head_block.as_ref().map(|b| b.block_on_chain(id)) { - return fetch_from_block_state(block_state) + return fetch_from_block_state(block_state); } fetch_from_db(&self.storage_provider) } @@ -824,7 +824,7 @@ impl BlockReader for ConsistentProvider { |db_provider| db_provider.find_block_by_hash(hash, BlockSource::Canonical), |block_state| Ok(Some(block_state.block_ref().recovered_block().clone_block())), )? { - return Ok(Some(block)) + return Ok(Some(block)); } } @@ -833,7 +833,7 @@ impl BlockReader for ConsistentProvider { .canonical_in_memory_state .pending_block() .filter(|b| b.hash() == hash) - .map(|b| b.into_block())) + .map(|b| b.into_block())); } Ok(None) @@ -969,7 +969,7 @@ impl TransactionsProvider for ConsistentProvider { fn transaction_by_hash(&self, hash: TxHash) -> ProviderResult> { if let Some(tx) = self.head_block.as_ref().and_then(|b| b.transaction_on_chain(hash)) { - return Ok(Some(tx)) + return Ok(Some(tx)); } self.storage_provider.transaction_by_hash(hash) @@ -982,7 +982,7 @@ impl TransactionsProvider for ConsistentProvider { if let Some((tx, meta)) = self.head_block.as_ref().and_then(|b| b.transaction_meta_on_chain(tx_hash)) { - return Ok(Some((tx, meta))) + return Ok(Some((tx, meta))); } self.storage_provider.transaction_by_hash_with_meta(tx_hash) @@ -1364,7 +1364,7 @@ impl StorageChangeSetReader for ConsistentProvider { .unwrap_or(true); if !storage_history_exists { - return Err(ProviderError::StateAtBlockPruned(block_number)) + return Err(ProviderError::StateAtBlockPruned(block_number)); } self.storage_provider.storage_changeset(block_number) @@ -1410,7 +1410,7 @@ impl ChangeSetReader for ConsistentProvider { .unwrap_or(true); if !account_history_exists { - return Err(ProviderError::StateAtBlockPruned(block_number)) + return Err(ProviderError::StateAtBlockPruned(block_number)); } self.storage_provider.account_block_changeset(block_number) diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index 4957def6e2..6307b5b1fd 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -71,7 +71,7 @@ where // data source that we used during initialization. In this case, that is static files if let Some((hash, number)) = self.tip { if provider_ro.sealed_header(number)?.is_none_or(|header| header.hash() != hash) { - return Err(ConsistentViewError::Reorged { block: hash }.into()) + return Err(ConsistentViewError::Reorged { block: hash }.into()); } } diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index 8178a8c313..bd2cf29cbd 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -168,10 +168,10 @@ impl DatabaseProvider { ) -> ProviderResult> { let mut block_number = self.block_number(block_hash)?.ok_or(ProviderError::BlockHashNotFound(block_hash))?; - if block_number == self.best_block_number().unwrap_or_default() && - block_number == self.last_block_number().unwrap_or_default() + if block_number == self.best_block_number().unwrap_or_default() + && block_number == self.last_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProviderRef::new(self))) + return Ok(Box::new(LatestStateProviderRef::new(self))); } // +1 as the changeset that we want is the one that was applied after this block. @@ -358,7 +358,7 @@ impl TryIntoHistoricalStateProvider for Databa // if the block number is the same as the currently best block number on disk we can use the // latest state provider here if block_number == self.best_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProvider::new(self))) + return Ok(Box::new(LatestStateProvider::new(self))); } // +1 as the changeset that we want is the one that was applied after this block. @@ -464,7 +464,7 @@ where while let Some((sharded_key, list)) = item { // If the shard does not belong to the key, break. if !shard_belongs_to_key(&sharded_key) { - break + break; } // Always delete the current shard from the database first @@ -479,18 +479,18 @@ where // Keep it deleted (don't return anything for reinsertion) if first >= block_number { item = cursor.prev()?; - continue + continue; } // Case 2: This is a boundary shard (spans across the unwinding point) // The shard contains some blocks below and some at/above the unwinding point else if block_number <= sharded_key.as_ref().highest_block_number { // Return only the block numbers that are below the unwinding point // These will be reinserted to preserve the historical data - return Ok(list.iter().take_while(|i| *i < block_number).collect::>()) + return Ok(list.iter().take_while(|i| *i < block_number).collect::>()); } // Case 3: Entire shard is below the unwinding point // Return all block numbers for reinsertion (preserve entire shard) - return Ok(list.iter().collect::>()) + return Ok(list.iter().collect::>()); } // No shards found or all processed @@ -611,7 +611,7 @@ impl DatabaseProvider { F: FnMut(H, BodyTy, Range) -> ProviderResult, { if range.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } let len = range.end().saturating_sub(*range.start()) as usize; @@ -806,7 +806,7 @@ impl DatabaseProvider { // delete old shard so new one can be inserted. cursor.delete_current()?; let list = list.iter().collect::>(); - return Ok(list) + return Ok(list); } Ok(Vec::new()) } @@ -965,7 +965,7 @@ impl HeaderSyncGapProvider } Ordering::Less => { // There's either missing or corrupted files. - return Err(ProviderError::HeaderNotFound(next_static_file_block_num.into())) + return Err(ProviderError::HeaderNotFound(next_static_file_block_num.into())); } Ordering::Equal => {} } @@ -1011,7 +1011,7 @@ impl HeaderProvider for DatabasePro if let Some(td) = self.chain_spec.final_paris_total_difficulty() { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)) + return Ok(Some(td)); } } @@ -1077,7 +1077,7 @@ impl HeaderProvider for DatabasePro .ok_or_else(|| ProviderError::HeaderNotFound(number.into()))?; let sealed = SealedHeader::new(header, hash); if !predicate(&sealed) { - break + break; } headers.push(sealed); } @@ -1174,7 +1174,7 @@ impl BlockReader for DatabaseProvid // If they exist but are not indexed, we don't have enough // information to return the block anyways, so we return `None`. let Some(transactions) = self.transactions_by_block(number.into())? else { - return Ok(None) + return Ok(None); }; let body = self @@ -1184,7 +1184,7 @@ impl BlockReader for DatabaseProvid .pop() .ok_or(ProviderError::InvalidStorageOutput)?; - return Ok(Some(Self::Block::new(header, body))) + return Ok(Some(Self::Block::new(header, body))); } } @@ -1427,7 +1427,7 @@ impl TransactionsProvider for Datab timestamp: header.timestamp(), }; - return Ok(Some((transaction, meta))) + return Ok(Some((transaction, meta))); } } } @@ -1455,7 +1455,7 @@ impl TransactionsProvider for Datab Ok(Some(Vec::new())) } else { Ok(Some(self.transactions_by_tx_range_with_cursor(tx_range, &mut tx_cursor)?)) - } + }; } } Ok(None) @@ -1537,7 +1537,7 @@ impl ReceiptProvider for DatabasePr Ok(Some(Vec::new())) } else { self.receipts_by_tx_range(tx_range).map(Some) - } + }; } } Ok(None) @@ -1815,8 +1815,8 @@ impl StateWriter // Prepare receipts static writer if we are going to write receipts to static files // // We are writing to static files if requested and if there's no receipt pruning configured - let mut receipts_static_writer = (write_receipts_to.static_files() && - !has_receipts_pruning) + let mut receipts_static_writer = (write_receipts_to.static_files() + && !has_receipts_pruning) .then(|| self.static_file_provider.get_writer(first_block, StaticFileSegment::Receipts)) .transpose()?; @@ -1845,12 +1845,13 @@ impl StateWriter } // Skip writing receipts if pruning configuration requires us to. - if prunable_receipts && - self.prune_modes + if prunable_receipts + && self + .prune_modes .receipts .is_some_and(|mode| mode.should_prune(block_number, tip)) { - continue + continue; } // If there are new addresses to retain after this block number, track them @@ -1862,11 +1863,11 @@ impl StateWriter let receipt_idx = first_tx_index + idx as u64; // Skip writing receipt if log filter is active and it does not have any logs to // retain - if prunable_receipts && - has_contract_log_filter && - !receipt.logs().iter().any(|log| allowed_addresses.contains(&log.address)) + if prunable_receipts + && has_contract_log_filter + && !receipt.logs().iter().any(|log| allowed_addresses.contains(&log.address)) { - continue + continue; } if let Some(writer) = &mut receipts_static_writer { @@ -2174,7 +2175,7 @@ impl StateWriter let range = block + 1..=self.last_block_number()?; if range.is_empty() { - return Ok(ExecutionOutcome::default()) + return Ok(ExecutionOutcome::default()); } let start_block_number = *range.start(); @@ -2292,7 +2293,7 @@ impl TrieWriter for DatabaseProvider /// Writes trie updates. Returns the number of entries modified. fn write_trie_updates(&self, trie_updates: &TrieUpdates) -> ProviderResult { if trie_updates.is_empty() { - return Ok(0) + return Ok(0); } // Track the number of inserted entries. @@ -2366,7 +2367,7 @@ impl StorageTrieWriter for DatabaseP updates: &StorageTrieUpdates, ) -> ProviderResult { if updates.is_empty() { - return Ok(0) + return Ok(0); } let cursor = self.tx_ref().cursor_dup_write::()?; @@ -2588,7 +2589,7 @@ impl HashingWriter for DatabaseProvi root: GotExpected { got: state_root, expected: expected_state_root }, block_number: *range.end(), block_hash: end_block_hash, - }))) + }))); } self.write_trie_updates(&trie_updates)?; } @@ -2674,8 +2675,8 @@ impl HistoryWriter for DatabaseProvi StorageShardedKey::last(address, storage_key), rem_index, |storage_sharded_key| { - storage_sharded_key.address == address && - storage_sharded_key.sharded_key.key == storage_key + storage_sharded_key.address == address + && storage_sharded_key.sharded_key.key == storage_key }, )?; @@ -3048,7 +3049,7 @@ impl BlockWrite ) -> ProviderResult<()> { if blocks.is_empty() { debug!(target: "providers::db", "Attempted to append empty block range"); - return Ok(()) + return Ok(()); } let first_number = blocks.first().unwrap().number(); diff --git a/crates/storage/provider/src/providers/state/historical.rs b/crates/storage/provider/src/providers/state/historical.rs index e815f98740..fdd56fb18e 100644 --- a/crates/storage/provider/src/providers/state/historical.rs +++ b/crates/storage/provider/src/providers/state/historical.rs @@ -81,7 +81,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Lookup an account in the `AccountsHistory` table pub fn account_history_lookup(&self, address: Address) -> ProviderResult { if !self.lowest_available_blocks.is_account_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)) + return Err(ProviderError::StateAtBlockPruned(self.block_number)); } // history key to search IntegerList of block number changesets. @@ -100,7 +100,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> storage_key: StorageKey, ) -> ProviderResult { if !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)) + return Err(ProviderError::StateAtBlockPruned(self.block_number)); } // history key to search IntegerList of block number changesets. @@ -121,10 +121,10 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Retrieve revert hashed state for this history provider. fn revert_state(&self) -> ProviderResult { - if !self.lowest_available_blocks.is_account_history_available(self.block_number) || - !self.lowest_available_blocks.is_storage_history_available(self.block_number) + if !self.lowest_available_blocks.is_account_history_available(self.block_number) + || !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)) + return Err(ProviderError::StateAtBlockPruned(self.block_number)); } if self.check_distance_against_limit(EPOCH_SLOTS)? { @@ -143,7 +143,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Retrieve revert hashed storage for this history provider and target address. fn revert_storage(&self, address: Address) -> ProviderResult { if !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)) + return Err(ProviderError::StateAtBlockPruned(self.block_number)); } if self.check_distance_against_limit(EPOCH_SLOTS * 10)? { @@ -189,9 +189,9 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> // This check is worth it, the `cursor.prev()` check is rarely triggered (the if will // short-circuit) and when it passes we save a full seek into the changeset/plain state // table. - if rank == 0 && - block_number != Some(self.block_number) && - !cursor.prev()?.is_some_and(|(key, _)| key_filter(&key)) + if rank == 0 + && block_number != Some(self.block_number) + && !cursor.prev()?.is_some_and(|(key, _)| key_filter(&key)) { if let (Some(_), Some(block_number)) = (lowest_available_block_number, block_number) { diff --git a/crates/storage/provider/src/providers/state/latest.rs b/crates/storage/provider/src/providers/state/latest.rs index 334e0109dc..e83049592a 100644 --- a/crates/storage/provider/src/providers/state/latest.rs +++ b/crates/storage/provider/src/providers/state/latest.rs @@ -172,7 +172,7 @@ impl StateProv let mut cursor = self.tx().cursor_dup_read::()?; if let Some(entry) = cursor.seek_by_key_subkey(account, storage_key)? { if entry.key == storage_key { - return Ok(Some(entry.value)) + return Ok(Some(entry.value)); } } Ok(None) diff --git a/crates/storage/provider/src/providers/static_file/jar.rs b/crates/storage/provider/src/providers/static_file/jar.rs index 365e54467a..76e730b00b 100644 --- a/crates/storage/provider/src/providers/static_file/jar.rs +++ b/crates/storage/provider/src/providers/static_file/jar.rs @@ -161,7 +161,7 @@ impl> HeaderProvider for StaticFileJarProv { let sealed = SealedHeader::new(header, hash); if !predicate(&sealed) { - break + break; } headers.push(sealed); } @@ -320,7 +320,7 @@ impl ProviderResult> { if let Some(tx_static_file) = &self.auxiliary_jar { if let Some(num) = tx_static_file.transaction_id(hash)? { - return self.receipt(num) + return self.receipt(num); } } Ok(None) diff --git a/crates/storage/provider/src/providers/static_file/manager.rs b/crates/storage/provider/src/providers/static_file/manager.rs index dee449c82d..4d82e4ad8e 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -158,11 +158,11 @@ impl StaticFileProvider { // We only care about modified data events if !matches!( event.kind, - notify::EventKind::Modify(_) | - notify::EventKind::Create(_) | - notify::EventKind::Remove(_) + notify::EventKind::Modify(_) + | notify::EventKind::Create(_) + | notify::EventKind::Remove(_) ) { - continue + continue; } // We only trigger a re-initialization if a configuration file was @@ -175,7 +175,7 @@ impl StaticFileProvider { .extension() .is_none_or(|s| s.to_str() != Some(CONFIG_FILE_EXTENSION)) { - continue + continue; } // Ensure it's well formatted static file name @@ -184,7 +184,7 @@ impl StaticFileProvider { ) .is_none() { - continue + continue; } // If we can read the metadata and modified timestamp, ensure this is @@ -195,7 +195,7 @@ impl StaticFileProvider { if last_event_timestamp.is_some_and(|last_timestamp| { last_timestamp >= current_modified_timestamp }) { - continue + continue; } last_event_timestamp = Some(current_modified_timestamp); } @@ -204,7 +204,7 @@ impl StaticFileProvider { if let Err(err) = provider.initialize_index() { warn!(target: "providers::static_file", "failed to re-initialize index: {err}"); } - break + break; } } @@ -419,7 +419,7 @@ impl StaticFileProvider { ) .and_then(|(parsed_segment, block_range)| { if parsed_segment == segment { - return Some(block_range) + return Some(block_range); } None }), @@ -428,7 +428,7 @@ impl StaticFileProvider { // Return cached `LoadedJar` or insert it for the first time, and then, return it. if let Some(block_range) = block_range { - return Ok(Some(self.get_or_create_jar_provider(segment, &block_range)?)) + return Ok(Some(self.get_or_create_jar_provider(segment, &block_range)?)); } Ok(None) @@ -455,18 +455,18 @@ impl StaticFileProvider { pub fn delete_transactions_below(&self, block: BlockNumber) -> ProviderResult<()> { // Nothing to delete if block is 0. if block == 0 { - return Ok(()) + return Ok(()); } loop { let Some(block_height) = self.get_lowest_static_file_block(StaticFileSegment::Transactions) else { - return Ok(()) + return Ok(()); }; if block_height >= block { - return Ok(()) + return Ok(()); } debug!( @@ -573,11 +573,11 @@ impl StaticFileProvider { while let Some((tx_end, block_range)) = static_files_rev_iter.next() { if tx > *tx_end { // request tx is higher than highest static file tx - return None + return None; } let tx_start = static_files_rev_iter.peek().map(|(tx_end, _)| *tx_end + 1).unwrap_or(0); if tx_start <= tx { - return Some(self.find_fixed_range(block_range.end())) + return Some(self.find_fixed_range(block_range.end())); } } None @@ -750,8 +750,8 @@ impl StaticFileProvider { // // If we detect an OVM import was done (block #1 ), skip it. // More on [#11099](https://github.com/paradigmxyz/reth/pull/11099). - if provider.chain_spec().is_optimism() && - reth_chainspec::Chain::optimism_mainnet() == provider.chain_spec().chain_id() + if provider.chain_spec().is_optimism() + && reth_chainspec::Chain::optimism_mainnet() == provider.chain_spec().chain_id() { // check whether we have the first OVM block: const OVM_HEADER_1_HASH: B256 = @@ -760,7 +760,7 @@ impl StaticFileProvider { info!(target: "reth::cli", "Skipping storage verification for OP mainnet, expected inconsistency in OVM chain" ); - return Ok(None) + return Ok(None); } } @@ -778,12 +778,12 @@ impl StaticFileProvider { for segment in StaticFileSegment::iter() { // Not integrated yet if segment.is_block_meta() { - continue + continue; } if has_receipt_pruning && segment.is_receipts() { // Pruned nodes (including full node) do not store receipts as static files. - continue + continue; } let initial_highest_block = self.get_highest_static_file_block(segment); @@ -830,16 +830,16 @@ impl StaticFileProvider { loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= highest_tx { - break + break; } } else { // If the block body indices can not be found, then it means that static // files is ahead of database, and the `ensure_invariants` check will fix // it by comparing with stage checkpoints. - break + break; } if last_block == 0 { - break + break; } last_block -= 1; @@ -948,7 +948,7 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_block)) + return Ok(Some(highest_block)); } } @@ -956,7 +956,7 @@ impl StaticFileProvider { if highest_static_file_entry .is_none_or(|highest_entry| db_last_entry > highest_entry) { - return Ok(None) + return Ok(None); } } } @@ -984,7 +984,7 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_static_file_block)) + return Ok(Some(highest_static_file_block)); } // If the checkpoint is behind, then we failed to do a database commit **but committed** to @@ -1085,7 +1085,7 @@ impl StaticFileProvider { let mut range = self.find_fixed_range(highest_block); while range.end() > 0 { if let Some(res) = func(self.get_or_create_jar_provider(segment, &range)?)? { - return Ok(Some(res)) + return Ok(Some(res)); } range = SegmentRangeInclusive::new( range.start().saturating_sub(self.blocks_per_file), @@ -1137,10 +1137,10 @@ impl StaticFileProvider { match get_fn(&mut cursor, number)? { Some(res) => { if !predicate(&res) { - break 'outer + break 'outer; } result.push(res); - break 'inner + break 'inner; } None => { if retrying { @@ -1156,7 +1156,7 @@ impl StaticFileProvider { } else { ProviderError::MissingStaticFileTx(segment, number) }; - return Err(err) + return Err(err); } // There is a very small chance of hitting a deadlock if two consecutive // static files share the same bucket in the @@ -1249,7 +1249,7 @@ impl StaticFileProvider { if static_file_upper_bound .is_some_and(|static_file_upper_bound| static_file_upper_bound >= number) { - return fetch_from_static_file(self) + return fetch_from_static_file(self); } fetch_from_database() } @@ -1351,7 +1351,7 @@ impl StaticFileWriter for StaticFileProvider { segment: StaticFileSegment, ) -> ProviderResult> { if self.access.is_read_only() { - return Err(ProviderError::ReadOnlyStaticFileAccess) + return Err(ProviderError::ReadOnlyStaticFileAccess); } trace!(target: "provider::static_file", ?block, ?segment, "Getting static file writer."); @@ -1382,7 +1382,7 @@ impl> HeaderProvider for StaticFileProvide .get_two::>(block_hash.into())? .and_then(|(header, hash)| { if &hash == block_hash { - return Some(header) + return Some(header); } None })) @@ -1505,7 +1505,7 @@ impl> Rec fn receipt_by_hash(&self, hash: TxHash) -> ProviderResult> { if let Some(num) = self.transaction_id(hash)? { - return self.receipt(num) + return self.receipt(num); } Ok(None) } @@ -1835,9 +1835,9 @@ impl BlockBodyIndicesProvider for StaticFileProvider { impl StatsReader for StaticFileProvider { fn count_entries(&self) -> ProviderResult { match T::NAME { - tables::CanonicalHeaders::NAME | - tables::Headers::

::NAME | - tables::HeaderTerminalDifficulties::NAME => Ok(self + tables::CanonicalHeaders::NAME + | tables::Headers::
::NAME + | tables::HeaderTerminalDifficulties::NAME => Ok(self .get_highest_static_file_block(StaticFileSegment::Headers) .map(|block| block + 1) .unwrap_or_default() diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index 3fd2828faa..bb62a409a8 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -381,7 +381,7 @@ impl StaticFileProviderRW { self.writer.user_header().segment(), expected_block_number, next_static_file_block, - )) + )); } Ok(()) } @@ -413,15 +413,15 @@ impl StaticFileProviderRW { // * it's a tx-based segment AND `last_block` is lower than the first block of this // file's block range. Otherwise, having no rows simply means that this block // range has no transactions, but the file should remain. - if block_start != 0 && - (segment.is_headers() || last_block.is_some_and(|b| b < block_start)) + if block_start != 0 + && (segment.is_headers() || last_block.is_some_and(|b| b < block_start)) { self.delete_current_and_open_previous()?; } else { // Update `SegmentHeader` self.writer.user_header_mut().prune(len); self.writer.prune_rows(len as usize).map_err(ProviderError::other)?; - break + break; } remaining_rows -= len; @@ -501,7 +501,7 @@ impl StaticFileProviderRW { self.writer.user_header().segment(), tx_num, next_tx, - )) + )); } self.writer.user_header_mut().increment_tx(); } else { diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 2d0cfb665d..d6be27b1c4 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -418,7 +418,7 @@ impl TransactionsProvider excess_blob_gas: block.header.excess_blob_gas, timestamp: block.header.timestamp, }; - return Ok(Some((tx.clone(), meta))) + return Ok(Some((tx.clone(), meta))); } } } @@ -430,7 +430,7 @@ impl TransactionsProvider let mut current_tx_number: TxNumber = 0; for block in lock.values() { if current_tx_number + (block.body.transactions.len() as TxNumber) > id { - return Ok(Some(block.header.number)) + return Ok(Some(block.header.number)); } current_tx_number += block.body.transactions.len() as TxNumber; } diff --git a/crates/storage/provider/src/writer/mod.rs b/crates/storage/provider/src/writer/mod.rs index cbdb773c20..d54dc845f5 100644 --- a/crates/storage/provider/src/writer/mod.rs +++ b/crates/storage/provider/src/writer/mod.rs @@ -74,7 +74,7 @@ impl<'a, ProviderDB, ProviderSF> UnifiedStorageWriter<'a, ProviderDB, ProviderSF #[expect(unused)] const fn ensure_static_file(&self) -> Result<(), UnifiedStorageWriterError> { if self.static_file.is_none() { - return Err(UnifiedStorageWriterError::MissingStaticFileWriter) + return Err(UnifiedStorageWriterError::MissingStaticFileWriter); } Ok(()) } @@ -139,7 +139,7 @@ where { if blocks.is_empty() { debug!(target: "provider::storage_writer", "Attempted to write empty block range"); - return Ok(()) + return Ok(()); } // NOTE: checked non-empty above diff --git a/crates/storage/storage-api/src/receipts.rs b/crates/storage/storage-api/src/receipts.rs index f8390ee538..3c883ae8da 100644 --- a/crates/storage/storage-api/src/receipts.rs +++ b/crates/storage/storage-api/src/receipts.rs @@ -73,7 +73,7 @@ pub trait ReceiptProviderIdExt: ReceiptProvider + BlockIdReader { if let Some(num) = self.convert_block_number(num_tag)? { BlockHashOrNumber::Number(num) } else { - return Ok(None) + return Ok(None); } } }; diff --git a/crates/storage/storage-api/src/state.rs b/crates/storage/storage-api/src/state.rs index 5581248d3e..f0e7ef696c 100644 --- a/crates/storage/storage-api/src/state.rs +++ b/crates/storage/storage-api/src/state.rs @@ -62,10 +62,10 @@ pub trait StateProvider: if let Some(code_hash) = acc.bytecode_hash { if code_hash == KECCAK_EMPTY { - return Ok(None) + return Ok(None); } // Get the code from the code hash - return self.bytecode_by_hash(&code_hash) + return self.bytecode_by_hash(&code_hash); } // Return `None` if no code hash is set diff --git a/crates/storage/zstd-compressors/src/lib.rs b/crates/storage/zstd-compressors/src/lib.rs index d7f2b65904..3c6205ccc5 100644 --- a/crates/storage/zstd-compressors/src/lib.rs +++ b/crates/storage/zstd-compressors/src/lib.rs @@ -120,7 +120,7 @@ impl ReusableDecompressor { reserved_upper_bound = true; if let Some(upper_bound) = Decompressor::upper_bound(src) { if let Some(additional) = upper_bound.checked_sub(self.buf.capacity()) { - break 'b additional + break 'b additional; } } } diff --git a/crates/tasks/src/lib.rs b/crates/tasks/src/lib.rs index 5f72037f7b..7de4a5793c 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -245,7 +245,7 @@ impl TaskManager { while self.graceful_tasks.load(Ordering::Relaxed) > 0 { if when.map(|when| std::time::Instant::now() > when).unwrap_or(false) { debug!("graceful shutdown timed out"); - return false + return false; } std::hint::spin_loop(); } diff --git a/crates/tokio-util/src/ratelimit.rs b/crates/tokio-util/src/ratelimit.rs index 33a9c5273d..93acd6fd5d 100644 --- a/crates/tokio-util/src/ratelimit.rs +++ b/crates/tokio-util/src/ratelimit.rs @@ -38,7 +38,7 @@ impl RateLimit { State::Ready { .. } => return Poll::Ready(()), State::Limited => { if Pin::new(&mut self.sleep).poll(cx).is_pending() { - return Poll::Pending + return Poll::Pending; } } } diff --git a/crates/transaction-pool/src/blobstore/disk.rs b/crates/transaction-pool/src/blobstore/disk.rs index e738bfc668..bd420a4055 100644 --- a/crates/transaction-pool/src/blobstore/disk.rs +++ b/crates/transaction-pool/src/blobstore/disk.rs @@ -62,7 +62,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec<(B256, BlobTransactionSidecarVariant)>, ) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()) + return Ok(()); } self.inner.insert_many(txs) } @@ -118,7 +118,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec, ) -> Result)>, BlobStoreError> { if txs.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } self.inner.get_all(txs) } @@ -128,7 +128,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec, ) -> Result>, BlobStoreError> { if txs.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } self.inner.get_exact(txs) } @@ -213,7 +213,7 @@ impl BlobStore for DiskFileBlobStore { // return early if all blobs are found. if result.iter().all(|blob| blob.is_some()) { // got all blobs, can return early - return Ok(Some(result.into_iter().map(Option::unwrap).collect())) + return Ok(Some(result.into_iter().map(Option::unwrap).collect())); } } @@ -393,7 +393,7 @@ impl DiskFileBlobStoreInner { /// Returns true if the blob for the given transaction hash is in the blob cache or on disk. fn contains(&self, tx: B256) -> Result { if self.blob_cache.lock().get(&tx).is_some() { - return Ok(true) + return Ok(true); } // we only check if the file exists and assume it's valid Ok(self.blob_disk_file(tx).is_file()) @@ -422,14 +422,14 @@ impl DiskFileBlobStoreInner { tx: B256, ) -> Result>, BlobStoreError> { if let Some(blob) = self.blob_cache.lock().get(&tx) { - return Ok(Some(blob.clone())) + return Ok(Some(blob.clone())); } let blob = self.read_one(tx)?; if let Some(blob) = &blob { let blob_arc = Arc::new(blob.clone()); self.blob_cache.lock().insert(tx, blob_arc.clone()); - return Ok(Some(blob_arc)) + return Ok(Some(blob_arc)); } Ok(None) @@ -536,11 +536,11 @@ impl DiskFileBlobStoreInner { } } if cache_miss.is_empty() { - return Ok(res) + return Ok(res); } let from_disk = self.read_many_decoded(cache_miss); if from_disk.is_empty() { - return Ok(res) + return Ok(res); } let mut cache = self.blob_cache.lock(); for (tx, data) in from_disk { diff --git a/crates/transaction-pool/src/blobstore/mem.rs b/crates/transaction-pool/src/blobstore/mem.rs index 44dff1cceb..881ba1f807 100644 --- a/crates/transaction-pool/src/blobstore/mem.rs +++ b/crates/transaction-pool/src/blobstore/mem.rs @@ -39,7 +39,7 @@ impl BlobStore for InMemoryBlobStore { txs: Vec<(B256, BlobTransactionSidecarVariant)>, ) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()) + return Ok(()); } let mut store = self.inner.store.write(); let mut total_add = 0; @@ -62,7 +62,7 @@ impl BlobStore for InMemoryBlobStore { fn delete_all(&self, txs: Vec) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()) + return Ok(()); } let mut store = self.inner.store.write(); let mut total_sub = 0; diff --git a/crates/transaction-pool/src/blobstore/mod.rs b/crates/transaction-pool/src/blobstore/mod.rs index 29844994bc..e78f29a627 100644 --- a/crates/transaction-pool/src/blobstore/mod.rs +++ b/crates/transaction-pool/src/blobstore/mod.rs @@ -169,8 +169,8 @@ impl BlobStoreSize { impl PartialEq for BlobStoreSize { fn eq(&self, other: &Self) -> bool { - self.data_size.load(Ordering::Relaxed) == other.data_size.load(Ordering::Relaxed) && - self.num_blobs.load(Ordering::Relaxed) == other.num_blobs.load(Ordering::Relaxed) + self.data_size.load(Ordering::Relaxed) == other.data_size.load(Ordering::Relaxed) + && self.num_blobs.load(Ordering::Relaxed) == other.num_blobs.load(Ordering::Relaxed) } } diff --git a/crates/transaction-pool/src/blobstore/noop.rs b/crates/transaction-pool/src/blobstore/noop.rs index bb03253ee6..b0a9020146 100644 --- a/crates/transaction-pool/src/blobstore/noop.rs +++ b/crates/transaction-pool/src/blobstore/noop.rs @@ -59,7 +59,7 @@ impl BlobStore for NoopBlobStore { txs: Vec, ) -> Result>, BlobStoreError> { if txs.is_empty() { - return Ok(vec![]) + return Ok(vec![]); } Err(BlobStoreError::MissingSidecar(txs[0])) } diff --git a/crates/transaction-pool/src/blobstore/tracker.rs b/crates/transaction-pool/src/blobstore/tracker.rs index 6789086abe..605f7853f3 100644 --- a/crates/transaction-pool/src/blobstore/tracker.rs +++ b/crates/transaction-pool/src/blobstore/tracker.rs @@ -65,7 +65,7 @@ impl BlobStoreCanonTracker { if *entry.key() <= finalized_block { finalized.extend(entry.remove_entry().1); } else { - break + break; } } diff --git a/crates/transaction-pool/src/config.rs b/crates/transaction-pool/src/config.rs index 5263cd1834..557edb86c1 100644 --- a/crates/transaction-pool/src/config.rs +++ b/crates/transaction-pool/src/config.rs @@ -69,10 +69,10 @@ impl PoolConfig { /// Returns whether the size and amount constraints in any sub-pools are exceeded. #[inline] pub const fn is_exceeded(&self, pool_size: PoolSize) -> bool { - self.blob_limit.is_exceeded(pool_size.blob, pool_size.blob_size) || - self.pending_limit.is_exceeded(pool_size.pending, pool_size.pending_size) || - self.basefee_limit.is_exceeded(pool_size.basefee, pool_size.basefee_size) || - self.queued_limit.is_exceeded(pool_size.queued, pool_size.queued_size) + self.blob_limit.is_exceeded(pool_size.blob, pool_size.blob_size) + || self.pending_limit.is_exceeded(pool_size.pending, pool_size.pending_size) + || self.basefee_limit.is_exceeded(pool_size.basefee, pool_size.basefee_size) + || self.queued_limit.is_exceeded(pool_size.queued, pool_size.queued_size) } } @@ -152,7 +152,7 @@ impl PriceBumpConfig { #[inline] pub const fn price_bump(&self, tx_type: u8) -> u128 { if tx_type == EIP4844_TX_TYPE_ID { - return self.replace_blob_tx_price_bump + return self.replace_blob_tx_price_bump; } self.default_price_bump } @@ -213,7 +213,7 @@ impl LocalTransactionConfig { #[inline] pub fn is_local(&self, origin: TransactionOrigin, sender: &Address) -> bool { if self.no_local_exemptions() { - return false + return false; } origin.is_local() || self.contains_local_address(sender) } diff --git a/crates/transaction-pool/src/error.rs b/crates/transaction-pool/src/error.rs index 686c9456d3..de5b1fdb75 100644 --- a/crates/transaction-pool/src/error.rs +++ b/crates/transaction-pool/src/error.rs @@ -289,14 +289,14 @@ impl InvalidPoolTransactionError { // depend on dynamic environmental conditions and should not be assumed to have been // intentionally caused by the sender match err { - InvalidTransactionError::InsufficientFunds { .. } | - InvalidTransactionError::NonceNotConsistent { .. } => { + InvalidTransactionError::InsufficientFunds { .. } + | InvalidTransactionError::NonceNotConsistent { .. } => { // transaction could just have arrived late/early false } - InvalidTransactionError::GasTooLow | - InvalidTransactionError::GasTooHigh | - InvalidTransactionError::TipAboveFeeCap => { + InvalidTransactionError::GasTooLow + | InvalidTransactionError::GasTooHigh + | InvalidTransactionError::TipAboveFeeCap => { // these are technically not invalid false } @@ -304,19 +304,19 @@ impl InvalidPoolTransactionError { // dynamic, but not used during validation false } - InvalidTransactionError::Eip2930Disabled | - InvalidTransactionError::Eip1559Disabled | - InvalidTransactionError::Eip4844Disabled | - InvalidTransactionError::Eip7702Disabled => { + InvalidTransactionError::Eip2930Disabled + | InvalidTransactionError::Eip1559Disabled + | InvalidTransactionError::Eip4844Disabled + | InvalidTransactionError::Eip7702Disabled => { // settings false } - InvalidTransactionError::OldLegacyChainId | - InvalidTransactionError::ChainIdMismatch | - InvalidTransactionError::GasUintOverflow | - InvalidTransactionError::TxTypeNotSupported | - InvalidTransactionError::SignerAccountHasBytecode | - InvalidTransactionError::GasLimitTooHigh => true, + InvalidTransactionError::OldLegacyChainId + | InvalidTransactionError::ChainIdMismatch + | InvalidTransactionError::GasUintOverflow + | InvalidTransactionError::TxTypeNotSupported + | InvalidTransactionError::SignerAccountHasBytecode + | InvalidTransactionError::GasLimitTooHigh => true, } } Self::ExceedsGasLimit(_, _) => true, @@ -355,8 +355,8 @@ impl InvalidPoolTransactionError { // this is a malformed transaction and should not be sent over the network true } - Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka | - Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka => { + Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka + | Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka => { // for now we do not want to penalize peers for broadcasting different // sidecars false @@ -379,8 +379,8 @@ impl InvalidPoolTransactionError { /// Returns `true` if an import failed due to nonce gap. pub const fn is_nonce_gap(&self) -> bool { - matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent { .. })) || - matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap)) + matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent { .. })) + || matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap)) } /// Returns the arbitrary error if it is [`InvalidPoolTransactionError::Other`] diff --git a/crates/transaction-pool/src/lib.rs b/crates/transaction-pool/src/lib.rs index 3d77651055..c185802b8d 100644 --- a/crates/transaction-pool/src/lib.rs +++ b/crates/transaction-pool/src/lib.rs @@ -499,7 +499,7 @@ where transactions: Vec, ) -> Vec> { if transactions.is_empty() { - return Vec::new() + return Vec::new(); } let validated = self.validate_all(origin, transactions).await; diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index b076255f1f..c0e81d4d4c 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -315,8 +315,8 @@ pub async fn maintain_transaction_pool( let old_first = old_blocks.first(); // check if the reorg is not canonical with the pool's block - if !(old_first.parent_hash() == pool_info.last_seen_block_hash || - new_first.parent_hash() == pool_info.last_seen_block_hash) + if !(old_first.parent_hash() == pool_info.last_seen_block_hash + || new_first.parent_hash() == pool_info.last_seen_block_hash) { // the new block points to a higher block than the oldest block in the old chain maintained_state = MaintainedPoolState::Drifted; @@ -462,7 +462,7 @@ pub async fn maintain_transaction_pool( // keep track of mined blob transactions blob_store_tracker.add_new_chain_blocks(&blocks); - continue + continue; } let mut changed_accounts = Vec::with_capacity(state.state().len()); @@ -612,14 +612,14 @@ where P: TransactionPool>, { if !file_path.exists() { - return Ok(()) + return Ok(()); } debug!(target: "txpool", txs_file =?file_path, "Check local persistent storage for saved transactions"); let data = reth_fs_util::read(file_path)?; if data.is_empty() { - return Ok(()) + return Ok(()); } let txs_signed: Vec<::Consensus> = @@ -648,7 +648,7 @@ where let local_transactions = pool.get_local_transactions(); if local_transactions.is_empty() { trace!(target: "txpool", "no local transactions to save"); - return + return; } let local_transactions = local_transactions @@ -697,7 +697,7 @@ pub async fn backup_local_transactions_task

( { let Some(transactions_path) = config.transactions_path else { // nothing to do - return + return; }; if let Err(err) = load_and_reinsert_transactions(pool.clone(), &transactions_path).await { diff --git a/crates/transaction-pool/src/noop.rs b/crates/transaction-pool/src/noop.rs index 132854bb71..9a58760bfb 100644 --- a/crates/transaction-pool/src/noop.rs +++ b/crates/transaction-pool/src/noop.rs @@ -319,7 +319,7 @@ impl TransactionPool for NoopTransactionPool { tx_hashes: Vec, ) -> Result>, BlobStoreError> { if tx_hashes.is_empty() { - return Ok(vec![]) + return Ok(vec![]); } Err(BlobStoreError::MissingSidecar(tx_hashes[0])) } diff --git a/crates/transaction-pool/src/pool/best.rs b/crates/transaction-pool/src/pool/best.rs index eba3c2c35d..49aa9853ad 100644 --- a/crates/transaction-pool/src/pool/best.rs +++ b/crates/transaction-pool/src/pool/best.rs @@ -55,8 +55,9 @@ impl Iterator for BestTransactionsWithFees { let best = Iterator::next(&mut self.best)?; // If both the base fee and blob fee (if applicable for EIP-4844) are satisfied, return // the transaction - if best.transaction.max_fee_per_gas() >= self.base_fee as u128 && - best.transaction + if best.transaction.max_fee_per_gas() >= self.base_fee as u128 + && best + .transaction .max_fee_per_blob_gas() .is_none_or(|fee| fee >= self.base_fee_per_blob_gas as u128) { @@ -197,7 +198,7 @@ impl Iterator for BestTransactions { "[{:?}] skipping invalid transaction", best.transaction.hash() ); - continue + continue; } // Insert transactions that just got unlocked. @@ -215,7 +216,7 @@ impl Iterator for BestTransactions { ), ) } else { - return Some(best.transaction) + return Some(best.transaction); } } } @@ -249,7 +250,7 @@ where loop { let best = self.best.next()?; if (self.predicate)(&best) { - return Some(best) + return Some(best); } self.best.mark_invalid( &best, @@ -329,12 +330,12 @@ where // If we have space, try prioritizing transactions if self.prioritized_gas < self.max_prioritized_gas { for item in &mut self.inner { - if self.prioritized_senders.contains(&item.transaction.sender()) && - self.prioritized_gas + item.transaction.gas_limit() <= - self.max_prioritized_gas + if self.prioritized_senders.contains(&item.transaction.sender()) + && self.prioritized_gas + item.transaction.gas_limit() + <= self.max_prioritized_gas { self.prioritized_gas += item.transaction.gas_limit(); - return Some(item) + return Some(item); } self.buffer.push_back(item); } diff --git a/crates/transaction-pool/src/pool/blob.rs b/crates/transaction-pool/src/pool/blob.rs index b083c62816..5af39c8ee1 100644 --- a/crates/transaction-pool/src/pool/blob.rs +++ b/crates/transaction-pool/src/pool/blob.rs @@ -97,16 +97,16 @@ impl BlobTransactions { let mut iter = self.by_id.iter().peekable(); while let Some((id, tx)) = iter.next() { - if tx.transaction.max_fee_per_blob_gas().unwrap_or_default() < - blob_fee_to_satisfy || - tx.transaction.max_fee_per_gas() < - best_transactions_attributes.basefee as u128 + if tx.transaction.max_fee_per_blob_gas().unwrap_or_default() + < blob_fee_to_satisfy + || tx.transaction.max_fee_per_gas() + < best_transactions_attributes.basefee as u128 { // does not satisfy the blob fee or base fee // still parked in blob pool -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this + break 'this; } iter.next(); } @@ -150,13 +150,13 @@ impl BlobTransactions { let mut iter = self.by_id.iter().peekable(); while let Some((id, tx)) = iter.next() { - if tx.transaction.max_fee_per_blob_gas() < Some(pending_fees.blob_fee) || - tx.transaction.max_fee_per_gas() < pending_fees.base_fee as u128 + if tx.transaction.max_fee_per_blob_gas() < Some(pending_fees.blob_fee) + || tx.transaction.max_fee_per_gas() < pending_fees.base_fee as u128 { // still parked in blob pool -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this + break 'this; } iter.next(); } @@ -347,7 +347,7 @@ const LOG_2_1_125: f64 = 0.16992500144231237; pub fn fee_delta(max_tx_fee: u128, current_fee: u128) -> i64 { if max_tx_fee == current_fee { // if these are equal, then there's no fee jump - return 0 + return 0; } let max_tx_fee_jumps = if max_tx_fee == 0 { diff --git a/crates/transaction-pool/src/pool/mod.rs b/crates/transaction-pool/src/pool/mod.rs index bf96431f78..32eefdfd4d 100644 --- a/crates/transaction-pool/src/pool/mod.rs +++ b/crates/transaction-pool/src/pool/mod.rs @@ -363,7 +363,7 @@ where elements.push(pooled.into_inner()); if limit.exceeds(size) { - break + break; } } @@ -602,7 +602,7 @@ where if listener.kind.is_propagate_only() && !propagate_allowed { // only emit this hash to listeners that are only allowed to receive propagate only // transactions, such as network - return !listener.sender.is_closed() + return !listener.sender.is_closed(); } // broadcast all pending transactions to the listener @@ -617,7 +617,7 @@ where if listener.kind.is_propagate_only() && !event.transaction.propagate { // only emit this hash to listeners that are only allowed to receive propagate only // transactions, such as network - return !listener.sender.is_closed() + return !listener.sender.is_closed(); } listener.send(event.clone()) @@ -628,7 +628,7 @@ where fn on_new_blob_sidecar(&self, tx_hash: &TxHash, sidecar: &BlobTransactionSidecarVariant) { let mut sidecar_listeners = self.blob_transaction_sidecar_listener.lock(); if sidecar_listeners.is_empty() { - return + return; } let sidecar = Arc::new(sidecar.clone()); sidecar_listeners.retain_mut(|listener| { @@ -758,7 +758,7 @@ where hashes: Vec, ) -> Vec>> { if hashes.is_empty() { - return Vec::new() + return Vec::new(); } let removed = self.pool.write().remove_transactions(hashes); @@ -778,7 +778,7 @@ where hashes: Vec, ) -> Vec>> { if hashes.is_empty() { - return Vec::new() + return Vec::new(); } let removed = self.pool.write().remove_transactions_and_descendants(hashes); @@ -814,7 +814,7 @@ where A: HandleMempoolData, { if announcement.is_empty() { - return + return; } let pool = self.get_pool_data(); announcement.retain_by_hash(|tx| !pool.contains(tx)) @@ -915,7 +915,7 @@ where /// If no transaction exists, it is skipped. pub fn get_all(&self, txs: Vec) -> Vec>> { if txs.is_empty() { - return Vec::new() + return Vec::new(); } self.get_pool_data().get_all(txs).collect() } @@ -923,7 +923,7 @@ where /// Notify about propagated transactions. pub fn on_propagated(&self, txs: PropagatedTransactions) { if txs.0.is_empty() { - return + return; } let mut listener = self.event_listener.write(); @@ -1049,9 +1049,9 @@ where loop { let next = self.iter.next()?; if self.kind.is_propagate_only() && !next.propagate { - continue + continue; } - return Some(*next.hash()) + return Some(*next.hash()); } } } @@ -1073,12 +1073,12 @@ where loop { let next = self.iter.next()?; if self.kind.is_propagate_only() && !next.propagate { - continue + continue; } return Some(NewTransactionEvent { subpool: SubPool::Pending, transaction: next.clone(), - }) + }); } } } diff --git a/crates/transaction-pool/src/pool/parked.rs b/crates/transaction-pool/src/pool/parked.rs index 33056dd6ec..6ff9d293d4 100644 --- a/crates/transaction-pool/src/pool/parked.rs +++ b/crates/transaction-pool/src/pool/parked.rs @@ -111,7 +111,7 @@ impl ParkedPool { if value.count == 0 { entry.remove() } else { - return + return; } } Entry::Vacant(_) => { @@ -190,7 +190,7 @@ impl ParkedPool { ) -> Vec>> { if !self.exceeds(&limit) { // if we are below the limits, we don't need to drop anything - return Vec::new() + return Vec::new(); } let mut removed = Vec::new(); @@ -208,7 +208,7 @@ impl ParkedPool { } if !self.exceeds(&limit) { - break + break; } } } @@ -294,7 +294,7 @@ impl ParkedPool> { // still parked -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this + break 'this; } iter.next(); } diff --git a/crates/transaction-pool/src/pool/pending.rs b/crates/transaction-pool/src/pool/pending.rs index d3e65f711f..c03f981d49 100644 --- a/crates/transaction-pool/src/pool/pending.rs +++ b/crates/transaction-pool/src/pool/pending.rs @@ -189,7 +189,7 @@ impl PendingPool { // Remove all dependent transactions. 'this: while let Some((next_id, next_tx)) = transactions_iter.peek() { if next_id.sender != id.sender { - break 'this + break 'this; } removed.push(Arc::clone(&next_tx.transaction)); transactions_iter.next(); @@ -231,7 +231,7 @@ impl PendingPool { // Remove all dependent transactions. 'this: while let Some((next_id, next_tx)) = transactions_iter.peek() { if next_id.sender != id.sender { - break 'this + break 'this; } removed.push(Arc::clone(&next_tx.transaction)); transactions_iter.next(); @@ -419,8 +419,8 @@ impl PendingPool { // loop through the highest nonces set, removing transactions until we reach the limit for tx in worst_transactions { // return early if the pool is under limits - if !limit.is_exceeded(original_length - total_removed, original_size - total_size) || - non_local_senders == 0 + if !limit.is_exceeded(original_length - total_removed, original_size - total_size) + || non_local_senders == 0 { // need to remove remaining transactions before exiting for id in &removed { @@ -429,7 +429,7 @@ impl PendingPool { } } - return + return; } if !remove_locals && tx.transaction.is_local() { @@ -437,7 +437,7 @@ impl PendingPool { if local_senders.insert(sender_id) { non_local_senders -= 1; } - continue + continue; } total_size += tx.transaction.size(); @@ -455,7 +455,7 @@ impl PendingPool { // return if either the pool is under limits or there are no more _eligible_ // transactions to remove if !self.exceeds(limit) || non_local_senders == 0 { - return + return; } } } @@ -477,13 +477,13 @@ impl PendingPool { let mut removed = Vec::new(); // return early if the pool is already under the limits if !self.exceeds(&limit) { - return removed + return removed; } // first truncate only non-local transactions, returning if the pool end up under the limit self.remove_to_limit(&limit, false, &mut removed); if !self.exceeds(&limit) { - return removed + return removed; } // now repeat for local transactions, since local transactions must be removed now for the diff --git a/crates/transaction-pool/src/pool/state.rs b/crates/transaction-pool/src/pool/state.rs index e04b463343..691c426127 100644 --- a/crates/transaction-pool/src/pool/state.rs +++ b/crates/transaction-pool/src/pool/state.rs @@ -160,10 +160,10 @@ mod tests { let state = TxState::default(); assert_eq!(SubPool::Queued, state.into()); - let state = TxState::NO_PARKED_ANCESTORS | - TxState::NO_NONCE_GAPS | - TxState::NOT_TOO_MUCH_GAS | - TxState::ENOUGH_FEE_CAP_BLOCK; + let state = TxState::NO_PARKED_ANCESTORS + | TxState::NO_NONCE_GAPS + | TxState::NOT_TOO_MUCH_GAS + | TxState::ENOUGH_FEE_CAP_BLOCK; assert_eq!(SubPool::Queued, state.into()); } diff --git a/crates/transaction-pool/src/pool/txpool.rs b/crates/transaction-pool/src/pool/txpool.rs index 66ba5368f0..1eef79bfa3 100644 --- a/crates/transaction-pool/src/pool/txpool.rs +++ b/crates/transaction-pool/src/pool/txpool.rs @@ -175,7 +175,7 @@ impl TxPool { let mut next_expected_nonce = on_chain.nonce; for (id, tx) in self.all().descendant_txs_inclusive(&on_chain) { if next_expected_nonce != id.nonce { - break + break; } next_expected_nonce = id.next_nonce(); last_consecutive_tx = Some(tx); @@ -652,7 +652,7 @@ impl TxPool { on_chain_code_hash: Option, ) -> PoolResult> { if self.contains(tx.hash()) { - return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported)) + return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported)); } self.validate_auth(&tx, on_chain_nonce, on_chain_code_hash)?; @@ -758,10 +758,10 @@ impl TxPool { on_chain_code_hash: Option, ) -> Result<(), PoolError> { // Short circuit if the sender has neither delegation nor pending delegation. - if (on_chain_code_hash.is_none() || on_chain_code_hash == Some(KECCAK_EMPTY)) && - !self.all_transactions.auths.contains_key(&transaction.sender_id()) + if (on_chain_code_hash.is_none() || on_chain_code_hash == Some(KECCAK_EMPTY)) + && !self.all_transactions.auths.contains_key(&transaction.sender_id()) { - return Ok(()) + return Ok(()); } let mut txs_by_sender = @@ -775,14 +775,14 @@ impl TxPool { PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702( Eip7702PoolTransactionError::OutOfOrderTxFromDelegated, )), - )) + )); } - return Ok(()) + return Ok(()); } if txs_by_sender.any(|id| id == &transaction.transaction_id) { // Transaction replacement is supported - return Ok(()) + return Ok(()); } Err(PoolError::new( @@ -819,7 +819,7 @@ impl TxPool { PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702( Eip7702PoolTransactionError::AuthorityReserved, )), - )) + )); } } } @@ -1004,7 +1004,7 @@ impl TxPool { } id = descendant; } else { - return + return; } } } @@ -1273,7 +1273,7 @@ impl AllTransactions { if *count == 1 { entry.remove(); self.metrics.all_transactions_by_all_senders.decrement(1.0); - return + return; } *count -= 1; self.metrics.all_transactions_by_all_senders.decrement(1.0); @@ -1348,7 +1348,7 @@ impl AllTransactions { ($iter:ident) => { 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this + break 'this; } iter.next(); } @@ -1365,7 +1365,7 @@ impl AllTransactions { current: tx.subpool, destination: Destination::Discard, }); - continue 'transactions + continue 'transactions; } let ancestor = TransactionId::ancestor(id.nonce, info.state_nonce, id.sender); @@ -1390,7 +1390,7 @@ impl AllTransactions { // If there's a nonce gap, we can shortcircuit, because there's nothing to update yet. if tx.state.has_nonce_gap() { next_sender!(iter); - continue 'transactions + continue 'transactions; } // Since this is the first transaction of the sender, it has no parked ancestors @@ -1413,7 +1413,7 @@ impl AllTransactions { while let Some((peek, tx)) = iter.peek_mut() { if peek.sender != id.sender { // Found the next sender we need to check - continue 'transactions + continue 'transactions; } if tx.transaction.nonce() == next_nonce_in_line { @@ -1422,7 +1422,7 @@ impl AllTransactions { } else { // can short circuit if there's still a nonce gap next_sender!(iter); - continue 'transactions + continue 'transactions; } // update for next iteration of this sender's loop @@ -1667,7 +1667,7 @@ impl AllTransactions { if current_txs >= self.max_account_slots && transaction.nonce() > on_chain_nonce { return Err(InsertErr::ExceededSenderTransactionsCapacity { transaction: Arc::new(transaction), - }) + }); } } if transaction.gas_limit() > self.block_gas_limit { @@ -1675,12 +1675,12 @@ impl AllTransactions { block_gas_limit: self.block_gas_limit, tx_gas_limit: transaction.gas_limit(), transaction: Arc::new(transaction), - }) + }); } if self.contains_conflicting_transaction(&transaction) { // blob vs non blob transactions are mutually exclusive for the same sender - return Err(InsertErr::TxTypeConflict { transaction: Arc::new(transaction) }) + return Err(InsertErr::TxTypeConflict { transaction: Arc::new(transaction) }); } Ok(transaction) @@ -1701,13 +1701,13 @@ impl AllTransactions { let Some(ancestor_tx) = self.txs.get(&ancestor) else { // ancestor tx is missing, so we can't insert the new blob self.metrics.blob_transactions_nonce_gaps.increment(1); - return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }) + return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }); }; if ancestor_tx.state.has_nonce_gap() { // the ancestor transaction already has a nonce gap, so we can't insert the new // blob self.metrics.blob_transactions_nonce_gaps.increment(1); - return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }) + return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }); } // the max cost executing this transaction requires @@ -1716,7 +1716,7 @@ impl AllTransactions { // check if the new blob would go into overdraft if cumulative_cost > on_chain_balance { // the transaction would go into overdraft - return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) + return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }); } // ensure that a replacement would not shift already propagated blob transactions into @@ -1733,14 +1733,16 @@ impl AllTransactions { cumulative_cost += tx.transaction.cost(); if tx.transaction.is_eip4844() && cumulative_cost > on_chain_balance { // the transaction would shift - return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) + return Err(InsertErr::Overdraft { + transaction: Arc::new(new_blob_tx), + }); } } } } } else if new_blob_tx.cost() > &on_chain_balance { // the transaction would go into overdraft - return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) + return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }); } Ok(new_blob_tx) @@ -1831,7 +1833,7 @@ impl AllTransactions { let fee_cap = transaction.max_fee_per_gas(); if fee_cap < self.minimal_protocol_basefee as u128 { - return Err(InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap }) + return Err(InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap }); } if fee_cap >= self.pending_fees.base_fee as u128 { state.insert(TxState::ENOUGH_FEE_CAP_BLOCK); @@ -1864,7 +1866,7 @@ impl AllTransactions { return Err(InsertErr::Underpriced { transaction: pool_tx.transaction, existing: *entry.get().transaction.hash(), - }) + }); } let new_hash = *pool_tx.transaction.hash(); let new_transaction = pool_tx.transaction.clone(); @@ -1904,7 +1906,7 @@ impl AllTransactions { // If there's a nonce gap, we can shortcircuit if next_nonce != id.nonce { - break + break; } // close the nonce gap diff --git a/crates/transaction-pool/src/test_utils/mock.rs b/crates/transaction-pool/src/test_utils/mock.rs index 9ddde67ba5..073b7a4145 100644 --- a/crates/transaction-pool/src/test_utils/mock.rs +++ b/crates/transaction-pool/src/test_utils/mock.rs @@ -57,11 +57,11 @@ macro_rules! set_value { ($this:ident => $field:ident) => { let new_value = $field; match $this { - MockTransaction::Legacy { ref mut $field, .. } | - MockTransaction::Eip1559 { ref mut $field, .. } | - MockTransaction::Eip4844 { ref mut $field, .. } | - MockTransaction::Eip2930 { ref mut $field, .. } | - MockTransaction::Eip7702 { ref mut $field, .. } => { + MockTransaction::Legacy { ref mut $field, .. } + | MockTransaction::Eip1559 { ref mut $field, .. } + | MockTransaction::Eip4844 { ref mut $field, .. } + | MockTransaction::Eip2930 { ref mut $field, .. } + | MockTransaction::Eip7702 { ref mut $field, .. } => { *$field = new_value; } } @@ -74,11 +74,11 @@ macro_rules! set_value { macro_rules! get_value { ($this:tt => $field:ident) => { match $this { - MockTransaction::Legacy { $field, .. } | - MockTransaction::Eip1559 { $field, .. } | - MockTransaction::Eip4844 { $field, .. } | - MockTransaction::Eip2930 { $field, .. } | - MockTransaction::Eip7702 { $field, .. } => $field, + MockTransaction::Legacy { $field, .. } + | MockTransaction::Eip1559 { $field, .. } + | MockTransaction::Eip4844 { $field, .. } + | MockTransaction::Eip2930 { $field, .. } + | MockTransaction::Eip7702 { $field, .. } => $field, } }; } @@ -414,8 +414,8 @@ impl MockTransaction { /// Sets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn set_priority_fee(&mut self, val: u128) -> &mut Self { - if let Self::Eip1559 { max_priority_fee_per_gas, .. } | - Self::Eip4844 { max_priority_fee_per_gas, .. } = self + if let Self::Eip1559 { max_priority_fee_per_gas, .. } + | Self::Eip4844 { max_priority_fee_per_gas, .. } = self { *max_priority_fee_per_gas = val; } @@ -431,18 +431,18 @@ impl MockTransaction { /// Gets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_priority_fee(&self) -> Option { match self { - Self::Eip1559 { max_priority_fee_per_gas, .. } | - Self::Eip4844 { max_priority_fee_per_gas, .. } | - Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), + Self::Eip1559 { max_priority_fee_per_gas, .. } + | Self::Eip4844 { max_priority_fee_per_gas, .. } + | Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), _ => None, } } /// Sets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn set_max_fee(&mut self, val: u128) -> &mut Self { - if let Self::Eip1559 { max_fee_per_gas, .. } | - Self::Eip4844 { max_fee_per_gas, .. } | - Self::Eip7702 { max_fee_per_gas, .. } = self + if let Self::Eip1559 { max_fee_per_gas, .. } + | Self::Eip4844 { max_fee_per_gas, .. } + | Self::Eip7702 { max_fee_per_gas, .. } = self { *max_fee_per_gas = val; } @@ -458,9 +458,9 @@ impl MockTransaction { /// Gets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_max_fee(&self) -> Option { match self { - Self::Eip1559 { max_fee_per_gas, .. } | - Self::Eip4844 { max_fee_per_gas, .. } | - Self::Eip7702 { max_fee_per_gas, .. } => Some(*max_fee_per_gas), + Self::Eip1559 { max_fee_per_gas, .. } + | Self::Eip4844 { max_fee_per_gas, .. } + | Self::Eip7702 { max_fee_per_gas, .. } => Some(*max_fee_per_gas), _ => None, } } @@ -469,10 +469,10 @@ impl MockTransaction { pub fn set_accesslist(&mut self, list: AccessList) -> &mut Self { match self { Self::Legacy { .. } => {} - Self::Eip1559 { access_list: accesslist, .. } | - Self::Eip4844 { access_list: accesslist, .. } | - Self::Eip2930 { access_list: accesslist, .. } | - Self::Eip7702 { access_list: accesslist, .. } => { + Self::Eip1559 { access_list: accesslist, .. } + | Self::Eip4844 { access_list: accesslist, .. } + | Self::Eip2930 { access_list: accesslist, .. } + | Self::Eip7702 { access_list: accesslist, .. } => { *accesslist = list; } } @@ -494,9 +494,9 @@ impl MockTransaction { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => { *gas_price = val; } - Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } | - Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } | - Self::Eip7702 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { + Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } + | Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } + | Self::Eip7702 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -510,9 +510,9 @@ impl MockTransaction { Self::Legacy { ref mut gas_price, .. } | Self::Eip2930 { ref mut gas_price, .. } => { *gas_price = val; } - Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } | - Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } | - Self::Eip7702 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => { + Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } + | Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } + | Self::Eip7702 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -524,9 +524,9 @@ impl MockTransaction { pub const fn get_gas_price(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_fee_per_gas, .. } | - Self::Eip4844 { max_fee_per_gas, .. } | - Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Eip1559 { max_fee_per_gas, .. } + | Self::Eip4844 { max_fee_per_gas, .. } + | Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, } } @@ -660,13 +660,13 @@ impl MockTransaction { fn update_cost(&mut self) { match self { - Self::Legacy { cost, gas_limit, gas_price, value, .. } | - Self::Eip2930 { cost, gas_limit, gas_price, value, .. } => { + Self::Legacy { cost, gas_limit, gas_price, value, .. } + | Self::Eip2930 { cost, gas_limit, gas_price, value, .. } => { *cost = U256::from(*gas_limit) * U256::from(*gas_price) + *value } - Self::Eip1559 { cost, gas_limit, max_fee_per_gas, value, .. } | - Self::Eip4844 { cost, gas_limit, max_fee_per_gas, value, .. } | - Self::Eip7702 { cost, gas_limit, max_fee_per_gas, value, .. } => { + Self::Eip1559 { cost, gas_limit, max_fee_per_gas, value, .. } + | Self::Eip4844 { cost, gas_limit, max_fee_per_gas, value, .. } + | Self::Eip7702 { cost, gas_limit, max_fee_per_gas, value, .. } => { *cost = U256::from(*gas_limit) * U256::from(*max_fee_per_gas) + *value } }; @@ -706,11 +706,11 @@ impl PoolTransaction for MockTransaction { // not to be manually set. fn cost(&self) -> &U256 { match self { - Self::Legacy { cost, .. } | - Self::Eip2930 { cost, .. } | - Self::Eip1559 { cost, .. } | - Self::Eip4844 { cost, .. } | - Self::Eip7702 { cost, .. } => cost, + Self::Legacy { cost, .. } + | Self::Eip2930 { cost, .. } + | Self::Eip1559 { cost, .. } + | Self::Eip4844 { cost, .. } + | Self::Eip7702 { cost, .. } => cost, } } @@ -742,10 +742,10 @@ impl alloy_consensus::Transaction for MockTransaction { fn chain_id(&self) -> Option { match self { Self::Legacy { chain_id, .. } => *chain_id, - Self::Eip1559 { chain_id, .. } | - Self::Eip4844 { chain_id, .. } | - Self::Eip2930 { chain_id, .. } | - Self::Eip7702 { chain_id, .. } => Some(*chain_id), + Self::Eip1559 { chain_id, .. } + | Self::Eip4844 { chain_id, .. } + | Self::Eip2930 { chain_id, .. } + | Self::Eip7702 { chain_id, .. } => Some(*chain_id), } } @@ -767,18 +767,18 @@ impl alloy_consensus::Transaction for MockTransaction { fn max_fee_per_gas(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_fee_per_gas, .. } | - Self::Eip4844 { max_fee_per_gas, .. } | - Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Eip1559 { max_fee_per_gas, .. } + | Self::Eip4844 { max_fee_per_gas, .. } + | Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, } } fn max_priority_fee_per_gas(&self) -> Option { match self { Self::Legacy { .. } | Self::Eip2930 { .. } => None, - Self::Eip1559 { max_priority_fee_per_gas, .. } | - Self::Eip4844 { max_priority_fee_per_gas, .. } | - Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), + Self::Eip1559 { max_priority_fee_per_gas, .. } + | Self::Eip4844 { max_priority_fee_per_gas, .. } + | Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), } } @@ -792,9 +792,9 @@ impl alloy_consensus::Transaction for MockTransaction { fn priority_fee_or_price(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_priority_fee_per_gas, .. } | - Self::Eip4844 { max_priority_fee_per_gas, .. } | - Self::Eip7702 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, + Self::Eip1559 { max_priority_fee_per_gas, .. } + | Self::Eip4844 { max_priority_fee_per_gas, .. } + | Self::Eip7702 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, } } @@ -838,11 +838,11 @@ impl alloy_consensus::Transaction for MockTransaction { fn value(&self) -> U256 { match self { - Self::Legacy { value, .. } | - Self::Eip1559 { value, .. } | - Self::Eip2930 { value, .. } | - Self::Eip4844 { value, .. } | - Self::Eip7702 { value, .. } => *value, + Self::Legacy { value, .. } + | Self::Eip1559 { value, .. } + | Self::Eip2930 { value, .. } + | Self::Eip4844 { value, .. } + | Self::Eip7702 { value, .. } => *value, } } @@ -853,10 +853,10 @@ impl alloy_consensus::Transaction for MockTransaction { fn access_list(&self) -> Option<&AccessList> { match self { Self::Legacy { .. } => None, - Self::Eip1559 { access_list: accesslist, .. } | - Self::Eip4844 { access_list: accesslist, .. } | - Self::Eip2930 { access_list: accesslist, .. } | - Self::Eip7702 { access_list: accesslist, .. } => Some(accesslist), + Self::Eip1559 { access_list: accesslist, .. } + | Self::Eip4844 { access_list: accesslist, .. } + | Self::Eip2930 { access_list: accesslist, .. } + | Self::Eip7702 { access_list: accesslist, .. } => Some(accesslist), } } diff --git a/crates/transaction-pool/src/traits.rs b/crates/transaction-pool/src/traits.rs index e9f58c27a3..0f353dd851 100644 --- a/crates/transaction-pool/src/traits.rs +++ b/crates/transaction-pool/src/traits.rs @@ -1574,7 +1574,7 @@ impl NewSubpoolTransactionStream { match self.st.try_recv() { Ok(event) => { if event.subpool == self.subpool { - return Ok(event) + return Ok(event); } } Err(e) => return Err(e), @@ -1591,7 +1591,7 @@ impl Stream for NewSubpoolTransactionStream { match ready!(self.st.poll_recv(cx)) { Some(event) => { if event.subpool == self.subpool { - return Poll::Ready(Some(event)) + return Poll::Ready(Some(event)); } } None => return Poll::Ready(None), diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index 90a61b86ec..fa64257de3 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -312,7 +312,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip2930Disabled.into(), - )) + )); } } EIP1559_TX_TYPE_ID => { @@ -321,7 +321,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip1559Disabled.into(), - )) + )); } } EIP4844_TX_TYPE_ID => { @@ -330,7 +330,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip4844Disabled.into(), - )) + )); } } EIP7702_TX_TYPE_ID => { @@ -339,7 +339,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip7702Disabled.into(), - )) + )); } } @@ -357,7 +357,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::Eip2681, - )) + )); } // Reject transactions over defined size to prevent DOS attacks @@ -366,13 +366,13 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::OversizedData(tx_input_len, self.max_tx_input_bytes), - )) + )); } // Check whether the init code size has been exceeded. if self.fork_tracker.is_shanghai_activated() { if let Err(err) = transaction.ensure_max_init_code_size(MAX_INIT_CODE_BYTE_SIZE) { - return Err(TransactionValidationOutcome::Invalid(transaction, err)) + return Err(TransactionValidationOutcome::Invalid(transaction, err)); } } @@ -386,7 +386,7 @@ where transaction_gas_limit, block_gas_limit, ), - )) + )); } // Ensure max_priority_fee_per_gas (if EIP1559) is less than max_fee_per_gas if any. @@ -394,7 +394,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TipAboveFeeCap.into(), - )) + )); } // determine whether the transaction should be treated as local @@ -417,7 +417,7 @@ where max_tx_fee_wei, tx_fee_cap_wei, }, - )) + )); } } } @@ -425,14 +425,14 @@ where // Drop non-local transactions with a fee lower than the configured fee for acceptance into // the pool. - if !is_local && - transaction.is_dynamic_fee() && - transaction.max_priority_fee_per_gas() < self.minimum_priority_fee + if !is_local + && transaction.is_dynamic_fee() + && transaction.max_priority_fee_per_gas() < self.minimum_priority_fee { return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::Underpriced, - )) + )); } // Checks for chainid @@ -441,7 +441,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::ChainIdMismatch.into(), - )) + )); } } @@ -451,19 +451,19 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - )) + )); } if transaction.authorization_list().is_none_or(|l| l.is_empty()) { return Err(TransactionValidationOutcome::Invalid( transaction, Eip7702PoolTransactionError::MissingEip7702AuthorizationList.into(), - )) + )); } } if let Err(err) = ensure_intrinsic_gas(&transaction, &self.fork_tracker) { - return Err(TransactionValidationOutcome::Invalid(transaction, err)) + return Err(TransactionValidationOutcome::Invalid(transaction, err)); } // light blob tx pre-checks @@ -473,7 +473,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - )) + )); } let blob_count = @@ -485,7 +485,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::NoEip4844Blobs, ), - )) + )); } let max_blob_count = self.fork_tracker.max_blob_count(); @@ -498,18 +498,18 @@ where permitted: max_blob_count, }, ), - )) + )); } } // Osaka validation of max tx gas. - if self.fork_tracker.is_osaka_activated() && - transaction.gas_limit() > MAX_TX_GAS_LIMIT_OSAKA + if self.fork_tracker.is_osaka_activated() + && transaction.gas_limit() > MAX_TX_GAS_LIMIT_OSAKA { return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::GasLimitTooHigh.into(), - )) + )); } Ok(transaction) @@ -558,7 +558,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::SignerAccountHasBytecode.into(), - ) + ); } } @@ -570,7 +570,7 @@ where transaction, InvalidTransactionError::NonceNotConsistent { tx: tx_nonce, state: account.nonce } .into(), - ) + ); } let cost = transaction.cost(); @@ -584,7 +584,7 @@ where GotExpected { got: account.balance, expected }.into(), ) .into(), - ) + ); } let mut maybe_blob_sidecar = None; @@ -598,7 +598,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ) + ); } EthBlobTransactionSidecar::Missing => { // This can happen for re-injected blob transactions (on re-org), since the blob @@ -613,7 +613,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::MissingEip4844BlobSidecar, ), - ) + ); } } EthBlobTransactionSidecar::Present(sidecar) => { @@ -626,7 +626,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka, ), - ) + ); } } else if sidecar.is_eip7594() { return TransactionValidationOutcome::Invalid( @@ -634,7 +634,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka, ), - ) + ); } // validate the blob @@ -644,7 +644,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::InvalidEip4844Blob(err), ), - ) + ); } // Record the duration of successful blob validation as histogram self.validation_metrics.blob_validation_duration.record(now.elapsed()); diff --git a/crates/transaction-pool/src/validate/mod.rs b/crates/transaction-pool/src/validate/mod.rs index 36d9f14add..f49832b509 100644 --- a/crates/transaction-pool/src/validate/mod.rs +++ b/crates/transaction-pool/src/validate/mod.rs @@ -459,7 +459,7 @@ impl ValidPoolTransaction { // Check if the max fee per gas is underpriced. if maybe_replacement.max_fee_per_gas() < self.max_fee_per_gas() * (100 + price_bump) / 100 { - return true + return true; } let existing_max_priority_fee_per_gas = @@ -468,12 +468,12 @@ impl ValidPoolTransaction { maybe_replacement.transaction.max_priority_fee_per_gas().unwrap_or_default(); // Check max priority fee per gas (relevant for EIP-1559 transactions only) - if existing_max_priority_fee_per_gas != 0 && - replacement_max_priority_fee_per_gas != 0 && - replacement_max_priority_fee_per_gas < - existing_max_priority_fee_per_gas * (100 + price_bump) / 100 + if existing_max_priority_fee_per_gas != 0 + && replacement_max_priority_fee_per_gas != 0 + && replacement_max_priority_fee_per_gas + < existing_max_priority_fee_per_gas * (100 + price_bump) / 100 { - return true + return true; } // Check max blob fee per gas @@ -481,10 +481,10 @@ impl ValidPoolTransaction { // This enforces that blob txs can only be replaced by blob txs let replacement_max_blob_fee_per_gas = maybe_replacement.transaction.max_fee_per_blob_gas().unwrap_or_default(); - if replacement_max_blob_fee_per_gas < - existing_max_blob_fee_per_gas * (100 + price_bump) / 100 + if replacement_max_blob_fee_per_gas + < existing_max_blob_fee_per_gas * (100 + price_bump) / 100 { - return true + return true; } } diff --git a/crates/trie/common/benches/prefix_set.rs b/crates/trie/common/benches/prefix_set.rs index bc2a8dc259..2da11d694f 100644 --- a/crates/trie/common/benches/prefix_set.rs +++ b/crates/trie/common/benches/prefix_set.rs @@ -195,12 +195,12 @@ mod implementations { for key in self.keys.range::(range) { if key.starts_with(&prefix) { self.last_checked = Some(prefix); - return true + return true; } if key > &prefix { self.last_checked = Some(prefix); - return false + return false; } } @@ -278,12 +278,12 @@ mod implementations { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(&prefix) { self.index += idx; - return true + return true; } if key > &prefix { self.index += idx; - return false + return false; } } diff --git a/crates/trie/common/src/hashed_state.rs b/crates/trie/common/src/hashed_state.rs index b6f60e2b2a..f3ec7eeccd 100644 --- a/crates/trie/common/src/hashed_state.rs +++ b/crates/trie/common/src/hashed_state.rs @@ -216,7 +216,7 @@ impl HashedPostState { let mut storage_not_in_targets = HashedStorage::default(); storage.storage.retain(|&slot, value| { if storage_in_targets.contains(&slot) { - return true + return true; } storage_not_in_targets.storage.insert(slot, *value); @@ -251,7 +251,7 @@ impl HashedPostState { }); self.accounts.retain(|&address, account| { if targets.contains_key(&address) { - return true + return true; } state_updates_not_in_targets.accounts.insert(address, *account); diff --git a/crates/trie/common/src/prefix_set.rs b/crates/trie/common/src/prefix_set.rs index e1f4150dd2..c46aa44e48 100644 --- a/crates/trie/common/src/prefix_set.rs +++ b/crates/trie/common/src/prefix_set.rs @@ -17,9 +17,9 @@ pub struct TriePrefixSetsMut { impl TriePrefixSetsMut { /// Returns `true` if all prefix sets are empty. pub fn is_empty(&self) -> bool { - self.account_prefix_set.is_empty() && - self.storage_prefix_sets.is_empty() && - self.destroyed_accounts.is_empty() + self.account_prefix_set.is_empty() + && self.storage_prefix_sets.is_empty() + && self.destroyed_accounts.is_empty() } /// Extends prefix sets with contents of another prefix set. @@ -195,7 +195,7 @@ impl PrefixSet { #[inline] pub fn contains(&mut self, prefix: &Nibbles) -> bool { if self.all { - return true + return true; } while self.index > 0 && &self.keys[self.index] > prefix { @@ -205,12 +205,12 @@ impl PrefixSet { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(prefix) { self.index += idx; - return true + return true; } if key > prefix { self.index += idx; - return false + return false; } } diff --git a/crates/trie/common/src/proofs.rs b/crates/trie/common/src/proofs.rs index 5c3b55b092..2065c6a3a4 100644 --- a/crates/trie/common/src/proofs.rs +++ b/crates/trie/common/src/proofs.rs @@ -179,10 +179,10 @@ pub struct MultiProof { impl MultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { - self.account_subtree.is_empty() && - self.branch_node_hash_masks.is_empty() && - self.branch_node_tree_masks.is_empty() && - self.storages.is_empty() + self.account_subtree.is_empty() + && self.branch_node_hash_masks.is_empty() + && self.branch_node_tree_masks.is_empty() + && self.storages.is_empty() } /// Return the account proof nodes for the given account path. @@ -238,7 +238,7 @@ impl MultiProof { nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), - }) + }); } } } @@ -310,10 +310,10 @@ pub struct DecodedMultiProof { impl DecodedMultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { - self.account_subtree.is_empty() && - self.branch_node_hash_masks.is_empty() && - self.branch_node_tree_masks.is_empty() && - self.storages.is_empty() + self.account_subtree.is_empty() + && self.branch_node_hash_masks.is_empty() + && self.branch_node_tree_masks.is_empty() + && self.storages.is_empty() } /// Return the account proof nodes for the given account path. @@ -368,7 +368,7 @@ impl DecodedMultiProof { nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), - }) + }); } } None @@ -489,7 +489,7 @@ impl StorageMultiProof { if let Some(last) = proof.last() { if let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? { if nibbles.ends_with(&leaf.key) { - break 'value U256::decode(&mut &leaf.value[..])? + break 'value U256::decode(&mut &leaf.value[..])?; } } } @@ -541,7 +541,7 @@ impl DecodedStorageMultiProof { let value = 'value: { if let Some(TrieNode::Leaf(leaf)) = proof.last() { if nibbles.ends_with(&leaf.key) { - break 'value U256::decode(&mut &leaf.value[..])? + break 'value U256::decode(&mut &leaf.value[..])?; } } U256::ZERO @@ -627,10 +627,10 @@ impl AccountProof { } = proof; let storage_proofs = storage_proof.into_iter().map(Into::into).collect(); - let (storage_root, info) = if nonce == 0 && - balance.is_zero() && - storage_hash.is_zero() && - code_hash == KECCAK_EMPTY + let (storage_root, info) = if nonce == 0 + && balance.is_zero() + && storage_hash.is_zero() + && code_hash == KECCAK_EMPTY { // Account does not exist in state. Return `None` here to prevent proof // verification. diff --git a/crates/trie/common/src/updates.rs b/crates/trie/common/src/updates.rs index dd82f4e192..0a2c28d80d 100644 --- a/crates/trie/common/src/updates.rs +++ b/crates/trie/common/src/updates.rs @@ -25,9 +25,9 @@ pub struct TrieUpdates { impl TrieUpdates { /// Returns `true` if the updates are empty. pub fn is_empty(&self) -> bool { - self.account_nodes.is_empty() && - self.removed_nodes.is_empty() && - self.storage_tries.is_empty() + self.account_nodes.is_empty() + && self.removed_nodes.is_empty() + && self.storage_tries.is_empty() } /// Returns reference to updated account nodes. diff --git a/crates/trie/db/tests/witness.rs b/crates/trie/db/tests/witness.rs index 5dfa1c3e4a..c1a5ad14a0 100644 --- a/crates/trie/db/tests/witness.rs +++ b/crates/trie/db/tests/witness.rs @@ -89,16 +89,12 @@ fn includes_nodes_for_destroyed_storage_nodes() { )])) .unwrap(); - let witness = - TrieWitness::from_tx(provider.tx_ref()) - .compute(HashedPostState { - accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), - storages: HashMap::from_iter([( - hashed_address, - HashedStorage::from_iter(true, []), - )]), // destroyed - }) - .unwrap(); + let witness = TrieWitness::from_tx(provider.tx_ref()) + .compute(HashedPostState { + accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), + storages: HashMap::from_iter([(hashed_address, HashedStorage::from_iter(true, []))]), // destroyed + }) + .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { assert_eq!(witness.get(&keccak256(node)), Some(node)); diff --git a/crates/trie/parallel/src/proof.rs b/crates/trie/parallel/src/proof.rs index 940a51a924..76babc4060 100644 --- a/crates/trie/parallel/src/proof.rs +++ b/crates/trie/parallel/src/proof.rs @@ -248,39 +248,38 @@ where hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_address, account) => { - let decoded_storage_multiproof = match storage_proof_receivers - .remove(&hashed_address) - { - Some(rx) => rx.recv().map_err(|e| { - ParallelStateRootError::StorageRoot(StorageRootError::Database( - DatabaseError::Other(format!( - "channel closed for {hashed_address}: {e}" - )), - )) - })??, - // Since we do not store all intermediate nodes in the database, there might - // be a possibility of re-adding a non-modified leaf to the hash builder. - None => { - tracker.inc_missed_leaves(); - - let raw_fallback_proof = StorageProof::new_hashed( - trie_cursor_factory.clone(), - hashed_cursor_factory.clone(), - hashed_address, - ) - .with_prefix_set_mut(Default::default()) - .storage_multiproof( - targets.get(&hashed_address).cloned().unwrap_or_default(), - ) - .map_err(|e| { + let decoded_storage_multiproof = + match storage_proof_receivers.remove(&hashed_address) { + Some(rx) => rx.recv().map_err(|e| { ParallelStateRootError::StorageRoot(StorageRootError::Database( - DatabaseError::Other(e.to_string()), + DatabaseError::Other(format!( + "channel closed for {hashed_address}: {e}" + )), )) - })?; - - raw_fallback_proof.try_into()? - } - }; + })??, + // Since we do not store all intermediate nodes in the database, there might + // be a possibility of re-adding a non-modified leaf to the hash builder. + None => { + tracker.inc_missed_leaves(); + + let raw_fallback_proof = StorageProof::new_hashed( + trie_cursor_factory.clone(), + hashed_cursor_factory.clone(), + hashed_address, + ) + .with_prefix_set_mut(Default::default()) + .storage_multiproof( + targets.get(&hashed_address).cloned().unwrap_or_default(), + ) + .map_err(|e| { + ParallelStateRootError::StorageRoot(StorageRootError::Database( + DatabaseError::Other(e.to_string()), + )) + })?; + + raw_fallback_proof.try_into()? + } + }; // Encode account account_rlp.clear(); diff --git a/crates/trie/parallel/src/proof_task.rs b/crates/trie/parallel/src/proof_task.rs index 4dc7810696..8ddcc96218 100644 --- a/crates/trie/parallel/src/proof_task.rs +++ b/crates/trie/parallel/src/proof_task.rs @@ -142,7 +142,7 @@ where let Some(proof_task_tx) = self.get_or_create_tx()? else { // if there are no txs available, requeue the proof task self.pending_tasks.push_front(task); - return Ok(()) + return Ok(()); }; let tx_sender = self.tx_sender.clone(); diff --git a/crates/trie/sparse-parallel/src/trie.rs b/crates/trie/sparse-parallel/src/trie.rs index b2d8d147f8..6cd0b146be 100644 --- a/crates/trie/sparse-parallel/src/trie.rs +++ b/crates/trie/sparse-parallel/src/trie.rs @@ -218,31 +218,31 @@ impl ParallelSparseTrie { found_full_path.extend(key); if &found_full_path == leaf_full_path { - return Ok(FindNextToLeafOutcome::Found) + return Ok(FindNextToLeafOutcome::Found); } Ok(FindNextToLeafOutcome::NotFound) } SparseNode::Extension { key, .. } => { if leaf_full_path.len() == from_path.len() { - return Ok(FindNextToLeafOutcome::NotFound) + return Ok(FindNextToLeafOutcome::NotFound); } let mut child_path = *from_path; child_path.extend(key); if !leaf_full_path.starts_with(&child_path) { - return Ok(FindNextToLeafOutcome::NotFound) + return Ok(FindNextToLeafOutcome::NotFound); } Ok(FindNextToLeafOutcome::ContinueFrom(child_path)) } SparseNode::Branch { state_mask, .. } => { if leaf_full_path.len() == from_path.len() { - return Ok(FindNextToLeafOutcome::NotFound) + return Ok(FindNextToLeafOutcome::NotFound); } let nibble = leaf_full_path.get_unchecked(from_path.len()); if !state_mask.is_bit_set(nibble) { - return Ok(FindNextToLeafOutcome::NotFound) + return Ok(FindNextToLeafOutcome::NotFound); } let mut child_path = *from_path; @@ -489,7 +489,7 @@ impl ParallelSparseTrie { // here, all remaining logic is related to the ancestors of the leaf. if leaf_path.is_empty() { self.upper_subtrie.nodes.insert(leaf_path, SparseNode::Empty); - return Ok(()) + return Ok(()); } // If there is a parent branch node (very likely, unless the leaf is at the root) execute @@ -553,7 +553,7 @@ impl ParallelSparseTrie { return Err(SparseTrieErrorKind::NodeNotFoundInProvider { path: remaining_child_path, } - .into()) + .into()); } } node => node, @@ -772,7 +772,7 @@ impl ParallelSparseTrie { // If we're past the subtrie path, we're done with this subtrie. Do not // advance the iterator, the next key will be processed either by the // next subtrie or inserted into the unchanged prefix set. - break + break; } } PrefixSetMut::from(new_prefix_set) @@ -852,7 +852,7 @@ impl SparseSubtrie { // If the node is already revealed and it's not a hash node, do nothing. if self.nodes.get(&path).is_some_and(|node| !node.is_hash()) { - return Ok(()) + return Ok(()); } if let Some(tree_mask) = masks.tree_mask { @@ -896,8 +896,8 @@ impl SparseSubtrie { // node. hash: Some(*hash), store_in_db_trie: Some( - masks.hash_mask.is_some_and(|mask| !mask.is_empty()) || - masks.tree_mask.is_some_and(|mask| !mask.is_empty()), + masks.hash_mask.is_some_and(|mask| !mask.is_empty()) + || masks.tree_mask.is_some_and(|mask| !mask.is_empty()), ), }); } @@ -973,9 +973,9 @@ impl SparseSubtrie { // Leaf node already exists. SparseNode::Leaf { .. } => {} // All other node types can't be handled. - node @ (SparseNode::Empty | - SparseNode::Extension { .. } | - SparseNode::Branch { .. }) => { + node @ (SparseNode::Empty + | SparseNode::Extension { .. } + | SparseNode::Branch { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), @@ -1032,7 +1032,7 @@ impl SparseSubtrie { entry.insert(SparseNode::Hash(hash)); } } - return Ok(()) + return Ok(()); } self.reveal_node(path, &TrieNode::decode(&mut &child[..])?, TrieMasks::none()) @@ -1231,7 +1231,7 @@ impl SparseSubtrieInner { }, RlpNodePathStackItem { path: child_path, is_in_prefix_set: None }, ]); - return + return; } } SparseNode::Branch { state_mask, hash, store_in_db_trie } => { @@ -1247,7 +1247,7 @@ impl SparseSubtrieInner { store_in_db_trie: Some(store_in_db_trie), }, }); - return + return; } let retain_updates = self.updates.is_some() && prefix_set_contains(&path); @@ -1293,8 +1293,9 @@ impl SparseSubtrieInner { store_in_db_trie } else { // A blinded node has the tree mask bit set - child_node_type.is_hash() && - self.branch_node_tree_masks + child_node_type.is_hash() + && self + .branch_node_tree_masks .get(&path) .is_some_and(|mask| mask.is_bit_set(last_child_nibble)) }; @@ -1306,11 +1307,12 @@ impl SparseSubtrieInner { // is a blinded node that has its hash mask bit set according to the // database, set the hash mask bit and save the hash. let hash = child.as_hash().filter(|_| { - child_node_type.is_branch() || - (child_node_type.is_hash() && - self.branch_node_hash_masks.get(&path).is_some_and( - |mask| mask.is_bit_set(last_child_nibble), - )) + child_node_type.is_branch() + || (child_node_type.is_hash() + && self + .branch_node_hash_masks + .get(&path) + .is_some_and(|mask| mask.is_bit_set(last_child_nibble))) }); if let Some(hash) = hash { hash_mask.set_bit(last_child_nibble); @@ -1338,7 +1340,7 @@ impl SparseSubtrieInner { .drain(..) .map(|path| RlpNodePathStackItem { path, is_in_prefix_set: None }), ); - return + return; } } @@ -1379,8 +1381,9 @@ impl SparseSubtrieInner { } else if self .branch_node_tree_masks .get(&path) - .is_some_and(|mask| !mask.is_empty()) || - self.branch_node_hash_masks + .is_some_and(|mask| !mask.is_empty()) + || self + .branch_node_hash_masks .get(&path) .is_some_and(|mask| !mask.is_empty()) { @@ -1392,8 +1395,8 @@ impl SparseSubtrieInner { } else if self .branch_node_hash_masks .get(&path) - .is_none_or(|mask| mask.is_empty()) && - self.branch_node_hash_masks.get(&path).is_none_or(|mask| mask.is_empty()) + .is_none_or(|mask| mask.is_empty()) + && self.branch_node_hash_masks.get(&path).is_none_or(|mask| mask.is_empty()) { // If new tree and hash masks are empty, and they were previously empty // as well, we need to remove the node update. diff --git a/crates/trie/sparse/src/state.rs b/crates/trie/sparse/src/state.rs index 66c3596363..a963861c1c 100644 --- a/crates/trie/sparse/src/state.rs +++ b/crates/trie/sparse/src/state.rs @@ -231,7 +231,7 @@ impl SparseStateTrie { // Reveal the remaining proof nodes. for (path, bytes) in proof { if self.revealed_account_paths.contains(&path) { - continue + continue; } let node = TrieNode::decode(&mut &bytes[..])?; trie.reveal_node(path, node, TrieMasks::none())?; @@ -278,7 +278,7 @@ impl SparseStateTrie { for (path, bytes) in proof { // If the node is already revealed, skip it. if revealed_nodes.contains(&path) { - continue + continue; } let node = TrieNode::decode(&mut &bytes[..])?; trie.reveal_node(path, node, TrieMasks::none())?; @@ -590,13 +590,13 @@ impl SparseStateTrie { // Validate root node. let Some((path, node)) = proof.next() else { return Ok(None) }; if !path.is_empty() { - return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()) + return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()); } // Decode root node and perform sanity check. let root_node = TrieNode::decode(&mut &node[..])?; if matches!(root_node, TrieNode::EmptyRoot) && proof.peek().is_some() { - return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()) + return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()); } Ok(Some(root_node)) @@ -613,7 +613,7 @@ impl SparseStateTrie { path, node: alloy_rlp::encode(&root_node).into(), } - .into()) + .into()); } // Perform sanity check. @@ -622,7 +622,7 @@ impl SparseStateTrie { path, node: alloy_rlp::encode(&root_node).into(), } - .into()) + .into()); } Ok(Some(root_node)) @@ -796,7 +796,7 @@ impl SparseStateTrie { EMPTY_ROOT_HASH } } else { - return Err(SparseTrieErrorKind::Blind.into()) + return Err(SparseTrieErrorKind::Blind.into()); }; if account.is_empty() && storage_root == EMPTY_ROOT_HASH { @@ -818,7 +818,7 @@ impl SparseStateTrie { /// will be removed. pub fn update_account_storage_root(&mut self, address: B256) -> SparseStateTrieResult<()> { if !self.is_account_revealed(address) { - return Err(SparseTrieErrorKind::Blind.into()) + return Err(SparseTrieErrorKind::Blind.into()); } // Nothing to update if the account doesn't exist in the trie. @@ -828,7 +828,7 @@ impl SparseStateTrie { .transpose()? else { trace!(target: "trie::sparse", ?address, "Account not found in trie, skipping storage root update"); - return Ok(()) + return Ok(()); }; // Calculate the new storage root. If the storage trie doesn't exist, the storage root will @@ -915,7 +915,7 @@ fn filter_revealed_nodes( // If the node is already revealed, skip it. if revealed_nodes.contains(&path) { result.skipped_nodes += 1; - continue + continue; } result.new_nodes += 1; diff --git a/crates/trie/sparse/src/trie.rs b/crates/trie/sparse/src/trie.rs index e2f28c2417..40ecec050d 100644 --- a/crates/trie/sparse/src/trie.rs +++ b/crates/trie/sparse/src/trie.rs @@ -634,7 +634,7 @@ impl

RevealedSparseTrie

{ ) -> SparseTrieResult<()> { // If the node is already revealed and it's not a hash node, do nothing. if self.nodes.get(&path).is_some_and(|node| !node.is_hash()) { - return Ok(()) + return Ok(()); } if let Some(tree_mask) = masks.tree_mask { @@ -674,8 +674,8 @@ impl

RevealedSparseTrie

{ // node. hash: Some(*hash), store_in_db_trie: Some( - masks.hash_mask.is_some_and(|mask| !mask.is_empty()) || - masks.tree_mask.is_some_and(|mask| !mask.is_empty()), + masks.hash_mask.is_some_and(|mask| !mask.is_empty()) + || masks.tree_mask.is_some_and(|mask| !mask.is_empty()), ), }); } @@ -747,9 +747,9 @@ impl

RevealedSparseTrie

{ // Left node already exists. SparseNode::Leaf { .. } => {} // All other node types can't be handled. - node @ (SparseNode::Empty | - SparseNode::Extension { .. } | - SparseNode::Branch { .. }) => { + node @ (SparseNode::Empty + | SparseNode::Extension { .. } + | SparseNode::Branch { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), @@ -806,7 +806,7 @@ impl

RevealedSparseTrie

{ entry.insert(SparseNode::Hash(hash)); } } - return Ok(()) + return Ok(()); } self.reveal_node(path, TrieNode::decode(&mut &child[..])?, TrieMasks::none()) @@ -854,7 +854,7 @@ impl

RevealedSparseTrie

{ node, unset_branch_nibble: None, }); - break + break; } SparseNode::Extension { key, .. } => { #[cfg(debug_assertions)] @@ -1030,14 +1030,14 @@ impl

RevealedSparseTrie

{ SparseNode::Empty | SparseNode::Hash(_) => {} SparseNode::Leaf { key: _, hash } => { if hash.is_some() && !prefix_set.contains(&path) { - continue + continue; } targets.push((level, path)); } SparseNode::Extension { key, hash, store_in_db_trie: _ } => { if hash.is_some() && !prefix_set.contains(&path) { - continue + continue; } if level >= depth { @@ -1051,7 +1051,7 @@ impl

RevealedSparseTrie

{ } SparseNode::Branch { state_mask, hash, store_in_db_trie: _ } => { if hash.is_some() && !prefix_set.contains(&path) { - continue + continue; } if level >= depth { @@ -1196,7 +1196,7 @@ impl

RevealedSparseTrie

{ is_in_prefix_set: None, }, ]); - continue + continue; } } SparseNode::Branch { state_mask, hash, store_in_db_trie } => { @@ -1210,7 +1210,7 @@ impl

RevealedSparseTrie

{ store_in_db_trie: Some(store_in_db_trie), }, }); - continue + continue; } let retain_updates = self.updates.is_some() && prefix_set_contains(&path); @@ -1255,10 +1255,11 @@ impl

RevealedSparseTrie

{ store_in_db_trie } else { // A blinded node has the tree mask bit set - child_node_type.is_hash() && - self.branch_node_tree_masks.get(&path).is_some_and( - |mask| mask.is_bit_set(last_child_nibble), - ) + child_node_type.is_hash() + && self + .branch_node_tree_masks + .get(&path) + .is_some_and(|mask| mask.is_bit_set(last_child_nibble)) }; if should_set_tree_mask_bit { tree_mask.set_bit(last_child_nibble); @@ -1268,13 +1269,11 @@ impl

RevealedSparseTrie

{ // is a blinded node that has its hash mask bit set according to the // database, set the hash mask bit and save the hash. let hash = child.as_hash().filter(|_| { - child_node_type.is_branch() || - (child_node_type.is_hash() && - self.branch_node_hash_masks - .get(&path) - .is_some_and(|mask| { - mask.is_bit_set(last_child_nibble) - })) + child_node_type.is_branch() + || (child_node_type.is_hash() + && self.branch_node_hash_masks.get(&path).is_some_and( + |mask| mask.is_bit_set(last_child_nibble), + )) }); if let Some(hash) = hash { hash_mask.set_bit(last_child_nibble); @@ -1302,7 +1301,7 @@ impl

RevealedSparseTrie

{ is_in_prefix_set: None, }, )); - continue 'main + continue 'main; } } @@ -1341,8 +1340,9 @@ impl

RevealedSparseTrie

{ } else if self .branch_node_tree_masks .get(&path) - .is_some_and(|mask| !mask.is_empty()) || - self.branch_node_hash_masks + .is_some_and(|mask| !mask.is_empty()) + || self + .branch_node_hash_masks .get(&path) .is_some_and(|mask| !mask.is_empty()) { @@ -1354,8 +1354,9 @@ impl

RevealedSparseTrie

{ } else if self .branch_node_hash_masks .get(&path) - .is_none_or(|mask| mask.is_empty()) && - self.branch_node_hash_masks + .is_none_or(|mask| mask.is_empty()) + && self + .branch_node_hash_masks .get(&path) .is_none_or(|mask| mask.is_empty()) { @@ -1597,7 +1598,7 @@ impl RevealedSparseTrie

{ let existing = self.values.insert(path, value); if existing.is_some() { // trie structure unchanged, return immediately - return Ok(()) + return Ok(()); } let mut current = Nibbles::default(); @@ -1605,7 +1606,7 @@ impl RevealedSparseTrie

{ match node { SparseNode::Empty => { *node = SparseNode::new_leaf(path); - break + break; } &mut SparseNode::Hash(hash) => { return Err(SparseTrieErrorKind::BlindedNode { path: current, hash }.into()) @@ -1731,12 +1732,12 @@ impl RevealedSparseTrie

{ if self.values.remove(path).is_none() { if let Some(&SparseNode::Hash(hash)) = self.nodes.get(path) { // Leaf is present in the trie, but it's blinded. - return Err(SparseTrieErrorKind::BlindedNode { path: *path, hash }.into()) + return Err(SparseTrieErrorKind::BlindedNode { path: *path, hash }.into()); } trace!(target: "trie::sparse", ?path, "Leaf node is not present in the trie"); // Leaf is not present in the trie. - return Ok(()) + return Ok(()); } self.prefix_set.insert(*path); @@ -1760,7 +1761,7 @@ impl RevealedSparseTrie

{ debug_assert!(self.nodes.is_empty()); self.nodes.insert(Nibbles::default(), SparseNode::Empty); - return Ok(()) + return Ok(()); } // Walk the stack of removed nodes from the back and re-insert them back into the trie, diff --git a/crates/trie/trie/src/hashed_cursor/post_state.rs b/crates/trie/trie/src/hashed_cursor/post_state.rs index b6c8994e13..a6a89c7f5b 100644 --- a/crates/trie/trie/src/hashed_cursor/post_state.rs +++ b/crates/trie/trie/src/hashed_cursor/post_state.rs @@ -80,7 +80,7 @@ where // It's an exact match, return the account from post state without looking up in the // database. if post_state_entry.is_some_and(|entry| entry.0 == key) { - return Ok(post_state_entry) + return Ok(post_state_entry); } // It's not an exact match, reposition to the first greater or equal account that wasn't @@ -215,7 +215,7 @@ where // If database storage was wiped or it's an exact match, // return the storage slot from post state without looking up in the database. if self.storage_wiped || post_state_entry.is_some_and(|entry| entry.0 == subkey) { - return Ok(post_state_entry) + return Ok(post_state_entry); } // It's not an exact match and storage was not wiped, @@ -237,7 +237,7 @@ where // Return post state entry immediately if database was wiped. if self.storage_wiped { - return Ok(post_state_entry) + return Ok(post_state_entry); } // If post state was given precedence, move the cursor forward. diff --git a/crates/trie/trie/src/node_iter.rs b/crates/trie/trie/src/node_iter.rs index dfb140fdf9..fe4c821f3d 100644 --- a/crates/trie/trie/src/node_iter.rs +++ b/crates/trie/trie/src/node_iter.rs @@ -211,7 +211,7 @@ where *key, self.walker.hash().unwrap(), self.walker.children_are_in_trie(), - )))) + )))); } } } @@ -221,7 +221,7 @@ where // Check if the walker's key is less than the key of the current hashed entry if self.walker.key().is_some_and(|key| key < &Nibbles::unpack(hashed_key)) { self.should_check_walker_key = false; - continue + continue; } // Set the next hashed entry as a leaf node and return @@ -230,7 +230,7 @@ where #[cfg(feature = "metrics")] self.metrics.inc_leaf_nodes_returned(); - return Ok(Some(TrieElement::Leaf(hashed_key, value))) + return Ok(Some(TrieElement::Leaf(hashed_key, value))); } // Handle seeking and advancing based on the previous hashed key @@ -274,9 +274,9 @@ where // the database, so the walker will advance to the branch node after it. Because // of this, we need to check that the current walker key has a prefix of the key // that we seeked to. - if can_skip_node && - self.walker.key().is_some_and(|key| key.starts_with(&seek_prefix)) && - self.walker.children_are_in_trie() + if can_skip_node + && self.walker.key().is_some_and(|key| key.starts_with(&seek_prefix)) + && self.walker.children_are_in_trie() { trace!( target: "trie::node_iter", @@ -286,7 +286,7 @@ where ); self.should_check_walker_key = false; - continue + continue; } self.current_hashed_entry = self.seek_hashed_entry(seek_key)?; diff --git a/crates/trie/trie/src/proof/mod.rs b/crates/trie/trie/src/proof/mod.rs index 266aac19a3..5260a7f12c 100644 --- a/crates/trie/trie/src/proof/mod.rs +++ b/crates/trie/trie/src/proof/mod.rs @@ -272,7 +272,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok(StorageMultiProof::empty()) + return Ok(StorageMultiProof::empty()); } let target_nibbles = targets.into_iter().map(Nibbles::unpack).collect::>(); diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index e6f5463b7d..b9d1c79787 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -230,9 +230,9 @@ where hash_builder.add_leaf(Nibbles::unpack(hashed_address), &account_rlp); // Decide if we need to return intermediate progress. - let total_updates_len = updated_storage_nodes + - account_node_iter.walker.removed_keys_len() + - hash_builder.updates_len(); + let total_updates_len = updated_storage_nodes + + account_node_iter.walker.removed_keys_len() + + hash_builder.updates_len(); if retain_updates && total_updates_len as u64 >= self.threshold { let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split(); trie_updates.removed_nodes.extend(walker_deleted_keys); @@ -249,7 +249,7 @@ where Box::new(state), hashed_entries_walked, trie_updates, - )) + )); } } } @@ -406,7 +406,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok((EMPTY_ROOT_HASH, 0, StorageTrieUpdates::deleted())) + return Ok((EMPTY_ROOT_HASH, 0, StorageTrieUpdates::deleted())); } let mut tracker = TrieTracker::default(); diff --git a/crates/trie/trie/src/trie_cursor/in_memory.rs b/crates/trie/trie/src/trie_cursor/in_memory.rs index 4925dc8a66..dda2d60621 100644 --- a/crates/trie/trie/src/trie_cursor/in_memory.rs +++ b/crates/trie/trie/src/trie_cursor/in_memory.rs @@ -79,7 +79,7 @@ impl<'a, C: TrieCursor> InMemoryAccountTrieCursor<'a, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.seek(&key); if in_memory.as_ref().is_some_and(|entry| entry.0 == key) { - return Ok(in_memory) + return Ok(in_memory); } // Reposition the cursor to the first greater or equal node that wasn't removed. @@ -203,7 +203,7 @@ impl InMemoryStorageTrieCursor<'_, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.seek(&key)); if self.storage_trie_cleared || in_memory.as_ref().is_some_and(|entry| entry.0 == key) { - return Ok(in_memory.filter(|(nibbles, _)| !exact || nibbles == &key)) + return Ok(in_memory.filter(|(nibbles, _)| !exact || nibbles == &key)); } // Reposition the cursor to the first greater or equal node that wasn't removed. @@ -227,7 +227,7 @@ impl InMemoryStorageTrieCursor<'_, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.first_after(&last)); if self.storage_trie_cleared { - return Ok(in_memory) + return Ok(in_memory); } // Reposition the cursor to the first greater or equal node that wasn't removed. diff --git a/crates/trie/trie/src/walker.rs b/crates/trie/trie/src/walker.rs index 5bbedb2353..e07261a416 100644 --- a/crates/trie/trie/src/walker.rs +++ b/crates/trie/trie/src/walker.rs @@ -265,7 +265,7 @@ impl TrieWalker { let Some((key, node)) = self.node(false)? else { // If no next node is found, clear the stack. self.stack.clear(); - return Ok(()) + return Ok(()); }; // Overwrite the root node's first nibble @@ -284,7 +284,7 @@ impl TrieWalker { #[cfg(feature = "metrics")] self.metrics.inc_out_of_order_subnode(1); self.move_to_next_sibling(false)?; - return Ok(()) + return Ok(()); } } @@ -315,18 +315,18 @@ impl TrieWalker { // Check if the walker needs to backtrack to the previous level in the trie during its // traversal. - if subnode.position().is_last_child() || - (subnode.position().is_parent() && !allow_root_to_child_nibble) + if subnode.position().is_last_child() + || (subnode.position().is_parent() && !allow_root_to_child_nibble) { self.stack.pop(); self.move_to_next_sibling(false)?; - return Ok(()) + return Ok(()); } subnode.inc_nibble(); if subnode.node.is_none() { - return self.consume_node() + return self.consume_node(); } // Find the next sibling with state. @@ -334,11 +334,11 @@ impl TrieWalker { let position = subnode.position(); if subnode.state_flag() { trace!(target: "trie::walker", ?position, "found next sibling with state"); - return Ok(()) + return Ok(()); } if position.is_last_child() { trace!(target: "trie::walker", ?position, "checked all siblings"); - break + break; } subnode.inc_nibble(); } diff --git a/crates/trie/trie/src/witness.rs b/crates/trie/trie/src/witness.rs index ce40a01e1c..be2a241259 100644 --- a/crates/trie/trie/src/witness.rs +++ b/crates/trie/trie/src/witness.rs @@ -106,7 +106,7 @@ where pub fn compute(mut self, state: HashedPostState) -> Result, TrieWitnessError> { let is_state_empty = state.is_empty(); if is_state_empty && !self.always_include_root_node { - return Ok(Default::default()) + return Ok(Default::default()); } let proof_targets = if is_state_empty { @@ -129,7 +129,7 @@ where } else { (EMPTY_ROOT_HASH, Bytes::from([EMPTY_STRING_CODE])) }; - return Ok(B256Map::from_iter([(root_hash, root_node)])) + return Ok(B256Map::from_iter([(root_hash, root_node)])); } // Record all nodes from multiproof in the witness diff --git a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs index 9bbb198ae1..cf53972357 100644 --- a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs +++ b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs @@ -110,7 +110,7 @@ where let mut actions_to_queue: Vec = Vec::new(); if txs.is_empty() { - return + return; } match self.pool.get_all_blobs_exact(txs.iter().map(|(tx, _)| *tx.tx_hash()).collect()) { @@ -168,7 +168,7 @@ where // Request locally first, otherwise request from CL loop { if let Some(mined_sidecar) = this.queued_actions.pop_front() { - return Poll::Ready(Some(Ok(mined_sidecar))) + return Poll::Ready(Some(Ok(mined_sidecar))); } // Check if any pending requests are ready and append to buffer @@ -253,7 +253,7 @@ async fn fetch_blobs_for_block( response.status().as_u16(), "Unhandled HTTP status.".to_string(), )), - } + }; } let bytes = match response.bytes().await { diff --git a/examples/custom-engine-types/src/main.rs b/examples/custom-engine-types/src/main.rs index ae42090d21..59fe91b5ad 100644 --- a/examples/custom-engine-types/src/main.rs +++ b/examples/custom-engine-types/src/main.rs @@ -237,7 +237,7 @@ where if attributes.custom == 0 { return Err(EngineObjectValidationError::invalid_params( CustomError::CustomFieldIsNotZero, - )) + )); } Ok(()) diff --git a/examples/custom-node/src/engine.rs b/examples/custom-node/src/engine.rs index e3bc6019d7..077ecdd4eb 100644 --- a/examples/custom-node/src/engine.rs +++ b/examples/custom-node/src/engine.rs @@ -270,7 +270,7 @@ where if attributes.extension == 0 { return Err(EngineObjectValidationError::invalid_params( CustomError::CustomFieldIsNotZero, - )) + )); } Ok(()) diff --git a/examples/custom-node/src/primitives/tx_custom.rs b/examples/custom-node/src/primitives/tx_custom.rs index 8729378bd5..7c7bceaae4 100644 --- a/examples/custom-node/src/primitives/tx_custom.rs +++ b/examples/custom-node/src/primitives/tx_custom.rs @@ -92,13 +92,13 @@ impl TxPayment { impl RlpEcdsaEncodableTx for TxPayment { /// Outputs the length of the transaction's fields, without a RLP header. fn rlp_encoded_fields_length(&self) -> usize { - self.chain_id.length() + - self.nonce.length() + - self.max_priority_fee_per_gas.length() + - self.max_fee_per_gas.length() + - self.gas_limit.length() + - self.to.length() + - self.value.length() + self.chain_id.length() + + self.nonce.length() + + self.max_priority_fee_per_gas.length() + + self.max_fee_per_gas.length() + + self.gas_limit.length() + + self.to.length() + + self.value.length() } /// Encodes only the transaction's fields into the desired buffer, without diff --git a/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs b/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs index 7fd8ac7f44..4a83ffe9f9 100644 --- a/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs +++ b/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs @@ -35,7 +35,7 @@ impl Stream for CustomRlpxConnection { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Some(initial_ping) = this.initial_ping.take() { - return Poll::Ready(Some(initial_ping.encoded())) + return Poll::Ready(Some(initial_ping.encoded())); } loop { @@ -45,13 +45,13 @@ impl Stream for CustomRlpxConnection { this.pending_pong = Some(response); Poll::Ready(Some(CustomRlpxProtoMessage::ping_message(msg).encoded())) } - } + }; } let Some(msg) = ready!(this.conn.poll_next_unpin(cx)) else { return Poll::Ready(None) }; let Some(msg) = CustomRlpxProtoMessage::decode_message(&mut &msg[..]) else { - return Poll::Ready(None) + return Poll::Ready(None); }; match msg.message { @@ -66,11 +66,11 @@ impl Stream for CustomRlpxConnection { if let Some(sender) = this.pending_pong.take() { sender.send(msg).ok(); } - continue + continue; } } - return Poll::Pending + return Poll::Pending; } } } diff --git a/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs b/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs index 495c435782..2cb225e091 100644 --- a/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs +++ b/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs @@ -75,8 +75,8 @@ impl CustomRlpxProtoMessage { buf.put_u8(self.message_type as u8); match &self.message { CustomRlpxProtoMessageKind::Ping | CustomRlpxProtoMessageKind::Pong => {} - CustomRlpxProtoMessageKind::PingMessage(msg) | - CustomRlpxProtoMessageKind::PongMessage(msg) => { + CustomRlpxProtoMessageKind::PingMessage(msg) + | CustomRlpxProtoMessageKind::PongMessage(msg) => { buf.put(msg.as_bytes()); } } @@ -86,7 +86,7 @@ impl CustomRlpxProtoMessage { /// Decodes a `CustomRlpxProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None + return None; } let id = buf[0]; buf.advance(1); diff --git a/examples/manual-p2p/src/main.rs b/examples/manual-p2p/src/main.rs index edd5ade245..366e95e8c5 100644 --- a/examples/manual-p2p/src/main.rs +++ b/examples/manual-p2p/src/main.rs @@ -54,14 +54,14 @@ async fn main() -> eyre::Result<()> { if let DiscoveryUpdate::Added(peer) = update { // Boot nodes hard at work, lets not disturb them if MAINNET_BOOT_NODES.contains(&peer) { - return + return; } let (p2p_stream, their_hello) = match handshake_p2p(peer, our_key).await { Ok(s) => s, Err(e) => { println!("Failed P2P handshake with peer {}, {}", peer.address, e); - return + return; } }; @@ -69,7 +69,7 @@ async fn main() -> eyre::Result<()> { Ok(s) => s, Err(e) => { println!("Failed ETH handshake with peer {}, {}", peer.address, e); - return + return; } }; diff --git a/examples/node-custom-rpc/src/main.rs b/examples/node-custom-rpc/src/main.rs index 9aba7c9922..bda1cc90cf 100644 --- a/examples/node-custom-rpc/src/main.rs +++ b/examples/node-custom-rpc/src/main.rs @@ -35,7 +35,7 @@ fn main() { .node(EthereumNode::default()) .extend_rpc_modules(move |ctx| { if !args.enable_ext { - return Ok(()) + return Ok(()); } // here we get the configured pool. diff --git a/examples/precompile-cache/src/main.rs b/examples/precompile-cache/src/main.rs index e72fee598c..2b68c5f752 100644 --- a/examples/precompile-cache/src/main.rs +++ b/examples/precompile-cache/src/main.rs @@ -129,7 +129,7 @@ impl Precompile for WrappedPrecompile { // get the result if it exists if let Some(result) = cache.cache.get(&key) { - return result.clone() + return result.clone(); } // call the precompile if cache miss diff --git a/testing/ef-tests/src/cases/blockchain_test.rs b/testing/ef-tests/src/cases/blockchain_test.rs index 4c463c612a..c9724fe24e 100644 --- a/testing/ef-tests/src/cases/blockchain_test.rs +++ b/testing/ef-tests/src/cases/blockchain_test.rs @@ -58,12 +58,12 @@ impl BlockchainTestCase { const fn excluded_fork(network: ForkSpec) -> bool { matches!( network, - ForkSpec::ByzantiumToConstantinopleAt5 | - ForkSpec::Constantinople | - ForkSpec::ConstantinopleFix | - ForkSpec::MergeEOF | - ForkSpec::MergeMeterInitCode | - ForkSpec::MergePush0 + ForkSpec::ByzantiumToConstantinopleAt5 + | ForkSpec::Constantinople + | ForkSpec::ConstantinopleFix + | ForkSpec::MergeEOF + | ForkSpec::MergeMeterInitCode + | ForkSpec::MergePush0 ) } @@ -157,7 +157,7 @@ impl Case for BlockchainTestCase { fn run(&self) -> Result<(), Error> { // If the test is marked for skipping, return a Skipped error immediately. if self.skip { - return Err(Error::Skipped) + return Err(Error::Skipped); } // Iterate through test cases, filtering by the network type to exclude specific forks. @@ -283,7 +283,7 @@ fn run_case(case: &BlockchainTest) -> Result<(), Error> { return Err(Error::block_failed( block_number, Error::Assertion("state root mismatch".to_string()), - )) + )); } // Commit the post state/state diff to the database diff --git a/testing/ef-tests/src/models.rs b/testing/ef-tests/src/models.rs index 6cad5331e5..26a5492669 100644 --- a/testing/ef-tests/src/models.rs +++ b/testing/ef-tests/src/models.rs @@ -243,12 +243,12 @@ impl Account { } else { return Err(Error::Assertion(format!( "Slot {slot:?} is missing from the database. Expected {value:?}" - ))) + ))); } } else { return Err(Error::Assertion(format!( "Slot {slot:?} is missing from the database. Expected {value:?}" - ))) + ))); } } @@ -325,17 +325,17 @@ impl From for ChainSpec { spec_builder.tangerine_whistle_activated() } ForkSpec::EIP158 => spec_builder.spurious_dragon_activated(), - ForkSpec::Byzantium | - ForkSpec::EIP158ToByzantiumAt5 | - ForkSpec::ConstantinopleFix | - ForkSpec::ByzantiumToConstantinopleFixAt5 => spec_builder.byzantium_activated(), + ForkSpec::Byzantium + | ForkSpec::EIP158ToByzantiumAt5 + | ForkSpec::ConstantinopleFix + | ForkSpec::ByzantiumToConstantinopleFixAt5 => spec_builder.byzantium_activated(), ForkSpec::Istanbul => spec_builder.istanbul_activated(), ForkSpec::Berlin => spec_builder.berlin_activated(), ForkSpec::London | ForkSpec::BerlinToLondonAt5 => spec_builder.london_activated(), - ForkSpec::Merge | - ForkSpec::MergeEOF | - ForkSpec::MergeMeterInitCode | - ForkSpec::MergePush0 => spec_builder.paris_activated(), + ForkSpec::Merge + | ForkSpec::MergeEOF + | ForkSpec::MergeMeterInitCode + | ForkSpec::MergePush0 => spec_builder.paris_activated(), ForkSpec::Shanghai => spec_builder.shanghai_activated(), ForkSpec::Cancun => spec_builder.cancun_activated(), ForkSpec::ByzantiumToConstantinopleAt5 | ForkSpec::Constantinople => { diff --git a/testing/testing-utils/src/generators.rs b/testing/testing-utils/src/generators.rs index 793448cdba..a9b28cf6ce 100644 --- a/testing/testing-utils/src/generators.rs +++ b/testing/testing-utils/src/generators.rs @@ -345,7 +345,7 @@ where let old = if entry.value.is_zero() { let old = storage.remove(&entry.key); if matches!(old, Some(U256::ZERO)) { - return None + return None; } old } else { From defc921c9a87b41b029c23c0f4cece091a5bebd5 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:17:38 +0800 Subject: [PATCH 08/18] Revert "fix: ci run cargo fmt --all" This reverts commit 27bd9da703694f5b2b41c7b28bc6e1cfc3889070. --- bin/reth-bench/src/valid_payload.rs | 8 +- crates/alloy-provider/src/lib.rs | 12 +- crates/chain-state/src/chain_info.rs | 4 +- crates/chain-state/src/in_memory.rs | 6 +- crates/chain-state/src/notifications.rs | 4 +- crates/chain-state/src/test_utils.rs | 4 +- crates/chainspec/src/spec.rs | 16 +- crates/cli/cli/src/chainspec.rs | 2 +- crates/cli/commands/src/common.rs | 2 +- crates/cli/commands/src/db/checksum.rs | 2 +- crates/cli/commands/src/db/diff.rs | 4 +- crates/cli/commands/src/db/list.rs | 2 +- crates/cli/commands/src/db/mod.rs | 2 +- crates/cli/commands/src/db/stats.rs | 8 +- crates/cli/commands/src/db/tui.rs | 2 +- crates/cli/commands/src/import.rs | 4 +- crates/cli/commands/src/import_era.rs | 4 +- .../commands/src/init_state/without_evm.rs | 2 +- .../src/stage/dump/hashing_account.rs | 2 +- .../src/stage/dump/hashing_storage.rs | 2 +- crates/cli/commands/src/stage/dump/merkle.rs | 2 +- crates/cli/commands/src/stage/run.rs | 8 +- .../cli/commands/src/test_vectors/compact.rs | 2 +- .../cli/commands/src/test_vectors/tables.rs | 2 +- crates/cli/util/src/parsers.rs | 8 +- crates/cli/util/src/sigsegv_handler.rs | 4 +- crates/consensus/common/src/validation.rs | 34 ++-- crates/consensus/consensus/src/lib.rs | 2 +- .../debug-client/src/providers/etherscan.rs | 2 +- crates/e2e-test-utils/src/network.rs | 6 +- crates/e2e-test-utils/src/node.rs | 6 +- crates/e2e-test-utils/src/payload.rs | 2 +- .../src/testsuite/actions/produce_blocks.rs | 4 +- crates/engine/local/src/miner.rs | 4 +- crates/engine/tree/src/backfill.rs | 6 +- crates/engine/tree/src/chain.rs | 6 +- crates/engine/tree/src/download.rs | 8 +- crates/engine/tree/src/engine.rs | 10 +- crates/engine/tree/src/tree/block_buffer.rs | 2 +- crates/engine/tree/src/tree/cached_state.rs | 10 +- .../engine/tree/src/tree/invalid_headers.rs | 2 +- crates/engine/tree/src/tree/mod.rs | 172 +++++++++--------- .../src/tree/payload_processor/multiproof.rs | 14 +- .../src/tree/payload_processor/prewarm.rs | 18 +- .../engine/tree/src/tree/precompile_cache.rs | 2 +- crates/engine/tree/src/tree/state.rs | 14 +- crates/engine/tree/src/tree/tests.rs | 4 +- crates/engine/tree/src/tree/trie_updates.rs | 22 +-- crates/engine/util/src/reorg.rs | 14 +- crates/engine/util/src/skip_fcu.rs | 4 +- crates/engine/util/src/skip_new_payload.rs | 4 +- crates/era-downloader/tests/it/checksums.rs | 18 +- crates/era-downloader/tests/it/main.rs | 18 +- crates/era/src/era1_file.rs | 26 +-- crates/era/tests/it/main.rs | 4 +- .../ethereum/cli/src/debug_cmd/execution.rs | 4 +- .../cli/src/debug_cmd/in_memory_merkle.rs | 6 +- crates/ethereum/cli/src/debug_cmd/merkle.rs | 20 +- crates/ethereum/consensus/src/lib.rs | 45 +++-- crates/ethereum/consensus/src/validation.rs | 12 +- crates/ethereum/node/tests/e2e/rpc.rs | 4 +- crates/ethereum/payload/src/lib.rs | 14 +- crates/ethereum/payload/src/validator.rs | 2 +- crates/ethereum/primitives/src/receipt.rs | 22 +-- crates/ethereum/primitives/src/transaction.rs | 6 +- crates/etl/src/lib.rs | 2 +- crates/evm/evm/src/metrics.rs | 6 +- crates/evm/execution-errors/src/trie.rs | 4 +- crates/evm/execution-types/src/chain.rs | 6 +- .../execution-types/src/execution_outcome.rs | 6 +- crates/exex/exex/src/backfill/job.rs | 4 +- crates/exex/exex/src/backfill/stream.rs | 2 +- crates/exex/exex/src/manager.rs | 8 +- crates/exex/exex/src/notifications.rs | 18 +- crates/exex/exex/src/wal/cache.rs | 2 +- crates/exex/exex/src/wal/mod.rs | 6 +- crates/net/banlist/src/lib.rs | 6 +- crates/net/discv4/src/lib.rs | 78 ++++---- crates/net/discv4/src/proto.rs | 24 +-- crates/net/discv4/src/test_utils.rs | 4 +- crates/net/discv5/src/config.rs | 14 +- crates/net/discv5/src/enr.rs | 2 +- crates/net/discv5/src/filter.rs | 4 +- crates/net/discv5/src/lib.rs | 8 +- crates/net/discv5/src/network_stack_id.rs | 4 +- crates/net/dns/src/lib.rs | 6 +- crates/net/dns/src/query.rs | 8 +- crates/net/dns/src/sync.rs | 12 +- crates/net/dns/src/tree.rs | 2 +- crates/net/downloaders/src/bodies/bodies.rs | 60 +++--- crates/net/downloaders/src/bodies/request.rs | 10 +- crates/net/downloaders/src/bodies/task.rs | 8 +- crates/net/downloaders/src/file_client.rs | 12 +- crates/net/downloaders/src/file_codec.rs | 2 +- .../src/headers/reverse_headers.rs | 54 +++--- crates/net/downloaders/src/headers/task.rs | 6 +- .../downloaders/src/receipt_file_client.rs | 6 +- .../src/test_utils/bodies_client.rs | 2 +- crates/net/ecies/src/algorithm.rs | 16 +- crates/net/ecies/src/codec.rs | 22 +-- crates/net/eth-wire-types/src/broadcast.rs | 10 +- .../eth-wire-types/src/disconnect_reason.rs | 8 +- crates/net/eth-wire-types/src/message.rs | 30 +-- crates/net/eth-wire/src/capability.rs | 10 +- crates/net/eth-wire/src/errors/eth.rs | 2 +- crates/net/eth-wire/src/errors/p2p.rs | 4 +- crates/net/eth-wire/src/eth_snap_stream.rs | 10 +- crates/net/eth-wire/src/ethstream.rs | 2 +- crates/net/eth-wire/src/multiplex.rs | 51 +++--- crates/net/eth-wire/src/p2pstream.rs | 38 ++-- crates/net/eth-wire/src/pinger.rs | 6 +- crates/net/eth-wire/src/test_utils.rs | 2 +- crates/net/nat/src/lib.rs | 2 +- crates/net/network-types/src/peers/mod.rs | 6 +- crates/net/network/src/discovery.rs | 6 +- crates/net/network/src/error.rs | 124 ++++++------- crates/net/network/src/eth_requests.rs | 18 +- crates/net/network/src/fetch/mod.rs | 18 +- crates/net/network/src/manager.rs | 4 +- crates/net/network/src/network.rs | 2 +- crates/net/network/src/peers.rs | 72 ++++---- crates/net/network/src/session/active.rs | 46 ++--- crates/net/network/src/session/counter.rs | 2 +- crates/net/network/src/session/mod.rs | 8 +- crates/net/network/src/state.rs | 14 +- crates/net/network/src/swarm.rs | 22 +-- crates/net/network/src/test_utils/init.rs | 2 +- crates/net/network/src/test_utils/testnet.rs | 8 +- .../net/network/src/transactions/constants.rs | 12 +- .../net/network/src/transactions/fetcher.rs | 72 ++++---- crates/net/network/src/transactions/mod.rs | 92 +++++----- crates/net/network/tests/it/connect.rs | 4 +- crates/net/network/tests/it/multiplex.rs | 16 +- crates/net/network/tests/it/txgossip.rs | 4 +- crates/net/p2p/src/error.rs | 10 +- crates/net/p2p/src/full_block.rs | 28 +-- crates/net/p2p/src/test_utils/headers.rs | 10 +- crates/net/peers/src/lib.rs | 8 +- crates/net/peers/src/node_record.rs | 8 +- crates/node/builder/src/launch/common.rs | 10 +- crates/node/builder/src/launch/exex.rs | 2 +- crates/node/core/src/args/debug.rs | 2 +- crates/node/core/src/args/network.rs | 6 +- crates/node/core/src/args/payload_builder.rs | 2 +- crates/node/core/src/node_config.rs | 4 +- crates/node/events/src/cl.rs | 6 +- crates/node/events/src/node.rs | 14 +- crates/node/metrics/src/hooks.rs | 6 +- .../chainspec/src/superchain/configs.rs | 4 +- crates/optimism/cli/src/commands/import.rs | 6 +- .../cli/src/commands/import_receipts.rs | 2 +- .../optimism/cli/src/commands/init_state.rs | 2 +- crates/optimism/cli/src/receipt_file_codec.rs | 2 +- crates/optimism/consensus/src/lib.rs | 12 +- crates/optimism/consensus/src/proof.rs | 12 +- .../consensus/src/validation/canyon.rs | 2 +- .../consensus/src/validation/isthmus.rs | 4 +- .../optimism/consensus/src/validation/mod.rs | 16 +- crates/optimism/node/src/engine.rs | 10 +- crates/optimism/node/src/node.rs | 8 +- crates/optimism/payload/src/builder.rs | 22 +-- crates/optimism/payload/src/validator.rs | 2 +- crates/optimism/primitives/src/bedrock.rs | 4 +- crates/optimism/primitives/src/receipt.rs | 78 ++++---- .../primitives/src/transaction/signed.rs | 10 +- crates/optimism/rpc/src/error.rs | 10 +- crates/optimism/rpc/src/eth/block.rs | 2 +- crates/optimism/rpc/src/eth/ext.rs | 4 +- crates/optimism/rpc/src/eth/transaction.rs | 2 +- crates/optimism/rpc/src/historical.rs | 12 +- .../optimism/txpool/src/supervisor/client.rs | 2 +- crates/optimism/txpool/src/transaction.rs | 2 +- crates/optimism/txpool/src/validator.rs | 10 +- crates/payload/basic/src/lib.rs | 8 +- .../payload/builder-primitives/src/events.rs | 12 +- crates/payload/builder/src/noop.rs | 2 +- crates/payload/builder/src/service.rs | 2 +- crates/payload/primitives/src/lib.rs | 32 ++-- crates/payload/util/src/traits.rs | 4 +- crates/payload/validator/src/cancun.rs | 20 +- crates/payload/validator/src/prague.rs | 4 +- crates/payload/validator/src/shanghai.rs | 4 +- crates/primitives-traits/src/account.rs | 6 +- crates/primitives-traits/src/block/mod.rs | 4 +- .../primitives-traits/src/block/recovered.rs | 6 +- crates/primitives-traits/src/block/sealed.rs | 2 +- crates/primitives-traits/src/size.rs | 23 ++- crates/primitives-traits/src/withdrawal.rs | 8 +- crates/prune/prune/src/db_ext.rs | 6 +- crates/prune/prune/src/pruner.rs | 12 +- crates/prune/prune/src/segments/mod.rs | 6 +- crates/prune/prune/src/segments/receipts.rs | 6 +- crates/prune/prune/src/segments/set.rs | 2 +- .../prune/src/segments/static_file/headers.rs | 16 +- .../src/segments/static_file/transactions.rs | 6 +- .../src/segments/user/account_history.rs | 8 +- .../prune/prune/src/segments/user/history.rs | 4 +- .../src/segments/user/receipts_by_logs.rs | 21 +-- .../src/segments/user/sender_recovery.rs | 6 +- .../src/segments/user/storage_history.rs | 8 +- .../src/segments/user/transaction_lookup.rs | 12 +- crates/prune/types/src/lib.rs | 4 +- crates/prune/types/src/mode.rs | 2 +- crates/ress/protocol/src/connection.rs | 4 +- crates/ress/protocol/src/provider.rs | 12 +- crates/ress/protocol/tests/it/e2e.rs | 4 +- crates/ress/provider/src/lib.rs | 6 +- crates/ress/provider/src/pending_state.rs | 10 +- crates/revm/src/cached.rs | 18 +- 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/lib.rs | 22 +-- crates/rpc/rpc-builder/tests/it/http.rs | 4 +- crates/rpc/rpc-convert/src/fees.rs | 10 +- crates/rpc/rpc-convert/src/transaction.rs | 2 +- crates/rpc/rpc-engine-api/src/engine_api.rs | 16 +- crates/rpc/rpc-engine-api/src/error.rs | 34 ++-- crates/rpc/rpc-eth-api/src/helpers/block.rs | 4 +- crates/rpc/rpc-eth-api/src/helpers/call.rs | 20 +- .../rpc/rpc-eth-api/src/helpers/estimate.rs | 18 +- crates/rpc/rpc-eth-api/src/helpers/fee.rs | 27 ++- .../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 | 4 +- .../rpc-eth-api/src/helpers/transaction.rs | 8 +- crates/rpc/rpc-eth-types/src/cache/mod.rs | 8 +- crates/rpc/rpc-eth-types/src/error/api.rs | 4 +- crates/rpc/rpc-eth-types/src/error/mod.rs | 104 +++++------ crates/rpc/rpc-eth-types/src/fee_history.rs | 12 +- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 22 +-- crates/rpc/rpc-eth-types/src/id_provider.rs | 2 +- crates/rpc/rpc-eth-types/src/utils.rs | 2 +- crates/rpc/rpc-layer/src/auth_client_layer.rs | 4 +- crates/rpc/rpc-server-types/src/module.rs | 2 +- crates/rpc/rpc-testing-util/tests/it/trace.rs | 6 +- crates/rpc/rpc/src/debug.rs | 14 +- crates/rpc/rpc/src/eth/bundle.rs | 15 +- crates/rpc/rpc/src/eth/filter.rs | 16 +- crates/rpc/rpc/src/eth/helpers/block.rs | 2 +- crates/rpc/rpc/src/eth/pubsub.rs | 6 +- crates/rpc/rpc/src/eth/sim_bundle.rs | 10 +- crates/rpc/rpc/src/otterscan.rs | 2 +- crates/rpc/rpc/src/reth.rs | 2 +- crates/rpc/rpc/src/trace.rs | 12 +- crates/rpc/rpc/src/validation.rs | 66 +++---- .../alloy/consensus/src/receipt/envelope.rs | 40 ++-- .../consensus/src/transaction/l1_message.rs | 12 +- crates/scroll/alloy/evm/src/block/feynman.rs | 2 +- crates/scroll/alloy/evm/src/block/mod.rs | 16 +- crates/scroll/alloy/evm/src/system_caller.rs | 4 +- crates/scroll/alloy/evm/src/tx/compression.rs | 2 +- .../alloy/rpc-types-engine/src/attributes.rs | 10 +- crates/scroll/chainspec/src/lib.rs | 10 +- crates/scroll/consensus/src/validation.rs | 20 +- crates/scroll/evm/src/lib.rs | 8 +- crates/scroll/payload/src/builder.rs | 18 +- crates/scroll/payload/src/config.rs | 4 +- crates/scroll/primitives/src/receipt.rs | 66 +++---- crates/scroll/rpc/src/error.rs | 2 +- crates/scroll/rpc/src/eth/block.rs | 2 +- crates/scroll/rpc/src/eth/transaction.rs | 11 +- crates/scroll/rpc/src/lib.rs | 2 +- crates/scroll/rpc/src/sequencer.rs | 10 +- crates/scroll/txpool/src/validator.rs | 8 +- crates/stages/api/src/error.rs | 18 +- crates/stages/api/src/metrics/listener.rs | 2 +- crates/stages/api/src/pipeline/mod.rs | 35 ++-- crates/stages/api/src/pipeline/set.rs | 4 +- crates/stages/api/src/stage.rs | 2 +- crates/stages/stages/src/stages/bodies.rs | 14 +- crates/stages/stages/src/stages/era.rs | 4 +- crates/stages/stages/src/stages/execution.rs | 30 +-- crates/stages/stages/src/stages/finish.rs | 2 +- .../stages/src/stages/hashing_account.rs | 4 +- .../stages/src/stages/hashing_storage.rs | 10 +- crates/stages/stages/src/stages/headers.rs | 18 +- .../src/stages/index_account_history.rs | 4 +- .../src/stages/index_storage_history.rs | 4 +- crates/stages/stages/src/stages/merkle.rs | 24 +-- crates/stages/stages/src/stages/prune.rs | 2 +- .../stages/src/stages/s3/downloader/fetch.rs | 8 +- .../stages/src/stages/s3/downloader/meta.rs | 2 +- crates/stages/stages/src/stages/s3/mod.rs | 16 +- .../stages/src/stages/sender_recovery.rs | 12 +- crates/stages/stages/src/stages/tx_lookup.rs | 6 +- crates/stages/stages/src/stages/utils.rs | 4 +- .../stages/stages/src/test_utils/test_db.rs | 4 +- crates/stages/types/src/checkpoints.rs | 24 +-- crates/stages/types/src/execution.rs | 8 +- crates/stateless/src/trie.rs | 8 +- .../static-file/src/static_file_producer.rs | 6 +- crates/static-file/types/src/lib.rs | 15 +- crates/static-file/types/src/segment.rs | 6 +- .../codecs/derive/src/compact/flags.rs | 4 +- .../codecs/derive/src/compact/generator.rs | 2 +- .../storage/codecs/derive/src/compact/mod.rs | 11 +- .../codecs/derive/src/compact/structs.rs | 2 +- crates/storage/codecs/derive/src/lib.rs | 6 +- crates/storage/codecs/src/lib.rs | 10 +- crates/storage/codecs/src/test_utils.rs | 2 +- crates/storage/db-api/src/cursor.rs | 6 +- .../db-api/src/models/storage_sharded_key.rs | 2 +- crates/storage/db-api/src/unwind.rs | 2 +- crates/storage/db-common/src/db_tool/mod.rs | 16 +- crates/storage/db-common/src/init.rs | 20 +- .../storage/db/src/implementation/mdbx/mod.rs | 4 +- .../storage/db/src/implementation/mdbx/tx.rs | 6 +- crates/storage/db/src/lockfile.rs | 2 +- crates/storage/db/src/static_file/cursor.rs | 4 +- crates/storage/db/src/version.rs | 2 +- crates/storage/libmdbx-rs/mdbx-sys/build.rs | 76 ++++---- crates/storage/libmdbx-rs/src/codec.rs | 6 +- crates/storage/libmdbx-rs/src/cursor.rs | 6 +- crates/storage/libmdbx-rs/src/environment.rs | 8 +- crates/storage/libmdbx-rs/src/error.rs | 6 +- crates/storage/libmdbx-rs/src/transaction.rs | 4 +- .../storage/nippy-jar/src/compression/lz4.rs | 2 +- .../storage/nippy-jar/src/compression/zstd.rs | 14 +- crates/storage/nippy-jar/src/consistency.rs | 16 +- crates/storage/nippy-jar/src/cursor.rs | 4 +- crates/storage/nippy-jar/src/lib.rs | 10 +- crates/storage/nippy-jar/src/writer.rs | 6 +- .../provider/src/providers/consistent.rs | 44 ++--- .../provider/src/providers/consistent_view.rs | 2 +- .../src/providers/database/provider.rs | 69 ++++--- .../src/providers/state/historical.rs | 18 +- .../provider/src/providers/state/latest.rs | 2 +- .../provider/src/providers/static_file/jar.rs | 4 +- .../src/providers/static_file/manager.rs | 74 ++++---- .../src/providers/static_file/writer.rs | 10 +- .../storage/provider/src/test_utils/mock.rs | 4 +- crates/storage/provider/src/writer/mod.rs | 4 +- crates/storage/storage-api/src/receipts.rs | 2 +- crates/storage/storage-api/src/state.rs | 4 +- crates/storage/zstd-compressors/src/lib.rs | 2 +- crates/tasks/src/lib.rs | 2 +- crates/tokio-util/src/ratelimit.rs | 2 +- crates/transaction-pool/src/blobstore/disk.rs | 18 +- crates/transaction-pool/src/blobstore/mem.rs | 4 +- crates/transaction-pool/src/blobstore/mod.rs | 4 +- crates/transaction-pool/src/blobstore/noop.rs | 2 +- .../transaction-pool/src/blobstore/tracker.rs | 2 +- crates/transaction-pool/src/config.rs | 12 +- crates/transaction-pool/src/error.rs | 38 ++-- crates/transaction-pool/src/lib.rs | 2 +- crates/transaction-pool/src/maintain.rs | 14 +- crates/transaction-pool/src/noop.rs | 2 +- crates/transaction-pool/src/pool/best.rs | 19 +- crates/transaction-pool/src/pool/blob.rs | 18 +- crates/transaction-pool/src/pool/mod.rs | 26 +-- crates/transaction-pool/src/pool/parked.rs | 8 +- crates/transaction-pool/src/pool/pending.rs | 18 +- crates/transaction-pool/src/pool/state.rs | 8 +- crates/transaction-pool/src/pool/txpool.rs | 56 +++--- .../transaction-pool/src/test_utils/mock.rs | 132 +++++++------- crates/transaction-pool/src/traits.rs | 4 +- crates/transaction-pool/src/validate/eth.rs | 64 +++---- crates/transaction-pool/src/validate/mod.rs | 18 +- crates/trie/common/benches/prefix_set.rs | 8 +- crates/trie/common/src/hashed_state.rs | 4 +- crates/trie/common/src/prefix_set.rs | 12 +- crates/trie/common/src/proofs.rs | 32 ++-- crates/trie/common/src/updates.rs | 6 +- crates/trie/db/tests/witness.rs | 16 +- crates/trie/parallel/src/proof.rs | 61 ++++--- crates/trie/parallel/src/proof_task.rs | 2 +- crates/trie/sparse-parallel/src/trie.rs | 61 +++---- crates/trie/sparse/src/state.rs | 20 +- crates/trie/sparse/src/trie.rs | 69 ++++--- .../trie/trie/src/hashed_cursor/post_state.rs | 6 +- crates/trie/trie/src/node_iter.rs | 14 +- crates/trie/trie/src/proof/mod.rs | 2 +- crates/trie/trie/src/trie.rs | 10 +- crates/trie/trie/src/trie_cursor/in_memory.rs | 6 +- crates/trie/trie/src/walker.rs | 16 +- crates/trie/trie/src/witness.rs | 4 +- .../src/mined_sidecar.rs | 6 +- examples/custom-engine-types/src/main.rs | 2 +- examples/custom-node/src/engine.rs | 2 +- .../custom-node/src/primitives/tx_custom.rs | 14 +- .../src/subprotocol/connection/mod.rs | 10 +- .../src/subprotocol/protocol/proto.rs | 6 +- examples/manual-p2p/src/main.rs | 6 +- examples/node-custom-rpc/src/main.rs | 2 +- examples/precompile-cache/src/main.rs | 2 +- testing/ef-tests/src/cases/blockchain_test.rs | 16 +- testing/ef-tests/src/models.rs | 20 +- testing/testing-utils/src/generators.rs | 2 +- 392 files changed, 2489 insertions(+), 2504 deletions(-) diff --git a/bin/reth-bench/src/valid_payload.rs b/bin/reth-bench/src/valid_payload.rs index abcb32e747..e2f83a0ec2 100644 --- a/bin/reth-bench/src/valid_payload.rs +++ b/bin/reth-bench/src/valid_payload.rs @@ -133,7 +133,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )); + )) } status = self .new_payload_v3(payload.clone(), versioned_hashes.clone(), parent_beacon_block_root) @@ -178,7 +178,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )); + )) } status = self .client() @@ -217,7 +217,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )); + )) } status = self.fork_choice_updated_v1(fork_choice_state, payload_attributes.clone()).await?; @@ -247,7 +247,7 @@ where if status.is_syncing() { return Err(alloy_json_rpc::RpcError::UnsupportedFeature( "invalid range: no canonical state found for parent of requested block", - )); + )) } status = self.fork_choice_updated_v2(fork_choice_state, payload_attributes.clone()).await?; diff --git a/crates/alloy-provider/src/lib.rs b/crates/alloy-provider/src/lib.rs index 0978808c12..ba4767006a 100644 --- a/crates/alloy-provider/src/lib.rs +++ b/crates/alloy-provider/src/lib.rs @@ -828,9 +828,9 @@ impl AlloyRethStateProvider { .map_err(ProviderError::other)?; // Only return account if it exists (has balance, nonce, or code) - if account_info.balance.is_zero() - && account_info.nonce == 0 - && account_info.code.is_empty() + if account_info.balance.is_zero() && + account_info.nonce == 0 && + account_info.code.is_empty() { Ok(None) } else { @@ -1711,9 +1711,9 @@ where .map_err(ProviderError::other)?; // Only return account if it exists - if account_info.balance.is_zero() - && account_info.nonce == 0 - && account_info.code.is_empty() + if account_info.balance.is_zero() && + account_info.nonce == 0 && + account_info.code.is_empty() { Ok(None) } else { diff --git a/crates/chain-state/src/chain_info.rs b/crates/chain-state/src/chain_info.rs index 191e7765ba..a8a0843056 100644 --- a/crates/chain-state/src/chain_info.rs +++ b/crates/chain-state/src/chain_info.rs @@ -111,7 +111,7 @@ where self.inner.safe_block.send_if_modified(|current_header| { if current_header.as_ref().map(SealedHeader::hash) != Some(header.hash()) { let _ = current_header.replace(header); - return true; + return true } false @@ -123,7 +123,7 @@ where self.inner.finalized_block.send_if_modified(|current_header| { if current_header.as_ref().map(SealedHeader::hash) != Some(header.hash()) { let _ = current_header.replace(header); - return true; + return true } false diff --git a/crates/chain-state/src/in_memory.rs b/crates/chain-state/src/in_memory.rs index 4fdb7b1cde..20f2a2a4c2 100644 --- a/crates/chain-state/src/in_memory.rs +++ b/crates/chain-state/src/in_memory.rs @@ -316,7 +316,7 @@ impl CanonicalInMemoryState { { if self.inner.in_memory_state.blocks.read().get(&persisted_num_hash.hash).is_none() { // do nothing - return; + return } } @@ -540,7 +540,7 @@ impl CanonicalInMemoryState { if let Some(tx) = block_state.block_ref().recovered_block().body().transaction_by_hash(&hash) { - return Some(tx.clone()); + return Some(tx.clone()) } } None @@ -570,7 +570,7 @@ impl CanonicalInMemoryState { timestamp: block_state.block_ref().recovered_block().timestamp(), excess_blob_gas: block_state.block_ref().recovered_block().excess_blob_gas(), }; - return Some((tx.clone(), meta)); + return Some((tx.clone(), meta)) } } None diff --git a/crates/chain-state/src/notifications.rs b/crates/chain-state/src/notifications.rs index 134e201de4..abf2405c87 100644 --- a/crates/chain-state/src/notifications.rs +++ b/crates/chain-state/src/notifications.rs @@ -68,10 +68,10 @@ impl Stream for CanonStateNotificationStream { Some(Ok(notification)) => Poll::Ready(Some(notification)), Some(Err(err)) => { debug!(%err, "canonical state notification stream lagging behind"); - continue; + continue } None => Poll::Ready(None), - }; + } } } } diff --git a/crates/chain-state/src/test_utils.rs b/crates/chain-state/src/test_utils.rs index 334bd4fea1..499a47de59 100644 --- a/crates/chain-state/src/test_utils.rs +++ b/crates/chain-state/src/test_utils.rs @@ -163,8 +163,8 @@ impl TestBlockBuilder { .into_trie_account(EMPTY_ROOT_HASH), )])), // use the number as the timestamp so it is monotonically increasing - timestamp: number - + EthereumHardfork::Cancun.activation_timestamp(self.chain_spec.chain).unwrap(), + timestamp: number + + EthereumHardfork::Cancun.activation_timestamp(self.chain_spec.chain).unwrap(), withdrawals_root: Some(calculate_withdrawals_root(&[])), blob_gas_used: Some(0), excess_blob_gas: Some(0), diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index 62090d3230..7accf96fa3 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -384,7 +384,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.hardforks.is_fork_active_at_timestamp(fork.clone(), timestamp) { - return *params; + return *params } } @@ -403,7 +403,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.hardforks.is_fork_active_at_block(fork.clone(), block_number) { - return *params; + return *params } } @@ -477,8 +477,8 @@ impl ChainSpec { // We filter out TTD-based forks w/o a pre-known block since those do not show up in the // fork filter. Some(match condition { - ForkCondition::Block(block) - | ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), + ForkCondition::Block(block) | + ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), ForkCondition::Timestamp(time) => ForkFilterKey::Time(time), _ => return None, }) @@ -505,8 +505,8 @@ impl ChainSpec { for (_, cond) in self.hardforks.forks_iter() { // handle block based forks and the sepolia merge netsplit block edge case (TTD // ForkCondition with Some(block)) - if let ForkCondition::Block(block) - | ForkCondition::TTD { fork_block: Some(block), .. } = cond + if let ForkCondition::Block(block) | + ForkCondition::TTD { fork_block: Some(block), .. } = cond { if head.number >= block { // skip duplicated hardforks: hardforks enabled at genesis block @@ -517,7 +517,7 @@ impl ChainSpec { } else { // we can return here because this block fork is not active, so we set the // `next` value - return ForkId { hash: forkhash, next: block }; + return ForkId { hash: forkhash, next: block } } } } @@ -539,7 +539,7 @@ impl ChainSpec { // can safely return here because we have already handled all block forks and // have handled all active timestamp forks, and set the next value to the // timestamp that is known but not active yet - return ForkId { hash: forkhash, next: timestamp }; + return ForkId { hash: forkhash, next: timestamp } } } diff --git a/crates/cli/cli/src/chainspec.rs b/crates/cli/cli/src/chainspec.rs index 00a6363323..b70430a910 100644 --- a/crates/cli/cli/src/chainspec.rs +++ b/crates/cli/cli/src/chainspec.rs @@ -75,7 +75,7 @@ pub fn parse_genesis(s: &str) -> eyre::Result { if s.contains('{') { s.to_string() } else { - return Err(io_err.into()); // assume invalid path + return Err(io_err.into()) // assume invalid path } } }; diff --git a/crates/cli/commands/src/common.rs b/crates/cli/commands/src/common.rs index 9b56da6742..be3bcec5a1 100644 --- a/crates/cli/commands/src/common.rs +++ b/crates/cli/commands/src/common.rs @@ -143,7 +143,7 @@ impl EnvironmentArgs { { if factory.db_ref().is_read_only()? { warn!(target: "reth::cli", ?unwind_target, "Inconsistent storage. Restart node to heal."); - return Ok(factory); + return Ok(factory) } // Highly unlikely to happen, and given its destructive nature, it's better to panic diff --git a/crates/cli/commands/src/db/checksum.rs b/crates/cli/commands/src/db/checksum.rs index 73142314db..40f0d22f6d 100644 --- a/crates/cli/commands/src/db/checksum.rs +++ b/crates/cli/commands/src/db/checksum.rs @@ -125,7 +125,7 @@ impl TableViewer<(u64, Duration)> for ChecksumViewer<'_, N total = index + 1; if total >= limit { - break; + break } } diff --git a/crates/cli/commands/src/db/diff.rs b/crates/cli/commands/src/db/diff.rs index 95f1b324c6..b22930302f 100644 --- a/crates/cli/commands/src/db/diff.rs +++ b/crates/cli/commands/src/db/diff.rs @@ -309,12 +309,12 @@ where ) { // do not bother comparing if the key is already in the discrepancies map if self.discrepancies.contains_key(&key) { - return; + return } // do not bother comparing if the key is already in the extra elements map if self.extra_elements.contains_key(&key) { - return; + return } match (first, second) { diff --git a/crates/cli/commands/src/db/list.rs b/crates/cli/commands/src/db/list.rs index bf8b705412..9288a56a86 100644 --- a/crates/cli/commands/src/db/list.rs +++ b/crates/cli/commands/src/db/list.rs @@ -67,7 +67,7 @@ impl Command { .as_ref() .map(|search| { if let Some(search) = search.strip_prefix("0x") { - return hex::decode(search).unwrap(); + return hex::decode(search).unwrap() } search.as_bytes().to_vec() }) diff --git a/crates/cli/commands/src/db/mod.rs b/crates/cli/commands/src/db/mod.rs index ddc3886c40..67b060f7e9 100644 --- a/crates/cli/commands/src/db/mod.rs +++ b/crates/cli/commands/src/db/mod.rs @@ -123,7 +123,7 @@ impl> Command if !input.trim().eq_ignore_ascii_case("y") { println!("Database drop aborted!"); - return Ok(()); + return Ok(()) } } diff --git a/crates/cli/commands/src/db/stats.rs b/crates/cli/commands/src/db/stats.rs index df25c07624..c8398d795c 100644 --- a/crates/cli/commands/src/db/stats.rs +++ b/crates/cli/commands/src/db/stats.rs @@ -291,10 +291,10 @@ impl Command { .add_cell(Cell::new(human_bytes(segment_config_size as f64))); } row.add_cell(Cell::new(human_bytes( - (segment_data_size - + segment_index_size - + segment_offsets_size - + segment_config_size) as f64, + (segment_data_size + + segment_index_size + + segment_offsets_size + + segment_config_size) as f64, ))); table.add_row(row); } diff --git a/crates/cli/commands/src/db/tui.rs b/crates/cli/commands/src/db/tui.rs index 213ffa0c35..800c17b8ef 100644 --- a/crates/cli/commands/src/db/tui.rs +++ b/crates/cli/commands/src/db/tui.rs @@ -291,7 +291,7 @@ where } } - return Ok(false); + return Ok(false) } match event { diff --git a/crates/cli/commands/src/import.rs b/crates/cli/commands/src/import.rs index 193369e768..eef6711706 100644 --- a/crates/cli/commands/src/import.rs +++ b/crates/cli/commands/src/import.rs @@ -143,8 +143,8 @@ impl> ImportComm let total_imported_blocks = provider.tx_ref().entries::()?; let total_imported_txns = provider.tx_ref().entries::()?; - if total_decoded_blocks != total_imported_blocks - || total_decoded_txns != total_imported_txns + if total_decoded_blocks != total_imported_blocks || + total_decoded_txns != total_imported_txns { error!(target: "reth::cli", total_decoded_blocks, diff --git a/crates/cli/commands/src/import_era.rs b/crates/cli/commands/src/import_era.rs index ebb569cdba..7920fda313 100644 --- a/crates/cli/commands/src/import_era.rs +++ b/crates/cli/commands/src/import_era.rs @@ -77,8 +77,8 @@ impl> ImportEraC let next_block = provider_factory .static_file_provider() .get_highest_static_file_block(StaticFileSegment::Headers) - .unwrap_or_default() - + 1; + .unwrap_or_default() + + 1; if let Some(path) = self.import.path { let stream = read_dir(path, next_block)?; diff --git a/crates/cli/commands/src/init_state/without_evm.rs b/crates/cli/commands/src/init_state/without_evm.rs index 7dad0b64c3..c839aaf268 100644 --- a/crates/cli/commands/src/init_state/without_evm.rs +++ b/crates/cli/commands/src/init_state/without_evm.rs @@ -148,7 +148,7 @@ where while let Ok(append_result) = rx.recv() { if let Err(err) = append_result { tracing::error!(target: "reth::cli", "Error appending dummy chain: {err}"); - return Err(err); + return Err(err) } } diff --git a/crates/cli/commands/src/stage/dump/hashing_account.rs b/crates/cli/commands/src/stage/dump/hashing_account.rs index 8d2ac1a554..8b9ba5e937 100644 --- a/crates/cli/commands/src/stage/dump/hashing_account.rs +++ b/crates/cli/commands/src/stage/dump/hashing_account.rs @@ -93,7 +93,7 @@ fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/crates/cli/commands/src/stage/dump/hashing_storage.rs b/crates/cli/commands/src/stage/dump/hashing_storage.rs index 7f520f1103..265048354b 100644 --- a/crates/cli/commands/src/stage/dump/hashing_storage.rs +++ b/crates/cli/commands/src/stage/dump/hashing_storage.rs @@ -88,7 +88,7 @@ fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/crates/cli/commands/src/stage/dump/merkle.rs b/crates/cli/commands/src/stage/dump/merkle.rs index 357522541d..cc21c0fc29 100644 --- a/crates/cli/commands/src/stage/dump/merkle.rs +++ b/crates/cli/commands/src/stage/dump/merkle.rs @@ -172,7 +172,7 @@ where checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/crates/cli/commands/src/stage/run.rs b/crates/cli/commands/src/stage/run.rs index ae792528fe..bba9858f21 100644 --- a/crates/cli/commands/src/stage/run.rs +++ b/crates/cli/commands/src/stage/run.rs @@ -188,7 +188,7 @@ impl match fetch_client.get_header(BlockHashOrNumber::Number(self.to)).await { Ok(header) => { if let Some(header) = header.into_data() { - break header; + break header } } Err(error) if error.is_retryable() => { @@ -246,8 +246,8 @@ impl config.stages.bodies.downloader_max_buffered_blocks_size_bytes, ) .with_concurrent_requests_range( - config.stages.bodies.downloader_min_concurrent_requests - ..=config.stages.bodies.downloader_max_concurrent_requests, + config.stages.bodies.downloader_min_concurrent_requests..= + config.stages.bodies.downloader_max_concurrent_requests, ) .build(fetch_client, consensus.clone(), provider_factory.clone()), ); @@ -377,7 +377,7 @@ impl } if done { - break; + break } } info!(target: "reth::cli", stage = %self.stage, time = ?start.elapsed(), "Finished stage"); diff --git a/crates/cli/commands/src/test_vectors/compact.rs b/crates/cli/commands/src/test_vectors/compact.rs index d38911ef48..abd3635e4f 100644 --- a/crates/cli/commands/src/test_vectors/compact.rs +++ b/crates/cli/commands/src/test_vectors/compact.rs @@ -215,7 +215,7 @@ where tries += 1; bytes.extend(std::iter::repeat_n(0u8, 256)); } else { - return Err(err)?; + return Err(err)? } } } diff --git a/crates/cli/commands/src/test_vectors/tables.rs b/crates/cli/commands/src/test_vectors/tables.rs index e30286b965..1bbd2604f9 100644 --- a/crates/cli/commands/src/test_vectors/tables.rs +++ b/crates/cli/commands/src/test_vectors/tables.rs @@ -133,7 +133,7 @@ where let key: T::Key = start_keys.new_tree(runner).map_err(|e| eyre::eyre!("{e}"))?.current(); if !seen_keys.insert(key.clone()) { - continue; + continue } let mut values: Vec = diff --git a/crates/cli/util/src/parsers.rs b/crates/cli/util/src/parsers.rs index 2c7868b3ad..ddb120452e 100644 --- a/crates/cli/util/src/parsers.rs +++ b/crates/cli/util/src/parsers.rs @@ -68,15 +68,15 @@ pub enum SocketAddressParsingError { /// An error is returned if the value is empty. pub fn parse_socket_address(value: &str) -> eyre::Result { if value.is_empty() { - return Err(SocketAddressParsingError::Empty); + return Err(SocketAddressParsingError::Empty) } if let Some(port) = value.strip_prefix(':').or_else(|| value.strip_prefix("localhost:")) { let port: u16 = port.parse()?; - return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)); + return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)) } if let Ok(port) = value.parse() { - return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)); + return Ok(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)) } value .to_socket_addrs()? @@ -100,7 +100,7 @@ pub fn read_json_from_file(path: &str) -> Result pub fn parse_ether_value(value: &str) -> eyre::Result { let eth = value.parse::()?; if eth.is_sign_negative() { - return Err(eyre::eyre!("Ether value cannot be negative")); + return Err(eyre::eyre!("Ether value cannot be negative")) } let wei = eth * 1e18; Ok(wei as u128) diff --git a/crates/cli/util/src/sigsegv_handler.rs b/crates/cli/util/src/sigsegv_handler.rs index 606478649f..b0a195391f 100644 --- a/crates/cli/util/src/sigsegv_handler.rs +++ b/crates/cli/util/src/sigsegv_handler.rs @@ -49,7 +49,7 @@ extern "C" fn print_stack_trace(_: libc::c_int) { // Collect return addresses let depth = libc::backtrace(stack_trace.as_mut_ptr(), MAX_FRAMES as i32); if depth == 0 { - return; + return } &stack_trace[0..depth as usize] }; @@ -67,7 +67,7 @@ extern "C" fn print_stack_trace(_: libc::c_int) { let period = period.saturating_add(1); // avoid "what if wrapped?" branches let Some(offset) = stack.iter().skip(period).zip(stack).position(cycled) else { // impossible. - return; + return }; // Count matching trace slices, else we could miscount "biphasic cycles" diff --git a/crates/consensus/common/src/validation.rs b/crates/consensus/common/src/validation.rs index 0a1556e242..a682bc2f91 100644 --- a/crates/consensus/common/src/validation.rs +++ b/crates/consensus/common/src/validation.rs @@ -18,11 +18,11 @@ pub fn validate_header_gas(header: &H) -> Result<(), ConsensusEr return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { gas_used: header.gas_used(), gas_limit: header.gas_limit(), - }); + }) } // Check that the gas limit is below the maximum allowed gas limit if header.gas_limit() > MAXIMUM_GAS_LIMIT_BLOCK { - return Err(ConsensusError::HeaderGasLimitExceedsMax { gas_limit: header.gas_limit() }); + return Err(ConsensusError::HeaderGasLimitExceedsMax { gas_limit: header.gas_limit() }) } Ok(()) } @@ -35,7 +35,7 @@ pub fn validate_header_base_fee( ) -> Result<(), ConsensusError> { if chain_spec.is_london_active_at_block(header.number()) && header.base_fee_per_gas().is_none() { - return Err(ConsensusError::BaseFeeMissing); + return Err(ConsensusError::BaseFeeMissing) } Ok(()) } @@ -100,14 +100,14 @@ where expected: header.ommers_hash(), } .into(), - )); + )) } let tx_root = body.calculate_tx_root(); if header.transactions_root() != tx_root { return Err(ConsensusError::BodyTransactionRootDiff( GotExpected { got: tx_root, expected: header.transactions_root() }.into(), - )); + )) } match (header.withdrawals_root(), body.calculate_withdrawals_root()) { @@ -115,7 +115,7 @@ where if withdrawals_root != header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root }.into(), - )); + )) } } (None, None) => { @@ -150,12 +150,12 @@ where expected: block.ommers_hash(), } .into(), - )); + )) } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())); + return Err(ConsensusError::BodyTransactionRootDiff(error.into())) } // EIP-4895: Beacon chain push withdrawals as operations @@ -187,21 +187,21 @@ pub fn validate_4844_header_standalone( let blob_gas_used = header.blob_gas_used().ok_or(ConsensusError::BlobGasUsedMissing)?; if header.parent_beacon_block_root().is_none() { - return Err(ConsensusError::ParentBeaconBlockRootMissing); + return Err(ConsensusError::ParentBeaconBlockRootMissing) } if blob_gas_used % DATA_GAS_PER_BLOB != 0 { return Err(ConsensusError::BlobGasUsedNotMultipleOfBlobGasPerBlob { blob_gas_used, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }); + }) } if blob_gas_used > blob_params.max_blob_gas_per_block() { return Err(ConsensusError::BlobGasUsedExceedsMaxBlobGasPerBlock { blob_gas_used, max_blob_gas_per_block: blob_params.max_blob_gas_per_block(), - }); + }) } Ok(()) @@ -235,13 +235,13 @@ pub fn validate_against_parent_hash_number( return Err(ConsensusError::ParentBlockNumberMismatch { parent_block_number: parent.number(), block_number: header.number(), - }); + }) } if parent.hash() != header.parent_hash() { return Err(ConsensusError::ParentHashMismatch( GotExpected { got: header.parent_hash(), expected: parent.hash() }.into(), - )); + )) } Ok(()) @@ -271,7 +271,7 @@ pub fn validate_against_parent_eip1559_base_fee( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp(), timestamp: header.timestamp(), - }); + }) } Ok(()) } @@ -312,7 +312,7 @@ pub fn validate_against_parent_4844( let parent_excess_blob_gas = parent.excess_blob_gas().unwrap_or(0); if header.blob_gas_used().is_none() { - return Err(ConsensusError::BlobGasUsedMissing); + return Err(ConsensusError::BlobGasUsedMissing) } let excess_blob_gas = header.excess_blob_gas().ok_or(ConsensusError::ExcessBlobGasMissing)?; @@ -323,7 +323,7 @@ pub fn validate_against_parent_4844( diff: GotExpected { got: excess_blob_gas, expected: expected_excess_blob_gas }, parent_excess_blob_gas, parent_blob_gas_used, - }); + }) } Ok(()) diff --git a/crates/consensus/consensus/src/lib.rs b/crates/consensus/consensus/src/lib.rs index d0a71aca2a..951c2c0ef5 100644 --- a/crates/consensus/consensus/src/lib.rs +++ b/crates/consensus/consensus/src/lib.rs @@ -133,7 +133,7 @@ pub fn validate_state_root(header: &H, root: B256) -> Result<(), if header.state_root() != root { return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: root, expected: header.state_root() }.into(), - )); + )) } Ok(()) diff --git a/crates/consensus/debug-client/src/providers/etherscan.rs b/crates/consensus/debug-client/src/providers/etherscan.rs index 4c09250806..c52ee609d2 100644 --- a/crates/consensus/debug-client/src/providers/etherscan.rs +++ b/crates/consensus/debug-client/src/providers/etherscan.rs @@ -99,7 +99,7 @@ where %err, "Failed to fetch a block from Etherscan", ); - continue; + continue } }; let block_number = block.header().number(); diff --git a/crates/e2e-test-utils/src/network.rs b/crates/e2e-test-utils/src/network.rs index 126736c9f5..dd703b312e 100644 --- a/crates/e2e-test-utils/src/network.rs +++ b/crates/e2e-test-utils/src/network.rs @@ -43,11 +43,11 @@ where pub async fn next_session_established(&mut self) -> Option { while let Some(ev) = self.network_events.next().await { match ev { - NetworkEvent::ActivePeerSession { info, .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { let peer_id = info.peer_id; info!("Session established with peer: {:?}", peer_id); - return Some(peer_id); + return Some(peer_id) } _ => {} } diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 688390abb7..0261978a66 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -168,7 +168,7 @@ where if check { if let Some(latest_block) = self.inner.provider.block_by_number(number)? { assert_eq!(latest_block.header().hash_slow(), expected_block_hash); - break; + break } assert!( !wait_finish_checkpoint, @@ -185,7 +185,7 @@ where tokio::time::sleep(std::time::Duration::from_millis(10)).await; if let Some(checkpoint) = self.inner.provider.get_stage_checkpoint(StageId::Headers)? { if checkpoint.block_number == number { - break; + break } } } @@ -218,7 +218,7 @@ where // make sure the block hash we submitted via FCU engine api is the new latest // block using an RPC call assert_eq!(latest_block.header().hash_slow(), block_hash); - break; + break } } } diff --git a/crates/e2e-test-utils/src/payload.rs b/crates/e2e-test-utils/src/payload.rs index 545850f899..b3f9b027fb 100644 --- a/crates/e2e-test-utils/src/payload.rs +++ b/crates/e2e-test-utils/src/payload.rs @@ -60,7 +60,7 @@ impl PayloadTestContext { let payload = self.payload_builder.best_payload(payload_id).await.unwrap().unwrap(); if payload.block().body().transactions().is_empty() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; - continue; + continue } // Resolve payload once its built self.payload_builder diff --git a/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs b/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs index 4215c1d855..c20b79d9ae 100644 --- a/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs +++ b/crates/e2e-test-utils/src/testsuite/actions/produce_blocks.rs @@ -256,8 +256,8 @@ where debug!("No payload ID returned, generating fresh payload attributes for forking"); let fresh_payload_attributes = PayloadAttributes { - timestamp: env.active_node_state()?.latest_header_time - + env.block_timestamp_increment, + timestamp: env.active_node_state()?.latest_header_time + + env.block_timestamp_increment, prev_randao: B256::random(), suggested_fee_recipient: alloy_primitives::Address::random(), withdrawals: Some(vec![]), diff --git a/crates/engine/local/src/miner.rs b/crates/engine/local/src/miner.rs index 30a9745785..a3318f1f5c 100644 --- a/crates/engine/local/src/miner.rs +++ b/crates/engine/local/src/miner.rs @@ -55,13 +55,13 @@ impl Future for MiningMode { Self::Instant(rx) => { // drain all transactions notifications if let Poll::Ready(Some(_)) = rx.poll_next_unpin(cx) { - return Poll::Ready(()); + return Poll::Ready(()) } Poll::Pending } Self::Interval(interval) => { if interval.poll_tick(cx).is_ready() { - return Poll::Ready(()); + return Poll::Ready(()) } Poll::Pending } diff --git a/crates/engine/tree/src/backfill.rs b/crates/engine/tree/src/backfill.rs index 4038bf02d1..9dad8c32a5 100644 --- a/crates/engine/tree/src/backfill.rs +++ b/crates/engine/tree/src/backfill.rs @@ -124,7 +124,7 @@ impl PipelineSync { "Pipeline target cannot be zero hash." ); // precaution to never sync to the zero hash - return; + return } self.pending_pipeline_target = Some(target); } @@ -187,14 +187,14 @@ impl BackfillSync for PipelineSync { fn poll(&mut self, cx: &mut Context<'_>) -> Poll { // try to spawn a pipeline if a target is set if let Some(event) = self.try_spawn_pipeline() { - return Poll::Ready(event); + return Poll::Ready(event) } // make sure we poll the pipeline if it's active, and return any ready pipeline events if self.is_pipeline_active() { // advance the pipeline if let Poll::Ready(event) = self.poll_pipeline(cx) { - return Poll::Ready(event); + return Poll::Ready(event) } } diff --git a/crates/engine/tree/src/chain.rs b/crates/engine/tree/src/chain.rs index 2850097074..e2893bb976 100644 --- a/crates/engine/tree/src/chain.rs +++ b/crates/engine/tree/src/chain.rs @@ -100,7 +100,7 @@ where tracing::error!( %err, "backfill sync failed"); Poll::Ready(ChainEvent::FatalError) } - }; + } } BackfillEvent::TaskDropped(err) => { tracing::error!( %err, "backfill sync task dropped"); @@ -124,13 +124,13 @@ where } HandlerEvent::FatalError => { error!(target: "engine::tree", "Fatal error"); - return Poll::Ready(ChainEvent::FatalError); + return Poll::Ready(ChainEvent::FatalError) } } } Poll::Pending => { // no more events to process - break 'outer; + break 'outer } } } diff --git a/crates/engine/tree/src/download.rs b/crates/engine/tree/src/download.rs index afea7790be..5d7d52af84 100644 --- a/crates/engine/tree/src/download.rs +++ b/crates/engine/tree/src/download.rs @@ -144,7 +144,7 @@ where /// given hash. fn download_full_block(&mut self, hash: B256) -> bool { if self.is_inflight_request(hash) { - return false; + return false } self.push_pending_event(DownloadOutcome::NewDownloadStarted { remaining_blocks: 1, @@ -172,8 +172,8 @@ where /// Sets the metrics for the active downloads fn update_block_download_metrics(&self) { - let blocks = self.inflight_full_block_requests.len() - + self.inflight_block_range_requests.iter().map(|r| r.count() as usize).sum::(); + 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); } @@ -256,7 +256,7 @@ where if peek.0 .0.hash() == block.0 .0.hash() { PeekMut::pop(peek); } else { - break; + break } } downloaded_blocks.push(block.0.into()); diff --git a/crates/engine/tree/src/engine.rs b/crates/engine/tree/src/engine.rs index 572f515ebb..16ba103439 100644 --- a/crates/engine/tree/src/engine.rs +++ b/crates/engine/tree/src/engine.rs @@ -96,7 +96,7 @@ where Poll::Ready(HandlerEvent::Event(ev)) } HandlerEvent::FatalError => Poll::Ready(HandlerEvent::FatalError), - }; + } } RequestHandlerEvent::Download(req) => { // delegate download request to the downloader @@ -110,7 +110,7 @@ where // and delegate the request to the handler self.handler.on_event(FromEngine::Request(req.into())); // skip downloading in this iteration to allow the handler to process the request - continue; + continue } // advance the downloader @@ -119,10 +119,10 @@ where // delegate the downloaded blocks to the handler self.handler.on_event(FromEngine::DownloadedBlocks(blocks)); } - continue; + continue } - return Poll::Pending; + return Poll::Pending } } } @@ -202,7 +202,7 @@ where fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { let Some(ev) = ready!(self.from_tree.poll_recv(cx)) else { - return Poll::Ready(RequestHandlerEvent::HandlerEvent(HandlerEvent::FatalError)); + return Poll::Ready(RequestHandlerEvent::HandlerEvent(HandlerEvent::FatalError)) }; let ev = match ev { diff --git a/crates/engine/tree/src/tree/block_buffer.rs b/crates/engine/tree/src/tree/block_buffer.rs index 3e842c7084..6da92818e2 100644 --- a/crates/engine/tree/src/tree/block_buffer.rs +++ b/crates/engine/tree/src/tree/block_buffer.rs @@ -109,7 +109,7 @@ impl BlockBuffer { // discard all blocks that are before the finalized number. while let Some(entry) = self.earliest_blocks.first_entry() { if *entry.key() > block_number { - break; + break } let block_hashes = entry.remove(); block_hashes_to_remove.extend(block_hashes); diff --git a/crates/engine/tree/src/tree/cached_state.rs b/crates/engine/tree/src/tree/cached_state.rs index bfdb849cea..bce9949564 100644 --- a/crates/engine/tree/src/tree/cached_state.rs +++ b/crates/engine/tree/src/tree/cached_state.rs @@ -117,7 +117,7 @@ impl AccountReader for CachedStateProvider { fn basic_account(&self, address: &Address) -> ProviderResult> { if let Some(res) = self.caches.account_cache.get(address) { self.metrics.account_cache_hits.increment(1); - return Ok(res); + return Ok(res) } self.metrics.account_cache_misses.increment(1); @@ -168,7 +168,7 @@ impl BytecodeReader for CachedStateProvider { fn bytecode_by_hash(&self, code_hash: &B256) -> ProviderResult> { if let Some(res) = self.caches.code_cache.get(code_hash) { self.metrics.code_cache_hits.increment(1); - return Ok(res); + return Ok(res) } self.metrics.code_cache_misses.increment(1); @@ -352,7 +352,7 @@ impl ProviderCaches { // If the account was not modified, as in not changed and not destroyed, then we have // nothing to do w.r.t. this particular account and can move on if account.status.is_not_modified() { - continue; + continue } // If the account was destroyed, invalidate from the account / storage caches @@ -361,7 +361,7 @@ impl ProviderCaches { self.account_cache.invalidate(addr); self.invalidate_account_storage(addr); - continue; + continue } // If we have an account that was modified, but it has a `None` account info, some wild @@ -369,7 +369,7 @@ impl ProviderCaches { // `None` current info, should be destroyed. let Some(ref account_info) = account.info else { trace!(target: "engine::caching", ?account, "Account with None account info found in state updates"); - return Err(()); + return Err(()) }; // Now we iterate over all storage and make updates to the cached storage values diff --git a/crates/engine/tree/src/tree/invalid_headers.rs b/crates/engine/tree/src/tree/invalid_headers.rs index 2fec318fb7..d349901a19 100644 --- a/crates/engine/tree/src/tree/invalid_headers.rs +++ b/crates/engine/tree/src/tree/invalid_headers.rs @@ -42,7 +42,7 @@ impl InvalidHeaderCache { let entry = self.headers.get(hash)?; entry.hit_count += 1; if entry.hit_count < INVALID_HEADER_HIT_EVICTION_THRESHOLD { - return Some(entry.header); + return Some(entry.header) } } // if we get here, the entry has been hit too many times, so we evict it diff --git a/crates/engine/tree/src/tree/mod.rs b/crates/engine/tree/src/tree/mod.rs index 1e79c467d6..a88c109787 100644 --- a/crates/engine/tree/src/tree/mod.rs +++ b/crates/engine/tree/src/tree/mod.rs @@ -452,7 +452,7 @@ where debug!(target: "engine::tree", %msg, "received new engine message"); if let Err(fatal) = self.on_engine_message(msg) { error!(target: "engine::tree", %fatal, "insert block fatal error"); - return; + return } } Ok(None) => { @@ -460,13 +460,13 @@ where } Err(_err) => { error!(target: "engine::tree", "Engine channel disconnected"); - return; + return } } if let Err(err) = self.advance_persistence() { error!(target: "engine::tree", %err, "Advancing persistence failed"); - return; + return } } } @@ -482,7 +482,7 @@ where ) -> Result, InsertBlockFatalError> { if blocks.is_empty() { // nothing to execute - return Ok(None); + return Ok(None) } trace!(target: "engine::tree", block_count = %blocks.len(), "received downloaded blocks"); @@ -493,7 +493,7 @@ where self.on_tree_event(event)?; if needs_backfill { // can exit early if backfill is needed - return Ok(None); + return Ok(None) } } } @@ -571,7 +571,7 @@ where }; let status = PayloadStatusEnum::from(error); - return Ok(TreeOutcome::new(PayloadStatus::new(status, latest_valid_hash))); + return Ok(TreeOutcome::new(PayloadStatus::new(status, latest_valid_hash))) } }; @@ -589,7 +589,7 @@ where if let Some(status) = self.check_invalid_ancestor_with_head(lowest_buffered_ancestor, &block)? { - return Ok(TreeOutcome::new(status)); + return Ok(TreeOutcome::new(status)) } let status = if self.backfill_sync_state.is_idle() { @@ -607,8 +607,8 @@ where latest_valid_hash = Some(block_hash); PayloadStatusEnum::Valid } - InsertPayloadOk::Inserted(BlockStatus::Disconnected { .. }) - | InsertPayloadOk::AlreadySeen(BlockStatus::Disconnected { .. }) => { + InsertPayloadOk::Inserted(BlockStatus::Disconnected { .. }) | + InsertPayloadOk::AlreadySeen(BlockStatus::Disconnected { .. }) => { // not known to be invalid, but we don't know anything else PayloadStatusEnum::Syncing } @@ -648,7 +648,7 @@ where // get the executed new head block let Some(new_head_block) = self.state.tree_state.blocks_by_hash.get(&new_head) else { debug!(target: "engine::tree", new_head=?new_head, "New head block not found in inmemory tree state"); - return Ok(None); + return Ok(None) }; let new_head_number = new_head_block.recovered_block().number(); @@ -751,11 +751,11 @@ where let mut current_block = Cow::Borrowed(target_header); loop { if current_block.hash() == canonical_head.hash { - return Ok(false); + return Ok(false) } // We already passed the canonical head if current_block.number() <= canonical_head.number { - break; + break } current_hash = current_block.parent_hash(); @@ -765,12 +765,12 @@ where // verify that the given hash is not already part of canonical chain stored in memory if self.canonical_in_memory_state.header_by_hash(target_hash).is_some() { - return Ok(false); + return Ok(false) } // verify that the given hash is not already part of persisted canonical chain if self.provider.block_number(target_hash)?.is_some() { - return Ok(false); + return Ok(false) } Ok(true) @@ -800,17 +800,17 @@ where fn persisting_kind_for(&self, block: &N::BlockHeader) -> PersistingKind { // Check that we're currently persisting. let Some(action) = self.persistence_state.current_action() else { - return PersistingKind::NotPersisting; + return PersistingKind::NotPersisting }; // Check that the persistince action is saving blocks, not removing them. let CurrentPersistenceAction::SavingBlocks { highest } = action else { - return PersistingKind::PersistingNotDescendant; + return PersistingKind::PersistingNotDescendant }; // The block being validated can only be a descendant if its number is higher than // the highest block persisting. Otherwise, it's likely a fork of a lower block. if block.number() > highest.number && self.state.tree_state.is_descendant(*highest, block) { - return PersistingKind::PersistingDescendant; + return PersistingKind::PersistingDescendant } // In all other cases, the block is not a descendant. @@ -837,7 +837,7 @@ where self.canonical_in_memory_state.on_forkchoice_update_received(); if let Some(on_updated) = self.pre_validate_forkchoice_update(state)? { - return Ok(TreeOutcome::new(on_updated)); + return Ok(TreeOutcome::new(on_updated)) } let valid_outcome = |head| { @@ -868,7 +868,7 @@ where // update the safe and finalized blocks and ensure their values are valid if let Err(outcome) = self.ensure_consistent_forkchoice_state(state) { // safe or finalized hashes are invalid - return Ok(TreeOutcome::new(outcome)); + return Ok(TreeOutcome::new(outcome)) } // we still need to process payload attributes if the head is already canonical @@ -881,11 +881,11 @@ where ProviderError::HeaderNotFound(state.head_block_hash.into()) })?; let updated = self.process_payload_attributes(attr, tip.header(), state, version); - return Ok(TreeOutcome::new(updated)); + return Ok(TreeOutcome::new(updated)) } // the head block is already canonical - return Ok(valid_outcome(state.head_block_hash)); + return Ok(valid_outcome(state.head_block_hash)) } // 2. check if the head is already part of the canonical chain @@ -895,14 +895,14 @@ where // For OpStack the proposers are allowed to reorg their own chain at will, so we need to // always trigger a new payload job if requested. // Also allow forcing this behavior via a config flag. - if self.engine_kind.is_opstack() - || self.config.always_process_payload_attributes_on_canonical_head() + if self.engine_kind.is_opstack() || + self.config.always_process_payload_attributes_on_canonical_head() { if let Some(attr) = attrs { debug!(target: "engine::tree", head = canonical_header.number(), "handling payload attributes for canonical head"); let updated = self.process_payload_attributes(attr, &canonical_header, state, version); - return Ok(TreeOutcome::new(updated)); + return Ok(TreeOutcome::new(updated)) } } @@ -915,7 +915,7 @@ where // the head block is already canonical, so we're not triggering a payload job and can // return right away - return Ok(valid_outcome(state.head_block_hash)); + return Ok(valid_outcome(state.head_block_hash)) } // 3. ensure we can apply a new chain update for the head block @@ -926,15 +926,15 @@ where // update the safe and finalized blocks and ensure their values are valid if let Err(outcome) = self.ensure_consistent_forkchoice_state(state) { // safe or finalized hashes are invalid - return Ok(TreeOutcome::new(outcome)); + return Ok(TreeOutcome::new(outcome)) } if let Some(attr) = attrs { let updated = self.process_payload_attributes(attr, &tip, state, version); - return Ok(TreeOutcome::new(updated)); + return Ok(TreeOutcome::new(updated)) } - return Ok(valid_outcome(state.head_block_hash)); + return Ok(valid_outcome(state.head_block_hash)) } // 4. we don't have the block to perform the update @@ -1006,7 +1006,7 @@ where fn persist_blocks(&mut self, blocks_to_persist: Vec>) { if blocks_to_persist.is_empty() { debug!(target: "engine::tree", "Returned empty set of blocks to persist"); - return; + return } // NOTE: checked non-empty above @@ -1046,7 +1046,7 @@ where // if this happened, then we persisted no blocks because we sent an // empty vec of blocks warn!(target: "engine::tree", "Persistence task completed but did not persist any blocks"); - return Ok(()); + return Ok(()) }; debug!(target: "engine::tree", ?last_persisted_block_hash, ?last_persisted_block_number, "Finished persisting, calling finish"); @@ -1094,7 +1094,7 @@ where let block_num_hash = block.recovered_block().num_hash(); if block_num_hash.number <= self.state.tree_state.canonical_block_number() { // outdated block that can be skipped - return Ok(()); + return Ok(()) } debug!(target: "engine::tree", block=?block_num_hash, "inserting already executed block"); @@ -1102,8 +1102,8 @@ where // if the parent is the canonical head, we can insert the block as the // pending block - if self.state.tree_state.canonical_block_hash() - == block.recovered_block().parent_hash() + if self.state.tree_state.canonical_block_hash() == + block.recovered_block().parent_hash() { debug!(target: "engine::tree", pending=?block_num_hash, "updating pending block"); self.canonical_in_memory_state.set_pending_block(block.clone()); @@ -1234,7 +1234,7 @@ where .map(|hash| BlockNumHash { hash, number: backfill_height }) else { debug!(target: "engine::tree", ?ctrl, "Backfill block not found"); - return Ok(()); + return Ok(()) }; if ctrl.is_unwind() { @@ -1272,11 +1272,11 @@ where // the backfill height let Some(sync_target_state) = self.state.forkchoice_state_tracker.sync_target_state() else { - return Ok(()); + return Ok(()) }; if sync_target_state.finalized_block_hash.is_zero() { // no finalized block, can't check distance - return Ok(()); + return Ok(()) } // get the block number of the finalized block, if we have it let newest_finalized = self @@ -1301,7 +1301,7 @@ where self.emit_event(EngineApiEvent::BackfillAction(BackfillAction::Start( backfill_target.into(), ))); - return Ok(()); + return Ok(()) }; // try to close the gap by executing buffered blocks that are child blocks of the new head @@ -1364,7 +1364,7 @@ where // backfill sync and persisting data are mutually exclusive, so we can't start // backfill while we're still persisting debug!(target: "engine::tree", "skipping backfill file while persistence task is active"); - return; + return } self.backfill_sync_state = BackfillSyncState::Pending; @@ -1383,12 +1383,12 @@ where pub const fn should_persist(&self) -> bool { if !self.backfill_sync_state.is_idle() { // can't persist if backfill is running - return false; + return false } let min_block = self.persistence_state.last_persisted_block.number; - self.state.tree_state.canonical_block_number().saturating_sub(min_block) - > self.config.persistence_threshold() + self.state.tree_state.canonical_block_number().saturating_sub(min_block) > + self.config.persistence_threshold() } /// Returns a batch of consecutive canonical blocks to persist in the range @@ -1434,7 +1434,7 @@ where // Calculate missing trie updates for block in &mut blocks_to_persist { if block.trie.is_present() { - continue; + continue } debug!( @@ -1487,7 +1487,7 @@ where // state. if let Some(remove_above) = self.find_disk_reorg()? { self.remove_blocks(remove_above); - return Ok(()); + return Ok(()) } let finalized = self.state.forkchoice_state_tracker.last_valid_finalized(); @@ -1510,7 +1510,7 @@ where trace!(target: "engine::tree", ?hash, "Fetching executed block by hash"); // check memory first if let Some(block) = self.state.tree_state.executed_block_by_hash(hash) { - return Ok(Some(block.block.clone())); + return Ok(Some(block.block.clone())) } let (block, senders) = self @@ -1597,7 +1597,7 @@ where ) -> ProviderResult> { // Check if parent exists in side chain or in canonical chain. if self.block_by_hash(parent_hash)?.is_some() { - return Ok(Some(parent_hash)); + return Ok(Some(parent_hash)) } // iterate over ancestors in the invalid cache @@ -1611,7 +1611,7 @@ where // If current_header is None, then the current_hash does not have an invalid // ancestor in the cache, check its presence in blockchain tree if current_block.is_none() && self.block_by_hash(current_hash)?.is_some() { - return Ok(Some(current_hash)); + return Ok(Some(current_hash)) } } Ok(None) @@ -1641,7 +1641,7 @@ where /// See [`ForkchoiceStateTracker::sync_target_state`] fn is_sync_target_head(&self, block_hash: B256) -> bool { if let Some(target) = self.state.forkchoice_state_tracker.sync_target_state() { - return target.head_block_hash == block_hash; + return target.head_block_hash == block_hash } false } @@ -1683,12 +1683,12 @@ where fn validate_block(&self, block: &RecoveredBlock) -> Result<(), ConsensusError> { if let Err(e) = self.consensus.validate_header(block.sealed_header()) { error!(target: "engine::tree", ?block, "Failed to validate header {}: {e}", block.hash()); - return Err(e); + return Err(e) } if let Err(e) = self.consensus.validate_block_pre_execution(block.sealed_block()) { error!(target: "engine::tree", ?block, "Failed to validate block {}: {e}", block.hash()); - return Err(e); + return Err(e) } Ok(()) @@ -1704,7 +1704,7 @@ where if blocks.is_empty() { // nothing to append - return Ok(()); + return Ok(()) } let now = Instant::now(); @@ -1714,8 +1714,8 @@ where match self.insert_block(child) { Ok(res) => { debug!(target: "engine::tree", child =?child_num_hash, ?res, "connected buffered block"); - if self.is_sync_target_head(child_num_hash.hash) - && matches!(res, InsertPayloadOk::Inserted(BlockStatus::Valid)) + if self.is_sync_target_head(child_num_hash.hash) && + matches!(res, InsertPayloadOk::Inserted(BlockStatus::Valid)) { self.make_canonical(child_num_hash.hash)?; } @@ -1724,7 +1724,7 @@ where debug!(target: "engine::tree", ?err, "failed to connect buffered block to tree"); if let Err(fatal) = self.on_insert_block_error(err) { warn!(target: "engine::tree", %fatal, "fatal error occurred while connecting buffered blocks"); - return Err(fatal); + return Err(fatal) } } } @@ -1740,7 +1740,7 @@ where block: RecoveredBlock, ) -> Result<(), InsertBlockError> { if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.into_sealed_block())); + return Err(InsertBlockError::consensus_error(err, block.into_sealed_block())) } self.state.buffer.insert_block(block); Ok(()) @@ -1816,7 +1816,7 @@ where if !state.finalized_block_hash.is_zero() { // we don't have the block yet and the distance exceeds the allowed // threshold - return Some(state.finalized_block_hash); + return Some(state.finalized_block_hash) } // OPTIMISTIC SYNCING @@ -1832,7 +1832,7 @@ where // However, optimism chains will do this. The risk of a reorg is however // low. debug!(target: "engine::tree", hash=?state.head_block_hash, "Setting head hash as an optimistic backfill target."); - return Some(state.head_block_hash); + return Some(state.head_block_hash) } Ok(Some(_)) => { // we're fully synced to the finalized block @@ -2043,11 +2043,11 @@ where .check_invalid_ancestor_with_head(lowest_buffered_ancestor, block.sealed_block())? .is_some() { - return Ok(None); + return Ok(None) } if !self.backfill_sync_state.is_idle() { - return Ok(None); + return Ok(None) } // try to append the block @@ -2060,7 +2060,7 @@ where // canonical return Ok(Some(TreeEvent::TreeAction(TreeAction::MakeCanonical { sync_target_head: block_num_hash.hash, - }))); + }))) } trace!(target: "engine::tree", "appended downloaded block"); self.try_connect_buffered_blocks(block_num_hash)?; @@ -2072,7 +2072,7 @@ where block_num_hash, missing_ancestor, head, - )); + )) } Ok(InsertPayloadOk::AlreadySeen(_)) => { trace!(target: "engine::tree", "downloaded block already executed"); @@ -2081,7 +2081,7 @@ where debug!(target: "engine::tree", err=%err.kind(), "failed to insert downloaded block"); if let Err(fatal) = self.on_insert_block_error(err) { warn!(target: "engine::tree", %fatal, "fatal error occurred while inserting downloaded block"); - return Err(fatal); + return Err(fatal) } } } @@ -2116,7 +2116,7 @@ where debug!(target: "engine::tree", block=?block_num_hash, parent = ?block.parent_hash(), state_root = ?block.state_root(), "Inserting new block into tree"); if ensure_ok!(self.block_by_hash(block.hash())).is_some() { - return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid)); + return Ok(InsertPayloadOk::AlreadySeen(BlockStatus::Valid)) } let start = Instant::now(); @@ -2143,7 +2143,7 @@ where return Ok(InsertPayloadOk::Inserted(BlockStatus::Disconnected { head: self.state.tree_state.current_canonical_head, missing_ancestor, - })); + })) }; // now validate against the parent @@ -2153,14 +2153,14 @@ where block.parent_hash().into(), )), block, - )); + )) }; if let Err(e) = self.consensus.validate_header_against_parent(block.sealed_header(), &parent_block) { warn!(target: "engine::tree", ?block, "Failed to validate header {} against parent: {e}", block.hash()); - return Err((e.into(), block)); + return Err((e.into(), block)) } let state_provider = ensure_ok!(provider_builder.build()); @@ -2188,9 +2188,9 @@ where // accounting for the prefix sets. let has_ancestors_with_missing_trie_updates = self.has_ancestors_with_missing_trie_updates(block.sealed_header()); - let mut use_state_root_task = run_parallel_state_root - && self.config.use_state_root_task() - && !has_ancestors_with_missing_trie_updates; + let mut use_state_root_task = run_parallel_state_root && + self.config.use_state_root_task() && + !has_ancestors_with_missing_trie_updates; debug!( target: "engine::tree", @@ -2274,7 +2274,7 @@ where if let Err(err) = self.consensus.validate_block_post_execution(&block, &output) { // call post-block hook self.on_invalid_block(&parent_block, &block, &output, None); - return Err((err.into(), block)); + return Err((err.into(), block)) } let hashed_state = self.provider.hashed_post_state(&output.state); @@ -2285,7 +2285,7 @@ where { // call post-block hook self.on_invalid_block(&parent_block, &block, &output, None); - return Err((err.into(), block)); + return Err((err.into(), block)) } debug!(target: "engine::tree", block=?block_num_hash, "Calculating block state root"); @@ -2341,9 +2341,7 @@ where Err(ParallelStateRootError::Provider(ProviderError::ConsistentView(error))) => { debug!(target: "engine::tree", %error, "Parallel state root computation failed consistency check, falling back"); } - Err(error) => { - return Err((InsertBlockErrorKind::Other(Box::new(error)), block)) - } + Err(error) => return Err((InsertBlockErrorKind::Other(Box::new(error)), block)), } } } @@ -2379,7 +2377,7 @@ where ) .into(), block, - )); + )) } // terminate prewarming task with good state output @@ -2537,7 +2535,7 @@ where } else { // If the block is higher than the best block number, stop filtering, as it's // the first block that's not in the database. - break; + break } } @@ -2651,18 +2649,18 @@ where finalized_block_hash: B256, ) -> Result<(), OnForkChoiceUpdated> { if finalized_block_hash.is_zero() { - return Ok(()); + return Ok(()) } match self.find_canonical_header(finalized_block_hash) { Ok(None) => { debug!(target: "engine::tree", "Finalized block not found in canonical chain"); // if the finalized block is not known, we can't update the finalized block - return Err(OnForkChoiceUpdated::invalid_state()); + return Err(OnForkChoiceUpdated::invalid_state()) } Ok(Some(finalized)) => { - if Some(finalized.num_hash()) - != self.canonical_in_memory_state.get_finalized_num_hash() + if Some(finalized.num_hash()) != + self.canonical_in_memory_state.get_finalized_num_hash() { // we're also persisting the finalized block on disk so we can reload it on // restart this is required by optimism which queries the finalized block: @@ -2681,14 +2679,14 @@ where /// Updates the tracked safe block if we have it fn update_safe_block(&self, safe_block_hash: B256) -> Result<(), OnForkChoiceUpdated> { if safe_block_hash.is_zero() { - return Ok(()); + return Ok(()) } match self.find_canonical_header(safe_block_hash) { Ok(None) => { debug!(target: "engine::tree", "Safe block not found in canonical chain"); // if the safe block is not known, we can't update the safe block - return Err(OnForkChoiceUpdated::invalid_state()); + return Err(OnForkChoiceUpdated::invalid_state()) } Ok(Some(safe)) => { if Some(safe.num_hash()) != self.canonical_in_memory_state.get_safe_num_hash() { @@ -2742,21 +2740,21 @@ where state: ForkchoiceState, ) -> ProviderResult> { if state.head_block_hash.is_zero() { - return Ok(Some(OnForkChoiceUpdated::invalid_state())); + return Ok(Some(OnForkChoiceUpdated::invalid_state())) } // check if the new head hash is connected to any ancestor that we previously marked as // invalid let lowest_buffered_ancestor_fcu = self.lowest_buffered_ancestor_or(state.head_block_hash); if let Some(status) = self.check_invalid_ancestor(lowest_buffered_ancestor_fcu)? { - return Ok(Some(OnForkChoiceUpdated::with_invalid(status))); + return Ok(Some(OnForkChoiceUpdated::with_invalid(status))) } if !self.backfill_sync_state.is_idle() { // We can only process new forkchoice updates if the pipeline is idle, since it requires // exclusive access to the database trace!(target: "engine::tree", "Pipeline is syncing, skipping forkchoice update"); - return Ok(Some(OnForkChoiceUpdated::syncing())); + return Ok(Some(OnForkChoiceUpdated::syncing())) } Ok(None) @@ -2777,7 +2775,7 @@ where self.payload_validator.validate_payload_attributes_against_header(&attrs, head) { warn!(target: "engine::tree", %err, ?head, "Invalid payload attributes"); - return OnForkChoiceUpdated::invalid_payload_attributes(); + return OnForkChoiceUpdated::invalid_payload_attributes() } // 8. Client software MUST begin a payload build process building on top of @@ -2859,7 +2857,7 @@ where self.provider.clone(), historical, Some(blocks), - ))); + ))) } // Check if the block is persisted @@ -2867,7 +2865,7 @@ where debug!(target: "engine::tree", %hash, number = %header.number(), "found canonical state for block in database, creating provider builder"); // For persisted blocks, we create a builder that will fetch state directly from the // database - return Ok(Some(StateProviderBuilder::new(self.provider.clone(), hash, None))); + return Ok(Some(StateProviderBuilder::new(self.provider.clone(), hash, None))) } debug!(target: "engine::tree", %hash, "no canonical state found for block"); diff --git a/crates/engine/tree/src/tree/payload_processor/multiproof.rs b/crates/engine/tree/src/tree/payload_processor/multiproof.rs index ac0a8972d1..0b62bc73ea 100644 --- a/crates/engine/tree/src/tree/payload_processor/multiproof.rs +++ b/crates/engine/tree/src/tree/payload_processor/multiproof.rs @@ -162,7 +162,7 @@ impl ProofSequencer { // return early if we don't have the next expected proof if !self.pending_proofs.contains_key(&self.next_to_deliver) { - return Vec::new(); + return Vec::new() } let mut consecutive_proofs = Vec::with_capacity(self.pending_proofs.len()); @@ -385,7 +385,7 @@ where "No proof targets, sending empty multiproof back immediately" ); input.send_empty_proof(); - return; + return } if self.inflight >= self.max_concurrent { @@ -760,7 +760,7 @@ where let Some(fetched_storage) = self.fetched_proof_targets.get(hashed_address) else { // this means the account has not been fetched yet, so we must fetch everything // associated with this account - continue; + continue }; let prev_target_storage_len = target_storage.len(); @@ -966,7 +966,7 @@ where target: "engine::root", "State updates finished and all proofs processed, ending calculation" ); - break; + break } } MultiProofMessage::EmptyProof { sequence_number, state } => { @@ -991,7 +991,7 @@ where target: "engine::root", "State updates finished and all proofs processed, ending calculation" ); - break; + break } } MultiProofMessage::ProofCalculated(proof_calculated) => { @@ -1030,7 +1030,7 @@ where debug!( target: "engine::root", "State updates finished and all proofs processed, ending calculation"); - break; + break } } MultiProofMessage::ProofCalculationError(err) => { @@ -1039,7 +1039,7 @@ where ?err, "proof calculation error" ); - return; + return } }, Err(_) => { diff --git a/crates/engine/tree/src/tree/payload_processor/prewarm.rs b/crates/engine/tree/src/tree/payload_processor/prewarm.rs index 57d0611821..85e9e80330 100644 --- a/crates/engine/tree/src/tree/payload_processor/prewarm.rs +++ b/crates/engine/tree/src/tree/payload_processor/prewarm.rs @@ -124,7 +124,7 @@ where self.ctx.cache_metrics.clone(), ); if cache.cache().insert_state(&state).is_err() { - return; + return } cache.update_metrics(); @@ -177,7 +177,7 @@ where if self.prewarm_outcomes_left == 0 && final_block_output.is_some() { // all tasks are done, and we have the block output, we can exit - break; + break } } PrewarmTaskEvent::Terminate { block_output } => { @@ -185,7 +185,7 @@ where if self.prewarm_outcomes_left == 0 { // all tasks are done, we can exit, which will save caches and exit - break; + break } } } @@ -249,7 +249,7 @@ where %err, "Failed to build state provider in prewarm thread" ); - return None; + return None } }; @@ -292,7 +292,7 @@ where /// executed sequentially. fn transact_batch(self, txs: &[Recovered], sender: Sender) { let Some((mut evm, evm_config, metrics, terminate_execution)) = self.evm_for_ctx() else { - return; + return }; for tx in txs { @@ -300,7 +300,7 @@ where // and exit. if terminate_execution.load(Ordering::Relaxed) { let _ = sender.send(PrewarmTaskEvent::Outcome { proof_targets: None }); - return; + return } // create the tx env @@ -316,7 +316,7 @@ where sender=%tx.signer(), "Error when executing prewarm transaction", ); - return; + return } }; metrics.execution_duration.record(start.elapsed()); @@ -344,7 +344,7 @@ fn multiproof_targets_from_state(state: EvmState) -> (MultiProofTargets, usize) // // See: https://eips.ethereum.org/EIPS/eip-6780 if !account.is_touched() || account.is_selfdestructed() { - continue; + continue } let mut storage_set = @@ -352,7 +352,7 @@ fn multiproof_targets_from_state(state: EvmState) -> (MultiProofTargets, usize) for (key, slot) in account.storage { // do nothing if unchanged if !slot.is_changed() { - continue; + continue } storage_set.insert(keccak256(B256::new(key.to_be_bytes()))); diff --git a/crates/engine/tree/src/tree/precompile_cache.rs b/crates/engine/tree/src/tree/precompile_cache.rs index d21d6de17f..a3eb3a5ba2 100644 --- a/crates/engine/tree/src/tree/precompile_cache.rs +++ b/crates/engine/tree/src/tree/precompile_cache.rs @@ -187,7 +187,7 @@ where if let Some(entry) = &self.cache.get(&key) { self.increment_by_one_precompile_cache_hits(); if input.gas >= entry.gas_used() { - return entry.to_precompile_result(); + return entry.to_precompile_result() } } diff --git a/crates/engine/tree/src/tree/state.rs b/crates/engine/tree/src/tree/state.rs index 74c9d08146..7bc443db93 100644 --- a/crates/engine/tree/src/tree/state.rs +++ b/crates/engine/tree/src/tree/state.rs @@ -176,13 +176,13 @@ impl TreeState { pub(crate) fn is_canonical(&self, hash: B256) -> bool { let mut current_block = self.current_canonical_head.hash; if current_block == hash { - return true; + return true } while let Some(executed) = self.blocks_by_hash.get(¤t_block) { current_block = executed.recovered_block().parent_hash(); if current_block == hash { - return true; + return true } } @@ -201,7 +201,7 @@ impl TreeState { // If the last persisted hash is not canonical, then we don't want to remove any canonical // blocks yet. if !self.is_canonical(last_persisted_hash) { - return; + return } // First, let's walk back the canonical chain and remove canonical blocks lower than the @@ -352,25 +352,25 @@ impl TreeState { // If the second block's parent is the first block's hash, then it is a direct descendant // and we can return early. if second.parent_hash() == first.hash { - return true; + return true } // If the second block is lower than, or has the same block number, they are not // descendants. if second.number() <= first.number { - return false; + return false } // iterate through parents of the second until we reach the number let Some(mut current_block) = self.block_by_hash(second.parent_hash()) else { // If we can't find its parent in the tree, we can't continue, so return false - return false; + return false }; while current_block.number() > first.number + 1 { let Some(block) = self.block_by_hash(current_block.header().parent_hash()) else { // If we can't find its parent in the tree, we can't continue, so return false - return false; + return false }; current_block = block; diff --git a/crates/engine/tree/src/tree/tests.rs b/crates/engine/tree/src/tree/tests.rs index 5ebccf8619..9922d29ff1 100644 --- a/crates/engine/tree/src/tree/tests.rs +++ b/crates/engine/tree/src/tree/tests.rs @@ -714,8 +714,8 @@ async fn test_get_canonical_blocks_to_persist() { assert!(!blocks_to_persist.iter().any(|b| b.recovered_block().hash() == fork_block_hash)); // check that the original block 4 is still included - assert!(blocks_to_persist.iter().any(|b| b.recovered_block().number == 4 - && b.recovered_block().hash() == blocks[4].recovered_block().hash())); + assert!(blocks_to_persist.iter().any(|b| b.recovered_block().number == 4 && + b.recovered_block().hash() == blocks[4].recovered_block().hash())); // check that if we advance persistence, the persistence action is the correct value test_harness.tree.advance_persistence().expect("advancing persistence should succeed"); diff --git a/crates/engine/tree/src/tree/trie_updates.rs b/crates/engine/tree/src/tree/trie_updates.rs index a01cb7f1c6..ba8f7fc16a 100644 --- a/crates/engine/tree/src/tree/trie_updates.rs +++ b/crates/engine/tree/src/tree/trie_updates.rs @@ -24,9 +24,9 @@ struct TrieUpdatesDiff { impl TrieUpdatesDiff { fn has_differences(&self) -> bool { - !self.account_nodes.is_empty() - || !self.removed_nodes.is_empty() - || !self.storage_tries.is_empty() + !self.account_nodes.is_empty() || + !self.removed_nodes.is_empty() || + !self.storage_tries.is_empty() } pub(super) fn log_differences(mut self) { @@ -63,9 +63,9 @@ struct StorageTrieUpdatesDiff { impl StorageTrieUpdatesDiff { fn has_differences(&self) -> bool { - self.is_deleted.is_some() - || !self.storage_nodes.is_empty() - || !self.removed_nodes.is_empty() + self.is_deleted.is_some() || + !self.storage_nodes.is_empty() || + !self.removed_nodes.is_empty() } fn log_differences(&self, address: B256) { @@ -287,11 +287,11 @@ fn branch_nodes_equal( ) -> Result { Ok(match (task, regular) { (Some(task), Some(regular)) => { - task.state_mask == regular.state_mask - && task.tree_mask == regular.tree_mask - && task.hash_mask == regular.hash_mask - && task.hashes == regular.hashes - && task.root_hash == regular.root_hash + task.state_mask == regular.state_mask && + task.tree_mask == regular.tree_mask && + task.hash_mask == regular.hash_mask && + task.hashes == regular.hashes && + task.root_hash == regular.root_hash } (None, None) => true, _ => { diff --git a/crates/engine/util/src/reorg.rs b/crates/engine/util/src/reorg.rs index 4dce37cf88..050a384c44 100644 --- a/crates/engine/util/src/reorg.rs +++ b/crates/engine/util/src/reorg.rs @@ -127,7 +127,7 @@ where } Err(_) => {} }; - continue; + continue } if let EngineReorgState::Reorg { queue } = &mut this.state { @@ -173,7 +173,7 @@ where return Poll::Ready(Some(BeaconEngineMessage::NewPayload { payload, tx, - })); + })) } }; let reorg_forkchoice_state = ForkchoiceState { @@ -206,7 +206,7 @@ where }, ]); *this.state = EngineReorgState::Reorg { queue }; - continue; + continue } ( Some(BeaconEngineMessage::ForkchoiceUpdated { @@ -231,7 +231,7 @@ where } (item, _) => item, }; - return Poll::Ready(item); + return Poll::Ready(item) } } } @@ -263,7 +263,7 @@ where .block_by_hash(previous_hash)? .ok_or_else(|| ProviderError::HeaderNotFound(previous_hash.into()))?; if depth == 0 { - break 'target reorg_target.seal_slow(); + break 'target reorg_target.seal_slow() } depth -= 1; @@ -294,7 +294,7 @@ where for tx in candidate_transactions { // ensure we still have capacity for this transaction if cumulative_gas_used + tx.gas_limit() > reorg_target.gas_limit() { - continue; + continue } let tx_recovered = @@ -306,7 +306,7 @@ where error, })) => { trace!(target: "engine::stream::reorg", hash = %hash, ?error, "Error executing transaction from next block"); - continue; + continue } // Treat error as fatal Err(error) => return Err(RethError::Execution(error)), diff --git a/crates/engine/util/src/skip_fcu.rs b/crates/engine/util/src/skip_fcu.rs index 0c724de080..a4712c2e0b 100644 --- a/crates/engine/util/src/skip_fcu.rs +++ b/crates/engine/util/src/skip_fcu.rs @@ -55,7 +55,7 @@ where *this.skipped += 1; tracing::warn!(target: "engine::stream::skip_fcu", ?state, ?payload_attrs, threshold=this.threshold, skipped=this.skipped, "Skipping FCU"); let _ = tx.send(Ok(OnForkChoiceUpdated::syncing())); - continue; + continue } *this.skipped = 0; Some(BeaconEngineMessage::ForkchoiceUpdated { @@ -67,7 +67,7 @@ where } next => next, }; - return Poll::Ready(item); + return Poll::Ready(item) } } } diff --git a/crates/engine/util/src/skip_new_payload.rs b/crates/engine/util/src/skip_new_payload.rs index 26d47fa36a..fa818f5453 100644 --- a/crates/engine/util/src/skip_new_payload.rs +++ b/crates/engine/util/src/skip_new_payload.rs @@ -53,14 +53,14 @@ where skipped=this.skipped, "Skipping new payload" ); let _ = tx.send(Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing))); - continue; + continue } *this.skipped = 0; Some(BeaconEngineMessage::NewPayload { payload, tx }) } next => next, }; - return Poll::Ready(item); + return Poll::Ready(item) } } } diff --git a/crates/era-downloader/tests/it/checksums.rs b/crates/era-downloader/tests/it/checksums.rs index 09faa01710..630cbece5d 100644 --- a/crates/era-downloader/tests/it/checksums.rs +++ b/crates/era-downloader/tests/it/checksums.rs @@ -64,17 +64,17 @@ impl HttpClient for FailingClient { "https://mainnet.era1.nimbus.team/" => Bytes::from_static(crate::NIMBUS), "https://era1.ethportal.net/" => Bytes::from_static(crate::ETH_PORTAL), "https://era.ithaca.xyz/era1/index.html" => Bytes::from_static(crate::ITHACA), - "https://mainnet.era1.nimbus.team/checksums.txt" - | "https://era1.ethportal.net/checksums.txt" - | "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), - "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" - | "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" - | "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { + "https://mainnet.era1.nimbus.team/checksums.txt" | + "https://era1.ethportal.net/checksums.txt" | + "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), + "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" | + "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" | + "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { Bytes::from_static(crate::MAINNET_0) } - "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" - | "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" - | "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { + "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" | + "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" | + "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { Bytes::from_static(crate::MAINNET_1) } v => unimplemented!("Unexpected URL \"{v}\""), diff --git a/crates/era-downloader/tests/it/main.rs b/crates/era-downloader/tests/it/main.rs index cc5839755d..526d3885bf 100644 --- a/crates/era-downloader/tests/it/main.rs +++ b/crates/era-downloader/tests/it/main.rs @@ -36,17 +36,17 @@ impl HttpClient for StubClient { "https://mainnet.era1.nimbus.team/" => Bytes::from_static(NIMBUS), "https://era1.ethportal.net/" => Bytes::from_static(ETH_PORTAL), "https://era.ithaca.xyz/era1/index.html" => Bytes::from_static(ITHACA), - "https://mainnet.era1.nimbus.team/checksums.txt" - | "https://era1.ethportal.net/checksums.txt" - | "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), - "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" - | "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" - | "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { + "https://mainnet.era1.nimbus.team/checksums.txt" | + "https://era1.ethportal.net/checksums.txt" | + "https://era.ithaca.xyz/era1/checksums.txt" => Bytes::from_static(CHECKSUMS), + "https://era1.ethportal.net/mainnet-00000-5ec1ffb8.era1" | + "https://mainnet.era1.nimbus.team/mainnet-00000-5ec1ffb8.era1" | + "https://era.ithaca.xyz/era1/mainnet-00000-5ec1ffb8.era1" => { Bytes::from_static(MAINNET_0) } - "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" - | "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" - | "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { + "https://era1.ethportal.net/mainnet-00001-a5364e9a.era1" | + "https://mainnet.era1.nimbus.team/mainnet-00001-a5364e9a.era1" | + "https://era.ithaca.xyz/era1/mainnet-00001-a5364e9a.era1" => { Bytes::from_static(MAINNET_1) } v => unimplemented!("Unexpected URL \"{v}\""), diff --git a/crates/era/src/era1_file.rs b/crates/era/src/era1_file.rs index 8b8b507c69..547d770f06 100644 --- a/crates/era/src/era1_file.rs +++ b/crates/era/src/era1_file.rs @@ -123,17 +123,13 @@ impl BlockTupleIterator { } execution_types::ACCUMULATOR => { if self.accumulator.is_some() { - return Err(E2sError::Ssz( - "Multiple accumulator entries found".to_string(), - )); + return Err(E2sError::Ssz("Multiple accumulator entries found".to_string())); } self.accumulator = Some(Accumulator::from_entry(&entry)?); } BLOCK_INDEX => { if self.block_index.is_some() { - return Err(E2sError::Ssz( - "Multiple block index entries found".to_string(), - )); + return Err(E2sError::Ssz("Multiple block index entries found".to_string())); } self.block_index = Some(BlockIndex::from_entry(&entry)?); } @@ -142,10 +138,10 @@ impl BlockTupleIterator { } } - if !self.headers.is_empty() - && !self.bodies.is_empty() - && !self.receipts.is_empty() - && !self.difficulties.is_empty() + if !self.headers.is_empty() && + !self.bodies.is_empty() && + !self.receipts.is_empty() && + !self.difficulties.is_empty() { let header = self.headers.pop_front().unwrap(); let body = self.bodies.pop_front().unwrap(); @@ -194,9 +190,9 @@ impl Era1Reader { } = iter; // Ensure we have matching counts for block components - if headers.len() != bodies.len() - || headers.len() != receipts.len() - || headers.len() != difficulties.len() + if headers.len() != bodies.len() || + headers.len() != receipts.len() || + headers.len() != difficulties.len() { return Err(E2sError::Ssz(format!( "Mismatched block component counts: headers={}, bodies={}, receipts={}, difficulties={}", @@ -279,9 +275,7 @@ impl Era1Writer { // Ensure blocks are written before other entries if era1_file.group.blocks.len() > MAX_BLOCKS_PER_ERA1 { - return Err(E2sError::Ssz( - "Era1 file cannot contain more than 8192 blocks".to_string(), - )); + return Err(E2sError::Ssz("Era1 file cannot contain more than 8192 blocks".to_string())); } // Write all blocks diff --git a/crates/era/tests/it/main.rs b/crates/era/tests/it/main.rs index 84fffff063..fa93981918 100644 --- a/crates/era/tests/it/main.rs +++ b/crates/era/tests/it/main.rs @@ -90,8 +90,8 @@ impl Era1TestDownloader { } // check if the filename is supported - if !ERA1_MAINNET_FILES_NAMES.contains(&filename) - && !ERA1_SEPOLIA_FILES_NAMES.contains(&filename) + if !ERA1_MAINNET_FILES_NAMES.contains(&filename) && + !ERA1_SEPOLIA_FILES_NAMES.contains(&filename) { return Err(eyre!( "Unknown file: {}. Only the following files are supported: {:?} or {:?}", diff --git a/crates/ethereum/cli/src/debug_cmd/execution.rs b/crates/ethereum/cli/src/debug_cmd/execution.rs index a68fa2a523..63a9cc3a80 100644 --- a/crates/ethereum/cli/src/debug_cmd/execution.rs +++ b/crates/ethereum/cli/src/debug_cmd/execution.rs @@ -156,7 +156,7 @@ impl> Command { match get_single_header(&client, BlockHashOrNumber::Number(block)).await { Ok(tip_header) => { info!(target: "reth::cli", ?block, "Successfully fetched block"); - return Ok(tip_header.hash()); + return Ok(tip_header.hash()) } Err(error) => { error!(target: "reth::cli", ?block, %error, "Failed to fetch the block. Retrying..."); @@ -209,7 +209,7 @@ impl> Command { provider.get_stage_checkpoint(StageId::Finish)?.map(|ch| ch.block_number); if latest_block_number.unwrap_or_default() >= self.to { info!(target: "reth::cli", latest = latest_block_number, "Nothing to run"); - return Ok(()); + return Ok(()) } ctx.task_executor.spawn_critical( diff --git a/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs b/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs index 86662e2842..b45e712da2 100644 --- a/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs +++ b/crates/ethereum/cli/src/debug_cmd/in_memory_merkle.rs @@ -159,7 +159,7 @@ impl> Command { if in_memory_state_root == block.state_root() { info!(target: "reth::cli", state_root = ?in_memory_state_root, "Computed in-memory state root matches"); - return Ok(()); + return Ok(()) } let provider_rw = provider_factory.database_provider_rw()?; @@ -203,8 +203,8 @@ impl> Command { match (in_mem_updates_iter.next(), incremental_updates_iter.next()) { (Some(in_mem), Some(incr)) => { similar_asserts::assert_eq!(in_mem.0, incr.0, "Nibbles don't match"); - if in_mem.1 != incr.1 - && in_mem.0.len() > self.skip_node_depth.unwrap_or_default() + if in_mem.1 != incr.1 && + in_mem.0.len() > self.skip_node_depth.unwrap_or_default() { in_mem_mismatched.push(in_mem); incremental_mismatched.push(incr); diff --git a/crates/ethereum/cli/src/debug_cmd/merkle.rs b/crates/ethereum/cli/src/debug_cmd/merkle.rs index 27d0876af7..09c435b6f3 100644 --- a/crates/ethereum/cli/src/debug_cmd/merkle.rs +++ b/crates/ethereum/cli/src/debug_cmd/merkle.rs @@ -192,7 +192,7 @@ impl> Command { if incremental_result.is_ok() { debug!(target: "reth::cli", block_number, "Successfully computed incremental root"); - continue; + continue } warn!(target: "reth::cli", block_number, "Incremental calculation failed, retrying from scratch"); @@ -235,14 +235,14 @@ impl> Command { let mut clean_account_mismatched = Vec::new(); let mut incremental_account_trie_iter = incremental_account_trie.into_iter().peekable(); let mut clean_account_trie_iter = clean_account_trie.into_iter().peekable(); - while incremental_account_trie_iter.peek().is_some() - || clean_account_trie_iter.peek().is_some() + while incremental_account_trie_iter.peek().is_some() || + clean_account_trie_iter.peek().is_some() { match (incremental_account_trie_iter.next(), clean_account_trie_iter.next()) { (Some(incremental), Some(clean)) => { similar_asserts::assert_eq!(incremental.0, clean.0, "Nibbles don't match"); - if incremental.1 != clean.1 - && clean.0 .0.len() > self.skip_node_depth.unwrap_or_default() + if incremental.1 != clean.1 && + clean.0 .0.len() > self.skip_node_depth.unwrap_or_default() { incremental_account_mismatched.push(incremental); clean_account_mismatched.push(clean); @@ -264,16 +264,16 @@ impl> Command { let mut first_mismatched_storage = None; let mut incremental_storage_trie_iter = incremental_storage_trie.into_iter().peekable(); let mut clean_storage_trie_iter = clean_storage_trie.into_iter().peekable(); - while incremental_storage_trie_iter.peek().is_some() - || clean_storage_trie_iter.peek().is_some() + while incremental_storage_trie_iter.peek().is_some() || + clean_storage_trie_iter.peek().is_some() { match (incremental_storage_trie_iter.next(), clean_storage_trie_iter.next()) { (Some(incremental), Some(clean)) => { - if incremental != clean - && clean.1.nibbles.len() > self.skip_node_depth.unwrap_or_default() + if incremental != clean && + clean.1.nibbles.len() > self.skip_node_depth.unwrap_or_default() { first_mismatched_storage = Some((incremental, clean)); - break; + break } } (Some(incremental), None) => { diff --git a/crates/ethereum/consensus/src/lib.rs b/crates/ethereum/consensus/src/lib.rs index bb7d4d860b..82a37b2386 100644 --- a/crates/ethereum/consensus/src/lib.rs +++ b/crates/ethereum/consensus/src/lib.rs @@ -56,12 +56,11 @@ impl EthBeaconConsensus parent: &SealedHeader, ) -> Result<(), ConsensusError> { // Determine the parent gas limit, considering elasticity multiplier on the London fork. - let parent_gas_limit = if !self.chain_spec.is_london_active_at_block(parent.number()) - && self.chain_spec.is_london_active_at_block(header.number()) + let parent_gas_limit = if !self.chain_spec.is_london_active_at_block(parent.number()) && + self.chain_spec.is_london_active_at_block(header.number()) { - parent.gas_limit() - * self - .chain_spec + parent.gas_limit() * + self.chain_spec .base_fee_params_at_timestamp(header.timestamp()) .elasticity_multiplier as u64 } else { @@ -74,23 +73,23 @@ impl EthBeaconConsensus return Err(ConsensusError::GasLimitInvalidIncrease { parent_gas_limit, child_gas_limit: header.gas_limit(), - }); + }) } } // Check for a decrease in gas limit beyond the allowed threshold. - else if parent_gas_limit - header.gas_limit() - >= parent_gas_limit / GAS_LIMIT_BOUND_DIVISOR + else if parent_gas_limit - header.gas_limit() >= + parent_gas_limit / GAS_LIMIT_BOUND_DIVISOR { return Err(ConsensusError::GasLimitInvalidDecrease { parent_gas_limit, child_gas_limit: header.gas_limit(), - }); + }) } // Check if the self gas limit is below the minimum required limit. else if header.gas_limit() < MINIMUM_GAS_LIMIT { return Err(ConsensusError::GasLimitInvalidMinimum { child_gas_limit: header.gas_limit(), - }); + }) } Ok(()) @@ -160,8 +159,8 @@ where .unwrap() .as_secs(); - if header.timestamp() - > present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS + if header.timestamp() > + present_timestamp + alloy_eips::merge::ALLOWED_FUTURE_BLOCK_TIME_SECONDS { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp(), @@ -175,14 +174,14 @@ where validate_header_base_fee(header, &self.chain_spec)?; // EIP-4895: Beacon chain push withdrawals as operations - if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) - && header.withdrawals_root().is_none() + if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) && + header.withdrawals_root().is_none() { - return Err(ConsensusError::WithdrawalsRootMissing); - } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) - && header.withdrawals_root().is_some() + return Err(ConsensusError::WithdrawalsRootMissing) + } else if !self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp()) && + header.withdrawals_root().is_some() { - return Err(ConsensusError::WithdrawalsRootUnexpected); + return Err(ConsensusError::WithdrawalsRootUnexpected) } // Ensures that EIP-4844 fields are valid once cancun is active. @@ -194,19 +193,19 @@ where .unwrap_or_else(BlobParams::cancun), )?; } else if header.blob_gas_used().is_some() { - return Err(ConsensusError::BlobGasUsedUnexpected); + return Err(ConsensusError::BlobGasUsedUnexpected) } else if header.excess_blob_gas().is_some() { - return Err(ConsensusError::ExcessBlobGasUnexpected); + return Err(ConsensusError::ExcessBlobGasUnexpected) } else if header.parent_beacon_block_root().is_some() { - return Err(ConsensusError::ParentBeaconBlockRootUnexpected); + return Err(ConsensusError::ParentBeaconBlockRootUnexpected) } if self.chain_spec.is_prague_active_at_timestamp(header.timestamp()) { if header.requests_hash().is_none() { - return Err(ConsensusError::RequestsHashMissing); + return Err(ConsensusError::RequestsHashMissing) } } else if header.requests_hash().is_some() { - return Err(ConsensusError::RequestsHashUnexpected); + return Err(ConsensusError::RequestsHashUnexpected) } Ok(()) diff --git a/crates/ethereum/consensus/src/validation.rs b/crates/ethereum/consensus/src/validation.rs index 01eb6d06fc..186403d865 100644 --- a/crates/ethereum/consensus/src/validation.rs +++ b/crates/ethereum/consensus/src/validation.rs @@ -30,7 +30,7 @@ where return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.header().gas_used() }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }); + }) } // Before Byzantium, receipts contained state root that would mean that expensive @@ -42,20 +42,20 @@ where verify_receipts(block.header().receipts_root(), block.header().logs_bloom(), receipts) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error); + return Err(error) } } // Validate that the header requests hash matches the calculated requests hash if chain_spec.is_prague_active_at_timestamp(block.header().timestamp()) { let Some(header_requests_hash) = block.header().requests_hash() else { - return Err(ConsensusError::RequestsHashMissing); + return Err(ConsensusError::RequestsHashMissing) }; let requests_hash = requests.requests_hash(); if requests_hash != header_requests_hash { return Err(ConsensusError::BodyRequestsHashDiff( GotExpected::new(requests_hash, header_requests_hash).into(), - )); + )) } } @@ -97,13 +97,13 @@ fn compare_receipts_root_and_logs_bloom( if calculated_receipts_root != expected_receipts_root { return Err(ConsensusError::BodyReceiptRootDiff( GotExpected { got: calculated_receipts_root, expected: expected_receipts_root }.into(), - )); + )) } if calculated_logs_bloom != expected_logs_bloom { return Err(ConsensusError::BodyBloomLogDiff( GotExpected { got: calculated_logs_bloom, expected: expected_logs_bloom }.into(), - )); + )) } Ok(()) diff --git a/crates/ethereum/node/tests/e2e/rpc.rs b/crates/ethereum/node/tests/e2e/rpc.rs index 60a3991c0f..ea49d8b3c8 100644 --- a/crates/ethereum/node/tests/e2e/rpc.rs +++ b/crates/ethereum/node/tests/e2e/rpc.rs @@ -61,8 +61,8 @@ async fn test_fee_history() -> eyre::Result<()> { let fee_history = provider.get_fee_history(10, 0_u64.into(), &[]).await?; let genesis_base_fee = chain_spec.initial_base_fee().unwrap() as u128; - let expected_first_base_fee = genesis_base_fee - - genesis_base_fee / chain_spec.base_fee_params_at_block(0).max_change_denominator; + let expected_first_base_fee = genesis_base_fee - + genesis_base_fee / chain_spec.base_fee_params_at_block(0).max_change_denominator; assert_eq!(fee_history.base_fee_per_gas[0], genesis_base_fee); assert_eq!(fee_history.base_fee_per_gas[1], expected_first_base_fee,); diff --git a/crates/ethereum/payload/src/lib.rs b/crates/ethereum/payload/src/lib.rs index 848c900ac7..603e7ab74e 100644 --- a/crates/ethereum/payload/src/lib.rs +++ b/crates/ethereum/payload/src/lib.rs @@ -208,12 +208,12 @@ where &pool_tx, InvalidPoolTransactionError::ExceedsGasLimit(pool_tx.gas_limit(), block_gas_limit), ); - continue; + continue } // check if the job was cancelled, if so we can exit early if cancel.is_cancelled() { - return Ok(BuildOutcome::Cancelled); + return Ok(BuildOutcome::Cancelled) } // convert tx to a signed transaction @@ -240,14 +240,14 @@ where }, ), ); - continue; + continue } let blob_sidecar_result = 'sidecar: { let Some(sidecar) = pool.get_blob(*tx.hash()).map_err(PayloadBuilderError::other)? else { - break 'sidecar Err(Eip4844PoolTransactionError::MissingEip4844BlobSidecar); + break 'sidecar Err(Eip4844PoolTransactionError::MissingEip4844BlobSidecar) }; if chain_spec.is_osaka_active_at_timestamp(attributes.timestamp) { @@ -267,7 +267,7 @@ where Ok(sidecar) => Some(sidecar), Err(error) => { best_txs.mark_invalid(&pool_tx, InvalidPoolTransactionError::Eip4844(error)); - continue; + continue } }; } @@ -291,7 +291,7 @@ where ), ); } - continue; + continue } // this is an error that we should treat as fatal for this attempt Err(err) => return Err(PayloadBuilderError::evm(err)), @@ -324,7 +324,7 @@ where // Release db drop(builder); // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) } let BlockBuilderOutcome { execution_result, block, .. } = builder.finish(&state_provider)?; diff --git a/crates/ethereum/payload/src/validator.rs b/crates/ethereum/payload/src/validator.rs index 0fac37fe30..75f4b1f474 100644 --- a/crates/ethereum/payload/src/validator.rs +++ b/crates/ethereum/payload/src/validator.rs @@ -85,7 +85,7 @@ impl EthereumExecutionPayloadValidator return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - }); + }) } shanghai::ensure_well_formed_fields( diff --git a/crates/ethereum/primitives/src/receipt.rs b/crates/ethereum/primitives/src/receipt.rs index 735decd620..ffc06c7fc8 100644 --- a/crates/ethereum/primitives/src/receipt.rs +++ b/crates/ethereum/primitives/src/receipt.rs @@ -38,10 +38,10 @@ pub struct Receipt { impl Receipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { - self.success.length() - + self.cumulative_gas_used.length() - + bloom.length() - + self.logs.length() + self.success.length() + + self.cumulative_gas_used.length() + + bloom.length() + + self.logs.length() } /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. @@ -178,7 +178,7 @@ impl RlpDecodableReceipt for Receipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, TxType::Legacy); + return Self::rlp_decode_inner(buf, TxType::Legacy) } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -198,8 +198,8 @@ impl RlpDecodableReceipt for Receipt { impl Encodable2718 for Receipt { fn encode_2718_len(&self) -> usize { - (!self.tx_type.is_legacy() as usize) - + self.rlp_header_inner_without_bloom().length_with_payload() + (!self.tx_type.is_legacy() as usize) + + self.rlp_header_inner_without_bloom().length_with_payload() } // encode the header @@ -276,10 +276,10 @@ impl IsTyped2718 for Receipt { impl InMemorySize for Receipt { fn size(&self) -> usize { - self.tx_type.size() - + core::mem::size_of::() - + core::mem::size_of::() - + self.logs.capacity() * core::mem::size_of::() + self.tx_type.size() + + core::mem::size_of::() + + core::mem::size_of::() + + self.logs.capacity() * core::mem::size_of::() } } diff --git a/crates/ethereum/primitives/src/transaction.rs b/crates/ethereum/primitives/src/transaction.rs index 9da37fe078..07191142e7 100644 --- a/crates/ethereum/primitives/src/transaction.rs +++ b/crates/ethereum/primitives/src/transaction.rs @@ -333,9 +333,9 @@ impl Hash for TransactionSigned { impl PartialEq for TransactionSigned { fn eq(&self, other: &Self) -> bool { - self.signature == other.signature - && self.transaction == other.transaction - && self.tx_hash() == other.tx_hash() + self.signature == other.signature && + self.transaction == other.transaction && + self.tx_hash() == other.tx_hash() } } diff --git a/crates/etl/src/lib.rs b/crates/etl/src/lib.rs index fdf4a2ec37..46d41d704d 100644 --- a/crates/etl/src/lib.rs +++ b/crates/etl/src/lib.rs @@ -256,7 +256,7 @@ impl EtlFile { /// Can return error if it reaches EOF before filling the internal buffers. pub(crate) fn read_next(&mut self) -> std::io::Result, Vec)>> { if self.len == 0 { - return Ok(None); + return Ok(None) } let mut buffer_key_length = [0; KV_LEN]; diff --git a/crates/evm/evm/src/metrics.rs b/crates/evm/evm/src/metrics.rs index 46f74e7aae..586c1c154d 100644 --- a/crates/evm/evm/src/metrics.rs +++ b/crates/evm/evm/src/metrics.rs @@ -303,9 +303,9 @@ mod tests { for metric in snapshot { let metric_name = metric.0.key().name(); - if metric_name == "sync.execution.accounts_loaded_histogram" - || metric_name == "sync.execution.storage_slots_loaded_histogram" - || metric_name == "sync.execution.bytecodes_loaded_histogram" + if metric_name == "sync.execution.accounts_loaded_histogram" || + metric_name == "sync.execution.storage_slots_loaded_histogram" || + metric_name == "sync.execution.bytecodes_loaded_histogram" { if let DebugValue::Histogram(vs) = metric.3 { assert!( diff --git a/crates/evm/execution-errors/src/trie.rs b/crates/evm/execution-errors/src/trie.rs index 8578b7443c..7c5ad72b1c 100644 --- a/crates/evm/execution-errors/src/trie.rs +++ b/crates/evm/execution-errors/src/trie.rs @@ -20,8 +20,8 @@ pub enum StateRootError { impl From for DatabaseError { fn from(err: StateRootError) -> Self { match err { - StateRootError::Database(err) - | StateRootError::StorageRootError(StorageRootError::Database(err)) => err, + StateRootError::Database(err) | + StateRootError::StorageRootError(StorageRootError::Database(err)) => err, } } } diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index bf5671c040..dc7218631f 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -140,13 +140,13 @@ impl Chain { block_number: BlockNumber, ) -> Option> { if self.tip().number() == block_number { - return Some(self.execution_outcome.clone()); + return Some(self.execution_outcome.clone()) } if self.blocks.contains_key(&block_number) { let mut execution_outcome = self.execution_outcome.clone(); execution_outcome.revert_to(block_number); - return Some(execution_outcome); + return Some(execution_outcome) } None } @@ -286,7 +286,7 @@ impl Chain { let chain_tip = self.tip(); let other_fork_block = other.fork_block(); if chain_tip.hash() != other_fork_block.hash { - return Err(other); + return Err(other) } // Insert blocks from other chain diff --git a/crates/evm/execution-types/src/execution_outcome.rs b/crates/evm/execution-types/src/execution_outcome.rs index 61d21b6b1a..b198713a2e 100644 --- a/crates/evm/execution-types/src/execution_outcome.rs +++ b/crates/evm/execution-types/src/execution_outcome.rs @@ -203,11 +203,11 @@ impl ExecutionOutcome { /// Transform block number to the index of block. pub fn block_number_to_index(&self, block_number: BlockNumber) -> Option { if self.first_block > block_number { - return None; + return None } let index = block_number - self.first_block; if index >= self.receipts.len() as u64 { - return None; + return None } Some(index as usize) } @@ -296,7 +296,7 @@ impl ExecutionOutcome { T: Clone, { if at == self.first_block { - return (None, self); + return (None, self) } let (mut lower_state, mut higher_state) = (self.clone(), self); diff --git a/crates/exex/exex/src/backfill/job.rs b/crates/exex/exex/src/backfill/job.rs index c73a22e4f4..bbfd6c2a89 100644 --- a/crates/exex/exex/src/backfill/job.rs +++ b/crates/exex/exex/src/backfill/job.rs @@ -46,7 +46,7 @@ where fn next(&mut self) -> Option { if self.range.is_empty() { - return None; + return None } Some(self.execute_range()) @@ -129,7 +129,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break; + break } } diff --git a/crates/exex/exex/src/backfill/stream.rs b/crates/exex/exex/src/backfill/stream.rs index 1f0fef798a..2525f80422 100644 --- a/crates/exex/exex/src/backfill/stream.rs +++ b/crates/exex/exex/src/backfill/stream.rs @@ -108,7 +108,7 @@ where // next. self.push_front(job); - return Poll::Ready(Some(job_result)); + return Poll::Ready(Some(job_result)) }; } diff --git a/crates/exex/exex/src/manager.rs b/crates/exex/exex/src/manager.rs index 7300eb4e28..d5006dd9f1 100644 --- a/crates/exex/exex/src/manager.rs +++ b/crates/exex/exex/src/manager.rs @@ -146,7 +146,7 @@ impl ExExHandle { ); self.next_notification_id = notification_id + 1; - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } // Do not handle [ExExNotification::ChainReorged] and @@ -482,9 +482,9 @@ where } this.push_notification(notification); - continue; + continue } - break; + break } // Update capacity @@ -504,7 +504,7 @@ where if let Some(notification) = this.buffer.get(notification_index) { if let Poll::Ready(Err(err)) = exex.send(cx, notification) { // The channel was closed, which is irrecoverable for the manager - return Poll::Ready(Err(err.into())); + return Poll::Ready(Err(err.into())) } } min_id = min_id.min(exex.next_notification_id); diff --git a/crates/exex/exex/src/notifications.rs b/crates/exex/exex/src/notifications.rs index f13d0693d5..651bd7d5b2 100644 --- a/crates/exex/exex/src/notifications.rs +++ b/crates/exex/exex/src/notifications.rs @@ -308,12 +308,12 @@ where /// we're not on the canonical chain and we need to revert the notification with the ExEx /// head block. fn check_canonical(&mut self) -> eyre::Result>> { - if self.provider.is_known(&self.initial_exex_head.block.hash)? - && self.initial_exex_head.block.number <= self.initial_local_head.number + if self.provider.is_known(&self.initial_exex_head.block.hash)? && + self.initial_exex_head.block.number <= self.initial_local_head.number { // we have the targeted block and that block is below the current head debug!(target: "exex::notifications", "ExEx head is on the canonical chain"); - return Ok(None); + return Ok(None) } // If the head block is not found in the database, it means we're not on the canonical @@ -333,7 +333,7 @@ where return Err(eyre::eyre!( "Could not find notification for block hash {:?} in the WAL", self.initial_exex_head.block.hash - )); + )) }; // Update the head block hash to the parent hash of the first committed block. @@ -397,7 +397,7 @@ where // 1. Check once whether we need to retrieve a notification gap from the WAL. if this.pending_check_canonical { if let Some(canonical_notification) = this.check_canonical()? { - return Poll::Ready(Some(Ok(canonical_notification))); + return Poll::Ready(Some(Ok(canonical_notification))) } // ExEx head is on the canonical chain, we no longer need to check it @@ -417,7 +417,7 @@ where debug!(target: "exex::notifications", range = ?chain.range(), "Backfill job returned a chain"); return Poll::Ready(Some(Ok(ExExNotification::ChainCommitted { new: Arc::new(chain), - }))); + }))) } // Backfill job is done, remove it @@ -427,18 +427,18 @@ where // 4. Otherwise advance the regular event stream loop { let Some(notification) = ready!(this.notifications.poll_recv(cx)) else { - return Poll::Ready(None); + return Poll::Ready(None) }; // 5. In case the exex is ahead of the new tip, we must skip it if let Some(committed) = notification.committed_chain() { // inclusive check because we should start with `exex.head + 1` if this.initial_exex_head.block.number >= committed.tip().number() { - continue; + continue } } - return Poll::Ready(Some(Ok(notification))); + return Poll::Ready(Some(Ok(notification))) } } } diff --git a/crates/exex/exex/src/wal/cache.rs b/crates/exex/exex/src/wal/cache.rs index 75506082a9..b5e0f2034e 100644 --- a/crates/exex/exex/src/wal/cache.rs +++ b/crates/exex/exex/src/wal/cache.rs @@ -59,7 +59,7 @@ impl BlockCache { debug_assert_eq!(popped_block, block); file_ids.insert(file_id); } else { - break; + break } } diff --git a/crates/exex/exex/src/wal/mod.rs b/crates/exex/exex/src/wal/mod.rs index 77048d17f2..b5537aa88f 100644 --- a/crates/exex/exex/src/wal/mod.rs +++ b/crates/exex/exex/src/wal/mod.rs @@ -169,7 +169,7 @@ where // Remove notifications from the storage. if file_ids.is_empty() { debug!(target: "exex::wal", "No notifications were finalized from the storage"); - return Ok(()); + return Ok(()) } let (removed_notifications, removed_size) = self.storage.remove_notifications(file_ids)?; @@ -199,7 +199,7 @@ where &self, ) -> WalResult>> + '_>> { let Some(range) = self.storage.files_range()? else { - return Ok(Box::new(std::iter::empty())); + return Ok(Box::new(std::iter::empty())) }; Ok(Box::new(self.storage.iter_notifications(range).map(|entry| Ok(entry?.2)))) @@ -223,7 +223,7 @@ where ) -> WalResult>> { let Some(file_id) = self.wal.block_cache().get_file_id_by_committed_block_hash(block_hash) else { - return Ok(None); + return Ok(None) }; self.wal diff --git a/crates/net/banlist/src/lib.rs b/crates/net/banlist/src/lib.rs index bc7d347195..29cf8eb76a 100644 --- a/crates/net/banlist/src/lib.rs +++ b/crates/net/banlist/src/lib.rs @@ -16,7 +16,7 @@ use std::{collections::HashMap, net::IpAddr, time::Instant}; /// Should be replaced with [`IpAddr::is_global`](std::net::IpAddr::is_global) once it is stable. pub const fn is_global(ip: &IpAddr) -> bool { if ip.is_unspecified() || ip.is_loopback() { - return false; + return false } match ip { @@ -62,7 +62,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false; + return false } } true @@ -77,7 +77,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false; + return false } } true diff --git a/crates/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index 2599af9384..976ade1728 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -772,8 +772,8 @@ impl Discv4Service { self.kbuckets .closest_values(&target_key) .filter(|node| { - node.value.has_endpoint_proof - && !self.pending_find_nodes.contains_key(&node.key.preimage().0) + node.value.has_endpoint_proof && + !self.pending_find_nodes.contains_key(&node.key.preimage().0) }) .take(MAX_NODES_PER_BUCKET) .map(|n| (target_key.distance(&n.key), n.value.record)), @@ -789,7 +789,7 @@ impl Discv4Service { // (e.g. connectivity problems over a long period of time, or issues during initial // bootstrapping) so we attempt to bootstrap again self.bootstrap(); - return; + return } trace!(target: "discv4", ?target, num = closest.len(), "Start lookup closest nodes"); @@ -883,7 +883,7 @@ impl Discv4Service { let Some(bucket) = self.kbuckets.get_bucket(&key) else { return false }; if bucket.num_entries() < MAX_NODES_PER_BUCKET / 2 { // skip half empty bucket - return false; + return false } self.remove_key(node_id, key) } @@ -906,7 +906,7 @@ impl Discv4Service { fn has_bond(&self, remote_id: PeerId, remote_ip: IpAddr) -> bool { if let Some(timestamp) = self.received_pongs.last_pong(remote_id, remote_ip) { if timestamp.elapsed() < self.config.bond_expiration { - return true; + return true } } false @@ -933,7 +933,7 @@ impl Discv4Service { /// a followup request to retrieve the updated ENR fn update_on_reping(&mut self, record: NodeRecord, mut last_enr_seq: Option) { if record.id == self.local_node_record.id { - return; + return } // If EIP868 extension is disabled then we want to ignore this @@ -968,7 +968,7 @@ impl Discv4Service { /// Callback invoked when we receive a pong from the peer. fn update_on_pong(&mut self, record: NodeRecord, mut last_enr_seq: Option) { if record.id == *self.local_peer_id() { - return; + return } // If EIP868 extension is disabled then we want to ignore this @@ -1077,7 +1077,7 @@ impl Discv4Service { fn on_ping(&mut self, ping: Ping, remote_addr: SocketAddr, remote_id: PeerId, hash: B256) { if self.is_expired(ping.expire) { // ping's expiration timestamp is in the past - return; + return } // create the record @@ -1209,17 +1209,17 @@ impl Discv4Service { fn try_ping(&mut self, node: NodeRecord, reason: PingReason) { if node.id == *self.local_peer_id() { // don't ping ourselves - return; + return } - if self.pending_pings.contains_key(&node.id) - || self.pending_find_nodes.contains_key(&node.id) + if self.pending_pings.contains_key(&node.id) || + self.pending_find_nodes.contains_key(&node.id) { - return; + return } if self.queued_pings.iter().any(|(n, _)| n.id == node.id) { - return; + return } if self.pending_pings.len() < MAX_NODES_PING { @@ -1254,7 +1254,7 @@ impl Discv4Service { /// Returns the echo hash of the ping message. pub(crate) fn send_enr_request(&mut self, node: NodeRecord) { if !self.config.enable_eip868 { - return; + return } let remote_addr = node.udp_addr(); let enr_request = EnrRequest { expire: self.enr_request_expiration() }; @@ -1269,7 +1269,7 @@ impl Discv4Service { /// Message handler for an incoming `Pong`. fn on_pong(&mut self, pong: Pong, remote_addr: SocketAddr, remote_id: PeerId) { if self.is_expired(pong.expire) { - return; + return } let PingRequest { node, reason, .. } = match self.pending_pings.entry(remote_id) { @@ -1278,7 +1278,7 @@ impl Discv4Service { let request = entry.get(); if request.echo_hash != pong.echo { trace!(target: "discv4", from=?remote_addr, expected=?request.echo_hash, echo_hash=?pong.echo,"Got unexpected Pong"); - return; + return } } entry.remove() @@ -1315,11 +1315,11 @@ impl Discv4Service { fn on_find_node(&mut self, msg: FindNode, remote_addr: SocketAddr, node_id: PeerId) { if self.is_expired(msg.expire) { // expiration timestamp is in the past - return; + return } if node_id == *self.local_peer_id() { // ignore find node requests to ourselves - return; + return } if self.has_bond(node_id, remote_addr.ip()) { @@ -1334,7 +1334,7 @@ impl Discv4Service { // ensure the ENR's public key matches the expected node id let enr_id = pk2id(&msg.enr.public_key()); if id != enr_id { - return; + return } if resp.echo_hash == msg.request_hash { @@ -1373,7 +1373,7 @@ impl Discv4Service { request_hash: B256, ) { if !self.config.enable_eip868 || self.is_expired(msg.expire) { - return; + return } if self.has_bond(id, remote_addr.ip()) { @@ -1392,7 +1392,7 @@ impl Discv4Service { fn on_neighbours(&mut self, msg: Neighbours, remote_addr: SocketAddr, node_id: PeerId) { if self.is_expired(msg.expire) { // response is expired - return; + return } // check if this request was expected let ctx = match self.pending_find_nodes.entry(node_id) { @@ -1408,7 +1408,7 @@ impl Discv4Service { request.response_count = total; } else { trace!(target: "discv4", total, from=?remote_addr, "Received neighbors packet entries exceeds max nodes per bucket"); - return; + return } }; @@ -1424,7 +1424,7 @@ impl Discv4Service { Entry::Vacant(_) => { // received neighbours response without requesting it trace!(target: "discv4", from=?remote_addr, "Received unsolicited Neighbours"); - return; + return } }; @@ -1444,7 +1444,7 @@ impl Discv4Service { // prevent banned peers from being added to the context if self.config.ban_list.is_banned(&node.id, &node.address) { trace!(target: "discv4", peer_id=?node.id, ip=?node.address, "ignoring banned record"); - continue; + continue } ctx.add_node(node); @@ -1540,7 +1540,7 @@ impl Discv4Service { self.pending_pings.retain(|node_id, ping_request| { if now.duration_since(ping_request.sent_at) > self.config.ping_expiration { failed_pings.push(*node_id); - return false; + return false } true }); @@ -1557,7 +1557,7 @@ impl Discv4Service { self.pending_lookup.retain(|node_id, (lookup_sent_at, _)| { if now.duration_since(*lookup_sent_at) > self.config.request_timeout { failed_lookups.push(*node_id); - return false; + return false } true }); @@ -1583,13 +1583,13 @@ impl Discv4Service { // treat this as an hard error since it responded. failed_find_nodes.push(*node_id); } - return false; + return false } true }); if failed_find_nodes.is_empty() { - return; + return } trace!(target: "discv4", num=%failed_find_nodes.len(), "processing failed find nodes"); @@ -1656,7 +1656,7 @@ impl Discv4Service { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(); if self.config.enforce_expiration_timestamps && timestamp < now { trace!(target: "discv4", "Expired packet"); - return Err(()); + return Err(()) } Ok(()) } @@ -1700,7 +1700,7 @@ impl Discv4Service { loop { // drain buffered events first if let Some(event) = self.queued_events.pop_front() { - return Poll::Ready(event); + return Poll::Ready(event) } // trigger self lookup @@ -1825,7 +1825,7 @@ impl Discv4Service { // this will make sure we're woken up again cx.waker().wake_by_ref(); } - break; + break } } @@ -1843,7 +1843,7 @@ impl Discv4Service { } if self.queued_events.is_empty() { - return Poll::Pending; + return Poll::Pending } } } @@ -1950,7 +1950,7 @@ pub(crate) async fn receive_loop(udp: Arc, tx: IngressSender, local_i // rate limit incoming packets by IP if cache.inc_ip(remote_addr.ip()) > MAX_INCOMING_PACKETS_PER_MINUTE_BY_IP { trace!(target: "discv4", ?remote_addr, "Too many incoming packets from IP."); - continue; + continue } let packet = &buf[..read]; @@ -1959,13 +1959,13 @@ pub(crate) async fn receive_loop(udp: Arc, tx: IngressSender, local_i if packet.node_id == local_id { // received our own message debug!(target: "discv4", ?remote_addr, "Received own packet."); - continue; + continue } // skip if we've already received the same packet if cache.contains_packet(packet.hash) { debug!(target: "discv4", ?remote_addr, "Received duplicate packet."); - continue; + continue } send(IngressEvent::Packet(remote_addr, packet)).await; @@ -2114,7 +2114,7 @@ impl LookupTargetRotator { self.counter += 1; self.counter %= self.interval; if self.counter == 0 { - return *local; + return *local } PeerId::random() } @@ -2488,7 +2488,7 @@ mod tests { assert!(service.pending_pings.contains_key(&node.id)); assert_eq!(service.pending_pings.len(), num_inserted); if num_inserted == MAX_NODES_PING { - break; + break } } } @@ -2668,8 +2668,8 @@ mod tests { }) .await; - let expiry = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() - + 10000000000000; + let expiry = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs() + + 10000000000000; let msg = Neighbours { nodes: vec![service2.local_node_record], expire: expiry }; service.on_neighbours(msg, record.tcp_addr(), id); // wait for the processed ping diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 25d3f94b58..2aabd45d99 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -141,7 +141,7 @@ impl Message { /// Returns the decoded message and the public key of the sender. pub fn decode(packet: &[u8]) -> Result { if packet.len() < MIN_PACKET_SIZE { - return Err(DecodePacketError::PacketTooShort); + return Err(DecodePacketError::PacketTooShort) } // parses the wire-protocol, every packet starts with a header: @@ -152,7 +152,7 @@ impl Message { let header_hash = keccak256(&packet[32..]); let data_hash = B256::from_slice(&packet[..32]); if data_hash != header_hash { - return Err(DecodePacketError::HashMismatch); + return Err(DecodePacketError::HashMismatch) } let signature = &packet[32..96]; @@ -282,7 +282,7 @@ impl Decodable for FindNode { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } let started_len = b.len(); @@ -296,7 +296,7 @@ impl Decodable for FindNode { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -324,7 +324,7 @@ impl Decodable for Neighbours { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } let started_len = b.len(); @@ -338,7 +338,7 @@ impl Decodable for Neighbours { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -367,7 +367,7 @@ impl Decodable for EnrRequest { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } let started_len = b.len(); @@ -381,7 +381,7 @@ impl Decodable for EnrRequest { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -475,7 +475,7 @@ impl Decodable for Ping { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } let started_len = b.len(); @@ -499,7 +499,7 @@ impl Decodable for Ping { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; b.advance(rem); @@ -554,7 +554,7 @@ impl Decodable for Pong { let b = &mut &**buf; let rlp_head = Header::decode(b)?; if !rlp_head.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } let started_len = b.len(); let mut this = Self { @@ -574,7 +574,7 @@ impl Decodable for Pong { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; b.advance(rem); diff --git a/crates/net/discv4/src/test_utils.rs b/crates/net/discv4/src/test_utils.rs index a75a322e77..15311dd9c0 100644 --- a/crates/net/discv4/src/test_utils.rs +++ b/crates/net/discv4/src/test_utils.rs @@ -167,7 +167,7 @@ impl Stream for MockDiscovery { ping, pong, to: remote_addr, - })); + })) } } Message::Pong(_) | Message::Neighbours(_) => {} @@ -181,7 +181,7 @@ impl Stream for MockDiscovery { return Poll::Ready(Some(MockEvent::Neighbours { nodes, to: remote_addr, - })); + })) } } Message::EnrRequest(_) | Message::EnrResponse(_) => todo!(), diff --git a/crates/net/discv5/src/config.rs b/crates/net/discv5/src/config.rs index 7d3ba6973c..ef89e72da5 100644 --- a/crates/net/discv5/src/config.rs +++ b/crates/net/discv5/src/config.rs @@ -350,8 +350,8 @@ impl Config { /// Returns the IPv4 discovery socket if one is configured. pub const fn ipv4(listen_config: &ListenConfig) -> Option { match listen_config { - ListenConfig::Ipv4 { ip, port } - | ListenConfig::DualStack { ipv4: ip, ipv4_port: port, .. } => { + ListenConfig::Ipv4 { ip, port } | + ListenConfig::DualStack { ipv4: ip, ipv4_port: port, .. } => { Some(SocketAddrV4::new(*ip, *port)) } ListenConfig::Ipv6 { .. } => None, @@ -362,8 +362,8 @@ pub const fn ipv4(listen_config: &ListenConfig) -> Option { pub const fn ipv6(listen_config: &ListenConfig) -> Option { match listen_config { ListenConfig::Ipv4 { .. } => None, - ListenConfig::Ipv6 { ip, port } - | ListenConfig::DualStack { ipv6: ip, ipv6_port: port, .. } => { + ListenConfig::Ipv6 { ip, port } | + ListenConfig::DualStack { ipv6: ip, ipv6_port: port, .. } => { Some(SocketAddrV6::new(*ip, *port, 0, 0)) } } @@ -511,9 +511,9 @@ mod test { for node in config.bootstrap_nodes { let BootNode::Enr(node) = node else { panic!() }; assert!( - socket_1 == node.udp4_socket().unwrap() && socket_1 == node.tcp4_socket().unwrap() - || socket_2 == node.udp4_socket().unwrap() - && socket_2 == node.tcp4_socket().unwrap() + socket_1 == node.udp4_socket().unwrap() && socket_1 == node.tcp4_socket().unwrap() || + socket_2 == node.udp4_socket().unwrap() && + socket_2 == node.tcp4_socket().unwrap() ); assert_eq!("84b4940500", hex::encode(node.get_raw_rlp("opstack").unwrap())); } diff --git a/crates/net/discv5/src/enr.rs b/crates/net/discv5/src/enr.rs index 80bdfb0b3e..02c5ec389b 100644 --- a/crates/net/discv5/src/enr.rs +++ b/crates/net/discv5/src/enr.rs @@ -11,7 +11,7 @@ use secp256k1::{PublicKey, SecretKey}; pub fn enr_to_discv4_id(enr: &discv5::Enr) -> Option { let pk = enr.public_key(); if !matches!(pk, CombinedPublicKey::Secp256k1(_)) { - return None; + return None } let pk = PublicKey::from_slice(&pk.encode()).unwrap(); diff --git a/crates/net/discv5/src/filter.rs b/crates/net/discv5/src/filter.rs index fe6bac9220..a83345a9a5 100644 --- a/crates/net/discv5/src/filter.rs +++ b/crates/net/discv5/src/filter.rs @@ -37,7 +37,7 @@ impl MustIncludeKey { if enr.get_raw_rlp(self.key).is_none() { return FilterOutcome::Ignore { reason: format!("{} fork required", String::from_utf8_lossy(self.key)), - }; + } } FilterOutcome::Ok } @@ -72,7 +72,7 @@ impl MustNotIncludeKeys { "{} forks not allowed", self.keys.iter().map(|key| String::from_utf8_lossy(key.key)).format(",") ), - }; + } } } diff --git a/crates/net/discv5/src/lib.rs b/crates/net/discv5/src/lib.rs index 1bc3f1b6cd..17fa68754e 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -100,7 +100,7 @@ impl Discv5 { err="key not utf-8", "failed to update local enr" ); - return; + return }; if let Err(err) = self.discv5.enr_insert(key_str, &rlp) { error!(target: "net::discv5", @@ -305,7 +305,7 @@ impl Discv5 { self.metrics.discovered_peers.increment_established_sessions_unreachable_enr(1); - return None; + return None } }; if let FilterOutcome::Ignore { reason } = self.filter_discovered_peer(enr) { @@ -317,7 +317,7 @@ impl Discv5 { self.metrics.discovered_peers.increment_established_sessions_filtered(1); - return None; + return None } // todo: extend for all network stacks in reth-network rlpx logic @@ -517,7 +517,7 @@ pub async fn bootstrap( match node { BootNode::Enr(node) => { if let Err(err) = discv5.add_enr(node) { - return Err(Error::AddNodeFailed(err)); + return Err(Error::AddNodeFailed(err)) } } BootNode::Enode(enode) => { diff --git a/crates/net/discv5/src/network_stack_id.rs b/crates/net/discv5/src/network_stack_id.rs index e2125f3d4c..a7b6944f35 100644 --- a/crates/net/discv5/src/network_stack_id.rs +++ b/crates/net/discv5/src/network_stack_id.rs @@ -23,9 +23,9 @@ impl NetworkStackId { /// Returns the [`NetworkStackId`] that matches the given chain spec. pub fn id(chain: impl EthChainSpec) -> Option<&'static [u8]> { if chain.is_optimism() { - return Some(Self::OPEL); + return Some(Self::OPEL) } else if chain.is_ethereum() { - return Some(Self::ETH); + return Some(Self::ETH) } None diff --git a/crates/net/dns/src/lib.rs b/crates/net/dns/src/lib.rs index 9ba887aaf7..14a78ab7cc 100644 --- a/crates/net/dns/src/lib.rs +++ b/crates/net/dns/src/lib.rs @@ -220,7 +220,7 @@ impl DnsDiscoveryService { // already resolved let cached = ResolveEntryResult { entry: Some(Ok(entry)), link, hash, kind }; self.on_resolved_entry(cached); - return; + return } self.queries.resolve_entry(link, hash, kind) } @@ -298,7 +298,7 @@ impl DnsDiscoveryService { loop { // drain buffered events first if let Some(event) = self.queued_events.pop_front() { - return Poll::Ready(event); + return Poll::Ready(event) } // process all incoming commands @@ -351,7 +351,7 @@ impl DnsDiscoveryService { } if !progress && self.queued_events.is_empty() { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/dns/src/query.rs b/crates/net/dns/src/query.rs index aee2196ecb..edf387ec5c 100644 --- a/crates/net/dns/src/query.rs +++ b/crates/net/dns/src/query.rs @@ -75,7 +75,7 @@ impl QueryPool { loop { // drain buffered events first if let Some(event) = self.queued_outcomes.pop_front() { - return Poll::Ready(event); + return Poll::Ready(event) } // queue in new queries if we have capacity @@ -84,10 +84,10 @@ impl QueryPool { if let Some(query) = self.queued_queries.pop_front() { self.rate_limit.tick(); self.active_queries.push(query); - continue 'queries; + continue 'queries } } - break; + break } // advance all queries @@ -102,7 +102,7 @@ impl QueryPool { } if self.queued_outcomes.is_empty() { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/dns/src/sync.rs b/crates/net/dns/src/sync.rs index 06de925d03..5b9453959d 100644 --- a/crates/net/dns/src/sync.rs +++ b/crates/net/dns/src/sync.rs @@ -73,27 +73,27 @@ impl SyncTree { match self.sync_state { SyncState::Pending => { self.sync_state = SyncState::Enr; - return Some(SyncAction::Link(self.root.link_root.clone())); + return Some(SyncAction::Link(self.root.link_root.clone())) } SyncState::Enr => { self.sync_state = SyncState::Active; - return Some(SyncAction::Enr(self.root.enr_root.clone())); + return Some(SyncAction::Enr(self.root.enr_root.clone())) } SyncState::Link => { self.sync_state = SyncState::Active; - return Some(SyncAction::Link(self.root.link_root.clone())); + return Some(SyncAction::Link(self.root.link_root.clone())) } SyncState::Active => { if now > self.root_updated + update_timeout { self.sync_state = SyncState::RootUpdate; - return Some(SyncAction::UpdateRoot); + return Some(SyncAction::UpdateRoot) } } SyncState::RootUpdate => return None, } if let Some(link) = self.unresolved_links.pop_front() { - return Some(SyncAction::Link(link)); + return Some(SyncAction::Link(link)) } let enr = self.unresolved_nodes.pop_front()?; @@ -124,7 +124,7 @@ impl SyncTree { } _ => { // unchanged - return; + return } }; self.sync_state = state; diff --git a/crates/net/dns/src/tree.rs b/crates/net/dns/src/tree.rs index 036725ca6f..822eec327c 100644 --- a/crates/net/dns/src/tree.rs +++ b/crates/net/dns/src/tree.rs @@ -205,7 +205,7 @@ impl BranchEntry { let decoded_len = base32_no_padding_decoded_len(hash.len()); if !(12..=32).contains(&decoded_len) || hash.chars().any(|c| c.is_whitespace()) { - return Err(ParseDnsEntryError::InvalidChildHash(hash.to_string())); + return Err(ParseDnsEntryError::InvalidChildHash(hash.to_string())) } Ok(hash.to_string()) } diff --git a/crates/net/downloaders/src/bodies/bodies.rs b/crates/net/downloaders/src/bodies/bodies.rs index 5fea0b0883..a6e454b041 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -103,7 +103,7 @@ where max_non_empty: u64, ) -> DownloadResult>>> { if range.is_empty() || max_non_empty == 0 { - return Ok(None); + return Ok(None) } // Collect headers while @@ -114,9 +114,9 @@ where let mut collected = 0; let mut non_empty_headers = 0; let headers = self.provider.sealed_headers_while(range.clone(), |header| { - let should_take = range.contains(&header.number()) - && non_empty_headers < max_non_empty - && collected < self.stream_batch_size; + let should_take = range.contains(&header.number()) && + non_empty_headers < max_non_empty && + collected < self.stream_batch_size; if should_take { collected += 1; @@ -152,7 +152,7 @@ where // if we're only connected to a few peers, we keep it low if num_peers < *self.concurrent_requests_range.start() { - return max_requests; + return max_requests } max_requests.min(*self.concurrent_requests_range.end()) @@ -171,10 +171,10 @@ where self.in_progress_queue .last_requested_block_number.is_some_and(|last| last == *self.download_range.end()); - nothing_to_request - && self.in_progress_queue.is_empty() - && self.buffered_responses.is_empty() - && self.queued_bodies.is_empty() + nothing_to_request && + self.in_progress_queue.is_empty() && + self.buffered_responses.is_empty() && + self.queued_bodies.is_empty() } /// Clear all download related data. @@ -216,8 +216,8 @@ where /// Adds a new response to the internal buffer fn buffer_bodies_response(&mut self, response: Vec>) { // take into account capacity - let size = response.iter().map(BlockResponse::size).sum::() - + response.capacity() * mem::size_of::>(); + let size = response.iter().map(BlockResponse::size).sum::() + + response.capacity() * mem::size_of::>(); let response = OrderedBodiesResponse { resp: response, size }; let response_len = response.len(); @@ -244,7 +244,7 @@ where .skip_while(|b| b.block_number() < expected) .take_while(|b| self.download_range.contains(&b.block_number())) .collect() - }); + }) } // Drop buffered response since we passed that range @@ -263,7 +263,7 @@ where self.queued_bodies.shrink_to_fit(); self.metrics.total_flushed.increment(next_batch.len() as u64); self.metrics.queued_blocks.set(self.queued_bodies.len() as f64); - return Some(next_batch); + return Some(next_batch) } None } @@ -276,9 +276,9 @@ where // requests are issued in order but not necessarily finished in order, so the queued bodies // can grow large if a certain request is slow, so we limit the followup requests if the // queued bodies grew too large - self.queued_bodies.len() < 4 * self.stream_batch_size - && self.has_buffer_capacity() - && self.in_progress_queue.len() < self.concurrent_request_limit() + self.queued_bodies.len() < 4 * self.stream_batch_size && + self.has_buffer_capacity() && + self.in_progress_queue.len() < self.concurrent_request_limit() } } @@ -320,16 +320,16 @@ where // Check if the range is valid. if range.is_empty() { tracing::error!(target: "downloaders::bodies", ?range, "Bodies download range is invalid (empty)"); - return Err(DownloadError::InvalidBodyRange { range }); + return Err(DownloadError::InvalidBodyRange { range }) } // Check if the provided range is the subset of the existing range. - let is_current_range_subset = self.download_range.contains(range.start()) - && *range.end() == *self.download_range.end(); + let is_current_range_subset = self.download_range.contains(range.start()) && + *range.end() == *self.download_range.end(); if is_current_range_subset { tracing::trace!(target: "downloaders::bodies", ?range, "Download range already in progress"); // The current range already includes requested. - return Ok(()); + return Ok(()) } // Check if the provided range is the next expected range. @@ -340,7 +340,7 @@ where tracing::trace!(target: "downloaders::bodies", ?range, "New download range set"); info!(target: "downloaders::bodies", count, ?range, "Downloading bodies"); self.download_range = range; - return Ok(()); + return Ok(()) } // The block range is reset. This can happen either after unwind or after the bodies were @@ -364,13 +364,13 @@ where fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if this.is_terminated() { - return Poll::Ready(None); + return Poll::Ready(None) } // Submit new requests and poll any in progress loop { // Yield next batch if ready if let Some(next_batch) = this.try_split_next_batch() { - return Poll::Ready(Some(Ok(next_batch))); + return Poll::Ready(Some(Ok(next_batch))) } // Poll requests @@ -383,7 +383,7 @@ where Err(error) => { tracing::debug!(target: "downloaders::bodies", %error, "Request failed"); this.clear(); - return Poll::Ready(Some(Err(error))); + return Poll::Ready(Some(Err(error))) } }; } @@ -406,7 +406,7 @@ where Err(error) => { tracing::error!(target: "downloaders::bodies", %error, "Failed to download from next request"); this.clear(); - return Poll::Ready(Some(Err(error))); + return Poll::Ready(Some(Err(error))) } }; } @@ -419,21 +419,21 @@ where this.buffered_responses.shrink_to_fit(); if !new_request_submitted { - break; + break } } // All requests are handled, stream is finished if this.in_progress_queue.is_empty() { if this.queued_bodies.is_empty() { - return Poll::Ready(None); + return Poll::Ready(None) } let batch_size = this.stream_batch_size.min(this.queued_bodies.len()); let next_batch = this.queued_bodies.drain(..batch_size).collect::>(); this.queued_bodies.shrink_to_fit(); this.metrics.total_flushed.increment(next_batch.len() as u64); this.metrics.queued_blocks.set(this.queued_bodies.len() as f64); - return Poll::Ready(Some(Ok(next_batch))); + return Poll::Ready(Some(Ok(next_batch))) } Poll::Pending @@ -522,8 +522,8 @@ impl BodiesDownloaderBuilder { .with_request_limit(config.downloader_request_limit) .with_max_buffered_blocks_size_bytes(config.downloader_max_buffered_blocks_size_bytes) .with_concurrent_requests_range( - config.downloader_min_concurrent_requests - ..=config.downloader_max_concurrent_requests, + config.downloader_min_concurrent_requests..= + config.downloader_max_concurrent_requests, ) } } diff --git a/crates/net/downloaders/src/bodies/request.rs b/crates/net/downloaders/src/bodies/request.rs index d06672566b..aa10db382a 100644 --- a/crates/net/downloaders/src/bodies/request.rs +++ b/crates/net/downloaders/src/bodies/request.rs @@ -134,14 +134,14 @@ where // next one exceed the soft response limit, if not then peer either does not have the next // block or deliberately sent a single block. if bodies.is_empty() { - return Err(DownloadError::EmptyResponse); + return Err(DownloadError::EmptyResponse) } if response_len > request_len { return Err(DownloadError::TooManyBodies(GotExpected { got: response_len, expected: request_len, - })); + })) } // Buffer block responses @@ -198,7 +198,7 @@ where hash, number, error: Box::new(error), - }); + }) } self.buffer.push(BlockResponse::Full(block)); @@ -225,7 +225,7 @@ where loop { if this.pending_headers.is_empty() { - return Poll::Ready(Ok(std::mem::take(&mut this.buffer))); + return Poll::Ready(Ok(std::mem::take(&mut this.buffer))) } // Check if there is a pending requests. It might not exist if all @@ -240,7 +240,7 @@ where } Err(error) => { if error.is_channel_closed() { - return Poll::Ready(Err(error.into())); + return Poll::Ready(Err(error.into())) } this.on_error(error.into(), None); diff --git a/crates/net/downloaders/src/bodies/task.rs b/crates/net/downloaders/src/bodies/task.rs index cf75814377..df1d5540db 100644 --- a/crates/net/downloaders/src/bodies/task.rs +++ b/crates/net/downloaders/src/bodies/task.rs @@ -136,13 +136,13 @@ impl Future for SpawnedDownloader { if forward_error_result.is_err() { // channel closed, this means [TaskDownloader] was dropped, // so we can also exit - return Poll::Ready(()); + return Poll::Ready(()) } } } else { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()); + return Poll::Ready(()) } } @@ -152,7 +152,7 @@ impl Future for SpawnedDownloader { if this.bodies_tx.send_item(bodies).is_err() { // channel closed, this means [TaskDownloader] was dropped, so we can // also exit - return Poll::Ready(()); + return Poll::Ready(()) } } None => return Poll::Pending, @@ -160,7 +160,7 @@ impl Future for SpawnedDownloader { Err(_) => { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()); + return Poll::Ready(()) } } } diff --git a/crates/net/downloaders/src/file_client.rs b/crates/net/downloaders/src/file_client.rs index aaa3cc8d88..a0b83d72d4 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -135,7 +135,7 @@ impl FileClient { /// Returns true if all blocks are canonical (no gaps) pub fn has_canonical_blocks(&self) -> bool { if self.headers.is_empty() { - return true; + return true } let mut nums = self.headers.keys().copied().collect::>(); nums.sort_unstable(); @@ -143,7 +143,7 @@ impl FileClient { let mut lowest = iter.next().expect("not empty"); for next in iter { if next != lowest + 1 { - return false; + return false } lowest = next; } @@ -247,7 +247,7 @@ impl> FromReader "partial block returned from decoding chunk" ); remaining_bytes = bytes; - break; + break } Err(err) => return Err(err), }; @@ -317,7 +317,7 @@ impl HeadersClient for FileClient { Some(num) => *num, None => { warn!(%hash, "Could not find starting block number for requested header hash"); - return Box::pin(async move { Err(RequestError::BadResponse) }); + return Box::pin(async move { Err(RequestError::BadResponse) }) } }, BlockHashOrNumber::Number(num) => num, @@ -341,7 +341,7 @@ impl HeadersClient for FileClient { Some(header) => headers.push(header), None => { warn!(number=%block_number, "Could not find header"); - return Box::pin(async move { Err(RequestError::BadResponse) }); + return Box::pin(async move { Err(RequestError::BadResponse) }) } } } @@ -454,7 +454,7 @@ impl ChunkedFileReader { async fn read_next_chunk(&mut self) -> Result, io::Error> { if self.file_byte_len == 0 && self.chunk.is_empty() { // eof - return Ok(None); + return Ok(None) } let chunk_target_len = self.chunk_len(); diff --git a/crates/net/downloaders/src/file_codec.rs b/crates/net/downloaders/src/file_codec.rs index c9ccb2cee9..57a15b6c88 100644 --- a/crates/net/downloaders/src/file_codec.rs +++ b/crates/net/downloaders/src/file_codec.rs @@ -32,7 +32,7 @@ impl Decoder for BlockFileCodec { fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None); + return Ok(None) } let buf_slice = &mut src.as_ref(); diff --git a/crates/net/downloaders/src/headers/reverse_headers.rs b/crates/net/downloaders/src/headers/reverse_headers.rs index bda6d5a70b..5f27467cf8 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -160,7 +160,7 @@ where // If only a few peers are connected we keep it low if num_peers < self.min_concurrent_requests { - return max_dynamic; + return max_dynamic } max_dynamic.min(self.max_concurrent_requests) @@ -183,7 +183,7 @@ where // headers so follow-up requests will use that as start. self.next_request_block_number -= request.limit; - return Some(request); + return Some(request) } } @@ -272,7 +272,7 @@ where trace!(target: "downloaders::headers", %error ,"Failed to validate header"); return Err( HeadersResponseError { request, peer_id: Some(peer_id), error }.into() - ); + ) } } else { self.validate_sync_target(&parent, request.clone(), peer_id)?; @@ -299,7 +299,7 @@ where error: Box::new(error), }, } - .into()); + .into()) } // If the header is valid on its own, but not against its parent, we return it as @@ -324,7 +324,7 @@ where header: Box::new(last_header.clone()), error: Box::new(error), } - .into()); + .into()) } } @@ -397,7 +397,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()); + .into()) } let header = headers.swap_remove(0); @@ -413,7 +413,7 @@ where GotExpected { got: target.hash(), expected: hash }.into(), ), } - .into()); + .into()) } } SyncTargetBlock::Number(number) => { @@ -426,7 +426,7 @@ where expected: number, }), } - .into()); + .into()) } } } @@ -475,7 +475,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()); + .into()) } if (headers.len() as u64) != request.limit { @@ -487,7 +487,7 @@ where }), request, } - .into()); + .into()) } // sort headers from highest to lowest block number @@ -507,7 +507,7 @@ where expected: requested_block_number, }), } - .into()); + .into()) } // check if the response is the next expected @@ -578,7 +578,7 @@ where self.metrics.buffered_responses.decrement(1.); if let Err(err) = self.process_next_headers(request, headers, peer_id) { - return Some(err); + return Some(err) } } Ordering::Greater => { @@ -729,7 +729,7 @@ where .map(|h| h.number()) { self.sync_target = Some(new_sync_target.with_number(target_number)); - return; + return } trace!(target: "downloaders::headers", new=?target, "Request new sync target"); @@ -796,7 +796,7 @@ where sync_target=?this.sync_target, "The downloader sync boundaries have not been set" ); - return Poll::Pending; + return Poll::Pending } // If we have a new tip request we need to complete that first before we send batched @@ -810,7 +810,7 @@ where trace!(target: "downloaders::headers", %error, "invalid sync target response"); if error.is_channel_closed() { // download channel closed which means the network was dropped - return Poll::Ready(None); + return Poll::Ready(None) } this.penalize_peer(error.peer_id, &error.error); @@ -820,13 +820,13 @@ where } Err(ReverseHeadersDownloaderError::Downloader(error)) => { this.clear(); - return Poll::Ready(Some(Err(error))); + return Poll::Ready(Some(Err(error))) } }; } Poll::Pending => { this.sync_target_request = Some(req); - return Poll::Pending; + return Poll::Pending } } } @@ -852,13 +852,13 @@ where Err(ReverseHeadersDownloaderError::Response(error)) => { if error.is_channel_closed() { // download channel closed which means the network was dropped - return Poll::Ready(None); + return Poll::Ready(None) } this.on_headers_error(error); } Err(ReverseHeadersDownloaderError::Downloader(error)) => { this.clear(); - return Poll::Ready(Some(Err(error))); + return Poll::Ready(Some(Err(error))) } }; } @@ -871,8 +871,8 @@ where let concurrent_request_limit = this.concurrent_request_limit(); // populate requests - while this.in_progress_queue.len() < concurrent_request_limit - && this.buffered_responses.len() < this.max_buffered_responses + while this.in_progress_queue.len() < concurrent_request_limit && + this.buffered_responses.len() < this.max_buffered_responses { if let Some(request) = this.next_request() { trace!( @@ -883,7 +883,7 @@ where this.submit_request(request, Priority::Normal); } else { // no more requests - break; + break } } @@ -900,11 +900,11 @@ where trace!(target: "downloaders::headers", batch=%next_batch.len(), "Returning validated batch"); this.metrics.total_flushed.increment(next_batch.len() as u64); - return Poll::Ready(Some(Ok(next_batch))); + return Poll::Ready(Some(Ok(next_batch))) } if !progress { - break; + break } } @@ -913,10 +913,10 @@ where let next_batch = this.split_next_batch(); if next_batch.is_empty() { this.clear(); - return Poll::Ready(None); + return Poll::Ready(None) } this.metrics.total_flushed.increment(next_batch.len() as u64); - return Poll::Ready(Some(Ok(next_batch))); + return Poll::Ready(Some(Ok(next_batch))) } Poll::Pending @@ -1009,7 +1009,7 @@ impl HeadersResponseError { /// Returns true if the error was caused by a closed channel to the network. const fn is_channel_closed(&self) -> bool { if let DownloadError::RequestError(ref err) = self.error { - return err.is_channel_closed(); + return err.is_channel_closed() } false } diff --git a/crates/net/downloaders/src/headers/task.rs b/crates/net/downloaders/src/headers/task.rs index 8a3649cc56..38eb1429a8 100644 --- a/crates/net/downloaders/src/headers/task.rs +++ b/crates/net/downloaders/src/headers/task.rs @@ -133,7 +133,7 @@ impl Future for SpawnedDownloader { Poll::Ready(None) => { // channel closed, this means [TaskDownloader] was dropped, so we can also // exit - return Poll::Ready(()); + return Poll::Ready(()) } Poll::Ready(Some(update)) => match update { DownloaderUpdates::UpdateSyncGap(head, target) => { @@ -159,7 +159,7 @@ impl Future for SpawnedDownloader { if this.headers_tx.send_item(headers).is_err() { // channel closed, this means [TaskDownloader] was dropped, so we // can also exit - return Poll::Ready(()); + return Poll::Ready(()) } } None => return Poll::Pending, @@ -168,7 +168,7 @@ impl Future for SpawnedDownloader { Err(_) => { // channel closed, this means [TaskDownloader] was dropped, so // we can also exit - return Poll::Ready(()); + return Poll::Ready(()) } } } diff --git a/crates/net/downloaders/src/receipt_file_client.rs b/crates/net/downloaders/src/receipt_file_client.rs index cdf774a900..60af1e7027 100644 --- a/crates/net/downloaders/src/receipt_file_client.rs +++ b/crates/net/downloaders/src/receipt_file_client.rs @@ -100,7 +100,7 @@ where remaining_bytes = bytes; - break; + break } Err(err) => return Err(err), }; @@ -109,7 +109,7 @@ where Some(ReceiptWithBlockNumber { receipt, number }) => { if block_number > number { warn!(target: "downloaders::file", previous_block_number = block_number, "skipping receipt from a lower block: {number}"); - continue; + continue } total_receipts += 1; @@ -266,7 +266,7 @@ mod test { fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None); + return Ok(None) } let buf_slice = &mut src.as_ref(); diff --git a/crates/net/downloaders/src/test_utils/bodies_client.rs b/crates/net/downloaders/src/test_utils/bodies_client.rs index 452a6707ac..6b0c65a38a 100644 --- a/crates/net/downloaders/src/test_utils/bodies_client.rs +++ b/crates/net/downloaders/src/test_utils/bodies_client.rs @@ -97,7 +97,7 @@ impl BodiesClient for TestBodiesClient { Box::pin(async move { if should_respond_empty { - return Ok((PeerId::default(), vec![]).into()); + return Ok((PeerId::default(), vec![]).into()) } if should_delay { diff --git a/crates/net/ecies/src/algorithm.rs b/crates/net/ecies/src/algorithm.rs index 0881665f2b..350cd3f7ed 100644 --- a/crates/net/ecies/src/algorithm.rs +++ b/crates/net/ecies/src/algorithm.rs @@ -99,7 +99,7 @@ impl core::fmt::Debug for ECIES { fn split_at_mut(arr: &mut [T], idx: usize) -> Result<(&mut [T], &mut [T]), ECIESError> { if idx > arr.len() { - return Err(ECIESErrorImpl::OutOfBounds { idx, len: arr.len() }.into()); + return Err(ECIESErrorImpl::OutOfBounds { idx, len: arr.len() }.into()) } Ok(arr.split_at_mut(idx)) } @@ -138,7 +138,7 @@ impl<'a> EncryptedMessage<'a> { pub fn parse(data: &mut [u8]) -> Result, ECIESError> { // Auth data is 2 bytes, public key is 65 bytes if data.len() < 65 + 2 { - return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()); + return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()) } let (auth_data, encrypted) = data.split_at_mut(2); @@ -164,7 +164,7 @@ impl<'a> EncryptedMessage<'a> { // now we can check if the encrypted data is long enough to contain the IV if data_iv.len() < 16 { - return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()); + return Err(ECIESErrorImpl::EncryptedDataTooSmall.into()) } let (iv, encrypted_data) = data_iv.split_at_mut(16); @@ -234,7 +234,7 @@ impl<'a> EncryptedMessage<'a> { &self.auth_data, ); if check_tag != self.tag { - return Err(ECIESErrorImpl::TagCheckDecryptFailed.into()); + return Err(ECIESErrorImpl::TagCheckDecryptFailed.into()) } Ok(()) @@ -656,7 +656,7 @@ impl ECIES { // // The header is 16 bytes, and the mac is 16 bytes, so the data must be at least 32 bytes if data.len() < 32 { - return Err(ECIESErrorImpl::InvalidHeader.into()); + return Err(ECIESErrorImpl::InvalidHeader.into()) } let (header_bytes, mac_bytes) = split_at_mut(data, 16)?; @@ -666,12 +666,12 @@ impl ECIES { self.ingress_mac.as_mut().unwrap().update_header(header); let check_mac = self.ingress_mac.as_mut().unwrap().digest(); if check_mac != mac { - return Err(ECIESErrorImpl::TagCheckHeaderFailed.into()); + return Err(ECIESErrorImpl::TagCheckHeaderFailed.into()) } self.ingress_aes.as_mut().unwrap().apply_keystream(header); if header.as_slice().len() < 3 { - return Err(ECIESErrorImpl::InvalidHeader.into()); + return Err(ECIESErrorImpl::InvalidHeader.into()) } let body_size = usize::try_from(header.as_slice().read_uint::(3)?)?; @@ -722,7 +722,7 @@ impl ECIES { self.ingress_mac.as_mut().unwrap().update_body(body); let check_mac = self.ingress_mac.as_mut().unwrap().digest(); if check_mac != mac { - return Err(ECIESErrorImpl::TagCheckBodyFailed.into()); + return Err(ECIESErrorImpl::TagCheckBodyFailed.into()) } let size = self.body_size.unwrap(); diff --git a/crates/net/ecies/src/codec.rs b/crates/net/ecies/src/codec.rs index 99c054906f..b5a10284cf 100644 --- a/crates/net/ecies/src/codec.rs +++ b/crates/net/ecies/src/codec.rs @@ -65,7 +65,7 @@ impl Decoder for ECIESCodec { ECIESState::Auth => { trace!("parsing auth"); if buf.len() < 2 { - return Ok(None); + return Ok(None) } let payload_size = u16::from_be_bytes([buf[0], buf[1]]) as usize; @@ -73,18 +73,18 @@ impl Decoder for ECIESCodec { if buf.len() < total_size { trace!("current len {}, need {}", buf.len(), total_size); - return Ok(None); + return Ok(None) } self.ecies.read_auth(&mut buf.split_to(total_size))?; self.state = ECIESState::InitialHeader; - return Ok(Some(IngressECIESValue::AuthReceive(self.ecies.remote_id()))); + return Ok(Some(IngressECIESValue::AuthReceive(self.ecies.remote_id()))) } ECIESState::Ack => { trace!("parsing ack with len {}", buf.len()); if buf.len() < 2 { - return Ok(None); + return Ok(None) } let payload_size = u16::from_be_bytes([buf[0], buf[1]]) as usize; @@ -92,18 +92,18 @@ impl Decoder for ECIESCodec { if buf.len() < total_size { trace!("current len {}, need {}", buf.len(), total_size); - return Ok(None); + return Ok(None) } self.ecies.read_ack(&mut buf.split_to(total_size))?; self.state = ECIESState::InitialHeader; - return Ok(Some(IngressECIESValue::Ack)); + return Ok(Some(IngressECIESValue::Ack)) } ECIESState::InitialHeader => { if buf.len() < ECIES::header_len() { trace!("current len {}, need {}", buf.len(), ECIES::header_len()); - return Ok(None); + return Ok(None) } let body_size = @@ -115,7 +115,7 @@ impl Decoder for ECIESCodec { body_size, max_body_size: MAX_INITIAL_HANDSHAKE_SIZE, } - .into()); + .into()) } self.state = ECIESState::Body; @@ -123,7 +123,7 @@ impl Decoder for ECIESCodec { ECIESState::Header => { if buf.len() < ECIES::header_len() { trace!("current len {}, need {}", buf.len(), ECIES::header_len()); - return Ok(None); + return Ok(None) } self.ecies.read_header(&mut buf.split_to(ECIES::header_len()))?; @@ -132,7 +132,7 @@ impl Decoder for ECIESCodec { } ECIESState::Body => { if buf.len() < self.ecies.body_len() { - return Ok(None); + return Ok(None) } let mut data = buf.split_to(self.ecies.body_len()); @@ -140,7 +140,7 @@ impl Decoder for ECIESCodec { ret.extend_from_slice(self.ecies.read_body(&mut data)?); self.state = ECIESState::Header; - return Ok(Some(IngressECIESValue::Message(ret))); + return Ok(Some(IngressECIESValue::Message(ret))) } } } diff --git a/crates/net/eth-wire-types/src/broadcast.rs b/crates/net/eth-wire-types/src/broadcast.rs index c963636e57..c877b673c7 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -33,7 +33,7 @@ impl NewBlockHashes { pub fn latest(&self) -> Option<&BlockHashNumber> { self.0.iter().fold(None, |latest, block| { if let Some(latest) = latest { - return if latest.number > block.number { Some(latest) } else { Some(block) }; + return if latest.number > block.number { Some(latest) } else { Some(block) } } Some(block) }) @@ -480,13 +480,13 @@ impl Decodable for NewPooledTransactionHashes68 { return Err(alloy_rlp::Error::ListLengthMismatch { expected: msg.hashes.len(), got: msg.types.len(), - }); + }) } if msg.hashes.len() != msg.sizes.len() { return Err(alloy_rlp::Error::ListLengthMismatch { expected: msg.hashes.len(), got: msg.sizes.len(), - }); + }) } Ok(msg) @@ -759,7 +759,7 @@ impl RequestTxHashes { pub fn retain_count(&mut self, count: usize) -> Self { let rest_capacity = self.hashes.len().saturating_sub(count); if rest_capacity == 0 { - return Self::empty(); + return Self::empty() } let mut rest = Self::with_capacity(rest_capacity); @@ -767,7 +767,7 @@ impl RequestTxHashes { self.hashes.retain(|hash| { if i >= count { rest.insert(*hash); - return false; + return false } i += 1; diff --git a/crates/net/eth-wire-types/src/disconnect_reason.rs b/crates/net/eth-wire-types/src/disconnect_reason.rs index c877e1d4c0..5efa9e571c 100644 --- a/crates/net/eth-wire-types/src/disconnect_reason.rs +++ b/crates/net/eth-wire-types/src/disconnect_reason.rs @@ -96,9 +96,9 @@ impl Decodable for DisconnectReason { /// reason encoded a single byte or a RLP list containing the disconnect reason. fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { if buf.is_empty() { - return Err(alloy_rlp::Error::InputTooShort); + return Err(alloy_rlp::Error::InputTooShort) } else if buf.len() > 2 { - return Err(alloy_rlp::Error::Overflow); + return Err(alloy_rlp::Error::Overflow) } if buf.len() > 1 { @@ -107,14 +107,14 @@ impl Decodable for DisconnectReason { let header = Header::decode(buf)?; if !header.list { - return Err(alloy_rlp::Error::UnexpectedString); + return Err(alloy_rlp::Error::UnexpectedString) } if header.payload_length != 1 { return Err(alloy_rlp::Error::ListLengthMismatch { expected: 1, got: header.payload_length, - }); + }) } } diff --git a/crates/net/eth-wire-types/src/message.rs b/crates/net/eth-wire-types/src/message.rs index 29e3cea740..0e54b86222 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -101,13 +101,13 @@ impl ProtocolMessage { } EthMessageID::GetNodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) } EthMessage::GetNodeData(RequestPair::decode(buf)?) } EthMessageID::NodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) } EthMessage::NodeData(RequestPair::decode(buf)?) } @@ -122,7 +122,7 @@ impl ProtocolMessage { } EthMessageID::BlockRangeUpdate => { if version < EthVersion::Eth69 { - return Err(MessageError::Invalid(version, EthMessageID::BlockRangeUpdate)); + return Err(MessageError::Invalid(version, EthMessageID::BlockRangeUpdate)) } EthMessage::BlockRangeUpdate(BlockRangeUpdate::decode(buf)?) } @@ -311,11 +311,11 @@ impl EthMessage { pub const fn is_request(&self) -> bool { matches!( self, - Self::GetBlockBodies(_) - | Self::GetBlockHeaders(_) - | Self::GetReceipts(_) - | Self::GetPooledTransactions(_) - | Self::GetNodeData(_) + Self::GetBlockBodies(_) | + Self::GetBlockHeaders(_) | + Self::GetReceipts(_) | + Self::GetPooledTransactions(_) | + Self::GetNodeData(_) ) } @@ -323,12 +323,12 @@ impl EthMessage { pub const fn is_response(&self) -> bool { matches!( self, - Self::PooledTransactions(_) - | Self::Receipts(_) - | Self::Receipts69(_) - | Self::BlockHeaders(_) - | Self::BlockBodies(_) - | Self::NodeData(_) + Self::PooledTransactions(_) | + Self::Receipts(_) | + Self::Receipts69(_) | + Self::BlockHeaders(_) | + Self::BlockBodies(_) | + Self::NodeData(_) ) } } @@ -627,7 +627,7 @@ where // RequestPair let consumed_len = initial_length - buf.len(); if consumed_len != header.payload_length { - return Err(alloy_rlp::Error::UnexpectedLength); + return Err(alloy_rlp::Error::UnexpectedLength) } Ok(Self { request_id, message }) diff --git a/crates/net/eth-wire/src/capability.rs b/crates/net/eth-wire/src/capability.rs index 775715d178..97e15dbe1f 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -58,7 +58,7 @@ impl SharedCapability { messages: u8, ) -> Result { if offset <= MAX_RESERVED_MESSAGE_ID { - return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)); + return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)) } match name { @@ -214,12 +214,12 @@ impl SharedCapabilities { let mut cap = iter.next()?; if offset < cap.message_id_offset() { // reserved message id space - return None; + return None } for next in iter { if offset < next.message_id_offset() { - return Some(cap); + return Some(cap) } cap = next } @@ -303,7 +303,7 @@ pub fn shared_capability_offsets( // disconnect if we don't share any capabilities if shared_capabilities.is_empty() { - return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)); + return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)) } // order versions based on capability name (alphabetical) and select offsets based on @@ -327,7 +327,7 @@ pub fn shared_capability_offsets( } if shared_with_offsets.is_empty() { - return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)); + return Err(P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities)) } Ok(shared_with_offsets) diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index 32ecace3ce..5e3cbbdb9a 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -66,7 +66,7 @@ impl EthStreamError { /// Returns the [`io::Error`] if it was caused by IO pub const fn as_io(&self) -> Option<&io::Error> { if let Self::P2PStreamError(P2PStreamError::Io(io)) = self { - return Some(io); + return Some(io) } None } diff --git a/crates/net/eth-wire/src/errors/p2p.rs b/crates/net/eth-wire/src/errors/p2p.rs index f6b98c2776..c77816b48b 100644 --- a/crates/net/eth-wire/src/errors/p2p.rs +++ b/crates/net/eth-wire/src/errors/p2p.rs @@ -82,8 +82,8 @@ impl P2PStreamError { /// Returns the [`DisconnectReason`] if it is the `Disconnected` variant. pub const fn as_disconnected(&self) -> Option { let reason = match self { - Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) - | Self::Disconnected(reason) => reason, + Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) | + Self::Disconnected(reason) => reason, _ => return None, }; diff --git a/crates/net/eth-wire/src/eth_snap_stream.rs b/crates/net/eth-wire/src/eth_snap_stream.rs index 384779843b..000e161510 100644 --- a/crates/net/eth-wire/src/eth_snap_stream.rs +++ b/crates/net/eth-wire/src/eth_snap_stream.rs @@ -236,9 +236,9 @@ where Err(EthSnapStreamError::InvalidMessage(self.eth_version, err.to_string())) } } - } else if message_id > EthMessageID::max(self.eth_version) - && message_id - <= EthMessageID::max(self.eth_version) + 1 + SnapMessageId::TrieNodes as u8 + } else if message_id > EthMessageID::max(self.eth_version) && + message_id <= + EthMessageID::max(self.eth_version) + 1 + SnapMessageId::TrieNodes as u8 { // Checks for multiplexed snap message IDs : // - message_id > EthMessageID::max() : ensures it's not an eth message @@ -405,8 +405,8 @@ mod tests { // This should be decoded as eth message let eth_boundary_result = inner.decode_message(eth_boundary_bytes); assert!( - eth_boundary_result.is_err() - || matches!(eth_boundary_result, Ok(EthSnapMessage::Eth(_))) + eth_boundary_result.is_err() || + matches!(eth_boundary_result, Ok(EthSnapMessage::Eth(_))) ); // Create a bytes buffer with message ID just above eth max, it should be snap min diff --git a/crates/net/eth-wire/src/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index 20ee7fd640..415603c8c2 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -289,7 +289,7 @@ where // allowing for its start_disconnect method to be called. // // self.project().inner.start_disconnect(DisconnectReason::ProtocolBreach); - return Err(EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake)); + return Err(EthStreamError::EthHandshakeError(EthHandshakeError::StatusNotInHandshake)) } self.project() diff --git a/crates/net/eth-wire/src/multiplex.rs b/crates/net/eth-wire/src/multiplex.rs index 6616d85f97..d44f5ea7eb 100644 --- a/crates/net/eth-wire/src/multiplex.rs +++ b/crates/net/eth-wire/src/multiplex.rs @@ -81,7 +81,7 @@ impl RlpxProtocolMultiplexer { { let Ok(shared_cap) = self.shared_capabilities().ensure_matching_capability(cap).cloned() else { - return Err(P2PStreamError::CapabilityNotShared); + return Err(P2PStreamError::CapabilityNotShared) }; let (to_primary, from_wire) = mpsc::unbounded_channel(); @@ -149,7 +149,7 @@ impl RlpxProtocolMultiplexer { { let Ok(shared_cap) = self.shared_capabilities().ensure_matching_capability(cap).cloned() else { - return Err(P2PStreamError::CapabilityNotShared.into()); + return Err(P2PStreamError::CapabilityNotShared.into()) }; let (to_primary, from_wire) = mpsc::unbounded_channel(); @@ -245,7 +245,7 @@ impl MultiplexInner { for proto in &self.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - return true; + return true } } false @@ -301,7 +301,7 @@ impl ProtocolProxy { fn try_send(&self, msg: Bytes) -> Result<(), io::Error> { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()); + return Err(io::ErrorKind::InvalidInput.into()) } self.to_wire.send(self.mask_msg_id(msg)?).map_err(|_| io::ErrorKind::BrokenPipe.into()) } @@ -311,7 +311,7 @@ impl ProtocolProxy { fn mask_msg_id(&self, msg: Bytes) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()); + return Err(io::ErrorKind::InvalidInput.into()) } let offset = self.shared_cap.relative_message_id_offset(); @@ -329,7 +329,7 @@ impl ProtocolProxy { fn unmask_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()); + return Err(io::ErrorKind::InvalidInput.into()) } msg[0] = msg[0] .checked_sub(self.shared_cap.relative_message_id_offset()) @@ -463,7 +463,7 @@ where loop { // first drain the primary stream if let Poll::Ready(Some(msg)) = this.primary.st.try_poll_next_unpin(cx) { - return Poll::Ready(Some(msg)); + return Poll::Ready(Some(msg)) } let mut conn_ready = true; @@ -472,23 +472,23 @@ where Poll::Ready(Ok(())) => { if let Some(msg) = this.inner.out_buffer.pop_front() { if let Err(err) = this.inner.conn.start_send_unpin(msg) { - return Poll::Ready(Some(Err(err.into()))); + return Poll::Ready(Some(Err(err.into()))) } } else { - break; + break } } Poll::Ready(Err(err)) => { if let Err(disconnect_err) = this.inner.conn.start_disconnect(DisconnectReason::DisconnectRequested) { - return Poll::Ready(Some(Err(disconnect_err.into()))); + return Poll::Ready(Some(Err(disconnect_err.into()))) } - return Poll::Ready(Some(Err(err.into()))); + return Poll::Ready(Some(Err(err.into()))) } Poll::Pending => { conn_ready = false; - break; + break } } } @@ -501,7 +501,7 @@ where } Poll::Ready(None) => { // primary closed - return Poll::Ready(None); + return Poll::Ready(None) } Poll::Pending => break, } @@ -521,7 +521,7 @@ where Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => { this.inner.protocols.push(proto); - break; + break } } } @@ -536,7 +536,7 @@ where let Some(offset) = msg.first().copied() else { return Poll::Ready(Some(Err( P2PStreamError::EmptyProtocolMessage.into() - ))); + ))) }; // delegate the multiplexed message to the correct protocol if let Some(cap) = @@ -550,27 +550,28 @@ where for proto in &this.inner.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - break; + break } } } } else { - return Poll::Ready(Some(Err( - P2PStreamError::UnknownReservedMessageId(offset).into(), - ))); + return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId( + offset, + ) + .into()))) } } Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err.into()))), Poll::Ready(None) => { // connection closed - return Poll::Ready(None); + return Poll::Ready(None) } Poll::Pending => break, } } if !conn_ready || (!delegated && this.inner.out_buffer.is_empty()) { - return Poll::Pending; + return Poll::Pending } } } @@ -587,10 +588,10 @@ where fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Err(err) = ready!(this.inner.conn.poll_ready_unpin(cx)) { - return Poll::Ready(Err(err.into())); + return Poll::Ready(Err(err.into())) } if let Err(err) = ready!(this.primary.st.poll_ready_unpin(cx)) { - return Poll::Ready(Err(err)); + return Poll::Ready(Err(err)) } Poll::Ready(Ok(())) } @@ -622,7 +623,7 @@ impl ProtocolStream { fn mask_msg_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()); + return Err(io::ErrorKind::InvalidInput.into()) } msg[0] = msg[0] .checked_add(self.shared_cap.relative_message_id_offset()) @@ -635,7 +636,7 @@ impl ProtocolStream { fn unmask_id(&self, mut msg: BytesMut) -> Result { if msg.is_empty() { // message must not be empty - return Err(io::ErrorKind::InvalidInput.into()); + return Err(io::ErrorKind::InvalidInput.into()) } msg[0] = msg[0] .checked_sub(self.shared_cap.relative_message_id_offset()) diff --git a/crates/net/eth-wire/src/p2pstream.rs b/crates/net/eth-wire/src/p2pstream.rs index cde7d30912..e794795b1c 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -107,7 +107,7 @@ where return Err(P2PStreamError::MessageTooBig { message_size: first_message_bytes.len(), max_size: MAX_PAYLOAD_SIZE, - }); + }) } // The first message sent MUST be a hello OR disconnect message @@ -149,7 +149,7 @@ where return Err(P2PStreamError::MismatchedProtocolVersion(GotExpected { got: their_hello.protocol_version, expected: hello.protocol_version, - })); + })) } // determine shared capabilities (currently returns only one capability) @@ -394,7 +394,7 @@ where if this.disconnecting { // if disconnecting, stop reading messages - return Poll::Ready(None); + return Poll::Ready(None) } // we should loop here to ensure we don't return Poll::Pending if we have a message to @@ -408,7 +408,7 @@ where if bytes.is_empty() { // empty messages are not allowed - return Poll::Ready(Some(Err(P2PStreamError::EmptyProtocolMessage))); + return Poll::Ready(Some(Err(P2PStreamError::EmptyProtocolMessage))) } // first decode disconnect reasons, because they can be encoded in a variety of forms @@ -429,7 +429,7 @@ where // message is snappy compressed. Failure handling in that step is the primary point // where an error is returned if the disconnect reason is malformed. if let Ok(reason) = DisconnectReason::decode(&mut &bytes[1..]) { - return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))); + return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))) } } @@ -440,7 +440,7 @@ where return Poll::Ready(Some(Err(P2PStreamError::MessageTooBig { message_size: decompressed_len, max_size: MAX_PAYLOAD_SIZE, - }))); + }))) } // create a buffer to hold the decompressed message, adding a byte to the length for @@ -471,7 +471,7 @@ where // an error return Poll::Ready(Some(Err(P2PStreamError::HandshakeError( P2PHandshakeError::HelloNotInHandshake, - )))); + )))) } _ if id == P2PMessageID::Pong as u8 => { // if we were waiting for a pong, this will reset the pinger state @@ -488,11 +488,11 @@ where %err, msg=%hex::encode(&decompress_buf[1..]), "Failed to decode disconnect message from peer" ); })?; - return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))); + return Poll::Ready(Some(Err(P2PStreamError::Disconnected(reason)))) } _ if id > MAX_P2P_MESSAGE_ID && id <= MAX_RESERVED_MESSAGE_ID => { // we have received an unknown reserved message - return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId(id)))); + return Poll::Ready(Some(Err(P2PStreamError::UnknownReservedMessageId(id)))) } _ => { // we have received a message that is outside the `p2p` reserved message space, @@ -520,7 +520,7 @@ where // decompress_buf[0] = bytes[0] - MAX_RESERVED_MESSAGE_ID - 1; - return Poll::Ready(Some(Ok(decompress_buf))); + return Poll::Ready(Some(Ok(decompress_buf))) } } } @@ -549,7 +549,7 @@ where this.start_disconnect(DisconnectReason::PingTimeout)?; // End the stream after ping related error - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } @@ -559,7 +559,7 @@ where Poll::Ready(Ok(())) => { let flushed = this.poll_flush(cx); if flushed.is_ready() { - return flushed; + return flushed } } } @@ -577,17 +577,17 @@ where return Err(P2PStreamError::MessageTooBig { message_size: item.len(), max_size: MAX_PAYLOAD_SIZE, - }); + }) } if item.is_empty() { // empty messages are not allowed - return Err(P2PStreamError::EmptyProtocolMessage); + return Err(P2PStreamError::EmptyProtocolMessage) } // ensure we have free capacity if !self.has_outgoing_capacity() { - return Err(P2PStreamError::SendBufferFull); + return Err(P2PStreamError::SendBufferFull) } let this = self.project(); @@ -624,10 +624,10 @@ where Poll::Ready(Err(err)) => break Poll::Ready(Err(err.into())), Poll::Ready(Ok(())) => { let Some(message) = this.outgoing_messages.pop_front() else { - break Poll::Ready(Ok(())); + break Poll::Ready(Ok(())) }; if let Err(err) = this.inner.as_mut().start_send(message) { - break Poll::Ready(Err(err.into())); + break Poll::Ready(Err(err.into())) } } } @@ -725,10 +725,10 @@ impl Decodable for P2PMessage { /// Removes the snappy prefix from the Ping/Pong buffer fn advance_snappy_ping_pong_payload(buf: &mut &[u8]) -> alloy_rlp::Result<()> { if buf.len() < 3 { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } if buf[..3] != [0x01, 0x00, EMPTY_LIST_CODE] { - return Err(RlpError::Custom("expected snappy payload")); + return Err(RlpError::Custom("expected snappy payload")) } buf.advance(3); Ok(()) diff --git a/crates/net/eth-wire/src/pinger.rs b/crates/net/eth-wire/src/pinger.rs index 90ac45831d..d93404c5f9 100644 --- a/crates/net/eth-wire/src/pinger.rs +++ b/crates/net/eth-wire/src/pinger.rs @@ -73,19 +73,19 @@ impl Pinger { if self.ping_interval.poll_tick(cx).is_ready() { self.timeout_timer.as_mut().reset(Instant::now() + self.timeout); self.state = PingState::WaitingForPong; - return Poll::Ready(Ok(PingerEvent::Ping)); + return Poll::Ready(Ok(PingerEvent::Ping)) } } PingState::WaitingForPong => { if self.timeout_timer.is_elapsed() { self.state = PingState::TimedOut; - return Poll::Ready(Ok(PingerEvent::Timeout)); + return Poll::Ready(Ok(PingerEvent::Timeout)) } } PingState::TimedOut => { // we treat continuous calls while in timeout as pending, since the connection is // not yet terminated - return Poll::Pending; + return Poll::Pending } }; Poll::Pending diff --git a/crates/net/eth-wire/src/test_utils.rs b/crates/net/eth-wire/src/test_utils.rs index e539900372..0cf96484f1 100644 --- a/crates/net/eth-wire/src/test_utils.rs +++ b/crates/net/eth-wire/src/test_utils.rs @@ -142,7 +142,7 @@ pub mod proto { /// Decodes a `TestProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None; + return None } let id = buf[0]; buf.advance(1); diff --git a/crates/net/nat/src/lib.rs b/crates/net/nat/src/lib.rs index 24db5c0003..c7466b4401 100644 --- a/crates/net/nat/src/lib.rs +++ b/crates/net/nat/src/lib.rs @@ -109,7 +109,7 @@ impl FromStr for NatResolver { let Some(ip) = s.strip_prefix("extip:") else { return Err(ParseNatResolverError::UnknownVariant(format!( "Unknown Nat Resolver: {s}" - ))); + ))) }; Self::ExternalIp(ip.parse()?) } diff --git a/crates/net/network-types/src/peers/mod.rs b/crates/net/network-types/src/peers/mod.rs index 4afd0e83be..f352987501 100644 --- a/crates/net/network-types/src/peers/mod.rs +++ b/crates/net/network-types/src/peers/mod.rs @@ -96,15 +96,15 @@ impl Peer { if self.state.is_connected() && self.is_banned() { self.state.disconnect(); - return ReputationChangeOutcome::DisconnectAndBan; + return ReputationChangeOutcome::DisconnectAndBan } if self.is_banned() && !is_banned_reputation(previous) { - return ReputationChangeOutcome::Ban; + return ReputationChangeOutcome::Ban } if !self.is_banned() && is_banned_reputation(previous) { - return ReputationChangeOutcome::Unban; + return ReputationChangeOutcome::Unban } ReputationChangeOutcome::None diff --git a/crates/net/network/src/discovery.rs b/crates/net/network/src/discovery.rs index 70b364e49d..5809380aa8 100644 --- a/crates/net/network/src/discovery.rs +++ b/crates/net/network/src/discovery.rs @@ -215,7 +215,7 @@ impl Discovery { let tcp_addr = record.tcp_addr(); if tcp_addr.port() == 0 { // useless peer for p2p - return; + return } let udp_addr = record.udp_addr(); let addr = PeerAddr::new(tcp_addr, Some(udp_addr)); @@ -253,7 +253,7 @@ impl Discovery { // Drain all buffered events first if let Some(event) = self.queued_events.pop_front() { self.notify_listeners(&event); - return Poll::Ready(event); + return Poll::Ready(event) } // drain the discv4 update stream @@ -291,7 +291,7 @@ impl Discovery { } if self.queued_events.is_empty() { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/network/src/error.rs b/crates/net/network/src/error.rs index 8698ac5e93..96ba2ff85e 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -72,7 +72,7 @@ impl NetworkError { ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err }, _ => { if let ServiceKind::Discovery(address) = kind { - return Self::Discovery(address, err); + return Self::Discovery(address, err) } Self::Io(err) } @@ -110,8 +110,8 @@ impl SessionError for EthStreamError { fn merits_discovery_ban(&self) -> bool { match self { Self::P2PStreamError(P2PStreamError::HandshakeError( - P2PHandshakeError::HelloNotInHandshake - | P2PHandshakeError::NonHelloMessageInHandshake, + P2PHandshakeError::HelloNotInHandshake | + P2PHandshakeError::NonHelloMessageInHandshake, )) => true, Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), _ => false, @@ -124,24 +124,24 @@ impl SessionError for EthStreamError { matches!( err, P2PStreamError::HandshakeError( - P2PHandshakeError::NoSharedCapabilities - | P2PHandshakeError::HelloNotInHandshake - | P2PHandshakeError::NonHelloMessageInHandshake - | P2PHandshakeError::Disconnected( - DisconnectReason::UselessPeer - | DisconnectReason::IncompatibleP2PProtocolVersion - | DisconnectReason::ProtocolBreach + P2PHandshakeError::NoSharedCapabilities | + P2PHandshakeError::HelloNotInHandshake | + P2PHandshakeError::NonHelloMessageInHandshake | + P2PHandshakeError::Disconnected( + DisconnectReason::UselessPeer | + DisconnectReason::IncompatibleP2PProtocolVersion | + DisconnectReason::ProtocolBreach ) - ) | P2PStreamError::UnknownReservedMessageId(_) - | P2PStreamError::EmptyProtocolMessage - | P2PStreamError::ParseSharedCapability(_) - | P2PStreamError::CapabilityNotShared - | P2PStreamError::Disconnected( - DisconnectReason::UselessPeer - | DisconnectReason::IncompatibleP2PProtocolVersion - | DisconnectReason::ProtocolBreach - ) - | P2PStreamError::MismatchedProtocolVersion { .. } + ) | P2PStreamError::UnknownReservedMessageId(_) | + P2PStreamError::EmptyProtocolMessage | + P2PStreamError::ParseSharedCapability(_) | + P2PStreamError::CapabilityNotShared | + P2PStreamError::Disconnected( + DisconnectReason::UselessPeer | + DisconnectReason::IncompatibleP2PProtocolVersion | + DisconnectReason::ProtocolBreach + ) | + P2PStreamError::MismatchedProtocolVersion { .. } ) } Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), @@ -151,50 +151,50 @@ impl SessionError for EthStreamError { fn should_backoff(&self) -> Option { if let Some(err) = self.as_io() { - return err.should_backoff(); + return err.should_backoff() } if let Some(err) = self.as_disconnected() { return match err { - DisconnectReason::TooManyPeers - | DisconnectReason::AlreadyConnected - | DisconnectReason::PingTimeout - | DisconnectReason::DisconnectRequested - | DisconnectReason::TcpSubsystemError => Some(BackoffKind::Low), + DisconnectReason::TooManyPeers | + DisconnectReason::AlreadyConnected | + DisconnectReason::PingTimeout | + DisconnectReason::DisconnectRequested | + DisconnectReason::TcpSubsystemError => Some(BackoffKind::Low), - DisconnectReason::ProtocolBreach - | DisconnectReason::UselessPeer - | DisconnectReason::IncompatibleP2PProtocolVersion - | DisconnectReason::NullNodeIdentity - | DisconnectReason::ClientQuitting - | DisconnectReason::UnexpectedHandshakeIdentity - | DisconnectReason::ConnectedToSelf - | DisconnectReason::SubprotocolSpecific => { + DisconnectReason::ProtocolBreach | + DisconnectReason::UselessPeer | + DisconnectReason::IncompatibleP2PProtocolVersion | + DisconnectReason::NullNodeIdentity | + DisconnectReason::ClientQuitting | + DisconnectReason::UnexpectedHandshakeIdentity | + DisconnectReason::ConnectedToSelf | + DisconnectReason::SubprotocolSpecific => { // These are considered fatal, and are handled by the // [`SessionError::is_fatal_protocol_error`] Some(BackoffKind::High) } - }; + } } // This only checks for a subset of error variants, the counterpart of // [`SessionError::is_fatal_protocol_error`] match self { // timeouts - Self::EthHandshakeError(EthHandshakeError::NoResponse) - | Self::P2PStreamError( - P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse) - | P2PStreamError::PingTimeout, + Self::EthHandshakeError(EthHandshakeError::NoResponse) | + Self::P2PStreamError( + P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse) | + P2PStreamError::PingTimeout, ) => Some(BackoffKind::Low), // malformed messages Self::P2PStreamError( - P2PStreamError::Rlp(_) - | P2PStreamError::UnknownReservedMessageId(_) - | P2PStreamError::UnknownDisconnectReason(_) - | P2PStreamError::MessageTooBig { .. } - | P2PStreamError::EmptyProtocolMessage - | P2PStreamError::PingerError(_) - | P2PStreamError::Snap(_), + P2PStreamError::Rlp(_) | + P2PStreamError::UnknownReservedMessageId(_) | + P2PStreamError::UnknownDisconnectReason(_) | + P2PStreamError::MessageTooBig { .. } | + P2PStreamError::EmptyProtocolMessage | + P2PStreamError::PingerError(_) | + P2PStreamError::Snap(_), ) => Some(BackoffKind::Medium), _ => None, } @@ -207,14 +207,14 @@ impl SessionError for PendingSessionHandshakeError { Self::Eth(eth) => eth.merits_discovery_ban(), Self::Ecies(err) => matches!( err.inner(), - ECIESErrorImpl::TagCheckDecryptFailed - | ECIESErrorImpl::TagCheckHeaderFailed - | ECIESErrorImpl::TagCheckBodyFailed - | ECIESErrorImpl::InvalidAuthData - | ECIESErrorImpl::InvalidAckData - | ECIESErrorImpl::InvalidHeader - | ECIESErrorImpl::Secp256k1(_) - | ECIESErrorImpl::InvalidHandshake { .. } + ECIESErrorImpl::TagCheckDecryptFailed | + ECIESErrorImpl::TagCheckHeaderFailed | + ECIESErrorImpl::TagCheckBodyFailed | + ECIESErrorImpl::InvalidAuthData | + ECIESErrorImpl::InvalidAckData | + ECIESErrorImpl::InvalidHeader | + ECIESErrorImpl::Secp256k1(_) | + ECIESErrorImpl::InvalidHandshake { .. } ), Self::Timeout | Self::UnsupportedExtraCapability => false, } @@ -225,14 +225,14 @@ impl SessionError for PendingSessionHandshakeError { Self::Eth(eth) => eth.is_fatal_protocol_error(), Self::Ecies(err) => matches!( err.inner(), - ECIESErrorImpl::TagCheckDecryptFailed - | ECIESErrorImpl::TagCheckHeaderFailed - | ECIESErrorImpl::TagCheckBodyFailed - | ECIESErrorImpl::InvalidAuthData - | ECIESErrorImpl::InvalidAckData - | ECIESErrorImpl::InvalidHeader - | ECIESErrorImpl::Secp256k1(_) - | ECIESErrorImpl::InvalidHandshake { .. } + ECIESErrorImpl::TagCheckDecryptFailed | + ECIESErrorImpl::TagCheckHeaderFailed | + ECIESErrorImpl::TagCheckBodyFailed | + ECIESErrorImpl::InvalidAuthData | + ECIESErrorImpl::InvalidAckData | + ECIESErrorImpl::InvalidHeader | + ECIESErrorImpl::Secp256k1(_) | + ECIESErrorImpl::InvalidHandshake { .. } ), Self::Timeout => false, Self::UnsupportedExtraCapability => true, diff --git a/crates/net/network/src/eth_requests.rs b/crates/net/network/src/eth_requests.rs index 64aa5b2da7..39e485318b 100644 --- a/crates/net/network/src/eth_requests.rs +++ b/crates/net/network/src/eth_requests.rs @@ -93,7 +93,7 @@ where BlockHashOrNumber::Hash(start) => start.into(), BlockHashOrNumber::Number(num) => { let Some(hash) = self.client.block_hash(num).unwrap_or_default() else { - return headers; + return headers }; hash.into() } @@ -109,7 +109,7 @@ where if let Some(next) = (header.number() + 1).checked_add(skip) { block = next.into() } else { - break; + break } } HeadersDirection::Falling => { @@ -121,7 +121,7 @@ where { block = next.into() } else { - break; + break } } else { block = header.parent_hash().into() @@ -133,10 +133,10 @@ where headers.push(header); if headers.len() >= MAX_HEADERS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } @@ -172,10 +172,10 @@ where bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } @@ -231,10 +231,10 @@ where receipts.push(transformed_receipts); if receipts.len() >= MAX_RECEIPTS_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index 82a74f9fe6..794c184e69 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -127,7 +127,7 @@ impl StateFetcher { if number > peer.best_number { peer.best_hash = hash; peer.best_number = number; - return true; + return true } } false @@ -152,12 +152,12 @@ impl StateFetcher { // replace best peer if our current best peer sent us a bad response last time if best_peer.1.last_response_likely_bad && !maybe_better.1.last_response_likely_bad { best_peer = maybe_better; - continue; + continue } // replace best peer if this peer has better rtt - if maybe_better.1.timeout() < best_peer.1.timeout() - && !maybe_better.1.last_response_likely_bad + if maybe_better.1.timeout() < best_peer.1.timeout() && + !maybe_better.1.last_response_likely_bad { best_peer = maybe_better; } @@ -170,7 +170,7 @@ impl StateFetcher { fn poll_action(&mut self) -> PollAction { // we only check and not pop here since we don't know yet whether a peer is available. if self.queued_requests.is_empty() { - return PollAction::NoRequests; + return PollAction::NoRequests } let Some(peer_id) = self.next_best_peer() else { return PollAction::NoPeersAvailable }; @@ -217,7 +217,7 @@ impl StateFetcher { } if self.queued_requests.is_empty() || no_peers_available { - return Poll::Pending; + return Poll::Pending } } } @@ -292,7 +292,7 @@ impl StateFetcher { // If the peer is still ready to accept new requests, we try to send a followup // request immediately. if peer.state.on_request_finished() && !is_error && !is_likely_bad_response { - return self.followup_request(peer_id); + return self.followup_request(peer_id) } } @@ -318,7 +318,7 @@ impl StateFetcher { peer.last_response_likely_bad = is_likely_bad_response; if peer.state.on_request_finished() && !is_likely_bad_response { - return self.followup_request(peer_id); + return self.followup_request(peer_id) } } None @@ -399,7 +399,7 @@ impl PeerState { const fn on_request_finished(&mut self) -> bool { if !matches!(self, Self::Closing) { *self = Self::Idle; - return true; + return true } false } diff --git a/crates/net/network/src/manager.rs b/crates/net/network/src/manager.rs index 1ff8b06886..aee8218382 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -650,7 +650,7 @@ impl NetworkManager { if self.handle.mode().is_stake() { // See [EIP-3675](https://eips.ethereum.org/EIPS/eip-3675#devp2p) warn!(target: "net", "Peer performed block propagation, but it is not supported in proof of stake (EIP-3675)"); - return; + return } let msg = NewBlockMessage { hash, block: Arc::new(block) }; self.swarm.state_mut().announce_new_block(msg); @@ -1142,7 +1142,7 @@ impl Future for NetworkManager { if maybe_more_handle_messages || maybe_more_swarm_events { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } this.update_poll_metrics(start, poll_durations); diff --git a/crates/net/network/src/network.rs b/crates/net/network/src/network.rs index f60a025684..ffe8bf1531 100644 --- a/crates/net/network/src/network.rs +++ b/crates/net/network/src/network.rs @@ -413,7 +413,7 @@ impl SyncStateProvider for NetworkHandle { // used to guard the txpool fn is_initially_syncing(&self) -> bool { if self.inner.initial_sync_done.load(Ordering::Relaxed) { - return false; + return false } self.inner.is_syncing.load(Ordering::Relaxed) } diff --git a/crates/net/network/src/peers.rs b/crates/net/network/src/peers.rs index 715648cfd4..c0694023ce 100644 --- a/crates/net/network/src/peers.rs +++ b/crates/net/network/src/peers.rs @@ -244,7 +244,7 @@ impl PeersManager { addr: IpAddr, ) -> Result<(), InboundConnectionError> { if self.ban_list.is_banned_ip(&addr) { - return Err(InboundConnectionError::IpBanned); + return Err(InboundConnectionError::IpBanned) } // check if we even have slots for a new incoming connection @@ -252,7 +252,7 @@ impl PeersManager { if self.trusted_peer_ids.is_empty() { // if we don't have any incoming slots and no trusted peers, we don't accept any new // connections - return Err(InboundConnectionError::ExceedsCapacity); + return Err(InboundConnectionError::ExceedsCapacity) } // there's an edge case here where no incoming connections besides from trusted peers @@ -265,17 +265,17 @@ impl PeersManager { self.trusted_peer_ids.len().max(self.connection_info.config.max_inbound); if self.connection_info.num_pending_in < max_inbound { self.connection_info.inc_pending_in(); - return Ok(()); + return Ok(()) } } // all trusted peers are either connected or connecting - return Err(InboundConnectionError::ExceedsCapacity); + return Err(InboundConnectionError::ExceedsCapacity) } // also cap the incoming connections we can process at once if !self.connection_info.has_in_pending_capacity() { - return Err(InboundConnectionError::ExceedsCapacity); + return Err(InboundConnectionError::ExceedsCapacity) } // apply the rate limit @@ -327,14 +327,14 @@ impl PeersManager { // on_incoming_pending_session. We also check if the peer is in the backoff list here. if self.ban_list.is_banned_peer(&peer_id) { self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id }); - return; + return } // check if the peer is trustable or not let mut is_trusted = self.trusted_peer_ids.contains(&peer_id); if self.trusted_nodes_only && !is_trusted { self.queued_actions.push_back(PeerAction::DisconnectUntrustedIncoming { peer_id }); - return; + return } // start a new tick, so the peer is not immediately rewarded for the time since last tick @@ -345,7 +345,7 @@ impl PeersManager { let peer = entry.get_mut(); if peer.is_banned() { self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id }); - return; + return } // it might be the case that we're also trying to connect to this peer at the same // time, so we need to adjust the state here @@ -466,12 +466,12 @@ impl PeersManager { // exempt trusted and static peers from reputation slashing for if matches!( rep, - ReputationChangeKind::Dropped - | ReputationChangeKind::BadAnnouncement - | ReputationChangeKind::Timeout - | ReputationChangeKind::AlreadySeenTransaction + ReputationChangeKind::Dropped | + ReputationChangeKind::BadAnnouncement | + ReputationChangeKind::Timeout | + ReputationChangeKind::AlreadySeenTransaction ) { - return; + return } // also be less strict with the reputation slashing for trusted peers @@ -483,7 +483,7 @@ impl PeersManager { peer.apply_reputation(reputation_change, rep) } } else { - return; + return }; match outcome { @@ -537,7 +537,7 @@ impl PeersManager { // session to that peer entry.get_mut().severe_backoff_counter = 0; entry.get_mut().state = PeerConnectionState::Idle; - return; + return } } Entry::Vacant(_) => return, @@ -582,7 +582,7 @@ impl PeersManager { if let Some(peer) = self.peers.get(peer_id) { if peer.state.is_incoming() { // we already have an active connection to the peer, so we can ignore this error - return; + return } if peer.is_trusted() && is_connection_failed_reputation(peer.reputation) { @@ -663,9 +663,9 @@ impl PeersManager { self.connection_info.decr_state(peer.state); peer.state = PeerConnectionState::Idle; - if peer.severe_backoff_counter > self.max_backoff_count - && !peer.is_trusted() - && !peer.is_static() + if peer.severe_backoff_counter > self.max_backoff_count && + !peer.is_trusted() && + !peer.is_static() { // mark peer for removal if it has been backoff too many times and is _not_ // trusted or static @@ -746,7 +746,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.tcp().ip()) { - return; + return } match self.peers.entry(peer_id) { @@ -781,7 +781,7 @@ impl PeersManager { pub(crate) fn remove_peer(&mut self, peer_id: PeerId) { let Entry::Occupied(entry) = self.peers.entry(peer_id) else { return }; if entry.get().is_trusted() { - return; + return } let mut peer = entry.remove(); @@ -827,7 +827,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.tcp().ip()) { - return; + return } match self.peers.entry(peer_id) { @@ -866,7 +866,7 @@ impl PeersManager { pub(crate) fn remove_peer_from_trusted_set(&mut self, peer_id: PeerId) { let Entry::Occupied(mut entry) = self.peers.entry(peer_id) else { return }; if !entry.get().is_trusted() { - return; + return } let peer = entry.get_mut(); @@ -886,23 +886,23 @@ impl PeersManager { /// Returns `None` if no peer is available. fn best_unconnected(&mut self) -> Option<(PeerId, &mut Peer)> { let mut unconnected = self.peers.iter_mut().filter(|(_, peer)| { - !peer.is_backed_off() - && !peer.is_banned() - && peer.state.is_unconnected() - && (!self.trusted_nodes_only || peer.is_trusted()) + !peer.is_backed_off() && + !peer.is_banned() && + peer.state.is_unconnected() && + (!self.trusted_nodes_only || peer.is_trusted()) }); // keep track of the best peer, if there's one let mut best_peer = unconnected.next()?; if best_peer.1.is_trusted() || best_peer.1.is_static() { - return Some((*best_peer.0, best_peer.1)); + return Some((*best_peer.0, best_peer.1)) } for maybe_better in unconnected { // if the peer is trusted or static, return it immediately if maybe_better.1.is_trusted() || maybe_better.1.is_static() { - return Some((*maybe_better.0, maybe_better.1)); + return Some((*maybe_better.0, maybe_better.1)) } // otherwise we keep track of the best peer using the reputation @@ -923,7 +923,7 @@ impl PeersManager { if !self.net_connection_state.is_active() { // nothing to fill - return; + return } // as long as there are slots available fill them with the best peers @@ -984,7 +984,7 @@ impl PeersManager { loop { // drain buffered actions if let Some(action) = self.queued_actions.pop_front() { - return Poll::Ready(action); + return Poll::Ready(action) } while let Poll::Ready(Some(cmd)) = self.handle_rx.poll_next_unpin(cx) { @@ -1023,7 +1023,7 @@ impl PeersManager { if let Some(peer) = self.peers.get_mut(peer_id) { peer.backed_off = false; } - return false; + return false } true }) @@ -1038,7 +1038,7 @@ impl PeersManager { } if self.queued_actions.is_empty() { - return Poll::Pending; + return Poll::Pending } } } @@ -1075,8 +1075,8 @@ impl ConnectionInfo { /// Returns `true` if there's still capacity to perform an outgoing connection. const fn has_out_capacity(&self) -> bool { - self.num_pending_out < self.config.max_concurrent_outbound_dials - && self.num_outbound < self.config.max_outbound + self.num_pending_out < self.config.max_concurrent_outbound_dials && + self.num_outbound < self.config.max_outbound } /// Returns `true` if there's still capacity to accept a new incoming connection. @@ -2038,7 +2038,7 @@ mod tests { let p = peers.peers.get(&peer).unwrap(); if p.is_banned() { - break; + break } } diff --git a/crates/net/network/src/session/active.rs b/crates/net/network/src/session/active.rs index 54102e8d93..827c4bfb19 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -238,7 +238,7 @@ impl ActiveSession { sizes_len: msg.sizes.len(), }, message: EthMessage::NewPooledTransactionHashes68(msg), - }; + } } self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into() } @@ -353,8 +353,8 @@ impl ActiveSession { /// Returns the deadline timestamp at which the request times out fn request_deadline(&self) -> Instant { - Instant::now() - + Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed)) + Instant::now() + + Duration::from_millis(self.internal_request_timeout.load(Ordering::Relaxed)) } /// Handle a Response to the peer @@ -499,7 +499,7 @@ impl ActiveSession { debug!(target: "net::session", ?id, remote_peer_id=?self.remote_peer_id, "timed out outgoing request"); req.timeout(); } else if now - req.timestamp > self.protocol_breach_request_timeout { - return true; + return true } } } @@ -523,7 +523,7 @@ impl ActiveSession { match tx.poll_reserve(cx) { Poll::Pending => { self.terminate_message = Some((tx, msg)); - return Some(Poll::Pending); + return Some(Poll::Pending) } Poll::Ready(Ok(())) => { let _ = tx.send_item(msg); @@ -545,11 +545,11 @@ impl Future for ActiveSession { // if the session is terminate we have to send the termination message before we can close if let Some(terminate) = this.poll_terminate_message(cx) { - return terminate; + return terminate } if this.is_disconnecting() { - return this.poll_disconnect(cx); + return this.poll_disconnect(cx) } // The receive loop can be CPU intensive since it involves message decoding which could take @@ -570,7 +570,7 @@ impl Future for ActiveSession { Poll::Ready(None) => { // this is only possible when the manager was dropped, in which case we also // terminate this session - return Poll::Ready(()); + return Poll::Ready(()) } Poll::Ready(Some(cmd)) => { progress = true; @@ -585,7 +585,7 @@ impl Future for ActiveSession { let reason = reason.unwrap_or(DisconnectReason::DisconnectRequested); - return this.try_disconnect(reason, cx); + return this.try_disconnect(reason, cx) } SessionCommand::Message(msg) => { this.on_internal_peer_message(msg); @@ -629,11 +629,11 @@ impl Future for ActiveSession { if let Err(err) = res { debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to send message"); // notify the manager - return this.close_on_error(err, cx); + return this.close_on_error(err, cx) } } else { // no more messages to send over the wire - break; + break } } @@ -644,7 +644,7 @@ impl Future for ActiveSession { if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - break 'main; + break 'main } // try to resend the pending message that we could not send because the channel was @@ -658,7 +658,7 @@ impl Future for ActiveSession { Poll::Ready(Err(_)) => return Poll::Ready(()), Poll::Pending => { this.pending_message_to_session = Some(msg); - break 'receive; + break 'receive } }; } @@ -670,12 +670,12 @@ impl Future for ActiveSession { // // Note: we don't need to register the waker here because we polled the requests // above - break 'receive; + break 'receive } // we also need to check if we have multiple responses queued up - if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES - && this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES + if this.queued_outgoing.messages.len() > MAX_QUEUED_OUTGOING_RESPONSES && + this.queued_response_count() > MAX_QUEUED_OUTGOING_RESPONSES { // if we've queued up more responses than allowed, we don't poll for new // messages and break the receive loop early @@ -683,17 +683,17 @@ impl Future for ActiveSession { // Note: we don't need to register the waker here because we still have // queued messages and the sink impl registered the waker because we've // already advanced it to `Pending` earlier - break 'receive; + break 'receive } match this.conn.poll_next_unpin(cx) { Poll::Pending => break, Poll::Ready(None) => { if this.is_disconnecting() { - break; + break } debug!(target: "net::session", remote_peer_id=?this.remote_peer_id, "eth stream completed"); - return this.emit_disconnect(cx); + return this.emit_disconnect(cx) } Poll::Ready(Some(res)) => { match res { @@ -707,7 +707,7 @@ impl Future for ActiveSession { } OnIncomingMessageOutcome::BadMessage { error, message } => { debug!(target: "net::session", %error, msg=?message, remote_peer_id=?this.remote_peer_id, "received invalid protocol message"); - return this.close_on_error(error, cx); + return this.close_on_error(error, cx) } OnIncomingMessageOutcome::NoCapacity(msg) => { // failed to send due to lack of capacity @@ -717,7 +717,7 @@ impl Future for ActiveSession { } Err(err) => { debug!(target: "net::session", %err, remote_peer_id=?this.remote_peer_id, "failed to receive message"); - return this.close_on_error(err, cx); + return this.close_on_error(err, cx) } } } @@ -725,7 +725,7 @@ impl Future for ActiveSession { } if !progress { - break 'main; + break 'main } } @@ -1262,7 +1262,7 @@ mod tests { .try_send(ActiveSessionMessage::ProtocolBreach { peer_id: PeerId::random() }) .is_err() { - break; + break } num_fill_messages += 1; } diff --git a/crates/net/network/src/session/counter.rs b/crates/net/network/src/session/counter.rs index f8fd73c678..215c7279d1 100644 --- a/crates/net/network/src/session/counter.rs +++ b/crates/net/network/src/session/counter.rs @@ -82,7 +82,7 @@ impl SessionCounter { const fn ensure(current: u32, limit: Option) -> Result<(), ExceedsSessionLimit> { if let Some(limit) = limit { if current >= limit { - return Err(ExceedsSessionLimit(limit)); + return Err(ExceedsSessionLimit(limit)) } } Ok(()) diff --git a/crates/net/network/src/session/mod.rs b/crates/net/network/src/session/mod.rs index 2d6df058a5..5aad90cbb6 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -409,7 +409,7 @@ impl SessionManager { ) { if !self.disconnections_counter.has_capacity() { // drop the connection if we don't have capacity for gracefully disconnecting - return; + return } let guard = self.disconnections_counter.clone(); @@ -517,7 +517,7 @@ impl SessionManager { peer_id, remote_addr, direction, - }); + }) } let (commands_to_session, commands_rx) = mpsc::channel(self.session_command_buffer); @@ -930,7 +930,7 @@ async fn start_pending_outbound_session( error, }) .await; - return; + return } }; authenticate( @@ -978,7 +978,7 @@ async fn authenticate( direction, }) .await; - return; + return } }; diff --git a/crates/net/network/src/state.rs b/crates/net/network/src/state.rs index 8146fb3fa8..89ad4874cc 100644 --- a/crates/net/network/src/state.rs +++ b/crates/net/network/src/state.rs @@ -211,7 +211,7 @@ impl NetworkState { for (peer_id, peer) in peers { if peer.blocks.contains(&msg.hash) { // skip peers which already reported the block - continue; + continue } // Queue a `NewBlock` message for the peer @@ -231,7 +231,7 @@ impl NetworkState { } if count >= num_propagate { - break; + break } } } @@ -244,7 +244,7 @@ impl NetworkState { for (peer_id, peer) in &mut self.active_peers { if peer.blocks.contains(&msg.hash) { // skip peers which already reported the block - continue; + continue } if self.state_fetcher.update_peer_block(peer_id, msg.hash, number) { @@ -351,8 +351,8 @@ impl NetworkState { self.state_fetcher.on_pending_disconnect(&peer_id); self.queued_messages.push_back(StateAction::Disconnect { peer_id, reason }); } - PeerAction::DisconnectBannedIncoming { peer_id } - | PeerAction::DisconnectUntrustedIncoming { peer_id } => { + PeerAction::DisconnectBannedIncoming { peer_id } | + PeerAction::DisconnectUntrustedIncoming { peer_id } => { self.state_fetcher.on_pending_disconnect(&peer_id); self.queued_messages.push_back(StateAction::Disconnect { peer_id, reason: None }); } @@ -433,7 +433,7 @@ impl NetworkState { loop { // drain buffered messages if let Some(message) = self.queued_messages.pop_front() { - return Poll::Ready(message); + return Poll::Ready(message) } while let Poll::Ready(discovery) = self.discovery.poll(cx) { @@ -503,7 +503,7 @@ impl NetworkState { // We need to poll again tn case we have received any responses because they may have // triggered follow-up requests. if self.queued_messages.is_empty() { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/network/src/swarm.rs b/crates/net/network/src/swarm.rs index 8f3526cb4c..fbb7b0bf94 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -187,7 +187,7 @@ impl Swarm { ListenerEvent::Incoming { stream, remote_addr } => { // Reject incoming connection if node is shutting down. if self.is_shutting_down() { - return None; + return None } // ensure we can handle an incoming connection from this address if let Err(err) = @@ -205,13 +205,13 @@ impl Swarm { ); } } - return None; + return None } match self.sessions.on_incoming(stream, remote_addr) { Ok(session_id) => { trace!(target: "net", ?remote_addr, "Incoming connection"); - return Some(SwarmEvent::IncomingTcpConnection { session_id, remote_addr }); + return Some(SwarmEvent::IncomingTcpConnection { session_id, remote_addr }) } Err(err) => { trace!(target: "net", %err, "Incoming connection rejected, capacity already reached."); @@ -230,7 +230,7 @@ impl Swarm { match event { StateAction::Connect { remote_addr, peer_id } => { self.dial_outbound(remote_addr, peer_id); - return Some(SwarmEvent::OutgoingTcpConnection { remote_addr, peer_id }); + return Some(SwarmEvent::OutgoingTcpConnection { remote_addr, peer_id }) } StateAction::Disconnect { peer_id, reason } => { self.sessions.disconnect(peer_id, reason); @@ -248,7 +248,7 @@ impl Swarm { StateAction::DiscoveredNode { peer_id, addr, fork_id } => { // Don't try to connect to peer if node is shutting down if self.is_shutting_down() { - return None; + return None } // Insert peer only if no fork id or a valid fork id if fork_id.map_or_else(|| true, |f| self.sessions.is_valid_fork_id(f)) { @@ -302,7 +302,7 @@ impl Stream for Swarm { loop { while let Poll::Ready(action) = this.state.poll(cx) { if let Some(event) = this.on_state_action(action) { - return Poll::Ready(Some(event)); + return Poll::Ready(Some(event)) } } @@ -311,9 +311,9 @@ impl Stream for Swarm { Poll::Pending => {} Poll::Ready(event) => { if let Some(event) = this.on_session_event(event) { - return Poll::Ready(Some(event)); + return Poll::Ready(Some(event)) } - continue; + continue } } @@ -322,13 +322,13 @@ impl Stream for Swarm { Poll::Pending => {} Poll::Ready(event) => { if let Some(event) = this.on_connection(event) { - return Poll::Ready(Some(event)); + return Poll::Ready(Some(event)) } - continue; + continue } } - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/network/src/test_utils/init.rs b/crates/net/network/src/test_utils/init.rs index 7adad9c5fa..51537f37d8 100644 --- a/crates/net/network/src/test_utils/init.rs +++ b/crates/net/network/src/test_utils/init.rs @@ -42,7 +42,7 @@ pub fn unused_tcp_and_udp_port() -> u16 { loop { let port = unused_port(); if std::net::UdpSocket::bind(format!("127.0.0.1:{port}")).is_ok() { - return port; + return port } } } diff --git a/crates/net/network/src/test_utils/testnet.rs b/crates/net/network/src/test_utils/testnet.rs index b1bece61ac..d064ed7eda 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -367,7 +367,7 @@ impl TestnetHandle { /// Returns once all sessions are established. pub async fn connect_peers(&self) { if self.peers.len() < 2 { - return; + return } // add an event stream for _each_ peer @@ -750,7 +750,7 @@ impl NetworkEventStream { pub async fn next_session_closed(&mut self) -> Option<(PeerId, Option)> { while let Some(ev) = self.inner.next().await { if let NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, reason }) = ev { - return Some((peer_id, reason)); + return Some((peer_id, reason)) } } None @@ -760,8 +760,8 @@ impl NetworkEventStream { pub async fn next_session_established(&mut self) -> Option { while let Some(ev) = self.inner.next().await { match ev { - NetworkEvent::ActivePeerSession { info, .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { return Some(info.peer_id) } _ => {} diff --git a/crates/net/network/src/transactions/constants.rs b/crates/net/network/src/transactions/constants.rs index 7f43a2c2bf..905c5931e9 100644 --- a/crates/net/network/src/transactions/constants.rs +++ b/crates/net/network/src/transactions/constants.rs @@ -137,8 +137,8 @@ pub mod tx_fetcher { /// [`DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES`], which is 25600 hashes and /// 65 requests, so it is 25665 hashes. pub const DEFAULT_MAX_CAPACITY_CACHE_INFLIGHT_AND_PENDING_FETCH: u32 = - DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH - + DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES as u32; + DEFAULT_MAX_CAPACITY_CACHE_PENDING_FETCH + + DEFAULT_MAX_COUNT_INFLIGHT_REQUESTS_ON_FETCH_PENDING_HASHES as u32; /// Default maximum number of hashes pending fetch to tolerate at any time. /// @@ -189,8 +189,8 @@ pub mod tx_fetcher { /// which defaults to 128 KiB, so 64 KiB. pub const DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES: usize = - DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ - / 2; + DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESP_ON_PACK_GET_POOLED_TRANSACTIONS_REQ / + 2; /// Default max inflight request when fetching pending hashes. /// @@ -239,8 +239,8 @@ pub mod tx_fetcher { /// divided by [`SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE`], which /// is spec'd at 4096 hashes, so 521 bytes. pub const AVERAGE_BYTE_SIZE_TX_ENCODED: usize = - SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE - / SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE; + SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE / + SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE; /// Median observed size in bytes of a small encoded legacy transaction. /// diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index 1de3675ecb..2656840128 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -162,7 +162,7 @@ impl TransactionFetcher { if let Some(inflight_count) = self.active_peers.get(peer_id) { *inflight_count = inflight_count.saturating_sub(1); if *inflight_count == 0 { - return true; + return true } } false @@ -178,7 +178,7 @@ impl TransactionFetcher { pub fn is_idle(&self, peer_id: &PeerId) -> bool { let Some(inflight_count) = self.active_peers.peek(peer_id) else { return true }; if *inflight_count < self.info.max_inflight_requests_per_peer { - return true; + return true } false } @@ -190,7 +190,7 @@ impl TransactionFetcher { for peer_id in fallback_peers.iter() { if self.is_idle(peer_id) { - return Some(peer_id); + return Some(peer_id) } } @@ -216,13 +216,13 @@ impl TransactionFetcher { if idle_peer.is_some() { hashes_to_request.insert(hash); - break idle_peer.copied(); + break idle_peer.copied() } if let Some(ref mut bud) = budget { *bud = bud.saturating_sub(1); if *bud == 0 { - return None; + return None } } }; @@ -245,7 +245,7 @@ impl TransactionFetcher { hashes_from_announcement: ValidAnnouncementData, ) -> RequestTxHashes { if hashes_from_announcement.msg_version().is_eth68() { - return self.pack_request_eth68(hashes_to_request, hashes_from_announcement); + return self.pack_request_eth68(hashes_to_request, hashes_from_announcement) } self.pack_request_eth66(hashes_to_request, hashes_from_announcement) } @@ -275,7 +275,7 @@ impl TransactionFetcher { // tx is really big, pack request with single tx if size >= self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request { - return hashes_from_announcement_iter.collect(); + return hashes_from_announcement_iter.collect() } acc_size_response = size; } @@ -293,8 +293,8 @@ impl TransactionFetcher { let next_acc_size = acc_size_response + size; - if next_acc_size - <= self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request + if next_acc_size <= + self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request { // only update accumulated size of tx response if tx will fit in without exceeding // soft limit @@ -305,11 +305,11 @@ impl TransactionFetcher { } let free_space = - self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request - - acc_size_response; + self.info.soft_limit_byte_size_pooled_transactions_response_on_pack_request - + acc_size_response; if free_space < MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED { - break; + break } } @@ -356,7 +356,7 @@ impl TransactionFetcher { hashes.retain(|hash| { if let Some(entry) = self.hashes_fetch_inflight_and_pending_fetch.get(hash) { entry.fallback_peers_mut().remove(peer_failed_to_serve); - return true; + return true } // tx has been seen over broadcast in the time it took for the request to resolve false @@ -383,13 +383,13 @@ impl TransactionFetcher { for hash in hashes { // hash could have been evicted from bounded lru map if self.hashes_fetch_inflight_and_pending_fetch.peek(&hash).is_none() { - continue; + continue } let Some(TxFetchMetadata { retries, fallback_peers, .. }) = self.hashes_fetch_inflight_and_pending_fetch.get(&hash) else { - return; + return }; if let Some(peer_id) = fallback_peer { @@ -405,7 +405,7 @@ impl TransactionFetcher { self.hashes_fetch_inflight_and_pending_fetch.remove(&hash); self.hashes_pending_fetch.remove(&hash); - continue; + continue } *retries += 1; } @@ -443,7 +443,7 @@ impl TransactionFetcher { budget_find_idle_fallback_peer, ) else { // no peers are idle or budget is depleted - return; + return }; peer_id @@ -601,7 +601,7 @@ impl TransactionFetcher { max_inflight_transaction_requests=self.info.max_inflight_requests, "limit for concurrent `GetPooledTransactions` requests reached, dropping request for hashes to peer" ); - return Some(new_announced_hashes); + return Some(new_announced_hashes) } let Some(inflight_count) = self.active_peers.get_or_insert(peer_id, || 0) else { @@ -611,7 +611,7 @@ impl TransactionFetcher { conn_eth_version=%conn_eth_version, "failed to cache active peer in schnellru::LruMap, dropping request to peer" ); - return Some(new_announced_hashes); + return Some(new_announced_hashes) }; if *inflight_count >= self.info.max_inflight_requests_per_peer { @@ -622,7 +622,7 @@ impl TransactionFetcher { max_concurrent_tx_reqs_per_peer=self.info.max_inflight_requests_per_peer, "limit for concurrent `GetPooledTransactions` requests per peer reached" ); - return Some(new_announced_hashes); + return Some(new_announced_hashes) } #[cfg(debug_assertions)] @@ -655,7 +655,7 @@ impl TransactionFetcher { self.metrics.egress_peer_channel_full.increment(1); Some(new_announced_hashes) } - }; + } } *inflight_count += 1; @@ -699,10 +699,10 @@ impl TransactionFetcher { .unwrap_or(AVERAGE_BYTE_SIZE_TX_ENCODED); // if request full enough already, we're satisfied, send request for single tx - if acc_size_response - >= DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES + if acc_size_response >= + DEFAULT_SOFT_LIMIT_BYTE_SIZE_POOLED_TRANSACTIONS_RESPONSE_ON_FETCH_PENDING_HASHES { - return; + return } // try to fill request by checking if any other hashes pending fetch (in lru order) are @@ -710,7 +710,7 @@ impl TransactionFetcher { for hash in self.hashes_pending_fetch.iter() { // 1. Check if a hash pending fetch is seen by peer. if !seen_hashes.contains(hash) { - continue; + continue }; // 2. Optimistically include the hash in the request. @@ -739,7 +739,7 @@ impl TransactionFetcher { if let Some(ref mut bud) = budget_fill_request { *bud -= 1; if *bud == 0 { - break; + break } } } @@ -775,8 +775,8 @@ impl TransactionFetcher { let info = &self.info; let tx_fetcher_has_capacity = self.has_capacity( - info.max_inflight_requests - / DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_IDLE_PEER, + info.max_inflight_requests / + DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_IDLE_PEER, ); let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports( DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_IDLE_PEER, @@ -814,8 +814,8 @@ impl TransactionFetcher { let info = &self.info; let tx_fetcher_has_capacity = self.has_capacity( - info.max_inflight_requests - / DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_INTERSECTION, + info.max_inflight_requests / + DEFAULT_DIVISOR_MAX_COUNT_INFLIGHT_REQUESTS_ON_FIND_INTERSECTION, ); let tx_pool_has_capacity = has_capacity_wrt_pending_pool_imports( DEFAULT_DIVISOR_MAX_COUNT_PENDING_POOL_IMPORTS_ON_FIND_INTERSECTION, @@ -866,7 +866,7 @@ impl TransactionFetcher { "received empty `PooledTransactions` response from peer, peer failed to serve hashes it announced" ); - return FetchEvent::EmptyResponse { peer_id }; + return FetchEvent::EmptyResponse { peer_id } } // @@ -897,7 +897,7 @@ impl TransactionFetcher { // peer has only sent hashes that we didn't request if verified_payload.is_empty() { - return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse }; + return FetchEvent::FetchError { peer_id, error: RequestError::BadResponse } } // @@ -933,7 +933,7 @@ impl TransactionFetcher { if valid_payload.contains_key(requested_hash) { // hash is now known, stop tracking fetched.push(*requested_hash); - return false; + return false } true }); @@ -979,11 +979,11 @@ impl Stream for TransactionFetcher { // `FuturesUnordered` doesn't close when `None` is returned. so just return pending. // if self.inflight_requests.is_empty() { - return Poll::Pending; + return Poll::Pending } if let Some(resp) = ready!(self.inflight_requests.poll_next_unpin(cx)) { - return Poll::Ready(Some(self.on_resolved_get_pooled_transactions_request_fut(resp))); + return Poll::Ready(Some(self.on_resolved_get_pooled_transactions_request_fut(resp))) } Poll::Pending @@ -1190,7 +1190,7 @@ impl VerifyPooledTransactionsResponse for UnverifiedPooled tx_hashes_not_requested_count += 1; } - return false; + return false } true }); diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index ab4ea570d8..18233700e2 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -131,7 +131,7 @@ impl TransactionsHandle { pub fn propagate_hashes_to(&self, hash: impl IntoIterator, peer: PeerId) { let hashes = hash.into_iter().collect::>(); if hashes.is_empty() { - return; + return } self.send(TransactionsCommand::PropagateHashesTo(hashes, peer)) } @@ -148,7 +148,7 @@ impl TransactionsHandle { /// Do nothing if transactions are empty. pub fn propagate_transactions_to(&self, transactions: Vec, peer: PeerId) { if transactions.is_empty() { - return; + return } self.send(TransactionsCommand::PropagateTransactionsTo(transactions, peer)) } @@ -159,7 +159,7 @@ impl TransactionsHandle { /// full. pub fn propagate_transactions(&self, transactions: Vec) { if transactions.is_empty() { - return; + return } self.send(TransactionsCommand::PropagateTransactions(transactions)) } @@ -175,7 +175,7 @@ impl TransactionsHandle { let transactions = transactions.into_iter().map(PropagateTransaction::new).collect::>(); if transactions.is_empty() { - return; + return } self.send(TransactionsCommand::BroadcastTransactions(transactions)) } @@ -186,7 +186,7 @@ impl TransactionsHandle { peers: Vec, ) -> Result>, RecvError> { if peers.is_empty() { - return Ok(Default::default()); + return Ok(Default::default()) } let (tx, rx) = oneshot::channel(); self.send(TransactionsCommand::GetTransactionHashes { peers, tx }); @@ -440,8 +440,8 @@ impl /// `false` if [`TransactionsManager`] is operating close to full capacity. fn has_capacity_for_fetching_pending_hashes(&self) -> bool { self.pending_pool_imports_info - .has_capacity(self.pending_pool_imports_info.max_pending_pool_imports) - && self.transaction_fetcher.has_capacity_for_fetching_pending_hashes() + .has_capacity(self.pending_pool_imports_info.max_pending_pool_imports) && + self.transaction_fetcher.has_capacity_for_fetching_pending_hashes() } fn report_peer_bad_transactions(&self, peer_id: PeerId) { @@ -492,7 +492,7 @@ impl // if we're _currently_ syncing, we ignore a bad transaction if !err.is_bad_transaction() || self.network.is_syncing() { - return; + return } // otherwise we penalize the peer that sent the bad transaction, with the assumption that // the peer should have known that this transaction is bad (e.g. violating consensus rules) @@ -523,7 +523,7 @@ impl RequestError::Timeout => ReputationChangeKind::Timeout, RequestError::ChannelClosed | RequestError::ConnectionDropped => { // peer is already disconnected - return; + return } RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id), }; @@ -582,10 +582,10 @@ impl ) { // If the node is initially syncing, ignore transactions if self.network.is_initially_syncing() { - return; + return } if self.network.tx_gossip_disabled() { - return; + return } // get handle to peer's session, if the session is still active @@ -596,7 +596,7 @@ impl "discarding announcement from inactive peer" ); - return; + return }; let client = peer.client_version.clone(); @@ -662,7 +662,7 @@ impl if partially_valid_msg.is_empty() { // nothing to request - return; + return } // 4. filter out invalid entries (spam) @@ -732,7 +732,7 @@ impl if valid_announcement_data.is_empty() { // no valid announcement data - return; + return } // 5. filter out already seen unknown hashes @@ -751,7 +751,7 @@ impl if valid_announcement_data.is_empty() { // nothing to request - return; + return } trace!(target: "net::tx::propagation", @@ -780,7 +780,7 @@ impl self.transaction_fetcher.buffer_hashes(hashes, Some(peer_id)); - return; + return } let mut hashes_to_request = @@ -854,10 +854,10 @@ where fn on_new_pending_transactions(&mut self, hashes: Vec) { // Nothing to propagate while initially syncing if self.network.is_initially_syncing() { - return; + return } if self.network.tx_gossip_disabled() { - return; + return } trace!(target: "net::tx", num_hashes=?hashes.len(), "Start propagating transactions"); @@ -900,7 +900,7 @@ where if full_transactions.is_empty() { // nothing to propagate - return None; + return None } let PropagateTransactions { pooled, full } = full_transactions.build(); @@ -951,7 +951,7 @@ where let propagated = { let Some(peer) = self.peers.get_mut(&peer_id) else { // no such peer - return; + return }; let to_propagate = self @@ -981,7 +981,7 @@ where if new_pooled_hashes.is_empty() { // nothing to propagate - return; + return } for hash in new_pooled_hashes.iter_hashes().copied() { @@ -1016,7 +1016,7 @@ where ) -> PropagatedTransactions { let mut propagated = PropagatedTransactions::default(); if self.network.tx_gossip_disabled() { - return propagated; + return propagated } // send full transactions to a set of the connected peers based on the configured mode @@ -1026,7 +1026,7 @@ where for (peer_idx, (peer_id, peer)) in self.peers.iter_mut().enumerate() { if !self.policies.propagation_policy().can_propagate(peer) { // skip peers we should not propagate to - continue; + continue } // determine whether to send full tx objects or hashes. let mut builder = if peer_idx > max_num_full { @@ -1052,7 +1052,7 @@ where if builder.is_empty() { trace!(target: "net::tx", ?peer_id, "Nothing to propagate to peer; has seen all transactions"); - continue; + continue } let PropagateTransactions { pooled, full } = builder.build(); @@ -1125,7 +1125,7 @@ where if let Some(peer) = self.peers.get_mut(&peer_id) { if self.network.tx_gossip_disabled() { let _ = response.send(Ok(PooledTransactions::default())); - return; + return } let transactions = self.pool.get_pooled_transaction_elements( request.0, @@ -1221,7 +1221,7 @@ where // transactions in the pool. if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() { trace!(target: "net::tx", ?peer_id, "Skipping transaction broadcast: node syncing or gossip disabled"); - return; + return } // Get transactions to broadcast @@ -1321,10 +1321,10 @@ where ) { // If the node is pipeline syncing, ignore transactions if self.network.is_initially_syncing() { - return; + return } if self.network.tx_gossip_disabled() { - return; + return } let Some(peer) = self.peers.get_mut(&peer_id) else { return }; @@ -1373,7 +1373,7 @@ where "failed ecrecovery for transaction" ); has_bad_transactions = true; - continue; + continue } }; @@ -1626,16 +1626,16 @@ where this.transaction_fetcher.update_metrics(); // all channels are fully drained and import futures pending - if maybe_more_network_events - || maybe_more_commands - || maybe_more_tx_events - || maybe_more_tx_fetch_events - || maybe_more_pool_imports - || maybe_more_pending_txns + if maybe_more_network_events || + maybe_more_commands || + maybe_more_tx_events || + maybe_more_tx_fetch_events || + maybe_more_pool_imports || + maybe_more_pending_txns { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } this.update_poll_metrics(start, poll_durations); @@ -1825,16 +1825,16 @@ impl FullTransactionsBuilder { // From: if !transaction.transaction.is_broadcastable_in_full() { self.pooled.push(transaction); - return; + return } let new_size = self.total_size + transaction.size; - if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE - && self.total_size > 0 + if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE && + self.total_size > 0 { // transaction does not fit into the message self.pooled.push(transaction); - return; + return } self.total_size = new_size; @@ -2233,8 +2233,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { // to insert a new peer in transactions peerset transactions.on_network_event(ev); } @@ -2402,8 +2402,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { // to insert a new peer in transactions peerset transactions.on_network_event(ev); } @@ -2480,8 +2480,8 @@ mod tests { let mut established = listener0.take(2); while let Some(ev) = established.next().await { match ev { - NetworkEvent::ActivePeerSession { .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { + NetworkEvent::ActivePeerSession { .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(_)) => { transactions.on_network_event(ev); } NetworkEvent::Peer(PeerEvent::PeerAdded(_peer_id)) => {} diff --git a/crates/net/network/tests/it/connect.rs b/crates/net/network/tests/it/connect.rs index 7e86b7de0c..f4c4aa159b 100644 --- a/crates/net/network/tests/it/connect.rs +++ b/crates/net/network/tests/it/connect.rs @@ -63,8 +63,8 @@ async fn test_establish_connections() { NetworkEvent::Peer(PeerEvent::SessionClosed { .. } | PeerEvent::PeerRemoved(_)) => { panic!("unexpected event") } - NetworkEvent::ActivePeerSession { info, .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { + NetworkEvent::ActivePeerSession { info, .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished(info)) => { let SessionInfo { peer_id, .. } = info; assert!(expected_connections.remove(&peer_id)); } diff --git a/crates/net/network/tests/it/multiplex.rs b/crates/net/network/tests/it/multiplex.rs index f0ba867c9e..d081100681 100644 --- a/crates/net/network/tests/it/multiplex.rs +++ b/crates/net/network/tests/it/multiplex.rs @@ -103,8 +103,8 @@ mod proto { buf.put_u8(self.message_type as u8); match &self.message { PingPongProtoMessageKind::Ping | PingPongProtoMessageKind::Pong => {} - PingPongProtoMessageKind::PingMessage(msg) - | PingPongProtoMessageKind::PongMessage(msg) => { + PingPongProtoMessageKind::PingMessage(msg) | + PingPongProtoMessageKind::PongMessage(msg) => { buf.put(msg.as_bytes()); } } @@ -114,7 +114,7 @@ mod proto { /// Decodes a `TestProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None; + return None } let id = buf[0]; buf.advance(1); @@ -238,7 +238,7 @@ impl Stream for PingPongProtoConnection { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Some(initial_ping) = this.initial_ping.take() { - return Poll::Ready(Some(initial_ping.encoded())); + return Poll::Ready(Some(initial_ping.encoded())) } loop { @@ -248,12 +248,12 @@ impl Stream for PingPongProtoConnection { this.pending_pong = Some(response); Poll::Ready(Some(PingPongProtoMessage::ping_message(msg).encoded())) } - }; + } } let Some(msg) = ready!(this.conn.poll_next_unpin(cx)) else { return Poll::Ready(None) }; let Some(msg) = PingPongProtoMessage::decode_message(&mut &msg[..]) else { - return Poll::Ready(None); + return Poll::Ready(None) }; match msg.message { @@ -268,11 +268,11 @@ impl Stream for PingPongProtoConnection { if let Some(sender) = this.pending_pong.take() { sender.send(msg).ok(); } - continue; + continue } } - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/net/network/tests/it/txgossip.rs b/crates/net/network/tests/it/txgossip.rs index f577ec5e41..4014f41bfc 100644 --- a/crates/net/network/tests/it/txgossip.rs +++ b/crates/net/network/tests/it/txgossip.rs @@ -212,8 +212,8 @@ async fn test_sending_invalid_transactions() { NetworkEvent::Peer(PeerEvent::SessionClosed { peer_id, .. }) => { assert_eq!(peer_id, *peer0.peer_id()); } - NetworkEvent::ActivePeerSession { .. } - | NetworkEvent::Peer(PeerEvent::SessionEstablished { .. }) => { + NetworkEvent::ActivePeerSession { .. } | + NetworkEvent::Peer(PeerEvent::SessionEstablished { .. }) => { panic!("unexpected SessionEstablished event") } NetworkEvent::Peer(PeerEvent::PeerAdded(_)) => { diff --git a/crates/net/p2p/src/error.rs b/crates/net/p2p/src/error.rs index 5664f92764..d650763b4e 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -34,7 +34,7 @@ impl EthResponseValidator for RequestResult> { let request_length = headers.len() as u64; if request_length <= 1 && request.limit != request_length { - return true; + return true } match request.start { @@ -62,10 +62,10 @@ impl EthResponseValidator for RequestResult> { fn reputation_change_err(&self) -> Option { if let Err(err) = self { match err { - RequestError::ChannelClosed - | RequestError::ConnectionDropped - | RequestError::UnsupportedCapability - | RequestError::BadResponse => None, + RequestError::ChannelClosed | + RequestError::ConnectionDropped | + RequestError::UnsupportedCapability | + RequestError::BadResponse => None, RequestError::Timeout => Some(ReputationChangeKind::Timeout), } } else { diff --git a/crates/net/p2p/src/full_block.rs b/crates/net/p2p/src/full_block.rs index d77b7c2188..aa48f6c610 100644 --- a/crates/net/p2p/src/full_block.rs +++ b/crates/net/p2p/src/full_block.rs @@ -146,7 +146,7 @@ where /// Returns the [`SealedBlock`] if the request is complete and valid. fn take_block(&mut self) -> Option> { if self.header.is_none() || self.body.is_none() { - return None; + return None } let header = self.header.take().unwrap(); @@ -161,7 +161,7 @@ where self.client.report_bad_message(resp.peer_id()); self.header = Some(header); self.request.body = Some(self.client.get_block_body(self.hash)); - return None; + return None } Some(SealedBlock::from_sealed_parts(header, resp.into_data())) } @@ -173,10 +173,10 @@ where if let Err(err) = self.consensus.validate_body_against_header(resp.data(), header) { debug!(target: "downloaders", %err, hash=?header.hash(), "Received wrong body"); self.client.report_bad_message(resp.peer_id()); - return; + return } self.body = Some(BodyResponse::Validated(resp.into_data())); - return; + return } self.body = Some(BodyResponse::PendingValidation(resp)); } @@ -240,7 +240,7 @@ where } if let Some(res) = this.take_block() { - return Poll::Ready(res); + return Poll::Ready(res) } // ensure we still have enough budget for another iteration @@ -248,7 +248,7 @@ where if budget == 0 { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } } } @@ -283,14 +283,14 @@ where if let Some(fut) = Pin::new(&mut self.header).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.header = None; - return Poll::Ready(ResponseResult::Header(res)); + return Poll::Ready(ResponseResult::Header(res)) } } if let Some(fut) = Pin::new(&mut self.body).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.body = None; - return Poll::Ready(ResponseResult::Body(res)); + return Poll::Ready(ResponseResult::Body(res)) } } @@ -395,7 +395,7 @@ where fn take_blocks(&mut self) -> Option>> { if !self.is_bodies_complete() { // not done with bodies yet - return None; + return None } let headers = self.headers.take()?; @@ -418,7 +418,7 @@ where // get body that doesn't match, put back into vecdeque, and retry it self.pending_headers.push_back(header.clone()); needs_retry = true; - continue; + continue } resp.into_data() @@ -444,7 +444,7 @@ where // create response for failing bodies let hashes = self.remaining_bodies_hashes(); self.request.bodies = Some(self.client.get_block_bodies(hashes)); - return None; + return None } Some(valid_responses) @@ -596,7 +596,7 @@ where } if let Some(res) = this.take_blocks() { - return Poll::Ready(res); + return Poll::Ready(res) } } } @@ -624,14 +624,14 @@ where if let Some(fut) = Pin::new(&mut self.headers).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.headers = None; - return Poll::Ready(RangeResponseResult::Header(res)); + return Poll::Ready(RangeResponseResult::Header(res)) } } if let Some(fut) = Pin::new(&mut self.bodies).as_pin_mut() { if let Poll::Ready(res) = fut.poll(cx) { self.bodies = None; - return Poll::Ready(RangeResponseResult::Body(res)); + return Poll::Ready(RangeResponseResult::Body(res)) } } diff --git a/crates/net/p2p/src/test_utils/headers.rs b/crates/net/p2p/src/test_utils/headers.rs index 53cd747bdf..b19b29d58d 100644 --- a/crates/net/p2p/src/test_utils/headers.rs +++ b/crates/net/p2p/src/test_utils/headers.rs @@ -72,7 +72,7 @@ impl Stream for TestHeaderDownloader { let this = self.get_mut(); loop { if this.queued_headers.len() == this.batch_size { - return Poll::Ready(Some(Ok(std::mem::take(&mut this.queued_headers)))); + return Poll::Ready(Some(Ok(std::mem::take(&mut this.queued_headers)))) } if this.download.is_none() { this.download = Some(this.create_download()); @@ -130,9 +130,9 @@ impl Stream for TestDownload { loop { if let Some(header) = this.buffer.pop() { - return Poll::Ready(Some(Ok(header))); + return Poll::Ready(Some(Ok(header))) } else if this.done { - return Poll::Ready(None); + return Poll::Ready(None) } match ready!(this.get_or_init_fut().poll_unpin(cx)) { @@ -151,7 +151,7 @@ impl Stream for TestDownload { return Poll::Ready(Some(Err(match err { RequestError::Timeout => DownloadError::Timeout, _ => DownloadError::RequestError(err), - }))); + }))) } } } @@ -217,7 +217,7 @@ impl HeadersClient for TestHeadersClient { Box::pin(async move { if let Some(err) = &mut *error.lock().await { - return Err(err.clone()); + return Err(err.clone()) } let mut lock = responses.lock().await; diff --git a/crates/net/peers/src/lib.rs b/crates/net/peers/src/lib.rs index 477ee40fb4..bfca16a82f 100644 --- a/crates/net/peers/src/lib.rs +++ b/crates/net/peers/src/lib.rs @@ -178,17 +178,17 @@ impl FromStr for AnyNode { fn from_str(s: &str) -> Result { if let Some(rem) = s.strip_prefix("enode://") { if let Ok(record) = NodeRecord::from_str(s) { - return Ok(Self::NodeRecord(record)); + return Ok(Self::NodeRecord(record)) } // incomplete enode if let Ok(peer_id) = PeerId::from_str(rem) { - return Ok(Self::PeerId(peer_id)); + return Ok(Self::PeerId(peer_id)) } - return Err(format!("invalid public key: {rem}")); + return Err(format!("invalid public key: {rem}")) } #[cfg(feature = "secp256k1")] if s.starts_with("enr:") { - return Enr::from_str(s).map(AnyNode::Enr); + return Enr::from_str(s).map(AnyNode::Enr) } Err("missing 'enr:' prefix for base64-encoded record".to_string()) } diff --git a/crates/net/peers/src/node_record.rs b/crates/net/peers/src/node_record.rs index c74b80542d..d9f10ebdbe 100644 --- a/crates/net/peers/src/node_record.rs +++ b/crates/net/peers/src/node_record.rs @@ -66,7 +66,7 @@ impl NodeRecord { if let IpAddr::V6(v6) = self.address { if let Some(v4) = v6.to_ipv4_mapped() { self.address = v4.into(); - return true; + return true } } false @@ -215,15 +215,15 @@ impl TryFrom<&Enr> for NodeRecord { fn try_from(enr: &Enr) -> Result { let Some(address) = enr.ip4().map(IpAddr::from).or_else(|| enr.ip6().map(IpAddr::from)) else { - return Err(NodeRecordParseError::InvalidUrl("ip missing".to_string())); + return Err(NodeRecordParseError::InvalidUrl("ip missing".to_string())) }; let Some(udp_port) = enr.udp4().or_else(|| enr.udp6()) else { - return Err(NodeRecordParseError::InvalidUrl("udp port missing".to_string())); + return Err(NodeRecordParseError::InvalidUrl("udp port missing".to_string())) }; let Some(tcp_port) = enr.tcp4().or_else(|| enr.tcp6()) else { - return Err(NodeRecordParseError::InvalidUrl("tcp port missing".to_string())); + return Err(NodeRecordParseError::InvalidUrl("tcp port missing".to_string())) }; let id = crate::pk2id(&enr.public_key()); diff --git a/crates/node/builder/src/launch/common.rs b/crates/node/builder/src/launch/common.rs index 02d96c24a4..f7696799e9 100644 --- a/crates/node/builder/src/launch/common.rs +++ b/crates/node/builder/src/launch/common.rs @@ -835,9 +835,9 @@ where /// This checks for OP-Mainnet and ensures we have all the necessary data to progress (past /// bedrock height) fn ensure_chain_specific_db_checks(&self) -> ProviderResult<()> { - if self.chain_spec().is_optimism() - && !self.is_dev() - && self.chain_id() == Chain::optimism_mainnet() + if self.chain_spec().is_optimism() && + !self.is_dev() && + self.chain_id() == Chain::optimism_mainnet() { let latest = self.blockchain_db().last_block_number()?; // bedrock height @@ -845,7 +845,7 @@ where error!( "Op-mainnet has been launched without importing the pre-Bedrock state. The chain can't progress without this. See also https://reth.rs/run/sync-op-mainnet.html?minimal-bootstrap-recommended" ); - return Err(ProviderError::BestBlockNotFound); + return Err(ProviderError::BestBlockNotFound) } } @@ -1016,7 +1016,7 @@ where &self, ) -> eyre::Result::Primitives>>> { let Some(ref hook) = self.node_config().debug.invalid_block_hook else { - return Ok(Box::new(NoopInvalidBlockHook::default())); + return Ok(Box::new(NoopInvalidBlockHook::default())) }; let healthy_node_rpc_client = self.get_healthy_node_client().await?; diff --git a/crates/node/builder/src/launch/exex.rs b/crates/node/builder/src/launch/exex.rs index 8fe44ce836..b40c9c8b61 100644 --- a/crates/node/builder/src/launch/exex.rs +++ b/crates/node/builder/src/launch/exex.rs @@ -47,7 +47,7 @@ impl ExExLauncher { if extensions.is_empty() { // nothing to launch - return Ok(None); + return Ok(None) } info!(target: "reth::cli", "Loading ExEx Write-Ahead Log..."); diff --git a/crates/node/core/src/args/debug.rs b/crates/node/core/src/args/debug.rs index 97c69c07ca..d8b6d57038 100644 --- a/crates/node/core/src/args/debug.rs +++ b/crates/node/core/src/args/debug.rs @@ -218,7 +218,7 @@ impl FromStr for InvalidBlockSelection { fn from_str(s: &str) -> Result { if s.is_empty() { - return Ok(Self(Default::default())); + return Ok(Self(Default::default())) } let hooks = s.split(',').map(str::trim).peekable(); Self::try_from_selection(hooks) diff --git a/crates/node/core/src/args/network.rs b/crates/node/core/src/args/network.rs index 18835a1e76..2f5908aaf4 100644 --- a/crates/node/core/src/args/network.rs +++ b/crates/node/core/src/args/network.rs @@ -496,9 +496,9 @@ impl DiscoveryArgs { return false; } - self.enable_discv5_discovery - || self.discv5_addr.is_some() - || self.discv5_addr_ipv6.is_some() + self.enable_discv5_discovery || + self.discv5_addr.is_some() || + self.discv5_addr_ipv6.is_some() } /// Set the discovery port to zero, to allow the OS to assign a random unused port when diff --git a/crates/node/core/src/args/payload_builder.rs b/crates/node/core/src/args/payload_builder.rs index 5c304ba25b..d658241c21 100644 --- a/crates/node/core/src/args/payload_builder.rs +++ b/crates/node/core/src/args/payload_builder.rs @@ -92,7 +92,7 @@ impl TypedValueParser for ExtraDataValueParser { format!( "Payload builder extradata size exceeds {MAXIMUM_EXTRA_DATA_SIZE}-byte limit" ), - )); + )) } Ok(val.to_string()) } diff --git a/crates/node/core/src/node_config.rs b/crates/node/core/src/node_config.rs index e434b2d726..b1998110a3 100644 --- a/crates/node/core/src/node_config.rs +++ b/crates/node/core/src/node_config.rs @@ -372,7 +372,7 @@ impl NodeConfig { // try to look up the header in the database if let Some(header) = header { info!(target: "reth::cli", ?tip, "Successfully looked up tip block in the database"); - return Ok(header.number()); + return Ok(header.number()) } Ok(self.fetch_tip_from_network(client, tip.into()).await.number()) @@ -395,7 +395,7 @@ impl NodeConfig { match get_single_header(&client, tip).await { Ok(tip_header) => { info!(target: "reth::cli", ?tip, "Successfully fetched tip"); - return tip_header; + return tip_header } Err(error) => { fetch_failures += 1; diff --git a/crates/node/events/src/cl.rs b/crates/node/events/src/cl.rs index ca974b49e2..bdced7c97d 100644 --- a/crates/node/events/src/cl.rs +++ b/crates/node/events/src/cl.rs @@ -51,18 +51,18 @@ impl Stream for ConsensusLayerHealthEvents { if let Some(fork_choice) = this.canon_chain.last_received_update_timestamp() { if fork_choice.elapsed() <= NO_FORKCHOICE_UPDATE_RECEIVED_PERIOD { // We had an FCU, and it's recent. CL is healthy. - continue; + continue } // We had an FCU, but it's too old. return Poll::Ready(Some( ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile( fork_choice.elapsed(), ), - )); + )) } // We never had both FCU and transition config exchange. - return Poll::Ready(Some(ConsensusLayerHealthEvent::NeverSeen)); + return Poll::Ready(Some(ConsensusLayerHealthEvent::NeverSeen)) } } } diff --git a/crates/node/events/src/node.rs b/crates/node/events/src/node.rs index 00530bdb02..bd583c45e4 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -220,8 +220,8 @@ impl NodeState { BeaconConsensusEngineEvent::ForkchoiceUpdated(state, status) => { let ForkchoiceState { head_block_hash, safe_block_hash, finalized_block_hash } = state; - if self.safe_block_hash != Some(safe_block_hash) - && self.finalized_block_hash != Some(finalized_block_hash) + if self.safe_block_hash != Some(safe_block_hash) && + self.finalized_block_hash != Some(finalized_block_hash) { let msg = match status { ForkchoiceStatus::Valid => "Forkchoice updated", @@ -556,7 +556,7 @@ impl Eta { else { self.eta = None; debug!(target: "reth::cli", %stage, ?current, ?self.last_checkpoint, "Failed to calculate the ETA: processed entities is less than the last checkpoint"); - return; + return }; let elapsed = last_checkpoint_time.elapsed(); let per_second = processed_since_last as f64 / elapsed.as_secs_f64(); @@ -564,7 +564,7 @@ impl Eta { let Some(remaining) = current.total.checked_sub(current.processed) else { self.eta = None; debug!(target: "reth::cli", %stage, ?current, "Failed to calculate the ETA: total entities is less than processed entities"); - return; + return }; self.eta = Duration::try_from_secs_f64(remaining as f64 / per_second).ok(); @@ -585,8 +585,8 @@ impl Eta { /// It's not the case for network-dependent ([`StageId::Headers`] and [`StageId::Bodies`]) and /// [`StageId::Execution`] stages. fn fmt_for_stage(&self, stage: StageId) -> Option { - if !self.is_available() - || matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution) + if !self.is_available() || + matches!(stage, StageId::Headers | StageId::Bodies | StageId::Execution) { None } else { @@ -605,7 +605,7 @@ impl Display for Eta { f, "{}", humantime::format_duration(Duration::from_secs(remaining.as_secs())) - ); + ) } } diff --git a/crates/node/metrics/src/hooks.rs b/crates/node/metrics/src/hooks.rs index 9d7ee076da..d8ddce0a4d 100644 --- a/crates/node/metrics/src/hooks.rs +++ b/crates/node/metrics/src/hooks.rs @@ -93,7 +93,7 @@ fn collect_memory_stats() { if epoch::advance().map_err(|error| error!(%error, "Failed to advance jemalloc epoch")).is_err() { - return; + return } if let Ok(value) = stats::active::read() @@ -144,13 +144,13 @@ fn collect_io_stats() { let Ok(process) = procfs::process::Process::myself() .map_err(|error| error!(%error, "Failed to get currently running process")) else { - return; + return }; let Ok(io) = process.io().map_err( |error| error!(%error, "Failed to get IO stats for the currently running process"), ) else { - return; + return }; counter!("io.rchar").absolute(io.rchar); diff --git a/crates/optimism/chainspec/src/superchain/configs.rs b/crates/optimism/chainspec/src/superchain/configs.rs index 456df1ff6e..428f197a04 100644 --- a/crates/optimism/chainspec/src/superchain/configs.rs +++ b/crates/optimism/chainspec/src/superchain/configs.rs @@ -78,7 +78,7 @@ fn read_file( ) -> Result, SuperchainConfigError> { for entry in archive.entries() { if entry.filename().as_str()? == file_path { - return Ok(entry.data().to_vec()); + return Ok(entry.data().to_vec()) } } Err(SuperchainConfigError::FileNotFound(file_path.to_string())) @@ -127,7 +127,7 @@ mod tests { .map(|s| s.to_string()) .collect::>(); if filename.first().unwrap().ne(&"genesis") { - continue; + continue } read_superchain_metadata( &filename.get(2).unwrap().replace(".json.zz", ""), diff --git a/crates/optimism/cli/src/commands/import.rs b/crates/optimism/cli/src/commands/import.rs index 4803bf0089..2fd0c56758 100644 --- a/crates/optimism/cli/src/commands/import.rs +++ b/crates/optimism/cli/src/commands/import.rs @@ -89,7 +89,7 @@ impl> ImportOpCommand { body.transactions.retain(|_| { if is_dup_tx(block_number) { total_filtered_out_dup_txns += 1; - return false; + return false } true }) @@ -132,8 +132,8 @@ impl> ImportOpCommand { let total_imported_blocks = provider.tx_ref().entries::()?; let total_imported_txns = provider.tx_ref().entries::()?; - if total_decoded_blocks != total_imported_blocks - || total_decoded_txns != total_imported_txns + total_filtered_out_dup_txns + if total_decoded_blocks != total_imported_blocks || + total_decoded_txns != total_imported_txns + total_filtered_out_dup_txns { error!(target: "reth::cli", total_decoded_blocks, diff --git a/crates/optimism/cli/src/commands/import_receipts.rs b/crates/optimism/cli/src/commands/import_receipts.rs index 0a49bc4275..38503bc2d3 100644 --- a/crates/optimism/cli/src/commands/import_receipts.rs +++ b/crates/optimism/cli/src/commands/import_receipts.rs @@ -175,7 +175,7 @@ where { if highest_block_receipts == highest_block_transactions { warn!(target: "reth::cli", highest_block_receipts, highest_block_transactions, "Ignoring all other blocks in the file since we have reached the desired height"); - break; + break } // create a new file client from chunk read from file diff --git a/crates/optimism/cli/src/commands/init_state.rs b/crates/optimism/cli/src/commands/init_state.rs index 5151334584..da574239d5 100644 --- a/crates/optimism/cli/src/commands/init_state.rs +++ b/crates/optimism/cli/src/commands/init_state.rs @@ -71,7 +71,7 @@ impl> InitStateCommandOp { } else if last_block_number > 0 && last_block_number < BEDROCK_HEADER.number { return Err(eyre::eyre!( "Data directory should be empty when calling init-state with --without-ovm." - )); + )) } } diff --git a/crates/optimism/cli/src/receipt_file_codec.rs b/crates/optimism/cli/src/receipt_file_codec.rs index bd479c21f8..f5b6b48b26 100644 --- a/crates/optimism/cli/src/receipt_file_codec.rs +++ b/crates/optimism/cli/src/receipt_file_codec.rs @@ -43,7 +43,7 @@ where fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { - return Ok(None); + return Ok(None) } let buf_slice = &mut src.as_ref(); diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index d147b46db3..3e4201dc73 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -96,12 +96,12 @@ where expected: block.ommers_hash(), } .into(), - )); + )) } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())); + return Err(ConsensusError::BodyTransactionRootDiff(error.into())) } // Check empty shanghai-withdrawals @@ -110,7 +110,7 @@ where ConsensusError::Other(format!("failed to verify block {}: {err}", block.number())) })? } else { - return Ok(()); + return Ok(()) } if self.chain_spec.is_ecotone_active_at_timestamp(block.timestamp()) { @@ -146,11 +146,11 @@ where ); if header.nonce() != Some(B64::ZERO) { - return Err(ConsensusError::TheMergeNonceIsNotZero); + return Err(ConsensusError::TheMergeNonceIsNotZero) } if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); + return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty) } // Post-merge, the consensus layer is expected to perform checks such that the block @@ -192,7 +192,7 @@ where return Err(ConsensusError::BaseFeeDiff(GotExpected { expected: expected_base_fee, got: header_base_fee, - })); + })) } } else { validate_against_parent_eip1559_base_fee( diff --git a/crates/optimism/consensus/src/proof.rs b/crates/optimism/consensus/src/proof.rs index 4d87638091..86f7b2ecbe 100644 --- a/crates/optimism/consensus/src/proof.rs +++ b/crates/optimism/consensus/src/proof.rs @@ -19,8 +19,8 @@ pub(crate) fn calculate_receipt_root_optimism( // encoding. In the Regolith Hardfork, we must strip the deposit nonce from the // receipts before calculating the receipt root. This was corrected in the Canyon // hardfork. - if chain_spec.is_regolith_active_at_timestamp(timestamp) - && !chain_spec.is_canyon_active_at_timestamp(timestamp) + if chain_spec.is_regolith_active_at_timestamp(timestamp) && + !chain_spec.is_canyon_active_at_timestamp(timestamp) { let receipts = receipts .iter() @@ -33,7 +33,7 @@ pub(crate) fn calculate_receipt_root_optimism( }) .collect::>(); - return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| r.encode_2718(buf)); + return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| r.encode_2718(buf)) } ordered_trie_root_with_encoder(receipts, |r, buf| r.encode_2718(buf)) @@ -52,8 +52,8 @@ pub fn calculate_receipt_root_no_memo_optimism( // encoding. In the Regolith Hardfork, we must strip the deposit nonce from the // receipts before calculating the receipt root. This was corrected in the Canyon // hardfork. - if chain_spec.is_regolith_active_at_timestamp(timestamp) - && !chain_spec.is_canyon_active_at_timestamp(timestamp) + if chain_spec.is_regolith_active_at_timestamp(timestamp) && + !chain_spec.is_canyon_active_at_timestamp(timestamp) { let receipts = receipts .iter() @@ -68,7 +68,7 @@ pub fn calculate_receipt_root_no_memo_optimism( return ordered_trie_root_with_encoder(&receipts, |r, buf| { r.with_bloom_ref().encode_2718(buf); - }); + }) } ordered_trie_root_with_encoder(receipts, |r, buf| { diff --git a/crates/optimism/consensus/src/validation/canyon.rs b/crates/optimism/consensus/src/validation/canyon.rs index 432b121a48..886f53bb20 100644 --- a/crates/optimism/consensus/src/validation/canyon.rs +++ b/crates/optimism/consensus/src/validation/canyon.rs @@ -34,7 +34,7 @@ pub fn ensure_empty_shanghai_withdrawals(body: &T) -> Result<(), O // Canyon rule if !withdrawals.as_ref().is_empty() { - return Err(OpConsensusError::WithdrawalsNonEmpty); + return Err(OpConsensusError::WithdrawalsNonEmpty) } Ok(()) diff --git a/crates/optimism/consensus/src/validation/isthmus.rs b/crates/optimism/consensus/src/validation/isthmus.rs index cdaf382661..64d45eae5c 100644 --- a/crates/optimism/consensus/src/validation/isthmus.rs +++ b/crates/optimism/consensus/src/validation/isthmus.rs @@ -90,7 +90,7 @@ where return Err(OpConsensusError::L2WithdrawalsRootMismatch { header: header_storage_root, exec_res: storage_root, - }); + }) } Ok(()) @@ -122,7 +122,7 @@ where return Err(OpConsensusError::L2WithdrawalsRootMismatch { header: header_storage_root, exec_res: storage_root, - }); + }) } Ok(()) diff --git a/crates/optimism/consensus/src/validation/mod.rs b/crates/optimism/consensus/src/validation/mod.rs index bd69c664d9..4977647d89 100644 --- a/crates/optimism/consensus/src/validation/mod.rs +++ b/crates/optimism/consensus/src/validation/mod.rs @@ -38,14 +38,14 @@ where expected: header.ommers_hash(), } .into(), - )); + )) } let tx_root = body.calculate_tx_root(); if header.transactions_root() != tx_root { return Err(ConsensusError::BodyTransactionRootDiff( GotExpected { got: tx_root, expected: header.transactions_root() }.into(), - )); + )) } match (header.withdrawals_root(), body.calculate_withdrawals_root()) { @@ -57,7 +57,7 @@ where if withdrawals_root != EMPTY_ROOT_HASH { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: EMPTY_ROOT_HASH }.into(), - )); + )) } } else { // before isthmus we ensure that the header root matches the body @@ -65,7 +65,7 @@ where return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root } .into(), - )); + )) } } } @@ -100,7 +100,7 @@ pub fn validate_block_post_execution( header.timestamp(), ) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error); + return Err(error) } } @@ -111,7 +111,7 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: header.gas_used() }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }); + }) } Ok(()) @@ -154,13 +154,13 @@ fn compare_receipts_root_and_logs_bloom( if calculated_receipts_root != expected_receipts_root { return Err(ConsensusError::BodyReceiptRootDiff( GotExpected { got: calculated_receipts_root, expected: expected_receipts_root }.into(), - )); + )) } if calculated_logs_bloom != expected_logs_bloom { return Err(ConsensusError::BodyBloomLogDiff( GotExpected { got: calculated_logs_bloom, expected: expected_logs_bloom }.into(), - )); + )) } Ok(()) diff --git a/crates/optimism/node/src/engine.rs b/crates/optimism/node/src/engine.rs index 670d9c2674..bba734ae8f 100644 --- a/crates/optimism/node/src/engine.rs +++ b/crates/optimism/node/src/engine.rs @@ -140,7 +140,7 @@ where // FIXME: we don't necessarily have access to the parent block here because the // parent block isn't necessarily part of the canonical chain yet. Instead this // function should receive the list of in memory blocks as input - return Ok(()); + return Ok(()) }; let predeploy_storage_updates = state_updates .storages @@ -264,10 +264,10 @@ pub fn validate_withdrawals_presence( .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); } } - EngineApiMessageVersion::V2 - | EngineApiMessageVersion::V3 - | EngineApiMessageVersion::V4 - | EngineApiMessageVersion::V5 => { + EngineApiMessageVersion::V2 | + EngineApiMessageVersion::V3 | + EngineApiMessageVersion::V4 | + EngineApiMessageVersion::V5 => { if is_shanghai && !has_withdrawals { return Err(message_validation_kind .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 4d9416976a..2d33f05f4a 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -786,8 +786,8 @@ where let Self { pool_config_overrides, .. } = self; // supervisor used for interop - if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) - && self.supervisor_http == DEFAULT_SUPERVISOR_URL + if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) && + self.supervisor_http == DEFAULT_SUPERVISOR_URL { info!(target: "reth::cli", url=%DEFAULT_SUPERVISOR_URL, @@ -830,8 +830,8 @@ where debug!(target: "reth::cli", "Spawned txpool maintenance task"); // The Op txpool maintenance task is only spawned when interop is active - if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) - && self.supervisor_http == DEFAULT_SUPERVISOR_URL + if ctx.chain_spec().is_interop_active_at_timestamp(ctx.head().timestamp) && + self.supervisor_http == DEFAULT_SUPERVISOR_URL { // spawn the Op txpool maintenance task let chain_events = ctx.provider().canonical_state_stream(); diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index f450fd7d9d..d5a3260420 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -311,13 +311,13 @@ impl OpBuilder<'_, Txs> { if !ctx.attributes().no_tx_pool { let best_txs = best(ctx.best_transaction_attributes(builder.evm_mut().block())); if ctx.execute_best_transactions(&mut info, &mut builder, best_txs)?.is_some() { - return Ok(BuildOutcomeKind::Cancelled); + return Ok(BuildOutcomeKind::Cancelled) } // check if the new payload is even more valuable if !ctx.is_better_payload(info.total_fees) { // can skip building the block - return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }); + return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }) } } @@ -593,7 +593,7 @@ where if sequencer_tx.value().is_eip4844() { return Err(PayloadBuilderError::other( OpPayloadBuilderError::BlobTransactionRejected, - )); + )) } // Convert the transaction to a [RecoveredTx]. This is @@ -611,11 +611,11 @@ where .. })) => { trace!(target: "payload_builder", %error, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue; + continue } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) } }; @@ -657,13 +657,13 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue; + continue } // A sequencer's block should never contain blob or deposit transactions from the pool. if tx.is_eip4844() || tx.is_deposit() { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue; + continue } // We skip invalid cross chain txs, they would be removed on the next block update in @@ -671,12 +671,12 @@ where if let Some(interop) = interop { if !is_valid_interop(interop, self.config.attributes.timestamp()) { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue; + continue } } // check if the job was cancelled, if so we can exit early if self.cancel.is_cancelled() { - return Ok(Some(())); + return Ok(Some(())) } let gas_used = match builder.execute_transaction(tx.clone()) { @@ -694,11 +694,11 @@ where trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid(tx.signer(), tx.nonce()); } - continue; + continue } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) } }; diff --git a/crates/optimism/payload/src/validator.rs b/crates/optimism/payload/src/validator.rs index ba808f0057..b287c55398 100644 --- a/crates/optimism/payload/src/validator.rs +++ b/crates/optimism/payload/src/validator.rs @@ -60,7 +60,7 @@ where return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - })?; + })? } shanghai::ensure_well_formed_fields( diff --git a/crates/optimism/primitives/src/bedrock.rs b/crates/optimism/primitives/src/bedrock.rs index 6c2e062f76..5ab72cf0d7 100644 --- a/crates/optimism/primitives/src/bedrock.rs +++ b/crates/optimism/primitives/src/bedrock.rs @@ -43,12 +43,12 @@ pub const BLOCK_NUMS_REPLAYED_TX: [u64; 6] = [ /// with replayed transaction happen to only contain the single transaction. pub fn is_dup_tx(block_number: u64) -> bool { if block_number > BLOCK_NUMS_REPLAYED_TX[5] { - return false; + return false } // these blocks just have one transaction! if BLOCK_NUMS_REPLAYED_TX.contains(&block_number) { - return true; + return true } false diff --git a/crates/optimism/primitives/src/receipt.rs b/crates/optimism/primitives/src/receipt.rs index c253a754b6..e0ef631808 100644 --- a/crates/optimism/primitives/src/receipt.rs +++ b/crates/optimism/primitives/src/receipt.rs @@ -45,10 +45,10 @@ impl OpReceipt { /// Returns inner [`Receipt`], pub const fn as_receipt(&self) -> &Receipt { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => &receipt.inner, } } @@ -56,10 +56,10 @@ impl OpReceipt { /// Returns a mutable reference to the inner [`Receipt`], pub const fn as_receipt_mut(&mut self) -> &mut Receipt { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => &mut receipt.inner, } } @@ -67,10 +67,10 @@ impl OpReceipt { /// Consumes this and returns the inner [`Receipt`]. pub fn into_receipt(self) -> Receipt { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt, + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt, Self::Deposit(receipt) => receipt.inner, } } @@ -78,10 +78,10 @@ impl OpReceipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), Self::Deposit(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), } } @@ -89,10 +89,10 @@ impl OpReceipt { /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encode_fields(&self, bloom: &Bloom, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), Self::Deposit(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), } } @@ -145,10 +145,10 @@ impl OpReceipt { /// RLP-encodes receipt fields without an RLP header. pub fn rlp_encode_fields_without_bloom(&self, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => { + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => { receipt.status.encode(out); receipt.cumulative_gas_used.encode(out); receipt.logs.encode(out); @@ -170,20 +170,20 @@ impl OpReceipt { /// Returns length of RLP-encoded receipt fields without an RLP header. pub fn rlp_encoded_fields_length_without_bloom(&self) -> usize { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => { - receipt.status.length() - + receipt.cumulative_gas_used.length() - + receipt.logs.length() + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => { + receipt.status.length() + + receipt.cumulative_gas_used.length() + + receipt.logs.length() } Self::Deposit(receipt) => { - receipt.inner.status.length() - + receipt.inner.cumulative_gas_used.length() - + receipt.inner.logs.length() - + receipt.deposit_nonce.map_or(0, |nonce| nonce.length()) - + receipt.deposit_receipt_version.map_or(0, |version| version.length()) + receipt.inner.status.length() + + receipt.inner.cumulative_gas_used.length() + + receipt.inner.logs.length() + + receipt.deposit_nonce.map_or(0, |nonce| nonce.length()) + + receipt.deposit_receipt_version.map_or(0, |version| version.length()) } } } @@ -276,7 +276,7 @@ impl RlpDecodableReceipt for OpReceipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, OpTxType::Legacy); + return Self::rlp_decode_inner(buf, OpTxType::Legacy) } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -296,8 +296,8 @@ impl RlpDecodableReceipt for OpReceipt { impl Encodable2718 for OpReceipt { fn encode_2718_len(&self) -> usize { - !self.tx_type().is_legacy() as usize - + self.rlp_header_inner_without_bloom().length_with_payload() + !self.tx_type().is_legacy() as usize + + self.rlp_header_inner_without_bloom().length_with_payload() } fn encode_2718(&self, out: &mut dyn BufMut) { diff --git a/crates/optimism/primitives/src/transaction/signed.rs b/crates/optimism/primitives/src/transaction/signed.rs index 164b6167ed..2a345229a6 100644 --- a/crates/optimism/primitives/src/transaction/signed.rs +++ b/crates/optimism/primitives/src/transaction/signed.rs @@ -108,7 +108,7 @@ impl SignerRecoverable for OpTransactionSigned { // Optimism's Deposit transaction does not have a signature. Directly return the // `from` address. if let OpTypedTransaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Ok(from); + return Ok(from) } let Self { transaction, signature, .. } = self; @@ -120,7 +120,7 @@ impl SignerRecoverable for OpTransactionSigned { // Optimism's Deposit transaction does not have a signature. Directly return the // `from` address. if let OpTypedTransaction::Deposit(TxDeposit { from, .. }) = &self.transaction { - return Ok(*from); + return Ok(*from) } let Self { transaction, signature, .. } = self; @@ -396,9 +396,9 @@ impl Typed2718 for OpTransactionSigned { impl PartialEq for OpTransactionSigned { fn eq(&self, other: &Self) -> bool { - self.signature == other.signature - && self.transaction == other.transaction - && self.tx_hash() == other.tx_hash() + self.signature == other.signature && + self.transaction == other.transaction && + self.tx_hash() == other.tx_hash() } } diff --git a/crates/optimism/rpc/src/error.rs b/crates/optimism/rpc/src/error.rs index 8defe79ffd..f544586349 100644 --- a/crates/optimism/rpc/src/error.rs +++ b/crates/optimism/rpc/src/error.rs @@ -50,9 +50,9 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { match err { OpEthApiError::Eth(err) => err.into(), OpEthApiError::InvalidTransaction(err) => err.into(), - OpEthApiError::Evm(_) - | OpEthApiError::L1BlockFeeError - | OpEthApiError::L1BlockGasError => internal_rpc_err(err.to_string()), + OpEthApiError::Evm(_) | + OpEthApiError::L1BlockFeeError | + OpEthApiError::L1BlockGasError => internal_rpc_err(err.to_string()), OpEthApiError::Sequencer(err) => err.into(), } } @@ -75,8 +75,8 @@ pub enum OpInvalidTransactionError { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(err: OpInvalidTransactionError) -> Self { match err { - OpInvalidTransactionError::DepositSystemTxPostRegolith - | OpInvalidTransactionError::HaltedDepositPostRegolith => { + OpInvalidTransactionError::DepositSystemTxPostRegolith | + OpInvalidTransactionError::HaltedDepositPostRegolith => { rpc_err(EthRpcErrorCode::TransactionRejected.code(), err.to_string(), None) } OpInvalidTransactionError::TxConditionalErr(_) => err.into(), diff --git a/crates/optimism/rpc/src/eth/block.rs b/crates/optimism/rpc/src/eth/block.rs index b74e69f47a..34ce4081b2 100644 --- a/crates/optimism/rpc/src/eth/block.rs +++ b/crates/optimism/rpc/src/eth/block.rs @@ -85,7 +85,7 @@ where .build()) }) .collect::, Self::Error>>() - .map(Some); + .map(Some) } Ok(None) diff --git a/crates/optimism/rpc/src/eth/ext.rs b/crates/optimism/rpc/src/eth/ext.rs index 6227aa123d..46008d0608 100644 --- a/crates/optimism/rpc/src/eth/ext.rs +++ b/crates/optimism/rpc/src/eth/ext.rs @@ -138,8 +138,8 @@ where .ok_or_else(header_not_found)?; // Ensure that the condition can still be met by checking the max bounds - if condition.has_exceeded_block_number(header.header().number()) - || condition.has_exceeded_timestamp(header.header().timestamp()) + if condition.has_exceeded_block_number(header.header().number()) || + condition.has_exceeded_timestamp(header.header().timestamp()) { return Err(TxConditionalErr::InvalidCondition.into()); } diff --git a/crates/optimism/rpc/src/eth/transaction.rs b/crates/optimism/rpc/src/eth/transaction.rs index 3d72493559..30422316ad 100644 --- a/crates/optimism/rpc/src/eth/transaction.rs +++ b/crates/optimism/rpc/src/eth/transaction.rs @@ -57,7 +57,7 @@ where tracing::warn!(target: "rpc::eth", %err, %hash, "successfully sent tx to sequencer, but failed to persist in local tx pool"); }); - return Ok(hash); + return Ok(hash) } // submit the transaction to the pool with a `Local` origin diff --git a/crates/optimism/rpc/src/historical.rs b/crates/optimism/rpc/src/historical.rs index 136e089d87..0f8824882b 100644 --- a/crates/optimism/rpc/src/historical.rs +++ b/crates/optimism/rpc/src/historical.rs @@ -139,12 +139,12 @@ where "eth_getBlockByNumber" | "eth_getBlockByHash" => { parse_block_id_from_params(&req.params(), 0) } - "eth_getBalance" - | "eth_getCode" - | "eth_getTransactionCount" - | "eth_call" - | "eth_estimateGas" - | "eth_createAccessList" => parse_block_id_from_params(&req.params(), 1), + "eth_getBalance" | + "eth_getCode" | + "eth_getTransactionCount" | + "eth_call" | + "eth_estimateGas" | + "eth_createAccessList" => parse_block_id_from_params(&req.params(), 1), "eth_getStorageAt" | "eth_getProof" => parse_block_id_from_params(&req.params(), 2), _ => None, }; diff --git a/crates/optimism/txpool/src/supervisor/client.rs b/crates/optimism/txpool/src/supervisor/client.rs index 6829c94ae8..4cc67685b5 100644 --- a/crates/optimism/txpool/src/supervisor/client.rs +++ b/crates/optimism/txpool/src/supervisor/client.rs @@ -103,7 +103,7 @@ impl SupervisorClient { // Interop check if !is_interop_active { // No cross chain tx allowed before interop - return Some(Err(InvalidCrossTx::CrossChainTxPreInterop)); + return Some(Err(InvalidCrossTx::CrossChainTxPreInterop)) } if let Err(err) = self diff --git a/crates/optimism/txpool/src/transaction.rs b/crates/optimism/txpool/src/transaction.rs index 9358d78589..6cbc645fe5 100644 --- a/crates/optimism/txpool/src/transaction.rs +++ b/crates/optimism/txpool/src/transaction.rs @@ -109,7 +109,7 @@ impl MaybeInteropTransaction for OpPooledTransaction fn interop_deadline(&self) -> Option { let interop = self.interop.load(Ordering::Relaxed); if interop > NO_INTEROP_TX { - return Some(interop); + return Some(interop) } None } diff --git a/crates/optimism/txpool/src/validator.rs b/crates/optimism/txpool/src/validator.rs index 45c3e03ba5..6c986e9498 100644 --- a/crates/optimism/txpool/src/validator.rs +++ b/crates/optimism/txpool/src/validator.rs @@ -187,7 +187,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ); + ) } // Interop cross tx validation @@ -199,7 +199,7 @@ where } err => InvalidPoolTransactionError::Other(Box::new(err)), }; - return TransactionValidationOutcome::Invalid(transaction, err); + return TransactionValidationOutcome::Invalid(transaction, err) } Some(Ok(_)) => { // valid interop tx @@ -222,7 +222,7 @@ where ) -> TransactionValidationOutcome { if !self.requires_l1_data_gas_fee() { // no need to check L1 gas fee - return outcome; + return outcome } // ensure that the account has enough balance to cover the L1 gas cost if let TransactionValidationOutcome::Valid { @@ -259,7 +259,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ); + ) } return TransactionValidationOutcome::Valid { @@ -269,7 +269,7 @@ where propagate, bytecode_hash, authorities, - }; + } } outcome } diff --git a/crates/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 06c7895cf9..470e34bee3 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -377,7 +377,7 @@ where // check if the deadline is reached if this.deadline.as_mut().poll(cx).is_ready() { trace!(target: "payload_builder", "payload building deadline reached"); - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } // check if the interval is reached @@ -597,7 +597,7 @@ where if let Some(best) = this.best_payload.take() { debug!(target: "payload_builder", "resolving best payload"); - return Poll::Ready(Ok(best)); + return Poll::Ready(Ok(best)) } if let Some(fut) = Pin::new(&mut this.empty_payload).as_pin_mut() { @@ -613,12 +613,12 @@ where Poll::Ready(res) } Err(err) => Poll::Ready(Err(err.into())), - }; + } } } if this.is_empty() { - return Poll::Ready(Err(PayloadBuilderError::MissingPayload)); + return Poll::Ready(Err(PayloadBuilderError::MissingPayload)) } Poll::Pending diff --git a/crates/payload/builder-primitives/src/events.rs b/crates/payload/builder-primitives/src/events.rs index ee6f09723e..d14d967500 100644 --- a/crates/payload/builder-primitives/src/events.rs +++ b/crates/payload/builder-primitives/src/events.rs @@ -69,14 +69,14 @@ impl Stream for BuiltPayloadStream { Some(Ok(Events::BuiltPayload(payload))) => Poll::Ready(Some(payload)), Some(Ok(Events::Attributes(_))) => { // ignoring attributes - continue; + continue } Some(Err(err)) => { debug!(%err, "payload event stream lagging behind"); - continue; + continue } None => Poll::Ready(None), - }; + } } } } @@ -99,14 +99,14 @@ impl Stream for PayloadAttributeStream { Some(Ok(Events::Attributes(attr))) => Poll::Ready(Some(attr)), Some(Ok(Events::BuiltPayload(_))) => { // ignoring payloads - continue; + continue } Some(Err(err)) => { debug!(%err, "payload event stream lagging behind"); - continue; + continue } None => Poll::Ready(None), - }; + } } } } diff --git a/crates/payload/builder/src/noop.rs b/crates/payload/builder/src/noop.rs index 54b64cd522..6047bffa8b 100644 --- a/crates/payload/builder/src/noop.rs +++ b/crates/payload/builder/src/noop.rs @@ -42,7 +42,7 @@ where let this = self.get_mut(); loop { let Some(cmd) = ready!(this.command_rx.poll_next_unpin(cx)) else { - return Poll::Ready(()); + return Poll::Ready(()) }; match cmd { PayloadServiceCommand::BuildNewPayload(attr, tx) => { diff --git a/crates/payload/builder/src/service.rs b/crates/payload/builder/src/service.rs index 05866f6871..3c4daf2555 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -440,7 +440,7 @@ where } if !new_job { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/payload/primitives/src/lib.rs b/crates/payload/primitives/src/lib.rs index dc21a9fa56..fb78cae16c 100644 --- a/crates/payload/primitives/src/lib.rs +++ b/crates/payload/primitives/src/lib.rs @@ -96,7 +96,7 @@ pub fn validate_payload_timestamp( // // 1. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // payload or payloadAttributes is greater or equal to the Cancun activation timestamp. - return Err(EngineObjectValidationError::UnsupportedFork); + return Err(EngineObjectValidationError::UnsupportedFork) } if version.is_v3() && !is_cancun { @@ -118,7 +118,7 @@ pub fn validate_payload_timestamp( // // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // the payload does not fall within the time frame of the Cancun fork. - return Err(EngineObjectValidationError::UnsupportedFork); + return Err(EngineObjectValidationError::UnsupportedFork) } let is_prague = chain_spec.is_prague_active_at_timestamp(timestamp); @@ -141,7 +141,7 @@ pub fn validate_payload_timestamp( // // 2. Client software **MUST** return `-38005: Unsupported fork` error if the `timestamp` of // the payload does not fall within the time frame of the Prague fork. - return Err(EngineObjectValidationError::UnsupportedFork); + return Err(EngineObjectValidationError::UnsupportedFork) } let is_osaka = chain_spec.is_osaka_active_at_timestamp(timestamp); @@ -153,7 +153,7 @@ pub fn validate_payload_timestamp( // // 1. Client software MUST return -38005: Unsupported fork error if the timestamp of the // built payload does not fall within the time frame of the Osaka fork. - return Err(EngineObjectValidationError::UnsupportedFork); + return Err(EngineObjectValidationError::UnsupportedFork) } Ok(()) @@ -175,20 +175,20 @@ pub fn validate_withdrawals_presence( EngineApiMessageVersion::V1 => { if has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)); + .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)) } } - EngineApiMessageVersion::V2 - | EngineApiMessageVersion::V3 - | EngineApiMessageVersion::V4 - | EngineApiMessageVersion::V5 => { + EngineApiMessageVersion::V2 | + EngineApiMessageVersion::V3 | + EngineApiMessageVersion::V4 | + EngineApiMessageVersion::V5 => { if is_shanghai_active && !has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) } if !is_shanghai_active && has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)); + .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)) } } }; @@ -279,13 +279,13 @@ pub fn validate_parent_beacon_block_root_presence( if has_parent_beacon_block_root { return Err(validation_kind.to_error( VersionSpecificValidationError::ParentBeaconBlockRootNotSupportedBeforeV3, - )); + )) } } EngineApiMessageVersion::V3 | EngineApiMessageVersion::V4 | EngineApiMessageVersion::V5 => { if !has_parent_beacon_block_root { return Err(validation_kind - .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)); + .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)) } } }; @@ -452,20 +452,20 @@ pub fn validate_execution_requests(requests: &[Bytes]) -> Result<(), EngineObjec if request.len() <= 1 { return Err(EngineObjectValidationError::InvalidParams( "EmptyExecutionRequest".to_string().into(), - )); + )) } let request_type = request[0]; if Some(request_type) < last_request_type { return Err(EngineObjectValidationError::InvalidParams( "OutOfOrderExecutionRequest".to_string().into(), - )); + )) } if Some(request_type) == last_request_type { return Err(EngineObjectValidationError::InvalidParams( "DuplicatedExecutionRequestType".to_string().into(), - )); + )) } last_request_type = Some(request_type); diff --git a/crates/payload/util/src/traits.rs b/crates/payload/util/src/traits.rs index 2c9954fa3c..7d076d3687 100644 --- a/crates/payload/util/src/traits.rs +++ b/crates/payload/util/src/traits.rs @@ -78,9 +78,9 @@ where loop { let tx = self.best.next()?; if self.invalid.contains(tx.sender_ref()) { - continue; + continue } - return Some(tx.transaction.clone()); + return Some(tx.transaction.clone()) } } diff --git a/crates/payload/validator/src/cancun.rs b/crates/payload/validator/src/cancun.rs index 0427bcdcfd..5a4deb139f 100644 --- a/crates/payload/validator/src/cancun.rs +++ b/crates/payload/validator/src/cancun.rs @@ -38,28 +38,28 @@ pub fn ensure_well_formed_header_and_sidecar_fields( if is_cancun_active { if block.blob_gas_used().is_none() { // cancun active but blob gas used not present - return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed); + return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed) } if block.excess_blob_gas().is_none() { // cancun active but excess blob gas not present - return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas); + return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas) } if cancun_sidecar_fields.is_none() { // cancun active but cancun fields not present - return Err(PayloadError::PostCancunWithoutCancunFields); + return Err(PayloadError::PostCancunWithoutCancunFields) } } else { if block.blob_gas_used().is_some() { // cancun not active but blob gas used present - return Err(PayloadError::PreCancunBlockWithBlobGasUsed); + return Err(PayloadError::PreCancunBlockWithBlobGasUsed) } if block.excess_blob_gas().is_some() { // cancun not active but excess blob gas present - return Err(PayloadError::PreCancunBlockWithExcessBlobGas); + return Err(PayloadError::PreCancunBlockWithExcessBlobGas) } if cancun_sidecar_fields.is_some() { // cancun not active but cancun fields present - return Err(PayloadError::PreCancunWithCancunFields); + return Err(PayloadError::PreCancunWithCancunFields) } } @@ -80,7 +80,7 @@ pub fn ensure_well_formed_transactions_field_with_sidecar( if let Some(versioned_hashes) = cancun_sidecar_fields.map(|fields| &fields.versioned_hashes) { if num_blob_versioned_hashes != versioned_hashes.len() { // Number of blob versioned hashes does not match - return Err(PayloadError::InvalidVersionedHashes); + return Err(PayloadError::InvalidVersionedHashes) } // we can use `zip` safely here because we already compared their length for (payload_versioned_hash, block_versioned_hash) in versioned_hashes.iter().zip(block_body.blob_versioned_hashes_iter()) { if payload_versioned_hash != block_versioned_hash { - return Err(PayloadError::InvalidVersionedHashes); + return Err(PayloadError::InvalidVersionedHashes) } } } else { // No Cancun fields, if block includes any blobs, this is an error if num_blob_versioned_hashes > 0 { - return Err(PayloadError::InvalidVersionedHashes); + return Err(PayloadError::InvalidVersionedHashes) } } diff --git a/crates/payload/validator/src/prague.rs b/crates/payload/validator/src/prague.rs index cbd6e7333a..d663469a82 100644 --- a/crates/payload/validator/src/prague.rs +++ b/crates/payload/validator/src/prague.rs @@ -27,7 +27,7 @@ pub const fn ensure_well_formed_sidecar_fields( ) -> Result<(), PayloadError> { if !is_prague_active && prague_fields.is_some() { // prague _not_ active but prague fields present - return Err(PayloadError::PrePragueBlockRequests); + return Err(PayloadError::PrePragueBlockRequests) } Ok(()) @@ -41,7 +41,7 @@ pub fn ensure_well_formed_transactions_field( is_prague_active: bool, ) -> Result<(), PayloadError> { if !is_prague_active && block_body.has_eip7702_transactions() { - return Err(PayloadError::PrePragueBlockWithEip7702Transactions); + return Err(PayloadError::PrePragueBlockWithEip7702Transactions) } Ok(()) diff --git a/crates/payload/validator/src/shanghai.rs b/crates/payload/validator/src/shanghai.rs index f88c4c45c0..743c96fa1b 100644 --- a/crates/payload/validator/src/shanghai.rs +++ b/crates/payload/validator/src/shanghai.rs @@ -12,11 +12,11 @@ pub fn ensure_well_formed_fields( if is_shanghai_active { if block_body.withdrawals().is_none() { // shanghai active but no withdrawals present - return Err(PayloadError::PostShanghaiBlockWithoutWithdrawals); + return Err(PayloadError::PostShanghaiBlockWithoutWithdrawals) } } else if block_body.withdrawals().is_some() { // shanghai not active but withdrawals present - return Err(PayloadError::PreShanghaiBlockWithWithdrawals); + return Err(PayloadError::PreShanghaiBlockWithWithdrawals) } Ok(()) diff --git a/crates/primitives-traits/src/account.rs b/crates/primitives-traits/src/account.rs index ee4b3be980..34a533fc4a 100644 --- a/crates/primitives-traits/src/account.rs +++ b/crates/primitives-traits/src/account.rs @@ -46,9 +46,9 @@ impl Account { /// After `SpuriousDragon` empty account is defined as account with nonce == 0 && balance == 0 /// && bytecode = None (or hash is [`KECCAK_EMPTY`]). pub fn is_empty(&self) -> bool { - self.nonce == 0 - && self.balance.is_zero() - && self.bytecode_hash.is_none_or(|hash| hash == KECCAK_EMPTY) + self.nonce == 0 && + self.balance.is_zero() && + self.bytecode_hash.is_none_or(|hash| hash == KECCAK_EMPTY) } /// Returns an account bytecode's hash. diff --git a/crates/primitives-traits/src/block/mod.rs b/crates/primitives-traits/src/block/mod.rs index 11ce3fc78e..35ecb17144 100644 --- a/crates/primitives-traits/src/block/mod.rs +++ b/crates/primitives-traits/src/block/mod.rs @@ -169,7 +169,7 @@ pub trait Block: } else { // Fall back to recovery if lengths don't match let Ok(senders) = self.body().recover_signers_unchecked() else { - return Err(BlockRecoveryError::new(self)); + return Err(BlockRecoveryError::new(self)) }; senders }; @@ -195,7 +195,7 @@ pub trait Block: ::Transaction: SignedTransaction, { let Ok(signers) = self.body().recover_signers() else { - return Err(BlockRecoveryError::new(self)); + return Err(BlockRecoveryError::new(self)) }; Ok(RecoveredBlock::new_unhashed(self, signers)) } diff --git a/crates/primitives-traits/src/block/recovered.rs b/crates/primitives-traits/src/block/recovered.rs index ee4faa8dfd..7da2bcf373 100644 --- a/crates/primitives-traits/src/block/recovered.rs +++ b/crates/primitives-traits/src/block/recovered.rs @@ -445,9 +445,9 @@ impl Eq for RecoveredBlock {} impl PartialEq for RecoveredBlock { fn eq(&self, other: &Self) -> bool { - self.hash_ref().eq(other.hash_ref()) - && self.block.eq(&other.block) - && self.senders.eq(&other.senders) + self.hash_ref().eq(other.hash_ref()) && + self.block.eq(&other.block) && + self.senders.eq(&other.senders) } } diff --git a/crates/primitives-traits/src/block/sealed.rs b/crates/primitives-traits/src/block/sealed.rs index 61663dcb6f..dd0bc0b665 100644 --- a/crates/primitives-traits/src/block/sealed.rs +++ b/crates/primitives-traits/src/block/sealed.rs @@ -266,7 +266,7 @@ impl SealedBlock { return Err(GotExpected { got: calculated_root, expected: self.header().transactions_root(), - }); + }) } Ok(()) diff --git a/crates/primitives-traits/src/size.rs b/crates/primitives-traits/src/size.rs index 24ba3bb200..21b192b6bc 100644 --- a/crates/primitives-traits/src/size.rs +++ b/crates/primitives-traits/src/size.rs @@ -72,9 +72,9 @@ impl_in_mem_size_size_of!(op_alloy_consensus::OpTxType); impl InMemorySize for alloy_consensus::Receipt { fn size(&self) -> usize { let Self { status, cumulative_gas_used, logs } = self; - core::mem::size_of_val(status) - + core::mem::size_of_val(cumulative_gas_used) - + logs.capacity() * core::mem::size_of::() + core::mem::size_of_val(status) + + core::mem::size_of_val(cumulative_gas_used) + + logs.capacity() * core::mem::size_of::() } } @@ -94,12 +94,11 @@ impl InMemorySize for alloy_consensus::BlockBo /// Calculates a heuristic for the in-memory size of the block body #[inline] fn size(&self) -> usize { - self.transactions.iter().map(T::size).sum::() - + self.transactions.capacity() * core::mem::size_of::() - + self.ommers.iter().map(H::size).sum::() - + self.ommers.capacity() * core::mem::size_of::

() - + self - .withdrawals + self.transactions.iter().map(T::size).sum::() + + self.transactions.capacity() * core::mem::size_of::() + + self.ommers.iter().map(H::size).sum::() + + self.ommers.capacity() * core::mem::size_of::
() + + self.withdrawals .as_ref() .map_or(core::mem::size_of::>(), Withdrawals::total_size) } @@ -133,9 +132,9 @@ mod op { impl InMemorySize for op_alloy_consensus::OpDepositReceipt { fn size(&self) -> usize { let Self { inner, deposit_nonce, deposit_receipt_version } = self; - inner.size() - + core::mem::size_of_val(deposit_nonce) - + core::mem::size_of_val(deposit_receipt_version) + inner.size() + + core::mem::size_of_val(deposit_nonce) + + core::mem::size_of_val(deposit_receipt_version) } } diff --git a/crates/primitives-traits/src/withdrawal.rs b/crates/primitives-traits/src/withdrawal.rs index 8c436c0090..0849ab6202 100644 --- a/crates/primitives-traits/src/withdrawal.rs +++ b/crates/primitives-traits/src/withdrawal.rs @@ -40,10 +40,10 @@ mod tests { impl PartialEq for RethWithdrawal { fn eq(&self, other: &Withdrawal) -> bool { - self.index == other.index - && self.validator_index == other.validator_index - && self.address == other.address - && self.amount == other.amount + self.index == other.index && + self.validator_index == other.validator_index && + self.address == other.address && + self.amount == other.amount } } diff --git a/crates/prune/prune/src/db_ext.rs b/crates/prune/prune/src/db_ext.rs index 7c7e05c1fb..63ab87c446 100644 --- a/crates/prune/prune/src/db_ext.rs +++ b/crates/prune/prune/src/db_ext.rs @@ -33,7 +33,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { table = %T::NAME, "Pruning limit reached" ); - break; + break } let row = cursor.seek_exact(key)?; @@ -76,7 +76,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { table = %T::NAME, "Pruning limit reached" ); - break false; + break false } let done = self.prune_table_with_range_step( @@ -87,7 +87,7 @@ pub(crate) trait DbTxPruneExt: DbTxMut { )?; if done { - break true; + break true } deleted_entries += 1; }; diff --git a/crates/prune/prune/src/pruner.rs b/crates/prune/prune/src/pruner.rs index f357aba7cf..60fa7a8b5c 100644 --- a/crates/prune/prune/src/pruner.rs +++ b/crates/prune/prune/src/pruner.rs @@ -120,13 +120,13 @@ where let Some(tip_block_number) = self.adjust_tip_block_number_to_finished_exex_height(tip_block_number) else { - return Ok(PruneProgress::Finished.into()); + return Ok(PruneProgress::Finished.into()) }; if tip_block_number == 0 { self.previous_tip_block_number = Some(tip_block_number); debug!(target: "pruner", %tip_block_number, "Nothing to prune yet"); - return Ok(PruneProgress::Finished.into()); + return Ok(PruneProgress::Finished.into()) } self.event_sender.notify(PrunerEvent::Started { tip_block_number }); @@ -189,7 +189,7 @@ where for segment in &self.segments { if limiter.is_limit_reached() { - break; + break } if let Some((to_block, prune_mode)) = segment @@ -270,14 +270,14 @@ where let Some(tip_block_number) = self.adjust_tip_block_number_to_finished_exex_height(tip_block_number) else { - return false; + return false }; // Saturating subtraction is needed for the case when the chain was reverted, meaning // current block number might be less than the previous tip block number. // If that's the case, no pruning is needed as outdated data is also reverted. - if tip_block_number.saturating_sub(self.previous_tip_block_number.unwrap_or_default()) - >= self.min_block_interval as u64 + if tip_block_number.saturating_sub(self.previous_tip_block_number.unwrap_or_default()) >= + self.min_block_interval as u64 { debug!( target: "pruner", diff --git a/crates/prune/prune/src/segments/mod.rs b/crates/prune/prune/src/segments/mod.rs index c2bfaaa2b9..c34e3a322a 100644 --- a/crates/prune/prune/src/segments/mod.rs +++ b/crates/prune/prune/src/segments/mod.rs @@ -95,7 +95,7 @@ impl PruneInput { // Prevents a scenario where the pruner correctly starts at a finalized block, // but the first transaction (tx_num = 0) only appears on a non-finalized one. // Should only happen on a test/hive scenario. - return Ok(None); + return Ok(None) } last_tx } @@ -104,7 +104,7 @@ impl PruneInput { let range = from_tx_number..=to_tx_number; if range.is_empty() { - return Ok(None); + return Ok(None) } Ok(Some(range)) @@ -122,7 +122,7 @@ impl PruneInput { let from_block = self.get_start_next_block_range(); let range = from_block..=self.to_block; if range.is_empty() { - return None; + return None } Some(range) diff --git a/crates/prune/prune/src/segments/receipts.rs b/crates/prune/prune/src/segments/receipts.rs index 2cfe72eddb..2c94b5e4a8 100644 --- a/crates/prune/prune/src/segments/receipts.rs +++ b/crates/prune/prune/src/segments/receipts.rs @@ -29,7 +29,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No receipts to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; let tx_range_end = *tx_range.end(); @@ -161,8 +161,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize - + input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/set.rs b/crates/prune/prune/src/segments/set.rs index 3fd9bf466c..52e6ee7544 100644 --- a/crates/prune/prune/src/segments/set.rs +++ b/crates/prune/prune/src/segments/set.rs @@ -34,7 +34,7 @@ impl SegmentSet { /// Adds new [Segment] to collection if it's [Some]. pub fn segment_opt + 'static>(self, segment: Option) -> Self { if let Some(segment) = segment { - return self.segment(segment); + return self.segment(segment) } self } diff --git a/crates/prune/prune/src/segments/static_file/headers.rs b/crates/prune/prune/src/segments/static_file/headers.rs index 1c80850898..be4e50fe48 100644 --- a/crates/prune/prune/src/segments/static_file/headers.rs +++ b/crates/prune/prune/src/segments/static_file/headers.rs @@ -54,7 +54,7 @@ impl> Segment (*range.start(), *range.end()), None => { trace!(target: "pruner", "No headers to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; @@ -144,7 +144,7 @@ where type Item = Result; fn next(&mut self) -> Option { if self.limiter.is_limit_reached() { - return None; + return None } let mut pruned_block_headers = None; @@ -157,7 +157,7 @@ where &mut |_| false, &mut |row| pruned_block_headers = Some(row.0), ) { - return Some(Err(err.into())); + return Some(Err(err.into())) } if let Err(err) = self.provider.tx_ref().prune_table_with_range_step( @@ -166,7 +166,7 @@ where &mut |_| false, &mut |row| pruned_block_td = Some(row.0), ) { - return Some(Err(err.into())); + return Some(Err(err.into())) } if let Err(err) = self.provider.tx_ref().prune_table_with_range_step( @@ -175,13 +175,13 @@ where &mut |_| false, &mut |row| pruned_block_canonical = Some(row.0), ) { - return Some(Err(err.into())); + return Some(Err(err.into())) } if ![pruned_block_headers, pruned_block_td, pruned_block_canonical].iter().all_equal() { return Some(Err(PrunerError::InconsistentData( "All headers-related tables should be pruned up to the same height", - ))); + ))) } pruned_block_headers.map(move |block| { @@ -278,8 +278,8 @@ mod tests { provider.commit().expect("commit"); let last_pruned_block_number = to_block.min( - next_block_number_to_prune - + (input.limiter.deleted_entries_limit().unwrap() / HEADER_TABLES_TO_PRUNE - 1) + next_block_number_to_prune + + (input.limiter.deleted_entries_limit().unwrap() / HEADER_TABLES_TO_PRUNE - 1) as u64, ); diff --git a/crates/prune/prune/src/segments/static_file/transactions.rs b/crates/prune/prune/src/segments/static_file/transactions.rs index 21b4f9b262..409e7f9b3d 100644 --- a/crates/prune/prune/src/segments/static_file/transactions.rs +++ b/crates/prune/prune/src/segments/static_file/transactions.rs @@ -53,7 +53,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transactions to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; @@ -178,8 +178,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize - + input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/user/account_history.rs b/crates/prune/prune/src/segments/user/account_history.rs index 75ab52518b..7780a9e07e 100644 --- a/crates/prune/prune/src/segments/user/account_history.rs +++ b/crates/prune/prune/src/segments/user/account_history.rs @@ -51,7 +51,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No account history to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; let range_end = *range.end(); @@ -65,7 +65,7 @@ where return Ok(SegmentOutput::not_done( limiter.interrupt_reason(), input.previous_checkpoint.map(SegmentOutputCheckpoint::from_prune_checkpoint), - )); + )) } let mut last_changeset_pruned_block = None; @@ -232,8 +232,8 @@ mod tests { .iter() .enumerate() .skip_while(|(i, (block_number, _))| { - *i < deleted_entries_limit / ACCOUNT_HISTORY_TABLES_TO_PRUNE * run - && *block_number <= to_block as usize + *i < deleted_entries_limit / ACCOUNT_HISTORY_TABLES_TO_PRUNE * run && + *block_number <= to_block as usize }) .next() .map(|(i, _)| i) diff --git a/crates/prune/prune/src/segments/user/history.rs b/crates/prune/prune/src/segments/user/history.rs index 91f825370f..9d95b2fd3b 100644 --- a/crates/prune/prune/src/segments/user/history.rs +++ b/crates/prune/prune/src/segments/user/history.rs @@ -49,7 +49,7 @@ where let Some((key, block_nums)) = shard.map(|(k, v)| Result::<_, DatabaseError>::Ok((k.key()?, v))).transpose()? else { - break; + break }; if key_matches(&key, &sharded_key) { @@ -60,7 +60,7 @@ where } } else { // If such shard doesn't exist, skip to the next sharded key - break 'shard; + break 'shard } shard = cursor.next()?; diff --git a/crates/prune/prune/src/segments/user/receipts_by_logs.rs b/crates/prune/prune/src/segments/user/receipts_by_logs.rs index 5e4510f737..b413a70394 100644 --- a/crates/prune/prune/src/segments/user/receipts_by_logs.rs +++ b/crates/prune/prune/src/segments/user/receipts_by_logs.rs @@ -141,7 +141,7 @@ where ?block_range, "No receipts to prune." ); - continue; + continue } }; let tx_range = from_tx_number..=tx_range_end; @@ -155,11 +155,10 @@ where tx_range, &mut limiter, |(tx_num, receipt)| { - let skip = num_addresses > 0 - && receipt - .logs() - .iter() - .any(|log| filtered_addresses[..num_addresses].contains(&&log.address)); + let skip = num_addresses > 0 && + receipt.logs().iter().any(|log| { + filtered_addresses[..num_addresses].contains(&&log.address) + }); if skip { last_skipped_transaction = *tx_num; @@ -191,7 +190,7 @@ where if limiter.is_limit_reached() { done &= end_block == to_block; - break; + break } from_tx_number = last_pruned_transaction + 1; @@ -337,8 +336,8 @@ mod tests { assert_eq!( db.table::().unwrap().len(), - blocks.iter().map(|block| block.transaction_count()).sum::() - - ((pruned_tx + 1) - unprunable) as usize + blocks.iter().map(|block| block.transaction_count()).sum::() - + ((pruned_tx + 1) - unprunable) as usize ); output.progress.is_finished() @@ -355,8 +354,8 @@ mod tests { // Either we only find our contract, or the receipt is part of the unprunable receipts // set by tip - 128 assert!( - receipt.logs.iter().any(|l| l.address == deposit_contract_addr) - || provider.transaction_block(tx_num).unwrap().unwrap() > tip - 128, + receipt.logs.iter().any(|l| l.address == deposit_contract_addr) || + provider.transaction_block(tx_num).unwrap().unwrap() > tip - 128, ); } } diff --git a/crates/prune/prune/src/segments/user/sender_recovery.rs b/crates/prune/prune/src/segments/user/sender_recovery.rs index 99f2656d8e..f379fb9951 100644 --- a/crates/prune/prune/src/segments/user/sender_recovery.rs +++ b/crates/prune/prune/src/segments/user/sender_recovery.rs @@ -43,7 +43,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transaction senders to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; let tx_range_end = *tx_range.end(); @@ -162,8 +162,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize - + input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/prune/src/segments/user/storage_history.rs b/crates/prune/prune/src/segments/user/storage_history.rs index 21de15a17b..aa9cb84644 100644 --- a/crates/prune/prune/src/segments/user/storage_history.rs +++ b/crates/prune/prune/src/segments/user/storage_history.rs @@ -53,7 +53,7 @@ where Some(range) => range, None => { trace!(target: "pruner", "No storage history to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } }; let range_end = *range.end(); @@ -67,7 +67,7 @@ where return Ok(SegmentOutput::not_done( limiter.interrupt_reason(), input.previous_checkpoint.map(SegmentOutputCheckpoint::from_prune_checkpoint), - )); + )) } let mut last_changeset_pruned_block = None; @@ -240,8 +240,8 @@ mod tests { .iter() .enumerate() .skip_while(|(i, (block_number, _, _))| { - *i < deleted_entries_limit / STORAGE_HISTORY_TABLES_TO_PRUNE * run - && *block_number <= to_block as usize + *i < deleted_entries_limit / STORAGE_HISTORY_TABLES_TO_PRUNE * run && + *block_number <= to_block as usize }) .next() .map(|(i, _)| i) diff --git a/crates/prune/prune/src/segments/user/transaction_lookup.rs b/crates/prune/prune/src/segments/user/transaction_lookup.rs index ed7e92cebb..92a69dfd12 100644 --- a/crates/prune/prune/src/segments/user/transaction_lookup.rs +++ b/crates/prune/prune/src/segments/user/transaction_lookup.rs @@ -43,12 +43,12 @@ where Some(range) => range, None => { trace!(target: "pruner", "No transaction lookup entries to prune"); - return Ok(SegmentOutput::done()); + return Ok(SegmentOutput::done()) } } .into_inner(); - let tx_range = start - ..=Some(end) + let tx_range = start..= + Some(end) .min(input.limiter.deleted_entries_limit_left().map(|left| start + left as u64 - 1)) .unwrap(); let tx_range_end = *tx_range.end(); @@ -65,7 +65,7 @@ where if hashes.len() != tx_count { return Err(PrunerError::InconsistentData( "Unexpected number of transaction hashes retrieved by transaction number range", - )); + )) } let mut limiter = input.limiter; @@ -187,8 +187,8 @@ mod tests { .map(|block| block.transaction_count()) .sum::() .min( - next_tx_number_to_prune as usize - + input.limiter.deleted_entries_limit().unwrap(), + next_tx_number_to_prune as usize + + input.limiter.deleted_entries_limit().unwrap(), ) .sub(1); diff --git a/crates/prune/types/src/lib.rs b/crates/prune/types/src/lib.rs index 761e5c3a00..c1d268a0fb 100644 --- a/crates/prune/types/src/lib.rs +++ b/crates/prune/types/src/lib.rs @@ -77,8 +77,8 @@ impl ReceiptsLogPruneConfig { let block = base_block.max( mode.prune_target_block(tip, PruneSegment::ContractLogs, PrunePurpose::User)? .map(|(block, _)| block) - .unwrap_or_default() - + 1, + .unwrap_or_default() + + 1, ); map.entry(block).or_insert_with(Vec::new).push(address) diff --git a/crates/prune/types/src/mode.rs b/crates/prune/types/src/mode.rs index 78e2b80023..42d34b30cc 100644 --- a/crates/prune/types/src/mode.rs +++ b/crates/prune/types/src/mode.rs @@ -62,7 +62,7 @@ impl PruneMode { Self::Full => true, Self::Distance(distance) => { if *distance > tip { - return false; + return false } block < tip - *distance } diff --git a/crates/ress/protocol/src/connection.rs b/crates/ress/protocol/src/connection.rs index e9a8fce59a..e97c4a0e90 100644 --- a/crates/ress/protocol/src/connection.rs +++ b/crates/ress/protocol/src/connection.rs @@ -264,12 +264,12 @@ where let this = self.get_mut(); if this.terminated { - return Poll::Ready(None); + return Poll::Ready(None) } if !this.node_type_sent { this.node_type_sent = true; - return Poll::Ready(Some(RessProtocolMessage::node_type(this.node_type).encoded())); + return Poll::Ready(Some(RessProtocolMessage::node_type(this.node_type).encoded())) } 'conn: loop { diff --git a/crates/ress/protocol/src/provider.rs b/crates/ress/protocol/src/provider.rs index 1e3709e082..bac8b1f5f0 100644 --- a/crates/ress/protocol/src/provider.rs +++ b/crates/ress/protocol/src/provider.rs @@ -21,11 +21,11 @@ pub trait RessProtocolProvider: Send + Sync { block_hash = header.parent_hash; total_bytes += header.length(); headers.push(header); - if headers.len() >= request.limit as usize - || headers.len() >= MAX_HEADERS_SERVE - || total_bytes > SOFT_RESPONSE_LIMIT + if headers.len() >= request.limit as usize || + headers.len() >= MAX_HEADERS_SERVE || + total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } Ok(headers) @@ -43,10 +43,10 @@ pub trait RessProtocolProvider: Send + Sync { total_bytes += body.length(); bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE || total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } Ok(bodies) diff --git a/crates/ress/protocol/tests/it/e2e.rs b/crates/ress/protocol/tests/it/e2e.rs index 00b5648f8c..5259e763a5 100644 --- a/crates/ress/protocol/tests/it/e2e.rs +++ b/crates/ress/protocol/tests/it/e2e.rs @@ -66,7 +66,7 @@ async fn disconnect_on_stateful_pair() { peer0_event_listener.next().await.unwrap() { assert_eq!(peer_id, *handle.peers()[1].peer_id()); - break; + break } } @@ -76,7 +76,7 @@ async fn disconnect_on_stateful_pair() { peer1_event_listener.next().await.unwrap() { assert_eq!(peer_id, *handle.peers()[0].peer_id()); - break; + break } } } diff --git a/crates/ress/provider/src/lib.rs b/crates/ress/provider/src/lib.rs index 30f7c8ed1d..41318ebaaf 100644 --- a/crates/ress/provider/src/lib.rs +++ b/crates/ress/provider/src/lib.rs @@ -97,7 +97,7 @@ where /// Generate state witness pub fn generate_witness(&self, block_hash: B256) -> ProviderResult> { if let Some(witness) = self.witness_cache.lock().get(&block_hash).cloned() { - return Ok(witness.as_ref().clone()); + return Ok(witness.as_ref().clone()) } let block = @@ -107,7 +107,7 @@ where if best_block_number.saturating_sub(block.number()) > self.max_witness_window { return Err(ProviderError::TrieWitnessError( "witness target block exceeds maximum witness window".to_owned(), - )); + )) } let mut executed_ancestors = Vec::new(); @@ -136,7 +136,7 @@ where } let Some(executed) = executed else { - return Err(ProviderError::StateForHashNotFound(ancestor_hash)); + return Err(ProviderError::StateForHashNotFound(ancestor_hash)) }; ancestor_hash = executed.sealed_block().parent_hash(); executed_ancestors.push(executed); diff --git a/crates/ress/provider/src/pending_state.rs b/crates/ress/provider/src/pending_state.rs index bebf73b4e3..1c4c81e29e 100644 --- a/crates/ress/provider/src/pending_state.rs +++ b/crates/ress/provider/src/pending_state.rs @@ -101,8 +101,8 @@ pub async fn maintain_pending_state

( { while let Some(event) = events.next().await { match event { - BeaconConsensusEngineEvent::CanonicalBlockAdded(block, _) - | BeaconConsensusEngineEvent::ForkBlockAdded(block, _) => { + BeaconConsensusEngineEvent::CanonicalBlockAdded(block, _) | + BeaconConsensusEngineEvent::ForkBlockAdded(block, _) => { trace!(target: "reth::ress_provider", block = ? block.recovered_block().num_hash(), "Insert block into pending state"); pending_state.insert_block(block); } @@ -122,9 +122,9 @@ pub async fn maintain_pending_state

( } } // ignore - BeaconConsensusEngineEvent::CanonicalChainCommitted(_, _) - | BeaconConsensusEngineEvent::BlockReceived(_) - | BeaconConsensusEngineEvent::LiveSyncProgress(_) => (), + BeaconConsensusEngineEvent::CanonicalChainCommitted(_, _) | + BeaconConsensusEngineEvent::BlockReceived(_) | + BeaconConsensusEngineEvent::LiveSyncProgress(_) => (), } } } diff --git a/crates/revm/src/cached.rs b/crates/revm/src/cached.rs index cbc17fa969..bf4bd6d5d1 100644 --- a/crates/revm/src/cached.rs +++ b/crates/revm/src/cached.rs @@ -235,20 +235,20 @@ mod tests { // Verify the combined state assert!( - primary.accounts.len() == 2 - && primary.contracts.len() == 2 - && primary.block_hashes.len() == 2, + primary.accounts.len() == 2 && + primary.contracts.len() == 2 && + primary.block_hashes.len() == 2, "All maps should contain 2 entries" ); // Verify specific entries assert!( - primary.accounts.contains_key(&address1) - && primary.accounts.contains_key(&address2) - && primary.contracts.contains_key(&hash1) - && primary.contracts.contains_key(&hash2) - && primary.block_hashes.get(&1) == Some(&hash1) - && primary.block_hashes.get(&2) == Some(&hash2), + primary.accounts.contains_key(&address1) && + primary.accounts.contains_key(&address2) && + primary.contracts.contains_key(&hash1) && + primary.contracts.contains_key(&hash2) && + primary.block_hashes.get(&1) == Some(&hash1) && + primary.block_hashes.get(&2) == Some(&hash2), "All expected entries should be present" ); } diff --git a/crates/rpc/ipc/src/server/connection.rs b/crates/rpc/ipc/src/server/connection.rs index 63582769af..0734296b98 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 b64c5be785..19992ead49 100644 --- a/crates/rpc/ipc/src/server/ipc.rs +++ b/crates/rpc/ipc/src/server/ipc.rs @@ -66,7 +66,7 @@ where while let Some(response) = pending_calls.next().await { if let Err(too_large) = batch_response.append(response) { - return Some(too_large.to_json().to_string()); + return Some(too_large.to_json().to_string()) } } @@ -138,7 +138,7 @@ where return Some( batch_response_error(Id::Null, reject_too_big_request(max_request_body_size as u32)) .to_string(), - ); + ) } // Single request or notification diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index 46a60abb09..4205081e3d 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 b08db390ae..b1a4f4166b 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -337,7 +337,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 18098a7d16..c68cf84942 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 343173e14d..4dcce346c0 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -1192,9 +1192,9 @@ impl RpcServerConfig { /// /// If no server is configured, no server will be launched on [`RpcServerConfig::start`]. pub const fn has_server(&self) -> bool { - self.http_server_config.is_some() - || self.ws_server_config.is_some() - || self.ipc_server_config.is_some() + self.http_server_config.is_some() || + self.ws_server_config.is_some() || + self.ipc_server_config.is_some() } /// Returns the [`SocketAddr`] of the http server @@ -1267,9 +1267,9 @@ impl RpcServerConfig { } // If both are configured on the same port, we combine them into one server. - if self.http_addr == self.ws_addr - && self.http_server_config.is_some() - && self.ws_server_config.is_some() + if self.http_addr == self.ws_addr && + self.http_server_config.is_some() && + self.ws_server_config.is_some() { let cors = match (self.ws_cors_domains.as_ref(), self.http_cors_domains.as_ref()) { (Some(ws_cors), Some(http_cors)) => { @@ -1642,7 +1642,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) } @@ -1654,7 +1654,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) } @@ -1666,7 +1666,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) } @@ -1982,8 +1982,8 @@ impl RpcServerHandle { "Bearer {}", secret .encode(&Claims { - iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() - + Duration::from_secs(60)) + iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + + Duration::from_secs(60)) .as_secs(), exp: None, }) diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index 1047b534a9..d21d6f915a 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -33,8 +33,8 @@ use std::collections::HashSet; fn is_unimplemented(err: jsonrpsee::core::client::Error) -> bool { match err { jsonrpsee::core::client::Error::Call(error_obj) => { - error_obj.code() == ErrorCode::InternalError.code() - && error_obj.message() == "unimplemented" + error_obj.code() == ErrorCode::InternalError.code() && + error_obj.message() == "unimplemented" } _ => false, } diff --git a/crates/rpc/rpc-convert/src/fees.rs b/crates/rpc/rpc-convert/src/fees.rs index e19a68d402..46f8fc8c20 100644 --- a/crates/rpc/rpc-convert/src/fees.rs +++ b/crates/rpc/rpc-convert/src/fees.rs @@ -60,17 +60,17 @@ impl CallFees { let max_priority_fee_per_gas = max_priority_fee_per_gas.unwrap_or(U256::ZERO); // only enforce the fee cap if provided input is not zero - if !(max_fee.is_zero() && max_priority_fee_per_gas.is_zero()) - && max_fee < block_base_fee + if !(max_fee.is_zero() && max_priority_fee_per_gas.is_zero()) && + max_fee < block_base_fee { // `base_fee_per_gas` is greater than the `max_fee_per_gas` - return Err(CallFeesError::FeeCapTooLow); + return Err(CallFeesError::FeeCapTooLow) } if max_fee < max_priority_fee_per_gas { return Err( // `max_priority_fee_per_gas` is greater than the `max_fee_per_gas` CallFeesError::TipAboveFeeCap, - ); + ) } // ref Ok(min( @@ -125,7 +125,7 @@ impl CallFees { // Ensure blob_hashes are present if !has_blob_hashes { // Blob transaction but no blob hashes - return Err(CallFeesError::BlobTransactionMissingBlobHashes); + return Err(CallFeesError::BlobTransactionMissingBlobHashes) } Ok(Self { diff --git a/crates/rpc/rpc-convert/src/transaction.rs b/crates/rpc/rpc-convert/src/transaction.rs index 93592bab70..68dc1a2974 100644 --- a/crates/rpc/rpc-convert/src/transaction.rs +++ b/crates/rpc/rpc-convert/src/transaction.rs @@ -224,7 +224,7 @@ impl TryIntoTxEnv for TransactionRequest { ) -> Result { // Ensure that if versioned hashes are set, they're not empty if self.blob_versioned_hashes.as_ref().is_some_and(|hashes| hashes.is_empty()) { - return Err(CallFeesError::BlobTransactionMissingBlobHashes.into()); + return Err(CallFeesError::BlobTransactionMissingBlobHashes.into()) } let tx_type = self.minimal_tx_type() as u8; diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index 681a53a9f7..3066b440a4 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -726,9 +726,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()) } } @@ -745,7 +745,7 @@ where versioned_hashes: Vec, ) -> EngineApiResult>> { if versioned_hashes.len() > MAX_BLOB_LIMIT { - return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }); + return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }) } self.inner @@ -779,7 +779,7 @@ where versioned_hashes: Vec, ) -> EngineApiResult>> { if versioned_hashes.len() > MAX_BLOB_LIMIT { - return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }); + return Err(EngineApiError::BlobRequestTooLarge { len: versioned_hashes.len() }) } self.inner @@ -1341,8 +1341,8 @@ mod tests { blocks .iter() .filter(|b| { - !first_missing_range.contains(&b.number) - && !second_missing_range.contains(&b.number) + !first_missing_range.contains(&b.number) && + !second_missing_range.contains(&b.number) }) .map(|b| (b.hash(), b.clone().into_block())), ); @@ -1371,8 +1371,8 @@ mod tests { // ensure we still return trailing `None`s here because by-hash will not be aware // of the missing block's number, and cannot compare it to the current best block .map(|b| { - if first_missing_range.contains(&b.number) - || second_missing_range.contains(&b.number) + if first_missing_range.contains(&b.number) || + second_missing_range.contains(&b.number) { None } else { diff --git a/crates/rpc/rpc-engine-api/src/error.rs b/crates/rpc/rpc-engine-api/src/error.rs index 3d41c9d2ad..2578b2f44e 100644 --- a/crates/rpc/rpc-engine-api/src/error.rs +++ b/crates/rpc/rpc-engine-api/src/error.rs @@ -128,12 +128,12 @@ impl ErrorData { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(error: EngineApiError) -> Self { match error { - EngineApiError::InvalidBodiesRange { .. } - | EngineApiError::EngineObjectValidationError( - EngineObjectValidationError::Payload(_) - | EngineObjectValidationError::InvalidParams(_), - ) - | EngineApiError::UnexpectedRequestsHash => { + EngineApiError::InvalidBodiesRange { .. } | + EngineApiError::EngineObjectValidationError( + EngineObjectValidationError::Payload(_) | + EngineObjectValidationError::InvalidParams(_), + ) | + EngineApiError::UnexpectedRequestsHash => { // Note: the data field is not required by the spec, but is also included by other // clients jsonrpsee_types::error::ErrorObject::owned( @@ -158,8 +158,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { error.to_string(), None::<()>, ), - EngineApiError::PayloadRequestTooLarge { .. } - | EngineApiError::BlobRequestTooLarge { .. } => { + EngineApiError::PayloadRequestTooLarge { .. } | + EngineApiError::BlobRequestTooLarge { .. } => { jsonrpsee_types::error::ErrorObject::owned( REQUEST_TOO_LARGE_CODE, REQUEST_TOO_LARGE_MESSAGE, @@ -183,8 +183,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { None::<()>, ) } - ForkchoiceUpdateError::InvalidState - | ForkchoiceUpdateError::UnknownFinalBlock => { + ForkchoiceUpdateError::InvalidState | + ForkchoiceUpdateError::UnknownFinalBlock => { jsonrpsee_types::error::ErrorObject::owned( INVALID_FORK_CHOICE_STATE_ERROR, INVALID_FORK_CHOICE_STATE_ERROR_MSG, @@ -192,8 +192,8 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { ) } }, - BeaconForkChoiceUpdateError::EngineUnavailable - | BeaconForkChoiceUpdateError::Internal(_) => { + BeaconForkChoiceUpdateError::EngineUnavailable | + BeaconForkChoiceUpdateError::Internal(_) => { jsonrpsee_types::error::ErrorObject::owned( INTERNAL_ERROR_CODE, SERVER_ERROR_MSG, @@ -202,11 +202,11 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { } }, // Any other server error - EngineApiError::TerminalTD { .. } - | EngineApiError::TerminalBlockHash { .. } - | EngineApiError::NewPayload(_) - | EngineApiError::Internal(_) - | EngineApiError::GetPayloadError(_) => jsonrpsee_types::error::ErrorObject::owned( + EngineApiError::TerminalTD { .. } | + EngineApiError::TerminalBlockHash { .. } | + EngineApiError::NewPayload(_) | + EngineApiError::Internal(_) | + EngineApiError::GetPayloadError(_) => jsonrpsee_types::error::ErrorObject::owned( INTERNAL_ERROR_CODE, SERVER_ERROR_MSG, Some(ErrorData::new(error)), diff --git a/crates/rpc/rpc-eth-api/src/helpers/block.rs b/crates/rpc/rpc-eth-api/src/helpers/block.rs index c407a32887..91a6739b8b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/block.rs @@ -80,7 +80,7 @@ pub trait EthBlocks: LoadBlock { .provider() .pending_block() .map_err(Self::Error::from_eth_err)? - .map(|block| block.body().transactions().len())); + .map(|block| block.body().transactions().len())) } let block_hash = match self @@ -147,7 +147,7 @@ pub trait EthBlocks: LoadBlock { .get_block_and_receipts(block_hash) .await .map_err(Self::Error::from_eth_err) - .map(|b| b.map(|(b, r)| (b.clone_sealed_block(), r))); + .map(|b| b.map(|(b, r)| (b.clone_sealed_block(), r))) } 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 6607e96444..12d63243f1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/call.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/call.rs @@ -76,7 +76,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA ) -> impl Future> + Send { async move { if payload.block_state_calls.len() > self.max_simulate_blocks() as usize { - return Err(EthApiError::InvalidParams("too many blocks.".to_string()).into()); + return Err(EthApiError::InvalidParams("too many blocks.".to_string()).into()) } let block = block.unwrap_or_default(); @@ -89,7 +89,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA } = payload; if block_state_calls.is_empty() { - return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()); + return Err(EthApiError::InvalidParams(String::from("calls are empty.")).into()) } let base_block = @@ -124,12 +124,12 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA if let Some(block_overrides) = block_overrides { // ensure we don't allow uncapped gas limit per block if let Some(gas_limit_override) = block_overrides.gas_limit { - if gas_limit_override > evm_env.block_env.gas_limit - && gas_limit_override > this.call_gas_limit() + if gas_limit_override > evm_env.block_env.gas_limit && + gas_limit_override > this.call_gas_limit() { return Err( EthApiError::other(EthSimulateError::GasLimitReached).into() - ); + ) } } apply_block_overrides(block_overrides, &mut db, &mut evm_env.block_env); @@ -151,7 +151,7 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA return Err(EthApiError::Other(Box::new( EthSimulateError::BlockGasLimitExceeded, )) - .into()); + .into()) } if txs_without_gas_limit > 0 { @@ -421,11 +421,11 @@ pub trait EthCall: EstimateCall + Call + LoadPendingBlock + LoadBlock + FullEthA ExecutionResult::Halt { reason, gas_used } => { let error = Some(Self::Error::from_evm_halt(reason, tx_env.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 { .. } => {} }; @@ -683,7 +683,7 @@ pub trait Call: for tx in transactions { if *tx.tx_hash() == target_tx_hash { // reached the target transaction - break; + break } let tx_env = self.evm_config().tx_env(tx); @@ -744,7 +744,7 @@ pub trait Call: // configured gas exceeds limit return Err( EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into() - ); + ) } // apply configured gas cap diff --git a/crates/rpc/rpc-eth-api/src/helpers/estimate.rs b/crates/rpc/rpc-eth-api/src/helpers/estimate.rs index 1e91c06ed0..91af2c37e4 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/estimate.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/estimate.rs @@ -119,7 +119,7 @@ pub trait EstimateCall: Call { // Reuse the same EVM instance if let Ok(res) = evm.transact(min_tx_env).map_err(Self::Error::from_evm_err) { if res.result.is_success() { - return Ok(U256::from(MIN_TRANSACTION_GAS)); + return Ok(U256::from(MIN_TRANSACTION_GAS)) } } } @@ -133,8 +133,8 @@ pub trait EstimateCall: Call { // retry the transaction with the block's gas limit to determine if // the failure was due to insufficient gas. Err(err) - if err.is_gas_too_high() - && (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) => + if err.is_gas_too_high() && + (tx_request_gas_limit.is_some() || tx_request_gas_price.is_some()) => { return Self::map_out_of_gas_err(&mut evm, tx_env, block_env_gas_limit); } @@ -146,7 +146,7 @@ pub trait EstimateCall: Call { return Err(RpcInvalidTransactionError::GasRequiredExceedsAllowance { gas_limit: tx_env.gas_limit(), } - .into_eth_err()); + .into_eth_err()) } // Propagate other results (successful or other errors). ethres => ethres?, @@ -157,7 +157,7 @@ pub trait EstimateCall: Call { ExecutionResult::Halt { reason, .. } => { // here we don't check for invalid opcode because already executed with highest gas // limit - return Err(Self::Error::from_evm_halt(reason, tx_env.gas_limit())); + return Err(Self::Error::from_evm_halt(reason, tx_env.gas_limit())) } ExecutionResult::Revert { output, .. } => { // if price or limit was included in the request then we can execute the request @@ -167,7 +167,7 @@ pub trait EstimateCall: Call { } else { // the transaction did revert Err(RpcInvalidTransactionError::Revert(RevertError::new(output)).into_eth_err()) - }; + } } }; @@ -225,10 +225,10 @@ pub trait EstimateCall: Call { // An estimation error is allowed once the current gas limit range used in the binary // search is small enough (less than 1.5% of the highest gas limit) // impl Future> + Send { async move { if block_count == 0 { - return Ok(FeeHistory::default()); + return Ok(FeeHistory::default()) } // ensure the given reward percentiles aren't excessive - if reward_percentiles.as_ref().map(|perc| perc.len() as u64) - > Some(self.gas_oracle().config().max_reward_percentile_count) + if reward_percentiles.as_ref().map(|perc| perc.len() as u64) > + Some(self.gas_oracle().config().max_reward_percentile_count) { - return Err(EthApiError::InvalidRewardPercentiles.into()); + return Err(EthApiError::InvalidRewardPercentiles.into()) } // See https://github.com/ethereum/go-ethereum/blob/2754b197c935ee63101cbbca2752338246384fec/eth/gasprice/feehistory.go#L218C8-L225 @@ -111,7 +111,7 @@ pub trait EthFees: // 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()) } } @@ -136,7 +136,7 @@ pub trait EthFees: 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 { @@ -168,12 +168,11 @@ pub trait EthFees: base_fee_per_blob_gas.push(last_entry.next_block_blob_fee().unwrap_or_default()); } else { // read the requested header range - let headers = self - .provider() + let headers = self.provider() .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()) } let chain_spec = self.provider().chain_spec(); @@ -193,8 +192,7 @@ pub trait EthFees: // Percentiles were specified, so we need to collect reward percentile info if let Some(percentiles) = &reward_percentiles { - let (block, receipts) = self - .cache() + let (block, receipts) = self.cache() .get_block_and_receipts(header.hash()) .await .map_err(Self::Error::from_eth_err)? @@ -227,10 +225,9 @@ pub trait EthFees: // > "[..] 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 - .maybe_next_block_blob_fee( - chain_spec.blob_params_at_timestamp(last_header.timestamp()), - ) - .unwrap_or_default(), + .maybe_next_block_blob_fee( + chain_spec.blob_params_at_timestamp(last_header.timestamp()) + ).unwrap_or_default() ); }; 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 55b8236f5f..272f3c18f1 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/pending_block.rs @@ -155,9 +155,9 @@ pub trait LoadPendingBlock: // check if the block is still good if let Some(pending_block) = lock.as_ref() { // this is guaranteed to be the `latest` header - if pending.evm_env.block_env.number == U256::from(pending_block.block.number()) - && parent.hash() == pending_block.block.parent_hash() - && now <= pending_block.expires_at + if pending.evm_env.block_env.number == U256::from(pending_block.block.number()) && + parent.hash() == pending_block.block.parent_hash() && + now <= pending_block.expires_at { return Ok(Some((pending_block.block.clone(), pending_block.receipts.clone()))); } @@ -174,7 +174,7 @@ pub trait LoadPendingBlock: Ok(block) => block, Err(err) => { debug!(target: "rpc", "Failed to build pending block: {:?}", err); - return Ok(None); + return Ok(None) } }; @@ -253,7 +253,7 @@ pub trait LoadPendingBlock: block_gas_limit, ), ); - continue; + continue } if pool_tx.origin.is_private() { @@ -266,7 +266,7 @@ pub trait LoadPendingBlock: InvalidTransactionError::TxTypeNotSupported, ), ); - continue; + continue } // convert tx to a signed transaction @@ -287,7 +287,7 @@ pub trait LoadPendingBlock: blob_params.max_blob_gas_per_block(), ), ); - continue; + continue } } @@ -309,7 +309,7 @@ pub trait LoadPendingBlock: ), ); } - continue; + continue } // this is an error that we should treat as fatal for this attempt Err(err) => return Err(Self::Error::from_eth_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 8f8c96c399..4fa4edee8b 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/state.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/state.rs @@ -107,7 +107,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()) } self.spawn_blocking_io(move |this| { @@ -142,7 +142,7 @@ pub trait EthState: LoadState + SpawnBlocking { .ok_or(EthApiError::HeaderNotFound(block_id))?; let max_window = this.max_proof_window(); if chain_info.best_number.saturating_sub(block_number) > max_window { - return Err(EthApiError::ExceedsMaxProofWindow.into()); + return Err(EthApiError::ExceedsMaxProofWindow.into()) } let balance = account.balance; diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index db31a1afb7..31085bdc08 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -294,7 +294,7 @@ pub trait Trace: async move { let block = async { if block.is_some() { - return Ok(block); + return Ok(block) } self.recovered_block(block_id).await }; @@ -305,7 +305,7 @@ pub trait Trace: if block.body().transactions().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 1d5fc19cf4..c0c759d400 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/transaction.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/transaction.rs @@ -158,7 +158,7 @@ pub trait EthTransactions: LoadTransaction { if let Some(tx) = self.pool().get_pooled_transaction_element(hash).map(|tx| tx.encoded_2718().into()) { - return Ok(Some(tx)); + return Ok(Some(tx)) } self.spawn_blocking_io(move |ref this| { @@ -269,7 +269,7 @@ pub trait EthTransactions: LoadTransaction { return Ok(Some( self.tx_resp_builder().fill(tx.clone().with_signer(*signer), tx_info)?, - )); + )) } } @@ -367,7 +367,7 @@ pub trait EthTransactions: LoadTransaction { async move { if let Some(block) = self.recovered_block(block_id).await? { if let Some(tx) = block.body().transactions().get(index) { - return Ok(Some(tx.encoded_2718().into())); + return Ok(Some(tx.encoded_2718().into())) } } @@ -391,7 +391,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 9dc84af42f..a055acac58 100644 --- a/crates/rpc/rpc-eth-types/src/cache/mod.rs +++ b/crates/rpc/rpc-eth-types/src/cache/mod.rs @@ -459,7 +459,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 @@ -488,7 +488,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 @@ -513,13 +513,13 @@ where // check if the header is cached if let Some(header) = this.headers_cache.get(&block_hash).cloned() { let _ = response_tx.send(Ok(header)); - continue; + continue } // it's possible we have the entire block cached if let Some(block) = this.full_block_cache.get(&block_hash) { let _ = response_tx.send(Ok(block.clone_header())); - continue; + continue } // header is not in the cache, request it if this is the first diff --git a/crates/rpc/rpc-eth-types/src/error/api.rs b/crates/rpc/rpc-eth-types/src/error/api.rs index f70f03e199..03641d067e 100644 --- a/crates/rpc/rpc-eth-types/src/error/api.rs +++ b/crates/rpc/rpc-eth-types/src/error/api.rs @@ -58,7 +58,7 @@ pub trait AsEthApiError { /// [`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 @@ -68,7 +68,7 @@ pub trait AsEthApiError { /// [`RpcInvalidTransactionError::GasTooLow`]. fn is_gas_too_low(&self) -> bool { if let Some(err) = self.as_err() { - return err.is_gas_too_low(); + return err.is_gas_too_low() } false diff --git a/crates/rpc/rpc-eth-types/src/error/mod.rs b/crates/rpc/rpc-eth-types/src/error/mod.rs index 04dc0093de..96adc4e67b 100644 --- a/crates/rpc/rpc-eth-types/src/error/mod.rs +++ b/crates/rpc/rpc-eth-types/src/error/mod.rs @@ -207,25 +207,25 @@ impl EthApiError { impl From for jsonrpsee_types::error::ErrorObject<'static> { fn from(error: EthApiError) -> Self { match error { - EthApiError::FailedToDecodeSignedTransaction - | EthApiError::InvalidTransactionSignature - | EthApiError::EmptyRawTransactionData - | EthApiError::InvalidBlockRange - | EthApiError::ExceedsMaxProofWindow - | EthApiError::ConflictingFeeFieldsInRequest - | EthApiError::Signing(_) - | EthApiError::BothStateAndStateDiffInOverride(_) - | EthApiError::InvalidTracerConfig - | EthApiError::TransactionConversionError - | EthApiError::InvalidRewardPercentiles - | EthApiError::InvalidBytecode(_) => invalid_params_rpc_err(error.to_string()), + EthApiError::FailedToDecodeSignedTransaction | + EthApiError::InvalidTransactionSignature | + EthApiError::EmptyRawTransactionData | + EthApiError::InvalidBlockRange | + EthApiError::ExceedsMaxProofWindow | + EthApiError::ConflictingFeeFieldsInRequest | + EthApiError::Signing(_) | + EthApiError::BothStateAndStateDiffInOverride(_) | + EthApiError::InvalidTracerConfig | + EthApiError::TransactionConversionError | + EthApiError::InvalidRewardPercentiles | + EthApiError::InvalidBytecode(_) => invalid_params_rpc_err(error.to_string()), EthApiError::InvalidTransaction(err) => err.into(), EthApiError::PoolError(err) => err.into(), - EthApiError::PrevrandaoNotSet - | EthApiError::ExcessBlobGasNotSet - | EthApiError::InvalidBlockData(_) - | EthApiError::Internal(_) - | EthApiError::EvmCustom(_) => internal_rpc_err(error.to_string()), + EthApiError::PrevrandaoNotSet | + EthApiError::ExcessBlobGasNotSet | + EthApiError::InvalidBlockData(_) | + EthApiError::Internal(_) | + EthApiError::EvmCustom(_) => internal_rpc_err(error.to_string()), EthApiError::UnknownBlockOrTxIndex | EthApiError::TransactionNotFound => { rpc_error_with_code(EthRpcErrorCode::ResourceNotFound.code(), error.to_string()) } @@ -586,14 +586,14 @@ impl RpcInvalidTransactionError { /// Returns the rpc error code for this error. pub const fn error_code(&self) -> i32 { match self { - Self::InvalidChainId - | Self::GasTooLow - | Self::GasTooHigh - | Self::GasRequiredExceedsAllowance { .. } - | Self::NonceTooLow { .. } - | Self::NonceTooHigh { .. } - | Self::FeeCapTooLow - | Self::FeeCapVeryHigh => EthRpcErrorCode::InvalidInput.code(), + Self::InvalidChainId | + Self::GasTooLow | + Self::GasTooHigh | + Self::GasRequiredExceedsAllowance { .. } | + Self::NonceTooLow { .. } | + Self::NonceTooHigh { .. } | + Self::FeeCapTooLow | + Self::FeeCapVeryHigh => EthRpcErrorCode::InvalidInput.code(), Self::Revert(_) => EthRpcErrorCode::ExecutionError.code(), _ => EthRpcErrorCode::TransactionRejected.code(), } @@ -648,8 +648,8 @@ impl From for RpcInvalidTransactionError { } InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap, InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow, - InvalidTransaction::CallerGasLimitMoreThanBlock - | InvalidTransaction::TxGasLimitGreaterThanCap { .. } => { + InvalidTransaction::CallerGasLimitMoreThanBlock | + InvalidTransaction::TxGasLimitGreaterThanCap { .. } => { // tx.gas > block.gas_limit Self::GasTooHigh } @@ -686,13 +686,13 @@ impl From for RpcInvalidTransactionError { InvalidTransaction::AuthorizationListNotSupported => { Self::AuthorizationListNotSupported } - InvalidTransaction::AuthorizationListInvalidFields - | InvalidTransaction::EmptyAuthorizationList => Self::AuthorizationListInvalidFields, - InvalidTransaction::Eip2930NotSupported - | InvalidTransaction::Eip1559NotSupported - | InvalidTransaction::Eip4844NotSupported - | InvalidTransaction::Eip7702NotSupported - | InvalidTransaction::Eip7873NotSupported => Self::TxTypeNotSupported, + InvalidTransaction::AuthorizationListInvalidFields | + InvalidTransaction::EmptyAuthorizationList => Self::AuthorizationListInvalidFields, + InvalidTransaction::Eip2930NotSupported | + InvalidTransaction::Eip1559NotSupported | + InvalidTransaction::Eip4844NotSupported | + InvalidTransaction::Eip7702NotSupported | + InvalidTransaction::Eip7873NotSupported => Self::TxTypeNotSupported, InvalidTransaction::Eip7873MissingTarget => { Self::other(internal_rpc_err(err.to_string())) } @@ -717,11 +717,11 @@ impl From for RpcInvalidTransactionError { Self::OldLegacyChainId } InvalidTransactionError::ChainIdMismatch => Self::InvalidChainId, - InvalidTransactionError::Eip2930Disabled - | InvalidTransactionError::Eip1559Disabled - | InvalidTransactionError::Eip4844Disabled - | InvalidTransactionError::Eip7702Disabled - | InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported, + InvalidTransactionError::Eip2930Disabled | + InvalidTransactionError::Eip1559Disabled | + InvalidTransactionError::Eip4844Disabled | + InvalidTransactionError::Eip7702Disabled | + InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported, InvalidTransactionError::GasUintOverflow => Self::GasUintOverflow, InvalidTransactionError::GasTooLow => Self::GasTooLow, InvalidTransactionError::GasTooHigh => Self::GasTooHigh, @@ -849,19 +849,19 @@ impl From for jsonrpsee_types::error::ErrorObject<'static> { RpcPoolError::TxPoolOverflow => { rpc_error_with_code(EthRpcErrorCode::TransactionRejected.code(), error.to_string()) } - RpcPoolError::AlreadyKnown - | RpcPoolError::InvalidSender - | RpcPoolError::Underpriced - | RpcPoolError::ReplaceUnderpriced - | RpcPoolError::ExceedsGasLimit - | RpcPoolError::ExceedsFeeCap { .. } - | RpcPoolError::NegativeValue - | RpcPoolError::OversizedData - | RpcPoolError::ExceedsMaxInitCodeSize - | RpcPoolError::PoolTransactionError(_) - | RpcPoolError::Eip4844(_) - | RpcPoolError::Eip7702(_) - | RpcPoolError::AddressAlreadyReserved => { + RpcPoolError::AlreadyKnown | + RpcPoolError::InvalidSender | + RpcPoolError::Underpriced | + RpcPoolError::ReplaceUnderpriced | + RpcPoolError::ExceedsGasLimit | + RpcPoolError::ExceedsFeeCap { .. } | + RpcPoolError::NegativeValue | + RpcPoolError::OversizedData | + RpcPoolError::ExceedsMaxInitCodeSize | + RpcPoolError::PoolTransactionError(_) | + RpcPoolError::Eip4844(_) | + RpcPoolError::Eip7702(_) | + RpcPoolError::AddressAlreadyReserved => { rpc_error_with_code(EthRpcErrorCode::InvalidInput.code(), error.to_string()) } RpcPoolError::Other(other) => internal_rpc_err(other.to_string()), diff --git a/crates/rpc/rpc-eth-types/src/fee_history.rs b/crates/rpc/rpc-eth-types/src/fee_history.rs index 3574ac94ab..7262c1c44c 100644 --- a/crates/rpc/rpc-eth-types/src/fee_history.rs +++ b/crates/rpc/rpc-eth-types/src/fee_history.rs @@ -109,7 +109,7 @@ where if entries.is_empty() { 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(); @@ -148,7 +148,7 @@ where ) -> Option>> { if end_block < start_block { // invalid range, return None - return None; + return None } let lower_bound = self.lower_bound(); let upper_bound = self.upper_bound(); @@ -160,7 +160,7 @@ where .collect::>(); if result.is_empty() { - return None; + return None } Some(result) @@ -324,7 +324,7 @@ where // 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; @@ -377,8 +377,8 @@ where base_fee_per_blob_gas: header .excess_blob_gas() .and_then(|excess_blob_gas| Some(blob_params?.calc_blob_fee(excess_blob_gas))), - blob_gas_used_ratio: block.body().blob_gas_used() as f64 - / blob_params + blob_gas_used_ratio: block.body().blob_gas_used() as f64 / + blob_params .as_ref() .map(|params| params.max_blob_gas_per_block()) .unwrap_or(alloy_eips::eip4844::MAX_DATA_GAS_PER_BLOCK_DENCUN) diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 065a2f5c2c..798a146e61 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -128,16 +128,16 @@ where /// Suggests a gas price estimate based on recent blocks, using the configured percentile. pub async fn suggest_tip_cap(&self) -> EthResult { - let header: reth_primitives_traits::SealedHeader<::Header> = - self.provider - .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? - .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; + let header: reth_primitives_traits::SealedHeader<::Header> = self + .provider + .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? + .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; let mut inner = self.inner.lock().await; // 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 @@ -182,7 +182,7 @@ where // break when we have enough populated blocks if populated_blocks >= self.oracle_config.blocks { - break; + break } current_hash = parent_hash; @@ -224,7 +224,7 @@ where ) -> EthResult)>> { // check the cache (this will hit the disk if the block is not cached) let Some(block) = self.cache.get_recovered_block(block_hash).await? else { - return Ok(None); + return Ok(None) }; let base_fee_per_gas = block.base_fee_per_gas(); @@ -251,13 +251,13 @@ where // ignore transactions with a tip under the configured threshold if let Some(ignore_under) = self.ignore_price { if effective_tip < Some(ignore_under) { - continue; + continue } } // check if the sender was the coinbase, if so, ignore if tx.signer() == block.beneficiary() { - continue; + continue } // a `None` effective_gas_tip represents a transaction where the max_fee_per_gas is @@ -266,7 +266,7 @@ where // we have enough entries if prices.len() >= limit { - break; + break } } @@ -352,7 +352,7 @@ where pub async fn get_block_median_tip(&self, block_hash: B256) -> EthResult> { // check the cache (this will hit the disk if the block is not cached) let Some(block) = self.cache.get_recovered_block(block_hash).await? else { - return Ok(None); + return Ok(None) }; let base_fee_per_gas = block.base_fee_per_gas(); diff --git a/crates/rpc/rpc-eth-types/src/id_provider.rs b/crates/rpc/rpc-eth-types/src/id_provider.rs index 1c4efa7707..a2020d0b21 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/utils.rs b/crates/rpc/rpc-eth-types/src/utils.rs index d2d8ac00ce..d3bb655be1 100644 --- a/crates/rpc/rpc-eth-types/src/utils.rs +++ b/crates/rpc/rpc-eth-types/src/utils.rs @@ -12,7 +12,7 @@ use std::future::Future; /// See [`alloy_eips::eip2718::Decodable2718::decode_2718`] pub fn recover_raw_transaction(mut data: &[u8]) -> EthResult> { if data.is_empty() { - return Err(EthApiError::EmptyRawTransactionData); + return Err(EthApiError::EmptyRawTransactionData) } let transaction = diff --git a/crates/rpc/rpc-layer/src/auth_client_layer.rs b/crates/rpc/rpc-layer/src/auth_client_layer.rs index c5899b0696..5eda04aa0f 100644 --- a/crates/rpc/rpc-layer/src/auth_client_layer.rs +++ b/crates/rpc/rpc-layer/src/auth_client_layer.rs @@ -66,8 +66,8 @@ pub fn secret_to_bearer_header(secret: &JwtSecret) -> HeaderValue { "Bearer {}", secret .encode(&Claims { - iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() - + Duration::from_secs(60)) + iat: (SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + + Duration::from_secs(60)) .as_secs(), exp: None, }) diff --git a/crates/rpc/rpc-server-types/src/module.rs b/crates/rpc/rpc-server-types/src/module.rs index 64bad737d6..fdca41cc19 100644 --- a/crates/rpc/rpc-server-types/src/module.rs +++ b/crates/rpc/rpc-server-types/src/module.rs @@ -204,7 +204,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 564a9e123a..301d65a820 100644 --- a/crates/rpc/rpc-testing-util/tests/it/trace.rs +++ b/crates/rpc/rpc-testing-util/tests/it/trace.rs @@ -20,7 +20,7 @@ use std::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(); @@ -107,7 +107,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(); @@ -141,7 +141,7 @@ async fn debug_trace_block_opcodes_entire_chain() { let opcodes7702 = ["EXTCODESIZE", "EXTCODECOPY", "EXTCODEHASH"]; 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/src/debug.rs b/crates/rpc/rpc/src/debug.rs index 2363243096..1e2f107398 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -445,7 +445,7 @@ where Ok(GethTrace::JS(res)) } - }; + } } // default structlog tracer @@ -481,7 +481,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(); @@ -739,7 +739,7 @@ where let mut inspector = FourByteInspector::default(); let (res, _) = self.eth_api().inspect(db, evm_env, tx_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 @@ -762,7 +762,7 @@ where .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 @@ -784,7 +784,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())) @@ -803,7 +803,7 @@ where let frame = inspector .try_into_mux_frame(&res, db, tx_info) .map_err(Eth::Error::from_eth_err)?; - return Ok((frame.into(), res.state)); + return Ok((frame.into(), res.state)) } GethDebugBuiltInTracerType::FlatCallTracer => { let flat_call_config = tracer_config @@ -848,7 +848,7 @@ where .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 4ebfa98681..8a0683b763 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -68,13 +68,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 @@ -113,14 +113,14 @@ where .chain_spec() .blob_params_at_timestamp(evm_env.block_env.timestamp.saturating_to()) .unwrap_or_else(BlobParams::cancun); - if transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::() - > blob_params.max_blob_gas_per_block() + if transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::() > + blob_params.max_blob_gas_per_block() { return Err(EthApiError::InvalidParams( EthBundleError::Eip4844BlobGasExceeded(blob_params.max_blob_gas_per_block()) .to_string(), ) - .into()); + .into()) } } @@ -128,10 +128,9 @@ where evm_env.block_env.gas_limit = self.inner.eth_api.call_gas_limit(); if let Some(gas_limit) = gas_limit { if gas_limit > evm_env.block_env.gas_limit { - return Err(EthApiError::InvalidTransaction( - RpcInvalidTransactionError::GasTooHigh, + return Err( + EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into() ) - .into()); } evm_env.block_env.gas_limit = gas_limit; } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index d9b81bdb59..d672fd10f6 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -199,7 +199,7 @@ where if filter.block > best_number { // no new blocks since the last poll - return Ok(FilterChanges::Empty); + return Ok(FilterChanges::Empty) } // update filter @@ -273,7 +273,7 @@ where *filter.clone() } else { // Not a log filter - return Err(EthFilterError::FilterNotFound(id)); + return Err(EthFilterError::FilterNotFound(id)) } }; @@ -534,13 +534,13 @@ where // perform boundary checks first if to_block < from_block { - return Err(EthFilterError::InvalidBlockRangeParams); + return Err(EthFilterError::InvalidBlockRangeParams) } if let Some(max_blocks_per_filter) = limits.max_blocks_per_filter.filter(|limit| to_block - from_block > *limit) { - return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter)); + return Err(EthFilterError::QueryExceedsMaxBlocks(max_blocks_per_filter)) } let (tx, rx) = oneshot::channel(); @@ -780,7 +780,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)) } @@ -827,9 +827,9 @@ impl From for jsonrpsee::types::error::ErrorObject<'static> { rpc_error_with_code(jsonrpsee::types::error::INTERNAL_ERROR_CODE, err.to_string()) } EthFilterError::EthAPIError(err) => err.into(), - err @ (EthFilterError::InvalidBlockRangeParams - | EthFilterError::QueryExceedsMaxBlocks(_) - | EthFilterError::QueryExceedsMaxResults { .. }) => { + err @ (EthFilterError::InvalidBlockRangeParams | + EthFilterError::QueryExceedsMaxBlocks(_) | + EthFilterError::QueryExceedsMaxResults { .. }) => { rpc_error_with_code(jsonrpsee::types::error::INVALID_PARAMS_CODE, err.to_string()) } } diff --git a/crates/rpc/rpc/src/eth/helpers/block.rs b/crates/rpc/rpc/src/eth/helpers/block.rs index 0b086ae481..724b3a5c96 100644 --- a/crates/rpc/rpc/src/eth/helpers/block.rs +++ b/crates/rpc/rpc/src/eth/helpers/block.rs @@ -65,7 +65,7 @@ where .map(|builder| builder.build()) }) .collect::, Self::Error>>() - .map(Some); + .map(Some) } Ok(None) diff --git a/crates/rpc/rpc/src/eth/pubsub.rs b/crates/rpc/rpc/src/eth/pubsub.rs index e3e9ddfae8..1c7982f80f 100644 --- a/crates/rpc/rpc/src/eth/pubsub.rs +++ b/crates/rpc/rpc/src/eth/pubsub.rs @@ -139,7 +139,7 @@ where }; std::future::ready(tx_value) }); - return pipe_from_stream(accepted_sink, stream).await; + return pipe_from_stream(accepted_sink, stream).await } Params::Bool(false) | Params::None => { // only hashes requested @@ -172,7 +172,7 @@ where .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - return Ok(()); + return Ok(()) } while canon_state.next().await.is_some() { @@ -192,7 +192,7 @@ where .map_err(SubscriptionSerializeError::new)?; if accepted_sink.send(msg).await.is_err() { - break; + break } } } diff --git a/crates/rpc/rpc/src/eth/sim_bundle.rs b/crates/rpc/rpc/src/eth/sim_bundle.rs index 98045d1f77..6221f6821c 100644 --- a/crates/rpc/rpc/src/eth/sim_bundle.rs +++ b/crates/rpc/rpc/src/eth/sim_bundle.rs @@ -270,8 +270,8 @@ where let max_block_number = item.inclusion.max_block_number().unwrap_or(block_number); - if current_block_number < block_number - || current_block_number > max_block_number + if current_block_number < block_number || + current_block_number > max_block_number { return Err(EthApiError::InvalidParams( EthSimBundleError::InvalidInclusion.to_string(), @@ -349,9 +349,9 @@ where }); // Calculate payout transaction fee - let payout_tx_fee = U256::from(basefee) - * U256::from(SBUNDLE_PAYOUT_MAX_COST) - * U256::from(refund_configs.len() as u64); + let payout_tx_fee = U256::from(basefee) * + U256::from(SBUNDLE_PAYOUT_MAX_COST) * + U256::from(refund_configs.len() as u64); // Add gas used for payout transactions total_gas_used += SBUNDLE_PAYOUT_MAX_COST * refund_configs.len() as u64; diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 691251db2e..bafbf0730b 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -227,7 +227,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 6e9669c820..3aaa1ebc5e 100644 --- a/crates/rpc/rpc/src/reth.rs +++ b/crates/rpc/rpc/src/reth.rs @@ -71,7 +71,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::HeaderNotFound(block_id)); + return Err(EthApiError::HeaderNotFound(block_id)) }; 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 94f84160fc..73d461bf22 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -224,7 +224,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 } @@ -298,7 +298,7 @@ where }; if is_paris_activated { - return Ok(None); + return Ok(None) } Ok(Some(base_block_reward_pre_merge(&chain_spec, header.number()))) @@ -373,7 +373,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 @@ -382,7 +382,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 @@ -437,7 +437,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 } } @@ -448,7 +448,7 @@ where if after < all_traces.len() { all_traces.drain(..after); } else { - return Ok(vec![]); + return Ok(vec![]) } } diff --git a/crates/rpc/rpc/src/validation.rs b/crates/rpc/rpc/src/validation.rs index e96410ae09..bd75a8045a 100644 --- a/crates/rpc/rpc/src/validation.rs +++ b/crates/rpc/rpc/src/validation.rs @@ -133,18 +133,18 @@ where if !self.disallow.is_empty() { if self.disallow.contains(&block.beneficiary()) { - return Err(ValidationApiError::Blacklist(block.beneficiary())); + return Err(ValidationApiError::Blacklist(block.beneficiary())) } if self.disallow.contains(&message.proposer_fee_recipient) { - return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient)); + return Err(ValidationApiError::Blacklist(message.proposer_fee_recipient)) } for (sender, tx) in block.senders_iter().zip(block.body().transactions()) { if self.disallow.contains(sender) { - return Err(ValidationApiError::Blacklist(*sender)); + return Err(ValidationApiError::Blacklist(*sender)) } if let Some(to) = tx.to() { if self.disallow.contains(&to) { - return Err(ValidationApiError::Blacklist(to)); + return Err(ValidationApiError::Blacklist(to)) } } } @@ -162,10 +162,10 @@ where .sealed_header_by_hash(block.parent_hash())? .ok_or_else(|| ValidationApiError::MissingParentBlock)?; - if latest_header.number().saturating_sub(parent_header.number()) - > self.validation_window + if latest_header.number().saturating_sub(parent_header.number()) > + self.validation_window { - return Err(ValidationApiError::BlockTooOld); + return Err(ValidationApiError::BlockTooOld) } parent_header }; @@ -194,7 +194,7 @@ where })?; if let Some(account) = accessed_blacklisted { - return Err(ValidationApiError::Blacklist(account)); + return Err(ValidationApiError::Blacklist(account)) } // update the cached reads @@ -211,7 +211,7 @@ where return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: state_root, expected: block.header().state_root() }.into(), ) - .into()); + .into()) } Ok(()) @@ -270,7 +270,7 @@ where return Err(ValidationApiError::GasLimitMismatch(GotExpected { got: header.gas_limit(), expected: best_gas_limit, - })); + })) } Ok(()) @@ -308,7 +308,7 @@ where } if balance_after >= balance_before + message.value { - return Ok(()); + return Ok(()) } let (receipt, tx) = output @@ -318,24 +318,24 @@ where .ok_or(ValidationApiError::ProposerPayment)?; if !receipt.status() { - return Err(ValidationApiError::ProposerPayment); + return Err(ValidationApiError::ProposerPayment) } if tx.to() != Some(message.proposer_fee_recipient) { - return Err(ValidationApiError::ProposerPayment); + return Err(ValidationApiError::ProposerPayment) } if tx.value() != message.value { - return Err(ValidationApiError::ProposerPayment); + return Err(ValidationApiError::ProposerPayment) } if !tx.input().is_empty() { - return Err(ValidationApiError::ProposerPayment); + return Err(ValidationApiError::ProposerPayment) } if let Some(block_base_fee) = block.header().base_fee_per_gas() { if tx.effective_tip_per_gas(block_base_fee).unwrap_or_default() != 0 { - return Err(ValidationApiError::ProposerPayment); + return Err(ValidationApiError::ProposerPayment) } } @@ -347,10 +347,10 @@ where &self, mut blobs_bundle: BlobsBundleV1, ) -> Result, ValidationApiError> { - if blobs_bundle.commitments.len() != blobs_bundle.proofs.len() - || blobs_bundle.commitments.len() != blobs_bundle.blobs.len() + if blobs_bundle.commitments.len() != blobs_bundle.proofs.len() || + blobs_bundle.commitments.len() != blobs_bundle.blobs.len() { - return Err(ValidationApiError::InvalidBlobsBundle); + return Err(ValidationApiError::InvalidBlobsBundle) } let versioned_hashes = blobs_bundle @@ -588,20 +588,20 @@ pub enum ValidationApiError { impl From for ErrorObject<'static> { fn from(error: ValidationApiError) -> Self { match error { - ValidationApiError::GasLimitMismatch(_) - | ValidationApiError::GasUsedMismatch(_) - | ValidationApiError::ParentHashMismatch(_) - | ValidationApiError::BlockHashMismatch(_) - | ValidationApiError::Blacklist(_) - | ValidationApiError::ProposerPayment - | ValidationApiError::InvalidBlobsBundle - | ValidationApiError::Blob(_) => invalid_params_rpc_err(error.to_string()), - - ValidationApiError::MissingLatestBlock - | ValidationApiError::MissingParentBlock - | ValidationApiError::BlockTooOld - | ValidationApiError::Consensus(_) - | ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()), + ValidationApiError::GasLimitMismatch(_) | + ValidationApiError::GasUsedMismatch(_) | + ValidationApiError::ParentHashMismatch(_) | + ValidationApiError::BlockHashMismatch(_) | + ValidationApiError::Blacklist(_) | + ValidationApiError::ProposerPayment | + ValidationApiError::InvalidBlobsBundle | + ValidationApiError::Blob(_) => invalid_params_rpc_err(error.to_string()), + + ValidationApiError::MissingLatestBlock | + ValidationApiError::MissingParentBlock | + ValidationApiError::BlockTooOld | + ValidationApiError::Consensus(_) | + ValidationApiError::Provider(_) => internal_rpc_err(error.to_string()), ValidationApiError::Execution(err) => match err { error @ BlockExecutionError::Validation(_) => { invalid_params_rpc_err(error.to_string()) diff --git a/crates/scroll/alloy/consensus/src/receipt/envelope.rs b/crates/scroll/alloy/consensus/src/receipt/envelope.rs index 0a0bf60abf..2ba0afdd84 100644 --- a/crates/scroll/alloy/consensus/src/receipt/envelope.rs +++ b/crates/scroll/alloy/consensus/src/receipt/envelope.rs @@ -116,11 +116,11 @@ impl ScrollReceiptEnvelope { /// Return the receipt's bloom. pub const fn logs_bloom(&self) -> &Bloom { match self { - Self::Legacy(t) - | Self::Eip2930(t) - | Self::Eip1559(t) - | Self::Eip7702(t) - | Self::L1Message(t) => &t.logs_bloom, + Self::Legacy(t) | + Self::Eip2930(t) | + Self::Eip1559(t) | + Self::Eip7702(t) | + Self::L1Message(t) => &t.logs_bloom, } } @@ -144,11 +144,11 @@ impl ScrollReceiptEnvelope { /// receipt types may be added. pub const fn as_receipt(&self) -> Option<&Receipt> { match self { - Self::Legacy(t) - | Self::Eip2930(t) - | Self::Eip1559(t) - | Self::Eip7702(t) - | Self::L1Message(t) => Some(&t.receipt), + Self::Legacy(t) | + Self::Eip2930(t) | + Self::Eip1559(t) | + Self::Eip7702(t) | + Self::L1Message(t) => Some(&t.receipt), } } } @@ -157,11 +157,11 @@ impl ScrollReceiptEnvelope { /// Get the length of the inner receipt in the 2718 encoding. pub fn inner_length(&self) -> usize { match self { - Self::Legacy(t) - | Self::Eip2930(t) - | Self::Eip1559(t) - | Self::Eip7702(t) - | Self::L1Message(t) => t.length(), + Self::Legacy(t) | + Self::Eip2930(t) | + Self::Eip1559(t) | + Self::Eip7702(t) | + Self::L1Message(t) => t.length(), } } @@ -251,11 +251,11 @@ impl Encodable2718 for ScrollReceiptEnvelope { Some(ty) => out.put_u8(ty), } match self { - Self::Legacy(t) - | Self::Eip2930(t) - | Self::Eip1559(t) - | Self::Eip7702(t) - | Self::L1Message(t) => t.encode(out), + Self::Legacy(t) | + Self::Eip2930(t) | + Self::Eip1559(t) | + Self::Eip7702(t) | + Self::L1Message(t) => t.encode(out), } } } diff --git a/crates/scroll/alloy/consensus/src/transaction/l1_message.rs b/crates/scroll/alloy/consensus/src/transaction/l1_message.rs index 2f18e24bbc..0c200904fb 100644 --- a/crates/scroll/alloy/consensus/src/transaction/l1_message.rs +++ b/crates/scroll/alloy/consensus/src/transaction/l1_message.rs @@ -102,12 +102,12 @@ impl TxL1Message { /// Outputs the length of the transaction's fields, without a RLP header. pub fn rlp_encoded_fields_length(&self) -> usize { - self.queue_index.length() - + self.gas_limit.length() - + self.to.length() - + self.value.length() - + self.input.0.length() - + self.sender.length() + self.queue_index.length() + + self.gas_limit.length() + + self.to.length() + + self.value.length() + + self.input.0.length() + + self.sender.length() } /// Encode the fields of the transaction without a RLP header. diff --git a/crates/scroll/alloy/evm/src/block/feynman.rs b/crates/scroll/alloy/evm/src/block/feynman.rs index 6e443bac87..e815f87cc5 100644 --- a/crates/scroll/alloy/evm/src/block/feynman.rs +++ b/crates/scroll/alloy/evm/src/block/feynman.rs @@ -50,7 +50,7 @@ pub(super) fn apply_feynman_hard_fork( // other reliable way to apply the change only at the transition block, since // `ScrollBlockExecutor` does not have access to the parent timestamp. if matches!(oracle.storage_slot(IS_FEYNMAN_SLOT), Some(val) if val == IS_FEYNMAN) { - return Ok(()); + return Ok(()) } // compute the code hash diff --git a/crates/scroll/alloy/evm/src/block/mod.rs b/crates/scroll/alloy/evm/src/block/mod.rs index ac696cfa5d..054b5a5b96 100644 --- a/crates/scroll/alloy/evm/src/block/mod.rs +++ b/crates/scroll/alloy/evm/src/block/mod.rs @@ -207,7 +207,7 @@ where transaction_gas_limit: tx.tx().gas_limit(), block_available_gas, } - .into()); + .into()) } let hash = tx.tx().trie_hash(); @@ -219,30 +219,30 @@ where hash, error: Box::new(InvalidTransaction::Eip2930NotSupported), } - .into()); + .into()) } if tx.tx().is_eip1559() && !chain_spec.is_curie_active_at_block(block.number.to()) { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip1559NotSupported), } - .into()); + .into()) } if tx.tx().is_eip4844() { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip4844NotSupported), } - .into()); + .into()) } - if tx.tx().is_eip7702() - && !chain_spec.is_euclid_v2_active_at_timestamp(block.timestamp.to()) + if tx.tx().is_eip7702() && + !chain_spec.is_euclid_v2_active_at_timestamp(block.timestamp.to()) { return Err(BlockValidationError::InvalidTx { hash, error: Box::new(InvalidTransaction::Eip7702NotSupported), } - .into()); + .into()) } // disable the base fee and nonce checks for l1 messages. @@ -254,7 +254,7 @@ where self.evm.transact(tx).map_err(move |err| BlockExecutionError::evm(err, hash))?; if !f(&result).should_commit() { - return Ok(None); + return Ok(None) }; let l1_fee = if is_l1_message { diff --git a/crates/scroll/alloy/evm/src/system_caller.rs b/crates/scroll/alloy/evm/src/system_caller.rs index 77e21b1b70..83cd003374 100644 --- a/crates/scroll/alloy/evm/src/system_caller.rs +++ b/crates/scroll/alloy/evm/src/system_caller.rs @@ -79,9 +79,7 @@ fn transact_blockhashes_contract_call( ) { Ok(res) => res, Err(e) => { - return Err( - BlockValidationError::BlockHashContractCall { message: e.to_string() }.into() - ) + return Err(BlockValidationError::BlockHashContractCall { message: e.to_string() }.into()) } }; diff --git a/crates/scroll/alloy/evm/src/tx/compression.rs b/crates/scroll/alloy/evm/src/tx/compression.rs index 4080d523ab..f8f151df77 100644 --- a/crates/scroll/alloy/evm/src/tx/compression.rs +++ b/crates/scroll/alloy/evm/src/tx/compression.rs @@ -49,7 +49,7 @@ mod zstd_compression { pub fn compute_compression_ratio>(bytes: &T) -> U256 { // By definition, the compression ratio of empty data is infinity if bytes.as_ref().is_empty() { - return U256::MAX; + return U256::MAX } // Instantiate the compressor diff --git a/crates/scroll/alloy/rpc-types-engine/src/attributes.rs b/crates/scroll/alloy/rpc-types-engine/src/attributes.rs index 4e2343059f..25b522ac03 100644 --- a/crates/scroll/alloy/rpc-types-engine/src/attributes.rs +++ b/crates/scroll/alloy/rpc-types-engine/src/attributes.rs @@ -47,11 +47,11 @@ impl BlockDataHint { /// Returns `true` if the [`BlockDataHint`] is empty. pub const fn is_empty(&self) -> bool { - self.extra_data.is_none() - && self.state_root.is_none() - && self.coinbase.is_none() - && self.nonce.is_none() - && self.difficulty.is_none() + self.extra_data.is_none() && + self.state_root.is_none() && + self.coinbase.is_none() && + self.nonce.is_none() && + self.difficulty.is_none() } } diff --git a/crates/scroll/chainspec/src/lib.rs b/crates/scroll/chainspec/src/lib.rs index efcd944bba..776b6b6cde 100644 --- a/crates/scroll/chainspec/src/lib.rs +++ b/crates/scroll/chainspec/src/lib.rs @@ -309,8 +309,8 @@ impl Hardforks for ScrollChainSpec { for (_, cond) in self.hardforks.forks_iter() { // handle block based forks and the sepolia merge netsplit block edge case (TTD // ForkCondition with Some(block)) - if let ForkCondition::Block(block) - | ForkCondition::TTD { fork_block: Some(block), .. } = cond + if let ForkCondition::Block(block) | + ForkCondition::TTD { fork_block: Some(block), .. } = cond { if head.number >= block { // skip duplicated hardforks: hardforks enabled at genesis block @@ -321,7 +321,7 @@ impl Hardforks for ScrollChainSpec { } else { // we can return here because this block fork is not active, so we set the // `next` value - return ForkId { hash: forkhash, next: block }; + return ForkId { hash: forkhash, next: block } } } } @@ -337,8 +337,8 @@ impl Hardforks for ScrollChainSpec { // We filter out TTD-based forks w/o a pre-known block since those do not show up in the // fork filter. Some(match condition { - ForkCondition::Block(block) - | ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), + ForkCondition::Block(block) | + ForkCondition::TTD { fork_block: Some(block), .. } => ForkFilterKey::Block(block), _ => return None, }) }); diff --git a/crates/scroll/consensus/src/validation.rs b/crates/scroll/consensus/src/validation.rs index 701bb258a9..adcd2706f8 100644 --- a/crates/scroll/consensus/src/validation.rs +++ b/crates/scroll/consensus/src/validation.rs @@ -98,19 +98,17 @@ impl Consensus expected: block.ommers_hash(), } .into(), - )); + )) } // Check transaction root if let Err(error) = block.ensure_transaction_root_valid() { - return Err(ConsensusError::BodyTransactionRootDiff(error.into())); + return Err(ConsensusError::BodyTransactionRootDiff(error.into())) } // Check withdrawals are empty if block.body().withdrawals().is_some() { - return Err(ConsensusError::Other( - ScrollConsensusError::WithdrawalsNonEmpty.to_string(), - )); + return Err(ConsensusError::Other(ScrollConsensusError::WithdrawalsNonEmpty.to_string())) } Ok(()) @@ -122,7 +120,7 @@ impl HeaderValidator< { fn validate_header(&self, header: &SealedHeader) -> Result<(), ConsensusError> { if header.ommers_hash() != EMPTY_OMMER_ROOT_HASH { - return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty); + return Err(ConsensusError::TheMergeOmmerRootIsNotEmpty) } validate_header_gas(header.header())?; @@ -145,7 +143,7 @@ impl HeaderValidator< if self.chain_spec.blob_params_at_timestamp(header.timestamp()).is_some() { return Err(ConsensusError::Other( ScrollConsensusError::UnexpectedBlobParams.to_string(), - )); + )) } Ok(()) @@ -166,10 +164,10 @@ fn validate_header_base_fee( header: &H, chain_spec: &ChainSpec, ) -> Result<(), ConsensusError> { - if chain_spec.scroll_fork_activation(ScrollHardfork::Curie).active_at_block(header.number()) - && header.base_fee_per_gas().is_none() + if chain_spec.scroll_fork_activation(ScrollHardfork::Curie).active_at_block(header.number()) && + header.base_fee_per_gas().is_none() { - return Err(ConsensusError::BaseFeeMissing); + return Err(ConsensusError::BaseFeeMissing) } Ok(()) } @@ -187,7 +185,7 @@ fn validate_against_parent_timestamp( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp(), timestamp: header.timestamp(), - }); + }) } Ok(()) } diff --git a/crates/scroll/evm/src/lib.rs b/crates/scroll/evm/src/lib.rs index dad40b3e1e..84b1afca19 100644 --- a/crates/scroll/evm/src/lib.rs +++ b/crates/scroll/evm/src/lib.rs @@ -116,11 +116,11 @@ pub fn spec_id_at_timestamp_and_number( ScrollSpecId::EUCLID } else if chain_spec .scroll_fork_activation(ScrollHardfork::Euclid) - .active_at_timestamp_or_number(timestamp, number) - || chain_spec + .active_at_timestamp_or_number(timestamp, number) || + chain_spec .scroll_fork_activation(ScrollHardfork::DarwinV2) - .active_at_timestamp_or_number(timestamp, number) - || chain_spec + .active_at_timestamp_or_number(timestamp, number) || + chain_spec .scroll_fork_activation(ScrollHardfork::Darwin) .active_at_timestamp_or_number(timestamp, number) { diff --git a/crates/scroll/payload/src/builder.rs b/crates/scroll/payload/src/builder.rs index 71fe3810d0..c69d2bd7e1 100644 --- a/crates/scroll/payload/src/builder.rs +++ b/crates/scroll/payload/src/builder.rs @@ -255,7 +255,7 @@ impl ScrollBuilder<'_, Txs> { // check if the new payload is even more valuable if !ctx.is_better_payload(info.total_fees) { // can skip building the block - return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }); + return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }) } } @@ -424,7 +424,7 @@ where if sequencer_tx.value().is_eip4844() { return Err(PayloadBuilderError::other( ScrollPayloadBuilderError::BlobTransactionRejected, - )); + )) } // Convert the transaction to a [RecoveredTx]. This is @@ -442,11 +442,11 @@ where .. })) => { tracing::trace!(target: "payload_builder", %error, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue; + continue } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) } }; @@ -479,18 +479,18 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue; + continue } // A sequencer's block should never contain blob or deposit transactions from the pool. if tx.is_eip4844() || tx.is_l1_message() { best_txs.mark_invalid(tx.signer(), tx.nonce()); - continue; + continue } // check if the job was cancelled, if so we can exit early if self.cancel.is_cancelled() { - return Ok(Some(())); + return Ok(Some(())) } // check if the execution needs to be halted. @@ -514,11 +514,11 @@ where tracing::trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid(tx.signer(), tx.nonce()); } - continue; + continue } Err(err) => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); + return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))) } }; diff --git a/crates/scroll/payload/src/config.rs b/crates/scroll/payload/src/config.rs index fc81719790..d51c59bf1d 100644 --- a/crates/scroll/payload/src/config.rs +++ b/crates/scroll/payload/src/config.rs @@ -41,8 +41,8 @@ impl PayloadBuildingBreaker { /// Returns whether the payload building should stop. pub(super) fn should_break(&self, cumulative_gas_used: u64) -> bool { - self.start.elapsed() >= self.time_limit - || cumulative_gas_used > self.gas_limit.saturating_sub(MIN_TRANSACTION_GAS) + self.start.elapsed() >= self.time_limit || + cumulative_gas_used > self.gas_limit.saturating_sub(MIN_TRANSACTION_GAS) } } diff --git a/crates/scroll/primitives/src/receipt.rs b/crates/scroll/primitives/src/receipt.rs index d57b6248af..6e214b3108 100644 --- a/crates/scroll/primitives/src/receipt.rs +++ b/crates/scroll/primitives/src/receipt.rs @@ -44,10 +44,10 @@ impl ScrollReceipt { /// Returns inner [`Receipt`], pub const fn as_receipt(&self) -> &Receipt { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => &receipt.inner, + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => &receipt.inner, Self::L1Message(receipt) => receipt, } } @@ -55,10 +55,10 @@ impl ScrollReceipt { /// Returns length of RLP-encoded receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encoded_fields_length(&self, bloom: &Bloom) -> usize { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), Self::L1Message(receipt) => receipt.rlp_encoded_fields_length_with_bloom(bloom), } } @@ -66,10 +66,10 @@ impl ScrollReceipt { /// RLP-encodes receipt fields with the given [`Bloom`] without an RLP header. pub fn rlp_encode_fields(&self, bloom: &Bloom, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), Self::L1Message(receipt) => receipt.rlp_encode_fields_with_bloom(bloom, out), } } @@ -122,10 +122,10 @@ impl ScrollReceipt { /// RLP-encodes receipt fields without an RLP header. pub fn rlp_encode_fields_without_bloom(&self, out: &mut dyn BufMut) { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => { + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => { receipt.inner.status.encode(out); receipt.inner.cumulative_gas_used.encode(out); receipt.inner.logs.encode(out); @@ -141,18 +141,18 @@ impl ScrollReceipt { /// Returns length of RLP-encoded receipt fields without an RLP header. pub fn rlp_encoded_fields_length_without_bloom(&self) -> usize { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => { - receipt.inner.status.length() - + receipt.inner.cumulative_gas_used.length() - + receipt.inner.logs.length() + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => { + receipt.inner.status.length() + + receipt.inner.cumulative_gas_used.length() + + receipt.inner.logs.length() } Self::L1Message(receipt) => { - receipt.status.length() - + receipt.cumulative_gas_used.length() - + receipt.logs.length() + receipt.status.length() + + receipt.cumulative_gas_used.length() + + receipt.logs.length() } } } @@ -198,10 +198,10 @@ impl ScrollReceipt { /// Returns the l1 fee for the transaction receipt. pub const fn l1_fee(&self) -> U256 { match self { - Self::Legacy(receipt) - | Self::Eip2930(receipt) - | Self::Eip1559(receipt) - | Self::Eip7702(receipt) => receipt.l1_fee, + Self::Legacy(receipt) | + Self::Eip2930(receipt) | + Self::Eip1559(receipt) | + Self::Eip7702(receipt) => receipt.l1_fee, Self::L1Message(_) => U256::ZERO, } } @@ -258,7 +258,7 @@ impl RlpDecodableReceipt for ScrollReceipt { // Legacy receipt, reuse initial buffer without advancing if header.list { - return Self::rlp_decode_inner(buf, ScrollTxType::Legacy); + return Self::rlp_decode_inner(buf, ScrollTxType::Legacy) } // Otherwise, advance the buffer and try decoding type flag followed by receipt @@ -278,8 +278,8 @@ impl RlpDecodableReceipt for ScrollReceipt { impl Encodable2718 for ScrollReceipt { fn encode_2718_len(&self) -> usize { - !self.tx_type().is_legacy() as usize - + self.rlp_header_inner_without_bloom().length_with_payload() + !self.tx_type().is_legacy() as usize + + self.rlp_header_inner_without_bloom().length_with_payload() } fn encode_2718(&self, out: &mut dyn BufMut) { diff --git a/crates/scroll/rpc/src/error.rs b/crates/scroll/rpc/src/error.rs index 5471ccf1c8..23ad2a9466 100644 --- a/crates/scroll/rpc/src/error.rs +++ b/crates/scroll/rpc/src/error.rs @@ -3,7 +3,7 @@ use alloy_json_rpc::ErrorPayload; use alloy_rpc_types_eth::BlockError; use alloy_transport::{RpcError, TransportErrorKind}; -use jsonrpsee_types::error::INTERNAL_ERROR_CODE; +use jsonrpsee_types::error::{INTERNAL_ERROR_CODE}; use reth_evm::execute::ProviderError; use reth_rpc_convert::transaction::EthTxEnvError; use reth_rpc_eth_api::{AsEthApiError, TransactionConversionError}; diff --git a/crates/scroll/rpc/src/eth/block.rs b/crates/scroll/rpc/src/eth/block.rs index f3205cafe3..49bcd5b29e 100644 --- a/crates/scroll/rpc/src/eth/block.rs +++ b/crates/scroll/rpc/src/eth/block.rs @@ -62,7 +62,7 @@ where .map(|builder| builder.build()) }) .collect::, Self::Error>>() - .map(Some); + .map(Some) } Ok(None) diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 11888567f0..07a7fbb569 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -13,7 +13,8 @@ use reth_provider::{ }; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, TxInfoMapper, + EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, + TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; use reth_scroll_primitives::ScrollReceipt; @@ -44,16 +45,16 @@ where // blocks that it builds. if let Some(client) = self.raw_tx_forwarder().as_ref() { tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); - + // Retain tx in local tx pool before forwarding to sequencer rpc, for local RPC usage. let hash = self .pool() .add_transaction(TransactionOrigin::Local, pool_transaction.clone()) .await .map_err(Self::Error::from_eth_err)?; - + tracing::debug!(target: "rpc::eth", %hash, "successfully added transaction to local tx pool"); - + // Forward to remote sequencer RPC. match client.forward_raw_transaction(&tx).await { Ok(sequencer_hash) => { @@ -63,7 +64,7 @@ where tracing::warn!(target: "rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); } } - + return Ok(hash); } diff --git a/crates/scroll/rpc/src/lib.rs b/crates/scroll/rpc/src/lib.rs index 76ecfbec7b..116bc181c8 100644 --- a/crates/scroll/rpc/src/lib.rs +++ b/crates/scroll/rpc/src/lib.rs @@ -14,4 +14,4 @@ pub mod sequencer; pub use error::{ScrollEthApiError, SequencerClientError}; pub use eth::{ScrollEthApi, ScrollReceiptBuilder}; -pub use sequencer::SequencerClient; +pub use sequencer::SequencerClient; \ No newline at end of file diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs index 094840f99e..5c7c5e610c 100644 --- a/crates/scroll/rpc/src/sequencer.rs +++ b/crates/scroll/rpc/src/sequencer.rs @@ -155,7 +155,10 @@ mod tests { let request = client .client() - .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) + .make_request( + "eth_sendRawTransaction", + format!("0x{}", hex::encode("abcd")), + ) .serialize() .unwrap() .take_request(); @@ -187,7 +190,10 @@ mod tests { let request = client .client() - .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) + .make_request( + "eth_sendRawTransaction", + format!("0x{}", hex::encode("abcd")), + ) .serialize() .unwrap() .take_request(); diff --git a/crates/scroll/txpool/src/validator.rs b/crates/scroll/txpool/src/validator.rs index 450d0db323..3b6ae3aac4 100644 --- a/crates/scroll/txpool/src/validator.rs +++ b/crates/scroll/txpool/src/validator.rs @@ -141,14 +141,14 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ); + ) } let outcome = self.inner.validate_one(origin, transaction); if !self.requires_l1_data_gas_fee() { // no need to check L1 gas fee - return outcome; + return outcome } // ensure that the account has enough balance to cover the L1 gas cost @@ -191,7 +191,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ); + ) } return TransactionValidationOutcome::Valid { @@ -201,7 +201,7 @@ where transaction: valid_tx, propagate, authorities, - }; + } } outcome diff --git a/crates/stages/api/src/error.rs b/crates/stages/api/src/error.rs index c11ff05c61..b4bbf390e2 100644 --- a/crates/stages/api/src/error.rs +++ b/crates/stages/api/src/error.rs @@ -123,15 +123,15 @@ impl StageError { pub const fn is_fatal(&self) -> bool { matches!( self, - Self::Database(_) - | Self::Download(_) - | Self::DatabaseIntegrity(_) - | Self::StageCheckpoint(_) - | Self::MissingDownloadBuffer - | Self::MissingSyncGap - | Self::ChannelClosed - | Self::Internal(_) - | Self::Fatal(_) + Self::Database(_) | + Self::Download(_) | + Self::DatabaseIntegrity(_) | + Self::StageCheckpoint(_) | + Self::MissingDownloadBuffer | + Self::MissingSyncGap | + Self::ChannelClosed | + Self::Internal(_) | + Self::Fatal(_) ) } } diff --git a/crates/stages/api/src/metrics/listener.rs b/crates/stages/api/src/metrics/listener.rs index b8df526c0f..aba001a92f 100644 --- a/crates/stages/api/src/metrics/listener.rs +++ b/crates/stages/api/src/metrics/listener.rs @@ -90,7 +90,7 @@ impl Future for MetricsListener { loop { let Some(event) = ready!(this.events_rx.poll_recv(cx)) else { // Channel has closed - return Poll::Ready(()); + return Poll::Ready(()) }; this.handle_event(event); diff --git a/crates/stages/api/src/pipeline/mod.rs b/crates/stages/api/src/pipeline/mod.rs index 214fc61ba3..b8d41e9e55 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -155,14 +155,14 @@ impl Pipeline { PipelineTarget::Sync(tip) => self.set_tip(tip), PipelineTarget::Unwind(target) => { if let Err(err) = self.move_to_static_files() { - return (self, Err(err.into())); + return (self, Err(err.into())) } if let Err(err) = self.unwind(target, None) { - return (self, Err(err)); + return (self, Err(err)) } self.progress.update(target); - return (self, Ok(ControlFlow::Continue { block_number: target })); + return (self, Ok(ControlFlow::Continue { block_number: target })) } } } @@ -182,14 +182,13 @@ impl Pipeline { let next_action = self.run_loop().await?; if next_action.is_unwind() && self.fail_on_unwind { - return Err(PipelineError::UnexpectedUnwind); + return Err(PipelineError::UnexpectedUnwind) } // Terminate the loop early if it's reached the maximum user // configured block. - if next_action.should_continue() - && self - .progress + if next_action.should_continue() && + self.progress .minimum_block_number .zip(self.max_block) .is_some_and(|(progress, target)| progress >= target) @@ -201,7 +200,7 @@ impl Pipeline { max_block = ?self.max_block, "Terminating pipeline." ); - return Ok(()); + return Ok(()) } } } @@ -239,7 +238,7 @@ impl Pipeline { ControlFlow::Continue { block_number } => self.progress.update(block_number), ControlFlow::Unwind { target, bad_block } => { self.unwind(target, Some(bad_block.block.number))?; - return Ok(ControlFlow::Unwind { target, bad_block }); + return Ok(ControlFlow::Unwind { target, bad_block }) } } @@ -328,7 +327,7 @@ impl Pipeline { ); self.event_sender.notify(PipelineEvent::Skipped { stage_id }); - continue; + continue } info!( @@ -374,8 +373,8 @@ impl Pipeline { // If None, that means the finalized block is not written so we should // always save in that case - if last_saved_finalized_block_number.is_none() - || Some(checkpoint.block_number) < last_saved_finalized_block_number + if last_saved_finalized_block_number.is_none() || + Some(checkpoint.block_number) < last_saved_finalized_block_number { provider_rw.save_finalized_block_number(BlockNumber::from( checkpoint.block_number, @@ -391,7 +390,7 @@ impl Pipeline { Err(err) => { self.event_sender.notify(PipelineEvent::Error { stage_id }); - return Err(PipelineError::Stage(StageError::Fatal(Box::new(err)))); + return Err(PipelineError::Stage(StageError::Fatal(Box::new(err)))) } } } @@ -430,7 +429,7 @@ impl Pipeline { // We reached the maximum block, so we skip the stage return Ok(ControlFlow::NoProgress { block_number: prev_checkpoint.map(|progress| progress.block_number), - }); + }) } let exec_input = ExecInput { target, checkpoint: prev_checkpoint }; @@ -498,7 +497,7 @@ impl Pipeline { ControlFlow::Continue { block_number } } else { ControlFlow::NoProgress { block_number: Some(block_number) } - }); + }) } } Err(err) => { @@ -506,7 +505,7 @@ impl Pipeline { self.event_sender.notify(PipelineEvent::Error { stage_id }); if let Some(ctrl) = self.on_stage_error(stage_id, prev_checkpoint, err)? { - return Ok(ctrl); + return Ok(ctrl) } } } @@ -523,8 +522,8 @@ impl Pipeline { warn!(target: "sync::pipeline", stage = %stage_id, ?local_head, ?header, %error, "Stage encountered detached head"); if let Some(last_detached_head_unwind_target) = self.last_detached_head_unwind_target { - if local_head.block.hash == last_detached_head_unwind_target - && header.block.number == local_head.block.number + 1 + if local_head.block.hash == last_detached_head_unwind_target && + header.block.number == local_head.block.number + 1 { self.detached_head_attempts += 1; } else { diff --git a/crates/stages/api/src/pipeline/set.rs b/crates/stages/api/src/pipeline/set.rs index 5ab4e390f5..8aea87ba03 100644 --- a/crates/stages/api/src/pipeline/set.rs +++ b/crates/stages/api/src/pipeline/set.rs @@ -241,7 +241,7 @@ impl StageSetBuilder { F: FnOnce() -> bool, { if f() { - return self.disable(stage_id); + return self.disable(stage_id) } self } @@ -255,7 +255,7 @@ impl StageSetBuilder { F: FnOnce() -> bool, { if f() { - return self.disable_all(stages); + return self.disable_all(stages) } self } diff --git a/crates/stages/api/src/stage.rs b/crates/stages/api/src/stage.rs index f251c3e40e..e390f02e15 100644 --- a/crates/stages/api/src/stage.rs +++ b/crates/stages/api/src/stage.rs @@ -95,7 +95,7 @@ impl ExecInput { if all_tx_cnt == 0 { // if there is no more transaction return back. - return Ok((first_tx_num..first_tx_num, start_block..=target_block, true)); + return Ok((first_tx_num..first_tx_num, start_block..=target_block, true)) } // get block of this tx diff --git a/crates/stages/stages/src/stages/bodies.rs b/crates/stages/stages/src/stages/bodies.rs index 321085d2e7..e503d8b5d5 100644 --- a/crates/stages/stages/src/stages/bodies.rs +++ b/crates/stages/stages/src/stages/bodies.rs @@ -125,7 +125,7 @@ where &static_file_provider, provider, StaticFileSegment::Transactions, - )?); + )?) } } else { return Err(missing_static_data_error( @@ -133,7 +133,7 @@ where &static_file_provider, provider, StaticFileSegment::Transactions, - )?); + )?) } } Ordering::Equal => {} @@ -162,7 +162,7 @@ where input: ExecInput, ) -> Poll> { if input.target_reached() || self.buffer.is_some() { - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } // Update the header range on the downloader @@ -188,7 +188,7 @@ where /// header, limited by the stage's batch size. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -789,7 +789,7 @@ mod tests { let this = self.get_mut(); if this.headers.is_empty() { - return Poll::Ready(None); + return Poll::Ready(None) } let mut response = @@ -806,12 +806,12 @@ mod tests { } if response.len() as u64 >= this.batch_size { - break; + break } } if !response.is_empty() { - return Poll::Ready(Some(Ok(response))); + return Poll::Ready(Some(Ok(response))) } panic!("requested bodies without setting headers") diff --git a/crates/stages/stages/src/stages/era.rs b/crates/stages/stages/src/stages/era.rs index b67cc96c5d..38b7f0c0db 100644 --- a/crates/stages/stages/src/stages/era.rs +++ b/crates/stages/stages/src/stages/era.rs @@ -446,8 +446,8 @@ mod tests { .header_td_by_number(initial_checkpoint.saturating_sub(1))? .unwrap_or_default(); - for block_num in initial_checkpoint - ..output + for block_num in initial_checkpoint.. + output .checkpoint .block_number .min(self.responses.as_ref().map(|v| v.len()).unwrap_or_default() diff --git a/crates/stages/stages/src/stages/execution.rs b/crates/stages/stages/src/stages/execution.rs index adf0f0a88d..e5592cd8de 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -167,8 +167,8 @@ where ) -> Result { // We can only prune changesets if we're not executing MerkleStage from scratch (by // threshold or first-sync) - Ok(max_block - start_block > self.external_clean_threshold - || provider.count_entries::()?.is_zero()) + Ok(max_block - start_block > self.external_clean_threshold || + provider.count_entries::()?.is_zero()) } /// Performs consistency check on static files. @@ -191,7 +191,7 @@ where // If there's any receipts pruning configured, receipts are written directly to database and // inconsistencies are expected. if provider.prune_modes_ref().has_receipts_pruning() { - return Ok(()); + return Ok(()) } // Get next expected receipt number @@ -232,7 +232,7 @@ where if next_receipt_num_after_unwind > next_static_file_receipt_num { // This means we need a deeper unwind. } else { - return Ok(()); + return Ok(()) } } @@ -241,7 +241,7 @@ where &static_file_provider, provider, StaticFileSegment::Receipts, - )?); + )?) } } @@ -280,7 +280,7 @@ where /// Execute the stage fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let start_block = input.next_block(); @@ -348,7 +348,7 @@ where return Err(StageError::Block { block: Box::new(block.block_with_parent()), error: BlockErrorKind::Validation(err), - }); + }) } results.push(result); @@ -385,7 +385,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break; + break } } @@ -420,7 +420,7 @@ where // means that we didn't send the notification to ExExes return Err(StageError::PostExecuteCommit( "Previous post execute commit input wasn't processed", - )); + )) } } @@ -434,15 +434,15 @@ where let Some(reverts) = state.bundle.reverts.get_mut((block_number - start_block) as usize) else { - break; + break }; // If both account history and storage history pruning is configured, clear reverts // for this block. if prune_modes .account_history - .is_some_and(|m| m.should_prune(block_number, max_block)) - && prune_modes + .is_some_and(|m| m.should_prune(block_number, max_block)) && + prune_modes .storage_history .is_some_and(|m| m.should_prune(block_number, max_block)) { @@ -496,7 +496,7 @@ where if range.is_empty() { return Ok(UnwindOutput { checkpoint: input.checkpoint.with_block_number(input.unwind_to), - }); + }) } self.ensure_consistency(provider, input.checkpoint.block_number, Some(unwind_to))?; @@ -619,8 +619,8 @@ fn execution_checkpoint( block_range: CheckpointBlockRange { from: start_block, to: max_block }, progress: EntitiesCheckpoint { processed, - total: processed - + calculate_gas_used_from_headers(provider, start_block..=max_block)?, + total: processed + + calculate_gas_used_from_headers(provider, start_block..=max_block)?, }, } } diff --git a/crates/stages/stages/src/stages/finish.rs b/crates/stages/stages/src/stages/finish.rs index a0498b994e..1b9e624b41 100644 --- a/crates/stages/stages/src/stages/finish.rs +++ b/crates/stages/stages/src/stages/finish.rs @@ -78,7 +78,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()); + return Ok(Vec::default()) } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/hashing_account.rs b/crates/stages/stages/src/stages/hashing_account.rs index 227a3eada1..726f9e8218 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -144,7 +144,7 @@ where /// Execute the stage. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -469,7 +469,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } } self.check_hashed_accounts() diff --git a/crates/stages/stages/src/stages/hashing_storage.rs b/crates/stages/stages/src/stages/hashing_storage.rs index a64d4e7fea..af811828fb 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -75,7 +75,7 @@ where fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { let tx = provider.tx_ref(); if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let (from_block, to_block) = input.next_block_range().into_inner(); @@ -270,7 +270,7 @@ mod tests { // Continue from checkpoint input.checkpoint = Some(checkpoint); - continue; + continue } assert_eq!(checkpoint.block_number, previous_stage); assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint { @@ -288,7 +288,7 @@ mod tests { "execution validation" ); - break; + break } panic!("Failed execution"); } @@ -422,7 +422,7 @@ mod tests { let start_block = input.checkpoint().block_number + 1; let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } } self.check_hashed_storage() @@ -523,7 +523,7 @@ mod tests { while let Some((bn_address, entry)) = rev_changeset_walker.next().transpose()? { if bn_address.block_number() < target_block { - break; + break } if storage_cursor diff --git a/crates/stages/stages/src/stages/headers.rs b/crates/stages/stages/src/stages/headers.rs index 47c6956a16..c622e743c1 100644 --- a/crates/stages/stages/src/stages/headers.rs +++ b/crates/stages/stages/src/stages/headers.rs @@ -130,7 +130,7 @@ where let (header, header_hash) = sealed_header.split_ref(); if header.number() == 0 { - continue; + continue } last_header_number = header.number(); @@ -206,7 +206,7 @@ where // Return if stage has already completed the gap on the ETL files if self.is_etl_ready { - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } // Lookup the head and tip of the sync range @@ -225,7 +225,7 @@ where ); self.is_etl_ready = true; self.sync_gap = Some(gap); - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } debug!(target: "sync::stages::headers", ?tip, head = ?gap.local_head.hash(), "Commencing sync"); @@ -260,7 +260,7 @@ where // filled the gap. if header_number == local_head_number + 1 { self.is_etl_ready = true; - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } } @@ -271,11 +271,11 @@ where local_head: Box::new(local_head.block_with_parent()), header: Box::new(header.block_with_parent()), error, - })); + })) } None => { self.sync_gap = None; - return Poll::Ready(Err(StageError::ChannelClosed)); + return Poll::Ready(Err(StageError::ChannelClosed)) } } } @@ -288,12 +288,12 @@ where if self.sync_gap.take().ok_or(StageError::MissingSyncGap)?.is_closed() { self.is_etl_ready = false; - return Ok(ExecOutput::done(current_checkpoint)); + return Ok(ExecOutput::done(current_checkpoint)) } // We should be here only after we have downloaded all headers into the disk buffer (ETL). if !self.is_etl_ready { - return Err(StageError::MissingDownloadBuffer); + return Err(StageError::MissingDownloadBuffer) } // Reset flag @@ -480,7 +480,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()); + return Ok(Vec::default()) } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/index_account_history.rs b/crates/stages/stages/src/stages/index_account_history.rs index 2d705d4db9..37db4f5f9f 100644 --- a/crates/stages/stages/src/stages/index_account_history.rs +++ b/crates/stages/stages/src/stages/index_account_history.rs @@ -88,7 +88,7 @@ where } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let mut range = input.next_block_range(); @@ -568,7 +568,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } assert_eq!( diff --git a/crates/stages/stages/src/stages/index_storage_history.rs b/crates/stages/stages/src/stages/index_storage_history.rs index 2711b0701e..09c9030cb3 100644 --- a/crates/stages/stages/src/stages/index_storage_history.rs +++ b/crates/stages/stages/src/stages/index_storage_history.rs @@ -91,7 +91,7 @@ where } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let mut range = input.next_block_range(); @@ -591,7 +591,7 @@ mod tests { let start_block = input.next_block(); let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } assert_eq!( diff --git a/crates/stages/stages/src/stages/merkle.rs b/crates/stages/stages/src/stages/merkle.rs index f5defa5df8..7d5dd69d2b 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -158,7 +158,7 @@ where provider.get_stage_checkpoint_progress(StageId::MerkleExecute)?.unwrap_or_default(); if buf.is_empty() { - return Ok(None); + return Ok(None) } let (checkpoint, _) = MerkleCheckpoint::from_compact(&buf, buf.len()); @@ -264,8 +264,8 @@ where } .unwrap_or(EntitiesCheckpoint { processed: 0, - total: (provider.count_entries::()? - + provider.count_entries::()?) + total: (provider.count_entries::()? + + provider.count_entries::()?) as u64, }); @@ -296,7 +296,7 @@ where .checkpoint() .with_entities_stage_checkpoint(entities_checkpoint), done: false, - }); + }) } StateRootProgress::Complete(root, hashed_entries_walked, updates) => { provider.write_trie_updates(&updates)?; @@ -335,8 +335,8 @@ where "Incremental merkle hashing did not produce a final root".into(), ))?; - let total_hashed_entries = (provider.count_entries::()? - + provider.count_entries::()?) + let total_hashed_entries = (provider.count_entries::()? + + provider.count_entries::()?) as u64; let entities_checkpoint = EntitiesCheckpoint { @@ -378,14 +378,14 @@ where let range = input.unwind_block_range(); if matches!(self, Self::Execution { .. }) { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); - return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) }); + return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) }) } let mut entities_checkpoint = input.checkpoint.entities_stage_checkpoint().unwrap_or(EntitiesCheckpoint { processed: 0, - total: (tx.entries::()? - + tx.entries::()?) as u64, + total: (tx.entries::()? + + tx.entries::()?) as u64, }); if input.unwind_to == 0 { @@ -397,7 +397,7 @@ where return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) .with_entities_stage_checkpoint(entities_checkpoint), - }); + }) } // Unwind trie only if there are transitions @@ -789,7 +789,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if bn_address.block_number() < target_block { - break; + break } tree.entry(keccak256(bn_address.address())) @@ -820,7 +820,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if block_number < target_block { - break; + break } if let Some(acc) = account_before_tx.info { diff --git a/crates/stages/stages/src/stages/prune.rs b/crates/stages/stages/src/stages/prune.rs index 4fa4313f49..6671c4a413 100644 --- a/crates/stages/stages/src/stages/prune.rs +++ b/crates/stages/stages/src/stages/prune.rs @@ -233,7 +233,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } let provider = self.db.factory.provider()?; diff --git a/crates/stages/stages/src/stages/s3/downloader/fetch.rs b/crates/stages/stages/src/stages/s3/downloader/fetch.rs index efac05c255..7f82552bda 100644 --- a/crates/stages/stages/src/stages/s3/downloader/fetch.rs +++ b/crates/stages/stages/src/stages/s3/downloader/fetch.rs @@ -47,7 +47,7 @@ pub async fn fetch( let data_file = download_dir.join(filename); let mut metadata = metadata(&data_file, url).await?; if metadata.is_done() { - return Ok(()); + return Ok(()) } // Ensure the file is preallocated so we can download it concurrently @@ -95,7 +95,7 @@ pub async fn fetch( } WorkerResponse::Err { worker_id, error } => { error!(target: "sync::stages::s3::downloader", ?worker_id, "Worker found an error: {:?}", error); - return Err(error); + return Err(error) } }; @@ -133,7 +133,7 @@ pub async fn fetch( async fn metadata(data_file: &Path, url: &str) -> Result { if Metadata::file_path(data_file).exists() { debug!(target: "sync::stages::s3::downloader", ?data_file, "Loading metadata "); - return Metadata::load(data_file); + return Metadata::load(data_file) } let client = Client::new(); @@ -158,7 +158,7 @@ fn check_file_hash(path: &Path, expected: &B256) -> Result<(), DownloaderError> let file_hash = hasher.finalize(); if file_hash.as_bytes() != expected { - return Err(DownloaderError::InvalidFileHash(file_hash.as_bytes().into(), *expected)); + return Err(DownloaderError::InvalidFileHash(file_hash.as_bytes().into(), *expected)) } Ok(()) diff --git a/crates/stages/stages/src/stages/s3/downloader/meta.rs b/crates/stages/stages/src/stages/s3/downloader/meta.rs index d44b06ad12..7ff4213fff 100644 --- a/crates/stages/stages/src/stages/s3/downloader/meta.rs +++ b/crates/stages/stages/src/stages/s3/downloader/meta.rs @@ -62,7 +62,7 @@ impl Metadata { let num_chunks = self.chunks.len(); if index >= self.chunks.len() { - return Err(DownloaderError::InvalidChunk(index, num_chunks)); + return Err(DownloaderError::InvalidChunk(index, num_chunks)) } // Update chunk with downloaded range diff --git a/crates/stages/stages/src/stages/s3/mod.rs b/crates/stages/stages/src/stages/s3/mod.rs index 486453df09..b5904f1c2c 100644 --- a/crates/stages/stages/src/stages/s3/mod.rs +++ b/crates/stages/stages/src/stages/s3/mod.rs @@ -71,7 +71,7 @@ where self.fetch_rx = None; } - return Poll::Ready(response); + return Poll::Ready(response) } // Spawns the downloader task if there are any missing files @@ -79,11 +79,11 @@ where self.fetch_rx = Some(fetch_rx); // Polls fetch_rx & registers waker - continue; + continue } // No files to be downloaded - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } @@ -147,7 +147,7 @@ impl S3Stage { StaticFileSegment::parse_filename(block_range_files[0].0).expect("qed"); if block_range.end() <= checkpoint.block_number { - continue; + continue } let mut block_range_requests = vec![]; @@ -156,7 +156,7 @@ impl S3Stage { // run. if self.static_file_directory.join(filename).exists() { // TODO: check hash if the file already exists - continue; + continue } block_range_requests.push((filename, file_hash)); @@ -167,7 +167,7 @@ impl S3Stage { // Return None, if we have downloaded all the files that are required. if requests.is_empty() { - return None; + return None } let static_file_directory = self.static_file_directory.clone(); @@ -190,7 +190,7 @@ impl S3Stage { .await { let _ = fetch_tx.send(Err(err)); - return; + return } } @@ -254,7 +254,7 @@ mod tests { let end = input.target.unwrap_or_default() + 1; if start + 1 >= end { - return Ok(Vec::default()); + return Ok(Vec::default()) } let mut headers = random_header_range(&mut rng, start + 1..end, head.hash()); diff --git a/crates/stages/stages/src/stages/sender_recovery.rs b/crates/stages/stages/src/stages/sender_recovery.rs index 771893239a..e6bdb92cf2 100644 --- a/crates/stages/stages/src/stages/sender_recovery.rs +++ b/crates/stages/stages/src/stages/sender_recovery.rs @@ -77,7 +77,7 @@ where /// entries in the [`TransactionSenders`][reth_db_api::tables::TransactionSenders] table. fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result { if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let (tx_range, block_range, is_final_range) = @@ -91,7 +91,7 @@ where checkpoint: StageCheckpoint::new(end_block) .with_entities_stage_checkpoint(stage_checkpoint(provider)?), done: is_final_range, - }); + }) } // Acquire the cursor for inserting elements @@ -206,7 +206,7 @@ where .into(), )) } - }; + } } }; senders_cursor.append(tx_id, &sender)?; @@ -271,7 +271,7 @@ where // We exit early since we could not process this chunk. let _ = recovered_senders_tx .send(Err(Box::new(SenderRecoveryStageError::StageError(err.into())))); - break; + break } }; @@ -294,7 +294,7 @@ where // Finish early if is_err { - break; + break } } }); @@ -663,7 +663,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } let mut body_cursor = diff --git a/crates/stages/stages/src/stages/tx_lookup.rs b/crates/stages/stages/src/stages/tx_lookup.rs index 688aa05af1..2010e5e355 100644 --- a/crates/stages/stages/src/stages/tx_lookup.rs +++ b/crates/stages/stages/src/stages/tx_lookup.rs @@ -242,8 +242,8 @@ where // If `TransactionHashNumbers` table was pruned, we will have a number of entries in it not // matching the actual number of processed transactions. To fix that, we add the // number of pruned `TransactionHashNumbers` entries. - processed: provider.count_entries::()? as u64 - + pruned_entries, + processed: provider.count_entries::()? as u64 + + pruned_entries, // Count only static files entries. If we count the database entries too, we may have // duplicates. We're sure that the static files have all entries that database has, // because we run the `StaticFileProducer` before starting the pipeline. @@ -548,7 +548,7 @@ mod tests { let end_block = output.checkpoint.block_number; if start_block > end_block { - return Ok(()); + return Ok(()) } let mut body_cursor = diff --git a/crates/stages/stages/src/stages/utils.rs b/crates/stages/stages/src/stages/utils.rs index 9659174806..2198b2db60 100644 --- a/crates/stages/stages/src/stages/utils.rs +++ b/crates/stages/stages/src/stages/utils.rs @@ -267,11 +267,11 @@ where loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= last_tx_num { - break; + break } } if last_block == 0 { - break; + break } last_block -= 1; } diff --git a/crates/stages/stages/src/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index 559f9b3f37..f3e29c1fa6 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -277,8 +277,8 @@ impl TestStageDB { // Backfill: some tests start at a forward block number, but static files // require no gaps. let segment_header = txs_writer.user_header(); - if segment_header.block_end().is_none() - && segment_header.expected_block_start() == 0 + if segment_header.block_end().is_none() && + segment_header.expected_block_start() == 0 { for block in 0..block.number { txs_writer.increment_block(block)?; diff --git a/crates/stages/types/src/checkpoints.rs b/crates/stages/types/src/checkpoints.rs index 48f1a86cf6..587d0508a2 100644 --- a/crates/stages/types/src/checkpoints.rs +++ b/crates/stages/types/src/checkpoints.rs @@ -163,7 +163,7 @@ impl EntitiesCheckpoint { /// Return [None] if `total == 0`. pub fn fmt_percentage(&self) -> Option { if self.total == 0 { - return None; + return None } // Calculate percentage with 2 decimal places. @@ -257,14 +257,14 @@ impl StageCheckpoint { match stage_checkpoint { StageUnitCheckpoint::Account(AccountHashingCheckpoint { progress: entities, .. - }) - | StageUnitCheckpoint::Storage(StorageHashingCheckpoint { + }) | + StageUnitCheckpoint::Storage(StorageHashingCheckpoint { progress: entities, .. - }) - | StageUnitCheckpoint::Entities(entities) - | StageUnitCheckpoint::Execution(ExecutionCheckpoint { progress: entities, .. }) - | StageUnitCheckpoint::Headers(HeadersCheckpoint { progress: entities, .. }) - | StageUnitCheckpoint::IndexHistory(IndexHistoryCheckpoint { + }) | + StageUnitCheckpoint::Entities(entities) | + StageUnitCheckpoint::Execution(ExecutionCheckpoint { progress: entities, .. }) | + StageUnitCheckpoint::Headers(HeadersCheckpoint { progress: entities, .. }) | + StageUnitCheckpoint::IndexHistory(IndexHistoryCheckpoint { progress: entities, .. }) => Some(entities), @@ -300,10 +300,10 @@ impl StageUnitCheckpoint { /// range. pub const fn set_block_range(&mut self, from: u64, to: u64) -> Option { match self { - Self::Account(AccountHashingCheckpoint { block_range, .. }) - | Self::Storage(StorageHashingCheckpoint { block_range, .. }) - | Self::Execution(ExecutionCheckpoint { block_range, .. }) - | Self::IndexHistory(IndexHistoryCheckpoint { block_range, .. }) => { + Self::Account(AccountHashingCheckpoint { block_range, .. }) | + Self::Storage(StorageHashingCheckpoint { block_range, .. }) | + Self::Execution(ExecutionCheckpoint { block_range, .. }) | + Self::IndexHistory(IndexHistoryCheckpoint { block_range, .. }) => { let old_range = *block_range; *block_range = CheckpointBlockRange { from, to }; diff --git a/crates/stages/types/src/execution.rs b/crates/stages/types/src/execution.rs index bdfbaf01cb..a334951abe 100644 --- a/crates/stages/types/src/execution.rs +++ b/crates/stages/types/src/execution.rs @@ -42,9 +42,9 @@ impl ExecutionStageThresholds { cumulative_gas_used: u64, elapsed: Duration, ) -> bool { - blocks_processed >= self.max_blocks.unwrap_or(u64::MAX) - || changes_processed >= self.max_changes.unwrap_or(u64::MAX) - || cumulative_gas_used >= self.max_cumulative_gas.unwrap_or(u64::MAX) - || elapsed >= self.max_duration.unwrap_or(Duration::MAX) + blocks_processed >= self.max_blocks.unwrap_or(u64::MAX) || + changes_processed >= self.max_changes.unwrap_or(u64::MAX) || + cumulative_gas_used >= self.max_cumulative_gas.unwrap_or(u64::MAX) || + elapsed >= self.max_duration.unwrap_or(Duration::MAX) } } diff --git a/crates/stateless/src/trie.rs b/crates/stateless/src/trie.rs index cb00d2d580..5a35e52a7f 100644 --- a/crates/stateless/src/trie.rs +++ b/crates/stateless/src/trie.rs @@ -70,7 +70,7 @@ impl StatelessSparseTrie { if let Some(bytes) = self.inner.get_account_value(&hashed_address) { let account = TrieAccount::decode(&mut bytes.as_slice())?; - return Ok(Some(account)); + return Ok(Some(account)) } if !self.inner.check_valid_account_witness(hashed_address) { @@ -91,7 +91,7 @@ impl StatelessSparseTrie { let hashed_slot = keccak256(B256::from(slot)); if let Some(raw) = self.inner.get_storage_slot_value(&hashed_address, &hashed_slot) { - return Ok(U256::decode(&mut raw.as_slice())?); + return Ok(U256::decode(&mut raw.as_slice())?) } // Storage slot value is not present in the trie, validate that the witness is complete. @@ -100,8 +100,8 @@ impl StatelessSparseTrie { // ...check that its storage is either empty or the storage trie was sufficiently // revealed... let account = TrieAccount::decode(&mut bytes.as_slice())?; - if account.storage_root != EMPTY_ROOT_HASH - && !self.inner.check_valid_storage_witness(hashed_address, hashed_slot) + if account.storage_root != EMPTY_ROOT_HASH && + !self.inner.check_valid_storage_witness(hashed_address, hashed_slot) { return Err(ProviderError::TrieWitnessError(format!( "incomplete storage witness: prover must supply exclusion proof for slot {hashed_slot:?} in account {hashed_address:?}" 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 9ddf89f6da..491419ef4b 100644 --- a/crates/static-file/static-file/src/static_file_producer.rs +++ b/crates/static-file/static-file/src/static_file_producer.rs @@ -116,7 +116,7 @@ where pub fn run(&self, targets: StaticFileTargets) -> StaticFileProducerResult { // If there are no targets, do not produce any static files and return early if !targets.any() { - return Ok(targets); + return Ok(targets) } debug_assert!(targets.is_contiguous_to_highest_static_files( @@ -209,8 +209,8 @@ where self.get_static_file_target(highest_static_files.headers, finalized_block_number) }), // StaticFile receipts only if they're not pruned according to the user configuration - receipts: if self.prune_modes.receipts.is_none() - && self.prune_modes.receipts_log_filter.is_empty() + receipts: if self.prune_modes.receipts.is_none() && + self.prune_modes.receipts_log_filter.is_empty() { finalized_block_numbers.receipts.and_then(|finalized_block_number| { self.get_static_file_target( diff --git a/crates/static-file/types/src/lib.rs b/crates/static-file/types/src/lib.rs index f9d4645811..5d63849364 100644 --- a/crates/static-file/types/src/lib.rs +++ b/crates/static-file/types/src/lib.rs @@ -94,10 +94,10 @@ pub struct StaticFileTargets { impl StaticFileTargets { /// Returns `true` if any of the targets are [Some]. pub const fn any(&self) -> bool { - self.headers.is_some() - || self.receipts.is_some() - || self.transactions.is_some() - || self.block_meta.is_some() + self.headers.is_some() || + self.receipts.is_some() || + self.transactions.is_some() || + self.block_meta.is_some() } /// Returns `true` if all targets are either [`None`] or has beginning of the range equal to the @@ -112,9 +112,10 @@ impl StaticFileTargets { .iter() .all(|(target_block_range, highest_static_fileted_block)| { target_block_range.is_none_or(|target_block_range| { - *target_block_range.start() - == highest_static_fileted_block - .map_or(0, |highest_static_fileted_block| highest_static_fileted_block + 1) + *target_block_range.start() == + highest_static_fileted_block.map_or(0, |highest_static_fileted_block| { + highest_static_fileted_block + 1 + }) }) }) } diff --git a/crates/static-file/types/src/segment.rs b/crates/static-file/types/src/segment.rs index 9ad44dc1e5..185eff18ea 100644 --- a/crates/static-file/types/src/segment.rs +++ b/crates/static-file/types/src/segment.rs @@ -115,14 +115,14 @@ impl StaticFileSegment { pub fn parse_filename(name: &str) -> Option<(Self, SegmentRangeInclusive)> { let mut parts = name.split('_'); if !(parts.next() == Some("static") && parts.next() == Some("file")) { - return None; + return None } let segment = Self::from_str(parts.next()?).ok()?; let (block_start, block_end) = (parts.next()?.parse().ok()?, parts.next()?.parse().ok()?); if block_start > block_end { - return None; + return None } Some((segment, SegmentRangeInclusive::new(block_start, block_end))) @@ -303,7 +303,7 @@ impl SegmentHeader { /// Returns the row offset which depends on whether the segment is block or transaction based. pub fn start(&self) -> Option { if self.segment.is_block_based() { - return self.block_start(); + return self.block_start() } self.tx_start() } diff --git a/crates/storage/codecs/derive/src/compact/flags.rs b/crates/storage/codecs/derive/src/compact/flags.rs index 67102c5266..b6bad46291 100644 --- a/crates/storage/codecs/derive/src/compact/flags.rs +++ b/crates/storage/codecs/derive/src/compact/flags.rs @@ -30,7 +30,7 @@ pub(crate) fn generate_flag_struct( .iter() .filter_map(|f| { if let FieldTypes::StructField(f) = f { - return Some(f); + return Some(f) } None }) @@ -41,7 +41,7 @@ pub(crate) fn generate_flag_struct( }; if total_bits == 0 { - return placeholder_flag_struct(ident, &flags_ident); + return placeholder_flag_struct(ident, &flags_ident) } let (total_bytes, unused_bits) = pad_flag_struct(total_bits, &mut field_flags); diff --git a/crates/storage/codecs/derive/src/compact/generator.rs b/crates/storage/codecs/derive/src/compact/generator.rs index 85b7186fe8..e6c06f44ad 100644 --- a/crates/storage/codecs/derive/src/compact/generator.rs +++ b/crates/storage/codecs/derive/src/compact/generator.rs @@ -144,7 +144,7 @@ fn generate_from_compact( let ident = format_ident!("{}", field.name); return Some(quote! { #ident: #ident, - }); + }) } None }); diff --git a/crates/storage/codecs/derive/src/compact/mod.rs b/crates/storage/codecs/derive/src/compact/mod.rs index 56d03ea5bc..0e795e7a94 100644 --- a/crates/storage/codecs/derive/src/compact/mod.rs +++ b/crates/storage/codecs/derive/src/compact/mod.rs @@ -150,11 +150,10 @@ fn load_field_from_segments( if is_enum { fields.push(FieldTypes::EnumUnnamedField((ftype, use_alt_impl))); } else { - let should_compact = is_flag_type(&ftype) - || field - .attrs - .iter() - .any(|attr| attr.path().segments.iter().any(|path| path.ident == "maybe_zero")); + let should_compact = is_flag_type(&ftype) || + field.attrs.iter().any(|attr| { + attr.path().segments.iter().any(|path| path.ident == "maybe_zero") + }); fields.push(FieldTypes::StructField(StructFieldDescriptor { name: field.ident.as_ref().map(|i| i.to_string()).unwrap_or_default(), @@ -189,7 +188,7 @@ fn should_use_alt_impl(ftype: &str, segment: &syn::PathSegment) -> bool { ] .contains(&path.ident.to_string().as_str()) { - return true; + return true } } } diff --git a/crates/storage/codecs/derive/src/compact/structs.rs b/crates/storage/codecs/derive/src/compact/structs.rs index 469f89a00b..f8ebda3349 100644 --- a/crates/storage/codecs/derive/src/compact/structs.rs +++ b/crates/storage/codecs/derive/src/compact/structs.rs @@ -67,7 +67,7 @@ impl<'a> StructHandler<'a> { }) } - return; + return } let name = format_ident!("{name}"); diff --git a/crates/storage/codecs/derive/src/lib.rs b/crates/storage/codecs/derive/src/lib.rs index 54ad3d25ca..a835e8fab3 100644 --- a/crates/storage/codecs/derive/src/lib.rs +++ b/crates/storage/codecs/derive/src/lib.rs @@ -80,11 +80,11 @@ pub fn derive_zstd(input: TokenStream) -> TokenStream { let path: syn::Path = value.parse()?; decompressor = Some(path); } else { - return Err(meta.error("unsupported attribute")); + return Err(meta.error("unsupported attribute")) } Ok(()) }) { - return err.to_compile_error().into(); + return err.to_compile_error().into() } } } @@ -93,7 +93,7 @@ pub fn derive_zstd(input: TokenStream) -> TokenStream { return quote! { compile_error!("missing compressor or decompressor attribute"); } - .into(); + .into() }; compact::derive(input, Some(ZstdConfig { compressor, decompressor })) diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index fe5ab44d80..a9cb7f2fcd 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -309,7 +309,7 @@ where #[inline] fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (None, buf); + return (None, buf) } let (len, mut buf) = decode_varuint(buf); @@ -338,7 +338,7 @@ where #[inline] fn specialized_from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (None, buf); + return (None, buf) } let (element, buf) = T::from_compact(buf, len); @@ -387,7 +387,7 @@ impl Compact for U256 { #[inline] fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (Self::ZERO, buf); + return (Self::ZERO, buf) } let mut arr = [0; 32]; @@ -427,7 +427,7 @@ impl Compact for [u8; N] { #[inline] fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return ([0; N], buf); + return ([0; N], buf) } let v = buf[..N].try_into().unwrap(); @@ -512,7 +512,7 @@ fn decode_varuint(buf: &[u8]) -> (usize, &[u8]) { let byte = buf[i]; value |= usize::from(byte & 0x7F) << (i * 7); if byte < 0x80 { - return (value, &buf[i + 1..]); + return (value, &buf[i + 1..]) } } diff --git a/crates/storage/codecs/src/test_utils.rs b/crates/storage/codecs/src/test_utils.rs index 12a8780722..b845645cb1 100644 --- a/crates/storage/codecs/src/test_utils.rs +++ b/crates/storage/codecs/src/test_utils.rs @@ -32,7 +32,7 @@ /// validate_bitflag_backwards_compat!(TExtension, UnusedBits::NotZero); /// } /// ``` -/// +/// /// ### 2. `Zero` -> `NotZero` /// If it becomes `NotZero`, it would break backwards compatibility, so there is not an action item, /// and should be handled with care in a case by case scenario. diff --git a/crates/storage/db-api/src/cursor.rs b/crates/storage/db-api/src/cursor.rs index 81520d1c20..3aeee949ea 100644 --- a/crates/storage/db-api/src/cursor.rs +++ b/crates/storage/db-api/src/cursor.rs @@ -225,7 +225,7 @@ impl> Iterator for ReverseWalker<'_, T, CURSOR> fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start; + return start } self.cursor.prev().transpose() @@ -265,7 +265,7 @@ impl> Iterator for RangeWalker<'_, T, CURSOR> { fn next(&mut self) -> Option { if self.is_done { - return None; + return None } let next_item = self.start.take().or_else(|| self.cursor.next().transpose()); @@ -356,7 +356,7 @@ impl> Iterator for DupWalker<'_, T, CURSOR> fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start; + return start } self.cursor.next_dup().transpose() } diff --git a/crates/storage/db-api/src/models/storage_sharded_key.rs b/crates/storage/db-api/src/models/storage_sharded_key.rs index eee429247d..a7a1ffb71b 100644 --- a/crates/storage/db-api/src/models/storage_sharded_key.rs +++ b/crates/storage/db-api/src/models/storage_sharded_key.rs @@ -68,7 +68,7 @@ impl Encode for StorageShardedKey { impl Decode for StorageShardedKey { fn decode(value: &[u8]) -> Result { if value.len() != STORAGE_SHARD_KEY_BYTES_SIZE { - return Err(DatabaseError::Decode); + return Err(DatabaseError::Decode) } let tx_num_index = value.len() - 8; diff --git a/crates/storage/db-api/src/unwind.rs b/crates/storage/db-api/src/unwind.rs index c553914f0c..79cf585a62 100644 --- a/crates/storage/db-api/src/unwind.rs +++ b/crates/storage/db-api/src/unwind.rs @@ -31,7 +31,7 @@ pub trait DbTxUnwindExt: DbTxMut { while let Some(Ok((entry_key, _))) = reverse_walker.next() { if selector(entry_key.clone()) <= key { - break; + break } reverse_walker.delete_current()?; deleted += 1; diff --git a/crates/storage/db-common/src/db_tool/mod.rs b/crates/storage/db-common/src/db_tool/mod.rs index b48ef3ab16..5866ad8ae2 100644 --- a/crates/storage/db-common/src/db_tool/mod.rs +++ b/crates/storage/db-common/src/db_tool/mod.rs @@ -50,18 +50,18 @@ impl DbTool { let (key, value) = (k.into_key(), v.into_value()); if key.len() + value.len() < filter.min_row_size { - return None; + return None } if key.len() < filter.min_key_size { - return None; + return None } if value.len() < filter.min_value_size { - return None; + return None } let result = || { if filter.only_count { - return None; + return None } Some(( ::Key::decode(&key).unwrap(), @@ -71,16 +71,16 @@ impl DbTool { match &*bmb { Some(searcher) => { - if searcher.find_first_in(&value).is_some() - || searcher.find_first_in(&key).is_some() + if searcher.find_first_in(&value).is_some() || + searcher.find_first_in(&key).is_some() { hits += 1; - return result(); + return result() } } None => { hits += 1; - return result(); + return result() } } } diff --git a/crates/storage/db-common/src/init.rs b/crates/storage/db-common/src/init.rs index 81756a648c..a29d02a42c 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -106,17 +106,17 @@ where // make sure that our database has been written to, and throw error if it's empty. if factory.get_stage_checkpoint(StageId::Headers)?.is_none() { error!(target: "reth::storage", "Genesis header found on static files, but database is uninitialized."); - return Err(InitStorageError::UninitializedDatabase); + return Err(InitStorageError::UninitializedDatabase) } debug!("Genesis already written, skipping."); - return Ok(hash); + return Ok(hash) } return Err(InitStorageError::GenesisHashMismatch { chainspec_hash: hash, storage_hash: block_hash, - }); + }) } Err(e) => { debug!(?e); @@ -381,7 +381,7 @@ where + AsRef, { if etl_config.file_size == 0 { - return Err(eyre::eyre!("ETL file size cannot be zero")); + return Err(eyre::eyre!("ETL file size cannot be zero")) } let block = provider_rw.last_block_number()?; @@ -403,7 +403,7 @@ where got: dump_state_root, expected: expected_state_root, }) - .into()); + .into()) } debug!(target: "reth::cli", @@ -436,7 +436,7 @@ where got: computed_state_root, expected: expected_state_root, }) - .into()); + .into()) } // insert sync stages for stages that require state @@ -470,7 +470,7 @@ fn parse_accounts( while let Ok(n) = reader.read_line(&mut line) { if n == 0 { - break; + break } let GenesisAccountWithAddress { genesis_account, address } = serde_json::from_str(&line)?; @@ -515,8 +515,8 @@ where accounts.push((address, account)); - if (index > 0 && index % AVERAGE_COUNT_ACCOUNTS_PER_GB_STATE_DUMP == 0) - || index == accounts_len - 1 + if (index > 0 && index % AVERAGE_COUNT_ACCOUNTS_PER_GB_STATE_DUMP == 0) || + index == accounts_len - 1 { total_inserted_accounts += accounts.len(); @@ -598,7 +598,7 @@ where "State root has been computed" ); - return Ok(root); + return Ok(root) } } } diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index 6be3ce7d83..d536e69a27 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -417,7 +417,7 @@ impl DatabaseEnv { LogLevel::Extra => 7, }); } else { - return Err(DatabaseError::LogLevelUnavailable(log_level)); + return Err(DatabaseError::LogLevelUnavailable(log_level)) } } @@ -465,7 +465,7 @@ impl DatabaseEnv { /// Records version that accesses the database with write privileges. pub fn record_client_version(&self, version: ClientVersion) -> Result<(), DatabaseError> { if version.is_empty() { - return Ok(()); + return Ok(()) } let tx = self.tx_mut()?; diff --git a/crates/storage/db/src/implementation/mdbx/tx.rs b/crates/storage/db/src/implementation/mdbx/tx.rs index e860e9e253..d2b20f5ae3 100644 --- a/crates/storage/db/src/implementation/mdbx/tx.rs +++ b/crates/storage/db/src/implementation/mdbx/tx.rs @@ -231,9 +231,9 @@ impl MetricsHandler { /// NOTE: Backtrace is recorded using [`Backtrace::force_capture`], so `RUST_BACKTRACE` env var /// is not needed. fn log_backtrace_on_long_read_transaction(&self) { - if self.record_backtrace - && !self.backtrace_recorded.load(Ordering::Relaxed) - && self.transaction_mode().is_read_only() + if self.record_backtrace && + !self.backtrace_recorded.load(Ordering::Relaxed) && + self.transaction_mode().is_read_only() { let open_duration = self.start.elapsed(); if open_duration >= self.long_transaction_duration { diff --git a/crates/storage/db/src/lockfile.rs b/crates/storage/db/src/lockfile.rs index 13cf09283c..a1a9946b57 100644 --- a/crates/storage/db/src/lockfile.rs +++ b/crates/storage/db/src/lockfile.rs @@ -53,7 +53,7 @@ impl StorageLock { start_time = process_lock.start_time, "Storage lock already taken." ); - return Err(StorageLockError::Taken(process_lock.pid)); + return Err(StorageLockError::Taken(process_lock.pid)) } } diff --git a/crates/storage/db/src/static_file/cursor.rs b/crates/storage/db/src/static_file/cursor.rs index 716bd44ea3..7721acc1a8 100644 --- a/crates/storage/db/src/static_file/cursor.rs +++ b/crates/storage/db/src/static_file/cursor.rs @@ -33,7 +33,7 @@ impl<'a> StaticFileCursor<'a> { mask: usize, ) -> ProviderResult>> { if self.jar().rows() == 0 { - return Ok(None); + return Ok(None) } let row = match key_or_num { @@ -41,7 +41,7 @@ impl<'a> StaticFileCursor<'a> { KeyOrNumber::Number(n) => match self.jar().user_header().start() { Some(offset) => { if offset > n { - return Ok(None); + return Ok(None) } self.row_by_number_with_cols((n - offset) as usize, mask) } diff --git a/crates/storage/db/src/version.rs b/crates/storage/db/src/version.rs index 424d543606..09c1f94678 100644 --- a/crates/storage/db/src/version.rs +++ b/crates/storage/db/src/version.rs @@ -48,7 +48,7 @@ pub enum DatabaseVersionError { pub fn check_db_version_file>(db_path: P) -> Result<(), DatabaseVersionError> { let version = get_db_version(db_path)?; if version != DB_VERSION { - return Err(DatabaseVersionError::VersionMismatch { version }); + return Err(DatabaseVersionError::VersionMismatch { version }) } Ok(()) diff --git a/crates/storage/libmdbx-rs/mdbx-sys/build.rs b/crates/storage/libmdbx-rs/mdbx-sys/build.rs index 6a4d5caa1d..c265d02e23 100644 --- a/crates/storage/libmdbx-rs/mdbx-sys/build.rs +++ b/crates/storage/libmdbx-rs/mdbx-sys/build.rs @@ -32,8 +32,8 @@ fn main() { // Propagate `-C target-cpu=native` let rustflags = env::var("CARGO_ENCODED_RUSTFLAGS").unwrap(); - if rustflags.contains("target-cpu=native") - && env::var("CARGO_CFG_TARGET_ENV").unwrap() != "msvc" + if rustflags.contains("target-cpu=native") && + env::var("CARGO_CFG_TARGET_ENV").unwrap() != "msvc" { cc.flag("-march=native"); } @@ -53,42 +53,42 @@ fn generate_bindings(mdbx: &Path, out_file: &Path) { impl ParseCallbacks for Callbacks { fn int_macro(&self, name: &str, _value: i64) -> Option { match name { - "MDBX_SUCCESS" - | "MDBX_KEYEXIST" - | "MDBX_NOTFOUND" - | "MDBX_PAGE_NOTFOUND" - | "MDBX_CORRUPTED" - | "MDBX_PANIC" - | "MDBX_VERSION_MISMATCH" - | "MDBX_INVALID" - | "MDBX_MAP_FULL" - | "MDBX_DBS_FULL" - | "MDBX_READERS_FULL" - | "MDBX_TLS_FULL" - | "MDBX_TXN_FULL" - | "MDBX_CURSOR_FULL" - | "MDBX_PAGE_FULL" - | "MDBX_MAP_RESIZED" - | "MDBX_INCOMPATIBLE" - | "MDBX_BAD_RSLOT" - | "MDBX_BAD_TXN" - | "MDBX_BAD_VALSIZE" - | "MDBX_BAD_DBI" - | "MDBX_LOG_DONTCHANGE" - | "MDBX_DBG_DONTCHANGE" - | "MDBX_RESULT_TRUE" - | "MDBX_UNABLE_EXTEND_MAPSIZE" - | "MDBX_PROBLEM" - | "MDBX_LAST_LMDB_ERRCODE" - | "MDBX_BUSY" - | "MDBX_EMULTIVAL" - | "MDBX_EBADSIGN" - | "MDBX_WANNA_RECOVERY" - | "MDBX_EKEYMISMATCH" - | "MDBX_TOO_LARGE" - | "MDBX_THREAD_MISMATCH" - | "MDBX_TXN_OVERLAPPING" - | "MDBX_LAST_ERRCODE" => Some(IntKind::Int), + "MDBX_SUCCESS" | + "MDBX_KEYEXIST" | + "MDBX_NOTFOUND" | + "MDBX_PAGE_NOTFOUND" | + "MDBX_CORRUPTED" | + "MDBX_PANIC" | + "MDBX_VERSION_MISMATCH" | + "MDBX_INVALID" | + "MDBX_MAP_FULL" | + "MDBX_DBS_FULL" | + "MDBX_READERS_FULL" | + "MDBX_TLS_FULL" | + "MDBX_TXN_FULL" | + "MDBX_CURSOR_FULL" | + "MDBX_PAGE_FULL" | + "MDBX_MAP_RESIZED" | + "MDBX_INCOMPATIBLE" | + "MDBX_BAD_RSLOT" | + "MDBX_BAD_TXN" | + "MDBX_BAD_VALSIZE" | + "MDBX_BAD_DBI" | + "MDBX_LOG_DONTCHANGE" | + "MDBX_DBG_DONTCHANGE" | + "MDBX_RESULT_TRUE" | + "MDBX_UNABLE_EXTEND_MAPSIZE" | + "MDBX_PROBLEM" | + "MDBX_LAST_LMDB_ERRCODE" | + "MDBX_BUSY" | + "MDBX_EMULTIVAL" | + "MDBX_EBADSIGN" | + "MDBX_WANNA_RECOVERY" | + "MDBX_EKEYMISMATCH" | + "MDBX_TOO_LARGE" | + "MDBX_THREAD_MISMATCH" | + "MDBX_TXN_OVERLAPPING" | + "MDBX_LAST_ERRCODE" => Some(IntKind::Int), _ => Some(IntKind::UInt), } } diff --git a/crates/storage/libmdbx-rs/src/codec.rs b/crates/storage/libmdbx-rs/src/codec.rs index c67d74c510..c78f79db9f 100644 --- a/crates/storage/libmdbx-rs/src/codec.rs +++ b/crates/storage/libmdbx-rs/src/codec.rs @@ -41,8 +41,8 @@ impl TableObject for Cow<'_, [u8]> { #[cfg(not(feature = "return-borrowed"))] { - let is_dirty = (!K::IS_READ_ONLY) - && crate::error::mdbx_result(ffi::mdbx_is_dirty(_txn, data_val.iov_base))?; + let is_dirty = (!K::IS_READ_ONLY) && + crate::error::mdbx_result(ffi::mdbx_is_dirty(_txn, data_val.iov_base))?; Ok(if is_dirty { Cow::Owned(s.to_vec()) } else { Cow::Borrowed(s) }) } @@ -81,7 +81,7 @@ impl TableObject for ObjectLength { impl TableObject for [u8; LEN] { fn decode(data_val: &[u8]) -> Result { if data_val.len() != LEN { - return Err(Error::DecodeErrorLenDiff); + return Err(Error::DecodeErrorLenDiff) } let mut a = [0; LEN]; a[..].copy_from_slice(data_val); diff --git a/crates/storage/libmdbx-rs/src/cursor.rs b/crates/storage/libmdbx-rs/src/cursor.rs index 13ae2f7ad5..8f7a4b5cd4 100644 --- a/crates/storage/libmdbx-rs/src/cursor.rs +++ b/crates/storage/libmdbx-rs/src/cursor.rs @@ -371,7 +371,7 @@ where { let res: Result> = self.set_range(key); if let Err(error) = res { - return Iter::Err(Some(error)); + return Iter::Err(Some(error)) }; Iter::new(self, ffi::MDBX_GET_CURRENT, ffi::MDBX_NEXT) } @@ -406,7 +406,7 @@ where { let res: Result> = self.set_range(key); if let Err(error) = res { - return IterDup::Err(Some(error)); + return IterDup::Err(Some(error)) }; IterDup::new(self, ffi::MDBX_GET_CURRENT) } @@ -422,7 +422,7 @@ where Ok(Some(_)) => (), Ok(None) => { let _: Result> = self.last(); - return Iter::new(self, ffi::MDBX_NEXT, ffi::MDBX_NEXT); + return Iter::new(self, ffi::MDBX_NEXT, ffi::MDBX_NEXT) } Err(error) => return Iter::Err(Some(error)), }; diff --git a/crates/storage/libmdbx-rs/src/environment.rs b/crates/storage/libmdbx-rs/src/environment.rs index 6c3e332627..9be857796f 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -121,10 +121,10 @@ impl Environment { warn!(target: "libmdbx", "Process stalled, awaiting read-write transaction lock."); } sleep(Duration::from_millis(250)); - continue; + continue } - break res; + break res }?; Ok(Transaction::new_from_ptr(self.clone(), txn.0)) } @@ -220,7 +220,7 @@ impl Environment { for result in cursor.iter_slices() { let (_key, value) = result?; if value.len() < size_of::() { - return Err(Error::Corrupted); + return Err(Error::Corrupted) } let s = &value[..size_of::()]; @@ -732,7 +732,7 @@ impl EnvironmentBuilder { })() { ffi::mdbx_env_close_ex(env, false); - return Err(e); + return Err(e) } } diff --git a/crates/storage/libmdbx-rs/src/error.rs b/crates/storage/libmdbx-rs/src/error.rs index da11540083..2f852c3dc7 100644 --- a/crates/storage/libmdbx-rs/src/error.rs +++ b/crates/storage/libmdbx-rs/src/error.rs @@ -200,9 +200,9 @@ impl Error { Self::DecodeErrorLenDiff | Self::DecodeError => ffi::MDBX_EINVAL, Self::TooLarge => ffi::MDBX_TOO_LARGE, Self::BadSignature => ffi::MDBX_EBADSIGN, - Self::Access - | Self::WriteTransactionUnsupportedInReadOnlyMode - | Self::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, + Self::Access | + Self::WriteTransactionUnsupportedInReadOnlyMode | + Self::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, Self::ReadTransactionTimeout => -96000, // Custom non-MDBX error code Self::Permission => ffi::MDBX_EPERM, Self::Other(err_code) => *err_code, diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index 38203d50ee..677a33474b 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -530,7 +530,7 @@ impl Transaction { /// Begins a new nested transaction inside of this transaction. pub fn begin_nested_txn(&mut self) -> Result { if self.inner.env.is_write_map() { - return Err(Error::NestedTransactionsUnsupportedWithWriteMap); + return Err(Error::NestedTransactionsUnsupportedWithWriteMap) } self.txn_execute(|txn| { let (tx, rx) = sync_channel(0); @@ -614,7 +614,7 @@ impl TransactionPtr { // to the `mdbx_txn_reset`. #[cfg(feature = "read-tx-timeouts")] if self.is_timed_out() { - return Err(Error::ReadTransactionTimeout); + return Err(Error::ReadTransactionTimeout) } Ok((f)(self.txn)) diff --git a/crates/storage/nippy-jar/src/compression/lz4.rs b/crates/storage/nippy-jar/src/compression/lz4.rs index 5bf96d3372..cdffd91529 100644 --- a/crates/storage/nippy-jar/src/compression/lz4.rs +++ b/crates/storage/nippy-jar/src/compression/lz4.rs @@ -42,7 +42,7 @@ impl Compression for Lz4 { Err(err) => { multiplier *= 2; if multiplier == 16 { - return Err(NippyJarError::Custom(err.to_string())); + return Err(NippyJarError::Custom(err.to_string())) } } } diff --git a/crates/storage/nippy-jar/src/compression/zstd.rs b/crates/storage/nippy-jar/src/compression/zstd.rs index 36560a3d5d..5f2888d041 100644 --- a/crates/storage/nippy-jar/src/compression/zstd.rs +++ b/crates/storage/nippy-jar/src/compression/zstd.rs @@ -64,7 +64,7 @@ impl Zstd { pub fn decompressors(&self) -> Result>, NippyJarError> { if let Some(dictionaries) = &self.dictionaries { debug_assert!(dictionaries.len() == self.columns); - return dictionaries.decompressors(); + return dictionaries.decompressors() } Ok(vec![]) @@ -76,12 +76,12 @@ impl Zstd { ZstdState::PendingDictionary => Err(NippyJarError::CompressorNotReady), ZstdState::Ready => { if !self.use_dict { - return Ok(None); + return Ok(None) } if let Some(dictionaries) = &self.dictionaries { debug!(target: "nippy-jar", count=?dictionaries.len(), "Generating ZSTD compressor dictionaries."); - return Ok(Some(dictionaries.compressors()?)); + return Ok(Some(dictionaries.compressors()?)) } Ok(None) } @@ -106,7 +106,7 @@ impl Zstd { buffer.reserve(column_value.len() * multiplier); multiplier += 1; if multiplier == 5 { - return Err(NippyJarError::Disconnect(err)); + return Err(NippyJarError::Disconnect(err)) } } @@ -196,7 +196,7 @@ impl Compression for Zstd { columns: Vec>>, ) -> Result<(), NippyJarError> { if !self.use_dict { - return Ok(()); + return Ok(()) } // There's a per 2GB hard limit on each column data set for training @@ -210,7 +210,7 @@ impl Compression for Zstd { // ``` if columns.len() != self.columns { - return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())); + return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())) } let mut dictionaries = Vec::with_capacity(columns.len()); @@ -369,7 +369,7 @@ impl Serialize for ZstdDictionary<'_> { impl PartialEq for ZstdDictionary<'_> { fn eq(&self, other: &Self) -> bool { if let (Self::Raw(a), Self::Raw(b)) = (self, &other) { - return a == b; + return a == b } unimplemented!( "`DecoderDictionary` can't be compared. So comparison should be done after decompressing a value." diff --git a/crates/storage/nippy-jar/src/consistency.rs b/crates/storage/nippy-jar/src/consistency.rs index 2fd4aba1ac..0abe118a4b 100644 --- a/crates/storage/nippy-jar/src/consistency.rs +++ b/crates/storage/nippy-jar/src/consistency.rs @@ -56,7 +56,7 @@ impl NippyJarChecker { // When an offset size is smaller than the initial (8), we are dealing with immutable // data. if reader.offset_size() != OFFSET_SIZE_BYTES { - return Err(NippyJarError::FrozenJar); + return Err(NippyJarError::FrozenJar) } let expected_offsets_file_size: u64 = (1 + // first byte is the size of one offset @@ -64,10 +64,10 @@ impl NippyJarChecker { OFFSET_SIZE_BYTES as usize) as u64; // expected size of the data file let actual_offsets_file_size = self.offsets_file().get_ref().metadata()?.len(); - if mode.should_err() - && expected_offsets_file_size.cmp(&actual_offsets_file_size) != Ordering::Equal + if mode.should_err() && + expected_offsets_file_size.cmp(&actual_offsets_file_size) != Ordering::Equal { - return Err(NippyJarError::InconsistentState); + return Err(NippyJarError::InconsistentState) } // Offsets configuration wasn't properly committed @@ -89,8 +89,8 @@ impl NippyJarChecker { self.jar.rows = ((actual_offsets_file_size. saturating_sub(1). // first byte is the size of one offset saturating_sub(OFFSET_SIZE_BYTES as u64) / // expected size of the data file - (self.jar.columns as u64)) - / OFFSET_SIZE_BYTES as u64) as usize; + (self.jar.columns as u64)) / + OFFSET_SIZE_BYTES as u64) as usize; // Freeze row count changed self.jar.freeze_config()?; @@ -103,7 +103,7 @@ impl NippyJarChecker { let data_file_len = self.data_file().get_ref().metadata()?.len(); if mode.should_err() && last_offset.cmp(&data_file_len) != Ordering::Equal { - return Err(NippyJarError::InconsistentState); + return Err(NippyJarError::InconsistentState) } // Offset list wasn't properly committed @@ -138,7 +138,7 @@ impl NippyJarChecker { // Since we decrease the offset list, we need to check the consistency of // `self.jar.rows` again self.handle_consistency(ConsistencyFailStrategy::Heal)?; - break; + break } } } diff --git a/crates/storage/nippy-jar/src/cursor.rs b/crates/storage/nippy-jar/src/cursor.rs index 3861a8fe1e..505a00260b 100644 --- a/crates/storage/nippy-jar/src/cursor.rs +++ b/crates/storage/nippy-jar/src/cursor.rs @@ -80,7 +80,7 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { if self.row as usize >= self.jar.rows { // Has reached the end - return Ok(None); + return Ok(None) } let mut row = Vec::with_capacity(self.jar.columns); @@ -120,7 +120,7 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { if self.row as usize >= self.jar.rows { // Has reached the end - return Ok(None); + return Ok(None) } let columns = self.jar.columns; diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index 0cc8b79868..daa272fdd1 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -306,12 +306,12 @@ impl NippyJar { columns: &[impl IntoIterator>>], ) -> Result<(), NippyJarError> { if columns.len() != self.columns { - return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())); + return Err(NippyJarError::ColumnLenMismatch(self.columns, columns.len())) } if let Some(compression) = &self.compressor { if !compression.is_ready() { - return Err(NippyJarError::CompressorNotReady); + return Err(NippyJarError::CompressorNotReady) } } @@ -353,9 +353,9 @@ impl DataReader { // Ensure that the size of an offset is at most 8 bytes. if offset_size > 8 { - return Err(NippyJarError::OffsetSizeTooBig { offset_size }); + return Err(NippyJarError::OffsetSizeTooBig { offset_size }) } else if offset_size == 0 { - return Err(NippyJarError::OffsetSizeTooSmall { offset_size }); + return Err(NippyJarError::OffsetSizeTooSmall { offset_size }) } Ok(Self { data_file, data_mmap, offset_file, offset_size, offset_mmap }) @@ -395,7 +395,7 @@ impl DataReader { let offset_end = index.saturating_add(self.offset_size as usize); if offset_end > self.offset_mmap.len() { - return Err(NippyJarError::OffsetOutOfBounds { index }); + return Err(NippyJarError::OffsetOutOfBounds { index }) } buffer[..self.offset_size as usize].copy_from_slice(&self.offset_mmap[index..offset_end]); diff --git a/crates/storage/nippy-jar/src/writer.rs b/crates/storage/nippy-jar/src/writer.rs index 0a4738db39..b20d9d6507 100644 --- a/crates/storage/nippy-jar/src/writer.rs +++ b/crates/storage/nippy-jar/src/writer.rs @@ -284,7 +284,7 @@ impl NippyJarWriter { return Err(NippyJarError::InvalidPruning( num_offsets, remaining_to_prune as u64, - )); + )) } let new_num_offsets = num_offsets.saturating_sub(remaining_to_prune as u64); @@ -310,7 +310,7 @@ impl NippyJarWriter { self.data_file.get_mut().set_len(last_offset)?; } } else { - return Err(NippyJarError::InvalidPruning(0, remaining_to_prune as u64)); + return Err(NippyJarError::InvalidPruning(0, remaining_to_prune as u64)) } } @@ -406,7 +406,7 @@ impl NippyJarWriter { for offset in self.offsets.drain(..) { if let Some(last_offset_ondisk) = last_offset_ondisk.take() { if last_offset_ondisk == offset { - continue; + continue } } self.offsets_file.write_all(&offset.to_le_bytes())?; diff --git a/crates/storage/provider/src/providers/consistent.rs b/crates/storage/provider/src/providers/consistent.rs index b0e32f2744..3922e286c2 100644 --- a/crates/storage/provider/src/providers/consistent.rs +++ b/crates/storage/provider/src/providers/consistent.rs @@ -148,7 +148,7 @@ impl ConsistentProvider { range: RangeInclusive, ) -> ProviderResult>>> { if range.is_empty() { - return Ok(None); + return Ok(None) } let start_block_number = *range.start(); let end_block_number = *range.end(); @@ -165,10 +165,10 @@ impl ConsistentProvider { // get transaction receipts let Some(from_transaction_num) = block_bodies.first().map(|body| body.1.first_tx_num()) else { - return Ok(None); + return Ok(None) }; let Some(to_transaction_num) = block_bodies.last().map(|body| body.1.last_tx_num()) else { - return Ok(None); + return Ok(None) }; let mut account_changeset = Vec::new(); @@ -327,7 +327,7 @@ impl ConsistentProvider { }); if start > end { - return Ok(vec![]); + return Ok(vec![]) } // Split range into storage_range and in-memory range. If the in-memory range is not @@ -375,7 +375,7 @@ impl ConsistentProvider { // The predicate was not met, if the number of items differs from the expected. So, we // return what we have. if items.len() as u64 != storage_range.end() - storage_range.start() + 1 { - return Ok(items); + return Ok(items) } } @@ -385,7 +385,7 @@ impl ConsistentProvider { if let Some(item) = map_block_state_item(block, &mut predicate) { items.push(item); } else { - break; + break } } } @@ -443,12 +443,12 @@ impl ConsistentProvider { in_mem_chain .iter() .map(|b| b.block_ref().recovered_block().body().transactions().len() as u64) - .sum::() - + last_block_body_index.last_tx_num() + .sum::() + + last_block_body_index.last_tx_num() }); if start > end { - return Ok(vec![]); + return Ok(vec![]) } let mut tx_range = start..=end; @@ -482,7 +482,7 @@ impl ConsistentProvider { // transaction, advance if *tx_range.start() >= in_memory_tx_num + block_tx_count as u64 { in_memory_tx_num += block_tx_count as u64; - continue; + continue } // This should only be more than 0 once, in case of a partial range inside a block. @@ -497,7 +497,7 @@ impl ConsistentProvider { // Break if the range has been fully processed if in_memory_tx_num > *tx_range.end() { - break; + break } // Set updated range @@ -540,7 +540,7 @@ impl ConsistentProvider { // database lookup if let HashOrNumber::Number(id) = id { if id < in_memory_tx_num { - return fetch_from_db(provider); + return fetch_from_db(provider) } } @@ -553,12 +553,12 @@ impl ConsistentProvider { match id { HashOrNumber::Hash(tx_hash) => { if tx_hash == block.body().transactions()[tx_index].trie_hash() { - return fetch_from_block_state(tx_index, in_memory_tx_num, block_state); + return fetch_from_block_state(tx_index, in_memory_tx_num, block_state) } } HashOrNumber::Number(id) => { if id == in_memory_tx_num { - return fetch_from_block_state(tx_index, in_memory_tx_num, block_state); + return fetch_from_block_state(tx_index, in_memory_tx_num, block_state) } } } @@ -569,7 +569,7 @@ impl ConsistentProvider { // Not found in-memory, so check database. if let HashOrNumber::Hash(_) = id { - return fetch_from_db(provider); + return fetch_from_db(provider) } Ok(None) @@ -587,7 +587,7 @@ impl ConsistentProvider { M: Fn(&BlockState) -> ProviderResult, { if let Some(Some(block_state)) = self.head_block.as_ref().map(|b| b.block_on_chain(id)) { - return fetch_from_block_state(block_state); + return fetch_from_block_state(block_state) } fetch_from_db(&self.storage_provider) } @@ -824,7 +824,7 @@ impl BlockReader for ConsistentProvider { |db_provider| db_provider.find_block_by_hash(hash, BlockSource::Canonical), |block_state| Ok(Some(block_state.block_ref().recovered_block().clone_block())), )? { - return Ok(Some(block)); + return Ok(Some(block)) } } @@ -833,7 +833,7 @@ impl BlockReader for ConsistentProvider { .canonical_in_memory_state .pending_block() .filter(|b| b.hash() == hash) - .map(|b| b.into_block())); + .map(|b| b.into_block())) } Ok(None) @@ -969,7 +969,7 @@ impl TransactionsProvider for ConsistentProvider { fn transaction_by_hash(&self, hash: TxHash) -> ProviderResult> { if let Some(tx) = self.head_block.as_ref().and_then(|b| b.transaction_on_chain(hash)) { - return Ok(Some(tx)); + return Ok(Some(tx)) } self.storage_provider.transaction_by_hash(hash) @@ -982,7 +982,7 @@ impl TransactionsProvider for ConsistentProvider { if let Some((tx, meta)) = self.head_block.as_ref().and_then(|b| b.transaction_meta_on_chain(tx_hash)) { - return Ok(Some((tx, meta))); + return Ok(Some((tx, meta))) } self.storage_provider.transaction_by_hash_with_meta(tx_hash) @@ -1364,7 +1364,7 @@ impl StorageChangeSetReader for ConsistentProvider { .unwrap_or(true); if !storage_history_exists { - return Err(ProviderError::StateAtBlockPruned(block_number)); + return Err(ProviderError::StateAtBlockPruned(block_number)) } self.storage_provider.storage_changeset(block_number) @@ -1410,7 +1410,7 @@ impl ChangeSetReader for ConsistentProvider { .unwrap_or(true); if !account_history_exists { - return Err(ProviderError::StateAtBlockPruned(block_number)); + return Err(ProviderError::StateAtBlockPruned(block_number)) } self.storage_provider.account_block_changeset(block_number) diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index 6307b5b1fd..4957def6e2 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -71,7 +71,7 @@ where // data source that we used during initialization. In this case, that is static files if let Some((hash, number)) = self.tip { if provider_ro.sealed_header(number)?.is_none_or(|header| header.hash() != hash) { - return Err(ConsistentViewError::Reorged { block: hash }.into()); + return Err(ConsistentViewError::Reorged { block: hash }.into()) } } diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index bd2cf29cbd..8178a8c313 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -168,10 +168,10 @@ impl DatabaseProvider { ) -> ProviderResult> { let mut block_number = self.block_number(block_hash)?.ok_or(ProviderError::BlockHashNotFound(block_hash))?; - if block_number == self.best_block_number().unwrap_or_default() - && block_number == self.last_block_number().unwrap_or_default() + if block_number == self.best_block_number().unwrap_or_default() && + block_number == self.last_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProviderRef::new(self))); + return Ok(Box::new(LatestStateProviderRef::new(self))) } // +1 as the changeset that we want is the one that was applied after this block. @@ -358,7 +358,7 @@ impl TryIntoHistoricalStateProvider for Databa // if the block number is the same as the currently best block number on disk we can use the // latest state provider here if block_number == self.best_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProvider::new(self))); + return Ok(Box::new(LatestStateProvider::new(self))) } // +1 as the changeset that we want is the one that was applied after this block. @@ -464,7 +464,7 @@ where while let Some((sharded_key, list)) = item { // If the shard does not belong to the key, break. if !shard_belongs_to_key(&sharded_key) { - break; + break } // Always delete the current shard from the database first @@ -479,18 +479,18 @@ where // Keep it deleted (don't return anything for reinsertion) if first >= block_number { item = cursor.prev()?; - continue; + continue } // Case 2: This is a boundary shard (spans across the unwinding point) // The shard contains some blocks below and some at/above the unwinding point else if block_number <= sharded_key.as_ref().highest_block_number { // Return only the block numbers that are below the unwinding point // These will be reinserted to preserve the historical data - return Ok(list.iter().take_while(|i| *i < block_number).collect::>()); + return Ok(list.iter().take_while(|i| *i < block_number).collect::>()) } // Case 3: Entire shard is below the unwinding point // Return all block numbers for reinsertion (preserve entire shard) - return Ok(list.iter().collect::>()); + return Ok(list.iter().collect::>()) } // No shards found or all processed @@ -611,7 +611,7 @@ impl DatabaseProvider { F: FnMut(H, BodyTy, Range) -> ProviderResult, { if range.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } let len = range.end().saturating_sub(*range.start()) as usize; @@ -806,7 +806,7 @@ impl DatabaseProvider { // delete old shard so new one can be inserted. cursor.delete_current()?; let list = list.iter().collect::>(); - return Ok(list); + return Ok(list) } Ok(Vec::new()) } @@ -965,7 +965,7 @@ impl HeaderSyncGapProvider } Ordering::Less => { // There's either missing or corrupted files. - return Err(ProviderError::HeaderNotFound(next_static_file_block_num.into())); + return Err(ProviderError::HeaderNotFound(next_static_file_block_num.into())) } Ordering::Equal => {} } @@ -1011,7 +1011,7 @@ impl HeaderProvider for DatabasePro if let Some(td) = self.chain_spec.final_paris_total_difficulty() { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)); + return Ok(Some(td)) } } @@ -1077,7 +1077,7 @@ impl HeaderProvider for DatabasePro .ok_or_else(|| ProviderError::HeaderNotFound(number.into()))?; let sealed = SealedHeader::new(header, hash); if !predicate(&sealed) { - break; + break } headers.push(sealed); } @@ -1174,7 +1174,7 @@ impl BlockReader for DatabaseProvid // If they exist but are not indexed, we don't have enough // information to return the block anyways, so we return `None`. let Some(transactions) = self.transactions_by_block(number.into())? else { - return Ok(None); + return Ok(None) }; let body = self @@ -1184,7 +1184,7 @@ impl BlockReader for DatabaseProvid .pop() .ok_or(ProviderError::InvalidStorageOutput)?; - return Ok(Some(Self::Block::new(header, body))); + return Ok(Some(Self::Block::new(header, body))) } } @@ -1427,7 +1427,7 @@ impl TransactionsProvider for Datab timestamp: header.timestamp(), }; - return Ok(Some((transaction, meta))); + return Ok(Some((transaction, meta))) } } } @@ -1455,7 +1455,7 @@ impl TransactionsProvider for Datab Ok(Some(Vec::new())) } else { Ok(Some(self.transactions_by_tx_range_with_cursor(tx_range, &mut tx_cursor)?)) - }; + } } } Ok(None) @@ -1537,7 +1537,7 @@ impl ReceiptProvider for DatabasePr Ok(Some(Vec::new())) } else { self.receipts_by_tx_range(tx_range).map(Some) - }; + } } } Ok(None) @@ -1815,8 +1815,8 @@ impl StateWriter // Prepare receipts static writer if we are going to write receipts to static files // // We are writing to static files if requested and if there's no receipt pruning configured - let mut receipts_static_writer = (write_receipts_to.static_files() - && !has_receipts_pruning) + let mut receipts_static_writer = (write_receipts_to.static_files() && + !has_receipts_pruning) .then(|| self.static_file_provider.get_writer(first_block, StaticFileSegment::Receipts)) .transpose()?; @@ -1845,13 +1845,12 @@ impl StateWriter } // Skip writing receipts if pruning configuration requires us to. - if prunable_receipts - && self - .prune_modes + if prunable_receipts && + self.prune_modes .receipts .is_some_and(|mode| mode.should_prune(block_number, tip)) { - continue; + continue } // If there are new addresses to retain after this block number, track them @@ -1863,11 +1862,11 @@ impl StateWriter let receipt_idx = first_tx_index + idx as u64; // Skip writing receipt if log filter is active and it does not have any logs to // retain - if prunable_receipts - && has_contract_log_filter - && !receipt.logs().iter().any(|log| allowed_addresses.contains(&log.address)) + if prunable_receipts && + has_contract_log_filter && + !receipt.logs().iter().any(|log| allowed_addresses.contains(&log.address)) { - continue; + continue } if let Some(writer) = &mut receipts_static_writer { @@ -2175,7 +2174,7 @@ impl StateWriter let range = block + 1..=self.last_block_number()?; if range.is_empty() { - return Ok(ExecutionOutcome::default()); + return Ok(ExecutionOutcome::default()) } let start_block_number = *range.start(); @@ -2293,7 +2292,7 @@ impl TrieWriter for DatabaseProvider /// Writes trie updates. Returns the number of entries modified. fn write_trie_updates(&self, trie_updates: &TrieUpdates) -> ProviderResult { if trie_updates.is_empty() { - return Ok(0); + return Ok(0) } // Track the number of inserted entries. @@ -2367,7 +2366,7 @@ impl StorageTrieWriter for DatabaseP updates: &StorageTrieUpdates, ) -> ProviderResult { if updates.is_empty() { - return Ok(0); + return Ok(0) } let cursor = self.tx_ref().cursor_dup_write::()?; @@ -2589,7 +2588,7 @@ impl HashingWriter for DatabaseProvi root: GotExpected { got: state_root, expected: expected_state_root }, block_number: *range.end(), block_hash: end_block_hash, - }))); + }))) } self.write_trie_updates(&trie_updates)?; } @@ -2675,8 +2674,8 @@ impl HistoryWriter for DatabaseProvi StorageShardedKey::last(address, storage_key), rem_index, |storage_sharded_key| { - storage_sharded_key.address == address - && storage_sharded_key.sharded_key.key == storage_key + storage_sharded_key.address == address && + storage_sharded_key.sharded_key.key == storage_key }, )?; @@ -3049,7 +3048,7 @@ impl BlockWrite ) -> ProviderResult<()> { if blocks.is_empty() { debug!(target: "providers::db", "Attempted to append empty block range"); - return Ok(()); + return Ok(()) } let first_number = blocks.first().unwrap().number(); diff --git a/crates/storage/provider/src/providers/state/historical.rs b/crates/storage/provider/src/providers/state/historical.rs index fdd56fb18e..e815f98740 100644 --- a/crates/storage/provider/src/providers/state/historical.rs +++ b/crates/storage/provider/src/providers/state/historical.rs @@ -81,7 +81,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Lookup an account in the `AccountsHistory` table pub fn account_history_lookup(&self, address: Address) -> ProviderResult { if !self.lowest_available_blocks.is_account_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)); + return Err(ProviderError::StateAtBlockPruned(self.block_number)) } // history key to search IntegerList of block number changesets. @@ -100,7 +100,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> storage_key: StorageKey, ) -> ProviderResult { if !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)); + return Err(ProviderError::StateAtBlockPruned(self.block_number)) } // history key to search IntegerList of block number changesets. @@ -121,10 +121,10 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Retrieve revert hashed state for this history provider. fn revert_state(&self) -> ProviderResult { - if !self.lowest_available_blocks.is_account_history_available(self.block_number) - || !self.lowest_available_blocks.is_storage_history_available(self.block_number) + if !self.lowest_available_blocks.is_account_history_available(self.block_number) || + !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)); + return Err(ProviderError::StateAtBlockPruned(self.block_number)) } if self.check_distance_against_limit(EPOCH_SLOTS)? { @@ -143,7 +143,7 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> /// Retrieve revert hashed storage for this history provider and target address. fn revert_storage(&self, address: Address) -> ProviderResult { if !self.lowest_available_blocks.is_storage_history_available(self.block_number) { - return Err(ProviderError::StateAtBlockPruned(self.block_number)); + return Err(ProviderError::StateAtBlockPruned(self.block_number)) } if self.check_distance_against_limit(EPOCH_SLOTS * 10)? { @@ -189,9 +189,9 @@ impl<'b, Provider: DBProvider + BlockNumReader + StateCommitmentProvider> // This check is worth it, the `cursor.prev()` check is rarely triggered (the if will // short-circuit) and when it passes we save a full seek into the changeset/plain state // table. - if rank == 0 - && block_number != Some(self.block_number) - && !cursor.prev()?.is_some_and(|(key, _)| key_filter(&key)) + if rank == 0 && + block_number != Some(self.block_number) && + !cursor.prev()?.is_some_and(|(key, _)| key_filter(&key)) { if let (Some(_), Some(block_number)) = (lowest_available_block_number, block_number) { diff --git a/crates/storage/provider/src/providers/state/latest.rs b/crates/storage/provider/src/providers/state/latest.rs index e83049592a..334e0109dc 100644 --- a/crates/storage/provider/src/providers/state/latest.rs +++ b/crates/storage/provider/src/providers/state/latest.rs @@ -172,7 +172,7 @@ impl StateProv let mut cursor = self.tx().cursor_dup_read::()?; if let Some(entry) = cursor.seek_by_key_subkey(account, storage_key)? { if entry.key == storage_key { - return Ok(Some(entry.value)); + return Ok(Some(entry.value)) } } Ok(None) diff --git a/crates/storage/provider/src/providers/static_file/jar.rs b/crates/storage/provider/src/providers/static_file/jar.rs index 76e730b00b..365e54467a 100644 --- a/crates/storage/provider/src/providers/static_file/jar.rs +++ b/crates/storage/provider/src/providers/static_file/jar.rs @@ -161,7 +161,7 @@ impl> HeaderProvider for StaticFileJarProv { let sealed = SealedHeader::new(header, hash); if !predicate(&sealed) { - break; + break } headers.push(sealed); } @@ -320,7 +320,7 @@ impl ProviderResult> { if let Some(tx_static_file) = &self.auxiliary_jar { if let Some(num) = tx_static_file.transaction_id(hash)? { - return self.receipt(num); + return self.receipt(num) } } Ok(None) diff --git a/crates/storage/provider/src/providers/static_file/manager.rs b/crates/storage/provider/src/providers/static_file/manager.rs index 4d82e4ad8e..dee449c82d 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -158,11 +158,11 @@ impl StaticFileProvider { // We only care about modified data events if !matches!( event.kind, - notify::EventKind::Modify(_) - | notify::EventKind::Create(_) - | notify::EventKind::Remove(_) + notify::EventKind::Modify(_) | + notify::EventKind::Create(_) | + notify::EventKind::Remove(_) ) { - continue; + continue } // We only trigger a re-initialization if a configuration file was @@ -175,7 +175,7 @@ impl StaticFileProvider { .extension() .is_none_or(|s| s.to_str() != Some(CONFIG_FILE_EXTENSION)) { - continue; + continue } // Ensure it's well formatted static file name @@ -184,7 +184,7 @@ impl StaticFileProvider { ) .is_none() { - continue; + continue } // If we can read the metadata and modified timestamp, ensure this is @@ -195,7 +195,7 @@ impl StaticFileProvider { if last_event_timestamp.is_some_and(|last_timestamp| { last_timestamp >= current_modified_timestamp }) { - continue; + continue } last_event_timestamp = Some(current_modified_timestamp); } @@ -204,7 +204,7 @@ impl StaticFileProvider { if let Err(err) = provider.initialize_index() { warn!(target: "providers::static_file", "failed to re-initialize index: {err}"); } - break; + break } } @@ -419,7 +419,7 @@ impl StaticFileProvider { ) .and_then(|(parsed_segment, block_range)| { if parsed_segment == segment { - return Some(block_range); + return Some(block_range) } None }), @@ -428,7 +428,7 @@ impl StaticFileProvider { // Return cached `LoadedJar` or insert it for the first time, and then, return it. if let Some(block_range) = block_range { - return Ok(Some(self.get_or_create_jar_provider(segment, &block_range)?)); + return Ok(Some(self.get_or_create_jar_provider(segment, &block_range)?)) } Ok(None) @@ -455,18 +455,18 @@ impl StaticFileProvider { pub fn delete_transactions_below(&self, block: BlockNumber) -> ProviderResult<()> { // Nothing to delete if block is 0. if block == 0 { - return Ok(()); + return Ok(()) } loop { let Some(block_height) = self.get_lowest_static_file_block(StaticFileSegment::Transactions) else { - return Ok(()); + return Ok(()) }; if block_height >= block { - return Ok(()); + return Ok(()) } debug!( @@ -573,11 +573,11 @@ impl StaticFileProvider { while let Some((tx_end, block_range)) = static_files_rev_iter.next() { if tx > *tx_end { // request tx is higher than highest static file tx - return None; + return None } let tx_start = static_files_rev_iter.peek().map(|(tx_end, _)| *tx_end + 1).unwrap_or(0); if tx_start <= tx { - return Some(self.find_fixed_range(block_range.end())); + return Some(self.find_fixed_range(block_range.end())) } } None @@ -750,8 +750,8 @@ impl StaticFileProvider { // // If we detect an OVM import was done (block #1 ), skip it. // More on [#11099](https://github.com/paradigmxyz/reth/pull/11099). - if provider.chain_spec().is_optimism() - && reth_chainspec::Chain::optimism_mainnet() == provider.chain_spec().chain_id() + if provider.chain_spec().is_optimism() && + reth_chainspec::Chain::optimism_mainnet() == provider.chain_spec().chain_id() { // check whether we have the first OVM block: const OVM_HEADER_1_HASH: B256 = @@ -760,7 +760,7 @@ impl StaticFileProvider { info!(target: "reth::cli", "Skipping storage verification for OP mainnet, expected inconsistency in OVM chain" ); - return Ok(None); + return Ok(None) } } @@ -778,12 +778,12 @@ impl StaticFileProvider { for segment in StaticFileSegment::iter() { // Not integrated yet if segment.is_block_meta() { - continue; + continue } if has_receipt_pruning && segment.is_receipts() { // Pruned nodes (including full node) do not store receipts as static files. - continue; + continue } let initial_highest_block = self.get_highest_static_file_block(segment); @@ -830,16 +830,16 @@ impl StaticFileProvider { loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= highest_tx { - break; + break } } else { // If the block body indices can not be found, then it means that static // files is ahead of database, and the `ensure_invariants` check will fix // it by comparing with stage checkpoints. - break; + break } if last_block == 0 { - break; + break } last_block -= 1; @@ -948,7 +948,7 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_block)); + return Ok(Some(highest_block)) } } @@ -956,7 +956,7 @@ impl StaticFileProvider { if highest_static_file_entry .is_none_or(|highest_entry| db_last_entry > highest_entry) { - return Ok(None); + return Ok(None) } } } @@ -984,7 +984,7 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_static_file_block)); + return Ok(Some(highest_static_file_block)) } // If the checkpoint is behind, then we failed to do a database commit **but committed** to @@ -1085,7 +1085,7 @@ impl StaticFileProvider { let mut range = self.find_fixed_range(highest_block); while range.end() > 0 { if let Some(res) = func(self.get_or_create_jar_provider(segment, &range)?)? { - return Ok(Some(res)); + return Ok(Some(res)) } range = SegmentRangeInclusive::new( range.start().saturating_sub(self.blocks_per_file), @@ -1137,10 +1137,10 @@ impl StaticFileProvider { match get_fn(&mut cursor, number)? { Some(res) => { if !predicate(&res) { - break 'outer; + break 'outer } result.push(res); - break 'inner; + break 'inner } None => { if retrying { @@ -1156,7 +1156,7 @@ impl StaticFileProvider { } else { ProviderError::MissingStaticFileTx(segment, number) }; - return Err(err); + return Err(err) } // There is a very small chance of hitting a deadlock if two consecutive // static files share the same bucket in the @@ -1249,7 +1249,7 @@ impl StaticFileProvider { if static_file_upper_bound .is_some_and(|static_file_upper_bound| static_file_upper_bound >= number) { - return fetch_from_static_file(self); + return fetch_from_static_file(self) } fetch_from_database() } @@ -1351,7 +1351,7 @@ impl StaticFileWriter for StaticFileProvider { segment: StaticFileSegment, ) -> ProviderResult> { if self.access.is_read_only() { - return Err(ProviderError::ReadOnlyStaticFileAccess); + return Err(ProviderError::ReadOnlyStaticFileAccess) } trace!(target: "provider::static_file", ?block, ?segment, "Getting static file writer."); @@ -1382,7 +1382,7 @@ impl> HeaderProvider for StaticFileProvide .get_two::>(block_hash.into())? .and_then(|(header, hash)| { if &hash == block_hash { - return Some(header); + return Some(header) } None })) @@ -1505,7 +1505,7 @@ impl> Rec fn receipt_by_hash(&self, hash: TxHash) -> ProviderResult> { if let Some(num) = self.transaction_id(hash)? { - return self.receipt(num); + return self.receipt(num) } Ok(None) } @@ -1835,9 +1835,9 @@ impl BlockBodyIndicesProvider for StaticFileProvider { impl StatsReader for StaticFileProvider { fn count_entries(&self) -> ProviderResult { match T::NAME { - tables::CanonicalHeaders::NAME - | tables::Headers::

::NAME - | tables::HeaderTerminalDifficulties::NAME => Ok(self + tables::CanonicalHeaders::NAME | + tables::Headers::
::NAME | + tables::HeaderTerminalDifficulties::NAME => Ok(self .get_highest_static_file_block(StaticFileSegment::Headers) .map(|block| block + 1) .unwrap_or_default() diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index bb62a409a8..3fd2828faa 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -381,7 +381,7 @@ impl StaticFileProviderRW { self.writer.user_header().segment(), expected_block_number, next_static_file_block, - )); + )) } Ok(()) } @@ -413,15 +413,15 @@ impl StaticFileProviderRW { // * it's a tx-based segment AND `last_block` is lower than the first block of this // file's block range. Otherwise, having no rows simply means that this block // range has no transactions, but the file should remain. - if block_start != 0 - && (segment.is_headers() || last_block.is_some_and(|b| b < block_start)) + if block_start != 0 && + (segment.is_headers() || last_block.is_some_and(|b| b < block_start)) { self.delete_current_and_open_previous()?; } else { // Update `SegmentHeader` self.writer.user_header_mut().prune(len); self.writer.prune_rows(len as usize).map_err(ProviderError::other)?; - break; + break } remaining_rows -= len; @@ -501,7 +501,7 @@ impl StaticFileProviderRW { self.writer.user_header().segment(), tx_num, next_tx, - )); + )) } self.writer.user_header_mut().increment_tx(); } else { diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index d6be27b1c4..2d0cfb665d 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -418,7 +418,7 @@ impl TransactionsProvider excess_blob_gas: block.header.excess_blob_gas, timestamp: block.header.timestamp, }; - return Ok(Some((tx.clone(), meta))); + return Ok(Some((tx.clone(), meta))) } } } @@ -430,7 +430,7 @@ impl TransactionsProvider let mut current_tx_number: TxNumber = 0; for block in lock.values() { if current_tx_number + (block.body.transactions.len() as TxNumber) > id { - return Ok(Some(block.header.number)); + return Ok(Some(block.header.number)) } current_tx_number += block.body.transactions.len() as TxNumber; } diff --git a/crates/storage/provider/src/writer/mod.rs b/crates/storage/provider/src/writer/mod.rs index d54dc845f5..cbdb773c20 100644 --- a/crates/storage/provider/src/writer/mod.rs +++ b/crates/storage/provider/src/writer/mod.rs @@ -74,7 +74,7 @@ impl<'a, ProviderDB, ProviderSF> UnifiedStorageWriter<'a, ProviderDB, ProviderSF #[expect(unused)] const fn ensure_static_file(&self) -> Result<(), UnifiedStorageWriterError> { if self.static_file.is_none() { - return Err(UnifiedStorageWriterError::MissingStaticFileWriter); + return Err(UnifiedStorageWriterError::MissingStaticFileWriter) } Ok(()) } @@ -139,7 +139,7 @@ where { if blocks.is_empty() { debug!(target: "provider::storage_writer", "Attempted to write empty block range"); - return Ok(()); + return Ok(()) } // NOTE: checked non-empty above diff --git a/crates/storage/storage-api/src/receipts.rs b/crates/storage/storage-api/src/receipts.rs index 3c883ae8da..f8390ee538 100644 --- a/crates/storage/storage-api/src/receipts.rs +++ b/crates/storage/storage-api/src/receipts.rs @@ -73,7 +73,7 @@ pub trait ReceiptProviderIdExt: ReceiptProvider + BlockIdReader { if let Some(num) = self.convert_block_number(num_tag)? { BlockHashOrNumber::Number(num) } else { - return Ok(None); + return Ok(None) } } }; diff --git a/crates/storage/storage-api/src/state.rs b/crates/storage/storage-api/src/state.rs index f0e7ef696c..5581248d3e 100644 --- a/crates/storage/storage-api/src/state.rs +++ b/crates/storage/storage-api/src/state.rs @@ -62,10 +62,10 @@ pub trait StateProvider: if let Some(code_hash) = acc.bytecode_hash { if code_hash == KECCAK_EMPTY { - return Ok(None); + return Ok(None) } // Get the code from the code hash - return self.bytecode_by_hash(&code_hash); + return self.bytecode_by_hash(&code_hash) } // Return `None` if no code hash is set diff --git a/crates/storage/zstd-compressors/src/lib.rs b/crates/storage/zstd-compressors/src/lib.rs index 3c6205ccc5..d7f2b65904 100644 --- a/crates/storage/zstd-compressors/src/lib.rs +++ b/crates/storage/zstd-compressors/src/lib.rs @@ -120,7 +120,7 @@ impl ReusableDecompressor { reserved_upper_bound = true; if let Some(upper_bound) = Decompressor::upper_bound(src) { if let Some(additional) = upper_bound.checked_sub(self.buf.capacity()) { - break 'b additional; + break 'b additional } } } diff --git a/crates/tasks/src/lib.rs b/crates/tasks/src/lib.rs index 7de4a5793c..5f72037f7b 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -245,7 +245,7 @@ impl TaskManager { while self.graceful_tasks.load(Ordering::Relaxed) > 0 { if when.map(|when| std::time::Instant::now() > when).unwrap_or(false) { debug!("graceful shutdown timed out"); - return false; + return false } std::hint::spin_loop(); } diff --git a/crates/tokio-util/src/ratelimit.rs b/crates/tokio-util/src/ratelimit.rs index 93acd6fd5d..33a9c5273d 100644 --- a/crates/tokio-util/src/ratelimit.rs +++ b/crates/tokio-util/src/ratelimit.rs @@ -38,7 +38,7 @@ impl RateLimit { State::Ready { .. } => return Poll::Ready(()), State::Limited => { if Pin::new(&mut self.sleep).poll(cx).is_pending() { - return Poll::Pending; + return Poll::Pending } } } diff --git a/crates/transaction-pool/src/blobstore/disk.rs b/crates/transaction-pool/src/blobstore/disk.rs index bd420a4055..e738bfc668 100644 --- a/crates/transaction-pool/src/blobstore/disk.rs +++ b/crates/transaction-pool/src/blobstore/disk.rs @@ -62,7 +62,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec<(B256, BlobTransactionSidecarVariant)>, ) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()); + return Ok(()) } self.inner.insert_many(txs) } @@ -118,7 +118,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec, ) -> Result)>, BlobStoreError> { if txs.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } self.inner.get_all(txs) } @@ -128,7 +128,7 @@ impl BlobStore for DiskFileBlobStore { txs: Vec, ) -> Result>, BlobStoreError> { if txs.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } self.inner.get_exact(txs) } @@ -213,7 +213,7 @@ impl BlobStore for DiskFileBlobStore { // return early if all blobs are found. if result.iter().all(|blob| blob.is_some()) { // got all blobs, can return early - return Ok(Some(result.into_iter().map(Option::unwrap).collect())); + return Ok(Some(result.into_iter().map(Option::unwrap).collect())) } } @@ -393,7 +393,7 @@ impl DiskFileBlobStoreInner { /// Returns true if the blob for the given transaction hash is in the blob cache or on disk. fn contains(&self, tx: B256) -> Result { if self.blob_cache.lock().get(&tx).is_some() { - return Ok(true); + return Ok(true) } // we only check if the file exists and assume it's valid Ok(self.blob_disk_file(tx).is_file()) @@ -422,14 +422,14 @@ impl DiskFileBlobStoreInner { tx: B256, ) -> Result>, BlobStoreError> { if let Some(blob) = self.blob_cache.lock().get(&tx) { - return Ok(Some(blob.clone())); + return Ok(Some(blob.clone())) } let blob = self.read_one(tx)?; if let Some(blob) = &blob { let blob_arc = Arc::new(blob.clone()); self.blob_cache.lock().insert(tx, blob_arc.clone()); - return Ok(Some(blob_arc)); + return Ok(Some(blob_arc)) } Ok(None) @@ -536,11 +536,11 @@ impl DiskFileBlobStoreInner { } } if cache_miss.is_empty() { - return Ok(res); + return Ok(res) } let from_disk = self.read_many_decoded(cache_miss); if from_disk.is_empty() { - return Ok(res); + return Ok(res) } let mut cache = self.blob_cache.lock(); for (tx, data) in from_disk { diff --git a/crates/transaction-pool/src/blobstore/mem.rs b/crates/transaction-pool/src/blobstore/mem.rs index 881ba1f807..44dff1cceb 100644 --- a/crates/transaction-pool/src/blobstore/mem.rs +++ b/crates/transaction-pool/src/blobstore/mem.rs @@ -39,7 +39,7 @@ impl BlobStore for InMemoryBlobStore { txs: Vec<(B256, BlobTransactionSidecarVariant)>, ) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()); + return Ok(()) } let mut store = self.inner.store.write(); let mut total_add = 0; @@ -62,7 +62,7 @@ impl BlobStore for InMemoryBlobStore { fn delete_all(&self, txs: Vec) -> Result<(), BlobStoreError> { if txs.is_empty() { - return Ok(()); + return Ok(()) } let mut store = self.inner.store.write(); let mut total_sub = 0; diff --git a/crates/transaction-pool/src/blobstore/mod.rs b/crates/transaction-pool/src/blobstore/mod.rs index e78f29a627..29844994bc 100644 --- a/crates/transaction-pool/src/blobstore/mod.rs +++ b/crates/transaction-pool/src/blobstore/mod.rs @@ -169,8 +169,8 @@ impl BlobStoreSize { impl PartialEq for BlobStoreSize { fn eq(&self, other: &Self) -> bool { - self.data_size.load(Ordering::Relaxed) == other.data_size.load(Ordering::Relaxed) - && self.num_blobs.load(Ordering::Relaxed) == other.num_blobs.load(Ordering::Relaxed) + self.data_size.load(Ordering::Relaxed) == other.data_size.load(Ordering::Relaxed) && + self.num_blobs.load(Ordering::Relaxed) == other.num_blobs.load(Ordering::Relaxed) } } diff --git a/crates/transaction-pool/src/blobstore/noop.rs b/crates/transaction-pool/src/blobstore/noop.rs index b0a9020146..bb03253ee6 100644 --- a/crates/transaction-pool/src/blobstore/noop.rs +++ b/crates/transaction-pool/src/blobstore/noop.rs @@ -59,7 +59,7 @@ impl BlobStore for NoopBlobStore { txs: Vec, ) -> Result>, BlobStoreError> { if txs.is_empty() { - return Ok(vec![]); + return Ok(vec![]) } Err(BlobStoreError::MissingSidecar(txs[0])) } diff --git a/crates/transaction-pool/src/blobstore/tracker.rs b/crates/transaction-pool/src/blobstore/tracker.rs index 605f7853f3..6789086abe 100644 --- a/crates/transaction-pool/src/blobstore/tracker.rs +++ b/crates/transaction-pool/src/blobstore/tracker.rs @@ -65,7 +65,7 @@ impl BlobStoreCanonTracker { if *entry.key() <= finalized_block { finalized.extend(entry.remove_entry().1); } else { - break; + break } } diff --git a/crates/transaction-pool/src/config.rs b/crates/transaction-pool/src/config.rs index 557edb86c1..5263cd1834 100644 --- a/crates/transaction-pool/src/config.rs +++ b/crates/transaction-pool/src/config.rs @@ -69,10 +69,10 @@ impl PoolConfig { /// Returns whether the size and amount constraints in any sub-pools are exceeded. #[inline] pub const fn is_exceeded(&self, pool_size: PoolSize) -> bool { - self.blob_limit.is_exceeded(pool_size.blob, pool_size.blob_size) - || self.pending_limit.is_exceeded(pool_size.pending, pool_size.pending_size) - || self.basefee_limit.is_exceeded(pool_size.basefee, pool_size.basefee_size) - || self.queued_limit.is_exceeded(pool_size.queued, pool_size.queued_size) + self.blob_limit.is_exceeded(pool_size.blob, pool_size.blob_size) || + self.pending_limit.is_exceeded(pool_size.pending, pool_size.pending_size) || + self.basefee_limit.is_exceeded(pool_size.basefee, pool_size.basefee_size) || + self.queued_limit.is_exceeded(pool_size.queued, pool_size.queued_size) } } @@ -152,7 +152,7 @@ impl PriceBumpConfig { #[inline] pub const fn price_bump(&self, tx_type: u8) -> u128 { if tx_type == EIP4844_TX_TYPE_ID { - return self.replace_blob_tx_price_bump; + return self.replace_blob_tx_price_bump } self.default_price_bump } @@ -213,7 +213,7 @@ impl LocalTransactionConfig { #[inline] pub fn is_local(&self, origin: TransactionOrigin, sender: &Address) -> bool { if self.no_local_exemptions() { - return false; + return false } origin.is_local() || self.contains_local_address(sender) } diff --git a/crates/transaction-pool/src/error.rs b/crates/transaction-pool/src/error.rs index de5b1fdb75..686c9456d3 100644 --- a/crates/transaction-pool/src/error.rs +++ b/crates/transaction-pool/src/error.rs @@ -289,14 +289,14 @@ impl InvalidPoolTransactionError { // depend on dynamic environmental conditions and should not be assumed to have been // intentionally caused by the sender match err { - InvalidTransactionError::InsufficientFunds { .. } - | InvalidTransactionError::NonceNotConsistent { .. } => { + InvalidTransactionError::InsufficientFunds { .. } | + InvalidTransactionError::NonceNotConsistent { .. } => { // transaction could just have arrived late/early false } - InvalidTransactionError::GasTooLow - | InvalidTransactionError::GasTooHigh - | InvalidTransactionError::TipAboveFeeCap => { + InvalidTransactionError::GasTooLow | + InvalidTransactionError::GasTooHigh | + InvalidTransactionError::TipAboveFeeCap => { // these are technically not invalid false } @@ -304,19 +304,19 @@ impl InvalidPoolTransactionError { // dynamic, but not used during validation false } - InvalidTransactionError::Eip2930Disabled - | InvalidTransactionError::Eip1559Disabled - | InvalidTransactionError::Eip4844Disabled - | InvalidTransactionError::Eip7702Disabled => { + InvalidTransactionError::Eip2930Disabled | + InvalidTransactionError::Eip1559Disabled | + InvalidTransactionError::Eip4844Disabled | + InvalidTransactionError::Eip7702Disabled => { // settings false } - InvalidTransactionError::OldLegacyChainId - | InvalidTransactionError::ChainIdMismatch - | InvalidTransactionError::GasUintOverflow - | InvalidTransactionError::TxTypeNotSupported - | InvalidTransactionError::SignerAccountHasBytecode - | InvalidTransactionError::GasLimitTooHigh => true, + InvalidTransactionError::OldLegacyChainId | + InvalidTransactionError::ChainIdMismatch | + InvalidTransactionError::GasUintOverflow | + InvalidTransactionError::TxTypeNotSupported | + InvalidTransactionError::SignerAccountHasBytecode | + InvalidTransactionError::GasLimitTooHigh => true, } } Self::ExceedsGasLimit(_, _) => true, @@ -355,8 +355,8 @@ impl InvalidPoolTransactionError { // this is a malformed transaction and should not be sent over the network true } - Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka - | Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka => { + Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka | + Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka => { // for now we do not want to penalize peers for broadcasting different // sidecars false @@ -379,8 +379,8 @@ impl InvalidPoolTransactionError { /// Returns `true` if an import failed due to nonce gap. pub const fn is_nonce_gap(&self) -> bool { - matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent { .. })) - || matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap)) + matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent { .. })) || + matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap)) } /// Returns the arbitrary error if it is [`InvalidPoolTransactionError::Other`] diff --git a/crates/transaction-pool/src/lib.rs b/crates/transaction-pool/src/lib.rs index c185802b8d..3d77651055 100644 --- a/crates/transaction-pool/src/lib.rs +++ b/crates/transaction-pool/src/lib.rs @@ -499,7 +499,7 @@ where transactions: Vec, ) -> Vec> { if transactions.is_empty() { - return Vec::new(); + return Vec::new() } let validated = self.validate_all(origin, transactions).await; diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index c0e81d4d4c..b076255f1f 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -315,8 +315,8 @@ pub async fn maintain_transaction_pool( let old_first = old_blocks.first(); // check if the reorg is not canonical with the pool's block - if !(old_first.parent_hash() == pool_info.last_seen_block_hash - || new_first.parent_hash() == pool_info.last_seen_block_hash) + if !(old_first.parent_hash() == pool_info.last_seen_block_hash || + new_first.parent_hash() == pool_info.last_seen_block_hash) { // the new block points to a higher block than the oldest block in the old chain maintained_state = MaintainedPoolState::Drifted; @@ -462,7 +462,7 @@ pub async fn maintain_transaction_pool( // keep track of mined blob transactions blob_store_tracker.add_new_chain_blocks(&blocks); - continue; + continue } let mut changed_accounts = Vec::with_capacity(state.state().len()); @@ -612,14 +612,14 @@ where P: TransactionPool>, { if !file_path.exists() { - return Ok(()); + return Ok(()) } debug!(target: "txpool", txs_file =?file_path, "Check local persistent storage for saved transactions"); let data = reth_fs_util::read(file_path)?; if data.is_empty() { - return Ok(()); + return Ok(()) } let txs_signed: Vec<::Consensus> = @@ -648,7 +648,7 @@ where let local_transactions = pool.get_local_transactions(); if local_transactions.is_empty() { trace!(target: "txpool", "no local transactions to save"); - return; + return } let local_transactions = local_transactions @@ -697,7 +697,7 @@ pub async fn backup_local_transactions_task

( { let Some(transactions_path) = config.transactions_path else { // nothing to do - return; + return }; if let Err(err) = load_and_reinsert_transactions(pool.clone(), &transactions_path).await { diff --git a/crates/transaction-pool/src/noop.rs b/crates/transaction-pool/src/noop.rs index 9a58760bfb..132854bb71 100644 --- a/crates/transaction-pool/src/noop.rs +++ b/crates/transaction-pool/src/noop.rs @@ -319,7 +319,7 @@ impl TransactionPool for NoopTransactionPool { tx_hashes: Vec, ) -> Result>, BlobStoreError> { if tx_hashes.is_empty() { - return Ok(vec![]); + return Ok(vec![]) } Err(BlobStoreError::MissingSidecar(tx_hashes[0])) } diff --git a/crates/transaction-pool/src/pool/best.rs b/crates/transaction-pool/src/pool/best.rs index 49aa9853ad..eba3c2c35d 100644 --- a/crates/transaction-pool/src/pool/best.rs +++ b/crates/transaction-pool/src/pool/best.rs @@ -55,9 +55,8 @@ impl Iterator for BestTransactionsWithFees { let best = Iterator::next(&mut self.best)?; // If both the base fee and blob fee (if applicable for EIP-4844) are satisfied, return // the transaction - if best.transaction.max_fee_per_gas() >= self.base_fee as u128 - && best - .transaction + if best.transaction.max_fee_per_gas() >= self.base_fee as u128 && + best.transaction .max_fee_per_blob_gas() .is_none_or(|fee| fee >= self.base_fee_per_blob_gas as u128) { @@ -198,7 +197,7 @@ impl Iterator for BestTransactions { "[{:?}] skipping invalid transaction", best.transaction.hash() ); - continue; + continue } // Insert transactions that just got unlocked. @@ -216,7 +215,7 @@ impl Iterator for BestTransactions { ), ) } else { - return Some(best.transaction); + return Some(best.transaction) } } } @@ -250,7 +249,7 @@ where loop { let best = self.best.next()?; if (self.predicate)(&best) { - return Some(best); + return Some(best) } self.best.mark_invalid( &best, @@ -330,12 +329,12 @@ where // If we have space, try prioritizing transactions if self.prioritized_gas < self.max_prioritized_gas { for item in &mut self.inner { - if self.prioritized_senders.contains(&item.transaction.sender()) - && self.prioritized_gas + item.transaction.gas_limit() - <= self.max_prioritized_gas + if self.prioritized_senders.contains(&item.transaction.sender()) && + self.prioritized_gas + item.transaction.gas_limit() <= + self.max_prioritized_gas { self.prioritized_gas += item.transaction.gas_limit(); - return Some(item); + return Some(item) } self.buffer.push_back(item); } diff --git a/crates/transaction-pool/src/pool/blob.rs b/crates/transaction-pool/src/pool/blob.rs index 5af39c8ee1..b083c62816 100644 --- a/crates/transaction-pool/src/pool/blob.rs +++ b/crates/transaction-pool/src/pool/blob.rs @@ -97,16 +97,16 @@ impl BlobTransactions { let mut iter = self.by_id.iter().peekable(); while let Some((id, tx)) = iter.next() { - if tx.transaction.max_fee_per_blob_gas().unwrap_or_default() - < blob_fee_to_satisfy - || tx.transaction.max_fee_per_gas() - < best_transactions_attributes.basefee as u128 + if tx.transaction.max_fee_per_blob_gas().unwrap_or_default() < + blob_fee_to_satisfy || + tx.transaction.max_fee_per_gas() < + best_transactions_attributes.basefee as u128 { // does not satisfy the blob fee or base fee // still parked in blob pool -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this; + break 'this } iter.next(); } @@ -150,13 +150,13 @@ impl BlobTransactions { let mut iter = self.by_id.iter().peekable(); while let Some((id, tx)) = iter.next() { - if tx.transaction.max_fee_per_blob_gas() < Some(pending_fees.blob_fee) - || tx.transaction.max_fee_per_gas() < pending_fees.base_fee as u128 + if tx.transaction.max_fee_per_blob_gas() < Some(pending_fees.blob_fee) || + tx.transaction.max_fee_per_gas() < pending_fees.base_fee as u128 { // still parked in blob pool -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this; + break 'this } iter.next(); } @@ -347,7 +347,7 @@ const LOG_2_1_125: f64 = 0.16992500144231237; pub fn fee_delta(max_tx_fee: u128, current_fee: u128) -> i64 { if max_tx_fee == current_fee { // if these are equal, then there's no fee jump - return 0; + return 0 } let max_tx_fee_jumps = if max_tx_fee == 0 { diff --git a/crates/transaction-pool/src/pool/mod.rs b/crates/transaction-pool/src/pool/mod.rs index 32eefdfd4d..bf96431f78 100644 --- a/crates/transaction-pool/src/pool/mod.rs +++ b/crates/transaction-pool/src/pool/mod.rs @@ -363,7 +363,7 @@ where elements.push(pooled.into_inner()); if limit.exceeds(size) { - break; + break } } @@ -602,7 +602,7 @@ where if listener.kind.is_propagate_only() && !propagate_allowed { // only emit this hash to listeners that are only allowed to receive propagate only // transactions, such as network - return !listener.sender.is_closed(); + return !listener.sender.is_closed() } // broadcast all pending transactions to the listener @@ -617,7 +617,7 @@ where if listener.kind.is_propagate_only() && !event.transaction.propagate { // only emit this hash to listeners that are only allowed to receive propagate only // transactions, such as network - return !listener.sender.is_closed(); + return !listener.sender.is_closed() } listener.send(event.clone()) @@ -628,7 +628,7 @@ where fn on_new_blob_sidecar(&self, tx_hash: &TxHash, sidecar: &BlobTransactionSidecarVariant) { let mut sidecar_listeners = self.blob_transaction_sidecar_listener.lock(); if sidecar_listeners.is_empty() { - return; + return } let sidecar = Arc::new(sidecar.clone()); sidecar_listeners.retain_mut(|listener| { @@ -758,7 +758,7 @@ where hashes: Vec, ) -> Vec>> { if hashes.is_empty() { - return Vec::new(); + return Vec::new() } let removed = self.pool.write().remove_transactions(hashes); @@ -778,7 +778,7 @@ where hashes: Vec, ) -> Vec>> { if hashes.is_empty() { - return Vec::new(); + return Vec::new() } let removed = self.pool.write().remove_transactions_and_descendants(hashes); @@ -814,7 +814,7 @@ where A: HandleMempoolData, { if announcement.is_empty() { - return; + return } let pool = self.get_pool_data(); announcement.retain_by_hash(|tx| !pool.contains(tx)) @@ -915,7 +915,7 @@ where /// If no transaction exists, it is skipped. pub fn get_all(&self, txs: Vec) -> Vec>> { if txs.is_empty() { - return Vec::new(); + return Vec::new() } self.get_pool_data().get_all(txs).collect() } @@ -923,7 +923,7 @@ where /// Notify about propagated transactions. pub fn on_propagated(&self, txs: PropagatedTransactions) { if txs.0.is_empty() { - return; + return } let mut listener = self.event_listener.write(); @@ -1049,9 +1049,9 @@ where loop { let next = self.iter.next()?; if self.kind.is_propagate_only() && !next.propagate { - continue; + continue } - return Some(*next.hash()); + return Some(*next.hash()) } } } @@ -1073,12 +1073,12 @@ where loop { let next = self.iter.next()?; if self.kind.is_propagate_only() && !next.propagate { - continue; + continue } return Some(NewTransactionEvent { subpool: SubPool::Pending, transaction: next.clone(), - }); + }) } } } diff --git a/crates/transaction-pool/src/pool/parked.rs b/crates/transaction-pool/src/pool/parked.rs index 6ff9d293d4..33056dd6ec 100644 --- a/crates/transaction-pool/src/pool/parked.rs +++ b/crates/transaction-pool/src/pool/parked.rs @@ -111,7 +111,7 @@ impl ParkedPool { if value.count == 0 { entry.remove() } else { - return; + return } } Entry::Vacant(_) => { @@ -190,7 +190,7 @@ impl ParkedPool { ) -> Vec>> { if !self.exceeds(&limit) { // if we are below the limits, we don't need to drop anything - return Vec::new(); + return Vec::new() } let mut removed = Vec::new(); @@ -208,7 +208,7 @@ impl ParkedPool { } if !self.exceeds(&limit) { - break; + break } } } @@ -294,7 +294,7 @@ impl ParkedPool> { // still parked -> skip descendant transactions 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this; + break 'this } iter.next(); } diff --git a/crates/transaction-pool/src/pool/pending.rs b/crates/transaction-pool/src/pool/pending.rs index c03f981d49..d3e65f711f 100644 --- a/crates/transaction-pool/src/pool/pending.rs +++ b/crates/transaction-pool/src/pool/pending.rs @@ -189,7 +189,7 @@ impl PendingPool { // Remove all dependent transactions. 'this: while let Some((next_id, next_tx)) = transactions_iter.peek() { if next_id.sender != id.sender { - break 'this; + break 'this } removed.push(Arc::clone(&next_tx.transaction)); transactions_iter.next(); @@ -231,7 +231,7 @@ impl PendingPool { // Remove all dependent transactions. 'this: while let Some((next_id, next_tx)) = transactions_iter.peek() { if next_id.sender != id.sender { - break 'this; + break 'this } removed.push(Arc::clone(&next_tx.transaction)); transactions_iter.next(); @@ -419,8 +419,8 @@ impl PendingPool { // loop through the highest nonces set, removing transactions until we reach the limit for tx in worst_transactions { // return early if the pool is under limits - if !limit.is_exceeded(original_length - total_removed, original_size - total_size) - || non_local_senders == 0 + if !limit.is_exceeded(original_length - total_removed, original_size - total_size) || + non_local_senders == 0 { // need to remove remaining transactions before exiting for id in &removed { @@ -429,7 +429,7 @@ impl PendingPool { } } - return; + return } if !remove_locals && tx.transaction.is_local() { @@ -437,7 +437,7 @@ impl PendingPool { if local_senders.insert(sender_id) { non_local_senders -= 1; } - continue; + continue } total_size += tx.transaction.size(); @@ -455,7 +455,7 @@ impl PendingPool { // return if either the pool is under limits or there are no more _eligible_ // transactions to remove if !self.exceeds(limit) || non_local_senders == 0 { - return; + return } } } @@ -477,13 +477,13 @@ impl PendingPool { let mut removed = Vec::new(); // return early if the pool is already under the limits if !self.exceeds(&limit) { - return removed; + return removed } // first truncate only non-local transactions, returning if the pool end up under the limit self.remove_to_limit(&limit, false, &mut removed); if !self.exceeds(&limit) { - return removed; + return removed } // now repeat for local transactions, since local transactions must be removed now for the diff --git a/crates/transaction-pool/src/pool/state.rs b/crates/transaction-pool/src/pool/state.rs index 691c426127..e04b463343 100644 --- a/crates/transaction-pool/src/pool/state.rs +++ b/crates/transaction-pool/src/pool/state.rs @@ -160,10 +160,10 @@ mod tests { let state = TxState::default(); assert_eq!(SubPool::Queued, state.into()); - let state = TxState::NO_PARKED_ANCESTORS - | TxState::NO_NONCE_GAPS - | TxState::NOT_TOO_MUCH_GAS - | TxState::ENOUGH_FEE_CAP_BLOCK; + let state = TxState::NO_PARKED_ANCESTORS | + TxState::NO_NONCE_GAPS | + TxState::NOT_TOO_MUCH_GAS | + TxState::ENOUGH_FEE_CAP_BLOCK; assert_eq!(SubPool::Queued, state.into()); } diff --git a/crates/transaction-pool/src/pool/txpool.rs b/crates/transaction-pool/src/pool/txpool.rs index 1eef79bfa3..66ba5368f0 100644 --- a/crates/transaction-pool/src/pool/txpool.rs +++ b/crates/transaction-pool/src/pool/txpool.rs @@ -175,7 +175,7 @@ impl TxPool { let mut next_expected_nonce = on_chain.nonce; for (id, tx) in self.all().descendant_txs_inclusive(&on_chain) { if next_expected_nonce != id.nonce { - break; + break } next_expected_nonce = id.next_nonce(); last_consecutive_tx = Some(tx); @@ -652,7 +652,7 @@ impl TxPool { on_chain_code_hash: Option, ) -> PoolResult> { if self.contains(tx.hash()) { - return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported)); + return Err(PoolError::new(*tx.hash(), PoolErrorKind::AlreadyImported)) } self.validate_auth(&tx, on_chain_nonce, on_chain_code_hash)?; @@ -758,10 +758,10 @@ impl TxPool { on_chain_code_hash: Option, ) -> Result<(), PoolError> { // Short circuit if the sender has neither delegation nor pending delegation. - if (on_chain_code_hash.is_none() || on_chain_code_hash == Some(KECCAK_EMPTY)) - && !self.all_transactions.auths.contains_key(&transaction.sender_id()) + if (on_chain_code_hash.is_none() || on_chain_code_hash == Some(KECCAK_EMPTY)) && + !self.all_transactions.auths.contains_key(&transaction.sender_id()) { - return Ok(()); + return Ok(()) } let mut txs_by_sender = @@ -775,14 +775,14 @@ impl TxPool { PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702( Eip7702PoolTransactionError::OutOfOrderTxFromDelegated, )), - )); + )) } - return Ok(()); + return Ok(()) } if txs_by_sender.any(|id| id == &transaction.transaction_id) { // Transaction replacement is supported - return Ok(()); + return Ok(()) } Err(PoolError::new( @@ -819,7 +819,7 @@ impl TxPool { PoolErrorKind::InvalidTransaction(InvalidPoolTransactionError::Eip7702( Eip7702PoolTransactionError::AuthorityReserved, )), - )); + )) } } } @@ -1004,7 +1004,7 @@ impl TxPool { } id = descendant; } else { - return; + return } } } @@ -1273,7 +1273,7 @@ impl AllTransactions { if *count == 1 { entry.remove(); self.metrics.all_transactions_by_all_senders.decrement(1.0); - return; + return } *count -= 1; self.metrics.all_transactions_by_all_senders.decrement(1.0); @@ -1348,7 +1348,7 @@ impl AllTransactions { ($iter:ident) => { 'this: while let Some((peek, _)) = iter.peek() { if peek.sender != id.sender { - break 'this; + break 'this } iter.next(); } @@ -1365,7 +1365,7 @@ impl AllTransactions { current: tx.subpool, destination: Destination::Discard, }); - continue 'transactions; + continue 'transactions } let ancestor = TransactionId::ancestor(id.nonce, info.state_nonce, id.sender); @@ -1390,7 +1390,7 @@ impl AllTransactions { // If there's a nonce gap, we can shortcircuit, because there's nothing to update yet. if tx.state.has_nonce_gap() { next_sender!(iter); - continue 'transactions; + continue 'transactions } // Since this is the first transaction of the sender, it has no parked ancestors @@ -1413,7 +1413,7 @@ impl AllTransactions { while let Some((peek, tx)) = iter.peek_mut() { if peek.sender != id.sender { // Found the next sender we need to check - continue 'transactions; + continue 'transactions } if tx.transaction.nonce() == next_nonce_in_line { @@ -1422,7 +1422,7 @@ impl AllTransactions { } else { // can short circuit if there's still a nonce gap next_sender!(iter); - continue 'transactions; + continue 'transactions } // update for next iteration of this sender's loop @@ -1667,7 +1667,7 @@ impl AllTransactions { if current_txs >= self.max_account_slots && transaction.nonce() > on_chain_nonce { return Err(InsertErr::ExceededSenderTransactionsCapacity { transaction: Arc::new(transaction), - }); + }) } } if transaction.gas_limit() > self.block_gas_limit { @@ -1675,12 +1675,12 @@ impl AllTransactions { block_gas_limit: self.block_gas_limit, tx_gas_limit: transaction.gas_limit(), transaction: Arc::new(transaction), - }); + }) } if self.contains_conflicting_transaction(&transaction) { // blob vs non blob transactions are mutually exclusive for the same sender - return Err(InsertErr::TxTypeConflict { transaction: Arc::new(transaction) }); + return Err(InsertErr::TxTypeConflict { transaction: Arc::new(transaction) }) } Ok(transaction) @@ -1701,13 +1701,13 @@ impl AllTransactions { let Some(ancestor_tx) = self.txs.get(&ancestor) else { // ancestor tx is missing, so we can't insert the new blob self.metrics.blob_transactions_nonce_gaps.increment(1); - return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }); + return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }) }; if ancestor_tx.state.has_nonce_gap() { // the ancestor transaction already has a nonce gap, so we can't insert the new // blob self.metrics.blob_transactions_nonce_gaps.increment(1); - return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }); + return Err(InsertErr::BlobTxHasNonceGap { transaction: Arc::new(new_blob_tx) }) } // the max cost executing this transaction requires @@ -1716,7 +1716,7 @@ impl AllTransactions { // check if the new blob would go into overdraft if cumulative_cost > on_chain_balance { // the transaction would go into overdraft - return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }); + return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) } // ensure that a replacement would not shift already propagated blob transactions into @@ -1733,16 +1733,14 @@ impl AllTransactions { cumulative_cost += tx.transaction.cost(); if tx.transaction.is_eip4844() && cumulative_cost > on_chain_balance { // the transaction would shift - return Err(InsertErr::Overdraft { - transaction: Arc::new(new_blob_tx), - }); + return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) } } } } } else if new_blob_tx.cost() > &on_chain_balance { // the transaction would go into overdraft - return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }); + return Err(InsertErr::Overdraft { transaction: Arc::new(new_blob_tx) }) } Ok(new_blob_tx) @@ -1833,7 +1831,7 @@ impl AllTransactions { let fee_cap = transaction.max_fee_per_gas(); if fee_cap < self.minimal_protocol_basefee as u128 { - return Err(InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap }); + return Err(InsertErr::FeeCapBelowMinimumProtocolFeeCap { transaction, fee_cap }) } if fee_cap >= self.pending_fees.base_fee as u128 { state.insert(TxState::ENOUGH_FEE_CAP_BLOCK); @@ -1866,7 +1864,7 @@ impl AllTransactions { return Err(InsertErr::Underpriced { transaction: pool_tx.transaction, existing: *entry.get().transaction.hash(), - }); + }) } let new_hash = *pool_tx.transaction.hash(); let new_transaction = pool_tx.transaction.clone(); @@ -1906,7 +1904,7 @@ impl AllTransactions { // If there's a nonce gap, we can shortcircuit if next_nonce != id.nonce { - break; + break } // close the nonce gap diff --git a/crates/transaction-pool/src/test_utils/mock.rs b/crates/transaction-pool/src/test_utils/mock.rs index 073b7a4145..9ddde67ba5 100644 --- a/crates/transaction-pool/src/test_utils/mock.rs +++ b/crates/transaction-pool/src/test_utils/mock.rs @@ -57,11 +57,11 @@ macro_rules! set_value { ($this:ident => $field:ident) => { let new_value = $field; match $this { - MockTransaction::Legacy { ref mut $field, .. } - | MockTransaction::Eip1559 { ref mut $field, .. } - | MockTransaction::Eip4844 { ref mut $field, .. } - | MockTransaction::Eip2930 { ref mut $field, .. } - | MockTransaction::Eip7702 { ref mut $field, .. } => { + MockTransaction::Legacy { ref mut $field, .. } | + MockTransaction::Eip1559 { ref mut $field, .. } | + MockTransaction::Eip4844 { ref mut $field, .. } | + MockTransaction::Eip2930 { ref mut $field, .. } | + MockTransaction::Eip7702 { ref mut $field, .. } => { *$field = new_value; } } @@ -74,11 +74,11 @@ macro_rules! set_value { macro_rules! get_value { ($this:tt => $field:ident) => { match $this { - MockTransaction::Legacy { $field, .. } - | MockTransaction::Eip1559 { $field, .. } - | MockTransaction::Eip4844 { $field, .. } - | MockTransaction::Eip2930 { $field, .. } - | MockTransaction::Eip7702 { $field, .. } => $field, + MockTransaction::Legacy { $field, .. } | + MockTransaction::Eip1559 { $field, .. } | + MockTransaction::Eip4844 { $field, .. } | + MockTransaction::Eip2930 { $field, .. } | + MockTransaction::Eip7702 { $field, .. } => $field, } }; } @@ -414,8 +414,8 @@ impl MockTransaction { /// Sets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn set_priority_fee(&mut self, val: u128) -> &mut Self { - if let Self::Eip1559 { max_priority_fee_per_gas, .. } - | Self::Eip4844 { max_priority_fee_per_gas, .. } = self + if let Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } = self { *max_priority_fee_per_gas = val; } @@ -431,18 +431,18 @@ impl MockTransaction { /// Gets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_priority_fee(&self) -> Option { match self { - Self::Eip1559 { max_priority_fee_per_gas, .. } - | Self::Eip4844 { max_priority_fee_per_gas, .. } - | Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } | + Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), _ => None, } } /// Sets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn set_max_fee(&mut self, val: u128) -> &mut Self { - if let Self::Eip1559 { max_fee_per_gas, .. } - | Self::Eip4844 { max_fee_per_gas, .. } - | Self::Eip7702 { max_fee_per_gas, .. } = self + if let Self::Eip1559 { max_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, .. } | + Self::Eip7702 { max_fee_per_gas, .. } = self { *max_fee_per_gas = val; } @@ -458,9 +458,9 @@ impl MockTransaction { /// Gets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_max_fee(&self) -> Option { match self { - Self::Eip1559 { max_fee_per_gas, .. } - | Self::Eip4844 { max_fee_per_gas, .. } - | Self::Eip7702 { max_fee_per_gas, .. } => Some(*max_fee_per_gas), + Self::Eip1559 { max_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, .. } | + Self::Eip7702 { max_fee_per_gas, .. } => Some(*max_fee_per_gas), _ => None, } } @@ -469,10 +469,10 @@ impl MockTransaction { pub fn set_accesslist(&mut self, list: AccessList) -> &mut Self { match self { Self::Legacy { .. } => {} - Self::Eip1559 { access_list: accesslist, .. } - | Self::Eip4844 { access_list: accesslist, .. } - | Self::Eip2930 { access_list: accesslist, .. } - | Self::Eip7702 { access_list: accesslist, .. } => { + Self::Eip1559 { access_list: accesslist, .. } | + Self::Eip4844 { access_list: accesslist, .. } | + Self::Eip2930 { access_list: accesslist, .. } | + Self::Eip7702 { access_list: accesslist, .. } => { *accesslist = list; } } @@ -494,9 +494,9 @@ impl MockTransaction { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => { *gas_price = val; } - Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } - | Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } - | Self::Eip7702 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { + Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } | + Self::Eip7702 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -510,9 +510,9 @@ impl MockTransaction { Self::Legacy { ref mut gas_price, .. } | Self::Eip2930 { ref mut gas_price, .. } => { *gas_price = val; } - Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } - | Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } - | Self::Eip7702 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => { + Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } | + Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } | + Self::Eip7702 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -524,9 +524,9 @@ impl MockTransaction { pub const fn get_gas_price(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_fee_per_gas, .. } - | Self::Eip4844 { max_fee_per_gas, .. } - | Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Eip1559 { max_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, .. } | + Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, } } @@ -660,13 +660,13 @@ impl MockTransaction { fn update_cost(&mut self) { match self { - Self::Legacy { cost, gas_limit, gas_price, value, .. } - | Self::Eip2930 { cost, gas_limit, gas_price, value, .. } => { + Self::Legacy { cost, gas_limit, gas_price, value, .. } | + Self::Eip2930 { cost, gas_limit, gas_price, value, .. } => { *cost = U256::from(*gas_limit) * U256::from(*gas_price) + *value } - Self::Eip1559 { cost, gas_limit, max_fee_per_gas, value, .. } - | Self::Eip4844 { cost, gas_limit, max_fee_per_gas, value, .. } - | Self::Eip7702 { cost, gas_limit, max_fee_per_gas, value, .. } => { + Self::Eip1559 { cost, gas_limit, max_fee_per_gas, value, .. } | + Self::Eip4844 { cost, gas_limit, max_fee_per_gas, value, .. } | + Self::Eip7702 { cost, gas_limit, max_fee_per_gas, value, .. } => { *cost = U256::from(*gas_limit) * U256::from(*max_fee_per_gas) + *value } }; @@ -706,11 +706,11 @@ impl PoolTransaction for MockTransaction { // not to be manually set. fn cost(&self) -> &U256 { match self { - Self::Legacy { cost, .. } - | Self::Eip2930 { cost, .. } - | Self::Eip1559 { cost, .. } - | Self::Eip4844 { cost, .. } - | Self::Eip7702 { cost, .. } => cost, + Self::Legacy { cost, .. } | + Self::Eip2930 { cost, .. } | + Self::Eip1559 { cost, .. } | + Self::Eip4844 { cost, .. } | + Self::Eip7702 { cost, .. } => cost, } } @@ -742,10 +742,10 @@ impl alloy_consensus::Transaction for MockTransaction { fn chain_id(&self) -> Option { match self { Self::Legacy { chain_id, .. } => *chain_id, - Self::Eip1559 { chain_id, .. } - | Self::Eip4844 { chain_id, .. } - | Self::Eip2930 { chain_id, .. } - | Self::Eip7702 { chain_id, .. } => Some(*chain_id), + Self::Eip1559 { chain_id, .. } | + Self::Eip4844 { chain_id, .. } | + Self::Eip2930 { chain_id, .. } | + Self::Eip7702 { chain_id, .. } => Some(*chain_id), } } @@ -767,18 +767,18 @@ impl alloy_consensus::Transaction for MockTransaction { fn max_fee_per_gas(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_fee_per_gas, .. } - | Self::Eip4844 { max_fee_per_gas, .. } - | Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Eip1559 { max_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, .. } | + Self::Eip7702 { max_fee_per_gas, .. } => *max_fee_per_gas, } } fn max_priority_fee_per_gas(&self) -> Option { match self { Self::Legacy { .. } | Self::Eip2930 { .. } => None, - Self::Eip1559 { max_priority_fee_per_gas, .. } - | Self::Eip4844 { max_priority_fee_per_gas, .. } - | Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } | + Self::Eip7702 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), } } @@ -792,9 +792,9 @@ impl alloy_consensus::Transaction for MockTransaction { fn priority_fee_or_price(&self) -> u128 { match self { Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, - Self::Eip1559 { max_priority_fee_per_gas, .. } - | Self::Eip4844 { max_priority_fee_per_gas, .. } - | Self::Eip7702 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } | + Self::Eip7702 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, } } @@ -838,11 +838,11 @@ impl alloy_consensus::Transaction for MockTransaction { fn value(&self) -> U256 { match self { - Self::Legacy { value, .. } - | Self::Eip1559 { value, .. } - | Self::Eip2930 { value, .. } - | Self::Eip4844 { value, .. } - | Self::Eip7702 { value, .. } => *value, + Self::Legacy { value, .. } | + Self::Eip1559 { value, .. } | + Self::Eip2930 { value, .. } | + Self::Eip4844 { value, .. } | + Self::Eip7702 { value, .. } => *value, } } @@ -853,10 +853,10 @@ impl alloy_consensus::Transaction for MockTransaction { fn access_list(&self) -> Option<&AccessList> { match self { Self::Legacy { .. } => None, - Self::Eip1559 { access_list: accesslist, .. } - | Self::Eip4844 { access_list: accesslist, .. } - | Self::Eip2930 { access_list: accesslist, .. } - | Self::Eip7702 { access_list: accesslist, .. } => Some(accesslist), + Self::Eip1559 { access_list: accesslist, .. } | + Self::Eip4844 { access_list: accesslist, .. } | + Self::Eip2930 { access_list: accesslist, .. } | + Self::Eip7702 { access_list: accesslist, .. } => Some(accesslist), } } diff --git a/crates/transaction-pool/src/traits.rs b/crates/transaction-pool/src/traits.rs index 0f353dd851..e9f58c27a3 100644 --- a/crates/transaction-pool/src/traits.rs +++ b/crates/transaction-pool/src/traits.rs @@ -1574,7 +1574,7 @@ impl NewSubpoolTransactionStream { match self.st.try_recv() { Ok(event) => { if event.subpool == self.subpool { - return Ok(event); + return Ok(event) } } Err(e) => return Err(e), @@ -1591,7 +1591,7 @@ impl Stream for NewSubpoolTransactionStream { match ready!(self.st.poll_recv(cx)) { Some(event) => { if event.subpool == self.subpool { - return Poll::Ready(Some(event)); + return Poll::Ready(Some(event)) } } None => return Poll::Ready(None), diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index fa64257de3..90a61b86ec 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -312,7 +312,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip2930Disabled.into(), - )); + )) } } EIP1559_TX_TYPE_ID => { @@ -321,7 +321,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip1559Disabled.into(), - )); + )) } } EIP4844_TX_TYPE_ID => { @@ -330,7 +330,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip4844Disabled.into(), - )); + )) } } EIP7702_TX_TYPE_ID => { @@ -339,7 +339,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::Eip7702Disabled.into(), - )); + )) } } @@ -357,7 +357,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::Eip2681, - )); + )) } // Reject transactions over defined size to prevent DOS attacks @@ -366,13 +366,13 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::OversizedData(tx_input_len, self.max_tx_input_bytes), - )); + )) } // Check whether the init code size has been exceeded. if self.fork_tracker.is_shanghai_activated() { if let Err(err) = transaction.ensure_max_init_code_size(MAX_INIT_CODE_BYTE_SIZE) { - return Err(TransactionValidationOutcome::Invalid(transaction, err)); + return Err(TransactionValidationOutcome::Invalid(transaction, err)) } } @@ -386,7 +386,7 @@ where transaction_gas_limit, block_gas_limit, ), - )); + )) } // Ensure max_priority_fee_per_gas (if EIP1559) is less than max_fee_per_gas if any. @@ -394,7 +394,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TipAboveFeeCap.into(), - )); + )) } // determine whether the transaction should be treated as local @@ -417,7 +417,7 @@ where max_tx_fee_wei, tx_fee_cap_wei, }, - )); + )) } } } @@ -425,14 +425,14 @@ where // Drop non-local transactions with a fee lower than the configured fee for acceptance into // the pool. - if !is_local - && transaction.is_dynamic_fee() - && transaction.max_priority_fee_per_gas() < self.minimum_priority_fee + if !is_local && + transaction.is_dynamic_fee() && + transaction.max_priority_fee_per_gas() < self.minimum_priority_fee { return Err(TransactionValidationOutcome::Invalid( transaction, InvalidPoolTransactionError::Underpriced, - )); + )) } // Checks for chainid @@ -441,7 +441,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::ChainIdMismatch.into(), - )); + )) } } @@ -451,19 +451,19 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - )); + )) } if transaction.authorization_list().is_none_or(|l| l.is_empty()) { return Err(TransactionValidationOutcome::Invalid( transaction, Eip7702PoolTransactionError::MissingEip7702AuthorizationList.into(), - )); + )) } } if let Err(err) = ensure_intrinsic_gas(&transaction, &self.fork_tracker) { - return Err(TransactionValidationOutcome::Invalid(transaction, err)); + return Err(TransactionValidationOutcome::Invalid(transaction, err)) } // light blob tx pre-checks @@ -473,7 +473,7 @@ where return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - )); + )) } let blob_count = @@ -485,7 +485,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::NoEip4844Blobs, ), - )); + )) } let max_blob_count = self.fork_tracker.max_blob_count(); @@ -498,18 +498,18 @@ where permitted: max_blob_count, }, ), - )); + )) } } // Osaka validation of max tx gas. - if self.fork_tracker.is_osaka_activated() - && transaction.gas_limit() > MAX_TX_GAS_LIMIT_OSAKA + if self.fork_tracker.is_osaka_activated() && + transaction.gas_limit() > MAX_TX_GAS_LIMIT_OSAKA { return Err(TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::GasLimitTooHigh.into(), - )); + )) } Ok(transaction) @@ -558,7 +558,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::SignerAccountHasBytecode.into(), - ); + ) } } @@ -570,7 +570,7 @@ where transaction, InvalidTransactionError::NonceNotConsistent { tx: tx_nonce, state: account.nonce } .into(), - ); + ) } let cost = transaction.cost(); @@ -584,7 +584,7 @@ where GotExpected { got: account.balance, expected }.into(), ) .into(), - ); + ) } let mut maybe_blob_sidecar = None; @@ -598,7 +598,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ); + ) } EthBlobTransactionSidecar::Missing => { // This can happen for re-injected blob transactions (on re-org), since the blob @@ -613,7 +613,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::MissingEip4844BlobSidecar, ), - ); + ) } } EthBlobTransactionSidecar::Present(sidecar) => { @@ -626,7 +626,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::UnexpectedEip4844SidecarAfterOsaka, ), - ); + ) } } else if sidecar.is_eip7594() { return TransactionValidationOutcome::Invalid( @@ -634,7 +634,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::UnexpectedEip7594SidecarBeforeOsaka, ), - ); + ) } // validate the blob @@ -644,7 +644,7 @@ where InvalidPoolTransactionError::Eip4844( Eip4844PoolTransactionError::InvalidEip4844Blob(err), ), - ); + ) } // Record the duration of successful blob validation as histogram self.validation_metrics.blob_validation_duration.record(now.elapsed()); diff --git a/crates/transaction-pool/src/validate/mod.rs b/crates/transaction-pool/src/validate/mod.rs index f49832b509..36d9f14add 100644 --- a/crates/transaction-pool/src/validate/mod.rs +++ b/crates/transaction-pool/src/validate/mod.rs @@ -459,7 +459,7 @@ impl ValidPoolTransaction { // Check if the max fee per gas is underpriced. if maybe_replacement.max_fee_per_gas() < self.max_fee_per_gas() * (100 + price_bump) / 100 { - return true; + return true } let existing_max_priority_fee_per_gas = @@ -468,12 +468,12 @@ impl ValidPoolTransaction { maybe_replacement.transaction.max_priority_fee_per_gas().unwrap_or_default(); // Check max priority fee per gas (relevant for EIP-1559 transactions only) - if existing_max_priority_fee_per_gas != 0 - && replacement_max_priority_fee_per_gas != 0 - && replacement_max_priority_fee_per_gas - < existing_max_priority_fee_per_gas * (100 + price_bump) / 100 + if existing_max_priority_fee_per_gas != 0 && + replacement_max_priority_fee_per_gas != 0 && + replacement_max_priority_fee_per_gas < + existing_max_priority_fee_per_gas * (100 + price_bump) / 100 { - return true; + return true } // Check max blob fee per gas @@ -481,10 +481,10 @@ impl ValidPoolTransaction { // This enforces that blob txs can only be replaced by blob txs let replacement_max_blob_fee_per_gas = maybe_replacement.transaction.max_fee_per_blob_gas().unwrap_or_default(); - if replacement_max_blob_fee_per_gas - < existing_max_blob_fee_per_gas * (100 + price_bump) / 100 + if replacement_max_blob_fee_per_gas < + existing_max_blob_fee_per_gas * (100 + price_bump) / 100 { - return true; + return true } } diff --git a/crates/trie/common/benches/prefix_set.rs b/crates/trie/common/benches/prefix_set.rs index 2da11d694f..bc2a8dc259 100644 --- a/crates/trie/common/benches/prefix_set.rs +++ b/crates/trie/common/benches/prefix_set.rs @@ -195,12 +195,12 @@ mod implementations { for key in self.keys.range::(range) { if key.starts_with(&prefix) { self.last_checked = Some(prefix); - return true; + return true } if key > &prefix { self.last_checked = Some(prefix); - return false; + return false } } @@ -278,12 +278,12 @@ mod implementations { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(&prefix) { self.index += idx; - return true; + return true } if key > &prefix { self.index += idx; - return false; + return false } } diff --git a/crates/trie/common/src/hashed_state.rs b/crates/trie/common/src/hashed_state.rs index f3ec7eeccd..b6f60e2b2a 100644 --- a/crates/trie/common/src/hashed_state.rs +++ b/crates/trie/common/src/hashed_state.rs @@ -216,7 +216,7 @@ impl HashedPostState { let mut storage_not_in_targets = HashedStorage::default(); storage.storage.retain(|&slot, value| { if storage_in_targets.contains(&slot) { - return true; + return true } storage_not_in_targets.storage.insert(slot, *value); @@ -251,7 +251,7 @@ impl HashedPostState { }); self.accounts.retain(|&address, account| { if targets.contains_key(&address) { - return true; + return true } state_updates_not_in_targets.accounts.insert(address, *account); diff --git a/crates/trie/common/src/prefix_set.rs b/crates/trie/common/src/prefix_set.rs index c46aa44e48..e1f4150dd2 100644 --- a/crates/trie/common/src/prefix_set.rs +++ b/crates/trie/common/src/prefix_set.rs @@ -17,9 +17,9 @@ pub struct TriePrefixSetsMut { impl TriePrefixSetsMut { /// Returns `true` if all prefix sets are empty. pub fn is_empty(&self) -> bool { - self.account_prefix_set.is_empty() - && self.storage_prefix_sets.is_empty() - && self.destroyed_accounts.is_empty() + self.account_prefix_set.is_empty() && + self.storage_prefix_sets.is_empty() && + self.destroyed_accounts.is_empty() } /// Extends prefix sets with contents of another prefix set. @@ -195,7 +195,7 @@ impl PrefixSet { #[inline] pub fn contains(&mut self, prefix: &Nibbles) -> bool { if self.all { - return true; + return true } while self.index > 0 && &self.keys[self.index] > prefix { @@ -205,12 +205,12 @@ impl PrefixSet { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.starts_with(prefix) { self.index += idx; - return true; + return true } if key > prefix { self.index += idx; - return false; + return false } } diff --git a/crates/trie/common/src/proofs.rs b/crates/trie/common/src/proofs.rs index 2065c6a3a4..5c3b55b092 100644 --- a/crates/trie/common/src/proofs.rs +++ b/crates/trie/common/src/proofs.rs @@ -179,10 +179,10 @@ pub struct MultiProof { impl MultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { - self.account_subtree.is_empty() - && self.branch_node_hash_masks.is_empty() - && self.branch_node_tree_masks.is_empty() - && self.storages.is_empty() + self.account_subtree.is_empty() && + self.branch_node_hash_masks.is_empty() && + self.branch_node_tree_masks.is_empty() && + self.storages.is_empty() } /// Return the account proof nodes for the given account path. @@ -238,7 +238,7 @@ impl MultiProof { nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), - }); + }) } } } @@ -310,10 +310,10 @@ pub struct DecodedMultiProof { impl DecodedMultiProof { /// Returns true if the multiproof is empty. pub fn is_empty(&self) -> bool { - self.account_subtree.is_empty() - && self.branch_node_hash_masks.is_empty() - && self.branch_node_tree_masks.is_empty() - && self.storages.is_empty() + self.account_subtree.is_empty() && + self.branch_node_hash_masks.is_empty() && + self.branch_node_tree_masks.is_empty() && + self.storages.is_empty() } /// Return the account proof nodes for the given account path. @@ -368,7 +368,7 @@ impl DecodedMultiProof { nonce: account.nonce, bytecode_hash: (account.code_hash != KECCAK_EMPTY) .then_some(account.code_hash), - }); + }) } } None @@ -489,7 +489,7 @@ impl StorageMultiProof { if let Some(last) = proof.last() { if let TrieNode::Leaf(leaf) = TrieNode::decode(&mut &last[..])? { if nibbles.ends_with(&leaf.key) { - break 'value U256::decode(&mut &leaf.value[..])?; + break 'value U256::decode(&mut &leaf.value[..])? } } } @@ -541,7 +541,7 @@ impl DecodedStorageMultiProof { let value = 'value: { if let Some(TrieNode::Leaf(leaf)) = proof.last() { if nibbles.ends_with(&leaf.key) { - break 'value U256::decode(&mut &leaf.value[..])?; + break 'value U256::decode(&mut &leaf.value[..])? } } U256::ZERO @@ -627,10 +627,10 @@ impl AccountProof { } = proof; let storage_proofs = storage_proof.into_iter().map(Into::into).collect(); - let (storage_root, info) = if nonce == 0 - && balance.is_zero() - && storage_hash.is_zero() - && code_hash == KECCAK_EMPTY + let (storage_root, info) = if nonce == 0 && + balance.is_zero() && + storage_hash.is_zero() && + code_hash == KECCAK_EMPTY { // Account does not exist in state. Return `None` here to prevent proof // verification. diff --git a/crates/trie/common/src/updates.rs b/crates/trie/common/src/updates.rs index 0a2c28d80d..dd82f4e192 100644 --- a/crates/trie/common/src/updates.rs +++ b/crates/trie/common/src/updates.rs @@ -25,9 +25,9 @@ pub struct TrieUpdates { impl TrieUpdates { /// Returns `true` if the updates are empty. pub fn is_empty(&self) -> bool { - self.account_nodes.is_empty() - && self.removed_nodes.is_empty() - && self.storage_tries.is_empty() + self.account_nodes.is_empty() && + self.removed_nodes.is_empty() && + self.storage_tries.is_empty() } /// Returns reference to updated account nodes. diff --git a/crates/trie/db/tests/witness.rs b/crates/trie/db/tests/witness.rs index c1a5ad14a0..5dfa1c3e4a 100644 --- a/crates/trie/db/tests/witness.rs +++ b/crates/trie/db/tests/witness.rs @@ -89,12 +89,16 @@ fn includes_nodes_for_destroyed_storage_nodes() { )])) .unwrap(); - let witness = TrieWitness::from_tx(provider.tx_ref()) - .compute(HashedPostState { - accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), - storages: HashMap::from_iter([(hashed_address, HashedStorage::from_iter(true, []))]), // destroyed - }) - .unwrap(); + let witness = + TrieWitness::from_tx(provider.tx_ref()) + .compute(HashedPostState { + accounts: HashMap::from_iter([(hashed_address, Some(Account::default()))]), + storages: HashMap::from_iter([( + hashed_address, + HashedStorage::from_iter(true, []), + )]), // destroyed + }) + .unwrap(); assert!(witness.contains_key(&state_root)); for node in multiproof.account_subtree.values() { assert_eq!(witness.get(&keccak256(node)), Some(node)); diff --git a/crates/trie/parallel/src/proof.rs b/crates/trie/parallel/src/proof.rs index 76babc4060..940a51a924 100644 --- a/crates/trie/parallel/src/proof.rs +++ b/crates/trie/parallel/src/proof.rs @@ -248,38 +248,39 @@ where hash_builder.add_branch(node.key, node.value, node.children_are_in_trie); } TrieElement::Leaf(hashed_address, account) => { - let decoded_storage_multiproof = - match storage_proof_receivers.remove(&hashed_address) { - Some(rx) => rx.recv().map_err(|e| { + let decoded_storage_multiproof = match storage_proof_receivers + .remove(&hashed_address) + { + Some(rx) => rx.recv().map_err(|e| { + ParallelStateRootError::StorageRoot(StorageRootError::Database( + DatabaseError::Other(format!( + "channel closed for {hashed_address}: {e}" + )), + )) + })??, + // Since we do not store all intermediate nodes in the database, there might + // be a possibility of re-adding a non-modified leaf to the hash builder. + None => { + tracker.inc_missed_leaves(); + + let raw_fallback_proof = StorageProof::new_hashed( + trie_cursor_factory.clone(), + hashed_cursor_factory.clone(), + hashed_address, + ) + .with_prefix_set_mut(Default::default()) + .storage_multiproof( + targets.get(&hashed_address).cloned().unwrap_or_default(), + ) + .map_err(|e| { ParallelStateRootError::StorageRoot(StorageRootError::Database( - DatabaseError::Other(format!( - "channel closed for {hashed_address}: {e}" - )), + DatabaseError::Other(e.to_string()), )) - })??, - // Since we do not store all intermediate nodes in the database, there might - // be a possibility of re-adding a non-modified leaf to the hash builder. - None => { - tracker.inc_missed_leaves(); - - let raw_fallback_proof = StorageProof::new_hashed( - trie_cursor_factory.clone(), - hashed_cursor_factory.clone(), - hashed_address, - ) - .with_prefix_set_mut(Default::default()) - .storage_multiproof( - targets.get(&hashed_address).cloned().unwrap_or_default(), - ) - .map_err(|e| { - ParallelStateRootError::StorageRoot(StorageRootError::Database( - DatabaseError::Other(e.to_string()), - )) - })?; - - raw_fallback_proof.try_into()? - } - }; + })?; + + raw_fallback_proof.try_into()? + } + }; // Encode account account_rlp.clear(); diff --git a/crates/trie/parallel/src/proof_task.rs b/crates/trie/parallel/src/proof_task.rs index 8ddcc96218..4dc7810696 100644 --- a/crates/trie/parallel/src/proof_task.rs +++ b/crates/trie/parallel/src/proof_task.rs @@ -142,7 +142,7 @@ where let Some(proof_task_tx) = self.get_or_create_tx()? else { // if there are no txs available, requeue the proof task self.pending_tasks.push_front(task); - return Ok(()); + return Ok(()) }; let tx_sender = self.tx_sender.clone(); diff --git a/crates/trie/sparse-parallel/src/trie.rs b/crates/trie/sparse-parallel/src/trie.rs index 6cd0b146be..b2d8d147f8 100644 --- a/crates/trie/sparse-parallel/src/trie.rs +++ b/crates/trie/sparse-parallel/src/trie.rs @@ -218,31 +218,31 @@ impl ParallelSparseTrie { found_full_path.extend(key); if &found_full_path == leaf_full_path { - return Ok(FindNextToLeafOutcome::Found); + return Ok(FindNextToLeafOutcome::Found) } Ok(FindNextToLeafOutcome::NotFound) } SparseNode::Extension { key, .. } => { if leaf_full_path.len() == from_path.len() { - return Ok(FindNextToLeafOutcome::NotFound); + return Ok(FindNextToLeafOutcome::NotFound) } let mut child_path = *from_path; child_path.extend(key); if !leaf_full_path.starts_with(&child_path) { - return Ok(FindNextToLeafOutcome::NotFound); + return Ok(FindNextToLeafOutcome::NotFound) } Ok(FindNextToLeafOutcome::ContinueFrom(child_path)) } SparseNode::Branch { state_mask, .. } => { if leaf_full_path.len() == from_path.len() { - return Ok(FindNextToLeafOutcome::NotFound); + return Ok(FindNextToLeafOutcome::NotFound) } let nibble = leaf_full_path.get_unchecked(from_path.len()); if !state_mask.is_bit_set(nibble) { - return Ok(FindNextToLeafOutcome::NotFound); + return Ok(FindNextToLeafOutcome::NotFound) } let mut child_path = *from_path; @@ -489,7 +489,7 @@ impl ParallelSparseTrie { // here, all remaining logic is related to the ancestors of the leaf. if leaf_path.is_empty() { self.upper_subtrie.nodes.insert(leaf_path, SparseNode::Empty); - return Ok(()); + return Ok(()) } // If there is a parent branch node (very likely, unless the leaf is at the root) execute @@ -553,7 +553,7 @@ impl ParallelSparseTrie { return Err(SparseTrieErrorKind::NodeNotFoundInProvider { path: remaining_child_path, } - .into()); + .into()) } } node => node, @@ -772,7 +772,7 @@ impl ParallelSparseTrie { // If we're past the subtrie path, we're done with this subtrie. Do not // advance the iterator, the next key will be processed either by the // next subtrie or inserted into the unchanged prefix set. - break; + break } } PrefixSetMut::from(new_prefix_set) @@ -852,7 +852,7 @@ impl SparseSubtrie { // If the node is already revealed and it's not a hash node, do nothing. if self.nodes.get(&path).is_some_and(|node| !node.is_hash()) { - return Ok(()); + return Ok(()) } if let Some(tree_mask) = masks.tree_mask { @@ -896,8 +896,8 @@ impl SparseSubtrie { // node. hash: Some(*hash), store_in_db_trie: Some( - masks.hash_mask.is_some_and(|mask| !mask.is_empty()) - || masks.tree_mask.is_some_and(|mask| !mask.is_empty()), + masks.hash_mask.is_some_and(|mask| !mask.is_empty()) || + masks.tree_mask.is_some_and(|mask| !mask.is_empty()), ), }); } @@ -973,9 +973,9 @@ impl SparseSubtrie { // Leaf node already exists. SparseNode::Leaf { .. } => {} // All other node types can't be handled. - node @ (SparseNode::Empty - | SparseNode::Extension { .. } - | SparseNode::Branch { .. }) => { + node @ (SparseNode::Empty | + SparseNode::Extension { .. } | + SparseNode::Branch { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), @@ -1032,7 +1032,7 @@ impl SparseSubtrie { entry.insert(SparseNode::Hash(hash)); } } - return Ok(()); + return Ok(()) } self.reveal_node(path, &TrieNode::decode(&mut &child[..])?, TrieMasks::none()) @@ -1231,7 +1231,7 @@ impl SparseSubtrieInner { }, RlpNodePathStackItem { path: child_path, is_in_prefix_set: None }, ]); - return; + return } } SparseNode::Branch { state_mask, hash, store_in_db_trie } => { @@ -1247,7 +1247,7 @@ impl SparseSubtrieInner { store_in_db_trie: Some(store_in_db_trie), }, }); - return; + return } let retain_updates = self.updates.is_some() && prefix_set_contains(&path); @@ -1293,9 +1293,8 @@ impl SparseSubtrieInner { store_in_db_trie } else { // A blinded node has the tree mask bit set - child_node_type.is_hash() - && self - .branch_node_tree_masks + child_node_type.is_hash() && + self.branch_node_tree_masks .get(&path) .is_some_and(|mask| mask.is_bit_set(last_child_nibble)) }; @@ -1307,12 +1306,11 @@ impl SparseSubtrieInner { // is a blinded node that has its hash mask bit set according to the // database, set the hash mask bit and save the hash. let hash = child.as_hash().filter(|_| { - child_node_type.is_branch() - || (child_node_type.is_hash() - && self - .branch_node_hash_masks - .get(&path) - .is_some_and(|mask| mask.is_bit_set(last_child_nibble))) + child_node_type.is_branch() || + (child_node_type.is_hash() && + self.branch_node_hash_masks.get(&path).is_some_and( + |mask| mask.is_bit_set(last_child_nibble), + )) }); if let Some(hash) = hash { hash_mask.set_bit(last_child_nibble); @@ -1340,7 +1338,7 @@ impl SparseSubtrieInner { .drain(..) .map(|path| RlpNodePathStackItem { path, is_in_prefix_set: None }), ); - return; + return } } @@ -1381,9 +1379,8 @@ impl SparseSubtrieInner { } else if self .branch_node_tree_masks .get(&path) - .is_some_and(|mask| !mask.is_empty()) - || self - .branch_node_hash_masks + .is_some_and(|mask| !mask.is_empty()) || + self.branch_node_hash_masks .get(&path) .is_some_and(|mask| !mask.is_empty()) { @@ -1395,8 +1392,8 @@ impl SparseSubtrieInner { } else if self .branch_node_hash_masks .get(&path) - .is_none_or(|mask| mask.is_empty()) - && self.branch_node_hash_masks.get(&path).is_none_or(|mask| mask.is_empty()) + .is_none_or(|mask| mask.is_empty()) && + self.branch_node_hash_masks.get(&path).is_none_or(|mask| mask.is_empty()) { // If new tree and hash masks are empty, and they were previously empty // as well, we need to remove the node update. diff --git a/crates/trie/sparse/src/state.rs b/crates/trie/sparse/src/state.rs index a963861c1c..66c3596363 100644 --- a/crates/trie/sparse/src/state.rs +++ b/crates/trie/sparse/src/state.rs @@ -231,7 +231,7 @@ impl SparseStateTrie { // Reveal the remaining proof nodes. for (path, bytes) in proof { if self.revealed_account_paths.contains(&path) { - continue; + continue } let node = TrieNode::decode(&mut &bytes[..])?; trie.reveal_node(path, node, TrieMasks::none())?; @@ -278,7 +278,7 @@ impl SparseStateTrie { for (path, bytes) in proof { // If the node is already revealed, skip it. if revealed_nodes.contains(&path) { - continue; + continue } let node = TrieNode::decode(&mut &bytes[..])?; trie.reveal_node(path, node, TrieMasks::none())?; @@ -590,13 +590,13 @@ impl SparseStateTrie { // Validate root node. let Some((path, node)) = proof.next() else { return Ok(None) }; if !path.is_empty() { - return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()); + return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()) } // Decode root node and perform sanity check. let root_node = TrieNode::decode(&mut &node[..])?; if matches!(root_node, TrieNode::EmptyRoot) && proof.peek().is_some() { - return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()); + return Err(SparseStateTrieErrorKind::InvalidRootNode { path, node }.into()) } Ok(Some(root_node)) @@ -613,7 +613,7 @@ impl SparseStateTrie { path, node: alloy_rlp::encode(&root_node).into(), } - .into()); + .into()) } // Perform sanity check. @@ -622,7 +622,7 @@ impl SparseStateTrie { path, node: alloy_rlp::encode(&root_node).into(), } - .into()); + .into()) } Ok(Some(root_node)) @@ -796,7 +796,7 @@ impl SparseStateTrie { EMPTY_ROOT_HASH } } else { - return Err(SparseTrieErrorKind::Blind.into()); + return Err(SparseTrieErrorKind::Blind.into()) }; if account.is_empty() && storage_root == EMPTY_ROOT_HASH { @@ -818,7 +818,7 @@ impl SparseStateTrie { /// will be removed. pub fn update_account_storage_root(&mut self, address: B256) -> SparseStateTrieResult<()> { if !self.is_account_revealed(address) { - return Err(SparseTrieErrorKind::Blind.into()); + return Err(SparseTrieErrorKind::Blind.into()) } // Nothing to update if the account doesn't exist in the trie. @@ -828,7 +828,7 @@ impl SparseStateTrie { .transpose()? else { trace!(target: "trie::sparse", ?address, "Account not found in trie, skipping storage root update"); - return Ok(()); + return Ok(()) }; // Calculate the new storage root. If the storage trie doesn't exist, the storage root will @@ -915,7 +915,7 @@ fn filter_revealed_nodes( // If the node is already revealed, skip it. if revealed_nodes.contains(&path) { result.skipped_nodes += 1; - continue; + continue } result.new_nodes += 1; diff --git a/crates/trie/sparse/src/trie.rs b/crates/trie/sparse/src/trie.rs index 40ecec050d..e2f28c2417 100644 --- a/crates/trie/sparse/src/trie.rs +++ b/crates/trie/sparse/src/trie.rs @@ -634,7 +634,7 @@ impl

RevealedSparseTrie

{ ) -> SparseTrieResult<()> { // If the node is already revealed and it's not a hash node, do nothing. if self.nodes.get(&path).is_some_and(|node| !node.is_hash()) { - return Ok(()); + return Ok(()) } if let Some(tree_mask) = masks.tree_mask { @@ -674,8 +674,8 @@ impl

RevealedSparseTrie

{ // node. hash: Some(*hash), store_in_db_trie: Some( - masks.hash_mask.is_some_and(|mask| !mask.is_empty()) - || masks.tree_mask.is_some_and(|mask| !mask.is_empty()), + masks.hash_mask.is_some_and(|mask| !mask.is_empty()) || + masks.tree_mask.is_some_and(|mask| !mask.is_empty()), ), }); } @@ -747,9 +747,9 @@ impl

RevealedSparseTrie

{ // Left node already exists. SparseNode::Leaf { .. } => {} // All other node types can't be handled. - node @ (SparseNode::Empty - | SparseNode::Extension { .. } - | SparseNode::Branch { .. }) => { + node @ (SparseNode::Empty | + SparseNode::Extension { .. } | + SparseNode::Branch { .. }) => { return Err(SparseTrieErrorKind::Reveal { path: *entry.key(), node: Box::new(node.clone()), @@ -806,7 +806,7 @@ impl

RevealedSparseTrie

{ entry.insert(SparseNode::Hash(hash)); } } - return Ok(()); + return Ok(()) } self.reveal_node(path, TrieNode::decode(&mut &child[..])?, TrieMasks::none()) @@ -854,7 +854,7 @@ impl

RevealedSparseTrie

{ node, unset_branch_nibble: None, }); - break; + break } SparseNode::Extension { key, .. } => { #[cfg(debug_assertions)] @@ -1030,14 +1030,14 @@ impl

RevealedSparseTrie

{ SparseNode::Empty | SparseNode::Hash(_) => {} SparseNode::Leaf { key: _, hash } => { if hash.is_some() && !prefix_set.contains(&path) { - continue; + continue } targets.push((level, path)); } SparseNode::Extension { key, hash, store_in_db_trie: _ } => { if hash.is_some() && !prefix_set.contains(&path) { - continue; + continue } if level >= depth { @@ -1051,7 +1051,7 @@ impl

RevealedSparseTrie

{ } SparseNode::Branch { state_mask, hash, store_in_db_trie: _ } => { if hash.is_some() && !prefix_set.contains(&path) { - continue; + continue } if level >= depth { @@ -1196,7 +1196,7 @@ impl

RevealedSparseTrie

{ is_in_prefix_set: None, }, ]); - continue; + continue } } SparseNode::Branch { state_mask, hash, store_in_db_trie } => { @@ -1210,7 +1210,7 @@ impl

RevealedSparseTrie

{ store_in_db_trie: Some(store_in_db_trie), }, }); - continue; + continue } let retain_updates = self.updates.is_some() && prefix_set_contains(&path); @@ -1255,11 +1255,10 @@ impl

RevealedSparseTrie

{ store_in_db_trie } else { // A blinded node has the tree mask bit set - child_node_type.is_hash() - && self - .branch_node_tree_masks - .get(&path) - .is_some_and(|mask| mask.is_bit_set(last_child_nibble)) + child_node_type.is_hash() && + self.branch_node_tree_masks.get(&path).is_some_and( + |mask| mask.is_bit_set(last_child_nibble), + ) }; if should_set_tree_mask_bit { tree_mask.set_bit(last_child_nibble); @@ -1269,11 +1268,13 @@ impl

RevealedSparseTrie

{ // is a blinded node that has its hash mask bit set according to the // database, set the hash mask bit and save the hash. let hash = child.as_hash().filter(|_| { - child_node_type.is_branch() - || (child_node_type.is_hash() - && self.branch_node_hash_masks.get(&path).is_some_and( - |mask| mask.is_bit_set(last_child_nibble), - )) + child_node_type.is_branch() || + (child_node_type.is_hash() && + self.branch_node_hash_masks + .get(&path) + .is_some_and(|mask| { + mask.is_bit_set(last_child_nibble) + })) }); if let Some(hash) = hash { hash_mask.set_bit(last_child_nibble); @@ -1301,7 +1302,7 @@ impl

RevealedSparseTrie

{ is_in_prefix_set: None, }, )); - continue 'main; + continue 'main } } @@ -1340,9 +1341,8 @@ impl

RevealedSparseTrie

{ } else if self .branch_node_tree_masks .get(&path) - .is_some_and(|mask| !mask.is_empty()) - || self - .branch_node_hash_masks + .is_some_and(|mask| !mask.is_empty()) || + self.branch_node_hash_masks .get(&path) .is_some_and(|mask| !mask.is_empty()) { @@ -1354,9 +1354,8 @@ impl

RevealedSparseTrie

{ } else if self .branch_node_hash_masks .get(&path) - .is_none_or(|mask| mask.is_empty()) - && self - .branch_node_hash_masks + .is_none_or(|mask| mask.is_empty()) && + self.branch_node_hash_masks .get(&path) .is_none_or(|mask| mask.is_empty()) { @@ -1598,7 +1597,7 @@ impl RevealedSparseTrie

{ let existing = self.values.insert(path, value); if existing.is_some() { // trie structure unchanged, return immediately - return Ok(()); + return Ok(()) } let mut current = Nibbles::default(); @@ -1606,7 +1605,7 @@ impl RevealedSparseTrie

{ match node { SparseNode::Empty => { *node = SparseNode::new_leaf(path); - break; + break } &mut SparseNode::Hash(hash) => { return Err(SparseTrieErrorKind::BlindedNode { path: current, hash }.into()) @@ -1732,12 +1731,12 @@ impl RevealedSparseTrie

{ if self.values.remove(path).is_none() { if let Some(&SparseNode::Hash(hash)) = self.nodes.get(path) { // Leaf is present in the trie, but it's blinded. - return Err(SparseTrieErrorKind::BlindedNode { path: *path, hash }.into()); + return Err(SparseTrieErrorKind::BlindedNode { path: *path, hash }.into()) } trace!(target: "trie::sparse", ?path, "Leaf node is not present in the trie"); // Leaf is not present in the trie. - return Ok(()); + return Ok(()) } self.prefix_set.insert(*path); @@ -1761,7 +1760,7 @@ impl RevealedSparseTrie

{ debug_assert!(self.nodes.is_empty()); self.nodes.insert(Nibbles::default(), SparseNode::Empty); - return Ok(()); + return Ok(()) } // Walk the stack of removed nodes from the back and re-insert them back into the trie, diff --git a/crates/trie/trie/src/hashed_cursor/post_state.rs b/crates/trie/trie/src/hashed_cursor/post_state.rs index a6a89c7f5b..b6c8994e13 100644 --- a/crates/trie/trie/src/hashed_cursor/post_state.rs +++ b/crates/trie/trie/src/hashed_cursor/post_state.rs @@ -80,7 +80,7 @@ where // It's an exact match, return the account from post state without looking up in the // database. if post_state_entry.is_some_and(|entry| entry.0 == key) { - return Ok(post_state_entry); + return Ok(post_state_entry) } // It's not an exact match, reposition to the first greater or equal account that wasn't @@ -215,7 +215,7 @@ where // If database storage was wiped or it's an exact match, // return the storage slot from post state without looking up in the database. if self.storage_wiped || post_state_entry.is_some_and(|entry| entry.0 == subkey) { - return Ok(post_state_entry); + return Ok(post_state_entry) } // It's not an exact match and storage was not wiped, @@ -237,7 +237,7 @@ where // Return post state entry immediately if database was wiped. if self.storage_wiped { - return Ok(post_state_entry); + return Ok(post_state_entry) } // If post state was given precedence, move the cursor forward. diff --git a/crates/trie/trie/src/node_iter.rs b/crates/trie/trie/src/node_iter.rs index fe4c821f3d..dfb140fdf9 100644 --- a/crates/trie/trie/src/node_iter.rs +++ b/crates/trie/trie/src/node_iter.rs @@ -211,7 +211,7 @@ where *key, self.walker.hash().unwrap(), self.walker.children_are_in_trie(), - )))); + )))) } } } @@ -221,7 +221,7 @@ where // Check if the walker's key is less than the key of the current hashed entry if self.walker.key().is_some_and(|key| key < &Nibbles::unpack(hashed_key)) { self.should_check_walker_key = false; - continue; + continue } // Set the next hashed entry as a leaf node and return @@ -230,7 +230,7 @@ where #[cfg(feature = "metrics")] self.metrics.inc_leaf_nodes_returned(); - return Ok(Some(TrieElement::Leaf(hashed_key, value))); + return Ok(Some(TrieElement::Leaf(hashed_key, value))) } // Handle seeking and advancing based on the previous hashed key @@ -274,9 +274,9 @@ where // the database, so the walker will advance to the branch node after it. Because // of this, we need to check that the current walker key has a prefix of the key // that we seeked to. - if can_skip_node - && self.walker.key().is_some_and(|key| key.starts_with(&seek_prefix)) - && self.walker.children_are_in_trie() + if can_skip_node && + self.walker.key().is_some_and(|key| key.starts_with(&seek_prefix)) && + self.walker.children_are_in_trie() { trace!( target: "trie::node_iter", @@ -286,7 +286,7 @@ where ); self.should_check_walker_key = false; - continue; + continue } self.current_hashed_entry = self.seek_hashed_entry(seek_key)?; diff --git a/crates/trie/trie/src/proof/mod.rs b/crates/trie/trie/src/proof/mod.rs index 5260a7f12c..266aac19a3 100644 --- a/crates/trie/trie/src/proof/mod.rs +++ b/crates/trie/trie/src/proof/mod.rs @@ -272,7 +272,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok(StorageMultiProof::empty()); + return Ok(StorageMultiProof::empty()) } let target_nibbles = targets.into_iter().map(Nibbles::unpack).collect::>(); diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index b9d1c79787..e6f5463b7d 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -230,9 +230,9 @@ where hash_builder.add_leaf(Nibbles::unpack(hashed_address), &account_rlp); // Decide if we need to return intermediate progress. - let total_updates_len = updated_storage_nodes - + account_node_iter.walker.removed_keys_len() - + hash_builder.updates_len(); + let total_updates_len = updated_storage_nodes + + account_node_iter.walker.removed_keys_len() + + hash_builder.updates_len(); if retain_updates && total_updates_len as u64 >= self.threshold { let (walker_stack, walker_deleted_keys) = account_node_iter.walker.split(); trie_updates.removed_nodes.extend(walker_deleted_keys); @@ -249,7 +249,7 @@ where Box::new(state), hashed_entries_walked, trie_updates, - )); + )) } } } @@ -406,7 +406,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok((EMPTY_ROOT_HASH, 0, StorageTrieUpdates::deleted())); + return Ok((EMPTY_ROOT_HASH, 0, StorageTrieUpdates::deleted())) } let mut tracker = TrieTracker::default(); diff --git a/crates/trie/trie/src/trie_cursor/in_memory.rs b/crates/trie/trie/src/trie_cursor/in_memory.rs index dda2d60621..4925dc8a66 100644 --- a/crates/trie/trie/src/trie_cursor/in_memory.rs +++ b/crates/trie/trie/src/trie_cursor/in_memory.rs @@ -79,7 +79,7 @@ impl<'a, C: TrieCursor> InMemoryAccountTrieCursor<'a, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.seek(&key); if in_memory.as_ref().is_some_and(|entry| entry.0 == key) { - return Ok(in_memory); + return Ok(in_memory) } // Reposition the cursor to the first greater or equal node that wasn't removed. @@ -203,7 +203,7 @@ impl InMemoryStorageTrieCursor<'_, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.seek(&key)); if self.storage_trie_cleared || in_memory.as_ref().is_some_and(|entry| entry.0 == key) { - return Ok(in_memory.filter(|(nibbles, _)| !exact || nibbles == &key)); + return Ok(in_memory.filter(|(nibbles, _)| !exact || nibbles == &key)) } // Reposition the cursor to the first greater or equal node that wasn't removed. @@ -227,7 +227,7 @@ impl InMemoryStorageTrieCursor<'_, C> { ) -> Result, DatabaseError> { let in_memory = self.in_memory_cursor.as_mut().and_then(|c| c.first_after(&last)); if self.storage_trie_cleared { - return Ok(in_memory); + return Ok(in_memory) } // Reposition the cursor to the first greater or equal node that wasn't removed. diff --git a/crates/trie/trie/src/walker.rs b/crates/trie/trie/src/walker.rs index e07261a416..5bbedb2353 100644 --- a/crates/trie/trie/src/walker.rs +++ b/crates/trie/trie/src/walker.rs @@ -265,7 +265,7 @@ impl TrieWalker { let Some((key, node)) = self.node(false)? else { // If no next node is found, clear the stack. self.stack.clear(); - return Ok(()); + return Ok(()) }; // Overwrite the root node's first nibble @@ -284,7 +284,7 @@ impl TrieWalker { #[cfg(feature = "metrics")] self.metrics.inc_out_of_order_subnode(1); self.move_to_next_sibling(false)?; - return Ok(()); + return Ok(()) } } @@ -315,18 +315,18 @@ impl TrieWalker { // Check if the walker needs to backtrack to the previous level in the trie during its // traversal. - if subnode.position().is_last_child() - || (subnode.position().is_parent() && !allow_root_to_child_nibble) + if subnode.position().is_last_child() || + (subnode.position().is_parent() && !allow_root_to_child_nibble) { self.stack.pop(); self.move_to_next_sibling(false)?; - return Ok(()); + return Ok(()) } subnode.inc_nibble(); if subnode.node.is_none() { - return self.consume_node(); + return self.consume_node() } // Find the next sibling with state. @@ -334,11 +334,11 @@ impl TrieWalker { let position = subnode.position(); if subnode.state_flag() { trace!(target: "trie::walker", ?position, "found next sibling with state"); - return Ok(()); + return Ok(()) } if position.is_last_child() { trace!(target: "trie::walker", ?position, "checked all siblings"); - break; + break } subnode.inc_nibble(); } diff --git a/crates/trie/trie/src/witness.rs b/crates/trie/trie/src/witness.rs index be2a241259..ce40a01e1c 100644 --- a/crates/trie/trie/src/witness.rs +++ b/crates/trie/trie/src/witness.rs @@ -106,7 +106,7 @@ where pub fn compute(mut self, state: HashedPostState) -> Result, TrieWitnessError> { let is_state_empty = state.is_empty(); if is_state_empty && !self.always_include_root_node { - return Ok(Default::default()); + return Ok(Default::default()) } let proof_targets = if is_state_empty { @@ -129,7 +129,7 @@ where } else { (EMPTY_ROOT_HASH, Bytes::from([EMPTY_STRING_CODE])) }; - return Ok(B256Map::from_iter([(root_hash, root_node)])); + return Ok(B256Map::from_iter([(root_hash, root_node)])) } // Record all nodes from multiproof in the witness diff --git a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs index cf53972357..9bbb198ae1 100644 --- a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs +++ b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs @@ -110,7 +110,7 @@ where let mut actions_to_queue: Vec = Vec::new(); if txs.is_empty() { - return; + return } match self.pool.get_all_blobs_exact(txs.iter().map(|(tx, _)| *tx.tx_hash()).collect()) { @@ -168,7 +168,7 @@ where // Request locally first, otherwise request from CL loop { if let Some(mined_sidecar) = this.queued_actions.pop_front() { - return Poll::Ready(Some(Ok(mined_sidecar))); + return Poll::Ready(Some(Ok(mined_sidecar))) } // Check if any pending requests are ready and append to buffer @@ -253,7 +253,7 @@ async fn fetch_blobs_for_block( response.status().as_u16(), "Unhandled HTTP status.".to_string(), )), - }; + } } let bytes = match response.bytes().await { diff --git a/examples/custom-engine-types/src/main.rs b/examples/custom-engine-types/src/main.rs index 59fe91b5ad..ae42090d21 100644 --- a/examples/custom-engine-types/src/main.rs +++ b/examples/custom-engine-types/src/main.rs @@ -237,7 +237,7 @@ where if attributes.custom == 0 { return Err(EngineObjectValidationError::invalid_params( CustomError::CustomFieldIsNotZero, - )); + )) } Ok(()) diff --git a/examples/custom-node/src/engine.rs b/examples/custom-node/src/engine.rs index 077ecdd4eb..e3bc6019d7 100644 --- a/examples/custom-node/src/engine.rs +++ b/examples/custom-node/src/engine.rs @@ -270,7 +270,7 @@ where if attributes.extension == 0 { return Err(EngineObjectValidationError::invalid_params( CustomError::CustomFieldIsNotZero, - )); + )) } Ok(()) diff --git a/examples/custom-node/src/primitives/tx_custom.rs b/examples/custom-node/src/primitives/tx_custom.rs index 7c7bceaae4..8729378bd5 100644 --- a/examples/custom-node/src/primitives/tx_custom.rs +++ b/examples/custom-node/src/primitives/tx_custom.rs @@ -92,13 +92,13 @@ impl TxPayment { impl RlpEcdsaEncodableTx for TxPayment { /// Outputs the length of the transaction's fields, without a RLP header. fn rlp_encoded_fields_length(&self) -> usize { - self.chain_id.length() - + self.nonce.length() - + self.max_priority_fee_per_gas.length() - + self.max_fee_per_gas.length() - + self.gas_limit.length() - + self.to.length() - + self.value.length() + self.chain_id.length() + + self.nonce.length() + + self.max_priority_fee_per_gas.length() + + self.max_fee_per_gas.length() + + self.gas_limit.length() + + self.to.length() + + self.value.length() } /// Encodes only the transaction's fields into the desired buffer, without diff --git a/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs b/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs index 4a83ffe9f9..7fd8ac7f44 100644 --- a/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs +++ b/examples/custom-rlpx-subprotocol/src/subprotocol/connection/mod.rs @@ -35,7 +35,7 @@ impl Stream for CustomRlpxConnection { fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let this = self.get_mut(); if let Some(initial_ping) = this.initial_ping.take() { - return Poll::Ready(Some(initial_ping.encoded())); + return Poll::Ready(Some(initial_ping.encoded())) } loop { @@ -45,13 +45,13 @@ impl Stream for CustomRlpxConnection { this.pending_pong = Some(response); Poll::Ready(Some(CustomRlpxProtoMessage::ping_message(msg).encoded())) } - }; + } } let Some(msg) = ready!(this.conn.poll_next_unpin(cx)) else { return Poll::Ready(None) }; let Some(msg) = CustomRlpxProtoMessage::decode_message(&mut &msg[..]) else { - return Poll::Ready(None); + return Poll::Ready(None) }; match msg.message { @@ -66,11 +66,11 @@ impl Stream for CustomRlpxConnection { if let Some(sender) = this.pending_pong.take() { sender.send(msg).ok(); } - continue; + continue } } - return Poll::Pending; + return Poll::Pending } } } diff --git a/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs b/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs index 2cb225e091..495c435782 100644 --- a/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs +++ b/examples/custom-rlpx-subprotocol/src/subprotocol/protocol/proto.rs @@ -75,8 +75,8 @@ impl CustomRlpxProtoMessage { buf.put_u8(self.message_type as u8); match &self.message { CustomRlpxProtoMessageKind::Ping | CustomRlpxProtoMessageKind::Pong => {} - CustomRlpxProtoMessageKind::PingMessage(msg) - | CustomRlpxProtoMessageKind::PongMessage(msg) => { + CustomRlpxProtoMessageKind::PingMessage(msg) | + CustomRlpxProtoMessageKind::PongMessage(msg) => { buf.put(msg.as_bytes()); } } @@ -86,7 +86,7 @@ impl CustomRlpxProtoMessage { /// Decodes a `CustomRlpxProtoMessage` from the given message buffer. pub fn decode_message(buf: &mut &[u8]) -> Option { if buf.is_empty() { - return None; + return None } let id = buf[0]; buf.advance(1); diff --git a/examples/manual-p2p/src/main.rs b/examples/manual-p2p/src/main.rs index 366e95e8c5..edd5ade245 100644 --- a/examples/manual-p2p/src/main.rs +++ b/examples/manual-p2p/src/main.rs @@ -54,14 +54,14 @@ async fn main() -> eyre::Result<()> { if let DiscoveryUpdate::Added(peer) = update { // Boot nodes hard at work, lets not disturb them if MAINNET_BOOT_NODES.contains(&peer) { - return; + return } let (p2p_stream, their_hello) = match handshake_p2p(peer, our_key).await { Ok(s) => s, Err(e) => { println!("Failed P2P handshake with peer {}, {}", peer.address, e); - return; + return } }; @@ -69,7 +69,7 @@ async fn main() -> eyre::Result<()> { Ok(s) => s, Err(e) => { println!("Failed ETH handshake with peer {}, {}", peer.address, e); - return; + return } }; diff --git a/examples/node-custom-rpc/src/main.rs b/examples/node-custom-rpc/src/main.rs index bda1cc90cf..9aba7c9922 100644 --- a/examples/node-custom-rpc/src/main.rs +++ b/examples/node-custom-rpc/src/main.rs @@ -35,7 +35,7 @@ fn main() { .node(EthereumNode::default()) .extend_rpc_modules(move |ctx| { if !args.enable_ext { - return Ok(()); + return Ok(()) } // here we get the configured pool. diff --git a/examples/precompile-cache/src/main.rs b/examples/precompile-cache/src/main.rs index 2b68c5f752..e72fee598c 100644 --- a/examples/precompile-cache/src/main.rs +++ b/examples/precompile-cache/src/main.rs @@ -129,7 +129,7 @@ impl Precompile for WrappedPrecompile { // get the result if it exists if let Some(result) = cache.cache.get(&key) { - return result.clone(); + return result.clone() } // call the precompile if cache miss diff --git a/testing/ef-tests/src/cases/blockchain_test.rs b/testing/ef-tests/src/cases/blockchain_test.rs index c9724fe24e..4c463c612a 100644 --- a/testing/ef-tests/src/cases/blockchain_test.rs +++ b/testing/ef-tests/src/cases/blockchain_test.rs @@ -58,12 +58,12 @@ impl BlockchainTestCase { const fn excluded_fork(network: ForkSpec) -> bool { matches!( network, - ForkSpec::ByzantiumToConstantinopleAt5 - | ForkSpec::Constantinople - | ForkSpec::ConstantinopleFix - | ForkSpec::MergeEOF - | ForkSpec::MergeMeterInitCode - | ForkSpec::MergePush0 + ForkSpec::ByzantiumToConstantinopleAt5 | + ForkSpec::Constantinople | + ForkSpec::ConstantinopleFix | + ForkSpec::MergeEOF | + ForkSpec::MergeMeterInitCode | + ForkSpec::MergePush0 ) } @@ -157,7 +157,7 @@ impl Case for BlockchainTestCase { fn run(&self) -> Result<(), Error> { // If the test is marked for skipping, return a Skipped error immediately. if self.skip { - return Err(Error::Skipped); + return Err(Error::Skipped) } // Iterate through test cases, filtering by the network type to exclude specific forks. @@ -283,7 +283,7 @@ fn run_case(case: &BlockchainTest) -> Result<(), Error> { return Err(Error::block_failed( block_number, Error::Assertion("state root mismatch".to_string()), - )); + )) } // Commit the post state/state diff to the database diff --git a/testing/ef-tests/src/models.rs b/testing/ef-tests/src/models.rs index 26a5492669..6cad5331e5 100644 --- a/testing/ef-tests/src/models.rs +++ b/testing/ef-tests/src/models.rs @@ -243,12 +243,12 @@ impl Account { } else { return Err(Error::Assertion(format!( "Slot {slot:?} is missing from the database. Expected {value:?}" - ))); + ))) } } else { return Err(Error::Assertion(format!( "Slot {slot:?} is missing from the database. Expected {value:?}" - ))); + ))) } } @@ -325,17 +325,17 @@ impl From for ChainSpec { spec_builder.tangerine_whistle_activated() } ForkSpec::EIP158 => spec_builder.spurious_dragon_activated(), - ForkSpec::Byzantium - | ForkSpec::EIP158ToByzantiumAt5 - | ForkSpec::ConstantinopleFix - | ForkSpec::ByzantiumToConstantinopleFixAt5 => spec_builder.byzantium_activated(), + ForkSpec::Byzantium | + ForkSpec::EIP158ToByzantiumAt5 | + ForkSpec::ConstantinopleFix | + ForkSpec::ByzantiumToConstantinopleFixAt5 => spec_builder.byzantium_activated(), ForkSpec::Istanbul => spec_builder.istanbul_activated(), ForkSpec::Berlin => spec_builder.berlin_activated(), ForkSpec::London | ForkSpec::BerlinToLondonAt5 => spec_builder.london_activated(), - ForkSpec::Merge - | ForkSpec::MergeEOF - | ForkSpec::MergeMeterInitCode - | ForkSpec::MergePush0 => spec_builder.paris_activated(), + ForkSpec::Merge | + ForkSpec::MergeEOF | + ForkSpec::MergeMeterInitCode | + ForkSpec::MergePush0 => spec_builder.paris_activated(), ForkSpec::Shanghai => spec_builder.shanghai_activated(), ForkSpec::Cancun => spec_builder.cancun_activated(), ForkSpec::ByzantiumToConstantinopleAt5 | ForkSpec::Constantinople => { diff --git a/testing/testing-utils/src/generators.rs b/testing/testing-utils/src/generators.rs index a9b28cf6ce..793448cdba 100644 --- a/testing/testing-utils/src/generators.rs +++ b/testing/testing-utils/src/generators.rs @@ -345,7 +345,7 @@ where let old = if entry.value.is_zero() { let old = storage.remove(&entry.key); if matches!(old, Some(U256::ZERO)) { - return None; + return None } old } else { From ace20b28d95c4ff732d83f9b18fc76917f378faa Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:22:32 +0800 Subject: [PATCH 09/18] fix: ci not found HeaderProvider --- crates/rpc/rpc-eth-types/src/gas_oracle.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/rpc/rpc-eth-types/src/gas_oracle.rs b/crates/rpc/rpc-eth-types/src/gas_oracle.rs index 798a146e61..795363f3df 100644 --- a/crates/rpc/rpc-eth-types/src/gas_oracle.rs +++ b/crates/rpc/rpc-eth-types/src/gas_oracle.rs @@ -128,7 +128,7 @@ where /// Suggests a gas price estimate based on recent blocks, using the configured percentile. pub async fn suggest_tip_cap(&self) -> EthResult { - let header: reth_primitives_traits::SealedHeader<::Header> = self + let header = self .provider .sealed_header_by_number_or_tag(BlockNumberOrTag::Latest)? .ok_or(EthApiError::HeaderNotFound(BlockId::latest()))?; From 1fe8809e13824c86cf98e1f467e1c8e37450dc5e Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:24:32 +0800 Subject: [PATCH 10/18] fix: ci not found try_into_scroll_tx_info --- crates/scroll/rpc/src/eth/transaction.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 07a7fbb569..d3a43582b6 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -13,7 +13,7 @@ use reth_provider::{ }; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, + try_into_scroll_tx_info, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; From 4572e311c4cb310ba6e8cf1a4732eeea3d5d71a4 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:29:02 +0800 Subject: [PATCH 11/18] fix: ci fmt --- crates/scroll/rpc/src/error.rs | 2 +- crates/scroll/rpc/src/eth/transaction.rs | 12 ++++++------ crates/scroll/rpc/src/lib.rs | 2 +- crates/scroll/rpc/src/sequencer.rs | 10 ++-------- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/crates/scroll/rpc/src/error.rs b/crates/scroll/rpc/src/error.rs index 23ad2a9466..5471ccf1c8 100644 --- a/crates/scroll/rpc/src/error.rs +++ b/crates/scroll/rpc/src/error.rs @@ -3,7 +3,7 @@ use alloy_json_rpc::ErrorPayload; use alloy_rpc_types_eth::BlockError; use alloy_transport::{RpcError, TransportErrorKind}; -use jsonrpsee_types::error::{INTERNAL_ERROR_CODE}; +use jsonrpsee_types::error::INTERNAL_ERROR_CODE; use reth_evm::execute::ProviderError; use reth_rpc_convert::transaction::EthTxEnvError; use reth_rpc_eth_api::{AsEthApiError, TransactionConversionError}; diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index d3a43582b6..286b7c709e 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -13,8 +13,8 @@ use reth_provider::{ }; use reth_rpc_eth_api::{ helpers::{EthSigner, EthTransactions, LoadTransaction, SpawnBlocking}, - try_into_scroll_tx_info, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, RpcNodeCoreExt, - TxInfoMapper, + try_into_scroll_tx_info, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcNodeCore, + RpcNodeCoreExt, TxInfoMapper, }; use reth_rpc_eth_types::utils::recover_raw_transaction; use reth_scroll_primitives::ScrollReceipt; @@ -45,16 +45,16 @@ where // blocks that it builds. if let Some(client) = self.raw_tx_forwarder().as_ref() { tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); - + // Retain tx in local tx pool before forwarding to sequencer rpc, for local RPC usage. let hash = self .pool() .add_transaction(TransactionOrigin::Local, pool_transaction.clone()) .await .map_err(Self::Error::from_eth_err)?; - + tracing::debug!(target: "rpc::eth", %hash, "successfully added transaction to local tx pool"); - + // Forward to remote sequencer RPC. match client.forward_raw_transaction(&tx).await { Ok(sequencer_hash) => { @@ -64,7 +64,7 @@ where tracing::warn!(target: "rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); } } - + return Ok(hash); } diff --git a/crates/scroll/rpc/src/lib.rs b/crates/scroll/rpc/src/lib.rs index 116bc181c8..76ecfbec7b 100644 --- a/crates/scroll/rpc/src/lib.rs +++ b/crates/scroll/rpc/src/lib.rs @@ -14,4 +14,4 @@ pub mod sequencer; pub use error::{ScrollEthApiError, SequencerClientError}; pub use eth::{ScrollEthApi, ScrollReceiptBuilder}; -pub use sequencer::SequencerClient; \ No newline at end of file +pub use sequencer::SequencerClient; diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs index 5c7c5e610c..094840f99e 100644 --- a/crates/scroll/rpc/src/sequencer.rs +++ b/crates/scroll/rpc/src/sequencer.rs @@ -155,10 +155,7 @@ mod tests { let request = client .client() - .make_request( - "eth_sendRawTransaction", - format!("0x{}", hex::encode("abcd")), - ) + .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) .serialize() .unwrap() .take_request(); @@ -190,10 +187,7 @@ mod tests { let request = client .client() - .make_request( - "eth_sendRawTransaction", - format!("0x{}", hex::encode("abcd")), - ) + .make_request("eth_sendRawTransaction", format!("0x{}", hex::encode("abcd"))) .serialize() .unwrap() .take_request(); From 8ded93c468c6958be3ff4cdf6422396549f75292 Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 17:33:18 +0800 Subject: [PATCH 12/18] fix: ci clippy --- Cargo.lock | 1 - bin/reth/Cargo.toml | 1 - 2 files changed, 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e42c28cc4f..7b7a8f7ed3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7232,7 +7232,6 @@ name = "reth" version = "1.5.0" dependencies = [ "alloy-rpc-types", - "alloy-transport", "aquamarine", "backon", "clap", diff --git a/bin/reth/Cargo.toml b/bin/reth/Cargo.toml index f312a170a6..fb94025003 100644 --- a/bin/reth/Cargo.toml +++ b/bin/reth/Cargo.toml @@ -61,7 +61,6 @@ tokio = { workspace = true, features = ["sync", "macros", "time", "rt-multi-thre aquamarine.workspace = true clap = { workspace = true, features = ["derive", "env"] } eyre.workspace = true -alloy-transport.workspace = true [dev-dependencies] backon.workspace = true From 499e9ae7e9bc4b63f72a25d2d48bab5c0e15a51d Mon Sep 17 00:00:00 2001 From: Morty Date: Thu, 17 Jul 2025 20:23:18 +0800 Subject: [PATCH 13/18] feat: enable override pool propagate_local_transactions --- crates/node/builder/src/components/pool.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/node/builder/src/components/pool.rs b/crates/node/builder/src/components/pool.rs index 2d431831ee..1bf56e17ca 100644 --- a/crates/node/builder/src/components/pool.rs +++ b/crates/node/builder/src/components/pool.rs @@ -61,6 +61,8 @@ pub struct PoolBuilderConfigOverrides { pub minimal_protocol_basefee: Option, /// Addresses that will be considered as local. Above exemptions apply. pub local_addresses: HashSet

, + /// Whether to propagate local transactions to the network. + pub propagate_local_transactions: bool, /// Additional tasks to validate new transactions. pub additional_validation_tasks: Option, } @@ -76,6 +78,7 @@ impl PoolBuilderConfigOverrides { max_account_slots, minimal_protocol_basefee, local_addresses, + propagate_local_transactions, additional_validation_tasks: _, } = self; @@ -98,6 +101,8 @@ impl PoolBuilderConfigOverrides { config.minimal_protocol_basefee = minimal_protocol_basefee; } config.local_transactions_config.local_addresses.extend(local_addresses); + config.local_transactions_config.propagate_local_transactions = + propagate_local_transactions; config } From 9c750c0577b5fa4fb2f2f4b002a26010f4ad8c75 Mon Sep 17 00:00:00 2001 From: Morty Date: Fri, 25 Jul 2025 18:37:39 +0800 Subject: [PATCH 14/18] fix: EthTransactionValidatorBuilder accepts custom local_transactions_config --- crates/ethereum/node/src/node.rs | 2 +- crates/optimism/node/src/node.rs | 2 +- crates/optimism/txpool/src/transaction.rs | 2 +- crates/scroll/node/src/builder/pool.rs | 2 +- crates/scroll/txpool/src/transaction.rs | 2 +- crates/transaction-pool/src/maintain.rs | 2 +- crates/transaction-pool/src/validate/eth.rs | 14 +++++++------- crates/transaction-pool/src/validate/task.rs | 11 ++++------- examples/custom-node-components/src/main.rs | 2 +- 9 files changed, 18 insertions(+), 21 deletions(-) diff --git a/crates/ethereum/node/src/node.rs b/crates/ethereum/node/src/node.rs index 02ebacdb7d..4dc086098a 100644 --- a/crates/ethereum/node/src/node.rs +++ b/crates/ethereum/node/src/node.rs @@ -405,7 +405,7 @@ where let blob_store = reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), Some(pool_config.local_transactions_config.clone())) .with_head_timestamp(ctx.head().timestamp) .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) .kzg_settings(ctx.kzg_settings()?) diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 2d33f05f4a..b192f8cd7e 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -800,7 +800,7 @@ where .await; let blob_store = reth_node_builder::components::create_blob_store(ctx)?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) .no_eip4844() .with_head_timestamp(ctx.head().timestamp) .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) diff --git a/crates/optimism/txpool/src/transaction.rs b/crates/optimism/txpool/src/transaction.rs index 6cbc645fe5..b0f3c38a1d 100644 --- a/crates/optimism/txpool/src/transaction.rs +++ b/crates/optimism/txpool/src/transaction.rs @@ -325,7 +325,7 @@ mod tests { #[tokio::test] async fn validate_optimism_transaction() { let client = MockEthProvider::default().with_chain_spec(OP_MAINNET.clone()); - let validator = EthTransactionValidatorBuilder::new(client) + let validator = EthTransactionValidatorBuilder::new(client, None) .no_shanghai() .no_cancun() .build(InMemoryBlobStore::default()); diff --git a/crates/scroll/node/src/builder/pool.rs b/crates/scroll/node/src/builder/pool.rs index bc8034ceb6..205c84b2f4 100644 --- a/crates/scroll/node/src/builder/pool.rs +++ b/crates/scroll/node/src/builder/pool.rs @@ -61,7 +61,7 @@ where let data_dir = ctx.config().datadir(); let blob_store = DiskFileBlobStore::open(data_dir.blobstore(), Default::default())?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), Some(pool_config_overrides.clone().apply(ctx.pool_config()).local_transactions_config)) .no_eip4844() .with_head_timestamp(ctx.head().timestamp) .kzg_settings(ctx.kzg_settings()?) diff --git a/crates/scroll/txpool/src/transaction.rs b/crates/scroll/txpool/src/transaction.rs index bee3096194..07513192c8 100644 --- a/crates/scroll/txpool/src/transaction.rs +++ b/crates/scroll/txpool/src/transaction.rs @@ -226,7 +226,7 @@ mod tests { #[test] fn validate_scroll_transaction() { let client = MockEthProvider::default().with_chain_spec(SCROLL_MAINNET.clone()); - let validator = EthTransactionValidatorBuilder::new(client) + let validator = EthTransactionValidatorBuilder::new(client, None) .no_shanghai() .no_cancun() .build(InMemoryBlobStore::default()); diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index fff0100625..a6a4df8c5c 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -776,7 +776,7 @@ mod tests { let sender = hex!("1f9090aaE28b8a3dCeaDf281B0F12828e676c326").into(); provider.add_account(sender, ExtendedAccount::new(42, U256::MAX)); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider).build(blob_store.clone()); + let validator = EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); let txpool = Pool::new( validator.clone(), diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index 90a61b86ec..c9865202fe 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -785,14 +785,14 @@ impl EthTransactionValidatorBuilder { /// - EIP-1559 /// - EIP-4844 /// - EIP-7702 - pub fn new(client: Client) -> Self { + pub fn new(client: Client, local_transactions_config: Option) -> Self { Self { block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M.into(), client, minimum_priority_fee: None, additional_tasks: 1, kzg_settings: EnvKzgSettings::Default, - local_transactions_config: Default::default(), + local_transactions_config: local_transactions_config.unwrap_or_default(), max_tx_input_bytes: DEFAULT_MAX_TX_INPUT_BYTES, tx_fee_cap: Some(1e18 as u128), // by default all transaction types are allowed @@ -1201,7 +1201,7 @@ mod tests { ExtendedAccount::new(transaction.nonce(), U256::MAX), ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider).build(blob_store.clone()); + let validator = EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone()); @@ -1228,7 +1228,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider) + let validator = EthTransactionValidatorBuilder::new(provider, None) .set_block_gas_limit(1_000_000) // tx gas limit is 1_015_288 .build(blob_store.clone()); @@ -1261,7 +1261,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider) + let validator = EthTransactionValidatorBuilder::new(provider, None) .set_tx_fee_cap(100) // 100 wei cap .build(blob_store.clone()); @@ -1298,7 +1298,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider) + let validator = EthTransactionValidatorBuilder::new(provider, None) .set_tx_fee_cap(0) // no cap .build(blob_store); @@ -1316,7 +1316,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider) + let validator = EthTransactionValidatorBuilder::new(provider, None) .set_tx_fee_cap(2e18 as u128) // 2 ETH cap .build(blob_store); diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index 7e417681fe..9bfa4faae2 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -1,10 +1,7 @@ //! A validation service for transactions. use crate::{ - blobstore::BlobStore, - validate::{EthTransactionValidatorBuilder, TransactionValidatorError}, - EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, - TransactionValidator, + blobstore::BlobStore, validate::{EthTransactionValidatorBuilder, TransactionValidatorError}, EthTransactionValidator, LocalTransactionConfig, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator }; use futures_util::{lock::Mutex, StreamExt}; use reth_primitives_traits::{Block, SealedBlock}; @@ -90,8 +87,8 @@ pub struct TransactionValidationTaskExecutor { impl TransactionValidationTaskExecutor<()> { /// Convenience method to create a [`EthTransactionValidatorBuilder`] - pub fn eth_builder(client: Client) -> EthTransactionValidatorBuilder { - EthTransactionValidatorBuilder::new(client) + pub fn eth_builder(client: Client, local_transactions_config: Option) -> EthTransactionValidatorBuilder { + EthTransactionValidatorBuilder::new(client, local_transactions_config) } } @@ -138,7 +135,7 @@ impl TransactionValidationTaskExecutor(tasks, blob_store) } diff --git a/examples/custom-node-components/src/main.rs b/examples/custom-node-components/src/main.rs index c4e571762e..a11d04a6bf 100644 --- a/examples/custom-node-components/src/main.rs +++ b/examples/custom-node-components/src/main.rs @@ -58,7 +58,7 @@ where async fn build_pool(self, ctx: &BuilderContext) -> eyre::Result { let data_dir = ctx.config().datadir(); let blob_store = InMemoryBlobStore::default(); - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) .with_head_timestamp(ctx.head().timestamp) .kzg_settings(ctx.kzg_settings()?) .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) From b115563b84aa0382485f588c3a31b2f4ed40bc70 Mon Sep 17 00:00:00 2001 From: Morty Date: Fri, 25 Jul 2025 22:09:54 +0800 Subject: [PATCH 15/18] fix: remove propagate_local_transactions --- crates/node/builder/src/components/pool.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/node/builder/src/components/pool.rs b/crates/node/builder/src/components/pool.rs index 3b625b3622..04b8c4b1bd 100644 --- a/crates/node/builder/src/components/pool.rs +++ b/crates/node/builder/src/components/pool.rs @@ -102,8 +102,6 @@ impl PoolBuilderConfigOverrides { config.minimal_protocol_basefee = minimal_protocol_basefee; } config.local_transactions_config.local_addresses.extend(local_addresses); - config.local_transactions_config.propagate_local_transactions = - propagate_local_transactions; config } From a876be3e33bc7a4992e812f74075d4df15f29961 Mon Sep 17 00:00:00 2001 From: Morty Date: Fri, 25 Jul 2025 22:41:03 +0800 Subject: [PATCH 16/18] fix: ci --- .../ethereum/cli/src/debug_cmd/build_block.rs | 2 +- crates/ethereum/node/src/node.rs | 19 +++++---- crates/node/builder/src/components/pool.rs | 3 -- crates/optimism/node/src/node.rs | 39 ++++++++++--------- crates/scroll/node/src/builder/pool.rs | 35 +++++++++-------- crates/transaction-pool/src/maintain.rs | 3 +- crates/transaction-pool/src/validate/eth.rs | 3 +- crates/transaction-pool/src/validate/task.rs | 10 ++++- examples/custom-node-components/src/main.rs | 11 +++--- 9 files changed, 69 insertions(+), 56 deletions(-) diff --git a/crates/ethereum/cli/src/debug_cmd/build_block.rs b/crates/ethereum/cli/src/debug_cmd/build_block.rs index 22260f7e33..3c5d37bd8e 100644 --- a/crates/ethereum/cli/src/debug_cmd/build_block.rs +++ b/crates/ethereum/cli/src/debug_cmd/build_block.rs @@ -116,7 +116,7 @@ impl> Command { let blockchain_db = BlockchainProvider::new(provider_factory.clone())?; let blob_store = InMemoryBlobStore::default(); - let validator = TransactionValidationTaskExecutor::eth_builder(blockchain_db.clone()) + let validator = TransactionValidationTaskExecutor::eth_builder(blockchain_db.clone(), None) .with_head_timestamp(best_block.timestamp) .kzg_settings(self.kzg_settings()?) .with_additional_tasks(1) diff --git a/crates/ethereum/node/src/node.rs b/crates/ethereum/node/src/node.rs index 4dc086098a..2bf171a3cc 100644 --- a/crates/ethereum/node/src/node.rs +++ b/crates/ethereum/node/src/node.rs @@ -405,14 +405,17 @@ where let blob_store = reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), Some(pool_config.local_transactions_config.clone())) - .with_head_timestamp(ctx.head().timestamp) - .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) - .kzg_settings(ctx.kzg_settings()?) - .with_local_transactions_config(pool_config.local_transactions_config.clone()) - .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) - .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); + let validator = TransactionValidationTaskExecutor::eth_builder( + ctx.provider().clone(), + Some(pool_config.local_transactions_config.clone()), + ) + .with_head_timestamp(ctx.head().timestamp) + .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) + .kzg_settings(ctx.kzg_settings()?) + .with_local_transactions_config(pool_config.local_transactions_config.clone()) + .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) + .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); let transaction_pool = TxPoolBuilder::new(ctx) .with_validator(validator) diff --git a/crates/node/builder/src/components/pool.rs b/crates/node/builder/src/components/pool.rs index 04b8c4b1bd..c12de25a3a 100644 --- a/crates/node/builder/src/components/pool.rs +++ b/crates/node/builder/src/components/pool.rs @@ -62,8 +62,6 @@ pub struct PoolBuilderConfigOverrides { pub minimal_protocol_basefee: Option, /// Addresses that will be considered as local. Above exemptions apply. pub local_addresses: HashSet
, - /// Whether to propagate local transactions to the network. - pub propagate_local_transactions: bool, /// Additional tasks to validate new transactions. pub additional_validation_tasks: Option, } @@ -79,7 +77,6 @@ impl PoolBuilderConfigOverrides { max_account_slots, minimal_protocol_basefee, local_addresses, - propagate_local_transactions, additional_validation_tasks: _, } = self; diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index b192f8cd7e..299a598633 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -800,25 +800,26 @@ where .await; let blob_store = reth_node_builder::components::create_blob_store(ctx)?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) - .no_eip4844() - .with_head_timestamp(ctx.head().timestamp) - .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) - .kzg_settings(ctx.kzg_settings()?) - .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) - .with_additional_tasks( - pool_config_overrides - .additional_validation_tasks - .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), - ) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) - .map(|validator| { - OpTransactionValidator::new(validator) - // In --dev mode we can't require gas fees because we're unable to decode - // the L1 block info - .require_l1_data_gas_fee(!ctx.config().dev.dev) - .with_supervisor(supervisor_client.clone()) - }); + let validator = + TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) + .no_eip4844() + .with_head_timestamp(ctx.head().timestamp) + .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) + .kzg_settings(ctx.kzg_settings()?) + .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) + .with_additional_tasks( + pool_config_overrides + .additional_validation_tasks + .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), + ) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) + .map(|validator| { + OpTransactionValidator::new(validator) + // In --dev mode we can't require gas fees because we're unable to decode + // the L1 block info + .require_l1_data_gas_fee(!ctx.config().dev.dev) + .with_supervisor(supervisor_client.clone()) + }); let final_pool_config = pool_config_overrides.apply(ctx.pool_config()); diff --git a/crates/scroll/node/src/builder/pool.rs b/crates/scroll/node/src/builder/pool.rs index 205c84b2f4..5eb4bfa2e3 100644 --- a/crates/scroll/node/src/builder/pool.rs +++ b/crates/scroll/node/src/builder/pool.rs @@ -61,22 +61,25 @@ where let data_dir = ctx.config().datadir(); let blob_store = DiskFileBlobStore::open(data_dir.blobstore(), Default::default())?; - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), Some(pool_config_overrides.clone().apply(ctx.pool_config()).local_transactions_config)) - .no_eip4844() - .with_head_timestamp(ctx.head().timestamp) - .kzg_settings(ctx.kzg_settings()?) - .with_additional_tasks( - pool_config_overrides - .additional_validation_tasks - .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), - ) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) - .map(|validator| { - ScrollTransactionValidator::new(validator) - // In --dev mode we can't require gas fees because we're unable to decode - // the L1 block info - .require_l1_data_gas_fee(!ctx.config().dev.dev) - }); + let validator = TransactionValidationTaskExecutor::eth_builder( + ctx.provider().clone(), + Some(pool_config_overrides.clone().apply(ctx.pool_config()).local_transactions_config), + ) + .no_eip4844() + .with_head_timestamp(ctx.head().timestamp) + .kzg_settings(ctx.kzg_settings()?) + .with_additional_tasks( + pool_config_overrides + .additional_validation_tasks + .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), + ) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) + .map(|validator| { + ScrollTransactionValidator::new(validator) + // In --dev mode we can't require gas fees because we're unable to decode + // the L1 block info + .require_l1_data_gas_fee(!ctx.config().dev.dev) + }); let transaction_pool = reth_transaction_pool::Pool::new( validator, diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index a6a4df8c5c..5b3943e831 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -776,7 +776,8 @@ mod tests { let sender = hex!("1f9090aaE28b8a3dCeaDf281B0F12828e676c326").into(); provider.add_account(sender, ExtendedAccount::new(42, U256::MAX)); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); + let validator = + EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); let txpool = Pool::new( validator.clone(), diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index c9865202fe..d4a93b591d 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -1201,7 +1201,8 @@ mod tests { ExtendedAccount::new(transaction.nonce(), U256::MAX), ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); + let validator = + EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone()); diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index 9bfa4faae2..e0446d7310 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -1,7 +1,10 @@ //! A validation service for transactions. use crate::{ - blobstore::BlobStore, validate::{EthTransactionValidatorBuilder, TransactionValidatorError}, EthTransactionValidator, LocalTransactionConfig, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, TransactionValidator + blobstore::BlobStore, + validate::{EthTransactionValidatorBuilder, TransactionValidatorError}, + EthTransactionValidator, LocalTransactionConfig, PoolTransaction, TransactionOrigin, + TransactionValidationOutcome, TransactionValidator, }; use futures_util::{lock::Mutex, StreamExt}; use reth_primitives_traits::{Block, SealedBlock}; @@ -87,7 +90,10 @@ pub struct TransactionValidationTaskExecutor { impl TransactionValidationTaskExecutor<()> { /// Convenience method to create a [`EthTransactionValidatorBuilder`] - pub fn eth_builder(client: Client, local_transactions_config: Option) -> EthTransactionValidatorBuilder { + pub fn eth_builder( + client: Client, + local_transactions_config: Option, + ) -> EthTransactionValidatorBuilder { EthTransactionValidatorBuilder::new(client, local_transactions_config) } } diff --git a/examples/custom-node-components/src/main.rs b/examples/custom-node-components/src/main.rs index a11d04a6bf..a2f97fb284 100644 --- a/examples/custom-node-components/src/main.rs +++ b/examples/custom-node-components/src/main.rs @@ -58,11 +58,12 @@ where async fn build_pool(self, ctx: &BuilderContext) -> eyre::Result { let data_dir = ctx.config().datadir(); let blob_store = InMemoryBlobStore::default(); - let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) - .with_head_timestamp(ctx.head().timestamp) - .kzg_settings(ctx.kzg_settings()?) - .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); + let validator = + TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) + .with_head_timestamp(ctx.head().timestamp) + .kzg_settings(ctx.kzg_settings()?) + .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); let transaction_pool = reth_ethereum::pool::Pool::eth_pool(validator, blob_store, self.pool_config); From d111f824e5d287c9e18def9a6275db378f7493ff Mon Sep 17 00:00:00 2001 From: Morty Date: Mon, 28 Jul 2025 14:57:02 +0800 Subject: [PATCH 17/18] address comments --- .../ethereum/cli/src/debug_cmd/build_block.rs | 2 +- crates/ethereum/node/src/node.rs | 19 ++++----- crates/optimism/node/src/node.rs | 39 +++++++++---------- crates/optimism/txpool/src/transaction.rs | 2 +- crates/rpc/rpc-eth-api/src/helpers/trace.rs | 8 ++-- crates/scroll/node/src/builder/pool.rs | 38 +++++++++--------- crates/scroll/txpool/src/transaction.rs | 2 +- crates/transaction-pool/src/maintain.rs | 3 +- .../transaction-pool/src/test_utils/mock.rs | 27 +++++++------ crates/transaction-pool/src/validate/eth.rs | 15 ++++--- crates/transaction-pool/src/validate/task.rs | 13 +++---- examples/custom-node-components/src/main.rs | 11 +++--- 12 files changed, 87 insertions(+), 92 deletions(-) diff --git a/crates/ethereum/cli/src/debug_cmd/build_block.rs b/crates/ethereum/cli/src/debug_cmd/build_block.rs index 3c5d37bd8e..22260f7e33 100644 --- a/crates/ethereum/cli/src/debug_cmd/build_block.rs +++ b/crates/ethereum/cli/src/debug_cmd/build_block.rs @@ -116,7 +116,7 @@ impl> Command { let blockchain_db = BlockchainProvider::new(provider_factory.clone())?; let blob_store = InMemoryBlobStore::default(); - let validator = TransactionValidationTaskExecutor::eth_builder(blockchain_db.clone(), None) + let validator = TransactionValidationTaskExecutor::eth_builder(blockchain_db.clone()) .with_head_timestamp(best_block.timestamp) .kzg_settings(self.kzg_settings()?) .with_additional_tasks(1) diff --git a/crates/ethereum/node/src/node.rs b/crates/ethereum/node/src/node.rs index 2bf171a3cc..02ebacdb7d 100644 --- a/crates/ethereum/node/src/node.rs +++ b/crates/ethereum/node/src/node.rs @@ -405,17 +405,14 @@ where let blob_store = reth_node_builder::components::create_blob_store_with_cache(ctx, blob_cache_size)?; - let validator = TransactionValidationTaskExecutor::eth_builder( - ctx.provider().clone(), - Some(pool_config.local_transactions_config.clone()), - ) - .with_head_timestamp(ctx.head().timestamp) - .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) - .kzg_settings(ctx.kzg_settings()?) - .with_local_transactions_config(pool_config.local_transactions_config.clone()) - .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) - .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + .with_head_timestamp(ctx.head().timestamp) + .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) + .kzg_settings(ctx.kzg_settings()?) + .with_local_transactions_config(pool_config.local_transactions_config.clone()) + .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) + .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); let transaction_pool = TxPoolBuilder::new(ctx) .with_validator(validator) diff --git a/crates/optimism/node/src/node.rs b/crates/optimism/node/src/node.rs index 299a598633..2d33f05f4a 100644 --- a/crates/optimism/node/src/node.rs +++ b/crates/optimism/node/src/node.rs @@ -800,26 +800,25 @@ where .await; let blob_store = reth_node_builder::components::create_blob_store(ctx)?; - let validator = - TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) - .no_eip4844() - .with_head_timestamp(ctx.head().timestamp) - .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) - .kzg_settings(ctx.kzg_settings()?) - .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) - .with_additional_tasks( - pool_config_overrides - .additional_validation_tasks - .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), - ) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) - .map(|validator| { - OpTransactionValidator::new(validator) - // In --dev mode we can't require gas fees because we're unable to decode - // the L1 block info - .require_l1_data_gas_fee(!ctx.config().dev.dev) - .with_supervisor(supervisor_client.clone()) - }); + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + .no_eip4844() + .with_head_timestamp(ctx.head().timestamp) + .with_max_tx_input_bytes(ctx.config().txpool.max_tx_input_bytes) + .kzg_settings(ctx.kzg_settings()?) + .set_tx_fee_cap(ctx.config().rpc.rpc_tx_fee_cap) + .with_additional_tasks( + pool_config_overrides + .additional_validation_tasks + .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), + ) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) + .map(|validator| { + OpTransactionValidator::new(validator) + // In --dev mode we can't require gas fees because we're unable to decode + // the L1 block info + .require_l1_data_gas_fee(!ctx.config().dev.dev) + .with_supervisor(supervisor_client.clone()) + }); let final_pool_config = pool_config_overrides.apply(ctx.pool_config()); diff --git a/crates/optimism/txpool/src/transaction.rs b/crates/optimism/txpool/src/transaction.rs index b0f3c38a1d..6cbc645fe5 100644 --- a/crates/optimism/txpool/src/transaction.rs +++ b/crates/optimism/txpool/src/transaction.rs @@ -325,7 +325,7 @@ mod tests { #[tokio::test] async fn validate_optimism_transaction() { let client = MockEthProvider::default().with_chain_spec(OP_MAINNET.clone()); - let validator = EthTransactionValidatorBuilder::new(client, None) + let validator = EthTransactionValidatorBuilder::new(client) .no_shanghai() .no_cancun() .build(InMemoryBlobStore::default()); diff --git a/crates/rpc/rpc-eth-api/src/helpers/trace.rs b/crates/rpc/rpc-eth-api/src/helpers/trace.rs index 31085bdc08..92f2b4fe4c 100644 --- a/crates/rpc/rpc-eth-api/src/helpers/trace.rs +++ b/crates/rpc/rpc-eth-api/src/helpers/trace.rs @@ -327,11 +327,13 @@ pub trait Trace: // prepare transactions, we do everything upfront to reduce time spent with open // state - let max_transactions = - highest_index.map_or(block.body().transaction_count(), |highest| { + let max_transactions = highest_index.map_or_else( + || block.body().transaction_count(), + |highest| { // we need + 1 because the index is 0-based highest as usize + 1 - }); + }, + ); let mut idx = 0; diff --git a/crates/scroll/node/src/builder/pool.rs b/crates/scroll/node/src/builder/pool.rs index 5eb4bfa2e3..8152a5fe5e 100644 --- a/crates/scroll/node/src/builder/pool.rs +++ b/crates/scroll/node/src/builder/pool.rs @@ -61,25 +61,25 @@ where let data_dir = ctx.config().datadir(); let blob_store = DiskFileBlobStore::open(data_dir.blobstore(), Default::default())?; - let validator = TransactionValidationTaskExecutor::eth_builder( - ctx.provider().clone(), - Some(pool_config_overrides.clone().apply(ctx.pool_config()).local_transactions_config), - ) - .no_eip4844() - .with_head_timestamp(ctx.head().timestamp) - .kzg_settings(ctx.kzg_settings()?) - .with_additional_tasks( - pool_config_overrides - .additional_validation_tasks - .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), - ) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) - .map(|validator| { - ScrollTransactionValidator::new(validator) - // In --dev mode we can't require gas fees because we're unable to decode - // the L1 block info - .require_l1_data_gas_fee(!ctx.config().dev.dev) - }); + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + .no_eip4844() + .with_head_timestamp(ctx.head().timestamp) + .kzg_settings(ctx.kzg_settings()?) + .with_local_transactions_config( + pool_config_overrides.clone().apply(ctx.pool_config()).local_transactions_config, + ) + .with_additional_tasks( + pool_config_overrides + .additional_validation_tasks + .unwrap_or_else(|| ctx.config().txpool.additional_validation_tasks), + ) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()) + .map(|validator| { + ScrollTransactionValidator::new(validator) + // In --dev mode we can't require gas fees because we're unable to decode + // the L1 block info + .require_l1_data_gas_fee(!ctx.config().dev.dev) + }); let transaction_pool = reth_transaction_pool::Pool::new( validator, diff --git a/crates/scroll/txpool/src/transaction.rs b/crates/scroll/txpool/src/transaction.rs index 07513192c8..bee3096194 100644 --- a/crates/scroll/txpool/src/transaction.rs +++ b/crates/scroll/txpool/src/transaction.rs @@ -226,7 +226,7 @@ mod tests { #[test] fn validate_scroll_transaction() { let client = MockEthProvider::default().with_chain_spec(SCROLL_MAINNET.clone()); - let validator = EthTransactionValidatorBuilder::new(client, None) + let validator = EthTransactionValidatorBuilder::new(client) .no_shanghai() .no_cancun() .build(InMemoryBlobStore::default()); diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index 5b3943e831..fff0100625 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -776,8 +776,7 @@ mod tests { let sender = hex!("1f9090aaE28b8a3dCeaDf281B0F12828e676c326").into(); provider.add_account(sender, ExtendedAccount::new(42, U256::MAX)); let blob_store = InMemoryBlobStore::default(); - let validator = - EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); + let validator = EthTransactionValidatorBuilder::new(provider).build(blob_store.clone()); let txpool = Pool::new( validator.clone(), diff --git a/crates/transaction-pool/src/test_utils/mock.rs b/crates/transaction-pool/src/test_utils/mock.rs index 9ddde67ba5..afa69b1f95 100644 --- a/crates/transaction-pool/src/test_utils/mock.rs +++ b/crates/transaction-pool/src/test_utils/mock.rs @@ -799,21 +799,24 @@ impl alloy_consensus::Transaction for MockTransaction { } fn effective_gas_price(&self, base_fee: Option) -> u128 { - base_fee.map_or(self.max_fee_per_gas(), |base_fee| { - // if the tip is greater than the max priority fee per gas, set it to the max - // priority fee per gas + base fee - let tip = self.max_fee_per_gas().saturating_sub(base_fee as u128); - if let Some(max_tip) = self.max_priority_fee_per_gas() { - if tip > max_tip { - max_tip + base_fee as u128 + base_fee.map_or_else( + || self.max_fee_per_gas(), + |base_fee| { + // if the tip is greater than the max priority fee per gas, set it to the max + // priority fee per gas + base fee + let tip = self.max_fee_per_gas().saturating_sub(base_fee as u128); + if let Some(max_tip) = self.max_priority_fee_per_gas() { + if tip > max_tip { + max_tip + base_fee as u128 + } else { + // otherwise return the max fee per gas + self.max_fee_per_gas() + } } else { - // otherwise return the max fee per gas self.max_fee_per_gas() } - } else { - self.max_fee_per_gas() - } - }) + }, + ) } fn is_dynamic_fee(&self) -> bool { diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index d4a93b591d..90a61b86ec 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -785,14 +785,14 @@ impl EthTransactionValidatorBuilder { /// - EIP-1559 /// - EIP-4844 /// - EIP-7702 - pub fn new(client: Client, local_transactions_config: Option) -> Self { + pub fn new(client: Client) -> Self { Self { block_gas_limit: ETHEREUM_BLOCK_GAS_LIMIT_30M.into(), client, minimum_priority_fee: None, additional_tasks: 1, kzg_settings: EnvKzgSettings::Default, - local_transactions_config: local_transactions_config.unwrap_or_default(), + local_transactions_config: Default::default(), max_tx_input_bytes: DEFAULT_MAX_TX_INPUT_BYTES, tx_fee_cap: Some(1e18 as u128), // by default all transaction types are allowed @@ -1201,8 +1201,7 @@ mod tests { ExtendedAccount::new(transaction.nonce(), U256::MAX), ); let blob_store = InMemoryBlobStore::default(); - let validator = - EthTransactionValidatorBuilder::new(provider, None).build(blob_store.clone()); + let validator = EthTransactionValidatorBuilder::new(provider).build(blob_store.clone()); let outcome = validator.validate_one(TransactionOrigin::External, transaction.clone()); @@ -1229,7 +1228,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None) + let validator = EthTransactionValidatorBuilder::new(provider) .set_block_gas_limit(1_000_000) // tx gas limit is 1_015_288 .build(blob_store.clone()); @@ -1262,7 +1261,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None) + let validator = EthTransactionValidatorBuilder::new(provider) .set_tx_fee_cap(100) // 100 wei cap .build(blob_store.clone()); @@ -1299,7 +1298,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None) + let validator = EthTransactionValidatorBuilder::new(provider) .set_tx_fee_cap(0) // no cap .build(blob_store); @@ -1317,7 +1316,7 @@ mod tests { ); let blob_store = InMemoryBlobStore::default(); - let validator = EthTransactionValidatorBuilder::new(provider, None) + let validator = EthTransactionValidatorBuilder::new(provider) .set_tx_fee_cap(2e18 as u128) // 2 ETH cap .build(blob_store); diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index e0446d7310..7e417681fe 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -3,8 +3,8 @@ use crate::{ blobstore::BlobStore, validate::{EthTransactionValidatorBuilder, TransactionValidatorError}, - EthTransactionValidator, LocalTransactionConfig, PoolTransaction, TransactionOrigin, - TransactionValidationOutcome, TransactionValidator, + EthTransactionValidator, PoolTransaction, TransactionOrigin, TransactionValidationOutcome, + TransactionValidator, }; use futures_util::{lock::Mutex, StreamExt}; use reth_primitives_traits::{Block, SealedBlock}; @@ -90,11 +90,8 @@ pub struct TransactionValidationTaskExecutor { impl TransactionValidationTaskExecutor<()> { /// Convenience method to create a [`EthTransactionValidatorBuilder`] - pub fn eth_builder( - client: Client, - local_transactions_config: Option, - ) -> EthTransactionValidatorBuilder { - EthTransactionValidatorBuilder::new(client, local_transactions_config) + pub fn eth_builder(client: Client) -> EthTransactionValidatorBuilder { + EthTransactionValidatorBuilder::new(client) } } @@ -141,7 +138,7 @@ impl TransactionValidationTaskExecutor(tasks, blob_store) } diff --git a/examples/custom-node-components/src/main.rs b/examples/custom-node-components/src/main.rs index a2f97fb284..c4e571762e 100644 --- a/examples/custom-node-components/src/main.rs +++ b/examples/custom-node-components/src/main.rs @@ -58,12 +58,11 @@ where async fn build_pool(self, ctx: &BuilderContext) -> eyre::Result { let data_dir = ctx.config().datadir(); let blob_store = InMemoryBlobStore::default(); - let validator = - TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone(), None) - .with_head_timestamp(ctx.head().timestamp) - .kzg_settings(ctx.kzg_settings()?) - .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) - .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); + let validator = TransactionValidationTaskExecutor::eth_builder(ctx.provider().clone()) + .with_head_timestamp(ctx.head().timestamp) + .kzg_settings(ctx.kzg_settings()?) + .with_additional_tasks(ctx.config().txpool.additional_validation_tasks) + .build_with_tasks(ctx.task_executor().clone(), blob_store.clone()); let transaction_pool = reth_ethereum::pool::Pool::eth_pool(validator, blob_store, self.pool_config); From 723bf8b774e39a322ffbec609772a9381cbbde7b Mon Sep 17 00:00:00 2001 From: Morty Date: Mon, 28 Jul 2025 17:28:25 +0800 Subject: [PATCH 18/18] fix: logging --- crates/scroll/rpc/src/eth/transaction.rs | 8 ++++---- crates/scroll/rpc/src/sequencer.rs | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/scroll/rpc/src/eth/transaction.rs b/crates/scroll/rpc/src/eth/transaction.rs index 286b7c709e..7a749f891d 100644 --- a/crates/scroll/rpc/src/eth/transaction.rs +++ b/crates/scroll/rpc/src/eth/transaction.rs @@ -44,7 +44,7 @@ where // On scroll, transactions are forwarded directly to the sequencer to be included in // blocks that it builds. if let Some(client) = self.raw_tx_forwarder().as_ref() { - tracing::debug!(target: "rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); + tracing::debug!(target: "scroll::rpc::eth", hash = %pool_transaction.hash(), "forwarding raw transaction to sequencer"); // Retain tx in local tx pool before forwarding to sequencer rpc, for local RPC usage. let hash = self @@ -53,15 +53,15 @@ where .await .map_err(Self::Error::from_eth_err)?; - tracing::debug!(target: "rpc::eth", %hash, "successfully added transaction to local tx pool"); + tracing::debug!(target: "scroll::rpc::eth", %hash, "successfully added transaction to local tx pool"); // Forward to remote sequencer RPC. match client.forward_raw_transaction(&tx).await { Ok(sequencer_hash) => { - tracing::debug!(target: "rpc::eth", local_hash=%hash, sequencer_hash=%sequencer_hash, "successfully forwarded transaction to sequencer"); + tracing::debug!(target: "scroll::rpc::eth", local_hash=%hash, sequencer_hash=%sequencer_hash, "successfully forwarded transaction to sequencer"); } Err(err) => { - tracing::warn!(target: "rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); + tracing::warn!(target: "scroll::rpc::eth", %err, %hash, "failed to forward transaction to sequencer, but transaction is in local pool"); } } diff --git a/crates/scroll/rpc/src/sequencer.rs b/crates/scroll/rpc/src/sequencer.rs index 094840f99e..637525460d 100644 --- a/crates/scroll/rpc/src/sequencer.rs +++ b/crates/scroll/rpc/src/sequencer.rs @@ -98,7 +98,7 @@ impl SequencerClient { self.client().request::(method.to_string(), params).await.inspect_err( |err| { warn!( - target: "rpc::sequencer", + target: "scroll::rpc::sequencer", %err, "HTTP request to sequencer failed", ); @@ -113,7 +113,7 @@ impl SequencerClient { let tx_hash = self.send_rpc_call("eth_sendRawTransaction", (rlp_hex,)).await.inspect_err(|err| { warn!( - target: "rpc::eth", + target: "scroll::rpc::eth", %err, "Failed to forward transaction to sequencer", );