diff --git a/Cargo.toml b/Cargo.toml index a94a65c65..c64b0def9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,6 +153,7 @@ uninhabited_references = "warn" unused_peekable = "warn" unused_rounding = "warn" useless_let_if_seq = "warn" +use_self = "warn" # These are nursery lints which have findings. Allow them for now. Some are not # quite mature enough for use in our codebase and some we don't really want. @@ -175,7 +176,6 @@ significant_drop_tightening = "allow" string_lit_as_bytes = "allow" type_repetition_in_bounds = "allow" unnecessary_struct_initialization = "allow" -use_self = "allow" [workspace.package] version = "0.2.0-beta.7" @@ -440,4 +440,4 @@ test-fuzz = "5" revm = { git = "https://github.com/bluealloy/revm", rev = "a28a543" } revm-interpreter = { git = "https://github.com/bluealloy/revm", rev = "a28a543" } revm-precompile = { git = "https://github.com/bluealloy/revm", rev = "a28a543" } -revm-primitives = { git = "https://github.com/bluealloy/revm", rev = "a28a543" } \ No newline at end of file +revm-primitives = { git = "https://github.com/bluealloy/revm", rev = "a28a543" } diff --git a/bin/reth/src/cli/mod.rs b/bin/reth/src/cli/mod.rs index 4bf413acd..69ff733b5 100644 --- a/bin/reth/src/cli/mod.rs +++ b/bin/reth/src/cli/mod.rs @@ -86,7 +86,7 @@ impl Cli { I: IntoIterator, T: Into + Clone, { - Cli::try_parse_from(itr) + Self::try_parse_from(itr) } } diff --git a/bin/reth/src/commands/db/tui.rs b/bin/reth/src/commands/db/tui.rs index 841440a47..487ee48c6 100644 --- a/bin/reth/src/commands/db/tui.rs +++ b/bin/reth/src/commands/db/tui.rs @@ -67,19 +67,19 @@ impl Entries { /// if needed. fn set(&mut self, new_entries: Vec>) { match self { - Entries::RawValues(old_entries) => { + Self::RawValues(old_entries) => { *old_entries = new_entries.into_iter().map(|(key, value)| (key, value.into())).collect() } - Entries::Values(old_entries) => *old_entries = new_entries, + Self::Values(old_entries) => *old_entries = new_entries, } } /// Returns the length of internal [Vec]. fn len(&self) -> usize { match self { - Entries::RawValues(entries) => entries.len(), - Entries::Values(entries) => entries.len(), + Self::RawValues(entries) => entries.len(), + Self::Values(entries) => entries.len(), } } diff --git a/bin/reth/src/commands/stage/unwind.rs b/bin/reth/src/commands/stage/unwind.rs index d2ebe70db..320539280 100644 --- a/bin/reth/src/commands/stage/unwind.rs +++ b/bin/reth/src/commands/stage/unwind.rs @@ -197,13 +197,13 @@ impl Subcommands { let provider = factory.provider()?; let last = provider.last_block_number()?; let target = match self { - Subcommands::ToBlock { target } => match target { + Self::ToBlock { target } => match target { BlockHashOrNumber::Hash(hash) => provider .block_number(*hash)? .ok_or_else(|| eyre::eyre!("Block hash not found in database: {hash:?}"))?, BlockHashOrNumber::Number(num) => *num, }, - Subcommands::NumBlocks { amount } => last.saturating_sub(*amount), + Self::NumBlocks { amount } => last.saturating_sub(*amount), } + 1; if target > last { eyre::bail!("Target block number is higher than the latest block number") diff --git a/crates/blockchain-tree-api/src/error.rs b/crates/blockchain-tree-api/src/error.rs index c48a97676..784b8532e 100644 --- a/crates/blockchain-tree-api/src/error.rs +++ b/crates/blockchain-tree-api/src/error.rs @@ -81,17 +81,14 @@ impl CanonicalError { /// Returns `true` if the underlying error matches /// [BlockchainTreeError::BlockHashNotFoundInChain]. pub fn is_block_hash_not_found(&self) -> bool { - matches!( - self, - CanonicalError::BlockchainTree(BlockchainTreeError::BlockHashNotFoundInChain { .. }) - ) + matches!(self, Self::BlockchainTree(BlockchainTreeError::BlockHashNotFoundInChain { .. })) } /// Returns `Some(BlockNumber)` if the underlying error matches /// [CanonicalError::OptimisticTargetRevert]. pub fn optimistic_revert_block_number(&self) -> Option { match self { - CanonicalError::OptimisticTargetRevert(block_number) => Some(*block_number), + Self::OptimisticTargetRevert(block_number) => Some(*block_number), _ => None, } } @@ -242,25 +239,25 @@ pub enum InsertBlockErrorKind { impl InsertBlockErrorKind { /// Returns true if the error is a tree error pub fn is_tree_error(&self) -> bool { - matches!(self, InsertBlockErrorKind::Tree(_)) + matches!(self, Self::Tree(_)) } /// Returns true if the error is a consensus error pub fn is_consensus_error(&self) -> bool { - matches!(self, InsertBlockErrorKind::Consensus(_)) + matches!(self, Self::Consensus(_)) } /// Returns true if this error is a state root error pub fn is_state_root_error(&self) -> bool { // we need to get the state root errors inside of the different variant branches match self { - InsertBlockErrorKind::Execution(err) => { + Self::Execution(err) => { matches!( err, BlockExecutionError::Validation(BlockValidationError::StateRoot { .. }) ) } - InsertBlockErrorKind::Canonical(err) => { + Self::Canonical(err) => { matches!( err, CanonicalError::Validation(BlockValidationError::StateRoot { .. }) | @@ -270,7 +267,7 @@ impl InsertBlockErrorKind { ) ) } - InsertBlockErrorKind::Provider(err) => { + Self::Provider(err) => { matches!( err, ProviderError::StateRootMismatch(_) | ProviderError::UnwindStateRootMismatch(_) @@ -285,9 +282,9 @@ impl InsertBlockErrorKind { /// This is intended to be used to determine if the block should be marked as invalid. pub fn is_invalid_block(&self) -> bool { match self { - InsertBlockErrorKind::SenderRecovery | InsertBlockErrorKind::Consensus(_) => true, + Self::SenderRecovery | Self::Consensus(_) => true, // other execution errors that are considered internal errors - InsertBlockErrorKind::Execution(err) => { + Self::Execution(err) => { match err { BlockExecutionError::Validation(_) | BlockExecutionError::Consensus(_) => { // this is caused by an invalid block @@ -303,7 +300,7 @@ impl InsertBlockErrorKind { BlockExecutionError::Other(_) => false, } } - InsertBlockErrorKind::Tree(err) => { + Self::Tree(err) => { match err { BlockchainTreeError::PendingBlockIsFinalized { .. } => { // the block's number is lower than the finalized block's number @@ -317,11 +314,11 @@ impl InsertBlockErrorKind { BlockchainTreeError::GenesisBlockHasNoParent => false, } } - InsertBlockErrorKind::Provider(_) | InsertBlockErrorKind::Internal(_) => { + Self::Provider(_) | Self::Internal(_) => { // any other error, such as database errors, are considered internal errors false } - InsertBlockErrorKind::Canonical(err) => match err { + Self::Canonical(err) => match err { CanonicalError::BlockchainTree(_) | CanonicalError::CanonicalCommit(_) | CanonicalError::CanonicalRevert(_) | @@ -329,7 +326,7 @@ impl InsertBlockErrorKind { CanonicalError::Validation(_) => true, CanonicalError::Provider(_) => false, }, - InsertBlockErrorKind::BlockchainTree(_) => false, + Self::BlockchainTree(_) => false, } } @@ -337,7 +334,7 @@ impl InsertBlockErrorKind { pub fn is_block_pre_merge(&self) -> bool { matches!( self, - InsertBlockErrorKind::Execution(BlockExecutionError::Validation( + Self::Execution(BlockExecutionError::Validation( BlockValidationError::BlockPreMerge { .. } )) ) @@ -345,18 +342,18 @@ impl InsertBlockErrorKind { /// Returns true if the error is an execution error pub fn is_execution_error(&self) -> bool { - matches!(self, InsertBlockErrorKind::Execution(_)) + matches!(self, Self::Execution(_)) } /// Returns true if the error is an internal error pub fn is_internal(&self) -> bool { - matches!(self, InsertBlockErrorKind::Internal(_)) + matches!(self, Self::Internal(_)) } /// Returns the error if it is a tree error pub fn as_tree_error(&self) -> Option { match self { - InsertBlockErrorKind::Tree(err) => Some(*err), + Self::Tree(err) => Some(*err), _ => None, } } @@ -364,7 +361,7 @@ impl InsertBlockErrorKind { /// Returns the error if it is a consensus error pub fn as_consensus_error(&self) -> Option<&ConsensusError> { match self { - InsertBlockErrorKind::Consensus(err) => Some(err), + Self::Consensus(err) => Some(err), _ => None, } } @@ -372,7 +369,7 @@ impl InsertBlockErrorKind { /// Returns the error if it is an execution error pub fn as_execution_error(&self) -> Option<&BlockExecutionError> { match self { - InsertBlockErrorKind::Execution(err) => Some(err), + Self::Execution(err) => Some(err), _ => None, } } diff --git a/crates/blockchain-tree-api/src/lib.rs b/crates/blockchain-tree-api/src/lib.rs index 19fa256eb..ce8bc1beb 100644 --- a/crates/blockchain-tree-api/src/lib.rs +++ b/crates/blockchain-tree-api/src/lib.rs @@ -140,17 +140,17 @@ pub enum BlockValidationKind { impl BlockValidationKind { /// Returns true if the state root should be validated if possible. pub fn is_exhaustive(&self) -> bool { - matches!(self, BlockValidationKind::Exhaustive) + matches!(self, Self::Exhaustive) } } impl std::fmt::Display for BlockValidationKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - BlockValidationKind::Exhaustive => { + Self::Exhaustive => { write!(f, "Exhaustive") } - BlockValidationKind::SkipStateRootValidation => { + Self::SkipStateRootValidation => { write!(f, "SkipStateRootValidation") } } @@ -179,22 +179,22 @@ impl CanonicalOutcome { /// Returns the header of the block that was made canonical. pub fn header(&self) -> &SealedHeader { match self { - CanonicalOutcome::AlreadyCanonical { header, .. } => header, - CanonicalOutcome::Committed { head } => head, + Self::AlreadyCanonical { header, .. } => header, + Self::Committed { head } => head, } } /// Consumes the outcome and returns the header of the block that was made canonical. pub fn into_header(self) -> SealedHeader { match self { - CanonicalOutcome::AlreadyCanonical { header, .. } => header, - CanonicalOutcome::Committed { head } => head, + Self::AlreadyCanonical { header, .. } => header, + Self::Committed { head } => head, } } /// Returns true if the block was already canonical. pub fn is_already_canonical(&self) -> bool { - matches!(self, CanonicalOutcome::AlreadyCanonical { .. }) + matches!(self, Self::AlreadyCanonical { .. }) } } @@ -241,7 +241,7 @@ impl BlockAttachment { /// Returns `true` if the block is canonical or a descendant of the canonical head. #[inline] pub const fn is_canonical(&self) -> bool { - matches!(self, BlockAttachment::Canonical) + matches!(self, Self::Canonical) } } diff --git a/crates/blockchain-tree/src/metrics.rs b/crates/blockchain-tree/src/metrics.rs index 71a4475c5..403b3014c 100644 --- a/crates/blockchain-tree/src/metrics.rs +++ b/crates/blockchain-tree/src/metrics.rs @@ -92,21 +92,17 @@ pub(crate) enum MakeCanonicalAction { impl MakeCanonicalAction { fn as_str(&self) -> &'static str { match self { - MakeCanonicalAction::CloneOldBlocks => "clone old blocks", - MakeCanonicalAction::FindCanonicalHeader => "find canonical header", - MakeCanonicalAction::SplitChain => "split chain", - MakeCanonicalAction::SplitChainForks => "split chain forks", - MakeCanonicalAction::MergeAllChains => "merge all chains", - MakeCanonicalAction::UpdateCanonicalIndex => "update canonical index", - MakeCanonicalAction::RetrieveStateTrieUpdates => "retrieve state trie updates", - MakeCanonicalAction::CommitCanonicalChainToDatabase => { - "commit canonical chain to database" - } - MakeCanonicalAction::RevertCanonicalChainFromDatabase => { - "revert canonical chain from database" - } - MakeCanonicalAction::InsertOldCanonicalChain => "insert old canonical chain", - MakeCanonicalAction::ClearTrieUpdatesForOtherChilds => { + Self::CloneOldBlocks => "clone old blocks", + Self::FindCanonicalHeader => "find canonical header", + Self::SplitChain => "split chain", + Self::SplitChainForks => "split chain forks", + Self::MergeAllChains => "merge all chains", + Self::UpdateCanonicalIndex => "update canonical index", + Self::RetrieveStateTrieUpdates => "retrieve state trie updates", + Self::CommitCanonicalChainToDatabase => "commit canonical chain to database", + Self::RevertCanonicalChainFromDatabase => "revert canonical chain from database", + Self::InsertOldCanonicalChain => "insert old canonical chain", + Self::ClearTrieUpdatesForOtherChilds => { "clear trie updates of other childs chains after fork choice update" } } diff --git a/crates/blockchain-tree/src/state.rs b/crates/blockchain-tree/src/state.rs index f02890654..86501a6d1 100644 --- a/crates/blockchain-tree/src/state.rs +++ b/crates/blockchain-tree/src/state.rs @@ -124,6 +124,6 @@ impl From for u64 { #[cfg(test)] impl From for BlockchainId { fn from(value: u64) -> Self { - BlockchainId(value) + Self(value) } } diff --git a/crates/consensus/auto-seal/src/mode.rs b/crates/consensus/auto-seal/src/mode.rs index b124010e6..2ff918af6 100644 --- a/crates/consensus/auto-seal/src/mode.rs +++ b/crates/consensus/auto-seal/src/mode.rs @@ -33,7 +33,7 @@ impl MiningMode { /// Creates a new instant mining mode that listens for new transactions and tries to build /// non-empty blocks as soon as transactions arrive. pub fn instant(max_transactions: usize, listener: Receiver) -> Self { - MiningMode::Auto(ReadyTransactionMiner { + Self::Auto(ReadyTransactionMiner { max_transactions, has_pending_txs: None, rx: ReceiverStream::new(listener).fuse(), @@ -42,7 +42,7 @@ impl MiningMode { /// Creates a new interval miner that builds a block ever `duration`. pub fn interval(duration: Duration) -> Self { - MiningMode::FixedBlockTime(FixedBlockTimeMiner::new(duration)) + Self::FixedBlockTime(FixedBlockTimeMiner::new(duration)) } /// polls the Pool and returns those transactions that should be put in a block, if any. @@ -55,9 +55,9 @@ impl MiningMode { Pool: TransactionPool, { match self { - MiningMode::None => Poll::Pending, - MiningMode::Auto(miner) => miner.poll(pool, cx), - MiningMode::FixedBlockTime(miner) => miner.poll(pool, cx), + Self::None => Poll::Pending, + Self::Auto(miner) => miner.poll(pool, cx), + Self::FixedBlockTime(miner) => miner.poll(pool, cx), } } } @@ -65,9 +65,9 @@ impl MiningMode { impl fmt::Display for MiningMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let kind = match self { - MiningMode::None => "None", - MiningMode::Auto(_) => "Auto", - MiningMode::FixedBlockTime(_) => "FixedBlockTime", + Self::None => "None", + Self::Auto(_) => "Auto", + Self::FixedBlockTime(_) => "FixedBlockTime", }; write!(f, "{kind}") } diff --git a/crates/consensus/beacon/src/engine/forkchoice.rs b/crates/consensus/beacon/src/engine/forkchoice.rs index 461881c64..2eb115b1a 100644 --- a/crates/consensus/beacon/src/engine/forkchoice.rs +++ b/crates/consensus/beacon/src/engine/forkchoice.rs @@ -107,15 +107,15 @@ pub enum ForkchoiceStatus { impl ForkchoiceStatus { pub(crate) fn is_valid(&self) -> bool { - matches!(self, ForkchoiceStatus::Valid) + matches!(self, Self::Valid) } pub(crate) fn is_invalid(&self) -> bool { - matches!(self, ForkchoiceStatus::Invalid) + matches!(self, Self::Invalid) } pub(crate) fn is_syncing(&self) -> bool { - matches!(self, ForkchoiceStatus::Syncing) + matches!(self, Self::Syncing) } /// Converts the general purpose [PayloadStatusEnum] into a [ForkchoiceStatus]. @@ -123,17 +123,17 @@ impl ForkchoiceStatus { match status { PayloadStatusEnum::Valid | PayloadStatusEnum::Accepted => { // `Accepted` is only returned on `newPayload`. It would be a valid state here. - ForkchoiceStatus::Valid + Self::Valid } - PayloadStatusEnum::Invalid { .. } => ForkchoiceStatus::Invalid, - PayloadStatusEnum::Syncing => ForkchoiceStatus::Syncing, + PayloadStatusEnum::Invalid { .. } => Self::Invalid, + PayloadStatusEnum::Syncing => Self::Syncing, } } } impl From for ForkchoiceStatus { fn from(status: PayloadStatusEnum) -> Self { - ForkchoiceStatus::from_payload_status(&status) + Self::from_payload_status(&status) } } @@ -149,11 +149,11 @@ impl ForkchoiceStateHash { /// Tries to find a matching hash in the given [ForkchoiceState]. pub(crate) fn find(state: &ForkchoiceState, hash: B256) -> Option { if state.head_block_hash == hash { - Some(ForkchoiceStateHash::Head(hash)) + Some(Self::Head(hash)) } else if state.safe_block_hash == hash { - Some(ForkchoiceStateHash::Safe(hash)) + Some(Self::Safe(hash)) } else if state.finalized_block_hash == hash { - Some(ForkchoiceStateHash::Finalized(hash)) + Some(Self::Finalized(hash)) } else { None } @@ -161,16 +161,14 @@ impl ForkchoiceStateHash { /// Returns true if this is the head hash of the [ForkchoiceState] pub(crate) fn is_head(&self) -> bool { - matches!(self, ForkchoiceStateHash::Head(_)) + matches!(self, Self::Head(_)) } } impl AsRef for ForkchoiceStateHash { fn as_ref(&self) -> &B256 { match self { - ForkchoiceStateHash::Head(h) | - ForkchoiceStateHash::Safe(h) | - ForkchoiceStateHash::Finalized(h) => h, + Self::Head(h) | Self::Safe(h) | Self::Finalized(h) => h, } } } diff --git a/crates/consensus/beacon/src/engine/hooks/prune.rs b/crates/consensus/beacon/src/engine/hooks/prune.rs index e6b5306e3..b70bd6d18 100644 --- a/crates/consensus/beacon/src/engine/hooks/prune.rs +++ b/crates/consensus/beacon/src/engine/hooks/prune.rs @@ -167,7 +167,7 @@ impl From for EngineHookError { fn from(err: PrunerError) -> Self { match err { PrunerError::PruneSegment(_) | PrunerError::InconsistentData(_) => { - EngineHookError::Internal(Box::new(err)) + Self::Internal(Box::new(err)) } PrunerError::Database(err) => RethError::Database(err).into(), PrunerError::Provider(err) => RethError::Provider(err).into(), diff --git a/crates/consensus/beacon/src/engine/sync.rs b/crates/consensus/beacon/src/engine/sync.rs index 810e3e748..730b0a4d0 100644 --- a/crates/consensus/beacon/src/engine/sync.rs +++ b/crates/consensus/beacon/src/engine/sync.rs @@ -419,7 +419,7 @@ enum PipelineState { impl PipelineState { /// Returns `true` if the state matches idle. fn is_idle(&self) -> bool { - matches!(self, PipelineState::Idle(_)) + matches!(self, Self::Idle(_)) } } diff --git a/crates/consensus/consensus/src/lib.rs b/crates/consensus/consensus/src/lib.rs index e90e73e93..a84808800 100644 --- a/crates/consensus/consensus/src/lib.rs +++ b/crates/consensus/consensus/src/lib.rs @@ -328,7 +328,7 @@ pub enum ConsensusError { impl ConsensusError { /// Returns `true` if the error is a state root error. pub fn is_state_root_error(&self) -> bool { - matches!(self, ConsensusError::BodyStateRootDiff(_)) + matches!(self, Self::BodyStateRootDiff(_)) } } diff --git a/crates/errors/src/error.rs b/crates/errors/src/error.rs index 4017be351..e74d58275 100644 --- a/crates/errors/src/error.rs +++ b/crates/errors/src/error.rs @@ -46,24 +46,24 @@ impl RethError { where E: std::error::Error + Send + Sync + 'static, { - RethError::Other(Box::new(error)) + Self::Other(Box::new(error)) } /// Create a new `RethError` from a given message. pub fn msg(msg: impl Display) -> Self { - RethError::Other(msg.to_string().into()) + Self::Other(msg.to_string().into()) } } impl From for RethError { fn from(error: BlockchainTreeError) -> Self { - RethError::Canonical(CanonicalError::BlockchainTree(error)) + Self::Canonical(CanonicalError::BlockchainTree(error)) } } impl From for RethError { fn from(err: FsPathError) -> Self { - RethError::other(err) + Self::other(err) } } diff --git a/crates/ethereum-forks/src/forkid.rs b/crates/ethereum-forks/src/forkid.rs index b5d031c5e..cf28cec88 100644 --- a/crates/ethereum-forks/src/forkid.rs +++ b/crates/ethereum-forks/src/forkid.rs @@ -87,9 +87,8 @@ impl PartialOrd for ForkFilterKey { impl Ord for ForkFilterKey { fn cmp(&self, other: &Self) -> Ordering { match (self, other) { - (ForkFilterKey::Block(a), ForkFilterKey::Block(b)) | - (ForkFilterKey::Time(a), ForkFilterKey::Time(b)) => a.cmp(b), - (ForkFilterKey::Block(_), ForkFilterKey::Time(_)) => Ordering::Less, + (Self::Block(a), Self::Block(b)) | (Self::Time(a), Self::Time(b)) => a.cmp(b), + (Self::Block(_), Self::Time(_)) => Ordering::Less, _ => Ordering::Greater, } } diff --git a/crates/ethereum-forks/src/hardfork.rs b/crates/ethereum-forks/src/hardfork.rs index 41d1f1302..11e9cac45 100644 --- a/crates/ethereum-forks/src/hardfork.rs +++ b/crates/ethereum-forks/src/hardfork.rs @@ -81,7 +81,7 @@ pub enum Hardfork { impl Hardfork { /// Retrieves the consensus type for the specified hardfork. pub fn consensus_type(&self) -> ConsensusType { - if *self >= Hardfork::Paris { + if *self >= Self::Paris { ConsensusType::ProofOfStake } else { ConsensusType::ProofOfWork @@ -127,23 +127,23 @@ impl Hardfork { pub fn mainnet_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(1150000), - Hardfork::Dao => Some(1920000), - Hardfork::Tangerine => Some(2463000), - Hardfork::SpuriousDragon => Some(2675000), - Hardfork::Byzantium => Some(4370000), - Hardfork::Constantinople => Some(7280000), - Hardfork::Petersburg => Some(7280000), - Hardfork::Istanbul => Some(9069000), - Hardfork::MuirGlacier => Some(9200000), - Hardfork::Berlin => Some(12244000), - Hardfork::London => Some(12965000), - Hardfork::ArrowGlacier => Some(13773000), - Hardfork::GrayGlacier => Some(15050000), - Hardfork::Paris => Some(15537394), - Hardfork::Shanghai => Some(17034870), - Hardfork::Cancun => Some(19426587), + Self::Frontier => Some(0), + Self::Homestead => Some(1150000), + Self::Dao => Some(1920000), + Self::Tangerine => Some(2463000), + Self::SpuriousDragon => Some(2675000), + Self::Byzantium => Some(4370000), + Self::Constantinople => Some(7280000), + Self::Petersburg => Some(7280000), + Self::Istanbul => Some(9069000), + Self::MuirGlacier => Some(9200000), + Self::Berlin => Some(12244000), + Self::London => Some(12965000), + Self::ArrowGlacier => Some(13773000), + Self::GrayGlacier => Some(15050000), + Self::Paris => Some(15537394), + Self::Shanghai => Some(17034870), + Self::Cancun => Some(19426587), _ => None, } @@ -153,23 +153,23 @@ impl Hardfork { pub fn sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Paris => Some(1735371), - Hardfork::Shanghai => Some(2990908), - Hardfork::Cancun => Some(5187023), - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(0), - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), + Self::Paris => Some(1735371), + Self::Shanghai => Some(2990908), + Self::Cancun => Some(5187023), + Self::Frontier => Some(0), + Self::Homestead => Some(0), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), _ => None, } } @@ -178,24 +178,24 @@ impl Hardfork { pub fn arbitrum_sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(0), - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), - Hardfork::Paris => Some(0), - Hardfork::Shanghai => Some(10653737), + Self::Frontier => Some(0), + Self::Homestead => Some(0), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), + Self::Paris => Some(0), + Self::Shanghai => Some(10653737), // Hardfork::ArbOS11 => Some(10653737), - Hardfork::Cancun => Some(18683405), + Self::Cancun => Some(18683405), // Hardfork::ArbOS20Atlas => Some(18683405), _ => None, } @@ -205,24 +205,24 @@ impl Hardfork { pub fn arbitrum_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(0), - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), - Hardfork::Paris => Some(0), - Hardfork::Shanghai => Some(184097479), + Self::Frontier => Some(0), + Self::Homestead => Some(0), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), + Self::Paris => Some(0), + Self::Shanghai => Some(184097479), // Hardfork::ArbOS11 => Some(184097479), - Hardfork::Cancun => Some(190301729), + Self::Cancun => Some(190301729), // Hardfork::ArbOS20Atlas => Some(190301729), _ => None, } @@ -233,27 +233,27 @@ impl Hardfork { pub fn base_sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(0), - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), - Hardfork::Paris => Some(0), - Hardfork::Bedrock => Some(0), - Hardfork::Regolith => Some(0), - Hardfork::Shanghai => Some(2106456), - Hardfork::Canyon => Some(2106456), - Hardfork::Cancun => Some(6383256), - Hardfork::Ecotone => Some(6383256), + Self::Frontier => Some(0), + Self::Homestead => Some(0), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), + Self::Paris => Some(0), + Self::Bedrock => Some(0), + Self::Regolith => Some(0), + Self::Shanghai => Some(2106456), + Self::Canyon => Some(2106456), + Self::Cancun => Some(6383256), + Self::Ecotone => Some(6383256), _ => None, } } @@ -263,27 +263,27 @@ impl Hardfork { pub fn base_mainnet_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(0), - Hardfork::Homestead => Some(0), - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), - Hardfork::Paris => Some(0), - Hardfork::Bedrock => Some(0), - Hardfork::Regolith => Some(0), - Hardfork::Shanghai => Some(9101527), - Hardfork::Canyon => Some(9101527), - Hardfork::Cancun => Some(11188936), - Hardfork::Ecotone => Some(11188936), + Self::Frontier => Some(0), + Self::Homestead => Some(0), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), + Self::Paris => Some(0), + Self::Bedrock => Some(0), + Self::Regolith => Some(0), + Self::Shanghai => Some(9101527), + Self::Canyon => Some(9101527), + Self::Cancun => Some(11188936), + Self::Ecotone => Some(11188936), _ => None, } } @@ -292,21 +292,21 @@ impl Hardfork { fn holesky_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Dao => Some(0), - Hardfork::Tangerine => Some(0), - Hardfork::SpuriousDragon => Some(0), - Hardfork::Byzantium => Some(0), - Hardfork::Constantinople => Some(0), - Hardfork::Petersburg => Some(0), - Hardfork::Istanbul => Some(0), - Hardfork::MuirGlacier => Some(0), - Hardfork::Berlin => Some(0), - Hardfork::London => Some(0), - Hardfork::ArrowGlacier => Some(0), - Hardfork::GrayGlacier => Some(0), - Hardfork::Paris => Some(0), - Hardfork::Shanghai => Some(6698), - Hardfork::Cancun => Some(894733), + Self::Dao => Some(0), + Self::Tangerine => Some(0), + Self::SpuriousDragon => Some(0), + Self::Byzantium => Some(0), + Self::Constantinople => Some(0), + Self::Petersburg => Some(0), + Self::Istanbul => Some(0), + Self::MuirGlacier => Some(0), + Self::Berlin => Some(0), + Self::London => Some(0), + Self::ArrowGlacier => Some(0), + Self::GrayGlacier => Some(0), + Self::Paris => Some(0), + Self::Shanghai => Some(6698), + Self::Cancun => Some(894733), _ => None, } } @@ -339,23 +339,23 @@ impl Hardfork { pub fn mainnet_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1438226773), - Hardfork::Homestead => Some(1457938193), - Hardfork::Dao => Some(1468977640), - Hardfork::Tangerine => Some(1476753571), - Hardfork::SpuriousDragon => Some(1479788144), - Hardfork::Byzantium => Some(1508131331), - Hardfork::Constantinople => Some(1551340324), - Hardfork::Petersburg => Some(1551340324), - Hardfork::Istanbul => Some(1575807909), - Hardfork::MuirGlacier => Some(1577953849), - Hardfork::Berlin => Some(1618481223), - Hardfork::London => Some(1628166822), - Hardfork::ArrowGlacier => Some(1639036523), - Hardfork::GrayGlacier => Some(1656586444), - Hardfork::Paris => Some(1663224162), - Hardfork::Shanghai => Some(1681338455), - Hardfork::Cancun => Some(1710338135), + Self::Frontier => Some(1438226773), + Self::Homestead => Some(1457938193), + Self::Dao => Some(1468977640), + Self::Tangerine => Some(1476753571), + Self::SpuriousDragon => Some(1479788144), + Self::Byzantium => Some(1508131331), + Self::Constantinople => Some(1551340324), + Self::Petersburg => Some(1551340324), + Self::Istanbul => Some(1575807909), + Self::MuirGlacier => Some(1577953849), + Self::Berlin => Some(1618481223), + Self::London => Some(1628166822), + Self::ArrowGlacier => Some(1639036523), + Self::GrayGlacier => Some(1656586444), + Self::Paris => Some(1663224162), + Self::Shanghai => Some(1681338455), + Self::Cancun => Some(1710338135), // upcoming hardforks _ => None, @@ -366,23 +366,23 @@ impl Hardfork { pub fn sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1633267481), - Hardfork::Homestead => Some(1633267481), - Hardfork::Dao => Some(1633267481), - Hardfork::Tangerine => Some(1633267481), - Hardfork::SpuriousDragon => Some(1633267481), - Hardfork::Byzantium => Some(1633267481), - Hardfork::Constantinople => Some(1633267481), - Hardfork::Petersburg => Some(1633267481), - Hardfork::Istanbul => Some(1633267481), - Hardfork::MuirGlacier => Some(1633267481), - Hardfork::Berlin => Some(1633267481), - Hardfork::London => Some(1633267481), - Hardfork::ArrowGlacier => Some(1633267481), - Hardfork::GrayGlacier => Some(1633267481), - Hardfork::Paris => Some(1633267481), - Hardfork::Shanghai => Some(1677557088), - Hardfork::Cancun => Some(1706655072), + Self::Frontier => Some(1633267481), + Self::Homestead => Some(1633267481), + Self::Dao => Some(1633267481), + Self::Tangerine => Some(1633267481), + Self::SpuriousDragon => Some(1633267481), + Self::Byzantium => Some(1633267481), + Self::Constantinople => Some(1633267481), + Self::Petersburg => Some(1633267481), + Self::Istanbul => Some(1633267481), + Self::MuirGlacier => Some(1633267481), + Self::Berlin => Some(1633267481), + Self::London => Some(1633267481), + Self::ArrowGlacier => Some(1633267481), + Self::GrayGlacier => Some(1633267481), + Self::Paris => Some(1633267481), + Self::Shanghai => Some(1677557088), + Self::Cancun => Some(1706655072), _ => None, } } @@ -391,23 +391,23 @@ impl Hardfork { pub fn holesky_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Shanghai => Some(1696000704), - Hardfork::Cancun => Some(1707305664), - Hardfork::Frontier => Some(1695902100), - Hardfork::Homestead => Some(1695902100), - Hardfork::Dao => Some(1695902100), - Hardfork::Tangerine => Some(1695902100), - Hardfork::SpuriousDragon => Some(1695902100), - Hardfork::Byzantium => Some(1695902100), - Hardfork::Constantinople => Some(1695902100), - Hardfork::Petersburg => Some(1695902100), - Hardfork::Istanbul => Some(1695902100), - Hardfork::MuirGlacier => Some(1695902100), - Hardfork::Berlin => Some(1695902100), - Hardfork::London => Some(1695902100), - Hardfork::ArrowGlacier => Some(1695902100), - Hardfork::GrayGlacier => Some(1695902100), - Hardfork::Paris => Some(1695902100), + Self::Shanghai => Some(1696000704), + Self::Cancun => Some(1707305664), + Self::Frontier => Some(1695902100), + Self::Homestead => Some(1695902100), + Self::Dao => Some(1695902100), + Self::Tangerine => Some(1695902100), + Self::SpuriousDragon => Some(1695902100), + Self::Byzantium => Some(1695902100), + Self::Constantinople => Some(1695902100), + Self::Petersburg => Some(1695902100), + Self::Istanbul => Some(1695902100), + Self::MuirGlacier => Some(1695902100), + Self::Berlin => Some(1695902100), + Self::London => Some(1695902100), + Self::ArrowGlacier => Some(1695902100), + Self::GrayGlacier => Some(1695902100), + Self::Paris => Some(1695902100), _ => None, } } @@ -417,24 +417,24 @@ impl Hardfork { pub fn arbitrum_sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1692726996), - Hardfork::Homestead => Some(1692726996), - Hardfork::Dao => Some(1692726996), - Hardfork::Tangerine => Some(1692726996), - Hardfork::SpuriousDragon => Some(1692726996), - Hardfork::Byzantium => Some(1692726996), - Hardfork::Constantinople => Some(1692726996), - Hardfork::Petersburg => Some(1692726996), - Hardfork::Istanbul => Some(1692726996), - Hardfork::MuirGlacier => Some(1692726996), - Hardfork::Berlin => Some(1692726996), - Hardfork::London => Some(1692726996), - Hardfork::ArrowGlacier => Some(1692726996), - Hardfork::GrayGlacier => Some(1692726996), - Hardfork::Paris => Some(1692726996), - Hardfork::Shanghai => Some(1706634000), + Self::Frontier => Some(1692726996), + Self::Homestead => Some(1692726996), + Self::Dao => Some(1692726996), + Self::Tangerine => Some(1692726996), + Self::SpuriousDragon => Some(1692726996), + Self::Byzantium => Some(1692726996), + Self::Constantinople => Some(1692726996), + Self::Petersburg => Some(1692726996), + Self::Istanbul => Some(1692726996), + Self::MuirGlacier => Some(1692726996), + Self::Berlin => Some(1692726996), + Self::London => Some(1692726996), + Self::ArrowGlacier => Some(1692726996), + Self::GrayGlacier => Some(1692726996), + Self::Paris => Some(1692726996), + Self::Shanghai => Some(1706634000), // Hardfork::ArbOS11 => Some(1706634000), - Hardfork::Cancun => Some(1709229600), + Self::Cancun => Some(1709229600), // Hardfork::ArbOS20Atlas => Some(1709229600), _ => None, } @@ -444,24 +444,24 @@ impl Hardfork { pub fn arbitrum_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1622240000), - Hardfork::Homestead => Some(1622240000), - Hardfork::Dao => Some(1622240000), - Hardfork::Tangerine => Some(1622240000), - Hardfork::SpuriousDragon => Some(1622240000), - Hardfork::Byzantium => Some(1622240000), - Hardfork::Constantinople => Some(1622240000), - Hardfork::Petersburg => Some(1622240000), - Hardfork::Istanbul => Some(1622240000), - Hardfork::MuirGlacier => Some(1622240000), - Hardfork::Berlin => Some(1622240000), - Hardfork::London => Some(1622240000), - Hardfork::ArrowGlacier => Some(1622240000), - Hardfork::GrayGlacier => Some(1622240000), - Hardfork::Paris => Some(1622240000), - Hardfork::Shanghai => Some(1708804873), + Self::Frontier => Some(1622240000), + Self::Homestead => Some(1622240000), + Self::Dao => Some(1622240000), + Self::Tangerine => Some(1622240000), + Self::SpuriousDragon => Some(1622240000), + Self::Byzantium => Some(1622240000), + Self::Constantinople => Some(1622240000), + Self::Petersburg => Some(1622240000), + Self::Istanbul => Some(1622240000), + Self::MuirGlacier => Some(1622240000), + Self::Berlin => Some(1622240000), + Self::London => Some(1622240000), + Self::ArrowGlacier => Some(1622240000), + Self::GrayGlacier => Some(1622240000), + Self::Paris => Some(1622240000), + Self::Shanghai => Some(1708804873), // Hardfork::ArbOS11 => Some(1708804873), - Hardfork::Cancun => Some(1710424089), + Self::Cancun => Some(1710424089), // Hardfork::ArbOS20Atlas => Some(1710424089), _ => None, } @@ -472,27 +472,27 @@ impl Hardfork { pub fn base_sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1695768288), - Hardfork::Homestead => Some(1695768288), - Hardfork::Dao => Some(1695768288), - Hardfork::Tangerine => Some(1695768288), - Hardfork::SpuriousDragon => Some(1695768288), - Hardfork::Byzantium => Some(1695768288), - Hardfork::Constantinople => Some(1695768288), - Hardfork::Petersburg => Some(1695768288), - Hardfork::Istanbul => Some(1695768288), - Hardfork::MuirGlacier => Some(1695768288), - Hardfork::Berlin => Some(1695768288), - Hardfork::London => Some(1695768288), - Hardfork::ArrowGlacier => Some(1695768288), - Hardfork::GrayGlacier => Some(1695768288), - Hardfork::Paris => Some(1695768288), - Hardfork::Bedrock => Some(1695768288), - Hardfork::Regolith => Some(1695768288), - Hardfork::Shanghai => Some(1699981200), - Hardfork::Canyon => Some(1699981200), - Hardfork::Cancun => Some(1708534800), - Hardfork::Ecotone => Some(1708534800), + Self::Frontier => Some(1695768288), + Self::Homestead => Some(1695768288), + Self::Dao => Some(1695768288), + Self::Tangerine => Some(1695768288), + Self::SpuriousDragon => Some(1695768288), + Self::Byzantium => Some(1695768288), + Self::Constantinople => Some(1695768288), + Self::Petersburg => Some(1695768288), + Self::Istanbul => Some(1695768288), + Self::MuirGlacier => Some(1695768288), + Self::Berlin => Some(1695768288), + Self::London => Some(1695768288), + Self::ArrowGlacier => Some(1695768288), + Self::GrayGlacier => Some(1695768288), + Self::Paris => Some(1695768288), + Self::Bedrock => Some(1695768288), + Self::Regolith => Some(1695768288), + Self::Shanghai => Some(1699981200), + Self::Canyon => Some(1699981200), + Self::Cancun => Some(1708534800), + Self::Ecotone => Some(1708534800), _ => None, } } @@ -502,27 +502,27 @@ impl Hardfork { pub fn base_mainnet_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { - Hardfork::Frontier => Some(1686789347), - Hardfork::Homestead => Some(1686789347), - Hardfork::Dao => Some(1686789347), - Hardfork::Tangerine => Some(1686789347), - Hardfork::SpuriousDragon => Some(1686789347), - Hardfork::Byzantium => Some(1686789347), - Hardfork::Constantinople => Some(1686789347), - Hardfork::Petersburg => Some(1686789347), - Hardfork::Istanbul => Some(1686789347), - Hardfork::MuirGlacier => Some(1686789347), - Hardfork::Berlin => Some(1686789347), - Hardfork::London => Some(1686789347), - Hardfork::ArrowGlacier => Some(1686789347), - Hardfork::GrayGlacier => Some(1686789347), - Hardfork::Paris => Some(1686789347), - Hardfork::Bedrock => Some(1686789347), - Hardfork::Regolith => Some(1686789347), - Hardfork::Shanghai => Some(1704992401), - Hardfork::Canyon => Some(1704992401), - Hardfork::Cancun => Some(1710374401), - Hardfork::Ecotone => Some(1710374401), + Self::Frontier => Some(1686789347), + Self::Homestead => Some(1686789347), + Self::Dao => Some(1686789347), + Self::Tangerine => Some(1686789347), + Self::SpuriousDragon => Some(1686789347), + Self::Byzantium => Some(1686789347), + Self::Constantinople => Some(1686789347), + Self::Petersburg => Some(1686789347), + Self::Istanbul => Some(1686789347), + Self::MuirGlacier => Some(1686789347), + Self::Berlin => Some(1686789347), + Self::London => Some(1686789347), + Self::ArrowGlacier => Some(1686789347), + Self::GrayGlacier => Some(1686789347), + Self::Paris => Some(1686789347), + Self::Bedrock => Some(1686789347), + Self::Regolith => Some(1686789347), + Self::Shanghai => Some(1704992401), + Self::Canyon => Some(1704992401), + Self::Cancun => Some(1710374401), + Self::Ecotone => Some(1710374401), _ => None, } } @@ -533,32 +533,32 @@ impl FromStr for Hardfork { fn from_str(s: &str) -> Result { Ok(match s.to_lowercase().as_str() { - "frontier" => Hardfork::Frontier, - "homestead" => Hardfork::Homestead, - "dao" => Hardfork::Dao, - "tangerine" => Hardfork::Tangerine, - "spuriousdragon" => Hardfork::SpuriousDragon, - "byzantium" => Hardfork::Byzantium, - "constantinople" => Hardfork::Constantinople, - "petersburg" => Hardfork::Petersburg, - "istanbul" => Hardfork::Istanbul, - "muirglacier" => Hardfork::MuirGlacier, - "berlin" => Hardfork::Berlin, - "london" => Hardfork::London, - "arrowglacier" => Hardfork::ArrowGlacier, - "grayglacier" => Hardfork::GrayGlacier, - "paris" => Hardfork::Paris, - "shanghai" => Hardfork::Shanghai, - "cancun" => Hardfork::Cancun, + "frontier" => Self::Frontier, + "homestead" => Self::Homestead, + "dao" => Self::Dao, + "tangerine" => Self::Tangerine, + "spuriousdragon" => Self::SpuriousDragon, + "byzantium" => Self::Byzantium, + "constantinople" => Self::Constantinople, + "petersburg" => Self::Petersburg, + "istanbul" => Self::Istanbul, + "muirglacier" => Self::MuirGlacier, + "berlin" => Self::Berlin, + "london" => Self::London, + "arrowglacier" => Self::ArrowGlacier, + "grayglacier" => Self::GrayGlacier, + "paris" => Self::Paris, + "shanghai" => Self::Shanghai, + "cancun" => Self::Cancun, #[cfg(feature = "optimism")] - "bedrock" => Hardfork::Bedrock, + "bedrock" => Self::Bedrock, #[cfg(feature = "optimism")] - "regolith" => Hardfork::Regolith, + "regolith" => Self::Regolith, #[cfg(feature = "optimism")] - "canyon" => Hardfork::Canyon, + "canyon" => Self::Canyon, #[cfg(feature = "optimism")] - "ecotone" => Hardfork::Ecotone, - "prague" => Hardfork::Prague, + "ecotone" => Self::Ecotone, + "prague" => Self::Prague, // "arbos11" => Hardfork::ArbOS11, // "arbos20atlas" => Hardfork::ArbOS20Atlas, _ => return Err(format!("Unknown hardfork: {s}")), diff --git a/crates/ethereum/engine-primitives/src/payload.rs b/crates/ethereum/engine-primitives/src/payload.rs index 37261d995..4910412b5 100644 --- a/crates/ethereum/engine-primitives/src/payload.rs +++ b/crates/ethereum/engine-primitives/src/payload.rs @@ -101,10 +101,7 @@ impl From for ExecutionPayloadEnvelopeV2 { fn from(value: EthBuiltPayload) -> Self { let EthBuiltPayload { block, fees, .. } = value; - ExecutionPayloadEnvelopeV2 { - block_value: fees, - execution_payload: convert_block_to_payload_field_v2(block), - } + Self { block_value: fees, execution_payload: convert_block_to_payload_field_v2(block) } } } @@ -112,7 +109,7 @@ impl From for ExecutionPayloadEnvelopeV3 { fn from(value: EthBuiltPayload) -> Self { let EthBuiltPayload { block, fees, sidecars, .. } = value; - ExecutionPayloadEnvelopeV3 { + Self { execution_payload: block_to_payload_v3(block).0, block_value: fees, // From the engine API spec: @@ -133,7 +130,7 @@ impl From for ExecutionPayloadEnvelopeV4 { fn from(value: EthBuiltPayload) -> Self { let EthBuiltPayload { block, fees, sidecars, .. } = value; - ExecutionPayloadEnvelopeV4 { + Self { execution_payload: block_to_payload_v4(block), block_value: fees, // From the engine API spec: diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index 8b5240719..c6b441d66 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -240,7 +240,7 @@ impl Chain { /// Merge two chains by appending the given chain into the current one. /// /// The state of accounts for this chain is set to the state of the newest chain. - pub fn append_chain(&mut self, other: Chain) -> Result<(), BlockExecutionError> { + pub fn append_chain(&mut self, other: Self) -> Result<(), BlockExecutionError> { let chain_tip = self.tip(); let other_fork_block = other.fork_block(); if chain_tip.hash() != other_fork_block.hash { @@ -315,12 +315,12 @@ impl Chain { // TODO: Currently, trie updates are reset on chain split. // Add tests ensuring that it is valid to leave updates in the pending chain. ChainSplit::Split { - canonical: Chain { + canonical: Self { state: canonical_state.expect("split in range"), blocks: self.blocks, trie_updates: None, }, - pending: Chain { + pending: Self { state: pending_state, blocks: higher_number_blocks, trie_updates: None, diff --git a/crates/evm/src/either.rs b/crates/evm/src/either.rs index 7d8320c31..695da5d28 100644 --- a/crates/evm/src/either.rs +++ b/crates/evm/src/either.rs @@ -26,8 +26,8 @@ where DB: Database, { match self { - Either::Left(a) => Either::Left(a.executor(db)), - Either::Right(b) => Either::Right(b.executor(db)), + Self::Left(a) => Either::Left(a.executor(db)), + Self::Right(b) => Either::Right(b.executor(db)), } } @@ -36,8 +36,8 @@ where DB: Database, { match self { - Either::Left(a) => Either::Left(a.batch_executor(db, prune_modes)), - Either::Right(b) => Either::Right(b.batch_executor(db, prune_modes)), + Self::Left(a) => Either::Left(a.batch_executor(db, prune_modes)), + Self::Right(b) => Either::Right(b.batch_executor(db, prune_modes)), } } } @@ -64,8 +64,8 @@ where fn execute(self, input: Self::Input<'_>) -> Result { match self { - Either::Left(a) => a.execute(input), - Either::Right(b) => b.execute(input), + Self::Left(a) => a.execute(input), + Self::Right(b) => b.execute(input), } } } @@ -92,29 +92,29 @@ where fn execute_and_verify_one(&mut self, input: Self::Input<'_>) -> Result<(), Self::Error> { match self { - Either::Left(a) => a.execute_and_verify_one(input), - Either::Right(b) => b.execute_and_verify_one(input), + Self::Left(a) => a.execute_and_verify_one(input), + Self::Right(b) => b.execute_and_verify_one(input), } } fn finalize(self) -> Self::Output { match self { - Either::Left(a) => a.finalize(), - Either::Right(b) => b.finalize(), + Self::Left(a) => a.finalize(), + Self::Right(b) => b.finalize(), } } fn set_tip(&mut self, tip: BlockNumber) { match self { - Either::Left(a) => a.set_tip(tip), - Either::Right(b) => b.set_tip(tip), + Self::Left(a) => a.set_tip(tip), + Self::Right(b) => b.set_tip(tip), } } fn size_hint(&self) -> Option { match self { - Either::Left(a) => a.size_hint(), - Either::Right(b) => b.size_hint(), + Self::Left(a) => a.size_hint(), + Self::Right(b) => b.size_hint(), } } } diff --git a/crates/fs-util/src/lib.rs b/crates/fs-util/src/lib.rs index c6c56dd44..6c5c2a722 100644 --- a/crates/fs-util/src/lib.rs +++ b/crates/fs-util/src/lib.rs @@ -143,57 +143,57 @@ pub enum FsPathError { impl FsPathError { /// Returns the complementary error variant for [`std::fs::write`]. pub fn write(source: io::Error, path: impl Into) -> Self { - FsPathError::Write { source, path: path.into() } + Self::Write { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::read`]. pub fn read(source: io::Error, path: impl Into) -> Self { - FsPathError::Read { source, path: path.into() } + Self::Read { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::read_link`]. pub fn read_link(source: io::Error, path: impl Into) -> Self { - FsPathError::ReadLink { source, path: path.into() } + Self::ReadLink { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::File::create`]. pub fn create_file(source: io::Error, path: impl Into) -> Self { - FsPathError::CreateFile { source, path: path.into() } + Self::CreateFile { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::remove_file`]. pub fn remove_file(source: io::Error, path: impl Into) -> Self { - FsPathError::RemoveFile { source, path: path.into() } + Self::RemoveFile { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::create_dir`]. pub fn create_dir(source: io::Error, path: impl Into) -> Self { - FsPathError::CreateDir { source, path: path.into() } + Self::CreateDir { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::remove_dir`]. pub fn remove_dir(source: io::Error, path: impl Into) -> Self { - FsPathError::RemoveDir { source, path: path.into() } + Self::RemoveDir { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::read_dir`]. pub fn read_dir(source: io::Error, path: impl Into) -> Self { - FsPathError::ReadDir { source, path: path.into() } + Self::ReadDir { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::File::open`]. pub fn open(source: io::Error, path: impl Into) -> Self { - FsPathError::Open { source, path: path.into() } + Self::Open { source, path: path.into() } } /// Returns the complementary error variant for [`std::fs::rename`]. pub fn rename(source: io::Error, from: impl Into, to: impl Into) -> Self { - FsPathError::Rename { source, from: from.into(), to: to.into() } + Self::Rename { source, from: from.into(), to: to.into() } } /// Returns the complementary error variant for [`std::fs::File::metadata`]. pub fn metadata(source: io::Error, path: impl Into) -> Self { - FsPathError::Metadata { source, path: path.into() } + Self::Metadata { source, path: path.into() } } } diff --git a/crates/metrics/metrics-derive/src/expand.rs b/crates/metrics/metrics-derive/src/expand.rs index cc14fb1b6..a4bb61b48 100644 --- a/crates/metrics/metrics-derive/src/expand.rs +++ b/crates/metrics/metrics-derive/src/expand.rs @@ -220,7 +220,7 @@ impl MetricsAttr { fn separator(&self) -> String { match &self.separator { Some(sep) => sep.value(), - None => MetricsAttr::DEFAULT_SEPARATOR.to_owned(), + None => Self::DEFAULT_SEPARATOR.to_owned(), } } } diff --git a/crates/net/common/src/ratelimit.rs b/crates/net/common/src/ratelimit.rs index 26440ae3c..2294e8552 100644 --- a/crates/net/common/src/ratelimit.rs +++ b/crates/net/common/src/ratelimit.rs @@ -24,7 +24,7 @@ impl RateLimit { let until = tokio::time::Instant::now(); let state = State::Ready { until, remaining: rate.limit() }; - RateLimit { rate, state, sleep: Box::pin(tokio::time::sleep_until(until)) } + Self { rate, state, sleep: Box::pin(tokio::time::sleep_until(until)) } } /// Returns the configured limit of the [RateLimit] @@ -107,7 +107,7 @@ pub struct Rate { impl Rate { /// Create a new [Rate] with the given `limit/duration` ratio. pub fn new(limit: u64, duration: Duration) -> Self { - Rate { limit, duration } + Self { limit, duration } } fn limit(&self) -> u64 { diff --git a/crates/net/discv4/src/error.rs b/crates/net/discv4/src/error.rs index 1fbd67d47..13ed56531 100644 --- a/crates/net/discv4/src/error.rs +++ b/crates/net/discv4/src/error.rs @@ -40,6 +40,6 @@ pub enum Discv4Error { impl From> for Discv4Error { fn from(_: SendError) -> Self { - Discv4Error::Send + Self::Send } } diff --git a/crates/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index 8e2ff1251..de6fd507a 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -562,7 +562,7 @@ impl Discv4Service { let shared_node_record = Arc::new(Mutex::new(local_node_record)); - Discv4Service { + Self { local_address, local_eip_868_enr, local_node_record, diff --git a/crates/net/discv4/src/node.rs b/crates/net/discv4/src/node.rs index 62e45db0e..c2e6d329e 100644 --- a/crates/net/discv4/src/node.rs +++ b/crates/net/discv4/src/node.rs @@ -8,7 +8,7 @@ pub(crate) struct NodeKey(pub(crate) PeerId); impl From for NodeKey { fn from(value: PeerId) -> Self { - NodeKey(value) + Self(value) } } @@ -16,13 +16,13 @@ impl From for discv5::Key { fn from(value: NodeKey) -> Self { let hash = keccak256(value.0.as_slice()); let hash = *GenericArray::from_slice(hash.as_slice()); - discv5::Key::new_raw(value, hash) + Self::new_raw(value, hash) } } impl From<&NodeRecord> for NodeKey { fn from(node: &NodeRecord) -> Self { - NodeKey(node.id) + Self(node.id) } } diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index be26487a6..9131b91da 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -40,12 +40,12 @@ impl MessageId { /// Converts the byte that represents the message id to the enum. fn from_u8(msg: u8) -> Result { Ok(match msg { - 1 => MessageId::Ping, - 2 => MessageId::Pong, - 3 => MessageId::FindNode, - 4 => MessageId::Neighbours, - 5 => MessageId::EnrRequest, - 6 => MessageId::EnrResponse, + 1 => Self::Ping, + 2 => Self::Pong, + 3 => Self::FindNode, + 4 => Self::Neighbours, + 5 => Self::EnrRequest, + 6 => Self::EnrResponse, _ => return Err(msg), }) } @@ -74,12 +74,12 @@ impl Message { /// Returns the id for this type pub const fn msg_type(&self) -> MessageId { match self { - Message::Ping(_) => MessageId::Ping, - Message::Pong(_) => MessageId::Pong, - Message::FindNode(_) => MessageId::FindNode, - Message::Neighbours(_) => MessageId::Neighbours, - Message::EnrRequest(_) => MessageId::EnrRequest, - Message::EnrResponse(_) => MessageId::EnrResponse, + Self::Ping(_) => MessageId::Ping, + Self::Pong(_) => MessageId::Pong, + Self::FindNode(_) => MessageId::FindNode, + Self::Neighbours(_) => MessageId::Neighbours, + Self::EnrRequest(_) => MessageId::EnrRequest, + Self::EnrResponse(_) => MessageId::EnrResponse, } } @@ -101,12 +101,12 @@ impl Message { // Match the message type and encode the corresponding message into the payload match self { - Message::Ping(message) => message.encode(&mut payload), - Message::Pong(message) => message.encode(&mut payload), - Message::FindNode(message) => message.encode(&mut payload), - Message::Neighbours(message) => message.encode(&mut payload), - Message::EnrRequest(message) => message.encode(&mut payload), - Message::EnrResponse(message) => message.encode(&mut payload), + Self::Ping(message) => message.encode(&mut payload), + Self::Pong(message) => message.encode(&mut payload), + Self::FindNode(message) => message.encode(&mut payload), + Self::Neighbours(message) => message.encode(&mut payload), + Self::EnrRequest(message) => message.encode(&mut payload), + Self::EnrResponse(message) => message.encode(&mut payload), } // Sign the payload with the secret key using recoverable ECDSA @@ -165,12 +165,12 @@ impl Message { let payload = &mut &packet[98..]; let msg = match MessageId::from_u8(msg_type).map_err(DecodePacketError::UnknownMessage)? { - MessageId::Ping => Message::Ping(Ping::decode(payload)?), - MessageId::Pong => Message::Pong(Pong::decode(payload)?), - MessageId::FindNode => Message::FindNode(FindNode::decode(payload)?), - MessageId::Neighbours => Message::Neighbours(Neighbours::decode(payload)?), - MessageId::EnrRequest => Message::EnrRequest(EnrRequest::decode(payload)?), - MessageId::EnrResponse => Message::EnrResponse(EnrResponse::decode(payload)?), + MessageId::Ping => Self::Ping(Ping::decode(payload)?), + MessageId::Pong => Self::Pong(Pong::decode(payload)?), + MessageId::FindNode => Self::FindNode(FindNode::decode(payload)?), + MessageId::Neighbours => Self::Neighbours(Neighbours::decode(payload)?), + MessageId::EnrRequest => Self::EnrRequest(EnrRequest::decode(payload)?), + MessageId::EnrResponse => Self::EnrResponse(EnrResponse::decode(payload)?), }; Ok(Packet { msg, node_id, hash: header_hash }) @@ -210,7 +210,7 @@ impl From for NodeEndpoint { impl NodeEndpoint { /// Creates a new [`NodeEndpoint`] from a given UDP address and TCP port. pub fn from_udp_address(udp_address: &std::net::SocketAddr, tcp_port: u16) -> Self { - NodeEndpoint { address: udp_address.ip(), udp_port: udp_address.port(), tcp_port } + Self { address: udp_address.ip(), udp_port: udp_address.port(), tcp_port } } } diff --git a/crates/net/discv5/src/filter.rs b/crates/net/discv5/src/filter.rs index d62a7584a..8c8e1f727 100644 --- a/crates/net/discv5/src/filter.rs +++ b/crates/net/discv5/src/filter.rs @@ -20,7 +20,7 @@ pub enum FilterOutcome { impl FilterOutcome { /// Returns `true` for [`FilterOutcome::Ok`]. pub fn is_ok(&self) -> bool { - matches!(self, FilterOutcome::Ok) + matches!(self, Self::Ok) } } @@ -58,7 +58,7 @@ impl MustNotIncludeKeys { _ = keys.insert(MustIncludeKey::new(key)); } - MustNotIncludeKeys { keys } + Self { keys } } } diff --git a/crates/net/discv5/src/lib.rs b/crates/net/discv5/src/lib.rs index ffa3c9caf..6f30244e3 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -798,23 +798,23 @@ mod test { } impl PartialEq for Key { - fn eq(&self, other: &Key) -> bool { + fn eq(&self, other: &Self) -> bool { self.hash == other.hash } } impl Eq for Key {} - impl AsRef> for Key { - fn as_ref(&self) -> &Key { + impl AsRef for Key { + fn as_ref(&self) -> &Self { self } } impl Key { /// Construct a new `Key` by providing the raw 32 byte hash. - pub fn new_raw(preimage: T, hash: GenericArray) -> Key { - Key { preimage, hash } + pub fn new_raw(preimage: T, hash: GenericArray) -> Self { + Self { preimage, hash } } /// Borrows the preimage of the key. @@ -846,7 +846,7 @@ mod test { impl From for Key { fn from(node_id: NodeId) -> Self { - Key { preimage: node_id, hash: *GenericArray::from_slice(&node_id.raw()) } + Self { preimage: node_id, hash: *GenericArray::from_slice(&node_id.raw()) } } } diff --git a/crates/net/dns/src/query.rs b/crates/net/dns/src/query.rs index a3cba5caf..dece35925 100644 --- a/crates/net/dns/src/query.rs +++ b/crates/net/dns/src/query.rs @@ -135,11 +135,11 @@ impl Query { /// Advances the query fn poll(&mut self, cx: &mut Context<'_>) -> Poll> { match self { - Query::Root(ref mut query) => { + Self::Root(ref mut query) => { let outcome = ready!(query.as_mut().poll(cx)); Poll::Ready(QueryOutcome::Root(outcome)) } - Query::Entry(ref mut query) => { + Self::Entry(ref mut query) => { let outcome = ready!(query.as_mut().poll(cx)); Poll::Ready(QueryOutcome::Entry(outcome)) } diff --git a/crates/net/dns/src/sync.rs b/crates/net/dns/src/sync.rs index 0174670b3..d33d0861c 100644 --- a/crates/net/dns/src/sync.rs +++ b/crates/net/dns/src/sync.rs @@ -157,6 +157,6 @@ pub(crate) enum ResolveKind { impl ResolveKind { pub(crate) fn is_link(&self) -> bool { - matches!(self, ResolveKind::Link) + matches!(self, Self::Link) } } diff --git a/crates/net/dns/src/tree.rs b/crates/net/dns/src/tree.rs index 614d5f1d2..1c8bb51cf 100644 --- a/crates/net/dns/src/tree.rs +++ b/crates/net/dns/src/tree.rs @@ -58,10 +58,10 @@ pub enum DnsEntry { impl fmt::Display for DnsEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - DnsEntry::Root(entry) => entry.fmt(f), - DnsEntry::Link(entry) => entry.fmt(f), - DnsEntry::Branch(entry) => entry.fmt(f), - DnsEntry::Node(entry) => entry.fmt(f), + Self::Root(entry) => entry.fmt(f), + Self::Link(entry) => entry.fmt(f), + Self::Branch(entry) => entry.fmt(f), + Self::Node(entry) => entry.fmt(f), } } } diff --git a/crates/net/downloaders/src/bodies/bodies.rs b/crates/net/downloaders/src/bodies/bodies.rs index ed5cdf64a..d8f0bfcbb 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -505,7 +505,7 @@ impl BodiesDownloaderBuilder { /// Creates a new [BodiesDownloaderBuilder] with configurations based on the provided /// [BodiesConfig]. pub fn new(config: BodiesConfig) -> Self { - BodiesDownloaderBuilder::default() + Self::default() .with_stream_batch_size(config.downloader_stream_batch_size) .with_request_limit(config.downloader_request_limit) .with_max_buffered_blocks_size_bytes(config.downloader_max_buffered_blocks_size_bytes) diff --git a/crates/net/downloaders/src/file_client.rs b/crates/net/downloaders/src/file_client.rs index 9411099e8..462f935eb 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -74,7 +74,7 @@ impl FileClient { /// Create a new file client from a file path. pub async fn new>(path: P) -> Result { let file = File::open(path).await?; - FileClient::from_file(file).await + Self::from_file(file).await } /// Initialize the [`FileClient`] with a file directly. diff --git a/crates/net/downloaders/src/headers/reverse_headers.rs b/crates/net/downloaders/src/headers/reverse_headers.rs index 2889eb84a..605123cb1 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -1090,7 +1090,7 @@ impl ReverseHeadersDownloaderBuilder { /// Creates a new [ReverseHeadersDownloaderBuilder] with configurations based on the provided /// [HeadersConfig]. pub fn new(config: HeadersConfig) -> Self { - ReverseHeadersDownloaderBuilder::default() + Self::default() .request_limit(config.downloader_request_limit) .min_concurrent_requests(config.downloader_min_concurrent_requests) .max_concurrent_requests(config.downloader_max_concurrent_requests) diff --git a/crates/net/ecies/src/algorithm.rs b/crates/net/ecies/src/algorithm.rs index 65d74627e..c1555c468 100644 --- a/crates/net/ecies/src/algorithm.rs +++ b/crates/net/ecies/src/algorithm.rs @@ -631,7 +631,7 @@ impl ECIES { self.egress_mac.as_mut().unwrap().update_header(&header); let tag = self.egress_mac.as_mut().unwrap().digest(); - out.reserve(ECIES::header_len()); + out.reserve(Self::header_len()); out.extend_from_slice(&header[..]); out.extend_from_slice(tag.as_slice()); } diff --git a/crates/net/ecies/src/error.rs b/crates/net/ecies/src/error.rs index 64526f16d..c4b18a89f 100644 --- a/crates/net/ecies/src/error.rs +++ b/crates/net/ecies/src/error.rs @@ -88,7 +88,7 @@ pub enum ECIESErrorImpl { impl From for ECIESError { fn from(source: ECIESErrorImpl) -> Self { - ECIESError { inner: Box::new(source) } + Self { inner: Box::new(source) } } } diff --git a/crates/net/eth-wire-types/src/blocks.rs b/crates/net/eth-wire-types/src/blocks.rs index ae5cfee9e..3a949f686 100644 --- a/crates/net/eth-wire-types/src/blocks.rs +++ b/crates/net/eth-wire-types/src/blocks.rs @@ -79,13 +79,13 @@ impl<'a> arbitrary::Arbitrary<'a> for BlockHeaders { )) } - Ok(BlockHeaders(headers)) + Ok(Self(headers)) } } impl From> for BlockHeaders { fn from(headers: Vec
) -> Self { - BlockHeaders(headers) + Self(headers) } } @@ -100,7 +100,7 @@ pub struct GetBlockBodies( impl From> for GetBlockBodies { fn from(hashes: Vec) -> Self { - GetBlockBodies(hashes) + Self(hashes) } } @@ -122,7 +122,7 @@ pub struct BlockBodies( impl From> for BlockBodies { fn from(bodies: Vec) -> Self { - BlockBodies(bodies) + Self(bodies) } } diff --git a/crates/net/eth-wire-types/src/broadcast.rs b/crates/net/eth-wire-types/src/broadcast.rs index b648f5a22..86485e8e4 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -60,7 +60,7 @@ pub struct BlockHashNumber { impl From> for NewBlockHashes { fn from(v: Vec) -> Self { - NewBlockHashes(v) + Self(v) } } @@ -101,7 +101,7 @@ impl Transactions { impl From> for Transactions { fn from(txs: Vec) -> Self { - Transactions(txs) + Self(txs) } } @@ -139,18 +139,18 @@ impl NewPooledTransactionHashes { /// Returns the message [`EthVersion`]. pub fn version(&self) -> EthVersion { match self { - NewPooledTransactionHashes::Eth66(_) => EthVersion::Eth66, - NewPooledTransactionHashes::Eth68(_) => EthVersion::Eth68, + Self::Eth66(_) => EthVersion::Eth66, + Self::Eth68(_) => EthVersion::Eth68, } } /// Returns `true` if the payload is valid for the given version pub fn is_valid_for_version(&self, version: EthVersion) -> bool { match self { - NewPooledTransactionHashes::Eth66(_) => { + Self::Eth66(_) => { matches!(version, EthVersion::Eth67 | EthVersion::Eth66) } - NewPooledTransactionHashes::Eth68(_) => { + Self::Eth68(_) => { matches!(version, EthVersion::Eth68) } } @@ -159,40 +159,40 @@ impl NewPooledTransactionHashes { /// Returns an iterator over all transaction hashes. pub fn iter_hashes(&self) -> impl Iterator + '_ { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0.iter(), - NewPooledTransactionHashes::Eth68(msg) => msg.hashes.iter(), + Self::Eth66(msg) => msg.0.iter(), + Self::Eth68(msg) => msg.hashes.iter(), } } /// Returns an immutable reference to transaction hashes. pub fn hashes(&self) -> &Vec { match self { - NewPooledTransactionHashes::Eth66(msg) => &msg.0, - NewPooledTransactionHashes::Eth68(msg) => &msg.hashes, + Self::Eth66(msg) => &msg.0, + Self::Eth68(msg) => &msg.hashes, } } /// Returns a mutable reference to transaction hashes. pub fn hashes_mut(&mut self) -> &mut Vec { match self { - NewPooledTransactionHashes::Eth66(msg) => &mut msg.0, - NewPooledTransactionHashes::Eth68(msg) => &mut msg.hashes, + Self::Eth66(msg) => &mut msg.0, + Self::Eth68(msg) => &mut msg.hashes, } } /// Consumes the type and returns all hashes pub fn into_hashes(self) -> Vec { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0, - NewPooledTransactionHashes::Eth68(msg) => msg.hashes, + Self::Eth66(msg) => msg.0, + Self::Eth68(msg) => msg.hashes, } } /// Returns an iterator over all transaction hashes. pub fn into_iter_hashes(self) -> impl Iterator { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0.into_iter(), - NewPooledTransactionHashes::Eth68(msg) => msg.hashes.into_iter(), + Self::Eth66(msg) => msg.0.into_iter(), + Self::Eth68(msg) => msg.hashes.into_iter(), } } @@ -200,8 +200,8 @@ impl NewPooledTransactionHashes { /// the rest. If `len` is greater than the number of hashes, this has no effect. pub fn truncate(&mut self, len: usize) { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0.truncate(len), - NewPooledTransactionHashes::Eth68(msg) => { + Self::Eth66(msg) => msg.0.truncate(len), + Self::Eth68(msg) => { msg.types.truncate(len); msg.sizes.truncate(len); msg.hashes.truncate(len); @@ -212,56 +212,56 @@ impl NewPooledTransactionHashes { /// Returns true if the message is empty pub fn is_empty(&self) -> bool { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0.is_empty(), - NewPooledTransactionHashes::Eth68(msg) => msg.hashes.is_empty(), + Self::Eth66(msg) => msg.0.is_empty(), + Self::Eth68(msg) => msg.hashes.is_empty(), } } /// Returns the number of hashes in the message pub fn len(&self) -> usize { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.0.len(), - NewPooledTransactionHashes::Eth68(msg) => msg.hashes.len(), + Self::Eth66(msg) => msg.0.len(), + Self::Eth68(msg) => msg.hashes.len(), } } /// Returns an immutable reference to the inner type if this an eth68 announcement. pub fn as_eth68(&self) -> Option<&NewPooledTransactionHashes68> { match self { - NewPooledTransactionHashes::Eth66(_) => None, - NewPooledTransactionHashes::Eth68(msg) => Some(msg), + Self::Eth66(_) => None, + Self::Eth68(msg) => Some(msg), } } /// Returns a mutable reference to the inner type if this an eth68 announcement. pub fn as_eth68_mut(&mut self) -> Option<&mut NewPooledTransactionHashes68> { match self { - NewPooledTransactionHashes::Eth66(_) => None, - NewPooledTransactionHashes::Eth68(msg) => Some(msg), + Self::Eth66(_) => None, + Self::Eth68(msg) => Some(msg), } } /// Returns a mutable reference to the inner type if this an eth66 announcement. pub fn as_eth66_mut(&mut self) -> Option<&mut NewPooledTransactionHashes66> { match self { - NewPooledTransactionHashes::Eth66(msg) => Some(msg), - NewPooledTransactionHashes::Eth68(_) => None, + Self::Eth66(msg) => Some(msg), + Self::Eth68(_) => None, } } /// Returns the inner type if this an eth68 announcement. pub fn take_eth68(&mut self) -> Option { match self { - NewPooledTransactionHashes::Eth66(_) => None, - NewPooledTransactionHashes::Eth68(msg) => Some(mem::take(msg)), + Self::Eth66(_) => None, + Self::Eth68(msg) => Some(mem::take(msg)), } } /// Returns the inner type if this an eth66 announcement. pub fn take_eth66(&mut self) -> Option { match self { - NewPooledTransactionHashes::Eth66(msg) => Some(mem::take(msg)), - NewPooledTransactionHashes::Eth68(_) => None, + Self::Eth66(msg) => Some(mem::take(msg)), + Self::Eth68(_) => None, } } } @@ -269,8 +269,8 @@ impl NewPooledTransactionHashes { impl From for EthMessage { fn from(value: NewPooledTransactionHashes) -> Self { match value { - NewPooledTransactionHashes::Eth66(msg) => EthMessage::NewPooledTransactionHashes66(msg), - NewPooledTransactionHashes::Eth68(msg) => EthMessage::NewPooledTransactionHashes68(msg), + NewPooledTransactionHashes::Eth66(msg) => Self::NewPooledTransactionHashes66(msg), + NewPooledTransactionHashes::Eth68(msg) => Self::NewPooledTransactionHashes68(msg), } } } @@ -301,7 +301,7 @@ pub struct NewPooledTransactionHashes66( impl From> for NewPooledTransactionHashes66 { fn from(v: Vec) -> Self { - NewPooledTransactionHashes66(v) + Self(v) } } @@ -359,11 +359,7 @@ impl Arbitrary for NewPooledTransactionHashes68 { (types_vec, sizes_vec, hashes_vec) }) - .prop_map(|(types, sizes, hashes)| NewPooledTransactionHashes68 { - types, - sizes, - hashes, - }) + .prop_map(|(types, sizes, hashes)| Self { types, sizes, hashes }) .boxed() } @@ -476,8 +472,8 @@ impl DedupPayload for NewPooledTransactionHashes { fn dedup(self) -> PartiallyValidData { match self { - NewPooledTransactionHashes::Eth66(msg) => msg.dedup(), - NewPooledTransactionHashes::Eth68(msg) => msg.dedup(), + Self::Eth66(msg) => msg.dedup(), + Self::Eth68(msg) => msg.dedup(), } } } @@ -733,7 +729,7 @@ impl RequestTxHashes { impl FromIterator<(TxHash, Eth68TxMetadata)> for RequestTxHashes { fn from_iter>(iter: I) -> Self { - RequestTxHashes::new(iter.into_iter().map(|(hash, _)| hash).collect::>()) + Self::new(iter.into_iter().map(|(hash, _)| hash).collect::>()) } } diff --git a/crates/net/eth-wire-types/src/message.rs b/crates/net/eth-wire-types/src/message.rs index c4101e852..2239353f2 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -114,7 +114,7 @@ impl ProtocolMessage { EthMessage::Receipts(request_pair) } }; - Ok(ProtocolMessage { message_type, message }) + Ok(Self { message_type, message }) } } @@ -132,7 +132,7 @@ impl Encodable for ProtocolMessage { impl From for ProtocolMessage { fn from(message: EthMessage) -> Self { - ProtocolMessage { message_type: message.message_id(), message } + Self { message_type: message.message_id(), message } } } @@ -160,7 +160,7 @@ impl Encodable for ProtocolBroadcastMessage { impl From for ProtocolBroadcastMessage { fn from(message: EthBroadcastMessage) -> Self { - ProtocolBroadcastMessage { message_type: message.message_id(), message } + Self { message_type: message.message_id(), message } } } @@ -223,22 +223,23 @@ impl EthMessage { /// Returns the message's ID. pub fn message_id(&self) -> EthMessageID { match self { - EthMessage::Status(_) => EthMessageID::Status, - EthMessage::NewBlockHashes(_) => EthMessageID::NewBlockHashes, - EthMessage::NewBlock(_) => EthMessageID::NewBlock, - EthMessage::Transactions(_) => EthMessageID::Transactions, - EthMessage::NewPooledTransactionHashes66(_) | - EthMessage::NewPooledTransactionHashes68(_) => EthMessageID::NewPooledTransactionHashes, - EthMessage::GetBlockHeaders(_) => EthMessageID::GetBlockHeaders, - EthMessage::BlockHeaders(_) => EthMessageID::BlockHeaders, - EthMessage::GetBlockBodies(_) => EthMessageID::GetBlockBodies, - EthMessage::BlockBodies(_) => EthMessageID::BlockBodies, - EthMessage::GetPooledTransactions(_) => EthMessageID::GetPooledTransactions, - EthMessage::PooledTransactions(_) => EthMessageID::PooledTransactions, - EthMessage::GetNodeData(_) => EthMessageID::GetNodeData, - EthMessage::NodeData(_) => EthMessageID::NodeData, - EthMessage::GetReceipts(_) => EthMessageID::GetReceipts, - EthMessage::Receipts(_) => EthMessageID::Receipts, + Self::Status(_) => EthMessageID::Status, + Self::NewBlockHashes(_) => EthMessageID::NewBlockHashes, + Self::NewBlock(_) => EthMessageID::NewBlock, + Self::Transactions(_) => EthMessageID::Transactions, + Self::NewPooledTransactionHashes66(_) | Self::NewPooledTransactionHashes68(_) => { + EthMessageID::NewPooledTransactionHashes + } + Self::GetBlockHeaders(_) => EthMessageID::GetBlockHeaders, + Self::BlockHeaders(_) => EthMessageID::BlockHeaders, + Self::GetBlockBodies(_) => EthMessageID::GetBlockBodies, + Self::BlockBodies(_) => EthMessageID::BlockBodies, + Self::GetPooledTransactions(_) => EthMessageID::GetPooledTransactions, + Self::PooledTransactions(_) => EthMessageID::PooledTransactions, + Self::GetNodeData(_) => EthMessageID::GetNodeData, + Self::NodeData(_) => EthMessageID::NodeData, + Self::GetReceipts(_) => EthMessageID::GetReceipts, + Self::Receipts(_) => EthMessageID::Receipts, } } } @@ -246,42 +247,42 @@ impl EthMessage { impl Encodable for EthMessage { fn encode(&self, out: &mut dyn BufMut) { match self { - EthMessage::Status(status) => status.encode(out), - EthMessage::NewBlockHashes(new_block_hashes) => new_block_hashes.encode(out), - EthMessage::NewBlock(new_block) => new_block.encode(out), - EthMessage::Transactions(transactions) => transactions.encode(out), - EthMessage::NewPooledTransactionHashes66(hashes) => hashes.encode(out), - EthMessage::NewPooledTransactionHashes68(hashes) => hashes.encode(out), - EthMessage::GetBlockHeaders(request) => request.encode(out), - EthMessage::BlockHeaders(headers) => headers.encode(out), - EthMessage::GetBlockBodies(request) => request.encode(out), - EthMessage::BlockBodies(bodies) => bodies.encode(out), - EthMessage::GetPooledTransactions(request) => request.encode(out), - EthMessage::PooledTransactions(transactions) => transactions.encode(out), - EthMessage::GetNodeData(request) => request.encode(out), - EthMessage::NodeData(data) => data.encode(out), - EthMessage::GetReceipts(request) => request.encode(out), - EthMessage::Receipts(receipts) => receipts.encode(out), + Self::Status(status) => status.encode(out), + Self::NewBlockHashes(new_block_hashes) => new_block_hashes.encode(out), + Self::NewBlock(new_block) => new_block.encode(out), + Self::Transactions(transactions) => transactions.encode(out), + Self::NewPooledTransactionHashes66(hashes) => hashes.encode(out), + Self::NewPooledTransactionHashes68(hashes) => hashes.encode(out), + Self::GetBlockHeaders(request) => request.encode(out), + Self::BlockHeaders(headers) => headers.encode(out), + Self::GetBlockBodies(request) => request.encode(out), + Self::BlockBodies(bodies) => bodies.encode(out), + Self::GetPooledTransactions(request) => request.encode(out), + Self::PooledTransactions(transactions) => transactions.encode(out), + Self::GetNodeData(request) => request.encode(out), + Self::NodeData(data) => data.encode(out), + Self::GetReceipts(request) => request.encode(out), + Self::Receipts(receipts) => receipts.encode(out), } } fn length(&self) -> usize { match self { - EthMessage::Status(status) => status.length(), - EthMessage::NewBlockHashes(new_block_hashes) => new_block_hashes.length(), - EthMessage::NewBlock(new_block) => new_block.length(), - EthMessage::Transactions(transactions) => transactions.length(), - EthMessage::NewPooledTransactionHashes66(hashes) => hashes.length(), - EthMessage::NewPooledTransactionHashes68(hashes) => hashes.length(), - EthMessage::GetBlockHeaders(request) => request.length(), - EthMessage::BlockHeaders(headers) => headers.length(), - EthMessage::GetBlockBodies(request) => request.length(), - EthMessage::BlockBodies(bodies) => bodies.length(), - EthMessage::GetPooledTransactions(request) => request.length(), - EthMessage::PooledTransactions(transactions) => transactions.length(), - EthMessage::GetNodeData(request) => request.length(), - EthMessage::NodeData(data) => data.length(), - EthMessage::GetReceipts(request) => request.length(), - EthMessage::Receipts(receipts) => receipts.length(), + Self::Status(status) => status.length(), + Self::NewBlockHashes(new_block_hashes) => new_block_hashes.length(), + Self::NewBlock(new_block) => new_block.length(), + Self::Transactions(transactions) => transactions.length(), + Self::NewPooledTransactionHashes66(hashes) => hashes.length(), + Self::NewPooledTransactionHashes68(hashes) => hashes.length(), + Self::GetBlockHeaders(request) => request.length(), + Self::BlockHeaders(headers) => headers.length(), + Self::GetBlockBodies(request) => request.length(), + Self::BlockBodies(bodies) => bodies.length(), + Self::GetPooledTransactions(request) => request.length(), + Self::PooledTransactions(transactions) => transactions.length(), + Self::GetNodeData(request) => request.length(), + Self::NodeData(data) => data.length(), + Self::GetReceipts(request) => request.length(), + Self::Receipts(receipts) => receipts.length(), } } } @@ -307,8 +308,8 @@ impl EthBroadcastMessage { /// Returns the message's ID. pub fn message_id(&self) -> EthMessageID { match self { - EthBroadcastMessage::NewBlock(_) => EthMessageID::NewBlock, - EthBroadcastMessage::Transactions(_) => EthMessageID::Transactions, + Self::NewBlock(_) => EthMessageID::NewBlock, + Self::Transactions(_) => EthMessageID::Transactions, } } } @@ -316,15 +317,15 @@ impl EthBroadcastMessage { impl Encodable for EthBroadcastMessage { fn encode(&self, out: &mut dyn BufMut) { match self { - EthBroadcastMessage::NewBlock(new_block) => new_block.encode(out), - EthBroadcastMessage::Transactions(transactions) => transactions.encode(out), + Self::NewBlock(new_block) => new_block.encode(out), + Self::Transactions(transactions) => transactions.encode(out), } } fn length(&self) -> usize { match self { - EthBroadcastMessage::NewBlock(new_block) => new_block.length(), - EthBroadcastMessage::Transactions(transactions) => transactions.length(), + Self::NewBlock(new_block) => new_block.length(), + Self::Transactions(transactions) => transactions.length(), } } } @@ -385,21 +386,21 @@ impl Encodable for EthMessageID { impl Decodable for EthMessageID { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { let id = match buf.first().ok_or(alloy_rlp::Error::InputTooShort)? { - 0x00 => EthMessageID::Status, - 0x01 => EthMessageID::NewBlockHashes, - 0x02 => EthMessageID::Transactions, - 0x03 => EthMessageID::GetBlockHeaders, - 0x04 => EthMessageID::BlockHeaders, - 0x05 => EthMessageID::GetBlockBodies, - 0x06 => EthMessageID::BlockBodies, - 0x07 => EthMessageID::NewBlock, - 0x08 => EthMessageID::NewPooledTransactionHashes, - 0x09 => EthMessageID::GetPooledTransactions, - 0x0a => EthMessageID::PooledTransactions, - 0x0d => EthMessageID::GetNodeData, - 0x0e => EthMessageID::NodeData, - 0x0f => EthMessageID::GetReceipts, - 0x10 => EthMessageID::Receipts, + 0x00 => Self::Status, + 0x01 => Self::NewBlockHashes, + 0x02 => Self::Transactions, + 0x03 => Self::GetBlockHeaders, + 0x04 => Self::BlockHeaders, + 0x05 => Self::GetBlockBodies, + 0x06 => Self::BlockBodies, + 0x07 => Self::NewBlock, + 0x08 => Self::NewPooledTransactionHashes, + 0x09 => Self::GetPooledTransactions, + 0x0a => Self::PooledTransactions, + 0x0d => Self::GetNodeData, + 0x0e => Self::NodeData, + 0x0f => Self::GetReceipts, + 0x10 => Self::Receipts, _ => return Err(alloy_rlp::Error::Custom("Invalid message ID")), }; buf.advance(1); @@ -412,21 +413,21 @@ impl TryFrom for EthMessageID { fn try_from(value: usize) -> Result { match value { - 0x00 => Ok(EthMessageID::Status), - 0x01 => Ok(EthMessageID::NewBlockHashes), - 0x02 => Ok(EthMessageID::Transactions), - 0x03 => Ok(EthMessageID::GetBlockHeaders), - 0x04 => Ok(EthMessageID::BlockHeaders), - 0x05 => Ok(EthMessageID::GetBlockBodies), - 0x06 => Ok(EthMessageID::BlockBodies), - 0x07 => Ok(EthMessageID::NewBlock), - 0x08 => Ok(EthMessageID::NewPooledTransactionHashes), - 0x09 => Ok(EthMessageID::GetPooledTransactions), - 0x0a => Ok(EthMessageID::PooledTransactions), - 0x0d => Ok(EthMessageID::GetNodeData), - 0x0e => Ok(EthMessageID::NodeData), - 0x0f => Ok(EthMessageID::GetReceipts), - 0x10 => Ok(EthMessageID::Receipts), + 0x00 => Ok(Self::Status), + 0x01 => Ok(Self::NewBlockHashes), + 0x02 => Ok(Self::Transactions), + 0x03 => Ok(Self::GetBlockHeaders), + 0x04 => Ok(Self::BlockHeaders), + 0x05 => Ok(Self::GetBlockBodies), + 0x06 => Ok(Self::BlockBodies), + 0x07 => Ok(Self::NewBlock), + 0x08 => Ok(Self::NewPooledTransactionHashes), + 0x09 => Ok(Self::GetPooledTransactions), + 0x0a => Ok(Self::PooledTransactions), + 0x0d => Ok(Self::GetNodeData), + 0x0e => Ok(Self::NodeData), + 0x0f => Ok(Self::GetReceipts), + 0x10 => Ok(Self::Receipts), _ => Err("Invalid message ID"), } } diff --git a/crates/net/eth-wire-types/src/status.rs b/crates/net/eth-wire-types/src/status.rs index fc6f7fd2c..a28f4ec45 100644 --- a/crates/net/eth-wire-types/src/status.rs +++ b/crates/net/eth-wire-types/src/status.rs @@ -43,12 +43,12 @@ pub struct Status { } impl From for Status { - fn from(genesis: Genesis) -> Status { + fn from(genesis: Genesis) -> Self { let chain = genesis.config.chain_id; let total_difficulty = genesis.difficulty; let chainspec = ChainSpec::from(genesis); - Status { + Self { version: EthVersion::Eth68 as u8, chain: Chain::from_id(chain), total_difficulty, @@ -135,7 +135,7 @@ impl Debug for Status { impl Default for Status { fn default() -> Self { let mainnet_genesis = MAINNET.genesis_hash(); - Status { + Self { version: EthVersion::Eth68 as u8, chain: Chain::from_named(NamedChain::Mainnet), total_difficulty: U256::from(17_179_869_184u64), diff --git a/crates/net/eth-wire-types/src/transactions.rs b/crates/net/eth-wire-types/src/transactions.rs index 2a7313ad1..d0a42d49b 100644 --- a/crates/net/eth-wire-types/src/transactions.rs +++ b/crates/net/eth-wire-types/src/transactions.rs @@ -24,7 +24,7 @@ where T: Into, { fn from(hashes: Vec) -> Self { - GetPooledTransactions(hashes.into_iter().map(|h| h.into()).collect()) + Self(hashes.into_iter().map(|h| h.into()).collect()) } } @@ -71,7 +71,7 @@ impl TryFrom> for PooledTransactions { impl FromIterator for PooledTransactions { fn from_iter>(iter: I) -> Self { - PooledTransactions(iter.into_iter().collect()) + Self(iter.into_iter().collect()) } } diff --git a/crates/net/eth-wire-types/src/version.rs b/crates/net/eth-wire-types/src/version.rs index e121ea6d7..add1ab378 100644 --- a/crates/net/eth-wire-types/src/version.rs +++ b/crates/net/eth-wire-types/src/version.rs @@ -25,13 +25,13 @@ pub enum EthVersion { impl EthVersion { /// The latest known eth version - pub const LATEST: EthVersion = EthVersion::Eth68; + pub const LATEST: Self = Self::Eth68; /// Returns the total number of messages the protocol version supports. pub const fn total_messages(&self) -> u8 { match self { - EthVersion::Eth66 => 15, - EthVersion::Eth67 | EthVersion::Eth68 => { + Self::Eth66 => 15, + Self::Eth67 | Self::Eth68 => { // eth/67,68 are eth/66 minus GetNodeData and NodeData messages 13 } @@ -40,17 +40,17 @@ impl EthVersion { /// Returns true if the version is eth/66 pub const fn is_eth66(&self) -> bool { - matches!(self, EthVersion::Eth66) + matches!(self, Self::Eth66) } /// Returns true if the version is eth/67 pub const fn is_eth67(&self) -> bool { - matches!(self, EthVersion::Eth67) + matches!(self, Self::Eth67) } /// Returns true if the version is eth/68 pub const fn is_eth68(&self) -> bool { - matches!(self, EthVersion::Eth68) + matches!(self, Self::Eth68) } } @@ -69,9 +69,9 @@ impl TryFrom<&str> for EthVersion { #[inline] fn try_from(s: &str) -> Result { match s { - "66" => Ok(EthVersion::Eth66), - "67" => Ok(EthVersion::Eth67), - "68" => Ok(EthVersion::Eth68), + "66" => Ok(Self::Eth66), + "67" => Ok(Self::Eth67), + "68" => Ok(Self::Eth68), _ => Err(ParseVersionError(s.to_string())), } } @@ -92,9 +92,9 @@ impl TryFrom for EthVersion { #[inline] fn try_from(u: u8) -> Result { match u { - 66 => Ok(EthVersion::Eth66), - 67 => Ok(EthVersion::Eth67), - 68 => Ok(EthVersion::Eth68), + 66 => Ok(Self::Eth66), + 67 => Ok(Self::Eth67), + 68 => Ok(Self::Eth68), _ => Err(ParseVersionError(u.to_string())), } } @@ -105,14 +105,14 @@ impl FromStr for EthVersion { #[inline] fn from_str(s: &str) -> Result { - EthVersion::try_from(s) + Self::try_from(s) } } impl From for u8 { #[inline] - fn from(v: EthVersion) -> u8 { - v as u8 + fn from(v: EthVersion) -> Self { + v as Self } } diff --git a/crates/net/eth-wire/src/capability.rs b/crates/net/eth-wire/src/capability.rs index 25e6bf0e2..657ee5b29 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -116,7 +116,7 @@ impl fmt::Display for Capability { impl From for Capability { #[inline] fn from(value: EthVersion) -> Self { - Capability::eth(value) + Self::eth(value) } } @@ -137,12 +137,12 @@ impl proptest::arbitrary::Arbitrary for Capability { proptest::arbitrary::any_with::(args) // TODO: what possible values? .prop_flat_map(move |name| { proptest::arbitrary::any_with::(()) // TODO: What's the max? - .prop_map(move |version| Capability::new(name.clone(), version)) + .prop_map(move |version| Self::new(name.clone(), version)) }) .boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } /// Represents all capabilities of a node. @@ -289,8 +289,8 @@ impl SharedCapability { /// Returns the capability. pub fn capability(&self) -> Cow<'_, Capability> { match self { - SharedCapability::Eth { version, .. } => Cow::Owned(Capability::eth(*version)), - SharedCapability::UnknownCapability { cap, .. } => Cow::Borrowed(cap), + Self::Eth { version, .. } => Cow::Owned(Capability::eth(*version)), + Self::UnknownCapability { cap, .. } => Cow::Borrowed(cap), } } @@ -298,29 +298,29 @@ impl SharedCapability { #[inline] pub fn name(&self) -> &str { match self { - SharedCapability::Eth { .. } => "eth", - SharedCapability::UnknownCapability { cap, .. } => cap.name.as_ref(), + Self::Eth { .. } => "eth", + Self::UnknownCapability { cap, .. } => cap.name.as_ref(), } } /// Returns true if the capability is eth. #[inline] pub fn is_eth(&self) -> bool { - matches!(self, SharedCapability::Eth { .. }) + matches!(self, Self::Eth { .. }) } /// Returns the version of the capability. pub fn version(&self) -> u8 { match self { - SharedCapability::Eth { version, .. } => *version as u8, - SharedCapability::UnknownCapability { cap, .. } => cap.version as u8, + Self::Eth { version, .. } => *version as u8, + Self::UnknownCapability { cap, .. } => cap.version as u8, } } /// Returns the eth version if it's the `eth` capability. pub fn eth_version(&self) -> Option { match self { - SharedCapability::Eth { version, .. } => Some(*version), + Self::Eth { version, .. } => Some(*version), _ => None, } } @@ -331,8 +331,8 @@ impl SharedCapability { /// message id space. pub fn message_id_offset(&self) -> u8 { match self { - SharedCapability::Eth { offset, .. } => *offset, - SharedCapability::UnknownCapability { offset, .. } => *offset, + Self::Eth { offset, .. } => *offset, + Self::UnknownCapability { offset, .. } => *offset, } } @@ -345,8 +345,8 @@ impl SharedCapability { /// Returns the number of protocol messages supported by this capability. pub fn num_messages(&self) -> u8 { match self { - SharedCapability::Eth { version: _version, .. } => EthMessageID::max() + 1, - SharedCapability::UnknownCapability { messages, .. } => *messages, + Self::Eth { version: _version, .. } => EthMessageID::max() + 1, + Self::UnknownCapability { messages, .. } => *messages, } } } diff --git a/crates/net/eth-wire/src/disconnect.rs b/crates/net/eth-wire/src/disconnect.rs index dbf24269c..50ced132f 100644 --- a/crates/net/eth-wire/src/disconnect.rs +++ b/crates/net/eth-wire/src/disconnect.rs @@ -50,25 +50,19 @@ pub enum DisconnectReason { impl Display for DisconnectReason { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let message = match self { - DisconnectReason::DisconnectRequested => "disconnect requested", - DisconnectReason::TcpSubsystemError => "TCP sub-system error", - DisconnectReason::ProtocolBreach => { - "breach of protocol, e.g. a malformed message, bad RLP, etc." - } - DisconnectReason::UselessPeer => "useless peer", - DisconnectReason::TooManyPeers => "too many peers", - DisconnectReason::AlreadyConnected => "already connected", - DisconnectReason::IncompatibleP2PProtocolVersion => "incompatible P2P protocol version", - DisconnectReason::NullNodeIdentity => { - "null node identity received - this is automatically invalid" - } - DisconnectReason::ClientQuitting => "client quitting", - DisconnectReason::UnexpectedHandshakeIdentity => "unexpected identity in handshake", - DisconnectReason::ConnectedToSelf => { - "identity is the same as this node (i.e. connected to itself)" - } - DisconnectReason::PingTimeout => "ping timeout", - DisconnectReason::SubprotocolSpecific => "some other reason specific to a subprotocol", + Self::DisconnectRequested => "disconnect requested", + Self::TcpSubsystemError => "TCP sub-system error", + Self::ProtocolBreach => "breach of protocol, e.g. a malformed message, bad RLP, etc.", + Self::UselessPeer => "useless peer", + Self::TooManyPeers => "too many peers", + Self::AlreadyConnected => "already connected", + Self::IncompatibleP2PProtocolVersion => "incompatible P2P protocol version", + Self::NullNodeIdentity => "null node identity received - this is automatically invalid", + Self::ClientQuitting => "client quitting", + Self::UnexpectedHandshakeIdentity => "unexpected identity in handshake", + Self::ConnectedToSelf => "identity is the same as this node (i.e. connected to itself)", + Self::PingTimeout => "ping timeout", + Self::SubprotocolSpecific => "some other reason specific to a subprotocol", }; f.write_str(message) } @@ -86,19 +80,19 @@ impl TryFrom for DisconnectReason { fn try_from(value: u8) -> Result { match value { - 0x00 => Ok(DisconnectReason::DisconnectRequested), - 0x01 => Ok(DisconnectReason::TcpSubsystemError), - 0x02 => Ok(DisconnectReason::ProtocolBreach), - 0x03 => Ok(DisconnectReason::UselessPeer), - 0x04 => Ok(DisconnectReason::TooManyPeers), - 0x05 => Ok(DisconnectReason::AlreadyConnected), - 0x06 => Ok(DisconnectReason::IncompatibleP2PProtocolVersion), - 0x07 => Ok(DisconnectReason::NullNodeIdentity), - 0x08 => Ok(DisconnectReason::ClientQuitting), - 0x09 => Ok(DisconnectReason::UnexpectedHandshakeIdentity), - 0x0a => Ok(DisconnectReason::ConnectedToSelf), - 0x0b => Ok(DisconnectReason::PingTimeout), - 0x10 => Ok(DisconnectReason::SubprotocolSpecific), + 0x00 => Ok(Self::DisconnectRequested), + 0x01 => Ok(Self::TcpSubsystemError), + 0x02 => Ok(Self::ProtocolBreach), + 0x03 => Ok(Self::UselessPeer), + 0x04 => Ok(Self::TooManyPeers), + 0x05 => Ok(Self::AlreadyConnected), + 0x06 => Ok(Self::IncompatibleP2PProtocolVersion), + 0x07 => Ok(Self::NullNodeIdentity), + 0x08 => Ok(Self::ClientQuitting), + 0x09 => Ok(Self::UnexpectedHandshakeIdentity), + 0x0a => Ok(Self::ConnectedToSelf), + 0x0b => Ok(Self::PingTimeout), + 0x10 => Ok(Self::SubprotocolSpecific), _ => Err(UnknownDisconnectReason(value)), } } @@ -143,9 +137,9 @@ impl Decodable for DisconnectReason { // string 0x80 if buf[0] == 0x00 { buf.advance(1); - Ok(DisconnectReason::DisconnectRequested) + Ok(Self::DisconnectRequested) } else { - DisconnectReason::try_from(u8::decode(buf)?) + Self::try_from(u8::decode(buf)?) .map_err(|_| RlpError::Custom("unknown disconnect reason")) } } diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index c9bf39882..c7b0718fc 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -44,7 +44,7 @@ pub enum EthStreamError { impl EthStreamError { /// Returns the [`DisconnectReason`] if the error is a disconnect message pub fn as_disconnected(&self) -> Option { - if let EthStreamError::P2PStreamError(err) = self { + if let Self::P2PStreamError(err) = self { err.as_disconnected() } else { None @@ -53,7 +53,7 @@ impl EthStreamError { /// Returns the [io::Error] if it was caused by IO pub fn as_io(&self) -> Option<&io::Error> { - if let EthStreamError::P2PStreamError(P2PStreamError::Io(io)) = self { + if let Self::P2PStreamError(P2PStreamError::Io(io)) = self { return Some(io) } None diff --git a/crates/net/eth-wire/src/errors/p2p.rs b/crates/net/eth-wire/src/errors/p2p.rs index 90512bf06..83a39e2b6 100644 --- a/crates/net/eth-wire/src/errors/p2p.rs +++ b/crates/net/eth-wire/src/errors/p2p.rs @@ -86,8 +86,8 @@ impl P2PStreamError { /// Returns the [`DisconnectReason`] if it is the `Disconnected` variant. pub fn as_disconnected(&self) -> Option { let reason = match self { - P2PStreamError::HandshakeError(P2PHandshakeError::Disconnected(reason)) => reason, - P2PStreamError::Disconnected(reason) => reason, + Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) => reason, + Self::Disconnected(reason) => reason, _ => return None, }; diff --git a/crates/net/eth-wire/src/p2pstream.rs b/crates/net/eth-wire/src/p2pstream.rs index 3e8bb096a..1523a3a35 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -665,10 +665,10 @@ impl P2PMessage { /// Gets the [`P2PMessageID`] for the given message. pub fn message_id(&self) -> P2PMessageID { match self { - P2PMessage::Hello(_) => P2PMessageID::Hello, - P2PMessage::Disconnect(_) => P2PMessageID::Disconnect, - P2PMessage::Ping => P2PMessageID::Ping, - P2PMessage::Pong => P2PMessageID::Pong, + Self::Hello(_) => P2PMessageID::Hello, + Self::Disconnect(_) => P2PMessageID::Disconnect, + Self::Ping => P2PMessageID::Ping, + Self::Pong => P2PMessageID::Pong, } } } @@ -681,15 +681,15 @@ impl Encodable for P2PMessage { fn encode(&self, out: &mut dyn BufMut) { (self.message_id() as u8).encode(out); match self { - P2PMessage::Hello(msg) => msg.encode(out), - P2PMessage::Disconnect(msg) => msg.encode(out), - P2PMessage::Ping => { + Self::Hello(msg) => msg.encode(out), + Self::Disconnect(msg) => msg.encode(out), + Self::Ping => { // Ping payload is _always_ snappy encoded out.put_u8(0x01); out.put_u8(0x00); out.put_u8(EMPTY_LIST_CODE); } - P2PMessage::Pong => { + Self::Pong => { // Pong payload is _always_ snappy encoded out.put_u8(0x01); out.put_u8(0x00); @@ -700,11 +700,11 @@ impl Encodable for P2PMessage { fn length(&self) -> usize { let payload_len = match self { - P2PMessage::Hello(msg) => msg.length(), - P2PMessage::Disconnect(msg) => msg.length(), + Self::Hello(msg) => msg.length(), + Self::Disconnect(msg) => msg.length(), // id + snappy encoded payload - P2PMessage::Ping => 3, // len([0x01, 0x00, 0xc0]) = 3 - P2PMessage::Pong => 3, // len([0x01, 0x00, 0xc0]) = 3 + Self::Ping => 3, // len([0x01, 0x00, 0xc0]) = 3 + Self::Pong => 3, // len([0x01, 0x00, 0xc0]) = 3 }; payload_len + 1 // (1 for length of p2p message id) } @@ -735,15 +735,15 @@ impl Decodable for P2PMessage { .or(Err(RlpError::Custom("unknown p2p message id")))?; buf.advance(1); match id { - P2PMessageID::Hello => Ok(P2PMessage::Hello(HelloMessage::decode(buf)?)), - P2PMessageID::Disconnect => Ok(P2PMessage::Disconnect(DisconnectReason::decode(buf)?)), + P2PMessageID::Hello => Ok(Self::Hello(HelloMessage::decode(buf)?)), + P2PMessageID::Disconnect => Ok(Self::Disconnect(DisconnectReason::decode(buf)?)), P2PMessageID::Ping => { advance_snappy_ping_pong_payload(buf)?; - Ok(P2PMessage::Ping) + Ok(Self::Ping) } P2PMessageID::Pong => { advance_snappy_ping_pong_payload(buf)?; - Ok(P2PMessage::Pong) + Ok(Self::Pong) } } } @@ -768,10 +768,10 @@ pub enum P2PMessageID { impl From for P2PMessageID { fn from(msg: P2PMessage) -> Self { match msg { - P2PMessage::Hello(_) => P2PMessageID::Hello, - P2PMessage::Disconnect(_) => P2PMessageID::Disconnect, - P2PMessage::Ping => P2PMessageID::Ping, - P2PMessage::Pong => P2PMessageID::Pong, + P2PMessage::Hello(_) => Self::Hello, + P2PMessage::Disconnect(_) => Self::Disconnect, + P2PMessage::Ping => Self::Ping, + P2PMessage::Pong => Self::Pong, } } } @@ -781,10 +781,10 @@ impl TryFrom for P2PMessageID { fn try_from(id: u8) -> Result { match id { - 0x00 => Ok(P2PMessageID::Hello), - 0x01 => Ok(P2PMessageID::Disconnect), - 0x02 => Ok(P2PMessageID::Ping), - 0x03 => Ok(P2PMessageID::Pong), + 0x00 => Ok(Self::Hello), + 0x01 => Ok(Self::Disconnect), + 0x02 => Ok(Self::Ping), + 0x03 => Ok(Self::Pong), _ => Err(P2PStreamError::UnknownReservedMessageId(id)), } } @@ -822,8 +822,8 @@ impl Decodable for ProtocolVersion { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { let version = u8::decode(buf)?; match version { - 4 => Ok(ProtocolVersion::V4), - 5 => Ok(ProtocolVersion::V5), + 4 => Ok(Self::V4), + 5 => Ok(Self::V5), _ => Err(RlpError::Custom("unknown p2p protocol version")), } } diff --git a/crates/net/eth-wire/tests/fuzz_roundtrip.rs b/crates/net/eth-wire/tests/fuzz_roundtrip.rs index 1fc5ea0bf..7bb3b7ad7 100644 --- a/crates/net/eth-wire/tests/fuzz_roundtrip.rs +++ b/crates/net/eth-wire/tests/fuzz_roundtrip.rs @@ -96,7 +96,7 @@ pub mod fuzz_rlp { impl Default for HelloMessageWrapper { fn default() -> Self { - HelloMessageWrapper(HelloMessage { + Self(HelloMessage { client_version: Default::default(), capabilities: Default::default(), protocol_version: Default::default(), @@ -138,7 +138,7 @@ pub mod fuzz_rlp { impl Default for GetBlockHeadersWrapper { fn default() -> Self { - GetBlockHeadersWrapper(GetBlockHeaders { + Self(GetBlockHeaders { start_block: BlockHashOrNumber::Number(0), limit: Default::default(), skip: Default::default(), diff --git a/crates/net/nat/src/lib.rs b/crates/net/nat/src/lib.rs index adc72aa83..33722bb5e 100644 --- a/crates/net/nat/src/lib.rs +++ b/crates/net/nat/src/lib.rs @@ -57,11 +57,11 @@ impl NatResolver { impl fmt::Display for NatResolver { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - NatResolver::Any => f.write_str("any"), - NatResolver::Upnp => f.write_str("upnp"), - NatResolver::PublicIp => f.write_str("publicip"), - NatResolver::ExternalIp(ip) => write!(f, "extip:{ip}"), - NatResolver::None => f.write_str("none"), + Self::Any => f.write_str("any"), + Self::Upnp => f.write_str("upnp"), + Self::PublicIp => f.write_str("publicip"), + Self::ExternalIp(ip) => write!(f, "extip:{ip}"), + Self::None => f.write_str("none"), } } } @@ -82,17 +82,17 @@ impl FromStr for NatResolver { fn from_str(s: &str) -> Result { let r = match s { - "any" => NatResolver::Any, - "upnp" => NatResolver::Upnp, - "none" => NatResolver::None, - "publicip" | "public-ip" => NatResolver::PublicIp, + "any" => Self::Any, + "upnp" => Self::Upnp, + "none" => Self::None, + "publicip" | "public-ip" => Self::PublicIp, s => { let Some(ip) = s.strip_prefix("extip:") else { return Err(ParseNatResolverError::UnknownVariant(format!( "Unknown Nat Resolver: {s}" ))) }; - NatResolver::ExternalIp(ip.parse::()?) + Self::ExternalIp(ip.parse::()?) } }; Ok(r) diff --git a/crates/net/network-api/src/error.rs b/crates/net/network-api/src/error.rs index 457214540..a500c4d48 100644 --- a/crates/net/network-api/src/error.rs +++ b/crates/net/network-api/src/error.rs @@ -11,12 +11,12 @@ pub enum NetworkError { impl From> for NetworkError { fn from(_: mpsc::error::SendError) -> Self { - NetworkError::ChannelClosed + Self::ChannelClosed } } impl From for NetworkError { fn from(_: oneshot::error::RecvError) -> Self { - NetworkError::ChannelClosed + Self::ChannelClosed } } diff --git a/crates/net/network-api/src/lib.rs b/crates/net/network-api/src/lib.rs index 10ffddb6a..c197ecba5 100644 --- a/crates/net/network-api/src/lib.rs +++ b/crates/net/network-api/src/lib.rs @@ -154,12 +154,12 @@ pub enum PeerKind { impl PeerKind { /// Returns `true` if the peer is trusted. pub const fn is_trusted(&self) -> bool { - matches!(self, PeerKind::Trusted) + matches!(self, Self::Trusted) } /// Returns `true` if the peer is basic. pub const fn is_basic(&self) -> bool { - matches!(self, PeerKind::Basic) + matches!(self, Self::Basic) } } @@ -198,20 +198,20 @@ pub enum Direction { impl Direction { /// Returns `true` if this an incoming connection. pub fn is_incoming(&self) -> bool { - matches!(self, Direction::Incoming) + matches!(self, Self::Incoming) } /// Returns `true` if this an outgoing connection. pub fn is_outgoing(&self) -> bool { - matches!(self, Direction::Outgoing(_)) + matches!(self, Self::Outgoing(_)) } } impl std::fmt::Display for Direction { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Direction::Incoming => write!(f, "incoming"), - Direction::Outgoing(_) => write!(f, "outgoing"), + Self::Incoming => write!(f, "incoming"), + Self::Outgoing(_) => write!(f, "outgoing"), } } } diff --git a/crates/net/network/src/builder.rs b/crates/net/network/src/builder.rs index 5fb673707..ed74de94f 100644 --- a/crates/net/network/src/builder.rs +++ b/crates/net/network/src/builder.rs @@ -25,7 +25,7 @@ pub struct NetworkBuilder { impl NetworkBuilder { /// Consumes the type and returns all fields. pub fn split(self) -> (NetworkManager, Tx, Eth) { - let NetworkBuilder { network, transactions, request_handler } = self; + let Self { network, transactions, request_handler } = self; (network, transactions, request_handler) } @@ -46,7 +46,7 @@ impl NetworkBuilder { /// Consumes the type and returns all fields and also return a [`NetworkHandle`]. pub fn split_with_handle(self) -> (NetworkHandle, NetworkManager, Tx, Eth) { - let NetworkBuilder { network, transactions, request_handler } = self; + let Self { network, transactions, request_handler } = self; let handle = network.handle().clone(); (handle, network, transactions, request_handler) } @@ -57,7 +57,7 @@ impl NetworkBuilder { pool: Pool, transactions_manager_config: TransactionsManagerConfig, ) -> NetworkBuilder, Eth> { - let NetworkBuilder { mut network, request_handler, .. } = self; + let Self { mut network, request_handler, .. } = self; let (tx, rx) = mpsc::unbounded_channel(); network.set_transactions(tx); let handle = network.handle().clone(); @@ -70,7 +70,7 @@ impl NetworkBuilder { self, client: Client, ) -> NetworkBuilder> { - let NetworkBuilder { mut network, transactions, .. } = self; + let Self { mut network, transactions, .. } = self; let (tx, rx) = mpsc::channel(ETH_REQUEST_CHANNEL_CAPACITY); network.set_eth_request_handler(tx); let peers = network.handle().peers_handle().clone(); diff --git a/crates/net/network/src/cache.rs b/crates/net/network/src/cache.rs index 2be4180d4..8f33127e7 100644 --- a/crates/net/network/src/cache.rs +++ b/crates/net/network/src/cache.rs @@ -152,7 +152,7 @@ where { /// Returns a new cache with default limiter and hash builder. pub fn new(max_length: u32) -> Self { - LruMap(schnellru::LruMap::new(ByLength::new(max_length))) + Self(schnellru::LruMap::new(ByLength::new(max_length))) } } @@ -162,7 +162,7 @@ where { /// Returns a new cache with [`Unlimited`] limiter and default hash builder. pub fn new_unlimited() -> Self { - LruMap(schnellru::LruMap::new(Unlimited)) + Self(schnellru::LruMap::new(Unlimited)) } } diff --git a/crates/net/network/src/config.rs b/crates/net/network/src/config.rs index 368f958b2..6a5c16777 100644 --- a/crates/net/network/src/config.rs +++ b/crates/net/network/src/config.rs @@ -566,7 +566,7 @@ pub enum NetworkMode { impl NetworkMode { /// Returns true if network has entered proof-of-stake pub fn is_stake(&self) -> bool { - matches!(self, NetworkMode::Stake) + matches!(self, Self::Stake) } } diff --git a/crates/net/network/src/error.rs b/crates/net/network/src/error.rs index 2bfa9f9c1..95cb5c630 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -21,8 +21,8 @@ impl ServiceKind { /// Returns the appropriate flags for each variant. pub fn flags(&self) -> &'static str { match self { - ServiceKind::Listener(_) => "--port", - ServiceKind::Discovery(_) => "--discovery.port", + Self::Listener(_) => "--port", + Self::Discovery(_) => "--discovery.port", } } } @@ -30,8 +30,8 @@ impl ServiceKind { impl fmt::Display for ServiceKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ServiceKind::Listener(addr) => write!(f, "{addr} (listener service)"), - ServiceKind::Discovery(addr) => write!(f, "{addr} (discovery service)"), + Self::Listener(addr) => write!(f, "{addr} (listener service)"), + Self::Discovery(addr) => write!(f, "{addr} (discovery service)"), } } } @@ -67,12 +67,12 @@ impl NetworkError { /// Converts a `std::io::Error` to a more descriptive `NetworkError`. pub fn from_io_error(err: io::Error, kind: ServiceKind) -> Self { match err.kind() { - ErrorKind::AddrInUse => NetworkError::AddressAlreadyInUse { kind, error: err }, + ErrorKind::AddrInUse => Self::AddressAlreadyInUse { kind, error: err }, _ => { if let ServiceKind::Discovery(_) = kind { - return NetworkError::Discovery(err) + return Self::Discovery(err) } - NetworkError::Io(err) + Self::Io(err) } } } @@ -128,27 +128,27 @@ pub enum BackoffKind { impl BackoffKind { /// Returns true if the backoff is considered severe. pub(crate) fn is_severe(&self) -> bool { - matches!(self, BackoffKind::Medium | BackoffKind::High) + matches!(self, Self::Medium | Self::High) } } impl SessionError for EthStreamError { fn merits_discovery_ban(&self) -> bool { match self { - EthStreamError::P2PStreamError(P2PStreamError::HandshakeError( + Self::P2PStreamError(P2PStreamError::HandshakeError( P2PHandshakeError::HelloNotInHandshake, )) | - EthStreamError::P2PStreamError(P2PStreamError::HandshakeError( + Self::P2PStreamError(P2PStreamError::HandshakeError( P2PHandshakeError::NonHelloMessageInHandshake, )) => true, - EthStreamError::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), + Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), _ => false, } } fn is_fatal_protocol_error(&self) -> bool { match self { - EthStreamError::P2PStreamError(err) => { + Self::P2PStreamError(err) => { matches!( err, P2PStreamError::HandshakeError(P2PHandshakeError::NoSharedCapabilities) | @@ -177,7 +177,7 @@ impl SessionError for EthStreamError { P2PStreamError::MismatchedProtocolVersion { .. } ) } - EthStreamError::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), + Self::EthHandshakeError(err) => !matches!(err, EthHandshakeError::NoResponse), _ => false, } } @@ -214,19 +214,17 @@ impl SessionError for EthStreamError { // [`SessionError::is_fatal_protocol_error`] match self { // timeouts - EthStreamError::EthHandshakeError(EthHandshakeError::NoResponse) | - EthStreamError::P2PStreamError(P2PStreamError::HandshakeError( - P2PHandshakeError::NoResponse, - )) | - EthStreamError::P2PStreamError(P2PStreamError::PingTimeout) => Some(BackoffKind::Low), + Self::EthHandshakeError(EthHandshakeError::NoResponse) | + Self::P2PStreamError(P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse)) | + Self::P2PStreamError(P2PStreamError::PingTimeout) => Some(BackoffKind::Low), // malformed messages - EthStreamError::P2PStreamError(P2PStreamError::Rlp(_)) | - EthStreamError::P2PStreamError(P2PStreamError::UnknownReservedMessageId(_)) | - EthStreamError::P2PStreamError(P2PStreamError::UnknownDisconnectReason(_)) | - EthStreamError::P2PStreamError(P2PStreamError::MessageTooBig { .. }) | - EthStreamError::P2PStreamError(P2PStreamError::EmptyProtocolMessage) | - EthStreamError::P2PStreamError(P2PStreamError::PingerError(_)) | - EthStreamError::P2PStreamError(P2PStreamError::Snap(_)) => Some(BackoffKind::Medium), + Self::P2PStreamError(P2PStreamError::Rlp(_)) | + Self::P2PStreamError(P2PStreamError::UnknownReservedMessageId(_)) | + Self::P2PStreamError(P2PStreamError::UnknownDisconnectReason(_)) | + Self::P2PStreamError(P2PStreamError::MessageTooBig { .. }) | + Self::P2PStreamError(P2PStreamError::EmptyProtocolMessage) | + Self::P2PStreamError(P2PStreamError::PingerError(_)) | + Self::P2PStreamError(P2PStreamError::Snap(_)) => Some(BackoffKind::Medium), _ => None, } } @@ -235,25 +233,25 @@ impl SessionError for EthStreamError { impl SessionError for PendingSessionHandshakeError { fn merits_discovery_ban(&self) -> bool { match self { - PendingSessionHandshakeError::Eth(eth) => eth.merits_discovery_ban(), - PendingSessionHandshakeError::Ecies(_) => true, - PendingSessionHandshakeError::Timeout => false, + Self::Eth(eth) => eth.merits_discovery_ban(), + Self::Ecies(_) => true, + Self::Timeout => false, } } fn is_fatal_protocol_error(&self) -> bool { match self { - PendingSessionHandshakeError::Eth(eth) => eth.is_fatal_protocol_error(), - PendingSessionHandshakeError::Ecies(_) => true, - PendingSessionHandshakeError::Timeout => false, + Self::Eth(eth) => eth.is_fatal_protocol_error(), + Self::Ecies(_) => true, + Self::Timeout => false, } } fn should_backoff(&self) -> Option { match self { - PendingSessionHandshakeError::Eth(eth) => eth.should_backoff(), - PendingSessionHandshakeError::Ecies(_) => Some(BackoffKind::Low), - PendingSessionHandshakeError::Timeout => Some(BackoffKind::Medium), + Self::Eth(eth) => eth.should_backoff(), + Self::Ecies(_) => Some(BackoffKind::Low), + Self::Timeout => Some(BackoffKind::Medium), } } } diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index 3a5ebf14b..9844d2f91 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -372,7 +372,7 @@ enum PeerState { impl PeerState { /// Returns true if the peer is currently idle. fn is_idle(&self) -> bool { - matches!(self, PeerState::Idle) + matches!(self, Self::Idle) } /// Resets the state on a received response. @@ -381,8 +381,8 @@ impl PeerState { /// /// Returns `true` if the peer is ready for another request. fn on_request_finished(&mut self) -> bool { - if !matches!(self, PeerState::Closing) { - *self = PeerState::Idle; + if !matches!(self, Self::Closing) { + *self = Self::Idle; return true } false @@ -423,16 +423,16 @@ impl DownloadRequest { /// Returns the corresponding state for a peer that handles the request. fn peer_state(&self) -> PeerState { match self { - DownloadRequest::GetBlockHeaders { .. } => PeerState::GetBlockHeaders, - DownloadRequest::GetBlockBodies { .. } => PeerState::GetBlockBodies, + Self::GetBlockHeaders { .. } => PeerState::GetBlockHeaders, + Self::GetBlockBodies { .. } => PeerState::GetBlockBodies, } } /// Returns the requested priority of this request fn get_priority(&self) -> &Priority { match self { - DownloadRequest::GetBlockHeaders { priority, .. } => priority, - DownloadRequest::GetBlockBodies { priority, .. } => priority, + Self::GetBlockHeaders { priority, .. } => priority, + Self::GetBlockBodies { priority, .. } => priority, } } diff --git a/crates/net/network/src/message.rs b/crates/net/network/src/message.rs index 861fb304e..3a067cbfd 100644 --- a/crates/net/network/src/message.rs +++ b/crates/net/network/src/message.rs @@ -135,33 +135,33 @@ impl PeerRequest { /// Send an error back to the receiver. pub(crate) fn send_err_response(self, err: RequestError) { let _ = match self { - PeerRequest::GetBlockHeaders { response, .. } => response.send(Err(err)).ok(), - PeerRequest::GetBlockBodies { response, .. } => response.send(Err(err)).ok(), - PeerRequest::GetPooledTransactions { response, .. } => response.send(Err(err)).ok(), - PeerRequest::GetNodeData { response, .. } => response.send(Err(err)).ok(), - PeerRequest::GetReceipts { response, .. } => response.send(Err(err)).ok(), + Self::GetBlockHeaders { response, .. } => response.send(Err(err)).ok(), + Self::GetBlockBodies { response, .. } => response.send(Err(err)).ok(), + Self::GetPooledTransactions { response, .. } => response.send(Err(err)).ok(), + Self::GetNodeData { response, .. } => response.send(Err(err)).ok(), + Self::GetReceipts { response, .. } => response.send(Err(err)).ok(), }; } /// Returns the [`EthMessage`] for this type pub fn create_request_message(&self, request_id: u64) -> EthMessage { match self { - PeerRequest::GetBlockHeaders { request, .. } => { + Self::GetBlockHeaders { request, .. } => { EthMessage::GetBlockHeaders(RequestPair { request_id, message: *request }) } - PeerRequest::GetBlockBodies { request, .. } => { + Self::GetBlockBodies { request, .. } => { EthMessage::GetBlockBodies(RequestPair { request_id, message: request.clone() }) } - PeerRequest::GetPooledTransactions { request, .. } => { + Self::GetPooledTransactions { request, .. } => { EthMessage::GetPooledTransactions(RequestPair { request_id, message: request.clone(), }) } - PeerRequest::GetNodeData { request, .. } => { + Self::GetNodeData { request, .. } => { EthMessage::GetNodeData(RequestPair { request_id, message: request.clone() }) } - PeerRequest::GetReceipts { request, .. } => { + Self::GetReceipts { request, .. } => { EthMessage::GetReceipts(RequestPair { request_id, message: request.clone() }) } } @@ -170,7 +170,7 @@ impl PeerRequest { /// Consumes the type and returns the inner [`GetPooledTransactions`] variant. pub fn into_get_pooled_transactions(self) -> Option { match self { - PeerRequest::GetPooledTransactions { request, .. } => Some(request), + Self::GetPooledTransactions { request, .. } => Some(request), _ => None, } } @@ -221,19 +221,19 @@ impl PeerResponse { } let res = match self { - PeerResponse::BlockHeaders { response } => { + Self::BlockHeaders { response } => { poll_request!(response, BlockHeaders, cx) } - PeerResponse::BlockBodies { response } => { + Self::BlockBodies { response } => { poll_request!(response, BlockBodies, cx) } - PeerResponse::PooledTransactions { response } => { + Self::PooledTransactions { response } => { poll_request!(response, PooledTransactions, cx) } - PeerResponse::NodeData { response } => { + Self::NodeData { response } => { poll_request!(response, NodeData, cx) } - PeerResponse::Receipts { response } => { + Self::Receipts { response } => { poll_request!(response, Receipts, cx) } }; @@ -273,19 +273,19 @@ impl PeerResponseResult { }; } match self { - PeerResponseResult::BlockHeaders(resp) => { + Self::BlockHeaders(resp) => { to_message!(resp, BlockHeaders, id) } - PeerResponseResult::BlockBodies(resp) => { + Self::BlockBodies(resp) => { to_message!(resp, BlockBodies, id) } - PeerResponseResult::PooledTransactions(resp) => { + Self::PooledTransactions(resp) => { to_message!(resp, PooledTransactions, id) } - PeerResponseResult::NodeData(resp) => { + Self::NodeData(resp) => { to_message!(resp, NodeData, id) } - PeerResponseResult::Receipts(resp) => { + Self::Receipts(resp) => { to_message!(resp, Receipts, id) } } @@ -294,11 +294,11 @@ impl PeerResponseResult { /// Returns the `Err` value if the result is an error. pub fn err(&self) -> Option<&RequestError> { match self { - PeerResponseResult::BlockHeaders(res) => res.as_ref().err(), - PeerResponseResult::BlockBodies(res) => res.as_ref().err(), - PeerResponseResult::PooledTransactions(res) => res.as_ref().err(), - PeerResponseResult::NodeData(res) => res.as_ref().err(), - PeerResponseResult::Receipts(res) => res.as_ref().err(), + Self::BlockHeaders(res) => res.as_ref().err(), + Self::BlockBodies(res) => res.as_ref().err(), + Self::PooledTransactions(res) => res.as_ref().err(), + Self::NodeData(res) => res.as_ref().err(), + Self::Receipts(res) => res.as_ref().err(), } } diff --git a/crates/net/network/src/peers/manager.rs b/crates/net/network/src/peers/manager.rs index e13b080af..e1ccb13be 100644 --- a/crates/net/network/src/peers/manager.rs +++ b/crates/net/network/src/peers/manager.rs @@ -915,7 +915,7 @@ impl PeersManager { impl Default for PeersManager { fn default() -> Self { - PeersManager::new(Default::default()) + Self::new(Default::default()) } } @@ -1002,7 +1002,7 @@ impl ConnectionInfo { impl Default for ConnectionInfo { fn default() -> Self { - ConnectionInfo { + Self { num_outbound: 0, num_inbound: 0, max_outbound: DEFAULT_MAX_COUNT_PEERS_OUTBOUND as usize, @@ -1161,8 +1161,8 @@ impl PeerConnectionState { #[inline] fn disconnect(&mut self) { match self { - PeerConnectionState::In => *self = PeerConnectionState::DisconnectingIn, - PeerConnectionState::Out => *self = PeerConnectionState::DisconnectingOut, + Self::In => *self = Self::DisconnectingIn, + Self::Out => *self = Self::DisconnectingOut, _ => {} } } @@ -1170,28 +1170,25 @@ impl PeerConnectionState { /// Returns true if this is an active incoming connection. #[inline] fn is_incoming(&self) -> bool { - matches!(self, PeerConnectionState::In) + matches!(self, Self::In) } /// Returns whether we're currently connected with this peer #[inline] fn is_connected(&self) -> bool { - matches!( - self, - PeerConnectionState::In | PeerConnectionState::Out | PeerConnectionState::PendingOut - ) + matches!(self, Self::In | Self::Out | Self::PendingOut) } /// Returns if there's currently no connection to that peer. #[inline] fn is_unconnected(&self) -> bool { - matches!(self, PeerConnectionState::Idle) + matches!(self, Self::Idle) } /// Returns true if there's currently an outbound dial to that peer. #[inline] fn is_pending_out(&self) -> bool { - matches!(self, PeerConnectionState::PendingOut) + matches!(self, Self::PendingOut) } } @@ -1501,7 +1498,7 @@ impl PeerBackoffDurations { /// Returns durations for testing. #[cfg(test)] const fn test() -> Self { - PeerBackoffDurations { + Self { low: Duration::from_millis(200), medium: Duration::from_millis(200), high: Duration::from_millis(200), diff --git a/crates/net/network/src/peers/reputation.rs b/crates/net/network/src/peers/reputation.rs index 1a335adc6..ad87446d0 100644 --- a/crates/net/network/src/peers/reputation.rs +++ b/crates/net/network/src/peers/reputation.rs @@ -135,6 +135,6 @@ impl From for Reputation { impl From for ReputationChange { fn from(value: Reputation) -> Self { - ReputationChange(value) + Self(value) } } diff --git a/crates/net/network/src/session/active.rs b/crates/net/network/src/session/active.rs index ce726a78a..7fed5b311 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -713,8 +713,8 @@ enum OnIncomingMessageOutcome { impl From> for OnIncomingMessageOutcome { fn from(res: Result<(), ActiveSessionMessage>) -> Self { match res { - Ok(_) => OnIncomingMessageOutcome::Ok, - Err(msg) => OnIncomingMessageOutcome::NoCapacity(msg), + Ok(_) => Self::Ok, + Err(msg) => Self::NoCapacity(msg), } } } @@ -736,13 +736,13 @@ pub(crate) enum OutgoingMessage { impl From for OutgoingMessage { fn from(value: EthMessage) -> Self { - OutgoingMessage::Eth(value) + Self::Eth(value) } } impl From for OutgoingMessage { fn from(value: EthBroadcastMessage) -> Self { - OutgoingMessage::Broadcast(value) + Self::Broadcast(value) } } diff --git a/crates/net/network/src/session/config.rs b/crates/net/network/src/session/config.rs index 7c21d232c..e285d2b7a 100644 --- a/crates/net/network/src/session/config.rs +++ b/crates/net/network/src/session/config.rs @@ -57,7 +57,7 @@ pub struct SessionsConfig { impl Default for SessionsConfig { fn default() -> Self { - SessionsConfig { + Self { // This should be sufficient to slots for handling commands sent to the session task, // since the manager is the sender. session_command_buffer: 32, diff --git a/crates/net/network/src/session/mod.rs b/crates/net/network/src/session/mod.rs index 95f426c54..5cbbc0dfe 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -755,7 +755,7 @@ impl PendingSessionHandshakeError { /// Returns the [`DisconnectReason`] if the error is a disconnect message pub fn as_disconnected(&self) -> Option { match self { - PendingSessionHandshakeError::Eth(eth_err) => eth_err.as_disconnected(), + Self::Eth(eth_err) => eth_err.as_disconnected(), _ => None, } } diff --git a/crates/net/network/src/swarm.rs b/crates/net/network/src/swarm.rs index 11ac5949a..729c5ff8a 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -443,11 +443,11 @@ pub enum NetworkConnectionState { impl NetworkConnectionState { /// Returns true if the node is active. pub(crate) fn is_active(&self) -> bool { - matches!(self, NetworkConnectionState::Active) + matches!(self, Self::Active) } /// Returns true if the node is shutting down. pub(crate) fn is_shutting_down(&self) -> bool { - matches!(self, NetworkConnectionState::ShuttingDown) + matches!(self, Self::ShuttingDown) } } diff --git a/crates/net/network/src/test_utils/testnet.rs b/crates/net/network/src/test_utils/testnet.rs index 99c98db55..8fd3ac9c7 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -227,7 +227,7 @@ impl Testnet { /// Creates a new [`Testnet`] with the given number of peers pub async fn try_create(num_peers: usize) -> Result { - let mut this = Testnet::default(); + let mut this = Self::default(); this.extend_peer_with_config((0..num_peers).map(|_| Default::default())).await?; Ok(this) @@ -531,7 +531,7 @@ where { /// Launches the network and returns the [Peer] that manages it pub async fn launch(self) -> Result, NetworkError> { - let PeerConfig { config, client, secret_key } = self; + let Self { config, client, secret_key } = self; let network = NetworkManager::new(config).await?; let peer = Peer { network, diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index e10cee9bd..91ae18442 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -124,7 +124,7 @@ impl TransactionFetcher { /// Sets up transaction fetcher with config pub fn with_transaction_fetcher_config(config: &TransactionFetcherConfig) -> Self { - let mut tx_fetcher = TransactionFetcher::default(); + let mut tx_fetcher = Self::default(); tx_fetcher.info.soft_limit_byte_size_pooled_transactions_response = config.soft_limit_byte_size_pooled_transactions_response; diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index 7a0fe600d..545c6f3bb 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -1437,8 +1437,8 @@ impl PooledTransactionsHashesBuilder { /// Push a transaction from the pool to the list. fn push_pooled(&mut self, pooled_tx: Arc>) { match self { - PooledTransactionsHashesBuilder::Eth66(msg) => msg.0.push(*pooled_tx.hash()), - PooledTransactionsHashesBuilder::Eth68(msg) => { + Self::Eth66(msg) => msg.0.push(*pooled_tx.hash()), + Self::Eth68(msg) => { msg.hashes.push(*pooled_tx.hash()); msg.sizes.push(pooled_tx.encoded_length()); msg.types.push(pooled_tx.transaction.tx_type()); @@ -1448,8 +1448,8 @@ impl PooledTransactionsHashesBuilder { fn push(&mut self, tx: &PropagateTransaction) { match self { - PooledTransactionsHashesBuilder::Eth66(msg) => msg.0.push(tx.hash()), - PooledTransactionsHashesBuilder::Eth68(msg) => { + Self::Eth66(msg) => msg.0.push(tx.hash()), + Self::Eth68(msg) => { msg.hashes.push(tx.hash()); msg.sizes.push(tx.size); msg.types.push(tx.transaction.tx_type().into()); @@ -1460,17 +1460,15 @@ impl PooledTransactionsHashesBuilder { /// Create a builder for the negotiated version of the peer's session fn new(version: EthVersion) -> Self { match version { - EthVersion::Eth66 | EthVersion::Eth67 => { - PooledTransactionsHashesBuilder::Eth66(Default::default()) - } - EthVersion::Eth68 => PooledTransactionsHashesBuilder::Eth68(Default::default()), + EthVersion::Eth66 | EthVersion::Eth67 => Self::Eth66(Default::default()), + EthVersion::Eth68 => Self::Eth68(Default::default()), } } fn build(self) -> NewPooledTransactionHashes { match self { - PooledTransactionsHashesBuilder::Eth66(msg) => msg.into(), - PooledTransactionsHashesBuilder::Eth68(msg) => msg.into(), + Self::Eth66(msg) => msg.into(), + Self::Eth68(msg) => msg.into(), } } } @@ -1488,7 +1486,7 @@ enum TransactionSource { impl TransactionSource { /// Whether the transaction were sent as broadcast. fn is_broadcast(&self) -> bool { - matches!(self, TransactionSource::Broadcast) + matches!(self, Self::Broadcast) } } diff --git a/crates/net/p2p/src/bodies/response.rs b/crates/net/p2p/src/bodies/response.rs index 2b32b7009..741745a43 100644 --- a/crates/net/p2p/src/bodies/response.rs +++ b/crates/net/p2p/src/bodies/response.rs @@ -13,8 +13,8 @@ impl BlockResponse { /// Return the reference to the response header pub fn header(&self) -> &SealedHeader { match self { - BlockResponse::Full(block) => &block.header, - BlockResponse::Empty(header) => header, + Self::Full(block) => &block.header, + Self::Empty(header) => header, } } @@ -22,8 +22,8 @@ impl BlockResponse { #[inline] pub fn size(&self) -> usize { match self { - BlockResponse::Full(block) => SealedBlock::size(block), - BlockResponse::Empty(header) => SealedHeader::size(header), + Self::Full(block) => SealedBlock::size(block), + Self::Empty(header) => SealedHeader::size(header), } } @@ -35,8 +35,8 @@ impl BlockResponse { /// Return the reference to the response header pub fn difficulty(&self) -> U256 { match self { - BlockResponse::Full(block) => block.difficulty, - BlockResponse::Empty(header) => header.difficulty, + Self::Full(block) => block.difficulty, + Self::Empty(header) => header.difficulty, } } } diff --git a/crates/net/p2p/src/either.rs b/crates/net/p2p/src/either.rs index 36e95d487..e8017e880 100644 --- a/crates/net/p2p/src/either.rs +++ b/crates/net/p2p/src/either.rs @@ -17,14 +17,14 @@ where { fn report_bad_message(&self, peer_id: reth_network_types::PeerId) { match self { - Either::Left(a) => a.report_bad_message(peer_id), - Either::Right(b) => b.report_bad_message(peer_id), + Self::Left(a) => a.report_bad_message(peer_id), + Self::Right(b) => b.report_bad_message(peer_id), } } fn num_connected_peers(&self) -> usize { match self { - Either::Left(a) => a.num_connected_peers(), - Either::Right(b) => b.num_connected_peers(), + Self::Left(a) => a.num_connected_peers(), + Self::Right(b) => b.num_connected_peers(), } } } @@ -42,8 +42,8 @@ where priority: Priority, ) -> Self::Output { match self { - Either::Left(a) => Either::Left(a.get_block_bodies_with_priority(hashes, priority)), - Either::Right(b) => Either::Right(b.get_block_bodies_with_priority(hashes, priority)), + Self::Left(a) => Either::Left(a.get_block_bodies_with_priority(hashes, priority)), + Self::Right(b) => Either::Right(b.get_block_bodies_with_priority(hashes, priority)), } } } @@ -61,8 +61,8 @@ where priority: Priority, ) -> Self::Output { match self { - Either::Left(a) => Either::Left(a.get_headers_with_priority(request, priority)), - Either::Right(b) => Either::Right(b.get_headers_with_priority(request, priority)), + Self::Left(a) => Either::Left(a.get_headers_with_priority(request, priority)), + Self::Right(b) => Either::Right(b.get_headers_with_priority(request, priority)), } } } diff --git a/crates/net/p2p/src/error.rs b/crates/net/p2p/src/error.rs index 3bd469e60..450d8ce97 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -105,24 +105,24 @@ pub enum RequestError { impl RequestError { /// Indicates whether this error is retryable or fatal. pub fn is_retryable(&self) -> bool { - matches!(self, RequestError::Timeout | RequestError::ConnectionDropped) + matches!(self, Self::Timeout | Self::ConnectionDropped) } /// Whether the error happened because the channel was closed. pub fn is_channel_closed(&self) -> bool { - matches!(self, RequestError::ChannelClosed) + matches!(self, Self::ChannelClosed) } } impl From> for RequestError { fn from(_: mpsc::error::SendError) -> Self { - RequestError::ChannelClosed + Self::ChannelClosed } } impl From for RequestError { fn from(_: oneshot::error::RecvError) -> Self { - RequestError::ChannelClosed + Self::ChannelClosed } } diff --git a/crates/net/p2p/src/headers/downloader.rs b/crates/net/p2p/src/headers/downloader.rs index b52a84877..16d5c1af8 100644 --- a/crates/net/p2p/src/headers/downloader.rs +++ b/crates/net/p2p/src/headers/downloader.rs @@ -61,9 +61,9 @@ impl SyncTarget { /// header in [SyncTarget::Gap] pub fn tip(&self) -> BlockHashOrNumber { match self { - SyncTarget::Tip(tip) => (*tip).into(), - SyncTarget::Gap(gap) => gap.parent_hash.into(), - SyncTarget::TipNum(num) => (*num).into(), + Self::Tip(tip) => (*tip).into(), + Self::Gap(gap) => gap.parent_hash.into(), + Self::TipNum(num) => (*num).into(), } } } diff --git a/crates/net/p2p/src/priority.rs b/crates/net/p2p/src/priority.rs index 5932b4496..38be9ead4 100644 --- a/crates/net/p2p/src/priority.rs +++ b/crates/net/p2p/src/priority.rs @@ -12,11 +12,11 @@ pub enum Priority { impl Priority { /// Returns `true` if this is [Priority::High] pub fn is_high(&self) -> bool { - matches!(self, Priority::High) + matches!(self, Self::High) } /// Returns `true` if this is [Priority::Normal] pub fn is_normal(&self) -> bool { - matches!(self, Priority::Normal) + matches!(self, Self::Normal) } } diff --git a/crates/net/p2p/src/sync.rs b/crates/net/p2p/src/sync.rs index 729271b57..5b3dd62e3 100644 --- a/crates/net/p2p/src/sync.rs +++ b/crates/net/p2p/src/sync.rs @@ -45,7 +45,7 @@ impl SyncState { /// /// Note: this does not include keep-up sync when the state is idle. pub fn is_syncing(&self) -> bool { - !matches!(self, SyncState::Idle) + !matches!(self, Self::Idle) } } diff --git a/crates/net/types/src/lib.rs b/crates/net/types/src/lib.rs index e4b9f28a4..dfcd4a5c2 100644 --- a/crates/net/types/src/lib.rs +++ b/crates/net/types/src/lib.rs @@ -68,17 +68,17 @@ impl AnyNode { /// Returns the peer id of the node. pub fn peer_id(&self) -> PeerId { match self { - AnyNode::NodeRecord(record) => record.id, - AnyNode::Enr(enr) => pk2id(&enr.public_key()), - AnyNode::PeerId(peer_id) => *peer_id, + Self::NodeRecord(record) => record.id, + Self::Enr(enr) => pk2id(&enr.public_key()), + Self::PeerId(peer_id) => *peer_id, } } /// Returns the full node record if available. pub fn node_record(&self) -> Option { match self { - AnyNode::NodeRecord(record) => Some(*record), - AnyNode::Enr(enr) => { + Self::NodeRecord(record) => Some(*record), + Self::Enr(enr) => { let node_record = NodeRecord { address: enr.ip4().map(IpAddr::from).or_else(|| enr.ip6().map(IpAddr::from))?, tcp_port: enr.tcp4().or_else(|| enr.tcp6())?, @@ -111,11 +111,11 @@ 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(AnyNode::NodeRecord(record)) + return Ok(Self::NodeRecord(record)) } // incomplete enode if let Ok(peer_id) = PeerId::from_str(rem) { - return Ok(AnyNode::PeerId(peer_id)) + return Ok(Self::PeerId(peer_id)) } return Err(format!("invalid public key: {rem}")) } @@ -129,9 +129,9 @@ impl FromStr for AnyNode { impl std::fmt::Display for AnyNode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - AnyNode::NodeRecord(record) => write!(f, "{record}"), - AnyNode::Enr(enr) => write!(f, "{enr}"), - AnyNode::PeerId(peer_id) => { + Self::NodeRecord(record) => write!(f, "{record}"), + Self::Enr(enr) => write!(f, "{enr}"), + Self::PeerId(peer_id) => { write!(f, "enode://{}", alloy_primitives::hex::encode(peer_id.as_slice())) } } diff --git a/crates/net/types/src/node_record.rs b/crates/net/types/src/node_record.rs index 5a6706201..f16d43dd1 100644 --- a/crates/net/types/src/node_record.rs +++ b/crates/net/types/src/node_record.rs @@ -189,7 +189,7 @@ impl TryFrom<&Enr> for NodeRecord { let id = pk2id(&enr.public_key()); - Ok(NodeRecord { address, tcp_port, udp_port, id }.into_ipv4_mapped()) + Ok(Self { address, tcp_port, udp_port, id }.into_ipv4_mapped()) } } diff --git a/crates/node-core/src/args/log.rs b/crates/node-core/src/args/log.rs index e5475e269..b7e69e663 100644 --- a/crates/node-core/src/args/log.rs +++ b/crates/node-core/src/args/log.rs @@ -127,9 +127,9 @@ pub enum ColorMode { impl Display for ColorMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ColorMode::Always => write!(f, "always"), - ColorMode::Auto => write!(f, "auto"), - ColorMode::Never => write!(f, "never"), + Self::Always => write!(f, "always"), + Self::Auto => write!(f, "auto"), + Self::Never => write!(f, "never"), } } } diff --git a/crates/node-core/src/cli/config.rs b/crates/node-core/src/cli/config.rs index 6e5d1f6a2..0fb8fbf41 100644 --- a/crates/node-core/src/cli/config.rs +++ b/crates/node-core/src/cli/config.rs @@ -122,7 +122,7 @@ pub trait RethNetworkConfig { impl RethNetworkConfig for reth_network::NetworkManager { fn add_rlpx_sub_protocol(&mut self, protocol: impl IntoRlpxSubProtocol) { - reth_network::NetworkManager::add_rlpx_sub_protocol(self, protocol); + Self::add_rlpx_sub_protocol(self, protocol); } fn secret_key(&self) -> secp256k1::SecretKey { diff --git a/crates/node-core/src/dirs.rs b/crates/node-core/src/dirs.rs index b33df18f2..86f6a3fd5 100644 --- a/crates/node-core/src/dirs.rs +++ b/crates/node-core/src/dirs.rs @@ -148,8 +148,8 @@ impl From> for PathBuf { impl PlatformPath { /// Returns the path joined with another path - pub fn join>(&self, path: P) -> PlatformPath { - PlatformPath::(self.0.join(path), std::marker::PhantomData) + pub fn join>(&self, path: P) -> Self { + Self(self.0.join(path), std::marker::PhantomData) } } @@ -161,7 +161,7 @@ impl PlatformPath { let path = self.0.join(chain_name); - let platform_path = PlatformPath::(path, std::marker::PhantomData); + let platform_path = Self(path, std::marker::PhantomData); ChainPath::new(platform_path, chain) } diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index c28e43579..3fd29085e 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -164,7 +164,7 @@ impl NodeBuilder { self, task_executor: TaskExecutor, data_dir: ChainPath, - ) -> WithLaunchContext> { + ) -> WithLaunchContext { WithLaunchContext { builder: self, task_executor, data_dir } } diff --git a/crates/node/events/src/node.rs b/crates/node/events/src/node.rs index 8c01c0a73..87da96a31 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -398,38 +398,38 @@ pub enum NodeEvent { } impl From for NodeEvent { - fn from(event: NetworkEvent) -> NodeEvent { - NodeEvent::Network(event) + fn from(event: NetworkEvent) -> Self { + Self::Network(event) } } impl From for NodeEvent { - fn from(event: PipelineEvent) -> NodeEvent { - NodeEvent::Pipeline(event) + fn from(event: PipelineEvent) -> Self { + Self::Pipeline(event) } } impl From for NodeEvent { fn from(event: BeaconConsensusEngineEvent) -> Self { - NodeEvent::ConsensusEngine(event) + Self::ConsensusEngine(event) } } impl From for NodeEvent { fn from(event: ConsensusLayerHealthEvent) -> Self { - NodeEvent::ConsensusLayerHealth(event) + Self::ConsensusLayerHealth(event) } } impl From for NodeEvent { fn from(event: PrunerEvent) -> Self { - NodeEvent::Pruner(event) + Self::Pruner(event) } } impl From for NodeEvent { fn from(event: StaticFileProducerEvent) -> Self { - NodeEvent::StaticFileProducer(event) + Self::StaticFileProducer(event) } } diff --git a/crates/optimism/evm/src/error.rs b/crates/optimism/evm/src/error.rs index 1041f30c8..57958b5ec 100644 --- a/crates/optimism/evm/src/error.rs +++ b/crates/optimism/evm/src/error.rs @@ -24,6 +24,6 @@ pub enum OptimismBlockExecutionError { impl From for BlockExecutionError { fn from(err: OptimismBlockExecutionError) -> Self { - BlockExecutionError::other(err) + Self::other(err) } } diff --git a/crates/optimism/node/src/rpc.rs b/crates/optimism/node/src/rpc.rs index 515e1d8eb..d3d004a19 100644 --- a/crates/optimism/node/src/rpc.rs +++ b/crates/optimism/node/src/rpc.rs @@ -35,7 +35,7 @@ impl ToRpcError for SequencerRpcError { impl From for EthApiError { fn from(err: SequencerRpcError) -> Self { - EthApiError::other(err) + Self::other(err) } } @@ -108,7 +108,7 @@ impl SequencerClient { #[async_trait::async_trait] impl RawTransactionForwarder for SequencerClient { async fn forward_raw_transaction(&self, tx: &[u8]) -> EthResult<()> { - SequencerClient::forward_raw_transaction(self, tx).await?; + Self::forward_raw_transaction(self, tx).await?; Ok(()) } } diff --git a/crates/optimism/payload/src/payload.rs b/crates/optimism/payload/src/payload.rs index 738246bf8..0314bcc84 100644 --- a/crates/optimism/payload/src/payload.rs +++ b/crates/optimism/payload/src/payload.rs @@ -239,10 +239,7 @@ impl From for ExecutionPayloadEnvelopeV2 { fn from(value: OptimismBuiltPayload) -> Self { let OptimismBuiltPayload { block, fees, .. } = value; - ExecutionPayloadEnvelopeV2 { - block_value: fees, - execution_payload: convert_block_to_payload_field_v2(block), - } + Self { block_value: fees, execution_payload: convert_block_to_payload_field_v2(block) } } } @@ -256,7 +253,7 @@ impl From for OptimismExecutionPayloadEnvelopeV3 { } else { B256::ZERO }; - OptimismExecutionPayloadEnvelopeV3 { + Self { execution_payload: block_to_payload_v3(block).0, block_value: fees, // From the engine API spec: @@ -283,7 +280,7 @@ impl From for OptimismExecutionPayloadEnvelopeV4 { } else { B256::ZERO }; - OptimismExecutionPayloadEnvelopeV4 { + Self { execution_payload: block_to_payload_v4(block), block_value: fees, // From the engine API spec: diff --git a/crates/payload/builder/src/error.rs b/crates/payload/builder/src/error.rs index af95b279b..a7aa7e88b 100644 --- a/crates/payload/builder/src/error.rs +++ b/crates/payload/builder/src/error.rs @@ -37,18 +37,18 @@ impl PayloadBuilderError { where E: std::error::Error + Send + Sync + 'static, { - PayloadBuilderError::Other(Box::new(error)) + Self::Other(Box::new(error)) } } impl From for PayloadBuilderError { fn from(error: ProviderError) -> Self { - PayloadBuilderError::Internal(RethError::Provider(error)) + Self::Internal(RethError::Provider(error)) } } impl From for PayloadBuilderError { fn from(_: oneshot::error::RecvError) -> Self { - PayloadBuilderError::ChannelClosed + Self::ChannelClosed } } diff --git a/crates/payload/builder/src/service.rs b/crates/payload/builder/src/service.rs index 81d3445b0..5228083ab 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -479,17 +479,17 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PayloadServiceCommand::BuildNewPayload(f0, f1) => { + Self::BuildNewPayload(f0, f1) => { f.debug_tuple("BuildNewPayload").field(&f0).field(&f1).finish() } - PayloadServiceCommand::BestPayload(f0, f1) => { + Self::BestPayload(f0, f1) => { f.debug_tuple("BestPayload").field(&f0).field(&f1).finish() } - PayloadServiceCommand::PayloadAttributes(f0, f1) => { + Self::PayloadAttributes(f0, f1) => { f.debug_tuple("PayloadAttributes").field(&f0).field(&f1).finish() } - PayloadServiceCommand::Resolve(f0, _f1) => f.debug_tuple("Resolve").field(&f0).finish(), - PayloadServiceCommand::Subscribe(f0) => f.debug_tuple("Subscribe").field(&f0).finish(), + Self::Resolve(f0, _f1) => f.debug_tuple("Resolve").field(&f0).finish(), + Self::Subscribe(f0) => f.debug_tuple("Subscribe").field(&f0).finish(), } } } diff --git a/crates/primitives/benches/integer_list.rs b/crates/primitives/benches/integer_list.rs index 56b0e9e38..8ce985d13 100644 --- a/crates/primitives/benches/integer_list.rs +++ b/crates/primitives/benches/integer_list.rs @@ -212,7 +212,7 @@ mod elias_fano { } impl<'de> Deserialize<'de> for IntegerList { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { diff --git a/crates/primitives/src/account.rs b/crates/primitives/src/account.rs index 78e796147..1bc691ec1 100644 --- a/crates/primitives/src/account.rs +++ b/crates/primitives/src/account.rs @@ -38,7 +38,7 @@ impl Account { /// Makes an [Account] from [GenesisAccount] type pub fn from_genesis_account(value: &GenesisAccount) -> Self { - Account { + Self { // nonce must exist, so we default to zero when converting a genesis account nonce: value.nonce.unwrap_or_default(), balance: value.balance, @@ -115,9 +115,9 @@ impl Compact for Bytecode { let bytes = Bytes::from(buf.copy_to_bytes(len as usize)); let variant = buf.read_u8().expect("could not read bytecode variant"); let decoded = match variant { - 0 => Bytecode(RevmBytecode::new_raw(bytes)), + 0 => Self(RevmBytecode::new_raw(bytes)), 1 => unreachable!("Junk data in database: checked Bytecode variant was removed"), - 2 => Bytecode(unsafe { + 2 => Self(unsafe { RevmBytecode::new_analyzed( bytes, buf.read_u64::().unwrap() as usize, diff --git a/crates/primitives/src/alloy_compat.rs b/crates/primitives/src/alloy_compat.rs index bd68860d2..b1b75f4db 100644 --- a/crates/primitives/src/alloy_compat.rs +++ b/crates/primitives/src/alloy_compat.rs @@ -122,7 +122,7 @@ impl TryFrom for Transaction { .into(), )) } - Ok(Transaction::Legacy(TxLegacy { + Ok(Self::Legacy(TxLegacy { chain_id: tx.chain_id, nonce: tx.nonce, gas_price: tx.gas_price.ok_or(ConversionError::MissingGasPrice)?, @@ -137,7 +137,7 @@ impl TryFrom for Transaction { } Some(TxType::Eip2930) => { // eip2930 - Ok(Transaction::Eip2930(TxEip2930 { + Ok(Self::Eip2930(TxEip2930 { chain_id: tx.chain_id.ok_or(ConversionError::MissingChainId)?, nonce: tx.nonce, gas_limit: tx @@ -153,7 +153,7 @@ impl TryFrom for Transaction { } Some(TxType::Eip1559) => { // EIP-1559 - Ok(Transaction::Eip1559(TxEip1559 { + Ok(Self::Eip1559(TxEip1559 { chain_id: tx.chain_id.ok_or(ConversionError::MissingChainId)?, nonce: tx.nonce, max_priority_fee_per_gas: tx @@ -174,7 +174,7 @@ impl TryFrom for Transaction { } Some(TxType::Eip4844) => { // EIP-4844 - Ok(Transaction::Eip4844(TxEip4844 { + Ok(Self::Eip4844(TxEip4844 { chain_id: tx.chain_id.ok_or(ConversionError::MissingChainId)?, nonce: tx.nonce, max_priority_fee_per_gas: tx @@ -215,7 +215,7 @@ impl TryFrom for TransactionSigned { let signature = tx.signature.ok_or(ConversionError::MissingSignature)?; let transaction: Transaction = tx.try_into()?; - Ok(TransactionSigned::from_transaction_and_signature( + Ok(Self::from_transaction_and_signature( transaction.clone(), Signature { r: signature.r, diff --git a/crates/primitives/src/chain/info.rs b/crates/primitives/src/chain/info.rs index fb954345b..38b73e276 100644 --- a/crates/primitives/src/chain/info.rs +++ b/crates/primitives/src/chain/info.rs @@ -11,6 +11,6 @@ pub struct ChainInfo { impl From for BlockNumHash { fn from(value: ChainInfo) -> Self { - BlockNumHash { number: value.best_number, hash: value.best_hash } + Self { number: value.best_number, hash: value.best_hash } } } diff --git a/crates/primitives/src/chain/spec.rs b/crates/primitives/src/chain/spec.rs index 3c166b2c7..e90b314e4 100644 --- a/crates/primitives/src/chain/spec.rs +++ b/crates/primitives/src/chain/spec.rs @@ -468,13 +468,13 @@ pub enum BaseFeeParamsKind { impl From for BaseFeeParamsKind { fn from(params: BaseFeeParams) -> Self { - BaseFeeParamsKind::Constant(params) + Self::Constant(params) } } impl From for BaseFeeParamsKind { fn from(params: ForkBaseFeeParams) -> Self { - BaseFeeParamsKind::Variable(params) + Self::Variable(params) } } @@ -485,7 +485,7 @@ pub struct ForkBaseFeeParams(Vec<(Hardfork, BaseFeeParams)>); impl From> for ForkBaseFeeParams { fn from(params: Vec<(Hardfork, BaseFeeParams)>) -> Self { - ForkBaseFeeParams(params) + Self(params) } } @@ -533,8 +533,8 @@ pub struct ChainSpec { } impl Default for ChainSpec { - fn default() -> ChainSpec { - ChainSpec { + fn default() -> Self { + Self { chain: Default::default(), genesis_hash: Default::default(), genesis: Default::default(), @@ -1347,7 +1347,7 @@ pub enum ForkCondition { impl ForkCondition { /// Returns true if the fork condition is timestamp based. pub fn is_timestamp(&self) -> bool { - matches!(self, ForkCondition::Timestamp(_)) + matches!(self, Self::Timestamp(_)) } /// Checks whether the fork condition is satisfied at the given block. @@ -1356,15 +1356,15 @@ impl ForkCondition { /// /// For timestamp conditions, this will always return false. pub fn active_at_block(&self, current_block: BlockNumber) -> bool { - matches!(self, ForkCondition::Block(block) - | ForkCondition::TTD { fork_block: Some(block), .. } if current_block >= *block) + 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 fn transitions_at_block(&self, current_block: BlockNumber) -> bool { - matches!(self, ForkCondition::Block(block) if current_block == *block) + matches!(self, Self::Block(block) if current_block == *block) } /// Checks whether the fork condition is satisfied at the given total difficulty and difficulty @@ -1377,7 +1377,7 @@ impl ForkCondition { /// /// 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, ForkCondition::TTD { total_difficulty, .. } + matches!(self, Self::TTD { total_difficulty, .. } if ttd.saturating_sub(difficulty) >= *total_difficulty) } @@ -1385,7 +1385,7 @@ impl ForkCondition { /// /// This will return false for any condition that is not timestamp-based. pub fn active_at_timestamp(&self, timestamp: u64) -> bool { - matches!(self, ForkCondition::Timestamp(time) if timestamp >= *time) + matches!(self, Self::Timestamp(time) if timestamp >= *time) } /// Checks whether the fork condition is satisfied at the given head block. @@ -1406,7 +1406,7 @@ impl ForkCondition { /// Returns `None` for fork conditions that are not TTD based. pub fn ttd(&self) -> Option { match self { - ForkCondition::TTD { total_difficulty, .. } => Some(*total_difficulty), + Self::TTD { total_difficulty, .. } => Some(*total_difficulty), _ => None, } } @@ -1414,7 +1414,7 @@ impl ForkCondition { /// Returns the timestamp of the fork condition, if it is timestamp based. pub fn as_timestamp(&self) -> Option { match self { - ForkCondition::Timestamp(timestamp) => Some(*timestamp), + Self::Timestamp(timestamp) => Some(*timestamp), _ => None, } } @@ -1602,7 +1602,7 @@ pub struct DepositContract { impl DepositContract { fn new(address: Address, block: BlockNumber, topic: B256) -> Self { - DepositContract { address, block, topic } + Self { address, block, topic } } } diff --git a/crates/primitives/src/header.rs b/crates/primitives/src/header.rs index b9574785a..7f48921fb 100644 --- a/crates/primitives/src/header.rs +++ b/crates/primitives/src/header.rs @@ -111,7 +111,7 @@ pub struct Header { impl Default for Header { fn default() -> Self { - Header { + Self { parent_hash: Default::default(), ommers_hash: EMPTY_OMMER_ROOT_HASH, beneficiary: Default::default(), @@ -674,7 +674,7 @@ impl SealedHeader { #[inline(always)] fn validate_gas_limit( &self, - parent: &SealedHeader, + parent: &Self, chain_spec: &ChainSpec, ) -> Result<(), HeaderValidationError> { // Determine the parent gas limit, considering elasticity multiplier on the London fork. @@ -739,7 +739,7 @@ impl SealedHeader { /// of certain features (e.g., Optimism feature) or the activation of specific hardforks. pub fn validate_against_parent( &self, - parent: &SealedHeader, + parent: &Self, chain_spec: &ChainSpec, ) -> Result<(), HeaderValidationError> { // Parent number is consistent. @@ -826,7 +826,7 @@ impl SealedHeader { /// parent header fields. pub fn validate_4844_header_against_parent( &self, - parent: &SealedHeader, + parent: &Self, ) -> Result<(), HeaderValidationError> { // From [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844#header-extension): // @@ -885,7 +885,7 @@ impl proptest::arbitrary::Arbitrary for SealedHeader { // map valid header strategy by sealing valid_header_strategy().prop_map(|header| header.seal_slow()).boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } #[cfg(any(test, feature = "arbitrary"))] @@ -971,12 +971,12 @@ pub enum HeadersDirection { impl HeadersDirection { /// Returns true for rising block numbers pub fn is_rising(&self) -> bool { - matches!(self, HeadersDirection::Rising) + matches!(self, Self::Rising) } /// Returns true for falling block numbers pub fn is_falling(&self) -> bool { - matches!(self, HeadersDirection::Falling) + matches!(self, Self::Falling) } /// Converts the bool into a direction. @@ -987,9 +987,9 @@ impl HeadersDirection { /// [`HeadersDirection::Falling`] block numbers for `reverse == 1 == true` pub fn new(reverse: bool) -> Self { if reverse { - HeadersDirection::Falling + Self::Falling } else { - HeadersDirection::Rising + Self::Rising } } } diff --git a/crates/primitives/src/integer_list.rs b/crates/primitives/src/integer_list.rs index edcf31086..33ddae452 100644 --- a/crates/primitives/src/integer_list.rs +++ b/crates/primitives/src/integer_list.rs @@ -123,7 +123,7 @@ impl<'de> Visitor<'de> for IntegerListVisitor { } impl<'de> Deserialize<'de> for IntegerList { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { diff --git a/crates/primitives/src/log.rs b/crates/primitives/src/log.rs index 628a20f83..b2b6b8a48 100644 --- a/crates/primitives/src/log.rs +++ b/crates/primitives/src/log.rs @@ -51,8 +51,8 @@ mod tests { } impl From for AlloyLog { - fn from(log: Log) -> AlloyLog { - AlloyLog::new_unchecked(log.address, log.topics, log.data) + fn from(log: Log) -> Self { + Self::new_unchecked(log.address, log.topics, log.data) } } diff --git a/crates/primitives/src/prune/mode.rs b/crates/primitives/src/prune/mode.rs index 3454573b9..46d38aa71 100644 --- a/crates/primitives/src/prune/mode.rs +++ b/crates/primitives/src/prune/mode.rs @@ -29,16 +29,16 @@ impl PruneMode { tip: BlockNumber, segment: PruneSegment, purpose: PrunePurpose, - ) -> Result, PruneSegmentError> { + ) -> Result, PruneSegmentError> { let result = match self { - PruneMode::Full if segment.min_blocks(purpose) == 0 => Some((tip, *self)), - PruneMode::Distance(distance) if *distance > tip => None, // Nothing to prune yet - PruneMode::Distance(distance) if *distance >= segment.min_blocks(purpose) => { + Self::Full if segment.min_blocks(purpose) == 0 => Some((tip, *self)), + Self::Distance(distance) if *distance > tip => None, // Nothing to prune yet + Self::Distance(distance) if *distance >= segment.min_blocks(purpose) => { Some((tip - distance, *self)) } - PruneMode::Before(n) if *n == tip + 1 && purpose.is_static_file() => Some((tip, *self)), - PruneMode::Before(n) if *n > tip => None, // Nothing to prune yet - PruneMode::Before(n) if tip - n >= segment.min_blocks(purpose) => Some((n - 1, *self)), + Self::Before(n) if *n == tip + 1 && purpose.is_static_file() => Some((tip, *self)), + Self::Before(n) if *n > tip => None, // Nothing to prune yet + Self::Before(n) if tip - n >= segment.min_blocks(purpose) => Some((n - 1, *self)), _ => return Err(PruneSegmentError::Configuration(segment)), }; Ok(result) @@ -47,14 +47,14 @@ impl PruneMode { /// Check if target block should be pruned according to the provided prune mode and tip. pub fn should_prune(&self, block: BlockNumber, tip: BlockNumber) -> bool { match self { - PruneMode::Full => true, - PruneMode::Distance(distance) => { + Self::Full => true, + Self::Distance(distance) => { if *distance > tip { return false } block < tip - *distance } - PruneMode::Before(n) => *n > block, + Self::Before(n) => *n > block, } } diff --git a/crates/primitives/src/prune/target.rs b/crates/primitives/src/prune/target.rs index 7f39c8d74..255976531 100644 --- a/crates/primitives/src/prune/target.rs +++ b/crates/primitives/src/prune/target.rs @@ -48,7 +48,7 @@ pub struct PruneModes { impl PruneModes { /// Sets pruning to no target. pub fn none() -> Self { - PruneModes::default() + Self::default() } /// Sets pruning to all targets. diff --git a/crates/primitives/src/receipt.rs b/crates/primitives/src/receipt.rs index 85470cb2e..1e9a2ac1f 100644 --- a/crates/primitives/src/receipt.rs +++ b/crates/primitives/src/receipt.rs @@ -157,7 +157,7 @@ impl FromIterator>> for Receipts { impl From for ReceiptWithBloom { fn from(receipt: Receipt) -> Self { let bloom = receipt.bloom_slow(); - ReceiptWithBloom { receipt, bloom } + Self { receipt, bloom } } } @@ -245,7 +245,7 @@ impl proptest::arbitrary::Arbitrary for Receipt { arbitrary_receipt().boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } #[cfg(any(test, feature = "arbitrary"))] diff --git a/crates/primitives/src/stage/checkpoints.rs b/crates/primitives/src/stage/checkpoints.rs index d9c10605c..a82a77dee 100644 --- a/crates/primitives/src/stage/checkpoints.rs +++ b/crates/primitives/src/stage/checkpoints.rs @@ -71,7 +71,7 @@ impl Compact for MerkleCheckpoint { } let (state, buf) = HashBuilderState::from_compact(buf, 0); - (MerkleCheckpoint { target_block, last_account_key, walker_stack, state }, buf) + (Self { target_block, last_account_key, walker_stack, state }, buf) } } diff --git a/crates/primitives/src/stage/id.rs b/crates/primitives/src/stage/id.rs index 2779c2608..f6b8508e0 100644 --- a/crates/primitives/src/stage/id.rs +++ b/crates/primitives/src/stage/id.rs @@ -38,66 +38,66 @@ pub enum StageId { impl StageId { /// All supported Stages - pub const ALL: [StageId; 12] = [ - StageId::Headers, - StageId::Bodies, - StageId::SenderRecovery, - StageId::Execution, - StageId::MerkleUnwind, - StageId::AccountHashing, - StageId::StorageHashing, - StageId::MerkleExecute, - StageId::TransactionLookup, - StageId::IndexStorageHistory, - StageId::IndexAccountHistory, - StageId::Finish, + pub const ALL: [Self; 12] = [ + Self::Headers, + Self::Bodies, + Self::SenderRecovery, + Self::Execution, + Self::MerkleUnwind, + Self::AccountHashing, + Self::StorageHashing, + Self::MerkleExecute, + Self::TransactionLookup, + Self::IndexStorageHistory, + Self::IndexAccountHistory, + Self::Finish, ]; /// Stages that require state. - pub const STATE_REQUIRED: [StageId; 7] = [ - StageId::Execution, - StageId::MerkleUnwind, - StageId::AccountHashing, - StageId::StorageHashing, - StageId::MerkleExecute, - StageId::IndexStorageHistory, - StageId::IndexAccountHistory, + pub const STATE_REQUIRED: [Self; 7] = [ + Self::Execution, + Self::MerkleUnwind, + Self::AccountHashing, + Self::StorageHashing, + Self::MerkleExecute, + Self::IndexStorageHistory, + Self::IndexAccountHistory, ]; /// Return stage id formatted as string. pub fn as_str(&self) -> &str { match self { #[allow(deprecated)] - StageId::StaticFile => "StaticFile", - StageId::Headers => "Headers", - StageId::Bodies => "Bodies", - StageId::SenderRecovery => "SenderRecovery", - StageId::Execution => "Execution", - StageId::MerkleUnwind => "MerkleUnwind", - StageId::AccountHashing => "AccountHashing", - StageId::StorageHashing => "StorageHashing", - StageId::MerkleExecute => "MerkleExecute", - StageId::TransactionLookup => "TransactionLookup", - StageId::IndexAccountHistory => "IndexAccountHistory", - StageId::IndexStorageHistory => "IndexStorageHistory", - StageId::Finish => "Finish", - StageId::Other(s) => s, + Self::StaticFile => "StaticFile", + Self::Headers => "Headers", + Self::Bodies => "Bodies", + Self::SenderRecovery => "SenderRecovery", + Self::Execution => "Execution", + Self::MerkleUnwind => "MerkleUnwind", + Self::AccountHashing => "AccountHashing", + Self::StorageHashing => "StorageHashing", + Self::MerkleExecute => "MerkleExecute", + Self::TransactionLookup => "TransactionLookup", + Self::IndexAccountHistory => "IndexAccountHistory", + Self::IndexStorageHistory => "IndexStorageHistory", + Self::Finish => "Finish", + Self::Other(s) => s, } } /// Returns true if it's a downloading stage [StageId::Headers] or [StageId::Bodies] pub fn is_downloading_stage(&self) -> bool { - matches!(self, StageId::Headers | StageId::Bodies) + matches!(self, Self::Headers | Self::Bodies) } /// Returns `true` if it's [TransactionLookup](StageId::TransactionLookup) stage. pub fn is_tx_lookup(&self) -> bool { - matches!(self, StageId::TransactionLookup) + matches!(self, Self::TransactionLookup) } /// Returns true indicating if it's the finish stage [StageId::Finish] pub fn is_finish(&self) -> bool { - matches!(self, StageId::Finish) + matches!(self, Self::Finish) } } diff --git a/crates/primitives/src/stage/mod.rs b/crates/primitives/src/stage/mod.rs index 3c7c972bc..9976cf575 100644 --- a/crates/primitives/src/stage/mod.rs +++ b/crates/primitives/src/stage/mod.rs @@ -29,8 +29,8 @@ impl PipelineTarget { /// - `None`: If the target is for backward unwinding. pub fn sync_target(self) -> Option { match self { - PipelineTarget::Sync(hash) => Some(hash), - PipelineTarget::Unwind(_) => None, + Self::Sync(hash) => Some(hash), + Self::Unwind(_) => None, } } @@ -42,8 +42,8 @@ impl PipelineTarget { /// - `None`: If the target is for forward synchronization. pub fn unwind_target(self) -> Option { match self { - PipelineTarget::Sync(_) => None, - PipelineTarget::Unwind(number) => Some(number), + Self::Sync(_) => None, + Self::Unwind(number) => Some(number), } } } diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index f53405d08..68c87a034 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -141,36 +141,36 @@ impl Transaction { /// It is only for signature signing or signer recovery. pub fn signature_hash(&self) -> B256 { match self { - Transaction::Legacy(tx) => tx.signature_hash(), - Transaction::Eip2930(tx) => tx.signature_hash(), - Transaction::Eip1559(tx) => tx.signature_hash(), - Transaction::Eip4844(tx) => tx.signature_hash(), + Self::Legacy(tx) => tx.signature_hash(), + Self::Eip2930(tx) => tx.signature_hash(), + Self::Eip1559(tx) => tx.signature_hash(), + Self::Eip4844(tx) => tx.signature_hash(), #[cfg(feature = "optimism")] - Transaction::Deposit(_) => B256::ZERO, + Self::Deposit(_) => B256::ZERO, } } /// Get chain_id. pub fn chain_id(&self) -> Option { match self { - Transaction::Legacy(TxLegacy { chain_id, .. }) => *chain_id, - Transaction::Eip2930(TxEip2930 { chain_id, .. }) | - Transaction::Eip1559(TxEip1559 { chain_id, .. }) | - Transaction::Eip4844(TxEip4844 { chain_id, .. }) => Some(*chain_id), + Self::Legacy(TxLegacy { chain_id, .. }) => *chain_id, + Self::Eip2930(TxEip2930 { chain_id, .. }) | + Self::Eip1559(TxEip1559 { chain_id, .. }) | + Self::Eip4844(TxEip4844 { chain_id, .. }) => Some(*chain_id), #[cfg(feature = "optimism")] - Transaction::Deposit(_) => None, + Self::Deposit(_) => None, } } /// Sets the transaction's chain id to the provided value. pub fn set_chain_id(&mut self, chain_id: u64) { match self { - Transaction::Legacy(TxLegacy { chain_id: ref mut c, .. }) => *c = Some(chain_id), - Transaction::Eip2930(TxEip2930 { chain_id: ref mut c, .. }) | - Transaction::Eip1559(TxEip1559 { chain_id: ref mut c, .. }) | - Transaction::Eip4844(TxEip4844 { chain_id: ref mut c, .. }) => *c = chain_id, + Self::Legacy(TxLegacy { chain_id: ref mut c, .. }) => *c = Some(chain_id), + Self::Eip2930(TxEip2930 { chain_id: ref mut c, .. }) | + Self::Eip1559(TxEip1559 { chain_id: ref mut c, .. }) | + Self::Eip4844(TxEip4844 { chain_id: ref mut c, .. }) => *c = chain_id, #[cfg(feature = "optimism")] - Transaction::Deposit(_) => { /* noop */ } + Self::Deposit(_) => { /* noop */ } } } @@ -178,12 +178,12 @@ impl Transaction { /// [`TxKind::Create`] if the transaction is a contract creation. pub fn kind(&self) -> TxKind { match self { - Transaction::Legacy(TxLegacy { to, .. }) | - Transaction::Eip2930(TxEip2930 { to, .. }) | - Transaction::Eip1559(TxEip1559 { to, .. }) => *to, - Transaction::Eip4844(TxEip4844 { to, .. }) => TxKind::Call(*to), + Self::Legacy(TxLegacy { to, .. }) | + Self::Eip2930(TxEip2930 { to, .. }) | + Self::Eip1559(TxEip1559 { to, .. }) => *to, + Self::Eip4844(TxEip4844 { to, .. }) => TxKind::Call(*to), #[cfg(feature = "optimism")] - Transaction::Deposit(TxDeposit { to, .. }) => *to, + Self::Deposit(TxDeposit { to, .. }) => *to, } } @@ -198,37 +198,37 @@ impl Transaction { /// Get the transaction's type pub fn tx_type(&self) -> TxType { match self { - Transaction::Legacy(legacy_tx) => legacy_tx.tx_type(), - Transaction::Eip2930(access_list_tx) => access_list_tx.tx_type(), - Transaction::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.tx_type(), - Transaction::Eip4844(blob_tx) => blob_tx.tx_type(), + Self::Legacy(legacy_tx) => legacy_tx.tx_type(), + Self::Eip2930(access_list_tx) => access_list_tx.tx_type(), + Self::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.tx_type(), + Self::Eip4844(blob_tx) => blob_tx.tx_type(), #[cfg(feature = "optimism")] - Transaction::Deposit(deposit_tx) => deposit_tx.tx_type(), + Self::Deposit(deposit_tx) => deposit_tx.tx_type(), } } /// Gets the transaction's value field. pub fn value(&self) -> U256 { *match self { - Transaction::Legacy(TxLegacy { value, .. }) | - Transaction::Eip2930(TxEip2930 { value, .. }) | - Transaction::Eip1559(TxEip1559 { value, .. }) | - Transaction::Eip4844(TxEip4844 { value, .. }) => value, + Self::Legacy(TxLegacy { value, .. }) | + Self::Eip2930(TxEip2930 { value, .. }) | + Self::Eip1559(TxEip1559 { value, .. }) | + Self::Eip4844(TxEip4844 { value, .. }) => value, #[cfg(feature = "optimism")] - Transaction::Deposit(TxDeposit { value, .. }) => value, + Self::Deposit(TxDeposit { value, .. }) => value, } } /// Get the transaction's nonce. pub fn nonce(&self) -> u64 { match self { - Transaction::Legacy(TxLegacy { nonce, .. }) | - Transaction::Eip2930(TxEip2930 { nonce, .. }) | - Transaction::Eip1559(TxEip1559 { nonce, .. }) | - Transaction::Eip4844(TxEip4844 { nonce, .. }) => *nonce, + Self::Legacy(TxLegacy { nonce, .. }) | + Self::Eip2930(TxEip2930 { nonce, .. }) | + Self::Eip1559(TxEip1559 { nonce, .. }) | + Self::Eip4844(TxEip4844 { nonce, .. }) => *nonce, // Deposit transactions do not have nonces. #[cfg(feature = "optimism")] - Transaction::Deposit(_) => 0, + Self::Deposit(_) => 0, } } @@ -237,34 +237,34 @@ impl Transaction { /// Returns `None` for legacy transactions. pub fn access_list(&self) -> Option<&AccessList> { match self { - Transaction::Legacy(_) => None, - Transaction::Eip2930(tx) => Some(&tx.access_list), - Transaction::Eip1559(tx) => Some(&tx.access_list), - Transaction::Eip4844(tx) => Some(&tx.access_list), + Self::Legacy(_) => None, + Self::Eip2930(tx) => Some(&tx.access_list), + Self::Eip1559(tx) => Some(&tx.access_list), + Self::Eip4844(tx) => Some(&tx.access_list), #[cfg(feature = "optimism")] - Transaction::Deposit(_) => None, + Self::Deposit(_) => None, } } /// Get the gas limit of the transaction. pub fn gas_limit(&self) -> u64 { match self { - Transaction::Legacy(TxLegacy { gas_limit, .. }) | - Transaction::Eip2930(TxEip2930 { gas_limit, .. }) | - Transaction::Eip1559(TxEip1559 { gas_limit, .. }) | - Transaction::Eip4844(TxEip4844 { gas_limit, .. }) => *gas_limit, + Self::Legacy(TxLegacy { gas_limit, .. }) | + Self::Eip2930(TxEip2930 { gas_limit, .. }) | + Self::Eip1559(TxEip1559 { gas_limit, .. }) | + Self::Eip4844(TxEip4844 { gas_limit, .. }) => *gas_limit, #[cfg(feature = "optimism")] - Transaction::Deposit(TxDeposit { gas_limit, .. }) => *gas_limit, + Self::Deposit(TxDeposit { gas_limit, .. }) => *gas_limit, } } /// Returns true if the tx supports dynamic fees pub fn is_dynamic_fee(&self) -> bool { match self { - Transaction::Legacy(_) | Transaction::Eip2930(_) => false, - Transaction::Eip1559(_) | Transaction::Eip4844(_) => true, + Self::Legacy(_) | Self::Eip2930(_) => false, + Self::Eip1559(_) | Self::Eip4844(_) => true, #[cfg(feature = "optimism")] - Transaction::Deposit(_) => false, + Self::Deposit(_) => false, } } @@ -273,14 +273,14 @@ impl Transaction { /// This is also commonly referred to as the "Gas Fee Cap" (`GasFeeCap`). pub fn max_fee_per_gas(&self) -> u128 { match self { - Transaction::Legacy(TxLegacy { gas_price, .. }) | - Transaction::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, - Transaction::Eip1559(TxEip1559 { max_fee_per_gas, .. }) | - Transaction::Eip4844(TxEip4844 { max_fee_per_gas, .. }) => *max_fee_per_gas, + Self::Legacy(TxLegacy { gas_price, .. }) | + Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, + Self::Eip1559(TxEip1559 { max_fee_per_gas, .. }) | + Self::Eip4844(TxEip4844 { max_fee_per_gas, .. }) => *max_fee_per_gas, // Deposit transactions buy their L2 gas on L1 and, as such, the L2 gas is not // refundable. #[cfg(feature = "optimism")] - Transaction::Deposit(_) => 0, + Self::Deposit(_) => 0, } } @@ -290,13 +290,13 @@ impl Transaction { /// This is also commonly referred to as the "Gas Tip Cap" (`GasTipCap`). pub fn max_priority_fee_per_gas(&self) -> Option { match self { - Transaction::Legacy(_) | Transaction::Eip2930(_) => None, - Transaction::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) | - Transaction::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => { + Self::Legacy(_) | Self::Eip2930(_) => None, + Self::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) | + Self::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => { Some(*max_priority_fee_per_gas) } #[cfg(feature = "optimism")] - Transaction::Deposit(_) => None, + Self::Deposit(_) => None, } } @@ -306,12 +306,12 @@ impl Transaction { /// This is also commonly referred to as the "blob versioned hashes" (`BlobVersionedHashes`). pub fn blob_versioned_hashes(&self) -> Option> { match self { - Transaction::Legacy(_) | Transaction::Eip2930(_) | Transaction::Eip1559(_) => None, - Transaction::Eip4844(TxEip4844 { blob_versioned_hashes, .. }) => { + Self::Legacy(_) | Self::Eip2930(_) | Self::Eip1559(_) => None, + Self::Eip4844(TxEip4844 { blob_versioned_hashes, .. }) => { Some(blob_versioned_hashes.to_vec()) } #[cfg(feature = "optimism")] - Transaction::Deposit(_) => None, + Self::Deposit(_) => None, } } @@ -322,9 +322,7 @@ impl Transaction { /// This is also commonly referred to as the "Blob Gas Fee Cap" (`BlobGasFeeCap`). pub fn max_fee_per_blob_gas(&self) -> Option { match self { - Transaction::Eip4844(TxEip4844 { max_fee_per_blob_gas, .. }) => { - Some(*max_fee_per_blob_gas) - } + Self::Eip4844(TxEip4844 { max_fee_per_blob_gas, .. }) => Some(*max_fee_per_blob_gas), _ => None, } } @@ -347,14 +345,12 @@ impl Transaction { /// non-EIP-1559 transactions. pub fn priority_fee_or_price(&self) -> u128 { match self { - Transaction::Legacy(TxLegacy { gas_price, .. }) | - Transaction::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, - Transaction::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) | - Transaction::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => { - *max_priority_fee_per_gas - } + Self::Legacy(TxLegacy { gas_price, .. }) | + Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, + Self::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) | + Self::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => *max_priority_fee_per_gas, #[cfg(feature = "optimism")] - Transaction::Deposit(_) => 0, + Self::Deposit(_) => 0, } } @@ -363,12 +359,12 @@ impl Transaction { /// If the transaction is a legacy or EIP2930 transaction, the gas price is returned. pub fn effective_gas_price(&self, base_fee: Option) -> u128 { match self { - Transaction::Legacy(tx) => tx.gas_price, - Transaction::Eip2930(tx) => tx.gas_price, - Transaction::Eip1559(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee), - Transaction::Eip4844(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee), + Self::Legacy(tx) => tx.gas_price, + Self::Eip2930(tx) => tx.gas_price, + Self::Eip1559(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee), + Self::Eip4844(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee), #[cfg(feature = "optimism")] - Transaction::Deposit(_) => 0, + Self::Deposit(_) => 0, } } @@ -406,12 +402,12 @@ impl Transaction { /// Get the transaction's input field. pub fn input(&self) -> &Bytes { match self { - Transaction::Legacy(TxLegacy { input, .. }) | - Transaction::Eip2930(TxEip2930 { input, .. }) | - Transaction::Eip1559(TxEip1559 { input, .. }) | - Transaction::Eip4844(TxEip4844 { input, .. }) => input, + Self::Legacy(TxLegacy { input, .. }) | + Self::Eip2930(TxEip2930 { input, .. }) | + Self::Eip1559(TxEip1559 { input, .. }) | + Self::Eip4844(TxEip4844 { input, .. }) => input, #[cfg(feature = "optimism")] - Transaction::Deposit(TxDeposit { input, .. }) => input, + Self::Deposit(TxDeposit { input, .. }) => input, } } @@ -420,7 +416,7 @@ impl Transaction { #[cfg(feature = "optimism")] pub fn source_hash(&self) -> Option { match self { - Transaction::Deposit(TxDeposit { source_hash, .. }) => Some(*source_hash), + Self::Deposit(TxDeposit { source_hash, .. }) => Some(*source_hash), _ => None, } } @@ -430,7 +426,7 @@ impl Transaction { #[cfg(feature = "optimism")] pub fn mint(&self) -> Option { match self { - Transaction::Deposit(TxDeposit { mint, .. }) => *mint, + Self::Deposit(TxDeposit { mint, .. }) => *mint, _ => None, } } @@ -440,7 +436,7 @@ impl Transaction { #[cfg(feature = "optimism")] pub fn is_system_transaction(&self) -> bool { match self { - Transaction::Deposit(TxDeposit { is_system_transaction, .. }) => *is_system_transaction, + Self::Deposit(TxDeposit { is_system_transaction, .. }) => *is_system_transaction, _ => false, } } @@ -448,7 +444,7 @@ impl Transaction { /// Returns whether or not the transaction is an Optimism Deposited transaction. #[cfg(feature = "optimism")] pub fn is_deposit(&self) -> bool { - matches!(self, Transaction::Deposit(_)) + matches!(self, Self::Deposit(_)) } /// This encodes the transaction _without_ the signature, and is only suitable for creating a @@ -466,57 +462,55 @@ impl Transaction { with_header: bool, ) { match self { - Transaction::Legacy(legacy_tx) => { + Self::Legacy(legacy_tx) => { // do nothing w/ with_header legacy_tx.encode_with_signature(signature, out) } - Transaction::Eip2930(access_list_tx) => { + Self::Eip2930(access_list_tx) => { access_list_tx.encode_with_signature(signature, out, with_header) } - Transaction::Eip1559(dynamic_fee_tx) => { + Self::Eip1559(dynamic_fee_tx) => { dynamic_fee_tx.encode_with_signature(signature, out, with_header) } - Transaction::Eip4844(blob_tx) => { - blob_tx.encode_with_signature(signature, out, with_header) - } + Self::Eip4844(blob_tx) => blob_tx.encode_with_signature(signature, out, with_header), #[cfg(feature = "optimism")] - Transaction::Deposit(deposit_tx) => deposit_tx.encode(out, with_header), + Self::Deposit(deposit_tx) => deposit_tx.encode(out, with_header), } } /// This sets the transaction's nonce. pub fn set_nonce(&mut self, nonce: u64) { match self { - Transaction::Legacy(tx) => tx.nonce = nonce, - Transaction::Eip2930(tx) => tx.nonce = nonce, - Transaction::Eip1559(tx) => tx.nonce = nonce, - Transaction::Eip4844(tx) => tx.nonce = nonce, + Self::Legacy(tx) => tx.nonce = nonce, + Self::Eip2930(tx) => tx.nonce = nonce, + Self::Eip1559(tx) => tx.nonce = nonce, + Self::Eip4844(tx) => tx.nonce = nonce, #[cfg(feature = "optimism")] - Transaction::Deposit(_) => { /* noop */ } + Self::Deposit(_) => { /* noop */ } } } /// This sets the transaction's value. pub fn set_value(&mut self, value: U256) { match self { - Transaction::Legacy(tx) => tx.value = value, - Transaction::Eip2930(tx) => tx.value = value, - Transaction::Eip1559(tx) => tx.value = value, - Transaction::Eip4844(tx) => tx.value = value, + Self::Legacy(tx) => tx.value = value, + Self::Eip2930(tx) => tx.value = value, + Self::Eip1559(tx) => tx.value = value, + Self::Eip4844(tx) => tx.value = value, #[cfg(feature = "optimism")] - Transaction::Deposit(tx) => tx.value = value, + Self::Deposit(tx) => tx.value = value, } } /// This sets the transaction's input field. pub fn set_input(&mut self, input: Bytes) { match self { - Transaction::Legacy(tx) => tx.input = input, - Transaction::Eip2930(tx) => tx.input = input, - Transaction::Eip1559(tx) => tx.input = input, - Transaction::Eip4844(tx) => tx.input = input, + Self::Legacy(tx) => tx.input = input, + Self::Eip2930(tx) => tx.input = input, + Self::Eip1559(tx) => tx.input = input, + Self::Eip4844(tx) => tx.input = input, #[cfg(feature = "optimism")] - Transaction::Deposit(tx) => tx.input = input, + Self::Deposit(tx) => tx.input = input, } } @@ -524,43 +518,43 @@ impl Transaction { #[inline] pub fn size(&self) -> usize { match self { - Transaction::Legacy(tx) => tx.size(), - Transaction::Eip2930(tx) => tx.size(), - Transaction::Eip1559(tx) => tx.size(), - Transaction::Eip4844(tx) => tx.size(), + Self::Legacy(tx) => tx.size(), + Self::Eip2930(tx) => tx.size(), + Self::Eip1559(tx) => tx.size(), + Self::Eip4844(tx) => tx.size(), #[cfg(feature = "optimism")] - Transaction::Deposit(tx) => tx.size(), + Self::Deposit(tx) => tx.size(), } } /// Returns true if the transaction is a legacy transaction. #[inline] pub const fn is_legacy(&self) -> bool { - matches!(self, Transaction::Legacy(_)) + matches!(self, Self::Legacy(_)) } /// Returns true if the transaction is an EIP-2930 transaction. #[inline] pub const fn is_eip2930(&self) -> bool { - matches!(self, Transaction::Eip2930(_)) + matches!(self, Self::Eip2930(_)) } /// Returns true if the transaction is an EIP-1559 transaction. #[inline] pub const fn is_eip1559(&self) -> bool { - matches!(self, Transaction::Eip1559(_)) + matches!(self, Self::Eip1559(_)) } /// Returns true if the transaction is an EIP-4844 transaction. #[inline] pub const fn is_eip4844(&self) -> bool { - matches!(self, Transaction::Eip4844(_)) + matches!(self, Self::Eip4844(_)) } /// Returns the [TxLegacy] variant if the transaction is a legacy transaction. pub fn as_legacy(&self) -> Option<&TxLegacy> { match self { - Transaction::Legacy(tx) => Some(tx), + Self::Legacy(tx) => Some(tx), _ => None, } } @@ -568,7 +562,7 @@ impl Transaction { /// Returns the [TxEip2930] variant if the transaction is an EIP-2930 transaction. pub fn as_eip2930(&self) -> Option<&TxEip2930> { match self { - Transaction::Eip2930(tx) => Some(tx), + Self::Eip2930(tx) => Some(tx), _ => None, } } @@ -576,7 +570,7 @@ impl Transaction { /// Returns the [TxEip1559] variant if the transaction is an EIP-1559 transaction. pub fn as_eip1559(&self) -> Option<&TxEip1559> { match self { - Transaction::Eip1559(tx) => Some(tx), + Self::Eip1559(tx) => Some(tx), _ => None, } } @@ -584,7 +578,7 @@ impl Transaction { /// Returns the [TxEip4844] variant if the transaction is an EIP-4844 transaction. pub fn as_eip4844(&self) -> Option<&TxEip4844> { match self { - Transaction::Eip4844(tx) => Some(tx), + Self::Eip4844(tx) => Some(tx), _ => None, } } @@ -592,25 +586,25 @@ impl Transaction { impl From for Transaction { fn from(tx: TxLegacy) -> Self { - Transaction::Legacy(tx) + Self::Legacy(tx) } } impl From for Transaction { fn from(tx: TxEip2930) -> Self { - Transaction::Eip2930(tx) + Self::Eip2930(tx) } } impl From for Transaction { fn from(tx: TxEip1559) -> Self { - Transaction::Eip1559(tx) + Self::Eip1559(tx) } } impl From for Transaction { fn from(tx: TxEip4844) -> Self { - Transaction::Eip4844(tx) + Self::Eip4844(tx) } } @@ -623,20 +617,20 @@ impl Compact for Transaction { { let identifier = self.tx_type().to_compact(buf); match self { - Transaction::Legacy(tx) => { + Self::Legacy(tx) => { tx.to_compact(buf); } - Transaction::Eip2930(tx) => { + Self::Eip2930(tx) => { tx.to_compact(buf); } - Transaction::Eip1559(tx) => { + Self::Eip1559(tx) => { tx.to_compact(buf); } - Transaction::Eip4844(tx) => { + Self::Eip4844(tx) => { tx.to_compact(buf); } #[cfg(feature = "optimism")] - Transaction::Deposit(tx) => { + Self::Deposit(tx) => { tx.to_compact(buf); } } @@ -655,15 +649,15 @@ impl Compact for Transaction { match identifier { 0 => { let (tx, buf) = TxLegacy::from_compact(buf, buf.len()); - (Transaction::Legacy(tx), buf) + (Self::Legacy(tx), buf) } 1 => { let (tx, buf) = TxEip2930::from_compact(buf, buf.len()); - (Transaction::Eip2930(tx), buf) + (Self::Eip2930(tx), buf) } 2 => { let (tx, buf) = TxEip1559::from_compact(buf, buf.len()); - (Transaction::Eip1559(tx), buf) + (Self::Eip1559(tx), buf) } 3 => { // An identifier of 3 indicates that the transaction type did not fit into @@ -675,12 +669,12 @@ impl Compact for Transaction { match identifier { 3 => { let (tx, buf) = TxEip4844::from_compact(buf, buf.len()); - (Transaction::Eip4844(tx), buf) + (Self::Eip4844(tx), buf) } #[cfg(feature = "optimism")] 126 => { let (tx, buf) = TxDeposit::from_compact(buf, buf.len()); - (Transaction::Deposit(tx), buf) + (Self::Deposit(tx), buf) } _ => unreachable!("Junk data in database: unknown Transaction variant"), } @@ -701,20 +695,20 @@ impl Encodable for Transaction { /// hash intended for signing. fn encode(&self, out: &mut dyn bytes::BufMut) { match self { - Transaction::Legacy(legacy_tx) => { + Self::Legacy(legacy_tx) => { legacy_tx.encode_for_signing(out); } - Transaction::Eip2930(access_list_tx) => { + Self::Eip2930(access_list_tx) => { access_list_tx.encode_for_signing(out); } - Transaction::Eip1559(dynamic_fee_tx) => { + Self::Eip1559(dynamic_fee_tx) => { dynamic_fee_tx.encode_for_signing(out); } - Transaction::Eip4844(blob_tx) => { + Self::Eip4844(blob_tx) => { blob_tx.encode_for_signing(out); } #[cfg(feature = "optimism")] - Transaction::Deposit(deposit_tx) => { + Self::Deposit(deposit_tx) => { deposit_tx.encode(out, true); } } @@ -722,12 +716,12 @@ impl Encodable for Transaction { fn length(&self) -> usize { match self { - Transaction::Legacy(legacy_tx) => legacy_tx.payload_len_for_signature(), - Transaction::Eip2930(access_list_tx) => access_list_tx.payload_len_for_signature(), - Transaction::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.payload_len_for_signature(), - Transaction::Eip4844(blob_tx) => blob_tx.payload_len_for_signature(), + Self::Legacy(legacy_tx) => legacy_tx.payload_len_for_signature(), + Self::Eip2930(access_list_tx) => access_list_tx.payload_len_for_signature(), + Self::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.payload_len_for_signature(), + Self::Eip4844(blob_tx) => blob_tx.payload_len_for_signature(), #[cfg(feature = "optimism")] - Transaction::Deposit(deposit_tx) => deposit_tx.payload_len(), + Self::Deposit(deposit_tx) => deposit_tx.payload_len(), } } } @@ -892,7 +886,7 @@ impl Compact for TransactionSignedNoHash { Transaction::from_compact(buf, transaction_type) }; - (TransactionSignedNoHash { signature, transaction }, buf) + (Self { signature, transaction }, buf) } } @@ -962,7 +956,7 @@ impl From for TransactionSigned { impl From for TransactionSignedNoHash { fn from(tx: TransactionSigned) -> Self { - TransactionSignedNoHash { signature: tx.signature, transaction: tx.transaction } + Self { signature: tx.signature, transaction: tx.transaction } } } @@ -1245,11 +1239,9 @@ impl TransactionSigned { /// This expects `rlp(legacy_tx)` // TODO: make buf advancement semantics consistent with `decode_enveloped_typed_transaction`, // so decoding methods do not need to manually advance the buffer - pub fn decode_rlp_legacy_transaction(data: &mut &[u8]) -> alloy_rlp::Result { - let (transaction, hash, signature) = - TransactionSigned::decode_rlp_legacy_transaction_tuple(data)?; - let signed = - TransactionSigned { transaction: Transaction::Legacy(transaction), hash, signature }; + pub fn decode_rlp_legacy_transaction(data: &mut &[u8]) -> alloy_rlp::Result { + let (transaction, hash, signature) = Self::decode_rlp_legacy_transaction_tuple(data)?; + let signed = Self { transaction: Transaction::Legacy(transaction), hash, signature }; Ok(signed) } @@ -1263,9 +1255,7 @@ impl TransactionSigned { /// byte indicating the transaction type. /// /// CAUTION: this expects that `data` is `tx-type || rlp(tx-data)` - pub fn decode_enveloped_typed_transaction( - data: &mut &[u8], - ) -> alloy_rlp::Result { + pub fn decode_enveloped_typed_transaction(data: &mut &[u8]) -> alloy_rlp::Result { // keep this around so we can use it to calculate the hash let original_encoding_without_header = *data; @@ -1313,7 +1303,7 @@ impl TransactionSigned { } let hash = keccak256(&original_encoding_without_header[..tx_length]); - let signed = TransactionSigned { transaction, hash, signature }; + let signed = Self { transaction, hash, signature }; Ok(signed) } @@ -1342,9 +1332,9 @@ impl TransactionSigned { // Check if the tx is a list let output_data = if input_data[0] >= EMPTY_LIST_CODE { // decode as legacy transaction - TransactionSigned::decode_rlp_legacy_transaction(input_data)? + Self::decode_rlp_legacy_transaction(input_data)? } else { - TransactionSigned::decode_enveloped_typed_transaction(input_data)? + Self::decode_enveloped_typed_transaction(input_data)? }; if !input_data.is_empty() { @@ -1437,7 +1427,7 @@ impl Decodable for TransactionSigned { // if the transaction is encoded as a string then it is a typed transaction if !header.list { - let tx = TransactionSigned::decode_enveloped_typed_transaction(buf)?; + let tx = Self::decode_enveloped_typed_transaction(buf)?; let bytes_consumed = remaining_len - buf.len(); // because Header::decode works for single bytes (including the tx type), returning a @@ -1449,7 +1439,7 @@ impl Decodable for TransactionSigned { Ok(tx) } else { - let tx = TransactionSigned::decode_rlp_legacy_transaction(&mut original_encoding)?; + let tx = Self::decode_rlp_legacy_transaction(&mut original_encoding)?; // advance the buffer based on how far `decode_rlp_legacy_transaction` advanced the // buffer @@ -1483,15 +1473,14 @@ impl proptest::arbitrary::Arbitrary for TransactionSigned { if tx_eip_4844.to != Address::default() { Some(()) } else { None }; } - let mut tx = - TransactionSigned { hash: Default::default(), signature: sig, transaction }; + let mut tx = Self { hash: Default::default(), signature: sig, transaction }; tx.hash = tx.recalculate_hash(); tx }) .boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } #[cfg(any(test, feature = "arbitrary"))] @@ -1512,7 +1501,7 @@ impl<'a> arbitrary::Arbitrary<'a> for TransactionSigned { signature }; - Ok(TransactionSigned::from_transaction_and_signature(transaction, signature)) + Ok(Self::from_transaction_and_signature(transaction, signature)) } } @@ -1575,7 +1564,7 @@ impl Decodable for TransactionSignedEcRecovered { let signer = signed_transaction .recover_signer() .ok_or(RlpError::Custom("Unable to recover decoded transaction signer."))?; - Ok(TransactionSignedEcRecovered { signer, signed_transaction }) + Ok(Self { signer, signed_transaction }) } } diff --git a/crates/primitives/src/transaction/pooled.rs b/crates/primitives/src/transaction/pooled.rs index 8323de470..0c39c5251 100644 --- a/crates/primitives/src/transaction/pooled.rs +++ b/crates/primitives/src/transaction/pooled.rs @@ -58,13 +58,13 @@ impl PooledTransactionsElement { pub fn try_from_broadcast(tx: TransactionSigned) -> Result { match tx { TransactionSigned { transaction: Transaction::Legacy(tx), signature, hash } => { - Ok(PooledTransactionsElement::Legacy { transaction: tx, signature, hash }) + Ok(Self::Legacy { transaction: tx, signature, hash }) } TransactionSigned { transaction: Transaction::Eip2930(tx), signature, hash } => { - Ok(PooledTransactionsElement::Eip2930 { transaction: tx, signature, hash }) + Ok(Self::Eip2930 { transaction: tx, signature, hash }) } TransactionSigned { transaction: Transaction::Eip1559(tx), signature, hash } => { - Ok(PooledTransactionsElement::Eip1559 { transaction: tx, signature, hash }) + Ok(Self::Eip1559 { transaction: tx, signature, hash }) } // Not supported because missing blob sidecar tx @ TransactionSigned { transaction: Transaction::Eip4844(_), .. } => Err(tx), @@ -87,12 +87,7 @@ impl PooledTransactionsElement { // If the transaction is an EIP-4844 transaction... TransactionSigned { transaction: Transaction::Eip4844(tx), signature, hash } => { // Construct a `PooledTransactionsElement::BlobTransaction` with provided sidecar. - PooledTransactionsElement::BlobTransaction(BlobTransaction { - transaction: tx, - signature, - hash, - sidecar, - }) + Self::BlobTransaction(BlobTransaction { transaction: tx, signature, hash, sidecar }) } // If the transaction is not EIP-4844, return an error with the original // transaction. @@ -114,10 +109,10 @@ impl PooledTransactionsElement { /// Reference to transaction hash. Used to identify transaction. pub fn hash(&self) -> &TxHash { match self { - PooledTransactionsElement::Legacy { hash, .. } | - PooledTransactionsElement::Eip2930 { hash, .. } | - PooledTransactionsElement::Eip1559 { hash, .. } => hash, - PooledTransactionsElement::BlobTransaction(tx) => &tx.hash, + Self::Legacy { hash, .. } | Self::Eip2930 { hash, .. } | Self::Eip1559 { hash, .. } => { + hash + } + Self::BlobTransaction(tx) => &tx.hash, } } @@ -215,7 +210,7 @@ impl PooledTransactionsElement { // Now, we decode the inner blob transaction: // `rlp([[chain_id, nonce, ...], blobs, commitments, proofs])` let blob_tx = BlobTransaction::decode_inner(data)?; - Ok(PooledTransactionsElement::BlobTransaction(blob_tx)) + Ok(Self::BlobTransaction(blob_tx)) } else { // DO NOT advance the buffer for the type, since we want the enveloped decoding to // decode it again and advance the buffer on its own. @@ -230,12 +225,12 @@ impl PooledTransactionsElement { Transaction::Eip4844(_) => Err(RlpError::Custom( "EIP-4844 transactions can only be decoded with transaction type 0x03", )), - Transaction::Eip2930(tx) => Ok(PooledTransactionsElement::Eip2930 { + Transaction::Eip2930(tx) => Ok(Self::Eip2930 { transaction: tx, signature: typed_tx.signature, hash: typed_tx.hash, }), - Transaction::Eip1559(tx) => Ok(PooledTransactionsElement::Eip1559 { + Transaction::Eip1559(tx) => Ok(Self::Eip1559 { transaction: tx, signature: typed_tx.signature, hash: typed_tx.hash, @@ -544,7 +539,7 @@ impl Decodable for PooledTransactionsElement { return Err(RlpError::UnexpectedLength) } - Ok(PooledTransactionsElement::BlobTransaction(blob_tx)) + Ok(Self::BlobTransaction(blob_tx)) } else { // DO NOT advance the buffer for the type, since we want the enveloped decoding to // decode it again and advance the buffer on its own. @@ -565,12 +560,12 @@ impl Decodable for PooledTransactionsElement { Transaction::Eip4844(_) => Err(RlpError::Custom( "EIP-4844 transactions can only be decoded with transaction type 0x03", )), - Transaction::Eip2930(tx) => Ok(PooledTransactionsElement::Eip2930 { + Transaction::Eip2930(tx) => Ok(Self::Eip2930 { transaction: tx, signature: typed_tx.signature, hash: typed_tx.hash, }), - Transaction::Eip1559(tx) => Ok(PooledTransactionsElement::Eip1559 { + Transaction::Eip1559(tx) => Ok(Self::Eip1559 { transaction: tx, signature: typed_tx.signature, hash: typed_tx.hash, @@ -587,8 +582,7 @@ impl TryFrom for PooledTransactionsElement { type Error = TransactionConversionError; fn try_from(tx: TransactionSigned) -> Result { - PooledTransactionsElement::try_from_broadcast(tx) - .map_err(|_| TransactionConversionError::UnsupportedForP2P) + Self::try_from_broadcast(tx).map_err(|_| TransactionConversionError::UnsupportedForP2P) } } @@ -605,11 +599,11 @@ impl<'a> arbitrary::Arbitrary<'a> for PooledTransactionsElement { // Attempt to create a `TransactionSigned` with arbitrary data. let tx_signed = TransactionSigned::arbitrary(u)?; // Attempt to create a `PooledTransactionsElement` with arbitrary data, handling the Result. - match PooledTransactionsElement::try_from(tx_signed) { - Ok(PooledTransactionsElement::BlobTransaction(mut tx)) => { + match Self::try_from(tx_signed) { + Ok(Self::BlobTransaction(mut tx)) => { // Successfully converted to a BlobTransaction, now generate a sidecar. tx.sidecar = crate::BlobTransactionSidecar::arbitrary(u)?; - Ok(PooledTransactionsElement::BlobTransaction(tx)) + Ok(Self::BlobTransaction(tx)) } Ok(tx) => Ok(tx), // Successfully converted, but not a BlobTransaction. Err(_) => Err(arbitrary::Error::IncorrectFormat), /* Conversion failed, return an @@ -626,13 +620,13 @@ impl proptest::arbitrary::Arbitrary for PooledTransactionsElement { any::<(TransactionSigned, crate::BlobTransactionSidecar)>() .prop_map(move |(transaction, sidecar)| { - match PooledTransactionsElement::try_from(transaction) { - Ok(PooledTransactionsElement::BlobTransaction(mut tx)) => { + match Self::try_from(transaction) { + Ok(Self::BlobTransaction(mut tx)) => { tx.sidecar = sidecar; - PooledTransactionsElement::BlobTransaction(tx) + Self::BlobTransaction(tx) } Ok(tx) => tx, - Err(_) => PooledTransactionsElement::Eip1559 { + Err(_) => Self::Eip1559 { transaction: Default::default(), signature: Default::default(), hash: Default::default(), @@ -642,7 +636,7 @@ impl proptest::arbitrary::Arbitrary for PooledTransactionsElement { .boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } /// A signed pooled transaction with recovered signer. diff --git a/crates/primitives/src/transaction/tx_type.rs b/crates/primitives/src/transaction/tx_type.rs index d203ecf77..975f70317 100644 --- a/crates/primitives/src/transaction/tx_type.rs +++ b/crates/primitives/src/transaction/tx_type.rs @@ -49,15 +49,15 @@ pub enum TxType { impl TxType { /// The max type reserved by an EIP. - pub const MAX_RESERVED_EIP: TxType = Self::Eip4844; + pub const MAX_RESERVED_EIP: Self = Self::Eip4844; /// Check if the transaction type has an access list. pub const fn has_access_list(&self) -> bool { match self { - TxType::Legacy => false, - TxType::Eip2930 | TxType::Eip1559 | TxType::Eip4844 => true, + Self::Legacy => false, + Self::Eip2930 | Self::Eip1559 | Self::Eip4844 => true, #[cfg(feature = "optimism")] - TxType::Deposit => false, + Self::Deposit => false, } } } @@ -77,7 +77,7 @@ impl From for u8 { impl From for U8 { fn from(value: TxType) -> Self { - U8::from(u8::from(value)) + Self::from(u8::from(value)) } } @@ -86,18 +86,18 @@ impl TryFrom for TxType { fn try_from(value: u8) -> Result { #[cfg(feature = "optimism")] - if value == TxType::Deposit { - return Ok(TxType::Deposit) + if value == Self::Deposit { + return Ok(Self::Deposit) } - if value == TxType::Legacy { - return Ok(TxType::Legacy) - } else if value == TxType::Eip2930 { - return Ok(TxType::Eip2930) - } else if value == TxType::Eip1559 { - return Ok(TxType::Eip1559) - } else if value == TxType::Eip4844 { - return Ok(TxType::Eip4844) + if value == Self::Legacy { + return Ok(Self::Legacy) + } else if value == Self::Eip2930 { + return Ok(Self::Eip2930) + } else if value == Self::Eip1559 { + return Ok(Self::Eip1559) + } else if value == Self::Eip4844 { + return Ok(Self::Eip4844) } Err("invalid tx type") @@ -127,10 +127,10 @@ impl Compact for TxType { B: bytes::BufMut + AsMut<[u8]>, { match self { - TxType::Legacy => 0, - TxType::Eip2930 => 1, - TxType::Eip1559 => 2, - TxType::Eip4844 => { + Self::Legacy => 0, + Self::Eip2930 => 1, + Self::Eip1559 => 2, + Self::Eip4844 => { // Write the full transaction type to the buffer when encoding > 3. // This allows compat decoding the [TyType] from a single byte as // opposed to 2 bits for the backwards-compatible encoding. @@ -138,7 +138,7 @@ impl Compact for TxType { 3 } #[cfg(feature = "optimism")] - TxType::Deposit => { + Self::Deposit => { buf.put_u8(self as u8); 3 } @@ -151,15 +151,15 @@ impl Compact for TxType { fn from_compact(mut buf: &[u8], identifier: usize) -> (Self, &[u8]) { ( match identifier { - 0 => TxType::Legacy, - 1 => TxType::Eip2930, - 2 => TxType::Eip1559, + 0 => Self::Legacy, + 1 => Self::Eip2930, + 2 => Self::Eip1559, 3 => { let extended_identifier = buf.get_u8(); match extended_identifier { - EIP4844_TX_TYPE_ID => TxType::Eip4844, + EIP4844_TX_TYPE_ID => Self::Eip4844, #[cfg(feature = "optimism")] - DEPOSIT_TX_TYPE_ID => TxType::Deposit, + DEPOSIT_TX_TYPE_ID => Self::Deposit, _ => panic!("Unsupported TxType identifier: {extended_identifier}"), } } @@ -178,7 +178,7 @@ impl PartialEq for TxType { impl PartialEq for u8 { fn eq(&self, other: &TxType) -> bool { - *self == *other as u8 + *self == *other as Self } } @@ -196,7 +196,7 @@ impl Decodable for TxType { fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { let ty = u8::decode(buf)?; - TxType::try_from(ty).map_err(alloy_rlp::Error::Custom) + Self::try_from(ty).map_err(alloy_rlp::Error::Custom) } } diff --git a/crates/primitives/src/transaction/variant.rs b/crates/primitives/src/transaction/variant.rs index c2818b754..a69356bb2 100644 --- a/crates/primitives/src/transaction/variant.rs +++ b/crates/primitives/src/transaction/variant.rs @@ -26,18 +26,18 @@ impl TransactionSignedVariant { /// Returns the raw transaction object pub fn as_raw(&self) -> &Transaction { match self { - TransactionSignedVariant::SignedNoHash(tx) => &tx.transaction, - TransactionSignedVariant::Signed(tx) => &tx.transaction, - TransactionSignedVariant::SignedEcRecovered(tx) => &tx.signed_transaction.transaction, + Self::SignedNoHash(tx) => &tx.transaction, + Self::Signed(tx) => &tx.transaction, + Self::SignedEcRecovered(tx) => &tx.signed_transaction.transaction, } } /// Returns the hash of the transaction pub fn hash(&self) -> B256 { match self { - TransactionSignedVariant::SignedNoHash(tx) => tx.hash(), - TransactionSignedVariant::Signed(tx) => tx.hash, - TransactionSignedVariant::SignedEcRecovered(tx) => tx.hash, + Self::SignedNoHash(tx) => tx.hash(), + Self::Signed(tx) => tx.hash, + Self::SignedEcRecovered(tx) => tx.hash, } } @@ -46,9 +46,9 @@ impl TransactionSignedVariant { /// If the transaction is of not of [TransactionSignedEcRecovered] it will be recovered. pub fn signer(&self) -> Option
{ match self { - TransactionSignedVariant::SignedNoHash(tx) => tx.recover_signer(), - TransactionSignedVariant::Signed(tx) => tx.recover_signer(), - TransactionSignedVariant::SignedEcRecovered(tx) => Some(tx.signer), + Self::SignedNoHash(tx) => tx.recover_signer(), + Self::Signed(tx) => tx.recover_signer(), + Self::SignedEcRecovered(tx) => Some(tx.signer), } } @@ -56,7 +56,7 @@ impl TransactionSignedVariant { /// else None pub fn as_signed(&self) -> Option<&TransactionSigned> { match self { - TransactionSignedVariant::Signed(tx) => Some(tx), + Self::Signed(tx) => Some(tx), _ => None, } } @@ -65,41 +65,41 @@ impl TransactionSignedVariant { /// else None pub fn as_signed_ec_recovered(&self) -> Option<&TransactionSignedEcRecovered> { match self { - TransactionSignedVariant::SignedEcRecovered(tx) => Some(tx), + Self::SignedEcRecovered(tx) => Some(tx), _ => None, } } /// Returns true if the transaction is of [TransactionSigned] variant pub fn is_signed(&self) -> bool { - matches!(self, TransactionSignedVariant::Signed(_)) + matches!(self, Self::Signed(_)) } /// Returns true if the transaction is of [TransactionSignedNoHash] variant pub fn is_signed_no_hash(&self) -> bool { - matches!(self, TransactionSignedVariant::SignedNoHash(_)) + matches!(self, Self::SignedNoHash(_)) } /// Returns true if the transaction is of [TransactionSignedEcRecovered] variant pub fn is_signed_ec_recovered(&self) -> bool { - matches!(self, TransactionSignedVariant::SignedEcRecovered(_)) + matches!(self, Self::SignedEcRecovered(_)) } /// Consumes the [TransactionSignedVariant] and returns the consumed [Transaction] pub fn into_raw(self) -> Transaction { match self { - TransactionSignedVariant::SignedNoHash(tx) => tx.transaction, - TransactionSignedVariant::Signed(tx) => tx.transaction, - TransactionSignedVariant::SignedEcRecovered(tx) => tx.signed_transaction.transaction, + Self::SignedNoHash(tx) => tx.transaction, + Self::Signed(tx) => tx.transaction, + Self::SignedEcRecovered(tx) => tx.signed_transaction.transaction, } } /// Consumes the [TransactionSignedVariant] and returns the consumed [TransactionSigned] pub fn into_signed(self) -> TransactionSigned { match self { - TransactionSignedVariant::SignedNoHash(tx) => tx.with_hash(), - TransactionSignedVariant::Signed(tx) => tx, - TransactionSignedVariant::SignedEcRecovered(tx) => tx.signed_transaction, + Self::SignedNoHash(tx) => tx.with_hash(), + Self::Signed(tx) => tx, + Self::SignedEcRecovered(tx) => tx.signed_transaction, } } @@ -123,28 +123,28 @@ impl TransactionSignedVariant { self, ) -> Result { match self { - TransactionSignedVariant::SignedEcRecovered(tx) => Ok(tx), - TransactionSignedVariant::Signed(tx) => tx.try_into_ecrecovered(), - TransactionSignedVariant::SignedNoHash(tx) => tx.with_hash().try_into_ecrecovered(), + Self::SignedEcRecovered(tx) => Ok(tx), + Self::Signed(tx) => tx.try_into_ecrecovered(), + Self::SignedNoHash(tx) => tx.with_hash().try_into_ecrecovered(), } } } impl From for TransactionSignedVariant { fn from(tx: TransactionSignedNoHash) -> Self { - TransactionSignedVariant::SignedNoHash(tx) + Self::SignedNoHash(tx) } } impl From for TransactionSignedVariant { fn from(tx: TransactionSigned) -> Self { - TransactionSignedVariant::Signed(tx) + Self::Signed(tx) } } impl From for TransactionSignedVariant { fn from(tx: TransactionSignedEcRecovered) -> Self { - TransactionSignedVariant::SignedEcRecovered(tx) + Self::SignedEcRecovered(tx) } } diff --git a/crates/primitives/src/trie/subnode.rs b/crates/primitives/src/trie/subnode.rs index 1822396f6..d151c21ef 100644 --- a/crates/primitives/src/trie/subnode.rs +++ b/crates/primitives/src/trie/subnode.rs @@ -63,7 +63,7 @@ impl Compact for StoredSubNode { None }; - (StoredSubNode { key, nibble, node }, buf) + (Self { key, nibble, node }, buf) } } diff --git a/crates/prune/src/builder.rs b/crates/prune/src/builder.rs index 4e0ffd21a..290b50724 100644 --- a/crates/prune/src/builder.rs +++ b/crates/prune/src/builder.rs @@ -31,7 +31,7 @@ impl PrunerBuilder { /// Creates a new [PrunerBuilder] from the given [PruneConfig]. pub fn new(pruner_config: PruneConfig) -> Self { - PrunerBuilder::default() + Self::default() .block_interval(pruner_config.block_interval) .segments(pruner_config.segments) } diff --git a/crates/prune/src/error.rs b/crates/prune/src/error.rs index 348b12f67..b223bccb9 100644 --- a/crates/prune/src/error.rs +++ b/crates/prune/src/error.rs @@ -23,11 +23,9 @@ pub enum PrunerError { impl From for RethError { fn from(err: PrunerError) -> Self { match err { - PrunerError::PruneSegment(_) | PrunerError::InconsistentData(_) => { - RethError::other(err) - } - PrunerError::Database(err) => RethError::Database(err), - PrunerError::Provider(err) => RethError::Provider(err), + PrunerError::PruneSegment(_) | PrunerError::InconsistentData(_) => Self::other(err), + PrunerError::Database(err) => Self::Database(err), + PrunerError::Provider(err) => Self::Provider(err), } } } diff --git a/crates/prune/src/segments/set.rs b/crates/prune/src/segments/set.rs index 7978bd4e5..0843589ec 100644 --- a/crates/prune/src/segments/set.rs +++ b/crates/prune/src/segments/set.rs @@ -47,7 +47,7 @@ impl SegmentSet { receipts_log_filter, } = prune_modes; - SegmentSet::default() + Self::default() // Receipts .segment_opt(receipts.map(Receipts::new)) // Receipts by logs diff --git a/crates/rpc/ipc/src/server/mod.rs b/crates/rpc/ipc/src/server/mod.rs index 2bec090cc..826f33ee7 100644 --- a/crates/rpc/ipc/src/server/mod.rs +++ b/crates/rpc/ipc/src/server/mod.rs @@ -284,7 +284,7 @@ pub struct RpcServiceBuilder(tower::ServiceBuilder); impl Default for RpcServiceBuilder { fn default() -> Self { - RpcServiceBuilder(tower::ServiceBuilder::new()) + Self(tower::ServiceBuilder::new()) } } @@ -577,7 +577,7 @@ pub struct Builder { impl Default for Builder { fn default() -> Self { - Builder { + Self { settings: Settings::default(), id_provider: Arc::new(RandomIntegerIdProvider), rpc_middleware: RpcServiceBuilder::new(), diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index 3245d776c..de6c4bf27 100644 --- a/crates/rpc/ipc/src/stream_codec.rs +++ b/crates/rpc/ipc/src/stream_codec.rs @@ -43,7 +43,7 @@ pub enum Separator { impl Default for Separator { fn default() -> Self { - Separator::Byte(b'\n') + Self::Byte(b'\n') } } @@ -57,12 +57,12 @@ pub struct StreamCodec { impl StreamCodec { /// Default codec with streaming input data. Input can be both enveloped and not. pub fn stream_incoming() -> Self { - StreamCodec::new(Separator::Empty, Default::default()) + Self::new(Separator::Empty, Default::default()) } /// New custom stream codec pub fn new(incoming_separator: Separator, outgoing_separator: Separator) -> Self { - StreamCodec { incoming_separator, outgoing_separator } + Self { incoming_separator, outgoing_separator } } } diff --git a/crates/rpc/rpc-builder/src/error.rs b/crates/rpc/rpc-builder/src/error.rs index 68a2183fe..1753b1fc9 100644 --- a/crates/rpc/rpc-builder/src/error.rs +++ b/crates/rpc/rpc-builder/src/error.rs @@ -19,10 +19,10 @@ impl ServerKind { /// Returns the appropriate flags for each variant. pub fn flags(&self) -> &'static str { match self { - ServerKind::Http(_) => "--http.port", - ServerKind::WS(_) => "--ws.port", - ServerKind::WsHttp(_) => "--ws.port and --http.port", - ServerKind::Auth(_) => "--authrpc.port", + Self::Http(_) => "--http.port", + Self::WS(_) => "--ws.port", + Self::WsHttp(_) => "--ws.port and --http.port", + Self::Auth(_) => "--authrpc.port", } } } @@ -30,10 +30,10 @@ impl ServerKind { impl std::fmt::Display for ServerKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - ServerKind::Http(addr) => write!(f, "{addr} (HTTP-RPC server)"), - ServerKind::WS(addr) => write!(f, "{addr} (WS-RPC server)"), - ServerKind::WsHttp(addr) => write!(f, "{addr} (WS-HTTP-RPC server)"), - ServerKind::Auth(addr) => write!(f, "{addr} (AUTH server)"), + Self::Http(addr) => write!(f, "{addr} (HTTP-RPC server)"), + Self::WS(addr) => write!(f, "{addr} (WS-RPC server)"), + Self::WsHttp(addr) => write!(f, "{addr} (WS-HTTP-RPC server)"), + Self::Auth(addr) => write!(f, "{addr} (AUTH server)"), } } } @@ -73,11 +73,11 @@ pub enum RpcError { impl RpcError { /// Converts an [io::Error] to a more descriptive `RpcError`. - pub fn server_error(io_error: io::Error, kind: ServerKind) -> RpcError { + pub fn server_error(io_error: io::Error, kind: ServerKind) -> Self { if io_error.kind() == ErrorKind::AddrInUse { - return RpcError::AddressAlreadyInUse { kind, error: io_error } + return Self::AddressAlreadyInUse { kind, error: io_error } } - RpcError::ServerError { kind, error: io_error } + Self::ServerError { kind, error: io_error } } } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index dfc52b67e..054535641 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -564,7 +564,7 @@ where impl Default for RpcModuleBuilder<(), (), (), (), (), ()> { fn default() -> Self { - RpcModuleBuilder::new((), (), (), (), (), ()) + Self::new((), (), (), (), (), ()) } } @@ -605,7 +605,7 @@ impl RpcModuleConfigBuilder { /// Consumes the type and creates the [RpcModuleConfig] pub fn build(self) -> RpcModuleConfig { - let RpcModuleConfigBuilder { eth } = self; + let Self { eth } = self; RpcModuleConfig { eth: eth.unwrap_or_default() } } } @@ -640,14 +640,14 @@ impl RpcModuleSelection { /// Returns a selection of [RethRpcModule] with all [RethRpcModule::all_variants]. pub fn all_modules() -> Vec { - RpcModuleSelection::try_from_selection(RethRpcModule::all_variants().iter().copied()) + Self::try_from_selection(RethRpcModule::all_variants().iter().copied()) .expect("valid selection") .into_selection() } /// Returns the [RpcModuleSelection::STANDARD_MODULES] as a selection. pub fn standard_modules() -> Vec { - RpcModuleSelection::try_from_selection(RpcModuleSelection::STANDARD_MODULES.iter().copied()) + Self::try_from_selection(Self::STANDARD_MODULES.iter().copied()) .expect("valid selection") .into_selection() } @@ -704,13 +704,13 @@ impl RpcModuleSelection { s.push(item); } } - Ok(RpcModuleSelection::Selection(s)) + Ok(Self::Selection(s)) } /// Returns true if no selection is configured pub fn is_empty(&self) -> bool { match self { - RpcModuleSelection::Selection(sel) => sel.is_empty(), + Self::Selection(sel) => sel.is_empty(), _ => false, } } @@ -718,23 +718,23 @@ impl RpcModuleSelection { /// Returns an iterator over all configured [RethRpcModule] pub fn iter_selection(&self) -> Box + '_> { match self { - RpcModuleSelection::All => Box::new(Self::all_modules().into_iter()), - RpcModuleSelection::Standard => Box::new(Self::STANDARD_MODULES.iter().copied()), - RpcModuleSelection::Selection(s) => Box::new(s.iter().copied()), + Self::All => Box::new(Self::all_modules().into_iter()), + Self::Standard => Box::new(Self::STANDARD_MODULES.iter().copied()), + Self::Selection(s) => Box::new(s.iter().copied()), } } /// Returns the list of configured [RethRpcModule] pub fn into_selection(self) -> Vec { match self { - RpcModuleSelection::All => Self::all_modules(), - RpcModuleSelection::Selection(s) => s, - RpcModuleSelection::Standard => Self::STANDARD_MODULES.to_vec(), + Self::All => Self::all_modules(), + Self::Selection(s) => s, + Self::Standard => Self::STANDARD_MODULES.to_vec(), } } /// Returns true if both selections are identical. - fn are_identical(http: Option<&RpcModuleSelection>, ws: Option<&RpcModuleSelection>) -> bool { + fn are_identical(http: Option<&Self>, ws: Option<&Self>) -> bool { match (http, ws) { (Some(http), Some(ws)) => { let http = http.clone().iter_selection().collect::>(); @@ -755,7 +755,7 @@ where T: Into, { fn from(value: I) -> Self { - RpcModuleSelection::Selection(value.into_iter().map(Into::into).collect()) + Self::Selection(value.into_iter().map(Into::into).collect()) } } @@ -769,9 +769,9 @@ impl FromStr for RpcModuleSelection { let mut modules = s.split(',').map(str::trim).peekable(); let first = modules.peek().copied().ok_or(ParseError::VariantNotFound)?; match first { - "all" | "All" => Ok(RpcModuleSelection::All), + "all" | "All" => Ok(Self::All), "none" | "None" => Ok(Selection(vec![])), - _ => RpcModuleSelection::try_from_selection(modules), + _ => Self::try_from_selection(modules), } } } @@ -845,7 +845,7 @@ impl RethRpcModule { } /// Returns all variants of the enum - pub fn modules() -> impl IntoIterator { + pub fn modules() -> impl IntoIterator { use strum::IntoEnumIterator; Self::iter() } @@ -862,17 +862,17 @@ impl FromStr for RethRpcModule { fn from_str(s: &str) -> Result { Ok(match s { - "admin" => RethRpcModule::Admin, - "debug" => RethRpcModule::Debug, - "eth" => RethRpcModule::Eth, - "net" => RethRpcModule::Net, - "trace" => RethRpcModule::Trace, - "txpool" => RethRpcModule::Txpool, - "web3" => RethRpcModule::Web3, - "rpc" => RethRpcModule::Rpc, - "reth" => RethRpcModule::Reth, - "ots" => RethRpcModule::Ots, - "eth-call-bundle" | "eth_callBundle" => RethRpcModule::EthCallBundle, + "admin" => Self::Admin, + "debug" => Self::Debug, + "eth" => Self::Eth, + "net" => Self::Net, + "trace" => Self::Trace, + "txpool" => Self::Txpool, + "web3" => Self::Web3, + "rpc" => Self::Rpc, + "reth" => Self::Reth, + "ots" => Self::Ots, + "eth-call-bundle" | "eth_callBundle" => Self::EthCallBundle, _ => return Err(ParseError::VariantNotFound), }) } @@ -880,7 +880,7 @@ impl FromStr for RethRpcModule { impl TryFrom<&str> for RethRpcModule { type Error = ParseError; - fn try_from(s: &str) -> Result>::Error> { + fn try_from(s: &str) -> Result>::Error> { FromStr::from_str(s) } } @@ -1969,7 +1969,7 @@ impl WsHttpServers { let mut http_handle = None; let mut ws_handle = None; match self { - WsHttpServers::SamePort(server) => { + Self::SamePort(server) => { // Make sure http and ws modules are identical, since we currently can't run // different modules on same server config.ensure_ws_http_identical()?; @@ -1980,7 +1980,7 @@ impl WsHttpServers { ws_handle = Some(handle); } } - WsHttpServers::DifferentPort { http, ws } => { + Self::DifferentPort { http, ws } => { if let Some((server, module)) = http.and_then(|server| http_module.map(|module| (server, module))) { @@ -2015,8 +2015,8 @@ pub struct RpcServer { // === impl RpcServer === impl RpcServer { - fn empty() -> RpcServer { - RpcServer { ws_http: Default::default(), ipc: None } + fn empty() -> Self { + Self { ws_http: Default::default(), ipc: None } } /// Returns the [`SocketAddr`] of the http server if started. diff --git a/crates/rpc/rpc-builder/src/metrics.rs b/crates/rpc/rpc-builder/src/metrics.rs index a0285622b..ade36ed21 100644 --- a/crates/rpc/rpc-builder/src/metrics.rs +++ b/crates/rpc/rpc-builder/src/metrics.rs @@ -185,9 +185,9 @@ impl RpcTransport { /// Returns the string representation of the transport protocol. pub(crate) const fn as_str(&self) -> &'static str { match self { - RpcTransport::Http => "http", - RpcTransport::WebSocket => "ws", - RpcTransport::Ipc => "ipc", + Self::Http => "http", + Self::WebSocket => "ws", + Self::Ipc => "ipc", } } diff --git a/crates/rpc/rpc-engine-api/src/engine_api.rs b/crates/rpc/rpc-engine-api/src/engine_api.rs index c3713f731..c09e996b2 100644 --- a/crates/rpc/rpc-engine-api/src/engine_api.rs +++ b/crates/rpc/rpc-engine-api/src/engine_api.rs @@ -564,7 +564,7 @@ where async fn new_payload_v1(&self, payload: ExecutionPayloadV1) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_newPayloadV1"); let start = Instant::now(); - let res = EngineApi::new_payload_v1(self, payload).await; + let res = Self::new_payload_v1(self, payload).await; self.inner.metrics.latency.new_payload_v1.record(start.elapsed()); self.inner.metrics.new_payload_response.update_response_metrics(&res); Ok(res?) @@ -575,7 +575,7 @@ where async fn new_payload_v2(&self, payload: ExecutionPayloadInputV2) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_newPayloadV2"); let start = Instant::now(); - let res = EngineApi::new_payload_v2(self, payload).await; + let res = Self::new_payload_v2(self, payload).await; self.inner.metrics.latency.new_payload_v2.record(start.elapsed()); self.inner.metrics.new_payload_response.update_response_metrics(&res); Ok(res?) @@ -592,8 +592,7 @@ where trace!(target: "rpc::engine", "Serving engine_newPayloadV3"); let start = Instant::now(); let res = - EngineApi::new_payload_v3(self, payload, versioned_hashes, parent_beacon_block_root) - .await; + Self::new_payload_v3(self, payload, versioned_hashes, parent_beacon_block_root).await; self.inner.metrics.latency.new_payload_v3.record(start.elapsed()); self.inner.metrics.new_payload_response.update_response_metrics(&res); Ok(res?) @@ -608,8 +607,7 @@ where trace!(target: "rpc::engine", "Serving engine_newPayloadV4"); let start = Instant::now(); let res = - EngineApi::new_payload_v4(self, payload, versioned_hashes, parent_beacon_block_root) - .await; + Self::new_payload_v4(self, payload, versioned_hashes, parent_beacon_block_root).await; self.inner.metrics.latency.new_payload_v4.record(start.elapsed()); self.inner.metrics.new_payload_response.update_response_metrics(&res); Ok(res?) @@ -626,8 +624,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_forkchoiceUpdatedV1"); let start = Instant::now(); - let res = - EngineApi::fork_choice_updated_v1(self, fork_choice_state, payload_attributes).await; + let res = Self::fork_choice_updated_v1(self, fork_choice_state, payload_attributes).await; self.inner.metrics.latency.fork_choice_updated_v1.record(start.elapsed()); self.inner.metrics.fcu_response.update_response_metrics(&res); Ok(res?) @@ -642,8 +639,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_forkchoiceUpdatedV2"); let start = Instant::now(); - let res = - EngineApi::fork_choice_updated_v2(self, fork_choice_state, payload_attributes).await; + let res = Self::fork_choice_updated_v2(self, fork_choice_state, payload_attributes).await; self.inner.metrics.latency.fork_choice_updated_v2.record(start.elapsed()); self.inner.metrics.fcu_response.update_response_metrics(&res); Ok(res?) @@ -659,8 +655,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_forkchoiceUpdatedV3"); let start = Instant::now(); - let res = - EngineApi::fork_choice_updated_v3(self, fork_choice_state, payload_attributes).await; + let res = Self::fork_choice_updated_v3(self, fork_choice_state, payload_attributes).await; self.inner.metrics.latency.fork_choice_updated_v3.record(start.elapsed()); self.inner.metrics.fcu_response.update_response_metrics(&res); Ok(res?) @@ -683,7 +678,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadV1"); let start = Instant::now(); - let res = EngineApi::get_payload_v1(self, payload_id).await; + let res = Self::get_payload_v1(self, payload_id).await; self.inner.metrics.latency.get_payload_v1.record(start.elapsed()); Ok(res?) } @@ -703,7 +698,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadV2"); let start = Instant::now(); - let res = EngineApi::get_payload_v2(self, payload_id).await; + let res = Self::get_payload_v2(self, payload_id).await; self.inner.metrics.latency.get_payload_v2.record(start.elapsed()); Ok(res?) } @@ -723,7 +718,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadV3"); let start = Instant::now(); - let res = EngineApi::get_payload_v3(self, payload_id).await; + let res = Self::get_payload_v3(self, payload_id).await; self.inner.metrics.latency.get_payload_v3.record(start.elapsed()); Ok(res?) } @@ -743,7 +738,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadV4"); let start = Instant::now(); - let res = EngineApi::get_payload_v4(self, payload_id).await; + let res = Self::get_payload_v4(self, payload_id).await; self.inner.metrics.latency.get_payload_v4.record(start.elapsed()); Ok(res?) } @@ -756,7 +751,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadBodiesByHashV1"); let start = Instant::now(); - let res = EngineApi::get_payload_bodies_by_hash(self, block_hashes); + let res = Self::get_payload_bodies_by_hash(self, block_hashes); self.inner.metrics.latency.get_payload_bodies_by_hash_v1.record(start.elapsed()); Ok(res?) } @@ -784,7 +779,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_getPayloadBodiesByRangeV1"); let start_time = Instant::now(); - let res = EngineApi::get_payload_bodies_by_range(self, start.to(), count.to()).await; + let res = Self::get_payload_bodies_by_range(self, start.to(), count.to()).await; self.inner.metrics.latency.get_payload_bodies_by_range_v1.record(start_time.elapsed()); Ok(res?) } @@ -797,7 +792,7 @@ where ) -> RpcResult { trace!(target: "rpc::engine", "Serving engine_exchangeTransitionConfigurationV1"); let start = Instant::now(); - let res = EngineApi::exchange_transition_configuration(self, config).await; + let res = Self::exchange_transition_configuration(self, config).await; self.inner.metrics.latency.exchange_transition_configuration.record(start.elapsed()); Ok(res?) } @@ -809,7 +804,7 @@ where client: ClientVersionV1, ) -> RpcResult> { trace!(target: "rpc::engine", "Serving engine_getClientVersionV1"); - let res = EngineApi::get_client_version_v1(self, client).await; + let res = Self::get_client_version_v1(self, client).await; Ok(res?) } diff --git a/crates/rpc/rpc-testing-util/src/debug.rs b/crates/rpc/rpc-testing-util/src/debug.rs index f409c3ce3..de5a4ed2c 100644 --- a/crates/rpc/rpc-testing-util/src/debug.rs +++ b/crates/rpc/rpc-testing-util/src/debug.rs @@ -272,7 +272,7 @@ impl std::fmt::Display for JsTracerBuilder { impl From for GethDebugTracingOptions { fn from(b: JsTracerBuilder) -> Self { - GethDebugTracingOptions { + Self { tracer: Some(GethDebugTracerType::JsTracer(b.code())), tracer_config: serde_json::Value::Object(Default::default()).into(), ..Default::default() @@ -356,7 +356,7 @@ pub struct NoopJsTracer; impl From for GethDebugTracingOptions { fn from(_: NoopJsTracer) -> Self { - GethDebugTracingOptions { + Self { tracer: Some(GethDebugTracerType::JsTracer(NOOP_TRACER.to_string())), tracer_config: serde_json::Value::Object(Default::default()).into(), ..Default::default() diff --git a/crates/rpc/rpc-testing-util/src/trace.rs b/crates/rpc/rpc-testing-util/src/trace.rs index df90e813b..64c84c11b 100644 --- a/crates/rpc/rpc-testing-util/src/trace.rs +++ b/crates/rpc/rpc-testing-util/src/trace.rs @@ -439,7 +439,7 @@ where /// * `client1` - The first RPC client. /// * `client2` - The second RPC client. pub fn new(client1: C1, client2: C2) -> Self { - RpcComparer { client1, client2 } + Self { client1, client2 } } /// Compares the `trace_block` responses from the two RPC clients. diff --git a/crates/rpc/rpc-types/src/mev.rs b/crates/rpc/rpc-types/src/mev.rs index 5da5a5667..61e79fab1 100644 --- a/crates/rpc/rpc-types/src/mev.rs +++ b/crates/rpc/rpc-types/src/mev.rs @@ -276,7 +276,7 @@ impl Serialize for PrivacyHint { impl<'de> Deserialize<'de> for PrivacyHint { fn deserialize>(deserializer: D) -> Result { let hints = Vec::::deserialize(deserializer)?; - let mut privacy_hint = PrivacyHint::default(); + let mut privacy_hint = Self::default(); for hint in hints { match hint.as_str() { "calldata" => privacy_hint.calldata = true, @@ -489,22 +489,22 @@ pub enum BundleStats { impl Serialize for BundleStats { fn serialize(&self, serializer: S) -> Result { match self { - BundleStats::Unknown => serde_json::json!({"isSimulated": false}).serialize(serializer), - BundleStats::Seen(stats) => stats.serialize(serializer), - BundleStats::Simulated(stats) => stats.serialize(serializer), + Self::Unknown => serde_json::json!({"isSimulated": false}).serialize(serializer), + Self::Seen(stats) => stats.serialize(serializer), + Self::Simulated(stats) => stats.serialize(serializer), } } } impl<'de> Deserialize<'de> for BundleStats { - fn deserialize(deserializer: D) -> Result + fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { let map = serde_json::Map::deserialize(deserializer)?; if map.get("receivedAt").is_none() { - Ok(BundleStats::Unknown) + Ok(Self::Unknown) } else if map["isSimulated"] == false { StatsSeen::deserialize(serde_json::Value::Object(map)) .map(BundleStats::Seen) diff --git a/crates/rpc/rpc/src/admin.rs b/crates/rpc/rpc/src/admin.rs index 6f3125e06..9e8a0b8aa 100644 --- a/crates/rpc/rpc/src/admin.rs +++ b/crates/rpc/rpc/src/admin.rs @@ -25,7 +25,7 @@ pub struct AdminApi { impl AdminApi { /// Creates a new instance of `AdminApi`. pub fn new(network: N, chain_spec: Arc) -> Self { - AdminApi { network, chain_spec } + Self { network, chain_spec } } } diff --git a/crates/rpc/rpc/src/debug.rs b/crates/rpc/rpc/src/debug.rs index f5c9ed2fe..01b3fb101 100644 --- a/crates/rpc/rpc/src/debug.rs +++ b/crates/rpc/rpc/src/debug.rs @@ -710,7 +710,7 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_raw_block(self, rlp_block, opts.unwrap_or_default()).await?) + Ok(Self::debug_trace_raw_block(self, rlp_block, opts.unwrap_or_default()).await?) } /// Handler for `debug_traceBlockByHash` @@ -720,7 +720,7 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) + Ok(Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) } /// Handler for `debug_traceBlockByNumber` @@ -730,7 +730,7 @@ where opts: Option, ) -> RpcResult> { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) + Ok(Self::debug_trace_block(self, block.into(), opts.unwrap_or_default()).await?) } /// Handler for `debug_traceTransaction` @@ -740,7 +740,7 @@ where opts: Option, ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_transaction(self, tx_hash, opts.unwrap_or_default()).await?) + Ok(Self::debug_trace_transaction(self, tx_hash, opts.unwrap_or_default()).await?) } /// Handler for `debug_traceCall` @@ -751,8 +751,7 @@ where opts: Option, ) -> RpcResult { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_call(self, request, block_number, opts.unwrap_or_default()) - .await?) + Ok(Self::debug_trace_call(self, request, block_number, opts.unwrap_or_default()).await?) } async fn debug_trace_call_many( @@ -762,7 +761,7 @@ where opts: Option, ) -> RpcResult>> { let _permit = self.acquire_trace_permit().await; - Ok(DebugApi::debug_trace_call_many(self, bundles, state_context, opts).await?) + Ok(Self::debug_trace_call_many(self, bundles, state_context, opts).await?) } async fn debug_backtrace_at(&self, _location: &str) -> RpcResult<()> { diff --git a/crates/rpc/rpc/src/eth/api/fee_history.rs b/crates/rpc/rpc/src/eth/api/fee_history.rs index 487dade17..9184607bc 100644 --- a/crates/rpc/rpc/src/eth/api/fee_history.rs +++ b/crates/rpc/rpc/src/eth/api/fee_history.rs @@ -178,7 +178,7 @@ pub struct FeeHistoryCacheConfig { impl Default for FeeHistoryCacheConfig { fn default() -> Self { - FeeHistoryCacheConfig { max_blocks: MAX_HEADER_HISTORY + 100, resolution: 4 } + Self { max_blocks: MAX_HEADER_HISTORY + 100, resolution: 4 } } } @@ -352,7 +352,7 @@ impl FeeHistoryEntry { /// /// Note: This does not calculate the rewards for the block. pub fn new(block: &SealedBlock) -> Self { - FeeHistoryEntry { + Self { base_fee_per_gas: block.base_fee_per_gas.unwrap_or_default(), gas_used_ratio: block.gas_used as f64 / block.gas_limit as f64, base_fee_per_blob_gas: block.blob_fee(), diff --git a/crates/rpc/rpc/src/eth/api/pending_block.rs b/crates/rpc/rpc/src/eth/api/pending_block.rs index b58949a67..a53542fa4 100644 --- a/crates/rpc/rpc/src/eth/api/pending_block.rs +++ b/crates/rpc/rpc/src/eth/api/pending_block.rs @@ -336,13 +336,13 @@ pub(crate) enum PendingBlockEnvOrigin { impl PendingBlockEnvOrigin { /// Returns true if the origin is the actual pending block as received from the CL. pub(crate) fn is_actual_pending(&self) -> bool { - matches!(self, PendingBlockEnvOrigin::ActualPending(_)) + matches!(self, Self::ActualPending(_)) } /// Consumes the type and returns the actual pending block. pub(crate) fn into_actual_pending(self) -> Option { match self { - PendingBlockEnvOrigin::ActualPending(block) => Some(block), + Self::ActualPending(block) => Some(block), _ => None, } } @@ -353,8 +353,8 @@ impl PendingBlockEnvOrigin { /// identify the block by its hash (latest block). pub(crate) fn state_block_id(&self) -> BlockId { match self { - PendingBlockEnvOrigin::ActualPending(_) => BlockNumberOrTag::Pending.into(), - PendingBlockEnvOrigin::DerivedFromLatest(header) => BlockId::Hash(header.hash().into()), + Self::ActualPending(_) => BlockNumberOrTag::Pending.into(), + Self::DerivedFromLatest(header) => BlockId::Hash(header.hash().into()), } } @@ -364,16 +364,16 @@ impl PendingBlockEnvOrigin { /// For the [PendingBlockEnvOrigin::DerivedFromLatest] this is the hash of the _latest_ header. fn build_target_hash(&self) -> B256 { match self { - PendingBlockEnvOrigin::ActualPending(block) => block.parent_hash, - PendingBlockEnvOrigin::DerivedFromLatest(header) => header.hash(), + Self::ActualPending(block) => block.parent_hash, + Self::DerivedFromLatest(header) => header.hash(), } } /// Returns the header this pending block is based on. pub(crate) fn header(&self) -> &SealedHeader { match self { - PendingBlockEnvOrigin::ActualPending(block) => &block.header, - PendingBlockEnvOrigin::DerivedFromLatest(header) => header, + Self::ActualPending(block) => &block.header, + Self::DerivedFromLatest(header) => header, } } } diff --git a/crates/rpc/rpc/src/eth/api/server.rs b/crates/rpc/rpc/src/eth/api/server.rs index 7fd358c13..969cd0167 100644 --- a/crates/rpc/rpc/src/eth/api/server.rs +++ b/crates/rpc/rpc/src/eth/api/server.rs @@ -86,7 +86,7 @@ where /// Handler for: `eth_getBlockByHash` async fn block_by_hash(&self, hash: B256, full: bool) -> Result> { trace!(target: "rpc::eth", ?hash, ?full, "Serving eth_getBlockByHash"); - Ok(EthApi::rpc_block(self, hash, full).await?) + Ok(Self::rpc_block(self, hash, full).await?) } /// Handler for: `eth_getBlockByNumber` @@ -96,13 +96,13 @@ where full: bool, ) -> Result> { trace!(target: "rpc::eth", ?number, ?full, "Serving eth_getBlockByNumber"); - Ok(EthApi::rpc_block(self, number, full).await?) + Ok(Self::rpc_block(self, number, full).await?) } /// Handler for: `eth_getBlockTransactionCountByHash` async fn block_transaction_count_by_hash(&self, hash: B256) -> Result> { trace!(target: "rpc::eth", ?hash, "Serving eth_getBlockTransactionCountByHash"); - Ok(EthApi::block_transaction_count(self, hash).await?.map(U256::from)) + Ok(Self::block_transaction_count(self, hash).await?.map(U256::from)) } /// Handler for: `eth_getBlockTransactionCountByNumber` @@ -111,19 +111,19 @@ where number: BlockNumberOrTag, ) -> Result> { trace!(target: "rpc::eth", ?number, "Serving eth_getBlockTransactionCountByNumber"); - Ok(EthApi::block_transaction_count(self, number).await?.map(U256::from)) + Ok(Self::block_transaction_count(self, number).await?.map(U256::from)) } /// Handler for: `eth_getUncleCountByBlockHash` async fn block_uncles_count_by_hash(&self, hash: B256) -> Result> { trace!(target: "rpc::eth", ?hash, "Serving eth_getUncleCountByBlockHash"); - Ok(EthApi::ommers(self, hash)?.map(|ommers| U256::from(ommers.len()))) + Ok(Self::ommers(self, hash)?.map(|ommers| U256::from(ommers.len()))) } /// Handler for: `eth_getUncleCountByBlockNumber` async fn block_uncles_count_by_number(&self, number: BlockNumberOrTag) -> Result> { trace!(target: "rpc::eth", ?number, "Serving eth_getUncleCountByBlockNumber"); - Ok(EthApi::ommers(self, number)?.map(|ommers| U256::from(ommers.len()))) + Ok(Self::ommers(self, number)?.map(|ommers| U256::from(ommers.len()))) } /// Handler for: `eth_getBlockReceipts` @@ -132,7 +132,7 @@ where block_id: BlockId, ) -> Result>> { trace!(target: "rpc::eth", ?block_id, "Serving eth_getBlockReceipts"); - Ok(EthApi::block_receipts(self, block_id).await?) + Ok(Self::block_receipts(self, block_id).await?) } /// Handler for: `eth_getUncleByBlockHashAndIndex` @@ -142,7 +142,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getUncleByBlockHashAndIndex"); - Ok(EthApi::ommer_by_block_and_index(self, hash, index).await?) + Ok(Self::ommer_by_block_and_index(self, hash, index).await?) } /// Handler for: `eth_getUncleByBlockNumberAndIndex` @@ -152,7 +152,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getUncleByBlockNumberAndIndex"); - Ok(EthApi::ommer_by_block_and_index(self, number, index).await?) + Ok(Self::ommer_by_block_and_index(self, number, index).await?) } /// Handler for: `eth_getRawTransactionByHash` @@ -174,7 +174,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getRawTransactionByBlockHashAndIndex"); - Ok(EthApi::raw_transaction_by_block_and_tx_index(self, hash, index).await?) + Ok(Self::raw_transaction_by_block_and_tx_index(self, hash, index).await?) } /// Handler for: `eth_getTransactionByBlockHashAndIndex` @@ -184,7 +184,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?hash, ?index, "Serving eth_getTransactionByBlockHashAndIndex"); - Ok(EthApi::transaction_by_block_and_tx_index(self, hash, index).await?) + Ok(Self::transaction_by_block_and_tx_index(self, hash, index).await?) } /// Handler for: `eth_getRawTransactionByBlockNumberAndIndex` @@ -194,7 +194,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getRawTransactionByBlockNumberAndIndex"); - Ok(EthApi::raw_transaction_by_block_and_tx_index(self, number, index).await?) + Ok(Self::raw_transaction_by_block_and_tx_index(self, number, index).await?) } /// Handler for: `eth_getTransactionByBlockNumberAndIndex` @@ -204,7 +204,7 @@ where index: Index, ) -> Result> { trace!(target: "rpc::eth", ?number, ?index, "Serving eth_getTransactionByBlockNumberAndIndex"); - Ok(EthApi::transaction_by_block_and_tx_index(self, number, index).await?) + Ok(Self::transaction_by_block_and_tx_index(self, number, index).await?) } /// Handler for: `eth_getTransactionReceipt` @@ -257,13 +257,13 @@ where /// Handler for: `eth_getHeaderByNumber` async fn header_by_number(&self, block_number: BlockNumberOrTag) -> Result> { trace!(target: "rpc::eth", ?block_number, "Serving eth_getHeaderByNumber"); - Ok(EthApi::rpc_block_header(self, block_number).await?) + Ok(Self::rpc_block_header(self, block_number).await?) } /// Handler for: `eth_getHeaderByHash` async fn header_by_hash(&self, hash: B256) -> Result> { trace!(target: "rpc::eth", ?hash, "Serving eth_getHeaderByHash"); - Ok(EthApi::rpc_block_header(self, hash).await?) + Ok(Self::rpc_block_header(self, hash).await?) } /// Handler for: `eth_call` @@ -288,7 +288,7 @@ where state_override: Option, ) -> Result> { trace!(target: "rpc::eth", ?bundle, ?state_context, ?state_override, "Serving eth_callMany"); - Ok(EthApi::call_many(self, bundle, state_context, state_override).await?) + Ok(Self::call_many(self, bundle, state_context, state_override).await?) } /// Handler for: `eth_createAccessList` @@ -317,19 +317,19 @@ where /// Handler for: `eth_gasPrice` async fn gas_price(&self) -> Result { trace!(target: "rpc::eth", "Serving eth_gasPrice"); - return Ok(EthApi::gas_price(self).await?) + return Ok(Self::gas_price(self).await?) } /// Handler for: `eth_maxPriorityFeePerGas` async fn max_priority_fee_per_gas(&self) -> Result { trace!(target: "rpc::eth", "Serving eth_maxPriorityFeePerGas"); - return Ok(EthApi::suggested_priority_fee(self).await?) + return Ok(Self::suggested_priority_fee(self).await?) } /// Handler for: `eth_blobBaseFee` async fn blob_base_fee(&self) -> Result { trace!(target: "rpc::eth", "Serving eth_blobBaseFee"); - return Ok(EthApi::blob_base_fee(self).await?) + return Ok(Self::blob_base_fee(self).await?) } // FeeHistory is calculated based on lazy evaluation of fees for historical blocks, and further @@ -348,7 +348,7 @@ where reward_percentiles: Option>, ) -> Result { trace!(target: "rpc::eth", ?block_count, ?newest_block, ?reward_percentiles, "Serving eth_feeHistory"); - return Ok(EthApi::fee_history(self, block_count, newest_block, reward_percentiles).await?) + return Ok(Self::fee_history(self, block_count, newest_block, reward_percentiles).await?) } /// Handler for: `eth_mining` @@ -391,7 +391,7 @@ where /// Handler for: `eth_sign` async fn sign(&self, address: Address, message: Bytes) -> Result { trace!(target: "rpc::eth", ?address, ?message, "Serving eth_sign"); - Ok(EthApi::sign(self, address, message).await?) + Ok(Self::sign(self, address, message).await?) } /// Handler for: `eth_signTransaction` @@ -402,7 +402,7 @@ where /// Handler for: `eth_signTypedData` async fn sign_typed_data(&self, address: Address, data: Value) -> Result { trace!(target: "rpc::eth", ?address, ?data, "Serving eth_signTypedData"); - Ok(EthApi::sign_typed_data(self, data, address)?) + Ok(Self::sign_typed_data(self, data, address)?) } /// Handler for: `eth_getProof` @@ -413,7 +413,7 @@ where block_number: Option, ) -> Result { trace!(target: "rpc::eth", ?address, ?keys, ?block_number, "Serving eth_getProof"); - let res = EthApi::get_proof(self, address, keys, block_number).await; + let res = Self::get_proof(self, address, keys, block_number).await; Ok(res.map_err(|e| match e { EthApiError::InvalidBlockRange => { diff --git a/crates/rpc/rpc/src/eth/api/transactions.rs b/crates/rpc/rpc/src/eth/api/transactions.rs index 6e01ce3a2..d9be1e91e 100644 --- a/crates/rpc/rpc/src/eth/api/transactions.rs +++ b/crates/rpc/rpc/src/eth/api/transactions.rs @@ -1623,7 +1623,7 @@ impl TransactionSource { /// Returns the transaction and block related info, if not pending pub fn split(self) -> (TransactionSignedEcRecovered, TransactionInfo) { match self { - TransactionSource::Pool(tx) => { + Self::Pool(tx) => { let hash = tx.hash(); ( tx, @@ -1636,7 +1636,7 @@ impl TransactionSource { }, ) } - TransactionSource::Block { transaction, index, block_hash, block_number, base_fee } => { + Self::Block { transaction, index, block_hash, block_number, base_fee } => { let hash = transaction.hash(); ( transaction, diff --git a/crates/rpc/rpc/src/eth/bundle.rs b/crates/rpc/rpc/src/eth/bundle.rs index 0523141eb..2135b43a6 100644 --- a/crates/rpc/rpc/src/eth/bundle.rs +++ b/crates/rpc/rpc/src/eth/bundle.rs @@ -216,7 +216,7 @@ where Eth: EthTransactions + 'static, { async fn call_bundle(&self, request: EthCallBundle) -> RpcResult { - Ok(EthBundle::call_bundle(self, request).await?) + Ok(Self::call_bundle(self, request).await?) } } diff --git a/crates/rpc/rpc/src/eth/cache/mod.rs b/crates/rpc/rpc/src/eth/cache/mod.rs index a3e401107..4dbf30227 100644 --- a/crates/rpc/rpc/src/eth/cache/mod.rs +++ b/crates/rpc/rpc/src/eth/cache/mod.rs @@ -92,7 +92,7 @@ impl EthStateCache { rate_limiter: Arc::new(Semaphore::new(max_concurrent_db_operations)), evm_config, }; - let cache = EthStateCache { to_service }; + let cache = Self { to_service }; (cache, service) } diff --git a/crates/rpc/rpc/src/eth/error.rs b/crates/rpc/rpc/src/eth/error.rs index ff12130b1..42a8d3624 100644 --- a/crates/rpc/rpc/src/eth/error.rs +++ b/crates/rpc/rpc/src/eth/error.rs @@ -127,7 +127,7 @@ pub enum EthApiError { impl EthApiError { /// crates a new [EthApiError::Other] variant. pub fn other(err: E) -> Self { - EthApiError::Other(Box::new(err)) + Self::Other(Box::new(err)) } } @@ -176,10 +176,8 @@ impl From for ErrorObject<'static> { impl From for EthApiError { fn from(error: JsInspectorError) -> Self { match error { - err @ JsInspectorError::JsError(_) => { - EthApiError::InternalJsTracerError(err.to_string()) - } - err => EthApiError::InvalidParams(err.to_string()), + err @ JsInspectorError::JsError(_) => Self::InternalJsTracerError(err.to_string()), + err => Self::InvalidParams(err.to_string()), } } } @@ -188,7 +186,7 @@ impl From for EthApiError { fn from(error: RethError) -> Self { match error { RethError::Provider(err) => err.into(), - err => EthApiError::Internal(err), + err => Self::Internal(err), } } } @@ -202,28 +200,26 @@ impl From for EthApiError { ProviderError::BestBlockNotFound | ProviderError::BlockNumberForTransactionIndexNotFound | ProviderError::TotalDifficultyNotFound { .. } | - ProviderError::UnknownBlockHash(_) => EthApiError::UnknownBlockNumber, + ProviderError::UnknownBlockHash(_) => Self::UnknownBlockNumber, ProviderError::FinalizedBlockNotFound | ProviderError::SafeBlockNotFound => { - EthApiError::UnknownSafeOrFinalizedBlock + Self::UnknownSafeOrFinalizedBlock } - err => EthApiError::Internal(err.into()), + err => Self::Internal(err.into()), } } } impl From> for EthApiError where - T: Into, + T: Into, { fn from(err: EVMError) -> Self { match err { EVMError::Transaction(err) => RpcInvalidTransactionError::from(err).into(), - EVMError::Header(InvalidHeader::PrevrandaoNotSet) => EthApiError::PrevrandaoNotSet, - EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => { - EthApiError::ExcessBlobGasNotSet - } + EVMError::Header(InvalidHeader::PrevrandaoNotSet) => Self::PrevrandaoNotSet, + EVMError::Header(InvalidHeader::ExcessBlobGasNotSet) => Self::ExcessBlobGasNotSet, EVMError::Database(err) => err.into(), - EVMError::Custom(err) => EthApiError::EvmCustom(err), + EVMError::Custom(err) => Self::EvmCustom(err), } } } @@ -373,10 +369,10 @@ impl RpcInvalidTransactionError { /// Returns the rpc error code for this error. fn error_code(&self) -> i32 { match self { - RpcInvalidTransactionError::InvalidChainId | - RpcInvalidTransactionError::GasTooLow | - RpcInvalidTransactionError::GasTooHigh => EthRpcErrorCode::InvalidInput.code(), - RpcInvalidTransactionError::Revert(_) => EthRpcErrorCode::ExecutionError.code(), + Self::InvalidChainId | Self::GasTooLow | Self::GasTooHigh => { + EthRpcErrorCode::InvalidInput.code() + } + Self::Revert(_) => EthRpcErrorCode::ExecutionError.code(), _ => EthRpcErrorCode::TransactionRejected.code(), } } @@ -386,22 +382,20 @@ impl RpcInvalidTransactionError { /// Takes the configured gas limit of the transaction which is attached to the error pub(crate) fn halt(reason: HaltReason, gas_limit: u64) -> Self { match reason { - HaltReason::OutOfGas(err) => RpcInvalidTransactionError::out_of_gas(err, gas_limit), - HaltReason::NonceOverflow => RpcInvalidTransactionError::NonceMaxValue, - err => RpcInvalidTransactionError::EvmHalt(err), + HaltReason::OutOfGas(err) => Self::out_of_gas(err, gas_limit), + HaltReason::NonceOverflow => Self::NonceMaxValue, + err => Self::EvmHalt(err), } } /// Converts the out of gas error pub(crate) fn out_of_gas(reason: OutOfGasError, gas_limit: u64) -> Self { match reason { - OutOfGasError::Basic => RpcInvalidTransactionError::BasicOutOfGas(gas_limit), - OutOfGasError::Memory => RpcInvalidTransactionError::MemoryOutOfGas(gas_limit), - OutOfGasError::Precompile => RpcInvalidTransactionError::PrecompileOutOfGas(gas_limit), - OutOfGasError::InvalidOperand => { - RpcInvalidTransactionError::InvalidOperandOutOfGas(gas_limit) - } - OutOfGasError::MemoryLimit => RpcInvalidTransactionError::MemoryOutOfGas(gas_limit), + OutOfGasError::Basic => Self::BasicOutOfGas(gas_limit), + OutOfGasError::Memory => Self::MemoryOutOfGas(gas_limit), + OutOfGasError::Precompile => Self::PrecompileOutOfGas(gas_limit), + OutOfGasError::InvalidOperand => Self::InvalidOperandOutOfGas(gas_limit), + OutOfGasError::MemoryLimit => Self::MemoryOutOfGas(gas_limit), } } } @@ -426,66 +420,36 @@ impl From for RpcInvalidTransactionError { fn from(err: revm::primitives::InvalidTransaction) -> Self { use revm::primitives::InvalidTransaction; match err { - InvalidTransaction::InvalidChainId => RpcInvalidTransactionError::InvalidChainId, - InvalidTransaction::PriorityFeeGreaterThanMaxFee => { - RpcInvalidTransactionError::TipAboveFeeCap - } - InvalidTransaction::GasPriceLessThanBasefee => RpcInvalidTransactionError::FeeCapTooLow, - InvalidTransaction::CallerGasLimitMoreThanBlock => { - RpcInvalidTransactionError::GasTooHigh - } - InvalidTransaction::CallGasCostMoreThanGasLimit => { - RpcInvalidTransactionError::GasTooHigh - } - InvalidTransaction::RejectCallerWithCode => RpcInvalidTransactionError::SenderNoEOA, - InvalidTransaction::LackOfFundForMaxFee { .. } => { - RpcInvalidTransactionError::InsufficientFunds - } - InvalidTransaction::OverflowPaymentInTransaction => { - RpcInvalidTransactionError::GasUintOverflow - } - InvalidTransaction::NonceOverflowInTransaction => { - RpcInvalidTransactionError::NonceMaxValue - } - InvalidTransaction::CreateInitCodeSizeLimit => { - RpcInvalidTransactionError::MaxInitCodeSizeExceeded - } - InvalidTransaction::NonceTooHigh { .. } => RpcInvalidTransactionError::NonceTooHigh, - InvalidTransaction::NonceTooLow { .. } => RpcInvalidTransactionError::NonceTooLow, - InvalidTransaction::AccessListNotSupported => { - RpcInvalidTransactionError::AccessListNotSupported - } - InvalidTransaction::MaxFeePerBlobGasNotSupported => { - RpcInvalidTransactionError::MaxFeePerBlobGasNotSupported - } + InvalidTransaction::InvalidChainId => Self::InvalidChainId, + InvalidTransaction::PriorityFeeGreaterThanMaxFee => Self::TipAboveFeeCap, + InvalidTransaction::GasPriceLessThanBasefee => Self::FeeCapTooLow, + InvalidTransaction::CallerGasLimitMoreThanBlock => Self::GasTooHigh, + InvalidTransaction::CallGasCostMoreThanGasLimit => Self::GasTooHigh, + InvalidTransaction::RejectCallerWithCode => Self::SenderNoEOA, + InvalidTransaction::LackOfFundForMaxFee { .. } => Self::InsufficientFunds, + InvalidTransaction::OverflowPaymentInTransaction => Self::GasUintOverflow, + InvalidTransaction::NonceOverflowInTransaction => Self::NonceMaxValue, + InvalidTransaction::CreateInitCodeSizeLimit => Self::MaxInitCodeSizeExceeded, + InvalidTransaction::NonceTooHigh { .. } => Self::NonceTooHigh, + InvalidTransaction::NonceTooLow { .. } => Self::NonceTooLow, + InvalidTransaction::AccessListNotSupported => Self::AccessListNotSupported, + InvalidTransaction::MaxFeePerBlobGasNotSupported => Self::MaxFeePerBlobGasNotSupported, InvalidTransaction::BlobVersionedHashesNotSupported => { - RpcInvalidTransactionError::BlobVersionedHashesNotSupported - } - InvalidTransaction::BlobGasPriceGreaterThanMax => { - RpcInvalidTransactionError::BlobFeeCapTooLow - } - InvalidTransaction::EmptyBlobs => { - RpcInvalidTransactionError::BlobTransactionMissingBlobHashes - } - InvalidTransaction::BlobVersionNotSupported => { - RpcInvalidTransactionError::BlobHashVersionMismatch - } - InvalidTransaction::TooManyBlobs { max, have } => { - RpcInvalidTransactionError::TooManyBlobs { max, have } - } - InvalidTransaction::BlobCreateTransaction => { - RpcInvalidTransactionError::BlobTransactionIsCreate + Self::BlobVersionedHashesNotSupported } + InvalidTransaction::BlobGasPriceGreaterThanMax => Self::BlobFeeCapTooLow, + InvalidTransaction::EmptyBlobs => Self::BlobTransactionMissingBlobHashes, + InvalidTransaction::BlobVersionNotSupported => Self::BlobHashVersionMismatch, + InvalidTransaction::TooManyBlobs { max, have } => Self::TooManyBlobs { max, have }, + InvalidTransaction::BlobCreateTransaction => Self::BlobTransactionIsCreate, #[cfg(feature = "optimism")] InvalidTransaction::DepositSystemTxPostRegolith => { - RpcInvalidTransactionError::Optimism( - OptimismInvalidTransactionError::DepositSystemTxPostRegolith, - ) + Self::Optimism(OptimismInvalidTransactionError::DepositSystemTxPostRegolith) } #[cfg(feature = "optimism")] - InvalidTransaction::HaltedDepositPostRegolith => RpcInvalidTransactionError::Optimism( - OptimismInvalidTransactionError::HaltedDepositPostRegolith, - ), + InvalidTransaction::HaltedDepositPostRegolith => { + Self::Optimism(OptimismInvalidTransactionError::HaltedDepositPostRegolith) + } // TODO(EOF) InvalidTransaction::EofCrateShouldHaveToAddress => todo!("EOF"), } @@ -498,31 +462,23 @@ impl From for RpcInvalidTransactionErr // This conversion is used to convert any transaction errors that could occur inside the // txpool (e.g. `eth_sendRawTransaction`) to their corresponding RPC match err { - InvalidTransactionError::InsufficientFunds { .. } => { - RpcInvalidTransactionError::InsufficientFunds - } - InvalidTransactionError::NonceNotConsistent => RpcInvalidTransactionError::NonceTooLow, + InvalidTransactionError::InsufficientFunds { .. } => Self::InsufficientFunds, + InvalidTransactionError::NonceNotConsistent => Self::NonceTooLow, InvalidTransactionError::OldLegacyChainId => { // Note: this should be unreachable since Spurious Dragon now enabled - RpcInvalidTransactionError::OldLegacyChainId + Self::OldLegacyChainId } - InvalidTransactionError::ChainIdMismatch => RpcInvalidTransactionError::InvalidChainId, + InvalidTransactionError::ChainIdMismatch => Self::InvalidChainId, InvalidTransactionError::Eip2930Disabled | InvalidTransactionError::Eip1559Disabled | - InvalidTransactionError::Eip4844Disabled => { - RpcInvalidTransactionError::TxTypeNotSupported - } - InvalidTransactionError::TxTypeNotSupported => { - RpcInvalidTransactionError::TxTypeNotSupported - } - InvalidTransactionError::GasUintOverflow => RpcInvalidTransactionError::GasUintOverflow, - InvalidTransactionError::GasTooLow => RpcInvalidTransactionError::GasTooLow, - InvalidTransactionError::GasTooHigh => RpcInvalidTransactionError::GasTooHigh, - InvalidTransactionError::TipAboveFeeCap => RpcInvalidTransactionError::TipAboveFeeCap, - InvalidTransactionError::FeeCapTooLow => RpcInvalidTransactionError::FeeCapTooLow, - InvalidTransactionError::SignerAccountHasBytecode => { - RpcInvalidTransactionError::SenderNoEOA - } + InvalidTransactionError::Eip4844Disabled => Self::TxTypeNotSupported, + InvalidTransactionError::TxTypeNotSupported => Self::TxTypeNotSupported, + InvalidTransactionError::GasUintOverflow => Self::GasUintOverflow, + InvalidTransactionError::GasTooLow => Self::GasTooLow, + InvalidTransactionError::GasTooHigh => Self::GasTooHigh, + InvalidTransactionError::TipAboveFeeCap => Self::TipAboveFeeCap, + InvalidTransactionError::FeeCapTooLow => Self::FeeCapTooLow, + InvalidTransactionError::SignerAccountHasBytecode => Self::SenderNoEOA, } } } @@ -629,39 +585,37 @@ impl From for ErrorObject<'static> { } impl From for RpcPoolError { - fn from(err: PoolError) -> RpcPoolError { + fn from(err: PoolError) -> Self { match err.kind { - PoolErrorKind::ReplacementUnderpriced => RpcPoolError::ReplaceUnderpriced, - PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(_) => RpcPoolError::Underpriced, - PoolErrorKind::SpammerExceededCapacity(_) => RpcPoolError::TxPoolOverflow, - PoolErrorKind::DiscardedOnInsert => RpcPoolError::TxPoolOverflow, + PoolErrorKind::ReplacementUnderpriced => Self::ReplaceUnderpriced, + PoolErrorKind::FeeCapBelowMinimumProtocolFeeCap(_) => Self::Underpriced, + PoolErrorKind::SpammerExceededCapacity(_) => Self::TxPoolOverflow, + PoolErrorKind::DiscardedOnInsert => Self::TxPoolOverflow, PoolErrorKind::InvalidTransaction(err) => err.into(), - PoolErrorKind::Other(err) => RpcPoolError::Other(err), - PoolErrorKind::AlreadyImported => RpcPoolError::AlreadyKnown, - PoolErrorKind::ExistingConflictingTransactionType(_, _) => { - RpcPoolError::AddressAlreadyReserved - } + PoolErrorKind::Other(err) => Self::Other(err), + PoolErrorKind::AlreadyImported => Self::AlreadyKnown, + PoolErrorKind::ExistingConflictingTransactionType(_, _) => Self::AddressAlreadyReserved, } } } impl From for RpcPoolError { - fn from(err: InvalidPoolTransactionError) -> RpcPoolError { + fn from(err: InvalidPoolTransactionError) -> Self { match err { - InvalidPoolTransactionError::Consensus(err) => RpcPoolError::Invalid(err.into()), - InvalidPoolTransactionError::ExceedsGasLimit(_, _) => RpcPoolError::ExceedsGasLimit, + InvalidPoolTransactionError::Consensus(err) => Self::Invalid(err.into()), + InvalidPoolTransactionError::ExceedsGasLimit(_, _) => Self::ExceedsGasLimit, InvalidPoolTransactionError::ExceedsMaxInitCodeSize(_, _) => { - RpcPoolError::ExceedsMaxInitCodeSize + Self::ExceedsMaxInitCodeSize } InvalidPoolTransactionError::IntrinsicGasTooLow => { - RpcPoolError::Invalid(RpcInvalidTransactionError::GasTooLow) + Self::Invalid(RpcInvalidTransactionError::GasTooLow) } - InvalidPoolTransactionError::OversizedData(_, _) => RpcPoolError::OversizedData, - InvalidPoolTransactionError::Underpriced => RpcPoolError::Underpriced, - InvalidPoolTransactionError::Other(err) => RpcPoolError::PoolTransactionError(err), - InvalidPoolTransactionError::Eip4844(err) => RpcPoolError::Eip4844(err), + InvalidPoolTransactionError::OversizedData(_, _) => Self::OversizedData, + InvalidPoolTransactionError::Underpriced => Self::Underpriced, + InvalidPoolTransactionError::Other(err) => Self::PoolTransactionError(err), + InvalidPoolTransactionError::Eip4844(err) => Self::Eip4844(err), InvalidPoolTransactionError::Overdraft => { - RpcPoolError::Invalid(RpcInvalidTransactionError::InsufficientFunds) + Self::Invalid(RpcInvalidTransactionError::InsufficientFunds) } } } @@ -669,7 +623,7 @@ impl From for RpcPoolError { impl From for EthApiError { fn from(err: PoolError) -> Self { - EthApiError::PoolError(RpcPoolError::from(err)) + Self::PoolError(RpcPoolError::from(err)) } } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index b14c20451..d0d7077e8 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -269,7 +269,7 @@ where /// Handler for `eth_getFilterChanges` async fn filter_changes(&self, id: FilterId) -> RpcResult { trace!(target: "rpc::eth", "Serving eth_getFilterChanges"); - Ok(EthFilter::filter_changes(self, id).await?) + Ok(Self::filter_changes(self, id).await?) } /// Returns an array of all logs matching filter with given id. @@ -279,7 +279,7 @@ where /// Handler for `eth_getFilterLogs` async fn filter_logs(&self, id: FilterId) -> RpcResult> { trace!(target: "rpc::eth", "Serving eth_getFilterLogs"); - Ok(EthFilter::filter_logs(self, id).await?) + Ok(Self::filter_logs(self, id).await?) } /// Handler for `eth_uninstallFilter` @@ -588,7 +588,7 @@ struct PendingTransactionsReceiver { impl PendingTransactionsReceiver { fn new(receiver: Receiver) -> Self { - PendingTransactionsReceiver { txs_receiver: Arc::new(Mutex::new(receiver)) } + Self { txs_receiver: Arc::new(Mutex::new(receiver)) } } /// Returns all new pending transactions received since the last poll. @@ -617,7 +617,7 @@ where { /// Creates a new `FullTransactionsReceiver` encapsulating the provided transaction stream. fn new(stream: NewSubpoolTransactionStream) -> Self { - FullTransactionsReceiver { txs_stream: Arc::new(Mutex::new(stream)) } + Self { txs_stream: Arc::new(Mutex::new(stream)) } } /// Returns all new pending transactions received since the last poll. @@ -646,7 +646,7 @@ where T: PoolTransaction + 'static, { async fn drain(&self) -> FilterChanges { - FullTransactionsReceiver::drain(self).await + Self::drain(self).await } } @@ -664,8 +664,8 @@ enum PendingTransactionKind { impl PendingTransactionKind { async fn drain(&self) -> FilterChanges { match self { - PendingTransactionKind::Hashes(receiver) => receiver.drain().await, - PendingTransactionKind::FullTransaction(receiver) => receiver.drain().await, + Self::Hashes(receiver) => receiver.drain().await, + Self::FullTransaction(receiver) => receiver.drain().await, } } } @@ -717,7 +717,7 @@ impl From for jsonrpsee::types::error::ErrorObject<'static> { impl From for FilterError { fn from(err: ProviderError) -> Self { - FilterError::EthAPIError(err.into()) + Self::EthAPIError(err.into()) } } diff --git a/crates/rpc/rpc/src/eth/gas_oracle.rs b/crates/rpc/rpc/src/eth/gas_oracle.rs index e9d04d67e..592c858d8 100644 --- a/crates/rpc/rpc/src/eth/gas_oracle.rs +++ b/crates/rpc/rpc/src/eth/gas_oracle.rs @@ -61,7 +61,7 @@ pub struct GasPriceOracleConfig { impl Default for GasPriceOracleConfig { fn default() -> Self { - GasPriceOracleConfig { + Self { blocks: DEFAULT_GAS_PRICE_BLOCKS, percentile: DEFAULT_GAS_PRICE_PERCENTILE, max_header_history: MAX_HEADER_HISTORY, diff --git a/crates/rpc/rpc/src/eth/optimism.rs b/crates/rpc/rpc/src/eth/optimism.rs index 24f6f36ff..fb1665b95 100644 --- a/crates/rpc/rpc/src/eth/optimism.rs +++ b/crates/rpc/rpc/src/eth/optimism.rs @@ -20,15 +20,13 @@ pub enum OptimismEthApiError { impl ToRpcError for OptimismEthApiError { fn to_rpc_error(&self) -> ErrorObject<'static> { match self { - OptimismEthApiError::L1BlockFeeError | OptimismEthApiError::L1BlockGasError => { - internal_rpc_err(self.to_string()) - } + Self::L1BlockFeeError | Self::L1BlockGasError => internal_rpc_err(self.to_string()), } } } impl From for EthApiError { fn from(err: OptimismEthApiError) -> Self { - EthApiError::other(err) + Self::other(err) } } diff --git a/crates/rpc/rpc/src/eth/revm_utils.rs b/crates/rpc/rpc/src/eth/revm_utils.rs index fcd132bfe..f5b6545a0 100644 --- a/crates/rpc/rpc/src/eth/revm_utils.rs +++ b/crates/rpc/rpc/src/eth/revm_utils.rs @@ -356,7 +356,7 @@ impl CallFees { blob_versioned_hashes: Option<&[B256]>, max_fee_per_blob_gas: Option, block_blob_fee: Option, - ) -> EthResult { + ) -> EthResult { /// Get the effective gas price of a transaction as specfified in EIP-1559 with relevant /// checks. fn get_effective_gas_price( @@ -399,7 +399,7 @@ impl CallFees { // either legacy transaction or no fee fields are specified // when no fields are specified, set gas price to zero let gas_price = gas_price.unwrap_or(U256::ZERO); - Ok(CallFees { + Ok(Self { gas_price, max_priority_fee_per_gas: None, max_fee_per_blob_gas: has_blob_hashes.then_some(block_blob_fee).flatten(), @@ -414,7 +414,7 @@ impl CallFees { )?; let max_fee_per_blob_gas = has_blob_hashes.then_some(block_blob_fee).flatten(); - Ok(CallFees { + Ok(Self { gas_price: effective_gas_price, max_priority_fee_per_gas, max_fee_per_blob_gas, @@ -433,7 +433,7 @@ impl CallFees { return Err(RpcInvalidTransactionError::BlobTransactionMissingBlobHashes.into()) } - Ok(CallFees { + Ok(Self { gas_price: effective_gas_price, max_priority_fee_per_gas, max_fee_per_blob_gas: Some(max_fee_per_blob_gas), diff --git a/crates/rpc/rpc/src/eth/signer.rs b/crates/rpc/rpc/src/eth/signer.rs index 578907604..9999a7dac 100644 --- a/crates/rpc/rpc/src/eth/signer.rs +++ b/crates/rpc/rpc/src/eth/signer.rs @@ -66,7 +66,7 @@ impl DevSigner { let address = reth_primitives::public_key_to_address(pk); let addresses = vec![address]; let accounts = HashMap::from([(address, sk)]); - signers.push(Box::new(DevSigner { addresses, accounts }) as Box); + signers.push(Box::new(Self { addresses, accounts }) as Box); } signers } diff --git a/crates/rpc/rpc/src/reth.rs b/crates/rpc/rpc/src/reth.rs index 43890bea0..87865ef31 100644 --- a/crates/rpc/rpc/src/reth.rs +++ b/crates/rpc/rpc/src/reth.rs @@ -93,7 +93,7 @@ where &self, block_id: BlockId, ) -> RpcResult> { - Ok(RethApi::balance_changes_in_block(self, block_id).await?) + Ok(Self::balance_changes_in_block(self, block_id).await?) } } diff --git a/crates/rpc/rpc/src/rpc.rs b/crates/rpc/rpc/src/rpc.rs index 97a49ddb3..771987a88 100644 --- a/crates/rpc/rpc/src/rpc.rs +++ b/crates/rpc/rpc/src/rpc.rs @@ -15,7 +15,7 @@ pub struct RPCApi { impl RPCApi { /// Return a new RPCApi struct, with given module_map pub fn new(module_map: HashMap) -> Self { - RPCApi { rpc_modules: Arc::new(RpcModules::new(module_map)) } + Self { rpc_modules: Arc::new(RpcModules::new(module_map)) } } } diff --git a/crates/rpc/rpc/src/trace.rs b/crates/rpc/rpc/src/trace.rs index b2104ff47..9c7dac6a8 100644 --- a/crates/rpc/rpc/src/trace.rs +++ b/crates/rpc/rpc/src/trace.rs @@ -501,7 +501,7 @@ where let _permit = self.acquire_trace_permit().await; let request = TraceCallRequest { call, trace_types, block_id, state_overrides, block_overrides }; - Ok(TraceApi::trace_call(self, request).await?) + Ok(Self::trace_call(self, request).await?) } /// Handler for `trace_callMany` @@ -511,7 +511,7 @@ where block_id: Option, ) -> Result> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_call_many(self, calls, block_id).await?) + Ok(Self::trace_call_many(self, calls, block_id).await?) } /// Handler for `trace_rawTransaction` @@ -522,7 +522,7 @@ where block_id: Option, ) -> Result { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_raw_transaction(self, data, trace_types, block_id).await?) + Ok(Self::trace_raw_transaction(self, data, trace_types, block_id).await?) } /// Handler for `trace_replayBlockTransactions` @@ -532,7 +532,7 @@ where trace_types: HashSet, ) -> Result>> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::replay_block_transactions(self, block_id, trace_types).await?) + Ok(Self::replay_block_transactions(self, block_id, trace_types).await?) } /// Handler for `trace_replayTransaction` @@ -542,7 +542,7 @@ where trace_types: HashSet, ) -> Result { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::replay_transaction(self, transaction, trace_types).await?) + Ok(Self::replay_transaction(self, transaction, trace_types).await?) } /// Handler for `trace_block` @@ -551,7 +551,7 @@ where block_id: BlockId, ) -> Result>> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_block(self, block_id).await?) + Ok(Self::trace_block(self, block_id).await?) } /// Handler for `trace_filter` @@ -561,7 +561,7 @@ where /// # Limitations /// This currently requires block filter fields, since reth does not have address indices yet. async fn trace_filter(&self, filter: TraceFilter) -> Result> { - Ok(TraceApi::trace_filter(self, filter).await?) + Ok(Self::trace_filter(self, filter).await?) } /// Returns transaction trace at given index. @@ -572,7 +572,7 @@ where indices: Vec, ) -> Result> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_get(self, hash, indices.into_iter().map(Into::into).collect()).await?) + Ok(Self::trace_get(self, hash, indices.into_iter().map(Into::into).collect()).await?) } /// Handler for `trace_transaction` @@ -581,7 +581,7 @@ where hash: B256, ) -> Result>> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_transaction(self, hash).await?) + Ok(Self::trace_transaction(self, hash).await?) } /// Handler for `trace_transactionOpcodeGas` @@ -590,13 +590,13 @@ where tx_hash: B256, ) -> Result> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_transaction_opcode_gas(self, tx_hash).await?) + Ok(Self::trace_transaction_opcode_gas(self, tx_hash).await?) } /// Handler for `trace_blockOpcodeGas` async fn trace_block_opcode_gas(&self, block_id: BlockId) -> Result> { let _permit = self.acquire_trace_permit().await; - Ok(TraceApi::trace_block_opcode_gas(self, block_id).await?) + Ok(Self::trace_block_opcode_gas(self, block_id).await?) } } diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index 202d69b57..aaef62f70 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -22,7 +22,7 @@ pub struct TxPoolApi { impl TxPoolApi { /// Creates a new instance of `TxpoolApi`. pub fn new(pool: Pool) -> Self { - TxPoolApi { pool } + Self { pool } } } diff --git a/crates/rpc/rpc/src/web3.rs b/crates/rpc/rpc/src/web3.rs index 604987e16..e7dc9e6be 100644 --- a/crates/rpc/rpc/src/web3.rs +++ b/crates/rpc/rpc/src/web3.rs @@ -16,7 +16,7 @@ pub struct Web3Api { impl Web3Api { /// Creates a new instance of `Web3Api`. pub fn new(network: N) -> Self { - Web3Api { network } + Self { network } } } diff --git a/crates/stages-api/src/error.rs b/crates/stages-api/src/error.rs index f6e528ca7..40b998bc1 100644 --- a/crates/stages-api/src/error.rs +++ b/crates/stages-api/src/error.rs @@ -23,8 +23,8 @@ impl BlockErrorKind { /// Returns `true` if the error is a state root error. pub fn is_state_root_error(&self) -> bool { match self { - BlockErrorKind::Validation(err) => err.is_state_root_error(), - BlockErrorKind::Execution(err) => err.is_state_root_error(), + Self::Validation(err) => err.is_state_root_error(), + Self::Execution(err) => err.is_state_root_error(), } } } @@ -138,24 +138,24 @@ impl StageError { pub fn is_fatal(&self) -> bool { matches!( self, - StageError::Database(_) | - StageError::Download(_) | - StageError::DatabaseIntegrity(_) | - StageError::StageCheckpoint(_) | - StageError::MissingDownloadBuffer | - StageError::MissingSyncGap | - StageError::ChannelClosed | - StageError::InconsistentBlockNumber { .. } | - StageError::InconsistentTxNumber { .. } | - StageError::Internal(_) | - StageError::Fatal(_) + Self::Database(_) | + Self::Download(_) | + Self::DatabaseIntegrity(_) | + Self::StageCheckpoint(_) | + Self::MissingDownloadBuffer | + Self::MissingSyncGap | + Self::ChannelClosed | + Self::InconsistentBlockNumber { .. } | + Self::InconsistentTxNumber { .. } | + Self::Internal(_) | + Self::Fatal(_) ) } } impl From for StageError { fn from(source: std::io::Error) -> Self { - StageError::Fatal(Box::new(source)) + Self::Fatal(Box::new(source)) } } diff --git a/crates/stages-api/src/pipeline/ctrl.rs b/crates/stages-api/src/pipeline/ctrl.rs index eb40bc7d4..dc19672bc 100644 --- a/crates/stages-api/src/pipeline/ctrl.rs +++ b/crates/stages-api/src/pipeline/ctrl.rs @@ -27,20 +27,20 @@ pub enum ControlFlow { impl ControlFlow { /// Whether the pipeline should continue executing stages. pub fn should_continue(&self) -> bool { - matches!(self, ControlFlow::Continue { .. } | ControlFlow::NoProgress { .. }) + matches!(self, Self::Continue { .. } | Self::NoProgress { .. }) } /// Returns true if the control flow is unwind. pub fn is_unwind(&self) -> bool { - matches!(self, ControlFlow::Unwind { .. }) + matches!(self, Self::Unwind { .. }) } /// Returns the pipeline block number the stage reached, if the state is not `Unwind`. pub fn block_number(&self) -> Option { match self { - ControlFlow::Unwind { .. } => None, - ControlFlow::Continue { block_number } => Some(*block_number), - ControlFlow::NoProgress { block_number } => *block_number, + Self::Unwind { .. } => None, + Self::Continue { block_number } => Some(*block_number), + Self::NoProgress { block_number } => *block_number, } } } diff --git a/crates/stages-api/src/pipeline/set.rs b/crates/stages-api/src/pipeline/set.rs index ede824359..01613f36c 100644 --- a/crates/stages-api/src/pipeline/set.rs +++ b/crates/stages-api/src/pipeline/set.rs @@ -240,7 +240,7 @@ where } impl StageSet for StageSetBuilder { - fn builder(self) -> StageSetBuilder { + fn builder(self) -> Self { self } } diff --git a/crates/stages/src/stages/execution.rs b/crates/stages/src/stages/execution.rs index b7057ab50..cee62b3b3 100644 --- a/crates/stages/src/stages/execution.rs +++ b/crates/stages/src/stages/execution.rs @@ -561,7 +561,7 @@ impl ExecutionStageThresholds { impl From for ExecutionStageThresholds { fn from(config: ExecutionConfig) -> Self { - ExecutionStageThresholds { + Self { max_blocks: config.max_blocks, max_changes: config.max_changes, max_cumulative_gas: config.max_cumulative_gas, diff --git a/crates/stages/src/stages/merkle.rs b/crates/stages/src/stages/merkle.rs index cb50dd39b..b4b7aec48 100644 --- a/crates/stages/src/stages/merkle.rs +++ b/crates/stages/src/stages/merkle.rs @@ -138,10 +138,10 @@ impl Stage for MerkleStage { /// Return the id of the stage fn id(&self) -> StageId { match self { - MerkleStage::Execution { .. } => StageId::MerkleExecute, - MerkleStage::Unwind => StageId::MerkleUnwind, + Self::Execution { .. } => StageId::MerkleExecute, + Self::Unwind => StageId::MerkleUnwind, #[cfg(any(test, feature = "test-utils"))] - MerkleStage::Both { .. } => StageId::Other("MerkleBoth"), + Self::Both { .. } => StageId::Other("MerkleBoth"), } } @@ -152,13 +152,13 @@ impl Stage for MerkleStage { input: ExecInput, ) -> Result { let threshold = match self { - MerkleStage::Unwind => { + Self::Unwind => { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); return Ok(ExecOutput::done(StageCheckpoint::new(input.target()))) } - MerkleStage::Execution { clean_threshold } => *clean_threshold, + Self::Execution { clean_threshold } => *clean_threshold, #[cfg(any(test, feature = "test-utils"))] - MerkleStage::Both { clean_threshold } => *clean_threshold, + Self::Both { clean_threshold } => *clean_threshold, }; let range = input.next_block_range(); @@ -292,7 +292,7 @@ impl Stage for MerkleStage { ) -> Result { let tx = provider.tx_ref(); let range = input.unwind_block_range(); - if matches!(self, MerkleStage::Execution { .. }) { + if matches!(self, Self::Execution { .. }) { info!(target: "sync::stages::merkle::unwind", "Stage is always skipped"); return Ok(UnwindOutput { checkpoint: StageCheckpoint::new(input.unwind_to) }) } diff --git a/crates/static-file-types/src/segment.rs b/crates/static-file-types/src/segment.rs index 82b937f29..d85d33dc2 100644 --- a/crates/static-file-types/src/segment.rs +++ b/crates/static-file-types/src/segment.rs @@ -40,9 +40,9 @@ impl StaticFileSegment { /// Returns the segment as a string. pub const fn as_str(&self) -> &'static str { match self { - StaticFileSegment::Headers => "headers", - StaticFileSegment::Transactions => "transactions", - StaticFileSegment::Receipts => "receipts", + Self::Headers => "headers", + Self::Transactions => "transactions", + Self::Receipts => "receipts", } } @@ -57,18 +57,18 @@ impl StaticFileSegment { }; match self { - StaticFileSegment::Headers => default_config, - StaticFileSegment::Transactions => default_config, - StaticFileSegment::Receipts => default_config, + Self::Headers => default_config, + Self::Transactions => default_config, + Self::Receipts => default_config, } } /// Returns the number of columns for the segment pub const fn columns(&self) -> usize { match self { - StaticFileSegment::Headers => 3, - StaticFileSegment::Transactions => 1, - StaticFileSegment::Receipts => 1, + Self::Headers => 3, + Self::Transactions => 1, + Self::Receipts => 1, } } @@ -134,7 +134,7 @@ impl StaticFileSegment { /// Returns `true` if the segment is `StaticFileSegment::Headers`. pub fn is_headers(&self) -> bool { - matches!(self, StaticFileSegment::Headers) + matches!(self, Self::Headers) } } @@ -344,7 +344,7 @@ impl std::fmt::Display for SegmentRangeInclusive { impl From> for SegmentRangeInclusive { fn from(value: RangeInclusive) -> Self { - SegmentRangeInclusive { start: *value.start(), end: *value.end() } + Self { start: *value.start(), end: *value.end() } } } diff --git a/crates/storage/codecs/src/alloy/access_list.rs b/crates/storage/codecs/src/alloy/access_list.rs index 22439f827..d3f906318 100644 --- a/crates/storage/codecs/src/alloy/access_list.rs +++ b/crates/storage/codecs/src/alloy/access_list.rs @@ -21,7 +21,7 @@ impl Compact for AccessListItem { buf = new_buf; let (storage_keys, new_buf) = Vec::specialized_from_compact(buf, buf.len()); buf = new_buf; - let access_list_item = AccessListItem { address, storage_keys }; + let access_list_item = Self { address, storage_keys }; (access_list_item, buf) } } @@ -41,7 +41,7 @@ impl Compact for AccessList { fn from_compact(mut buf: &[u8], _: usize) -> (Self, &[u8]) { let (access_list_items, new_buf) = Vec::from_compact(buf, buf.len()); buf = new_buf; - let access_list = AccessList(access_list_items); + let access_list = Self(access_list_items); (access_list, buf) } } diff --git a/crates/storage/codecs/src/alloy/genesis_account.rs b/crates/storage/codecs/src/alloy/genesis_account.rs index 619d9db51..bc3843ab7 100644 --- a/crates/storage/codecs/src/alloy/genesis_account.rs +++ b/crates/storage/codecs/src/alloy/genesis_account.rs @@ -53,7 +53,7 @@ impl Compact for AlloyGenesisAccount { fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { let (account, _) = GenesisAccount::from_compact(buf, len); - let alloy_account = AlloyGenesisAccount { + let alloy_account = Self { nonce: account.nonce, balance: account.balance, code: account.code, diff --git a/crates/storage/codecs/src/alloy/log.rs b/crates/storage/codecs/src/alloy/log.rs index a374b3680..8d5c30e0a 100644 --- a/crates/storage/codecs/src/alloy/log.rs +++ b/crates/storage/codecs/src/alloy/log.rs @@ -23,7 +23,7 @@ impl Compact for LogData { let (topics, new_buf) = Vec::specialized_from_compact(buf, buf.len()); buf = new_buf; let (data, buf) = Bytes::from_compact(buf, buf.len()); - let log_data = LogData::new_unchecked(topics, data); + let log_data = Self::new_unchecked(topics, data); (log_data, buf) } } @@ -46,7 +46,7 @@ impl Compact for Log { buf = new_buf; let (log_data, new_buf) = LogData::from_compact(buf, buf.len()); buf = new_buf; - let log = Log { address, data: log_data }; + let log = Self { address, data: log_data }; (log, buf) } } diff --git a/crates/storage/codecs/src/alloy/request.rs b/crates/storage/codecs/src/alloy/request.rs index d5d4daa4a..c732e30b2 100644 --- a/crates/storage/codecs/src/alloy/request.rs +++ b/crates/storage/codecs/src/alloy/request.rs @@ -18,7 +18,7 @@ impl Compact for Request { fn from_compact(buf: &[u8], _: usize) -> (Self, &[u8]) { let (raw, buf) = Bytes::from_compact(buf, buf.len()); - (Request::decode_7685(&mut raw.as_ref()).expect("invalid eip-7685 request in db"), buf) + (Self::decode_7685(&mut raw.as_ref()).expect("invalid eip-7685 request in db"), buf) } } diff --git a/crates/storage/codecs/src/alloy/txkind.rs b/crates/storage/codecs/src/alloy/txkind.rs index e1dffa15b..14ab51236 100644 --- a/crates/storage/codecs/src/alloy/txkind.rs +++ b/crates/storage/codecs/src/alloy/txkind.rs @@ -9,8 +9,8 @@ impl Compact for TxKind { B: bytes::BufMut + AsMut<[u8]>, { match self { - TxKind::Create => 0, - TxKind::Call(address) => { + Self::Create => 0, + Self::Call(address) => { address.to_compact(buf); 1 } @@ -18,7 +18,7 @@ impl Compact for TxKind { } fn from_compact(buf: &[u8], identifier: usize) -> (Self, &[u8]) { match identifier { - 0 => (TxKind::Create, buf), + 0 => (Self::Create, buf), 1 => { let (addr, buf) = Address::from_compact(buf, buf.len()); (addr.into(), buf) diff --git a/crates/storage/codecs/src/alloy/withdrawal.rs b/crates/storage/codecs/src/alloy/withdrawal.rs index 5cdc1a667..3238048ad 100644 --- a/crates/storage/codecs/src/alloy/withdrawal.rs +++ b/crates/storage/codecs/src/alloy/withdrawal.rs @@ -35,7 +35,7 @@ impl Compact for AlloyWithdrawal { fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { let (withdrawal, _) = Withdrawal::from_compact(buf, len); - let alloy_withdrawal = AlloyWithdrawal { + let alloy_withdrawal = Self { index: withdrawal.index, validator_index: withdrawal.validator_index, address: withdrawal.address, diff --git a/crates/storage/codecs/src/lib.rs b/crates/storage/codecs/src/lib.rs index 79f579919..b0927a148 100644 --- a/crates/storage/codecs/src/lib.rs +++ b/crates/storage/codecs/src/lib.rs @@ -153,7 +153,7 @@ where #[inline] fn from_compact(buf: &[u8], _: usize) -> (Self, &[u8]) { let (length, mut buf) = decode_varuint(buf); - let mut list = Vec::with_capacity(length); + let mut list = Self::with_capacity(length); for _ in 0..length { let len; (len, buf) = decode_varuint(buf); @@ -184,7 +184,7 @@ where #[inline] fn specialized_from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) { let (length, mut buf) = decode_varuint(buf); - let mut list = Vec::with_capacity(length); + let mut list = Self::with_capacity(length); for _ in 0..length { let element; @@ -274,13 +274,13 @@ impl Compact for U256 { #[inline] fn from_compact(mut buf: &[u8], len: usize) -> (Self, &[u8]) { if len == 0 { - return (U256::ZERO, buf) + return (Self::ZERO, buf) } let mut arr = [0; 32]; arr[(32 - len)..].copy_from_slice(&buf[..len]); buf.advance(len); - (U256::from_be_bytes(arr), buf) + (Self::from_be_bytes(arr), buf) } } @@ -573,7 +573,7 @@ mod tests { impl Default for TestStruct { fn default() -> Self { - TestStruct { + Self { f_u64: 1u64, // 4 bits | 1 byte f_u256: U256::from(1u64), // 6 bits | 1 byte f_bool_f: false, // 1 bit | 0 bytes diff --git a/crates/storage/db/src/abstraction/mock.rs b/crates/storage/db/src/abstraction/mock.rs index cb6717036..f62746cca 100644 --- a/crates/storage/db/src/abstraction/mock.rs +++ b/crates/storage/db/src/abstraction/mock.rs @@ -138,8 +138,8 @@ impl DbCursorRO for CursorMock { fn walk(&mut self, start_key: Option) -> Result, DatabaseError> { let start: IterPairResult = match start_key { - Some(key) => >::seek(self, key).transpose(), - None => >::first(self).transpose(), + Some(key) => >::seek(self, key).transpose(), + None => >::first(self).transpose(), }; Ok(Walker::new(self, start)) @@ -160,8 +160,8 @@ impl DbCursorRO for CursorMock { }; let start: IterPairResult = match start_key { - Some(key) => >::seek(self, key).transpose(), - None => >::first(self).transpose(), + Some(key) => >::seek(self, key).transpose(), + None => >::first(self).transpose(), }; Ok(RangeWalker::new(self, start, end_key)) @@ -172,8 +172,8 @@ impl DbCursorRO for CursorMock { start_key: Option, ) -> Result, DatabaseError> { let start: IterPairResult = match start_key { - Some(key) => >::seek(self, key).transpose(), - None => >::last(self).transpose(), + Some(key) => >::seek(self, key).transpose(), + None => >::last(self).transpose(), }; Ok(ReverseWalker::new(self, start)) } diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index 58977811f..6f19bd911 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -250,7 +250,7 @@ impl DatabaseEnv { path: &Path, kind: DatabaseEnvKind, args: DatabaseArguments, - ) -> Result { + ) -> Result { let mut inner_env = Environment::builder(); let mode = match kind { @@ -379,7 +379,7 @@ impl DatabaseEnv { inner_env.set_max_read_transaction_duration(max_read_transaction_duration); } - let env = DatabaseEnv { + let env = Self { inner: inner_env.open(path).map_err(|e| DatabaseError::Open(e.into()))?, metrics: None, }; diff --git a/crates/storage/db/src/metrics.rs b/crates/storage/db/src/metrics.rs index a37ca123f..16d19beb5 100644 --- a/crates/storage/db/src/metrics.rs +++ b/crates/storage/db/src/metrics.rs @@ -156,14 +156,14 @@ impl TransactionMode { /// Returns the transaction mode as a string. pub(crate) const fn as_str(&self) -> &'static str { match self { - TransactionMode::ReadOnly => "read-only", - TransactionMode::ReadWrite => "read-write", + Self::ReadOnly => "read-only", + Self::ReadWrite => "read-write", } } /// Returns `true` if the transaction mode is read-only. pub(crate) const fn is_read_only(&self) -> bool { - matches!(self, TransactionMode::ReadOnly) + matches!(self, Self::ReadOnly) } } @@ -182,15 +182,15 @@ impl TransactionOutcome { /// Returns the transaction outcome as a string. pub(crate) const fn as_str(&self) -> &'static str { match self { - TransactionOutcome::Commit => "commit", - TransactionOutcome::Abort => "abort", - TransactionOutcome::Drop => "drop", + Self::Commit => "commit", + Self::Abort => "abort", + Self::Drop => "drop", } } /// Returns `true` if the transaction outcome is a commit. pub(crate) const fn is_commit(&self) -> bool { - matches!(self, TransactionOutcome::Commit) + matches!(self, Self::Commit) } } @@ -221,15 +221,15 @@ impl Operation { /// Returns the operation as a string. pub(crate) const fn as_str(&self) -> &'static str { match self { - Operation::Get => "get", - Operation::Put => "put", - Operation::Delete => "delete", - Operation::CursorUpsert => "cursor-upsert", - Operation::CursorInsert => "cursor-insert", - Operation::CursorAppend => "cursor-append", - Operation::CursorAppendDup => "cursor-append-dup", - Operation::CursorDeleteCurrent => "cursor-delete-current", - Operation::CursorDeleteCurrentDuplicates => "cursor-delete-current-duplicates", + Self::Get => "get", + Self::Put => "put", + Self::Delete => "delete", + Self::CursorUpsert => "cursor-upsert", + Self::CursorInsert => "cursor-insert", + Self::CursorAppend => "cursor-append", + Self::CursorAppendDup => "cursor-append-dup", + Self::CursorDeleteCurrent => "cursor-delete-current", + Self::CursorDeleteCurrentDuplicates => "cursor-delete-current-duplicates", } } } @@ -250,10 +250,10 @@ impl Labels { /// Converts each label variant into its corresponding string representation. pub(crate) fn as_str(&self) -> &'static str { match self { - Labels::Table => "table", - Labels::TransactionMode => "mode", - Labels::TransactionOutcome => "outcome", - Labels::Operation => "operation", + Self::Table => "table", + Self::TransactionMode => "mode", + Self::TransactionOutcome => "outcome", + Self::Operation => "operation", } } } diff --git a/crates/storage/db/src/tables/codecs/fuzz/inputs.rs b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs index ff8d8b39c..533b6b692 100644 --- a/crates/storage/db/src/tables/codecs/fuzz/inputs.rs +++ b/crates/storage/db/src/tables/codecs/fuzz/inputs.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; pub struct IntegerListInput(pub Vec); impl From for IntegerList { - fn from(list: IntegerListInput) -> IntegerList { + fn from(list: IntegerListInput) -> Self { let mut v = list.0; // Empty lists are not supported by `IntegerList`, so we want to skip these cases. diff --git a/crates/storage/db/src/tables/models/accounts.rs b/crates/storage/db/src/tables/models/accounts.rs index 7b0770da2..9549aa8e6 100644 --- a/crates/storage/db/src/tables/models/accounts.rs +++ b/crates/storage/db/src/tables/models/accounts.rs @@ -92,7 +92,7 @@ impl BlockNumberAddress { impl From<(BlockNumber, Address)> for BlockNumberAddress { fn from(tpl: (u64, Address)) -> Self { - BlockNumberAddress(tpl) + Self(tpl) } } @@ -117,7 +117,7 @@ impl Decode for BlockNumberAddress { let num = u64::from_be_bytes(value[..8].try_into().map_err(|_| DatabaseError::Decode)?); let hash = Address::from_slice(&value[8..]); - Ok(BlockNumberAddress((num, hash))) + Ok(Self((num, hash))) } } @@ -150,7 +150,7 @@ impl Decode for AddressStorageKey { let address = Address::from_slice(&value[..20]); let storage_key = StorageKey::from_slice(&value[20..]); - Ok(AddressStorageKey((address, storage_key))) + Ok(Self((address, storage_key))) } } diff --git a/crates/storage/db/src/tables/models/integer_list.rs b/crates/storage/db/src/tables/models/integer_list.rs index 94746a121..e419a9435 100644 --- a/crates/storage/db/src/tables/models/integer_list.rs +++ b/crates/storage/db/src/tables/models/integer_list.rs @@ -19,6 +19,6 @@ impl Compress for IntegerList { impl Decompress for IntegerList { fn decompress>(value: B) -> Result { - IntegerList::from_bytes(value.as_ref()).map_err(|_| DatabaseError::Decode) + Self::from_bytes(value.as_ref()).map_err(|_| DatabaseError::Decode) } } diff --git a/crates/storage/db/src/tables/models/mod.rs b/crates/storage/db/src/tables/models/mod.rs index f1270cec3..4a15a2d55 100644 --- a/crates/storage/db/src/tables/models/mod.rs +++ b/crates/storage/db/src/tables/models/mod.rs @@ -51,7 +51,7 @@ macro_rules! impl_uints { impl_uints!(u64, u32, u16, u8); impl Encode for Vec { - type Encoded = Vec; + type Encoded = Self; fn encode(self) -> Self::Encoded { self @@ -74,7 +74,7 @@ impl Encode for Address { impl Decode for Address { fn decode>(value: B) -> Result { - Ok(Address::from_slice(value.as_ref())) + Ok(Self::from_slice(value.as_ref())) } } @@ -88,7 +88,7 @@ impl Encode for B256 { impl Decode for B256 { fn decode>(value: B) -> Result { - Ok(B256::new(value.as_ref().try_into().map_err(|_| DatabaseError::Decode)?)) + Ok(Self::new(value.as_ref().try_into().map_err(|_| DatabaseError::Decode)?)) } } @@ -102,7 +102,7 @@ impl Encode for String { impl Decode for String { fn decode>(value: B) -> Result { - String::from_utf8(value.as_ref().to_vec()).map_err(|_| DatabaseError::Decode) + Self::from_utf8(value.as_ref().to_vec()).map_err(|_| DatabaseError::Decode) } } diff --git a/crates/storage/db/src/tables/models/sharded_key.rs b/crates/storage/db/src/tables/models/sharded_key.rs index 9c0664da4..3a55baeda 100644 --- a/crates/storage/db/src/tables/models/sharded_key.rs +++ b/crates/storage/db/src/tables/models/sharded_key.rs @@ -26,8 +26,8 @@ pub struct ShardedKey { pub highest_block_number: BlockNumber, } -impl AsRef> for ShardedKey { - fn as_ref(&self) -> &ShardedKey { +impl AsRef for ShardedKey { + fn as_ref(&self) -> &Self { self } } @@ -35,7 +35,7 @@ impl AsRef> for ShardedKey { impl ShardedKey { /// Creates a new `ShardedKey`. pub fn new(key: T, highest_block_number: BlockNumber) -> Self { - ShardedKey { key, highest_block_number } + Self { key, highest_block_number } } /// Creates a new key with the highest block number set to maximum. @@ -73,7 +73,7 @@ where ); let key = T::decode(&value[..tx_num_index])?; - Ok(ShardedKey::new(key, highest_tx_number)) + Ok(Self::new(key, highest_tx_number)) } } diff --git a/crates/storage/db/src/tables/raw.rs b/crates/storage/db/src/tables/raw.rs index 90d4b96ae..21bcc281c 100644 --- a/crates/storage/db/src/tables/raw.rs +++ b/crates/storage/db/src/tables/raw.rs @@ -77,7 +77,7 @@ impl RawKey { impl From for RawKey { fn from(key: K) -> Self { - RawKey::new(key) + Self::new(key) } } @@ -142,7 +142,7 @@ impl RawValue { impl From for RawValue { fn from(value: V) -> Self { - RawValue::new(value) + Self::new(value) } } diff --git a/crates/storage/errors/src/provider.rs b/crates/storage/errors/src/provider.rs index 6ae7aad8e..aeecf64a7 100644 --- a/crates/storage/errors/src/provider.rs +++ b/crates/storage/errors/src/provider.rs @@ -132,7 +132,7 @@ pub enum ProviderError { impl From for ProviderError { fn from(err: reth_fs_util::FsPathError) -> Self { - ProviderError::FsPathError(err.to_string()) + Self::FsPathError(err.to_string()) } } diff --git a/crates/storage/libmdbx-rs/src/database.rs b/crates/storage/libmdbx-rs/src/database.rs index 55eb7e0bb..4e3a6c062 100644 --- a/crates/storage/libmdbx-rs/src/database.rs +++ b/crates/storage/libmdbx-rs/src/database.rs @@ -42,7 +42,7 @@ impl Database { /// Opens the freelist database with DBI `0`. pub fn freelist_db() -> Self { - Database { dbi: 0, _env: None } + Self { dbi: 0, _env: None } } /// Returns the underlying MDBX database handle. diff --git a/crates/storage/libmdbx-rs/src/environment.rs b/crates/storage/libmdbx-rs/src/environment.rs index ba7385b94..c6d206435 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -281,14 +281,14 @@ impl EnvironmentKind { /// Returns true if the environment was opened as WRITEMAP. #[inline] pub const fn is_write_map(&self) -> bool { - matches!(self, EnvironmentKind::WriteMap) + matches!(self, Self::WriteMap) } /// Additional flags required when opening the environment. pub(crate) fn extra_flags(&self) -> ffi::MDBX_env_flags_t { match self { - EnvironmentKind::Default => ffi::MDBX_ENV_DEFAULTS, - EnvironmentKind::WriteMap => ffi::MDBX_WRITEMAP, + Self::Default => ffi::MDBX_ENV_DEFAULTS, + Self::WriteMap => ffi::MDBX_WRITEMAP, } } } @@ -307,8 +307,8 @@ pub struct Stat(ffi::MDBX_stat); impl Stat { /// Create a new Stat with zero'd inner struct `ffi::MDB_stat`. - pub(crate) fn new() -> Stat { - unsafe { Stat(mem::zeroed()) } + pub(crate) fn new() -> Self { + unsafe { Self(mem::zeroed()) } } /// Returns a mut pointer to `ffi::MDB_stat`. @@ -859,8 +859,8 @@ pub(crate) mod read_transactions { impl MaxReadTransactionDuration { pub fn as_duration(&self) -> Option { match self { - MaxReadTransactionDuration::Unbounded => None, - MaxReadTransactionDuration::Set(duration) => Some(*duration), + Self::Unbounded => None, + Self::Set(duration) => Some(*duration), } } } diff --git a/crates/storage/libmdbx-rs/src/error.rs b/crates/storage/libmdbx-rs/src/error.rs index 84a6ef361..4776cc4ae 100644 --- a/crates/storage/libmdbx-rs/src/error.rs +++ b/crates/storage/libmdbx-rs/src/error.rs @@ -127,77 +127,77 @@ pub enum Error { impl Error { /// Converts a raw error code to an [Error]. - pub fn from_err_code(err_code: c_int) -> Error { + pub fn from_err_code(err_code: c_int) -> Self { match err_code { - ffi::MDBX_KEYEXIST => Error::KeyExist, - ffi::MDBX_NOTFOUND => Error::NotFound, - ffi::MDBX_ENODATA => Error::NoData, - ffi::MDBX_PAGE_NOTFOUND => Error::PageNotFound, - ffi::MDBX_CORRUPTED => Error::Corrupted, - ffi::MDBX_PANIC => Error::Panic, - ffi::MDBX_VERSION_MISMATCH => Error::VersionMismatch, - ffi::MDBX_INVALID => Error::Invalid, - ffi::MDBX_MAP_FULL => Error::MapFull, - ffi::MDBX_DBS_FULL => Error::DbsFull, - ffi::MDBX_READERS_FULL => Error::ReadersFull, - ffi::MDBX_TXN_FULL => Error::TxnFull, - ffi::MDBX_CURSOR_FULL => Error::CursorFull, - ffi::MDBX_PAGE_FULL => Error::PageFull, - ffi::MDBX_UNABLE_EXTEND_MAPSIZE => Error::UnableExtendMapSize, - ffi::MDBX_INCOMPATIBLE => Error::Incompatible, - ffi::MDBX_BAD_RSLOT => Error::BadRslot, - ffi::MDBX_BAD_TXN => Error::BadTxn, - ffi::MDBX_BAD_VALSIZE => Error::BadValSize, - ffi::MDBX_BAD_DBI => Error::BadDbi, - ffi::MDBX_PROBLEM => Error::Problem, - ffi::MDBX_BUSY => Error::Busy, - ffi::MDBX_EMULTIVAL => Error::Multival, - ffi::MDBX_WANNA_RECOVERY => Error::WannaRecovery, - ffi::MDBX_EKEYMISMATCH => Error::KeyMismatch, - ffi::MDBX_EINVAL => Error::DecodeError, - ffi::MDBX_EACCESS => Error::Access, - ffi::MDBX_TOO_LARGE => Error::TooLarge, - ffi::MDBX_EBADSIGN => Error::BadSignature, - other => Error::Other(other), + ffi::MDBX_KEYEXIST => Self::KeyExist, + ffi::MDBX_NOTFOUND => Self::NotFound, + ffi::MDBX_ENODATA => Self::NoData, + ffi::MDBX_PAGE_NOTFOUND => Self::PageNotFound, + ffi::MDBX_CORRUPTED => Self::Corrupted, + ffi::MDBX_PANIC => Self::Panic, + ffi::MDBX_VERSION_MISMATCH => Self::VersionMismatch, + ffi::MDBX_INVALID => Self::Invalid, + ffi::MDBX_MAP_FULL => Self::MapFull, + ffi::MDBX_DBS_FULL => Self::DbsFull, + ffi::MDBX_READERS_FULL => Self::ReadersFull, + ffi::MDBX_TXN_FULL => Self::TxnFull, + ffi::MDBX_CURSOR_FULL => Self::CursorFull, + ffi::MDBX_PAGE_FULL => Self::PageFull, + ffi::MDBX_UNABLE_EXTEND_MAPSIZE => Self::UnableExtendMapSize, + ffi::MDBX_INCOMPATIBLE => Self::Incompatible, + ffi::MDBX_BAD_RSLOT => Self::BadRslot, + ffi::MDBX_BAD_TXN => Self::BadTxn, + ffi::MDBX_BAD_VALSIZE => Self::BadValSize, + ffi::MDBX_BAD_DBI => Self::BadDbi, + ffi::MDBX_PROBLEM => Self::Problem, + ffi::MDBX_BUSY => Self::Busy, + ffi::MDBX_EMULTIVAL => Self::Multival, + ffi::MDBX_WANNA_RECOVERY => Self::WannaRecovery, + ffi::MDBX_EKEYMISMATCH => Self::KeyMismatch, + ffi::MDBX_EINVAL => Self::DecodeError, + ffi::MDBX_EACCESS => Self::Access, + ffi::MDBX_TOO_LARGE => Self::TooLarge, + ffi::MDBX_EBADSIGN => Self::BadSignature, + other => Self::Other(other), } } /// Converts an [Error] to the raw error code. pub fn to_err_code(&self) -> i32 { match self { - Error::KeyExist => ffi::MDBX_KEYEXIST, - Error::NotFound => ffi::MDBX_NOTFOUND, - Error::NoData => ffi::MDBX_ENODATA, - Error::PageNotFound => ffi::MDBX_PAGE_NOTFOUND, - Error::Corrupted => ffi::MDBX_CORRUPTED, - Error::Panic => ffi::MDBX_PANIC, - Error::VersionMismatch => ffi::MDBX_VERSION_MISMATCH, - Error::Invalid => ffi::MDBX_INVALID, - Error::MapFull => ffi::MDBX_MAP_FULL, - Error::DbsFull => ffi::MDBX_DBS_FULL, - Error::ReadersFull => ffi::MDBX_READERS_FULL, - Error::TxnFull => ffi::MDBX_TXN_FULL, - Error::CursorFull => ffi::MDBX_CURSOR_FULL, - Error::PageFull => ffi::MDBX_PAGE_FULL, - Error::UnableExtendMapSize => ffi::MDBX_UNABLE_EXTEND_MAPSIZE, - Error::Incompatible => ffi::MDBX_INCOMPATIBLE, - Error::BadRslot => ffi::MDBX_BAD_RSLOT, - Error::BadTxn => ffi::MDBX_BAD_TXN, - Error::BadValSize => ffi::MDBX_BAD_VALSIZE, - Error::BadDbi => ffi::MDBX_BAD_DBI, - Error::Problem => ffi::MDBX_PROBLEM, - Error::Busy => ffi::MDBX_BUSY, - Error::Multival => ffi::MDBX_EMULTIVAL, - Error::WannaRecovery => ffi::MDBX_WANNA_RECOVERY, - Error::KeyMismatch => ffi::MDBX_EKEYMISMATCH, - Error::DecodeErrorLenDiff | Error::DecodeError => ffi::MDBX_EINVAL, - Error::Access => ffi::MDBX_EACCESS, - Error::TooLarge => ffi::MDBX_TOO_LARGE, - Error::BadSignature => ffi::MDBX_EBADSIGN, - Error::WriteTransactionUnsupportedInReadOnlyMode => ffi::MDBX_EACCESS, - Error::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, - Error::ReadTransactionTimeout => -96000, // Custom non-MDBX error code - Error::Other(err_code) => *err_code, + Self::KeyExist => ffi::MDBX_KEYEXIST, + Self::NotFound => ffi::MDBX_NOTFOUND, + Self::NoData => ffi::MDBX_ENODATA, + Self::PageNotFound => ffi::MDBX_PAGE_NOTFOUND, + Self::Corrupted => ffi::MDBX_CORRUPTED, + Self::Panic => ffi::MDBX_PANIC, + Self::VersionMismatch => ffi::MDBX_VERSION_MISMATCH, + Self::Invalid => ffi::MDBX_INVALID, + Self::MapFull => ffi::MDBX_MAP_FULL, + Self::DbsFull => ffi::MDBX_DBS_FULL, + Self::ReadersFull => ffi::MDBX_READERS_FULL, + Self::TxnFull => ffi::MDBX_TXN_FULL, + Self::CursorFull => ffi::MDBX_CURSOR_FULL, + Self::PageFull => ffi::MDBX_PAGE_FULL, + Self::UnableExtendMapSize => ffi::MDBX_UNABLE_EXTEND_MAPSIZE, + Self::Incompatible => ffi::MDBX_INCOMPATIBLE, + Self::BadRslot => ffi::MDBX_BAD_RSLOT, + Self::BadTxn => ffi::MDBX_BAD_TXN, + Self::BadValSize => ffi::MDBX_BAD_VALSIZE, + Self::BadDbi => ffi::MDBX_BAD_DBI, + Self::Problem => ffi::MDBX_PROBLEM, + Self::Busy => ffi::MDBX_BUSY, + Self::Multival => ffi::MDBX_EMULTIVAL, + Self::WannaRecovery => ffi::MDBX_WANNA_RECOVERY, + Self::KeyMismatch => ffi::MDBX_EKEYMISMATCH, + Self::DecodeErrorLenDiff | Self::DecodeError => ffi::MDBX_EINVAL, + Self::Access => ffi::MDBX_EACCESS, + Self::TooLarge => ffi::MDBX_TOO_LARGE, + Self::BadSignature => ffi::MDBX_EBADSIGN, + Self::WriteTransactionUnsupportedInReadOnlyMode => ffi::MDBX_EACCESS, + Self::NestedTransactionsUnsupportedWithWriteMap => ffi::MDBX_EACCESS, + Self::ReadTransactionTimeout => -96000, // Custom non-MDBX error code + Self::Other(err_code) => *err_code, } } } diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index 45259ba7b..20fcddead 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -502,7 +502,7 @@ impl Transaction { impl Transaction { /// Begins a new nested transaction inside of this transaction. - pub fn begin_nested_txn(&mut self) -> Result> { + pub fn begin_nested_txn(&mut self) -> Result { if self.inner.env.is_write_map() { return Err(Error::NestedTransactionsUnsupportedWithWriteMap) } @@ -514,7 +514,7 @@ impl Transaction { sender: tx, }); - rx.recv().unwrap().map(|ptr| Transaction::new_from_ptr(self.env().clone(), ptr.0)) + rx.recv().unwrap().map(|ptr| Self::new_from_ptr(self.env().clone(), ptr.0)) })? } } diff --git a/crates/storage/nippy-jar/src/compression/mod.rs b/crates/storage/nippy-jar/src/compression/mod.rs index a8f99fa53..76e8c6d16 100644 --- a/crates/storage/nippy-jar/src/compression/mod.rs +++ b/crates/storage/nippy-jar/src/compression/mod.rs @@ -50,14 +50,14 @@ pub enum Compressors { impl Compression for Compressors { fn decompress_to(&self, value: &[u8], dest: &mut Vec) -> Result<(), NippyJarError> { match self { - Compressors::Zstd(zstd) => zstd.decompress_to(value, dest), - Compressors::Lz4(lz4) => lz4.decompress_to(value, dest), + Self::Zstd(zstd) => zstd.decompress_to(value, dest), + Self::Lz4(lz4) => lz4.decompress_to(value, dest), } } fn decompress(&self, value: &[u8]) -> Result, NippyJarError> { match self { - Compressors::Zstd(zstd) => zstd.decompress(value), - Compressors::Lz4(lz4) => lz4.decompress(value), + Self::Zstd(zstd) => zstd.decompress(value), + Self::Lz4(lz4) => lz4.decompress(value), } } @@ -65,8 +65,8 @@ impl Compression for Compressors { let initial_capacity = dest.capacity(); loop { let result = match self { - Compressors::Zstd(zstd) => zstd.compress_to(src, dest), - Compressors::Lz4(lz4) => lz4.compress_to(src, dest), + Self::Zstd(zstd) => zstd.compress_to(src, dest), + Self::Lz4(lz4) => lz4.compress_to(src, dest), }; match result { @@ -83,15 +83,15 @@ impl Compression for Compressors { fn compress(&self, src: &[u8]) -> Result, NippyJarError> { match self { - Compressors::Zstd(zstd) => zstd.compress(src), - Compressors::Lz4(lz4) => lz4.compress(src), + Self::Zstd(zstd) => zstd.compress(src), + Self::Lz4(lz4) => lz4.compress(src), } } fn is_ready(&self) -> bool { match self { - Compressors::Zstd(zstd) => zstd.is_ready(), - Compressors::Lz4(lz4) => lz4.is_ready(), + Self::Zstd(zstd) => zstd.is_ready(), + Self::Lz4(lz4) => lz4.is_ready(), } } @@ -100,8 +100,8 @@ impl Compression for Compressors { columns: Vec>>, ) -> Result<(), NippyJarError> { match self { - Compressors::Zstd(zstd) => zstd.prepare_compression(columns), - Compressors::Lz4(lz4) => lz4.prepare_compression(columns), + Self::Zstd(zstd) => zstd.prepare_compression(columns), + Self::Lz4(lz4) => lz4.prepare_compression(columns), } } } diff --git a/crates/storage/nippy-jar/src/filter/cuckoo.rs b/crates/storage/nippy-jar/src/filter/cuckoo.rs index 7c05a8f58..0e338a032 100644 --- a/crates/storage/nippy-jar/src/filter/cuckoo.rs +++ b/crates/storage/nippy-jar/src/filter/cuckoo.rs @@ -21,7 +21,7 @@ impl Cuckoo { // close to capacity. Therefore, we increase it. let max_capacity = max_capacity + 100 + max_capacity / 3; - Cuckoo { remaining: max_capacity, filter: CuckooFilter::with_capacity(max_capacity) } + Self { remaining: max_capacity, filter: CuckooFilter::with_capacity(max_capacity) } } } @@ -73,7 +73,7 @@ impl<'de> Deserialize<'de> for Cuckoo { let (remaining, exported): (usize, ExportedCuckooFilter) = Deserialize::deserialize(deserializer)?; - Ok(Cuckoo { remaining, filter: exported.into() }) + Ok(Self { remaining, filter: exported.into() }) } } diff --git a/crates/storage/nippy-jar/src/filter/mod.rs b/crates/storage/nippy-jar/src/filter/mod.rs index dd3e78049..3ddae0148 100644 --- a/crates/storage/nippy-jar/src/filter/mod.rs +++ b/crates/storage/nippy-jar/src/filter/mod.rs @@ -27,22 +27,22 @@ pub enum InclusionFilters { impl InclusionFilter for InclusionFilters { fn add(&mut self, element: &[u8]) -> Result<(), NippyJarError> { match self { - InclusionFilters::Cuckoo(c) => c.add(element), - InclusionFilters::Unused => todo!(), + Self::Cuckoo(c) => c.add(element), + Self::Unused => todo!(), } } fn contains(&self, element: &[u8]) -> Result { match self { - InclusionFilters::Cuckoo(c) => c.contains(element), - InclusionFilters::Unused => todo!(), + Self::Cuckoo(c) => c.contains(element), + Self::Unused => todo!(), } } fn size(&self) -> usize { match self { - InclusionFilters::Cuckoo(c) => c.size(), - InclusionFilters::Unused => 0, + Self::Cuckoo(c) => c.size(), + Self::Unused => 0, } } } diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index 2eafe68c4..6a629702b 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -144,12 +144,12 @@ impl std::fmt::Debug for NippyJar { impl NippyJar<()> { /// Creates a new [`NippyJar`] without an user-defined header data. pub fn new_without_header(columns: usize, path: &Path) -> Self { - NippyJar::<()>::new(columns, path, ()) + Self::new(columns, path, ()) } /// Loads the file configuration and returns [`Self`] on a jar without user-defined header data. pub fn load_without_header(path: &Path) -> Result { - NippyJar::<()>::load(path) + Self::load(path) } /// Whether this [`NippyJar`] uses a [`InclusionFilters`] and [`Functions`]. @@ -161,7 +161,7 @@ impl NippyJar<()> { impl NippyJar { /// Creates a new [`NippyJar`] with a user-defined header data. pub fn new(columns: usize, path: &Path, user_header: H) -> Self { - NippyJar { + Self { version: NIPPY_JAR_VERSION, user_header, columns, diff --git a/crates/storage/nippy-jar/src/phf/fmph.rs b/crates/storage/nippy-jar/src/phf/fmph.rs index 8753334b5..7a67ecd3b 100644 --- a/crates/storage/nippy-jar/src/phf/fmph.rs +++ b/crates/storage/nippy-jar/src/phf/fmph.rs @@ -88,12 +88,12 @@ impl<'de> Deserialize<'de> for Fmph { D: Deserializer<'de>, { if let Some(buffer) = >>::deserialize(deserializer)? { - return Ok(Fmph { + return Ok(Self { function: Some( Function::read(&mut std::io::Cursor::new(buffer)).map_err(D::Error::custom)?, ), }) } - Ok(Fmph { function: None }) + 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 b2ed28f68..f0a6507b4 100644 --- a/crates/storage/nippy-jar/src/phf/go_fmph.rs +++ b/crates/storage/nippy-jar/src/phf/go_fmph.rs @@ -88,13 +88,13 @@ impl<'de> Deserialize<'de> for GoFmph { D: Deserializer<'de>, { if let Some(buffer) = >>::deserialize(deserializer)? { - return Ok(GoFmph { + return Ok(Self { function: Some( GOFunction::read(&mut std::io::Cursor::new(buffer)) .map_err(D::Error::custom)?, ), }) } - Ok(GoFmph { function: None }) + Ok(Self { function: None }) } } diff --git a/crates/storage/nippy-jar/src/phf/mod.rs b/crates/storage/nippy-jar/src/phf/mod.rs index 5ac5d5169..ade48b60a 100644 --- a/crates/storage/nippy-jar/src/phf/mod.rs +++ b/crates/storage/nippy-jar/src/phf/mod.rs @@ -32,15 +32,15 @@ pub enum Functions { impl PerfectHashingFunction for Functions { fn set_keys(&mut self, keys: &[T]) -> Result<(), NippyJarError> { match self { - Functions::Fmph(f) => f.set_keys(keys), - Functions::GoFmph(f) => f.set_keys(keys), + Self::Fmph(f) => f.set_keys(keys), + Self::GoFmph(f) => f.set_keys(keys), } } fn get_index(&self, key: &[u8]) -> Result, NippyJarError> { match self { - Functions::Fmph(f) => f.get_index(key), - Functions::GoFmph(f) => f.get_index(key), + Self::Fmph(f) => f.get_index(key), + Self::GoFmph(f) => f.get_index(key), } } } diff --git a/crates/storage/provider/src/providers/database/metrics.rs b/crates/storage/provider/src/providers/database/metrics.rs index 0eb21aed8..57f67847d 100644 --- a/crates/storage/provider/src/providers/database/metrics.rs +++ b/crates/storage/provider/src/providers/database/metrics.rs @@ -67,28 +67,28 @@ pub(crate) enum Action { impl Action { fn as_str(&self) -> &'static str { match self { - Action::InsertStorageHashing => "insert storage hashing", - Action::InsertAccountHashing => "insert account hashing", - Action::InsertMerkleTree => "insert merkle tree", - Action::InsertBlock => "insert block", - Action::InsertState => "insert state", - Action::InsertHashes => "insert hashes", - Action::InsertHistoryIndices => "insert history indices", - Action::UpdatePipelineStages => "update pipeline stages", - Action::InsertCanonicalHeaders => "insert canonical headers", - Action::InsertHeaders => "insert headers", - Action::InsertHeaderNumbers => "insert header numbers", - Action::InsertHeaderTerminalDifficulties => "insert header TD", - Action::InsertBlockOmmers => "insert block ommers", - Action::InsertTransactionSenders => "insert tx senders", - Action::InsertTransactions => "insert transactions", - Action::InsertTransactionHashNumbers => "insert transaction hash numbers", - Action::InsertBlockWithdrawals => "insert block withdrawals", - Action::InsertBlockRequests => "insert block withdrawals", - Action::InsertBlockBodyIndices => "insert block body indices", - Action::InsertTransactionBlocks => "insert transaction blocks", - Action::GetNextTxNum => "get next tx num", - Action::GetParentTD => "get parent TD", + Self::InsertStorageHashing => "insert storage hashing", + Self::InsertAccountHashing => "insert account hashing", + Self::InsertMerkleTree => "insert merkle tree", + Self::InsertBlock => "insert block", + Self::InsertState => "insert state", + Self::InsertHashes => "insert hashes", + Self::InsertHistoryIndices => "insert history indices", + Self::UpdatePipelineStages => "update pipeline stages", + Self::InsertCanonicalHeaders => "insert canonical headers", + Self::InsertHeaders => "insert headers", + Self::InsertHeaderNumbers => "insert header numbers", + Self::InsertHeaderTerminalDifficulties => "insert header TD", + Self::InsertBlockOmmers => "insert block ommers", + Self::InsertTransactionSenders => "insert tx senders", + Self::InsertTransactions => "insert transactions", + Self::InsertTransactionHashNumbers => "insert transaction hash numbers", + Self::InsertBlockWithdrawals => "insert block withdrawals", + Self::InsertBlockRequests => "insert block withdrawals", + Self::InsertBlockBodyIndices => "insert block body indices", + Self::InsertTransactionBlocks => "insert transaction blocks", + Self::GetNextTxNum => "get next tx num", + Self::GetParentTD => "get parent TD", } } } diff --git a/crates/storage/provider/src/providers/database/mod.rs b/crates/storage/provider/src/providers/database/mod.rs index f7ab2e574..8b83cc26a 100644 --- a/crates/storage/provider/src/providers/database/mod.rs +++ b/crates/storage/provider/src/providers/database/mod.rs @@ -54,7 +54,7 @@ impl ProviderFactory { db: DB, chain_spec: Arc, static_files_path: PathBuf, - ) -> ProviderResult> { + ) -> ProviderResult { Ok(Self { db: Arc::new(db), chain_spec, @@ -89,7 +89,7 @@ impl ProviderFactory { args: DatabaseArguments, static_files_path: PathBuf, ) -> RethResult { - Ok(ProviderFactory:: { + Ok(Self { db: Arc::new(init_db(path, args).map_err(RethError::msg)?), chain_spec, static_file_provider: StaticFileProvider::new(static_files_path)?, @@ -577,7 +577,7 @@ impl PruneCheckpointReader for ProviderFactory { impl Clone for ProviderFactory { fn clone(&self) -> Self { - ProviderFactory { + Self { db: Arc::clone(&self.db), chain_spec: self.chain_spec.clone(), static_file_provider: self.static_file_provider.clone(), diff --git a/crates/storage/provider/src/providers/static_file/jar.rs b/crates/storage/provider/src/providers/static_file/jar.rs index 7f4b14fee..e296e1d0f 100644 --- a/crates/storage/provider/src/providers/static_file/jar.rs +++ b/crates/storage/provider/src/providers/static_file/jar.rs @@ -63,7 +63,7 @@ impl<'a> StaticFileJarProvider<'a> { } /// Adds a new auxiliary static file to help query data from the main one - pub fn with_auxiliary(mut self, auxiliary_jar: StaticFileJarProvider<'a>) -> Self { + pub fn with_auxiliary(mut self, auxiliary_jar: Self) -> Self { self.auxiliary_jar = Some(Box::new(auxiliary_jar)); self } diff --git a/crates/storage/provider/src/providers/static_file/manager.rs b/crates/storage/provider/src/providers/static_file/manager.rs index 1dfd15cd7..fd877a447 100644 --- a/crates/storage/provider/src/providers/static_file/manager.rs +++ b/crates/storage/provider/src/providers/static_file/manager.rs @@ -622,7 +622,7 @@ impl StaticFileProvider { fetch_from_database: FD, ) -> ProviderResult> where - FS: Fn(&StaticFileProvider) -> ProviderResult>, + FS: Fn(&Self) -> ProviderResult>, FD: Fn() -> ProviderResult>, { // If there is, check the maximum block or transaction number of the segment. @@ -661,7 +661,7 @@ impl StaticFileProvider { mut predicate: P, ) -> ProviderResult> where - FS: Fn(&StaticFileProvider, Range, &mut P) -> ProviderResult>, + FS: Fn(&Self, Range, &mut P) -> ProviderResult>, FD: FnMut(Range, P) -> ProviderResult>, P: FnMut(&T) -> bool, { diff --git a/crates/storage/provider/src/test_utils/mock.rs b/crates/storage/provider/src/test_utils/mock.rs index 3498677c0..0a8ce79f0 100644 --- a/crates/storage/provider/src/test_utils/mock.rs +++ b/crates/storage/provider/src/test_utils/mock.rs @@ -42,8 +42,8 @@ pub struct MockEthProvider { } impl Default for MockEthProvider { - fn default() -> MockEthProvider { - MockEthProvider { + fn default() -> Self { + Self { blocks: Default::default(), headers: Default::default(), accounts: Default::default(), diff --git a/crates/storage/storage-api/src/block.rs b/crates/storage/storage-api/src/block.rs index c85b15e39..8b8ec5835 100644 --- a/crates/storage/storage-api/src/block.rs +++ b/crates/storage/storage-api/src/block.rs @@ -32,12 +32,12 @@ pub enum BlockSource { impl BlockSource { /// Returns `true` if the block source is `Pending` or `Any`. pub fn is_pending(&self) -> bool { - matches!(self, BlockSource::Pending | BlockSource::Any) + matches!(self, Self::Pending | Self::Any) } /// Returns `true` if the block source is `Database` or `Any`. pub fn is_database(&self) -> bool { - matches!(self, BlockSource::Database | BlockSource::Any) + matches!(self, Self::Database | Self::Any) } } diff --git a/crates/tasks/src/lib.rs b/crates/tasks/src/lib.rs index 3e526a344..362a692d1 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -560,7 +560,7 @@ impl TaskSpawner for TaskExecutor { fn spawn_critical(&self, name: &'static str, fut: BoxFuture<'static, ()>) -> JoinHandle<()> { self.metrics.inc_critical_tasks(); - TaskExecutor::spawn_critical(self, name, fut) + Self::spawn_critical(self, name, fut) } fn spawn_blocking(&self, fut: BoxFuture<'static, ()>) -> JoinHandle<()> { @@ -572,7 +572,7 @@ impl TaskSpawner for TaskExecutor { name: &'static str, fut: BoxFuture<'static, ()>, ) -> JoinHandle<()> { - TaskExecutor::spawn_critical_blocking(self, name, fut) + Self::spawn_critical_blocking(self, name, fut) } } @@ -610,7 +610,7 @@ impl TaskSpawnerExt for TaskExecutor { where F: Future + Send + 'static, { - TaskExecutor::spawn_critical_with_graceful_shutdown_signal(self, name, f) + Self::spawn_critical_with_graceful_shutdown_signal(self, name, f) } fn spawn_with_graceful_shutdown_signal( @@ -620,7 +620,7 @@ impl TaskSpawnerExt for TaskExecutor { where F: Future + Send + 'static, { - TaskExecutor::spawn_with_graceful_shutdown_signal(self, f) + Self::spawn_with_graceful_shutdown_signal(self, f) } } diff --git a/crates/tasks/src/metrics.rs b/crates/tasks/src/metrics.rs index 127783cf0..a8397b7fe 100644 --- a/crates/tasks/src/metrics.rs +++ b/crates/tasks/src/metrics.rs @@ -42,7 +42,7 @@ impl fmt::Debug for IncCounterOnDrop { impl IncCounterOnDrop { /// Creates a new instance of `IncCounterOnDrop` with the given counter. pub fn new(counter: Counter) -> Self { - IncCounterOnDrop(counter) + Self(counter) } } diff --git a/crates/tokio-util/src/event_stream.rs b/crates/tokio-util/src/event_stream.rs index 67bc72a97..3faaece6d 100644 --- a/crates/tokio-util/src/event_stream.rs +++ b/crates/tokio-util/src/event_stream.rs @@ -20,7 +20,7 @@ where /// Creates a new `EventStream`. pub fn new(receiver: tokio::sync::broadcast::Receiver) -> Self { let inner = tokio_stream::wrappers::BroadcastStream::new(receiver); - EventStream { inner } + Self { inner } } } diff --git a/crates/tracing/src/formatter.rs b/crates/tracing/src/formatter.rs index 872a0b5c8..1322377f1 100644 --- a/crates/tracing/src/formatter.rs +++ b/crates/tracing/src/formatter.rs @@ -57,7 +57,7 @@ impl LogFormat { filter.max_level_hint().map_or(true, |max_level| max_level > tracing::Level::INFO)); match self { - LogFormat::Json => { + Self::Json => { let layer = tracing_subscriber::fmt::layer().json().with_ansi(ansi).with_target(target); @@ -67,8 +67,8 @@ impl LogFormat { layer.with_filter(filter).boxed() } } - LogFormat::LogFmt => tracing_logfmt::layer().with_filter(filter).boxed(), - LogFormat::Terminal => { + Self::LogFmt => tracing_logfmt::layer().with_filter(filter).boxed(), + Self::Terminal => { let layer = tracing_subscriber::fmt::layer().with_ansi(ansi).with_target(target); if let Some(writer) = file_writer { @@ -84,9 +84,9 @@ impl LogFormat { impl Display for LogFormat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - LogFormat::Json => write!(f, "json"), - LogFormat::LogFmt => write!(f, "logfmt"), - LogFormat::Terminal => write!(f, "terminal"), + Self::Json => write!(f, "json"), + Self::LogFmt => write!(f, "logfmt"), + Self::Terminal => write!(f, "terminal"), } } } diff --git a/crates/transaction-pool/src/blobstore/disk.rs b/crates/transaction-pool/src/blobstore/disk.rs index 5f44c87f5..862c4923d 100644 --- a/crates/transaction-pool/src/blobstore/disk.rs +++ b/crates/transaction-pool/src/blobstore/disk.rs @@ -405,7 +405,7 @@ pub enum DiskFileBlobStoreError { impl From for BlobStoreError { fn from(value: DiskFileBlobStoreError) -> Self { - BlobStoreError::Other(Box::new(value)) + Self::Other(Box::new(value)) } } diff --git a/crates/transaction-pool/src/error.rs b/crates/transaction-pool/src/error.rs index 8334c0f37..e20624801 100644 --- a/crates/transaction-pool/src/error.rs +++ b/crates/transaction-pool/src/error.rs @@ -216,7 +216,7 @@ impl InvalidPoolTransactionError { #[inline] fn is_bad_transaction(&self) -> bool { match self { - InvalidPoolTransactionError::Consensus(err) => { + Self::Consensus(err) => { // transaction considered invalid by the consensus rules // We do not consider the following errors to be erroneous transactions, since they // depend on dynamic environmental conditions and should not be assumed to have been @@ -250,17 +250,17 @@ impl InvalidPoolTransactionError { InvalidTransactionError::SignerAccountHasBytecode => true, } } - InvalidPoolTransactionError::ExceedsGasLimit(_, _) => true, - InvalidPoolTransactionError::ExceedsMaxInitCodeSize(_, _) => true, - InvalidPoolTransactionError::OversizedData(_, _) => true, - InvalidPoolTransactionError::Underpriced => { + Self::ExceedsGasLimit(_, _) => true, + Self::ExceedsMaxInitCodeSize(_, _) => true, + Self::OversizedData(_, _) => true, + Self::Underpriced => { // local setting false } - InvalidPoolTransactionError::IntrinsicGasTooLow => true, - InvalidPoolTransactionError::Overdraft => false, - InvalidPoolTransactionError::Other(err) => err.is_bad_transaction(), - InvalidPoolTransactionError::Eip4844(eip4844_err) => { + Self::IntrinsicGasTooLow => true, + Self::Overdraft => false, + Self::Other(err) => err.is_bad_transaction(), + Self::Eip4844(eip4844_err) => { match eip4844_err { Eip4844PoolTransactionError::MissingEip4844BlobSidecar => { // this is only reachable when blob transactions are reinjected and we're @@ -291,12 +291,7 @@ impl InvalidPoolTransactionError { /// Returns `true` if an import failed due to nonce gap. pub const fn is_nonce_gap(&self) -> bool { - matches!( - self, - InvalidPoolTransactionError::Consensus(InvalidTransactionError::NonceNotConsistent) - ) || matches!( - self, - InvalidPoolTransactionError::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap) - ) + matches!(self, Self::Consensus(InvalidTransactionError::NonceNotConsistent)) || + matches!(self, Self::Eip4844(Eip4844PoolTransactionError::Eip4844NonceGap)) } } diff --git a/crates/transaction-pool/src/identifier.rs b/crates/transaction-pool/src/identifier.rs index ecc46cae8..f6c50f8d9 100644 --- a/crates/transaction-pool/src/identifier.rs +++ b/crates/transaction-pool/src/identifier.rs @@ -65,7 +65,7 @@ impl SenderId { impl From for SenderId { fn from(value: u64) -> Self { - SenderId(value) + Self(value) } } @@ -93,11 +93,7 @@ impl TransactionId { /// /// This returns `transaction_nonce - 1` if `transaction_nonce` is higher than the /// `on_chain_nonce` - pub fn ancestor( - transaction_nonce: u64, - on_chain_nonce: u64, - sender: SenderId, - ) -> Option { + pub fn ancestor(transaction_nonce: u64, on_chain_nonce: u64, sender: SenderId) -> Option { if transaction_nonce == on_chain_nonce { return None } @@ -106,13 +102,13 @@ impl TransactionId { } /// Returns the `TransactionId` that would come before this transaction. - pub(crate) fn unchecked_ancestor(&self) -> Option { - (self.nonce != 0).then(|| TransactionId::new(self.sender, self.nonce - 1)) + pub(crate) fn unchecked_ancestor(&self) -> Option { + (self.nonce != 0).then(|| Self::new(self.sender, self.nonce - 1)) } /// Returns the `TransactionId` that directly follows this transaction: `self.nonce + 1` - pub const fn descendant(&self) -> TransactionId { - TransactionId::new(self.sender, self.nonce + 1) + pub const fn descendant(&self) -> Self { + Self::new(self.sender, self.nonce + 1) } /// Returns the nonce that follows immediately after this one. diff --git a/crates/transaction-pool/src/maintain.rs b/crates/transaction-pool/src/maintain.rs index 923683d8a..5da2e4e76 100644 --- a/crates/transaction-pool/src/maintain.rs +++ b/crates/transaction-pool/src/maintain.rs @@ -485,7 +485,7 @@ impl MaintainedPoolState { /// Returns `true` if the pool is assumed to be out of sync with the current state. #[inline] const fn is_drifted(&self) -> bool { - matches!(self, MaintainedPoolState::Drifted) + matches!(self, Self::Drifted) } } diff --git a/crates/transaction-pool/src/ordering.rs b/crates/transaction-pool/src/ordering.rs index 8187520ee..e4928710b 100644 --- a/crates/transaction-pool/src/ordering.rs +++ b/crates/transaction-pool/src/ordering.rs @@ -15,7 +15,7 @@ pub enum Priority { impl From> for Priority { fn from(value: Option) -> Self { - value.map_or(Priority::None, Priority::Value) + value.map_or(Self::None, Priority::Value) } } diff --git a/crates/transaction-pool/src/pool/best.rs b/crates/transaction-pool/src/pool/best.rs index 5e870de2b..35ab9e5cc 100644 --- a/crates/transaction-pool/src/pool/best.rs +++ b/crates/transaction-pool/src/pool/best.rs @@ -148,7 +148,7 @@ impl BestTransactions { impl crate::traits::BestTransactions for BestTransactions { fn mark_invalid(&mut self, tx: &Self::Item) { - BestTransactions::mark_invalid(self, tx) + Self::mark_invalid(self, tx) } fn no_updates(&mut self) { diff --git a/crates/transaction-pool/src/pool/events.rs b/crates/transaction-pool/src/pool/events.rs index 58578d08f..7b17dcec5 100644 --- a/crates/transaction-pool/src/pool/events.rs +++ b/crates/transaction-pool/src/pool/events.rs @@ -80,11 +80,6 @@ impl TransactionEvent { /// Returns `true` if the event is final and no more events are expected for this transaction /// hash. pub const fn is_final(&self) -> bool { - matches!( - self, - TransactionEvent::Replaced(_) | - TransactionEvent::Mined(_) | - TransactionEvent::Discarded - ) + matches!(self, Self::Replaced(_) | Self::Mined(_) | Self::Discarded) } } diff --git a/crates/transaction-pool/src/pool/mod.rs b/crates/transaction-pool/src/pool/mod.rs index fe84e6e90..a23db3964 100644 --- a/crates/transaction-pool/src/pool/mod.rs +++ b/crates/transaction-pool/src/pool/mod.rs @@ -1023,7 +1023,7 @@ impl AddedTransaction { /// Returns whether the transaction has been added to the pending pool. pub(crate) const fn as_pending(&self) -> Option<&AddedPendingTransaction> { match self { - AddedTransaction::Pending(tx) => Some(tx), + Self::Pending(tx) => Some(tx), _ => None, } } @@ -1031,16 +1031,16 @@ impl AddedTransaction { /// Returns the replaced transaction if there was one pub(crate) const fn replaced(&self) -> Option<&Arc>> { match self { - AddedTransaction::Pending(tx) => tx.replaced.as_ref(), - AddedTransaction::Parked { replaced, .. } => replaced.as_ref(), + Self::Pending(tx) => tx.replaced.as_ref(), + Self::Parked { replaced, .. } => replaced.as_ref(), } } /// Returns the discarded transactions if there were any pub(crate) fn discarded_transactions(&self) -> Option<&[Arc>]> { match self { - AddedTransaction::Pending(tx) => Some(&tx.discarded), - AddedTransaction::Parked { .. } => None, + Self::Pending(tx) => Some(&tx.discarded), + Self::Parked { .. } => None, } } @@ -1052,18 +1052,18 @@ impl AddedTransaction { /// Returns the hash of the transaction pub(crate) fn hash(&self) -> &TxHash { match self { - AddedTransaction::Pending(tx) => tx.transaction.hash(), - AddedTransaction::Parked { transaction, .. } => transaction.hash(), + Self::Pending(tx) => tx.transaction.hash(), + Self::Parked { transaction, .. } => transaction.hash(), } } /// Converts this type into the event type for listeners pub(crate) fn into_new_transaction_event(self) -> NewTransactionEvent { match self { - AddedTransaction::Pending(tx) => { + Self::Pending(tx) => { NewTransactionEvent { subpool: SubPool::Pending, transaction: tx.transaction } } - AddedTransaction::Parked { transaction, subpool, .. } => { + Self::Parked { transaction, subpool, .. } => { NewTransactionEvent { transaction, subpool } } } @@ -1073,8 +1073,8 @@ impl AddedTransaction { #[cfg(test)] pub(crate) const fn subpool(&self) -> SubPool { match self { - AddedTransaction::Pending(_) => SubPool::Pending, - AddedTransaction::Parked { subpool, .. } => *subpool, + Self::Pending(_) => SubPool::Pending, + Self::Parked { subpool, .. } => *subpool, } } @@ -1082,8 +1082,8 @@ impl AddedTransaction { #[cfg(test)] pub(crate) fn id(&self) -> &TransactionId { match self { - AddedTransaction::Pending(added) => added.transaction.id(), - AddedTransaction::Parked { transaction, .. } => transaction.id(), + Self::Pending(added) => added.transaction.id(), + Self::Parked { transaction, .. } => transaction.id(), } } } diff --git a/crates/transaction-pool/src/pool/size.rs b/crates/transaction-pool/src/pool/size.rs index 93dfb9bc0..5e5a0acea 100644 --- a/crates/transaction-pool/src/pool/size.rs +++ b/crates/transaction-pool/src/pool/size.rs @@ -31,6 +31,6 @@ impl SubAssign for SizeTracker { impl From for usize { fn from(value: SizeTracker) -> Self { - value.0 as usize + value.0 as Self } } diff --git a/crates/transaction-pool/src/pool/state.rs b/crates/transaction-pool/src/pool/state.rs index a71c8bbfc..d0a3b10f8 100644 --- a/crates/transaction-pool/src/pool/state.rs +++ b/crates/transaction-pool/src/pool/state.rs @@ -56,19 +56,19 @@ impl TxState { /// - enough blob fee cap #[inline] pub(crate) const fn is_pending(&self) -> bool { - self.bits() >= TxState::PENDING_POOL_BITS.bits() + self.bits() >= Self::PENDING_POOL_BITS.bits() } /// Whether this transaction is a blob transaction. #[inline] pub(crate) const fn is_blob(&self) -> bool { - self.contains(TxState::BLOB_TRANSACTION) + self.contains(Self::BLOB_TRANSACTION) } /// Returns `true` if the transaction has a nonce gap. #[inline] pub(crate) const fn has_nonce_gap(&self) -> bool { - !self.intersects(TxState::NO_NONCE_GAPS) + !self.intersects(Self::NO_NONCE_GAPS) } } @@ -95,30 +95,30 @@ impl SubPool { /// Whether this transaction is to be moved to the pending sub-pool. #[inline] pub const fn is_pending(&self) -> bool { - matches!(self, SubPool::Pending) + matches!(self, Self::Pending) } /// Whether this transaction is in the queued pool. #[inline] pub const fn is_queued(&self) -> bool { - matches!(self, SubPool::Queued) + matches!(self, Self::Queued) } /// Whether this transaction is in the base fee pool. #[inline] pub const fn is_base_fee(&self) -> bool { - matches!(self, SubPool::BaseFee) + matches!(self, Self::BaseFee) } /// Whether this transaction is in the blob pool. #[inline] pub const fn is_blob(&self) -> bool { - matches!(self, SubPool::Blob) + matches!(self, Self::Blob) } /// Returns whether this is a promotion depending on the current sub-pool location. #[inline] - pub fn is_promoted(&self, other: SubPool) -> bool { + pub fn is_promoted(&self, other: Self) -> bool { self > &other } } @@ -126,16 +126,16 @@ impl SubPool { impl From for SubPool { fn from(value: TxState) -> Self { if value.is_pending() { - return SubPool::Pending + return Self::Pending } if value.is_blob() { // all _non-pending_ blob transactions are in the blob sub-pool - return SubPool::Blob + return Self::Blob } if value.bits() < TxState::BASE_FEE_POOL_BITS.bits() { - return SubPool::Queued + return Self::Queued } - SubPool::BaseFee + Self::BaseFee } } diff --git a/crates/transaction-pool/src/pool/txpool.rs b/crates/transaction-pool/src/pool/txpool.rs index 4e35733d4..28d0df38a 100644 --- a/crates/transaction-pool/src/pool/txpool.rs +++ b/crates/transaction-pool/src/pool/txpool.rs @@ -1704,7 +1704,7 @@ pub(crate) struct PendingFees { impl Default for PendingFees { fn default() -> Self { - PendingFees { base_fee: Default::default(), blob_fee: BLOB_TX_MIN_BLOB_GASPRICE } + Self { base_fee: Default::default(), blob_fee: BLOB_TX_MIN_BLOB_GASPRICE } } } diff --git a/crates/transaction-pool/src/test_utils/gen.rs b/crates/transaction-pool/src/test_utils/gen.rs index e5c99ec03..0b981ea15 100644 --- a/crates/transaction-pool/src/test_utils/gen.rs +++ b/crates/transaction-pool/src/test_utils/gen.rs @@ -142,7 +142,7 @@ pub struct TransactionBuilder { impl TransactionBuilder { /// Converts the transaction builder into a legacy transaction format. pub fn into_legacy(self) -> TransactionSigned { - TransactionBuilder::signed( + Self::signed( TxLegacy { chain_id: Some(self.chain_id), nonce: self.nonce, @@ -159,7 +159,7 @@ impl TransactionBuilder { /// Converts the transaction builder into a transaction format using EIP-1559. pub fn into_eip1559(self) -> TransactionSigned { - TransactionBuilder::signed( + Self::signed( TxEip1559 { chain_id: self.chain_id, nonce: self.nonce, @@ -177,7 +177,7 @@ impl TransactionBuilder { } /// Converts the transaction builder into a transaction format using EIP-4844. pub fn into_eip4844(self) -> TransactionSigned { - TransactionBuilder::signed( + Self::signed( TxEip4844 { chain_id: self.chain_id, nonce: self.nonce, diff --git a/crates/transaction-pool/src/test_utils/mock.rs b/crates/transaction-pool/src/test_utils/mock.rs index 15755b4e6..171c29d91 100644 --- a/crates/transaction-pool/src/test_utils/mock.rs +++ b/crates/transaction-pool/src/test_utils/mock.rs @@ -218,7 +218,7 @@ impl MockTransaction { /// Returns a new legacy transaction with random address and hash and empty values pub fn legacy() -> Self { - MockTransaction::Legacy { + Self::Legacy { chain_id: Some(1), hash: B256::random(), sender: Address::random(), @@ -234,7 +234,7 @@ impl MockTransaction { /// Returns a new EIP2930 transaction with random address and hash and empty values pub fn eip2930() -> Self { - MockTransaction::Eip2930 { + Self::Eip2930 { chain_id: 1, hash: B256::random(), sender: Address::random(), @@ -251,7 +251,7 @@ impl MockTransaction { /// Returns a new EIP1559 transaction with random address and hash and empty values pub fn eip1559() -> Self { - MockTransaction::Eip1559 { + Self::Eip1559 { chain_id: 1, hash: B256::random(), sender: Address::random(), @@ -269,7 +269,7 @@ impl MockTransaction { /// Returns a new EIP4844 transaction with random address and hash and empty values pub fn eip4844() -> Self { - MockTransaction::Eip4844 { + Self::Eip4844 { chain_id: 1, hash: B256::random(), sender: Address::random(), @@ -291,8 +291,7 @@ impl MockTransaction { /// Returns a new EIP4844 transaction with a provided sidecar pub fn eip4844_with_sidecar(sidecar: BlobTransactionSidecar) -> Self { let mut transaction = Self::eip4844(); - if let MockTransaction::Eip4844 { sidecar: ref mut existing_sidecar, .. } = &mut transaction - { + if let Self::Eip4844 { sidecar: ref mut existing_sidecar, .. } = &mut transaction { *existing_sidecar = sidecar; } transaction @@ -326,7 +325,7 @@ impl MockTransaction { /// Sets the max fee per blob gas for EIP-4844 transactions, pub fn set_blob_fee(&mut self, val: u128) -> &mut Self { - if let MockTransaction::Eip4844 { max_fee_per_blob_gas, .. } = self { + if let Self::Eip4844 { max_fee_per_blob_gas, .. } = self { *max_fee_per_blob_gas = val; } self @@ -334,8 +333,8 @@ impl MockTransaction { /// Sets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub fn set_priority_fee(&mut self, val: u128) -> &mut Self { - if let MockTransaction::Eip1559 { max_priority_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_priority_fee_per_gas, .. } = self + if let Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } = self { *max_priority_fee_per_gas = val; } @@ -351,18 +350,15 @@ impl MockTransaction { /// Gets the priority fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_priority_fee(&self) -> Option { match self { - MockTransaction::Eip1559 { max_priority_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_priority_fee_per_gas, .. } => { - Some(*max_priority_fee_per_gas) - } + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), _ => None, } } /// Sets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub fn set_max_fee(&mut self, val: u128) -> &mut Self { - if let MockTransaction::Eip1559 { max_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, .. } = self + if let Self::Eip1559 { max_fee_per_gas, .. } | Self::Eip4844 { max_fee_per_gas, .. } = self { *max_fee_per_gas = val; } @@ -378,8 +374,9 @@ impl MockTransaction { /// Gets the max fee for dynamic fee transactions (EIP-1559 and EIP-4844) pub const fn get_max_fee(&self) -> Option { match self { - MockTransaction::Eip1559 { max_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, .. } => Some(*max_fee_per_gas), + Self::Eip1559 { max_fee_per_gas, .. } | Self::Eip4844 { max_fee_per_gas, .. } => { + Some(*max_fee_per_gas) + } _ => None, } } @@ -387,10 +384,10 @@ impl MockTransaction { /// Sets the access list for transactions supporting EIP-1559, EIP-4844, and EIP-2930. pub fn set_accesslist(&mut self, list: AccessList) -> &mut Self { match self { - MockTransaction::Legacy { .. } => {} - MockTransaction::Eip1559 { access_list: accesslist, .. } | - MockTransaction::Eip4844 { access_list: accesslist, .. } | - MockTransaction::Eip2930 { access_list: accesslist, .. } => { + Self::Legacy { .. } => {} + Self::Eip1559 { access_list: accesslist, .. } | + Self::Eip4844 { access_list: accesslist, .. } | + Self::Eip2930 { access_list: accesslist, .. } => { *accesslist = list; } } @@ -400,12 +397,11 @@ impl MockTransaction { /// Sets the gas price for the transaction. pub fn set_gas_price(&mut self, val: u128) -> &mut Self { match self { - MockTransaction::Legacy { gas_price, .. } | - MockTransaction::Eip2930 { gas_price, .. } => { + Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => { *gas_price = val; } - MockTransaction::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { + Self::Eip1559 { max_fee_per_gas, max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_fee_per_gas, max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -416,20 +412,11 @@ impl MockTransaction { /// Sets the gas price for the transaction. pub fn with_gas_price(mut self, val: u128) -> Self { match self { - MockTransaction::Legacy { ref mut gas_price, .. } | - MockTransaction::Eip2930 { ref mut gas_price, .. } => { + Self::Legacy { ref mut gas_price, .. } | Self::Eip2930 { ref mut gas_price, .. } => { *gas_price = val; } - MockTransaction::Eip1559 { - ref mut max_fee_per_gas, - ref mut max_priority_fee_per_gas, - .. - } | - MockTransaction::Eip4844 { - ref mut max_fee_per_gas, - ref mut max_priority_fee_per_gas, - .. - } => { + Self::Eip1559 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } | + Self::Eip4844 { ref mut max_fee_per_gas, ref mut max_priority_fee_per_gas, .. } => { *max_fee_per_gas = val; *max_priority_fee_per_gas = val; } @@ -440,10 +427,10 @@ impl MockTransaction { /// Gets the gas price for the transaction. pub const fn get_gas_price(&self) -> u128 { match self { - MockTransaction::Legacy { gas_price, .. } | - MockTransaction::Eip2930 { gas_price, .. } => *gas_price, - MockTransaction::Eip1559 { max_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, + Self::Eip1559 { max_fee_per_gas, .. } | Self::Eip4844 { max_fee_per_gas, .. } => { + *max_fee_per_gas + } } } @@ -515,7 +502,7 @@ impl MockTransaction { /// If it's an EIP-4844 transaction. pub fn inc_blob_fee_by(&self, value: u128) -> Self { let mut this = self.clone(); - if let MockTransaction::Eip4844 { max_fee_per_blob_gas, .. } = &mut this { + if let Self::Eip4844 { max_fee_per_blob_gas, .. } = &mut this { *max_fee_per_blob_gas = max_fee_per_blob_gas.checked_add(value).unwrap(); } this @@ -533,7 +520,7 @@ impl MockTransaction { /// If it's an EIP-4844 transaction. pub fn decr_blob_fee_by(&self, value: u128) -> Self { let mut this = self.clone(); - if let MockTransaction::Eip4844 { max_fee_per_blob_gas, .. } = &mut this { + if let Self::Eip4844 { max_fee_per_blob_gas, .. } = &mut this { *max_fee_per_blob_gas = max_fee_per_blob_gas.checked_sub(value).unwrap(); } this @@ -551,61 +538,61 @@ impl MockTransaction { /// Checks if the transaction is of the legacy type. pub const fn is_legacy(&self) -> bool { - matches!(self, MockTransaction::Legacy { .. }) + matches!(self, Self::Legacy { .. }) } /// Checks if the transaction is of the EIP-1559 type. pub const fn is_eip1559(&self) -> bool { - matches!(self, MockTransaction::Eip1559 { .. }) + matches!(self, Self::Eip1559 { .. }) } /// Checks if the transaction is of the EIP-4844 type. pub const fn is_eip4844(&self) -> bool { - matches!(self, MockTransaction::Eip4844 { .. }) + matches!(self, Self::Eip4844 { .. }) } /// Checks if the transaction is of the EIP-2930 type. pub const fn is_eip2930(&self) -> bool { - matches!(self, MockTransaction::Eip2930 { .. }) + matches!(self, Self::Eip2930 { .. }) } } impl PoolTransaction for MockTransaction { fn hash(&self) -> &TxHash { match self { - MockTransaction::Legacy { hash, .. } | - MockTransaction::Eip1559 { hash, .. } | - MockTransaction::Eip4844 { hash, .. } | - MockTransaction::Eip2930 { hash, .. } => hash, + Self::Legacy { hash, .. } | + Self::Eip1559 { hash, .. } | + Self::Eip4844 { hash, .. } | + Self::Eip2930 { hash, .. } => hash, } } fn sender(&self) -> Address { match self { - MockTransaction::Legacy { sender, .. } | - MockTransaction::Eip1559 { sender, .. } | - MockTransaction::Eip4844 { sender, .. } | - MockTransaction::Eip2930 { sender, .. } => *sender, + Self::Legacy { sender, .. } | + Self::Eip1559 { sender, .. } | + Self::Eip4844 { sender, .. } | + Self::Eip2930 { sender, .. } => *sender, } } fn nonce(&self) -> u64 { match self { - MockTransaction::Legacy { nonce, .. } | - MockTransaction::Eip1559 { nonce, .. } | - MockTransaction::Eip4844 { nonce, .. } | - MockTransaction::Eip2930 { nonce, .. } => *nonce, + Self::Legacy { nonce, .. } | + Self::Eip1559 { nonce, .. } | + Self::Eip4844 { nonce, .. } | + Self::Eip2930 { nonce, .. } => *nonce, } } fn cost(&self) -> U256 { match self { - MockTransaction::Legacy { gas_price, value, gas_limit, .. } | - MockTransaction::Eip2930 { gas_limit, gas_price, value, .. } => { + Self::Legacy { gas_price, value, gas_limit, .. } | + Self::Eip2930 { gas_limit, gas_price, value, .. } => { U256::from(*gas_limit) * U256::from(*gas_price) + *value } - MockTransaction::Eip1559 { max_fee_per_gas, value, gas_limit, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, value, gas_limit, .. } => { + Self::Eip1559 { max_fee_per_gas, value, gas_limit, .. } | + Self::Eip4844 { max_fee_per_gas, value, gas_limit, .. } => { U256::from(*gas_limit) * U256::from(*max_fee_per_gas) + *value } } @@ -617,35 +604,33 @@ impl PoolTransaction for MockTransaction { fn max_fee_per_gas(&self) -> u128 { match self { - MockTransaction::Legacy { gas_price, .. } | - MockTransaction::Eip2930 { gas_price, .. } => *gas_price, - MockTransaction::Eip1559 { max_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_fee_per_gas, .. } => *max_fee_per_gas, + Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, + Self::Eip1559 { max_fee_per_gas, .. } | Self::Eip4844 { max_fee_per_gas, .. } => { + *max_fee_per_gas + } } } fn access_list(&self) -> Option<&AccessList> { match self { - MockTransaction::Legacy { .. } => None, - MockTransaction::Eip1559 { access_list: accesslist, .. } | - MockTransaction::Eip4844 { access_list: accesslist, .. } | - MockTransaction::Eip2930 { access_list: accesslist, .. } => Some(accesslist), + Self::Legacy { .. } => None, + Self::Eip1559 { access_list: accesslist, .. } | + Self::Eip4844 { access_list: accesslist, .. } | + Self::Eip2930 { access_list: accesslist, .. } => Some(accesslist), } } fn max_priority_fee_per_gas(&self) -> Option { match self { - MockTransaction::Legacy { .. } | MockTransaction::Eip2930 { .. } => None, - MockTransaction::Eip1559 { max_priority_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_priority_fee_per_gas, .. } => { - Some(*max_priority_fee_per_gas) - } + Self::Legacy { .. } | Self::Eip2930 { .. } => None, + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } => Some(*max_priority_fee_per_gas), } } fn max_fee_per_blob_gas(&self) -> Option { match self { - MockTransaction::Eip4844 { max_fee_per_blob_gas, .. } => Some(*max_fee_per_blob_gas), + Self::Eip4844 { max_fee_per_blob_gas, .. } => Some(*max_fee_per_blob_gas), _ => None, } } @@ -679,50 +664,47 @@ impl PoolTransaction for MockTransaction { /// Returns the priority fee or gas price based on the transaction type. fn priority_fee_or_price(&self) -> u128 { match self { - MockTransaction::Legacy { gas_price, .. } | - MockTransaction::Eip2930 { gas_price, .. } => *gas_price, - MockTransaction::Eip1559 { max_priority_fee_per_gas, .. } | - MockTransaction::Eip4844 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, + Self::Legacy { gas_price, .. } | Self::Eip2930 { gas_price, .. } => *gas_price, + Self::Eip1559 { max_priority_fee_per_gas, .. } | + Self::Eip4844 { max_priority_fee_per_gas, .. } => *max_priority_fee_per_gas, } } /// Returns the transaction kind associated with the transaction. fn kind(&self) -> TxKind { match self { - MockTransaction::Legacy { to, .. } | - MockTransaction::Eip1559 { to, .. } | - MockTransaction::Eip2930 { to, .. } => *to, - MockTransaction::Eip4844 { to, .. } => TxKind::Call(*to), + Self::Legacy { to, .. } | Self::Eip1559 { to, .. } | Self::Eip2930 { to, .. } => *to, + Self::Eip4844 { to, .. } => TxKind::Call(*to), } } /// Returns the input data associated with the transaction. fn input(&self) -> &[u8] { match self { - MockTransaction::Legacy { .. } => &[], - MockTransaction::Eip1559 { input, .. } | - MockTransaction::Eip4844 { input, .. } | - MockTransaction::Eip2930 { input, .. } => input, + Self::Legacy { .. } => &[], + Self::Eip1559 { input, .. } | + Self::Eip4844 { input, .. } | + Self::Eip2930 { input, .. } => input, } } /// Returns the size of the transaction. fn size(&self) -> usize { match self { - MockTransaction::Legacy { size, .. } | - MockTransaction::Eip1559 { size, .. } | - MockTransaction::Eip4844 { size, .. } | - MockTransaction::Eip2930 { size, .. } => *size, + Self::Legacy { size, .. } | + Self::Eip1559 { size, .. } | + Self::Eip4844 { size, .. } | + Self::Eip2930 { size, .. } => *size, } } /// Returns the transaction type as a byte identifier. fn tx_type(&self) -> u8 { match self { - MockTransaction::Legacy { .. } => TxType::Legacy.into(), - MockTransaction::Eip1559 { .. } => TxType::Eip1559.into(), - MockTransaction::Eip4844 { .. } => TxType::Eip4844.into(), - MockTransaction::Eip2930 { .. } => TxType::Eip2930.into(), + Self::Legacy { .. } => TxType::Legacy.into(), + Self::Eip1559 { .. } => TxType::Eip1559.into(), + Self::Eip4844 { .. } => TxType::Eip4844.into(), + Self::Eip2930 { .. } => TxType::Eip2930.into(), } } @@ -734,10 +716,10 @@ impl PoolTransaction for MockTransaction { /// Returns the chain ID associated with the transaction. fn chain_id(&self) -> Option { match self { - MockTransaction::Legacy { chain_id, .. } => *chain_id, - MockTransaction::Eip1559 { chain_id, .. } | - MockTransaction::Eip4844 { chain_id, .. } | - MockTransaction::Eip2930 { chain_id, .. } => Some(*chain_id), + Self::Legacy { chain_id, .. } => *chain_id, + Self::Eip1559 { chain_id, .. } | + Self::Eip4844 { chain_id, .. } | + Self::Eip2930 { chain_id, .. } => Some(*chain_id), } } } @@ -790,7 +772,7 @@ impl TryFromRecoveredTransaction for MockTransaction { to, value, input, - }) => Ok(MockTransaction::Legacy { + }) => Ok(Self::Legacy { chain_id, hash, sender, @@ -811,7 +793,7 @@ impl TryFromRecoveredTransaction for MockTransaction { value, input, access_list, - }) => Ok(MockTransaction::Eip2930 { + }) => Ok(Self::Eip2930 { chain_id, hash, sender, @@ -834,7 +816,7 @@ impl TryFromRecoveredTransaction for MockTransaction { value, input, access_list, - }) => Ok(MockTransaction::Eip1559 { + }) => Ok(Self::Eip1559 { chain_id, hash, sender, @@ -861,7 +843,7 @@ impl TryFromRecoveredTransaction for MockTransaction { access_list, blob_versioned_hashes: _, max_fee_per_blob_gas, - }) => Ok(MockTransaction::Eip4844 { + }) => Ok(Self::Eip4844 { chain_id, hash, sender, @@ -1017,7 +999,7 @@ impl proptest::arbitrary::Arbitrary for MockTransaction { to, value, input, - }) => MockTransaction::Legacy { + }) => Self::Legacy { chain_id: *chain_id, sender, hash: tx_hash, @@ -1039,7 +1021,7 @@ impl proptest::arbitrary::Arbitrary for MockTransaction { value, access_list, input, - }) => MockTransaction::Eip2930 { + }) => Self::Eip2930 { chain_id: *chain_id, sender, hash: tx_hash, @@ -1062,7 +1044,7 @@ impl proptest::arbitrary::Arbitrary for MockTransaction { value, input, access_list, - }) => MockTransaction::Eip1559 { + }) => Self::Eip1559 { chain_id: *chain_id, sender, hash: tx_hash, @@ -1089,7 +1071,7 @@ impl proptest::arbitrary::Arbitrary for MockTransaction { access_list, blob_versioned_hashes: _, placeholder, - }) => MockTransaction::Eip4844 { + }) => Self::Eip4844 { chain_id: *chain_id, sender, hash: tx_hash, @@ -1114,7 +1096,7 @@ impl proptest::arbitrary::Arbitrary for MockTransaction { .boxed() } - type Strategy = proptest::strategy::BoxedStrategy; + type Strategy = proptest::strategy::BoxedStrategy; } /// A factory for creating and managing various types of mock transactions. @@ -1433,7 +1415,7 @@ impl NonConflictingSetOutcome { /// Returns the inner [MockTransactionSet] pub fn into_inner(self) -> MockTransactionSet { match self { - NonConflictingSetOutcome::BlobsOnly(set) | NonConflictingSetOutcome::Mixed(set) => set, + Self::BlobsOnly(set) | Self::Mixed(set) => set, } } @@ -1451,8 +1433,8 @@ impl NonConflictingSetOutcome { rng: &mut impl rand::Rng, ) { match self { - NonConflictingSetOutcome::BlobsOnly(_) => {} - NonConflictingSetOutcome::Mixed(set) => set.with_nonce_gaps(gap_pct, gap_range, rng), + Self::BlobsOnly(_) => {} + Self::Mixed(set) => set.with_nonce_gaps(gap_pct, gap_range, rng), } } } diff --git a/crates/transaction-pool/src/traits.rs b/crates/transaction-pool/src/traits.rs index dd465a77b..58377a19e 100644 --- a/crates/transaction-pool/src/traits.rs +++ b/crates/transaction-pool/src/traits.rs @@ -497,7 +497,7 @@ impl PropagateKind { /// Returns the peer the transaction was sent to pub const fn peer(&self) -> &PeerId { match self { - PropagateKind::Full(peer) | PropagateKind::Hash(peer) => peer, + Self::Full(peer) | Self::Hash(peer) => peer, } } } @@ -561,16 +561,16 @@ pub enum TransactionOrigin { impl TransactionOrigin { /// Whether the transaction originates from a local source. pub const fn is_local(&self) -> bool { - matches!(self, TransactionOrigin::Local) + matches!(self, Self::Local) } /// Whether the transaction originates from an external source. pub const fn is_external(&self) -> bool { - matches!(self, TransactionOrigin::External) + matches!(self, Self::External) } /// Whether the transaction originates from a private source. pub const fn is_private(&self) -> bool { - matches!(self, TransactionOrigin::Private) + matches!(self, Self::Private) } } @@ -909,7 +909,7 @@ impl EthBlobTransactionSidecar { /// Returns the blob sidecar if it is present pub const fn maybe_sidecar(&self) -> Option<&BlobTransactionSidecar> { match self { - EthBlobTransactionSidecar::Present(sidecar) => Some(sidecar), + Self::Present(sidecar) => Some(sidecar), _ => None, } } @@ -969,13 +969,13 @@ impl From for EthPooledTransaction { // include the blob sidecar let (tx, blob) = tx.into_parts(); let tx = TransactionSignedEcRecovered::from_signed_transaction(tx, signer); - let mut pooled = EthPooledTransaction::new(tx, encoded_length); + let mut pooled = Self::new(tx, encoded_length); pooled.blob_sidecar = EthBlobTransactionSidecar::Present(blob); pooled } tx => { // no blob sidecar - EthPooledTransaction::new(tx.into_ecrecovered_transaction(signer), encoded_length) + Self::new(tx.into_ecrecovered_transaction(signer), encoded_length) } } } @@ -1146,14 +1146,14 @@ impl TryFromRecoveredTransaction for EthPooledTransaction { }; let encoded_length = tx.length_without_header(); - let transaction = EthPooledTransaction::new(tx, encoded_length); + let transaction = Self::new(tx, encoded_length); Ok(transaction) } } impl FromRecoveredPooledTransaction for EthPooledTransaction { fn from_recovered_pooled_transaction(tx: PooledTransactionsElementEcRecovered) -> Self { - EthPooledTransaction::from(tx) + Self::from(tx) } } @@ -1231,8 +1231,8 @@ impl GetPooledTransactionLimit { #[inline] pub const fn exceeds(&self, size: usize) -> bool { match self { - GetPooledTransactionLimit::None => false, - GetPooledTransactionLimit::ResponseSizeSoftLimit(limit) => size > *limit, + Self::None => false, + Self::ResponseSizeSoftLimit(limit) => size > *limit, } } } diff --git a/crates/transaction-pool/src/validate/task.rs b/crates/transaction-pool/src/validate/task.rs index 018b3aab0..a18cdad84 100644 --- a/crates/transaction-pool/src/validate/task.rs +++ b/crates/transaction-pool/src/validate/task.rs @@ -42,7 +42,7 @@ impl ValidationTask { /// Creates a new task with the given receiver. pub fn with_receiver(jobs: mpsc::Receiver + Send>>>) -> Self { - ValidationTask { validation_jobs: Arc::new(Mutex::new(ReceiverStream::new(jobs))) } + Self { validation_jobs: Arc::new(Mutex::new(ReceiverStream::new(jobs))) } } /// Executes all new validation jobs that come in. diff --git a/crates/trie-parallel/src/parallel_root.rs b/crates/trie-parallel/src/parallel_root.rs index 044173605..513ae1577 100644 --- a/crates/trie-parallel/src/parallel_root.rs +++ b/crates/trie-parallel/src/parallel_root.rs @@ -206,7 +206,7 @@ impl From for ProviderError { match error { ParallelStateRootError::Provider(error) => error, ParallelStateRootError::StorageRoot(StorageRootError::DB(error)) => { - ProviderError::Database(error) + Self::Database(error) } } } diff --git a/crates/trie/benches/prefix_set.rs b/crates/trie/benches/prefix_set.rs index c45c1f2b2..bd199c2cd 100644 --- a/crates/trie/benches/prefix_set.rs +++ b/crates/trie/benches/prefix_set.rs @@ -19,11 +19,11 @@ pub trait PrefixSetAbstraction: Default { impl PrefixSetAbstraction for PrefixSetMut { fn insert(&mut self, key: Nibbles) { - PrefixSetMut::insert(self, key) + Self::insert(self, key) } fn contains(&mut self, key: Nibbles) -> bool { - PrefixSetMut::contains(self, &key) + Self::contains(self, &key) } } diff --git a/crates/trie/src/prefix_set/mod.rs b/crates/trie/src/prefix_set/mod.rs index 32fdc68c8..c37b90d4a 100644 --- a/crates/trie/src/prefix_set/mod.rs +++ b/crates/trie/src/prefix_set/mod.rs @@ -58,7 +58,7 @@ where I: IntoIterator, { fn from(value: I) -> Self { - PrefixSetMut { keys: value.into_iter().collect(), ..Default::default() } + Self { keys: value.into_iter().collect(), ..Default::default() } } } diff --git a/crates/trie/src/trie_cursor/subnode.rs b/crates/trie/src/trie_cursor/subnode.rs index c3eca176a..c8b77daea 100644 --- a/crates/trie/src/trie_cursor/subnode.rs +++ b/crates/trie/src/trie_cursor/subnode.rs @@ -64,7 +64,7 @@ impl CursorSubNode { CHILD_INDEX_RANGE.clone().find(|i| n.state_mask.is_bit_set(*i)).unwrap() as i8 }); let full_key = full_key(key.clone(), nibble); - CursorSubNode { key, node, nibble, full_key } + Self { key, node, nibble, full_key } } /// Returns the full key of the current node. diff --git a/crates/trie/src/updates.rs b/crates/trie/src/updates.rs index 1d31ee31f..91fc63b10 100644 --- a/crates/trie/src/updates.rs +++ b/crates/trie/src/updates.rs @@ -37,7 +37,7 @@ pub enum TrieOp { impl TrieOp { /// Returns `true` if the operation is an update. pub fn is_update(&self) -> bool { - matches!(self, TrieOp::Update(..)) + matches!(self, Self::Update(..)) } } diff --git a/testing/ef-tests/src/cases/blockchain_test.rs b/testing/ef-tests/src/cases/blockchain_test.rs index 6ea0fad70..5c1746045 100644 --- a/testing/ef-tests/src/cases/blockchain_test.rs +++ b/testing/ef-tests/src/cases/blockchain_test.rs @@ -42,7 +42,7 @@ pub struct BlockchainTestCase { impl Case for BlockchainTestCase { fn load(path: &Path) -> Result { - Ok(BlockchainTestCase { + Ok(Self { tests: { let s = fs::read_to_string(path) .map_err(|error| Error::Io { path: path.into(), error })?; diff --git a/testing/ef-tests/src/result.rs b/testing/ef-tests/src/result.rs index c7a893c4c..409b273fd 100644 --- a/testing/ef-tests/src/result.rs +++ b/testing/ef-tests/src/result.rs @@ -66,7 +66,7 @@ pub struct CaseResult { impl CaseResult { /// Create a new test result. pub fn new(path: &Path, case: &impl Case, result: Result<(), Error>) -> Self { - CaseResult { desc: case.description(), path: path.into(), result } + Self { desc: case.description(), path: path.into(), result } } }