From 0f3cf1ad38dee40d31717d999c1f189e0d76d9a4 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 17 Jun 2024 16:11:59 +0100 Subject: [PATCH 01/16] feat(examples): remote exex --- Cargo.lock | 330 ++++++++++++++++-- crates/evm/Cargo.toml | 2 + crates/evm/execution-types/src/chain.rs | 1 + .../execution-types/src/execution_outcome.rs | 1 + crates/exex/exex/Cargo.toml | 5 + crates/exex/exex/src/notification.rs | 1 + crates/primitives/src/receipt.rs | 15 +- crates/storage/provider/Cargo.toml | 1 + examples/exex/remote/Cargo.toml | 42 +++ examples/exex/remote/bin/consumer.rs | 33 ++ examples/exex/remote/bin/exex.rs | 127 +++++++ examples/exex/remote/build.rs | 4 + examples/exex/remote/proto/exex.proto | 21 ++ examples/exex/remote/src/codec.rs | 12 + examples/exex/remote/src/lib.rs | 4 + 15 files changed, 577 insertions(+), 22 deletions(-) create mode 100644 examples/exex/remote/Cargo.toml create mode 100644 examples/exex/remote/bin/consumer.rs create mode 100644 examples/exex/remote/bin/exex.rs create mode 100644 examples/exex/remote/build.rs create mode 100644 examples/exex/remote/proto/exex.proto create mode 100644 examples/exex/remote/src/codec.rs create mode 100644 examples/exex/remote/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 3ab202d1c2a2..83b8af73fa05 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -315,7 +315,7 @@ dependencies = [ "alloy-transport", "alloy-transport-http", "alloy-transport-ws", - "async-stream", + "async-stream 0.3.5", "async-trait", "auto_impl", "dashmap", @@ -1038,17 +1038,38 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-stream" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22068c0c19514942eefcfd4daf8976ef1aad84e61539f95cd200c35202f80af5" +dependencies = [ + "async-stream-impl 0.2.1", + "futures-core", +] + [[package]] name = "async-stream" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" dependencies = [ - "async-stream-impl", + "async-stream-impl 0.3.5", "futures-core", "pin-project-lite", ] +[[package]] +name = "async-stream-impl" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f9db3b38af870bf7e5cc649167533b493928e50744e2c30ae350230b414670" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "async-stream-impl" version = "0.3.5" @@ -1121,6 +1142,51 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +[[package]] +name = "axum" +version = "0.6.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" +dependencies = [ + "async-trait", + "axum-core", + "bitflags 1.3.2", + "bytes", + "futures-util", + "http 0.2.12", + "http-body 0.4.6", + "hyper 0.14.29", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "rustversion", + "serde", + "sync_wrapper", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" +dependencies = [ + "async-trait", + "bytes", + "futures-util", + "http 0.2.12", + "http-body 0.4.6", + "mime", + "rustversion", + "tower-layer", + "tower-service", +] + [[package]] name = "backon" version = "0.4.4" @@ -2957,6 +3023,29 @@ dependencies = [ "tokio", ] +[[package]] +name = "exex-remote" +version = "0.0.0" +dependencies = [ + "async-stream 0.2.1", + "eyre", + "futures", + "prost", + "rand 0.8.5", + "reth", + "reth-exex", + "reth-exex-test-utils", + "reth-node-api", + "reth-node-ethereum", + "reth-tracing", + "serde", + "serde_json", + "tokio", + "tokio-stream", + "tonic", + "tonic-build", +] + [[package]] name = "exex-rollup" version = "0.0.0" @@ -3088,6 +3177,12 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "flate2" version = "1.0.30" @@ -3385,6 +3480,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.3.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap 2.2.6", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "h2" version = "0.4.5" @@ -3585,6 +3699,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http-body" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +dependencies = [ + "bytes", + "http 0.2.12", + "pin-project-lite", +] + [[package]] name = "http-body" version = "1.0.0" @@ -3604,7 +3729,7 @@ dependencies = [ "bytes", "futures-util", "http 1.1.0", - "http-body", + "http-body 1.0.0", "pin-project-lite", ] @@ -3668,6 +3793,30 @@ dependencies = [ "serde", ] +[[package]] +name = "hyper" +version = "0.14.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f361cde2f109281a220d4307746cdfd5ee3f410da58a70377762396775634b33" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2 0.3.26", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.5.7", + "tokio", + "tower-service", + "tracing", + "want", +] + [[package]] name = "hyper" version = "1.3.1" @@ -3677,9 +3826,9 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "h2", + "h2 0.4.5", "http 1.1.0", - "http-body", + "http-body 1.0.0", "httparse", "httpdate", "itoa", @@ -3697,7 +3846,7 @@ checksum = "a0bea761b46ae2b24eb4aef630d8d1c398157b6fc29e6350ecf090a0b70c952c" dependencies = [ "futures-util", "http 1.1.0", - "hyper", + "hyper 1.3.1", "hyper-util", "rustls 0.22.4", "rustls-pki-types", @@ -3714,7 +3863,7 @@ checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" dependencies = [ "futures-util", "http 1.1.0", - "hyper", + "hyper 1.3.1", "hyper-util", "log", "rustls 0.23.10", @@ -3724,6 +3873,18 @@ dependencies = [ "tower-service", ] +[[package]] +name = "hyper-timeout" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1" +dependencies = [ + "hyper 0.14.29", + "pin-project-lite", + "tokio", + "tokio-io-timeout", +] + [[package]] name = "hyper-util" version = "0.1.5" @@ -3734,8 +3895,8 @@ dependencies = [ "futures-channel", "futures-util", "http 1.1.0", - "http-body", - "hyper", + "http-body 1.0.0", + "hyper 1.3.1", "pin-project-lite", "socket2 0.5.7", "tokio", @@ -4299,7 +4460,7 @@ dependencies = [ "futures-timer", "futures-util", "http 1.1.0", - "http-body", + "http-body 1.0.0", "http-body-util", "jsonrpsee-types", "parking_lot 0.12.3", @@ -4323,8 +4484,8 @@ checksum = "fb25cab482c8512c4f3323a5c90b95a3b8f7c90681a87bf7a68b942d52f08933" dependencies = [ "async-trait", "base64 0.22.1", - "http-body", - "hyper", + "http-body 1.0.0", + "hyper 1.3.1", "hyper-rustls 0.27.2", "hyper-util", "jsonrpsee-core", @@ -4362,9 +4523,9 @@ dependencies = [ "anyhow", "futures-util", "http 1.1.0", - "http-body", + "http-body 1.0.0", "http-body-util", - "hyper", + "hyper 1.3.1", "hyper-util", "jsonrpsee-core", "jsonrpsee-types", @@ -4808,6 +4969,12 @@ dependencies = [ "regex-automata 0.1.10", ] +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + [[package]] name = "memchr" version = "2.7.4" @@ -5056,6 +5223,12 @@ dependencies = [ "unsigned-varint 0.7.2", ] +[[package]] +name = "multimap" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" + [[package]] name = "multistream-select" version = "0.13.0" @@ -5506,6 +5679,16 @@ dependencies = [ "ucd-trie", ] +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap 2.2.6", +] + [[package]] name = "ph" version = "0.8.3" @@ -5903,6 +6086,59 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "prost" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4" +dependencies = [ + "bytes", + "heck 0.5.0", + "itertools 0.12.1", + "log", + "multimap", + "once_cell", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 2.0.66", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" +dependencies = [ + "anyhow", + "itertools 0.12.1", + "proc-macro2", + "quote", + "syn 2.0.66", +] + +[[package]] +name = "prost-types" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0" +dependencies = [ + "prost", +] + [[package]] name = "quanta" version = "0.12.3" @@ -6196,9 +6432,9 @@ dependencies = [ "futures-core", "futures-util", "http 1.1.0", - "http-body", + "http-body 1.0.0", "http-body-util", - "hyper", + "hyper 1.3.1", "hyper-rustls 0.26.0", "hyper-util", "ipnet", @@ -6881,7 +7117,7 @@ version = "1.0.0-rc.1" dependencies = [ "alloy-rlp", "arbitrary", - "async-stream", + "async-stream 0.3.5", "bytes", "derive_more", "futures", @@ -6915,7 +7151,7 @@ version = "1.0.0-rc.1" dependencies = [ "alloy-rlp", "arbitrary", - "async-stream", + "async-stream 0.3.5", "bytes", "derive_more", "proptest", @@ -7013,6 +7249,7 @@ dependencies = [ "reth-storage-errors", "revm", "revm-primitives", + "serde", ] [[package]] @@ -7093,6 +7330,7 @@ dependencies = [ "reth-provider", "reth-tasks", "reth-tracing", + "serde", "tokio", "tokio-util", ] @@ -7850,8 +8088,8 @@ dependencies = [ "dyn-clone", "futures", "http 1.1.0", - "http-body", - "hyper", + "http-body 1.0.0", + "hyper 1.3.1", "jsonrpsee", "jsonwebtoken", "metrics", @@ -9776,6 +10014,16 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "tokio-io-timeout" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b74022ada614a1b4834de765f9bb43877f910cc8ce4be40e89042c9223a8bf" +dependencies = [ + "pin-project-lite", + "tokio", +] + [[package]] name = "tokio-macros" version = "2.3.0" @@ -9897,6 +10145,46 @@ dependencies = [ "winnow 0.6.13", ] +[[package]] +name = "tonic" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76c4eb7a4e9ef9d4763600161f12f5070b92a578e1b634db88a6887844c91a13" +dependencies = [ + "async-stream 0.3.5", + "async-trait", + "axum", + "base64 0.21.7", + "bytes", + "h2 0.3.26", + "http 0.2.12", + "http-body 0.4.6", + "hyper 0.14.29", + "hyper-timeout", + "percent-encoding", + "pin-project", + "prost", + "tokio", + "tokio-stream", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be4ef6dd70a610078cb4e338a0f79d06bc759ff1b22d2120c2ff02ae264ba9c2" +dependencies = [ + "prettyplease", + "proc-macro2", + "prost-build", + "quote", + "syn 2.0.66", +] + [[package]] name = "tower" version = "0.4.13" @@ -9931,7 +10219,7 @@ dependencies = [ "futures-core", "futures-util", "http 1.1.0", - "http-body", + "http-body 1.0.0", "http-body-util", "http-range-header", "httpdate", diff --git a/crates/evm/Cargo.toml b/crates/evm/Cargo.toml index e836148101ad..9440773e0e9c 100644 --- a/crates/evm/Cargo.toml +++ b/crates/evm/Cargo.toml @@ -24,9 +24,11 @@ revm.workspace = true auto_impl.workspace = true futures-util.workspace = true parking_lot = { workspace = true, optional = true } +serde = { workspace = true, optional = true } [dev-dependencies] parking_lot.workspace = true [features] +serde = ["dep:serde"] test-utils = ["dep:parking_lot"] diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index 97bd6fcf30ce..de46952b9ee2 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -21,6 +21,7 @@ use std::{borrow::Cow, collections::BTreeMap, fmt, ops::RangeInclusive}; /// /// A chain of blocks should not be empty. #[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct Chain { /// All blocks in this chain. blocks: BTreeMap, diff --git a/crates/evm/execution-types/src/execution_outcome.rs b/crates/evm/execution-types/src/execution_outcome.rs index be9fd67b14ce..eb84af7d19a3 100644 --- a/crates/evm/execution-types/src/execution_outcome.rs +++ b/crates/evm/execution-types/src/execution_outcome.rs @@ -16,6 +16,7 @@ use std::collections::HashMap; /// The `ExecutionOutcome` structure aggregates the state changes over an arbitrary number of /// blocks, capturing the resulting state, receipts, and requests following the execution. #[derive(Default, Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ExecutionOutcome { /// Bundle state with reverts. pub bundle: BundleState, diff --git a/crates/exex/exex/Cargo.toml b/crates/exex/exex/Cargo.toml index 4df59b3fc8c8..5bbf177d098b 100644 --- a/crates/exex/exex/Cargo.toml +++ b/crates/exex/exex/Cargo.toml @@ -32,3 +32,8 @@ tokio-util.workspace = true ## misc eyre.workspace = true metrics.workspace = true +serde = { workspace = true, optional = true } + +[features] +default = [] +serde = ["dep:serde", "reth-provider/serde"] diff --git a/crates/exex/exex/src/notification.rs b/crates/exex/exex/src/notification.rs index 9f1beec414d3..390d9dc665a7 100644 --- a/crates/exex/exex/src/notification.rs +++ b/crates/exex/exex/src/notification.rs @@ -4,6 +4,7 @@ use reth_provider::{CanonStateNotification, Chain}; /// Notifications sent to an `ExEx`. #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum ExExNotification { /// Chain got committed without a reorg, and only the new chain is returned. ChainCommitted { diff --git a/crates/primitives/src/receipt.rs b/crates/primitives/src/receipt.rs index 56be2d0a1690..b7f084c0391d 100644 --- a/crates/primitives/src/receipt.rs +++ b/crates/primitives/src/receipt.rs @@ -11,6 +11,7 @@ use proptest::strategy::Strategy; #[cfg(feature = "zstd-codec")] use reth_codecs::CompactZstd; use reth_codecs::{add_arbitrary_tests, main_codec, Compact}; +use serde::{Deserialize, Serialize}; #[cfg(not(feature = "std"))] use alloc::{vec, vec::Vec}; @@ -66,7 +67,19 @@ impl Receipt { } /// A collection of receipts organized as a two-dimensional vector. -#[derive(Clone, Debug, PartialEq, Eq, Default, From, Deref, DerefMut, IntoIterator)] +#[derive( + Clone, + Debug, + PartialEq, + Eq, + Default, + Serialize, + Deserialize, + From, + Deref, + DerefMut, + IntoIterator, +)] pub struct Receipts { /// A two-dimensional vector of optional `Receipt` instances. pub receipt_vec: Vec>>, diff --git a/crates/storage/provider/Cargo.toml b/crates/storage/provider/Cargo.toml index de2fea7578d9..6c1e02d6dde9 100644 --- a/crates/storage/provider/Cargo.toml +++ b/crates/storage/provider/Cargo.toml @@ -72,5 +72,6 @@ assert_matches.workspace = true rand.workspace = true [features] +serde = ["dep:serde", "reth-execution-types/serde"] test-utils = ["alloy-rlp", "reth-db/test-utils", "reth-nippy-jar/test-utils"] optimism = ["reth-primitives/optimism", "reth-execution-types/optimism"] diff --git a/examples/exex/remote/Cargo.toml b/examples/exex/remote/Cargo.toml new file mode 100644 index 000000000000..dc928002e67f --- /dev/null +++ b/examples/exex/remote/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "exex-remote" +version = "0.0.0" +publish = false +edition.workspace = true +license.workspace = true + +[dependencies] +reth.workspace = true +reth-exex = { workspace = true, features = ["serde"] } +reth-node-api.workspace = true +reth-node-ethereum.workspace = true +reth-tracing.workspace = true + +eyre.workspace = true +futures.workspace = true + +tonic = "0.11" +prost = "0.12" +tokio = { version = "1.0", features = ["full"] } +tokio-stream = "0.1" + +async-stream = "0.2" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +rand = "0.8" + +[build-dependencies] +tonic-build = "0.11" + +[dev-dependencies] +reth-exex-test-utils.workspace = true + +tokio.workspace = true + +[[bin]] +name = "exex" +path = "bin/exex.rs" + +[[bin]] +name = "consumer" +path = "bin/consumer.rs" diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs new file mode 100644 index 000000000000..8567154ffb93 --- /dev/null +++ b/examples/exex/remote/bin/consumer.rs @@ -0,0 +1,33 @@ +use exex_remote::{ + codec::from_u8_slice, + proto::{ + remote_ex_ex_client::RemoteExExClient, ExExNotification as ProtoExExNotification, + Notification, SubscribeRequest, + }, +}; + +#[tokio::main] +async fn main() -> eyre::Result<()> { + let mut client = RemoteExExClient::connect("http://[::1]:10000").await?; + + let mut stream = client + .subscribe(SubscribeRequest { + notifications: vec![ + ProtoExExNotification::ChainCommitted as i32, + ProtoExExNotification::ChainReorged as i32, + ProtoExExNotification::ChainReverted as i32, + ], + }) + .await? + .into_inner(); + + while let Some(Notification { data }) = stream.message().await? { + // TODO(alexey): it doesn't work, because data inside the notification is boxed. + // We need to implement a proper encoding via Serde. + // let notification = unsafe { from_u8_slice(&data) }; + // println!("{:?}", notification); + println!("{:?}", data); + } + + Ok(()) +} diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs new file mode 100644 index 000000000000..4f2718486caa --- /dev/null +++ b/examples/exex/remote/bin/exex.rs @@ -0,0 +1,127 @@ +use std::sync::Arc; + +use exex_remote::{ + codec::to_u8_slice, + proto::{ + remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, + ExExNotification as ProtoExExNotification, Notification as ProtoNotification, + SubscribeRequest as ProtoSubscribeRequest, + }, +}; +use futures::TryFutureExt; +use reth_exex::{ExExContext, ExExEvent, ExExNotification}; +use reth_node_api::FullNodeComponents; +use reth_node_ethereum::EthereumNode; +use reth_tracing::tracing::info; +use tokio::sync::{broadcast, mpsc}; +use tokio_stream::wrappers::ReceiverStream; +use tonic::{transport::Server, Request, Response, Status}; + +#[derive(Debug)] +struct ExExService { + notifications: Arc>, +} + +#[tonic::async_trait] +impl RemoteExEx for ExExService { + type SubscribeStream = ReceiverStream>; + + async fn subscribe( + &self, + request: Request, + ) -> Result, Status> { + let (tx, rx) = mpsc::channel(1); + + let mut notifications = self.notifications.subscribe(); + let filter = request + .into_inner() + .notifications + .into_iter() + .map(|notification| { + move |exex_notification: &ExExNotification| match notification.try_into() { + Ok(ProtoExExNotification::ChainCommitted) => { + matches!(exex_notification, ExExNotification::ChainCommitted { .. }) + } + Ok(ProtoExExNotification::ChainReorged) => { + matches!(exex_notification, ExExNotification::ChainReorged { .. }) + } + Ok(ProtoExExNotification::ChainReverted) => { + matches!(exex_notification, ExExNotification::ChainReverted { .. }) + } + Err(_) => false, + } + }) + .collect::>(); + let matches_filter = + move |exex_notification: &ExExNotification| filter.iter().any(|f| f(exex_notification)); + + tokio::spawn(async move { + while let Ok(notification) = notifications.recv().await { + if matches_filter(¬ification) { + tx.send(Ok(ProtoNotification { + data: unsafe { to_u8_slice(¬ification) }.to_vec(), + })) + .await + .expect("failed to send notification to client"); + } + } + }); + + Ok(Response::new(ReceiverStream::new(rx))) + } +} + +/// An ExEx is just a future, which means you can implement all of it in an async function! +/// +/// This ExEx just prints out whenever either a new chain of blocks being added, or a chain of +/// blocks being re-orged. After processing the chain, emits an [ExExEvent::FinishedHeight] event. +async fn exex( + mut ctx: ExExContext, + notifications: Arc>, +) -> eyre::Result<()> { + while let Some(notification) = ctx.notifications.recv().await { + match ¬ification { + ExExNotification::ChainCommitted { new } => { + info!(committed_chain = ?new.range(), "Received commit"); + } + ExExNotification::ChainReorged { old, new } => { + info!(from_chain = ?old.range(), to_chain = ?new.range(), "Received reorg"); + } + ExExNotification::ChainReverted { old } => { + info!(reverted_chain = ?old.range(), "Received revert"); + } + }; + + if let Some(committed_chain) = notification.committed_chain() { + ctx.events.send(ExExEvent::FinishedHeight(committed_chain.tip().number))?; + } + + let _ = notifications.send(notification); + } + + Ok(()) +} + +fn main() -> eyre::Result<()> { + reth::cli::Cli::parse_args().run(|builder, _| async move { + let notifications = Arc::new(broadcast::channel(1).0); + + let server = Server::builder() + .add_service(RemoteExExServer::new(ExExService { + notifications: notifications.clone(), + })) + .serve("[::1]:10000".parse().unwrap()) + .map_err(|err| err.into()); + + let node = builder + .node(EthereumNode::default()) + .install_exex("Remote", |ctx| async move { Ok(exex(ctx, notifications)) }) + .launch() + .await? + .wait_for_node_exit(); + + futures::try_join!(server, node)?; + + Ok(()) + }) +} diff --git a/examples/exex/remote/build.rs b/examples/exex/remote/build.rs new file mode 100644 index 000000000000..9e70bbe9b31f --- /dev/null +++ b/examples/exex/remote/build.rs @@ -0,0 +1,4 @@ +fn main() { + tonic_build::compile_protos("proto/exex.proto") + .unwrap_or_else(|e| panic!("Failed to compile protos {:?}", e)); +} diff --git a/examples/exex/remote/proto/exex.proto b/examples/exex/remote/proto/exex.proto new file mode 100644 index 000000000000..be3e89c35e1b --- /dev/null +++ b/examples/exex/remote/proto/exex.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +package exex; + +service RemoteExEx { + rpc Subscribe(SubscribeRequest) returns (stream Notification) {} +} + +message SubscribeRequest { + repeated ExExNotification notifications = 1; +} + +enum ExExNotification { + CHAIN_COMMITTED = 0; + CHAIN_REORGED = 1; + CHAIN_REVERTED = 2; +} + +message Notification { + bytes data = 1; +} diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs new file mode 100644 index 000000000000..c8c49ac1d0fa --- /dev/null +++ b/examples/exex/remote/src/codec.rs @@ -0,0 +1,12 @@ +use reth_exex::ExExNotification; + +pub unsafe fn to_u8_slice(notification: &ExExNotification) -> &[u8] { + core::slice::from_raw_parts( + (notification as *const ExExNotification) as *const u8, + core::mem::size_of::(), + ) +} + +pub unsafe fn from_u8_slice(bytes: &[u8]) -> &ExExNotification { + unsafe { &*(bytes.as_ptr() as *const reth_exex::ExExNotification) } +} diff --git a/examples/exex/remote/src/lib.rs b/examples/exex/remote/src/lib.rs new file mode 100644 index 000000000000..9b8aa5781a8f --- /dev/null +++ b/examples/exex/remote/src/lib.rs @@ -0,0 +1,4 @@ +pub mod codec; +pub mod proto { + tonic::include_proto!("exex"); +} From 251249bd719dc27b70644178a467082cb37b619b Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 17 Jun 2024 17:20:12 +0100 Subject: [PATCH 02/16] ok it works --- Cargo.lock | 322 +++++++++++--------------- Cargo.toml | 58 ++--- crates/evm/execution-types/Cargo.toml | 5 +- crates/storage/provider/Cargo.toml | 2 +- crates/trie/trie/Cargo.toml | 4 + crates/trie/trie/src/updates.rs | 3 + examples/exex/remote/Cargo.toml | 5 +- examples/exex/remote/bin/consumer.rs | 31 ++- examples/exex/remote/bin/exex.rs | 14 +- examples/exex/remote/src/codec.rs | 12 - examples/exex/remote/src/lib.rs | 1 - 11 files changed, 201 insertions(+), 256 deletions(-) delete mode 100644 examples/exex/remote/src/codec.rs diff --git a/Cargo.lock b/Cargo.lock index 76c083d4df11..304520f3f134 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -121,33 +121,20 @@ dependencies = [ "strum", ] -[[package]] -name = "alloy-consensus" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" -dependencies = [ - "alloy-eips 0.1.0", - "alloy-primitives", - "alloy-rlp", - "alloy-serde 0.1.0", - "arbitrary", - "c-kzg", - "proptest", - "proptest-derive", - "serde", -] - [[package]] name = "alloy-consensus" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3cc7579e4fb5558af44810f542c90d1145dba8b92c08211c215196160c48d2ea" dependencies = [ - "alloy-eips 0.1.1", + "alloy-eips", "alloy-primitives", "alloy-rlp", - "alloy-serde 0.1.1", + "alloy-serde", + "arbitrary", "c-kzg", + "proptest", + "proptest-derive", "serde", ] @@ -171,12 +158,13 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bdbc8d98cc36ebe17bb5b42d0873137bc76628a4ee0f7e7acad5b8fc59d3597" dependencies = [ "alloy-primitives", "alloy-rlp", - "alloy-serde 0.1.0", + "alloy-serde", "arbitrary", "c-kzg", "derive_more", @@ -188,27 +176,13 @@ dependencies = [ ] [[package]] -name = "alloy-eips" +name = "alloy-genesis" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bdbc8d98cc36ebe17bb5b42d0873137bc76628a4ee0f7e7acad5b8fc59d3597" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "alloy-serde 0.1.1", - "c-kzg", - "once_cell", - "serde", - "sha2 0.10.8", -] - -[[package]] -name = "alloy-genesis" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +checksum = "5e10a047066076b32d52b3228e95a4f7793db7a204f648aa1a1ea675085bffd8" dependencies = [ "alloy-primitives", - "alloy-serde 0.1.0", + "alloy-serde", "serde", "serde_json", ] @@ -227,8 +201,9 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d06d33b79246313c4103ef9596c721674a926f1ddc8b605aa2bac4d8ba94ee34" dependencies = [ "alloy-primitives", "serde", @@ -239,15 +214,16 @@ dependencies = [ [[package]] name = "alloy-network" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef742b478a2db5c27063cde82128dfbecffcd38237d7f682a91d3ecf6aa1836c" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-json-rpc", "alloy-primitives", - "alloy-rpc-types-eth 0.1.0", - "alloy-serde 0.1.0", + "alloy-rpc-types-eth", + "alloy-serde", "alloy-signer", "alloy-sol-types", "async-trait", @@ -258,8 +234,9 @@ dependencies = [ [[package]] name = "alloy-node-bindings" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4890cdebc750890b1cd3b5a61f72df992e262c5bfb5423b2999f0d81449f04e" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -300,12 +277,13 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200b786259a17acf318b9c423afe9669bec24ce9cdf59de153ff9a4009914bb6" dependencies = [ "alloy-chains", - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-json-rpc", "alloy-network", "alloy-primitives", @@ -313,11 +291,11 @@ dependencies = [ "alloy-rpc-client", "alloy-rpc-types-admin", "alloy-rpc-types-engine", - "alloy-rpc-types-eth 0.1.0", + "alloy-rpc-types-eth", "alloy-transport", "alloy-transport-http", "alloy-transport-ws", - "async-stream 0.3.5", + "async-stream", "async-trait", "auto_impl", "dashmap", @@ -335,8 +313,9 @@ dependencies = [ [[package]] name = "alloy-pubsub" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e6e6c1eab938a18a8e88d430cc9d548edf54c850a550873888285c85428eca" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -375,8 +354,9 @@ dependencies = [ [[package]] name = "alloy-rpc-client" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "328a6a14aba6152ddf6d01bac5e17a70dbe9d6f343bf402b995c30bac63a1fbf" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -398,19 +378,21 @@ dependencies = [ [[package]] name = "alloy-rpc-types" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3164e7d8a718a22ede70b2c1d2bb554a8b4bd8e56c07ab630b75c74c06c53752" dependencies = [ "alloy-rpc-types-engine", - "alloy-rpc-types-eth 0.1.0", + "alloy-rpc-types-eth", "alloy-rpc-types-trace", - "alloy-serde 0.1.0", + "alloy-serde", ] [[package]] name = "alloy-rpc-types-admin" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b61b27c1a30ee71c751fe8a1b926d897e6795527bba2832f458acd432408df20" dependencies = [ "alloy-genesis", "alloy-primitives", @@ -420,20 +402,22 @@ dependencies = [ [[package]] name = "alloy-rpc-types-anvil" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21cdf2617cfb0ae95ef462a0144abfef5ff56d25b56915d7a08f8a5a7b92926" dependencies = [ "alloy-primitives", - "alloy-serde 0.1.0", + "alloy-serde", "serde", ] [[package]] name = "alloy-rpc-types-beacon" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36a3c7fd58772e4eadec5f08153573aa0ce8d998bd03f239ca74cd2927022d4c" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-primitives", "alloy-rpc-types-engine", "serde", @@ -443,15 +427,16 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90c3de574f90d9b939e3ee666a74bea29fb1a2ae66f1569b111bb6a922b1c762" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 0.1.0", - "alloy-serde 0.1.0", + "alloy-rpc-types-eth", + "alloy-serde", "jsonrpsee-types", "jsonwebtoken", "rand 0.8.5", @@ -461,14 +446,15 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bce0676f144be1eae71122d1d417885a3b063add0353b35e46cdf1440d6b33b1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-primitives", "alloy-rlp", - "alloy-serde 0.1.0", + "alloy-serde", "alloy-sol-types", "arbitrary", "itertools 0.13.0", @@ -481,50 +467,35 @@ dependencies = [ ] [[package]] -name = "alloy-rpc-types-eth" +name = "alloy-rpc-types-trace" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bce0676f144be1eae71122d1d417885a3b063add0353b35e46cdf1440d6b33b1" +checksum = "a39c52613dc4d9995ff284b496158594ae63f9bfc58b5ef04e48ec5da2e3d747" dependencies = [ - "alloy-consensus 0.1.1", - "alloy-eips 0.1.1", "alloy-primitives", - "alloy-rlp", - "alloy-serde 0.1.1", - "alloy-sol-types", - "itertools 0.13.0", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "alloy-rpc-types-trace" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" -dependencies = [ - "alloy-primitives", - "alloy-rpc-types-eth 0.1.0", - "alloy-serde 0.1.0", + "alloy-rpc-types-eth", + "alloy-serde", "serde", "serde_json", ] [[package]] name = "alloy-rpc-types-txpool" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aeb7995e8859f3931b6199e13a533c9fde89affa900addb7218db2f15f9687d" dependencies = [ "alloy-primitives", - "alloy-rpc-types-eth 0.1.0", - "alloy-serde 0.1.0", + "alloy-rpc-types-eth", + "alloy-serde", "serde", ] [[package]] name = "alloy-serde" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c224916316519558d8c2b6a60dc7626688c08f1b8951774702562dbcb8666ee" dependencies = [ "alloy-primitives", "arbitrary", @@ -535,20 +506,10 @@ dependencies = [ ] [[package]] -name = "alloy-serde" +name = "alloy-signer" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c224916316519558d8c2b6a60dc7626688c08f1b8951774702562dbcb8666ee" -dependencies = [ - "alloy-primitives", - "serde", - "serde_json", -] - -[[package]] -name = "alloy-signer" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +checksum = "227c5fd0ed6e06e1ccc30593f8ff6d9fb907ac5f03a709a6d687f0943494a229" dependencies = [ "alloy-primitives", "async-trait", @@ -560,10 +521,11 @@ dependencies = [ [[package]] name = "alloy-signer-local" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66c44057ac1e8707f8c6a983db9f83ac1265c9e05be81d432acf2aad2880e1c0" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-primitives", "alloy-signer", @@ -649,8 +611,9 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3628d81530263fe837a09cd527022f5728202a669973f04270942f4d390b5f5" dependencies = [ "alloy-json-rpc", "base64 0.22.1", @@ -666,8 +629,9 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f35d34e7a51503c9ff267404a5850bd58f991b7ab524b892f364901e3576376" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -680,8 +644,9 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7d2f106151a583f7d258fe8cc846c5196da90a9f502d4b3516c56d63e1f25a2" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -698,8 +663,9 @@ dependencies = [ [[package]] name = "alloy-transport-ws" -version = "0.1.0" -source = "git+https://github.com/alloy-rs/alloy?rev=6cb3713#6cb3713a14c047cd5fcf17b99d27055341c41aaf" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20a80da44d3709c4ceaf47745ad820eae8f121404b9ffd8e285522ac4eb06681" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -1033,38 +999,17 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-stream" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22068c0c19514942eefcfd4daf8976ef1aad84e61539f95cd200c35202f80af5" -dependencies = [ - "async-stream-impl 0.2.1", - "futures-core", -] - [[package]] name = "async-stream" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" dependencies = [ - "async-stream-impl 0.3.5", + "async-stream-impl", "futures-core", "pin-project-lite", ] -[[package]] -name = "async-stream-impl" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25f9db3b38af870bf7e5cc649167533b493928e50744e2c30ae350230b414670" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "async-stream-impl" version = "0.3.5" @@ -3022,19 +2967,16 @@ dependencies = [ name = "exex-remote" version = "0.0.0" dependencies = [ - "async-stream 0.2.1", + "bincode", "eyre", "futures", "prost", - "rand 0.8.5", "reth", "reth-exex", "reth-exex-test-utils", "reth-node-api", "reth-node-ethereum", "reth-tracing", - "serde", - "serde_json", "tokio", "tokio-stream", "tonic", @@ -3045,7 +2987,7 @@ dependencies = [ name = "exex-rollup" version = "0.0.0" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-rlp", "alloy-sol-types", "eyre", @@ -3210,10 +3152,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "195bb5b228e1215c50d828f3e7d48a809a0af2bc0120462710ea5e7fcba3cbe2" dependencies = [ "alloy-chains", - "alloy-eips 0.1.1", + "alloy-eips", "alloy-primitives", - "alloy-rpc-types-eth 0.1.1", - "alloy-serde 0.1.1", + "alloy-rpc-types-eth", + "alloy-serde", "chrono", "reqwest", "serde", @@ -4651,7 +4593,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-targets 0.48.5", + "windows-targets 0.52.5", ] [[package]] @@ -6655,8 +6597,8 @@ dependencies = [ name = "reth-bench" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-json-rpc", "alloy-provider", "alloy-pubsub", @@ -6739,7 +6681,7 @@ name = "reth-chainspec" version = "1.0.0-rc.1" dependencies = [ "alloy-chains", - "alloy-eips 0.1.0", + "alloy-eips", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -6770,8 +6712,8 @@ dependencies = [ name = "reth-codecs" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-genesis", "alloy-primitives", "arbitrary", @@ -6833,8 +6775,8 @@ dependencies = [ name = "reth-consensus-debug-client" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-provider", "auto_impl", "eyre", @@ -7054,7 +6996,7 @@ dependencies = [ name = "reth-e2e-test-utils" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-network", "alloy-rpc-types", "alloy-signer", @@ -7136,7 +7078,7 @@ version = "1.0.0-rc.1" dependencies = [ "alloy-rlp", "arbitrary", - "async-stream 0.3.5", + "async-stream", "bytes", "derive_more", "futures", @@ -7170,7 +7112,7 @@ version = "1.0.0-rc.1" dependencies = [ "alloy-rlp", "arbitrary", - "async-stream 0.3.5", + "async-stream", "bytes", "derive_more", "proptest", @@ -7275,7 +7217,7 @@ dependencies = [ name = "reth-evm-ethereum" version = "1.0.0-rc.1" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-sol-types", "reth-ethereum-consensus", "reth-evm", @@ -7311,7 +7253,7 @@ dependencies = [ name = "reth-execution-errors" version = "1.0.0-rc.1" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-primitives", "reth-consensus", "reth-prune-types", @@ -7324,12 +7266,13 @@ dependencies = [ name = "reth-execution-types" version = "1.0.0-rc.1" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-primitives", "reth-execution-errors", "reth-primitives", "reth-trie", "revm", + "serde", ] [[package]] @@ -7921,8 +7864,8 @@ dependencies = [ name = "reth-primitives" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -7968,12 +7911,12 @@ dependencies = [ name = "reth-primitives-traits" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", - "alloy-eips 0.1.0", + "alloy-consensus", + "alloy-eips", "alloy-genesis", "alloy-primitives", "alloy-rlp", - "alloy-rpc-types-eth 0.1.0", + "alloy-rpc-types-eth", "arbitrary", "bytes", "derive_more", @@ -8079,7 +8022,7 @@ dependencies = [ name = "reth-revm" version = "1.0.0-rc.1" dependencies = [ - "alloy-eips 0.1.0", + "alloy-eips", "alloy-rlp", "reth-consensus-common", "reth-execution-errors", @@ -8288,7 +8231,7 @@ dependencies = [ "alloy-rpc-types-engine", "alloy-rpc-types-trace", "alloy-rpc-types-txpool", - "alloy-serde 0.1.0", + "alloy-serde", "arbitrary", "bytes", "jsonrpsee-types", @@ -8563,6 +8506,7 @@ dependencies = [ "reth-storage-errors", "reth-trie-common", "revm", + "serde", "serde_json", "similar-asserts", "tokio", @@ -8575,7 +8519,7 @@ dependencies = [ name = "reth-trie-common" version = "1.0.0-rc.1" dependencies = [ - "alloy-consensus 0.1.0", + "alloy-consensus", "alloy-genesis", "alloy-primitives", "alloy-rlp", @@ -8627,7 +8571,7 @@ dependencies = [ [[package]] name = "revm" version = "9.0.0" -source = "git+https://github.com/bluealloy/revm.git?rev=dd98b3b#dd98b3bb977396d23966e0a2f40d97678d931573" +source = "git+https://github.com/bluealloy/revm.git?rev=41e2f7f#41e2f7f9740c0fb70c5ba888a36453712b6de39c" dependencies = [ "auto_impl", "cfg-if", @@ -8641,7 +8585,7 @@ dependencies = [ [[package]] name = "revm-inspectors" version = "0.1.0" -source = "git+https://github.com/paradigmxyz/revm-inspectors?rev=79774a6#79774a6e4add9da9247130bf73305531092d0895" +source = "git+https://github.com/paradigmxyz/revm-inspectors?rev=92d3893#92d38937832e86214e47c5234ba5aae15ead4a13" dependencies = [ "alloy-primitives", "alloy-rpc-types", @@ -8658,7 +8602,7 @@ dependencies = [ [[package]] name = "revm-interpreter" version = "5.0.0" -source = "git+https://github.com/bluealloy/revm.git?rev=dd98b3b#dd98b3bb977396d23966e0a2f40d97678d931573" +source = "git+https://github.com/bluealloy/revm.git?rev=41e2f7f#41e2f7f9740c0fb70c5ba888a36453712b6de39c" dependencies = [ "revm-primitives", "serde", @@ -8667,7 +8611,7 @@ dependencies = [ [[package]] name = "revm-precompile" version = "7.0.0" -source = "git+https://github.com/bluealloy/revm.git?rev=dd98b3b#dd98b3bb977396d23966e0a2f40d97678d931573" +source = "git+https://github.com/bluealloy/revm.git?rev=41e2f7f#41e2f7f9740c0fb70c5ba888a36453712b6de39c" dependencies = [ "aurora-engine-modexp", "blst", @@ -8685,7 +8629,7 @@ dependencies = [ [[package]] name = "revm-primitives" version = "4.0.0" -source = "git+https://github.com/bluealloy/revm.git?rev=dd98b3b#dd98b3bb977396d23966e0a2f40d97678d931573" +source = "git+https://github.com/bluealloy/revm.git?rev=41e2f7f#41e2f7f9740c0fb70c5ba888a36453712b6de39c" dependencies = [ "alloy-primitives", "auto_impl", @@ -10169,7 +10113,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76c4eb7a4e9ef9d4763600161f12f5070b92a578e1b634db88a6887844c91a13" dependencies = [ - "async-stream 0.3.5", + "async-stream", "async-trait", "axum", "base64 0.21.7", diff --git a/Cargo.toml b/Cargo.toml index 63d297ab88d0..fa58e035f150 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -346,7 +346,7 @@ revm = { version = "9.0.0", features = [ revm-primitives = { version = "4.0.0", features = [ "std", ], default-features = false } -revm-inspectors = { git = "https://github.com/paradigmxyz/revm-inspectors", rev = "79774a6" } +revm-inspectors = { git = "https://github.com/paradigmxyz/revm-inspectors", rev = "92d3893" } # eth alloy-chains = "0.1.15" @@ -355,36 +355,36 @@ alloy-dyn-abi = "0.7.2" alloy-sol-types = "0.7.2" alloy-rlp = "0.3.4" alloy-trie = "0.4" -alloy-rpc-types = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false, features = [ +alloy-rpc-types = { version = "0.1", default-features = false, features = [ "eth", ] } -alloy-rpc-types-anvil = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-beacon = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-admin = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-txpool = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-serde = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-engine = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-eth = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-types-trace = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-genesis = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-node-bindings = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-provider = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false, features = [ +alloy-rpc-types-anvil = { version = "0.1", default-features = false } +alloy-rpc-types-beacon = { version = "0.1", default-features = false } +alloy-rpc-types-admin = { version = "0.1", default-features = false } +alloy-rpc-types-txpool = { version = "0.1", default-features = false } +alloy-serde = { version = "0.1", default-features = false } +alloy-rpc-types-engine = { version = "0.1", default-features = false } +alloy-rpc-types-eth = { version = "0.1", default-features = false } +alloy-rpc-types-trace = { version = "0.1", default-features = false } +alloy-genesis = { version = "0.1", default-features = false } +alloy-node-bindings = { version = "0.1", default-features = false } +alloy-provider = { version = "0.1", default-features = false, features = [ "reqwest", ] } -alloy-eips = { git = "https://github.com/alloy-rs/alloy", default-features = false, rev = "6cb3713" } -alloy-signer = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-signer-local = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-network = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-consensus = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-transport = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713" } -alloy-transport-http = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", features = [ +alloy-eips = { version = "0.1", default-features = false } +alloy-signer = { version = "0.1", default-features = false } +alloy-signer-local = { version = "0.1", default-features = false } +alloy-network = { version = "0.1", default-features = false } +alloy-consensus = { version = "0.1", default-features = false } +alloy-transport = { version = "0.1" } +alloy-transport-http = { version = "0.1", features = [ "reqwest-rustls-tls", ], default-features = false } -alloy-transport-ws = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-transport-ipc = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-pubsub = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-json-rpc = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } -alloy-rpc-client = { git = "https://github.com/alloy-rs/alloy", rev = "6cb3713", default-features = false } +alloy-transport-ws = { version = "0.1", default-features = false } +alloy-transport-ipc = { version = "0.1", default-features = false } +alloy-pubsub = { version = "0.1", default-features = false } +alloy-json-rpc = { version = "0.1", default-features = false } +alloy-rpc-client = { version = "0.1", default-features = false } # misc auto_impl = "1" @@ -499,7 +499,7 @@ similar-asserts = "1.5.0" test-fuzz = "5" [patch.crates-io] -revm = { git = "https://github.com/bluealloy/revm.git", rev = "dd98b3b" } -revm-interpreter = { git = "https://github.com/bluealloy/revm.git", rev = "dd98b3b" } -revm-precompile = { git = "https://github.com/bluealloy/revm.git", rev = "dd98b3b" } -revm-primitives = { git = "https://github.com/bluealloy/revm.git", rev = "dd98b3b" } +revm = { git = "https://github.com/bluealloy/revm.git", rev = "41e2f7f" } +revm-interpreter = { git = "https://github.com/bluealloy/revm.git", rev = "41e2f7f" } +revm-precompile = { git = "https://github.com/bluealloy/revm.git", rev = "41e2f7f" } +revm-primitives = { git = "https://github.com/bluealloy/revm.git", rev = "41e2f7f" } diff --git a/crates/evm/execution-types/Cargo.toml b/crates/evm/execution-types/Cargo.toml index 5f61a1eb8885..bcf3aa155647 100644 --- a/crates/evm/execution-types/Cargo.toml +++ b/crates/evm/execution-types/Cargo.toml @@ -17,10 +17,13 @@ reth-trie.workspace = true revm.workspace = true +serde = { workspace = true, optional = true } + [dev-dependencies] reth-primitives = { workspace = true, features = ["test-utils"] } alloy-primitives.workspace = true alloy-eips.workspace = true [features] -optimism = [] \ No newline at end of file +serde = ["dep:serde", "reth-trie/serde", "revm/serde"] +optimism = [] diff --git a/crates/storage/provider/Cargo.toml b/crates/storage/provider/Cargo.toml index 6c1e02d6dde9..9836fac9489a 100644 --- a/crates/storage/provider/Cargo.toml +++ b/crates/storage/provider/Cargo.toml @@ -72,6 +72,6 @@ assert_matches.workspace = true rand.workspace = true [features] -serde = ["dep:serde", "reth-execution-types/serde"] +serde = ["reth-execution-types/serde"] test-utils = ["alloy-rlp", "reth-db/test-utils", "reth-nippy-jar/test-utils"] optimism = ["reth-primitives/optimism", "reth-execution-types/optimism"] diff --git a/crates/trie/trie/Cargo.toml b/crates/trie/trie/Cargo.toml index d01914759a87..4ae09f557e78 100644 --- a/crates/trie/trie/Cargo.toml +++ b/crates/trie/trie/Cargo.toml @@ -40,6 +40,9 @@ metrics = { workspace = true, optional = true } # `test-utils` feature triehash = { version = "0.8", optional = true } +# `serde` feature +serde = { workspace = true, optional = true } + [dev-dependencies] # reth reth-primitives = { workspace = true, features = ["test-utils", "arbitrary"] } @@ -66,6 +69,7 @@ criterion.workspace = true [features] metrics = ["reth-metrics", "dep:metrics"] +serde = ["dep:serde"] test-utils = ["triehash", "reth-trie-common/test-utils"] [[bench]] diff --git a/crates/trie/trie/src/updates.rs b/crates/trie/trie/src/updates.rs index 457266eeabab..39628e6d5272 100644 --- a/crates/trie/trie/src/updates.rs +++ b/crates/trie/trie/src/updates.rs @@ -13,6 +13,7 @@ use std::collections::{hash_map::IntoIter, HashMap, HashSet}; /// The key of a trie node. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum TrieKey { /// A node in the account trie. AccountNode(StoredNibbles), @@ -24,6 +25,7 @@ pub enum TrieKey { /// The operation to perform on the trie. #[derive(PartialEq, Eq, Debug, Clone)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum TrieOp { /// Delete the node entry. Delete, @@ -40,6 +42,7 @@ impl TrieOp { /// The aggregation of trie updates. #[derive(Debug, Default, Clone, PartialEq, Eq, Deref)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct TrieUpdates { trie_operations: HashMap, } diff --git a/examples/exex/remote/Cargo.toml b/examples/exex/remote/Cargo.toml index dc928002e67f..7ca78689fe98 100644 --- a/examples/exex/remote/Cargo.toml +++ b/examples/exex/remote/Cargo.toml @@ -20,10 +20,7 @@ prost = "0.12" tokio = { version = "1.0", features = ["full"] } tokio-stream = "0.1" -async-stream = "0.2" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -rand = "0.8" +bincode = "1.3" [build-dependencies] tonic-build = "0.11" diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs index 8567154ffb93..39b4e5740175 100644 --- a/examples/exex/remote/bin/consumer.rs +++ b/examples/exex/remote/bin/consumer.rs @@ -1,13 +1,14 @@ -use exex_remote::{ - codec::from_u8_slice, - proto::{ - remote_ex_ex_client::RemoteExExClient, ExExNotification as ProtoExExNotification, - Notification, SubscribeRequest, - }, +use exex_remote::proto::{ + remote_ex_ex_client::RemoteExExClient, ExExNotification as ProtoExExNotification, Notification, + SubscribeRequest, }; +use reth_exex::ExExNotification; +use reth_tracing::{tracing::info, RethTracer, Tracer}; #[tokio::main] async fn main() -> eyre::Result<()> { + let _ = RethTracer::new().init()?; + let mut client = RemoteExExClient::connect("http://[::1]:10000").await?; let mut stream = client @@ -22,11 +23,19 @@ async fn main() -> eyre::Result<()> { .into_inner(); while let Some(Notification { data }) = stream.message().await? { - // TODO(alexey): it doesn't work, because data inside the notification is boxed. - // We need to implement a proper encoding via Serde. - // let notification = unsafe { from_u8_slice(&data) }; - // println!("{:?}", notification); - println!("{:?}", data); + let notification = bincode::deserialize::(&data)?; + + match notification { + ExExNotification::ChainCommitted { new } => { + info!(committed_chain = ?new.range(), "Received commit"); + } + ExExNotification::ChainReorged { old, new } => { + info!(from_chain = ?old.range(), to_chain = ?new.range(), "Received reorg"); + } + ExExNotification::ChainReverted { old } => { + info!(reverted_chain = ?old.range(), "Received revert"); + } + }; } Ok(()) diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index 4f2718486caa..936e0a986798 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -1,12 +1,9 @@ use std::sync::Arc; -use exex_remote::{ - codec::to_u8_slice, - proto::{ - remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, - ExExNotification as ProtoExExNotification, Notification as ProtoNotification, - SubscribeRequest as ProtoSubscribeRequest, - }, +use exex_remote::proto::{ + remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, + ExExNotification as ProtoExExNotification, Notification as ProtoNotification, + SubscribeRequest as ProtoSubscribeRequest, }; use futures::TryFutureExt; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; @@ -59,7 +56,8 @@ impl RemoteExEx for ExExService { while let Ok(notification) = notifications.recv().await { if matches_filter(¬ification) { tx.send(Ok(ProtoNotification { - data: unsafe { to_u8_slice(¬ification) }.to_vec(), + data: bincode::serialize(¬ification) + .expect("failed to serialize notification"), })) .await .expect("failed to send notification to client"); diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs deleted file mode 100644 index c8c49ac1d0fa..000000000000 --- a/examples/exex/remote/src/codec.rs +++ /dev/null @@ -1,12 +0,0 @@ -use reth_exex::ExExNotification; - -pub unsafe fn to_u8_slice(notification: &ExExNotification) -> &[u8] { - core::slice::from_raw_parts( - (notification as *const ExExNotification) as *const u8, - core::mem::size_of::(), - ) -} - -pub unsafe fn from_u8_slice(bytes: &[u8]) -> &ExExNotification { - unsafe { &*(bytes.as_ptr() as *const reth_exex::ExExNotification) } -} diff --git a/examples/exex/remote/src/lib.rs b/examples/exex/remote/src/lib.rs index 9b8aa5781a8f..9abb458bd3c0 100644 --- a/examples/exex/remote/src/lib.rs +++ b/examples/exex/remote/src/lib.rs @@ -1,4 +1,3 @@ -pub mod codec; pub mod proto { tonic::include_proto!("exex"); } From 5b6a9d8058379ec4aa64a10b9a180b91ed787a19 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 17 Jun 2024 17:37:39 +0100 Subject: [PATCH 03/16] simplify service --- examples/exex/remote/bin/consumer.rs | 17 ++-------- examples/exex/remote/bin/exex.rs | 45 +++++---------------------- examples/exex/remote/proto/exex.proto | 10 +----- 3 files changed, 11 insertions(+), 61 deletions(-) diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs index 39b4e5740175..c48da7d97442 100644 --- a/examples/exex/remote/bin/consumer.rs +++ b/examples/exex/remote/bin/consumer.rs @@ -1,7 +1,4 @@ -use exex_remote::proto::{ - remote_ex_ex_client::RemoteExExClient, ExExNotification as ProtoExExNotification, Notification, - SubscribeRequest, -}; +use exex_remote::proto::{remote_ex_ex_client::RemoteExExClient, Notification, SubscribeRequest}; use reth_exex::ExExNotification; use reth_tracing::{tracing::info, RethTracer, Tracer}; @@ -11,17 +8,7 @@ async fn main() -> eyre::Result<()> { let mut client = RemoteExExClient::connect("http://[::1]:10000").await?; - let mut stream = client - .subscribe(SubscribeRequest { - notifications: vec![ - ProtoExExNotification::ChainCommitted as i32, - ProtoExExNotification::ChainReorged as i32, - ProtoExExNotification::ChainReverted as i32, - ], - }) - .await? - .into_inner(); - + let mut stream = client.subscribe(SubscribeRequest {}).await?.into_inner(); while let Some(Notification { data }) = stream.message().await? { let notification = bincode::deserialize::(&data)?; diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index 936e0a986798..cb8bf5a4128b 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -2,8 +2,7 @@ use std::sync::Arc; use exex_remote::proto::{ remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, - ExExNotification as ProtoExExNotification, Notification as ProtoNotification, - SubscribeRequest as ProtoSubscribeRequest, + Notification as ProtoNotification, SubscribeRequest as ProtoSubscribeRequest, }; use futures::TryFutureExt; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; @@ -25,43 +24,19 @@ impl RemoteExEx for ExExService { async fn subscribe( &self, - request: Request, + _request: Request, ) -> Result, Status> { let (tx, rx) = mpsc::channel(1); let mut notifications = self.notifications.subscribe(); - let filter = request - .into_inner() - .notifications - .into_iter() - .map(|notification| { - move |exex_notification: &ExExNotification| match notification.try_into() { - Ok(ProtoExExNotification::ChainCommitted) => { - matches!(exex_notification, ExExNotification::ChainCommitted { .. }) - } - Ok(ProtoExExNotification::ChainReorged) => { - matches!(exex_notification, ExExNotification::ChainReorged { .. }) - } - Ok(ProtoExExNotification::ChainReverted) => { - matches!(exex_notification, ExExNotification::ChainReverted { .. }) - } - Err(_) => false, - } - }) - .collect::>(); - let matches_filter = - move |exex_notification: &ExExNotification| filter.iter().any(|f| f(exex_notification)); - tokio::spawn(async move { while let Ok(notification) = notifications.recv().await { - if matches_filter(¬ification) { - tx.send(Ok(ProtoNotification { - data: bincode::serialize(¬ification) - .expect("failed to serialize notification"), - })) - .await - .expect("failed to send notification to client"); - } + tx.send(Ok(ProtoNotification { + data: bincode::serialize(¬ification) + .expect("failed to serialize notification"), + })) + .await + .expect("failed to send notification to client"); } }); @@ -69,10 +44,6 @@ impl RemoteExEx for ExExService { } } -/// An ExEx is just a future, which means you can implement all of it in an async function! -/// -/// This ExEx just prints out whenever either a new chain of blocks being added, or a chain of -/// blocks being re-orged. After processing the chain, emits an [ExExEvent::FinishedHeight] event. async fn exex( mut ctx: ExExContext, notifications: Arc>, diff --git a/examples/exex/remote/proto/exex.proto b/examples/exex/remote/proto/exex.proto index be3e89c35e1b..9c8cdac39c11 100644 --- a/examples/exex/remote/proto/exex.proto +++ b/examples/exex/remote/proto/exex.proto @@ -6,15 +6,7 @@ service RemoteExEx { rpc Subscribe(SubscribeRequest) returns (stream Notification) {} } -message SubscribeRequest { - repeated ExExNotification notifications = 1; -} - -enum ExExNotification { - CHAIN_COMMITTED = 0; - CHAIN_REORGED = 1; - CHAIN_REVERTED = 2; -} +message SubscribeRequest {} message Notification { bytes data = 1; From 19fed4c3b6fc560d7e25d1df099853c069d1eb0a Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 17 Jun 2024 17:43:26 +0100 Subject: [PATCH 04/16] do not log in exex --- examples/exex/remote/bin/exex.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index cb8bf5a4128b..af956d2f1df9 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -8,7 +8,6 @@ use futures::TryFutureExt; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; use reth_node_api::FullNodeComponents; use reth_node_ethereum::EthereumNode; -use reth_tracing::tracing::info; use tokio::sync::{broadcast, mpsc}; use tokio_stream::wrappers::ReceiverStream; use tonic::{transport::Server, Request, Response, Status}; @@ -49,18 +48,6 @@ async fn exex( notifications: Arc>, ) -> eyre::Result<()> { while let Some(notification) = ctx.notifications.recv().await { - match ¬ification { - ExExNotification::ChainCommitted { new } => { - info!(committed_chain = ?new.range(), "Received commit"); - } - ExExNotification::ChainReorged { old, new } => { - info!(from_chain = ?old.range(), to_chain = ?new.range(), "Received reorg"); - } - ExExNotification::ChainReverted { old } => { - info!(reverted_chain = ?old.range(), "Received revert"); - } - }; - if let Some(committed_chain) = notification.committed_chain() { ctx.events.send(ExExEvent::FinishedHeight(committed_chain.tip().number))?; } From be0adf4e454da6691101f2f9837f684cdda928f0 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 17 Jun 2024 17:59:11 +0100 Subject: [PATCH 05/16] exclude exex example from CI --- .github/workflows/integration.yml | 2 +- .github/workflows/unit.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 319896154b19..9c12d513f7ed 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -41,7 +41,7 @@ jobs: run: | cargo nextest run \ --locked --features "asm-keccak ${{ matrix.network }}" \ - --workspace --exclude examples --exclude ef-tests \ + --workspace --exclude examples --exclude exex-remote --exclude ef-tests \ -E "kind(test)" - if: matrix.network == 'optimism' name: Run tests diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index 05ff0960916c..de1cbe333927 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -39,7 +39,7 @@ jobs: run: | cargo nextest run \ --locked --features "asm-keccak ${{ matrix.network }}" \ - --workspace --exclude examples --exclude ef-tests \ + --workspace --exclude examples --exclude exex-remote --exclude ef-tests \ --partition hash:${{ matrix.partition }}/2 \ -E "!kind(test)" From b5f410a54953152576bb7458957eb60721f8e661 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Tue, 18 Jun 2024 15:37:10 +0100 Subject: [PATCH 06/16] protobuf rabbithole --- Cargo.lock | 5 - bin/reth/src/commands/common.rs | 2 +- bin/reth/src/commands/db/checksum.rs | 2 +- bin/reth/src/commands/db/diff.rs | 4 +- bin/reth/src/commands/db/list.rs | 2 +- bin/reth/src/commands/db/mod.rs | 2 +- bin/reth/src/commands/db/tui.rs | 2 +- bin/reth/src/commands/debug_cmd/execution.rs | 4 +- .../commands/debug_cmd/in_memory_merkle.rs | 2 +- bin/reth/src/commands/debug_cmd/merkle.rs | 6 +- bin/reth/src/commands/import_op.rs | 2 +- bin/reth/src/commands/import_receipts_op.rs | 2 +- .../commands/stage/dump/hashing_account.rs | 2 +- .../commands/stage/dump/hashing_storage.rs | 2 +- bin/reth/src/commands/stage/dump/merkle.rs | 2 +- bin/reth/src/commands/stage/run.rs | 2 +- bin/reth/src/commands/test_vectors/tables.rs | 2 +- bin/reth/src/sigsegv_handler.rs | 4 +- bin/reth/src/utils.rs | 12 +- crates/blockchain-tree/src/block_buffer.rs | 2 +- crates/blockchain-tree/src/block_indices.rs | 6 +- crates/blockchain-tree/src/blockchain_tree.rs | 56 +- crates/blockchain-tree/src/bundle.rs | 2 +- crates/blockchain-tree/src/chain.rs | 2 +- crates/blockchain-tree/src/state.rs | 2 +- crates/chainspec/src/spec.rs | 16 +- crates/config/src/config.rs | 2 +- crates/consensus/auto-seal/src/client.rs | 6 +- crates/consensus/auto-seal/src/mode.rs | 6 +- crates/consensus/auto-seal/src/task.rs | 10 +- .../beacon/src/engine/hooks/controller.rs | 6 +- .../beacon/src/engine/hooks/static_file.rs | 6 +- .../beacon/src/engine/invalid_headers.rs | 2 +- crates/consensus/beacon/src/engine/mod.rs | 82 +- crates/consensus/beacon/src/engine/sync.rs | 12 +- .../consensus/beacon/src/engine/test_utils.rs | 4 +- crates/consensus/common/src/validation.rs | 34 +- .../debug-client/src/providers/etherscan.rs | 2 +- crates/e2e-test-utils/src/node.rs | 6 +- crates/e2e-test-utils/src/payload.rs | 4 +- crates/ethereum-forks/src/forkid.rs | 14 +- crates/ethereum-forks/src/hardfork.rs | 20 +- crates/ethereum/consensus/src/lib.rs | 30 +- crates/ethereum/consensus/src/validation.rs | 12 +- crates/ethereum/evm/src/execute.rs | 2 +- crates/ethereum/payload/src/lib.rs | 12 +- crates/etl/src/lib.rs | 2 +- crates/evm/execution-types/src/chain.rs | 16 +- .../execution-types/src/execution_outcome.rs | 6 +- crates/exex/exex/src/manager.rs | 8 +- crates/metrics/metrics-derive/src/expand.rs | 20 +- crates/metrics/metrics-derive/src/metric.rs | 4 +- crates/net/common/src/ban_list.rs | 6 +- crates/net/common/src/ratelimit.rs | 2 +- crates/net/discv4/src/lib.rs | 64 +- crates/net/discv4/src/proto.rs | 24 +- crates/net/discv4/src/test_utils.rs | 4 +- crates/net/discv5/src/enr.rs | 2 +- crates/net/discv5/src/filter.rs | 4 +- crates/net/discv5/src/lib.rs | 12 +- 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 | 28 +- 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 +- .../downloaders/src/file_codec_ovm_receipt.rs | 2 +- .../src/headers/reverse_headers.rs | 50 +- crates/net/downloaders/src/headers/task.rs | 6 +- .../downloaders/src/receipt_file_client.rs | 2 +- .../src/test_utils/bodies_client.rs | 2 +- crates/net/ecies/src/algorithm.rs | 16 +- crates/net/ecies/src/codec.rs | 18 +- crates/net/eth-wire-types/src/broadcast.rs | 10 +- crates/net/eth-wire-types/src/message.rs | 6 +- crates/net/eth-wire/src/capability.rs | 10 +- crates/net/eth-wire/src/disconnect.rs | 11 +- crates/net/eth-wire/src/errors/eth.rs | 2 +- crates/net/eth-wire/src/ethstream.rs | 24 +- 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/protocol.rs | 2 +- crates/net/eth-wire/src/test_utils.rs | 2 +- crates/net/nat/src/lib.rs | 2 +- crates/net/network/src/discovery.rs | 4 +- crates/net/network/src/error.rs | 6 +- crates/net/network/src/eth_requests.rs | 26 +- crates/net/network/src/fetch/mod.rs | 14 +- crates/net/network/src/manager.rs | 4 +- crates/net/network/src/network.rs | 2 +- crates/net/network/src/peers/manager.rs | 44 +- crates/net/network/src/session/active.rs | 36 +- crates/net/network/src/session/config.rs | 2 +- crates/net/network/src/session/mod.rs | 6 +- crates/net/network/src/state.rs | 10 +- crates/net/network/src/swarm.rs | 22 +- crates/net/network/src/test_utils/init.rs | 2 +- crates/net/network/src/test_utils/testnet.rs | 6 +- .../net/network/src/transactions/fetcher.rs | 52 +- crates/net/network/src/transactions/mod.rs | 46 +- .../network/src/transactions/validation.rs | 6 +- crates/net/network/tests/it/multiplex.rs | 12 +- crates/net/p2p/src/error.rs | 2 +- crates/net/p2p/src/full_block.rs | 40 +- crates/net/p2p/src/test_utils/headers.rs | 14 +- crates/net/peers/src/lib.rs | 8 +- crates/net/peers/src/node_record.rs | 8 +- crates/net/peers/src/trusted_peer.rs | 4 +- crates/node-core/src/args/payload_builder.rs | 2 +- crates/node-core/src/args/pruning.rs | 2 +- crates/node-core/src/args/utils.rs | 8 +- crates/node-core/src/engine/skip_fcu.rs | 4 +- .../node-core/src/engine/skip_new_payload.rs | 4 +- .../src/metrics/prometheus_exporter.rs | 6 +- crates/node-core/src/node_config.rs | 4 +- crates/node/builder/src/launch/exex.rs | 2 +- crates/node/events/src/cl.rs | 8 +- crates/node/events/src/node.rs | 6 +- crates/optimism/consensus/src/lib.rs | 6 +- crates/optimism/consensus/src/validation.rs | 8 +- crates/optimism/evm/src/execute.rs | 4 +- crates/optimism/evm/src/l1.rs | 14 +- crates/optimism/node/src/engine.rs | 8 +- crates/optimism/node/src/txpool.rs | 6 +- crates/optimism/payload/src/builder.rs | 18 +- .../optimism/primitives/src/bedrock_import.rs | 4 +- crates/payload/basic/src/lib.rs | 16 +- crates/payload/builder/src/noop.rs | 2 +- crates/payload/builder/src/service.rs | 2 +- crates/payload/primitives/src/lib.rs | 16 +- crates/payload/primitives/src/traits.rs | 2 +- crates/payload/validator/src/lib.rs | 24 +- crates/primitives-traits/src/header/mod.rs | 8 +- crates/primitives/src/alloy_compat.rs | 4 +- crates/primitives/src/block.rs | 4 +- crates/primitives/src/compression/mod.rs | 2 +- crates/primitives/src/lib.rs | 2 +- crates/primitives/src/log.rs | 2 +- crates/primitives/src/proofs.rs | 6 +- crates/primitives/src/receipt.rs | 6 +- crates/primitives/src/revm/config.rs | 12 +- crates/primitives/src/transaction/mod.rs | 30 +- crates/primitives/src/transaction/pooled.rs | 8 +- crates/primitives/src/transaction/sidecar.rs | 10 +- .../primitives/src/transaction/signature.rs | 8 +- crates/primitives/src/transaction/tx_type.rs | 10 +- crates/prune/prune/Cargo.toml | 1 - crates/prune/prune/src/builder.rs | 2 +- crates/prune/prune/src/pruner.rs | 2 +- crates/revm/src/batch.rs | 4 +- crates/revm/src/state_change.rs | 14 +- crates/rpc/rpc-api/src/admin.rs | 3 +- crates/rpc/rpc-builder/Cargo.toml | 1 - crates/rpc/rpc-builder/tests/it/http.rs | 4 +- crates/rpc/rpc-builder/tests/it/utils.rs | 2 +- crates/rpc/rpc-engine-api/Cargo.toml | 1 - crates/rpc/rpc-engine-api/src/engine_api.rs | 6 +- crates/rpc/rpc/Cargo.toml | 1 - crates/rpc/rpc/src/admin.rs | 5 +- crates/rpc/rpc/src/eth/api/fee_history.rs | 3 +- crates/rpc/rpc/src/eth/api/mod.rs | 4 +- crates/rpc/rpc/src/eth/api/pending_block.rs | 5 +- crates/rpc/rpc/src/eth/api/server.rs | 5 +- crates/rpc/rpc/src/eth/filter.rs | 3 +- crates/rpc/rpc/src/eth/logs_utils.rs | 3 +- crates/stages/api/src/metrics/listener.rs | 2 +- crates/stages/api/src/pipeline/mod.rs | 20 +- crates/stages/api/src/pipeline/set.rs | 4 +- crates/stages/api/src/stage.rs | 2 +- crates/stages/stages/src/stages/bodies.rs | 22 +- crates/stages/stages/src/stages/execution.rs | 12 +- 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 | 16 +- .../src/stages/index_account_history.rs | 4 +- .../src/stages/index_storage_history.rs | 4 +- crates/stages/stages/src/stages/merkle.rs | 14 +- .../stages/src/stages/sender_recovery.rs | 8 +- crates/stages/stages/src/stages/tx_lookup.rs | 8 +- .../stages/stages/src/test_utils/test_db.rs | 2 +- crates/stages/types/src/checkpoints.rs | 2 +- .../static-file/src/static_file_producer.rs | 2 +- crates/static-file/types/src/segment.rs | 4 +- .../codecs/derive/src/compact/flags.rs | 4 +- .../codecs/derive/src/compact/generator.rs | 2 +- .../storage/codecs/derive/src/compact/mod.rs | 2 +- .../codecs/derive/src/compact/structs.rs | 2 +- crates/storage/codecs/src/lib.rs | 10 +- crates/storage/db-api/src/cursor.rs | 8 +- crates/storage/db-common/src/init.rs | 8 +- .../storage/db/src/implementation/mdbx/mod.rs | 4 +- crates/storage/db/src/lockfile.rs | 2 +- crates/storage/db/src/static_file/cursor.rs | 4 +- .../db/src/tables/codecs/fuzz/inputs.rs | 2 +- crates/storage/db/src/version.rs | 2 +- crates/storage/libmdbx-rs/src/codec.rs | 2 +- crates/storage/libmdbx-rs/src/cursor.rs | 6 +- crates/storage/libmdbx-rs/src/environment.rs | 8 +- 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/cursor.rs | 12 +- crates/storage/nippy-jar/src/filter/cuckoo.rs | 2 +- crates/storage/nippy-jar/src/lib.rs | 10 +- crates/storage/nippy-jar/src/phf/fmph.rs | 4 +- crates/storage/nippy-jar/src/phf/go_fmph.rs | 4 +- crates/storage/nippy-jar/src/writer.rs | 14 +- .../src/providers/bundle_state_provider.rs | 6 +- .../provider/src/providers/consistent_view.rs | 4 +- .../provider/src/providers/database/mod.rs | 2 +- .../src/providers/database/provider.rs | 64 +- crates/storage/provider/src/providers/mod.rs | 4 +- .../src/providers/state/historical.rs | 6 +- .../provider/src/providers/state/latest.rs | 2 +- .../provider/src/providers/static_file/jar.rs | 4 +- .../src/providers/static_file/manager.rs | 38 +- .../src/providers/static_file/writer.rs | 10 +- .../storage/provider/src/test_utils/mock.rs | 4 +- crates/storage/provider/src/traits/chain.rs | 4 +- crates/storage/storage-api/src/receipts.rs | 2 +- crates/storage/storage-api/src/state.rs | 4 +- crates/tasks/src/lib.rs | 2 +- crates/tokio-util/src/event_stream.rs | 2 +- crates/transaction-pool/Cargo.toml | 1 - crates/transaction-pool/src/lib.rs | 6 +- crates/transaction-pool/src/maintain.rs | 3 +- crates/transaction-pool/src/test_utils/gen.rs | 3 +- crates/transaction-pool/src/validate/eth.rs | 10 +- crates/transaction-pool/src/validate/task.rs | 3 +- crates/trie/trie/benches/prefix_set.rs | 8 +- .../trie/trie/src/hashed_cursor/post_state.rs | 4 +- crates/trie/trie/src/node_iter.rs | 6 +- crates/trie/trie/src/prefix_set/mod.rs | 8 +- crates/trie/trie/src/proof.rs | 2 +- crates/trie/trie/src/trie.rs | 4 +- crates/trie/trie/src/updates.rs | 2 +- crates/trie/trie/src/walker.rs | 10 +- .../src/mined_sidecar.rs | 6 +- examples/custom-engine-types/src/main.rs | 2 +- examples/exex/remote/bin/consumer.rs | 9 +- examples/exex/remote/bin/exex.rs | 20 +- examples/exex/remote/proto/exex.proto | 272 +++++- examples/exex/remote/src/codec.rs | 822 ++++++++++++++++++ examples/exex/remote/src/lib.rs | 1 + examples/exex/rollup/src/execution.rs | 4 +- examples/exex/rollup/src/main.rs | 8 +- examples/manual-p2p/src/main.rs | 6 +- examples/node-custom-rpc/src/main.rs | 2 +- testing/ef-tests/src/cases/blockchain_test.rs | 2 +- testing/ef-tests/src/models.rs | 4 +- testing/testing-utils/src/generators.rs | 2 +- 257 files changed, 2211 insertions(+), 1129 deletions(-) create mode 100644 examples/exex/remote/src/codec.rs diff --git a/Cargo.lock b/Cargo.lock index 8a0c8c3bb065..98f774df9c1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8020,7 +8020,6 @@ dependencies = [ "itertools 0.12.1", "metrics", "rayon", - "reth-chainspec", "reth-config", "reth-db", "reth-db-api", @@ -8099,7 +8098,6 @@ dependencies = [ "parking_lot 0.12.3", "pin-project", "rand 0.8.5", - "reth-chainspec", "reth-consensus-common", "reth-errors", "reth-evm", @@ -8173,7 +8171,6 @@ dependencies = [ "metrics", "pin-project", "reth-beacon-consensus", - "reth-chainspec", "reth-engine-primitives", "reth-ethereum-engine-primitives", "reth-evm", @@ -8216,7 +8213,6 @@ dependencies = [ "jsonrpsee-types", "metrics", "reth-beacon-consensus", - "reth-chainspec", "reth-engine-primitives", "reth-ethereum-engine-primitives", "reth-evm", @@ -8512,7 +8508,6 @@ dependencies = [ "pprof", "proptest", "rand 0.8.5", - "reth-chainspec", "reth-eth-wire-types", "reth-fs-util", "reth-metrics", diff --git a/bin/reth/src/commands/common.rs b/bin/reth/src/commands/common.rs index 329047cdddae..8740314aa891 100644 --- a/bin/reth/src/commands/common.rs +++ b/bin/reth/src/commands/common.rs @@ -116,7 +116,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); } let prune_modes = config.prune.clone().map(|prune| prune.segments).unwrap_or_default(); diff --git a/bin/reth/src/commands/db/checksum.rs b/bin/reth/src/commands/db/checksum.rs index 6aa6b69e6d3b..b0dbb1f7732b 100644 --- a/bin/reth/src/commands/db/checksum.rs +++ b/bin/reth/src/commands/db/checksum.rs @@ -115,7 +115,7 @@ impl TableViewer<(u64, Duration)> for ChecksumViewer<'_, DB> { total = index + 1; if total >= limit { - break + break; } } diff --git a/bin/reth/src/commands/db/diff.rs b/bin/reth/src/commands/db/diff.rs index 246b107fa4a1..fda004f3c34c 100644 --- a/bin/reth/src/commands/db/diff.rs +++ b/bin/reth/src/commands/db/diff.rs @@ -298,12 +298,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/bin/reth/src/commands/db/list.rs b/bin/reth/src/commands/db/list.rs index dd1a1846acbd..4689bbfdc0fa 100644 --- a/bin/reth/src/commands/db/list.rs +++ b/bin/reth/src/commands/db/list.rs @@ -62,7 +62,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/bin/reth/src/commands/db/mod.rs b/bin/reth/src/commands/db/mod.rs index fcafcc41ac09..b4e4ded41aed 100644 --- a/bin/reth/src/commands/db/mod.rs +++ b/bin/reth/src/commands/db/mod.rs @@ -110,7 +110,7 @@ impl Command { if !input.trim().eq_ignore_ascii_case("y") { println!("Database drop aborted!"); - return Ok(()) + return Ok(()); } } diff --git a/bin/reth/src/commands/db/tui.rs b/bin/reth/src/commands/db/tui.rs index 746f2cd974f1..2c40308d87cf 100644 --- a/bin/reth/src/commands/db/tui.rs +++ b/bin/reth/src/commands/db/tui.rs @@ -295,7 +295,7 @@ where } } - return Ok(false) + return Ok(false); } match event { diff --git a/bin/reth/src/commands/debug_cmd/execution.rs b/bin/reth/src/commands/debug_cmd/execution.rs index c1fd4cfa5fa2..f37825e45c67 100644 --- a/bin/reth/src/commands/debug_cmd/execution.rs +++ b/bin/reth/src/commands/debug_cmd/execution.rs @@ -153,7 +153,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..."); @@ -202,7 +202,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(()); } let pipeline_events = pipeline.events(); diff --git a/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs b/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs index aef62326a1a5..8b2c0e867ea9 100644 --- a/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs +++ b/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs @@ -156,7 +156,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.provider_rw()?; diff --git a/bin/reth/src/commands/debug_cmd/merkle.rs b/bin/reth/src/commands/debug_cmd/merkle.rs index 46e76d1da090..76b2e87e65fa 100644 --- a/bin/reth/src/commands/debug_cmd/merkle.rs +++ b/bin/reth/src/commands/debug_cmd/merkle.rs @@ -190,7 +190,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"); @@ -210,7 +210,7 @@ impl Command { let clean_result = merkle_stage.execute(&provider_rw, clean_input); assert!(clean_result.is_ok(), "Clean state root calculation failed"); if clean_result.unwrap().done { - break + break; } } @@ -270,7 +270,7 @@ impl Command { 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/bin/reth/src/commands/import_op.rs b/bin/reth/src/commands/import_op.rs index 646cd4f97232..3e2cae23c1d9 100644 --- a/bin/reth/src/commands/import_op.rs +++ b/bin/reth/src/commands/import_op.rs @@ -83,7 +83,7 @@ impl ImportOpCommand { body.transactions.retain(|_| { if is_dup_tx(block_number) { total_filtered_out_dup_txns += 1; - return false + return false; } true }) diff --git a/bin/reth/src/commands/import_receipts_op.rs b/bin/reth/src/commands/import_receipts_op.rs index 9d84cdd01fc0..cad0aa64cd32 100644 --- a/bin/reth/src/commands/import_receipts_op.rs +++ b/bin/reth/src/commands/import_receipts_op.rs @@ -154,7 +154,7 @@ where if total_decoded_receipts == 0 { error!(target: "reth::cli", "No receipts were imported, ensure the receipt file is valid and not empty"); - return Ok(()) + return Ok(()); } let total_imported_receipts = static_file_provider diff --git a/bin/reth/src/commands/stage/dump/hashing_account.rs b/bin/reth/src/commands/stage/dump/hashing_account.rs index 2e50a8ad6059..116d4919733e 100644 --- a/bin/reth/src/commands/stage/dump/hashing_account.rs +++ b/bin/reth/src/commands/stage/dump/hashing_account.rs @@ -90,7 +90,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/bin/reth/src/commands/stage/dump/hashing_storage.rs b/bin/reth/src/commands/stage/dump/hashing_storage.rs index 1dfd722f5099..d5671aae024d 100644 --- a/bin/reth/src/commands/stage/dump/hashing_storage.rs +++ b/bin/reth/src/commands/stage/dump/hashing_storage.rs @@ -85,7 +85,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/bin/reth/src/commands/stage/dump/merkle.rs b/bin/reth/src/commands/stage/dump/merkle.rs index fa345bb474a4..451133dc2085 100644 --- a/bin/reth/src/commands/stage/dump/merkle.rs +++ b/bin/reth/src/commands/stage/dump/merkle.rs @@ -161,7 +161,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break + break; } } diff --git a/bin/reth/src/commands/stage/run.rs b/bin/reth/src/commands/stage/run.rs index 01a57fd52f4d..050895e1130c 100644 --- a/bin/reth/src/commands/stage/run.rs +++ b/bin/reth/src/commands/stage/run.rs @@ -281,7 +281,7 @@ impl Command { } if done { - break + break; } } info!(target: "reth::cli", stage = %self.stage, time = ?start.elapsed(), "Finished stage"); diff --git a/bin/reth/src/commands/test_vectors/tables.rs b/bin/reth/src/commands/test_vectors/tables.rs index 9442f52aef4f..0cd2cf04d7e9 100644 --- a/bin/reth/src/commands/test_vectors/tables.rs +++ b/bin/reth/src/commands/test_vectors/tables.rs @@ -133,7 +133,7 @@ where let key: T::Key = strat_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/bin/reth/src/sigsegv_handler.rs b/bin/reth/src/sigsegv_handler.rs index 9e6833b75404..fea00c6a617c 100644 --- a/bin/reth/src/sigsegv_handler.rs +++ b/bin/reth/src/sigsegv_handler.rs @@ -51,7 +51,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.as_slice()[0..(depth as _)] }; @@ -69,7 +69,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/bin/reth/src/utils.rs b/bin/reth/src/utils.rs index 1dd4f6893c1f..509da8624320 100644 --- a/bin/reth/src/utils.rs +++ b/bin/reth/src/utils.rs @@ -68,18 +68,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(), @@ -93,12 +93,12 @@ impl DbTool { searcher.find_first_in(&key).is_some() { hits += 1; - return result() + return result(); } } None => { hits += 1; - return result() + return result(); } } } diff --git a/crates/blockchain-tree/src/block_buffer.rs b/crates/blockchain-tree/src/block_buffer.rs index 6ad4bd3fa1e0..ce0495986518 100644 --- a/crates/blockchain-tree/src/block_buffer.rs +++ b/crates/blockchain-tree/src/block_buffer.rs @@ -107,7 +107,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/blockchain-tree/src/block_indices.rs b/crates/blockchain-tree/src/block_indices.rs index 494b6fc98d62..420912b4088c 100644 --- a/crates/blockchain-tree/src/block_indices.rs +++ b/crates/blockchain-tree/src/block_indices.rs @@ -154,7 +154,7 @@ impl BlockIndices { added.push(new.into()); new_hash = new_hashes.next(); } - break + break; }; let Some(new_block_value) = new_hash else { // Old canonical chain had more block than new chain. @@ -164,7 +164,7 @@ impl BlockIndices { removed.push(rem); old_hash = old_hashes.next(); } - break + break; }; // compare old and new canonical block number match new_block_value.0.cmp(&old_block_value.0) { @@ -251,7 +251,7 @@ impl BlockIndices { /// It is assumed that blocks are interconnected and that they connect to canonical chain pub fn canonicalize_blocks(&mut self, blocks: &BTreeMap) { if blocks.is_empty() { - return + return; } // Remove all blocks from canonical chain diff --git a/crates/blockchain-tree/src/blockchain_tree.rs b/crates/blockchain-tree/src/blockchain_tree.rs index a3a16e954afe..63193b815769 100644 --- a/crates/blockchain-tree/src/blockchain_tree.rs +++ b/crates/blockchain-tree/src/blockchain_tree.rs @@ -182,7 +182,7 @@ where ) -> Result, InsertBlockErrorKind> { // check if block is canonical if self.is_block_hash_canonical(&block.hash)? { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); } let last_finalized_block = self.block_indices().last_finalized_block(); @@ -190,18 +190,18 @@ where if block.number <= last_finalized_block { // check if block is inside database if self.externals.provider_factory.provider()?.block_number(block.hash)?.is_some() { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); } return Err(BlockchainTreeError::PendingBlockIsFinalized { last_finalized: last_finalized_block, } - .into()) + .into()); } // is block inside chain if let Some(attachment) = self.is_block_inside_sidechain(&block) { - return Ok(Some(BlockStatus::Valid(attachment))) + return Ok(Some(BlockStatus::Valid(attachment))); } // check if block is disconnected @@ -209,7 +209,7 @@ where return Ok(Some(BlockStatus::Disconnected { head: self.state.block_indices.canonical_tip(), missing_ancestor: block.parent_num_hash(), - })) + })); } Ok(None) @@ -285,7 +285,7 @@ where let Some((first_pending_block_number, _)) = parent_block_hashes.first_key_value() else { debug!(target: "blockchain_tree", ?chain_id, "No block hashes stored"); - return None + return None; }; let canonical_chain = canonical_chain .iter() @@ -295,7 +295,7 @@ where // get canonical fork. let canonical_fork = self.canonical_fork(chain_id)?; - return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }) + return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }); } // check if there is canonical block @@ -305,7 +305,7 @@ where canonical_fork: ForkBlock { number: canonical_number, hash: block_hash }, execution_outcome: ExecutionOutcome::default(), parent_block_hashes: canonical_chain.inner().clone(), - }) + }); } None @@ -328,12 +328,12 @@ where // check if block parent can be found in any side chain. if let Some(chain_id) = self.block_indices().get_block_chain_id(&parent.hash) { // found parent in side tree, try to insert there - return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind) + return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind); } // if not found, check if the parent can be found inside canonical chain. if self.is_block_hash_canonical(&parent.hash)? { - return self.try_append_canonical_chain(block.clone(), block_validation_kind) + return self.try_append_canonical_chain(block.clone(), block_validation_kind); } // this is another check to ensure that if the block points to a canonical block its block @@ -347,7 +347,7 @@ where parent_block_number: canonical_parent_number, block_number: block.number, } - .into()) + .into()); } } @@ -408,7 +408,7 @@ where return Err(BlockExecutionError::Validation(BlockValidationError::BlockPreMerge { hash: block.hash(), }) - .into()) + .into()); } let parent_header = provider @@ -546,7 +546,7 @@ where } else { // if there is no fork block that point to other chains, break the loop. // it means that this fork joins to canonical block. - break + break; } } hashes @@ -567,9 +567,9 @@ where // get fork block chain if let Some(fork_chain_id) = self.block_indices().get_block_chain_id(&fork.hash) { chain_id = fork_chain_id; - continue + continue; } - break + break; } (self.block_indices().canonical_hash(&fork.number) == Some(fork.hash)).then_some(fork) } @@ -684,7 +684,7 @@ where pub fn buffer_block(&mut self, block: SealedBlockWithSenders) -> Result<(), InsertBlockError> { // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)) + return Err(InsertBlockError::consensus_error(err, block.block)); } self.state.buffered_blocks.insert_block(block); @@ -702,17 +702,17 @@ where "Failed to validate total difficulty for block {}: {e}", block.header.hash() ); - return Err(e) + return Err(e); } if let Err(e) = self.externals.consensus.validate_header(block) { error!(?block, "Failed to validate header {}: {e}", block.header.hash()); - return Err(e) + return Err(e); } if let Err(e) = self.externals.consensus.validate_block_pre_execution(block) { error!(?block, "Failed to validate block {}: {e}", block.header.hash()); - return Err(e) + return Err(e); } Ok(()) @@ -737,7 +737,7 @@ where Some(BlockAttachment::Canonical) } else { Some(BlockAttachment::HistoricalFork) - } + }; } None } @@ -778,7 +778,7 @@ where // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)) + return Err(InsertBlockError::consensus_error(err, block.block)); } let status = self @@ -985,7 +985,7 @@ where } if header.is_none() && self.sidechain_block_by_hash(*hash).is_some() { - return Ok(None) + return Ok(None); } if header.is_none() { @@ -1048,18 +1048,18 @@ where { return Err(CanonicalError::from(BlockValidationError::BlockPreMerge { hash: block_hash, - })) + })); } let head = self.state.block_indices.canonical_tip(); - return Ok(CanonicalOutcome::AlreadyCanonical { header, head }) + return Ok(CanonicalOutcome::AlreadyCanonical { header, head }); } let Some(chain_id) = self.block_indices().get_block_chain_id(&block_hash) else { debug!(target: "blockchain_tree", ?block_hash, "Block hash not found in block indices"); return Err(CanonicalError::from(BlockchainTreeError::BlockHashNotFoundInChain { block_hash, - })) + })); }; // we are splitting chain at the block hash that we want to make canonical @@ -1245,7 +1245,7 @@ where block_number: tip.number, block_hash: tip.hash(), })) - .into()) + .into()); } self.metrics.trie_updates_insert_recomputed.increment(1); trie_updates @@ -1274,7 +1274,7 @@ where pub fn unwind(&mut self, unwind_to: BlockNumber) -> Result<(), CanonicalError> { // nothing to be done if unwind_to is higher then the tip if self.block_indices().canonical_tip().number <= unwind_to { - return Ok(()) + return Ok(()); } // revert `N` blocks from current canonical chain and put them inside BlockchainTree let old_canon_chain = self.revert_canonical_from_database(unwind_to)?; @@ -1316,7 +1316,7 @@ where "Reverting optimistic canonical chain to block {}", revert_until ); - return Err(CanonicalError::OptimisticTargetRevert(revert_until)) + return Err(CanonicalError::OptimisticTargetRevert(revert_until)); } // read data that is needed for new sidechain diff --git a/crates/blockchain-tree/src/bundle.rs b/crates/blockchain-tree/src/bundle.rs index 01d1d717f211..90a03230de2d 100644 --- a/crates/blockchain-tree/src/bundle.rs +++ b/crates/blockchain-tree/src/bundle.rs @@ -25,7 +25,7 @@ impl<'a> ExecutionDataProvider for BundleStateDataRef<'a> { fn block_hash(&self, block_number: BlockNumber) -> Option { let block_hash = self.sidechain_block_hashes.get(&block_number).cloned(); if block_hash.is_some() { - return block_hash + return block_hash; } self.canonical_block_hashes.get(&block_number).cloned() diff --git a/crates/blockchain-tree/src/chain.rs b/crates/blockchain-tree/src/chain.rs index 613cb59cdd34..d53009b76609 100644 --- a/crates/blockchain-tree/src/chain.rs +++ b/crates/blockchain-tree/src/chain.rs @@ -238,7 +238,7 @@ impl AppendableChain { return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: state_root, expected: block.state_root }.into(), ) - .into()) + .into()); } tracing::debug!( diff --git a/crates/blockchain-tree/src/state.rs b/crates/blockchain-tree/src/state.rs index e44e1aae552a..72d38f1fce20 100644 --- a/crates/blockchain-tree/src/state.rs +++ b/crates/blockchain-tree/src/state.rs @@ -87,7 +87,7 @@ impl TreeState { /// Inserts a chain into the tree and builds the block indices. pub(crate) fn insert_chain(&mut self, chain: AppendableChain) -> Option { if chain.is_empty() { - return None + return None; } let chain_id = self.next_id(); diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index 2462da93a12c..e0944330be75 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -691,7 +691,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.is_fork_active_at_timestamp(*fork, timestamp) { - return *params + return *params; } } @@ -710,7 +710,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.is_fork_active_at_block(*fork, block_number) { - return *params + return *params; } } @@ -896,7 +896,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 }; } } } @@ -917,7 +917,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 }; } } @@ -932,7 +932,7 @@ impl ChainSpec { // to satisfy every timestamp ForkCondition, we find the last ForkCondition::Block // if one exists, and include its block_num in the returned Head if let Some(last_block_num) = self.last_block_fork_before_merge_or_timestamp() { - return Head { timestamp, number: last_block_num, ..Default::default() } + return Head { timestamp, number: last_block_num, ..Default::default() }; } Head { timestamp, ..Default::default() } } @@ -960,17 +960,17 @@ impl ChainSpec { ForkCondition::TTD { fork_block, .. } => { // handle Sepolia merge netsplit case if fork_block.is_some() { - return *fork_block + return *fork_block; } // ensure curr_cond is indeed ForkCondition::Block and return block_num if let ForkCondition::Block(block_num) = curr_cond { - return Some(block_num) + return Some(block_num); } } ForkCondition::Timestamp(_) => { // ensure curr_cond is indeed ForkCondition::Block and return block_num if let ForkCondition::Block(block_num) = curr_cond { - return Some(block_num) + return Some(block_num); } } ForkCondition::Block(_) | ForkCondition::Never => continue, diff --git a/crates/config/src/config.rs b/crates/config/src/config.rs index f458ef41646f..95fd06a76aec 100644 --- a/crates/config/src/config.rs +++ b/crates/config/src/config.rs @@ -47,7 +47,7 @@ impl Config { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!("reth config file extension must be '{EXTENSION}'"), - )) + )); } confy::store_path(path, self).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) } diff --git a/crates/consensus/auto-seal/src/client.rs b/crates/consensus/auto-seal/src/client.rs index b9befa73857b..11d511ced068 100644 --- a/crates/consensus/auto-seal/src/client.rs +++ b/crates/consensus/auto-seal/src/client.rs @@ -41,7 +41,7 @@ impl AutoSealClient { hash.into() } else { warn!(target: "consensus::auto", num, "no matching block found"); - return headers + return headers; } } }; @@ -58,7 +58,7 @@ impl AutoSealClient { } headers.push(header); } else { - break + break; } } @@ -75,7 +75,7 @@ impl AutoSealClient { if let Some(body) = storage.bodies.get(&hash).cloned() { bodies.push(body); } else { - break + break; } } diff --git a/crates/consensus/auto-seal/src/mode.rs b/crates/consensus/auto-seal/src/mode.rs index 2ff918af63dc..df9846f0a800 100644 --- a/crates/consensus/auto-seal/src/mode.rs +++ b/crates/consensus/auto-seal/src/mode.rs @@ -102,7 +102,7 @@ impl FixedBlockTimeMiner { { if self.interval.poll_tick(cx).is_ready() { // drain the pool - return Poll::Ready(pool.best_transactions().collect()) + return Poll::Ready(pool.best_transactions().collect()); } Poll::Pending } @@ -141,7 +141,7 @@ impl ReadyTransactionMiner { } if self.has_pending_txs == Some(false) { - return Poll::Pending + return Poll::Pending; } let transactions = pool.best_transactions().take(self.max_transactions).collect::>(); @@ -150,7 +150,7 @@ impl ReadyTransactionMiner { self.has_pending_txs = Some(transactions.len() >= self.max_transactions); if transactions.is_empty() { - return Poll::Pending + return Poll::Pending; } Poll::Ready(transactions) diff --git a/crates/consensus/auto-seal/src/task.rs b/crates/consensus/auto-seal/src/task.rs index 856d02631cb0..39491a65f2cb 100644 --- a/crates/consensus/auto-seal/src/task.rs +++ b/crates/consensus/auto-seal/src/task.rs @@ -103,7 +103,7 @@ where if this.insert_task.is_none() { if this.queued.is_empty() { // nothing to insert - break + break; } // ready to queue in new insert task @@ -170,18 +170,18 @@ where ForkchoiceStatus::Valid => break, ForkchoiceStatus::Invalid => { error!(target: "consensus::auto", ?fcu_response, "Forkchoice update returned invalid response"); - return None + return None; } ForkchoiceStatus::Syncing => { debug!(target: "consensus::auto", ?fcu_response, "Forkchoice update returned SYNCING, waiting for VALID"); // wait for the next fork choice update - continue + continue; } } } Err(err) => { error!(target: "consensus::auto", %err, "Autoseal fork choice update failed"); - return None + return None; } } } @@ -207,7 +207,7 @@ where } Poll::Pending => { this.insert_task = Some(fut); - break + break; } } } diff --git a/crates/consensus/beacon/src/engine/hooks/controller.rs b/crates/consensus/beacon/src/engine/hooks/controller.rs index bd5c8a9e2b91..55c1b2aac6e2 100644 --- a/crates/consensus/beacon/src/engine/hooks/controller.rs +++ b/crates/consensus/beacon/src/engine/hooks/controller.rs @@ -74,7 +74,7 @@ impl EngineHooksController { self.hooks.push_back(hook); } - return Poll::Ready(Ok(result)) + return Poll::Ready(Ok(result)); } Poll::Pending => { self.active_db_write_hook = Some(hook); @@ -141,7 +141,7 @@ impl EngineHooksController { db_write_active || args.finalized_block_number.is_none()) { - return Poll::Pending + return Poll::Pending; } if let Poll::Ready(event) = hook.poll(cx, args)? { @@ -155,7 +155,7 @@ impl EngineHooksController { "Polled next hook" ); - return Poll::Ready(Ok(result)) + return Poll::Ready(Ok(result)); } else { debug!(target: "consensus::engine::hooks", hook = hook.name(), "Next hook is not ready"); } diff --git a/crates/consensus/beacon/src/engine/hooks/static_file.rs b/crates/consensus/beacon/src/engine/hooks/static_file.rs index 43c47ef41b02..fdb36fc9b775 100644 --- a/crates/consensus/beacon/src/engine/hooks/static_file.rs +++ b/crates/consensus/beacon/src/engine/hooks/static_file.rs @@ -88,12 +88,12 @@ impl StaticFileHook { StaticFileProducerState::Idle(static_file_producer) => { let Some(static_file_producer) = static_file_producer.take() else { trace!(target: "consensus::engine::hooks::static_file", "StaticFileProducer is already running but the state is idle"); - return Ok(None) + return Ok(None); }; let Some(locked_static_file_producer) = static_file_producer.try_lock_arc() else { trace!(target: "consensus::engine::hooks::static_file", "StaticFileProducer lock is already taken"); - return Ok(None) + return Ok(None); }; let targets = @@ -138,7 +138,7 @@ impl EngineHook for StaticFileHook { ) -> Poll> { let Some(finalized_block_number) = ctx.finalized_block_number else { trace!(target: "consensus::engine::hooks::static_file", ?ctx, "Finalized block number is not available"); - return Poll::Pending + return Poll::Pending; }; // Try to spawn a static_file_producer diff --git a/crates/consensus/beacon/src/engine/invalid_headers.rs b/crates/consensus/beacon/src/engine/invalid_headers.rs index 2a37c60014da..d98df18b2984 100644 --- a/crates/consensus/beacon/src/engine/invalid_headers.rs +++ b/crates/consensus/beacon/src/engine/invalid_headers.rs @@ -39,7 +39,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.clone()) + return Some(entry.header.clone()); } } // if we get here, the entry has been hit too many times, so we evict it diff --git a/crates/consensus/beacon/src/engine/mod.rs b/crates/consensus/beacon/src/engine/mod.rs index 29c5c6a1c124..c1092b0f3a1e 100644 --- a/crates/consensus/beacon/src/engine/mod.rs +++ b/crates/consensus/beacon/src/engine/mod.rs @@ -357,21 +357,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.sync.is_pipeline_active() { // We can only process new forkchoice updates if the pipeline is idle, since it requires // exclusive access to the database trace!(target: "consensus::engine", "Pipeline is syncing, skipping forkchoice update"); - return Ok(Some(OnForkChoiceUpdated::syncing())) + return Ok(Some(OnForkChoiceUpdated::syncing())); } Ok(None) @@ -460,7 +460,7 @@ where current_head_num=?head.number, "[Optimism] Allowing beacon reorg to old head" ); - return true + return true; } // 2. Client software MAY skip an update of the forkchoice state and MUST NOT begin a @@ -604,7 +604,7 @@ where inconsistent_stage_checkpoint = stage_checkpoint, "Pipeline sync progress is inconsistent" ); - return Ok(self.blockchain.block_hash(first_stage_checkpoint)?) + return Ok(self.blockchain.block_hash(first_stage_checkpoint)?); } } @@ -682,7 +682,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 @@ -698,7 +698,7 @@ where // However, optimism chains will do this. The risk of a reorg is however // low. debug!(target: "consensus::engine", hash=?state.head_block_hash, "Setting head hash as an optimistic pipeline target."); - return Some(state.head_block_hash) + return Some(state.head_block_hash); } Ok(Some(_)) => { // we're fully synced to the finalized block @@ -738,7 +738,7 @@ where ) -> ProviderResult> { // Check if parent exists in side chain or in canonical chain. if self.blockchain.find_block_by_hash(parent_hash, BlockSource::Any)?.is_some() { - return Ok(Some(parent_hash)) + return Ok(Some(parent_hash)); } // iterate over ancestors in the invalid cache @@ -754,7 +754,7 @@ where if current_header.is_none() && self.blockchain.find_block_by_hash(current_hash, BlockSource::Any)?.is_some() { - return Ok(Some(current_hash)) + return Ok(Some(current_hash)); } } Ok(None) @@ -854,7 +854,7 @@ where if !state.finalized_block_hash.is_zero() && !self.blockchain.is_canonical(state.finalized_block_hash)? { - return Ok(Some(OnForkChoiceUpdated::invalid_state())) + return Ok(Some(OnForkChoiceUpdated::invalid_state())); } // Finalized block is consistent, so update it in the canon chain tracker. @@ -868,7 +868,7 @@ where if !state.safe_block_hash.is_zero() && !self.blockchain.is_canonical(state.safe_block_hash)? { - return Ok(Some(OnForkChoiceUpdated::invalid_state())) + return Ok(Some(OnForkChoiceUpdated::invalid_state())); } // Safe block is consistent, so update it in the canon chain tracker. @@ -929,7 +929,7 @@ where if !safe_block_hash.is_zero() { if self.blockchain.safe_block_hash()? == Some(safe_block_hash) { // nothing to update - return Ok(()) + return Ok(()); } let safe = self @@ -949,7 +949,7 @@ where if !finalized_block_hash.is_zero() { if self.blockchain.finalized_block_hash()? == Some(finalized_block_hash) { // nothing to update - return Ok(()) + return Ok(()); } let finalized = self @@ -981,7 +981,7 @@ where if let Some(invalid_ancestor) = self.check_invalid_ancestor(state.head_block_hash)? { warn!(target: "consensus::engine", %error, ?state, ?invalid_ancestor, head=?state.head_block_hash, "Failed to canonicalize the head hash, head is also considered invalid"); debug!(target: "consensus::engine", head=?state.head_block_hash, current_error=%error, "Head was previously marked as invalid"); - return Ok(invalid_ancestor) + return Ok(invalid_ancestor); } match &error { @@ -990,7 +990,7 @@ where return Ok(PayloadStatus::from_status(PayloadStatusEnum::Invalid { validation_error: error.to_string(), }) - .with_latest_valid_hash(B256::ZERO)) + .with_latest_valid_hash(B256::ZERO)); } CanonicalError::BlockchainTree(BlockchainTreeError::BlockHashNotFoundInChain { .. @@ -1001,7 +1001,7 @@ where } CanonicalError::OptimisticTargetRevert(block_number) => { self.sync.set_pipeline_sync_target(PipelineTarget::Unwind(*block_number)); - return Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing)) + return Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing)); } _ => { warn!(target: "consensus::engine", %error, ?state, "Failed to canonicalize the head hash"); @@ -1125,7 +1125,7 @@ where }; let status = PayloadStatusEnum::from(error); - return Ok(Either::Left(PayloadStatus::new(status, latest_valid_hash))) + return Ok(Either::Left(PayloadStatus::new(status, latest_valid_hash))); } }; @@ -1161,7 +1161,7 @@ where // begin a payload build process. In such an event, the forkchoiceState update MUST NOT // be rolled back. if attrs.timestamp() <= head.timestamp { - return OnForkChoiceUpdated::invalid_payload_attributes() + return OnForkChoiceUpdated::invalid_payload_attributes(); } // 8. Client software MUST begin a payload build process building on top of @@ -1257,7 +1257,7 @@ where |error| InsertBlockError::new(block, InsertBlockErrorKind::Provider(error)), )? { - return Ok(status) + return Ok(status); } // not known to be invalid, but we don't know anything else @@ -1293,7 +1293,7 @@ where // threshold self.sync.set_pipeline_sync_target(target.into()); // we can exit early here because the pipeline will take care of syncing - return + return; } // continue downloading the missing parent @@ -1424,7 +1424,7 @@ where } EngineSyncEvent::PipelineTaskDropped => { error!(target: "consensus::engine", "Failed to receive spawned pipeline"); - return Err(BeaconConsensusEngineError::PipelineChannelClosed) + return Err(BeaconConsensusEngineError::PipelineChannelClosed); } }; @@ -1441,7 +1441,7 @@ where warn!(target: "consensus::engine", invalid_hash=?bad_block.hash(), invalid_number=?bad_block.number, "Bad block detected in unwind"); // update the `invalid_headers` cache with the new invalid header self.invalid_headers.insert(*bad_block); - return Ok(()) + return Ok(()); } let sync_target_state = match self.forkchoice_state_tracker.sync_target_state() { @@ -1450,7 +1450,7 @@ where // This is only possible if the node was run with `debug.tip` // argument and without CL. warn!(target: "consensus::engine", "No fork choice state available"); - return Ok(()) + return Ok(()); } }; @@ -1459,7 +1459,7 @@ where self.blockchain.update_block_hashes_and_clear_buffered()?; self.blockchain.connect_buffered_blocks_to_canonical_hashes()?; // We are on an optimistic syncing process, better to wait for the next FCU to handle - return Ok(()) + return Ok(()); } // Next, we check if we need to schedule another pipeline run or transition @@ -1491,7 +1491,7 @@ where head = %sync_target_state.head_block_hash, "Current head has an invalid ancestor" ); - return Ok(()) + return Ok(()); } // get the block number of the finalized block, if we have it @@ -1576,7 +1576,7 @@ where self.blockchain.connect_buffered_blocks_to_canonical_hashes() { error!(target: "consensus::engine", %error, "Error connecting buffered blocks to canonical hashes on hook result"); - return Err(RethError::Canonical(error).into()) + return Err(RethError::Canonical(error).into()); } } } @@ -1610,14 +1610,14 @@ where if self.sync.has_reached_max_block(tip_number) { // Terminate the sync early if it's reached // the maximum user configured block. - return Ok(EngineEventOutcome::ReachedMaxBlock) + return Ok(EngineEventOutcome::ReachedMaxBlock); } } } Err(error) => { let _ = tx.send(Err(RethError::Canonical(error.clone()))); if error.is_fatal() { - return Err(RethError::Canonical(error)) + return Err(RethError::Canonical(error)); } } }; @@ -1643,7 +1643,7 @@ where // TODO: revise if any error should be considered fatal at this point. let _ = tx.send(Err(BeaconOnNewPayloadError::Internal(Box::new(error)))); - return Ok(EngineEventOutcome::Processed) + return Ok(EngineEventOutcome::Processed); } // If the error was due to an invalid payload, the payload is added to the @@ -1677,7 +1677,7 @@ where tx, }, ); - return Ok(EngineEventOutcome::Processed) + return Ok(EngineEventOutcome::Processed); } } // block was successfully inserted, so we can cancel the full block @@ -1696,7 +1696,7 @@ where let response = Err(BeaconOnNewPayloadError::Internal(Box::new(error.clone()))); let _ = tx.send(response); - return Err(RethError::Canonical(error)) + return Err(RethError::Canonical(error)); } else if error.optimistic_revert_block_number().is_some() { // engine already set the pipeline unwind target on // `try_make_sync_target_canonical` @@ -1813,7 +1813,7 @@ where this.hooks.poll_active_db_write_hook(cx, this.current_engine_hook_context()?)? { this.on_hook_result(result)?; - continue + continue; } // Process any blockchain tree action result as set forth during engine message @@ -1824,12 +1824,12 @@ where Ok(EngineEventOutcome::ReachedMaxBlock) => return Poll::Ready(Ok(())), Err(error) => { error!(target: "consensus::engine", %error, "Encountered fatal error"); - return Poll::Ready(Err(error.into())) + return Poll::Ready(Err(error.into())); } }; // Blockchain tree action handler might set next action to take. - continue + continue; } // If the db write hook is no longer active and we have a pending forkchoice update, @@ -1839,7 +1839,7 @@ where this.set_blockchain_tree_action( BlockchainTreeAction::MakeForkchoiceHeadCanonical { state, attrs, tx }, ); - continue + continue; } } @@ -1872,12 +1872,12 @@ where this.blockchain.on_transition_configuration_exchanged(); } } - continue + continue; } // Both running hook with db write access and engine messages are pending, // proceed to other polls - break + break; } // process sync events if any @@ -1891,7 +1891,7 @@ where // this could have taken a while, so we start the next cycle to handle any new // engine messages - continue 'main + continue 'main; } // at this point, all engine messages and sync events are fully drained @@ -1909,13 +1909,13 @@ where // ensure we're polling until pending while also checking for new engine // messages before polling the next hook - continue 'main + continue 'main; } } // incoming engine messages and sync events are drained, so we can yield back // control - return Poll::Pending + return Poll::Pending; } } } @@ -2064,7 +2064,7 @@ mod tests { result, Err(BeaconConsensusEngineError::Pipeline(n)) if matches!(*n.as_ref(), PipelineError::Stage(StageError::ChannelClosed)) ); - break + break; } Err(TryRecvError::Empty) => { let _ = env diff --git a/crates/consensus/beacon/src/engine/sync.rs b/crates/consensus/beacon/src/engine/sync.rs index 76a6d0e81552..73fac64cf27e 100644 --- a/crates/consensus/beacon/src/engine/sync.rs +++ b/crates/consensus/beacon/src/engine/sync.rs @@ -176,7 +176,7 @@ where /// given hash. pub(crate) fn download_full_block(&mut self, hash: B256) -> bool { if self.is_inflight_request(hash) { - return false + return false; } trace!( target: "consensus::engine::sync", @@ -210,7 +210,7 @@ where "Pipeline target cannot be zero hash." ); // precaution to never sync to the zero hash - return + return; } self.pending_pipeline_target = Some(target); } @@ -290,14 +290,14 @@ where pub(crate) 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_idle() { // advance the pipeline if let Poll::Ready(event) = self.poll_pipeline(cx) { - return Poll::Ready(event) + return Poll::Ready(event); } } @@ -335,10 +335,10 @@ where if peek.0 .0.hash() == block.0 .0.hash() { PeekMut::pop(peek); } else { - break + break; } } - return Poll::Ready(EngineSyncEvent::FetchedFullBlock(block.0 .0)) + return Poll::Ready(EngineSyncEvent::FetchedFullBlock(block.0 .0)); } Poll::Pending diff --git a/crates/consensus/beacon/src/engine/test_utils.rs b/crates/consensus/beacon/src/engine/test_utils.rs index f58063d3ef58..967296e74537 100644 --- a/crates/consensus/beacon/src/engine/test_utils.rs +++ b/crates/consensus/beacon/src/engine/test_utils.rs @@ -85,7 +85,7 @@ impl TestEnv { loop { let result = self.send_new_payload(payload.clone(), cancun_fields.clone()).await?; if !result.is_syncing() { - return Ok(result) + return Ok(result); } } } @@ -106,7 +106,7 @@ impl TestEnv { loop { let result = self.engine_handle.fork_choice_updated(state, None).await?; if !result.is_syncing() { - return Ok(result) + return Ok(result); } } } diff --git a/crates/consensus/common/src/validation.rs b/crates/consensus/common/src/validation.rs index 31bde166ece0..dba5202ad69f 100644 --- a/crates/consensus/common/src/validation.rs +++ b/crates/consensus/common/src/validation.rs @@ -18,7 +18,7 @@ pub fn validate_header_gas(header: &SealedHeader) -> Result<(), ConsensusError> return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { gas_used: header.gas_used, gas_limit: header.gas_limit, - }) + }); } Ok(()) } @@ -32,7 +32,7 @@ pub fn validate_header_base_fee( if chain_spec.fork(Hardfork::London).active_at_block(header.number) && header.base_fee_per_gas.is_none() { - return Err(ConsensusError::BaseFeeMissing) + return Err(ConsensusError::BaseFeeMissing); } Ok(()) } @@ -52,12 +52,12 @@ pub fn validate_block_pre_execution( if block.header.ommers_hash != ommers_hash { return Err(ConsensusError::BodyOmmersHashDiff( GotExpected { got: ommers_hash, expected: block.header.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 @@ -70,7 +70,7 @@ pub fn validate_block_pre_execution( if withdrawals_root != *header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: *header_withdrawals_root }.into(), - )) + )); } } @@ -84,7 +84,7 @@ pub fn validate_block_pre_execution( return Err(ConsensusError::BlobGasUsedDiff(GotExpected { got: header_blob_gas_used, expected: total_blob_gas, - })) + })); } } @@ -97,7 +97,7 @@ pub fn validate_block_pre_execution( if requests_root != *header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected { got: requests_root, expected: *header_requests_root }.into(), - )) + )); } } @@ -117,21 +117,21 @@ pub fn validate_4844_header_standalone(header: &SealedHeader) -> Result<(), Cons let excess_blob_gas = header.excess_blob_gas.ok_or(ConsensusError::ExcessBlobGasMissing)?; if header.parent_beacon_block_root.is_none() { - return Err(ConsensusError::ParentBeaconBlockRootMissing) + return Err(ConsensusError::ParentBeaconBlockRootMissing); } if blob_gas_used > MAX_DATA_GAS_PER_BLOCK { return Err(ConsensusError::BlobGasUsedExceedsMaxBlobGasPerBlock { blob_gas_used, max_blob_gas_per_block: MAX_DATA_GAS_PER_BLOCK, - }) + }); } if blob_gas_used % DATA_GAS_PER_BLOB != 0 { return Err(ConsensusError::BlobGasUsedNotMultipleOfBlobGasPerBlob { blob_gas_used, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }) + }); } // `excess_blob_gas` must also be a multiple of `DATA_GAS_PER_BLOB`. This will be checked later @@ -140,7 +140,7 @@ pub fn validate_4844_header_standalone(header: &SealedHeader) -> Result<(), Cons return Err(ConsensusError::ExcessBlobGasNotMultipleOfBlobGasPerBlob { excess_blob_gas, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }) + }); } Ok(()) @@ -173,13 +173,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(()) @@ -209,7 +209,7 @@ pub fn validate_against_parent_eip1559_base_fee( return Err(ConsensusError::BaseFeeDiff(GotExpected { expected: expected_base_fee, got: base_fee, - })) + })); } } @@ -226,7 +226,7 @@ pub fn validate_against_parent_timestamp( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp, timestamp: header.timestamp, - }) + }); } Ok(()) } @@ -249,7 +249,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)?; @@ -260,7 +260,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/debug-client/src/providers/etherscan.rs b/crates/consensus/debug-client/src/providers/etherscan.rs index e189913d1264..e7d1234c0069 100644 --- a/crates/consensus/debug-client/src/providers/etherscan.rs +++ b/crates/consensus/debug-client/src/providers/etherscan.rs @@ -46,7 +46,7 @@ impl BlockProvider for EtherscanBlockProvider { Ok(block) => block, Err(err) => { warn!(target: "consensus::debug-client", %err, "failed to fetch a block from Etherscan"); - continue + continue; } }; let block_number = block.header.number.unwrap(); diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index 524a5d5562be..e3e873d77d66 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -173,7 +173,7 @@ where if check { if let Some(latest_block) = self.inner.provider.block_by_number(number)? { assert_eq!(latest_block.hash_slow(), expected_block_hash); - break + break; } if wait_finish_checkpoint { panic!("Finish checkpoint matches, but could not fetch block."); @@ -188,7 +188,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; } } } @@ -221,7 +221,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.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 828bc5f32c4f..47f4134d7fe8 100644 --- a/crates/e2e-test-utils/src/payload.rs +++ b/crates/e2e-test-utils/src/payload.rs @@ -50,9 +50,9 @@ impl PayloadTestContext { let payload = self.payload_builder.best_payload(payload_id).await.unwrap().unwrap(); if payload.block().body.is_empty() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; - continue + continue; } - break + break; } } diff --git a/crates/ethereum-forks/src/forkid.rs b/crates/ethereum-forks/src/forkid.rs index 48ef778fcfbf..0a4d752b9b0d 100644 --- a/crates/ethereum-forks/src/forkid.rs +++ b/crates/ethereum-forks/src/forkid.rs @@ -141,7 +141,7 @@ impl Decodable for EnrForkIdEntry { 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(); @@ -155,7 +155,7 @@ impl Decodable for EnrForkIdEntry { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -324,7 +324,7 @@ impl ForkFilter { if self.current().hash == fork_id.hash { if fork_id.next == 0 { // 1b) No remotely announced fork, connect. - return Ok(()) + return Ok(()); } let is_incompatible = if self.head.number < TIMESTAMP_BEFORE_ETHEREUM_MAINNET { @@ -355,7 +355,7 @@ impl ForkFilter { } else { // 1b) Remotely announced fork not yet passed locally, connect. Ok(()) - } + }; } // 2) If the remote FORK_HASH is a subset of the local past forks... @@ -369,10 +369,10 @@ impl ForkFilter { Ok(()) } else { Err(ValidationError::RemoteStale { local: self.current(), remote: fork_id }) - } + }; } - break + break; } } @@ -380,7 +380,7 @@ impl ForkFilter { // with locally known future forks, connect. for future_fork_hash in &self.cache.future { if *future_fork_hash == fork_id.hash { - return Ok(()) + return Ok(()); } } diff --git a/crates/ethereum-forks/src/hardfork.rs b/crates/ethereum-forks/src/hardfork.rs index fa095dea5a18..3de55bd43916 100644 --- a/crates/ethereum-forks/src/hardfork.rs +++ b/crates/ethereum-forks/src/hardfork.rs @@ -108,22 +108,22 @@ impl Hardfork { /// Retrieves the activation block for the specified hardfork on the given chain. pub fn activation_block(&self, chain: Chain) -> Option { if chain == Chain::mainnet() { - return self.mainnet_activation_block() + return self.mainnet_activation_block(); } if chain == Chain::sepolia() { - return self.sepolia_activation_block() + return self.sepolia_activation_block(); } if chain == Chain::holesky() { - return self.holesky_activation_block() + return self.holesky_activation_block(); } #[cfg(feature = "optimism")] { if chain == Chain::base_sepolia() { - return self.base_sepolia_activation_block() + return self.base_sepolia_activation_block(); } if chain == Chain::base_mainnet() { - return self.base_mainnet_activation_block() + return self.base_mainnet_activation_block(); } } @@ -317,21 +317,21 @@ impl Hardfork { /// Retrieves the activation timestamp for the specified hardfork on the given chain. pub fn activation_timestamp(&self, chain: Chain) -> Option { if chain == Chain::mainnet() { - return self.mainnet_activation_timestamp() + return self.mainnet_activation_timestamp(); } if chain == Chain::sepolia() { - return self.sepolia_activation_timestamp() + return self.sepolia_activation_timestamp(); } if chain == Chain::holesky() { - return self.holesky_activation_timestamp() + return self.holesky_activation_timestamp(); } #[cfg(feature = "optimism")] { if chain == Chain::base_sepolia() { - return self.base_sepolia_activation_timestamp() + return self.base_sepolia_activation_timestamp(); } if chain == Chain::base_mainnet() { - return self.base_mainnet_activation_timestamp() + return self.base_mainnet_activation_timestamp(); } } diff --git a/crates/ethereum/consensus/src/lib.rs b/crates/ethereum/consensus/src/lib.rs index 210f54461394..a0d8c6d60ac9 100644 --- a/crates/ethereum/consensus/src/lib.rs +++ b/crates/ethereum/consensus/src/lib.rs @@ -66,7 +66,7 @@ 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. @@ -74,11 +74,13 @@ impl EthBeaconConsensus { 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 }) + return Err(ConsensusError::GasLimitInvalidMinimum { + child_gas_limit: header.gas_limit, + }); } Ok(()) @@ -94,30 +96,30 @@ impl Consensus for EthBeaconConsensus { if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp) && header.withdrawals_root.is_none() { - return Err(ConsensusError::WithdrawalsRootMissing) + 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. if self.chain_spec.is_cancun_active_at_timestamp(header.timestamp) { validate_4844_header_standalone(header)?; } 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_root.is_none() { - return Err(ConsensusError::RequestsRootMissing) + return Err(ConsensusError::RequestsRootMissing); } } else if header.requests_root.is_some() { - return Err(ConsensusError::RequestsRootUnexpected) + return Err(ConsensusError::RequestsRootUnexpected); } Ok(()) @@ -158,15 +160,15 @@ impl Consensus for EthBeaconConsensus { if is_post_merge { if !header.is_zero_difficulty() { - return Err(ConsensusError::TheMergeDifficultyIsNotZero) + return Err(ConsensusError::TheMergeDifficultyIsNotZero); } if header.nonce != 0 { - 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 @@ -195,7 +197,7 @@ impl Consensus for EthBeaconConsensus { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp, present_timestamp, - }) + }); } // Goerli and early OP exception: diff --git a/crates/ethereum/consensus/src/validation.rs b/crates/ethereum/consensus/src/validation.rs index 1566ec176215..6d4d2e0a0f74 100644 --- a/crates/ethereum/consensus/src/validation.rs +++ b/crates/ethereum/consensus/src/validation.rs @@ -23,7 +23,7 @@ pub fn validate_block_post_execution( verify_receipts(block.header.receipts_root, block.header.logs_bloom, receipts) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error) + return Err(error); } } @@ -34,19 +34,19 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.gas_used }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }) + }); } // Validate that the header requests root matches the calculated requests root if chain_spec.is_prague_active_at_timestamp(block.timestamp) { let Some(header_requests_root) = block.header.requests_root else { - return Err(ConsensusError::RequestsRootMissing) + return Err(ConsensusError::RequestsRootMissing); }; let requests_root = reth_primitives::proofs::calculate_requests_root(requests); if requests_root != header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected::new(requests_root, header_requests_root).into(), - )) + )); } } @@ -88,13 +88,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/evm/src/execute.rs b/crates/ethereum/evm/src/execute.rs index f9a5b752d20c..2b8e8bf0b02d 100644 --- a/crates/ethereum/evm/src/execute.rs +++ b/crates/ethereum/evm/src/execute.rs @@ -170,7 +170,7 @@ where transaction_gas_limit: transaction.gas_limit(), block_available_gas, } - .into()) + .into()); } EvmConfig::fill_tx_env(evm.tx_mut(), transaction, *sender); diff --git a/crates/ethereum/payload/src/lib.rs b/crates/ethereum/payload/src/lib.rs index c979397d7553..fad345bc8854 100644 --- a/crates/ethereum/payload/src/lib.rs +++ b/crates/ethereum/payload/src/lib.rs @@ -312,12 +312,12 @@ where // which also removes all dependent transaction from the iterator before we can // continue best_txs.mark_invalid(&pool_tx); - 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 @@ -334,7 +334,7 @@ where // for regular transactions above. trace!(target: "payload_builder", tx=?tx.hash, ?sum_blob_gas_used, ?tx_blob_gas, "skipping blob transaction because it would exceed the max data gas per block"); best_txs.mark_invalid(&pool_tx); - continue + continue; } } @@ -362,11 +362,11 @@ where best_txs.mark_invalid(&pool_tx); } - continue + continue; } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)) + return Err(PayloadBuilderError::EvmExecutionError(err)); } } } @@ -415,7 +415,7 @@ where // check if we have a better block if !is_better_payload(best_payload.as_ref(), total_fees) { // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); } // calculate the requests and the requests root diff --git a/crates/etl/src/lib.rs b/crates/etl/src/lib.rs index 2dbf4cada4fa..0793e585334e 100644 --- a/crates/etl/src/lib.rs +++ b/crates/etl/src/lib.rs @@ -246,7 +246,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; 8]; diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index de46952b9ee2..9c9c72dfc0d2 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -126,13 +126,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 } @@ -259,7 +259,7 @@ impl Chain { return Err(BlockExecutionError::AppendChainDoesntConnect { chain_tip: Box::new(chain_tip.num_hash()), other_chain_fork: Box::new(other_fork_block), - }) + }); } // Insert blocks from other chain @@ -296,23 +296,23 @@ impl Chain { let block_number = match split_at { ChainSplitTarget::Hash(block_hash) => { let Some(block_number) = self.block_number(block_hash) else { - return ChainSplit::NoSplitPending(self) + return ChainSplit::NoSplitPending(self); }; // If block number is same as tip whole chain is becoming canonical. if block_number == chain_tip { - return ChainSplit::NoSplitCanonical(self) + return ChainSplit::NoSplitCanonical(self); } block_number } ChainSplitTarget::Number(block_number) => { if block_number > chain_tip { - return ChainSplit::NoSplitPending(self) + return ChainSplit::NoSplitPending(self); } if block_number == chain_tip { - return ChainSplit::NoSplitCanonical(self) + return ChainSplit::NoSplitCanonical(self); } if block_number < *self.blocks.first_entry().expect("chain is never empty").key() { - return ChainSplit::NoSplitPending(self) + return ChainSplit::NoSplitPending(self); } block_number } diff --git a/crates/evm/execution-types/src/execution_outcome.rs b/crates/evm/execution-types/src/execution_outcome.rs index 9c51faf85e32..c9359c4d37ca 100644 --- a/crates/evm/execution-types/src/execution_outcome.rs +++ b/crates/evm/execution-types/src/execution_outcome.rs @@ -154,11 +154,11 @@ impl ExecutionOutcome { /// Transform block number to the index of block. 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) } @@ -266,7 +266,7 @@ impl ExecutionOutcome { /// If the target block number is not included in the state block range. pub fn split_at(self, at: BlockNumber) -> (Option, Self) { 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/manager.rs b/crates/exex/exex/src/manager.rs index ce4994c34b03..718f157cef78 100644 --- a/crates/exex/exex/src/manager.rs +++ b/crates/exex/exex/src/manager.rs @@ -102,7 +102,7 @@ impl ExExHandle { ); self.next_notification_id = notification_id + 1; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } // Do not handle [ExExNotification::ChainReorged] and @@ -291,9 +291,9 @@ impl Future for ExExManager { "Received new notification" ); self.push_notification(notification); - continue + continue; } - break + break; } // update capacity @@ -313,7 +313,7 @@ impl Future for ExExManager { if let Some(notification) = self.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/metrics/metrics-derive/src/expand.rs b/crates/metrics/metrics-derive/src/expand.rs index ac0efd4f3e7a..d1b25a12a47a 100644 --- a/crates/metrics/metrics-derive/src/expand.rs +++ b/crates/metrics/metrics-derive/src/expand.rs @@ -242,14 +242,14 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { }; if kv.path.is_ident("scope") { if scope.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `scope` value provided.")) + return Err(Error::new_spanned(kv, "Duplicate `scope` value provided.")); } let scope_lit = parse_str_lit(lit)?; validate_metric_name(&scope_lit)?; scope = Some(scope_lit); } else if kv.path.is_ident("separator") { if separator.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `separator` value provided.")) + return Err(Error::new_spanned(kv, "Duplicate `separator` value provided.")); } let separator_lit = parse_str_lit(lit)?; if !SUPPORTED_SEPARATORS.contains(&&*separator_lit.value()) { @@ -263,16 +263,16 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { .collect::>() .join(", ") ), - )) + )); } separator = Some(separator_lit); } else if kv.path.is_ident("dynamic") { if dynamic.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `dynamic` flag provided.")) + return Err(Error::new_spanned(kv, "Duplicate `dynamic` flag provided.")); } dynamic = Some(parse_bool_lit(lit)?.value); } else { - return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) + return Err(Error::new_spanned(kv, "Unsupported attribute entry.")); } } @@ -295,7 +295,7 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { fn parse_metric_fields(node: &DeriveInput) -> Result>> { let Data::Struct(ref data) = node.data else { - return Err(Error::new_spanned(node, "Only structs are supported.")) + return Err(Error::new_spanned(node, "Only structs are supported.")); }; let mut metrics = Vec::with_capacity(data.fields.len()); @@ -317,7 +317,7 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { return Err(Error::new_spanned( kv, "Duplicate `describe` value provided.", - )) + )); } describe = Some(parse_str_lit(lit)?); } else if kv.path.is_ident("rename") { @@ -325,13 +325,13 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { return Err(Error::new_spanned( kv, "Duplicate `rename` value provided.", - )) + )); } let rename_lit = parse_str_lit(lit)?; validate_metric_name(&rename_lit)?; rename = Some(rename_lit) } else { - return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) + return Err(Error::new_spanned(kv, "Unsupported attribute entry.")); } } _ => return Err(Error::new_spanned(meta, "Unsupported attribute entry.")), @@ -341,7 +341,7 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { if skip { metrics.push(MetricField::Skipped(field)); - continue + continue; } let description = match describe { diff --git a/crates/metrics/metrics-derive/src/metric.rs b/crates/metrics/metrics-derive/src/metric.rs index e8dfb24847a8..88be9a31fd1d 100644 --- a/crates/metrics/metrics-derive/src/metric.rs +++ b/crates/metrics/metrics-derive/src/metric.rs @@ -33,7 +33,7 @@ impl<'a> Metric<'a> { _ => return Err(Error::new_spanned(path_ty, "Unsupported metric type")), }; - return Ok(quote! { #registrar }) + return Ok(quote! { #registrar }); } } @@ -50,7 +50,7 @@ impl<'a> Metric<'a> { _ => return Err(Error::new_spanned(path_ty, "Unsupported metric type")), }; - return Ok(quote! { #descriptor }) + return Ok(quote! { #descriptor }); } } diff --git a/crates/net/common/src/ban_list.rs b/crates/net/common/src/ban_list.rs index 6586becae0ae..e547d4c399e5 100644 --- a/crates/net/common/src/ban_list.rs +++ b/crates/net/common/src/ban_list.rs @@ -8,7 +8,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 { @@ -54,7 +54,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false + return false; } } true @@ -69,7 +69,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false + return false; } } true diff --git a/crates/net/common/src/ratelimit.rs b/crates/net/common/src/ratelimit.rs index 16e403f10aa2..f717d18b3a0e 100644 --- a/crates/net/common/src/ratelimit.rs +++ b/crates/net/common/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/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index 47f810d96337..d921b75ddc7f 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -767,7 +767,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"); @@ -847,7 +847,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 @@ -859,7 +859,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 @@ -894,7 +894,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 @@ -1003,7 +1003,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 @@ -1121,17 +1121,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) { - return + return; } if self.queued_pings.iter().any(|(n, _)| n.id == node.id) { - return + return; } if self.pending_pings.len() < MAX_NODES_PING { @@ -1166,7 +1166,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() }; @@ -1181,7 +1181,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) { @@ -1190,7 +1190,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() @@ -1226,11 +1226,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()) { @@ -1245,7 +1245,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 { @@ -1284,7 +1284,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()) { @@ -1303,7 +1303,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) { @@ -1319,7 +1319,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; } }; @@ -1335,7 +1335,7 @@ impl Discv4Service { Entry::Vacant(_) => { // received neighbours response without requesting it trace!(target: "discv4", from=?remote_addr, "Received unsolicited Neighbours"); - return + return; } }; @@ -1345,7 +1345,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); @@ -1427,7 +1427,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 }); @@ -1443,7 +1443,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 }); @@ -1467,7 +1467,7 @@ impl Discv4Service { // treat this as an hard error since it responded. failed_neighbours.push(*node_id); } - return false + return false; } true }); @@ -1495,7 +1495,7 @@ impl Discv4Service { if let Some(bucket) = self.kbuckets.get_bucket(&key) { if bucket.num_entries() < MAX_NODES_PER_BUCKET / 2 { // skip half empty bucket - continue + continue; } } self.remove_node(node_id); @@ -1542,7 +1542,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(()) } @@ -1586,7 +1586,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 @@ -1711,7 +1711,7 @@ impl Discv4Service { // this will make sure we're woken up again cx.waker().wake_by_ref(); } - break + break; } } @@ -1729,7 +1729,7 @@ impl Discv4Service { } if self.queued_events.is_empty() { - return Poll::Pending + return Poll::Pending; } } } @@ -1836,7 +1836,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]; @@ -1845,13 +1845,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; @@ -2000,7 +2000,7 @@ impl LookupTargetRotator { self.counter += 1; self.counter %= self.interval; if self.counter == 0 { - return *local + return *local; } PeerId::random() } @@ -2363,7 +2363,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; } } } diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 610628d56b4f..8e8da311cf2f 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -138,7 +138,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: @@ -149,7 +149,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]; @@ -232,7 +232,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(); @@ -246,7 +246,7 @@ impl Decodable for FindNode { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -274,7 +274,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(); @@ -288,7 +288,7 @@ impl Decodable for Neighbours { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -317,7 +317,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(); @@ -331,7 +331,7 @@ impl Decodable for EnrRequest { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } let rem = rlp_head.payload_length - consumed; @@ -425,7 +425,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(); @@ -450,7 +450,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); @@ -505,7 +505,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 { @@ -525,7 +525,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 06133dba6790..37d8c60db7f5 100644 --- a/crates/net/discv4/src/test_utils.rs +++ b/crates/net/discv4/src/test_utils.rs @@ -165,7 +165,7 @@ impl Stream for MockDiscovery { ping, pong, to: remote_addr, - })) + })); } } Message::Pong(_) | Message::Neighbours(_) => {} @@ -179,7 +179,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/enr.rs b/crates/net/discv5/src/enr.rs index eb8b6be006b2..5050aed1dfb8 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 325544de6c18..5dbdec13d7a9 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 728c44791d16..f21720804dfb 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -98,7 +98,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: "discv5", @@ -301,7 +301,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) { @@ -313,7 +313,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 @@ -340,14 +340,14 @@ impl Discv5 { let id = enr_to_discv4_id(enr).ok_or(Error::IncompatibleKeyType)?; if enr.tcp4().is_none() && enr.tcp6().is_none() { - return Err(Error::UnreachableRlpx) + return Err(Error::UnreachableRlpx); } let Some(tcp_port) = (match self.rlpx_ip_mode { IpMode::Ip4 => enr.tcp4(), IpMode::Ip6 => enr.tcp6(), _ => unimplemented!("dual-stack support not implemented for rlpx"), }) else { - return Err(Error::IpVersionMismatchRlpx(self.rlpx_ip_mode)) + return Err(Error::IpVersionMismatchRlpx(self.rlpx_ip_mode)); }; Ok(NodeRecord { address: socket.ip(), tcp_port, udp_port: socket.port(), id }) @@ -498,7 +498,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 5fcb1ae41b55..4b2e07cdce71 100644 --- a/crates/net/discv5/src/network_stack_id.rs +++ b/crates/net/discv5/src/network_stack_id.rs @@ -24,9 +24,9 @@ impl NetworkStackId { /// Returns the [`NetworkStackId`] that matches the given [`ChainSpec`]. pub fn id(chain: &ChainSpec) -> Option<&'static [u8]> { if chain.is_optimism() { - return Some(Self::OPEL) + return Some(Self::OPEL); } else if chain.is_eth() { - 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 f07fde2e4a67..eec205d948bb 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 a1c67740ed7a..c8831cbbbc1b 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 cfe6862c934d..278c0f892d2e 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 80182b694f80..16f66af5252f 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.bytes().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 27a576e2f702..29cc505c63b3 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -95,7 +95,7 @@ where max_non_empty: u64, ) -> DownloadResult>> { if range.is_empty() || max_non_empty == 0 { - return Ok(None) + return Ok(None); } // Collect headers while @@ -144,7 +144,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()) @@ -238,7 +238,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 @@ -257,7 +257,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 } @@ -311,7 +311,7 @@ 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. @@ -320,7 +320,7 @@ where 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. @@ -331,7 +331,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 @@ -354,13 +354,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 @@ -373,7 +373,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))); } }; } @@ -396,7 +396,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))); } }; } @@ -409,21 +409,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 diff --git a/crates/net/downloaders/src/bodies/request.rs b/crates/net/downloaders/src/bodies/request.rs index f27801041e83..36038aa7d03a 100644 --- a/crates/net/downloaders/src/bodies/request.rs +++ b/crates/net/downloaders/src/bodies/request.rs @@ -128,14 +128,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 @@ -189,7 +189,7 @@ where hash, number, error: Box::new(error), - }) + }); } self.buffer.push(BlockResponse::Full(block)); @@ -215,7 +215,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 @@ -230,7 +230,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 42b21d5f1699..345b22f71180 100644 --- a/crates/net/downloaders/src/bodies/task.rs +++ b/crates/net/downloaders/src/bodies/task.rs @@ -128,13 +128,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(()); } } @@ -144,7 +144,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, @@ -152,7 +152,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 0ef12f1ba552..728b7c8f2f37 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -118,7 +118,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(); @@ -126,7 +126,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; } @@ -218,7 +218,7 @@ impl FromReader for FileClient { "partial block returned from decoding chunk" ); remaining_bytes = bytes; - break + break; } Err(err) => return Err(err), }; @@ -278,7 +278,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, @@ -302,7 +302,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) }); } } } @@ -409,7 +409,7 @@ impl ChunkedFileReader { if self.file_byte_len == 0 && self.chunk.is_empty() { dbg!(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 156f3316c431..1d0eca211704 100644 --- a/crates/net/downloaders/src/file_codec.rs +++ b/crates/net/downloaders/src/file_codec.rs @@ -29,7 +29,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/file_codec_ovm_receipt.rs b/crates/net/downloaders/src/file_codec_ovm_receipt.rs index 5b3c81a9233a..ca666fffb8ff 100644 --- a/crates/net/downloaders/src/file_codec_ovm_receipt.rs +++ b/crates/net/downloaders/src/file_codec_ovm_receipt.rs @@ -31,7 +31,7 @@ impl Decoder for HackReceiptFileCodec { 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 e123ce71229a..badcef3b0f76 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -158,7 +158,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) @@ -181,7 +181,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); } } @@ -259,7 +259,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)?; @@ -286,7 +286,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 @@ -299,7 +299,7 @@ where header: Box::new(last_header.clone()), error: Box::new(error), } - .into()) + .into()); } } @@ -372,7 +372,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()) + .into()); } let target = headers.remove(0).seal_slow(); @@ -387,7 +387,7 @@ where GotExpected { got: target.hash(), expected: hash }.into(), ), } - .into()) + .into()); } } SyncTargetBlock::Number(number) => { @@ -400,7 +400,7 @@ where expected: number, }), } - .into()) + .into()); } } } @@ -449,7 +449,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()) + .into()); } if (headers.len() as u64) != request.limit { @@ -461,7 +461,7 @@ where }), request, } - .into()) + .into()); } // sort headers from highest to lowest block number @@ -481,7 +481,7 @@ where expected: requested_block_number, }), } - .into()) + .into()); } // check if the response is the next expected @@ -552,7 +552,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 => { @@ -684,7 +684,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"); @@ -751,7 +751,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 @@ -765,7 +765,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); @@ -775,13 +775,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; } } } @@ -807,13 +807,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))); } }; } @@ -838,7 +838,7 @@ where this.submit_request(request, Priority::Normal); } else { // no more requests - break + break; } } @@ -855,11 +855,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; } } @@ -868,10 +868,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 @@ -964,7 +964,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 b3fa27fde59c..f3043476deb8 100644 --- a/crates/net/downloaders/src/headers/task.rs +++ b/crates/net/downloaders/src/headers/task.rs @@ -127,7 +127,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) => { @@ -153,7 +153,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, @@ -162,7 +162,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 7b05543894ec..fb37cccdbe00 100644 --- a/crates/net/downloaders/src/receipt_file_client.rs +++ b/crates/net/downloaders/src/receipt_file_client.rs @@ -70,7 +70,7 @@ impl FromReader for ReceiptFileClient { remaining_bytes = bytes; - break + break; } Err(err) => return Err(err), }; diff --git a/crates/net/downloaders/src/test_utils/bodies_client.rs b/crates/net/downloaders/src/test_utils/bodies_client.rs index 7b655dae2891..160dee9b26bf 100644 --- a/crates/net/downloaders/src/test_utils/bodies_client.rs +++ b/crates/net/downloaders/src/test_utils/bodies_client.rs @@ -93,7 +93,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 83dcc657bce9..ad40a9da45da 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(()) @@ -655,7 +655,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)?; @@ -665,12 +665,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)?)?; @@ -721,7 +721,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 7ad30d38d0d9..9bdaedbd8864 100644 --- a/crates/net/ecies/src/codec.rs +++ b/crates/net/ecies/src/codec.rs @@ -50,7 +50,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; @@ -58,18 +58,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::Header; - 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; @@ -77,18 +77,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::Header; - return Ok(Some(IngressECIESValue::Ack)) + return Ok(Some(IngressECIESValue::Ack)); } 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()))?; @@ -97,7 +97,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()); @@ -105,7 +105,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 e413ab9ee9fe..602356dda9b2 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -40,7 +40,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) }) @@ -428,13 +428,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) @@ -708,7 +708,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); @@ -716,7 +716,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/message.rs b/crates/net/eth-wire-types/src/message.rs index cbd5ca536108..61ff55b1cf77 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -93,14 +93,14 @@ impl ProtocolMessage { } EthMessageID::GetNodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); } let request_pair = RequestPair::::decode(buf)?; EthMessage::GetNodeData(request_pair) } EthMessageID::NodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); } let request_pair = RequestPair::::decode(buf)?; EthMessage::NodeData(request_pair) @@ -485,7 +485,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 2bf096287635..b7dd3e257cd5 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -268,7 +268,7 @@ impl SharedCapability { messages: u8, ) -> Result { if offset <= MAX_RESERVED_MESSAGE_ID { - return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)) + return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)); } match name { @@ -424,12 +424,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 } @@ -513,7 +513,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 @@ -537,7 +537,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/disconnect.rs b/crates/net/eth-wire/src/disconnect.rs index 50ced132f2a6..d382f47c0806 100644 --- a/crates/net/eth-wire/src/disconnect.rs +++ b/crates/net/eth-wire/src/disconnect.rs @@ -114,9 +114,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(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } else if buf.len() > 2 { - return Err(RlpError::Overflow) + return Err(RlpError::Overflow); } if buf.len() > 1 { @@ -125,11 +125,14 @@ impl Decodable for DisconnectReason { let header = Header::decode(buf)?; if !header.list { - return Err(RlpError::UnexpectedString) + return Err(RlpError::UnexpectedString); } if header.payload_length != 1 { - return Err(RlpError::ListLengthMismatch { expected: 1, got: header.payload_length }) + return Err(RlpError::ListLengthMismatch { + expected: 1, + got: header.payload_length, + }); } } diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index 485a4ae2e7a4..1bd803b53226 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -55,7 +55,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/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index fac5e05495a7..6bb73c21f2f1 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -95,13 +95,13 @@ where Some(msg) => msg, None => { self.inner.disconnect(DisconnectReason::DisconnectRequested).await?; - return Err(EthStreamError::EthHandshakeError(EthHandshakeError::NoResponse)) + return Err(EthStreamError::EthHandshakeError(EthHandshakeError::NoResponse)); } }?; if their_msg.len() > MAX_MESSAGE_SIZE { self.inner.disconnect(DisconnectReason::ProtocolBreach).await?; - return Err(EthStreamError::MessageTooBig(their_msg.len())) + return Err(EthStreamError::MessageTooBig(their_msg.len())); } let version = EthVersion::try_from(status.version)?; @@ -110,7 +110,7 @@ where Err(err) => { debug!("decode error in eth handshake: msg={their_msg:x}"); self.inner.disconnect(DisconnectReason::DisconnectRequested).await?; - return Err(EthStreamError::InvalidMessage(err)) + return Err(EthStreamError::InvalidMessage(err)); } }; @@ -127,7 +127,7 @@ where return Err(EthHandshakeError::MismatchedGenesis( GotExpected { expected: status.genesis, got: resp.genesis }.into(), ) - .into()) + .into()); } if status.version != resp.version { @@ -136,7 +136,7 @@ where got: resp.version, expected: status.version, }) - .into()) + .into()); } if status.chain != resp.chain { @@ -145,7 +145,7 @@ where got: resp.chain, expected: status.chain, }) - .into()) + .into()); } // TD at mainnet block #7753254 is 76 bits. If it becomes 100 million times @@ -156,14 +156,14 @@ where got: status.total_difficulty.bit_len(), maximum: 100, } - .into()) + .into()); } if let Err(err) = fork_filter.validate(resp.forkid).map_err(EthHandshakeError::InvalidFork) { self.inner.disconnect(DisconnectReason::ProtocolBreach).await?; - return Err(err.into()) + return Err(err.into()); } // now we can create the `EthStream` because the peer has successfully completed @@ -261,7 +261,7 @@ where }; if bytes.len() > MAX_MESSAGE_SIZE { - return Poll::Ready(Some(Err(EthStreamError::MessageTooBig(bytes.len())))) + return Poll::Ready(Some(Err(EthStreamError::MessageTooBig(bytes.len())))); } let msg = match ProtocolMessage::decode_message(*this.version, &mut bytes.as_ref()) { @@ -277,14 +277,14 @@ where %msg, "failed to decode protocol message" ); - return Poll::Ready(Some(Err(EthStreamError::InvalidMessage(err)))) + return Poll::Ready(Some(Err(EthStreamError::InvalidMessage(err)))); } }; if matches!(msg.message, EthMessage::Status(_)) { return Poll::Ready(Some(Err(EthStreamError::EthHandshakeError( EthHandshakeError::StatusNotInHandshake, - )))) + )))); } Poll::Ready(Some(Ok(msg.message))) @@ -313,7 +313,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 262c2c193921..84d43e8a87af 100644 --- a/crates/net/eth-wire/src/multiplex.rs +++ b/crates/net/eth-wire/src/multiplex.rs @@ -79,7 +79,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(); @@ -147,7 +147,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(); @@ -243,7 +243,7 @@ impl MultiplexInner { for proto in &self.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - return true + return true; } } false @@ -299,7 +299,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()) } @@ -309,7 +309,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 mut masked_bytes = BytesMut::zeroed(msg.len()); @@ -326,7 +326,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()) @@ -460,7 +460,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; @@ -469,23 +469,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; } } } @@ -498,7 +498,7 @@ where } Poll::Ready(None) => { // primary closed - return Poll::Ready(None) + return Poll::Ready(None); } Poll::Pending => break, } @@ -518,7 +518,7 @@ where Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => { this.inner.protocols.push(proto); - break + break; } } } @@ -533,7 +533,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) = @@ -547,28 +547,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; } } } @@ -585,10 +584,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(())) } @@ -620,7 +619,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()) @@ -633,7 +632,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 23f106da9a42..7312a891e5db 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -105,7 +105,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 @@ -147,7 +147,7 @@ where return Err(P2PStreamError::MismatchedProtocolVersion(GotExpected { got: their_hello.protocol_version, expected: hello.protocol_version, - })) + })); } // determine shared capabilities (currently returns only one capability) @@ -389,7 +389,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 @@ -403,7 +403,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 @@ -424,7 +424,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)))); } } @@ -435,7 +435,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 @@ -466,7 +466,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 @@ -484,11 +484,11 @@ where ); err })?; - 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, @@ -516,7 +516,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))); } } } @@ -545,7 +545,7 @@ where this.start_disconnect(DisconnectReason::PingTimeout)?; // End the stream after ping related error - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } @@ -555,7 +555,7 @@ where Poll::Ready(Ok(())) => { let flushed = this.poll_flush(cx); if flushed.is_ready() { - return flushed + return flushed; } } } @@ -573,17 +573,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(); @@ -619,10 +619,10 @@ where Err(err) => return Poll::Ready(Err(err.into())), Ok(()) => { let Some(message) = this.outgoing_messages.pop_front() else { - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); }; if let Err(err) = this.inner.as_mut().start_send(message) { - return Poll::Ready(Err(err.into())) + return Poll::Ready(Err(err.into())); } } } @@ -715,10 +715,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 d93404c5f974..90ac45831dd4 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/protocol.rs b/crates/net/eth-wire/src/protocol.rs index 26b7d6d1b6af..35d2f27a9f01 100644 --- a/crates/net/eth-wire/src/protocol.rs +++ b/crates/net/eth-wire/src/protocol.rs @@ -54,7 +54,7 @@ impl Protocol { /// The number of values needed to represent all message IDs of capability. pub fn messages(&self) -> u8 { if self.cap.is_eth() { - return EthMessageID::max() + 1 + return EthMessageID::max() + 1; } self.messages } diff --git a/crates/net/eth-wire/src/test_utils.rs b/crates/net/eth-wire/src/test_utils.rs index 466bc0f1cefa..18b68ca28232 100644 --- a/crates/net/eth-wire/src/test_utils.rs +++ b/crates/net/eth-wire/src/test_utils.rs @@ -137,7 +137,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 8f757908958f..c653c1e517de 100644 --- a/crates/net/nat/src/lib.rs +++ b/crates/net/nat/src/lib.rs @@ -91,7 +91,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/src/discovery.rs b/crates/net/network/src/discovery.rs index c320c7fe1575..efb915cf42e3 100644 --- a/crates/net/network/src/discovery.rs +++ b/crates/net/network/src/discovery.rs @@ -240,7 +240,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 @@ -278,7 +278,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 9019a79f2371..8e61edfe9ee9 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -70,7 +70,7 @@ impl NetworkError { ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err }, _ => { if let ServiceKind::Discovery(_) = kind { - return Self::Discovery(err) + return Self::Discovery(err); } Self::Io(err) } @@ -184,7 +184,7 @@ 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() { @@ -207,7 +207,7 @@ impl SessionError for EthStreamError { // [`SessionError::is_fatal_protocol_error`] Some(BackoffKind::High) } - } + }; } // This only checks for a subset of error variants, the counterpart of diff --git a/crates/net/network/src/eth_requests.rs b/crates/net/network/src/eth_requests.rs index 2e403a517dc0..44666b093822 100644 --- a/crates/net/network/src/eth_requests.rs +++ b/crates/net/network/src/eth_requests.rs @@ -85,7 +85,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() } @@ -101,7 +101,7 @@ where if let Some(next) = (header.number + 1).checked_add(skip) { block = next.into() } else { - break + break; } } HeadersDirection::Falling => { @@ -113,7 +113,7 @@ where { block = next.into() } else { - break + break; } } else { block = header.parent_hash.into() @@ -125,14 +125,14 @@ where headers.push(header); if headers.len() >= MAX_HEADERS_SERVE { - break + break; } if total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } @@ -174,14 +174,14 @@ where bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE { - break + break; } if total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } @@ -213,14 +213,14 @@ where receipts.push(receipt); if receipts.len() >= MAX_RECEIPTS_SERVE { - break + break; } if total_bytes > SOFT_RESPONSE_LIMIT { - break + break; } } else { - break + break; } } @@ -271,7 +271,7 @@ where if maybe_more_incoming_requests { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending + return Poll::Pending; } Poll::Pending diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index 4825532e4856..feb7e2a44afb 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -114,7 +114,7 @@ impl StateFetcher { if number > peer.best_number { peer.best_hash = hash; peer.best_number = number; - return true + return true; } } false @@ -139,7 +139,7 @@ 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 @@ -157,7 +157,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 }; @@ -204,7 +204,7 @@ impl StateFetcher { } if self.queued_requests.is_empty() || no_peers_available { - return Poll::Pending + return Poll::Pending; } } } @@ -279,7 +279,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); } } @@ -305,7 +305,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 @@ -383,7 +383,7 @@ impl PeerState { 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 d07b9e02488f..fb98947f794c 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -538,7 +538,7 @@ where 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); @@ -984,7 +984,7 @@ where 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 b26dd3e3700e..868e074cf56e 100644 --- a/crates/net/network/src/network.rs +++ b/crates/net/network/src/network.rs @@ -347,7 +347,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/manager.rs b/crates/net/network/src/peers/manager.rs index 7468ba1a06ad..4d3b83b3b04e 100644 --- a/crates/net/network/src/peers/manager.rs +++ b/crates/net/network/src/peers/manager.rs @@ -235,7 +235,7 @@ impl PeersManager { addr: IpAddr, ) -> Result<(), InboundConnectionError> { if self.ban_list.is_banned_ip(&addr) { - return Err(InboundConnectionError::IpBanned) + return Err(InboundConnectionError::IpBanned); } if (!self.connection_info.has_in_capacity() || self.connection_info.max_inbound == 0) && @@ -243,7 +243,7 @@ impl PeersManager { { // if we don't have any inbound slots and no trusted peers, we don't accept any new // connections - return Err(InboundConnectionError::ExceedsCapacity) + return Err(InboundConnectionError::ExceedsCapacity); } self.connection_info.inc_pending_in(); @@ -292,14 +292,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 @@ -313,7 +313,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 @@ -437,7 +437,7 @@ impl PeersManager { ReputationChangeKind::Timeout | ReputationChangeKind::AlreadySeenTransaction ) { - return + return; } // also be less strict with the reputation slashing for trusted peers @@ -449,7 +449,7 @@ impl PeersManager { peer.apply_reputation(reputation_change) } } else { - return + return; }; match outcome { @@ -503,7 +503,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, @@ -548,7 +548,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; } } @@ -690,7 +690,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.ip()) { - return + return; } match self.peers.entry(peer_id) { @@ -725,7 +725,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(); @@ -752,7 +752,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(); @@ -782,13 +782,13 @@ impl PeersManager { let mut best_peer = unconnected.next()?; if best_peer.1.is_trusted() { - 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, return it immediately if maybe_better.1.is_trusted() { - 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 @@ -809,7 +809,7 @@ impl PeersManager { if !self.net_connection_state.is_active() { // nothing to fill - return + return; } // as long as there a slots available fill them with the best peers @@ -855,7 +855,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) { @@ -894,7 +894,7 @@ impl PeersManager { if let Some(peer) = self.peers.get_mut(peer_id) { peer.backed_off = false; } - return false + return false; } true }) @@ -905,7 +905,7 @@ impl PeersManager { } if self.queued_actions.is_empty() { - return Poll::Pending + return Poll::Pending; } } } @@ -1084,15 +1084,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 @@ -2236,7 +2236,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 9357cc325adb..fe36418f21eb 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -197,7 +197,7 @@ impl ActiveSession { sizes_len: msg.sizes.len(), }, message: EthMessage::NewPooledTransactionHashes68(msg), - } + }; } self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into() } @@ -429,7 +429,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; } } } @@ -453,7 +453,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); @@ -475,11 +475,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 @@ -500,7 +500,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; @@ -515,7 +515,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); @@ -558,11 +558,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; } } @@ -573,7 +573,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 @@ -587,7 +587,7 @@ impl Future for ActiveSession { Poll::Ready(Err(_)) => return Poll::Ready(()), Poll::Pending => { this.pending_message_to_session = Some(msg); - break 'receive + break 'receive; } }; } @@ -596,10 +596,10 @@ impl Future for ActiveSession { Poll::Pending => break, Poll::Ready(None) => { if this.is_disconnecting() { - break + break; } else { 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)) => { @@ -614,18 +614,18 @@ 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 this.pending_message_to_session = Some(msg); - continue 'receive + continue 'receive; } } } 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); } } } @@ -633,7 +633,7 @@ impl Future for ActiveSession { } if !progress { - break 'main + break 'main; } } @@ -1109,7 +1109,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/config.rs b/crates/net/network/src/session/config.rs index 6c7fc282d0a5..98136ee80a10 100644 --- a/crates/net/network/src/session/config.rs +++ b/crates/net/network/src/session/config.rs @@ -223,7 +223,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 4f6be86317a0..9ad79bbc03a9 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -447,7 +447,7 @@ impl SessionManager { peer_id, remote_addr, direction, - }) + }); } let (commands_to_session, commands_rx) = mpsc::channel(self.session_command_buffer); @@ -842,7 +842,7 @@ async fn start_pending_outbound_session( error, }) .await; - return + return; } }; authenticate( @@ -888,7 +888,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 afbf05dde691..9a7b597eb59a 100644 --- a/crates/net/network/src/state.rs +++ b/crates/net/network/src/state.rs @@ -178,7 +178,7 @@ where 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 @@ -198,7 +198,7 @@ where } if count >= num_propagate { - break + break; } } } @@ -211,7 +211,7 @@ where 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) { @@ -397,7 +397,7 @@ where 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) { @@ -461,7 +461,7 @@ where } 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 cfc1f841713c..ec1ca5e28a01 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -193,7 +193,7 @@ where 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) = @@ -207,13 +207,13 @@ where trace!(target: "net", ?remote_addr, "No capacity for incoming connection"); } } - 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."); @@ -232,7 +232,7 @@ where 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); @@ -250,7 +250,7 @@ where StateAction::DiscoveredNode { peer_id, socket_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)) { @@ -307,7 +307,7 @@ where 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)); } } @@ -316,9 +316,9 @@ where 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; } } @@ -327,13 +327,13 @@ where 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 87ccbb5f9d79..b44019e4e884 100644 --- a/crates/net/network/src/test_utils/init.rs +++ b/crates/net/network/src/test_utils/init.rs @@ -45,7 +45,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 c7642accd0d8..7f06f9645881 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -297,7 +297,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 @@ -627,7 +627,7 @@ impl NetworkEventStream { /// Awaits the next `num` events for an established session pub async fn take_session_established(&mut self, mut num: usize) -> Vec { if num == 0 { - return Vec::new() + return Vec::new(); } let mut peers = Vec::with_capacity(num); while let Some(ev) = self.inner.next().await { @@ -636,7 +636,7 @@ impl NetworkEventStream { peers.push(peer_id); num -= 1; if num == 0 { - return peers + return peers; } } _ => continue, diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index 41081b191515..04d9b60238b4 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -156,7 +156,7 @@ impl TransactionFetcher { if let Some(inflight_count) = self.active_peers.get(peer_id) { *inflight_count -= 1; if *inflight_count == 0 { - return true + return true; } } false @@ -171,7 +171,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 < DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER { - return true + return true; } false } @@ -187,7 +187,7 @@ impl TransactionFetcher { for peer_id in fallback_peers.iter() { if self.is_idle(peer_id) && is_session_active(peer_id) { - return Some(peer_id) + return Some(peer_id); } } @@ -214,13 +214,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; } } }; @@ -243,7 +243,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) } @@ -274,7 +274,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::(); } else { acc_size_response = size; } @@ -309,7 +309,7 @@ impl TransactionFetcher { acc_size_response; if free_space < MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED { - break + break; } } @@ -358,7 +358,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 @@ -377,13 +377,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 { @@ -398,7 +398,7 @@ impl TransactionFetcher { ); max_retried_and_evicted_hashes.push(hash); - continue + continue; } *retries += 1; } @@ -438,7 +438,7 @@ impl TransactionFetcher { budget_find_idle_fallback_peer, ) else { // no peers are idle or budget is depleted - return + return; }; peer_id @@ -633,7 +633,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 { @@ -643,7 +643,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 >= DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER { @@ -654,7 +654,7 @@ impl TransactionFetcher { max_concurrent_tx_reqs_per_peer=DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER, "limit for concurrent `GetPooledTransactions` requests per peer reached" ); - return Some(new_announced_hashes) + return Some(new_announced_hashes); } *inflight_count += 1; @@ -691,7 +691,7 @@ impl TransactionFetcher { self.metrics.egress_peer_channel_full.increment(1); Some(new_announced_hashes) } - } + }; } else { // stores a new request future for the request self.inflight_requests.push(GetPooledTxRequestFut::new( @@ -741,7 +741,7 @@ impl TransactionFetcher { 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 @@ -749,7 +749,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. @@ -778,7 +778,7 @@ impl TransactionFetcher { if let Some(ref mut bud) = budget_fill_request { *bud = bud.saturating_sub(1); if *bud == 0 { - return + return; } } } @@ -929,7 +929,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 }; } // @@ -956,7 +956,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 }; } // @@ -993,7 +993,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 }); @@ -1040,11 +1040,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 @@ -1248,7 +1248,7 @@ impl VerifyPooledTransactionsResponse for UnverifiedPooledTransactions { 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 14568590252f..cf4f8af78e0b 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -351,7 +351,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, @@ -383,10 +383,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"); @@ -413,7 +413,7 @@ where ) -> PropagatedTransactions { let mut propagated = PropagatedTransactions::default(); if self.network.tx_gossip_disabled() { - return propagated + return propagated; } // send full transactions to a fraction of the connected peers (square root of the total @@ -523,7 +523,7 @@ where if full_transactions.transactions.is_empty() { // nothing to propagate - return None + return None; } let new_full_transactions = full_transactions.build(); @@ -550,7 +550,7 @@ where let propagated = { let Some(peer) = self.peers.get_mut(&peer_id) else { // no such peer - return + return; }; let to_propagate: Vec = @@ -571,7 +571,7 @@ where if new_pooled_hashes.is_empty() { // nothing to propagate - return + return; } for hash in new_pooled_hashes.iter_hashes().copied() { @@ -599,10 +599,10 @@ where ) { // 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 @@ -613,7 +613,7 @@ where "discarding announcement from inactive peer" ); - return + return; }; let client = peer.client_version.clone(); @@ -674,7 +674,7 @@ where if partially_valid_msg.is_empty() { // nothing to request - return + return; } // 4. filter out invalid entries (spam) @@ -703,7 +703,7 @@ where if valid_announcement_data.is_empty() { // no valid announcement data - return + return; } // 5. filter out already seen unknown hashes @@ -723,7 +723,7 @@ where if valid_announcement_data.is_empty() { // nothing to request - return + return; } trace!(target: "net::tx", @@ -752,7 +752,7 @@ where self.transaction_fetcher.buffer_hashes(hashes, Some(peer_id)); - return + return; } // load message version before announcement data type is destructed in packing @@ -904,7 +904,7 @@ where // `SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE` // transactions in the pool. if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() { - return + return; } let pooled_txs = self.pool.pooled_transactions_max( @@ -912,7 +912,7 @@ where ); if pooled_txs.is_empty() { // do not send a message if there are no transactions in the pool - return + return; } let mut msg_builder = PooledTransactionsHashesBuilder::new(version); @@ -937,10 +937,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 }; @@ -990,7 +990,7 @@ where "failed ecrecovery for transaction" ); has_bad_transactions = true; - continue + continue; } }; @@ -1127,7 +1127,7 @@ where RequestError::Timeout => ReputationChangeKind::Timeout, RequestError::ChannelClosed | RequestError::ConnectionDropped => { // peer is already disconnected - return + return; } RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id), }; @@ -1172,7 +1172,7 @@ where // 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) @@ -1348,7 +1348,7 @@ where { // 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); @@ -1399,7 +1399,7 @@ impl FullTransactionsBuilder { if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE && self.total_size > 0 { - return + return; } self.total_size = new_size; diff --git a/crates/net/network/src/transactions/validation.rs b/crates/net/network/src/transactions/validation.rs index 931cfdb9e514..b40bde4a5f98 100644 --- a/crates/net/network/src/transactions/validation.rs +++ b/crates/net/network/src/transactions/validation.rs @@ -80,7 +80,7 @@ pub trait PartiallyFilterMessage { msg=?msg, "empty payload" ); - return (FilterOutcome::ReportPeer, PartiallyValidData::empty_eth66()) + return (FilterOutcome::ReportPeer, PartiallyValidData::empty_eth66()); } // 2. checks if announcement is spam packed with duplicate hashes @@ -179,7 +179,7 @@ impl ValidateTx68 for EthMessageFilter { "invalid tx type in eth68 announcement" ); - return ValidationOutcome::ReportPeer + return ValidationOutcome::ReportPeer; } }; tx_types_counter.increase_by_tx_type(tx_type); @@ -201,7 +201,7 @@ impl ValidateTx68 for EthMessageFilter { "invalid tx size in eth68 announcement" ); - return ValidationOutcome::Ignore + return ValidationOutcome::Ignore; } } if let Some(reasonable_min_encoded_tx_length) = self.min_encoded_tx_length(tx_type) { diff --git a/crates/net/network/tests/it/multiplex.rs b/crates/net/network/tests/it/multiplex.rs index ae84f43aae3a..471afc562b3f 100644 --- a/crates/net/network/tests/it/multiplex.rs +++ b/crates/net/network/tests/it/multiplex.rs @@ -111,7 +111,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); @@ -235,7 +235,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 { @@ -245,12 +245,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 { @@ -265,11 +265,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/p2p/src/error.rs b/crates/net/p2p/src/error.rs index e005f4ea9253..df1b38142ace 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -32,7 +32,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 { diff --git a/crates/net/p2p/src/full_block.rs b/crates/net/p2p/src/full_block.rs index 93af03d5b076..6e3893ba6152 100644 --- a/crates/net/p2p/src/full_block.rs +++ b/crates/net/p2p/src/full_block.rs @@ -133,7 +133,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(); @@ -147,7 +147,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::new(header, resp.into_data())) } @@ -159,10 +159,10 @@ where if let Err(err) = ensure_valid_body_response(header, resp.data()) { 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)); } @@ -223,7 +223,7 @@ where } if let Some(res) = this.take_block() { - return Poll::Ready(res) + return Poll::Ready(res); } } } @@ -258,14 +258,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)); } } @@ -303,14 +303,14 @@ fn ensure_valid_body_response( if header.ommers_hash != ommers_hash { return Err(ConsensusError::BodyOmmersHashDiff( GotExpected { got: ommers_hash, expected: header.ommers_hash }.into(), - )) + )); } let tx_root = block.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, &block.withdrawals) { @@ -320,7 +320,7 @@ fn ensure_valid_body_response( if withdrawals_root != header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root }.into(), - )) + )); } } (None, None) => { @@ -336,7 +336,7 @@ fn ensure_valid_body_response( if requests_root != header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected { got: requests_root, expected: header_requests_root }.into(), - )) + )); } } (None, None) => { @@ -430,7 +430,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()?; @@ -451,7 +451,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() @@ -476,7 +476,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) @@ -501,7 +501,7 @@ where if let Err(err) = self.consensus.validate_header_range(&headers_rising) { debug!(target: "downloaders", %err, ?self.start_hash, "Received bad header response"); self.client.report_bad_message(peer); - return + return; } // get the bodies request so it can be polled later @@ -629,7 +629,7 @@ where } if let Some(res) = this.take_blocks() { - return Poll::Ready(res) + return Poll::Ready(res); } } } @@ -671,13 +671,13 @@ where if let Some(blocks) = &mut this.blocks { if blocks.is_empty() { // Stream is finished - return Poll::Ready(None) + return Poll::Ready(None); } // return the next block if it's ready - the vec should be in ascending order since it // is reversed right after it is received from the future, so we can just pop() the // elements to return them from the stream in descending order - return Poll::Ready(blocks.pop()) + return Poll::Ready(blocks.pop()); } // poll the inner future if the blocks are not yet ready @@ -717,14 +717,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 73dd04849d44..41c26da713fe 100644 --- a/crates/net/p2p/src/test_utils/headers.rs +++ b/crates/net/p2p/src/test_utils/headers.rs @@ -76,7 +76,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()); @@ -136,9 +136,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); } let empty = SealedHeader::default(); @@ -148,7 +148,7 @@ impl Stream for TestDownload { hash: empty.hash(), number: empty.number, error: Box::new(error), - }))) + }))); } match ready!(this.get_or_init_fut().poll_unpin(cx)) { @@ -159,14 +159,14 @@ impl Stream for TestDownload { headers.sort_unstable_by_key(|h| h.number); headers.into_iter().for_each(|h| this.buffer.push(h)); this.done = true; - continue + continue; } Err(err) => { this.done = true; return Poll::Ready(Some(Err(match err { RequestError::Timeout => DownloadError::Timeout, _ => DownloadError::RequestError(err), - }))) + }))); } } } @@ -231,7 +231,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 f531f1eb8f09..1da12cd4a3a1 100644 --- a/crates/net/peers/src/lib.rs +++ b/crates/net/peers/src/lib.rs @@ -160,17 +160,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 3b6c38170d56..090ef67e0e00 100644 --- a/crates/net/peers/src/node_record.rs +++ b/crates/net/peers/src/node_record.rs @@ -63,7 +63,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 @@ -192,15 +192,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/net/peers/src/trusted_peer.rs b/crates/net/peers/src/trusted_peer.rs index 27096bcab3d8..bd1923dcc612 100644 --- a/crates/net/peers/src/trusted_peer.rs +++ b/crates/net/peers/src/trusted_peer.rs @@ -53,14 +53,14 @@ impl TrustedPeer { let tcp_port = self.tcp_port; let udp_port = self.udp_port; - return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }) + return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }); } Host::Ipv6(ip) => { let id = self.id; let tcp_port = self.tcp_port; let udp_port = self.udp_port; - return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }) + return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }); } Host::Domain(domain) => domain, }; diff --git a/crates/node-core/src/args/payload_builder.rs b/crates/node-core/src/args/payload_builder.rs index b6a937156de5..a22074c01228 100644 --- a/crates/node-core/src/args/payload_builder.rs +++ b/crates/node-core/src/args/payload_builder.rs @@ -91,7 +91,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/args/pruning.rs b/crates/node-core/src/args/pruning.rs index 1621f2d8ed8b..5e20aef8d727 100644 --- a/crates/node-core/src/args/pruning.rs +++ b/crates/node-core/src/args/pruning.rs @@ -19,7 +19,7 @@ impl PruningArgs { /// Returns pruning configuration. pub fn prune_config(&self, chain_spec: &ChainSpec) -> Option { if !self.full { - return None + return None; } Some(PruneConfig { block_interval: 5, diff --git a/crates/node-core/src/args/utils.rs b/crates/node-core/src/args/utils.rs index 527e1ac228ac..13a6afcfa1d0 100644 --- a/crates/node-core/src/args/utils.rs +++ b/crates/node-core/src/args/utils.rs @@ -99,7 +99,7 @@ pub fn genesis_value_parser(s: &str) -> eyre::Result, eyre::Error if s.contains('{') { s.to_string() } else { - return Err(io_err.into()) // assume invalid path + return Err(io_err.into()); // assume invalid path } } }; @@ -149,15 +149,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()? diff --git a/crates/node-core/src/engine/skip_fcu.rs b/crates/node-core/src/engine/skip_fcu.rs index d63894a5c951..729e79b75c31 100644 --- a/crates/node-core/src/engine/skip_fcu.rs +++ b/crates/node-core/src/engine/skip_fcu.rs @@ -50,7 +50,7 @@ where *this.skipped += 1; tracing::warn!(target: "engine::intercept", ?state, ?payload_attrs, threshold=this.threshold, skipped=this.skipped, "Skipping FCU"); let _ = tx.send(Ok(OnForkChoiceUpdated::syncing())); - continue + continue; } else { *this.skipped = 0; Some(BeaconEngineMessage::ForkchoiceUpdated { state, payload_attrs, tx }) @@ -58,7 +58,7 @@ where } next => next, }; - return Poll::Ready(item) + return Poll::Ready(item); } } } diff --git a/crates/node-core/src/engine/skip_new_payload.rs b/crates/node-core/src/engine/skip_new_payload.rs index 04db70e0a676..a8e063b41986 100644 --- a/crates/node-core/src/engine/skip_new_payload.rs +++ b/crates/node-core/src/engine/skip_new_payload.rs @@ -53,7 +53,7 @@ where skipped=this.skipped, "Skipping new payload" ); let _ = tx.send(Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing))); - continue + continue; } else { *this.skipped = 0; Some(BeaconEngineMessage::NewPayload { payload, cancun_fields, tx }) @@ -61,7 +61,7 @@ where } next => next, }; - return Poll::Ready(item) + return Poll::Ready(item); } } } diff --git a/crates/node-core/src/metrics/prometheus_exporter.rs b/crates/node-core/src/metrics/prometheus_exporter.rs index b7a3ba7015c3..11e1891b7295 100644 --- a/crates/node-core/src/metrics/prometheus_exporter.rs +++ b/crates/node-core/src/metrics/prometheus_exporter.rs @@ -164,7 +164,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() @@ -253,13 +253,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/node-core/src/node_config.rs b/crates/node-core/src/node_config.rs index 3a3b742cef02..a731e6d3aa58 100644 --- a/crates/node-core/src/node_config.rs +++ b/crates/node-core/src/node_config.rs @@ -352,7 +352,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) @@ -375,7 +375,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/builder/src/launch/exex.rs b/crates/node/builder/src/launch/exex.rs index 103223357c7c..696978ae55ab 100644 --- a/crates/node/builder/src/launch/exex.rs +++ b/crates/node/builder/src/launch/exex.rs @@ -37,7 +37,7 @@ impl ExExLauncher { if extensions.is_empty() { // nothing to launch - return None + return None; } let mut exex_handles = Vec::with_capacity(extensions.len()); diff --git a/crates/node/events/src/cl.rs b/crates/node/events/src/cl.rs index 47f1de6683f0..0ad05b723038 100644 --- a/crates/node/events/src/cl.rs +++ b/crates/node/events/src/cl.rs @@ -52,14 +52,14 @@ 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; } else { // We had an FCU, but it's too old. return Poll::Ready(Some( ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile( fork_choice.elapsed(), ), - )) + )); } } @@ -74,11 +74,11 @@ impl Stream for ConsensusLayerHealthEvents { Poll::Ready(Some(ConsensusLayerHealthEvent::HasNotBeenSeenForAWhile( transition_config.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 8a25c370037b..352c1a382366 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -614,7 +614,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(); @@ -622,7 +622,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(); @@ -663,7 +663,7 @@ impl Display for Eta { f, "{}", humantime::format_duration(Duration::from_secs(remaining.as_secs())) - ) + ); } } diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index 0c5439bf7448..a3561a0c8267 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -83,11 +83,11 @@ impl Consensus for OptimismBeaconConsensus { if is_post_merge { if header.nonce != 0 { - 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 @@ -112,7 +112,7 @@ impl Consensus for OptimismBeaconConsensus { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp, present_timestamp, - }) + }); } } diff --git a/crates/optimism/consensus/src/validation.rs b/crates/optimism/consensus/src/validation.rs index 8aa00c53cec4..8e582f2bab11 100644 --- a/crates/optimism/consensus/src/validation.rs +++ b/crates/optimism/consensus/src/validation.rs @@ -27,7 +27,7 @@ pub fn validate_block_post_execution( block.timestamp, ) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error) + return Err(error); } } @@ -38,7 +38,7 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.gas_used }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }) + }); } Ok(()) @@ -81,13 +81,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/evm/src/execute.rs b/crates/optimism/evm/src/execute.rs index a3062b89aae8..ee30920eb2eb 100644 --- a/crates/optimism/evm/src/execute.rs +++ b/crates/optimism/evm/src/execute.rs @@ -153,12 +153,12 @@ where transaction_gas_limit: transaction.gas_limit(), block_available_gas, } - .into()) + .into()); } // An optimism block should never contain blob transactions. if matches!(transaction.tx_type(), TxType::Eip4844) { - return Err(OptimismBlockExecutionError::BlobTransactionRejected.into()) + return Err(OptimismBlockExecutionError::BlobTransactionRejected.into()); } // Cache the depositor account prior to the state transition for the deposit nonce. diff --git a/crates/optimism/evm/src/l1.rs b/crates/optimism/evm/src/l1.rs index a750c8f4f0a9..3096fa5112f8 100644 --- a/crates/optimism/evm/src/l1.rs +++ b/crates/optimism/evm/src/l1.rs @@ -40,7 +40,7 @@ pub fn extract_l1_info(block: &Block) -> Result Result Result Result { if is_deposit { - return Ok(U256::ZERO) + return Ok(U256::ZERO); } let spec_id = if chain_spec.is_fork_active_at_timestamp(Hardfork::Fjord, timestamp) { @@ -203,7 +203,7 @@ impl RethL1BlockInfo for L1BlockInfo { return Err(OptimismBlockExecutionError::L1BlockInfoError { message: "Optimism hardforks are not active".to_string(), } - .into()) + .into()); }; Ok(self.calculate_tx_l1_cost(input, spec_id)) } @@ -224,7 +224,7 @@ impl RethL1BlockInfo for L1BlockInfo { return Err(OptimismBlockExecutionError::L1BlockInfoError { message: "Optimism hardforks are not active".to_string(), } - .into()) + .into()); }; Ok(self.data_gas(input, spec_id)) } @@ -264,7 +264,7 @@ where // Commit the create2 deployer account to the database. db.commit(HashMap::from([(CREATE_2_DEPLOYER_ADDR, revm_acc)])); - return Ok(()) + return Ok(()); } Ok(()) diff --git a/crates/optimism/node/src/engine.rs b/crates/optimism/node/src/engine.rs index 6507d5c9290f..5169f1e80ba5 100644 --- a/crates/optimism/node/src/engine.rs +++ b/crates/optimism/node/src/engine.rs @@ -75,21 +75,21 @@ pub fn validate_withdrawals_presence( EngineApiMessageVersion::V1 => { if has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)) + .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)); } if is_shanghai { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); } } EngineApiMessageVersion::V2 | EngineApiMessageVersion::V3 | EngineApiMessageVersion::V4 => { if is_shanghai && !has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); } if !is_shanghai && has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)) + .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)); } } }; diff --git a/crates/optimism/node/src/txpool.rs b/crates/optimism/node/src/txpool.rs index b29bc4bb0303..67a1b1f3df08 100644 --- a/crates/optimism/node/src/txpool.rs +++ b/crates/optimism/node/src/txpool.rs @@ -97,7 +97,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ) + ); } let outcome = self.inner.validate_one(origin, transaction); @@ -136,7 +136,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ) + ); } return TransactionValidationOutcome::Valid { @@ -144,7 +144,7 @@ where state_nonce, transaction: valid_tx, propagate, - } + }; } outcome diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index d0289efc8bd6..7379e4f3d268 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -311,14 +311,14 @@ where for sequencer_tx in &attributes.transactions { // Check if the job was cancelled, if so we can exit early. if cancel.is_cancelled() { - return Ok(BuildOutcome::Cancelled) + return Ok(BuildOutcome::Cancelled); } // A sequencer's block should never contain blob transactions. if sequencer_tx.is_eip4844() { return Err(PayloadBuilderError::other( OptimismPayloadBuilderError::BlobTransactionRejected, - )) + )); } // Convert the transaction to a [TransactionSignedEcRecovered]. This is @@ -360,11 +360,11 @@ where match err { EVMError::Transaction(err) => { trace!(target: "payload_builder", %err, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue + continue; } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)) + return Err(PayloadBuilderError::EvmExecutionError(err)); } } } @@ -410,7 +410,7 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(&pool_tx); - continue + continue; } // A sequencer's block should never contain blob or deposit transactions from the pool. @@ -420,7 +420,7 @@ where // 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 @@ -449,11 +449,11 @@ where best_txs.mark_invalid(&pool_tx); } - continue + continue; } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)) + return Err(PayloadBuilderError::EvmExecutionError(err)); } } } @@ -493,7 +493,7 @@ where // check if we have a better block if !is_better_payload(best_payload.as_ref(), total_fees) { // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); } let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals( diff --git a/crates/optimism/primitives/src/bedrock_import.rs b/crates/optimism/primitives/src/bedrock_import.rs index 17020f9f2b90..5ced80835ac4 100644 --- a/crates/optimism/primitives/src/bedrock_import.rs +++ b/crates/optimism/primitives/src/bedrock_import.rs @@ -40,12 +40,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/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 26dc06293404..65d2eea56102 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -412,7 +412,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 @@ -473,7 +473,7 @@ where fn best_payload(&self) -> Result { if let Some(ref payload) = self.best_payload { - return Ok(payload.clone()) + return Ok(payload.clone()); } // No payload has been built yet, but we need to return something that the CL then can // deliver, so we need to return an empty payload. @@ -591,14 +591,14 @@ where this.maybe_better = None; if let Ok(BuildOutcome::Better { payload, .. }) = res { debug!(target: "payload_builder", "resolving better payload"); - return Poll::Ready(Ok(payload)) + return Poll::Ready(Ok(payload)); } } } 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() { @@ -614,12 +614,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 @@ -902,11 +902,11 @@ pub fn commit_withdrawals>( withdrawals: Withdrawals, ) -> Result { if !chain_spec.is_shanghai_active_at_timestamp(timestamp) { - return Ok(WithdrawalsOutcome::pre_shanghai()) + return Ok(WithdrawalsOutcome::pre_shanghai()); } if withdrawals.is_empty() { - return Ok(WithdrawalsOutcome::empty()) + return Ok(WithdrawalsOutcome::empty()); } let balance_increments = diff --git a/crates/payload/builder/src/noop.rs b/crates/payload/builder/src/noop.rs index ef919ecf76e8..9cb1a8d66799 100644 --- a/crates/payload/builder/src/noop.rs +++ b/crates/payload/builder/src/noop.rs @@ -43,7 +43,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 98790ef7d8b7..d0a39799cd49 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -446,7 +446,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 52029a3c4a37..b2729030913c 100644 --- a/crates/payload/primitives/src/lib.rs +++ b/crates/payload/primitives/src/lib.rs @@ -67,7 +67,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 == EngineApiMessageVersion::V3 && !is_cancun { @@ -89,7 +89,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); @@ -112,7 +112,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); } Ok(()) } @@ -133,17 +133,17 @@ 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 => { 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)); } } }; @@ -234,13 +234,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 => { if !has_parent_beacon_block_root { return Err(validation_kind - .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)) + .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)); } } }; diff --git a/crates/payload/primitives/src/traits.rs b/crates/payload/primitives/src/traits.rs index 094fe829234e..259b14b3f6e3 100644 --- a/crates/payload/primitives/src/traits.rs +++ b/crates/payload/primitives/src/traits.rs @@ -150,7 +150,7 @@ impl PayloadAttributes for OptimismPayloadAttributes { if self.gas_limit.is_none() && chain_spec.is_optimism() { return Err(EngineObjectValidationError::InvalidParams( "MissingGasLimitInPayloadAttributes".to_string().into(), - )) + )); } Ok(()) diff --git a/crates/payload/validator/src/lib.rs b/crates/payload/validator/src/lib.rs index afc19037732d..e5cfd94c4dc7 100644 --- a/crates/payload/validator/src/lib.rs +++ b/crates/payload/validator/src/lib.rs @@ -59,20 +59,20 @@ impl ExecutionPayloadValidator { if let Some(versioned_hashes) = cancun_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(sealed_block.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); } } @@ -118,45 +118,45 @@ impl ExecutionPayloadValidator { return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - }) + }); } if self.is_cancun_active_at_timestamp(sealed_block.timestamp) { if sealed_block.header.blob_gas_used.is_none() { // cancun active but blob gas used not present - return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed) + return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed); } if sealed_block.header.excess_blob_gas.is_none() { // cancun active but excess blob gas not present - return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas) + return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas); } if cancun_fields.as_ref().is_none() { // cancun active but cancun fields not present - return Err(PayloadError::PostCancunWithoutCancunFields) + return Err(PayloadError::PostCancunWithoutCancunFields); } } else { if sealed_block.has_blob_transactions() { // cancun not active but blob transactions present - return Err(PayloadError::PreCancunBlockWithBlobTransactions) + return Err(PayloadError::PreCancunBlockWithBlobTransactions); } if sealed_block.header.blob_gas_used.is_some() { // cancun not active but blob gas used present - return Err(PayloadError::PreCancunBlockWithBlobGasUsed) + return Err(PayloadError::PreCancunBlockWithBlobGasUsed); } if sealed_block.header.excess_blob_gas.is_some() { // cancun not active but excess blob gas present - return Err(PayloadError::PreCancunBlockWithExcessBlobGas) + return Err(PayloadError::PreCancunBlockWithExcessBlobGas); } if cancun_fields.as_ref().is_some() { // cancun not active but cancun fields present - return Err(PayloadError::PreCancunWithCancunFields) + return Err(PayloadError::PreCancunWithCancunFields); } } let shanghai_active = self.is_shanghai_active_at_timestamp(sealed_block.timestamp); if !shanghai_active && sealed_block.withdrawals.is_some() { // shanghai not active but withdrawals present - return Err(PayloadError::PreShanghaiBlockWithWitdrawals) + return Err(PayloadError::PreShanghaiBlockWithWitdrawals); } // EIP-4844 checks diff --git a/crates/primitives-traits/src/header/mod.rs b/crates/primitives-traits/src/header/mod.rs index 5ec41d41450c..1235fb86bdf1 100644 --- a/crates/primitives-traits/src/header/mod.rs +++ b/crates/primitives-traits/src/header/mod.rs @@ -155,7 +155,7 @@ impl Header { /// Returns an error if the extradata size is larger than 100 KB. pub fn ensure_extradata_valid(&self) -> Result<(), HeaderError> { if self.extra_data.len() > 100 * 1024 { - return Err(HeaderError::LargeExtraData) + return Err(HeaderError::LargeExtraData); } Ok(()) } @@ -167,7 +167,7 @@ impl Header { /// Returns an error if the block difficulty exceeds 80 bits. pub fn ensure_difficulty_valid(&self) -> Result<(), HeaderError> { if self.difficulty.bit_len() > 80 { - return Err(HeaderError::LargeDifficulty) + return Err(HeaderError::LargeDifficulty); } Ok(()) } @@ -435,7 +435,7 @@ impl Decodable for Header { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { let rlp_head = alloy_rlp::Header::decode(buf)?; if !rlp_head.list { - return Err(alloy_rlp::Error::UnexpectedString) + return Err(alloy_rlp::Error::UnexpectedString); } let started_len = buf.len(); let mut this = Self { @@ -502,7 +502,7 @@ impl Decodable for Header { return Err(alloy_rlp::Error::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } Ok(this) } diff --git a/crates/primitives/src/alloy_compat.rs b/crates/primitives/src/alloy_compat.rs index d193b787fd52..20b3ef9ac22e 100644 --- a/crates/primitives/src/alloy_compat.rs +++ b/crates/primitives/src/alloy_compat.rs @@ -82,7 +82,7 @@ impl TryFrom for Transaction { return Err(ConversionError::Eip2718Error( RlpError::Custom("EIP-1559 fields are present in a legacy transaction") .into(), - )) + )); } // extract the chain id if possible @@ -98,7 +98,7 @@ impl TryFrom for Transaction { .map_err(|err| ConversionError::Eip2718Error(err.into()))? .1 } else { - return Err(ConversionError::MissingChainId) + return Err(ConversionError::MissingChainId); } } }; diff --git a/crates/primitives/src/block.rs b/crates/primitives/src/block.rs index 1e14392bffb6..4a65b7329229 100644 --- a/crates/primitives/src/block.rs +++ b/crates/primitives/src/block.rs @@ -126,7 +126,7 @@ impl Block { let Some(senders) = TransactionSigned::recover_signers_unchecked(&self.body, self.body.len()) else { - return Err(self) + return Err(self); }; senders }; @@ -430,7 +430,7 @@ impl SealedBlock { return Err(GotExpected { got: calculated_root, expected: self.header.transactions_root, - }) + }); } Ok(()) diff --git a/crates/primitives/src/compression/mod.rs b/crates/primitives/src/compression/mod.rs index f7af0acbe4de..4b039b5a627f 100644 --- a/crates/primitives/src/compression/mod.rs +++ b/crates/primitives/src/compression/mod.rs @@ -74,7 +74,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/primitives/src/lib.rs b/crates/primitives/src/lib.rs index b965de1673df..771417678183 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -62,7 +62,7 @@ pub use error::{GotExpected, GotExpectedBoxed}; pub use genesis::{ChainConfig, Genesis, GenesisAccount}; pub use header::{Header, HeadersDirection, SealedHeader}; pub use integer_list::IntegerList; -pub use log::{logs_bloom, Log}; +pub use log::{logs_bloom, Log, LogData}; pub use receipt::{ gas_spent_by_transactions, Receipt, ReceiptWithBloom, ReceiptWithBloomRef, Receipts, }; diff --git a/crates/primitives/src/log.rs b/crates/primitives/src/log.rs index b2b6b8a4852c..9d04fed387e0 100644 --- a/crates/primitives/src/log.rs +++ b/crates/primitives/src/log.rs @@ -1,6 +1,6 @@ use crate::Bloom; -pub use alloy_primitives::Log; +pub use alloy_primitives::{Log, LogData}; /// Calculate receipt logs bloom. pub fn logs_bloom<'a>(logs: impl IntoIterator) -> Bloom { diff --git a/crates/primitives/src/proofs.rs b/crates/primitives/src/proofs.rs index 4e40dd480cff..bce08ceabfca 100644 --- a/crates/primitives/src/proofs.rs +++ b/crates/primitives/src/proofs.rs @@ -64,7 +64,7 @@ pub fn calculate_receipt_root_optimism( return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| { r.encode_inner(buf, false) - }) + }); } ordered_trie_root_with_encoder(receipts, |r, buf| r.encode_inner(buf, false)) @@ -112,7 +112,7 @@ pub fn calculate_receipt_root_no_memo_optimism( return ordered_trie_root_with_encoder(&receipts, |r, buf| { ReceiptWithBloomRef::from(r).encode_inner(buf, false) - }) + }); } ordered_trie_root_with_encoder(receipts, |r, buf| { @@ -124,7 +124,7 @@ pub fn calculate_receipt_root_no_memo_optimism( pub fn calculate_ommers_root(ommers: &[Header]) -> B256 { // Check if `ommers` list is empty if ommers.is_empty() { - return EMPTY_OMMER_ROOT_HASH + return EMPTY_OMMER_ROOT_HASH; } // RLP Encode let mut ommers_rlp = Vec::new(); diff --git a/crates/primitives/src/receipt.rs b/crates/primitives/src/receipt.rs index da84dda8b4a7..1e9b983f1ae0 100644 --- a/crates/primitives/src/receipt.rs +++ b/crates/primitives/src/receipt.rs @@ -295,7 +295,7 @@ impl ReceiptWithBloom { let b = &mut &**buf; let rlp_head = alloy_rlp::Header::decode(b)?; if !rlp_head.list { - return Err(alloy_rlp::Error::UnexpectedString) + return Err(alloy_rlp::Error::UnexpectedString); } let started_len = b.len(); @@ -340,7 +340,7 @@ impl ReceiptWithBloom { return Err(alloy_rlp::Error::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }) + }); } *buf = *b; Ok(this) @@ -493,7 +493,7 @@ impl<'a> ReceiptWithBloomEncoder<'a> { fn encode_inner(&self, out: &mut dyn BufMut, with_header: bool) { if matches!(self.receipt.tx_type, TxType::Legacy) { self.encode_fields(out); - return + return; } let mut payload = Vec::new(); diff --git a/crates/primitives/src/revm/config.rs b/crates/primitives/src/revm/config.rs index 6ad76123f149..5c424b355c30 100644 --- a/crates/primitives/src/revm/config.rs +++ b/crates/primitives/src/revm/config.rs @@ -19,7 +19,7 @@ pub fn revm_spec_by_timestamp_after_merge( revm_primitives::REGOLITH } else { revm_primitives::BEDROCK - } + }; } if chain_spec.is_prague_active_at_timestamp(timestamp) { @@ -38,15 +38,15 @@ pub fn revm_spec(chain_spec: &ChainSpec, block: Head) -> revm_primitives::SpecId #[cfg(feature = "optimism")] if chain_spec.is_optimism() { if chain_spec.fork(Hardfork::Fjord).active_at_head(&block) { - return revm_primitives::FJORD + return revm_primitives::FJORD; } else if chain_spec.fork(Hardfork::Ecotone).active_at_head(&block) { - return revm_primitives::ECOTONE + return revm_primitives::ECOTONE; } else if chain_spec.fork(Hardfork::Canyon).active_at_head(&block) { - return revm_primitives::CANYON + return revm_primitives::CANYON; } else if chain_spec.fork(Hardfork::Regolith).active_at_head(&block) { - return revm_primitives::REGOLITH + return revm_primitives::REGOLITH; } else if chain_spec.fork(Hardfork::Bedrock).active_at_head(&block) { - return revm_primitives::BEDROCK + return revm_primitives::BEDROCK; } } diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 42e420a5e9f7..471c9c4269f1 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -388,7 +388,7 @@ impl Transaction { // Check if max_fee_per_gas is less than base_fee if max_fee_per_gas < base_fee { - return None + return None; } // Calculate the difference between max_fee_per_gas and base_fee @@ -773,7 +773,7 @@ impl TransactionSignedNoHash { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from) + return Some(from); } let signature_hash = self.signature_hash(); @@ -802,7 +802,7 @@ impl TransactionSignedNoHash { #[cfg(feature = "optimism")] { if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from) + return Some(from); } // pre bedrock system transactions were sent from the zero address as legacy @@ -810,7 +810,7 @@ impl TransactionSignedNoHash { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if self.is_legacy() && self.signature == Signature::optimism_deposit_tx_signature() { - return Some(Address::ZERO) + return Some(Address::ZERO); } } @@ -1026,7 +1026,7 @@ impl TransactionSigned { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from) + return Some(from); } let signature_hash = self.signature_hash(); self.signature.recover_signer(signature_hash) @@ -1042,7 +1042,7 @@ impl TransactionSigned { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from) + return Some(from); } let signature_hash = self.signature_hash(); self.signature.recover_signer_unchecked(signature_hash) @@ -1216,7 +1216,7 @@ impl TransactionSigned { let transaction_payload_len = header.payload_length; if transaction_payload_len > remaining_len { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } let mut transaction = TxLegacy { @@ -1234,7 +1234,7 @@ impl TransactionSigned { // check the new length, compared to the original length and the header length let decoded = remaining_len - data.len(); if decoded != transaction_payload_len { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } let tx_length = header.payload_length + header.length(); @@ -1279,7 +1279,7 @@ impl TransactionSigned { // decode the list header for the rest of the transaction let header = Header::decode(data)?; if !header.list { - return Err(RlpError::Custom("typed tx fields must be encoded as a list")) + return Err(RlpError::Custom("typed tx fields must be encoded as a list")); } let remaining_len = data.len(); @@ -1289,7 +1289,7 @@ impl TransactionSigned { // decode common fields let Ok(tx_type) = TxType::try_from(tx_type) else { - return Err(RlpError::Custom("unsupported typed transaction type")) + return Err(RlpError::Custom("unsupported typed transaction type")); }; let transaction = match tx_type { @@ -1313,7 +1313,7 @@ impl TransactionSigned { let bytes_consumed = remaining_len - data.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } let hash = keccak256(&original_encoding_without_header[..tx_length]); @@ -1340,7 +1340,7 @@ impl TransactionSigned { /// of bytes in input data. pub fn decode_enveloped(input_data: &mut &[u8]) -> alloy_rlp::Result { if input_data.is_empty() { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } // Check if the tx is a list @@ -1352,7 +1352,7 @@ impl TransactionSigned { }; if !input_data.is_empty() { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } Ok(output_data) @@ -1430,7 +1430,7 @@ impl Decodable for TransactionSigned { /// string header if the first byte is less than `0xf7`. fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { if buf.is_empty() { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } // decode header @@ -1448,7 +1448,7 @@ impl Decodable for TransactionSigned { // string Header with payload_length of 1, we need to make sure this check is only // performed for transactions with a string header if bytes_consumed != header.payload_length && original_encoding[0] > EMPTY_STRING_CODE { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } Ok(tx) diff --git a/crates/primitives/src/transaction/pooled.rs b/crates/primitives/src/transaction/pooled.rs index 2ca58b179748..23864823e6d5 100644 --- a/crates/primitives/src/transaction/pooled.rs +++ b/crates/primitives/src/transaction/pooled.rs @@ -183,7 +183,7 @@ impl PooledTransactionsElement { /// `[chain_id, nonce, max_priority_fee_per_gas, ..., y_parity, r, s]` pub fn decode_enveloped(data: &mut &[u8]) -> alloy_rlp::Result { if data.is_empty() { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } // Check if the tx is a list - tx types are less than EMPTY_LIST_CODE (0xc0) @@ -493,7 +493,7 @@ impl Decodable for PooledTransactionsElement { // // First, we check whether or not the transaction is a legacy transaction. if buf.is_empty() { - return Err(RlpError::InputTooShort) + return Err(RlpError::InputTooShort); } // keep the original buf around for legacy decoding @@ -539,7 +539,7 @@ impl Decodable for PooledTransactionsElement { // check that the bytes consumed match the payload length let bytes_consumed = remaining_len - buf.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } Ok(Self::BlobTransaction(blob_tx)) @@ -551,7 +551,7 @@ impl Decodable for PooledTransactionsElement { // check that the bytes consumed match the payload length let bytes_consumed = remaining_len - buf.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } // because we checked the tx type, we can be sure that the transaction is not a diff --git a/crates/primitives/src/transaction/sidecar.rs b/crates/primitives/src/transaction/sidecar.rs index c45683ce7980..eb6762a57ff5 100644 --- a/crates/primitives/src/transaction/sidecar.rs +++ b/crates/primitives/src/transaction/sidecar.rs @@ -216,7 +216,7 @@ impl BlobTransaction { // decode the _first_ list header for the rest of the transaction let outer_header = Header::decode(data)?; if !outer_header.list { - return Err(RlpError::Custom("PooledTransactions blob tx must be encoded as a list")) + return Err(RlpError::Custom("PooledTransactions blob tx must be encoded as a list")); } let outer_remaining_len = data.len(); @@ -228,7 +228,7 @@ impl BlobTransaction { if !inner_header.list { return Err(RlpError::Custom( "PooledTransactions inner blob tx must be encoded as a list", - )) + )); } let inner_remaining_len = data.len(); @@ -242,7 +242,7 @@ impl BlobTransaction { // the inner header only decodes the transaction and signature, so we check the length here let inner_consumed = inner_remaining_len - data.len(); if inner_consumed != inner_header.payload_length { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } // All that's left are the blobs, commitments, and proofs @@ -271,7 +271,7 @@ impl BlobTransaction { // the outer header is for the entire transaction, so we check the length here let outer_consumed = outer_remaining_len - data.len(); if outer_consumed != outer_header.payload_length { - return Err(RlpError::UnexpectedLength) + return Err(RlpError::UnexpectedLength); } Ok(Self { transaction, hash, signature, sidecar }) @@ -357,7 +357,7 @@ mod tests { // Ensure the entry is a file and not a directory if !file_path.is_file() || file_path.extension().unwrap_or_default() != "json" { - continue + continue; } // Read the contents of the JSON file into a string. diff --git a/crates/primitives/src/transaction/signature.rs b/crates/primitives/src/transaction/signature.rs index 077858a3c579..3176f8934561 100644 --- a/crates/primitives/src/transaction/signature.rs +++ b/crates/primitives/src/transaction/signature.rs @@ -89,7 +89,7 @@ impl Signature { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if *self == Self::optimism_deposit_tx_signature() { - return 0 + return 0; } self.odd_y_parity as u64 + 27 } @@ -113,7 +113,7 @@ impl Signature { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if v == 0 && r.is_zero() && s.is_zero() { - return Ok((Self { r, s, odd_y_parity: false }, None)) + return Ok((Self { r, s, odd_y_parity: false }, None)); } } } @@ -168,7 +168,7 @@ impl Signature { /// If the S value is too large, then this will return `None` pub fn recover_signer(&self, hash: B256) -> Option
{ if self.s > SECP256K1N_HALF { - return None + return None; } self.recover_signer_unchecked(hash) @@ -204,7 +204,7 @@ pub const fn extract_chain_id(v: u64) -> alloy_rlp::Result<(bool, Option)> if v < 35 { // non-EIP-155 legacy scheme, v = 27 for even y-parity, v = 28 for odd y-parity if v != 27 && v != 28 { - return Err(RlpError::Custom("invalid Ethereum signature (V is not 27 or 28)")) + return Err(RlpError::Custom("invalid Ethereum signature (V is not 27 or 28)")); } Ok((v == 28, None)) } else { diff --git a/crates/primitives/src/transaction/tx_type.rs b/crates/primitives/src/transaction/tx_type.rs index 7530fda086f8..fc99458b2e6b 100644 --- a/crates/primitives/src/transaction/tx_type.rs +++ b/crates/primitives/src/transaction/tx_type.rs @@ -87,17 +87,17 @@ impl TryFrom for TxType { fn try_from(value: u8) -> Result { #[cfg(feature = "optimism")] if value == Self::Deposit { - return Ok(Self::Deposit) + return Ok(Self::Deposit); } if value == Self::Legacy { - return Ok(Self::Legacy) + return Ok(Self::Legacy); } else if value == Self::Eip2930 { - return Ok(Self::Eip2930) + return Ok(Self::Eip2930); } else if value == Self::Eip1559 { - return Ok(Self::Eip1559) + return Ok(Self::Eip1559); } else if value == Self::Eip4844 { - return Ok(Self::Eip4844) + return Ok(Self::Eip4844); } Err("invalid tx type") diff --git a/crates/prune/prune/Cargo.toml b/crates/prune/prune/Cargo.toml index c45ea9d3f7f1..016265e1b5c6 100644 --- a/crates/prune/prune/Cargo.toml +++ b/crates/prune/prune/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] # reth -reth-chainspec.workspace = true reth-exex-types.workspace = true reth-primitives.workspace = true reth-db.workspace = true diff --git a/crates/prune/prune/src/builder.rs b/crates/prune/prune/src/builder.rs index 233e80a71a9a..a91a0faa6d51 100644 --- a/crates/prune/prune/src/builder.rs +++ b/crates/prune/prune/src/builder.rs @@ -1,8 +1,8 @@ use crate::{segments::SegmentSet, Pruner}; -use reth_chainspec::MAINNET; use reth_config::PruneConfig; use reth_db_api::database::Database; use reth_exex_types::FinishedExExHeight; +use reth_primitives::MAINNET; use reth_provider::ProviderFactory; use reth_prune_types::PruneModes; use std::time::Duration; diff --git a/crates/prune/prune/src/pruner.rs b/crates/prune/prune/src/pruner.rs index 47864a274e03..da805c77fa77 100644 --- a/crates/prune/prune/src/pruner.rs +++ b/crates/prune/prune/src/pruner.rs @@ -332,9 +332,9 @@ impl Pruner { mod tests { use crate::Pruner; - use reth_chainspec::MAINNET; use reth_db::test_utils::{create_test_rw_db, create_test_static_files_dir}; use reth_exex_types::FinishedExExHeight; + use reth_primitives::MAINNET; use reth_provider::{providers::StaticFileProvider, ProviderFactory}; #[test] diff --git a/crates/revm/src/batch.rs b/crates/revm/src/batch.rs index 6f1b55b2195d..7b1980cdc22c 100644 --- a/crates/revm/src/batch.rs +++ b/crates/revm/src/batch.rs @@ -137,7 +137,7 @@ impl BlockBatchRecord { self.prune_modes.receipts.map_or(false, |mode| mode.should_prune(block_number, tip)) { receipts.clear(); - return Ok(()) + return Ok(()); } // All receipts from the last 128 blocks are required for blockchain tree, even with @@ -145,7 +145,7 @@ impl BlockBatchRecord { let prunable_receipts = PruneMode::Distance(MINIMUM_PRUNING_DISTANCE).should_prune(block_number, tip); if !prunable_receipts { - return Ok(()) + return Ok(()); } let contract_log_pruner = self.prune_modes.receipts_log_filter.group_by_block(tip, None)?; diff --git a/crates/revm/src/state_change.rs b/crates/revm/src/state_change.rs index 1709b54cb80d..71ed774e2aa6 100644 --- a/crates/revm/src/state_change.rs +++ b/crates/revm/src/state_change.rs @@ -92,7 +92,7 @@ where { // If Prague is not activated or this is the genesis block, no hashes are added. if !chain_spec.is_prague_active_at_timestamp(block_timestamp) || block_number == 0 { - return Ok(()) + return Ok(()); } assert!(block_number > 0); @@ -158,7 +158,7 @@ where DB::Error: std::fmt::Display, { if !chain_spec.is_cancun_active_at_timestamp(block_timestamp) { - return Ok(()) + return Ok(()); } let parent_beacon_block_root = @@ -171,9 +171,9 @@ where return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { parent_beacon_block_root, } - .into()) + .into()); } - return Ok(()) + return Ok(()); } // get previous env @@ -190,7 +190,7 @@ where parent_beacon_block_root: Box::new(parent_beacon_block_root), message: e.to_string(), } - .into()) + .into()); } }; @@ -273,7 +273,7 @@ where return Err(BlockValidationError::WithdrawalRequestsContractCall { message: format!("execution failed: {e}"), } - .into()) + .into()); } }; @@ -314,7 +314,7 @@ where return Err(BlockValidationError::WithdrawalRequestsContractCall { message: "invalid withdrawal request length".to_string(), } - .into()) + .into()); } let mut source_address = Address::ZERO; diff --git a/crates/rpc/rpc-api/src/admin.rs b/crates/rpc/rpc-api/src/admin.rs index 173cd8ef7a98..15904fee4989 100644 --- a/crates/rpc/rpc-api/src/admin.rs +++ b/crates/rpc/rpc-api/src/admin.rs @@ -1,5 +1,6 @@ use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_network_peers::{AnyNode, NodeRecord}; +use reth_network_peers::AnyNode; +use reth_primitives::NodeRecord; use reth_rpc_types::{admin::NodeInfo, PeerInfo}; /// Admin namespace rpc interface that gives access to several non-standard RPC methods. diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index 46105030cb63..fa1aabae7118 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -43,7 +43,6 @@ thiserror.workspace = true tracing.workspace = true [dev-dependencies] -reth-chainspec.workspace = true reth-beacon-consensus.workspace = true reth-network-api.workspace = true reth-evm-ethereum.workspace = true diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index caf16ebf6fce..34ac352eee22 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -11,9 +11,9 @@ use jsonrpsee::{ rpc_params, types::error::ErrorCode, }; -use reth_chainspec::net::NodeRecord; use reth_primitives::{ - hex_literal::hex, Address, BlockId, BlockNumberOrTag, Bytes, TxHash, B256, B64, U256, U64, + hex_literal::hex, Address, BlockId, BlockNumberOrTag, Bytes, NodeRecord, TxHash, B256, B64, + U256, U64, }; use reth_rpc_api::{ clients::{AdminApiClient, EthApiClient}, diff --git a/crates/rpc/rpc-builder/tests/it/utils.rs b/crates/rpc/rpc-builder/tests/it/utils.rs index d751b2d331a2..9d660ae3035d 100644 --- a/crates/rpc/rpc-builder/tests/it/utils.rs +++ b/crates/rpc/rpc-builder/tests/it/utils.rs @@ -1,9 +1,9 @@ use reth_beacon_consensus::BeaconConsensusEngineHandle; -use reth_chainspec::MAINNET; use reth_ethereum_engine_primitives::EthEngineTypes; use reth_evm_ethereum::EthEvmConfig; use reth_network_api::noop::NoopNetwork; use reth_payload_builder::test_utils::spawn_test_payload_service; +use reth_primitives::MAINNET; use reth_provider::test_utils::{NoopProvider, TestCanonStateSubscriptions}; use reth_rpc_builder::{ auth::{AuthRpcModule, AuthServerConfig, AuthServerHandle}, diff --git a/crates/rpc/rpc-engine-api/Cargo.toml b/crates/rpc/rpc-engine-api/Cargo.toml index d067515f6c2a..80c69d8a4dc4 100644 --- a/crates/rpc/rpc-engine-api/Cargo.toml +++ b/crates/rpc/rpc-engine-api/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] # reth -reth-chainspec.workspace = true reth-primitives.workspace = true reth-rpc-api.workspace = true reth-rpc-types.workspace = true diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index 8185bbe8cc04..a856bdc1707a 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -2,7 +2,6 @@ use crate::{metrics::EngineApiMetrics, EngineApiError, EngineApiResult}; use async_trait::async_trait; use jsonrpsee_core::RpcResult; use reth_beacon_consensus::BeaconConsensusEngineHandle; -use reth_chainspec::ChainSpec; use reth_engine_primitives::EngineTypes; use reth_evm::provider::EvmEnvProvider; use reth_payload_builder::PayloadStore; @@ -10,7 +9,7 @@ use reth_payload_primitives::{ validate_payload_timestamp, EngineApiMessageVersion, PayloadAttributes, PayloadBuilderAttributes, PayloadOrAttributes, }; -use reth_primitives::{BlockHash, BlockHashOrNumber, BlockNumber, Hardfork, B256, U64}; +use reth_primitives::{BlockHash, BlockHashOrNumber, BlockNumber, ChainSpec, Hardfork, B256, U64}; use reth_rpc_api::EngineApiServer; use reth_rpc_types::engine::{ CancunPayloadFields, ClientVersionV1, ExecutionPayload, ExecutionPayloadBodiesV1, @@ -843,9 +842,8 @@ mod tests { use reth_ethereum_engine_primitives::EthEngineTypes; use reth_testing_utils::generators::random_block; - use reth_chainspec::MAINNET; use reth_payload_builder::test_utils::spawn_test_payload_service; - use reth_primitives::{SealedBlock, B256}; + use reth_primitives::{SealedBlock, B256, MAINNET}; use reth_provider::test_utils::MockEthProvider; use reth_rpc_types::engine::{ClientCode, ClientVersionV1}; use reth_rpc_types_compat::engine::payload::execution_payload_from_sealed_block; diff --git a/crates/rpc/rpc/Cargo.toml b/crates/rpc/rpc/Cargo.toml index 378f665bf90b..85ef532d22f4 100644 --- a/crates/rpc/rpc/Cargo.toml +++ b/crates/rpc/rpc/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] # reth -reth-chainspec.workspace = true reth-primitives.workspace = true reth-rpc-api.workspace = true reth-rpc-server-types.workspace = true diff --git a/crates/rpc/rpc/src/admin.rs b/crates/rpc/rpc/src/admin.rs index 2ee093aed28e..2ea412bb207f 100644 --- a/crates/rpc/rpc/src/admin.rs +++ b/crates/rpc/rpc/src/admin.rs @@ -2,10 +2,9 @@ use crate::result::ToRpcResult; use alloy_primitives::B256; use async_trait::async_trait; use jsonrpsee::core::RpcResult; -use reth_chainspec::ChainSpec; use reth_network_api::{NetworkInfo, PeerKind, Peers}; -use reth_network_peers::{AnyNode, NodeRecord}; -use reth_primitives::ChainConfig; +use reth_network_peers::AnyNode; +use reth_primitives::{ChainConfig, ChainSpec, NodeRecord}; use reth_rpc_api::AdminApiServer; use reth_rpc_types::{ admin::{EthProtocolInfo, NodeInfo, Ports, ProtocolInfo}, diff --git a/crates/rpc/rpc/src/eth/api/fee_history.rs b/crates/rpc/rpc/src/eth/api/fee_history.rs index 626c670376c8..da43be5510ab 100644 --- a/crates/rpc/rpc/src/eth/api/fee_history.rs +++ b/crates/rpc/rpc/src/eth/api/fee_history.rs @@ -6,11 +6,10 @@ use futures::{ FutureExt, Stream, StreamExt, }; use metrics::atomics::AtomicU64; -use reth_chainspec::ChainSpec; use reth_primitives::{ basefee::calc_next_block_base_fee, eip4844::{calc_blob_gasprice, calculate_excess_blob_gas}, - Receipt, SealedBlock, TransactionSigned, B256, + ChainSpec, Receipt, SealedBlock, TransactionSigned, B256, }; use reth_provider::{BlockReaderIdExt, CanonStateNotification, ChainSpecProvider}; use reth_rpc_server_types::constants::gas_oracle::MAX_HEADER_HISTORY; diff --git a/crates/rpc/rpc/src/eth/api/mod.rs b/crates/rpc/rpc/src/eth/api/mod.rs index 364a55842d3c..9d4e8d817c23 100644 --- a/crates/rpc/rpc/src/eth/api/mod.rs +++ b/crates/rpc/rpc/src/eth/api/mod.rs @@ -13,13 +13,13 @@ use crate::eth::{ traits::RawTransactionForwarder, }; use async_trait::async_trait; -use reth_chainspec::ChainInfo; use reth_errors::{RethError, RethResult}; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; use reth_primitives::{ revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg}, - Address, BlockId, BlockNumberOrTag, SealedBlockWithSenders, SealedHeader, B256, U256, U64, + Address, BlockId, BlockNumberOrTag, ChainInfo, SealedBlockWithSenders, SealedHeader, B256, + U256, U64, }; use reth_provider::{ BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProviderBox, StateProviderFactory, diff --git a/crates/rpc/rpc/src/eth/api/pending_block.rs b/crates/rpc/rpc/src/eth/api/pending_block.rs index c3645b3c85a1..b3375e2b5554 100644 --- a/crates/rpc/rpc/src/eth/api/pending_block.rs +++ b/crates/rpc/rpc/src/eth/api/pending_block.rs @@ -1,7 +1,6 @@ //! Support for building a pending block via local txpool. use crate::eth::error::{EthApiError, EthResult}; -use reth_chainspec::ChainSpec; use reth_errors::ProviderError; use reth_primitives::{ constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE, EMPTY_ROOT_HASH}, @@ -10,8 +9,8 @@ use reth_primitives::{ revm_primitives::{ BlockEnv, CfgEnvWithHandlerCfg, EVMError, Env, InvalidTransaction, ResultAndState, SpecId, }, - Block, BlockId, BlockNumberOrTag, Header, IntoRecoveredTransaction, Receipt, Requests, - SealedBlockWithSenders, SealedHeader, B256, EMPTY_OMMER_ROOT_HASH, U256, + Block, BlockId, BlockNumberOrTag, ChainSpec, Header, IntoRecoveredTransaction, Receipt, + Requests, SealedBlockWithSenders, SealedHeader, B256, EMPTY_OMMER_ROOT_HASH, U256, }; use reth_provider::{ChainSpecProvider, ExecutionOutcome, StateProviderFactory}; use reth_revm::{ diff --git a/crates/rpc/rpc/src/eth/api/server.rs b/crates/rpc/rpc/src/eth/api/server.rs index f238b4da079a..41c68da48300 100644 --- a/crates/rpc/rpc/src/eth/api/server.rs +++ b/crates/rpc/rpc/src/eth/api/server.rs @@ -433,12 +433,11 @@ mod tests { EthApi, }; use jsonrpsee::types::error::INVALID_PARAMS_CODE; - use reth_chainspec::BaseFeeParams; use reth_evm_ethereum::EthEvmConfig; use reth_network_api::noop::NoopNetwork; use reth_primitives::{ - constants::ETHEREUM_BLOCK_GAS_LIMIT, Block, BlockNumberOrTag, Header, TransactionSigned, - B256, U64, + constants::ETHEREUM_BLOCK_GAS_LIMIT, BaseFeeParams, Block, BlockNumberOrTag, Header, + TransactionSigned, B256, U64, }; use reth_provider::{ test_utils::{MockEthProvider, NoopProvider}, diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 1fea2df4a4b4..08b22aa74073 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -11,8 +11,7 @@ use core::fmt; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, server::IdProvider}; -use reth_chainspec::ChainInfo; -use reth_primitives::{IntoRecoveredTransaction, TxHash}; +use reth_primitives::{ChainInfo, IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockIdReader, BlockReader, EvmEnvProvider, ProviderError}; use reth_rpc_api::EthFilterApiServer; use reth_rpc_types::{ diff --git a/crates/rpc/rpc/src/eth/logs_utils.rs b/crates/rpc/rpc/src/eth/logs_utils.rs index c57ce5fcb986..4fdf9b3a704e 100644 --- a/crates/rpc/rpc/src/eth/logs_utils.rs +++ b/crates/rpc/rpc/src/eth/logs_utils.rs @@ -1,7 +1,6 @@ use super::filter::FilterError; use alloy_primitives::TxHash; -use reth_chainspec::ChainInfo; -use reth_primitives::{BlockNumHash, Receipt}; +use reth_primitives::{BlockNumHash, ChainInfo, Receipt}; use reth_provider::{BlockReader, ProviderError}; use reth_rpc_types::{FilteredParams, Log}; diff --git a/crates/stages/api/src/metrics/listener.rs b/crates/stages/api/src/metrics/listener.rs index 408ecab4a95c..46f23d79311c 100644 --- a/crates/stages/api/src/metrics/listener.rs +++ b/crates/stages/api/src/metrics/listener.rs @@ -98,7 +98,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 2b7fcf6cbec4..9d5b8b9ba01b 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -140,14 +140,14 @@ where 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 })); } } } @@ -181,7 +181,7 @@ where max_block = ?self.max_block, "Terminating pipeline." ); - return Ok(()) + return Ok(()); } } } @@ -219,7 +219,7 @@ where ControlFlow::Continue { block_number } => self.progress.update(block_number), ControlFlow::Unwind { target, bad_block } => { self.unwind(target, Some(bad_block.number))?; - return Ok(ControlFlow::Unwind { target, bad_block }) + return Ok(ControlFlow::Unwind { target, bad_block }); } } @@ -312,7 +312,7 @@ where ); self.event_sender.notify(PipelineEvent::Skipped { stage_id }); - continue + continue; } info!( @@ -375,7 +375,7 @@ where 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)))); } } } @@ -415,7 +415,7 @@ where // 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 }; @@ -488,7 +488,7 @@ where ControlFlow::Continue { block_number } } else { ControlFlow::NoProgress { block_number: Some(block_number) } - }) + }); } } Err(err) => { @@ -498,7 +498,7 @@ where if let Some(ctrl) = on_stage_error(&self.provider_factory, stage_id, prev_checkpoint, err)? { - return Ok(ctrl) + return Ok(ctrl); } } } diff --git a/crates/stages/api/src/pipeline/set.rs b/crates/stages/api/src/pipeline/set.rs index 527d9a99a468..c6113753ace4 100644 --- a/crates/stages/api/src/pipeline/set.rs +++ b/crates/stages/api/src/pipeline/set.rs @@ -206,7 +206,7 @@ where F: FnOnce() -> bool, { if f() { - return self.disable(stage_id) + return self.disable(stage_id); } self } @@ -219,7 +219,7 @@ where 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 381acf5f2d99..acdae56e3568 100644 --- a/crates/stages/api/src/stage.rs +++ b/crates/stages/api/src/stage.rs @@ -93,7 +93,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 454ee50bbe20..a1c7c8c9efad 100644 --- a/crates/stages/stages/src/stages/bodies.rs +++ b/crates/stages/stages/src/stages/bodies.rs @@ -83,7 +83,7 @@ impl Stage for BodyStage { 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 @@ -113,7 +113,7 @@ impl Stage for BodyStage { 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(); @@ -192,7 +192,7 @@ impl Stage for BodyStage { segment: StaticFileSegment::Transactions, database: block_number, static_file: appended_block_number, - }) + }); } } @@ -215,7 +215,7 @@ impl Stage for BodyStage { segment: StaticFileSegment::Transactions, database: next_tx_num, static_file: appended_tx_number, - }) + }); } // Increment transaction id for each transaction. @@ -284,7 +284,7 @@ impl Stage for BodyStage { let mut rev_walker = body_cursor.walk_back(None)?; while let Some((number, block_meta)) = rev_walker.next().transpose()? { if number <= input.unwind_to { - break + break; } // Delete the ommers entry if any @@ -331,7 +331,7 @@ impl Stage for BodyStage { static_file_tx_num, static_file_provider, provider, - )?) + )?); } // Unwinds static file @@ -359,11 +359,11 @@ fn missing_static_data_error( 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; } @@ -929,7 +929,7 @@ mod tests { let this = self.get_mut(); if this.headers.is_empty() { - return Poll::Ready(None) + return Poll::Ready(None); } let mut response = Vec::default(); @@ -949,12 +949,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/execution.rs b/crates/stages/stages/src/stages/execution.rs index 9f3b229268ed..83be0f1e0058 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -199,7 +199,7 @@ where 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(); @@ -294,7 +294,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break + break; } } @@ -382,7 +382,7 @@ where if range.is_empty() { return Ok(UnwindOutput { checkpoint: input.checkpoint.with_block_number(input.unwind_to), - }) + }); } // Unwind account and storage changesets, as well as receipts. @@ -679,11 +679,11 @@ where loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= last_receipt_num { - break + break; } } if last_block == 0 { - break + break; } last_block -= 1; } @@ -694,7 +694,7 @@ where return Err(StageError::MissingStaticFileData { block: missing_block, segment: StaticFileSegment::Receipts, - }) + }); } } diff --git a/crates/stages/stages/src/stages/finish.rs b/crates/stages/stages/src/stages/finish.rs index 9eb3a6d762b8..8bcab88276d2 100644 --- a/crates/stages/stages/src/stages/finish.rs +++ b/crates/stages/stages/src/stages/finish.rs @@ -80,7 +80,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 fe8bc8547a58..978c0f716f48 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -134,7 +134,7 @@ impl Stage for AccountHashingStage { 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(); @@ -459,7 +459,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 662f1d1a7728..46b855e754d4 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -76,7 +76,7 @@ impl Stage for StorageHashingStage { ) -> 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(); @@ -272,7 +272,7 @@ mod tests { // Continue from checkpoint input.checkpoint = Some(checkpoint); - continue + continue; } else { assert_eq!(checkpoint.block_number, previous_stage); assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint { @@ -290,7 +290,7 @@ mod tests { "execution validation" ); - break + break; } } panic!("Failed execution"); @@ -423,7 +423,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() @@ -524,7 +524,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 58c578e34d99..a43f3739b90a 100644 --- a/crates/stages/stages/src/stages/headers.rs +++ b/crates/stages/stages/src/stages/headers.rs @@ -122,7 +122,7 @@ where let (sealed_header, _) = SealedHeader::from_compact(&header_buf, header_buf.len()); let (header, header_hash) = sealed_header.split(); if header.number == 0 { - continue + continue; } last_header_number = header.number; @@ -202,7 +202,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 @@ -219,7 +219,7 @@ where "Target block already reached" ); self.is_etl_ready = true; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } debug!(target: "sync::stages::headers", ?tip, head = ?gap.local_head.hash(), "Commencing sync"); @@ -243,13 +243,13 @@ where // filled the gap. if header_number == local_head_number + 1 { self.is_etl_ready = true; - return Poll::Ready(Ok(())) + return Poll::Ready(Ok(())); } } } Some(Err(HeadersDownloaderError::DetachedHead { local_head, header, error })) => { error!(target: "sync::stages::headers", %error, "Cannot attach header to head"); - return Poll::Ready(Err(StageError::DetachedHead { local_head, header, error })) + return Poll::Ready(Err(StageError::DetachedHead { local_head, header, error })); } None => return Poll::Ready(Err(StageError::ChannelClosed)), } @@ -267,12 +267,12 @@ where if self.sync_gap.as_ref().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 @@ -457,7 +457,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 7f83185277c6..bea027ac6c3d 100644 --- a/crates/stages/stages/src/stages/index_account_history.rs +++ b/crates/stages/stages/src/stages/index_account_history.rs @@ -87,7 +87,7 @@ impl Stage for IndexAccountHistoryStage { } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let mut range = input.next_block_range(); @@ -563,7 +563,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 23332f2d6ee8..cd37cfb6f8e8 100644 --- a/crates/stages/stages/src/stages/index_storage_history.rs +++ b/crates/stages/stages/src/stages/index_storage_history.rs @@ -90,7 +90,7 @@ impl Stage for IndexStorageHistoryStage { } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } let mut range = input.next_block_range(); @@ -585,7 +585,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 885fc86c579b..c1abd0d243a8 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -105,7 +105,7 @@ impl MerkleStage { 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()); @@ -151,7 +151,7 @@ impl Stage for MerkleStage { let threshold = match self { Self::Unwind => { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); - return Ok(ExecOutput::done(StageCheckpoint::new(input.target()))) + return Ok(ExecOutput::done(StageCheckpoint::new(input.target()))); } Self::Execution { clean_threshold } => *clean_threshold, #[cfg(any(test, feature = "test-utils"))] @@ -234,7 +234,7 @@ impl Stage for MerkleStage { .checkpoint() .with_entities_stage_checkpoint(entities_checkpoint), done: false, - }) + }); } StateRootProgress::Complete(root, hashed_entries_walked, updates) => { updates.flush(tx)?; @@ -291,7 +291,7 @@ impl Stage for MerkleStage { 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 = @@ -310,7 +310,7 @@ impl Stage for MerkleStage { return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) .with_entities_stage_checkpoint(entities_checkpoint), - }) + }); } // Unwind trie only if there are transitions @@ -620,7 +620,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if bn_address.block_number() < target_block { - break + break; } tree.entry(keccak256(bn_address.address())) @@ -651,7 +651,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/sender_recovery.rs b/crates/stages/stages/src/stages/sender_recovery.rs index 41df7795c3c4..2e4245b2e89f 100644 --- a/crates/stages/stages/src/stages/sender_recovery.rs +++ b/crates/stages/stages/src/stages/sender_recovery.rs @@ -67,7 +67,7 @@ impl Stage for SenderRecoveryStage { 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) = @@ -81,7 +81,7 @@ impl Stage for SenderRecoveryStage { checkpoint: StageCheckpoint::new(end_block) .with_entities_stage_checkpoint(stage_checkpoint(provider)?), done: is_final_range, - }) + }); } let tx = provider.tx_ref(); @@ -210,7 +210,7 @@ fn recover_range( }) } SenderRecoveryStageError::StageError(err) => Err(err), - } + }; } }; senders_cursor.append(tx_id, sender)?; @@ -562,7 +562,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 4cb422e3392d..94d4683bbe9b 100644 --- a/crates/stages/stages/src/stages/tx_lookup.rs +++ b/crates/stages/stages/src/stages/tx_lookup.rs @@ -101,7 +101,7 @@ impl Stage for TransactionLookupStage { } } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())) + return Ok(ExecOutput::done(input.checkpoint())); } // 500MB temporary files @@ -164,7 +164,7 @@ impl Stage for TransactionLookupStage { "Transaction hashes inserted" ); - break + break; } } @@ -191,7 +191,7 @@ impl Stage for TransactionLookupStage { let mut rev_walker = body_cursor.walk_back(Some(*range.end()))?; while let Some((number, body)) = rev_walker.next().transpose()? { if number <= unwind_to { - break + break; } // Delete all transactions that belong to this block @@ -514,7 +514,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/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index 8f72b5aab225..f149720a83ef 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -490,7 +490,7 @@ impl StorageKind { fn tx_offset(&self) -> u64 { if let Self::Database(offset) = self { - return offset.unwrap_or_default() + return offset.unwrap_or_default(); } 0 } diff --git a/crates/stages/types/src/checkpoints.rs b/crates/stages/types/src/checkpoints.rs index d7188de1be9f..ee830015486e 100644 --- a/crates/stages/types/src/checkpoints.rs +++ b/crates/stages/types/src/checkpoints.rs @@ -145,7 +145,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. 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 396fdd5ed08d..4b00a9eab325 100644 --- a/crates/static-file/static-file/src/static_file_producer.rs +++ b/crates/static-file/static-file/src/static_file_producer.rs @@ -111,7 +111,7 @@ impl StaticFileProducerInner { 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( diff --git a/crates/static-file/types/src/segment.rs b/crates/static-file/types/src/segment.rs index d609f4a98b27..e3be17c748b0 100644 --- a/crates/static-file/types/src/segment.rs +++ b/crates/static-file/types/src/segment.rs @@ -116,14 +116,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))) diff --git a/crates/storage/codecs/derive/src/compact/flags.rs b/crates/storage/codecs/derive/src/compact/flags.rs index 24757d8e6b91..46a165023605 100644 --- a/crates/storage/codecs/derive/src/compact/flags.rs +++ b/crates/storage/codecs/derive/src/compact/flags.rs @@ -25,7 +25,7 @@ pub(crate) fn generate_flag_struct( .iter() .filter_map(|f| { if let FieldTypes::StructField(f) = f { - return Some(f) + return Some(f); } None }) @@ -36,7 +36,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 c28bf8d1a4fb..889c68b0026b 100644 --- a/crates/storage/codecs/derive/src/compact/generator.rs +++ b/crates/storage/codecs/derive/src/compact/generator.rs @@ -89,7 +89,7 @@ fn generate_from_compact(fields: &FieldList, ident: &Ident, is_zstd: bool) -> To let ident = format_ident!("{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 c2f0b1e56793..40b7b2f31eff 100644 --- a/crates/storage/codecs/derive/src/compact/mod.rs +++ b/crates/storage/codecs/derive/src/compact/mod.rs @@ -156,7 +156,7 @@ fn should_use_alt_impl(ftype: &String, 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 b8882448bb8e..a9c978b21b23 100644 --- a/crates/storage/codecs/derive/src/compact/structs.rs +++ b/crates/storage/codecs/derive/src/compact/structs.rs @@ -66,7 +66,7 @@ impl<'a> StructHandler<'a> { }) } - return + return; } let name = format_ident!("{name}"); diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index b0927a1481cb..80fd549c0285 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -222,7 +222,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); @@ -251,7 +251,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); @@ -274,7 +274,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]; @@ -314,7 +314,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(); @@ -399,7 +399,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/db-api/src/cursor.rs b/crates/storage/db-api/src/cursor.rs index bada512831eb..dd1f0de1f02b 100644 --- a/crates/storage/db-api/src/cursor.rs +++ b/crates/storage/db-api/src/cursor.rs @@ -158,7 +158,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for Walker<'cursor, T, C fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start + return start; } self.cursor.next().transpose() @@ -235,7 +235,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for ReverseWalker<'curso fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start + return start; } self.cursor.prev().transpose() @@ -275,7 +275,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for RangeWalker<'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()); @@ -366,7 +366,7 @@ impl<'cursor, T: DupSort, CURSOR: DbDupCursorRO> Iterator for DupWalker<'curs 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-common/src/init.rs b/crates/storage/db-common/src/init.rs index d8bf583dfbb3..012a9540ab26 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -92,13 +92,13 @@ pub fn init_genesis(factory: ProviderFactory) -> Result { if block_hash == hash { debug!("Genesis already written, skipping."); - return Ok(hash) + return Ok(hash); } return Err(InitDatabaseError::GenesisHashMismatch { chainspec_hash: hash, database_hash: block_hash, - }) + }); } Err(e) => return Err(dbg!(e).into()), } @@ -376,7 +376,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)?; @@ -499,7 +499,7 @@ fn compute_state_root(provider: &DatabaseProviderRW) -> eyre:: "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 4191d7aae364..6545a77dafd1 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -394,7 +394,7 @@ impl DatabaseEnv { LogLevel::Extra => 7, }); } else { - return Err(DatabaseError::LogLevelUnavailable(log_level)) + return Err(DatabaseError::LogLevelUnavailable(log_level)); } } @@ -439,7 +439,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/lockfile.rs b/crates/storage/db/src/lockfile.rs index e0da20348a53..07507a1a5504 100644 --- a/crates/storage/db/src/lockfile.rs +++ b/crates/storage/db/src/lockfile.rs @@ -49,7 +49,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 9a93ca224429..c37cb59e92ff 100644 --- a/crates/storage/db/src/static_file/cursor.rs +++ b/crates/storage/db/src/static_file/cursor.rs @@ -32,7 +32,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 { @@ -40,7 +40,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/tables/codecs/fuzz/inputs.rs b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs index 533b6b6926dd..1498dcc907bb 100644 --- a/crates/storage/db/src/tables/codecs/fuzz/inputs.rs +++ b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs @@ -13,7 +13,7 @@ impl From for IntegerList { // Empty lists are not supported by `IntegerList`, so we want to skip these cases. if v.is_empty() { - return vec![1u64].into() + return vec![1u64].into(); } v.sort(); v.into() diff --git a/crates/storage/db/src/version.rs b/crates/storage/db/src/version.rs index 09c1f946780a..424d543606d4 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/src/codec.rs b/crates/storage/libmdbx-rs/src/codec.rs index 15f20204e20a..26af0999045e 100644 --- a/crates/storage/libmdbx-rs/src/codec.rs +++ b/crates/storage/libmdbx-rs/src/codec.rs @@ -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 36da31caa633..ca51ac816b28 100644 --- a/crates/storage/libmdbx-rs/src/cursor.rs +++ b/crates/storage/libmdbx-rs/src/cursor.rs @@ -372,7 +372,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) } @@ -407,7 +407,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) } @@ -423,7 +423,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 1549d42e1866..b4360a2b87f1 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -116,10 +116,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)) } @@ -214,7 +214,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::()]; @@ -696,7 +696,7 @@ impl EnvironmentBuilder { })() { ffi::mdbx_env_close_ex(env, false); - return Err(e) + return Err(e); } } diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index 37af501c1838..f6ab5ffb2a0d 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -504,7 +504,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); @@ -585,7 +585,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 670bed82b669..d5169ea54196 100644 --- a/crates/storage/nippy-jar/src/compression/lz4.rs +++ b/crates/storage/nippy-jar/src/compression/lz4.rs @@ -43,7 +43,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 c55ca103aff5..8194538e42f8 100644 --- a/crates/storage/nippy-jar/src/compression/zstd.rs +++ b/crates/storage/nippy-jar/src/compression/zstd.rs @@ -60,7 +60,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![]) @@ -72,12 +72,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) } @@ -102,7 +102,7 @@ impl Zstd { buffer.reserve(column_value.len() * multiplier); multiplier += 1; if multiplier == 5 { - return Err(NippyJarError::Disconnect(err)) + return Err(NippyJarError::Disconnect(err)); } } @@ -191,7 +191,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 @@ -205,7 +205,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())); } // TODO: parallel calculation @@ -363,7 +363,7 @@ impl<'a> Serialize for ZstdDictionary<'a> { impl<'a> PartialEq for ZstdDictionary<'a> { 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/cursor.rs b/crates/storage/nippy-jar/src/cursor.rs index 434c40a9a69b..be7fc829e379 100644 --- a/crates/storage/nippy-jar/src/cursor.rs +++ b/crates/storage/nippy-jar/src/cursor.rs @@ -86,11 +86,11 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { .offsets_index .access(row_index as usize) .expect("built from same set") as u64; - return self.next_row() + return self.next_row(); } } } else { - return Err(NippyJarError::UnsupportedFilterQuery) + return Err(NippyJarError::UnsupportedFilterQuery); } Ok(None) @@ -108,7 +108,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); @@ -154,11 +154,11 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { .offsets_index .access(row_index as usize) .expect("built from same set") as u64; - return self.next_row_with_cols(mask) + return self.next_row_with_cols(mask); } } } else { - return Err(NippyJarError::UnsupportedFilterQuery) + return Err(NippyJarError::UnsupportedFilterQuery); } Ok(None) @@ -182,7 +182,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/filter/cuckoo.rs b/crates/storage/nippy-jar/src/filter/cuckoo.rs index b4e05fbb7493..f8e5d5d26526 100644 --- a/crates/storage/nippy-jar/src/filter/cuckoo.rs +++ b/crates/storage/nippy-jar/src/filter/cuckoo.rs @@ -28,7 +28,7 @@ impl Cuckoo { impl InclusionFilter for Cuckoo { fn add(&mut self, element: &[u8]) -> Result<(), NippyJarError> { if self.remaining == 0 { - return Err(NippyJarError::FilterMaxCapacity) + return Err(NippyJarError::FilterMaxCapacity); } self.remaining -= 1; diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index 8247599d7aeb..8e132425abe1 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -413,12 +413,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); } } @@ -513,9 +513,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 }) @@ -555,7 +555,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/phf/fmph.rs b/crates/storage/nippy-jar/src/phf/fmph.rs index a332c40cf720..20e1d9ac0c96 100644 --- a/crates/storage/nippy-jar/src/phf/fmph.rs +++ b/crates/storage/nippy-jar/src/phf/fmph.rs @@ -28,7 +28,7 @@ impl PerfectHashingFunction for Fmph { fn get_index(&self, key: &[u8]) -> Result, NippyJarError> { if let Some(f) = &self.function { - return Ok(f.get(key)) + return Ok(f.get(key)); } Err(NippyJarError::PHFMissingKeys) } @@ -92,7 +92,7 @@ impl<'de> Deserialize<'de> for Fmph { function: Some( Function::read(&mut std::io::Cursor::new(buffer)).map_err(D::Error::custom)?, ), - }) + }); } Ok(Self { function: None }) } diff --git a/crates/storage/nippy-jar/src/phf/go_fmph.rs b/crates/storage/nippy-jar/src/phf/go_fmph.rs index 328ddcb4ddcb..8898c8be1adf 100644 --- a/crates/storage/nippy-jar/src/phf/go_fmph.rs +++ b/crates/storage/nippy-jar/src/phf/go_fmph.rs @@ -28,7 +28,7 @@ impl PerfectHashingFunction for GoFmph { fn get_index(&self, key: &[u8]) -> Result, NippyJarError> { if let Some(f) = &self.function { - return Ok(f.get(key)) + return Ok(f.get(key)); } Err(NippyJarError::PHFMissingKeys) } @@ -93,7 +93,7 @@ impl<'de> Deserialize<'de> for GoFmph { GOFunction::read(&mut std::io::Cursor::new(buffer)) .map_err(D::Error::custom)?, ), - }) + }); } Ok(Self { function: None }) } diff --git a/crates/storage/nippy-jar/src/writer.rs b/crates/storage/nippy-jar/src/writer.rs index 695fd6642e54..44b3bd5ed152 100644 --- a/crates/storage/nippy-jar/src/writer.rs +++ b/crates/storage/nippy-jar/src/writer.rs @@ -163,7 +163,7 @@ impl NippyJarWriter { // 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 @@ -174,7 +174,7 @@ impl NippyJarWriter { if check_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 @@ -205,7 +205,7 @@ impl NippyJarWriter { let data_file_len = self.data_file.get_ref().metadata()?.len(); if check_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 @@ -235,7 +235,7 @@ impl NippyJarWriter { // Since we decrease the offset list, we need to check the consistency of // `self.jar.rows` again self.ensure_file_consistency(ConsistencyFailStrategy::Heal)?; - break + break; } } } @@ -372,7 +372,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); @@ -398,7 +398,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)); } } @@ -490,7 +490,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/bundle_state_provider.rs b/crates/storage/provider/src/providers/bundle_state_provider.rs index 49fb196ffb18..61aa16b6a244 100644 --- a/crates/storage/provider/src/providers/bundle_state_provider.rs +++ b/crates/storage/provider/src/providers/bundle_state_provider.rs @@ -35,7 +35,7 @@ impl BlockHashReader fn block_hash(&self, block_number: BlockNumber) -> ProviderResult> { let block_hash = self.block_execution_data_provider.block_hash(block_number); if block_hash.is_some() { - return Ok(block_hash) + return Ok(block_hash); } self.state_provider.block_hash(block_number) } @@ -92,7 +92,7 @@ impl StateProvider for BundleStat .execution_outcome() .storage(&account, u256_storage_key) { - return Ok(Some(value)) + return Ok(Some(value)); } self.state_provider.storage(account, storage_key) @@ -102,7 +102,7 @@ impl StateProvider for BundleStat if let Some(bytecode) = self.block_execution_data_provider.execution_outcome().bytecode(&code_hash) { - return Ok(Some(bytecode)) + return Ok(Some(bytecode)); } self.state_provider.bytecode_by_hash(code_hash) diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index fe9b65941107..325174e8369a 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -62,7 +62,7 @@ where return Err(ConsistentViewError::Inconsistent { tip: GotExpected { got: tip, expected: self.tip }, } - .into()) + .into()); } // Check that the best block number is the same as the latest stored header. @@ -73,7 +73,7 @@ where return Err(ConsistentViewError::Syncing { best_block: GotExpected { got: best_block_number, expected: last_num }, } - .into()) + .into()); } Ok(provider_ro) diff --git a/crates/storage/provider/src/providers/database/mod.rs b/crates/storage/provider/src/providers/database/mod.rs index 57e7e9615217..c954b63aad16 100644 --- a/crates/storage/provider/src/providers/database/mod.rs +++ b/crates/storage/provider/src/providers/database/mod.rs @@ -195,7 +195,7 @@ impl HeaderProvider for ProviderFactory { if let Some(td) = self.chain_spec.final_paris_total_difficulty(number) { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)) + return Ok(Some(td)); } self.static_file_provider.get_with_static_file_or_database( diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index f0932f45dbf4..70da8285fe26 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -134,7 +134,7 @@ impl DatabaseProvider { if block_number == self.best_block_number().unwrap_or_default() && block_number == self.last_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProvider::new(self.tx, self.static_file_provider))) + return Ok(Box::new(LatestStateProvider::new(self.tx, self.static_file_provider))); } // +1 as the changeset that we want is the one that was applied after this block. @@ -230,7 +230,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; } cursor.delete_current()?; @@ -239,12 +239,12 @@ where let first = list.iter().next().expect("List can't be empty"); if first >= block_number { item = cursor.prev()?; - continue + continue; } else if block_number <= sharded_key.as_ref().highest_block_number { // Filter out all elements greater than block number. - return Ok(list.iter().take_while(|i| *i < block_number).collect::>()) + return Ok(list.iter().take_while(|i| *i < block_number).collect::>()); } else { - return Ok(list.iter().collect::>()) + return Ok(list.iter().collect::>()); } } @@ -386,7 +386,7 @@ impl DatabaseProvider { ) -> ProviderResult, { if range.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } let len = range.end().saturating_sub(*range.start()) as usize; @@ -553,7 +553,7 @@ impl DatabaseProvider { range: RangeInclusive, ) -> ProviderResult { if range.is_empty() { - return Ok(ExecutionOutcome::default()) + return Ok(ExecutionOutcome::default()); } let start_block_number = *range.start(); @@ -732,7 +732,7 @@ impl DatabaseProvider { let block_bodies = self.get_or_take::(range)?; if block_bodies.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } // Compute the first and last tx ID in the range @@ -741,7 +741,7 @@ impl DatabaseProvider { // If this is the case then all of the blocks in the range are empty if last_transaction < first_transaction { - return Ok(block_bodies.into_iter().map(|(n, _)| (n, Vec::new())).collect()) + return Ok(block_bodies.into_iter().map(|(n, _)| (n, Vec::new())).collect()); } // Get transactions and senders @@ -883,7 +883,7 @@ impl DatabaseProvider { let block_headers = self.get_or_take::(range.clone())?; if block_headers.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } let block_header_hashes = @@ -1006,7 +1006,7 @@ impl DatabaseProvider { while let Some(Ok((entry_key, _))) = reverse_walker.next() { if selector(entry_key.clone()) <= key { - break + break; } reverse_walker.delete_current()?; deleted += 1; @@ -1053,7 +1053,7 @@ impl DatabaseProvider { table = %T::NAME, "Pruning limit reached" ); - break + break; } let row = cursor.seek_exact(key)?; @@ -1096,7 +1096,7 @@ impl DatabaseProvider { table = %T::NAME, "Pruning limit reached" ); - break false + break false; } let done = self.prune_table_with_range_step( @@ -1107,7 +1107,7 @@ impl DatabaseProvider { )?; if done { - break true + break true; } else { deleted_entries += 1; } @@ -1155,7 +1155,7 @@ impl DatabaseProvider { // delete old shard so new one can be inserted. self.tx.delete::(shard_key, None)?; let list = list.iter().collect::>(); - return Ok(list) + return Ok(list); } Ok(Vec::new()) } @@ -1300,7 +1300,7 @@ impl HeaderSyncGapProvider for DatabaseProvider { } 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 => {} } @@ -1345,7 +1345,7 @@ impl HeaderProvider for DatabaseProvider { if let Some(td) = self.chain_spec.final_paris_total_difficulty(number) { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)) + return Ok(Some(td)); } self.static_file_provider.get_with_static_file_or_database( @@ -1402,7 +1402,7 @@ impl HeaderProvider for DatabaseProvider { .ok_or_else(|| ProviderError::HeaderNotFound(number.into()))?; let sealed = header.seal(hash); if !predicate(&sealed) { - break + break; } headers.push(sealed); } @@ -1500,7 +1500,13 @@ impl BlockReader for DatabaseProvider { None => return Ok(None), }; - return Ok(Some(Block { header, body: transactions, ommers, withdrawals, requests })) + return Ok(Some(Block { + header, + body: transactions, + ommers, + withdrawals, + requests, + })); } } @@ -1524,11 +1530,11 @@ impl BlockReader for DatabaseProvider { // If the Paris (Merge) hardfork block is known and block is after it, return empty // ommers. if self.chain_spec.final_paris_total_difficulty(number).is_some() { - return Ok(Some(Vec::new())) + return Ok(Some(Vec::new())); } let ommers = self.tx.get::(number)?.map(|o| o.ommers); - return Ok(ommers) + return Ok(ommers); } Ok(None) @@ -1788,7 +1794,7 @@ impl TransactionsProvider for DatabaseProvider { timestamp: header.timestamp, }; - return Ok(Some((transaction, meta))) + return Ok(Some((transaction, meta))); } } } @@ -1821,7 +1827,7 @@ impl TransactionsProvider for DatabaseProvider { .map(Into::into) .collect(), )) - } + }; } } Ok(None) @@ -1899,7 +1905,7 @@ impl ReceiptProvider for DatabaseProvider { Ok(Some(Vec::new())) } else { self.receipts_by_tx_range(tx_range).map(Some) - } + }; } } Ok(None) @@ -1934,7 +1940,7 @@ impl WithdrawalsProvider for DatabaseProvider { .get::(number) .map(|w| w.map(|w| w.withdrawals))? .unwrap_or_default(); - return Ok(Some(withdrawals)) + return Ok(Some(withdrawals)); } } Ok(None) @@ -1958,7 +1964,7 @@ impl RequestsProvider for DatabaseProvider { // If we are past Prague, then all blocks should have a requests list, even if // empty let requests = self.tx.get::(number)?.unwrap_or_default(); - return Ok(Some(requests)) + return Ok(Some(requests)); } } Ok(None) @@ -2378,7 +2384,7 @@ impl HashingWriter for DatabaseProvider { root: GotExpected { got: state_root, expected: expected_state_root }, block_number: *range.end(), block_hash: end_block_hash, - }))) + }))); } trie_updates.flush(&self.tx)?; } @@ -2574,7 +2580,7 @@ impl BlockExecutionWriter for DatabaseProvider { root: GotExpected { got: new_state_root, expected: parent_state_root }, block_number: parent_number, block_hash: parent_hash, - }))) + }))); } trie_updates.flush(&self.tx)?; } @@ -2753,7 +2759,7 @@ impl BlockWriter for DatabaseProvider { ) -> 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/mod.rs b/crates/storage/provider/src/providers/mod.rs index 9da41269c137..2f14bf4d5d48 100644 --- a/crates/storage/provider/src/providers/mod.rs +++ b/crates/storage/provider/src/providers/mod.rs @@ -648,7 +648,7 @@ where if let Some(block) = self.tree.pending_block_num_hash() { if let Ok(pending) = self.tree.pending_state_provider(block.hash) { - return self.pending_with_provider(pending) + return self.pending_with_provider(pending); } } @@ -658,7 +658,7 @@ where fn pending_state_by_hash(&self, block_hash: B256) -> ProviderResult> { if let Some(state) = self.tree.find_pending_state_provider(block_hash) { - return Ok(Some(self.pending_with_provider(state)?)) + return Ok(Some(self.pending_with_provider(state)?)); } Ok(None) } diff --git a/crates/storage/provider/src/providers/state/historical.rs b/crates/storage/provider/src/providers/state/historical.rs index 12545fe7838e..2f20ca7954bd 100644 --- a/crates/storage/provider/src/providers/state/historical.rs +++ b/crates/storage/provider/src/providers/state/historical.rs @@ -73,7 +73,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { /// 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. @@ -92,7 +92,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { 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. @@ -109,7 +109,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { 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)); } let tip = self diff --git a/crates/storage/provider/src/providers/state/latest.rs b/crates/storage/provider/src/providers/state/latest.rs index 56b4ecc38b11..64a5c9b24b4c 100644 --- a/crates/storage/provider/src/providers/state/latest.rs +++ b/crates/storage/provider/src/providers/state/latest.rs @@ -100,7 +100,7 @@ impl<'b, TX: DbTx> StateProvider for LatestStateProviderRef<'b, TX> { 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 5e20572e3d61..10d725d2a43f 100644 --- a/crates/storage/provider/src/providers/static_file/jar.rs +++ b/crates/storage/provider/src/providers/static_file/jar.rs @@ -137,7 +137,7 @@ impl<'a> HeaderProvider for StaticFileJarProvider<'a> { { let sealed = header.seal(hash); if !predicate(&sealed) { - break + break; } headers.push(sealed); } @@ -297,7 +297,7 @@ impl<'a> ReceiptProvider for StaticFileJarProvider<'a> { fn receipt_by_hash(&self, hash: TxHash) -> 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 39e588c7f5f4..acdc336c8206 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -261,7 +261,7 @@ impl StaticFileProvider { ) .and_then(|(parsed_segment, block_range)| { if parsed_segment == segment { - return Some(block_range) + return Some(block_range); } None }), @@ -270,7 +270,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) @@ -379,11 +379,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(find_fixed_range(block_range.end())) + return Some(find_fixed_range(block_range.end())); } } None @@ -544,7 +544,7 @@ impl StaticFileProvider { for segment in StaticFileSegment::iter() { 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); @@ -586,16 +586,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; @@ -674,12 +674,12 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_static_file_block)) + return Ok(Some(highest_static_file_block)); } if let Some((db_last_entry, _)) = db_cursor.last()? { if db_last_entry > highest_static_file_entry { - return Ok(None) + return Ok(None); } } } @@ -704,7 +704,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 @@ -768,7 +768,7 @@ impl StaticFileProvider { let mut range = 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(BLOCKS_PER_STATIC_FILE), @@ -821,10 +821,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 { @@ -840,7 +840,7 @@ impl StaticFileProvider { } else { ProviderError::MissingStaticFileTx(segment, number) }; - return Err(err) + return Err(err); } provider = get_provider(number)?; cursor = provider.cursor()?; @@ -923,7 +923,7 @@ impl StaticFileProvider { if static_file_upper_bound .map_or(false, |static_file_upper_bound| static_file_upper_bound >= number) { - return fetch_from_static_file(self) + return fetch_from_static_file(self); } fetch_from_database() } @@ -1016,7 +1016,7 @@ impl StaticFileWriter for StaticFileProvider { segment: StaticFileSegment, ) -> ProviderResult> { if self.access.is_read_only() { - return Err(ProviderError::ReadOnlyStaticFileAccess) + return Err(ProviderError::ReadOnlyStaticFileAccess); } tracing::trace!(target: "providers::static_file", ?block, ?segment, "Getting static file writer."); @@ -1079,7 +1079,7 @@ impl HeaderProvider for StaticFileProvider { .get_two::>(block_hash.into())? .and_then(|(header, hash)| { if &hash == block_hash { - return Some(header) + return Some(header); } None })) @@ -1192,7 +1192,7 @@ impl ReceiptProvider for StaticFileProvider { 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) } diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index 304429a0150b..397606083528 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -139,7 +139,7 @@ impl StaticFileProviderRW { self.writer.ensure_file_consistency(check_mode).map_err(|error| { if matches!(error, NippyJarError::InconsistentState) { - return inconsistent_error() + return inconsistent_error(); } ProviderError::NippyJar(error.to_string()) })?; @@ -153,7 +153,7 @@ impl StaticFileProviderRW { let pruned_rows = expected_rows - self.writer.rows() as u64; if pruned_rows > 0 { if read_only { - return Err(inconsistent_error()) + return Err(inconsistent_error()); } self.user_header_mut().prune(pruned_rows); } @@ -327,7 +327,7 @@ impl StaticFileProviderRW { segment, expected_block_number, next_static_file_block, - )) + )); } Ok(()) } @@ -369,7 +369,7 @@ impl StaticFileProviderRW { self.writer .prune_rows(len as usize) .map_err(|e| ProviderError::NippyJar(e.to_string()))?; - break + break; } remaining_rows -= len; @@ -634,7 +634,7 @@ impl StaticFileProviderRW { if self.prune_on_commit.is_some() { return Err(ProviderError::NippyJar( "Pruning should be committed before appending or pruning more data".to_string(), - )) + )); } Ok(()) } diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 974982121a7e..da92875248db 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -249,7 +249,7 @@ impl TransactionsProvider for MockEthProvider { excess_blob_gas: block.header.excess_blob_gas, timestamp: block.header.timestamp, }; - return Ok(Some((tx.clone(), meta))) + return Ok(Some((tx.clone(), meta))); } } } @@ -261,7 +261,7 @@ impl TransactionsProvider for MockEthProvider { let mut current_tx_number: TxNumber = 0; for block in lock.values() { if current_tx_number + (block.body.len() as TxNumber) > id { - return Ok(Some(block.header.number)) + return Ok(Some(block.header.number)); } current_tx_number += block.body.len() as TxNumber; } diff --git a/crates/storage/provider/src/traits/chain.rs b/crates/storage/provider/src/traits/chain.rs index 98957fcfdcc8..9f8224f709ee 100644 --- a/crates/storage/provider/src/traits/chain.rs +++ b/crates/storage/provider/src/traits/chain.rs @@ -51,10 +51,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/storage/storage-api/src/receipts.rs b/crates/storage/storage-api/src/receipts.rs index b050ca3e248c..246c6a6cf008 100644 --- a/crates/storage/storage-api/src/receipts.rs +++ b/crates/storage/storage-api/src/receipts.rs @@ -47,7 +47,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 059909a463b0..03dfd7a9b857 100644 --- a/crates/storage/storage-api/src/state.rs +++ b/crates/storage/storage-api/src/state.rs @@ -40,10 +40,10 @@ pub trait StateProvider: BlockHashReader + AccountReader + StateRootProvider + S 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/tasks/src/lib.rs b/crates/tasks/src/lib.rs index ee5222e91312..de0043fb8366 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -222,7 +222,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/event_stream.rs b/crates/tokio-util/src/event_stream.rs index 0e041f8d4c31..88aebcceb08b 100644 --- a/crates/tokio-util/src/event_stream.rs +++ b/crates/tokio-util/src/event_stream.rs @@ -36,7 +36,7 @@ where Poll::Ready(Some(Ok(item))) => return Poll::Ready(Some(item)), Poll::Ready(Some(Err(e))) => { warn!("BroadcastStream lagged: {e:?}"); - continue + continue; } Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => return Poll::Pending, diff --git a/crates/transaction-pool/Cargo.toml b/crates/transaction-pool/Cargo.toml index 03b5d1d5f21a..e742c569b76a 100644 --- a/crates/transaction-pool/Cargo.toml +++ b/crates/transaction-pool/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] # reth -reth-chainspec.workspace = true reth-eth-wire-types.workspace = true reth-primitives.workspace = true reth-fs-util.workspace = true diff --git a/crates/transaction-pool/src/lib.rs b/crates/transaction-pool/src/lib.rs index 527c3412e1aa..e02e49ca9885 100644 --- a/crates/transaction-pool/src/lib.rs +++ b/crates/transaction-pool/src/lib.rs @@ -79,7 +79,7 @@ //! Listen for new transactions and print them: //! //! ``` -//! use reth_chainspec::MAINNET; +//! use reth_primitives::MAINNET; //! use reth_provider::{BlockReaderIdExt, ChainSpecProvider, StateProviderFactory}; //! use reth_tasks::TokioTaskExecutor; //! use reth_transaction_pool::{TransactionValidationTaskExecutor, Pool, TransactionPool}; @@ -107,7 +107,7 @@ //! //! ``` //! use futures_util::Stream; -//! use reth_chainspec::MAINNET; +//! use reth_primitives::MAINNET; //! use reth_provider::{BlockReaderIdExt, CanonStateNotification, ChainSpecProvider, StateProviderFactory}; //! use reth_tasks::TokioTaskExecutor; //! use reth_tasks::TaskSpawner; @@ -285,7 +285,7 @@ where /// # Example /// /// ``` - /// use reth_chainspec::MAINNET; + /// use reth_primitives::MAINNET; /// use reth_provider::{BlockReaderIdExt, StateProviderFactory}; /// use reth_tasks::TokioTaskExecutor; /// use reth_transaction_pool::{ diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index 99b29ed01289..02c259f9a0a9 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -681,9 +681,8 @@ mod tests { blobstore::InMemoryBlobStore, validate::EthTransactionValidatorBuilder, CoinbaseTipOrdering, EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, }; - use reth_chainspec::MAINNET; use reth_fs_util as fs; - use reth_primitives::{hex, PooledTransactionsElement, U256}; + use reth_primitives::{hex, PooledTransactionsElement, MAINNET, U256}; use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; use reth_tasks::TaskManager; diff --git a/crates/transaction-pool/src/test_utils/gen.rs b/crates/transaction-pool/src/test_utils/gen.rs index 2be4d8aa9a9a..87c2ba580d38 100644 --- a/crates/transaction-pool/src/test_utils/gen.rs +++ b/crates/transaction-pool/src/test_utils/gen.rs @@ -1,10 +1,9 @@ use crate::EthPooledTransaction; use rand::Rng; -use reth_chainspec::MAINNET; use reth_primitives::{ constants::MIN_PROTOCOL_BASE_FEE, sign_message, AccessList, Address, Bytes, Transaction, TransactionSigned, TryFromRecoveredTransaction, TxEip1559, TxEip4844, TxKind, TxLegacy, B256, - U256, + MAINNET, U256, }; /// A generator for transactions for testing purposes. diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index 3b3779cfdcb5..3e7e7d519a2f 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -9,7 +9,6 @@ use crate::{ EthBlobTransactionSidecar, EthPoolTransaction, LocalTransactionConfig, PoolTransaction, TransactionValidationOutcome, TransactionValidationTaskExecutor, TransactionValidator, }; -use reth_chainspec::ChainSpec; use reth_primitives::{ constants::{ eip4844::{MAINNET_KZG_TRUSTED_SETUP, MAX_BLOBS_PER_BLOCK}, @@ -17,8 +16,8 @@ use reth_primitives::{ }, kzg::KzgSettings, revm::compat::calculate_intrinsic_gas_after_merge, - GotExpected, InvalidTransactionError, SealedBlock, EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, - EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID, + ChainSpec, GotExpected, InvalidTransactionError, SealedBlock, EIP1559_TX_TYPE_ID, + EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID, }; use reth_provider::{AccountReader, BlockReaderIdExt, StateProviderFactory}; use reth_tasks::TaskSpawner; @@ -735,8 +734,9 @@ mod tests { blobstore::InMemoryBlobStore, error::PoolErrorKind, CoinbaseTipOrdering, EthPooledTransaction, Pool, TransactionPool, }; - use reth_chainspec::MAINNET; - use reth_primitives::{hex, FromRecoveredPooledTransaction, PooledTransactionsElement, U256}; + use reth_primitives::{ + hex, FromRecoveredPooledTransaction, PooledTransactionsElement, MAINNET, U256, + }; use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; fn get_transaction() -> EthPooledTransaction { diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index 72ab1d81a13a..f8f98e3f4755 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -7,8 +7,7 @@ use crate::{ TransactionValidator, }; use futures_util::{lock::Mutex, StreamExt}; -use reth_chainspec::ChainSpec; -use reth_primitives::SealedBlock; +use reth_primitives::{ChainSpec, SealedBlock}; use reth_provider::BlockReaderIdExt; use reth_tasks::TaskSpawner; use std::{future::Future, pin::Pin, sync::Arc}; diff --git a/crates/trie/trie/benches/prefix_set.rs b/crates/trie/trie/benches/prefix_set.rs index db02b5dd17cc..a4604cdc2900 100644 --- a/crates/trie/trie/benches/prefix_set.rs +++ b/crates/trie/trie/benches/prefix_set.rs @@ -150,12 +150,12 @@ mod implementations { for key in self.keys.range::(range) { if key.has_prefix(&prefix) { self.last_checked = Some(prefix); - return true + return true; } if key > &prefix { self.last_checked = Some(prefix); - return false + return false; } } @@ -219,12 +219,12 @@ mod implementations { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(&prefix) { self.index += idx; - return true + return true; } if key > &prefix { self.index += idx; - return false + return false; } } diff --git a/crates/trie/trie/src/hashed_cursor/post_state.rs b/crates/trie/trie/src/hashed_cursor/post_state.rs index df04d332d2c6..61b1e093b3d6 100644 --- a/crates/trie/trie/src/hashed_cursor/post_state.rs +++ b/crates/trie/trie/src/hashed_cursor/post_state.rs @@ -118,7 +118,7 @@ where if let Some((address, account)) = post_state_entry { if address == &key { self.last_account = Some(*address); - return Ok(Some((*address, *account))) + return Ok(Some((*address, *account))); } } @@ -273,7 +273,7 @@ where if let Some((slot, value)) = post_state_entry { if slot == &subkey { self.last_slot = Some(*slot); - return Ok(Some((*slot, *value))) + return Ok(Some((*slot, *value))); } } diff --git a/crates/trie/trie/src/node_iter.rs b/crates/trie/trie/src/node_iter.rs index 29c6fd4f2344..f4aa7609d26c 100644 --- a/crates/trie/trie/src/node_iter.rs +++ b/crates/trie/trie/src/node_iter.rs @@ -97,7 +97,7 @@ where key.clone(), self.walker.hash().unwrap(), self.walker.children_are_in_trie(), - )))) + )))); } } } @@ -108,12 +108,12 @@ where // reset the checked status and continue if self.walker.key().map_or(false, |key| key < &Nibbles::unpack(hashed_key)) { self.current_walker_key_checked = false; - continue + continue; } // Set the next hashed entry as a leaf node and return self.current_hashed_entry = self.hashed_cursor.next()?; - 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 diff --git a/crates/trie/trie/src/prefix_set/mod.rs b/crates/trie/trie/src/prefix_set/mod.rs index f6a8789e0105..79aaae0c90a7 100644 --- a/crates/trie/trie/src/prefix_set/mod.rs +++ b/crates/trie/trie/src/prefix_set/mod.rs @@ -84,12 +84,12 @@ impl PrefixSetMut { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(prefix) { self.index += idx; - return true + return true; } if *key > *prefix { self.index += idx; - return false + return false; } } @@ -149,12 +149,12 @@ impl PrefixSet { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(prefix) { self.index += idx; - return true + return true; } if key > prefix { self.index += idx; - return false + return false; } } diff --git a/crates/trie/trie/src/proof.rs b/crates/trie/trie/src/proof.rs index 04e7952f5db7..4b34c86a0ca2 100644 --- a/crates/trie/trie/src/proof.rs +++ b/crates/trie/trie/src/proof.rs @@ -113,7 +113,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok((EMPTY_ROOT_HASH, proofs)) + return Ok((EMPTY_ROOT_HASH, proofs)); } let target_nibbles = proofs.iter().map(|p| p.nibbles.clone()).collect::>(); diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index 3fe97a6f788c..1edb33e25606 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -305,7 +305,7 @@ where Box::new(state), hashed_entries_walked, trie_updates, - )) + )); } } } @@ -487,7 +487,7 @@ where EMPTY_ROOT_HASH, 0, TrieUpdates::from([(TrieKey::StorageTrie(self.hashed_address), TrieOp::Delete)]), - )) + )); } let mut tracker = TrieTracker::default(); diff --git a/crates/trie/trie/src/updates.rs b/crates/trie/trie/src/updates.rs index 39628e6d5272..60ccf4850690 100644 --- a/crates/trie/trie/src/updates.rs +++ b/crates/trie/trie/src/updates.rs @@ -131,7 +131,7 @@ impl TrieUpdates { /// Flush updates all aggregated updates to the database. pub fn flush(self, tx: &(impl DbTx + DbTxMut)) -> Result<(), reth_db::DatabaseError> { if self.trie_operations.is_empty() { - return Ok(()) + return Ok(()); } let mut account_trie_cursor = tx.cursor_write::()?; diff --git a/crates/trie/trie/src/walker.rs b/crates/trie/trie/src/walker.rs index 6486a9b08006..9959f4f95a5c 100644 --- a/crates/trie/trie/src/walker.rs +++ b/crates/trie/trie/src/walker.rs @@ -174,7 +174,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 @@ -213,22 +213,22 @@ impl TrieWalker { if subnode.nibble() >= 0xf || (subnode.nibble() < 0 && !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. loop { if subnode.state_flag() { - return Ok(()) + return Ok(()); } if subnode.nibble() == 0xf { - break + break; } subnode.inc_nibble(); } diff --git a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs index 70c6c98a9fd0..5f5f4cbf1eb0 100644 --- a/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs +++ b/examples/beacon-api-sidecar-fetcher/src/mined_sidecar.rs @@ -103,7 +103,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.hash()).collect()) { @@ -157,7 +157,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 @@ -243,7 +243,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 07fd78c5ffc9..0ffdb9a32f49 100644 --- a/examples/custom-engine-types/src/main.rs +++ b/examples/custom-engine-types/src/main.rs @@ -102,7 +102,7 @@ impl PayloadAttributes for CustomPayloadAttributes { if self.custom == 0 { return Err(EngineObjectValidationError::invalid_params( CustomError::CustomFieldIsNotZero, - )) + )); } Ok(()) diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs index c48da7d97442..87695b9a6853 100644 --- a/examples/exex/remote/bin/consumer.rs +++ b/examples/exex/remote/bin/consumer.rs @@ -1,4 +1,7 @@ -use exex_remote::proto::{remote_ex_ex_client::RemoteExExClient, Notification, SubscribeRequest}; +use exex_remote::{ + codec::from_proto_notification, + proto::{remote_ex_ex_client::RemoteExExClient, SubscribeRequest}, +}; use reth_exex::ExExNotification; use reth_tracing::{tracing::info, RethTracer, Tracer}; @@ -9,8 +12,8 @@ async fn main() -> eyre::Result<()> { let mut client = RemoteExExClient::connect("http://[::1]:10000").await?; let mut stream = client.subscribe(SubscribeRequest {}).await?.into_inner(); - while let Some(Notification { data }) = stream.message().await? { - let notification = bincode::deserialize::(&data)?; + while let Some(notification) = stream.message().await? { + let notification = from_proto_notification(¬ification)?; match notification { ExExNotification::ChainCommitted { new } => { diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index af956d2f1df9..5640e5b5321a 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -1,8 +1,11 @@ use std::sync::Arc; -use exex_remote::proto::{ - remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, - Notification as ProtoNotification, SubscribeRequest as ProtoSubscribeRequest, +use exex_remote::{ + codec, + proto::{ + remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, + ExExNotification as ProtoExExNotification, SubscribeRequest as ProtoSubscribeRequest, + }, }; use futures::TryFutureExt; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; @@ -19,7 +22,7 @@ struct ExExService { #[tonic::async_trait] impl RemoteExEx for ExExService { - type SubscribeStream = ReceiverStream>; + type SubscribeStream = ReceiverStream>; async fn subscribe( &self, @@ -30,12 +33,9 @@ impl RemoteExEx for ExExService { let mut notifications = self.notifications.subscribe(); tokio::spawn(async move { while let Ok(notification) = notifications.recv().await { - tx.send(Ok(ProtoNotification { - data: bincode::serialize(¬ification) - .expect("failed to serialize notification"), - })) - .await - .expect("failed to send notification to client"); + tx.send(Ok(codec::to_proto_notification(¬ification).expect("failed to encode"))) + .await + .expect("failed to send notification to client"); } }); diff --git a/examples/exex/remote/proto/exex.proto b/examples/exex/remote/proto/exex.proto index 9c8cdac39c11..17620b6802ab 100644 --- a/examples/exex/remote/proto/exex.proto +++ b/examples/exex/remote/proto/exex.proto @@ -2,12 +2,278 @@ syntax = "proto3"; package exex; +import "google/protobuf/empty.proto"; + service RemoteExEx { - rpc Subscribe(SubscribeRequest) returns (stream Notification) {} + rpc Subscribe(SubscribeRequest) returns (stream ExExNotification) {} } message SubscribeRequest {} -message Notification { - bytes data = 1; +message ExExNotification { + oneof notification { + ChainCommitted chain_committed = 1; + ChainReorged chain_reorged = 2; + ChainReverted chain_reverted = 3; + } +} + +message ChainCommitted { + Chain new = 1; +} + +message ChainReorged { + Chain old = 1; + Chain new = 2; +} + +message ChainReverted { + Chain old = 1; +} + +message Chain { + repeated Block blocks = 1; + ExecutionOutcome execution_outcome = 2; +} + +message Block { + SealedHeader header = 1; + repeated Transaction body = 2; + repeated Header ommers = 3; + repeated bytes senders = 4; + // TODO: add withdrawals and requests +} + +message SealedHeader { + bytes hash = 1; + Header header = 2; +} + +message Header { + bytes parent_hash = 1; + bytes ommers_hash = 2; + bytes beneficiary = 3; + bytes state_root = 4; + bytes transactions_root = 5; + bytes receipts_root = 6; + optional bytes withdrawals_root = 7; + bytes logs_bloom = 8; + bytes difficulty = 9; + uint64 number = 10; + uint64 gas_limit = 11; + uint64 gas_used = 12; + uint64 timestamp = 13; + bytes mix_hash = 14; + uint64 nonce = 15; + optional uint64 base_fee_per_gas = 16; + optional uint64 blob_gas_used = 17; + optional uint64 excess_blob_gas = 18; + optional bytes parent_beacon_block_root = 19; + // TODO: add requests_root + bytes extra_data = 20; +} + +message Transaction { + bytes hash = 1; + Signature signature = 2; + oneof transaction { + TransactionLegacy legacy = 3; + TransactionEip2930 eip2930 = 4; + TransactionEip1559 eip1559 = 5; + TransactionEip4844 eip4844 = 6; + } +} + +message Signature { + bytes r = 1; + bytes s = 2; + bool odd_y_parity = 3; +} + +message TransactionLegacy { + optional uint64 chain_id = 1; + uint64 nonce = 2; + bytes gas_price = 3; + uint64 gas_limit = 4; + TxKind to = 5; + bytes value = 6; + bytes input = 7; +} + +message TransactionEip2930 { + uint64 chain_id = 1; + uint64 nonce = 2; + bytes gas_price = 3; + uint64 gas_limit = 4; + TxKind to = 5; + bytes value = 6; + repeated AccessListItem access_list = 7; + bytes input = 8; +} + +message TransactionEip1559 { + uint64 chain_id = 1; + uint64 nonce = 2; + uint64 gas_limit = 3; + bytes max_fee_per_gas = 4; + bytes max_priority_fee_per_gas = 5; + TxKind to = 6; + bytes value = 7; + repeated AccessListItem access_list = 8; + bytes input = 9; +} + +message TransactionEip4844 { + uint64 chain_id = 1; + uint64 nonce = 2; + uint64 gas_limit = 3; + bytes max_fee_per_gas = 4; + bytes max_priority_fee_per_gas = 5; + bytes to = 6; + bytes value = 7; + repeated AccessListItem access_list = 8; + repeated bytes blob_versioned_hashes = 9; + bytes max_fee_per_blob_gas = 10; + bytes input = 11; +} + +message TxKind { + oneof kind { + google.protobuf.Empty create = 1; + bytes call = 2; + } +} + +message AccessListItem { + bytes address = 1; + repeated bytes storage_keys = 2; +} + +message ExecutionOutcome { + BundleState bundle = 1; + repeated BlockReceipts receipts = 2; + uint64 first_block = 3; + // TODO: add requests +} + +message BundleState { + repeated BundleAccount state = 1; + repeated ContractBytecode contracts = 2; + repeated BlockReverts reverts = 3; + uint64 state_size = 4; + uint64 reverts_size = 5; +} + +message BundleAccount { + bytes address = 1; + AccountInfo info = 2; + AccountInfo original_info = 3; + repeated StorageSlot storage = 4; + AccountStatus status = 5; +} + +message AccountInfo { + bytes balance = 1; + uint64 nonce = 2; + bytes code_hash = 3; + Bytecode code = 4; +} + +message StorageSlot { + bytes key = 1; + bytes previous_or_original_value = 2; + bytes present_value = 3; +} + +enum AccountStatus { + LOADED_NOT_EXISTING = 0; + LOADED = 1; + LOADED_EMPTY_EIP161 = 2; + IN_MEMORY_CHANGE = 3; + CHANGED = 4; + DESTROYED = 5; + DESTROYED_CHANGED = 6; + DESTROYED_AGAIN = 7; +} + +message ContractBytecode { + bytes hash = 1; + Bytecode bytecode = 2; +} + +message Bytecode { + oneof bytecode { + bytes legacy_raw = 1; + LegacyAnalyzedBytecode legacy_analyzed = 2; + // TODO: add EOF + } +} + +message LegacyAnalyzedBytecode { + bytes bytecode = 1; + uint64 original_len = 2; + repeated uint32 jump_table = 3; +} + +message BlockReverts { + repeated Revert reverts = 1; +} + +message Revert { + bytes address = 1; + AccountInfoRevert account = 2; + repeated RevertToSlot storage = 3; + AccountStatus previous_status = 4; + bool wipe_storage = 5; +} + +message AccountInfoRevert { + oneof revert { + google.protobuf.Empty do_nothing = 1; + google.protobuf.Empty delete_it = 2; + AccountInfo revert_to = 3; + } +} + +message RevertToSlot { + bytes key = 1; + oneof revert { + bytes some = 2; + google.protobuf.Empty destroyed = 3; + } +} + +message BlockReceipts { + repeated Receipt receipts = 1; +} + +message Receipt { + oneof receipt { + google.protobuf.Empty empty = 1; + NonEmptyReceipt non_empty = 2; + } +} + +message NonEmptyReceipt { + TxType tx_type = 1; + bool success = 2; + uint64 cumulative_gas_used = 3; + repeated Log logs = 4; +} + +enum TxType { + LEGACY = 0; + EIP2930 = 1; + EIP1559 = 2; + EIP4844 = 3; +} + +message Log { + bytes address = 1; + LogData data = 2; +} + +message LogData { + repeated bytes topics = 1; + bytes data = 2; } diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs new file mode 100644 index 000000000000..fcc866a333fe --- /dev/null +++ b/examples/exex/remote/src/codec.rs @@ -0,0 +1,822 @@ +use std::sync::Arc; + +use eyre::OptionExt; +use reth::primitives::{Address, BlockHash, Bloom, TxHash, B256, U256}; + +use crate::proto; + +pub fn to_proto_notification( + notification: &reth_exex::ExExNotification, +) -> eyre::Result { + let notification = match notification { + reth_exex::ExExNotification::ChainCommitted { new } => { + proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { + new: Some(to_proto_chain(&new)?), + }) + } + reth_exex::ExExNotification::ChainReorged { old, new } => { + proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { + old: Some(to_proto_chain(&old)?), + new: Some(to_proto_chain(&new)?), + }) + } + reth_exex::ExExNotification::ChainReverted { old } => { + proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { + old: Some(to_proto_chain(&old)?), + }) + } + }; + + Ok(proto::ExExNotification { notification: Some(notification) }) +} + +pub fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result { + let bundle_state = chain.execution_outcome().state(); + Ok(proto::Chain { + blocks: chain + .blocks_iter() + .map(|block| proto::Block { + header: Some(proto::SealedHeader { + hash: block.header.hash().to_vec(), + header: Some(to_proto_header(&block.header.header())), + }), + body: block.transactions().map(to_proto_transaction).collect(), + ommers: block.ommers.iter().map(to_proto_header).collect(), + senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), + }) + .collect(), + execution_outcome: Some(proto::ExecutionOutcome { + bundle: Some(proto::BundleState { + state: bundle_state + .state + .iter() + .map(|(address, account)| { + Ok(proto::BundleAccount { + address: address.to_vec(), + info: account.info.as_ref().map(to_proto_account_info).transpose()?, + original_info: account + .original_info + .as_ref() + .map(to_proto_account_info) + .transpose()?, + storage: account + .storage + .iter() + .map(|(key, slot)| proto::StorageSlot { + key: key.to_le_bytes_vec(), + previous_or_original_value: slot + .previous_or_original_value + .to_le_bytes_vec(), + present_value: slot.present_value.to_le_bytes_vec(), + }) + .collect(), + status: to_proto_account_status(account.status) as i32, + }) + }) + .collect::>()?, + contracts: bundle_state + .contracts + .iter() + .map(|(hash, bytecode)| { + Ok(proto::ContractBytecode { + hash: hash.to_vec(), + bytecode: Some(to_proto_bytecode(bytecode)?), + }) + }) + .collect::>()?, + reverts: bundle_state + .reverts + .iter() + .map(|block_reverts| Ok(proto::BlockReverts { + reverts: block_reverts + .iter() + .map(|(address, revert)| Ok(proto::Revert { + address: address.to_vec(), + account: Some(proto::AccountInfoRevert { revert: Some(match &revert.account { + reth::revm::db::states::reverts::AccountInfoRevert::DoNothing => proto::account_info_revert::Revert::DoNothing(()), + reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt => proto::account_info_revert::Revert::DeleteIt(()), + reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info) => proto::account_info_revert::Revert::RevertTo(to_proto_account_info(account_info)?), + })}), + storage: revert.storage.iter().map(|(key, slot)| Ok(proto::RevertToSlot { + key: key.to_le_bytes_vec(), + revert: Some(match slot { + reth::revm::db::RevertToSlot::Some(value) => proto::revert_to_slot::Revert::Some(value.to_le_bytes_vec()), + reth::revm::db::RevertToSlot::Destroyed => proto::revert_to_slot::Revert::Destroyed(()), + }), + })).collect::>()?, + previous_status: to_proto_account_status(revert.previous_status) as i32, + wipe_storage: revert.wipe_storage, + })) + .collect::>()?, + })) + .collect::>()?, + state_size: bundle_state.state_size as u64, + reverts_size: bundle_state.reverts_size as u64, + }), + receipts: chain + .execution_outcome() + .receipts() + .iter() + .map(|block_receipts| proto::BlockReceipts { + receipts: block_receipts + .iter() + .map(|receipt| proto::Receipt { + receipt: Some(receipt.as_ref().map_or( + proto::receipt::Receipt::Empty(()), + |receipt| { + proto::receipt::Receipt::NonEmpty(proto::NonEmptyReceipt { + tx_type: match receipt.tx_type { + reth::primitives::TxType::Legacy => { + proto::TxType::Legacy + } + reth::primitives::TxType::Eip2930 => { + proto::TxType::Eip2930 + } + reth::primitives::TxType::Eip1559 => { + proto::TxType::Eip1559 + } + reth::primitives::TxType::Eip4844 => { + proto::TxType::Eip4844 + } + } as i32, + success: receipt.success, + cumulative_gas_used: receipt.cumulative_gas_used, + logs: receipt + .logs + .iter() + .map(|log| proto::Log { + address: log.address.to_vec(), + data: Some(proto::LogData { + topics: log + .data + .topics() + .iter() + .map(|topic| topic.to_vec()) + .collect(), + data: log.data.data.to_vec(), + }), + }) + .collect(), + }) + }, + )), + }) + .collect(), + }) + .collect(), + first_block: chain.execution_outcome().first_block, + }), + }) +} + +pub fn to_proto_header(header: &reth::primitives::Header) -> proto::Header { + proto::Header { + parent_hash: header.parent_hash.to_vec(), + ommers_hash: header.ommers_hash.to_vec(), + beneficiary: header.beneficiary.to_vec(), + state_root: header.state_root.to_vec(), + transactions_root: header.transactions_root.to_vec(), + receipts_root: header.receipts_root.to_vec(), + withdrawals_root: header.withdrawals_root.map(|root| root.to_vec()), + logs_bloom: header.logs_bloom.to_vec(), + difficulty: header.difficulty.to_le_bytes_vec(), + number: header.number, + gas_limit: header.gas_limit, + gas_used: header.gas_used, + timestamp: header.timestamp, + mix_hash: header.mix_hash.to_vec(), + nonce: header.nonce, + base_fee_per_gas: header.base_fee_per_gas, + blob_gas_used: header.blob_gas_used, + excess_blob_gas: header.excess_blob_gas, + parent_beacon_block_root: header.parent_beacon_block_root.map(|root| root.to_vec()), + extra_data: header.extra_data.to_vec(), + } +} + +pub fn to_proto_transaction( + transaction: &reth::primitives::TransactionSigned, +) -> proto::Transaction { + let hash = transaction.hash().to_vec(); + let signature = proto::Signature { + r: transaction.signature.r.to_le_bytes_vec(), + s: transaction.signature.s.to_le_bytes_vec(), + odd_y_parity: transaction.signature.odd_y_parity, + }; + let transaction = match &transaction.transaction { + reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + input, + }) => proto::transaction::Transaction::Legacy(proto::TransactionLegacy { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: gas_price.to_le_bytes().to_vec(), + gas_limit: *gas_limit, + to: Some(to_proto_tx_kind(to)), + value: value.to_le_bytes_vec(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + access_list, + input, + }) => proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: gas_price.to_le_bytes().to_vec(), + gas_limit: *gas_limit, + to: Some(to_proto_tx_kind(to)), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(to_proto_access_list_item).collect(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + input, + }) => proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), + max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), + to: Some(to_proto_tx_kind(to)), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(to_proto_access_list_item).collect(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + placeholder: _, + to, + value, + access_list, + blob_versioned_hashes, + max_fee_per_blob_gas, + input, + }) => proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), + max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), + to: to.to_vec(), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(to_proto_access_list_item).collect(), + blob_versioned_hashes: blob_versioned_hashes.iter().map(|hash| hash.to_vec()).collect(), + max_fee_per_blob_gas: max_fee_per_blob_gas.to_le_bytes().to_vec(), + input: input.to_vec(), + }), + }; + + proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) } +} + +pub fn to_proto_tx_kind(kind: &reth::primitives::TxKind) -> proto::TxKind { + proto::TxKind { + kind: match kind { + reth::primitives::TxKind::Create => Some(proto::tx_kind::Kind::Create(())), + reth::primitives::TxKind::Call(address) => { + Some(proto::tx_kind::Kind::Call(address.to_vec())) + } + }, + } +} + +pub fn to_proto_access_list_item(item: &reth::primitives::AccessListItem) -> proto::AccessListItem { + proto::AccessListItem { + address: item.address.to_vec(), + storage_keys: item.storage_keys.iter().map(|key| key.to_vec()).collect(), + } +} + +pub fn to_proto_account_info( + account_info: &reth::revm::primitives::AccountInfo, +) -> eyre::Result { + Ok(proto::AccountInfo { + balance: account_info.balance.to_le_bytes_vec(), + nonce: account_info.nonce, + code_hash: account_info.code_hash.to_vec(), + code: account_info.code.as_ref().map(to_proto_bytecode).transpose()?, + }) +} + +pub fn to_proto_bytecode( + bytecode: &reth::revm::primitives::Bytecode, +) -> eyre::Result { + let bytecode = match bytecode { + reth::revm::primitives::Bytecode::LegacyRaw(code) => { + proto::bytecode::Bytecode::LegacyRaw(code.to_vec()) + } + reth::revm::primitives::Bytecode::LegacyAnalyzed(legacy_analyzed) => { + proto::bytecode::Bytecode::LegacyAnalyzed(proto::LegacyAnalyzedBytecode { + bytecode: legacy_analyzed.bytecode().to_vec(), + original_len: legacy_analyzed.original_len() as u64, + jump_table: legacy_analyzed + .jump_table() + .0 + .iter() + .by_vals() + .map(|x| x.into()) + .collect(), + }) + } + reth::revm::primitives::Bytecode::Eof(_) => { + return Err(eyre::eyre!("EOF bytecode not supported")) + } + }; + Ok(proto::Bytecode { bytecode: Some(bytecode) }) +} + +pub fn to_proto_account_status(status: reth::revm::db::AccountStatus) -> proto::AccountStatus { + match status { + reth::revm::db::AccountStatus::LoadedNotExisting => proto::AccountStatus::LoadedNotExisting, + reth::revm::db::AccountStatus::Loaded => proto::AccountStatus::Loaded, + reth::revm::db::AccountStatus::LoadedEmptyEIP161 => proto::AccountStatus::LoadedEmptyEip161, + reth::revm::db::AccountStatus::InMemoryChange => proto::AccountStatus::InMemoryChange, + reth::revm::db::AccountStatus::Changed => proto::AccountStatus::Changed, + reth::revm::db::AccountStatus::Destroyed => proto::AccountStatus::Destroyed, + reth::revm::db::AccountStatus::DestroyedChanged => proto::AccountStatus::DestroyedChanged, + reth::revm::db::AccountStatus::DestroyedAgain => proto::AccountStatus::DestroyedAgain, + } +} + +pub fn from_proto_notification( + notification: &proto::ExExNotification, +) -> eyre::Result { + match notification.notification.as_ref().ok_or_eyre("no notification")? { + proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { new }) => { + Ok(reth_exex::ExExNotification::ChainCommitted { + new: from_proto_chain(new.as_ref().ok_or_eyre("no new chain")?)?, + }) + } + proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { old, new }) => { + Ok(reth_exex::ExExNotification::ChainReorged { + old: from_proto_chain(old.as_ref().ok_or_eyre("no old chain")?)?, + new: from_proto_chain(new.as_ref().ok_or_eyre("no new chain")?)?, + }) + } + proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { old }) => { + Ok(reth_exex::ExExNotification::ChainReverted { + old: from_proto_chain(old.as_ref().ok_or_eyre("no old chain")?)?, + }) + } + } +} + +pub fn from_proto_chain(chain: &proto::Chain) -> eyre::Result> { + let execution_outcome = chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; + let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; + Ok(Arc::new(reth::providers::Chain::new( + chain.blocks.iter().map(from_proto_block).collect::>>()?, + reth::providers::ExecutionOutcome { + bundle: reth::revm::db::BundleState { + state: bundle + .state + .iter() + .map(|account| { + Ok(( + Address::try_from(account.address.as_slice())?, + reth::revm::db::BundleAccount { + info: account + .info + .as_ref() + .map(from_proto_account_info) + .transpose()?, + original_info: account + .original_info + .as_ref() + .map(from_proto_account_info) + .transpose()?, + storage: account + .storage + .iter() + .map(|slot| { + Ok(( + U256::try_from_le_slice(slot.key.as_slice()) + .ok_or_eyre("failed to parse key")?, + reth::revm::db::states::StorageSlot { + previous_or_original_value: U256::try_from_le_slice( + slot.previous_or_original_value.as_slice(), + ) + .ok_or_eyre( + "failed to parse previous or original value", + )?, + present_value: U256::try_from_le_slice( + slot.present_value.as_slice(), + ) + .ok_or_eyre("failed to parse present value")?, + }, + )) + }) + .collect::>()?, + status: from_proto_account_status(proto::AccountStatus::try_from( + account.status, + )?), + }, + )) + }) + .collect::>()?, + contracts: bundle + .contracts + .iter() + .map(|contract| { + Ok(( + B256::try_from(contract.hash.as_slice())?, + from_proto_bytecode( + contract.bytecode.as_ref().ok_or_eyre("no bytecode")?, + )?, + )) + }) + .collect::>()?, + reverts: reth::revm::db::states::reverts::Reverts::new( + bundle + .reverts + .iter() + .map(|block_reverts| { + Ok(block_reverts + .reverts + .iter() + .map(|revert| { + Ok(( + Address::try_from(revert.address.as_slice())?, + reth::revm::db::states::reverts::AccountRevert { + account: match revert.account.as_ref().ok_or_eyre("no revert account")?.revert.as_ref().ok_or_eyre("no revert account revert")? { + proto::account_info_revert::Revert::DoNothing(()) => reth::revm::db::states::reverts::AccountInfoRevert::DoNothing, + proto::account_info_revert::Revert::DeleteIt(()) => reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt, + proto::account_info_revert::Revert::RevertTo(account_info) => reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(from_proto_account_info(account_info)?), + }, + storage: revert + .storage + .iter() + .map(|slot| Ok(( + U256::try_from_le_slice(slot.key.as_slice()) + .ok_or_eyre("failed to parse slot key")?, + match slot.revert.as_ref().ok_or_eyre("no slot revert")? { + proto::revert_to_slot::Revert::Some(value) => reth::revm::db::states::reverts::RevertToSlot::Some(U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse slot revert")?), + proto::revert_to_slot::Revert::Destroyed(()) => reth::revm::db::states::reverts::RevertToSlot::Destroyed, + } + ))) + .collect::>()?, + previous_status: from_proto_account_status( + proto::AccountStatus::try_from( + revert.previous_status, + )?, + ), + wipe_storage: revert.wipe_storage, + }, + )) + }) + .collect::>()?) + }) + .collect::>()?, + ), + state_size: bundle.state_size as usize, + reverts_size: bundle.reverts_size as usize, + }, + receipts: reth::primitives::Receipts::from_iter(execution_outcome + .receipts + .iter() + .map(|block_receipts| { + Ok(block_receipts + .receipts + .iter() + .map(|receipt| { + Ok(match receipt.receipt.as_ref().ok_or_eyre("no receipt")? { + proto::receipt::Receipt::Empty(()) => None, + proto::receipt::Receipt::NonEmpty(receipt) => { + Some(reth::primitives::Receipt { + tx_type: match proto::TxType::try_from(receipt.tx_type)? { + proto::TxType::Legacy => { + reth::primitives::TxType::Legacy + } + proto::TxType::Eip2930 => { + reth::primitives::TxType::Eip2930 + } + proto::TxType::Eip1559 => { + reth::primitives::TxType::Eip1559 + } + proto::TxType::Eip4844 => { + reth::primitives::TxType::Eip4844 + } + }, + success: receipt.success, + cumulative_gas_used: receipt.cumulative_gas_used, + logs: receipt + .logs + .iter() + .map(|log| { + let data = + log.data.as_ref().ok_or_eyre("no log data")?; + Ok(reth::primitives::Log { + address: Address::try_from( + log.address.as_slice(), + )?, + data: reth::primitives::LogData::new_unchecked( + data.topics + .iter() + .map(|topic| { + Ok(B256::try_from( + topic.as_slice(), + )?) + }) + .collect::>()?, + data.data.clone().into(), + ), + }) + }) + .collect::>()?, + }) + } + }) + }) + .collect::>()?) + }) + .collect::>>()?), + first_block: execution_outcome.first_block, + requests: Default::default(), + }, + None, + ))) +} + +pub fn from_proto_block( + block: &proto::Block, +) -> eyre::Result { + let sealed_header = block.header.as_ref().ok_or_eyre("no sealed header")?; + let header = from_proto_header(sealed_header.header.as_ref().ok_or_eyre("no header")?)?; + let sealed_header = reth::primitives::SealedHeader::new( + header, + BlockHash::try_from(sealed_header.hash.as_slice())?, + ); + + let transactions = + block.body.iter().map(from_proto_transaction).collect::>()?; + let ommers = block.ommers.iter().map(from_proto_header).collect::>()?; + let senders = block + .senders + .iter() + .map(|sender| Address::try_from(sender.as_slice())) + .collect::>()?; + + reth::primitives::SealedBlockWithSenders::new( + reth::primitives::SealedBlock::new( + sealed_header, + reth::primitives::BlockBody { + transactions, + ommers, + withdrawals: Default::default(), + requests: Default::default(), + }, + ), + senders, + ) + .ok_or_eyre("senders do not match transactions") +} + +pub fn from_proto_header(header: &proto::Header) -> eyre::Result { + Ok(reth::primitives::Header { + parent_hash: B256::try_from(header.parent_hash.as_slice())?, + ommers_hash: B256::try_from(header.ommers_hash.as_slice())?, + beneficiary: Address::try_from(header.beneficiary.as_slice())?, + state_root: B256::try_from(header.state_root.as_slice())?, + transactions_root: B256::try_from(header.transactions_root.as_slice())?, + receipts_root: B256::try_from(header.receipts_root.as_slice())?, + withdrawals_root: header + .withdrawals_root + .as_ref() + .map(|root| B256::try_from(root.as_slice())) + .transpose()?, + logs_bloom: Bloom::try_from(header.logs_bloom.as_slice())?, + difficulty: U256::try_from_le_slice(&header.difficulty) + .ok_or_eyre("failed to parse difficulty")?, + number: header.number, + gas_limit: header.gas_limit, + gas_used: header.gas_used, + timestamp: header.timestamp, + mix_hash: B256::try_from(header.mix_hash.as_slice())?, + nonce: header.nonce, + base_fee_per_gas: header.base_fee_per_gas, + blob_gas_used: header.blob_gas_used, + excess_blob_gas: header.excess_blob_gas, + parent_beacon_block_root: header + .parent_beacon_block_root + .as_ref() + .map(|root| B256::try_from(root.as_slice())) + .transpose()?, + requests_root: None, + extra_data: header.extra_data.as_slice().to_vec().into(), + }) +} + +pub fn from_proto_transaction( + transaction: &proto::Transaction, +) -> eyre::Result { + let hash = TxHash::try_from(transaction.hash.as_slice())?; + let signature = transaction.signature.as_ref().ok_or_eyre("no signature")?; + let signature = reth::primitives::Signature { + r: U256::try_from_le_slice(signature.r.as_slice()).ok_or_eyre("failed to parse r")?, + s: U256::try_from_le_slice(signature.s.as_slice()).ok_or_eyre("failed to parse s")?, + odd_y_parity: signature.odd_y_parity, + }; + let transaction = match transaction.transaction.as_ref().ok_or_eyre("no transaction")? { + proto::transaction::Transaction::Legacy(proto::TransactionLegacy { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + input, + }) => reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), + gas_limit: *gas_limit, + to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, + value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + access_list, + input, + }) => reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), + gas_limit: *gas_limit, + to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, + value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(from_proto_access_list_item) + .collect::>>()? + .into(), + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + input, + }) => reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), + max_priority_fee_per_gas: u128::from_le_bytes( + max_priority_fee_per_gas.as_slice().try_into()?, + ), + to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, + value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(from_proto_access_list_item) + .collect::>>()? + .into(), + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + blob_versioned_hashes, + max_fee_per_blob_gas, + input, + }) => reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), + max_priority_fee_per_gas: u128::from_le_bytes( + max_priority_fee_per_gas.as_slice().try_into()?, + ), + placeholder: None, + to: Address::try_from(to.as_slice())?, + value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(from_proto_access_list_item) + .collect::>>()? + .into(), + blob_versioned_hashes: blob_versioned_hashes + .iter() + .map(|hash| B256::try_from(hash.as_slice())) + .collect::>()?, + max_fee_per_blob_gas: u128::from_le_bytes(max_fee_per_blob_gas.as_slice().try_into()?), + input: input.to_vec().into(), + }), + }; + + Ok(reth::primitives::TransactionSigned { hash, signature, transaction }) +} + +pub fn from_proto_tx_kind(tx_kind: &proto::TxKind) -> eyre::Result { + Ok(match tx_kind.kind.as_ref().ok_or_eyre("no kind")? { + proto::tx_kind::Kind::Create(()) => reth::primitives::TxKind::Create, + proto::tx_kind::Kind::Call(address) => { + reth::primitives::TxKind::Call(Address::try_from(address.as_slice())?) + } + }) +} + +pub fn from_proto_access_list_item( + item: &proto::AccessListItem, +) -> eyre::Result { + Ok(reth::primitives::AccessListItem { + address: Address::try_from(item.address.as_slice())?, + storage_keys: item + .storage_keys + .iter() + .map(|key| B256::try_from(key.as_slice())) + .collect::>()?, + }) +} + +pub fn from_proto_account_info( + account_info: &proto::AccountInfo, +) -> eyre::Result { + Ok(reth::revm::primitives::AccountInfo { + balance: U256::try_from_le_slice(account_info.balance.as_slice()) + .ok_or_eyre("failed to parse balance")?, + nonce: account_info.nonce, + code_hash: B256::try_from(account_info.code_hash.as_slice())?, + code: account_info.code.as_ref().map(from_proto_bytecode).transpose()?, + }) +} + +pub fn from_proto_bytecode( + bytecode: &proto::Bytecode, +) -> eyre::Result { + let bytecode = match bytecode.bytecode.as_ref().ok_or_eyre("no bytecode")? { + proto::bytecode::Bytecode::LegacyRaw(code) => { + reth::revm::primitives::Bytecode::LegacyRaw(code.clone().into()) + } + proto::bytecode::Bytecode::LegacyAnalyzed(legacy_analyzed) => { + reth::revm::primitives::Bytecode::LegacyAnalyzed( + reth::revm::primitives::LegacyAnalyzedBytecode::new( + legacy_analyzed.bytecode.clone().into(), + legacy_analyzed.original_len as usize, + reth::revm::primitives::JumpTable::from_slice( + legacy_analyzed + .jump_table + .iter() + .map(|dest| *dest as u8) + .collect::>() + .as_slice(), + ), + ), + ) + } + }; + Ok(bytecode) +} + +pub fn from_proto_account_status(status: proto::AccountStatus) -> reth::revm::db::AccountStatus { + match status { + proto::AccountStatus::LoadedNotExisting => reth::revm::db::AccountStatus::LoadedNotExisting, + proto::AccountStatus::Loaded => reth::revm::db::AccountStatus::Loaded, + proto::AccountStatus::LoadedEmptyEip161 => reth::revm::db::AccountStatus::LoadedEmptyEIP161, + proto::AccountStatus::InMemoryChange => reth::revm::db::AccountStatus::InMemoryChange, + proto::AccountStatus::Changed => reth::revm::db::AccountStatus::Changed, + proto::AccountStatus::Destroyed => reth::revm::db::AccountStatus::Destroyed, + proto::AccountStatus::DestroyedChanged => reth::revm::db::AccountStatus::DestroyedChanged, + proto::AccountStatus::DestroyedAgain => reth::revm::db::AccountStatus::DestroyedAgain, + } +} diff --git a/examples/exex/remote/src/lib.rs b/examples/exex/remote/src/lib.rs index 9abb458bd3c0..9b8aa5781a8f 100644 --- a/examples/exex/remote/src/lib.rs +++ b/examples/exex/remote/src/lib.rs @@ -1,3 +1,4 @@ +pub mod codec; pub mod proto { tonic::include_proto!("exex"); } diff --git a/examples/exex/rollup/src/execution.rs b/examples/exex/rollup/src/execution.rs index e1fcfb5c485b..deffc3a80e11 100644 --- a/examples/exex/rollup/src/execution.rs +++ b/examples/exex/rollup/src/execution.rs @@ -212,7 +212,7 @@ fn execute_transactions( transaction_gas_limit: transaction.gas_limit(), block_available_gas, } - .into()) + .into()); } // Execute transaction. // Fill revm structure. @@ -225,7 +225,7 @@ fn execute_transactions( EVMError::Transaction(err) => { // if the transaction is invalid, we can skip it debug!(%err, ?transaction, "Skipping invalid transaction"); - continue + continue; } err => { // this is an error that we should treat as fatal for this attempt diff --git a/examples/exex/rollup/src/main.rs b/examples/exex/rollup/src/main.rs index f8a2ffc401f6..547779908cb7 100644 --- a/examples/exex/rollup/src/main.rs +++ b/examples/exex/rollup/src/main.rs @@ -132,11 +132,11 @@ impl Rollup { }) => { if rollupChainId != U256::from(CHAIN_ID) { error!(tx_hash = %tx.recalculate_hash(), "Invalid rollup chain ID"); - continue + continue; } if token != Address::ZERO { error!(tx_hash = %tx.recalculate_hash(), "Only ETH deposits are supported"); - continue + continue; } self.db.upsert_account(rollupRecipient, |account| { @@ -197,11 +197,11 @@ impl Rollup { }) => { if rollupChainId != U256::from(CHAIN_ID) { error!(tx_hash = %tx.recalculate_hash(), "Invalid rollup chain ID"); - continue + continue; } if token != Address::ZERO { error!(tx_hash = %tx.recalculate_hash(), "Only ETH deposits are supported"); - continue + continue; } self.db.upsert_account(rollupRecipient, |account| { diff --git a/examples/manual-p2p/src/main.rs b/examples/manual-p2p/src/main.rs index 2b89b5539d4f..d86631ad01a2 100644 --- a/examples/manual-p2p/src/main.rs +++ b/examples/manual-p2p/src/main.rs @@ -46,14 +46,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; } }; @@ -61,7 +61,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 08b27d3ac4a6..fe84e654d7ee 100644 --- a/examples/node-custom-rpc/src/main.rs +++ b/examples/node-custom-rpc/src/main.rs @@ -25,7 +25,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/testing/ef-tests/src/cases/blockchain_test.rs b/testing/ef-tests/src/cases/blockchain_test.rs index 87c3b8df1d8f..fdfb2a5db6f1 100644 --- a/testing/ef-tests/src/cases/blockchain_test.rs +++ b/testing/ef-tests/src/cases/blockchain_test.rs @@ -63,7 +63,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. diff --git a/testing/ef-tests/src/models.rs b/testing/ef-tests/src/models.rs index 2c580dc54ea8..806591c47749 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:?}" - ))) + ))); } } diff --git a/testing/testing-utils/src/generators.rs b/testing/testing-utils/src/generators.rs index 4ef65043f602..ee09e2873070 100644 --- a/testing/testing-utils/src/generators.rs +++ b/testing/testing-utils/src/generators.rs @@ -250,7 +250,7 @@ where } else { let old = storage.remove(&entry.key); if matches!(old, Some(U256::ZERO)) { - return None + return None; } old }; From c931f74464bcec1565decfed8c8be2cacd633aab Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Tue, 18 Jun 2024 15:40:39 +0100 Subject: [PATCH 07/16] ok revert some ; --- Cargo.lock | 1 - bin/reth/Cargo.toml | 1 - bin/reth/src/cli/mod.rs | 2 +- bin/reth/src/commands/common.rs | 5 +- bin/reth/src/commands/db/checksum.rs | 2 +- bin/reth/src/commands/db/diff.rs | 4 +- bin/reth/src/commands/db/list.rs | 2 +- bin/reth/src/commands/db/mod.rs | 2 +- bin/reth/src/commands/db/tui.rs | 2 +- bin/reth/src/commands/debug_cmd/execution.rs | 4 +- .../commands/debug_cmd/in_memory_merkle.rs | 2 +- bin/reth/src/commands/debug_cmd/merkle.rs | 6 +- bin/reth/src/commands/dump_genesis.rs | 4 +- bin/reth/src/commands/import.rs | 2 +- bin/reth/src/commands/import_op.rs | 2 +- bin/reth/src/commands/import_receipts_op.rs | 2 +- bin/reth/src/commands/node/mod.rs | 6 +- bin/reth/src/commands/p2p/mod.rs | 3 +- .../commands/stage/dump/hashing_account.rs | 2 +- .../commands/stage/dump/hashing_storage.rs | 2 +- bin/reth/src/commands/stage/dump/merkle.rs | 2 +- bin/reth/src/commands/stage/run.rs | 2 +- bin/reth/src/commands/test_vectors/tables.rs | 2 +- bin/reth/src/sigsegv_handler.rs | 4 +- bin/reth/src/utils.rs | 14 +- crates/blockchain-tree/src/block_buffer.rs | 2 +- crates/blockchain-tree/src/block_indices.rs | 6 +- crates/blockchain-tree/src/blockchain_tree.rs | 56 +++--- crates/blockchain-tree/src/bundle.rs | 2 +- crates/blockchain-tree/src/chain.rs | 2 +- crates/blockchain-tree/src/state.rs | 2 +- crates/chainspec/src/spec.rs | 16 +- crates/config/src/config.rs | 2 +- crates/consensus/auto-seal/src/client.rs | 6 +- crates/consensus/auto-seal/src/mode.rs | 6 +- crates/consensus/auto-seal/src/task.rs | 10 +- .../beacon/src/engine/hooks/controller.rs | 6 +- .../beacon/src/engine/hooks/static_file.rs | 6 +- .../beacon/src/engine/invalid_headers.rs | 2 +- crates/consensus/beacon/src/engine/mod.rs | 82 ++++---- crates/consensus/beacon/src/engine/sync.rs | 12 +- .../consensus/beacon/src/engine/test_utils.rs | 4 +- crates/consensus/common/src/validation.rs | 34 ++-- .../debug-client/src/providers/etherscan.rs | 2 +- crates/e2e-test-utils/src/node.rs | 6 +- crates/e2e-test-utils/src/payload.rs | 4 +- crates/ethereum-forks/src/display.rs | 181 ++++++++++++++++++ crates/ethereum-forks/src/forkcondition.rs | 103 ++++++++++ crates/ethereum-forks/src/forkid.rs | 14 +- crates/ethereum-forks/src/hardfork.rs | 20 +- crates/ethereum/consensus/src/lib.rs | 30 ++- crates/ethereum/consensus/src/validation.rs | 12 +- crates/ethereum/evm/src/execute.rs | 2 +- crates/ethereum/payload/src/lib.rs | 12 +- crates/etl/src/lib.rs | 2 +- crates/evm/execution-types/src/chain.rs | 16 +- .../execution-types/src/execution_outcome.rs | 6 +- crates/exex/exex/src/manager.rs | 8 +- crates/metrics/metrics-derive/src/expand.rs | 20 +- crates/metrics/metrics-derive/src/metric.rs | 4 +- crates/net/common/src/ban_list.rs | 6 +- crates/net/common/src/ratelimit.rs | 2 +- crates/net/discv4/src/lib.rs | 64 +++---- crates/net/discv4/src/proto.rs | 24 +-- crates/net/discv4/src/test_utils.rs | 4 +- crates/net/discv5/src/enr.rs | 2 +- crates/net/discv5/src/filter.rs | 4 +- crates/net/discv5/src/lib.rs | 12 +- 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 | 28 +-- 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 +- .../downloaders/src/file_codec_ovm_receipt.rs | 2 +- .../src/headers/reverse_headers.rs | 50 ++--- crates/net/downloaders/src/headers/task.rs | 6 +- .../downloaders/src/receipt_file_client.rs | 2 +- .../src/test_utils/bodies_client.rs | 2 +- crates/net/ecies/src/algorithm.rs | 16 +- crates/net/ecies/src/codec.rs | 18 +- crates/net/eth-wire-types/src/broadcast.rs | 10 +- crates/net/eth-wire-types/src/message.rs | 6 +- crates/net/eth-wire/src/capability.rs | 10 +- crates/net/eth-wire/src/disconnect.rs | 11 +- crates/net/eth-wire/src/errors/eth.rs | 2 +- crates/net/eth-wire/src/ethstream.rs | 24 +-- 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/protocol.rs | 2 +- crates/net/eth-wire/src/test_utils.rs | 2 +- crates/net/nat/src/lib.rs | 2 +- crates/net/network/src/discovery.rs | 4 +- crates/net/network/src/error.rs | 6 +- crates/net/network/src/eth_requests.rs | 26 +-- crates/net/network/src/fetch/mod.rs | 14 +- crates/net/network/src/manager.rs | 4 +- crates/net/network/src/network.rs | 2 +- crates/net/network/src/peers/manager.rs | 44 ++--- crates/net/network/src/session/active.rs | 36 ++-- crates/net/network/src/session/config.rs | 2 +- crates/net/network/src/session/mod.rs | 6 +- crates/net/network/src/state.rs | 10 +- crates/net/network/src/swarm.rs | 22 +-- crates/net/network/src/test_utils/init.rs | 2 +- crates/net/network/src/test_utils/testnet.rs | 6 +- .../net/network/src/transactions/fetcher.rs | 52 ++--- crates/net/network/src/transactions/mod.rs | 46 ++--- .../network/src/transactions/validation.rs | 6 +- crates/net/network/tests/it/multiplex.rs | 12 +- crates/net/p2p/src/error.rs | 2 +- crates/net/p2p/src/full_block.rs | 40 ++-- crates/net/p2p/src/test_utils/headers.rs | 14 +- crates/net/peers/src/lib.rs | 8 +- crates/net/peers/src/node_record.rs | 8 +- crates/net/peers/src/trusted_peer.rs | 4 +- crates/node-core/src/args/payload_builder.rs | 2 +- crates/node-core/src/args/pruning.rs | 2 +- crates/node-core/src/args/utils.rs | 8 +- crates/node-core/src/engine/skip_fcu.rs | 4 +- .../node-core/src/engine/skip_new_payload.rs | 4 +- .../src/metrics/prometheus_exporter.rs | 6 +- crates/node-core/src/node_config.rs | 4 +- crates/node/builder/src/launch/exex.rs | 2 +- crates/node/events/src/cl.rs | 8 +- crates/node/events/src/node.rs | 6 +- crates/optimism/consensus/src/lib.rs | 6 +- crates/optimism/consensus/src/validation.rs | 8 +- crates/optimism/evm/src/execute.rs | 4 +- crates/optimism/evm/src/l1.rs | 14 +- crates/optimism/node/src/engine.rs | 8 +- crates/optimism/node/src/txpool.rs | 6 +- crates/optimism/payload/src/builder.rs | 18 +- .../optimism/primitives/src/bedrock_import.rs | 4 +- crates/payload/basic/src/lib.rs | 16 +- crates/payload/builder/src/noop.rs | 2 +- crates/payload/builder/src/service.rs | 2 +- crates/payload/primitives/src/lib.rs | 16 +- crates/payload/primitives/src/traits.rs | 2 +- crates/payload/validator/src/lib.rs | 24 +-- crates/primitives-traits/src/header/mod.rs | 8 +- crates/primitives/src/alloy_compat.rs | 4 +- crates/primitives/src/block.rs | 4 +- crates/primitives/src/compression/mod.rs | 2 +- crates/primitives/src/lib.rs | 2 +- crates/primitives/src/log.rs | 2 +- crates/primitives/src/proofs.rs | 6 +- crates/primitives/src/receipt.rs | 6 +- crates/primitives/src/revm/config.rs | 12 +- crates/primitives/src/transaction/mod.rs | 30 +-- crates/primitives/src/transaction/pooled.rs | 8 +- crates/primitives/src/transaction/sidecar.rs | 10 +- .../primitives/src/transaction/signature.rs | 8 +- crates/primitives/src/transaction/tx_type.rs | 10 +- crates/prune/prune/Cargo.toml | 1 + crates/prune/prune/src/builder.rs | 2 +- crates/prune/prune/src/pruner.rs | 2 +- crates/revm/src/batch.rs | 4 +- crates/revm/src/state_change.rs | 14 +- crates/rpc/rpc-api/src/admin.rs | 3 +- crates/rpc/rpc-builder/Cargo.toml | 1 + crates/rpc/rpc-builder/tests/it/http.rs | 4 +- crates/rpc/rpc-builder/tests/it/utils.rs | 2 +- crates/rpc/rpc-engine-api/Cargo.toml | 1 + crates/rpc/rpc-engine-api/src/engine_api.rs | 6 +- crates/rpc/rpc/Cargo.toml | 1 + crates/rpc/rpc/src/admin.rs | 5 +- crates/rpc/rpc/src/eth/api/fee_history.rs | 3 +- crates/rpc/rpc/src/eth/api/mod.rs | 4 +- crates/rpc/rpc/src/eth/api/pending_block.rs | 5 +- crates/rpc/rpc/src/eth/api/server.rs | 5 +- crates/rpc/rpc/src/eth/filter.rs | 3 +- crates/rpc/rpc/src/eth/logs_utils.rs | 3 +- crates/stages/api/src/metrics/listener.rs | 2 +- crates/stages/api/src/pipeline/mod.rs | 20 +- crates/stages/api/src/pipeline/set.rs | 4 +- crates/stages/api/src/stage.rs | 2 +- crates/stages/stages/src/stages/bodies.rs | 22 +-- crates/stages/stages/src/stages/execution.rs | 12 +- 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 | 16 +- .../src/stages/index_account_history.rs | 4 +- .../src/stages/index_storage_history.rs | 4 +- crates/stages/stages/src/stages/merkle.rs | 14 +- .../stages/src/stages/sender_recovery.rs | 8 +- crates/stages/stages/src/stages/tx_lookup.rs | 8 +- .../stages/stages/src/test_utils/test_db.rs | 2 +- crates/stages/types/src/checkpoints.rs | 2 +- .../static-file/src/static_file_producer.rs | 2 +- crates/static-file/types/src/segment.rs | 4 +- .../codecs/derive/src/compact/flags.rs | 4 +- .../codecs/derive/src/compact/generator.rs | 2 +- .../storage/codecs/derive/src/compact/mod.rs | 2 +- .../codecs/derive/src/compact/structs.rs | 2 +- crates/storage/codecs/src/lib.rs | 10 +- crates/storage/db-api/src/cursor.rs | 8 +- crates/storage/db-common/src/init.rs | 8 +- .../storage/db/src/implementation/mdbx/mod.rs | 4 +- crates/storage/db/src/lockfile.rs | 2 +- crates/storage/db/src/static_file/cursor.rs | 4 +- .../db/src/tables/codecs/fuzz/inputs.rs | 2 +- crates/storage/db/src/version.rs | 2 +- crates/storage/libmdbx-rs/src/codec.rs | 2 +- crates/storage/libmdbx-rs/src/cursor.rs | 6 +- crates/storage/libmdbx-rs/src/environment.rs | 8 +- 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/cursor.rs | 12 +- crates/storage/nippy-jar/src/filter/cuckoo.rs | 2 +- crates/storage/nippy-jar/src/lib.rs | 10 +- crates/storage/nippy-jar/src/phf/fmph.rs | 4 +- crates/storage/nippy-jar/src/phf/go_fmph.rs | 4 +- crates/storage/nippy-jar/src/writer.rs | 14 +- .../src/providers/bundle_state_provider.rs | 6 +- .../provider/src/providers/consistent_view.rs | 4 +- .../provider/src/providers/database/mod.rs | 2 +- .../src/providers/database/provider.rs | 64 +++---- crates/storage/provider/src/providers/mod.rs | 4 +- .../src/providers/state/historical.rs | 6 +- .../provider/src/providers/state/latest.rs | 2 +- .../provider/src/providers/static_file/jar.rs | 4 +- .../src/providers/static_file/manager.rs | 38 ++-- .../src/providers/static_file/writer.rs | 10 +- .../storage/provider/src/test_utils/mock.rs | 4 +- crates/storage/provider/src/traits/chain.rs | 4 +- crates/storage/storage-api/src/receipts.rs | 2 +- crates/storage/storage-api/src/state.rs | 4 +- crates/tasks/src/lib.rs | 2 +- crates/tokio-util/src/event_stream.rs | 2 +- crates/transaction-pool/Cargo.toml | 1 + crates/transaction-pool/src/lib.rs | 6 +- crates/transaction-pool/src/maintain.rs | 3 +- crates/transaction-pool/src/test_utils/gen.rs | 3 +- crates/transaction-pool/src/validate/eth.rs | 10 +- crates/transaction-pool/src/validate/task.rs | 3 +- crates/trie/trie/benches/prefix_set.rs | 8 +- .../trie/trie/src/hashed_cursor/post_state.rs | 4 +- crates/trie/trie/src/node_iter.rs | 6 +- crates/trie/trie/src/prefix_set/mod.rs | 8 +- crates/trie/trie/src/proof.rs | 2 +- crates/trie/trie/src/trie.rs | 4 +- crates/trie/trie/src/updates.rs | 2 +- crates/trie/trie/src/walker.rs | 10 +- 251 files changed, 1384 insertions(+), 1099 deletions(-) create mode 100644 crates/ethereum-forks/src/display.rs create mode 100644 crates/ethereum-forks/src/forkcondition.rs diff --git a/Cargo.lock b/Cargo.lock index 98f774df9c1d..7bd86c79d6a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6453,7 +6453,6 @@ dependencies = [ "reth-basic-payload-builder", "reth-beacon-consensus", "reth-blockchain-tree", - "reth-chainspec", "reth-cli-runner", "reth-config", "reth-consensus", diff --git a/bin/reth/Cargo.toml b/bin/reth/Cargo.toml index 5e0e7d2de091..f6ec9bd7d440 100644 --- a/bin/reth/Cargo.toml +++ b/bin/reth/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] # reth -reth-chainspec.workspace = true reth-config.workspace = true reth-primitives.workspace = true reth-fs-util.workspace = true diff --git a/bin/reth/src/cli/mod.rs b/bin/reth/src/cli/mod.rs index 8750b84f543a..60792cb76b14 100644 --- a/bin/reth/src/cli/mod.rs +++ b/bin/reth/src/cli/mod.rs @@ -13,10 +13,10 @@ use crate::{ version::{LONG_VERSION, SHORT_VERSION}, }; use clap::{value_parser, Parser, Subcommand}; -use reth_chainspec::ChainSpec; use reth_cli_runner::CliRunner; use reth_db::DatabaseEnv; use reth_node_builder::{NodeBuilder, WithLaunchContext}; +use reth_primitives::ChainSpec; use reth_tracing::FileWorkerGuard; use std::{ffi::OsString, fmt, future::Future, sync::Arc}; use tracing::info; diff --git a/bin/reth/src/commands/common.rs b/bin/reth/src/commands/common.rs index 8740314aa891..ed6a92cdbc68 100644 --- a/bin/reth/src/commands/common.rs +++ b/bin/reth/src/commands/common.rs @@ -2,7 +2,6 @@ use clap::Parser; use reth_beacon_consensus::EthBeaconConsensus; -use reth_chainspec::ChainSpec; use reth_config::{config::EtlConfig, Config}; use reth_db::{init_db, open_db_read_only, DatabaseEnv}; use reth_db_common::init::init_genesis; @@ -15,7 +14,7 @@ use reth_node_core::{ }, dirs::{ChainPath, DataDirPath}, }; -use reth_primitives::B256; +use reth_primitives::{ChainSpec, B256}; use reth_provider::{providers::StaticFileProvider, ProviderFactory, StaticFileProviderFactory}; use reth_stages::{sets::DefaultStages, Pipeline, PipelineTarget}; use reth_static_file::StaticFileProducer; @@ -116,7 +115,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) } let prune_modes = config.prune.clone().map(|prune| prune.segments).unwrap_or_default(); diff --git a/bin/reth/src/commands/db/checksum.rs b/bin/reth/src/commands/db/checksum.rs index b0dbb1f7732b..6aa6b69e6d3b 100644 --- a/bin/reth/src/commands/db/checksum.rs +++ b/bin/reth/src/commands/db/checksum.rs @@ -115,7 +115,7 @@ impl TableViewer<(u64, Duration)> for ChecksumViewer<'_, DB> { total = index + 1; if total >= limit { - break; + break } } diff --git a/bin/reth/src/commands/db/diff.rs b/bin/reth/src/commands/db/diff.rs index fda004f3c34c..246b107fa4a1 100644 --- a/bin/reth/src/commands/db/diff.rs +++ b/bin/reth/src/commands/db/diff.rs @@ -298,12 +298,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/bin/reth/src/commands/db/list.rs b/bin/reth/src/commands/db/list.rs index 4689bbfdc0fa..dd1a1846acbd 100644 --- a/bin/reth/src/commands/db/list.rs +++ b/bin/reth/src/commands/db/list.rs @@ -62,7 +62,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/bin/reth/src/commands/db/mod.rs b/bin/reth/src/commands/db/mod.rs index b4e4ded41aed..fcafcc41ac09 100644 --- a/bin/reth/src/commands/db/mod.rs +++ b/bin/reth/src/commands/db/mod.rs @@ -110,7 +110,7 @@ impl Command { if !input.trim().eq_ignore_ascii_case("y") { println!("Database drop aborted!"); - return Ok(()); + return Ok(()) } } diff --git a/bin/reth/src/commands/db/tui.rs b/bin/reth/src/commands/db/tui.rs index 2c40308d87cf..746f2cd974f1 100644 --- a/bin/reth/src/commands/db/tui.rs +++ b/bin/reth/src/commands/db/tui.rs @@ -295,7 +295,7 @@ where } } - return Ok(false); + return Ok(false) } match event { diff --git a/bin/reth/src/commands/debug_cmd/execution.rs b/bin/reth/src/commands/debug_cmd/execution.rs index f37825e45c67..c1fd4cfa5fa2 100644 --- a/bin/reth/src/commands/debug_cmd/execution.rs +++ b/bin/reth/src/commands/debug_cmd/execution.rs @@ -153,7 +153,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..."); @@ -202,7 +202,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(()) } let pipeline_events = pipeline.events(); diff --git a/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs b/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs index 8b2c0e867ea9..aef62326a1a5 100644 --- a/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs +++ b/bin/reth/src/commands/debug_cmd/in_memory_merkle.rs @@ -156,7 +156,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.provider_rw()?; diff --git a/bin/reth/src/commands/debug_cmd/merkle.rs b/bin/reth/src/commands/debug_cmd/merkle.rs index 76b2e87e65fa..46e76d1da090 100644 --- a/bin/reth/src/commands/debug_cmd/merkle.rs +++ b/bin/reth/src/commands/debug_cmd/merkle.rs @@ -190,7 +190,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"); @@ -210,7 +210,7 @@ impl Command { let clean_result = merkle_stage.execute(&provider_rw, clean_input); assert!(clean_result.is_ok(), "Clean state root calculation failed"); if clean_result.unwrap().done { - break; + break } } @@ -270,7 +270,7 @@ impl Command { 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/bin/reth/src/commands/dump_genesis.rs b/bin/reth/src/commands/dump_genesis.rs index f4208584fbda..843d3d18a64b 100644 --- a/bin/reth/src/commands/dump_genesis.rs +++ b/bin/reth/src/commands/dump_genesis.rs @@ -1,7 +1,7 @@ //! Command that dumps genesis block JSON configuration to stdout use crate::args::utils::{chain_help, genesis_value_parser, SUPPORTED_CHAINS}; use clap::Parser; -use reth_chainspec::ChainSpec; +use reth_primitives::ChainSpec; use std::sync::Arc; /// Dumps genesis block JSON configuration to stdout @@ -39,7 +39,7 @@ mod tests { DumpGenesisCommand::parse_from(["reth", "--chain", chain]); assert_eq!( Ok(args.chain.chain), - chain.parse::(), + chain.parse::(), "failed to parse chain {chain}" ); } diff --git a/bin/reth/src/commands/import.rs b/bin/reth/src/commands/import.rs index 25d1864a2434..baf194714573 100644 --- a/bin/reth/src/commands/import.rs +++ b/bin/reth/src/commands/import.rs @@ -237,7 +237,7 @@ mod tests { let args: ImportCommand = ImportCommand::parse_from(["reth", "--chain", chain, "."]); assert_eq!( Ok(args.env.chain.chain), - chain.parse::(), + chain.parse::(), "failed to parse chain {chain}" ); } diff --git a/bin/reth/src/commands/import_op.rs b/bin/reth/src/commands/import_op.rs index 3e2cae23c1d9..646cd4f97232 100644 --- a/bin/reth/src/commands/import_op.rs +++ b/bin/reth/src/commands/import_op.rs @@ -83,7 +83,7 @@ impl ImportOpCommand { body.transactions.retain(|_| { if is_dup_tx(block_number) { total_filtered_out_dup_txns += 1; - return false; + return false } true }) diff --git a/bin/reth/src/commands/import_receipts_op.rs b/bin/reth/src/commands/import_receipts_op.rs index cad0aa64cd32..9d84cdd01fc0 100644 --- a/bin/reth/src/commands/import_receipts_op.rs +++ b/bin/reth/src/commands/import_receipts_op.rs @@ -154,7 +154,7 @@ where if total_decoded_receipts == 0 { error!(target: "reth::cli", "No receipts were imported, ensure the receipt file is valid and not empty"); - return Ok(()); + return Ok(()) } let total_imported_receipts = static_file_provider diff --git a/bin/reth/src/commands/node/mod.rs b/bin/reth/src/commands/node/mod.rs index 606e0de42bb2..f11cb24ce682 100644 --- a/bin/reth/src/commands/node/mod.rs +++ b/bin/reth/src/commands/node/mod.rs @@ -6,11 +6,11 @@ use crate::args::{ RpcServerArgs, TxPoolArgs, }; use clap::{value_parser, Args, Parser}; -use reth_chainspec::ChainSpec; use reth_cli_runner::CliContext; use reth_db::{init_db, DatabaseEnv}; use reth_node_builder::{NodeBuilder, WithLaunchContext}; use reth_node_core::{node_config::NodeConfig, version}; +use reth_primitives::ChainSpec; use std::{ffi::OsString, fmt, future::Future, net::SocketAddr, path::PathBuf, sync::Arc}; /// Start the node @@ -213,7 +213,7 @@ mod tests { fn parse_common_node_command_chain_args() { for chain in SUPPORTED_CHAINS { let args: NodeCommand = NodeCommand::::parse_from(["reth", "--chain", chain]); - assert_eq!(args.chain.chain, chain.parse::().unwrap()); + assert_eq!(args.chain.chain, chain.parse::().unwrap()); } } @@ -305,7 +305,7 @@ mod tests { #[cfg(not(feature = "optimism"))] // dev mode not yet supported in op-reth fn parse_dev() { let cmd = NodeCommand::::parse_from(["reth", "--dev"]); - let chain = reth_chainspec::DEV.clone(); + let chain = reth_primitives::DEV.clone(); assert_eq!(cmd.chain.chain, chain.chain); assert_eq!(cmd.chain.genesis_hash, chain.genesis_hash); assert_eq!( diff --git a/bin/reth/src/commands/p2p/mod.rs b/bin/reth/src/commands/p2p/mod.rs index 2de5a9aa5cff..b57a2f07aaba 100644 --- a/bin/reth/src/commands/p2p/mod.rs +++ b/bin/reth/src/commands/p2p/mod.rs @@ -11,13 +11,12 @@ use crate::{ use backon::{ConstantBuilder, Retryable}; use clap::{Parser, Subcommand}; use discv5::ListenConfig; -use reth_chainspec::ChainSpec; use reth_config::Config; use reth_db::create_db; use reth_network::NetworkConfigBuilder; use reth_network_p2p::bodies::client::BodiesClient; use reth_node_core::args::DatadirArgs; -use reth_primitives::BlockHashOrNumber; +use reth_primitives::{BlockHashOrNumber, ChainSpec}; use reth_provider::{providers::StaticFileProvider, ProviderFactory}; use std::{ net::{IpAddr, SocketAddrV4, SocketAddrV6}, diff --git a/bin/reth/src/commands/stage/dump/hashing_account.rs b/bin/reth/src/commands/stage/dump/hashing_account.rs index 116d4919733e..2e50a8ad6059 100644 --- a/bin/reth/src/commands/stage/dump/hashing_account.rs +++ b/bin/reth/src/commands/stage/dump/hashing_account.rs @@ -90,7 +90,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/bin/reth/src/commands/stage/dump/hashing_storage.rs b/bin/reth/src/commands/stage/dump/hashing_storage.rs index d5671aae024d..1dfd722f5099 100644 --- a/bin/reth/src/commands/stage/dump/hashing_storage.rs +++ b/bin/reth/src/commands/stage/dump/hashing_storage.rs @@ -85,7 +85,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/bin/reth/src/commands/stage/dump/merkle.rs b/bin/reth/src/commands/stage/dump/merkle.rs index 451133dc2085..fa345bb474a4 100644 --- a/bin/reth/src/commands/stage/dump/merkle.rs +++ b/bin/reth/src/commands/stage/dump/merkle.rs @@ -161,7 +161,7 @@ async fn dry_run( checkpoint: Some(StageCheckpoint::new(from)), }; if stage.execute(&provider, input)?.done { - break; + break } } diff --git a/bin/reth/src/commands/stage/run.rs b/bin/reth/src/commands/stage/run.rs index 050895e1130c..01a57fd52f4d 100644 --- a/bin/reth/src/commands/stage/run.rs +++ b/bin/reth/src/commands/stage/run.rs @@ -281,7 +281,7 @@ impl Command { } if done { - break; + break } } info!(target: "reth::cli", stage = %self.stage, time = ?start.elapsed(), "Finished stage"); diff --git a/bin/reth/src/commands/test_vectors/tables.rs b/bin/reth/src/commands/test_vectors/tables.rs index 0cd2cf04d7e9..9442f52aef4f 100644 --- a/bin/reth/src/commands/test_vectors/tables.rs +++ b/bin/reth/src/commands/test_vectors/tables.rs @@ -133,7 +133,7 @@ where let key: T::Key = strat_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/bin/reth/src/sigsegv_handler.rs b/bin/reth/src/sigsegv_handler.rs index fea00c6a617c..9e6833b75404 100644 --- a/bin/reth/src/sigsegv_handler.rs +++ b/bin/reth/src/sigsegv_handler.rs @@ -51,7 +51,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.as_slice()[0..(depth as _)] }; @@ -69,7 +69,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/bin/reth/src/utils.rs b/bin/reth/src/utils.rs index 509da8624320..ca25506a9124 100644 --- a/bin/reth/src/utils.rs +++ b/bin/reth/src/utils.rs @@ -2,7 +2,6 @@ use boyer_moore_magiclen::BMByte; use eyre::Result; -use reth_chainspec::ChainSpec; use reth_db::{RawTable, TableRawRow}; use reth_db_api::{ cursor::{DbCursorRO, DbDupCursorRO}, @@ -12,6 +11,7 @@ use reth_db_api::{ DatabaseError, }; use reth_fs_util as fs; +use reth_primitives::ChainSpec; use reth_provider::{ChainSpecProvider, ProviderFactory}; use std::{path::Path, rc::Rc, sync::Arc}; use tracing::info; @@ -68,18 +68,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(), @@ -93,12 +93,12 @@ impl DbTool { searcher.find_first_in(&key).is_some() { hits += 1; - return result(); + return result() } } None => { hits += 1; - return result(); + return result() } } } diff --git a/crates/blockchain-tree/src/block_buffer.rs b/crates/blockchain-tree/src/block_buffer.rs index ce0495986518..6ad4bd3fa1e0 100644 --- a/crates/blockchain-tree/src/block_buffer.rs +++ b/crates/blockchain-tree/src/block_buffer.rs @@ -107,7 +107,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/blockchain-tree/src/block_indices.rs b/crates/blockchain-tree/src/block_indices.rs index 420912b4088c..494b6fc98d62 100644 --- a/crates/blockchain-tree/src/block_indices.rs +++ b/crates/blockchain-tree/src/block_indices.rs @@ -154,7 +154,7 @@ impl BlockIndices { added.push(new.into()); new_hash = new_hashes.next(); } - break; + break }; let Some(new_block_value) = new_hash else { // Old canonical chain had more block than new chain. @@ -164,7 +164,7 @@ impl BlockIndices { removed.push(rem); old_hash = old_hashes.next(); } - break; + break }; // compare old and new canonical block number match new_block_value.0.cmp(&old_block_value.0) { @@ -251,7 +251,7 @@ impl BlockIndices { /// It is assumed that blocks are interconnected and that they connect to canonical chain pub fn canonicalize_blocks(&mut self, blocks: &BTreeMap) { if blocks.is_empty() { - return; + return } // Remove all blocks from canonical chain diff --git a/crates/blockchain-tree/src/blockchain_tree.rs b/crates/blockchain-tree/src/blockchain_tree.rs index 63193b815769..a3a16e954afe 100644 --- a/crates/blockchain-tree/src/blockchain_tree.rs +++ b/crates/blockchain-tree/src/blockchain_tree.rs @@ -182,7 +182,7 @@ where ) -> Result, InsertBlockErrorKind> { // check if block is canonical if self.is_block_hash_canonical(&block.hash)? { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) } let last_finalized_block = self.block_indices().last_finalized_block(); @@ -190,18 +190,18 @@ where if block.number <= last_finalized_block { // check if block is inside database if self.externals.provider_factory.provider()?.block_number(block.hash)?.is_some() { - return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))); + return Ok(Some(BlockStatus::Valid(BlockAttachment::Canonical))) } return Err(BlockchainTreeError::PendingBlockIsFinalized { last_finalized: last_finalized_block, } - .into()); + .into()) } // is block inside chain if let Some(attachment) = self.is_block_inside_sidechain(&block) { - return Ok(Some(BlockStatus::Valid(attachment))); + return Ok(Some(BlockStatus::Valid(attachment))) } // check if block is disconnected @@ -209,7 +209,7 @@ where return Ok(Some(BlockStatus::Disconnected { head: self.state.block_indices.canonical_tip(), missing_ancestor: block.parent_num_hash(), - })); + })) } Ok(None) @@ -285,7 +285,7 @@ where let Some((first_pending_block_number, _)) = parent_block_hashes.first_key_value() else { debug!(target: "blockchain_tree", ?chain_id, "No block hashes stored"); - return None; + return None }; let canonical_chain = canonical_chain .iter() @@ -295,7 +295,7 @@ where // get canonical fork. let canonical_fork = self.canonical_fork(chain_id)?; - return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }); + return Some(ExecutionData { execution_outcome, parent_block_hashes, canonical_fork }) } // check if there is canonical block @@ -305,7 +305,7 @@ where canonical_fork: ForkBlock { number: canonical_number, hash: block_hash }, execution_outcome: ExecutionOutcome::default(), parent_block_hashes: canonical_chain.inner().clone(), - }); + }) } None @@ -328,12 +328,12 @@ where // check if block parent can be found in any side chain. if let Some(chain_id) = self.block_indices().get_block_chain_id(&parent.hash) { // found parent in side tree, try to insert there - return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind); + return self.try_insert_block_into_side_chain(block, chain_id, block_validation_kind) } // if not found, check if the parent can be found inside canonical chain. if self.is_block_hash_canonical(&parent.hash)? { - return self.try_append_canonical_chain(block.clone(), block_validation_kind); + return self.try_append_canonical_chain(block.clone(), block_validation_kind) } // this is another check to ensure that if the block points to a canonical block its block @@ -347,7 +347,7 @@ where parent_block_number: canonical_parent_number, block_number: block.number, } - .into()); + .into()) } } @@ -408,7 +408,7 @@ where return Err(BlockExecutionError::Validation(BlockValidationError::BlockPreMerge { hash: block.hash(), }) - .into()); + .into()) } let parent_header = provider @@ -546,7 +546,7 @@ where } else { // if there is no fork block that point to other chains, break the loop. // it means that this fork joins to canonical block. - break; + break } } hashes @@ -567,9 +567,9 @@ where // get fork block chain if let Some(fork_chain_id) = self.block_indices().get_block_chain_id(&fork.hash) { chain_id = fork_chain_id; - continue; + continue } - break; + break } (self.block_indices().canonical_hash(&fork.number) == Some(fork.hash)).then_some(fork) } @@ -684,7 +684,7 @@ where pub fn buffer_block(&mut self, block: SealedBlockWithSenders) -> Result<(), InsertBlockError> { // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)); + return Err(InsertBlockError::consensus_error(err, block.block)) } self.state.buffered_blocks.insert_block(block); @@ -702,17 +702,17 @@ where "Failed to validate total difficulty for block {}: {e}", block.header.hash() ); - return Err(e); + return Err(e) } if let Err(e) = self.externals.consensus.validate_header(block) { error!(?block, "Failed to validate header {}: {e}", block.header.hash()); - return Err(e); + return Err(e) } if let Err(e) = self.externals.consensus.validate_block_pre_execution(block) { error!(?block, "Failed to validate block {}: {e}", block.header.hash()); - return Err(e); + return Err(e) } Ok(()) @@ -737,7 +737,7 @@ where Some(BlockAttachment::Canonical) } else { Some(BlockAttachment::HistoricalFork) - }; + } } None } @@ -778,7 +778,7 @@ where // validate block consensus rules if let Err(err) = self.validate_block(&block) { - return Err(InsertBlockError::consensus_error(err, block.block)); + return Err(InsertBlockError::consensus_error(err, block.block)) } let status = self @@ -985,7 +985,7 @@ where } if header.is_none() && self.sidechain_block_by_hash(*hash).is_some() { - return Ok(None); + return Ok(None) } if header.is_none() { @@ -1048,18 +1048,18 @@ where { return Err(CanonicalError::from(BlockValidationError::BlockPreMerge { hash: block_hash, - })); + })) } let head = self.state.block_indices.canonical_tip(); - return Ok(CanonicalOutcome::AlreadyCanonical { header, head }); + return Ok(CanonicalOutcome::AlreadyCanonical { header, head }) } let Some(chain_id) = self.block_indices().get_block_chain_id(&block_hash) else { debug!(target: "blockchain_tree", ?block_hash, "Block hash not found in block indices"); return Err(CanonicalError::from(BlockchainTreeError::BlockHashNotFoundInChain { block_hash, - })); + })) }; // we are splitting chain at the block hash that we want to make canonical @@ -1245,7 +1245,7 @@ where block_number: tip.number, block_hash: tip.hash(), })) - .into()); + .into()) } self.metrics.trie_updates_insert_recomputed.increment(1); trie_updates @@ -1274,7 +1274,7 @@ where pub fn unwind(&mut self, unwind_to: BlockNumber) -> Result<(), CanonicalError> { // nothing to be done if unwind_to is higher then the tip if self.block_indices().canonical_tip().number <= unwind_to { - return Ok(()); + return Ok(()) } // revert `N` blocks from current canonical chain and put them inside BlockchainTree let old_canon_chain = self.revert_canonical_from_database(unwind_to)?; @@ -1316,7 +1316,7 @@ where "Reverting optimistic canonical chain to block {}", revert_until ); - return Err(CanonicalError::OptimisticTargetRevert(revert_until)); + return Err(CanonicalError::OptimisticTargetRevert(revert_until)) } // read data that is needed for new sidechain diff --git a/crates/blockchain-tree/src/bundle.rs b/crates/blockchain-tree/src/bundle.rs index 90a03230de2d..01d1d717f211 100644 --- a/crates/blockchain-tree/src/bundle.rs +++ b/crates/blockchain-tree/src/bundle.rs @@ -25,7 +25,7 @@ impl<'a> ExecutionDataProvider for BundleStateDataRef<'a> { fn block_hash(&self, block_number: BlockNumber) -> Option { let block_hash = self.sidechain_block_hashes.get(&block_number).cloned(); if block_hash.is_some() { - return block_hash; + return block_hash } self.canonical_block_hashes.get(&block_number).cloned() diff --git a/crates/blockchain-tree/src/chain.rs b/crates/blockchain-tree/src/chain.rs index d53009b76609..613cb59cdd34 100644 --- a/crates/blockchain-tree/src/chain.rs +++ b/crates/blockchain-tree/src/chain.rs @@ -238,7 +238,7 @@ impl AppendableChain { return Err(ConsensusError::BodyStateRootDiff( GotExpected { got: state_root, expected: block.state_root }.into(), ) - .into()); + .into()) } tracing::debug!( diff --git a/crates/blockchain-tree/src/state.rs b/crates/blockchain-tree/src/state.rs index 72d38f1fce20..e44e1aae552a 100644 --- a/crates/blockchain-tree/src/state.rs +++ b/crates/blockchain-tree/src/state.rs @@ -87,7 +87,7 @@ impl TreeState { /// Inserts a chain into the tree and builds the block indices. pub(crate) fn insert_chain(&mut self, chain: AppendableChain) -> Option { if chain.is_empty() { - return None; + return None } let chain_id = self.next_id(); diff --git a/crates/chainspec/src/spec.rs b/crates/chainspec/src/spec.rs index e0944330be75..2462da93a12c 100644 --- a/crates/chainspec/src/spec.rs +++ b/crates/chainspec/src/spec.rs @@ -691,7 +691,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.is_fork_active_at_timestamp(*fork, timestamp) { - return *params; + return *params } } @@ -710,7 +710,7 @@ impl ChainSpec { // given timestamp. for (fork, params) in bf_params.iter().rev() { if self.is_fork_active_at_block(*fork, block_number) { - return *params; + return *params } } @@ -896,7 +896,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 } } } } @@ -917,7 +917,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 } } } @@ -932,7 +932,7 @@ impl ChainSpec { // to satisfy every timestamp ForkCondition, we find the last ForkCondition::Block // if one exists, and include its block_num in the returned Head if let Some(last_block_num) = self.last_block_fork_before_merge_or_timestamp() { - return Head { timestamp, number: last_block_num, ..Default::default() }; + return Head { timestamp, number: last_block_num, ..Default::default() } } Head { timestamp, ..Default::default() } } @@ -960,17 +960,17 @@ impl ChainSpec { ForkCondition::TTD { fork_block, .. } => { // handle Sepolia merge netsplit case if fork_block.is_some() { - return *fork_block; + return *fork_block } // ensure curr_cond is indeed ForkCondition::Block and return block_num if let ForkCondition::Block(block_num) = curr_cond { - return Some(block_num); + return Some(block_num) } } ForkCondition::Timestamp(_) => { // ensure curr_cond is indeed ForkCondition::Block and return block_num if let ForkCondition::Block(block_num) = curr_cond { - return Some(block_num); + return Some(block_num) } } ForkCondition::Block(_) | ForkCondition::Never => continue, diff --git a/crates/config/src/config.rs b/crates/config/src/config.rs index 95fd06a76aec..f458ef41646f 100644 --- a/crates/config/src/config.rs +++ b/crates/config/src/config.rs @@ -47,7 +47,7 @@ impl Config { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!("reth config file extension must be '{EXTENSION}'"), - )); + )) } confy::store_path(path, self).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)) } diff --git a/crates/consensus/auto-seal/src/client.rs b/crates/consensus/auto-seal/src/client.rs index 11d511ced068..b9befa73857b 100644 --- a/crates/consensus/auto-seal/src/client.rs +++ b/crates/consensus/auto-seal/src/client.rs @@ -41,7 +41,7 @@ impl AutoSealClient { hash.into() } else { warn!(target: "consensus::auto", num, "no matching block found"); - return headers; + return headers } } }; @@ -58,7 +58,7 @@ impl AutoSealClient { } headers.push(header); } else { - break; + break } } @@ -75,7 +75,7 @@ impl AutoSealClient { if let Some(body) = storage.bodies.get(&hash).cloned() { bodies.push(body); } else { - break; + break } } diff --git a/crates/consensus/auto-seal/src/mode.rs b/crates/consensus/auto-seal/src/mode.rs index df9846f0a800..2ff918af63dc 100644 --- a/crates/consensus/auto-seal/src/mode.rs +++ b/crates/consensus/auto-seal/src/mode.rs @@ -102,7 +102,7 @@ impl FixedBlockTimeMiner { { if self.interval.poll_tick(cx).is_ready() { // drain the pool - return Poll::Ready(pool.best_transactions().collect()); + return Poll::Ready(pool.best_transactions().collect()) } Poll::Pending } @@ -141,7 +141,7 @@ impl ReadyTransactionMiner { } if self.has_pending_txs == Some(false) { - return Poll::Pending; + return Poll::Pending } let transactions = pool.best_transactions().take(self.max_transactions).collect::>(); @@ -150,7 +150,7 @@ impl ReadyTransactionMiner { self.has_pending_txs = Some(transactions.len() >= self.max_transactions); if transactions.is_empty() { - return Poll::Pending; + return Poll::Pending } Poll::Ready(transactions) diff --git a/crates/consensus/auto-seal/src/task.rs b/crates/consensus/auto-seal/src/task.rs index 39491a65f2cb..856d02631cb0 100644 --- a/crates/consensus/auto-seal/src/task.rs +++ b/crates/consensus/auto-seal/src/task.rs @@ -103,7 +103,7 @@ where if this.insert_task.is_none() { if this.queued.is_empty() { // nothing to insert - break; + break } // ready to queue in new insert task @@ -170,18 +170,18 @@ where ForkchoiceStatus::Valid => break, ForkchoiceStatus::Invalid => { error!(target: "consensus::auto", ?fcu_response, "Forkchoice update returned invalid response"); - return None; + return None } ForkchoiceStatus::Syncing => { debug!(target: "consensus::auto", ?fcu_response, "Forkchoice update returned SYNCING, waiting for VALID"); // wait for the next fork choice update - continue; + continue } } } Err(err) => { error!(target: "consensus::auto", %err, "Autoseal fork choice update failed"); - return None; + return None } } } @@ -207,7 +207,7 @@ where } Poll::Pending => { this.insert_task = Some(fut); - break; + break } } } diff --git a/crates/consensus/beacon/src/engine/hooks/controller.rs b/crates/consensus/beacon/src/engine/hooks/controller.rs index 55c1b2aac6e2..bd5c8a9e2b91 100644 --- a/crates/consensus/beacon/src/engine/hooks/controller.rs +++ b/crates/consensus/beacon/src/engine/hooks/controller.rs @@ -74,7 +74,7 @@ impl EngineHooksController { self.hooks.push_back(hook); } - return Poll::Ready(Ok(result)); + return Poll::Ready(Ok(result)) } Poll::Pending => { self.active_db_write_hook = Some(hook); @@ -141,7 +141,7 @@ impl EngineHooksController { db_write_active || args.finalized_block_number.is_none()) { - return Poll::Pending; + return Poll::Pending } if let Poll::Ready(event) = hook.poll(cx, args)? { @@ -155,7 +155,7 @@ impl EngineHooksController { "Polled next hook" ); - return Poll::Ready(Ok(result)); + return Poll::Ready(Ok(result)) } else { debug!(target: "consensus::engine::hooks", hook = hook.name(), "Next hook is not ready"); } diff --git a/crates/consensus/beacon/src/engine/hooks/static_file.rs b/crates/consensus/beacon/src/engine/hooks/static_file.rs index fdb36fc9b775..43c47ef41b02 100644 --- a/crates/consensus/beacon/src/engine/hooks/static_file.rs +++ b/crates/consensus/beacon/src/engine/hooks/static_file.rs @@ -88,12 +88,12 @@ impl StaticFileHook { StaticFileProducerState::Idle(static_file_producer) => { let Some(static_file_producer) = static_file_producer.take() else { trace!(target: "consensus::engine::hooks::static_file", "StaticFileProducer is already running but the state is idle"); - return Ok(None); + return Ok(None) }; let Some(locked_static_file_producer) = static_file_producer.try_lock_arc() else { trace!(target: "consensus::engine::hooks::static_file", "StaticFileProducer lock is already taken"); - return Ok(None); + return Ok(None) }; let targets = @@ -138,7 +138,7 @@ impl EngineHook for StaticFileHook { ) -> Poll> { let Some(finalized_block_number) = ctx.finalized_block_number else { trace!(target: "consensus::engine::hooks::static_file", ?ctx, "Finalized block number is not available"); - return Poll::Pending; + return Poll::Pending }; // Try to spawn a static_file_producer diff --git a/crates/consensus/beacon/src/engine/invalid_headers.rs b/crates/consensus/beacon/src/engine/invalid_headers.rs index d98df18b2984..2a37c60014da 100644 --- a/crates/consensus/beacon/src/engine/invalid_headers.rs +++ b/crates/consensus/beacon/src/engine/invalid_headers.rs @@ -39,7 +39,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.clone()); + return Some(entry.header.clone()) } } // if we get here, the entry has been hit too many times, so we evict it diff --git a/crates/consensus/beacon/src/engine/mod.rs b/crates/consensus/beacon/src/engine/mod.rs index c1092b0f3a1e..29c5c6a1c124 100644 --- a/crates/consensus/beacon/src/engine/mod.rs +++ b/crates/consensus/beacon/src/engine/mod.rs @@ -357,21 +357,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.sync.is_pipeline_active() { // We can only process new forkchoice updates if the pipeline is idle, since it requires // exclusive access to the database trace!(target: "consensus::engine", "Pipeline is syncing, skipping forkchoice update"); - return Ok(Some(OnForkChoiceUpdated::syncing())); + return Ok(Some(OnForkChoiceUpdated::syncing())) } Ok(None) @@ -460,7 +460,7 @@ where current_head_num=?head.number, "[Optimism] Allowing beacon reorg to old head" ); - return true; + return true } // 2. Client software MAY skip an update of the forkchoice state and MUST NOT begin a @@ -604,7 +604,7 @@ where inconsistent_stage_checkpoint = stage_checkpoint, "Pipeline sync progress is inconsistent" ); - return Ok(self.blockchain.block_hash(first_stage_checkpoint)?); + return Ok(self.blockchain.block_hash(first_stage_checkpoint)?) } } @@ -682,7 +682,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 @@ -698,7 +698,7 @@ where // However, optimism chains will do this. The risk of a reorg is however // low. debug!(target: "consensus::engine", hash=?state.head_block_hash, "Setting head hash as an optimistic pipeline target."); - return Some(state.head_block_hash); + return Some(state.head_block_hash) } Ok(Some(_)) => { // we're fully synced to the finalized block @@ -738,7 +738,7 @@ where ) -> ProviderResult> { // Check if parent exists in side chain or in canonical chain. if self.blockchain.find_block_by_hash(parent_hash, BlockSource::Any)?.is_some() { - return Ok(Some(parent_hash)); + return Ok(Some(parent_hash)) } // iterate over ancestors in the invalid cache @@ -754,7 +754,7 @@ where if current_header.is_none() && self.blockchain.find_block_by_hash(current_hash, BlockSource::Any)?.is_some() { - return Ok(Some(current_hash)); + return Ok(Some(current_hash)) } } Ok(None) @@ -854,7 +854,7 @@ where if !state.finalized_block_hash.is_zero() && !self.blockchain.is_canonical(state.finalized_block_hash)? { - return Ok(Some(OnForkChoiceUpdated::invalid_state())); + return Ok(Some(OnForkChoiceUpdated::invalid_state())) } // Finalized block is consistent, so update it in the canon chain tracker. @@ -868,7 +868,7 @@ where if !state.safe_block_hash.is_zero() && !self.blockchain.is_canonical(state.safe_block_hash)? { - return Ok(Some(OnForkChoiceUpdated::invalid_state())); + return Ok(Some(OnForkChoiceUpdated::invalid_state())) } // Safe block is consistent, so update it in the canon chain tracker. @@ -929,7 +929,7 @@ where if !safe_block_hash.is_zero() { if self.blockchain.safe_block_hash()? == Some(safe_block_hash) { // nothing to update - return Ok(()); + return Ok(()) } let safe = self @@ -949,7 +949,7 @@ where if !finalized_block_hash.is_zero() { if self.blockchain.finalized_block_hash()? == Some(finalized_block_hash) { // nothing to update - return Ok(()); + return Ok(()) } let finalized = self @@ -981,7 +981,7 @@ where if let Some(invalid_ancestor) = self.check_invalid_ancestor(state.head_block_hash)? { warn!(target: "consensus::engine", %error, ?state, ?invalid_ancestor, head=?state.head_block_hash, "Failed to canonicalize the head hash, head is also considered invalid"); debug!(target: "consensus::engine", head=?state.head_block_hash, current_error=%error, "Head was previously marked as invalid"); - return Ok(invalid_ancestor); + return Ok(invalid_ancestor) } match &error { @@ -990,7 +990,7 @@ where return Ok(PayloadStatus::from_status(PayloadStatusEnum::Invalid { validation_error: error.to_string(), }) - .with_latest_valid_hash(B256::ZERO)); + .with_latest_valid_hash(B256::ZERO)) } CanonicalError::BlockchainTree(BlockchainTreeError::BlockHashNotFoundInChain { .. @@ -1001,7 +1001,7 @@ where } CanonicalError::OptimisticTargetRevert(block_number) => { self.sync.set_pipeline_sync_target(PipelineTarget::Unwind(*block_number)); - return Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing)); + return Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing)) } _ => { warn!(target: "consensus::engine", %error, ?state, "Failed to canonicalize the head hash"); @@ -1125,7 +1125,7 @@ where }; let status = PayloadStatusEnum::from(error); - return Ok(Either::Left(PayloadStatus::new(status, latest_valid_hash))); + return Ok(Either::Left(PayloadStatus::new(status, latest_valid_hash))) } }; @@ -1161,7 +1161,7 @@ where // begin a payload build process. In such an event, the forkchoiceState update MUST NOT // be rolled back. if attrs.timestamp() <= head.timestamp { - return OnForkChoiceUpdated::invalid_payload_attributes(); + return OnForkChoiceUpdated::invalid_payload_attributes() } // 8. Client software MUST begin a payload build process building on top of @@ -1257,7 +1257,7 @@ where |error| InsertBlockError::new(block, InsertBlockErrorKind::Provider(error)), )? { - return Ok(status); + return Ok(status) } // not known to be invalid, but we don't know anything else @@ -1293,7 +1293,7 @@ where // threshold self.sync.set_pipeline_sync_target(target.into()); // we can exit early here because the pipeline will take care of syncing - return; + return } // continue downloading the missing parent @@ -1424,7 +1424,7 @@ where } EngineSyncEvent::PipelineTaskDropped => { error!(target: "consensus::engine", "Failed to receive spawned pipeline"); - return Err(BeaconConsensusEngineError::PipelineChannelClosed); + return Err(BeaconConsensusEngineError::PipelineChannelClosed) } }; @@ -1441,7 +1441,7 @@ where warn!(target: "consensus::engine", invalid_hash=?bad_block.hash(), invalid_number=?bad_block.number, "Bad block detected in unwind"); // update the `invalid_headers` cache with the new invalid header self.invalid_headers.insert(*bad_block); - return Ok(()); + return Ok(()) } let sync_target_state = match self.forkchoice_state_tracker.sync_target_state() { @@ -1450,7 +1450,7 @@ where // This is only possible if the node was run with `debug.tip` // argument and without CL. warn!(target: "consensus::engine", "No fork choice state available"); - return Ok(()); + return Ok(()) } }; @@ -1459,7 +1459,7 @@ where self.blockchain.update_block_hashes_and_clear_buffered()?; self.blockchain.connect_buffered_blocks_to_canonical_hashes()?; // We are on an optimistic syncing process, better to wait for the next FCU to handle - return Ok(()); + return Ok(()) } // Next, we check if we need to schedule another pipeline run or transition @@ -1491,7 +1491,7 @@ where head = %sync_target_state.head_block_hash, "Current head has an invalid ancestor" ); - return Ok(()); + return Ok(()) } // get the block number of the finalized block, if we have it @@ -1576,7 +1576,7 @@ where self.blockchain.connect_buffered_blocks_to_canonical_hashes() { error!(target: "consensus::engine", %error, "Error connecting buffered blocks to canonical hashes on hook result"); - return Err(RethError::Canonical(error).into()); + return Err(RethError::Canonical(error).into()) } } } @@ -1610,14 +1610,14 @@ where if self.sync.has_reached_max_block(tip_number) { // Terminate the sync early if it's reached // the maximum user configured block. - return Ok(EngineEventOutcome::ReachedMaxBlock); + return Ok(EngineEventOutcome::ReachedMaxBlock) } } } Err(error) => { let _ = tx.send(Err(RethError::Canonical(error.clone()))); if error.is_fatal() { - return Err(RethError::Canonical(error)); + return Err(RethError::Canonical(error)) } } }; @@ -1643,7 +1643,7 @@ where // TODO: revise if any error should be considered fatal at this point. let _ = tx.send(Err(BeaconOnNewPayloadError::Internal(Box::new(error)))); - return Ok(EngineEventOutcome::Processed); + return Ok(EngineEventOutcome::Processed) } // If the error was due to an invalid payload, the payload is added to the @@ -1677,7 +1677,7 @@ where tx, }, ); - return Ok(EngineEventOutcome::Processed); + return Ok(EngineEventOutcome::Processed) } } // block was successfully inserted, so we can cancel the full block @@ -1696,7 +1696,7 @@ where let response = Err(BeaconOnNewPayloadError::Internal(Box::new(error.clone()))); let _ = tx.send(response); - return Err(RethError::Canonical(error)); + return Err(RethError::Canonical(error)) } else if error.optimistic_revert_block_number().is_some() { // engine already set the pipeline unwind target on // `try_make_sync_target_canonical` @@ -1813,7 +1813,7 @@ where this.hooks.poll_active_db_write_hook(cx, this.current_engine_hook_context()?)? { this.on_hook_result(result)?; - continue; + continue } // Process any blockchain tree action result as set forth during engine message @@ -1824,12 +1824,12 @@ where Ok(EngineEventOutcome::ReachedMaxBlock) => return Poll::Ready(Ok(())), Err(error) => { error!(target: "consensus::engine", %error, "Encountered fatal error"); - return Poll::Ready(Err(error.into())); + return Poll::Ready(Err(error.into())) } }; // Blockchain tree action handler might set next action to take. - continue; + continue } // If the db write hook is no longer active and we have a pending forkchoice update, @@ -1839,7 +1839,7 @@ where this.set_blockchain_tree_action( BlockchainTreeAction::MakeForkchoiceHeadCanonical { state, attrs, tx }, ); - continue; + continue } } @@ -1872,12 +1872,12 @@ where this.blockchain.on_transition_configuration_exchanged(); } } - continue; + continue } // Both running hook with db write access and engine messages are pending, // proceed to other polls - break; + break } // process sync events if any @@ -1891,7 +1891,7 @@ where // this could have taken a while, so we start the next cycle to handle any new // engine messages - continue 'main; + continue 'main } // at this point, all engine messages and sync events are fully drained @@ -1909,13 +1909,13 @@ where // ensure we're polling until pending while also checking for new engine // messages before polling the next hook - continue 'main; + continue 'main } } // incoming engine messages and sync events are drained, so we can yield back // control - return Poll::Pending; + return Poll::Pending } } } @@ -2064,7 +2064,7 @@ mod tests { result, Err(BeaconConsensusEngineError::Pipeline(n)) if matches!(*n.as_ref(), PipelineError::Stage(StageError::ChannelClosed)) ); - break; + break } Err(TryRecvError::Empty) => { let _ = env diff --git a/crates/consensus/beacon/src/engine/sync.rs b/crates/consensus/beacon/src/engine/sync.rs index 73fac64cf27e..76a6d0e81552 100644 --- a/crates/consensus/beacon/src/engine/sync.rs +++ b/crates/consensus/beacon/src/engine/sync.rs @@ -176,7 +176,7 @@ where /// given hash. pub(crate) fn download_full_block(&mut self, hash: B256) -> bool { if self.is_inflight_request(hash) { - return false; + return false } trace!( target: "consensus::engine::sync", @@ -210,7 +210,7 @@ where "Pipeline target cannot be zero hash." ); // precaution to never sync to the zero hash - return; + return } self.pending_pipeline_target = Some(target); } @@ -290,14 +290,14 @@ where pub(crate) 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_idle() { // advance the pipeline if let Poll::Ready(event) = self.poll_pipeline(cx) { - return Poll::Ready(event); + return Poll::Ready(event) } } @@ -335,10 +335,10 @@ where if peek.0 .0.hash() == block.0 .0.hash() { PeekMut::pop(peek); } else { - break; + break } } - return Poll::Ready(EngineSyncEvent::FetchedFullBlock(block.0 .0)); + return Poll::Ready(EngineSyncEvent::FetchedFullBlock(block.0 .0)) } Poll::Pending diff --git a/crates/consensus/beacon/src/engine/test_utils.rs b/crates/consensus/beacon/src/engine/test_utils.rs index 967296e74537..f58063d3ef58 100644 --- a/crates/consensus/beacon/src/engine/test_utils.rs +++ b/crates/consensus/beacon/src/engine/test_utils.rs @@ -85,7 +85,7 @@ impl TestEnv { loop { let result = self.send_new_payload(payload.clone(), cancun_fields.clone()).await?; if !result.is_syncing() { - return Ok(result); + return Ok(result) } } } @@ -106,7 +106,7 @@ impl TestEnv { loop { let result = self.engine_handle.fork_choice_updated(state, None).await?; if !result.is_syncing() { - return Ok(result); + return Ok(result) } } } diff --git a/crates/consensus/common/src/validation.rs b/crates/consensus/common/src/validation.rs index dba5202ad69f..31bde166ece0 100644 --- a/crates/consensus/common/src/validation.rs +++ b/crates/consensus/common/src/validation.rs @@ -18,7 +18,7 @@ pub fn validate_header_gas(header: &SealedHeader) -> Result<(), ConsensusError> return Err(ConsensusError::HeaderGasUsedExceedsGasLimit { gas_used: header.gas_used, gas_limit: header.gas_limit, - }); + }) } Ok(()) } @@ -32,7 +32,7 @@ pub fn validate_header_base_fee( if chain_spec.fork(Hardfork::London).active_at_block(header.number) && header.base_fee_per_gas.is_none() { - return Err(ConsensusError::BaseFeeMissing); + return Err(ConsensusError::BaseFeeMissing) } Ok(()) } @@ -52,12 +52,12 @@ pub fn validate_block_pre_execution( if block.header.ommers_hash != ommers_hash { return Err(ConsensusError::BodyOmmersHashDiff( GotExpected { got: ommers_hash, expected: block.header.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 @@ -70,7 +70,7 @@ pub fn validate_block_pre_execution( if withdrawals_root != *header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: *header_withdrawals_root }.into(), - )); + )) } } @@ -84,7 +84,7 @@ pub fn validate_block_pre_execution( return Err(ConsensusError::BlobGasUsedDiff(GotExpected { got: header_blob_gas_used, expected: total_blob_gas, - })); + })) } } @@ -97,7 +97,7 @@ pub fn validate_block_pre_execution( if requests_root != *header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected { got: requests_root, expected: *header_requests_root }.into(), - )); + )) } } @@ -117,21 +117,21 @@ pub fn validate_4844_header_standalone(header: &SealedHeader) -> Result<(), Cons let excess_blob_gas = header.excess_blob_gas.ok_or(ConsensusError::ExcessBlobGasMissing)?; if header.parent_beacon_block_root.is_none() { - return Err(ConsensusError::ParentBeaconBlockRootMissing); + return Err(ConsensusError::ParentBeaconBlockRootMissing) } if blob_gas_used > MAX_DATA_GAS_PER_BLOCK { return Err(ConsensusError::BlobGasUsedExceedsMaxBlobGasPerBlock { blob_gas_used, max_blob_gas_per_block: MAX_DATA_GAS_PER_BLOCK, - }); + }) } if blob_gas_used % DATA_GAS_PER_BLOB != 0 { return Err(ConsensusError::BlobGasUsedNotMultipleOfBlobGasPerBlob { blob_gas_used, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }); + }) } // `excess_blob_gas` must also be a multiple of `DATA_GAS_PER_BLOB`. This will be checked later @@ -140,7 +140,7 @@ pub fn validate_4844_header_standalone(header: &SealedHeader) -> Result<(), Cons return Err(ConsensusError::ExcessBlobGasNotMultipleOfBlobGasPerBlob { excess_blob_gas, blob_gas_per_blob: DATA_GAS_PER_BLOB, - }); + }) } Ok(()) @@ -173,13 +173,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(()) @@ -209,7 +209,7 @@ pub fn validate_against_parent_eip1559_base_fee( return Err(ConsensusError::BaseFeeDiff(GotExpected { expected: expected_base_fee, got: base_fee, - })); + })) } } @@ -226,7 +226,7 @@ pub fn validate_against_parent_timestamp( return Err(ConsensusError::TimestampIsInPast { parent_timestamp: parent.timestamp, timestamp: header.timestamp, - }); + }) } Ok(()) } @@ -249,7 +249,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)?; @@ -260,7 +260,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/debug-client/src/providers/etherscan.rs b/crates/consensus/debug-client/src/providers/etherscan.rs index e7d1234c0069..e189913d1264 100644 --- a/crates/consensus/debug-client/src/providers/etherscan.rs +++ b/crates/consensus/debug-client/src/providers/etherscan.rs @@ -46,7 +46,7 @@ impl BlockProvider for EtherscanBlockProvider { Ok(block) => block, Err(err) => { warn!(target: "consensus::debug-client", %err, "failed to fetch a block from Etherscan"); - continue; + continue } }; let block_number = block.header.number.unwrap(); diff --git a/crates/e2e-test-utils/src/node.rs b/crates/e2e-test-utils/src/node.rs index e3e873d77d66..524a5d5562be 100644 --- a/crates/e2e-test-utils/src/node.rs +++ b/crates/e2e-test-utils/src/node.rs @@ -173,7 +173,7 @@ where if check { if let Some(latest_block) = self.inner.provider.block_by_number(number)? { assert_eq!(latest_block.hash_slow(), expected_block_hash); - break; + break } if wait_finish_checkpoint { panic!("Finish checkpoint matches, but could not fetch block."); @@ -188,7 +188,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 } } } @@ -221,7 +221,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.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 47f4134d7fe8..828bc5f32c4f 100644 --- a/crates/e2e-test-utils/src/payload.rs +++ b/crates/e2e-test-utils/src/payload.rs @@ -50,9 +50,9 @@ impl PayloadTestContext { let payload = self.payload_builder.best_payload(payload_id).await.unwrap().unwrap(); if payload.block().body.is_empty() { tokio::time::sleep(std::time::Duration::from_millis(20)).await; - continue; + continue } - break; + break } } diff --git a/crates/ethereum-forks/src/display.rs b/crates/ethereum-forks/src/display.rs new file mode 100644 index 000000000000..3c1424083638 --- /dev/null +++ b/crates/ethereum-forks/src/display.rs @@ -0,0 +1,181 @@ +#[cfg(not(feature = "std"))] +use alloc::{ + collections::BTreeMap, + format, + string::{String, ToString}, + vec::Vec, +}; + +use crate::{ForkCondition, Hardfork}; +#[cfg(feature = "std")] +use std::collections::BTreeMap; + +/// A container to pretty-print a hardfork. +/// +/// The fork is formatted depending on its fork condition: +/// +/// - Block and timestamp based forks are formatted in the same manner (`{name} <({eip})> +/// @{condition}`) +/// - TTD based forks are formatted separately as `{name} <({eip})> @{ttd} (network is known +/// to be merged)` +/// +/// An optional EIP can be attached to the fork to display as well. This should generally be in the +/// form of just `EIP-x`, e.g. `EIP-1559`. +#[derive(Debug)] +struct DisplayFork { + /// The name of the hardfork (e.g. Frontier) + name: String, + /// The fork condition + activated_at: ForkCondition, + /// An optional EIP (e.g. `EIP-1559`). + eip: Option, +} + +impl core::fmt::Display for DisplayFork { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let name_with_eip = if let Some(eip) = &self.eip { + format!("{} ({})", self.name, eip) + } else { + self.name.clone() + }; + + match self.activated_at { + ForkCondition::Block(at) | ForkCondition::Timestamp(at) => { + write!(f, "{name_with_eip:32} @{at}")?; + } + ForkCondition::TTD { fork_block, total_difficulty } => { + write!( + f, + "{:32} @{} ({})", + name_with_eip, + total_difficulty, + if fork_block.is_some() { + "network is known to be merged" + } else { + "network is not known to be merged" + } + )?; + } + ForkCondition::Never => unreachable!(), + } + + Ok(()) + } +} + +// Todo: This will result in dep cycle so currently commented out +// # Examples +// +// ``` +// # use reth_chainspec::MAINNET; +// println!("{}", MAINNET.display_hardforks()); +// ``` +// +/// A container for pretty-printing a list of hardforks. +/// +/// An example of the output: +/// +/// ```text +/// Pre-merge hard forks (block based): +// - Frontier @0 +// - Homestead @1150000 +// - Dao @1920000 +// - Tangerine @2463000 +// - SpuriousDragon @2675000 +// - Byzantium @4370000 +// - Constantinople @7280000 +// - Petersburg @7280000 +// - Istanbul @9069000 +// - MuirGlacier @9200000 +// - Berlin @12244000 +// - London @12965000 +// - ArrowGlacier @13773000 +// - GrayGlacier @15050000 +// Merge hard forks: +// - Paris @58750000000000000000000 (network is known to be merged) +// Post-merge hard forks (timestamp based): +// - Shanghai @1681338455 +/// ``` +#[derive(Debug)] +pub struct DisplayHardforks { + /// A list of pre-merge (block based) hardforks + pre_merge: Vec, + /// A list of merge (TTD based) hardforks + with_merge: Vec, + /// A list of post-merge (timestamp based) hardforks + post_merge: Vec, +} + +impl core::fmt::Display for DisplayHardforks { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + fn format( + header: &str, + forks: &[DisplayFork], + next_is_empty: bool, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + writeln!(f, "{header}:")?; + let mut iter = forks.iter().peekable(); + while let Some(fork) = iter.next() { + write!(f, "- {fork}")?; + if !next_is_empty || iter.peek().is_some() { + writeln!(f)?; + } + } + Ok(()) + } + + format( + "Pre-merge hard forks (block based)", + &self.pre_merge, + self.with_merge.is_empty(), + f, + )?; + + if !self.with_merge.is_empty() { + format("Merge hard forks", &self.with_merge, self.post_merge.is_empty(), f)?; + } + + if !self.post_merge.is_empty() { + format("Post-merge hard forks (timestamp based)", &self.post_merge, true, f)?; + } + + Ok(()) + } +} + +impl DisplayHardforks { + /// Creates a new [`DisplayHardforks`] from an iterator of hardforks. + pub fn new( + hardforks: &BTreeMap, + known_paris_block: Option, + ) -> Self { + let mut pre_merge = Vec::new(); + let mut with_merge = Vec::new(); + let mut post_merge = Vec::new(); + + for (fork, condition) in hardforks { + let mut display_fork = + DisplayFork { name: fork.to_string(), activated_at: *condition, eip: None }; + + match condition { + ForkCondition::Block(_) => { + pre_merge.push(display_fork); + } + ForkCondition::TTD { total_difficulty, .. } => { + display_fork.activated_at = ForkCondition::TTD { + fork_block: known_paris_block, + total_difficulty: *total_difficulty, + }; + with_merge.push(display_fork); + } + ForkCondition::Timestamp(_) => { + post_merge.push(display_fork); + } + ForkCondition::Never => continue, + } + } + + Self { pre_merge, with_merge, post_merge } + } +} diff --git a/crates/ethereum-forks/src/forkcondition.rs b/crates/ethereum-forks/src/forkcondition.rs new file mode 100644 index 000000000000..f57216845cc9 --- /dev/null +++ b/crates/ethereum-forks/src/forkcondition.rs @@ -0,0 +1,103 @@ +use crate::Head; +use alloy_primitives::{BlockNumber, U256}; + +/// The condition at which a fork is activated. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum ForkCondition { + /// The fork is activated after a certain block. + Block(BlockNumber), + /// The fork is activated after a total difficulty has been reached. + TTD { + /// The block number at which TTD is reached, if it is known. + /// + /// This should **NOT** be set unless you want this block advertised as [EIP-2124][eip2124] + /// `FORK_NEXT`. This is currently only the case for Sepolia and Holesky. + /// + /// [eip2124]: https://eips.ethereum.org/EIPS/eip-2124 + fork_block: Option, + /// The total difficulty after which the fork is activated. + total_difficulty: U256, + }, + /// The fork is activated after a specific timestamp. + Timestamp(u64), + /// The fork is never activated + #[default] + Never, +} + +impl ForkCondition { + /// Returns true if the fork condition is timestamp based. + pub const fn is_timestamp(&self) -> bool { + matches!(self, Self::Timestamp(_)) + } + + /// Checks whether the fork condition is satisfied at the given block. + /// + /// For TTD conditions, this will only return true if the activation block is already known. + /// + /// For timestamp conditions, this will always return false. + pub const fn active_at_block(&self, current_block: BlockNumber) -> bool { + matches!(self, Self::Block(block) + | Self::TTD { fork_block: Some(block), .. } if current_block >= *block) + } + + /// Checks if the given block is the first block that satisfies the fork condition. + /// + /// This will return false for any condition that is not block based. + pub const fn transitions_at_block(&self, current_block: BlockNumber) -> bool { + matches!(self, Self::Block(block) if current_block == *block) + } + + /// Checks whether the fork condition is satisfied at the given total difficulty and difficulty + /// of a current block. + /// + /// The fork is considered active if the _previous_ total difficulty is above the threshold. + /// To achieve that, we subtract the passed `difficulty` from the current block's total + /// difficulty, and check if it's above the Fork Condition's total difficulty (here: + /// `58_750_000_000_000_000_000_000`) + /// + /// This will return false for any condition that is not TTD-based. + pub fn active_at_ttd(&self, ttd: U256, difficulty: U256) -> bool { + matches!(self, Self::TTD { total_difficulty, .. } + if ttd.saturating_sub(difficulty) >= *total_difficulty) + } + + /// Checks whether the fork condition is satisfied at the given timestamp. + /// + /// This will return false for any condition that is not timestamp-based. + pub const fn active_at_timestamp(&self, timestamp: u64) -> bool { + matches!(self, Self::Timestamp(time) if timestamp >= *time) + } + + /// Checks whether the fork condition is satisfied at the given head block. + /// + /// This will return true if: + /// + /// - The condition is satisfied by the block number; + /// - The condition is satisfied by the timestamp; + /// - or the condition is satisfied by the total difficulty + pub fn active_at_head(&self, head: &Head) -> bool { + self.active_at_block(head.number) || + self.active_at_timestamp(head.timestamp) || + self.active_at_ttd(head.total_difficulty, head.difficulty) + } + + /// Get the total terminal difficulty for this fork condition. + /// + /// Returns `None` for fork conditions that are not TTD based. + pub const fn ttd(&self) -> Option { + match self { + Self::TTD { total_difficulty, .. } => Some(*total_difficulty), + _ => None, + } + } + + /// Returns the timestamp of the fork condition, if it is timestamp based. + pub const fn as_timestamp(&self) -> Option { + match self { + Self::Timestamp(timestamp) => Some(*timestamp), + _ => None, + } + } +} diff --git a/crates/ethereum-forks/src/forkid.rs b/crates/ethereum-forks/src/forkid.rs index 0a4d752b9b0d..48ef778fcfbf 100644 --- a/crates/ethereum-forks/src/forkid.rs +++ b/crates/ethereum-forks/src/forkid.rs @@ -141,7 +141,7 @@ impl Decodable for EnrForkIdEntry { 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(); @@ -155,7 +155,7 @@ impl Decodable for EnrForkIdEntry { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -324,7 +324,7 @@ impl ForkFilter { if self.current().hash == fork_id.hash { if fork_id.next == 0 { // 1b) No remotely announced fork, connect. - return Ok(()); + return Ok(()) } let is_incompatible = if self.head.number < TIMESTAMP_BEFORE_ETHEREUM_MAINNET { @@ -355,7 +355,7 @@ impl ForkFilter { } else { // 1b) Remotely announced fork not yet passed locally, connect. Ok(()) - }; + } } // 2) If the remote FORK_HASH is a subset of the local past forks... @@ -369,10 +369,10 @@ impl ForkFilter { Ok(()) } else { Err(ValidationError::RemoteStale { local: self.current(), remote: fork_id }) - }; + } } - break; + break } } @@ -380,7 +380,7 @@ impl ForkFilter { // with locally known future forks, connect. for future_fork_hash in &self.cache.future { if *future_fork_hash == fork_id.hash { - return Ok(()); + return Ok(()) } } diff --git a/crates/ethereum-forks/src/hardfork.rs b/crates/ethereum-forks/src/hardfork.rs index 3de55bd43916..fa095dea5a18 100644 --- a/crates/ethereum-forks/src/hardfork.rs +++ b/crates/ethereum-forks/src/hardfork.rs @@ -108,22 +108,22 @@ impl Hardfork { /// Retrieves the activation block for the specified hardfork on the given chain. pub fn activation_block(&self, chain: Chain) -> Option { if chain == Chain::mainnet() { - return self.mainnet_activation_block(); + return self.mainnet_activation_block() } if chain == Chain::sepolia() { - return self.sepolia_activation_block(); + return self.sepolia_activation_block() } if chain == Chain::holesky() { - return self.holesky_activation_block(); + return self.holesky_activation_block() } #[cfg(feature = "optimism")] { if chain == Chain::base_sepolia() { - return self.base_sepolia_activation_block(); + return self.base_sepolia_activation_block() } if chain == Chain::base_mainnet() { - return self.base_mainnet_activation_block(); + return self.base_mainnet_activation_block() } } @@ -317,21 +317,21 @@ impl Hardfork { /// Retrieves the activation timestamp for the specified hardfork on the given chain. pub fn activation_timestamp(&self, chain: Chain) -> Option { if chain == Chain::mainnet() { - return self.mainnet_activation_timestamp(); + return self.mainnet_activation_timestamp() } if chain == Chain::sepolia() { - return self.sepolia_activation_timestamp(); + return self.sepolia_activation_timestamp() } if chain == Chain::holesky() { - return self.holesky_activation_timestamp(); + return self.holesky_activation_timestamp() } #[cfg(feature = "optimism")] { if chain == Chain::base_sepolia() { - return self.base_sepolia_activation_timestamp(); + return self.base_sepolia_activation_timestamp() } if chain == Chain::base_mainnet() { - return self.base_mainnet_activation_timestamp(); + return self.base_mainnet_activation_timestamp() } } diff --git a/crates/ethereum/consensus/src/lib.rs b/crates/ethereum/consensus/src/lib.rs index a0d8c6d60ac9..210f54461394 100644 --- a/crates/ethereum/consensus/src/lib.rs +++ b/crates/ethereum/consensus/src/lib.rs @@ -66,7 +66,7 @@ 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. @@ -74,13 +74,11 @@ impl EthBeaconConsensus { 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, - }); + return Err(ConsensusError::GasLimitInvalidMinimum { child_gas_limit: header.gas_limit }) } Ok(()) @@ -96,30 +94,30 @@ impl Consensus for EthBeaconConsensus { if self.chain_spec.is_shanghai_active_at_timestamp(header.timestamp) && header.withdrawals_root.is_none() { - return Err(ConsensusError::WithdrawalsRootMissing); + 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. if self.chain_spec.is_cancun_active_at_timestamp(header.timestamp) { validate_4844_header_standalone(header)?; } 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_root.is_none() { - return Err(ConsensusError::RequestsRootMissing); + return Err(ConsensusError::RequestsRootMissing) } } else if header.requests_root.is_some() { - return Err(ConsensusError::RequestsRootUnexpected); + return Err(ConsensusError::RequestsRootUnexpected) } Ok(()) @@ -160,15 +158,15 @@ impl Consensus for EthBeaconConsensus { if is_post_merge { if !header.is_zero_difficulty() { - return Err(ConsensusError::TheMergeDifficultyIsNotZero); + return Err(ConsensusError::TheMergeDifficultyIsNotZero) } if header.nonce != 0 { - 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 @@ -197,7 +195,7 @@ impl Consensus for EthBeaconConsensus { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp, present_timestamp, - }); + }) } // Goerli and early OP exception: diff --git a/crates/ethereum/consensus/src/validation.rs b/crates/ethereum/consensus/src/validation.rs index 6d4d2e0a0f74..1566ec176215 100644 --- a/crates/ethereum/consensus/src/validation.rs +++ b/crates/ethereum/consensus/src/validation.rs @@ -23,7 +23,7 @@ pub fn validate_block_post_execution( verify_receipts(block.header.receipts_root, block.header.logs_bloom, receipts) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error); + return Err(error) } } @@ -34,19 +34,19 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.gas_used }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }); + }) } // Validate that the header requests root matches the calculated requests root if chain_spec.is_prague_active_at_timestamp(block.timestamp) { let Some(header_requests_root) = block.header.requests_root else { - return Err(ConsensusError::RequestsRootMissing); + return Err(ConsensusError::RequestsRootMissing) }; let requests_root = reth_primitives::proofs::calculate_requests_root(requests); if requests_root != header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected::new(requests_root, header_requests_root).into(), - )); + )) } } @@ -88,13 +88,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/evm/src/execute.rs b/crates/ethereum/evm/src/execute.rs index 2b8e8bf0b02d..f9a5b752d20c 100644 --- a/crates/ethereum/evm/src/execute.rs +++ b/crates/ethereum/evm/src/execute.rs @@ -170,7 +170,7 @@ where transaction_gas_limit: transaction.gas_limit(), block_available_gas, } - .into()); + .into()) } EvmConfig::fill_tx_env(evm.tx_mut(), transaction, *sender); diff --git a/crates/ethereum/payload/src/lib.rs b/crates/ethereum/payload/src/lib.rs index fad345bc8854..c979397d7553 100644 --- a/crates/ethereum/payload/src/lib.rs +++ b/crates/ethereum/payload/src/lib.rs @@ -312,12 +312,12 @@ where // which also removes all dependent transaction from the iterator before we can // continue best_txs.mark_invalid(&pool_tx); - 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 @@ -334,7 +334,7 @@ where // for regular transactions above. trace!(target: "payload_builder", tx=?tx.hash, ?sum_blob_gas_used, ?tx_blob_gas, "skipping blob transaction because it would exceed the max data gas per block"); best_txs.mark_invalid(&pool_tx); - continue; + continue } } @@ -362,11 +362,11 @@ where best_txs.mark_invalid(&pool_tx); } - continue; + continue } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)); + return Err(PayloadBuilderError::EvmExecutionError(err)) } } } @@ -415,7 +415,7 @@ where // check if we have a better block if !is_better_payload(best_payload.as_ref(), total_fees) { // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) } // calculate the requests and the requests root diff --git a/crates/etl/src/lib.rs b/crates/etl/src/lib.rs index 0793e585334e..2dbf4cada4fa 100644 --- a/crates/etl/src/lib.rs +++ b/crates/etl/src/lib.rs @@ -246,7 +246,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; 8]; diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index 9c9c72dfc0d2..de46952b9ee2 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -126,13 +126,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 } @@ -259,7 +259,7 @@ impl Chain { return Err(BlockExecutionError::AppendChainDoesntConnect { chain_tip: Box::new(chain_tip.num_hash()), other_chain_fork: Box::new(other_fork_block), - }); + }) } // Insert blocks from other chain @@ -296,23 +296,23 @@ impl Chain { let block_number = match split_at { ChainSplitTarget::Hash(block_hash) => { let Some(block_number) = self.block_number(block_hash) else { - return ChainSplit::NoSplitPending(self); + return ChainSplit::NoSplitPending(self) }; // If block number is same as tip whole chain is becoming canonical. if block_number == chain_tip { - return ChainSplit::NoSplitCanonical(self); + return ChainSplit::NoSplitCanonical(self) } block_number } ChainSplitTarget::Number(block_number) => { if block_number > chain_tip { - return ChainSplit::NoSplitPending(self); + return ChainSplit::NoSplitPending(self) } if block_number == chain_tip { - return ChainSplit::NoSplitCanonical(self); + return ChainSplit::NoSplitCanonical(self) } if block_number < *self.blocks.first_entry().expect("chain is never empty").key() { - return ChainSplit::NoSplitPending(self); + return ChainSplit::NoSplitPending(self) } block_number } diff --git a/crates/evm/execution-types/src/execution_outcome.rs b/crates/evm/execution-types/src/execution_outcome.rs index c9359c4d37ca..9c51faf85e32 100644 --- a/crates/evm/execution-types/src/execution_outcome.rs +++ b/crates/evm/execution-types/src/execution_outcome.rs @@ -154,11 +154,11 @@ impl ExecutionOutcome { /// Transform block number to the index of block. 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) } @@ -266,7 +266,7 @@ impl ExecutionOutcome { /// If the target block number is not included in the state block range. pub fn split_at(self, at: BlockNumber) -> (Option, Self) { 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/manager.rs b/crates/exex/exex/src/manager.rs index 718f157cef78..ce4994c34b03 100644 --- a/crates/exex/exex/src/manager.rs +++ b/crates/exex/exex/src/manager.rs @@ -102,7 +102,7 @@ impl ExExHandle { ); self.next_notification_id = notification_id + 1; - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } // Do not handle [ExExNotification::ChainReorged] and @@ -291,9 +291,9 @@ impl Future for ExExManager { "Received new notification" ); self.push_notification(notification); - continue; + continue } - break; + break } // update capacity @@ -313,7 +313,7 @@ impl Future for ExExManager { if let Some(notification) = self.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/metrics/metrics-derive/src/expand.rs b/crates/metrics/metrics-derive/src/expand.rs index d1b25a12a47a..ac0efd4f3e7a 100644 --- a/crates/metrics/metrics-derive/src/expand.rs +++ b/crates/metrics/metrics-derive/src/expand.rs @@ -242,14 +242,14 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { }; if kv.path.is_ident("scope") { if scope.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `scope` value provided.")); + return Err(Error::new_spanned(kv, "Duplicate `scope` value provided.")) } let scope_lit = parse_str_lit(lit)?; validate_metric_name(&scope_lit)?; scope = Some(scope_lit); } else if kv.path.is_ident("separator") { if separator.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `separator` value provided.")); + return Err(Error::new_spanned(kv, "Duplicate `separator` value provided.")) } let separator_lit = parse_str_lit(lit)?; if !SUPPORTED_SEPARATORS.contains(&&*separator_lit.value()) { @@ -263,16 +263,16 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { .collect::>() .join(", ") ), - )); + )) } separator = Some(separator_lit); } else if kv.path.is_ident("dynamic") { if dynamic.is_some() { - return Err(Error::new_spanned(kv, "Duplicate `dynamic` flag provided.")); + return Err(Error::new_spanned(kv, "Duplicate `dynamic` flag provided.")) } dynamic = Some(parse_bool_lit(lit)?.value); } else { - return Err(Error::new_spanned(kv, "Unsupported attribute entry.")); + return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) } } @@ -295,7 +295,7 @@ fn parse_metrics_attr(node: &DeriveInput) -> Result { fn parse_metric_fields(node: &DeriveInput) -> Result>> { let Data::Struct(ref data) = node.data else { - return Err(Error::new_spanned(node, "Only structs are supported.")); + return Err(Error::new_spanned(node, "Only structs are supported.")) }; let mut metrics = Vec::with_capacity(data.fields.len()); @@ -317,7 +317,7 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { return Err(Error::new_spanned( kv, "Duplicate `describe` value provided.", - )); + )) } describe = Some(parse_str_lit(lit)?); } else if kv.path.is_ident("rename") { @@ -325,13 +325,13 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { return Err(Error::new_spanned( kv, "Duplicate `rename` value provided.", - )); + )) } let rename_lit = parse_str_lit(lit)?; validate_metric_name(&rename_lit)?; rename = Some(rename_lit) } else { - return Err(Error::new_spanned(kv, "Unsupported attribute entry.")); + return Err(Error::new_spanned(kv, "Unsupported attribute entry.")) } } _ => return Err(Error::new_spanned(meta, "Unsupported attribute entry.")), @@ -341,7 +341,7 @@ fn parse_metric_fields(node: &DeriveInput) -> Result>> { if skip { metrics.push(MetricField::Skipped(field)); - continue; + continue } let description = match describe { diff --git a/crates/metrics/metrics-derive/src/metric.rs b/crates/metrics/metrics-derive/src/metric.rs index 88be9a31fd1d..e8dfb24847a8 100644 --- a/crates/metrics/metrics-derive/src/metric.rs +++ b/crates/metrics/metrics-derive/src/metric.rs @@ -33,7 +33,7 @@ impl<'a> Metric<'a> { _ => return Err(Error::new_spanned(path_ty, "Unsupported metric type")), }; - return Ok(quote! { #registrar }); + return Ok(quote! { #registrar }) } } @@ -50,7 +50,7 @@ impl<'a> Metric<'a> { _ => return Err(Error::new_spanned(path_ty, "Unsupported metric type")), }; - return Ok(quote! { #descriptor }); + return Ok(quote! { #descriptor }) } } diff --git a/crates/net/common/src/ban_list.rs b/crates/net/common/src/ban_list.rs index e547d4c399e5..6586becae0ae 100644 --- a/crates/net/common/src/ban_list.rs +++ b/crates/net/common/src/ban_list.rs @@ -8,7 +8,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 { @@ -54,7 +54,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false; + return false } } true @@ -69,7 +69,7 @@ impl BanList { if let Some(until) = until { if now > *until { evicted.push(*peer); - return false; + return false } } true diff --git a/crates/net/common/src/ratelimit.rs b/crates/net/common/src/ratelimit.rs index f717d18b3a0e..16e403f10aa2 100644 --- a/crates/net/common/src/ratelimit.rs +++ b/crates/net/common/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/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index d921b75ddc7f..47f810d96337 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -767,7 +767,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"); @@ -847,7 +847,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 @@ -859,7 +859,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 @@ -894,7 +894,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 @@ -1003,7 +1003,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 @@ -1121,17 +1121,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) { - return; + return } if self.queued_pings.iter().any(|(n, _)| n.id == node.id) { - return; + return } if self.pending_pings.len() < MAX_NODES_PING { @@ -1166,7 +1166,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() }; @@ -1181,7 +1181,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) { @@ -1190,7 +1190,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() @@ -1226,11 +1226,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()) { @@ -1245,7 +1245,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 { @@ -1284,7 +1284,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()) { @@ -1303,7 +1303,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) { @@ -1319,7 +1319,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 } }; @@ -1335,7 +1335,7 @@ impl Discv4Service { Entry::Vacant(_) => { // received neighbours response without requesting it trace!(target: "discv4", from=?remote_addr, "Received unsolicited Neighbours"); - return; + return } }; @@ -1345,7 +1345,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); @@ -1427,7 +1427,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 }); @@ -1443,7 +1443,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 }); @@ -1467,7 +1467,7 @@ impl Discv4Service { // treat this as an hard error since it responded. failed_neighbours.push(*node_id); } - return false; + return false } true }); @@ -1495,7 +1495,7 @@ impl Discv4Service { if let Some(bucket) = self.kbuckets.get_bucket(&key) { if bucket.num_entries() < MAX_NODES_PER_BUCKET / 2 { // skip half empty bucket - continue; + continue } } self.remove_node(node_id); @@ -1542,7 +1542,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(()) } @@ -1586,7 +1586,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 @@ -1711,7 +1711,7 @@ impl Discv4Service { // this will make sure we're woken up again cx.waker().wake_by_ref(); } - break; + break } } @@ -1729,7 +1729,7 @@ impl Discv4Service { } if self.queued_events.is_empty() { - return Poll::Pending; + return Poll::Pending } } } @@ -1836,7 +1836,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]; @@ -1845,13 +1845,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; @@ -2000,7 +2000,7 @@ impl LookupTargetRotator { self.counter += 1; self.counter %= self.interval; if self.counter == 0 { - return *local; + return *local } PeerId::random() } @@ -2363,7 +2363,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 } } } diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 8e8da311cf2f..610628d56b4f 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -138,7 +138,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: @@ -149,7 +149,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]; @@ -232,7 +232,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(); @@ -246,7 +246,7 @@ impl Decodable for FindNode { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -274,7 +274,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(); @@ -288,7 +288,7 @@ impl Decodable for Neighbours { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -317,7 +317,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(); @@ -331,7 +331,7 @@ impl Decodable for EnrRequest { return Err(RlpError::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } let rem = rlp_head.payload_length - consumed; @@ -425,7 +425,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(); @@ -450,7 +450,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); @@ -505,7 +505,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 { @@ -525,7 +525,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 37d8c60db7f5..06133dba6790 100644 --- a/crates/net/discv4/src/test_utils.rs +++ b/crates/net/discv4/src/test_utils.rs @@ -165,7 +165,7 @@ impl Stream for MockDiscovery { ping, pong, to: remote_addr, - })); + })) } } Message::Pong(_) | Message::Neighbours(_) => {} @@ -179,7 +179,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/enr.rs b/crates/net/discv5/src/enr.rs index 5050aed1dfb8..eb8b6be006b2 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 5dbdec13d7a9..325544de6c18 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 f21720804dfb..728c44791d16 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -98,7 +98,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: "discv5", @@ -301,7 +301,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) { @@ -313,7 +313,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 @@ -340,14 +340,14 @@ impl Discv5 { let id = enr_to_discv4_id(enr).ok_or(Error::IncompatibleKeyType)?; if enr.tcp4().is_none() && enr.tcp6().is_none() { - return Err(Error::UnreachableRlpx); + return Err(Error::UnreachableRlpx) } let Some(tcp_port) = (match self.rlpx_ip_mode { IpMode::Ip4 => enr.tcp4(), IpMode::Ip6 => enr.tcp6(), _ => unimplemented!("dual-stack support not implemented for rlpx"), }) else { - return Err(Error::IpVersionMismatchRlpx(self.rlpx_ip_mode)); + return Err(Error::IpVersionMismatchRlpx(self.rlpx_ip_mode)) }; Ok(NodeRecord { address: socket.ip(), tcp_port, udp_port: socket.port(), id }) @@ -498,7 +498,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 4b2e07cdce71..5fcb1ae41b55 100644 --- a/crates/net/discv5/src/network_stack_id.rs +++ b/crates/net/discv5/src/network_stack_id.rs @@ -24,9 +24,9 @@ impl NetworkStackId { /// Returns the [`NetworkStackId`] that matches the given [`ChainSpec`]. pub fn id(chain: &ChainSpec) -> Option<&'static [u8]> { if chain.is_optimism() { - return Some(Self::OPEL); + return Some(Self::OPEL) } else if chain.is_eth() { - 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 eec205d948bb..f07fde2e4a67 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 c8831cbbbc1b..a1c67740ed7a 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 278c0f892d2e..cfe6862c934d 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 16f66af5252f..80182b694f80 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.bytes().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 29cc505c63b3..27a576e2f702 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -95,7 +95,7 @@ where max_non_empty: u64, ) -> DownloadResult>> { if range.is_empty() || max_non_empty == 0 { - return Ok(None); + return Ok(None) } // Collect headers while @@ -144,7 +144,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()) @@ -238,7 +238,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 @@ -257,7 +257,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 } @@ -311,7 +311,7 @@ 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. @@ -320,7 +320,7 @@ where 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. @@ -331,7 +331,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 @@ -354,13 +354,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 @@ -373,7 +373,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))) } }; } @@ -396,7 +396,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))) } }; } @@ -409,21 +409,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 diff --git a/crates/net/downloaders/src/bodies/request.rs b/crates/net/downloaders/src/bodies/request.rs index 36038aa7d03a..f27801041e83 100644 --- a/crates/net/downloaders/src/bodies/request.rs +++ b/crates/net/downloaders/src/bodies/request.rs @@ -128,14 +128,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 @@ -189,7 +189,7 @@ where hash, number, error: Box::new(error), - }); + }) } self.buffer.push(BlockResponse::Full(block)); @@ -215,7 +215,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 @@ -230,7 +230,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 345b22f71180..42b21d5f1699 100644 --- a/crates/net/downloaders/src/bodies/task.rs +++ b/crates/net/downloaders/src/bodies/task.rs @@ -128,13 +128,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(()) } } @@ -144,7 +144,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, @@ -152,7 +152,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 728b7c8f2f37..0ef12f1ba552 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -118,7 +118,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(); @@ -126,7 +126,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; } @@ -218,7 +218,7 @@ impl FromReader for FileClient { "partial block returned from decoding chunk" ); remaining_bytes = bytes; - break; + break } Err(err) => return Err(err), }; @@ -278,7 +278,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, @@ -302,7 +302,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) }) } } } @@ -409,7 +409,7 @@ impl ChunkedFileReader { if self.file_byte_len == 0 && self.chunk.is_empty() { dbg!(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 1d0eca211704..156f3316c431 100644 --- a/crates/net/downloaders/src/file_codec.rs +++ b/crates/net/downloaders/src/file_codec.rs @@ -29,7 +29,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/file_codec_ovm_receipt.rs b/crates/net/downloaders/src/file_codec_ovm_receipt.rs index ca666fffb8ff..5b3c81a9233a 100644 --- a/crates/net/downloaders/src/file_codec_ovm_receipt.rs +++ b/crates/net/downloaders/src/file_codec_ovm_receipt.rs @@ -31,7 +31,7 @@ impl Decoder for HackReceiptFileCodec { 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 badcef3b0f76..e123ce71229a 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -158,7 +158,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) @@ -181,7 +181,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) } } @@ -259,7 +259,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)?; @@ -286,7 +286,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 @@ -299,7 +299,7 @@ where header: Box::new(last_header.clone()), error: Box::new(error), } - .into()); + .into()) } } @@ -372,7 +372,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()); + .into()) } let target = headers.remove(0).seal_slow(); @@ -387,7 +387,7 @@ where GotExpected { got: target.hash(), expected: hash }.into(), ), } - .into()); + .into()) } } SyncTargetBlock::Number(number) => { @@ -400,7 +400,7 @@ where expected: number, }), } - .into()); + .into()) } } } @@ -449,7 +449,7 @@ where peer_id: Some(peer_id), error: DownloadError::EmptyResponse, } - .into()); + .into()) } if (headers.len() as u64) != request.limit { @@ -461,7 +461,7 @@ where }), request, } - .into()); + .into()) } // sort headers from highest to lowest block number @@ -481,7 +481,7 @@ where expected: requested_block_number, }), } - .into()); + .into()) } // check if the response is the next expected @@ -552,7 +552,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 => { @@ -684,7 +684,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"); @@ -751,7 +751,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 @@ -765,7 +765,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); @@ -775,13 +775,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 } } } @@ -807,13 +807,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))) } }; } @@ -838,7 +838,7 @@ where this.submit_request(request, Priority::Normal); } else { // no more requests - break; + break } } @@ -855,11 +855,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 } } @@ -868,10 +868,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 @@ -964,7 +964,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 f3043476deb8..b3fa27fde59c 100644 --- a/crates/net/downloaders/src/headers/task.rs +++ b/crates/net/downloaders/src/headers/task.rs @@ -127,7 +127,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) => { @@ -153,7 +153,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, @@ -162,7 +162,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 fb37cccdbe00..7b05543894ec 100644 --- a/crates/net/downloaders/src/receipt_file_client.rs +++ b/crates/net/downloaders/src/receipt_file_client.rs @@ -70,7 +70,7 @@ impl FromReader for ReceiptFileClient { remaining_bytes = bytes; - break; + break } Err(err) => return Err(err), }; diff --git a/crates/net/downloaders/src/test_utils/bodies_client.rs b/crates/net/downloaders/src/test_utils/bodies_client.rs index 160dee9b26bf..7b655dae2891 100644 --- a/crates/net/downloaders/src/test_utils/bodies_client.rs +++ b/crates/net/downloaders/src/test_utils/bodies_client.rs @@ -93,7 +93,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 ad40a9da45da..83dcc657bce9 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(()) @@ -655,7 +655,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)?; @@ -665,12 +665,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)?)?; @@ -721,7 +721,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 9bdaedbd8864..7ad30d38d0d9 100644 --- a/crates/net/ecies/src/codec.rs +++ b/crates/net/ecies/src/codec.rs @@ -50,7 +50,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; @@ -58,18 +58,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::Header; - 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; @@ -77,18 +77,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::Header; - return Ok(Some(IngressECIESValue::Ack)); + return Ok(Some(IngressECIESValue::Ack)) } 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()))?; @@ -97,7 +97,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()); @@ -105,7 +105,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 602356dda9b2..e413ab9ee9fe 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -40,7 +40,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) }) @@ -428,13 +428,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) @@ -708,7 +708,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); @@ -716,7 +716,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/message.rs b/crates/net/eth-wire-types/src/message.rs index 61ff55b1cf77..cbd5ca536108 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -93,14 +93,14 @@ impl ProtocolMessage { } EthMessageID::GetNodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) } let request_pair = RequestPair::::decode(buf)?; EthMessage::GetNodeData(request_pair) } EthMessageID::NodeData => { if version >= EthVersion::Eth67 { - return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)); + return Err(MessageError::Invalid(version, EthMessageID::GetNodeData)) } let request_pair = RequestPair::::decode(buf)?; EthMessage::NodeData(request_pair) @@ -485,7 +485,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 b7dd3e257cd5..2bf096287635 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -268,7 +268,7 @@ impl SharedCapability { messages: u8, ) -> Result { if offset <= MAX_RESERVED_MESSAGE_ID { - return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)); + return Err(SharedCapabilityError::ReservedMessageIdOffset(offset)) } match name { @@ -424,12 +424,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 } @@ -513,7 +513,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 @@ -537,7 +537,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/disconnect.rs b/crates/net/eth-wire/src/disconnect.rs index d382f47c0806..50ced132f2a6 100644 --- a/crates/net/eth-wire/src/disconnect.rs +++ b/crates/net/eth-wire/src/disconnect.rs @@ -114,9 +114,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(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } else if buf.len() > 2 { - return Err(RlpError::Overflow); + return Err(RlpError::Overflow) } if buf.len() > 1 { @@ -125,14 +125,11 @@ impl Decodable for DisconnectReason { let header = Header::decode(buf)?; if !header.list { - return Err(RlpError::UnexpectedString); + return Err(RlpError::UnexpectedString) } if header.payload_length != 1 { - return Err(RlpError::ListLengthMismatch { - expected: 1, - got: header.payload_length, - }); + return Err(RlpError::ListLengthMismatch { expected: 1, got: header.payload_length }) } } diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index 1bd803b53226..485a4ae2e7a4 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -55,7 +55,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/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index 6bb73c21f2f1..fac5e05495a7 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -95,13 +95,13 @@ where Some(msg) => msg, None => { self.inner.disconnect(DisconnectReason::DisconnectRequested).await?; - return Err(EthStreamError::EthHandshakeError(EthHandshakeError::NoResponse)); + return Err(EthStreamError::EthHandshakeError(EthHandshakeError::NoResponse)) } }?; if their_msg.len() > MAX_MESSAGE_SIZE { self.inner.disconnect(DisconnectReason::ProtocolBreach).await?; - return Err(EthStreamError::MessageTooBig(their_msg.len())); + return Err(EthStreamError::MessageTooBig(their_msg.len())) } let version = EthVersion::try_from(status.version)?; @@ -110,7 +110,7 @@ where Err(err) => { debug!("decode error in eth handshake: msg={their_msg:x}"); self.inner.disconnect(DisconnectReason::DisconnectRequested).await?; - return Err(EthStreamError::InvalidMessage(err)); + return Err(EthStreamError::InvalidMessage(err)) } }; @@ -127,7 +127,7 @@ where return Err(EthHandshakeError::MismatchedGenesis( GotExpected { expected: status.genesis, got: resp.genesis }.into(), ) - .into()); + .into()) } if status.version != resp.version { @@ -136,7 +136,7 @@ where got: resp.version, expected: status.version, }) - .into()); + .into()) } if status.chain != resp.chain { @@ -145,7 +145,7 @@ where got: resp.chain, expected: status.chain, }) - .into()); + .into()) } // TD at mainnet block #7753254 is 76 bits. If it becomes 100 million times @@ -156,14 +156,14 @@ where got: status.total_difficulty.bit_len(), maximum: 100, } - .into()); + .into()) } if let Err(err) = fork_filter.validate(resp.forkid).map_err(EthHandshakeError::InvalidFork) { self.inner.disconnect(DisconnectReason::ProtocolBreach).await?; - return Err(err.into()); + return Err(err.into()) } // now we can create the `EthStream` because the peer has successfully completed @@ -261,7 +261,7 @@ where }; if bytes.len() > MAX_MESSAGE_SIZE { - return Poll::Ready(Some(Err(EthStreamError::MessageTooBig(bytes.len())))); + return Poll::Ready(Some(Err(EthStreamError::MessageTooBig(bytes.len())))) } let msg = match ProtocolMessage::decode_message(*this.version, &mut bytes.as_ref()) { @@ -277,14 +277,14 @@ where %msg, "failed to decode protocol message" ); - return Poll::Ready(Some(Err(EthStreamError::InvalidMessage(err)))); + return Poll::Ready(Some(Err(EthStreamError::InvalidMessage(err)))) } }; if matches!(msg.message, EthMessage::Status(_)) { return Poll::Ready(Some(Err(EthStreamError::EthHandshakeError( EthHandshakeError::StatusNotInHandshake, - )))); + )))) } Poll::Ready(Some(Ok(msg.message))) @@ -313,7 +313,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 84d43e8a87af..262c2c193921 100644 --- a/crates/net/eth-wire/src/multiplex.rs +++ b/crates/net/eth-wire/src/multiplex.rs @@ -79,7 +79,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(); @@ -147,7 +147,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(); @@ -243,7 +243,7 @@ impl MultiplexInner { for proto in &self.protocols { if proto.shared_cap == *cap { proto.send_raw(msg); - return true; + return true } } false @@ -299,7 +299,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()) } @@ -309,7 +309,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 mut masked_bytes = BytesMut::zeroed(msg.len()); @@ -326,7 +326,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()) @@ -460,7 +460,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; @@ -469,23 +469,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 } } } @@ -498,7 +498,7 @@ where } Poll::Ready(None) => { // primary closed - return Poll::Ready(None); + return Poll::Ready(None) } Poll::Pending => break, } @@ -518,7 +518,7 @@ where Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => { this.inner.protocols.push(proto); - break; + break } } } @@ -533,7 +533,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) = @@ -547,27 +547,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 } } } @@ -584,10 +585,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(())) } @@ -619,7 +620,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()) @@ -632,7 +633,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 7312a891e5db..23f106da9a42 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -105,7 +105,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 @@ -147,7 +147,7 @@ where return Err(P2PStreamError::MismatchedProtocolVersion(GotExpected { got: their_hello.protocol_version, expected: hello.protocol_version, - })); + })) } // determine shared capabilities (currently returns only one capability) @@ -389,7 +389,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 @@ -403,7 +403,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 @@ -424,7 +424,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)))) } } @@ -435,7 +435,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 @@ -466,7 +466,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 @@ -484,11 +484,11 @@ where ); err })?; - 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, @@ -516,7 +516,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))) } } } @@ -545,7 +545,7 @@ where this.start_disconnect(DisconnectReason::PingTimeout)?; // End the stream after ping related error - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } @@ -555,7 +555,7 @@ where Poll::Ready(Ok(())) => { let flushed = this.poll_flush(cx); if flushed.is_ready() { - return flushed; + return flushed } } } @@ -573,17 +573,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(); @@ -619,10 +619,10 @@ where Err(err) => return Poll::Ready(Err(err.into())), Ok(()) => { let Some(message) = this.outgoing_messages.pop_front() else { - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) }; if let Err(err) = this.inner.as_mut().start_send(message) { - return Poll::Ready(Err(err.into())); + return Poll::Ready(Err(err.into())) } } } @@ -715,10 +715,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 90ac45831dd4..d93404c5f974 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/protocol.rs b/crates/net/eth-wire/src/protocol.rs index 35d2f27a9f01..26b7d6d1b6af 100644 --- a/crates/net/eth-wire/src/protocol.rs +++ b/crates/net/eth-wire/src/protocol.rs @@ -54,7 +54,7 @@ impl Protocol { /// The number of values needed to represent all message IDs of capability. pub fn messages(&self) -> u8 { if self.cap.is_eth() { - return EthMessageID::max() + 1; + return EthMessageID::max() + 1 } self.messages } diff --git a/crates/net/eth-wire/src/test_utils.rs b/crates/net/eth-wire/src/test_utils.rs index 18b68ca28232..466bc0f1cefa 100644 --- a/crates/net/eth-wire/src/test_utils.rs +++ b/crates/net/eth-wire/src/test_utils.rs @@ -137,7 +137,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 c653c1e517de..8f757908958f 100644 --- a/crates/net/nat/src/lib.rs +++ b/crates/net/nat/src/lib.rs @@ -91,7 +91,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/src/discovery.rs b/crates/net/network/src/discovery.rs index efb915cf42e3..c320c7fe1575 100644 --- a/crates/net/network/src/discovery.rs +++ b/crates/net/network/src/discovery.rs @@ -240,7 +240,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 @@ -278,7 +278,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 8e61edfe9ee9..9019a79f2371 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -70,7 +70,7 @@ impl NetworkError { ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err }, _ => { if let ServiceKind::Discovery(_) = kind { - return Self::Discovery(err); + return Self::Discovery(err) } Self::Io(err) } @@ -184,7 +184,7 @@ 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() { @@ -207,7 +207,7 @@ impl SessionError for EthStreamError { // [`SessionError::is_fatal_protocol_error`] Some(BackoffKind::High) } - }; + } } // This only checks for a subset of error variants, the counterpart of diff --git a/crates/net/network/src/eth_requests.rs b/crates/net/network/src/eth_requests.rs index 44666b093822..2e403a517dc0 100644 --- a/crates/net/network/src/eth_requests.rs +++ b/crates/net/network/src/eth_requests.rs @@ -85,7 +85,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() } @@ -101,7 +101,7 @@ where if let Some(next) = (header.number + 1).checked_add(skip) { block = next.into() } else { - break; + break } } HeadersDirection::Falling => { @@ -113,7 +113,7 @@ where { block = next.into() } else { - break; + break } } else { block = header.parent_hash.into() @@ -125,14 +125,14 @@ where headers.push(header); if headers.len() >= MAX_HEADERS_SERVE { - break; + break } if total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } @@ -174,14 +174,14 @@ where bodies.push(body); if bodies.len() >= MAX_BODIES_SERVE { - break; + break } if total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } @@ -213,14 +213,14 @@ where receipts.push(receipt); if receipts.len() >= MAX_RECEIPTS_SERVE { - break; + break } if total_bytes > SOFT_RESPONSE_LIMIT { - break; + break } } else { - break; + break } } @@ -271,7 +271,7 @@ where if maybe_more_incoming_requests { // make sure we're woken up again cx.waker().wake_by_ref(); - return Poll::Pending; + return Poll::Pending } Poll::Pending diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index feb7e2a44afb..4825532e4856 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -114,7 +114,7 @@ impl StateFetcher { if number > peer.best_number { peer.best_hash = hash; peer.best_number = number; - return true; + return true } } false @@ -139,7 +139,7 @@ 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 @@ -157,7 +157,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 }; @@ -204,7 +204,7 @@ impl StateFetcher { } if self.queued_requests.is_empty() || no_peers_available { - return Poll::Pending; + return Poll::Pending } } } @@ -279,7 +279,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) } } @@ -305,7 +305,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 @@ -383,7 +383,7 @@ impl PeerState { 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 fb98947f794c..d07b9e02488f 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -538,7 +538,7 @@ where 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); @@ -984,7 +984,7 @@ where 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 868e074cf56e..b26dd3e3700e 100644 --- a/crates/net/network/src/network.rs +++ b/crates/net/network/src/network.rs @@ -347,7 +347,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/manager.rs b/crates/net/network/src/peers/manager.rs index 4d3b83b3b04e..7468ba1a06ad 100644 --- a/crates/net/network/src/peers/manager.rs +++ b/crates/net/network/src/peers/manager.rs @@ -235,7 +235,7 @@ impl PeersManager { addr: IpAddr, ) -> Result<(), InboundConnectionError> { if self.ban_list.is_banned_ip(&addr) { - return Err(InboundConnectionError::IpBanned); + return Err(InboundConnectionError::IpBanned) } if (!self.connection_info.has_in_capacity() || self.connection_info.max_inbound == 0) && @@ -243,7 +243,7 @@ impl PeersManager { { // if we don't have any inbound slots and no trusted peers, we don't accept any new // connections - return Err(InboundConnectionError::ExceedsCapacity); + return Err(InboundConnectionError::ExceedsCapacity) } self.connection_info.inc_pending_in(); @@ -292,14 +292,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 @@ -313,7 +313,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 @@ -437,7 +437,7 @@ impl PeersManager { ReputationChangeKind::Timeout | ReputationChangeKind::AlreadySeenTransaction ) { - return; + return } // also be less strict with the reputation slashing for trusted peers @@ -449,7 +449,7 @@ impl PeersManager { peer.apply_reputation(reputation_change) } } else { - return; + return }; match outcome { @@ -503,7 +503,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, @@ -548,7 +548,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 } } @@ -690,7 +690,7 @@ impl PeersManager { fork_id: Option, ) { if self.ban_list.is_banned(&peer_id, &addr.ip()) { - return; + return } match self.peers.entry(peer_id) { @@ -725,7 +725,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(); @@ -752,7 +752,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(); @@ -782,13 +782,13 @@ impl PeersManager { let mut best_peer = unconnected.next()?; if best_peer.1.is_trusted() { - 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, return it immediately if maybe_better.1.is_trusted() { - 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 @@ -809,7 +809,7 @@ impl PeersManager { if !self.net_connection_state.is_active() { // nothing to fill - return; + return } // as long as there a slots available fill them with the best peers @@ -855,7 +855,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) { @@ -894,7 +894,7 @@ impl PeersManager { if let Some(peer) = self.peers.get_mut(peer_id) { peer.backed_off = false; } - return false; + return false } true }) @@ -905,7 +905,7 @@ impl PeersManager { } if self.queued_actions.is_empty() { - return Poll::Pending; + return Poll::Pending } } } @@ -1084,15 +1084,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 @@ -2236,7 +2236,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 fe36418f21eb..9357cc325adb 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -197,7 +197,7 @@ impl ActiveSession { sizes_len: msg.sizes.len(), }, message: EthMessage::NewPooledTransactionHashes68(msg), - }; + } } self.try_emit_broadcast(PeerMessage::PooledTransactions(msg.into())).into() } @@ -429,7 +429,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 } } } @@ -453,7 +453,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); @@ -475,11 +475,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 @@ -500,7 +500,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; @@ -515,7 +515,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); @@ -558,11 +558,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 } } @@ -573,7 +573,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 @@ -587,7 +587,7 @@ impl Future for ActiveSession { Poll::Ready(Err(_)) => return Poll::Ready(()), Poll::Pending => { this.pending_message_to_session = Some(msg); - break 'receive; + break 'receive } }; } @@ -596,10 +596,10 @@ impl Future for ActiveSession { Poll::Pending => break, Poll::Ready(None) => { if this.is_disconnecting() { - break; + break } else { 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)) => { @@ -614,18 +614,18 @@ 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 this.pending_message_to_session = Some(msg); - continue 'receive; + continue 'receive } } } 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) } } } @@ -633,7 +633,7 @@ impl Future for ActiveSession { } if !progress { - break 'main; + break 'main } } @@ -1109,7 +1109,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/config.rs b/crates/net/network/src/session/config.rs index 98136ee80a10..6c7fc282d0a5 100644 --- a/crates/net/network/src/session/config.rs +++ b/crates/net/network/src/session/config.rs @@ -223,7 +223,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 9ad79bbc03a9..4f6be86317a0 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -447,7 +447,7 @@ impl SessionManager { peer_id, remote_addr, direction, - }); + }) } let (commands_to_session, commands_rx) = mpsc::channel(self.session_command_buffer); @@ -842,7 +842,7 @@ async fn start_pending_outbound_session( error, }) .await; - return; + return } }; authenticate( @@ -888,7 +888,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 9a7b597eb59a..afbf05dde691 100644 --- a/crates/net/network/src/state.rs +++ b/crates/net/network/src/state.rs @@ -178,7 +178,7 @@ where 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 @@ -198,7 +198,7 @@ where } if count >= num_propagate { - break; + break } } } @@ -211,7 +211,7 @@ where 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) { @@ -397,7 +397,7 @@ where 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) { @@ -461,7 +461,7 @@ where } 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 ec1ca5e28a01..cfc1f841713c 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -193,7 +193,7 @@ where 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) = @@ -207,13 +207,13 @@ where trace!(target: "net", ?remote_addr, "No capacity for incoming connection"); } } - 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."); @@ -232,7 +232,7 @@ where 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); @@ -250,7 +250,7 @@ where StateAction::DiscoveredNode { peer_id, socket_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)) { @@ -307,7 +307,7 @@ where 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)) } } @@ -316,9 +316,9 @@ where 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 } } @@ -327,13 +327,13 @@ where 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 b44019e4e884..87ccbb5f9d79 100644 --- a/crates/net/network/src/test_utils/init.rs +++ b/crates/net/network/src/test_utils/init.rs @@ -45,7 +45,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 7f06f9645881..c7642accd0d8 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -297,7 +297,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 @@ -627,7 +627,7 @@ impl NetworkEventStream { /// Awaits the next `num` events for an established session pub async fn take_session_established(&mut self, mut num: usize) -> Vec { if num == 0 { - return Vec::new(); + return Vec::new() } let mut peers = Vec::with_capacity(num); while let Some(ev) = self.inner.next().await { @@ -636,7 +636,7 @@ impl NetworkEventStream { peers.push(peer_id); num -= 1; if num == 0 { - return peers; + return peers } } _ => continue, diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index 04d9b60238b4..41081b191515 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -156,7 +156,7 @@ impl TransactionFetcher { if let Some(inflight_count) = self.active_peers.get(peer_id) { *inflight_count -= 1; if *inflight_count == 0 { - return true; + return true } } false @@ -171,7 +171,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 < DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER { - return true; + return true } false } @@ -187,7 +187,7 @@ impl TransactionFetcher { for peer_id in fallback_peers.iter() { if self.is_idle(peer_id) && is_session_active(peer_id) { - return Some(peer_id); + return Some(peer_id) } } @@ -214,13 +214,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 } } }; @@ -243,7 +243,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) } @@ -274,7 +274,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::() } else { acc_size_response = size; } @@ -309,7 +309,7 @@ impl TransactionFetcher { acc_size_response; if free_space < MEDIAN_BYTE_SIZE_SMALL_LEGACY_TX_ENCODED { - break; + break } } @@ -358,7 +358,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 @@ -377,13 +377,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 { @@ -398,7 +398,7 @@ impl TransactionFetcher { ); max_retried_and_evicted_hashes.push(hash); - continue; + continue } *retries += 1; } @@ -438,7 +438,7 @@ impl TransactionFetcher { budget_find_idle_fallback_peer, ) else { // no peers are idle or budget is depleted - return; + return }; peer_id @@ -633,7 +633,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 { @@ -643,7 +643,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 >= DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER { @@ -654,7 +654,7 @@ impl TransactionFetcher { max_concurrent_tx_reqs_per_peer=DEFAULT_MAX_COUNT_CONCURRENT_REQUESTS_PER_PEER, "limit for concurrent `GetPooledTransactions` requests per peer reached" ); - return Some(new_announced_hashes); + return Some(new_announced_hashes) } *inflight_count += 1; @@ -691,7 +691,7 @@ impl TransactionFetcher { self.metrics.egress_peer_channel_full.increment(1); Some(new_announced_hashes) } - }; + } } else { // stores a new request future for the request self.inflight_requests.push(GetPooledTxRequestFut::new( @@ -741,7 +741,7 @@ impl TransactionFetcher { 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 @@ -749,7 +749,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. @@ -778,7 +778,7 @@ impl TransactionFetcher { if let Some(ref mut bud) = budget_fill_request { *bud = bud.saturating_sub(1); if *bud == 0 { - return; + return } } } @@ -929,7 +929,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 } } // @@ -956,7 +956,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 } } // @@ -993,7 +993,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 }); @@ -1040,11 +1040,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 @@ -1248,7 +1248,7 @@ impl VerifyPooledTransactionsResponse for UnverifiedPooledTransactions { 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 cf4f8af78e0b..14568590252f 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -351,7 +351,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, @@ -383,10 +383,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"); @@ -413,7 +413,7 @@ where ) -> PropagatedTransactions { let mut propagated = PropagatedTransactions::default(); if self.network.tx_gossip_disabled() { - return propagated; + return propagated } // send full transactions to a fraction of the connected peers (square root of the total @@ -523,7 +523,7 @@ where if full_transactions.transactions.is_empty() { // nothing to propagate - return None; + return None } let new_full_transactions = full_transactions.build(); @@ -550,7 +550,7 @@ where let propagated = { let Some(peer) = self.peers.get_mut(&peer_id) else { // no such peer - return; + return }; let to_propagate: Vec = @@ -571,7 +571,7 @@ where if new_pooled_hashes.is_empty() { // nothing to propagate - return; + return } for hash in new_pooled_hashes.iter_hashes().copied() { @@ -599,10 +599,10 @@ where ) { // 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 @@ -613,7 +613,7 @@ where "discarding announcement from inactive peer" ); - return; + return }; let client = peer.client_version.clone(); @@ -674,7 +674,7 @@ where if partially_valid_msg.is_empty() { // nothing to request - return; + return } // 4. filter out invalid entries (spam) @@ -703,7 +703,7 @@ where if valid_announcement_data.is_empty() { // no valid announcement data - return; + return } // 5. filter out already seen unknown hashes @@ -723,7 +723,7 @@ where if valid_announcement_data.is_empty() { // nothing to request - return; + return } trace!(target: "net::tx", @@ -752,7 +752,7 @@ where self.transaction_fetcher.buffer_hashes(hashes, Some(peer_id)); - return; + return } // load message version before announcement data type is destructed in packing @@ -904,7 +904,7 @@ where // `SOFT_LIMIT_COUNT_HASHES_IN_NEW_POOLED_TRANSACTIONS_BROADCAST_MESSAGE` // transactions in the pool. if self.network.is_initially_syncing() || self.network.tx_gossip_disabled() { - return; + return } let pooled_txs = self.pool.pooled_transactions_max( @@ -912,7 +912,7 @@ where ); if pooled_txs.is_empty() { // do not send a message if there are no transactions in the pool - return; + return } let mut msg_builder = PooledTransactionsHashesBuilder::new(version); @@ -937,10 +937,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 }; @@ -990,7 +990,7 @@ where "failed ecrecovery for transaction" ); has_bad_transactions = true; - continue; + continue } }; @@ -1127,7 +1127,7 @@ where RequestError::Timeout => ReputationChangeKind::Timeout, RequestError::ChannelClosed | RequestError::ConnectionDropped => { // peer is already disconnected - return; + return } RequestError::BadResponse => return self.report_peer_bad_transactions(peer_id), }; @@ -1172,7 +1172,7 @@ where // 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) @@ -1348,7 +1348,7 @@ where { // 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); @@ -1399,7 +1399,7 @@ impl FullTransactionsBuilder { if new_size > DEFAULT_SOFT_LIMIT_BYTE_SIZE_TRANSACTIONS_BROADCAST_MESSAGE && self.total_size > 0 { - return; + return } self.total_size = new_size; diff --git a/crates/net/network/src/transactions/validation.rs b/crates/net/network/src/transactions/validation.rs index b40bde4a5f98..931cfdb9e514 100644 --- a/crates/net/network/src/transactions/validation.rs +++ b/crates/net/network/src/transactions/validation.rs @@ -80,7 +80,7 @@ pub trait PartiallyFilterMessage { msg=?msg, "empty payload" ); - return (FilterOutcome::ReportPeer, PartiallyValidData::empty_eth66()); + return (FilterOutcome::ReportPeer, PartiallyValidData::empty_eth66()) } // 2. checks if announcement is spam packed with duplicate hashes @@ -179,7 +179,7 @@ impl ValidateTx68 for EthMessageFilter { "invalid tx type in eth68 announcement" ); - return ValidationOutcome::ReportPeer; + return ValidationOutcome::ReportPeer } }; tx_types_counter.increase_by_tx_type(tx_type); @@ -201,7 +201,7 @@ impl ValidateTx68 for EthMessageFilter { "invalid tx size in eth68 announcement" ); - return ValidationOutcome::Ignore; + return ValidationOutcome::Ignore } } if let Some(reasonable_min_encoded_tx_length) = self.min_encoded_tx_length(tx_type) { diff --git a/crates/net/network/tests/it/multiplex.rs b/crates/net/network/tests/it/multiplex.rs index 471afc562b3f..ae84f43aae3a 100644 --- a/crates/net/network/tests/it/multiplex.rs +++ b/crates/net/network/tests/it/multiplex.rs @@ -111,7 +111,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); @@ -235,7 +235,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 { @@ -245,12 +245,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 { @@ -265,11 +265,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/p2p/src/error.rs b/crates/net/p2p/src/error.rs index df1b38142ace..e005f4ea9253 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -32,7 +32,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 { diff --git a/crates/net/p2p/src/full_block.rs b/crates/net/p2p/src/full_block.rs index 6e3893ba6152..93af03d5b076 100644 --- a/crates/net/p2p/src/full_block.rs +++ b/crates/net/p2p/src/full_block.rs @@ -133,7 +133,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(); @@ -147,7 +147,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::new(header, resp.into_data())) } @@ -159,10 +159,10 @@ where if let Err(err) = ensure_valid_body_response(header, resp.data()) { 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)); } @@ -223,7 +223,7 @@ where } if let Some(res) = this.take_block() { - return Poll::Ready(res); + return Poll::Ready(res) } } } @@ -258,14 +258,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)) } } @@ -303,14 +303,14 @@ fn ensure_valid_body_response( if header.ommers_hash != ommers_hash { return Err(ConsensusError::BodyOmmersHashDiff( GotExpected { got: ommers_hash, expected: header.ommers_hash }.into(), - )); + )) } let tx_root = block.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, &block.withdrawals) { @@ -320,7 +320,7 @@ fn ensure_valid_body_response( if withdrawals_root != header_withdrawals_root { return Err(ConsensusError::BodyWithdrawalsRootDiff( GotExpected { got: withdrawals_root, expected: header_withdrawals_root }.into(), - )); + )) } } (None, None) => { @@ -336,7 +336,7 @@ fn ensure_valid_body_response( if requests_root != header_requests_root { return Err(ConsensusError::BodyRequestsRootDiff( GotExpected { got: requests_root, expected: header_requests_root }.into(), - )); + )) } } (None, None) => { @@ -430,7 +430,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()?; @@ -451,7 +451,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() @@ -476,7 +476,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) @@ -501,7 +501,7 @@ where if let Err(err) = self.consensus.validate_header_range(&headers_rising) { debug!(target: "downloaders", %err, ?self.start_hash, "Received bad header response"); self.client.report_bad_message(peer); - return; + return } // get the bodies request so it can be polled later @@ -629,7 +629,7 @@ where } if let Some(res) = this.take_blocks() { - return Poll::Ready(res); + return Poll::Ready(res) } } } @@ -671,13 +671,13 @@ where if let Some(blocks) = &mut this.blocks { if blocks.is_empty() { // Stream is finished - return Poll::Ready(None); + return Poll::Ready(None) } // return the next block if it's ready - the vec should be in ascending order since it // is reversed right after it is received from the future, so we can just pop() the // elements to return them from the stream in descending order - return Poll::Ready(blocks.pop()); + return Poll::Ready(blocks.pop()) } // poll the inner future if the blocks are not yet ready @@ -717,14 +717,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 41c26da713fe..73dd04849d44 100644 --- a/crates/net/p2p/src/test_utils/headers.rs +++ b/crates/net/p2p/src/test_utils/headers.rs @@ -76,7 +76,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()); @@ -136,9 +136,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) } let empty = SealedHeader::default(); @@ -148,7 +148,7 @@ impl Stream for TestDownload { hash: empty.hash(), number: empty.number, error: Box::new(error), - }))); + }))) } match ready!(this.get_or_init_fut().poll_unpin(cx)) { @@ -159,14 +159,14 @@ impl Stream for TestDownload { headers.sort_unstable_by_key(|h| h.number); headers.into_iter().for_each(|h| this.buffer.push(h)); this.done = true; - continue; + continue } Err(err) => { this.done = true; return Poll::Ready(Some(Err(match err { RequestError::Timeout => DownloadError::Timeout, _ => DownloadError::RequestError(err), - }))); + }))) } } } @@ -231,7 +231,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 1da12cd4a3a1..f531f1eb8f09 100644 --- a/crates/net/peers/src/lib.rs +++ b/crates/net/peers/src/lib.rs @@ -160,17 +160,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 090ef67e0e00..3b6c38170d56 100644 --- a/crates/net/peers/src/node_record.rs +++ b/crates/net/peers/src/node_record.rs @@ -63,7 +63,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 @@ -192,15 +192,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/net/peers/src/trusted_peer.rs b/crates/net/peers/src/trusted_peer.rs index bd1923dcc612..27096bcab3d8 100644 --- a/crates/net/peers/src/trusted_peer.rs +++ b/crates/net/peers/src/trusted_peer.rs @@ -53,14 +53,14 @@ impl TrustedPeer { let tcp_port = self.tcp_port; let udp_port = self.udp_port; - return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }); + return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }) } Host::Ipv6(ip) => { let id = self.id; let tcp_port = self.tcp_port; let udp_port = self.udp_port; - return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }); + return Ok(NodeRecord { address: ip.into(), id, tcp_port, udp_port }) } Host::Domain(domain) => domain, }; diff --git a/crates/node-core/src/args/payload_builder.rs b/crates/node-core/src/args/payload_builder.rs index a22074c01228..b6a937156de5 100644 --- a/crates/node-core/src/args/payload_builder.rs +++ b/crates/node-core/src/args/payload_builder.rs @@ -91,7 +91,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/args/pruning.rs b/crates/node-core/src/args/pruning.rs index 5e20aef8d727..1621f2d8ed8b 100644 --- a/crates/node-core/src/args/pruning.rs +++ b/crates/node-core/src/args/pruning.rs @@ -19,7 +19,7 @@ impl PruningArgs { /// Returns pruning configuration. pub fn prune_config(&self, chain_spec: &ChainSpec) -> Option { if !self.full { - return None; + return None } Some(PruneConfig { block_interval: 5, diff --git a/crates/node-core/src/args/utils.rs b/crates/node-core/src/args/utils.rs index 13a6afcfa1d0..527e1ac228ac 100644 --- a/crates/node-core/src/args/utils.rs +++ b/crates/node-core/src/args/utils.rs @@ -99,7 +99,7 @@ pub fn genesis_value_parser(s: &str) -> eyre::Result, eyre::Error if s.contains('{') { s.to_string() } else { - return Err(io_err.into()); // assume invalid path + return Err(io_err.into()) // assume invalid path } } }; @@ -149,15 +149,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()? diff --git a/crates/node-core/src/engine/skip_fcu.rs b/crates/node-core/src/engine/skip_fcu.rs index 729e79b75c31..d63894a5c951 100644 --- a/crates/node-core/src/engine/skip_fcu.rs +++ b/crates/node-core/src/engine/skip_fcu.rs @@ -50,7 +50,7 @@ where *this.skipped += 1; tracing::warn!(target: "engine::intercept", ?state, ?payload_attrs, threshold=this.threshold, skipped=this.skipped, "Skipping FCU"); let _ = tx.send(Ok(OnForkChoiceUpdated::syncing())); - continue; + continue } else { *this.skipped = 0; Some(BeaconEngineMessage::ForkchoiceUpdated { state, payload_attrs, tx }) @@ -58,7 +58,7 @@ where } next => next, }; - return Poll::Ready(item); + return Poll::Ready(item) } } } diff --git a/crates/node-core/src/engine/skip_new_payload.rs b/crates/node-core/src/engine/skip_new_payload.rs index a8e063b41986..04db70e0a676 100644 --- a/crates/node-core/src/engine/skip_new_payload.rs +++ b/crates/node-core/src/engine/skip_new_payload.rs @@ -53,7 +53,7 @@ where skipped=this.skipped, "Skipping new payload" ); let _ = tx.send(Ok(PayloadStatus::from_status(PayloadStatusEnum::Syncing))); - continue; + continue } else { *this.skipped = 0; Some(BeaconEngineMessage::NewPayload { payload, cancun_fields, tx }) @@ -61,7 +61,7 @@ where } next => next, }; - return Poll::Ready(item); + return Poll::Ready(item) } } } diff --git a/crates/node-core/src/metrics/prometheus_exporter.rs b/crates/node-core/src/metrics/prometheus_exporter.rs index 11e1891b7295..b7a3ba7015c3 100644 --- a/crates/node-core/src/metrics/prometheus_exporter.rs +++ b/crates/node-core/src/metrics/prometheus_exporter.rs @@ -164,7 +164,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() @@ -253,13 +253,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/node-core/src/node_config.rs b/crates/node-core/src/node_config.rs index a731e6d3aa58..3a3b742cef02 100644 --- a/crates/node-core/src/node_config.rs +++ b/crates/node-core/src/node_config.rs @@ -352,7 +352,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) @@ -375,7 +375,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/builder/src/launch/exex.rs b/crates/node/builder/src/launch/exex.rs index 696978ae55ab..103223357c7c 100644 --- a/crates/node/builder/src/launch/exex.rs +++ b/crates/node/builder/src/launch/exex.rs @@ -37,7 +37,7 @@ impl ExExLauncher { if extensions.is_empty() { // nothing to launch - return None; + return None } let mut exex_handles = Vec::with_capacity(extensions.len()); diff --git a/crates/node/events/src/cl.rs b/crates/node/events/src/cl.rs index 0ad05b723038..47f1de6683f0 100644 --- a/crates/node/events/src/cl.rs +++ b/crates/node/events/src/cl.rs @@ -52,14 +52,14 @@ 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 } else { // We had an FCU, but it's too old. return Poll::Ready(Some( ConsensusLayerHealthEvent::HaveNotReceivedUpdatesForAWhile( fork_choice.elapsed(), ), - )); + )) } } @@ -74,11 +74,11 @@ impl Stream for ConsensusLayerHealthEvents { Poll::Ready(Some(ConsensusLayerHealthEvent::HasNotBeenSeenForAWhile( transition_config.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 352c1a382366..8a25c370037b 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -614,7 +614,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(); @@ -622,7 +622,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(); @@ -663,7 +663,7 @@ impl Display for Eta { f, "{}", humantime::format_duration(Duration::from_secs(remaining.as_secs())) - ); + ) } } diff --git a/crates/optimism/consensus/src/lib.rs b/crates/optimism/consensus/src/lib.rs index a3561a0c8267..0c5439bf7448 100644 --- a/crates/optimism/consensus/src/lib.rs +++ b/crates/optimism/consensus/src/lib.rs @@ -83,11 +83,11 @@ impl Consensus for OptimismBeaconConsensus { if is_post_merge { if header.nonce != 0 { - 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 @@ -112,7 +112,7 @@ impl Consensus for OptimismBeaconConsensus { return Err(ConsensusError::TimestampIsInFuture { timestamp: header.timestamp, present_timestamp, - }); + }) } } diff --git a/crates/optimism/consensus/src/validation.rs b/crates/optimism/consensus/src/validation.rs index 8e582f2bab11..8aa00c53cec4 100644 --- a/crates/optimism/consensus/src/validation.rs +++ b/crates/optimism/consensus/src/validation.rs @@ -27,7 +27,7 @@ pub fn validate_block_post_execution( block.timestamp, ) { tracing::debug!(%error, ?receipts, "receipts verification failed"); - return Err(error); + return Err(error) } } @@ -38,7 +38,7 @@ pub fn validate_block_post_execution( return Err(ConsensusError::BlockGasUsed { gas: GotExpected { got: cumulative_gas_used, expected: block.gas_used }, gas_spent_by_tx: gas_spent_by_transactions(receipts), - }); + }) } Ok(()) @@ -81,13 +81,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/evm/src/execute.rs b/crates/optimism/evm/src/execute.rs index ee30920eb2eb..a3062b89aae8 100644 --- a/crates/optimism/evm/src/execute.rs +++ b/crates/optimism/evm/src/execute.rs @@ -153,12 +153,12 @@ where transaction_gas_limit: transaction.gas_limit(), block_available_gas, } - .into()); + .into()) } // An optimism block should never contain blob transactions. if matches!(transaction.tx_type(), TxType::Eip4844) { - return Err(OptimismBlockExecutionError::BlobTransactionRejected.into()); + return Err(OptimismBlockExecutionError::BlobTransactionRejected.into()) } // Cache the depositor account prior to the state transition for the deposit nonce. diff --git a/crates/optimism/evm/src/l1.rs b/crates/optimism/evm/src/l1.rs index 3096fa5112f8..a750c8f4f0a9 100644 --- a/crates/optimism/evm/src/l1.rs +++ b/crates/optimism/evm/src/l1.rs @@ -40,7 +40,7 @@ pub fn extract_l1_info(block: &Block) -> Result Result Result Result { if is_deposit { - return Ok(U256::ZERO); + return Ok(U256::ZERO) } let spec_id = if chain_spec.is_fork_active_at_timestamp(Hardfork::Fjord, timestamp) { @@ -203,7 +203,7 @@ impl RethL1BlockInfo for L1BlockInfo { return Err(OptimismBlockExecutionError::L1BlockInfoError { message: "Optimism hardforks are not active".to_string(), } - .into()); + .into()) }; Ok(self.calculate_tx_l1_cost(input, spec_id)) } @@ -224,7 +224,7 @@ impl RethL1BlockInfo for L1BlockInfo { return Err(OptimismBlockExecutionError::L1BlockInfoError { message: "Optimism hardforks are not active".to_string(), } - .into()); + .into()) }; Ok(self.data_gas(input, spec_id)) } @@ -264,7 +264,7 @@ where // Commit the create2 deployer account to the database. db.commit(HashMap::from([(CREATE_2_DEPLOYER_ADDR, revm_acc)])); - return Ok(()); + return Ok(()) } Ok(()) diff --git a/crates/optimism/node/src/engine.rs b/crates/optimism/node/src/engine.rs index 5169f1e80ba5..6507d5c9290f 100644 --- a/crates/optimism/node/src/engine.rs +++ b/crates/optimism/node/src/engine.rs @@ -75,21 +75,21 @@ pub fn validate_withdrawals_presence( EngineApiMessageVersion::V1 => { if has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)); + .to_error(VersionSpecificValidationError::WithdrawalsNotSupportedInV1)) } if is_shanghai { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) } } EngineApiMessageVersion::V2 | EngineApiMessageVersion::V3 | EngineApiMessageVersion::V4 => { if is_shanghai && !has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)); + .to_error(VersionSpecificValidationError::NoWithdrawalsPostShanghai)) } if !is_shanghai && has_withdrawals { return Err(message_validation_kind - .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)); + .to_error(VersionSpecificValidationError::HasWithdrawalsPreShanghai)) } } }; diff --git a/crates/optimism/node/src/txpool.rs b/crates/optimism/node/src/txpool.rs index 67a1b1f3df08..b29bc4bb0303 100644 --- a/crates/optimism/node/src/txpool.rs +++ b/crates/optimism/node/src/txpool.rs @@ -97,7 +97,7 @@ where return TransactionValidationOutcome::Invalid( transaction, InvalidTransactionError::TxTypeNotSupported.into(), - ); + ) } let outcome = self.inner.validate_one(origin, transaction); @@ -136,7 +136,7 @@ where GotExpected { got: balance, expected: cost }.into(), ) .into(), - ); + ) } return TransactionValidationOutcome::Valid { @@ -144,7 +144,7 @@ where state_nonce, transaction: valid_tx, propagate, - }; + } } outcome diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index 7379e4f3d268..d0289efc8bd6 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -311,14 +311,14 @@ where for sequencer_tx in &attributes.transactions { // Check if the job was cancelled, if so we can exit early. if cancel.is_cancelled() { - return Ok(BuildOutcome::Cancelled); + return Ok(BuildOutcome::Cancelled) } // A sequencer's block should never contain blob transactions. if sequencer_tx.is_eip4844() { return Err(PayloadBuilderError::other( OptimismPayloadBuilderError::BlobTransactionRejected, - )); + )) } // Convert the transaction to a [TransactionSignedEcRecovered]. This is @@ -360,11 +360,11 @@ where match err { EVMError::Transaction(err) => { trace!(target: "payload_builder", %err, ?sequencer_tx, "Error in sequencer transaction, skipping."); - continue; + continue } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)); + return Err(PayloadBuilderError::EvmExecutionError(err)) } } } @@ -410,7 +410,7 @@ where // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(&pool_tx); - continue; + continue } // A sequencer's block should never contain blob or deposit transactions from the pool. @@ -420,7 +420,7 @@ where // 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 @@ -449,11 +449,11 @@ where best_txs.mark_invalid(&pool_tx); } - continue; + continue } err => { // this is an error that we should treat as fatal for this attempt - return Err(PayloadBuilderError::EvmExecutionError(err)); + return Err(PayloadBuilderError::EvmExecutionError(err)) } } } @@ -493,7 +493,7 @@ where // check if we have a better block if !is_better_payload(best_payload.as_ref(), total_fees) { // can skip building the block - return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }); + return Ok(BuildOutcome::Aborted { fees: total_fees, cached_reads }) } let WithdrawalsOutcome { withdrawals_root, withdrawals } = commit_withdrawals( diff --git a/crates/optimism/primitives/src/bedrock_import.rs b/crates/optimism/primitives/src/bedrock_import.rs index 5ced80835ac4..17020f9f2b90 100644 --- a/crates/optimism/primitives/src/bedrock_import.rs +++ b/crates/optimism/primitives/src/bedrock_import.rs @@ -40,12 +40,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/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 65d2eea56102..26dc06293404 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -412,7 +412,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 @@ -473,7 +473,7 @@ where fn best_payload(&self) -> Result { if let Some(ref payload) = self.best_payload { - return Ok(payload.clone()); + return Ok(payload.clone()) } // No payload has been built yet, but we need to return something that the CL then can // deliver, so we need to return an empty payload. @@ -591,14 +591,14 @@ where this.maybe_better = None; if let Ok(BuildOutcome::Better { payload, .. }) = res { debug!(target: "payload_builder", "resolving better payload"); - return Poll::Ready(Ok(payload)); + return Poll::Ready(Ok(payload)) } } } 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() { @@ -614,12 +614,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 @@ -902,11 +902,11 @@ pub fn commit_withdrawals>( withdrawals: Withdrawals, ) -> Result { if !chain_spec.is_shanghai_active_at_timestamp(timestamp) { - return Ok(WithdrawalsOutcome::pre_shanghai()); + return Ok(WithdrawalsOutcome::pre_shanghai()) } if withdrawals.is_empty() { - return Ok(WithdrawalsOutcome::empty()); + return Ok(WithdrawalsOutcome::empty()) } let balance_increments = diff --git a/crates/payload/builder/src/noop.rs b/crates/payload/builder/src/noop.rs index 9cb1a8d66799..ef919ecf76e8 100644 --- a/crates/payload/builder/src/noop.rs +++ b/crates/payload/builder/src/noop.rs @@ -43,7 +43,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 d0a39799cd49..98790ef7d8b7 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -446,7 +446,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 b2729030913c..52029a3c4a37 100644 --- a/crates/payload/primitives/src/lib.rs +++ b/crates/payload/primitives/src/lib.rs @@ -67,7 +67,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 == EngineApiMessageVersion::V3 && !is_cancun { @@ -89,7 +89,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); @@ -112,7 +112,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) } Ok(()) } @@ -133,17 +133,17 @@ 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 => { 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)) } } }; @@ -234,13 +234,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 => { if !has_parent_beacon_block_root { return Err(validation_kind - .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)); + .to_error(VersionSpecificValidationError::NoParentBeaconBlockRootPostCancun)) } } }; diff --git a/crates/payload/primitives/src/traits.rs b/crates/payload/primitives/src/traits.rs index 259b14b3f6e3..094fe829234e 100644 --- a/crates/payload/primitives/src/traits.rs +++ b/crates/payload/primitives/src/traits.rs @@ -150,7 +150,7 @@ impl PayloadAttributes for OptimismPayloadAttributes { if self.gas_limit.is_none() && chain_spec.is_optimism() { return Err(EngineObjectValidationError::InvalidParams( "MissingGasLimitInPayloadAttributes".to_string().into(), - )); + )) } Ok(()) diff --git a/crates/payload/validator/src/lib.rs b/crates/payload/validator/src/lib.rs index e5cfd94c4dc7..afc19037732d 100644 --- a/crates/payload/validator/src/lib.rs +++ b/crates/payload/validator/src/lib.rs @@ -59,20 +59,20 @@ impl ExecutionPayloadValidator { if let Some(versioned_hashes) = cancun_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(sealed_block.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) } } @@ -118,45 +118,45 @@ impl ExecutionPayloadValidator { return Err(PayloadError::BlockHash { execution: sealed_block.hash(), consensus: expected_hash, - }); + }) } if self.is_cancun_active_at_timestamp(sealed_block.timestamp) { if sealed_block.header.blob_gas_used.is_none() { // cancun active but blob gas used not present - return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed); + return Err(PayloadError::PostCancunBlockWithoutBlobGasUsed) } if sealed_block.header.excess_blob_gas.is_none() { // cancun active but excess blob gas not present - return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas); + return Err(PayloadError::PostCancunBlockWithoutExcessBlobGas) } if cancun_fields.as_ref().is_none() { // cancun active but cancun fields not present - return Err(PayloadError::PostCancunWithoutCancunFields); + return Err(PayloadError::PostCancunWithoutCancunFields) } } else { if sealed_block.has_blob_transactions() { // cancun not active but blob transactions present - return Err(PayloadError::PreCancunBlockWithBlobTransactions); + return Err(PayloadError::PreCancunBlockWithBlobTransactions) } if sealed_block.header.blob_gas_used.is_some() { // cancun not active but blob gas used present - return Err(PayloadError::PreCancunBlockWithBlobGasUsed); + return Err(PayloadError::PreCancunBlockWithBlobGasUsed) } if sealed_block.header.excess_blob_gas.is_some() { // cancun not active but excess blob gas present - return Err(PayloadError::PreCancunBlockWithExcessBlobGas); + return Err(PayloadError::PreCancunBlockWithExcessBlobGas) } if cancun_fields.as_ref().is_some() { // cancun not active but cancun fields present - return Err(PayloadError::PreCancunWithCancunFields); + return Err(PayloadError::PreCancunWithCancunFields) } } let shanghai_active = self.is_shanghai_active_at_timestamp(sealed_block.timestamp); if !shanghai_active && sealed_block.withdrawals.is_some() { // shanghai not active but withdrawals present - return Err(PayloadError::PreShanghaiBlockWithWitdrawals); + return Err(PayloadError::PreShanghaiBlockWithWitdrawals) } // EIP-4844 checks diff --git a/crates/primitives-traits/src/header/mod.rs b/crates/primitives-traits/src/header/mod.rs index 1235fb86bdf1..5ec41d41450c 100644 --- a/crates/primitives-traits/src/header/mod.rs +++ b/crates/primitives-traits/src/header/mod.rs @@ -155,7 +155,7 @@ impl Header { /// Returns an error if the extradata size is larger than 100 KB. pub fn ensure_extradata_valid(&self) -> Result<(), HeaderError> { if self.extra_data.len() > 100 * 1024 { - return Err(HeaderError::LargeExtraData); + return Err(HeaderError::LargeExtraData) } Ok(()) } @@ -167,7 +167,7 @@ impl Header { /// Returns an error if the block difficulty exceeds 80 bits. pub fn ensure_difficulty_valid(&self) -> Result<(), HeaderError> { if self.difficulty.bit_len() > 80 { - return Err(HeaderError::LargeDifficulty); + return Err(HeaderError::LargeDifficulty) } Ok(()) } @@ -435,7 +435,7 @@ impl Decodable for Header { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { let rlp_head = alloy_rlp::Header::decode(buf)?; if !rlp_head.list { - return Err(alloy_rlp::Error::UnexpectedString); + return Err(alloy_rlp::Error::UnexpectedString) } let started_len = buf.len(); let mut this = Self { @@ -502,7 +502,7 @@ impl Decodable for Header { return Err(alloy_rlp::Error::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } Ok(this) } diff --git a/crates/primitives/src/alloy_compat.rs b/crates/primitives/src/alloy_compat.rs index 20b3ef9ac22e..d193b787fd52 100644 --- a/crates/primitives/src/alloy_compat.rs +++ b/crates/primitives/src/alloy_compat.rs @@ -82,7 +82,7 @@ impl TryFrom for Transaction { return Err(ConversionError::Eip2718Error( RlpError::Custom("EIP-1559 fields are present in a legacy transaction") .into(), - )); + )) } // extract the chain id if possible @@ -98,7 +98,7 @@ impl TryFrom for Transaction { .map_err(|err| ConversionError::Eip2718Error(err.into()))? .1 } else { - return Err(ConversionError::MissingChainId); + return Err(ConversionError::MissingChainId) } } }; diff --git a/crates/primitives/src/block.rs b/crates/primitives/src/block.rs index 4a65b7329229..1e14392bffb6 100644 --- a/crates/primitives/src/block.rs +++ b/crates/primitives/src/block.rs @@ -126,7 +126,7 @@ impl Block { let Some(senders) = TransactionSigned::recover_signers_unchecked(&self.body, self.body.len()) else { - return Err(self); + return Err(self) }; senders }; @@ -430,7 +430,7 @@ impl SealedBlock { return Err(GotExpected { got: calculated_root, expected: self.header.transactions_root, - }); + }) } Ok(()) diff --git a/crates/primitives/src/compression/mod.rs b/crates/primitives/src/compression/mod.rs index 4b039b5a627f..f7af0acbe4de 100644 --- a/crates/primitives/src/compression/mod.rs +++ b/crates/primitives/src/compression/mod.rs @@ -74,7 +74,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/primitives/src/lib.rs b/crates/primitives/src/lib.rs index 771417678183..b965de1673df 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -62,7 +62,7 @@ pub use error::{GotExpected, GotExpectedBoxed}; pub use genesis::{ChainConfig, Genesis, GenesisAccount}; pub use header::{Header, HeadersDirection, SealedHeader}; pub use integer_list::IntegerList; -pub use log::{logs_bloom, Log, LogData}; +pub use log::{logs_bloom, Log}; pub use receipt::{ gas_spent_by_transactions, Receipt, ReceiptWithBloom, ReceiptWithBloomRef, Receipts, }; diff --git a/crates/primitives/src/log.rs b/crates/primitives/src/log.rs index 9d04fed387e0..b2b6b8a4852c 100644 --- a/crates/primitives/src/log.rs +++ b/crates/primitives/src/log.rs @@ -1,6 +1,6 @@ use crate::Bloom; -pub use alloy_primitives::{Log, LogData}; +pub use alloy_primitives::Log; /// Calculate receipt logs bloom. pub fn logs_bloom<'a>(logs: impl IntoIterator) -> Bloom { diff --git a/crates/primitives/src/proofs.rs b/crates/primitives/src/proofs.rs index bce08ceabfca..4e40dd480cff 100644 --- a/crates/primitives/src/proofs.rs +++ b/crates/primitives/src/proofs.rs @@ -64,7 +64,7 @@ pub fn calculate_receipt_root_optimism( return ordered_trie_root_with_encoder(receipts.as_slice(), |r, buf| { r.encode_inner(buf, false) - }); + }) } ordered_trie_root_with_encoder(receipts, |r, buf| r.encode_inner(buf, false)) @@ -112,7 +112,7 @@ pub fn calculate_receipt_root_no_memo_optimism( return ordered_trie_root_with_encoder(&receipts, |r, buf| { ReceiptWithBloomRef::from(r).encode_inner(buf, false) - }); + }) } ordered_trie_root_with_encoder(receipts, |r, buf| { @@ -124,7 +124,7 @@ pub fn calculate_receipt_root_no_memo_optimism( pub fn calculate_ommers_root(ommers: &[Header]) -> B256 { // Check if `ommers` list is empty if ommers.is_empty() { - return EMPTY_OMMER_ROOT_HASH; + return EMPTY_OMMER_ROOT_HASH } // RLP Encode let mut ommers_rlp = Vec::new(); diff --git a/crates/primitives/src/receipt.rs b/crates/primitives/src/receipt.rs index 1e9b983f1ae0..da84dda8b4a7 100644 --- a/crates/primitives/src/receipt.rs +++ b/crates/primitives/src/receipt.rs @@ -295,7 +295,7 @@ impl ReceiptWithBloom { let b = &mut &**buf; let rlp_head = alloy_rlp::Header::decode(b)?; if !rlp_head.list { - return Err(alloy_rlp::Error::UnexpectedString); + return Err(alloy_rlp::Error::UnexpectedString) } let started_len = b.len(); @@ -340,7 +340,7 @@ impl ReceiptWithBloom { return Err(alloy_rlp::Error::ListLengthMismatch { expected: rlp_head.payload_length, got: consumed, - }); + }) } *buf = *b; Ok(this) @@ -493,7 +493,7 @@ impl<'a> ReceiptWithBloomEncoder<'a> { fn encode_inner(&self, out: &mut dyn BufMut, with_header: bool) { if matches!(self.receipt.tx_type, TxType::Legacy) { self.encode_fields(out); - return; + return } let mut payload = Vec::new(); diff --git a/crates/primitives/src/revm/config.rs b/crates/primitives/src/revm/config.rs index 5c424b355c30..6ad76123f149 100644 --- a/crates/primitives/src/revm/config.rs +++ b/crates/primitives/src/revm/config.rs @@ -19,7 +19,7 @@ pub fn revm_spec_by_timestamp_after_merge( revm_primitives::REGOLITH } else { revm_primitives::BEDROCK - }; + } } if chain_spec.is_prague_active_at_timestamp(timestamp) { @@ -38,15 +38,15 @@ pub fn revm_spec(chain_spec: &ChainSpec, block: Head) -> revm_primitives::SpecId #[cfg(feature = "optimism")] if chain_spec.is_optimism() { if chain_spec.fork(Hardfork::Fjord).active_at_head(&block) { - return revm_primitives::FJORD; + return revm_primitives::FJORD } else if chain_spec.fork(Hardfork::Ecotone).active_at_head(&block) { - return revm_primitives::ECOTONE; + return revm_primitives::ECOTONE } else if chain_spec.fork(Hardfork::Canyon).active_at_head(&block) { - return revm_primitives::CANYON; + return revm_primitives::CANYON } else if chain_spec.fork(Hardfork::Regolith).active_at_head(&block) { - return revm_primitives::REGOLITH; + return revm_primitives::REGOLITH } else if chain_spec.fork(Hardfork::Bedrock).active_at_head(&block) { - return revm_primitives::BEDROCK; + return revm_primitives::BEDROCK } } diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 471c9c4269f1..42e420a5e9f7 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -388,7 +388,7 @@ impl Transaction { // Check if max_fee_per_gas is less than base_fee if max_fee_per_gas < base_fee { - return None; + return None } // Calculate the difference between max_fee_per_gas and base_fee @@ -773,7 +773,7 @@ impl TransactionSignedNoHash { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from); + return Some(from) } let signature_hash = self.signature_hash(); @@ -802,7 +802,7 @@ impl TransactionSignedNoHash { #[cfg(feature = "optimism")] { if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from); + return Some(from) } // pre bedrock system transactions were sent from the zero address as legacy @@ -810,7 +810,7 @@ impl TransactionSignedNoHash { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if self.is_legacy() && self.signature == Signature::optimism_deposit_tx_signature() { - return Some(Address::ZERO); + return Some(Address::ZERO) } } @@ -1026,7 +1026,7 @@ impl TransactionSigned { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from); + return Some(from) } let signature_hash = self.signature_hash(); self.signature.recover_signer(signature_hash) @@ -1042,7 +1042,7 @@ impl TransactionSigned { // `from` address. #[cfg(feature = "optimism")] if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction { - return Some(from); + return Some(from) } let signature_hash = self.signature_hash(); self.signature.recover_signer_unchecked(signature_hash) @@ -1216,7 +1216,7 @@ impl TransactionSigned { let transaction_payload_len = header.payload_length; if transaction_payload_len > remaining_len { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } let mut transaction = TxLegacy { @@ -1234,7 +1234,7 @@ impl TransactionSigned { // check the new length, compared to the original length and the header length let decoded = remaining_len - data.len(); if decoded != transaction_payload_len { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } let tx_length = header.payload_length + header.length(); @@ -1279,7 +1279,7 @@ impl TransactionSigned { // decode the list header for the rest of the transaction let header = Header::decode(data)?; if !header.list { - return Err(RlpError::Custom("typed tx fields must be encoded as a list")); + return Err(RlpError::Custom("typed tx fields must be encoded as a list")) } let remaining_len = data.len(); @@ -1289,7 +1289,7 @@ impl TransactionSigned { // decode common fields let Ok(tx_type) = TxType::try_from(tx_type) else { - return Err(RlpError::Custom("unsupported typed transaction type")); + return Err(RlpError::Custom("unsupported typed transaction type")) }; let transaction = match tx_type { @@ -1313,7 +1313,7 @@ impl TransactionSigned { let bytes_consumed = remaining_len - data.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } let hash = keccak256(&original_encoding_without_header[..tx_length]); @@ -1340,7 +1340,7 @@ impl TransactionSigned { /// of bytes in input data. pub fn decode_enveloped(input_data: &mut &[u8]) -> alloy_rlp::Result { if input_data.is_empty() { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } // Check if the tx is a list @@ -1352,7 +1352,7 @@ impl TransactionSigned { }; if !input_data.is_empty() { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } Ok(output_data) @@ -1430,7 +1430,7 @@ impl Decodable for TransactionSigned { /// string header if the first byte is less than `0xf7`. fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { if buf.is_empty() { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } // decode header @@ -1448,7 +1448,7 @@ impl Decodable for TransactionSigned { // string Header with payload_length of 1, we need to make sure this check is only // performed for transactions with a string header if bytes_consumed != header.payload_length && original_encoding[0] > EMPTY_STRING_CODE { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } Ok(tx) diff --git a/crates/primitives/src/transaction/pooled.rs b/crates/primitives/src/transaction/pooled.rs index 23864823e6d5..2ca58b179748 100644 --- a/crates/primitives/src/transaction/pooled.rs +++ b/crates/primitives/src/transaction/pooled.rs @@ -183,7 +183,7 @@ impl PooledTransactionsElement { /// `[chain_id, nonce, max_priority_fee_per_gas, ..., y_parity, r, s]` pub fn decode_enveloped(data: &mut &[u8]) -> alloy_rlp::Result { if data.is_empty() { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } // Check if the tx is a list - tx types are less than EMPTY_LIST_CODE (0xc0) @@ -493,7 +493,7 @@ impl Decodable for PooledTransactionsElement { // // First, we check whether or not the transaction is a legacy transaction. if buf.is_empty() { - return Err(RlpError::InputTooShort); + return Err(RlpError::InputTooShort) } // keep the original buf around for legacy decoding @@ -539,7 +539,7 @@ impl Decodable for PooledTransactionsElement { // check that the bytes consumed match the payload length let bytes_consumed = remaining_len - buf.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } Ok(Self::BlobTransaction(blob_tx)) @@ -551,7 +551,7 @@ impl Decodable for PooledTransactionsElement { // check that the bytes consumed match the payload length let bytes_consumed = remaining_len - buf.len(); if bytes_consumed != header.payload_length { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } // because we checked the tx type, we can be sure that the transaction is not a diff --git a/crates/primitives/src/transaction/sidecar.rs b/crates/primitives/src/transaction/sidecar.rs index eb6762a57ff5..c45683ce7980 100644 --- a/crates/primitives/src/transaction/sidecar.rs +++ b/crates/primitives/src/transaction/sidecar.rs @@ -216,7 +216,7 @@ impl BlobTransaction { // decode the _first_ list header for the rest of the transaction let outer_header = Header::decode(data)?; if !outer_header.list { - return Err(RlpError::Custom("PooledTransactions blob tx must be encoded as a list")); + return Err(RlpError::Custom("PooledTransactions blob tx must be encoded as a list")) } let outer_remaining_len = data.len(); @@ -228,7 +228,7 @@ impl BlobTransaction { if !inner_header.list { return Err(RlpError::Custom( "PooledTransactions inner blob tx must be encoded as a list", - )); + )) } let inner_remaining_len = data.len(); @@ -242,7 +242,7 @@ impl BlobTransaction { // the inner header only decodes the transaction and signature, so we check the length here let inner_consumed = inner_remaining_len - data.len(); if inner_consumed != inner_header.payload_length { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } // All that's left are the blobs, commitments, and proofs @@ -271,7 +271,7 @@ impl BlobTransaction { // the outer header is for the entire transaction, so we check the length here let outer_consumed = outer_remaining_len - data.len(); if outer_consumed != outer_header.payload_length { - return Err(RlpError::UnexpectedLength); + return Err(RlpError::UnexpectedLength) } Ok(Self { transaction, hash, signature, sidecar }) @@ -357,7 +357,7 @@ mod tests { // Ensure the entry is a file and not a directory if !file_path.is_file() || file_path.extension().unwrap_or_default() != "json" { - continue; + continue } // Read the contents of the JSON file into a string. diff --git a/crates/primitives/src/transaction/signature.rs b/crates/primitives/src/transaction/signature.rs index 3176f8934561..077858a3c579 100644 --- a/crates/primitives/src/transaction/signature.rs +++ b/crates/primitives/src/transaction/signature.rs @@ -89,7 +89,7 @@ impl Signature { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if *self == Self::optimism_deposit_tx_signature() { - return 0; + return 0 } self.odd_y_parity as u64 + 27 } @@ -113,7 +113,7 @@ impl Signature { // // NOTE: this is very hacky and only relevant for op-mainnet pre bedrock if v == 0 && r.is_zero() && s.is_zero() { - return Ok((Self { r, s, odd_y_parity: false }, None)); + return Ok((Self { r, s, odd_y_parity: false }, None)) } } } @@ -168,7 +168,7 @@ impl Signature { /// If the S value is too large, then this will return `None` pub fn recover_signer(&self, hash: B256) -> Option
{ if self.s > SECP256K1N_HALF { - return None; + return None } self.recover_signer_unchecked(hash) @@ -204,7 +204,7 @@ pub const fn extract_chain_id(v: u64) -> alloy_rlp::Result<(bool, Option)> if v < 35 { // non-EIP-155 legacy scheme, v = 27 for even y-parity, v = 28 for odd y-parity if v != 27 && v != 28 { - return Err(RlpError::Custom("invalid Ethereum signature (V is not 27 or 28)")); + return Err(RlpError::Custom("invalid Ethereum signature (V is not 27 or 28)")) } Ok((v == 28, None)) } else { diff --git a/crates/primitives/src/transaction/tx_type.rs b/crates/primitives/src/transaction/tx_type.rs index fc99458b2e6b..7530fda086f8 100644 --- a/crates/primitives/src/transaction/tx_type.rs +++ b/crates/primitives/src/transaction/tx_type.rs @@ -87,17 +87,17 @@ impl TryFrom for TxType { fn try_from(value: u8) -> Result { #[cfg(feature = "optimism")] if value == Self::Deposit { - return Ok(Self::Deposit); + return Ok(Self::Deposit) } if value == Self::Legacy { - return Ok(Self::Legacy); + return Ok(Self::Legacy) } else if value == Self::Eip2930 { - return Ok(Self::Eip2930); + return Ok(Self::Eip2930) } else if value == Self::Eip1559 { - return Ok(Self::Eip1559); + return Ok(Self::Eip1559) } else if value == Self::Eip4844 { - return Ok(Self::Eip4844); + return Ok(Self::Eip4844) } Err("invalid tx type") diff --git a/crates/prune/prune/Cargo.toml b/crates/prune/prune/Cargo.toml index 016265e1b5c6..c45ea9d3f7f1 100644 --- a/crates/prune/prune/Cargo.toml +++ b/crates/prune/prune/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] # reth +reth-chainspec.workspace = true reth-exex-types.workspace = true reth-primitives.workspace = true reth-db.workspace = true diff --git a/crates/prune/prune/src/builder.rs b/crates/prune/prune/src/builder.rs index a91a0faa6d51..233e80a71a9a 100644 --- a/crates/prune/prune/src/builder.rs +++ b/crates/prune/prune/src/builder.rs @@ -1,8 +1,8 @@ use crate::{segments::SegmentSet, Pruner}; +use reth_chainspec::MAINNET; use reth_config::PruneConfig; use reth_db_api::database::Database; use reth_exex_types::FinishedExExHeight; -use reth_primitives::MAINNET; use reth_provider::ProviderFactory; use reth_prune_types::PruneModes; use std::time::Duration; diff --git a/crates/prune/prune/src/pruner.rs b/crates/prune/prune/src/pruner.rs index da805c77fa77..47864a274e03 100644 --- a/crates/prune/prune/src/pruner.rs +++ b/crates/prune/prune/src/pruner.rs @@ -332,9 +332,9 @@ impl Pruner { mod tests { use crate::Pruner; + use reth_chainspec::MAINNET; use reth_db::test_utils::{create_test_rw_db, create_test_static_files_dir}; use reth_exex_types::FinishedExExHeight; - use reth_primitives::MAINNET; use reth_provider::{providers::StaticFileProvider, ProviderFactory}; #[test] diff --git a/crates/revm/src/batch.rs b/crates/revm/src/batch.rs index 7b1980cdc22c..6f1b55b2195d 100644 --- a/crates/revm/src/batch.rs +++ b/crates/revm/src/batch.rs @@ -137,7 +137,7 @@ impl BlockBatchRecord { self.prune_modes.receipts.map_or(false, |mode| mode.should_prune(block_number, tip)) { receipts.clear(); - return Ok(()); + return Ok(()) } // All receipts from the last 128 blocks are required for blockchain tree, even with @@ -145,7 +145,7 @@ impl BlockBatchRecord { let prunable_receipts = PruneMode::Distance(MINIMUM_PRUNING_DISTANCE).should_prune(block_number, tip); if !prunable_receipts { - return Ok(()); + return Ok(()) } let contract_log_pruner = self.prune_modes.receipts_log_filter.group_by_block(tip, None)?; diff --git a/crates/revm/src/state_change.rs b/crates/revm/src/state_change.rs index 71ed774e2aa6..1709b54cb80d 100644 --- a/crates/revm/src/state_change.rs +++ b/crates/revm/src/state_change.rs @@ -92,7 +92,7 @@ where { // If Prague is not activated or this is the genesis block, no hashes are added. if !chain_spec.is_prague_active_at_timestamp(block_timestamp) || block_number == 0 { - return Ok(()); + return Ok(()) } assert!(block_number > 0); @@ -158,7 +158,7 @@ where DB::Error: std::fmt::Display, { if !chain_spec.is_cancun_active_at_timestamp(block_timestamp) { - return Ok(()); + return Ok(()) } let parent_beacon_block_root = @@ -171,9 +171,9 @@ where return Err(BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { parent_beacon_block_root, } - .into()); + .into()) } - return Ok(()); + return Ok(()) } // get previous env @@ -190,7 +190,7 @@ where parent_beacon_block_root: Box::new(parent_beacon_block_root), message: e.to_string(), } - .into()); + .into()) } }; @@ -273,7 +273,7 @@ where return Err(BlockValidationError::WithdrawalRequestsContractCall { message: format!("execution failed: {e}"), } - .into()); + .into()) } }; @@ -314,7 +314,7 @@ where return Err(BlockValidationError::WithdrawalRequestsContractCall { message: "invalid withdrawal request length".to_string(), } - .into()); + .into()) } let mut source_address = Address::ZERO; diff --git a/crates/rpc/rpc-api/src/admin.rs b/crates/rpc/rpc-api/src/admin.rs index 15904fee4989..173cd8ef7a98 100644 --- a/crates/rpc/rpc-api/src/admin.rs +++ b/crates/rpc/rpc-api/src/admin.rs @@ -1,6 +1,5 @@ use jsonrpsee::{core::RpcResult, proc_macros::rpc}; -use reth_network_peers::AnyNode; -use reth_primitives::NodeRecord; +use reth_network_peers::{AnyNode, NodeRecord}; use reth_rpc_types::{admin::NodeInfo, PeerInfo}; /// Admin namespace rpc interface that gives access to several non-standard RPC methods. diff --git a/crates/rpc/rpc-builder/Cargo.toml b/crates/rpc/rpc-builder/Cargo.toml index fa1aabae7118..46105030cb63 100644 --- a/crates/rpc/rpc-builder/Cargo.toml +++ b/crates/rpc/rpc-builder/Cargo.toml @@ -43,6 +43,7 @@ thiserror.workspace = true tracing.workspace = true [dev-dependencies] +reth-chainspec.workspace = true reth-beacon-consensus.workspace = true reth-network-api.workspace = true reth-evm-ethereum.workspace = true diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index 34ac352eee22..caf16ebf6fce 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -11,9 +11,9 @@ use jsonrpsee::{ rpc_params, types::error::ErrorCode, }; +use reth_chainspec::net::NodeRecord; use reth_primitives::{ - hex_literal::hex, Address, BlockId, BlockNumberOrTag, Bytes, NodeRecord, TxHash, B256, B64, - U256, U64, + hex_literal::hex, Address, BlockId, BlockNumberOrTag, Bytes, TxHash, B256, B64, U256, U64, }; use reth_rpc_api::{ clients::{AdminApiClient, EthApiClient}, diff --git a/crates/rpc/rpc-builder/tests/it/utils.rs b/crates/rpc/rpc-builder/tests/it/utils.rs index 9d660ae3035d..d751b2d331a2 100644 --- a/crates/rpc/rpc-builder/tests/it/utils.rs +++ b/crates/rpc/rpc-builder/tests/it/utils.rs @@ -1,9 +1,9 @@ use reth_beacon_consensus::BeaconConsensusEngineHandle; +use reth_chainspec::MAINNET; use reth_ethereum_engine_primitives::EthEngineTypes; use reth_evm_ethereum::EthEvmConfig; use reth_network_api::noop::NoopNetwork; use reth_payload_builder::test_utils::spawn_test_payload_service; -use reth_primitives::MAINNET; use reth_provider::test_utils::{NoopProvider, TestCanonStateSubscriptions}; use reth_rpc_builder::{ auth::{AuthRpcModule, AuthServerConfig, AuthServerHandle}, diff --git a/crates/rpc/rpc-engine-api/Cargo.toml b/crates/rpc/rpc-engine-api/Cargo.toml index 80c69d8a4dc4..d067515f6c2a 100644 --- a/crates/rpc/rpc-engine-api/Cargo.toml +++ b/crates/rpc/rpc-engine-api/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] # reth +reth-chainspec.workspace = true reth-primitives.workspace = true reth-rpc-api.workspace = true reth-rpc-types.workspace = true diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index a856bdc1707a..8185bbe8cc04 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -2,6 +2,7 @@ use crate::{metrics::EngineApiMetrics, EngineApiError, EngineApiResult}; use async_trait::async_trait; use jsonrpsee_core::RpcResult; use reth_beacon_consensus::BeaconConsensusEngineHandle; +use reth_chainspec::ChainSpec; use reth_engine_primitives::EngineTypes; use reth_evm::provider::EvmEnvProvider; use reth_payload_builder::PayloadStore; @@ -9,7 +10,7 @@ use reth_payload_primitives::{ validate_payload_timestamp, EngineApiMessageVersion, PayloadAttributes, PayloadBuilderAttributes, PayloadOrAttributes, }; -use reth_primitives::{BlockHash, BlockHashOrNumber, BlockNumber, ChainSpec, Hardfork, B256, U64}; +use reth_primitives::{BlockHash, BlockHashOrNumber, BlockNumber, Hardfork, B256, U64}; use reth_rpc_api::EngineApiServer; use reth_rpc_types::engine::{ CancunPayloadFields, ClientVersionV1, ExecutionPayload, ExecutionPayloadBodiesV1, @@ -842,8 +843,9 @@ mod tests { use reth_ethereum_engine_primitives::EthEngineTypes; use reth_testing_utils::generators::random_block; + use reth_chainspec::MAINNET; use reth_payload_builder::test_utils::spawn_test_payload_service; - use reth_primitives::{SealedBlock, B256, MAINNET}; + use reth_primitives::{SealedBlock, B256}; use reth_provider::test_utils::MockEthProvider; use reth_rpc_types::engine::{ClientCode, ClientVersionV1}; use reth_rpc_types_compat::engine::payload::execution_payload_from_sealed_block; diff --git a/crates/rpc/rpc/Cargo.toml b/crates/rpc/rpc/Cargo.toml index 85ef532d22f4..378f665bf90b 100644 --- a/crates/rpc/rpc/Cargo.toml +++ b/crates/rpc/rpc/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] # reth +reth-chainspec.workspace = true reth-primitives.workspace = true reth-rpc-api.workspace = true reth-rpc-server-types.workspace = true diff --git a/crates/rpc/rpc/src/admin.rs b/crates/rpc/rpc/src/admin.rs index 2ea412bb207f..2ee093aed28e 100644 --- a/crates/rpc/rpc/src/admin.rs +++ b/crates/rpc/rpc/src/admin.rs @@ -2,9 +2,10 @@ use crate::result::ToRpcResult; use alloy_primitives::B256; use async_trait::async_trait; use jsonrpsee::core::RpcResult; +use reth_chainspec::ChainSpec; use reth_network_api::{NetworkInfo, PeerKind, Peers}; -use reth_network_peers::AnyNode; -use reth_primitives::{ChainConfig, ChainSpec, NodeRecord}; +use reth_network_peers::{AnyNode, NodeRecord}; +use reth_primitives::ChainConfig; use reth_rpc_api::AdminApiServer; use reth_rpc_types::{ admin::{EthProtocolInfo, NodeInfo, Ports, ProtocolInfo}, diff --git a/crates/rpc/rpc/src/eth/api/fee_history.rs b/crates/rpc/rpc/src/eth/api/fee_history.rs index da43be5510ab..626c670376c8 100644 --- a/crates/rpc/rpc/src/eth/api/fee_history.rs +++ b/crates/rpc/rpc/src/eth/api/fee_history.rs @@ -6,10 +6,11 @@ use futures::{ FutureExt, Stream, StreamExt, }; use metrics::atomics::AtomicU64; +use reth_chainspec::ChainSpec; use reth_primitives::{ basefee::calc_next_block_base_fee, eip4844::{calc_blob_gasprice, calculate_excess_blob_gas}, - ChainSpec, Receipt, SealedBlock, TransactionSigned, B256, + Receipt, SealedBlock, TransactionSigned, B256, }; use reth_provider::{BlockReaderIdExt, CanonStateNotification, ChainSpecProvider}; use reth_rpc_server_types::constants::gas_oracle::MAX_HEADER_HISTORY; diff --git a/crates/rpc/rpc/src/eth/api/mod.rs b/crates/rpc/rpc/src/eth/api/mod.rs index 9d4e8d817c23..364a55842d3c 100644 --- a/crates/rpc/rpc/src/eth/api/mod.rs +++ b/crates/rpc/rpc/src/eth/api/mod.rs @@ -13,13 +13,13 @@ use crate::eth::{ traits::RawTransactionForwarder, }; use async_trait::async_trait; +use reth_chainspec::ChainInfo; use reth_errors::{RethError, RethResult}; use reth_evm::ConfigureEvm; use reth_network_api::NetworkInfo; use reth_primitives::{ revm_primitives::{BlockEnv, CfgEnvWithHandlerCfg}, - Address, BlockId, BlockNumberOrTag, ChainInfo, SealedBlockWithSenders, SealedHeader, B256, - U256, U64, + Address, BlockId, BlockNumberOrTag, SealedBlockWithSenders, SealedHeader, B256, U256, U64, }; use reth_provider::{ BlockReaderIdExt, ChainSpecProvider, EvmEnvProvider, StateProviderBox, StateProviderFactory, diff --git a/crates/rpc/rpc/src/eth/api/pending_block.rs b/crates/rpc/rpc/src/eth/api/pending_block.rs index b3375e2b5554..c3645b3c85a1 100644 --- a/crates/rpc/rpc/src/eth/api/pending_block.rs +++ b/crates/rpc/rpc/src/eth/api/pending_block.rs @@ -1,6 +1,7 @@ //! Support for building a pending block via local txpool. use crate::eth::error::{EthApiError, EthResult}; +use reth_chainspec::ChainSpec; use reth_errors::ProviderError; use reth_primitives::{ constants::{eip4844::MAX_DATA_GAS_PER_BLOCK, BEACON_NONCE, EMPTY_ROOT_HASH}, @@ -9,8 +10,8 @@ use reth_primitives::{ revm_primitives::{ BlockEnv, CfgEnvWithHandlerCfg, EVMError, Env, InvalidTransaction, ResultAndState, SpecId, }, - Block, BlockId, BlockNumberOrTag, ChainSpec, Header, IntoRecoveredTransaction, Receipt, - Requests, SealedBlockWithSenders, SealedHeader, B256, EMPTY_OMMER_ROOT_HASH, U256, + Block, BlockId, BlockNumberOrTag, Header, IntoRecoveredTransaction, Receipt, Requests, + SealedBlockWithSenders, SealedHeader, B256, EMPTY_OMMER_ROOT_HASH, U256, }; use reth_provider::{ChainSpecProvider, ExecutionOutcome, StateProviderFactory}; use reth_revm::{ diff --git a/crates/rpc/rpc/src/eth/api/server.rs b/crates/rpc/rpc/src/eth/api/server.rs index 41c68da48300..f238b4da079a 100644 --- a/crates/rpc/rpc/src/eth/api/server.rs +++ b/crates/rpc/rpc/src/eth/api/server.rs @@ -433,11 +433,12 @@ mod tests { EthApi, }; use jsonrpsee::types::error::INVALID_PARAMS_CODE; + use reth_chainspec::BaseFeeParams; use reth_evm_ethereum::EthEvmConfig; use reth_network_api::noop::NoopNetwork; use reth_primitives::{ - constants::ETHEREUM_BLOCK_GAS_LIMIT, BaseFeeParams, Block, BlockNumberOrTag, Header, - TransactionSigned, B256, U64, + constants::ETHEREUM_BLOCK_GAS_LIMIT, Block, BlockNumberOrTag, Header, TransactionSigned, + B256, U64, }; use reth_provider::{ test_utils::{MockEthProvider, NoopProvider}, diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index 08b22aa74073..1fea2df4a4b4 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -11,7 +11,8 @@ use core::fmt; use async_trait::async_trait; use jsonrpsee::{core::RpcResult, server::IdProvider}; -use reth_primitives::{ChainInfo, IntoRecoveredTransaction, TxHash}; +use reth_chainspec::ChainInfo; +use reth_primitives::{IntoRecoveredTransaction, TxHash}; use reth_provider::{BlockIdReader, BlockReader, EvmEnvProvider, ProviderError}; use reth_rpc_api::EthFilterApiServer; use reth_rpc_types::{ diff --git a/crates/rpc/rpc/src/eth/logs_utils.rs b/crates/rpc/rpc/src/eth/logs_utils.rs index 4fdf9b3a704e..c57ce5fcb986 100644 --- a/crates/rpc/rpc/src/eth/logs_utils.rs +++ b/crates/rpc/rpc/src/eth/logs_utils.rs @@ -1,6 +1,7 @@ use super::filter::FilterError; use alloy_primitives::TxHash; -use reth_primitives::{BlockNumHash, ChainInfo, Receipt}; +use reth_chainspec::ChainInfo; +use reth_primitives::{BlockNumHash, Receipt}; use reth_provider::{BlockReader, ProviderError}; use reth_rpc_types::{FilteredParams, Log}; diff --git a/crates/stages/api/src/metrics/listener.rs b/crates/stages/api/src/metrics/listener.rs index 46f23d79311c..408ecab4a95c 100644 --- a/crates/stages/api/src/metrics/listener.rs +++ b/crates/stages/api/src/metrics/listener.rs @@ -98,7 +98,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 9d5b8b9ba01b..2b7fcf6cbec4 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -140,14 +140,14 @@ where 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 })) } } } @@ -181,7 +181,7 @@ where max_block = ?self.max_block, "Terminating pipeline." ); - return Ok(()); + return Ok(()) } } } @@ -219,7 +219,7 @@ where ControlFlow::Continue { block_number } => self.progress.update(block_number), ControlFlow::Unwind { target, bad_block } => { self.unwind(target, Some(bad_block.number))?; - return Ok(ControlFlow::Unwind { target, bad_block }); + return Ok(ControlFlow::Unwind { target, bad_block }) } } @@ -312,7 +312,7 @@ where ); self.event_sender.notify(PipelineEvent::Skipped { stage_id }); - continue; + continue } info!( @@ -375,7 +375,7 @@ where 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)))) } } } @@ -415,7 +415,7 @@ where // 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 }; @@ -488,7 +488,7 @@ where ControlFlow::Continue { block_number } } else { ControlFlow::NoProgress { block_number: Some(block_number) } - }); + }) } } Err(err) => { @@ -498,7 +498,7 @@ where if let Some(ctrl) = on_stage_error(&self.provider_factory, stage_id, prev_checkpoint, err)? { - return Ok(ctrl); + return Ok(ctrl) } } } diff --git a/crates/stages/api/src/pipeline/set.rs b/crates/stages/api/src/pipeline/set.rs index c6113753ace4..527d9a99a468 100644 --- a/crates/stages/api/src/pipeline/set.rs +++ b/crates/stages/api/src/pipeline/set.rs @@ -206,7 +206,7 @@ where F: FnOnce() -> bool, { if f() { - return self.disable(stage_id); + return self.disable(stage_id) } self } @@ -219,7 +219,7 @@ where 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 acdae56e3568..381acf5f2d99 100644 --- a/crates/stages/api/src/stage.rs +++ b/crates/stages/api/src/stage.rs @@ -93,7 +93,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 a1c7c8c9efad..454ee50bbe20 100644 --- a/crates/stages/stages/src/stages/bodies.rs +++ b/crates/stages/stages/src/stages/bodies.rs @@ -83,7 +83,7 @@ impl Stage for BodyStage { 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 @@ -113,7 +113,7 @@ impl Stage for BodyStage { 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(); @@ -192,7 +192,7 @@ impl Stage for BodyStage { segment: StaticFileSegment::Transactions, database: block_number, static_file: appended_block_number, - }); + }) } } @@ -215,7 +215,7 @@ impl Stage for BodyStage { segment: StaticFileSegment::Transactions, database: next_tx_num, static_file: appended_tx_number, - }); + }) } // Increment transaction id for each transaction. @@ -284,7 +284,7 @@ impl Stage for BodyStage { let mut rev_walker = body_cursor.walk_back(None)?; while let Some((number, block_meta)) = rev_walker.next().transpose()? { if number <= input.unwind_to { - break; + break } // Delete the ommers entry if any @@ -331,7 +331,7 @@ impl Stage for BodyStage { static_file_tx_num, static_file_provider, provider, - )?); + )?) } // Unwinds static file @@ -359,11 +359,11 @@ fn missing_static_data_error( 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; } @@ -929,7 +929,7 @@ mod tests { let this = self.get_mut(); if this.headers.is_empty() { - return Poll::Ready(None); + return Poll::Ready(None) } let mut response = Vec::default(); @@ -949,12 +949,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/execution.rs b/crates/stages/stages/src/stages/execution.rs index 83be0f1e0058..9f3b229268ed 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -199,7 +199,7 @@ where 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(); @@ -294,7 +294,7 @@ where cumulative_gas, batch_start.elapsed(), ) { - break; + break } } @@ -382,7 +382,7 @@ where if range.is_empty() { return Ok(UnwindOutput { checkpoint: input.checkpoint.with_block_number(input.unwind_to), - }); + }) } // Unwind account and storage changesets, as well as receipts. @@ -679,11 +679,11 @@ where loop { if let Some(indices) = provider.block_body_indices(last_block)? { if indices.last_tx_num() <= last_receipt_num { - break; + break } } if last_block == 0 { - break; + break } last_block -= 1; } @@ -694,7 +694,7 @@ where return Err(StageError::MissingStaticFileData { block: missing_block, segment: StaticFileSegment::Receipts, - }); + }) } } diff --git a/crates/stages/stages/src/stages/finish.rs b/crates/stages/stages/src/stages/finish.rs index 8bcab88276d2..9eb3a6d762b8 100644 --- a/crates/stages/stages/src/stages/finish.rs +++ b/crates/stages/stages/src/stages/finish.rs @@ -80,7 +80,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 978c0f716f48..fe8bc8547a58 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -134,7 +134,7 @@ impl Stage for AccountHashingStage { 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(); @@ -459,7 +459,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 46b855e754d4..662f1d1a7728 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -76,7 +76,7 @@ impl Stage for StorageHashingStage { ) -> 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(); @@ -272,7 +272,7 @@ mod tests { // Continue from checkpoint input.checkpoint = Some(checkpoint); - continue; + continue } else { assert_eq!(checkpoint.block_number, previous_stage); assert_matches!(checkpoint.storage_hashing_stage_checkpoint(), Some(StorageHashingCheckpoint { @@ -290,7 +290,7 @@ mod tests { "execution validation" ); - break; + break } } panic!("Failed execution"); @@ -423,7 +423,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() @@ -524,7 +524,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 a43f3739b90a..58c578e34d99 100644 --- a/crates/stages/stages/src/stages/headers.rs +++ b/crates/stages/stages/src/stages/headers.rs @@ -122,7 +122,7 @@ where let (sealed_header, _) = SealedHeader::from_compact(&header_buf, header_buf.len()); let (header, header_hash) = sealed_header.split(); if header.number == 0 { - continue; + continue } last_header_number = header.number; @@ -202,7 +202,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 @@ -219,7 +219,7 @@ where "Target block already reached" ); self.is_etl_ready = true; - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } debug!(target: "sync::stages::headers", ?tip, head = ?gap.local_head.hash(), "Commencing sync"); @@ -243,13 +243,13 @@ where // filled the gap. if header_number == local_head_number + 1 { self.is_etl_ready = true; - return Poll::Ready(Ok(())); + return Poll::Ready(Ok(())) } } } Some(Err(HeadersDownloaderError::DetachedHead { local_head, header, error })) => { error!(target: "sync::stages::headers", %error, "Cannot attach header to head"); - return Poll::Ready(Err(StageError::DetachedHead { local_head, header, error })); + return Poll::Ready(Err(StageError::DetachedHead { local_head, header, error })) } None => return Poll::Ready(Err(StageError::ChannelClosed)), } @@ -267,12 +267,12 @@ where if self.sync_gap.as_ref().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 @@ -457,7 +457,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 bea027ac6c3d..7f83185277c6 100644 --- a/crates/stages/stages/src/stages/index_account_history.rs +++ b/crates/stages/stages/src/stages/index_account_history.rs @@ -87,7 +87,7 @@ impl Stage for IndexAccountHistoryStage { } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let mut range = input.next_block_range(); @@ -563,7 +563,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 cd37cfb6f8e8..23332f2d6ee8 100644 --- a/crates/stages/stages/src/stages/index_storage_history.rs +++ b/crates/stages/stages/src/stages/index_storage_history.rs @@ -90,7 +90,7 @@ impl Stage for IndexStorageHistoryStage { } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } let mut range = input.next_block_range(); @@ -585,7 +585,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 c1abd0d243a8..885fc86c579b 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -105,7 +105,7 @@ impl MerkleStage { 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()); @@ -151,7 +151,7 @@ impl Stage for MerkleStage { let threshold = match self { Self::Unwind => { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); - return Ok(ExecOutput::done(StageCheckpoint::new(input.target()))); + return Ok(ExecOutput::done(StageCheckpoint::new(input.target()))) } Self::Execution { clean_threshold } => *clean_threshold, #[cfg(any(test, feature = "test-utils"))] @@ -234,7 +234,7 @@ impl Stage for MerkleStage { .checkpoint() .with_entities_stage_checkpoint(entities_checkpoint), done: false, - }); + }) } StateRootProgress::Complete(root, hashed_entries_walked, updates) => { updates.flush(tx)?; @@ -291,7 +291,7 @@ impl Stage for MerkleStage { 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 = @@ -310,7 +310,7 @@ impl Stage for MerkleStage { return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) .with_entities_stage_checkpoint(entities_checkpoint), - }); + }) } // Unwind trie only if there are transitions @@ -620,7 +620,7 @@ mod tests { rev_changeset_walker.next().transpose().unwrap() { if bn_address.block_number() < target_block { - break; + break } tree.entry(keccak256(bn_address.address())) @@ -651,7 +651,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/sender_recovery.rs b/crates/stages/stages/src/stages/sender_recovery.rs index 2e4245b2e89f..41df7795c3c4 100644 --- a/crates/stages/stages/src/stages/sender_recovery.rs +++ b/crates/stages/stages/src/stages/sender_recovery.rs @@ -67,7 +67,7 @@ impl Stage for SenderRecoveryStage { 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) = @@ -81,7 +81,7 @@ impl Stage for SenderRecoveryStage { checkpoint: StageCheckpoint::new(end_block) .with_entities_stage_checkpoint(stage_checkpoint(provider)?), done: is_final_range, - }); + }) } let tx = provider.tx_ref(); @@ -210,7 +210,7 @@ fn recover_range( }) } SenderRecoveryStageError::StageError(err) => Err(err), - }; + } } }; senders_cursor.append(tx_id, sender)?; @@ -562,7 +562,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 94d4683bbe9b..4cb422e3392d 100644 --- a/crates/stages/stages/src/stages/tx_lookup.rs +++ b/crates/stages/stages/src/stages/tx_lookup.rs @@ -101,7 +101,7 @@ impl Stage for TransactionLookupStage { } } if input.target_reached() { - return Ok(ExecOutput::done(input.checkpoint())); + return Ok(ExecOutput::done(input.checkpoint())) } // 500MB temporary files @@ -164,7 +164,7 @@ impl Stage for TransactionLookupStage { "Transaction hashes inserted" ); - break; + break } } @@ -191,7 +191,7 @@ impl Stage for TransactionLookupStage { let mut rev_walker = body_cursor.walk_back(Some(*range.end()))?; while let Some((number, body)) = rev_walker.next().transpose()? { if number <= unwind_to { - break; + break } // Delete all transactions that belong to this block @@ -514,7 +514,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/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index f149720a83ef..8f72b5aab225 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -490,7 +490,7 @@ impl StorageKind { fn tx_offset(&self) -> u64 { if let Self::Database(offset) = self { - return offset.unwrap_or_default(); + return offset.unwrap_or_default() } 0 } diff --git a/crates/stages/types/src/checkpoints.rs b/crates/stages/types/src/checkpoints.rs index ee830015486e..d7188de1be9f 100644 --- a/crates/stages/types/src/checkpoints.rs +++ b/crates/stages/types/src/checkpoints.rs @@ -145,7 +145,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. 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 4b00a9eab325..396fdd5ed08d 100644 --- a/crates/static-file/static-file/src/static_file_producer.rs +++ b/crates/static-file/static-file/src/static_file_producer.rs @@ -111,7 +111,7 @@ impl StaticFileProducerInner { 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( diff --git a/crates/static-file/types/src/segment.rs b/crates/static-file/types/src/segment.rs index e3be17c748b0..d609f4a98b27 100644 --- a/crates/static-file/types/src/segment.rs +++ b/crates/static-file/types/src/segment.rs @@ -116,14 +116,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))) diff --git a/crates/storage/codecs/derive/src/compact/flags.rs b/crates/storage/codecs/derive/src/compact/flags.rs index 46a165023605..24757d8e6b91 100644 --- a/crates/storage/codecs/derive/src/compact/flags.rs +++ b/crates/storage/codecs/derive/src/compact/flags.rs @@ -25,7 +25,7 @@ pub(crate) fn generate_flag_struct( .iter() .filter_map(|f| { if let FieldTypes::StructField(f) = f { - return Some(f); + return Some(f) } None }) @@ -36,7 +36,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 889c68b0026b..c28bf8d1a4fb 100644 --- a/crates/storage/codecs/derive/src/compact/generator.rs +++ b/crates/storage/codecs/derive/src/compact/generator.rs @@ -89,7 +89,7 @@ fn generate_from_compact(fields: &FieldList, ident: &Ident, is_zstd: bool) -> To let ident = format_ident!("{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 40b7b2f31eff..c2f0b1e56793 100644 --- a/crates/storage/codecs/derive/src/compact/mod.rs +++ b/crates/storage/codecs/derive/src/compact/mod.rs @@ -156,7 +156,7 @@ fn should_use_alt_impl(ftype: &String, 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 a9c978b21b23..b8882448bb8e 100644 --- a/crates/storage/codecs/derive/src/compact/structs.rs +++ b/crates/storage/codecs/derive/src/compact/structs.rs @@ -66,7 +66,7 @@ impl<'a> StructHandler<'a> { }) } - return; + return } let name = format_ident!("{name}"); diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index 80fd549c0285..b0927a1481cb 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -222,7 +222,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); @@ -251,7 +251,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); @@ -274,7 +274,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]; @@ -314,7 +314,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(); @@ -399,7 +399,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/db-api/src/cursor.rs b/crates/storage/db-api/src/cursor.rs index dd1f0de1f02b..bada512831eb 100644 --- a/crates/storage/db-api/src/cursor.rs +++ b/crates/storage/db-api/src/cursor.rs @@ -158,7 +158,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for Walker<'cursor, T, C fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start; + return start } self.cursor.next().transpose() @@ -235,7 +235,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for ReverseWalker<'curso fn next(&mut self) -> Option { let start = self.start.take(); if start.is_some() { - return start; + return start } self.cursor.prev().transpose() @@ -275,7 +275,7 @@ impl<'cursor, T: Table, CURSOR: DbCursorRO> Iterator for RangeWalker<'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()); @@ -366,7 +366,7 @@ impl<'cursor, T: DupSort, CURSOR: DbDupCursorRO> Iterator for DupWalker<'curs 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-common/src/init.rs b/crates/storage/db-common/src/init.rs index 012a9540ab26..d8bf583dfbb3 100644 --- a/crates/storage/db-common/src/init.rs +++ b/crates/storage/db-common/src/init.rs @@ -92,13 +92,13 @@ pub fn init_genesis(factory: ProviderFactory) -> Result { if block_hash == hash { debug!("Genesis already written, skipping."); - return Ok(hash); + return Ok(hash) } return Err(InitDatabaseError::GenesisHashMismatch { chainspec_hash: hash, database_hash: block_hash, - }); + }) } Err(e) => return Err(dbg!(e).into()), } @@ -376,7 +376,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)?; @@ -499,7 +499,7 @@ fn compute_state_root(provider: &DatabaseProviderRW) -> eyre:: "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 6545a77dafd1..4191d7aae364 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -394,7 +394,7 @@ impl DatabaseEnv { LogLevel::Extra => 7, }); } else { - return Err(DatabaseError::LogLevelUnavailable(log_level)); + return Err(DatabaseError::LogLevelUnavailable(log_level)) } } @@ -439,7 +439,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/lockfile.rs b/crates/storage/db/src/lockfile.rs index 07507a1a5504..e0da20348a53 100644 --- a/crates/storage/db/src/lockfile.rs +++ b/crates/storage/db/src/lockfile.rs @@ -49,7 +49,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 c37cb59e92ff..9a93ca224429 100644 --- a/crates/storage/db/src/static_file/cursor.rs +++ b/crates/storage/db/src/static_file/cursor.rs @@ -32,7 +32,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 { @@ -40,7 +40,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/tables/codecs/fuzz/inputs.rs b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs index 1498dcc907bb..533b6b6926dd 100644 --- a/crates/storage/db/src/tables/codecs/fuzz/inputs.rs +++ b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs @@ -13,7 +13,7 @@ impl From for IntegerList { // Empty lists are not supported by `IntegerList`, so we want to skip these cases. if v.is_empty() { - return vec![1u64].into(); + return vec![1u64].into() } v.sort(); v.into() diff --git a/crates/storage/db/src/version.rs b/crates/storage/db/src/version.rs index 424d543606d4..09c1f946780a 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/src/codec.rs b/crates/storage/libmdbx-rs/src/codec.rs index 26af0999045e..15f20204e20a 100644 --- a/crates/storage/libmdbx-rs/src/codec.rs +++ b/crates/storage/libmdbx-rs/src/codec.rs @@ -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 ca51ac816b28..36da31caa633 100644 --- a/crates/storage/libmdbx-rs/src/cursor.rs +++ b/crates/storage/libmdbx-rs/src/cursor.rs @@ -372,7 +372,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) } @@ -407,7 +407,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) } @@ -423,7 +423,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 b4360a2b87f1..1549d42e1866 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -116,10 +116,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)) } @@ -214,7 +214,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::()]; @@ -696,7 +696,7 @@ impl EnvironmentBuilder { })() { ffi::mdbx_env_close_ex(env, false); - return Err(e); + return Err(e) } } diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index f6ab5ffb2a0d..37af501c1838 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -504,7 +504,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); @@ -585,7 +585,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 d5169ea54196..670bed82b669 100644 --- a/crates/storage/nippy-jar/src/compression/lz4.rs +++ b/crates/storage/nippy-jar/src/compression/lz4.rs @@ -43,7 +43,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 8194538e42f8..c55ca103aff5 100644 --- a/crates/storage/nippy-jar/src/compression/zstd.rs +++ b/crates/storage/nippy-jar/src/compression/zstd.rs @@ -60,7 +60,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![]) @@ -72,12 +72,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) } @@ -102,7 +102,7 @@ impl Zstd { buffer.reserve(column_value.len() * multiplier); multiplier += 1; if multiplier == 5 { - return Err(NippyJarError::Disconnect(err)); + return Err(NippyJarError::Disconnect(err)) } } @@ -191,7 +191,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 @@ -205,7 +205,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())) } // TODO: parallel calculation @@ -363,7 +363,7 @@ impl<'a> Serialize for ZstdDictionary<'a> { impl<'a> PartialEq for ZstdDictionary<'a> { 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/cursor.rs b/crates/storage/nippy-jar/src/cursor.rs index be7fc829e379..434c40a9a69b 100644 --- a/crates/storage/nippy-jar/src/cursor.rs +++ b/crates/storage/nippy-jar/src/cursor.rs @@ -86,11 +86,11 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { .offsets_index .access(row_index as usize) .expect("built from same set") as u64; - return self.next_row(); + return self.next_row() } } } else { - return Err(NippyJarError::UnsupportedFilterQuery); + return Err(NippyJarError::UnsupportedFilterQuery) } Ok(None) @@ -108,7 +108,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); @@ -154,11 +154,11 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { .offsets_index .access(row_index as usize) .expect("built from same set") as u64; - return self.next_row_with_cols(mask); + return self.next_row_with_cols(mask) } } } else { - return Err(NippyJarError::UnsupportedFilterQuery); + return Err(NippyJarError::UnsupportedFilterQuery) } Ok(None) @@ -182,7 +182,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/filter/cuckoo.rs b/crates/storage/nippy-jar/src/filter/cuckoo.rs index f8e5d5d26526..b4e05fbb7493 100644 --- a/crates/storage/nippy-jar/src/filter/cuckoo.rs +++ b/crates/storage/nippy-jar/src/filter/cuckoo.rs @@ -28,7 +28,7 @@ impl Cuckoo { impl InclusionFilter for Cuckoo { fn add(&mut self, element: &[u8]) -> Result<(), NippyJarError> { if self.remaining == 0 { - return Err(NippyJarError::FilterMaxCapacity); + return Err(NippyJarError::FilterMaxCapacity) } self.remaining -= 1; diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index 8e132425abe1..8247599d7aeb 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -413,12 +413,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) } } @@ -513,9 +513,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 }) @@ -555,7 +555,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/phf/fmph.rs b/crates/storage/nippy-jar/src/phf/fmph.rs index 20e1d9ac0c96..a332c40cf720 100644 --- a/crates/storage/nippy-jar/src/phf/fmph.rs +++ b/crates/storage/nippy-jar/src/phf/fmph.rs @@ -28,7 +28,7 @@ impl PerfectHashingFunction for Fmph { fn get_index(&self, key: &[u8]) -> Result, NippyJarError> { if let Some(f) = &self.function { - return Ok(f.get(key)); + return Ok(f.get(key)) } Err(NippyJarError::PHFMissingKeys) } @@ -92,7 +92,7 @@ impl<'de> Deserialize<'de> for Fmph { function: Some( Function::read(&mut std::io::Cursor::new(buffer)).map_err(D::Error::custom)?, ), - }); + }) } Ok(Self { function: None }) } diff --git a/crates/storage/nippy-jar/src/phf/go_fmph.rs b/crates/storage/nippy-jar/src/phf/go_fmph.rs index 8898c8be1adf..328ddcb4ddcb 100644 --- a/crates/storage/nippy-jar/src/phf/go_fmph.rs +++ b/crates/storage/nippy-jar/src/phf/go_fmph.rs @@ -28,7 +28,7 @@ impl PerfectHashingFunction for GoFmph { fn get_index(&self, key: &[u8]) -> Result, NippyJarError> { if let Some(f) = &self.function { - return Ok(f.get(key)); + return Ok(f.get(key)) } Err(NippyJarError::PHFMissingKeys) } @@ -93,7 +93,7 @@ impl<'de> Deserialize<'de> for GoFmph { GOFunction::read(&mut std::io::Cursor::new(buffer)) .map_err(D::Error::custom)?, ), - }); + }) } Ok(Self { function: None }) } diff --git a/crates/storage/nippy-jar/src/writer.rs b/crates/storage/nippy-jar/src/writer.rs index 44b3bd5ed152..695fd6642e54 100644 --- a/crates/storage/nippy-jar/src/writer.rs +++ b/crates/storage/nippy-jar/src/writer.rs @@ -163,7 +163,7 @@ impl NippyJarWriter { // 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 @@ -174,7 +174,7 @@ impl NippyJarWriter { if check_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 @@ -205,7 +205,7 @@ impl NippyJarWriter { let data_file_len = self.data_file.get_ref().metadata()?.len(); if check_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 @@ -235,7 +235,7 @@ impl NippyJarWriter { // Since we decrease the offset list, we need to check the consistency of // `self.jar.rows` again self.ensure_file_consistency(ConsistencyFailStrategy::Heal)?; - break; + break } } } @@ -372,7 +372,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); @@ -398,7 +398,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)) } } @@ -490,7 +490,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/bundle_state_provider.rs b/crates/storage/provider/src/providers/bundle_state_provider.rs index 61aa16b6a244..49fb196ffb18 100644 --- a/crates/storage/provider/src/providers/bundle_state_provider.rs +++ b/crates/storage/provider/src/providers/bundle_state_provider.rs @@ -35,7 +35,7 @@ impl BlockHashReader fn block_hash(&self, block_number: BlockNumber) -> ProviderResult> { let block_hash = self.block_execution_data_provider.block_hash(block_number); if block_hash.is_some() { - return Ok(block_hash); + return Ok(block_hash) } self.state_provider.block_hash(block_number) } @@ -92,7 +92,7 @@ impl StateProvider for BundleStat .execution_outcome() .storage(&account, u256_storage_key) { - return Ok(Some(value)); + return Ok(Some(value)) } self.state_provider.storage(account, storage_key) @@ -102,7 +102,7 @@ impl StateProvider for BundleStat if let Some(bytecode) = self.block_execution_data_provider.execution_outcome().bytecode(&code_hash) { - return Ok(Some(bytecode)); + return Ok(Some(bytecode)) } self.state_provider.bytecode_by_hash(code_hash) diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index 325174e8369a..fe9b65941107 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -62,7 +62,7 @@ where return Err(ConsistentViewError::Inconsistent { tip: GotExpected { got: tip, expected: self.tip }, } - .into()); + .into()) } // Check that the best block number is the same as the latest stored header. @@ -73,7 +73,7 @@ where return Err(ConsistentViewError::Syncing { best_block: GotExpected { got: best_block_number, expected: last_num }, } - .into()); + .into()) } Ok(provider_ro) diff --git a/crates/storage/provider/src/providers/database/mod.rs b/crates/storage/provider/src/providers/database/mod.rs index c954b63aad16..57e7e9615217 100644 --- a/crates/storage/provider/src/providers/database/mod.rs +++ b/crates/storage/provider/src/providers/database/mod.rs @@ -195,7 +195,7 @@ impl HeaderProvider for ProviderFactory { if let Some(td) = self.chain_spec.final_paris_total_difficulty(number) { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)); + return Ok(Some(td)) } self.static_file_provider.get_with_static_file_or_database( diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index 70da8285fe26..f0932f45dbf4 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -134,7 +134,7 @@ impl DatabaseProvider { if block_number == self.best_block_number().unwrap_or_default() && block_number == self.last_block_number().unwrap_or_default() { - return Ok(Box::new(LatestStateProvider::new(self.tx, self.static_file_provider))); + return Ok(Box::new(LatestStateProvider::new(self.tx, self.static_file_provider))) } // +1 as the changeset that we want is the one that was applied after this block. @@ -230,7 +230,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 } cursor.delete_current()?; @@ -239,12 +239,12 @@ where let first = list.iter().next().expect("List can't be empty"); if first >= block_number { item = cursor.prev()?; - continue; + continue } else if block_number <= sharded_key.as_ref().highest_block_number { // Filter out all elements greater than block number. - return Ok(list.iter().take_while(|i| *i < block_number).collect::>()); + return Ok(list.iter().take_while(|i| *i < block_number).collect::>()) } else { - return Ok(list.iter().collect::>()); + return Ok(list.iter().collect::>()) } } @@ -386,7 +386,7 @@ impl DatabaseProvider { ) -> ProviderResult, { if range.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } let len = range.end().saturating_sub(*range.start()) as usize; @@ -553,7 +553,7 @@ impl DatabaseProvider { range: RangeInclusive, ) -> ProviderResult { if range.is_empty() { - return Ok(ExecutionOutcome::default()); + return Ok(ExecutionOutcome::default()) } let start_block_number = *range.start(); @@ -732,7 +732,7 @@ impl DatabaseProvider { let block_bodies = self.get_or_take::(range)?; if block_bodies.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } // Compute the first and last tx ID in the range @@ -741,7 +741,7 @@ impl DatabaseProvider { // If this is the case then all of the blocks in the range are empty if last_transaction < first_transaction { - return Ok(block_bodies.into_iter().map(|(n, _)| (n, Vec::new())).collect()); + return Ok(block_bodies.into_iter().map(|(n, _)| (n, Vec::new())).collect()) } // Get transactions and senders @@ -883,7 +883,7 @@ impl DatabaseProvider { let block_headers = self.get_or_take::(range.clone())?; if block_headers.is_empty() { - return Ok(Vec::new()); + return Ok(Vec::new()) } let block_header_hashes = @@ -1006,7 +1006,7 @@ impl DatabaseProvider { while let Some(Ok((entry_key, _))) = reverse_walker.next() { if selector(entry_key.clone()) <= key { - break; + break } reverse_walker.delete_current()?; deleted += 1; @@ -1053,7 +1053,7 @@ impl DatabaseProvider { table = %T::NAME, "Pruning limit reached" ); - break; + break } let row = cursor.seek_exact(key)?; @@ -1096,7 +1096,7 @@ impl DatabaseProvider { table = %T::NAME, "Pruning limit reached" ); - break false; + break false } let done = self.prune_table_with_range_step( @@ -1107,7 +1107,7 @@ impl DatabaseProvider { )?; if done { - break true; + break true } else { deleted_entries += 1; } @@ -1155,7 +1155,7 @@ impl DatabaseProvider { // delete old shard so new one can be inserted. self.tx.delete::(shard_key, None)?; let list = list.iter().collect::>(); - return Ok(list); + return Ok(list) } Ok(Vec::new()) } @@ -1300,7 +1300,7 @@ impl HeaderSyncGapProvider for DatabaseProvider { } 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 => {} } @@ -1345,7 +1345,7 @@ impl HeaderProvider for DatabaseProvider { if let Some(td) = self.chain_spec.final_paris_total_difficulty(number) { // if this block is higher than the final paris(merge) block, return the final paris // difficulty - return Ok(Some(td)); + return Ok(Some(td)) } self.static_file_provider.get_with_static_file_or_database( @@ -1402,7 +1402,7 @@ impl HeaderProvider for DatabaseProvider { .ok_or_else(|| ProviderError::HeaderNotFound(number.into()))?; let sealed = header.seal(hash); if !predicate(&sealed) { - break; + break } headers.push(sealed); } @@ -1500,13 +1500,7 @@ impl BlockReader for DatabaseProvider { None => return Ok(None), }; - return Ok(Some(Block { - header, - body: transactions, - ommers, - withdrawals, - requests, - })); + return Ok(Some(Block { header, body: transactions, ommers, withdrawals, requests })) } } @@ -1530,11 +1524,11 @@ impl BlockReader for DatabaseProvider { // If the Paris (Merge) hardfork block is known and block is after it, return empty // ommers. if self.chain_spec.final_paris_total_difficulty(number).is_some() { - return Ok(Some(Vec::new())); + return Ok(Some(Vec::new())) } let ommers = self.tx.get::(number)?.map(|o| o.ommers); - return Ok(ommers); + return Ok(ommers) } Ok(None) @@ -1794,7 +1788,7 @@ impl TransactionsProvider for DatabaseProvider { timestamp: header.timestamp, }; - return Ok(Some((transaction, meta))); + return Ok(Some((transaction, meta))) } } } @@ -1827,7 +1821,7 @@ impl TransactionsProvider for DatabaseProvider { .map(Into::into) .collect(), )) - }; + } } } Ok(None) @@ -1905,7 +1899,7 @@ impl ReceiptProvider for DatabaseProvider { Ok(Some(Vec::new())) } else { self.receipts_by_tx_range(tx_range).map(Some) - }; + } } } Ok(None) @@ -1940,7 +1934,7 @@ impl WithdrawalsProvider for DatabaseProvider { .get::(number) .map(|w| w.map(|w| w.withdrawals))? .unwrap_or_default(); - return Ok(Some(withdrawals)); + return Ok(Some(withdrawals)) } } Ok(None) @@ -1964,7 +1958,7 @@ impl RequestsProvider for DatabaseProvider { // If we are past Prague, then all blocks should have a requests list, even if // empty let requests = self.tx.get::(number)?.unwrap_or_default(); - return Ok(Some(requests)); + return Ok(Some(requests)) } } Ok(None) @@ -2384,7 +2378,7 @@ impl HashingWriter for DatabaseProvider { root: GotExpected { got: state_root, expected: expected_state_root }, block_number: *range.end(), block_hash: end_block_hash, - }))); + }))) } trie_updates.flush(&self.tx)?; } @@ -2580,7 +2574,7 @@ impl BlockExecutionWriter for DatabaseProvider { root: GotExpected { got: new_state_root, expected: parent_state_root }, block_number: parent_number, block_hash: parent_hash, - }))); + }))) } trie_updates.flush(&self.tx)?; } @@ -2759,7 +2753,7 @@ impl BlockWriter for DatabaseProvider { ) -> 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/mod.rs b/crates/storage/provider/src/providers/mod.rs index 2f14bf4d5d48..9da41269c137 100644 --- a/crates/storage/provider/src/providers/mod.rs +++ b/crates/storage/provider/src/providers/mod.rs @@ -648,7 +648,7 @@ where if let Some(block) = self.tree.pending_block_num_hash() { if let Ok(pending) = self.tree.pending_state_provider(block.hash) { - return self.pending_with_provider(pending); + return self.pending_with_provider(pending) } } @@ -658,7 +658,7 @@ where fn pending_state_by_hash(&self, block_hash: B256) -> ProviderResult> { if let Some(state) = self.tree.find_pending_state_provider(block_hash) { - return Ok(Some(self.pending_with_provider(state)?)); + return Ok(Some(self.pending_with_provider(state)?)) } Ok(None) } diff --git a/crates/storage/provider/src/providers/state/historical.rs b/crates/storage/provider/src/providers/state/historical.rs index 2f20ca7954bd..12545fe7838e 100644 --- a/crates/storage/provider/src/providers/state/historical.rs +++ b/crates/storage/provider/src/providers/state/historical.rs @@ -73,7 +73,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { /// 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. @@ -92,7 +92,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { 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. @@ -109,7 +109,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { 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)) } let tip = self diff --git a/crates/storage/provider/src/providers/state/latest.rs b/crates/storage/provider/src/providers/state/latest.rs index 64a5c9b24b4c..56b4ecc38b11 100644 --- a/crates/storage/provider/src/providers/state/latest.rs +++ b/crates/storage/provider/src/providers/state/latest.rs @@ -100,7 +100,7 @@ impl<'b, TX: DbTx> StateProvider for LatestStateProviderRef<'b, TX> { 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 10d725d2a43f..5e20572e3d61 100644 --- a/crates/storage/provider/src/providers/static_file/jar.rs +++ b/crates/storage/provider/src/providers/static_file/jar.rs @@ -137,7 +137,7 @@ impl<'a> HeaderProvider for StaticFileJarProvider<'a> { { let sealed = header.seal(hash); if !predicate(&sealed) { - break; + break } headers.push(sealed); } @@ -297,7 +297,7 @@ impl<'a> ReceiptProvider for StaticFileJarProvider<'a> { fn receipt_by_hash(&self, hash: TxHash) -> 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 acdc336c8206..39e588c7f5f4 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -261,7 +261,7 @@ impl StaticFileProvider { ) .and_then(|(parsed_segment, block_range)| { if parsed_segment == segment { - return Some(block_range); + return Some(block_range) } None }), @@ -270,7 +270,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) @@ -379,11 +379,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(find_fixed_range(block_range.end())); + return Some(find_fixed_range(block_range.end())) } } None @@ -544,7 +544,7 @@ impl StaticFileProvider { for segment in StaticFileSegment::iter() { 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); @@ -586,16 +586,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; @@ -674,12 +674,12 @@ impl StaticFileProvider { ?segment, "Setting unwind target." ); - return Ok(Some(highest_static_file_block)); + return Ok(Some(highest_static_file_block)) } if let Some((db_last_entry, _)) = db_cursor.last()? { if db_last_entry > highest_static_file_entry { - return Ok(None); + return Ok(None) } } } @@ -704,7 +704,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 @@ -768,7 +768,7 @@ impl StaticFileProvider { let mut range = 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(BLOCKS_PER_STATIC_FILE), @@ -821,10 +821,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 { @@ -840,7 +840,7 @@ impl StaticFileProvider { } else { ProviderError::MissingStaticFileTx(segment, number) }; - return Err(err); + return Err(err) } provider = get_provider(number)?; cursor = provider.cursor()?; @@ -923,7 +923,7 @@ impl StaticFileProvider { if static_file_upper_bound .map_or(false, |static_file_upper_bound| static_file_upper_bound >= number) { - return fetch_from_static_file(self); + return fetch_from_static_file(self) } fetch_from_database() } @@ -1016,7 +1016,7 @@ impl StaticFileWriter for StaticFileProvider { segment: StaticFileSegment, ) -> ProviderResult> { if self.access.is_read_only() { - return Err(ProviderError::ReadOnlyStaticFileAccess); + return Err(ProviderError::ReadOnlyStaticFileAccess) } tracing::trace!(target: "providers::static_file", ?block, ?segment, "Getting static file writer."); @@ -1079,7 +1079,7 @@ impl HeaderProvider for StaticFileProvider { .get_two::>(block_hash.into())? .and_then(|(header, hash)| { if &hash == block_hash { - return Some(header); + return Some(header) } None })) @@ -1192,7 +1192,7 @@ impl ReceiptProvider for StaticFileProvider { 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) } diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index 397606083528..304429a0150b 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -139,7 +139,7 @@ impl StaticFileProviderRW { self.writer.ensure_file_consistency(check_mode).map_err(|error| { if matches!(error, NippyJarError::InconsistentState) { - return inconsistent_error(); + return inconsistent_error() } ProviderError::NippyJar(error.to_string()) })?; @@ -153,7 +153,7 @@ impl StaticFileProviderRW { let pruned_rows = expected_rows - self.writer.rows() as u64; if pruned_rows > 0 { if read_only { - return Err(inconsistent_error()); + return Err(inconsistent_error()) } self.user_header_mut().prune(pruned_rows); } @@ -327,7 +327,7 @@ impl StaticFileProviderRW { segment, expected_block_number, next_static_file_block, - )); + )) } Ok(()) } @@ -369,7 +369,7 @@ impl StaticFileProviderRW { self.writer .prune_rows(len as usize) .map_err(|e| ProviderError::NippyJar(e.to_string()))?; - break; + break } remaining_rows -= len; @@ -634,7 +634,7 @@ impl StaticFileProviderRW { if self.prune_on_commit.is_some() { return Err(ProviderError::NippyJar( "Pruning should be committed before appending or pruning more data".to_string(), - )); + )) } Ok(()) } diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index da92875248db..974982121a7e 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -249,7 +249,7 @@ impl TransactionsProvider for MockEthProvider { excess_blob_gas: block.header.excess_blob_gas, timestamp: block.header.timestamp, }; - return Ok(Some((tx.clone(), meta))); + return Ok(Some((tx.clone(), meta))) } } } @@ -261,7 +261,7 @@ impl TransactionsProvider for MockEthProvider { let mut current_tx_number: TxNumber = 0; for block in lock.values() { if current_tx_number + (block.body.len() as TxNumber) > id { - return Ok(Some(block.header.number)); + return Ok(Some(block.header.number)) } current_tx_number += block.body.len() as TxNumber; } diff --git a/crates/storage/provider/src/traits/chain.rs b/crates/storage/provider/src/traits/chain.rs index 9f8224f709ee..98957fcfdcc8 100644 --- a/crates/storage/provider/src/traits/chain.rs +++ b/crates/storage/provider/src/traits/chain.rs @@ -51,10 +51,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/storage/storage-api/src/receipts.rs b/crates/storage/storage-api/src/receipts.rs index 246c6a6cf008..b050ca3e248c 100644 --- a/crates/storage/storage-api/src/receipts.rs +++ b/crates/storage/storage-api/src/receipts.rs @@ -47,7 +47,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 03dfd7a9b857..059909a463b0 100644 --- a/crates/storage/storage-api/src/state.rs +++ b/crates/storage/storage-api/src/state.rs @@ -40,10 +40,10 @@ pub trait StateProvider: BlockHashReader + AccountReader + StateRootProvider + S 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/tasks/src/lib.rs b/crates/tasks/src/lib.rs index de0043fb8366..ee5222e91312 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -222,7 +222,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/event_stream.rs b/crates/tokio-util/src/event_stream.rs index 88aebcceb08b..0e041f8d4c31 100644 --- a/crates/tokio-util/src/event_stream.rs +++ b/crates/tokio-util/src/event_stream.rs @@ -36,7 +36,7 @@ where Poll::Ready(Some(Ok(item))) => return Poll::Ready(Some(item)), Poll::Ready(Some(Err(e))) => { warn!("BroadcastStream lagged: {e:?}"); - continue; + continue } Poll::Ready(None) => return Poll::Ready(None), Poll::Pending => return Poll::Pending, diff --git a/crates/transaction-pool/Cargo.toml b/crates/transaction-pool/Cargo.toml index e742c569b76a..03b5d1d5f21a 100644 --- a/crates/transaction-pool/Cargo.toml +++ b/crates/transaction-pool/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] # reth +reth-chainspec.workspace = true reth-eth-wire-types.workspace = true reth-primitives.workspace = true reth-fs-util.workspace = true diff --git a/crates/transaction-pool/src/lib.rs b/crates/transaction-pool/src/lib.rs index e02e49ca9885..527c3412e1aa 100644 --- a/crates/transaction-pool/src/lib.rs +++ b/crates/transaction-pool/src/lib.rs @@ -79,7 +79,7 @@ //! Listen for new transactions and print them: //! //! ``` -//! use reth_primitives::MAINNET; +//! use reth_chainspec::MAINNET; //! use reth_provider::{BlockReaderIdExt, ChainSpecProvider, StateProviderFactory}; //! use reth_tasks::TokioTaskExecutor; //! use reth_transaction_pool::{TransactionValidationTaskExecutor, Pool, TransactionPool}; @@ -107,7 +107,7 @@ //! //! ``` //! use futures_util::Stream; -//! use reth_primitives::MAINNET; +//! use reth_chainspec::MAINNET; //! use reth_provider::{BlockReaderIdExt, CanonStateNotification, ChainSpecProvider, StateProviderFactory}; //! use reth_tasks::TokioTaskExecutor; //! use reth_tasks::TaskSpawner; @@ -285,7 +285,7 @@ where /// # Example /// /// ``` - /// use reth_primitives::MAINNET; + /// use reth_chainspec::MAINNET; /// use reth_provider::{BlockReaderIdExt, StateProviderFactory}; /// use reth_tasks::TokioTaskExecutor; /// use reth_transaction_pool::{ diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index 02c259f9a0a9..99b29ed01289 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -681,8 +681,9 @@ mod tests { blobstore::InMemoryBlobStore, validate::EthTransactionValidatorBuilder, CoinbaseTipOrdering, EthPooledTransaction, Pool, PoolTransaction, TransactionOrigin, }; + use reth_chainspec::MAINNET; use reth_fs_util as fs; - use reth_primitives::{hex, PooledTransactionsElement, MAINNET, U256}; + use reth_primitives::{hex, PooledTransactionsElement, U256}; use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; use reth_tasks::TaskManager; diff --git a/crates/transaction-pool/src/test_utils/gen.rs b/crates/transaction-pool/src/test_utils/gen.rs index 87c2ba580d38..2be4d8aa9a9a 100644 --- a/crates/transaction-pool/src/test_utils/gen.rs +++ b/crates/transaction-pool/src/test_utils/gen.rs @@ -1,9 +1,10 @@ use crate::EthPooledTransaction; use rand::Rng; +use reth_chainspec::MAINNET; use reth_primitives::{ constants::MIN_PROTOCOL_BASE_FEE, sign_message, AccessList, Address, Bytes, Transaction, TransactionSigned, TryFromRecoveredTransaction, TxEip1559, TxEip4844, TxKind, TxLegacy, B256, - MAINNET, U256, + U256, }; /// A generator for transactions for testing purposes. diff --git a/crates/transaction-pool/src/validate/eth.rs b/crates/transaction-pool/src/validate/eth.rs index 3e7e7d519a2f..3b3779cfdcb5 100644 --- a/crates/transaction-pool/src/validate/eth.rs +++ b/crates/transaction-pool/src/validate/eth.rs @@ -9,6 +9,7 @@ use crate::{ EthBlobTransactionSidecar, EthPoolTransaction, LocalTransactionConfig, PoolTransaction, TransactionValidationOutcome, TransactionValidationTaskExecutor, TransactionValidator, }; +use reth_chainspec::ChainSpec; use reth_primitives::{ constants::{ eip4844::{MAINNET_KZG_TRUSTED_SETUP, MAX_BLOBS_PER_BLOCK}, @@ -16,8 +17,8 @@ use reth_primitives::{ }, kzg::KzgSettings, revm::compat::calculate_intrinsic_gas_after_merge, - ChainSpec, GotExpected, InvalidTransactionError, SealedBlock, EIP1559_TX_TYPE_ID, - EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID, + GotExpected, InvalidTransactionError, SealedBlock, EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, + EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID, }; use reth_provider::{AccountReader, BlockReaderIdExt, StateProviderFactory}; use reth_tasks::TaskSpawner; @@ -734,9 +735,8 @@ mod tests { blobstore::InMemoryBlobStore, error::PoolErrorKind, CoinbaseTipOrdering, EthPooledTransaction, Pool, TransactionPool, }; - use reth_primitives::{ - hex, FromRecoveredPooledTransaction, PooledTransactionsElement, MAINNET, U256, - }; + use reth_chainspec::MAINNET; + use reth_primitives::{hex, FromRecoveredPooledTransaction, PooledTransactionsElement, U256}; use reth_provider::test_utils::{ExtendedAccount, MockEthProvider}; fn get_transaction() -> EthPooledTransaction { diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index f8f98e3f4755..72ab1d81a13a 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -7,7 +7,8 @@ use crate::{ TransactionValidator, }; use futures_util::{lock::Mutex, StreamExt}; -use reth_primitives::{ChainSpec, SealedBlock}; +use reth_chainspec::ChainSpec; +use reth_primitives::SealedBlock; use reth_provider::BlockReaderIdExt; use reth_tasks::TaskSpawner; use std::{future::Future, pin::Pin, sync::Arc}; diff --git a/crates/trie/trie/benches/prefix_set.rs b/crates/trie/trie/benches/prefix_set.rs index a4604cdc2900..db02b5dd17cc 100644 --- a/crates/trie/trie/benches/prefix_set.rs +++ b/crates/trie/trie/benches/prefix_set.rs @@ -150,12 +150,12 @@ mod implementations { for key in self.keys.range::(range) { if key.has_prefix(&prefix) { self.last_checked = Some(prefix); - return true; + return true } if key > &prefix { self.last_checked = Some(prefix); - return false; + return false } } @@ -219,12 +219,12 @@ mod implementations { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(&prefix) { self.index += idx; - return true; + return true } if key > &prefix { self.index += idx; - return false; + return false } } diff --git a/crates/trie/trie/src/hashed_cursor/post_state.rs b/crates/trie/trie/src/hashed_cursor/post_state.rs index 61b1e093b3d6..df04d332d2c6 100644 --- a/crates/trie/trie/src/hashed_cursor/post_state.rs +++ b/crates/trie/trie/src/hashed_cursor/post_state.rs @@ -118,7 +118,7 @@ where if let Some((address, account)) = post_state_entry { if address == &key { self.last_account = Some(*address); - return Ok(Some((*address, *account))); + return Ok(Some((*address, *account))) } } @@ -273,7 +273,7 @@ where if let Some((slot, value)) = post_state_entry { if slot == &subkey { self.last_slot = Some(*slot); - return Ok(Some((*slot, *value))); + return Ok(Some((*slot, *value))) } } diff --git a/crates/trie/trie/src/node_iter.rs b/crates/trie/trie/src/node_iter.rs index f4aa7609d26c..29c6fd4f2344 100644 --- a/crates/trie/trie/src/node_iter.rs +++ b/crates/trie/trie/src/node_iter.rs @@ -97,7 +97,7 @@ where key.clone(), self.walker.hash().unwrap(), self.walker.children_are_in_trie(), - )))); + )))) } } } @@ -108,12 +108,12 @@ where // reset the checked status and continue if self.walker.key().map_or(false, |key| key < &Nibbles::unpack(hashed_key)) { self.current_walker_key_checked = false; - continue; + continue } // Set the next hashed entry as a leaf node and return self.current_hashed_entry = self.hashed_cursor.next()?; - 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 diff --git a/crates/trie/trie/src/prefix_set/mod.rs b/crates/trie/trie/src/prefix_set/mod.rs index 79aaae0c90a7..f6a8789e0105 100644 --- a/crates/trie/trie/src/prefix_set/mod.rs +++ b/crates/trie/trie/src/prefix_set/mod.rs @@ -84,12 +84,12 @@ impl PrefixSetMut { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(prefix) { self.index += idx; - return true; + return true } if *key > *prefix { self.index += idx; - return false; + return false } } @@ -149,12 +149,12 @@ impl PrefixSet { for (idx, key) in self.keys[self.index..].iter().enumerate() { if key.has_prefix(prefix) { self.index += idx; - return true; + return true } if key > prefix { self.index += idx; - return false; + return false } } diff --git a/crates/trie/trie/src/proof.rs b/crates/trie/trie/src/proof.rs index 4b34c86a0ca2..04e7952f5db7 100644 --- a/crates/trie/trie/src/proof.rs +++ b/crates/trie/trie/src/proof.rs @@ -113,7 +113,7 @@ where // short circuit on empty storage if hashed_storage_cursor.is_storage_empty()? { - return Ok((EMPTY_ROOT_HASH, proofs)); + return Ok((EMPTY_ROOT_HASH, proofs)) } let target_nibbles = proofs.iter().map(|p| p.nibbles.clone()).collect::>(); diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index 1edb33e25606..3fe97a6f788c 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -305,7 +305,7 @@ where Box::new(state), hashed_entries_walked, trie_updates, - )); + )) } } } @@ -487,7 +487,7 @@ where EMPTY_ROOT_HASH, 0, TrieUpdates::from([(TrieKey::StorageTrie(self.hashed_address), TrieOp::Delete)]), - )); + )) } let mut tracker = TrieTracker::default(); diff --git a/crates/trie/trie/src/updates.rs b/crates/trie/trie/src/updates.rs index 60ccf4850690..39628e6d5272 100644 --- a/crates/trie/trie/src/updates.rs +++ b/crates/trie/trie/src/updates.rs @@ -131,7 +131,7 @@ impl TrieUpdates { /// Flush updates all aggregated updates to the database. pub fn flush(self, tx: &(impl DbTx + DbTxMut)) -> Result<(), reth_db::DatabaseError> { if self.trie_operations.is_empty() { - return Ok(()); + return Ok(()) } let mut account_trie_cursor = tx.cursor_write::()?; diff --git a/crates/trie/trie/src/walker.rs b/crates/trie/trie/src/walker.rs index 9959f4f95a5c..6486a9b08006 100644 --- a/crates/trie/trie/src/walker.rs +++ b/crates/trie/trie/src/walker.rs @@ -174,7 +174,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 @@ -213,22 +213,22 @@ impl TrieWalker { if subnode.nibble() >= 0xf || (subnode.nibble() < 0 && !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. loop { if subnode.state_flag() { - return Ok(()); + return Ok(()) } if subnode.nibble() == 0xf { - break; + break } subnode.inc_nibble(); } From 0830f5274107d065bddf674a78974eea6af135d5 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Tue, 18 Jun 2024 15:50:51 +0100 Subject: [PATCH 08/16] unlimited max decode/encode grpc message size --- crates/primitives/src/lib.rs | 2 +- crates/primitives/src/log.rs | 2 +- examples/exex/remote/bin/consumer.rs | 5 ++++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/primitives/src/lib.rs b/crates/primitives/src/lib.rs index b965de1673df..771417678183 100644 --- a/crates/primitives/src/lib.rs +++ b/crates/primitives/src/lib.rs @@ -62,7 +62,7 @@ pub use error::{GotExpected, GotExpectedBoxed}; pub use genesis::{ChainConfig, Genesis, GenesisAccount}; pub use header::{Header, HeadersDirection, SealedHeader}; pub use integer_list::IntegerList; -pub use log::{logs_bloom, Log}; +pub use log::{logs_bloom, Log, LogData}; pub use receipt::{ gas_spent_by_transactions, Receipt, ReceiptWithBloom, ReceiptWithBloomRef, Receipts, }; diff --git a/crates/primitives/src/log.rs b/crates/primitives/src/log.rs index b2b6b8a4852c..9d04fed387e0 100644 --- a/crates/primitives/src/log.rs +++ b/crates/primitives/src/log.rs @@ -1,6 +1,6 @@ use crate::Bloom; -pub use alloy_primitives::Log; +pub use alloy_primitives::{Log, LogData}; /// Calculate receipt logs bloom. pub fn logs_bloom<'a>(logs: impl IntoIterator) -> Bloom { diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs index 87695b9a6853..16d0ae96430b 100644 --- a/examples/exex/remote/bin/consumer.rs +++ b/examples/exex/remote/bin/consumer.rs @@ -9,7 +9,10 @@ use reth_tracing::{tracing::info, RethTracer, Tracer}; async fn main() -> eyre::Result<()> { let _ = RethTracer::new().init()?; - let mut client = RemoteExExClient::connect("http://[::1]:10000").await?; + let mut client = RemoteExExClient::connect("http://[::1]:10000") + .await? + .max_encoding_message_size(usize::MAX) + .max_decoding_message_size(usize::MAX); let mut stream = client.subscribe(SubscribeRequest {}).await?.into_inner(); while let Some(notification) = stream.message().await? { From 4e1497fa539421e30e85a332c1e6922857721713 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 13:14:23 +0100 Subject: [PATCH 09/16] use node task manager --- Cargo.lock | 1 - examples/exex/remote/Cargo.toml | 1 - examples/exex/remote/bin/exex.rs | 15 ++++++----- examples/exex/remote/src/codec.rs | 42 +++++++++++++++---------------- 4 files changed, 28 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 872a021d34fb..31e460b7ef8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2976,7 +2976,6 @@ version = "0.0.0" dependencies = [ "bincode", "eyre", - "futures", "prost", "reth", "reth-exex", diff --git a/examples/exex/remote/Cargo.toml b/examples/exex/remote/Cargo.toml index 7ca78689fe98..3597b2cd6080 100644 --- a/examples/exex/remote/Cargo.toml +++ b/examples/exex/remote/Cargo.toml @@ -13,7 +13,6 @@ reth-node-ethereum.workspace = true reth-tracing.workspace = true eyre.workspace = true -futures.workspace = true tonic = "0.11" prost = "0.12" diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index 5640e5b5321a..7cc2d4b03952 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -7,7 +7,6 @@ use exex_remote::{ ExExNotification as ProtoExExNotification, SubscribeRequest as ProtoSubscribeRequest, }, }; -use futures::TryFutureExt; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; use reth_node_api::FullNodeComponents; use reth_node_ethereum::EthereumNode; @@ -66,18 +65,18 @@ fn main() -> eyre::Result<()> { .add_service(RemoteExExServer::new(ExExService { notifications: notifications.clone(), })) - .serve("[::1]:10000".parse().unwrap()) - .map_err(|err| err.into()); + .serve("[::1]:10000".parse().unwrap()); - let node = builder + let handle = builder .node(EthereumNode::default()) .install_exex("Remote", |ctx| async move { Ok(exex(ctx, notifications)) }) .launch() - .await? - .wait_for_node_exit(); + .await?; - futures::try_join!(server, node)?; + handle.node.task_executor.spawn_critical("gRPC server", async move { + server.await.expect("gRPC server crashed") + }); - Ok(()) + handle.wait_for_node_exit().await }) } diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs index fcc866a333fe..22167724c7bd 100644 --- a/examples/exex/remote/src/codec.rs +++ b/examples/exex/remote/src/codec.rs @@ -5,6 +5,8 @@ use reth::primitives::{Address, BlockHash, Bloom, TxHash, B256, U256}; use crate::proto; +/// Converts a [Reth ExEx notification](`reth_exex::ExExNotification`) into +/// a [Protobuf ExEx notification](`proto::ExExNotification`) pub fn to_proto_notification( notification: &reth_exex::ExExNotification, ) -> eyre::Result { @@ -30,7 +32,7 @@ pub fn to_proto_notification( Ok(proto::ExExNotification { notification: Some(notification) }) } -pub fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result { +fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result { let bundle_state = chain.execution_outcome().state(); Ok(proto::Chain { blocks: chain @@ -169,7 +171,7 @@ pub fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result proto::Header { +fn to_proto_header(header: &reth::primitives::Header) -> proto::Header { proto::Header { parent_hash: header.parent_hash.to_vec(), ommers_hash: header.ommers_hash.to_vec(), @@ -194,9 +196,7 @@ pub fn to_proto_header(header: &reth::primitives::Header) -> proto::Header { } } -pub fn to_proto_transaction( - transaction: &reth::primitives::TransactionSigned, -) -> proto::Transaction { +fn to_proto_transaction(transaction: &reth::primitives::TransactionSigned) -> proto::Transaction { let hash = transaction.hash().to_vec(); let signature = proto::Signature { r: transaction.signature.r.to_le_bytes_vec(), @@ -292,7 +292,7 @@ pub fn to_proto_transaction( proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) } } -pub fn to_proto_tx_kind(kind: &reth::primitives::TxKind) -> proto::TxKind { +fn to_proto_tx_kind(kind: &reth::primitives::TxKind) -> proto::TxKind { proto::TxKind { kind: match kind { reth::primitives::TxKind::Create => Some(proto::tx_kind::Kind::Create(())), @@ -303,14 +303,14 @@ pub fn to_proto_tx_kind(kind: &reth::primitives::TxKind) -> proto::TxKind { } } -pub fn to_proto_access_list_item(item: &reth::primitives::AccessListItem) -> proto::AccessListItem { +fn to_proto_access_list_item(item: &reth::primitives::AccessListItem) -> proto::AccessListItem { proto::AccessListItem { address: item.address.to_vec(), storage_keys: item.storage_keys.iter().map(|key| key.to_vec()).collect(), } } -pub fn to_proto_account_info( +fn to_proto_account_info( account_info: &reth::revm::primitives::AccountInfo, ) -> eyre::Result { Ok(proto::AccountInfo { @@ -321,9 +321,7 @@ pub fn to_proto_account_info( }) } -pub fn to_proto_bytecode( - bytecode: &reth::revm::primitives::Bytecode, -) -> eyre::Result { +fn to_proto_bytecode(bytecode: &reth::revm::primitives::Bytecode) -> eyre::Result { let bytecode = match bytecode { reth::revm::primitives::Bytecode::LegacyRaw(code) => { proto::bytecode::Bytecode::LegacyRaw(code.to_vec()) @@ -348,7 +346,7 @@ pub fn to_proto_bytecode( Ok(proto::Bytecode { bytecode: Some(bytecode) }) } -pub fn to_proto_account_status(status: reth::revm::db::AccountStatus) -> proto::AccountStatus { +fn to_proto_account_status(status: reth::revm::db::AccountStatus) -> proto::AccountStatus { match status { reth::revm::db::AccountStatus::LoadedNotExisting => proto::AccountStatus::LoadedNotExisting, reth::revm::db::AccountStatus::Loaded => proto::AccountStatus::Loaded, @@ -361,6 +359,8 @@ pub fn to_proto_account_status(status: reth::revm::db::AccountStatus) -> proto:: } } +/// Converts a [Protobuf ExEx notification](`proto::ExExNotification`) into +/// a [Reth ExEx notification](`reth_exex::ExExNotification`) pub fn from_proto_notification( notification: &proto::ExExNotification, ) -> eyre::Result { @@ -384,7 +384,7 @@ pub fn from_proto_notification( } } -pub fn from_proto_chain(chain: &proto::Chain) -> eyre::Result> { +fn from_proto_chain(chain: &proto::Chain) -> eyre::Result> { let execution_outcome = chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; Ok(Arc::new(reth::providers::Chain::new( @@ -560,7 +560,7 @@ pub fn from_proto_chain(chain: &proto::Chain) -> eyre::Result eyre::Result { let sealed_header = block.header.as_ref().ok_or_eyre("no sealed header")?; @@ -594,7 +594,7 @@ pub fn from_proto_block( .ok_or_eyre("senders do not match transactions") } -pub fn from_proto_header(header: &proto::Header) -> eyre::Result { +fn from_proto_header(header: &proto::Header) -> eyre::Result { Ok(reth::primitives::Header { parent_hash: B256::try_from(header.parent_hash.as_slice())?, ommers_hash: B256::try_from(header.ommers_hash.as_slice())?, @@ -629,7 +629,7 @@ pub fn from_proto_header(header: &proto::Header) -> eyre::Result eyre::Result { let hash = TxHash::try_from(transaction.hash.as_slice())?; @@ -747,7 +747,7 @@ pub fn from_proto_transaction( Ok(reth::primitives::TransactionSigned { hash, signature, transaction }) } -pub fn from_proto_tx_kind(tx_kind: &proto::TxKind) -> eyre::Result { +fn from_proto_tx_kind(tx_kind: &proto::TxKind) -> eyre::Result { Ok(match tx_kind.kind.as_ref().ok_or_eyre("no kind")? { proto::tx_kind::Kind::Create(()) => reth::primitives::TxKind::Create, proto::tx_kind::Kind::Call(address) => { @@ -756,7 +756,7 @@ pub fn from_proto_tx_kind(tx_kind: &proto::TxKind) -> eyre::Result eyre::Result { Ok(reth::primitives::AccessListItem { @@ -769,7 +769,7 @@ pub fn from_proto_access_list_item( }) } -pub fn from_proto_account_info( +fn from_proto_account_info( account_info: &proto::AccountInfo, ) -> eyre::Result { Ok(reth::revm::primitives::AccountInfo { @@ -781,7 +781,7 @@ pub fn from_proto_account_info( }) } -pub fn from_proto_bytecode( +fn from_proto_bytecode( bytecode: &proto::Bytecode, ) -> eyre::Result { let bytecode = match bytecode.bytecode.as_ref().ok_or_eyre("no bytecode")? { @@ -808,7 +808,7 @@ pub fn from_proto_bytecode( Ok(bytecode) } -pub fn from_proto_account_status(status: proto::AccountStatus) -> reth::revm::db::AccountStatus { +fn from_proto_account_status(status: proto::AccountStatus) -> reth::revm::db::AccountStatus { match status { proto::AccountStatus::LoadedNotExisting => reth::revm::db::AccountStatus::LoadedNotExisting, proto::AccountStatus::Loaded => reth::revm::db::AccountStatus::Loaded, From 64dca4676c5d21aa04c757c00ce2941e9fdb6c69 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 14:20:36 +0100 Subject: [PATCH 10/16] switch to from/tryfrom impls --- examples/exex/remote/bin/consumer.rs | 7 +- examples/exex/remote/bin/exex.rs | 11 +- examples/exex/remote/src/codec.rs | 1037 ++++++++++++++------------ 3 files changed, 557 insertions(+), 498 deletions(-) diff --git a/examples/exex/remote/bin/consumer.rs b/examples/exex/remote/bin/consumer.rs index 16d0ae96430b..ab28b06950a3 100644 --- a/examples/exex/remote/bin/consumer.rs +++ b/examples/exex/remote/bin/consumer.rs @@ -1,7 +1,4 @@ -use exex_remote::{ - codec::from_proto_notification, - proto::{remote_ex_ex_client::RemoteExExClient, SubscribeRequest}, -}; +use exex_remote::proto::{remote_ex_ex_client::RemoteExExClient, SubscribeRequest}; use reth_exex::ExExNotification; use reth_tracing::{tracing::info, RethTracer, Tracer}; @@ -16,7 +13,7 @@ async fn main() -> eyre::Result<()> { let mut stream = client.subscribe(SubscribeRequest {}).await?.into_inner(); while let Some(notification) = stream.message().await? { - let notification = from_proto_notification(¬ification)?; + let notification = ExExNotification::try_from(¬ification)?; match notification { ExExNotification::ChainCommitted { new } => { diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index 7cc2d4b03952..31cce4bf6c43 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -1,11 +1,8 @@ use std::sync::Arc; -use exex_remote::{ - codec, - proto::{ - remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, - ExExNotification as ProtoExExNotification, SubscribeRequest as ProtoSubscribeRequest, - }, +use exex_remote::proto::{ + remote_ex_ex_server::{RemoteExEx, RemoteExExServer}, + ExExNotification as ProtoExExNotification, SubscribeRequest as ProtoSubscribeRequest, }; use reth_exex::{ExExContext, ExExEvent, ExExNotification}; use reth_node_api::FullNodeComponents; @@ -32,7 +29,7 @@ impl RemoteExEx for ExExService { let mut notifications = self.notifications.subscribe(); tokio::spawn(async move { while let Ok(notification) = notifications.recv().await { - tx.send(Ok(codec::to_proto_notification(¬ification).expect("failed to encode"))) + tx.send(Ok((¬ification).try_into().expect("failed to encode"))) .await .expect("failed to send notification to client"); } diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs index 22167724c7bd..8f5386dc3613 100644 --- a/examples/exex/remote/src/codec.rs +++ b/examples/exex/remote/src/codec.rs @@ -5,45 +5,48 @@ use reth::primitives::{Address, BlockHash, Bloom, TxHash, B256, U256}; use crate::proto; -/// Converts a [Reth ExEx notification](`reth_exex::ExExNotification`) into -/// a [Protobuf ExEx notification](`proto::ExExNotification`) -pub fn to_proto_notification( - notification: &reth_exex::ExExNotification, -) -> eyre::Result { - let notification = match notification { - reth_exex::ExExNotification::ChainCommitted { new } => { - proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { - new: Some(to_proto_chain(&new)?), - }) - } - reth_exex::ExExNotification::ChainReorged { old, new } => { - proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { - old: Some(to_proto_chain(&old)?), - new: Some(to_proto_chain(&new)?), - }) - } - reth_exex::ExExNotification::ChainReverted { old } => { - proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { - old: Some(to_proto_chain(&old)?), - }) - } - }; +impl<'a> TryFrom<&'a reth_exex::ExExNotification> for proto::ExExNotification { + type Error = eyre::Error; - Ok(proto::ExExNotification { notification: Some(notification) }) + fn try_from(notification: &'a reth_exex::ExExNotification) -> Result { + let notification = match notification { + reth_exex::ExExNotification::ChainCommitted { new } => { + proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { + new: Some(new.as_ref().try_into()?), + }) + } + reth_exex::ExExNotification::ChainReorged { old, new } => { + proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { + old: Some(old.as_ref().try_into()?), + new: Some(new.as_ref().try_into()?), + }) + } + reth_exex::ExExNotification::ChainReverted { old } => { + proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { + old: Some(old.as_ref().try_into()?), + }) + } + }; + + Ok(proto::ExExNotification { notification: Some(notification) }) + } } -fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result { - let bundle_state = chain.execution_outcome().state(); - Ok(proto::Chain { +impl<'a> TryFrom<&'a reth::providers::Chain> for proto::Chain { + type Error = eyre::Error; + + fn try_from(chain: &'a reth::providers::Chain) -> Result { + let bundle_state = chain.execution_outcome().state(); + Ok(proto::Chain { blocks: chain .blocks_iter() .map(|block| proto::Block { header: Some(proto::SealedHeader { hash: block.header.hash().to_vec(), - header: Some(to_proto_header(&block.header.header())), + header: Some(block.header.header().into()), }), - body: block.transactions().map(to_proto_transaction).collect(), - ommers: block.ommers.iter().map(to_proto_header).collect(), + body: block.transactions().map(Into::into).collect(), + ommers: block.ommers.iter().map(Into::into).collect(), senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), }) .collect(), @@ -55,11 +58,11 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result .map(|(address, account)| { Ok(proto::BundleAccount { address: address.to_vec(), - info: account.info.as_ref().map(to_proto_account_info).transpose()?, + info: account.info.as_ref().map(TryInto::try_into).transpose()?, original_info: account .original_info .as_ref() - .map(to_proto_account_info) + .map(TryInto::try_into) .transpose()?, storage: account .storage @@ -72,7 +75,7 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result present_value: slot.present_value.to_le_bytes_vec(), }) .collect(), - status: to_proto_account_status(account.status) as i32, + status: proto::AccountStatus::from(account.status) as i32, }) }) .collect::>()?, @@ -82,7 +85,7 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result .map(|(hash, bytecode)| { Ok(proto::ContractBytecode { hash: hash.to_vec(), - bytecode: Some(to_proto_bytecode(bytecode)?), + bytecode: Some(bytecode.try_into()?), }) }) .collect::>()?, @@ -97,7 +100,7 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result account: Some(proto::AccountInfoRevert { revert: Some(match &revert.account { reth::revm::db::states::reverts::AccountInfoRevert::DoNothing => proto::account_info_revert::Revert::DoNothing(()), reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt => proto::account_info_revert::Revert::DeleteIt(()), - reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info) => proto::account_info_revert::Revert::RevertTo(to_proto_account_info(account_info)?), + reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info) => proto::account_info_revert::Revert::RevertTo(account_info.try_into()?), })}), storage: revert.storage.iter().map(|(key, slot)| Ok(proto::RevertToSlot { key: key.to_le_bytes_vec(), @@ -106,7 +109,7 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result reth::revm::db::RevertToSlot::Destroyed => proto::revert_to_slot::Revert::Destroyed(()), }), })).collect::>()?, - previous_status: to_proto_account_status(revert.previous_status) as i32, + previous_status: proto::AccountStatus::from(revert.previous_status) as i32, wipe_storage: revert.wipe_storage, })) .collect::>()?, @@ -169,226 +172,259 @@ fn to_proto_chain(chain: &reth::providers::Chain) -> eyre::Result first_block: chain.execution_outcome().first_block, }), }) + } } -fn to_proto_header(header: &reth::primitives::Header) -> proto::Header { - proto::Header { - parent_hash: header.parent_hash.to_vec(), - ommers_hash: header.ommers_hash.to_vec(), - beneficiary: header.beneficiary.to_vec(), - state_root: header.state_root.to_vec(), - transactions_root: header.transactions_root.to_vec(), - receipts_root: header.receipts_root.to_vec(), - withdrawals_root: header.withdrawals_root.map(|root| root.to_vec()), - logs_bloom: header.logs_bloom.to_vec(), - difficulty: header.difficulty.to_le_bytes_vec(), - number: header.number, - gas_limit: header.gas_limit, - gas_used: header.gas_used, - timestamp: header.timestamp, - mix_hash: header.mix_hash.to_vec(), - nonce: header.nonce, - base_fee_per_gas: header.base_fee_per_gas, - blob_gas_used: header.blob_gas_used, - excess_blob_gas: header.excess_blob_gas, - parent_beacon_block_root: header.parent_beacon_block_root.map(|root| root.to_vec()), - extra_data: header.extra_data.to_vec(), +impl<'a> From<&'a reth::primitives::Header> for proto::Header { + fn from(header: &'a reth::primitives::Header) -> Self { + proto::Header { + parent_hash: header.parent_hash.to_vec(), + ommers_hash: header.ommers_hash.to_vec(), + beneficiary: header.beneficiary.to_vec(), + state_root: header.state_root.to_vec(), + transactions_root: header.transactions_root.to_vec(), + receipts_root: header.receipts_root.to_vec(), + withdrawals_root: header.withdrawals_root.map(|root| root.to_vec()), + logs_bloom: header.logs_bloom.to_vec(), + difficulty: header.difficulty.to_le_bytes_vec(), + number: header.number, + gas_limit: header.gas_limit, + gas_used: header.gas_used, + timestamp: header.timestamp, + mix_hash: header.mix_hash.to_vec(), + nonce: header.nonce, + base_fee_per_gas: header.base_fee_per_gas, + blob_gas_used: header.blob_gas_used, + excess_blob_gas: header.excess_blob_gas, + parent_beacon_block_root: header.parent_beacon_block_root.map(|root| root.to_vec()), + extra_data: header.extra_data.to_vec(), + } } } -fn to_proto_transaction(transaction: &reth::primitives::TransactionSigned) -> proto::Transaction { - let hash = transaction.hash().to_vec(); - let signature = proto::Signature { - r: transaction.signature.r.to_le_bytes_vec(), - s: transaction.signature.s.to_le_bytes_vec(), - odd_y_parity: transaction.signature.odd_y_parity, - }; - let transaction = match &transaction.transaction { - reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { - chain_id, - nonce, - gas_price, - gas_limit, - to, - value, - input, - }) => proto::transaction::Transaction::Legacy(proto::TransactionLegacy { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_price: gas_price.to_le_bytes().to_vec(), - gas_limit: *gas_limit, - to: Some(to_proto_tx_kind(to)), - value: value.to_le_bytes_vec(), - input: input.to_vec(), - }), - reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { - chain_id, - nonce, - gas_price, - gas_limit, - to, - value, - access_list, - input, - }) => proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_price: gas_price.to_le_bytes().to_vec(), - gas_limit: *gas_limit, - to: Some(to_proto_tx_kind(to)), - value: value.to_le_bytes_vec(), - access_list: access_list.iter().map(to_proto_access_list_item).collect(), - input: input.to_vec(), - }), - reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { - chain_id, - nonce, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to, - value, - access_list, - input, - }) => proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_limit: *gas_limit, - max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), - max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), - to: Some(to_proto_tx_kind(to)), - value: value.to_le_bytes_vec(), - access_list: access_list.iter().map(to_proto_access_list_item).collect(), - input: input.to_vec(), - }), - reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { - chain_id, - nonce, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - placeholder: _, - to, - value, - access_list, - blob_versioned_hashes, - max_fee_per_blob_gas, - input, - }) => proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_limit: *gas_limit, - max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), - max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), - to: to.to_vec(), - value: value.to_le_bytes_vec(), - access_list: access_list.iter().map(to_proto_access_list_item).collect(), - blob_versioned_hashes: blob_versioned_hashes.iter().map(|hash| hash.to_vec()).collect(), - max_fee_per_blob_gas: max_fee_per_blob_gas.to_le_bytes().to_vec(), - input: input.to_vec(), - }), - }; +impl<'a> From<&'a reth::primitives::TransactionSigned> for proto::Transaction { + fn from(transaction: &'a reth::primitives::TransactionSigned) -> Self { + let hash = transaction.hash().to_vec(); + let signature = proto::Signature { + r: transaction.signature.r.to_le_bytes_vec(), + s: transaction.signature.s.to_le_bytes_vec(), + odd_y_parity: transaction.signature.odd_y_parity, + }; + let transaction = match &transaction.transaction { + reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + input, + }) => proto::transaction::Transaction::Legacy(proto::TransactionLegacy { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: gas_price.to_le_bytes().to_vec(), + gas_limit: *gas_limit, + to: Some(to.into()), + value: value.to_le_bytes_vec(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + access_list, + input, + }) => proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: gas_price.to_le_bytes().to_vec(), + gas_limit: *gas_limit, + to: Some(to.into()), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(Into::into).collect(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + input, + }) => proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), + max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), + to: Some(to.into()), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(Into::into).collect(), + input: input.to_vec(), + }), + reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + placeholder: _, + to, + value, + access_list, + blob_versioned_hashes, + max_fee_per_blob_gas, + input, + }) => proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), + max_priority_fee_per_gas: max_priority_fee_per_gas.to_le_bytes().to_vec(), + to: to.to_vec(), + value: value.to_le_bytes_vec(), + access_list: access_list.iter().map(Into::into).collect(), + blob_versioned_hashes: blob_versioned_hashes + .iter() + .map(|hash| hash.to_vec()) + .collect(), + max_fee_per_blob_gas: max_fee_per_blob_gas.to_le_bytes().to_vec(), + input: input.to_vec(), + }), + }; - proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) } + proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) } + } } -fn to_proto_tx_kind(kind: &reth::primitives::TxKind) -> proto::TxKind { - proto::TxKind { - kind: match kind { - reth::primitives::TxKind::Create => Some(proto::tx_kind::Kind::Create(())), - reth::primitives::TxKind::Call(address) => { - Some(proto::tx_kind::Kind::Call(address.to_vec())) - } - }, +impl<'a> From<&'a reth::primitives::TxKind> for proto::TxKind { + fn from(kind: &'a reth::primitives::TxKind) -> Self { + proto::TxKind { + kind: match kind { + reth::primitives::TxKind::Create => Some(proto::tx_kind::Kind::Create(())), + reth::primitives::TxKind::Call(address) => { + Some(proto::tx_kind::Kind::Call(address.to_vec())) + } + }, + } } } -fn to_proto_access_list_item(item: &reth::primitives::AccessListItem) -> proto::AccessListItem { - proto::AccessListItem { - address: item.address.to_vec(), - storage_keys: item.storage_keys.iter().map(|key| key.to_vec()).collect(), +impl<'a> From<&'a reth::primitives::AccessListItem> for proto::AccessListItem { + fn from(item: &'a reth::primitives::AccessListItem) -> Self { + proto::AccessListItem { + address: item.address.to_vec(), + storage_keys: item.storage_keys.iter().map(|key| key.to_vec()).collect(), + } } } -fn to_proto_account_info( - account_info: &reth::revm::primitives::AccountInfo, -) -> eyre::Result { - Ok(proto::AccountInfo { - balance: account_info.balance.to_le_bytes_vec(), - nonce: account_info.nonce, - code_hash: account_info.code_hash.to_vec(), - code: account_info.code.as_ref().map(to_proto_bytecode).transpose()?, - }) -} +impl<'a> TryFrom<&'a reth::revm::primitives::AccountInfo> for proto::AccountInfo { + type Error = eyre::Error; -fn to_proto_bytecode(bytecode: &reth::revm::primitives::Bytecode) -> eyre::Result { - let bytecode = match bytecode { - reth::revm::primitives::Bytecode::LegacyRaw(code) => { - proto::bytecode::Bytecode::LegacyRaw(code.to_vec()) - } - reth::revm::primitives::Bytecode::LegacyAnalyzed(legacy_analyzed) => { - proto::bytecode::Bytecode::LegacyAnalyzed(proto::LegacyAnalyzedBytecode { - bytecode: legacy_analyzed.bytecode().to_vec(), - original_len: legacy_analyzed.original_len() as u64, - jump_table: legacy_analyzed - .jump_table() - .0 - .iter() - .by_vals() - .map(|x| x.into()) - .collect(), - }) - } - reth::revm::primitives::Bytecode::Eof(_) => { - return Err(eyre::eyre!("EOF bytecode not supported")) - } - }; - Ok(proto::Bytecode { bytecode: Some(bytecode) }) + fn try_from( + account_info: &'a reth::revm::primitives::AccountInfo, + ) -> Result { + Ok(proto::AccountInfo { + balance: account_info.balance.to_le_bytes_vec(), + nonce: account_info.nonce, + code_hash: account_info.code_hash.to_vec(), + code: account_info.code.as_ref().map(TryInto::try_into).transpose()?, + }) + } } -fn to_proto_account_status(status: reth::revm::db::AccountStatus) -> proto::AccountStatus { - match status { - reth::revm::db::AccountStatus::LoadedNotExisting => proto::AccountStatus::LoadedNotExisting, - reth::revm::db::AccountStatus::Loaded => proto::AccountStatus::Loaded, - reth::revm::db::AccountStatus::LoadedEmptyEIP161 => proto::AccountStatus::LoadedEmptyEip161, - reth::revm::db::AccountStatus::InMemoryChange => proto::AccountStatus::InMemoryChange, - reth::revm::db::AccountStatus::Changed => proto::AccountStatus::Changed, - reth::revm::db::AccountStatus::Destroyed => proto::AccountStatus::Destroyed, - reth::revm::db::AccountStatus::DestroyedChanged => proto::AccountStatus::DestroyedChanged, - reth::revm::db::AccountStatus::DestroyedAgain => proto::AccountStatus::DestroyedAgain, +impl<'a> TryFrom<&'a reth::revm::primitives::Bytecode> for proto::Bytecode { + type Error = eyre::Error; + + fn try_from(bytecode: &'a reth::revm::primitives::Bytecode) -> Result { + let bytecode = match bytecode { + reth::revm::primitives::Bytecode::LegacyRaw(code) => { + proto::bytecode::Bytecode::LegacyRaw(code.to_vec()) + } + reth::revm::primitives::Bytecode::LegacyAnalyzed(legacy_analyzed) => { + proto::bytecode::Bytecode::LegacyAnalyzed(proto::LegacyAnalyzedBytecode { + bytecode: legacy_analyzed.bytecode().to_vec(), + original_len: legacy_analyzed.original_len() as u64, + jump_table: legacy_analyzed + .jump_table() + .0 + .iter() + .by_vals() + .map(|x| x.into()) + .collect(), + }) + } + reth::revm::primitives::Bytecode::Eof(_) => { + return Err(eyre::eyre!("EOF bytecode not supported")) + } + }; + Ok(proto::Bytecode { bytecode: Some(bytecode) }) } } -/// Converts a [Protobuf ExEx notification](`proto::ExExNotification`) into -/// a [Reth ExEx notification](`reth_exex::ExExNotification`) -pub fn from_proto_notification( - notification: &proto::ExExNotification, -) -> eyre::Result { - match notification.notification.as_ref().ok_or_eyre("no notification")? { - proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { new }) => { - Ok(reth_exex::ExExNotification::ChainCommitted { - new: from_proto_chain(new.as_ref().ok_or_eyre("no new chain")?)?, - }) - } - proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { old, new }) => { - Ok(reth_exex::ExExNotification::ChainReorged { - old: from_proto_chain(old.as_ref().ok_or_eyre("no old chain")?)?, - new: from_proto_chain(new.as_ref().ok_or_eyre("no new chain")?)?, - }) - } - proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { old }) => { - Ok(reth_exex::ExExNotification::ChainReverted { - old: from_proto_chain(old.as_ref().ok_or_eyre("no old chain")?)?, - }) +impl From for proto::AccountStatus { + fn from(status: reth::revm::db::AccountStatus) -> Self { + match status { + reth::revm::db::AccountStatus::LoadedNotExisting => { + proto::AccountStatus::LoadedNotExisting + } + reth::revm::db::AccountStatus::Loaded => proto::AccountStatus::Loaded, + reth::revm::db::AccountStatus::LoadedEmptyEIP161 => { + proto::AccountStatus::LoadedEmptyEip161 + } + reth::revm::db::AccountStatus::InMemoryChange => proto::AccountStatus::InMemoryChange, + reth::revm::db::AccountStatus::Changed => proto::AccountStatus::Changed, + reth::revm::db::AccountStatus::Destroyed => proto::AccountStatus::Destroyed, + reth::revm::db::AccountStatus::DestroyedChanged => { + proto::AccountStatus::DestroyedChanged + } + reth::revm::db::AccountStatus::DestroyedAgain => proto::AccountStatus::DestroyedAgain, } } } -fn from_proto_chain(chain: &proto::Chain) -> eyre::Result> { - let execution_outcome = chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; - let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; - Ok(Arc::new(reth::providers::Chain::new( - chain.blocks.iter().map(from_proto_block).collect::>>()?, +impl<'a> TryFrom<&'a proto::ExExNotification> for reth_exex::ExExNotification { + type Error = eyre::Error; + + fn try_from(notification: &'a proto::ExExNotification) -> Result { + Ok(match notification.notification.as_ref().ok_or_eyre("no notification")? { + proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { + new, + }) => reth_exex::ExExNotification::ChainCommitted { + new: Arc::new(new.as_ref().ok_or_eyre("no new chain")?.try_into()?), + }, + proto::ex_ex_notification::Notification::ChainReorged(proto::ChainReorged { + old, + new, + }) => reth_exex::ExExNotification::ChainReorged { + old: Arc::new(old.as_ref().ok_or_eyre("no old chain")?.try_into()?), + new: Arc::new(new.as_ref().ok_or_eyre("no new chain")?.try_into()?), + }, + proto::ex_ex_notification::Notification::ChainReverted(proto::ChainReverted { + old, + }) => reth_exex::ExExNotification::ChainReverted { + old: Arc::new(old.as_ref().ok_or_eyre("no old chain")?.try_into()?), + }, + }) + } +} + +impl<'a> TryFrom<&'a proto::Chain> for reth::providers::Chain { + type Error = eyre::Error; + + fn try_from(chain: &'a proto::Chain) -> Result { + let execution_outcome = + chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; + let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; + Ok(reth::providers::Chain::new( + chain.blocks.iter().map(TryInto::try_into).collect::>>()?, reth::providers::ExecutionOutcome { bundle: reth::revm::db::BundleState { state: bundle @@ -401,12 +437,12 @@ fn from_proto_chain(chain: &proto::Chain) -> eyre::Result eyre::Result>()?, - status: from_proto_account_status(proto::AccountStatus::try_from( + status: proto::AccountStatus::try_from( account.status, - )?), + )?.into(), }, )) }) @@ -443,9 +479,8 @@ fn from_proto_chain(chain: &proto::Chain) -> eyre::Result>()?, @@ -464,7 +499,7 @@ fn from_proto_chain(chain: &proto::Chain) -> eyre::Result reth::revm::db::states::reverts::AccountInfoRevert::DoNothing, proto::account_info_revert::Revert::DeleteIt(()) => reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt, - proto::account_info_revert::Revert::RevertTo(account_info) => reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(from_proto_account_info(account_info)?), + proto::account_info_revert::Revert::RevertTo(account_info) => reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info.try_into()?), }, storage: revert .storage @@ -478,11 +513,10 @@ fn from_proto_chain(chain: &proto::Chain) -> eyre::Result>()?, - previous_status: from_proto_account_status( + previous_status: proto::AccountStatus::try_from( revert.previous_status, - )?, - ), + )?.into(), wipe_storage: revert.wipe_storage, }, )) @@ -557,266 +591,297 @@ fn from_proto_chain(chain: &proto::Chain) -> eyre::Result eyre::Result { - let sealed_header = block.header.as_ref().ok_or_eyre("no sealed header")?; - let header = from_proto_header(sealed_header.header.as_ref().ok_or_eyre("no header")?)?; - let sealed_header = reth::primitives::SealedHeader::new( - header, - BlockHash::try_from(sealed_header.hash.as_slice())?, - ); - - let transactions = - block.body.iter().map(from_proto_transaction).collect::>()?; - let ommers = block.ommers.iter().map(from_proto_header).collect::>()?; - let senders = block - .senders - .iter() - .map(|sender| Address::try_from(sender.as_slice())) - .collect::>()?; - - reth::primitives::SealedBlockWithSenders::new( - reth::primitives::SealedBlock::new( - sealed_header, - reth::primitives::BlockBody { - transactions, - ommers, - withdrawals: Default::default(), - requests: Default::default(), - }, - ), - senders, - ) - .ok_or_eyre("senders do not match transactions") +impl<'a> TryFrom<&'a proto::Block> for reth::primitives::SealedBlockWithSenders { + type Error = eyre::Error; + + fn try_from(block: &'a proto::Block) -> Result { + let sealed_header = block.header.as_ref().ok_or_eyre("no sealed header")?; + let header = sealed_header.header.as_ref().ok_or_eyre("no header")?.try_into()?; + let sealed_header = reth::primitives::SealedHeader::new( + header, + BlockHash::try_from(sealed_header.hash.as_slice())?, + ); + + let transactions = block.body.iter().map(TryInto::try_into).collect::>()?; + let ommers = block.ommers.iter().map(TryInto::try_into).collect::>()?; + let senders = block + .senders + .iter() + .map(|sender| Address::try_from(sender.as_slice())) + .collect::>()?; + + reth::primitives::SealedBlockWithSenders::new( + reth::primitives::SealedBlock::new( + sealed_header, + reth::primitives::BlockBody { + transactions, + ommers, + withdrawals: Default::default(), + requests: Default::default(), + }, + ), + senders, + ) + .ok_or_eyre("senders do not match transactions") + } } -fn from_proto_header(header: &proto::Header) -> eyre::Result { - Ok(reth::primitives::Header { - parent_hash: B256::try_from(header.parent_hash.as_slice())?, - ommers_hash: B256::try_from(header.ommers_hash.as_slice())?, - beneficiary: Address::try_from(header.beneficiary.as_slice())?, - state_root: B256::try_from(header.state_root.as_slice())?, - transactions_root: B256::try_from(header.transactions_root.as_slice())?, - receipts_root: B256::try_from(header.receipts_root.as_slice())?, - withdrawals_root: header - .withdrawals_root - .as_ref() - .map(|root| B256::try_from(root.as_slice())) - .transpose()?, - logs_bloom: Bloom::try_from(header.logs_bloom.as_slice())?, - difficulty: U256::try_from_le_slice(&header.difficulty) - .ok_or_eyre("failed to parse difficulty")?, - number: header.number, - gas_limit: header.gas_limit, - gas_used: header.gas_used, - timestamp: header.timestamp, - mix_hash: B256::try_from(header.mix_hash.as_slice())?, - nonce: header.nonce, - base_fee_per_gas: header.base_fee_per_gas, - blob_gas_used: header.blob_gas_used, - excess_blob_gas: header.excess_blob_gas, - parent_beacon_block_root: header - .parent_beacon_block_root - .as_ref() - .map(|root| B256::try_from(root.as_slice())) - .transpose()?, - requests_root: None, - extra_data: header.extra_data.as_slice().to_vec().into(), - }) +impl<'a> TryFrom<&'a proto::Header> for reth::primitives::Header { + type Error = eyre::Error; + + fn try_from(header: &'a proto::Header) -> Result { + Ok(reth::primitives::Header { + parent_hash: B256::try_from(header.parent_hash.as_slice())?, + ommers_hash: B256::try_from(header.ommers_hash.as_slice())?, + beneficiary: Address::try_from(header.beneficiary.as_slice())?, + state_root: B256::try_from(header.state_root.as_slice())?, + transactions_root: B256::try_from(header.transactions_root.as_slice())?, + receipts_root: B256::try_from(header.receipts_root.as_slice())?, + withdrawals_root: header + .withdrawals_root + .as_ref() + .map(|root| B256::try_from(root.as_slice())) + .transpose()?, + logs_bloom: Bloom::try_from(header.logs_bloom.as_slice())?, + difficulty: U256::try_from_le_slice(&header.difficulty) + .ok_or_eyre("failed to parse difficulty")?, + number: header.number, + gas_limit: header.gas_limit, + gas_used: header.gas_used, + timestamp: header.timestamp, + mix_hash: B256::try_from(header.mix_hash.as_slice())?, + nonce: header.nonce, + base_fee_per_gas: header.base_fee_per_gas, + blob_gas_used: header.blob_gas_used, + excess_blob_gas: header.excess_blob_gas, + parent_beacon_block_root: header + .parent_beacon_block_root + .as_ref() + .map(|root| B256::try_from(root.as_slice())) + .transpose()?, + requests_root: None, + extra_data: header.extra_data.as_slice().to_vec().into(), + }) + } } -fn from_proto_transaction( - transaction: &proto::Transaction, -) -> eyre::Result { - let hash = TxHash::try_from(transaction.hash.as_slice())?; - let signature = transaction.signature.as_ref().ok_or_eyre("no signature")?; - let signature = reth::primitives::Signature { - r: U256::try_from_le_slice(signature.r.as_slice()).ok_or_eyre("failed to parse r")?, - s: U256::try_from_le_slice(signature.s.as_slice()).ok_or_eyre("failed to parse s")?, - odd_y_parity: signature.odd_y_parity, - }; - let transaction = match transaction.transaction.as_ref().ok_or_eyre("no transaction")? { - proto::transaction::Transaction::Legacy(proto::TransactionLegacy { - chain_id, - nonce, - gas_price, - gas_limit, - to, - value, - input, - }) => reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), - gas_limit: *gas_limit, - to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, - value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, - input: input.to_vec().into(), - }), - proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { - chain_id, - nonce, - gas_price, - gas_limit, - to, - value, - access_list, - input, - }) => reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), - gas_limit: *gas_limit, - to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, - value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, - access_list: access_list - .iter() - .map(from_proto_access_list_item) - .collect::>>()? - .into(), - input: input.to_vec().into(), - }), - proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { - chain_id, - nonce, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to, - value, - access_list, - input, - }) => reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_limit: *gas_limit, - max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), - max_priority_fee_per_gas: u128::from_le_bytes( - max_priority_fee_per_gas.as_slice().try_into()?, - ), - to: from_proto_tx_kind(to.as_ref().ok_or_eyre("no to")?)?, - value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, - access_list: access_list - .iter() - .map(from_proto_access_list_item) - .collect::>>()? - .into(), - input: input.to_vec().into(), - }), - proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { - chain_id, - nonce, - gas_limit, - max_fee_per_gas, - max_priority_fee_per_gas, - to, - value, - access_list, - blob_versioned_hashes, - max_fee_per_blob_gas, - input, - }) => reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { - chain_id: chain_id.clone(), - nonce: *nonce, - gas_limit: *gas_limit, - max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), - max_priority_fee_per_gas: u128::from_le_bytes( - max_priority_fee_per_gas.as_slice().try_into()?, - ), - placeholder: None, - to: Address::try_from(to.as_slice())?, - value: U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse value")?, - access_list: access_list - .iter() - .map(from_proto_access_list_item) - .collect::>>()? - .into(), - blob_versioned_hashes: blob_versioned_hashes - .iter() - .map(|hash| B256::try_from(hash.as_slice())) - .collect::>()?, - max_fee_per_blob_gas: u128::from_le_bytes(max_fee_per_blob_gas.as_slice().try_into()?), - input: input.to_vec().into(), - }), - }; +impl<'a> TryFrom<&'a proto::Transaction> for reth::primitives::TransactionSigned { + type Error = eyre::Error; - Ok(reth::primitives::TransactionSigned { hash, signature, transaction }) + fn try_from(transaction: &'a proto::Transaction) -> Result { + let hash = TxHash::try_from(transaction.hash.as_slice())?; + let signature = transaction.signature.as_ref().ok_or_eyre("no signature")?; + let signature = reth::primitives::Signature { + r: U256::try_from_le_slice(signature.r.as_slice()).ok_or_eyre("failed to parse r")?, + s: U256::try_from_le_slice(signature.s.as_slice()).ok_or_eyre("failed to parse s")?, + odd_y_parity: signature.odd_y_parity, + }; + let transaction = match transaction.transaction.as_ref().ok_or_eyre("no transaction")? { + proto::transaction::Transaction::Legacy(proto::TransactionLegacy { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + input, + }) => reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), + gas_limit: *gas_limit, + to: to.as_ref().ok_or_eyre("no to")?.try_into()?, + value: U256::try_from_le_slice(value.as_slice()) + .ok_or_eyre("failed to parse value")?, + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { + chain_id, + nonce, + gas_price, + gas_limit, + to, + value, + access_list, + input, + }) => reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), + gas_limit: *gas_limit, + to: to.as_ref().ok_or_eyre("no to")?.try_into()?, + value: U256::try_from_le_slice(value.as_slice()) + .ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(TryInto::try_into) + .collect::>>()? + .into(), + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + input, + }) => reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), + max_priority_fee_per_gas: u128::from_le_bytes( + max_priority_fee_per_gas.as_slice().try_into()?, + ), + to: to.as_ref().ok_or_eyre("no to")?.try_into()?, + value: U256::try_from_le_slice(value.as_slice()) + .ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(TryInto::try_into) + .collect::>>()? + .into(), + input: input.to_vec().into(), + }), + proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { + chain_id, + nonce, + gas_limit, + max_fee_per_gas, + max_priority_fee_per_gas, + to, + value, + access_list, + blob_versioned_hashes, + max_fee_per_blob_gas, + input, + }) => reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { + chain_id: chain_id.clone(), + nonce: *nonce, + gas_limit: *gas_limit, + max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), + max_priority_fee_per_gas: u128::from_le_bytes( + max_priority_fee_per_gas.as_slice().try_into()?, + ), + placeholder: None, + to: Address::try_from(to.as_slice())?, + value: U256::try_from_le_slice(value.as_slice()) + .ok_or_eyre("failed to parse value")?, + access_list: access_list + .iter() + .map(TryInto::try_into) + .collect::>>()? + .into(), + blob_versioned_hashes: blob_versioned_hashes + .iter() + .map(|hash| B256::try_from(hash.as_slice())) + .collect::>()?, + max_fee_per_blob_gas: u128::from_le_bytes( + max_fee_per_blob_gas.as_slice().try_into()?, + ), + input: input.to_vec().into(), + }), + }; + + Ok(reth::primitives::TransactionSigned { hash, signature, transaction }) + } } -fn from_proto_tx_kind(tx_kind: &proto::TxKind) -> eyre::Result { - Ok(match tx_kind.kind.as_ref().ok_or_eyre("no kind")? { - proto::tx_kind::Kind::Create(()) => reth::primitives::TxKind::Create, - proto::tx_kind::Kind::Call(address) => { - reth::primitives::TxKind::Call(Address::try_from(address.as_slice())?) - } - }) +impl<'a> TryFrom<&'a proto::TxKind> for reth::primitives::TxKind { + type Error = eyre::Error; + + fn try_from(tx_kind: &'a proto::TxKind) -> Result { + Ok(match tx_kind.kind.as_ref().ok_or_eyre("no kind")? { + proto::tx_kind::Kind::Create(()) => reth::primitives::TxKind::Create, + proto::tx_kind::Kind::Call(address) => { + reth::primitives::TxKind::Call(Address::try_from(address.as_slice())?) + } + }) + } } -fn from_proto_access_list_item( - item: &proto::AccessListItem, -) -> eyre::Result { - Ok(reth::primitives::AccessListItem { - address: Address::try_from(item.address.as_slice())?, - storage_keys: item - .storage_keys - .iter() - .map(|key| B256::try_from(key.as_slice())) - .collect::>()?, - }) +impl<'a> TryFrom<&'a proto::AccessListItem> for reth::primitives::AccessListItem { + type Error = eyre::Error; + + fn try_from(item: &'a proto::AccessListItem) -> Result { + Ok(reth::primitives::AccessListItem { + address: Address::try_from(item.address.as_slice())?, + storage_keys: item + .storage_keys + .iter() + .map(|key| B256::try_from(key.as_slice())) + .collect::>()?, + }) + } } -fn from_proto_account_info( - account_info: &proto::AccountInfo, -) -> eyre::Result { - Ok(reth::revm::primitives::AccountInfo { - balance: U256::try_from_le_slice(account_info.balance.as_slice()) - .ok_or_eyre("failed to parse balance")?, - nonce: account_info.nonce, - code_hash: B256::try_from(account_info.code_hash.as_slice())?, - code: account_info.code.as_ref().map(from_proto_bytecode).transpose()?, - }) +impl<'a> TryFrom<&'a proto::AccountInfo> for reth::revm::primitives::AccountInfo { + type Error = eyre::Error; + + fn try_from(account_info: &'a proto::AccountInfo) -> Result { + Ok(reth::revm::primitives::AccountInfo { + balance: U256::try_from_le_slice(account_info.balance.as_slice()) + .ok_or_eyre("failed to parse balance")?, + nonce: account_info.nonce, + code_hash: B256::try_from(account_info.code_hash.as_slice())?, + code: account_info.code.as_ref().map(TryInto::try_into).transpose()?, + }) + } } -fn from_proto_bytecode( - bytecode: &proto::Bytecode, -) -> eyre::Result { - let bytecode = match bytecode.bytecode.as_ref().ok_or_eyre("no bytecode")? { - proto::bytecode::Bytecode::LegacyRaw(code) => { - reth::revm::primitives::Bytecode::LegacyRaw(code.clone().into()) - } - proto::bytecode::Bytecode::LegacyAnalyzed(legacy_analyzed) => { - reth::revm::primitives::Bytecode::LegacyAnalyzed( - reth::revm::primitives::LegacyAnalyzedBytecode::new( - legacy_analyzed.bytecode.clone().into(), - legacy_analyzed.original_len as usize, - reth::revm::primitives::JumpTable::from_slice( - legacy_analyzed - .jump_table - .iter() - .map(|dest| *dest as u8) - .collect::>() - .as_slice(), +impl<'a> TryFrom<&'a proto::Bytecode> for reth::revm::primitives::Bytecode { + type Error = eyre::Error; + + fn try_from(bytecode: &'a proto::Bytecode) -> Result { + Ok(match bytecode.bytecode.as_ref().ok_or_eyre("no bytecode")? { + proto::bytecode::Bytecode::LegacyRaw(code) => { + reth::revm::primitives::Bytecode::LegacyRaw(code.clone().into()) + } + proto::bytecode::Bytecode::LegacyAnalyzed(legacy_analyzed) => { + reth::revm::primitives::Bytecode::LegacyAnalyzed( + reth::revm::primitives::LegacyAnalyzedBytecode::new( + legacy_analyzed.bytecode.clone().into(), + legacy_analyzed.original_len as usize, + reth::revm::primitives::JumpTable::from_slice( + legacy_analyzed + .jump_table + .iter() + .map(|dest| *dest as u8) + .collect::>() + .as_slice(), + ), ), - ), - ) - } - }; - Ok(bytecode) + ) + } + }) + } } -fn from_proto_account_status(status: proto::AccountStatus) -> reth::revm::db::AccountStatus { - match status { - proto::AccountStatus::LoadedNotExisting => reth::revm::db::AccountStatus::LoadedNotExisting, - proto::AccountStatus::Loaded => reth::revm::db::AccountStatus::Loaded, - proto::AccountStatus::LoadedEmptyEip161 => reth::revm::db::AccountStatus::LoadedEmptyEIP161, - proto::AccountStatus::InMemoryChange => reth::revm::db::AccountStatus::InMemoryChange, - proto::AccountStatus::Changed => reth::revm::db::AccountStatus::Changed, - proto::AccountStatus::Destroyed => reth::revm::db::AccountStatus::Destroyed, - proto::AccountStatus::DestroyedChanged => reth::revm::db::AccountStatus::DestroyedChanged, - proto::AccountStatus::DestroyedAgain => reth::revm::db::AccountStatus::DestroyedAgain, +impl From for reth::revm::db::AccountStatus { + fn from(status: proto::AccountStatus) -> Self { + match status { + proto::AccountStatus::LoadedNotExisting => { + reth::revm::db::AccountStatus::LoadedNotExisting + } + proto::AccountStatus::Loaded => reth::revm::db::AccountStatus::Loaded, + proto::AccountStatus::LoadedEmptyEip161 => { + reth::revm::db::AccountStatus::LoadedEmptyEIP161 + } + proto::AccountStatus::InMemoryChange => reth::revm::db::AccountStatus::InMemoryChange, + proto::AccountStatus::Changed => reth::revm::db::AccountStatus::Changed, + proto::AccountStatus::Destroyed => reth::revm::db::AccountStatus::Destroyed, + proto::AccountStatus::DestroyedChanged => { + reth::revm::db::AccountStatus::DestroyedChanged + } + proto::AccountStatus::DestroyedAgain => reth::revm::db::AccountStatus::DestroyedAgain, + } } } From d4136075e58ece1514bf338f0d90f7e31eadbd6c Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 14:33:33 +0100 Subject: [PATCH 11/16] more granular impls --- examples/exex/remote/src/codec.rs | 626 ++++++++++++++++-------------- 1 file changed, 335 insertions(+), 291 deletions(-) diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs index 8f5386dc3613..385d9b8db4c8 100644 --- a/examples/exex/remote/src/codec.rs +++ b/examples/exex/remote/src/codec.rs @@ -38,140 +38,61 @@ impl<'a> TryFrom<&'a reth::providers::Chain> for proto::Chain { fn try_from(chain: &'a reth::providers::Chain) -> Result { let bundle_state = chain.execution_outcome().state(); Ok(proto::Chain { - blocks: chain - .blocks_iter() - .map(|block| proto::Block { - header: Some(proto::SealedHeader { - hash: block.header.hash().to_vec(), - header: Some(block.header.header().into()), - }), - body: block.transactions().map(Into::into).collect(), - ommers: block.ommers.iter().map(Into::into).collect(), - senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), - }) - .collect(), - execution_outcome: Some(proto::ExecutionOutcome { - bundle: Some(proto::BundleState { - state: bundle_state - .state - .iter() - .map(|(address, account)| { - Ok(proto::BundleAccount { - address: address.to_vec(), - info: account.info.as_ref().map(TryInto::try_into).transpose()?, - original_info: account - .original_info - .as_ref() - .map(TryInto::try_into) - .transpose()?, - storage: account - .storage - .iter() - .map(|(key, slot)| proto::StorageSlot { - key: key.to_le_bytes_vec(), - previous_or_original_value: slot - .previous_or_original_value - .to_le_bytes_vec(), - present_value: slot.present_value.to_le_bytes_vec(), - }) - .collect(), - status: proto::AccountStatus::from(account.status) as i32, + blocks: chain + .blocks_iter() + .map(|block| proto::Block { + header: Some(proto::SealedHeader { + hash: block.header.hash().to_vec(), + header: Some(block.header.header().into()), + }), + body: block.transactions().map(Into::into).collect(), + ommers: block.ommers.iter().map(Into::into).collect(), + senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), + }) + .collect(), + execution_outcome: Some(proto::ExecutionOutcome { + bundle: Some(proto::BundleState { + state: bundle_state + .state + .iter() + .map(|(address, account)| (*address, account).try_into()) + .collect::>()?, + contracts: bundle_state + .contracts + .iter() + .map(|(hash, bytecode)| { + Ok(proto::ContractBytecode { + hash: hash.to_vec(), + bytecode: Some(bytecode.try_into()?), + }) }) - }) - .collect::>()?, - contracts: bundle_state - .contracts - .iter() - .map(|(hash, bytecode)| { - Ok(proto::ContractBytecode { - hash: hash.to_vec(), - bytecode: Some(bytecode.try_into()?), + .collect::>()?, + reverts: bundle_state + .reverts + .iter() + .map(|block_reverts| { + Ok(proto::BlockReverts { + reverts: block_reverts + .iter() + .map(|(address, revert)| (*address, revert).try_into()) + .collect::>()?, + }) }) - }) - .collect::>()?, - reverts: bundle_state - .reverts + .collect::>()?, + state_size: bundle_state.state_size as u64, + reverts_size: bundle_state.reverts_size as u64, + }), + receipts: chain + .execution_outcome() + .receipts() .iter() - .map(|block_reverts| Ok(proto::BlockReverts { - reverts: block_reverts - .iter() - .map(|(address, revert)| Ok(proto::Revert { - address: address.to_vec(), - account: Some(proto::AccountInfoRevert { revert: Some(match &revert.account { - reth::revm::db::states::reverts::AccountInfoRevert::DoNothing => proto::account_info_revert::Revert::DoNothing(()), - reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt => proto::account_info_revert::Revert::DeleteIt(()), - reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info) => proto::account_info_revert::Revert::RevertTo(account_info.try_into()?), - })}), - storage: revert.storage.iter().map(|(key, slot)| Ok(proto::RevertToSlot { - key: key.to_le_bytes_vec(), - revert: Some(match slot { - reth::revm::db::RevertToSlot::Some(value) => proto::revert_to_slot::Revert::Some(value.to_le_bytes_vec()), - reth::revm::db::RevertToSlot::Destroyed => proto::revert_to_slot::Revert::Destroyed(()), - }), - })).collect::>()?, - previous_status: proto::AccountStatus::from(revert.previous_status) as i32, - wipe_storage: revert.wipe_storage, - })) - .collect::>()?, - })) - .collect::>()?, - state_size: bundle_state.state_size as u64, - reverts_size: bundle_state.reverts_size as u64, + .map(|block_receipts| proto::BlockReceipts { + receipts: block_receipts.iter().map(Into::into).collect(), + }) + .collect(), + first_block: chain.execution_outcome().first_block, }), - receipts: chain - .execution_outcome() - .receipts() - .iter() - .map(|block_receipts| proto::BlockReceipts { - receipts: block_receipts - .iter() - .map(|receipt| proto::Receipt { - receipt: Some(receipt.as_ref().map_or( - proto::receipt::Receipt::Empty(()), - |receipt| { - proto::receipt::Receipt::NonEmpty(proto::NonEmptyReceipt { - tx_type: match receipt.tx_type { - reth::primitives::TxType::Legacy => { - proto::TxType::Legacy - } - reth::primitives::TxType::Eip2930 => { - proto::TxType::Eip2930 - } - reth::primitives::TxType::Eip1559 => { - proto::TxType::Eip1559 - } - reth::primitives::TxType::Eip4844 => { - proto::TxType::Eip4844 - } - } as i32, - success: receipt.success, - cumulative_gas_used: receipt.cumulative_gas_used, - logs: receipt - .logs - .iter() - .map(|log| proto::Log { - address: log.address.to_vec(), - data: Some(proto::LogData { - topics: log - .data - .topics() - .iter() - .map(|topic| topic.to_vec()) - .collect(), - data: log.data.data.to_vec(), - }), - }) - .collect(), - }) - }, - )), - }) - .collect(), - }) - .collect(), - first_block: chain.execution_outcome().first_block, - }), - }) + }) } } @@ -325,6 +246,30 @@ impl<'a> From<&'a reth::primitives::AccessListItem> for proto::AccessListItem { } } +impl<'a> TryFrom<(Address, &'a reth::revm::db::BundleAccount)> for proto::BundleAccount { + type Error = eyre::Error; + + fn try_from( + (address, account): (Address, &'a reth::revm::db::BundleAccount), + ) -> Result { + Ok(proto::BundleAccount { + address: address.to_vec(), + info: account.info.as_ref().map(TryInto::try_into).transpose()?, + original_info: account.original_info.as_ref().map(TryInto::try_into).transpose()?, + storage: account + .storage + .iter() + .map(|(key, slot)| proto::StorageSlot { + key: key.to_le_bytes_vec(), + previous_or_original_value: slot.previous_or_original_value.to_le_bytes_vec(), + present_value: slot.present_value.to_le_bytes_vec(), + }) + .collect(), + status: proto::AccountStatus::from(account.status) as i32, + }) + } +} + impl<'a> TryFrom<&'a reth::revm::primitives::AccountInfo> for proto::AccountInfo { type Error = eyre::Error; @@ -390,6 +335,86 @@ impl From for proto::AccountStatus { } } +impl<'a> TryFrom<(Address, &reth::revm::db::states::reverts::AccountRevert)> for proto::Revert { + type Error = eyre::Error; + + fn try_from( + (address, revert): (Address, &reth::revm::db::states::reverts::AccountRevert), + ) -> Result { + Ok(proto::Revert { + address: address.to_vec(), + account: Some(proto::AccountInfoRevert { + revert: Some(match &revert.account { + reth::revm::db::states::reverts::AccountInfoRevert::DoNothing => { + proto::account_info_revert::Revert::DoNothing(()) + } + reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt => { + proto::account_info_revert::Revert::DeleteIt(()) + } + reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info) => { + proto::account_info_revert::Revert::RevertTo(account_info.try_into()?) + } + }), + }), + storage: revert + .storage + .iter() + .map(|(key, slot)| { + Ok(proto::RevertToSlot { + key: key.to_le_bytes_vec(), + revert: Some(match slot { + reth::revm::db::RevertToSlot::Some(value) => { + proto::revert_to_slot::Revert::Some(value.to_le_bytes_vec()) + } + reth::revm::db::RevertToSlot::Destroyed => { + proto::revert_to_slot::Revert::Destroyed(()) + } + }), + }) + }) + .collect::>()?, + previous_status: proto::AccountStatus::from(revert.previous_status) as i32, + wipe_storage: revert.wipe_storage, + }) + } +} + +impl<'a> From<&'a Option> for proto::Receipt { + fn from(receipt: &'a Option) -> Self { + proto::Receipt { + receipt: Some(receipt.as_ref().map_or(proto::receipt::Receipt::Empty(()), |receipt| { + proto::receipt::Receipt::NonEmpty(receipt.into()) + })), + } + } +} + +impl<'a> From<&'a reth::primitives::Receipt> for proto::NonEmptyReceipt { + fn from(receipt: &'a reth::primitives::Receipt) -> Self { + proto::NonEmptyReceipt { + tx_type: match receipt.tx_type { + reth::primitives::TxType::Legacy => proto::TxType::Legacy, + reth::primitives::TxType::Eip2930 => proto::TxType::Eip2930, + reth::primitives::TxType::Eip1559 => proto::TxType::Eip1559, + reth::primitives::TxType::Eip4844 => proto::TxType::Eip4844, + } as i32, + success: receipt.success, + cumulative_gas_used: receipt.cumulative_gas_used, + logs: receipt + .logs + .iter() + .map(|log| proto::Log { + address: log.address.to_vec(), + data: Some(proto::LogData { + topics: log.data.topics().iter().map(|topic| topic.to_vec()).collect(), + data: log.data.data.to_vec(), + }), + }) + .collect(), + } + } +} + impl<'a> TryFrom<&'a proto::ExExNotification> for reth_exex::ExExNotification { type Error = eyre::Error; @@ -424,174 +449,58 @@ impl<'a> TryFrom<&'a proto::Chain> for reth::providers::Chain { chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; Ok(reth::providers::Chain::new( - chain.blocks.iter().map(TryInto::try_into).collect::>>()?, - reth::providers::ExecutionOutcome { - bundle: reth::revm::db::BundleState { - state: bundle - .state - .iter() - .map(|account| { - Ok(( - Address::try_from(account.address.as_slice())?, - reth::revm::db::BundleAccount { - info: account - .info - .as_ref() - .map(TryInto::try_into) - .transpose()?, - original_info: account - .original_info - .as_ref() - .map(TryInto::try_into) - .transpose()?, - storage: account - .storage - .iter() - .map(|slot| { - Ok(( - U256::try_from_le_slice(slot.key.as_slice()) - .ok_or_eyre("failed to parse key")?, - reth::revm::db::states::StorageSlot { - previous_or_original_value: U256::try_from_le_slice( - slot.previous_or_original_value.as_slice(), - ) - .ok_or_eyre( - "failed to parse previous or original value", - )?, - present_value: U256::try_from_le_slice( - slot.present_value.as_slice(), - ) - .ok_or_eyre("failed to parse present value")?, - }, - )) - }) - .collect::>()?, - status: proto::AccountStatus::try_from( - account.status, - )?.into(), - }, - )) - }) - .collect::>()?, - contracts: bundle - .contracts - .iter() - .map(|contract| { - Ok(( - B256::try_from(contract.hash.as_slice())?, - + chain.blocks.iter().map(TryInto::try_into).collect::>>()?, + reth::providers::ExecutionOutcome { + bundle: reth::revm::db::BundleState { + state: bundle + .state + .iter() + .map(TryInto::try_into) + .collect::>()?, + contracts: bundle + .contracts + .iter() + .map(|contract| { + Ok(( + B256::try_from(contract.hash.as_slice())?, contract.bytecode.as_ref().ok_or_eyre("no bytecode")?.try_into()?, - )) - }) - .collect::>()?, - reverts: reth::revm::db::states::reverts::Reverts::new( - bundle - .reverts + )) + }) + .collect::>()?, + reverts: reth::revm::db::states::reverts::Reverts::new( + bundle + .reverts + .iter() + .map(|block_reverts| { + Ok(block_reverts + .reverts + .iter() + .map(TryInto::try_into) + .collect::>()?) + }) + .collect::>()?, + ), + state_size: bundle.state_size as usize, + reverts_size: bundle.reverts_size as usize, + }, + receipts: reth::primitives::Receipts::from_iter( + execution_outcome + .receipts .iter() - .map(|block_reverts| { - Ok(block_reverts - .reverts + .map(|block_receipts| { + Ok(block_receipts + .receipts .iter() - .map(|revert| { - Ok(( - Address::try_from(revert.address.as_slice())?, - reth::revm::db::states::reverts::AccountRevert { - account: match revert.account.as_ref().ok_or_eyre("no revert account")?.revert.as_ref().ok_or_eyre("no revert account revert")? { - proto::account_info_revert::Revert::DoNothing(()) => reth::revm::db::states::reverts::AccountInfoRevert::DoNothing, - proto::account_info_revert::Revert::DeleteIt(()) => reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt, - proto::account_info_revert::Revert::RevertTo(account_info) => reth::revm::db::states::reverts::AccountInfoRevert::RevertTo(account_info.try_into()?), - }, - storage: revert - .storage - .iter() - .map(|slot| Ok(( - U256::try_from_le_slice(slot.key.as_slice()) - .ok_or_eyre("failed to parse slot key")?, - match slot.revert.as_ref().ok_or_eyre("no slot revert")? { - proto::revert_to_slot::Revert::Some(value) => reth::revm::db::states::reverts::RevertToSlot::Some(U256::try_from_le_slice(value.as_slice()).ok_or_eyre("failed to parse slot revert")?), - proto::revert_to_slot::Revert::Destroyed(()) => reth::revm::db::states::reverts::RevertToSlot::Destroyed, - } - ))) - .collect::>()?, - previous_status: - proto::AccountStatus::try_from( - revert.previous_status, - )?.into(), - wipe_storage: revert.wipe_storage, - }, - )) - }) + .map(TryInto::try_into) .collect::>()?) }) - .collect::>()?, + .collect::>>()?, ), - state_size: bundle.state_size as usize, - reverts_size: bundle.reverts_size as usize, + first_block: execution_outcome.first_block, + requests: Default::default(), }, - receipts: reth::primitives::Receipts::from_iter(execution_outcome - .receipts - .iter() - .map(|block_receipts| { - Ok(block_receipts - .receipts - .iter() - .map(|receipt| { - Ok(match receipt.receipt.as_ref().ok_or_eyre("no receipt")? { - proto::receipt::Receipt::Empty(()) => None, - proto::receipt::Receipt::NonEmpty(receipt) => { - Some(reth::primitives::Receipt { - tx_type: match proto::TxType::try_from(receipt.tx_type)? { - proto::TxType::Legacy => { - reth::primitives::TxType::Legacy - } - proto::TxType::Eip2930 => { - reth::primitives::TxType::Eip2930 - } - proto::TxType::Eip1559 => { - reth::primitives::TxType::Eip1559 - } - proto::TxType::Eip4844 => { - reth::primitives::TxType::Eip4844 - } - }, - success: receipt.success, - cumulative_gas_used: receipt.cumulative_gas_used, - logs: receipt - .logs - .iter() - .map(|log| { - let data = - log.data.as_ref().ok_or_eyre("no log data")?; - Ok(reth::primitives::Log { - address: Address::try_from( - log.address.as_slice(), - )?, - data: reth::primitives::LogData::new_unchecked( - data.topics - .iter() - .map(|topic| { - Ok(B256::try_from( - topic.as_slice(), - )?) - }) - .collect::>()?, - data.data.clone().into(), - ), - }) - }) - .collect::>()?, - }) - } - }) - }) - .collect::>()?) - }) - .collect::>>()?), - first_block: execution_outcome.first_block, - requests: Default::default(), - }, - None, - )) + None, + )) } } @@ -885,3 +794,138 @@ impl From for reth::revm::db::AccountStatus { } } } + +impl<'a> TryFrom<&'a proto::BundleAccount> for (Address, reth::revm::db::BundleAccount) { + type Error = eyre::Error; + + fn try_from(account: &'a proto::BundleAccount) -> Result { + Ok(( + Address::try_from(account.address.as_slice())?, + reth::revm::db::BundleAccount { + info: account.info.as_ref().map(TryInto::try_into).transpose()?, + original_info: account.original_info.as_ref().map(TryInto::try_into).transpose()?, + storage: account + .storage + .iter() + .map(|slot| { + Ok(( + U256::try_from_le_slice(slot.key.as_slice()) + .ok_or_eyre("failed to parse key")?, + reth::revm::db::states::StorageSlot { + previous_or_original_value: U256::try_from_le_slice( + slot.previous_or_original_value.as_slice(), + ) + .ok_or_eyre("failed to parse previous or original value")?, + present_value: U256::try_from_le_slice( + slot.present_value.as_slice(), + ) + .ok_or_eyre("failed to parse present value")?, + }, + )) + }) + .collect::>()?, + status: proto::AccountStatus::try_from(account.status)?.into(), + }, + )) + } +} + +impl<'a> TryFrom<&'a proto::Revert> for (Address, reth::revm::db::states::reverts::AccountRevert) { + type Error = eyre::Error; + + fn try_from(revert: &'a proto::Revert) -> Result { + Ok(( + Address::try_from(revert.address.as_slice())?, + reth::revm::db::states::reverts::AccountRevert { + account: match revert + .account + .as_ref() + .ok_or_eyre("no revert account")? + .revert + .as_ref() + .ok_or_eyre("no revert account revert")? + { + proto::account_info_revert::Revert::DoNothing(()) => { + reth::revm::db::states::reverts::AccountInfoRevert::DoNothing + } + proto::account_info_revert::Revert::DeleteIt(()) => { + reth::revm::db::states::reverts::AccountInfoRevert::DeleteIt + } + proto::account_info_revert::Revert::RevertTo(account_info) => { + reth::revm::db::states::reverts::AccountInfoRevert::RevertTo( + account_info.try_into()?, + ) + } + }, + storage: revert + .storage + .iter() + .map(|slot| { + Ok(( + U256::try_from_le_slice(slot.key.as_slice()) + .ok_or_eyre("failed to parse slot key")?, + match slot.revert.as_ref().ok_or_eyre("no slot revert")? { + proto::revert_to_slot::Revert::Some(value) => { + reth::revm::db::states::reverts::RevertToSlot::Some( + U256::try_from_le_slice(value.as_slice()) + .ok_or_eyre("failed to parse slot revert")?, + ) + } + proto::revert_to_slot::Revert::Destroyed(()) => { + reth::revm::db::states::reverts::RevertToSlot::Destroyed + } + }, + )) + }) + .collect::>()?, + previous_status: proto::AccountStatus::try_from(revert.previous_status)?.into(), + wipe_storage: revert.wipe_storage, + }, + )) + } +} + +impl<'a> TryFrom<&'a proto::Receipt> for Option { + type Error = eyre::Error; + + fn try_from(receipt: &'a proto::Receipt) -> Result { + Ok(match receipt.receipt.as_ref().ok_or_eyre("no receipt")? { + proto::receipt::Receipt::Empty(()) => None, + proto::receipt::Receipt::NonEmpty(receipt) => Some(receipt.try_into()?), + }) + } +} + +impl<'a> TryFrom<&'a proto::NonEmptyReceipt> for reth::primitives::Receipt { + type Error = eyre::Error; + + fn try_from(receipt: &'a proto::NonEmptyReceipt) -> Result { + Ok(reth::primitives::Receipt { + tx_type: match proto::TxType::try_from(receipt.tx_type)? { + proto::TxType::Legacy => reth::primitives::TxType::Legacy, + proto::TxType::Eip2930 => reth::primitives::TxType::Eip2930, + proto::TxType::Eip1559 => reth::primitives::TxType::Eip1559, + proto::TxType::Eip4844 => reth::primitives::TxType::Eip4844, + }, + success: receipt.success, + cumulative_gas_used: receipt.cumulative_gas_used, + logs: receipt + .logs + .iter() + .map(|log| { + let data = log.data.as_ref().ok_or_eyre("no log data")?; + Ok(reth::primitives::Log { + address: Address::try_from(log.address.as_slice())?, + data: reth::primitives::LogData::new_unchecked( + data.topics + .iter() + .map(|topic| Ok(B256::try_from(topic.as_slice())?)) + .collect::>()?, + data.data.clone().into(), + ), + }) + }) + .collect::>()?, + }) + } +} From 13b15af3b1e8b3f4369f0318ce43917d981de6be Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 14:37:49 +0100 Subject: [PATCH 12/16] remove lifetimes --- examples/exex/remote/src/codec.rs | 100 +++++++++++++++--------------- 1 file changed, 49 insertions(+), 51 deletions(-) diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs index 385d9b8db4c8..3abb511c7546 100644 --- a/examples/exex/remote/src/codec.rs +++ b/examples/exex/remote/src/codec.rs @@ -5,10 +5,10 @@ use reth::primitives::{Address, BlockHash, Bloom, TxHash, B256, U256}; use crate::proto; -impl<'a> TryFrom<&'a reth_exex::ExExNotification> for proto::ExExNotification { +impl TryFrom<&reth_exex::ExExNotification> for proto::ExExNotification { type Error = eyre::Error; - fn try_from(notification: &'a reth_exex::ExExNotification) -> Result { + fn try_from(notification: &reth_exex::ExExNotification) -> Result { let notification = match notification { reth_exex::ExExNotification::ChainCommitted { new } => { proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { @@ -32,10 +32,10 @@ impl<'a> TryFrom<&'a reth_exex::ExExNotification> for proto::ExExNotification { } } -impl<'a> TryFrom<&'a reth::providers::Chain> for proto::Chain { +impl TryFrom<&reth::providers::Chain> for proto::Chain { type Error = eyre::Error; - fn try_from(chain: &'a reth::providers::Chain) -> Result { + fn try_from(chain: &reth::providers::Chain) -> Result { let bundle_state = chain.execution_outcome().state(); Ok(proto::Chain { blocks: chain @@ -96,8 +96,8 @@ impl<'a> TryFrom<&'a reth::providers::Chain> for proto::Chain { } } -impl<'a> From<&'a reth::primitives::Header> for proto::Header { - fn from(header: &'a reth::primitives::Header) -> Self { +impl From<&reth::primitives::Header> for proto::Header { + fn from(header: &reth::primitives::Header) -> Self { proto::Header { parent_hash: header.parent_hash.to_vec(), ommers_hash: header.ommers_hash.to_vec(), @@ -123,8 +123,8 @@ impl<'a> From<&'a reth::primitives::Header> for proto::Header { } } -impl<'a> From<&'a reth::primitives::TransactionSigned> for proto::Transaction { - fn from(transaction: &'a reth::primitives::TransactionSigned) -> Self { +impl From<&reth::primitives::TransactionSigned> for proto::Transaction { + fn from(transaction: &reth::primitives::TransactionSigned) -> Self { let hash = transaction.hash().to_vec(); let signature = proto::Signature { r: transaction.signature.r.to_le_bytes_vec(), @@ -224,8 +224,8 @@ impl<'a> From<&'a reth::primitives::TransactionSigned> for proto::Transaction { } } -impl<'a> From<&'a reth::primitives::TxKind> for proto::TxKind { - fn from(kind: &'a reth::primitives::TxKind) -> Self { +impl From<&reth::primitives::TxKind> for proto::TxKind { + fn from(kind: &reth::primitives::TxKind) -> Self { proto::TxKind { kind: match kind { reth::primitives::TxKind::Create => Some(proto::tx_kind::Kind::Create(())), @@ -237,8 +237,8 @@ impl<'a> From<&'a reth::primitives::TxKind> for proto::TxKind { } } -impl<'a> From<&'a reth::primitives::AccessListItem> for proto::AccessListItem { - fn from(item: &'a reth::primitives::AccessListItem) -> Self { +impl From<&reth::primitives::AccessListItem> for proto::AccessListItem { + fn from(item: &reth::primitives::AccessListItem) -> Self { proto::AccessListItem { address: item.address.to_vec(), storage_keys: item.storage_keys.iter().map(|key| key.to_vec()).collect(), @@ -246,11 +246,11 @@ impl<'a> From<&'a reth::primitives::AccessListItem> for proto::AccessListItem { } } -impl<'a> TryFrom<(Address, &'a reth::revm::db::BundleAccount)> for proto::BundleAccount { +impl TryFrom<(Address, &reth::revm::db::BundleAccount)> for proto::BundleAccount { type Error = eyre::Error; fn try_from( - (address, account): (Address, &'a reth::revm::db::BundleAccount), + (address, account): (Address, &reth::revm::db::BundleAccount), ) -> Result { Ok(proto::BundleAccount { address: address.to_vec(), @@ -270,12 +270,10 @@ impl<'a> TryFrom<(Address, &'a reth::revm::db::BundleAccount)> for proto::Bundle } } -impl<'a> TryFrom<&'a reth::revm::primitives::AccountInfo> for proto::AccountInfo { +impl TryFrom<&reth::revm::primitives::AccountInfo> for proto::AccountInfo { type Error = eyre::Error; - fn try_from( - account_info: &'a reth::revm::primitives::AccountInfo, - ) -> Result { + fn try_from(account_info: &reth::revm::primitives::AccountInfo) -> Result { Ok(proto::AccountInfo { balance: account_info.balance.to_le_bytes_vec(), nonce: account_info.nonce, @@ -285,10 +283,10 @@ impl<'a> TryFrom<&'a reth::revm::primitives::AccountInfo> for proto::AccountInfo } } -impl<'a> TryFrom<&'a reth::revm::primitives::Bytecode> for proto::Bytecode { +impl TryFrom<&reth::revm::primitives::Bytecode> for proto::Bytecode { type Error = eyre::Error; - fn try_from(bytecode: &'a reth::revm::primitives::Bytecode) -> Result { + fn try_from(bytecode: &reth::revm::primitives::Bytecode) -> Result { let bytecode = match bytecode { reth::revm::primitives::Bytecode::LegacyRaw(code) => { proto::bytecode::Bytecode::LegacyRaw(code.to_vec()) @@ -335,7 +333,7 @@ impl From for proto::AccountStatus { } } -impl<'a> TryFrom<(Address, &reth::revm::db::states::reverts::AccountRevert)> for proto::Revert { +impl TryFrom<(Address, &reth::revm::db::states::reverts::AccountRevert)> for proto::Revert { type Error = eyre::Error; fn try_from( @@ -379,8 +377,8 @@ impl<'a> TryFrom<(Address, &reth::revm::db::states::reverts::AccountRevert)> for } } -impl<'a> From<&'a Option> for proto::Receipt { - fn from(receipt: &'a Option) -> Self { +impl From<&Option> for proto::Receipt { + fn from(receipt: &Option) -> Self { proto::Receipt { receipt: Some(receipt.as_ref().map_or(proto::receipt::Receipt::Empty(()), |receipt| { proto::receipt::Receipt::NonEmpty(receipt.into()) @@ -389,8 +387,8 @@ impl<'a> From<&'a Option> for proto::Receipt { } } -impl<'a> From<&'a reth::primitives::Receipt> for proto::NonEmptyReceipt { - fn from(receipt: &'a reth::primitives::Receipt) -> Self { +impl From<&reth::primitives::Receipt> for proto::NonEmptyReceipt { + fn from(receipt: &reth::primitives::Receipt) -> Self { proto::NonEmptyReceipt { tx_type: match receipt.tx_type { reth::primitives::TxType::Legacy => proto::TxType::Legacy, @@ -415,10 +413,10 @@ impl<'a> From<&'a reth::primitives::Receipt> for proto::NonEmptyReceipt { } } -impl<'a> TryFrom<&'a proto::ExExNotification> for reth_exex::ExExNotification { +impl TryFrom<&proto::ExExNotification> for reth_exex::ExExNotification { type Error = eyre::Error; - fn try_from(notification: &'a proto::ExExNotification) -> Result { + fn try_from(notification: &proto::ExExNotification) -> Result { Ok(match notification.notification.as_ref().ok_or_eyre("no notification")? { proto::ex_ex_notification::Notification::ChainCommitted(proto::ChainCommitted { new, @@ -441,10 +439,10 @@ impl<'a> TryFrom<&'a proto::ExExNotification> for reth_exex::ExExNotification { } } -impl<'a> TryFrom<&'a proto::Chain> for reth::providers::Chain { +impl TryFrom<&proto::Chain> for reth::providers::Chain { type Error = eyre::Error; - fn try_from(chain: &'a proto::Chain) -> Result { + fn try_from(chain: &proto::Chain) -> Result { let execution_outcome = chain.execution_outcome.as_ref().ok_or_eyre("no execution outcome")?; let bundle = execution_outcome.bundle.as_ref().ok_or_eyre("no bundle")?; @@ -504,10 +502,10 @@ impl<'a> TryFrom<&'a proto::Chain> for reth::providers::Chain { } } -impl<'a> TryFrom<&'a proto::Block> for reth::primitives::SealedBlockWithSenders { +impl TryFrom<&proto::Block> for reth::primitives::SealedBlockWithSenders { type Error = eyre::Error; - fn try_from(block: &'a proto::Block) -> Result { + fn try_from(block: &proto::Block) -> Result { let sealed_header = block.header.as_ref().ok_or_eyre("no sealed header")?; let header = sealed_header.header.as_ref().ok_or_eyre("no header")?.try_into()?; let sealed_header = reth::primitives::SealedHeader::new( @@ -539,10 +537,10 @@ impl<'a> TryFrom<&'a proto::Block> for reth::primitives::SealedBlockWithSenders } } -impl<'a> TryFrom<&'a proto::Header> for reth::primitives::Header { +impl TryFrom<&proto::Header> for reth::primitives::Header { type Error = eyre::Error; - fn try_from(header: &'a proto::Header) -> Result { + fn try_from(header: &proto::Header) -> Result { Ok(reth::primitives::Header { parent_hash: B256::try_from(header.parent_hash.as_slice())?, ommers_hash: B256::try_from(header.ommers_hash.as_slice())?, @@ -578,10 +576,10 @@ impl<'a> TryFrom<&'a proto::Header> for reth::primitives::Header { } } -impl<'a> TryFrom<&'a proto::Transaction> for reth::primitives::TransactionSigned { +impl TryFrom<&proto::Transaction> for reth::primitives::TransactionSigned { type Error = eyre::Error; - fn try_from(transaction: &'a proto::Transaction) -> Result { + fn try_from(transaction: &proto::Transaction) -> Result { let hash = TxHash::try_from(transaction.hash.as_slice())?; let signature = transaction.signature.as_ref().ok_or_eyre("no signature")?; let signature = reth::primitives::Signature { @@ -704,10 +702,10 @@ impl<'a> TryFrom<&'a proto::Transaction> for reth::primitives::TransactionSigned } } -impl<'a> TryFrom<&'a proto::TxKind> for reth::primitives::TxKind { +impl TryFrom<&proto::TxKind> for reth::primitives::TxKind { type Error = eyre::Error; - fn try_from(tx_kind: &'a proto::TxKind) -> Result { + fn try_from(tx_kind: &proto::TxKind) -> Result { Ok(match tx_kind.kind.as_ref().ok_or_eyre("no kind")? { proto::tx_kind::Kind::Create(()) => reth::primitives::TxKind::Create, proto::tx_kind::Kind::Call(address) => { @@ -717,10 +715,10 @@ impl<'a> TryFrom<&'a proto::TxKind> for reth::primitives::TxKind { } } -impl<'a> TryFrom<&'a proto::AccessListItem> for reth::primitives::AccessListItem { +impl TryFrom<&proto::AccessListItem> for reth::primitives::AccessListItem { type Error = eyre::Error; - fn try_from(item: &'a proto::AccessListItem) -> Result { + fn try_from(item: &proto::AccessListItem) -> Result { Ok(reth::primitives::AccessListItem { address: Address::try_from(item.address.as_slice())?, storage_keys: item @@ -732,10 +730,10 @@ impl<'a> TryFrom<&'a proto::AccessListItem> for reth::primitives::AccessListItem } } -impl<'a> TryFrom<&'a proto::AccountInfo> for reth::revm::primitives::AccountInfo { +impl TryFrom<&proto::AccountInfo> for reth::revm::primitives::AccountInfo { type Error = eyre::Error; - fn try_from(account_info: &'a proto::AccountInfo) -> Result { + fn try_from(account_info: &proto::AccountInfo) -> Result { Ok(reth::revm::primitives::AccountInfo { balance: U256::try_from_le_slice(account_info.balance.as_slice()) .ok_or_eyre("failed to parse balance")?, @@ -746,10 +744,10 @@ impl<'a> TryFrom<&'a proto::AccountInfo> for reth::revm::primitives::AccountInfo } } -impl<'a> TryFrom<&'a proto::Bytecode> for reth::revm::primitives::Bytecode { +impl TryFrom<&proto::Bytecode> for reth::revm::primitives::Bytecode { type Error = eyre::Error; - fn try_from(bytecode: &'a proto::Bytecode) -> Result { + fn try_from(bytecode: &proto::Bytecode) -> Result { Ok(match bytecode.bytecode.as_ref().ok_or_eyre("no bytecode")? { proto::bytecode::Bytecode::LegacyRaw(code) => { reth::revm::primitives::Bytecode::LegacyRaw(code.clone().into()) @@ -795,10 +793,10 @@ impl From for reth::revm::db::AccountStatus { } } -impl<'a> TryFrom<&'a proto::BundleAccount> for (Address, reth::revm::db::BundleAccount) { +impl TryFrom<&proto::BundleAccount> for (Address, reth::revm::db::BundleAccount) { type Error = eyre::Error; - fn try_from(account: &'a proto::BundleAccount) -> Result { + fn try_from(account: &proto::BundleAccount) -> Result { Ok(( Address::try_from(account.address.as_slice())?, reth::revm::db::BundleAccount { @@ -830,10 +828,10 @@ impl<'a> TryFrom<&'a proto::BundleAccount> for (Address, reth::revm::db::BundleA } } -impl<'a> TryFrom<&'a proto::Revert> for (Address, reth::revm::db::states::reverts::AccountRevert) { +impl TryFrom<&proto::Revert> for (Address, reth::revm::db::states::reverts::AccountRevert) { type Error = eyre::Error; - fn try_from(revert: &'a proto::Revert) -> Result { + fn try_from(revert: &proto::Revert) -> Result { Ok(( Address::try_from(revert.address.as_slice())?, reth::revm::db::states::reverts::AccountRevert { @@ -885,10 +883,10 @@ impl<'a> TryFrom<&'a proto::Revert> for (Address, reth::revm::db::states::revert } } -impl<'a> TryFrom<&'a proto::Receipt> for Option { +impl TryFrom<&proto::Receipt> for Option { type Error = eyre::Error; - fn try_from(receipt: &'a proto::Receipt) -> Result { + fn try_from(receipt: &proto::Receipt) -> Result { Ok(match receipt.receipt.as_ref().ok_or_eyre("no receipt")? { proto::receipt::Receipt::Empty(()) => None, proto::receipt::Receipt::NonEmpty(receipt) => Some(receipt.try_into()?), @@ -896,10 +894,10 @@ impl<'a> TryFrom<&'a proto::Receipt> for Option { } } -impl<'a> TryFrom<&'a proto::NonEmptyReceipt> for reth::primitives::Receipt { +impl TryFrom<&proto::NonEmptyReceipt> for reth::primitives::Receipt { type Error = eyre::Error; - fn try_from(receipt: &'a proto::NonEmptyReceipt) -> Result { + fn try_from(receipt: &proto::NonEmptyReceipt) -> Result { Ok(reth::primitives::Receipt { tx_type: match proto::TxType::try_from(receipt.tx_type)? { proto::TxType::Legacy => reth::primitives::TxType::Legacy, From 165956360504a5746d3d6c403c71cb209924de9e Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 15:45:34 +0100 Subject: [PATCH 13/16] fix ci --- .github/workflows/book.yml | 2 +- .github/workflows/lint.yml | 2 ++ .github/workflows/unit.yml | 1 + 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/book.yml b/.github/workflows/book.yml index 449908f45078..3fcd2e9c16b5 100644 --- a/.github/workflows/book.yml +++ b/.github/workflows/book.yml @@ -78,7 +78,7 @@ jobs: run: mdbook build - name: Build docs - run: cargo docs + run: cargo docs --exclude exex-remote env: # Keep in sync with ./ci.yml:jobs.docs RUSTDOCFLAGS: diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index c07cee38830b..59ca1f6da37c 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -41,6 +41,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true + - uses: arduino/setup-protoc@v3 - run: cargo clippy --workspace --lib --examples --tests --benches --all-features --locked env: RUSTFLAGS: -D warnings @@ -105,6 +106,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true + - uses: arduino/setup-protoc@v3 - run: cargo docs --document-private-items env: # Keep in sync with ./book.yml:jobs.build diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index de1cbe333927..2b6502b501b2 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -84,6 +84,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true + - uses: arduino/setup-protoc@v3 - name: Run doctests run: cargo test --doc --workspace --features "${{ matrix.network }}" From 5cae0ac60db5b822ff2ba1ebd137a7b5266c914f Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 16:04:18 +0100 Subject: [PATCH 14/16] optimism feature --- examples/exex/remote/Cargo.toml | 4 ++ examples/exex/remote/src/codec.rs | 110 +++++++++++++++++++----------- 2 files changed, 75 insertions(+), 39 deletions(-) diff --git a/examples/exex/remote/Cargo.toml b/examples/exex/remote/Cargo.toml index 3597b2cd6080..6061f2bef312 100644 --- a/examples/exex/remote/Cargo.toml +++ b/examples/exex/remote/Cargo.toml @@ -29,6 +29,10 @@ reth-exex-test-utils.workspace = true tokio.workspace = true +[features] +default = [] +optimism = ["reth/optimism"] + [[bin]] name = "exex" path = "bin/exex.rs" diff --git a/examples/exex/remote/src/codec.rs b/examples/exex/remote/src/codec.rs index 3abb511c7546..d36b60b92a5c 100644 --- a/examples/exex/remote/src/codec.rs +++ b/examples/exex/remote/src/codec.rs @@ -40,16 +40,21 @@ impl TryFrom<&reth::providers::Chain> for proto::Chain { Ok(proto::Chain { blocks: chain .blocks_iter() - .map(|block| proto::Block { - header: Some(proto::SealedHeader { - hash: block.header.hash().to_vec(), - header: Some(block.header.header().into()), - }), - body: block.transactions().map(Into::into).collect(), - ommers: block.ommers.iter().map(Into::into).collect(), - senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), + .map(|block| { + Ok(proto::Block { + header: Some(proto::SealedHeader { + hash: block.header.hash().to_vec(), + header: Some(block.header.header().into()), + }), + body: block + .transactions() + .map(TryInto::try_into) + .collect::>()?, + ommers: block.ommers.iter().map(Into::into).collect(), + senders: block.senders.iter().map(|sender| sender.to_vec()).collect(), + }) }) - .collect(), + .collect::>()?, execution_outcome: Some(proto::ExecutionOutcome { bundle: Some(proto::BundleState { state: bundle_state @@ -86,10 +91,15 @@ impl TryFrom<&reth::providers::Chain> for proto::Chain { .execution_outcome() .receipts() .iter() - .map(|block_receipts| proto::BlockReceipts { - receipts: block_receipts.iter().map(Into::into).collect(), + .map(|block_receipts| { + Ok(proto::BlockReceipts { + receipts: block_receipts + .iter() + .map(TryInto::try_into) + .collect::>()?, + }) }) - .collect(), + .collect::>()?, first_block: chain.execution_outcome().first_block, }), }) @@ -123,8 +133,10 @@ impl From<&reth::primitives::Header> for proto::Header { } } -impl From<&reth::primitives::TransactionSigned> for proto::Transaction { - fn from(transaction: &reth::primitives::TransactionSigned) -> Self { +impl TryFrom<&reth::primitives::TransactionSigned> for proto::Transaction { + type Error = eyre::Error; + + fn try_from(transaction: &reth::primitives::TransactionSigned) -> Result { let hash = transaction.hash().to_vec(); let signature = proto::Signature { r: transaction.signature.r.to_le_bytes_vec(), @@ -141,7 +153,7 @@ impl From<&reth::primitives::TransactionSigned> for proto::Transaction { value, input, }) => proto::transaction::Transaction::Legacy(proto::TransactionLegacy { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_price: gas_price.to_le_bytes().to_vec(), gas_limit: *gas_limit, @@ -159,7 +171,7 @@ impl From<&reth::primitives::TransactionSigned> for proto::Transaction { access_list, input, }) => proto::transaction::Transaction::Eip2930(proto::TransactionEip2930 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_price: gas_price.to_le_bytes().to_vec(), gas_limit: *gas_limit, @@ -179,7 +191,7 @@ impl From<&reth::primitives::TransactionSigned> for proto::Transaction { access_list, input, }) => proto::transaction::Transaction::Eip1559(proto::TransactionEip1559 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_limit: *gas_limit, max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), @@ -203,7 +215,7 @@ impl From<&reth::primitives::TransactionSigned> for proto::Transaction { max_fee_per_blob_gas, input, }) => proto::transaction::Transaction::Eip4844(proto::TransactionEip4844 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_limit: *gas_limit, max_fee_per_gas: max_fee_per_gas.to_le_bytes().to_vec(), @@ -218,9 +230,13 @@ impl From<&reth::primitives::TransactionSigned> for proto::Transaction { max_fee_per_blob_gas: max_fee_per_blob_gas.to_le_bytes().to_vec(), input: input.to_vec(), }), + #[cfg(feature = "optimism")] + reth::primitives::Transaction::Deposit(_) => { + eyre::bail!("deposit transaction not supported") + } }; - proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) } + Ok(proto::Transaction { hash, signature: Some(signature), transaction: Some(transaction) }) } } @@ -305,7 +321,7 @@ impl TryFrom<&reth::revm::primitives::Bytecode> for proto::Bytecode { }) } reth::revm::primitives::Bytecode::Eof(_) => { - return Err(eyre::eyre!("EOF bytecode not supported")) + eyre::bail!("EOF bytecode not supported"); } }; Ok(proto::Bytecode { bytecode: Some(bytecode) }) @@ -377,24 +393,36 @@ impl TryFrom<(Address, &reth::revm::db::states::reverts::AccountRevert)> for pro } } -impl From<&Option> for proto::Receipt { - fn from(receipt: &Option) -> Self { - proto::Receipt { - receipt: Some(receipt.as_ref().map_or(proto::receipt::Receipt::Empty(()), |receipt| { - proto::receipt::Receipt::NonEmpty(receipt.into()) - })), - } +impl TryFrom<&Option> for proto::Receipt { + type Error = eyre::Error; + + fn try_from(receipt: &Option) -> Result { + Ok(proto::Receipt { + receipt: Some( + receipt + .as_ref() + .map_or(eyre::Ok(proto::receipt::Receipt::Empty(())), |receipt| { + Ok(proto::receipt::Receipt::NonEmpty(receipt.try_into()?)) + })?, + ), + }) } } -impl From<&reth::primitives::Receipt> for proto::NonEmptyReceipt { - fn from(receipt: &reth::primitives::Receipt) -> Self { - proto::NonEmptyReceipt { +impl TryFrom<&reth::primitives::Receipt> for proto::NonEmptyReceipt { + type Error = eyre::Error; + + fn try_from(receipt: &reth::primitives::Receipt) -> Result { + Ok(proto::NonEmptyReceipt { tx_type: match receipt.tx_type { reth::primitives::TxType::Legacy => proto::TxType::Legacy, reth::primitives::TxType::Eip2930 => proto::TxType::Eip2930, reth::primitives::TxType::Eip1559 => proto::TxType::Eip1559, reth::primitives::TxType::Eip4844 => proto::TxType::Eip4844, + #[cfg(feature = "optimism")] + reth::primitives::TxType::Deposit => { + eyre::bail!("deposit transaction not supported") + } } as i32, success: receipt.success, cumulative_gas_used: receipt.cumulative_gas_used, @@ -409,7 +437,7 @@ impl From<&reth::primitives::Receipt> for proto::NonEmptyReceipt { }), }) .collect(), - } + }) } } @@ -470,11 +498,11 @@ impl TryFrom<&proto::Chain> for reth::providers::Chain { .reverts .iter() .map(|block_reverts| { - Ok(block_reverts + block_reverts .reverts .iter() .map(TryInto::try_into) - .collect::>()?) + .collect::>() }) .collect::>()?, ), @@ -486,11 +514,11 @@ impl TryFrom<&proto::Chain> for reth::providers::Chain { .receipts .iter() .map(|block_receipts| { - Ok(block_receipts + block_receipts .receipts .iter() .map(TryInto::try_into) - .collect::>()?) + .collect::>() }) .collect::>>()?, ), @@ -597,7 +625,7 @@ impl TryFrom<&proto::Transaction> for reth::primitives::TransactionSigned { value, input, }) => reth::primitives::Transaction::Legacy(reth::primitives::TxLegacy { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), gas_limit: *gas_limit, @@ -616,7 +644,7 @@ impl TryFrom<&proto::Transaction> for reth::primitives::TransactionSigned { access_list, input, }) => reth::primitives::Transaction::Eip2930(reth::primitives::TxEip2930 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_price: u128::from_le_bytes(gas_price.as_slice().try_into()?), gas_limit: *gas_limit, @@ -641,7 +669,7 @@ impl TryFrom<&proto::Transaction> for reth::primitives::TransactionSigned { access_list, input, }) => reth::primitives::Transaction::Eip1559(reth::primitives::TxEip1559 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_limit: *gas_limit, max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), @@ -671,7 +699,7 @@ impl TryFrom<&proto::Transaction> for reth::primitives::TransactionSigned { max_fee_per_blob_gas, input, }) => reth::primitives::Transaction::Eip4844(reth::primitives::TxEip4844 { - chain_id: chain_id.clone(), + chain_id: *chain_id, nonce: *nonce, gas_limit: *gas_limit, max_fee_per_gas: u128::from_le_bytes(max_fee_per_gas.as_slice().try_into()?), @@ -924,6 +952,10 @@ impl TryFrom<&proto::NonEmptyReceipt> for reth::primitives::Receipt { }) }) .collect::>()?, + #[cfg(feature = "optimism")] + deposit_nonce: None, + #[cfg(feature = "optimism")] + deposit_receipt_version: None, }) } } From 8c444c665fa568800e9aab8ef550f7855c0bff6a Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Wed, 19 Jun 2024 16:41:02 +0100 Subject: [PATCH 15/16] install protoc in cargo hack check --- .github/workflows/lint.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 59ca1f6da37c..c758f6945a05 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -71,6 +71,7 @@ jobs: - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true + - uses: arduino/setup-protoc@v3 - run: cargo hack check msrv: From a1960d80b94fc33e3736bd7bdbb90e212d9db918 Mon Sep 17 00:00:00 2001 From: Alexey Shekhirin Date: Mon, 24 Jun 2024 12:55:03 +0100 Subject: [PATCH 16/16] unarc broadcast sender --- examples/exex/remote/bin/exex.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/exex/remote/bin/exex.rs b/examples/exex/remote/bin/exex.rs index 6b8fcf375243..6eb1cde37915 100644 --- a/examples/exex/remote/bin/exex.rs +++ b/examples/exex/remote/bin/exex.rs @@ -13,7 +13,7 @@ use tonic::{transport::Server, Request, Response, Status}; #[derive(Debug)] struct ExExService { - notifications: Arc>, + notifications: broadcast::Sender, } #[tonic::async_trait] @@ -41,7 +41,7 @@ impl RemoteExEx for ExExService { async fn exex( mut ctx: ExExContext, - notifications: Arc>, + notifications: broadcast::Sender, ) -> eyre::Result<()> { while let Some(notification) = ctx.notifications.recv().await { if let Some(committed_chain) = notification.committed_chain() { @@ -56,7 +56,7 @@ async fn exex( fn main() -> eyre::Result<()> { reth::cli::Cli::parse_args().run(|builder, _| async move { - let notifications = Arc::new(broadcast::channel(1).0); + let notifications = broadcast::channel(1).0; let server = Server::builder() .add_service(RemoteExExServer::new(ExExService {