diff --git a/Cargo.toml b/Cargo.toml index 5987ff4ca..35f5f1524 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,6 +153,7 @@ unused_peekable = "warn" unused_rounding = "warn" useless_let_if_seq = "warn" use_self = "warn" +missing_const_for_fn = "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. @@ -165,7 +166,6 @@ empty_line_after_doc_comments = "allow" fallible_impl_from = "allow" future_not_send = "allow" iter_on_single_items = "allow" -missing_const_for_fn = "allow" needless_collect = "allow" non_send_fields_in_send_ty = "allow" option_if_let_else = "allow" diff --git a/bin/reth/src/commands/db/checksum.rs b/bin/reth/src/commands/db/checksum.rs index 9562c9839..4e172fe5c 100644 --- a/bin/reth/src/commands/db/checksum.rs +++ b/bin/reth/src/commands/db/checksum.rs @@ -55,7 +55,7 @@ pub(crate) struct ChecksumViewer<'a, DB: Database> { } impl ChecksumViewer<'_, DB> { - pub(crate) fn new(tool: &'_ DbTool) -> ChecksumViewer<'_, DB> { + pub(crate) const fn new(tool: &'_ DbTool) -> ChecksumViewer<'_, DB> { ChecksumViewer { tool, start_key: None, end_key: None, limit: None } } diff --git a/bin/reth/src/commands/db/diff.rs b/bin/reth/src/commands/db/diff.rs index 3c7bfb8c0..5ef4f6c7f 100644 --- a/bin/reth/src/commands/db/diff.rs +++ b/bin/reth/src/commands/db/diff.rs @@ -418,7 +418,7 @@ enum ExtraTableElement { impl ExtraTableElement { /// Return the key for the extra element - fn key(&self) -> &T::Key { + const fn key(&self) -> &T::Key { match self { Self::First { key, .. } => key, Self::Second { key, .. } => key, diff --git a/bin/reth/src/commands/db/tui.rs b/bin/reth/src/commands/db/tui.rs index 487ee48c6..5a0a1c24f 100644 --- a/bin/reth/src/commands/db/tui.rs +++ b/bin/reth/src/commands/db/tui.rs @@ -55,7 +55,7 @@ enum Entries { impl Entries { /// Creates new empty [Entries] as [Entries::RawValues] if `raw_values == true` and as /// [Entries::Values] if `raw == false`. - fn new_with_raw_values(raw_values: bool) -> Self { + const fn new_with_raw_values(raw_values: bool) -> Self { if raw_values { Self::RawValues(Vec::new()) } else { @@ -85,7 +85,7 @@ impl Entries { /// Returns an iterator over keys of the internal [Vec]. For both [Entries::RawValues] and /// [Entries::Values], this iterator will yield [Table::Key]. - fn iter_keys(&self) -> EntriesKeyIter<'_, T> { + const fn iter_keys(&self) -> EntriesKeyIter<'_, T> { EntriesKeyIter { entries: self, index: 0 } } } diff --git a/bin/reth/src/sigsegv_handler.rs b/bin/reth/src/sigsegv_handler.rs index c45d84ae2..9e6833b75 100644 --- a/bin/reth/src/sigsegv_handler.rs +++ b/bin/reth/src/sigsegv_handler.rs @@ -148,6 +148,6 @@ fn min_sigstack_size() -> usize { /// Not all OS support hardware where this is needed. #[cfg(not(any(target_os = "linux", target_os = "android")))] -fn min_sigstack_size() -> usize { +const fn min_sigstack_size() -> usize { libc::MINSIGSTKSZ } diff --git a/crates/blockchain-tree-api/src/error.rs b/crates/blockchain-tree-api/src/error.rs index 784b8532e..ad9f7abcd 100644 --- a/crates/blockchain-tree-api/src/error.rs +++ b/crates/blockchain-tree-api/src/error.rs @@ -74,19 +74,19 @@ pub enum CanonicalError { impl CanonicalError { /// Returns `true` if the error is fatal. - pub fn is_fatal(&self) -> bool { + pub const fn is_fatal(&self) -> bool { matches!(self, Self::CanonicalCommit(_) | Self::CanonicalRevert(_)) } /// Returns `true` if the underlying error matches /// [BlockchainTreeError::BlockHashNotFoundInChain]. - pub fn is_block_hash_not_found(&self) -> bool { + pub const fn is_block_hash_not_found(&self) -> bool { matches!(self, Self::BlockchainTree(BlockchainTreeError::BlockHashNotFoundInChain { .. })) } /// Returns `Some(BlockNumber)` if the underlying error matches /// [CanonicalError::OptimisticTargetRevert]. - pub fn optimistic_revert_block_number(&self) -> Option { + pub const fn optimistic_revert_block_number(&self) -> Option { match self { Self::OptimisticTargetRevert(block_number) => Some(*block_number), _ => None, @@ -137,13 +137,13 @@ impl InsertBlockError { /// Returns the error kind #[inline] - pub fn kind(&self) -> &InsertBlockErrorKind { + pub const fn kind(&self) -> &InsertBlockErrorKind { &self.inner.kind } /// Returns the block that resulted in the error #[inline] - pub fn block(&self) -> &SealedBlock { + pub const fn block(&self) -> &SealedBlock { &self.inner.block } @@ -198,7 +198,7 @@ impl std::error::Error for InsertBlockErrorData { } impl InsertBlockErrorData { - fn new(block: SealedBlock, kind: InsertBlockErrorKind) -> Self { + const fn new(block: SealedBlock, kind: InsertBlockErrorKind) -> Self { Self { block, kind } } @@ -238,17 +238,17 @@ pub enum InsertBlockErrorKind { impl InsertBlockErrorKind { /// Returns true if the error is a tree error - pub fn is_tree_error(&self) -> bool { + pub const fn is_tree_error(&self) -> bool { matches!(self, Self::Tree(_)) } /// Returns true if the error is a consensus error - pub fn is_consensus_error(&self) -> bool { + pub const fn is_consensus_error(&self) -> bool { matches!(self, Self::Consensus(_)) } /// Returns true if this error is a state root error - pub fn is_state_root_error(&self) -> bool { + pub const fn is_state_root_error(&self) -> bool { // we need to get the state root errors inside of the different variant branches match self { Self::Execution(err) => { @@ -280,7 +280,7 @@ impl InsertBlockErrorKind { /// Returns true if the error is caused by an invalid block /// /// This is intended to be used to determine if the block should be marked as invalid. - pub fn is_invalid_block(&self) -> bool { + pub const fn is_invalid_block(&self) -> bool { match self { Self::SenderRecovery | Self::Consensus(_) => true, // other execution errors that are considered internal errors @@ -331,7 +331,7 @@ impl InsertBlockErrorKind { } /// Returns true if this is a block pre merge error. - pub fn is_block_pre_merge(&self) -> bool { + pub const fn is_block_pre_merge(&self) -> bool { matches!( self, Self::Execution(BlockExecutionError::Validation( @@ -341,17 +341,17 @@ impl InsertBlockErrorKind { } /// Returns true if the error is an execution error - pub fn is_execution_error(&self) -> bool { + pub const fn is_execution_error(&self) -> bool { matches!(self, Self::Execution(_)) } /// Returns true if the error is an internal error - pub fn is_internal(&self) -> bool { + pub const fn is_internal(&self) -> bool { matches!(self, Self::Internal(_)) } /// Returns the error if it is a tree error - pub fn as_tree_error(&self) -> Option { + pub const fn as_tree_error(&self) -> Option { match self { Self::Tree(err) => Some(*err), _ => None, @@ -359,7 +359,7 @@ impl InsertBlockErrorKind { } /// Returns the error if it is a consensus error - pub fn as_consensus_error(&self) -> Option<&ConsensusError> { + pub const fn as_consensus_error(&self) -> Option<&ConsensusError> { match self { Self::Consensus(err) => Some(err), _ => None, @@ -367,7 +367,7 @@ impl InsertBlockErrorKind { } /// Returns the error if it is an execution error - pub fn as_execution_error(&self) -> Option<&BlockExecutionError> { + pub const fn as_execution_error(&self) -> Option<&BlockExecutionError> { match self { 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 ce8bc1beb..6e1f7b10d 100644 --- a/crates/blockchain-tree-api/src/lib.rs +++ b/crates/blockchain-tree-api/src/lib.rs @@ -139,7 +139,7 @@ pub enum BlockValidationKind { impl BlockValidationKind { /// Returns true if the state root should be validated if possible. - pub fn is_exhaustive(&self) -> bool { + pub const fn is_exhaustive(&self) -> bool { matches!(self, Self::Exhaustive) } } @@ -177,7 +177,7 @@ pub enum CanonicalOutcome { impl CanonicalOutcome { /// Returns the header of the block that was made canonical. - pub fn header(&self) -> &SealedHeader { + pub const fn header(&self) -> &SealedHeader { match self { Self::AlreadyCanonical { header, .. } => header, Self::Committed { head } => head, @@ -193,7 +193,7 @@ impl CanonicalOutcome { } /// Returns true if the block was already canonical. - pub fn is_already_canonical(&self) -> bool { + pub const fn is_already_canonical(&self) -> bool { matches!(self, Self::AlreadyCanonical { .. }) } } diff --git a/crates/blockchain-tree/src/block_buffer.rs b/crates/blockchain-tree/src/block_buffer.rs index 25e3f32ad..153ff0288 100644 --- a/crates/blockchain-tree/src/block_buffer.rs +++ b/crates/blockchain-tree/src/block_buffer.rs @@ -47,7 +47,7 @@ impl BlockBuffer { } /// Return reference to buffered blocks - pub fn blocks(&self) -> &HashMap { + pub const fn blocks(&self) -> &HashMap { &self.blocks } diff --git a/crates/blockchain-tree/src/block_indices.rs b/crates/blockchain-tree/src/block_indices.rs index 7df973682..292f5a12a 100644 --- a/crates/blockchain-tree/src/block_indices.rs +++ b/crates/blockchain-tree/src/block_indices.rs @@ -58,12 +58,12 @@ impl BlockIndices { } /// Return fork to child indices - pub fn fork_to_child(&self) -> &HashMap> { + pub const fn fork_to_child(&self) -> &HashMap> { &self.fork_to_child } /// Return block to chain id - pub fn blocks_to_chain(&self) -> &HashMap { + pub const fn blocks_to_chain(&self) -> &HashMap { &self.blocks_to_chain } @@ -94,7 +94,7 @@ impl BlockIndices { } /// Last finalized block - pub fn last_finalized_block(&self) -> BlockNumber { + pub const fn last_finalized_block(&self) -> BlockNumber { self.last_finalized_block } @@ -366,7 +366,7 @@ impl BlockIndices { /// Canonical chain needed for execution of EVM. It should contain last 256 block hashes. #[inline] - pub(crate) fn canonical_chain(&self) -> &CanonicalChain { + pub(crate) const fn canonical_chain(&self) -> &CanonicalChain { &self.canonical_chain } } diff --git a/crates/blockchain-tree/src/blockchain_tree.rs b/crates/blockchain-tree/src/blockchain_tree.rs index c653e9374..f006888fd 100644 --- a/crates/blockchain-tree/src/blockchain_tree.rs +++ b/crates/blockchain-tree/src/blockchain_tree.rs @@ -227,7 +227,7 @@ where /// Expose internal indices of the BlockchainTree. #[inline] - pub fn block_indices(&self) -> &BlockIndices { + pub const fn block_indices(&self) -> &BlockIndices { self.state.block_indices() } @@ -1463,7 +1463,7 @@ mod tests { } impl TreeTester { - fn with_chain_num(mut self, chain_num: usize) -> Self { + const fn with_chain_num(mut self, chain_num: usize) -> Self { self.chain_num = Some(chain_num); self } diff --git a/crates/blockchain-tree/src/canonical_chain.rs b/crates/blockchain-tree/src/canonical_chain.rs index 0aca1bf94..ab91ee547 100644 --- a/crates/blockchain-tree/src/canonical_chain.rs +++ b/crates/blockchain-tree/src/canonical_chain.rs @@ -58,7 +58,7 @@ impl CanonicalChain { } #[inline] - pub(crate) fn inner(&self) -> &BTreeMap { + pub(crate) const fn inner(&self) -> &BTreeMap { &self.chain } diff --git a/crates/blockchain-tree/src/chain.rs b/crates/blockchain-tree/src/chain.rs index 38806b9da..9b7e394cd 100644 --- a/crates/blockchain-tree/src/chain.rs +++ b/crates/blockchain-tree/src/chain.rs @@ -53,7 +53,7 @@ impl DerefMut for AppendableChain { impl AppendableChain { /// Create a new appendable chain from a given chain. - pub fn new(chain: Chain) -> Self { + pub const fn new(chain: Chain) -> Self { Self { chain } } diff --git a/crates/blockchain-tree/src/config.rs b/crates/blockchain-tree/src/config.rs index 54ea855a4..377656be5 100644 --- a/crates/blockchain-tree/src/config.rs +++ b/crates/blockchain-tree/src/config.rs @@ -57,18 +57,18 @@ impl BlockchainTreeConfig { } /// Return the maximum reorg depth. - pub fn max_reorg_depth(&self) -> u64 { + pub const fn max_reorg_depth(&self) -> u64 { self.max_reorg_depth } /// Return the maximum number of blocks in one chain. - pub fn max_blocks_in_chain(&self) -> u64 { + pub const fn max_blocks_in_chain(&self) -> u64 { self.max_blocks_in_chain } /// Return number of additional canonical block hashes that we need to retain /// in order to have enough information for EVM execution. - pub fn num_of_additional_canonical_block_hashes(&self) -> u64 { + pub const fn num_of_additional_canonical_block_hashes(&self) -> u64 { self.num_of_additional_canonical_block_hashes } @@ -84,7 +84,7 @@ impl BlockchainTreeConfig { } /// Return max number of unconnected blocks that we are buffering - pub fn max_unconnected_blocks(&self) -> u32 { + pub const fn max_unconnected_blocks(&self) -> u32 { self.max_unconnected_blocks } } diff --git a/crates/blockchain-tree/src/metrics.rs b/crates/blockchain-tree/src/metrics.rs index 403b3014c..ee6fda011 100644 --- a/crates/blockchain-tree/src/metrics.rs +++ b/crates/blockchain-tree/src/metrics.rs @@ -90,7 +90,7 @@ pub(crate) enum MakeCanonicalAction { } impl MakeCanonicalAction { - fn as_str(&self) -> &'static str { + const fn as_str(&self) -> &'static str { match self { Self::CloneOldBlocks => "clone old blocks", Self::FindCanonicalHeader => "find canonical header", diff --git a/crates/blockchain-tree/src/state.rs b/crates/blockchain-tree/src/state.rs index 86501a6d1..2c97c1923 100644 --- a/crates/blockchain-tree/src/state.rs +++ b/crates/blockchain-tree/src/state.rs @@ -49,7 +49,7 @@ impl TreeState { /// Expose internal indices of the BlockchainTree. #[inline] - pub(crate) fn block_indices(&self) -> &BlockIndices { + pub(crate) const fn block_indices(&self) -> &BlockIndices { &self.block_indices } diff --git a/crates/config/src/config.rs b/crates/config/src/config.rs index 7847ae202..b804f7f9a 100644 --- a/crates/config/src/config.rs +++ b/crates/config/src/config.rs @@ -280,7 +280,7 @@ impl Default for EtlConfig { impl EtlConfig { /// Creates an ETL configuration - pub fn new(dir: Option, file_size: usize) -> Self { + pub const fn new(dir: Option, file_size: usize) -> Self { Self { dir, file_size } } diff --git a/crates/consensus/auto-seal/src/client.rs b/crates/consensus/auto-seal/src/client.rs index d89061e96..339f10cf2 100644 --- a/crates/consensus/auto-seal/src/client.rs +++ b/crates/consensus/auto-seal/src/client.rs @@ -23,7 +23,7 @@ pub struct AutoSealClient { } impl AutoSealClient { - pub(crate) fn new(storage: Storage) -> Self { + pub(crate) const fn new(storage: Storage) -> Self { Self { storage } } diff --git a/crates/consensus/beacon/src/engine/forkchoice.rs b/crates/consensus/beacon/src/engine/forkchoice.rs index 2eb115b1a..f614ef976 100644 --- a/crates/consensus/beacon/src/engine/forkchoice.rs +++ b/crates/consensus/beacon/src/engine/forkchoice.rs @@ -76,12 +76,12 @@ impl ForkchoiceStateTracker { } /// Returns the last received ForkchoiceState to which we need to sync. - pub(crate) fn sync_target_state(&self) -> Option { + pub(crate) const fn sync_target_state(&self) -> Option { self.last_syncing } /// Returns true if no forkchoice state has been received yet. - pub(crate) fn is_empty(&self) -> bool { + pub(crate) const fn is_empty(&self) -> bool { self.latest.is_none() } } @@ -106,20 +106,20 @@ pub enum ForkchoiceStatus { } impl ForkchoiceStatus { - pub(crate) fn is_valid(&self) -> bool { + pub(crate) const fn is_valid(&self) -> bool { matches!(self, Self::Valid) } - pub(crate) fn is_invalid(&self) -> bool { + pub(crate) const fn is_invalid(&self) -> bool { matches!(self, Self::Invalid) } - pub(crate) fn is_syncing(&self) -> bool { + pub(crate) const fn is_syncing(&self) -> bool { matches!(self, Self::Syncing) } /// Converts the general purpose [PayloadStatusEnum] into a [ForkchoiceStatus]. - pub(crate) fn from_payload_status(status: &PayloadStatusEnum) -> Self { + pub(crate) const fn from_payload_status(status: &PayloadStatusEnum) -> Self { match status { PayloadStatusEnum::Valid | PayloadStatusEnum::Accepted => { // `Accepted` is only returned on `newPayload`. It would be a valid state here. @@ -160,7 +160,7 @@ impl ForkchoiceStateHash { } /// Returns true if this is the head hash of the [ForkchoiceState] - pub(crate) fn is_head(&self) -> bool { + pub(crate) const fn is_head(&self) -> bool { matches!(self, Self::Head(_)) } } diff --git a/crates/consensus/beacon/src/engine/handle.rs b/crates/consensus/beacon/src/engine/handle.rs index 420871487..0f0d9e1da 100644 --- a/crates/consensus/beacon/src/engine/handle.rs +++ b/crates/consensus/beacon/src/engine/handle.rs @@ -33,7 +33,7 @@ where Engine: EngineTypes, { /// Creates a new beacon consensus engine handle. - pub fn new( + pub const fn new( to_engine: UnboundedSender>, event_sender: EventSender, ) -> Self { diff --git a/crates/consensus/beacon/src/engine/hooks/mod.rs b/crates/consensus/beacon/src/engine/hooks/mod.rs index 0777186b6..9d0ec626b 100644 --- a/crates/consensus/beacon/src/engine/hooks/mod.rs +++ b/crates/consensus/beacon/src/engine/hooks/mod.rs @@ -83,12 +83,12 @@ pub enum EngineHookEvent { impl EngineHookEvent { /// Returns `true` if the event is [`EngineHookEvent::Started`]. - pub fn is_started(&self) -> bool { + pub const fn is_started(&self) -> bool { matches!(self, Self::Started) } /// Returns `true` if the event is [`EngineHookEvent::Finished`]. - pub fn is_finished(&self) -> bool { + pub const fn is_finished(&self) -> bool { matches!(self, Self::Finished(_)) } } @@ -118,12 +118,12 @@ pub enum EngineHookDBAccessLevel { impl EngineHookDBAccessLevel { /// Returns `true` if the hook needs read-only access to the database. - pub fn is_read_only(&self) -> bool { + pub const fn is_read_only(&self) -> bool { matches!(self, Self::ReadOnly) } /// Returns `true` if the hook needs read-write access to the database. - pub fn is_read_write(&self) -> bool { + pub const fn is_read_write(&self) -> bool { matches!(self, Self::ReadWrite) } } diff --git a/crates/consensus/beacon/src/engine/message.rs b/crates/consensus/beacon/src/engine/message.rs index e3433062a..ee057aa98 100644 --- a/crates/consensus/beacon/src/engine/message.rs +++ b/crates/consensus/beacon/src/engine/message.rs @@ -33,7 +33,7 @@ pub struct OnForkChoiceUpdated { impl OnForkChoiceUpdated { /// Returns the determined status of the received ForkchoiceState. - pub fn forkchoice_status(&self) -> ForkchoiceStatus { + pub const fn forkchoice_status(&self) -> ForkchoiceStatus { self.forkchoice_status } diff --git a/crates/consensus/beacon/src/engine/mod.rs b/crates/consensus/beacon/src/engine/mod.rs index bcf677097..84efe7cff 100644 --- a/crates/consensus/beacon/src/engine/mod.rs +++ b/crates/consensus/beacon/src/engine/mod.rs @@ -602,7 +602,7 @@ where /// /// If the `local_tip` is greater than the `block`, then this will return false. #[inline] - fn exceeds_pipeline_run_threshold(&self, local_tip: u64, block: u64) -> bool { + const fn exceeds_pipeline_run_threshold(&self, local_tip: u64, block: u64) -> bool { block > local_tip && block - local_tip > self.pipeline_run_threshold } @@ -692,7 +692,7 @@ where /// Returns how far the local tip is from the given block. If the local tip is at the same /// height or its block number is greater than the given block, this returns None. #[inline] - fn distance_from_local_tip(&self, local_tip: u64, block: u64) -> Option { + const fn distance_from_local_tip(&self, local_tip: u64, block: u64) -> Option { if block > local_tip { Some(block - local_tip) } else { diff --git a/crates/consensus/beacon/src/engine/sync.rs b/crates/consensus/beacon/src/engine/sync.rs index 730b0a4d0..cce625032 100644 --- a/crates/consensus/beacon/src/engine/sync.rs +++ b/crates/consensus/beacon/src/engine/sync.rs @@ -123,23 +123,23 @@ where } /// Returns whether or not the sync controller is set to run the pipeline continuously. - pub(crate) fn run_pipeline_continuously(&self) -> bool { + pub(crate) const fn run_pipeline_continuously(&self) -> bool { self.run_pipeline_continuously } /// Returns `true` if a pipeline target is queued and will be triggered on the next `poll`. #[allow(dead_code)] - pub(crate) fn is_pipeline_sync_pending(&self) -> bool { + pub(crate) const fn is_pipeline_sync_pending(&self) -> bool { self.pending_pipeline_target.is_some() && self.pipeline_state.is_idle() } /// Returns `true` if the pipeline is idle. - pub(crate) fn is_pipeline_idle(&self) -> bool { + pub(crate) const fn is_pipeline_idle(&self) -> bool { self.pipeline_state.is_idle() } /// Returns `true` if the pipeline is active. - pub(crate) fn is_pipeline_active(&self) -> bool { + pub(crate) const fn is_pipeline_active(&self) -> bool { !self.is_pipeline_idle() } @@ -418,7 +418,7 @@ enum PipelineState { impl PipelineState { /// Returns `true` if the state matches idle. - fn is_idle(&self) -> bool { + const fn is_idle(&self) -> bool { matches!(self, Self::Idle(_)) } } @@ -478,7 +478,7 @@ mod tests { /// Sets the max block for the pipeline to run. #[allow(dead_code)] - fn with_max_block(mut self, max_block: BlockNumber) -> Self { + const fn with_max_block(mut self, max_block: BlockNumber) -> Self { self.max_block = Some(max_block); self } @@ -516,13 +516,13 @@ mod tests { impl TestSyncControllerBuilder { /// Create a new [TestSyncControllerBuilder]. - fn new() -> Self { + const fn new() -> Self { Self { max_block: None, client: None } } /// Sets the max block for the pipeline to run. #[allow(dead_code)] - fn with_max_block(mut self, max_block: BlockNumber) -> Self { + const fn with_max_block(mut self, max_block: BlockNumber) -> Self { self.max_block = Some(max_block); self } diff --git a/crates/consensus/beacon/src/engine/test_utils.rs b/crates/consensus/beacon/src/engine/test_utils.rs index 73777d94d..cc6181456 100644 --- a/crates/consensus/beacon/src/engine/test_utils.rs +++ b/crates/consensus/beacon/src/engine/test_utils.rs @@ -192,7 +192,7 @@ impl TestConsensusEngineBuilder { } /// Sets the max block for the pipeline to run. - pub fn with_max_block(mut self, max_block: BlockNumber) -> Self { + pub const fn with_max_block(mut self, max_block: BlockNumber) -> Self { self.max_block = Some(max_block); self } @@ -210,21 +210,24 @@ impl TestConsensusEngineBuilder { } /// Uses a real consensus engine instead of a test consensus engine. - pub fn with_real_consensus(mut self) -> Self { + pub const fn with_real_consensus(mut self) -> Self { self.consensus = TestConsensusConfig::Real; self } /// Disables blockchain tree driven sync. This is the same as setting the pipeline run /// threshold to 0. - pub fn disable_blockchain_tree_sync(mut self) -> Self { + pub const fn disable_blockchain_tree_sync(mut self) -> Self { self.pipeline_run_threshold = Some(0); self } /// Sets the client to use for network operations. #[allow(dead_code)] - pub fn with_client(self, client: Client) -> NetworkedTestConsensusEngineBuilder + pub const fn with_client( + self, + client: Client, + ) -> NetworkedTestConsensusEngineBuilder where Client: HeadersClient + BodiesClient + 'static, { @@ -274,7 +277,7 @@ where /// Sets the max block for the pipeline to run. #[allow(dead_code)] - pub fn with_max_block(mut self, max_block: BlockNumber) -> Self { + pub const fn with_max_block(mut self, max_block: BlockNumber) -> Self { self.base_config.max_block = Some(max_block); self } @@ -296,7 +299,7 @@ where /// Disables blockchain tree driven sync. This is the same as setting the pipeline run /// threshold to 0. #[allow(dead_code)] - pub fn disable_blockchain_tree_sync(mut self) -> Self { + pub const fn disable_blockchain_tree_sync(mut self) -> Self { self.base_config.pipeline_run_threshold = Some(0); self } diff --git a/crates/consensus/common/src/calc.rs b/crates/consensus/common/src/calc.rs index ef0f7b76e..318cbc028 100644 --- a/crates/consensus/common/src/calc.rs +++ b/crates/consensus/common/src/calc.rs @@ -67,7 +67,7 @@ pub fn base_block_reward( /// - Definition: [Yellow Paper][yp] (page 15, 11.3) /// /// [yp]: https://ethereum.github.io/yellowpaper/paper.pdf -pub fn block_reward(base_block_reward: u128, ommers: usize) -> u128 { +pub const fn block_reward(base_block_reward: u128, ommers: usize) -> u128 { base_block_reward + (base_block_reward >> 5) * ommers as u128 } @@ -91,7 +91,7 @@ pub fn block_reward(base_block_reward: u128, ommers: usize) -> u128 { /// /// [oe]: https://github.com/openethereum/openethereum/blob/6c2d392d867b058ff867c4373e40850ca3f96969/crates/ethcore/src/ethereum/ethash.rs#L319-L333 /// [yp]: https://ethereum.github.io/yellowpaper/paper.pdf -pub fn ommer_reward( +pub const fn ommer_reward( base_block_reward: u128, block_number: BlockNumber, ommer_block_number: BlockNumber, diff --git a/crates/consensus/consensus/src/lib.rs b/crates/consensus/consensus/src/lib.rs index a84808800..22e7053a9 100644 --- a/crates/consensus/consensus/src/lib.rs +++ b/crates/consensus/consensus/src/lib.rs @@ -33,7 +33,7 @@ pub struct PostExecutionInput<'a> { impl<'a> PostExecutionInput<'a> { /// Creates a new instance of `PostExecutionInput`. - pub fn new(receipts: &'a [Receipt], requests: &'a [Request]) -> Self { + pub const fn new(receipts: &'a [Receipt], requests: &'a [Request]) -> Self { Self { receipts, requests } } } @@ -327,7 +327,7 @@ pub enum ConsensusError { impl ConsensusError { /// Returns `true` if the error is a state root error. - pub fn is_state_root_error(&self) -> bool { + pub const fn is_state_root_error(&self) -> bool { matches!(self, Self::BodyStateRootDiff(_)) } } diff --git a/crates/engine-primitives/src/lib.rs b/crates/engine-primitives/src/lib.rs index d9cd340a8..015993df9 100644 --- a/crates/engine-primitives/src/lib.rs +++ b/crates/engine-primitives/src/lib.rs @@ -303,7 +303,10 @@ pub enum MessageValidationKind { impl MessageValidationKind { /// Returns an `EngineObjectValidationError` based on the given /// `VersionSpecificValidationError` and the current validation kind. - pub fn to_error(self, error: VersionSpecificValidationError) -> EngineObjectValidationError { + pub const fn to_error( + self, + error: VersionSpecificValidationError, + ) -> EngineObjectValidationError { match self { Self::Payload => EngineObjectValidationError::Payload(error), Self::PayloadAttributes => EngineObjectValidationError::PayloadAttributes(error), diff --git a/crates/engine-primitives/src/payload.rs b/crates/engine-primitives/src/payload.rs index 89e9446d3..b982eaafa 100644 --- a/crates/engine-primitives/src/payload.rs +++ b/crates/engine-primitives/src/payload.rs @@ -24,7 +24,7 @@ where { /// Construct a [PayloadOrAttributes] from an [ExecutionPayload] and optional parent beacon /// block root. - pub fn from_execution_payload( + pub const fn from_execution_payload( payload: &'a ExecutionPayload, parent_beacon_block_root: Option, ) -> Self { @@ -56,7 +56,7 @@ where } /// Return a [MessageValidationKind] for the payload or attributes. - pub fn message_validation_kind(&self) -> MessageValidationKind { + pub const fn message_validation_kind(&self) -> MessageValidationKind { match self { Self::ExecutionPayload { .. } => MessageValidationKind::Payload, Self::PayloadAttributes(_) => MessageValidationKind::PayloadAttributes, diff --git a/crates/ethereum-forks/src/hardfork.rs b/crates/ethereum-forks/src/hardfork.rs index 11e9cac45..6a7792727 100644 --- a/crates/ethereum-forks/src/hardfork.rs +++ b/crates/ethereum-forks/src/hardfork.rs @@ -124,7 +124,7 @@ impl Hardfork { } /// Retrieves the activation block for the specified hardfork on the Ethereum mainnet. - pub fn mainnet_activation_block(&self) -> Option { + pub const fn mainnet_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(0), @@ -150,7 +150,7 @@ impl Hardfork { } /// Retrieves the activation block for the specified hardfork on the Sepolia testnet. - pub fn sepolia_activation_block(&self) -> Option { + pub const fn sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Paris => Some(1735371), @@ -175,7 +175,7 @@ impl Hardfork { } /// Retrieves the activation block for the specified hardfork on the Arbitrum Sepolia testnet. - pub fn arbitrum_sepolia_activation_block(&self) -> Option { + pub const fn arbitrum_sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(0), @@ -202,7 +202,7 @@ impl Hardfork { } /// Retrieves the activation block for the specified hardfork on the Arbitrum One mainnet. - pub fn arbitrum_activation_block(&self) -> Option { + pub const fn arbitrum_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(0), @@ -230,7 +230,7 @@ impl Hardfork { /// Retrieves the activation block for the specified hardfork on the Base Sepolia testnet. #[cfg(feature = "optimism")] - pub fn base_sepolia_activation_block(&self) -> Option { + pub const fn base_sepolia_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(0), @@ -260,7 +260,7 @@ impl Hardfork { /// Retrieves the activation block for the specified hardfork on the Base mainnet. #[cfg(feature = "optimism")] - pub fn base_mainnet_activation_block(&self) -> Option { + pub const fn base_mainnet_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(0), @@ -289,7 +289,7 @@ impl Hardfork { } /// Retrieves the activation block for the specified hardfork on the holesky testnet. - fn holesky_activation_block(&self) -> Option { + const fn holesky_activation_block(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Dao => Some(0), @@ -336,7 +336,7 @@ impl Hardfork { } /// Retrieves the activation timestamp for the specified hardfork on the Ethereum mainnet. - pub fn mainnet_activation_timestamp(&self) -> Option { + pub const fn mainnet_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1438226773), @@ -363,7 +363,7 @@ impl Hardfork { } /// Retrieves the activation timestamp for the specified hardfork on the Sepolia testnet. - pub fn sepolia_activation_timestamp(&self) -> Option { + pub const fn sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1633267481), @@ -388,7 +388,7 @@ impl Hardfork { } /// Retrieves the activation timestamp for the specified hardfork on the Holesky testnet. - pub fn holesky_activation_timestamp(&self) -> Option { + pub const fn holesky_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Shanghai => Some(1696000704), @@ -414,7 +414,7 @@ impl Hardfork { /// Retrieves the activation timestamp for the specified hardfork on the Arbitrum Sepolia /// testnet. - pub fn arbitrum_sepolia_activation_timestamp(&self) -> Option { + pub const fn arbitrum_sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1692726996), @@ -441,7 +441,7 @@ impl Hardfork { } /// Retrieves the activation timestamp for the specified hardfork on the Arbitrum One mainnet. - pub fn arbitrum_activation_timestamp(&self) -> Option { + pub const fn arbitrum_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1622240000), @@ -469,7 +469,7 @@ impl Hardfork { /// Retrieves the activation timestamp for the specified hardfork on the Base Sepolia testnet. #[cfg(feature = "optimism")] - pub fn base_sepolia_activation_timestamp(&self) -> Option { + pub const fn base_sepolia_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1695768288), @@ -499,7 +499,7 @@ impl Hardfork { /// Retrieves the activation timestamp for the specified hardfork on the Base mainnet. #[cfg(feature = "optimism")] - pub fn base_mainnet_activation_timestamp(&self) -> Option { + pub const fn base_mainnet_activation_timestamp(&self) -> Option { #[allow(unreachable_patterns)] match self { Self::Frontier => Some(1686789347), diff --git a/crates/ethereum-forks/src/head.rs b/crates/ethereum-forks/src/head.rs index ff3087d5e..2cf29cca9 100644 --- a/crates/ethereum-forks/src/head.rs +++ b/crates/ethereum-forks/src/head.rs @@ -25,7 +25,7 @@ pub struct Head { } impl Head { /// Creates a new `Head` instance. - pub fn new( + pub const fn new( number: BlockNumber, hash: B256, difficulty: U256, diff --git a/crates/ethereum/engine-primitives/src/payload.rs b/crates/ethereum/engine-primitives/src/payload.rs index 4910412b5..58d8b8a95 100644 --- a/crates/ethereum/engine-primitives/src/payload.rs +++ b/crates/ethereum/engine-primitives/src/payload.rs @@ -44,17 +44,17 @@ impl EthBuiltPayload { } /// Returns the identifier of the payload. - pub fn id(&self) -> PayloadId { + pub const fn id(&self) -> PayloadId { self.id } /// Returns the built block(sealed) - pub fn block(&self) -> &SealedBlock { + pub const fn block(&self) -> &SealedBlock { &self.block } /// Fees of the block - pub fn fees(&self) -> U256 { + pub const fn fees(&self) -> U256 { self.fees } @@ -172,7 +172,7 @@ pub struct EthPayloadBuilderAttributes { impl EthPayloadBuilderAttributes { /// Returns the identifier of the payload. - pub fn payload_id(&self) -> PayloadId { + pub const fn payload_id(&self) -> PayloadId { self.id } diff --git a/crates/ethereum/node/tests/e2e/main.rs b/crates/ethereum/node/tests/e2e/main.rs index 1d0d6db8c..e7bd7f032 100644 --- a/crates/ethereum/node/tests/e2e/main.rs +++ b/crates/ethereum/node/tests/e2e/main.rs @@ -4,4 +4,4 @@ mod eth; mod p2p; mod utils; -fn main() {} +const fn main() {} diff --git a/crates/ethereum/node/tests/it/main.rs b/crates/ethereum/node/tests/it/main.rs index 5fc321fe3..be04f7ed8 100644 --- a/crates/ethereum/node/tests/it/main.rs +++ b/crates/ethereum/node/tests/it/main.rs @@ -1,4 +1,4 @@ mod builder; mod exex; -fn main() {} +const fn main() {} diff --git a/crates/evm/execution-errors/src/lib.rs b/crates/evm/execution-errors/src/lib.rs index f08fcc018..d7e1f55d5 100644 --- a/crates/evm/execution-errors/src/lib.rs +++ b/crates/evm/execution-errors/src/lib.rs @@ -149,12 +149,12 @@ impl BlockExecutionError { /// Returns `true` if the error is fatal. /// /// This represents an unrecoverable database related error. - pub fn is_fatal(&self) -> bool { + pub const fn is_fatal(&self) -> bool { matches!(self, Self::CanonicalCommit { .. } | Self::CanonicalRevert { .. }) } /// Returns `true` if the error is a state root error. - pub fn is_state_root_error(&self) -> bool { + pub const fn is_state_root_error(&self) -> bool { matches!(self, Self::Validation(BlockValidationError::StateRoot(_))) } } diff --git a/crates/evm/execution-types/src/bundle.rs b/crates/evm/execution-types/src/bundle.rs index 2b823e731..9952d5de4 100644 --- a/crates/evm/execution-types/src/bundle.rs +++ b/crates/evm/execution-types/src/bundle.rs @@ -58,7 +58,7 @@ pub type RevertsInit = HashMap> impl BundleStateWithReceipts { /// Create Bundle State. - pub fn new(bundle: BundleState, receipts: Receipts, first_block: BlockNumber) -> Self { + pub const fn new(bundle: BundleState, receipts: Receipts, first_block: BlockNumber) -> Self { Self { bundle, receipts, first_block } } @@ -101,7 +101,7 @@ impl BundleStateWithReceipts { } /// Return revm bundle state. - pub fn state(&self) -> &BundleState { + pub const fn state(&self) -> &BundleState { &self.bundle } @@ -199,7 +199,7 @@ impl BundleStateWithReceipts { } /// Returns reference to receipts. - pub fn receipts(&self) -> &Receipts { + pub const fn receipts(&self) -> &Receipts { &self.receipts } @@ -225,7 +225,7 @@ impl BundleStateWithReceipts { } /// Return first block of the bundle - pub fn first_block(&self) -> BlockNumber { + pub const fn first_block(&self) -> BlockNumber { self.first_block } diff --git a/crates/evm/execution-types/src/chain.rs b/crates/evm/execution-types/src/chain.rs index c6b441d66..a71150c86 100644 --- a/crates/evm/execution-types/src/chain.rs +++ b/crates/evm/execution-types/src/chain.rs @@ -62,7 +62,7 @@ impl Chain { } /// Get the blocks in this chain. - pub fn blocks(&self) -> &BTreeMap { + pub const fn blocks(&self) -> &BTreeMap { &self.blocks } @@ -77,7 +77,7 @@ impl Chain { } /// Get cached trie updates for this chain. - pub fn trie_updates(&self) -> Option<&TrieUpdates> { + pub const fn trie_updates(&self) -> Option<&TrieUpdates> { self.trie_updates.as_ref() } @@ -87,7 +87,7 @@ impl Chain { } /// Get post state of this chain - pub fn state(&self) -> &BundleStateWithReceipts { + pub const fn state(&self) -> &BundleStateWithReceipts { &self.state } @@ -141,7 +141,7 @@ impl Chain { /// Destructure the chain into its inner components, the blocks and the state at the tip of the /// chain. - pub fn inner(&self) -> (ChainBlocks<'_>, &BundleStateWithReceipts) { + pub const fn inner(&self) -> (ChainBlocks<'_>, &BundleStateWithReceipts) { (ChainBlocks { blocks: Cow::Borrowed(&self.blocks) }, &self.state) } diff --git a/crates/evm/src/execute.rs b/crates/evm/src/execute.rs index f459eceb1..8409f5c37 100644 --- a/crates/evm/src/execute.rs +++ b/crates/evm/src/execute.rs @@ -149,7 +149,7 @@ pub struct BlockExecutionInput<'a, Block> { impl<'a, Block> BlockExecutionInput<'a, Block> { /// Creates a new input. - pub fn new(block: &'a Block, total_difficulty: U256) -> Self { + pub const fn new(block: &'a Block, total_difficulty: U256) -> Self { Self { block, total_difficulty } } } diff --git a/crates/exex/src/manager.rs b/crates/exex/src/manager.rs index 088328c86..48bd8619b 100644 --- a/crates/exex/src/manager.rs +++ b/crates/exex/src/manager.rs @@ -436,7 +436,7 @@ impl ExExManagerHandle { } /// Returns `true` if there are ExEx's installed in the node. - pub fn has_exexs(&self) -> bool { + pub const fn has_exexs(&self) -> bool { self.num_exexs > 0 } diff --git a/crates/metrics/metrics-derive/src/expand.rs b/crates/metrics/metrics-derive/src/expand.rs index a4bb61b48..366268f4c 100644 --- a/crates/metrics/metrics-derive/src/expand.rs +++ b/crates/metrics/metrics-derive/src/expand.rs @@ -23,7 +23,7 @@ enum MetricField<'a> { } impl<'a> MetricField<'a> { - fn field(&self) -> &'a Field { + const fn field(&self) -> &'a Field { match self { MetricField::Included(Metric { field, .. }) | MetricField::Skipped(field) => field, } diff --git a/crates/metrics/metrics-derive/src/metric.rs b/crates/metrics/metrics-derive/src/metric.rs index 61aa63768..51ba984d5 100644 --- a/crates/metrics/metrics-derive/src/metric.rs +++ b/crates/metrics/metrics-derive/src/metric.rs @@ -12,7 +12,7 @@ pub(crate) struct Metric<'a> { } impl<'a> Metric<'a> { - pub(crate) fn new(field: &'a Field, description: String, rename: Option) -> Self { + pub(crate) const fn new(field: &'a Field, description: String, rename: Option) -> Self { Self { field, description, rename } } diff --git a/crates/metrics/src/common/mpsc.rs b/crates/metrics/src/common/mpsc.rs index 40c6c2359..d45fe87de 100644 --- a/crates/metrics/src/common/mpsc.rs +++ b/crates/metrics/src/common/mpsc.rs @@ -152,7 +152,7 @@ impl MeteredSender { } /// Returns the underlying [Sender](mpsc::Sender). - pub fn inner(&self) -> &mpsc::Sender { + pub const fn inner(&self) -> &mpsc::Sender { &self.sender } @@ -283,7 +283,7 @@ impl MeteredPollSender { } /// Returns the underlying [PollSender]. - pub fn inner(&self) -> &PollSender { + pub const fn inner(&self) -> &PollSender { &self.sender } diff --git a/crates/net/common/src/ban_list.rs b/crates/net/common/src/ban_list.rs index 1cde15ef2..6586becae 100644 --- a/crates/net/common/src/ban_list.rs +++ b/crates/net/common/src/ban_list.rs @@ -6,7 +6,7 @@ use std::{collections::HashMap, net::IpAddr, time::Instant}; /// Determines whether or not the IP is globally routable. /// Should be replaced with [`IpAddr::is_global`](std::net::IpAddr::is_global) once it is stable. -pub fn is_global(ip: &IpAddr) -> bool { +pub const fn is_global(ip: &IpAddr) -> bool { if ip.is_unspecified() || ip.is_loopback() { return false } @@ -40,7 +40,7 @@ impl BanList { } /// Creates a new ban list that bans the given peers and ips with an optional timeout. - pub fn new_with_timeout( + pub const fn new_with_timeout( banned_peers: HashMap>, banned_ips: HashMap>, ) -> Self { diff --git a/crates/net/common/src/bandwidth_meter.rs b/crates/net/common/src/bandwidth_meter.rs index ba24ffff7..fffd16956 100644 --- a/crates/net/common/src/bandwidth_meter.rs +++ b/crates/net/common/src/bandwidth_meter.rs @@ -104,17 +104,17 @@ impl MeteredStream { /// Creates a new [`MeteredStream`] wrapping around the provided stream, /// attaching the provided [`BandwidthMeter`] - pub fn new_with_meter(inner: S, meter: BandwidthMeter) -> Self { + pub const fn new_with_meter(inner: S, meter: BandwidthMeter) -> Self { Self { inner, meter } } /// Provides a reference to the [`BandwidthMeter`] attached to this [`MeteredStream`] - pub fn get_bandwidth_meter(&self) -> &BandwidthMeter { + pub const fn get_bandwidth_meter(&self) -> &BandwidthMeter { &self.meter } /// Returns the wrapped stream - pub fn inner(&self) -> &S { + pub const fn inner(&self) -> &S { &self.inner } } diff --git a/crates/net/common/src/ratelimit.rs b/crates/net/common/src/ratelimit.rs index 2294e8552..16365b551 100644 --- a/crates/net/common/src/ratelimit.rs +++ b/crates/net/common/src/ratelimit.rs @@ -28,7 +28,7 @@ impl RateLimit { } /// Returns the configured limit of the [RateLimit] - pub fn limit(&self) -> u64 { + pub const fn limit(&self) -> u64 { self.rate.limit() } @@ -106,15 +106,15 @@ pub struct Rate { impl Rate { /// Create a new [Rate] with the given `limit/duration` ratio. - pub fn new(limit: u64, duration: Duration) -> Self { + pub const fn new(limit: u64, duration: Duration) -> Self { Self { limit, duration } } - fn limit(&self) -> u64 { + const fn limit(&self) -> u64 { self.limit } - fn duration(&self) -> Duration { + const fn duration(&self) -> Duration { self.duration } } diff --git a/crates/net/discv4/src/lib.rs b/crates/net/discv4/src/lib.rs index de6fd507a..91123e41e 100644 --- a/crates/net/discv4/src/lib.rs +++ b/crates/net/discv4/src/lib.rs @@ -259,7 +259,7 @@ impl Discv4 { } /// Returns the address of the UDP socket. - pub fn local_addr(&self) -> SocketAddr { + pub const fn local_addr(&self) -> SocketAddr { self.local_addr } @@ -1977,7 +1977,7 @@ struct LookupTargetRotator { impl LookupTargetRotator { /// Returns a rotator that always returns the local target. - fn local_only() -> Self { + const fn local_only() -> Self { Self { interval: 1, counter: 0 } } } diff --git a/crates/net/discv4/src/proto.rs b/crates/net/discv4/src/proto.rs index 9131b91da..46988f60d 100644 --- a/crates/net/discv4/src/proto.rs +++ b/crates/net/discv4/src/proto.rs @@ -38,7 +38,7 @@ pub enum MessageId { impl MessageId { /// Converts the byte that represents the message id to the enum. - fn from_u8(msg: u8) -> Result { + const fn from_u8(msg: u8) -> Result { Ok(match msg { 1 => Self::Ping, 2 => Self::Pong, @@ -209,7 +209,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 { + pub const fn from_udp_address(udp_address: &std::net::SocketAddr, tcp_port: u16) -> Self { Self { address: udp_address.ip(), udp_port: udp_address.port(), tcp_port } } } diff --git a/crates/net/discv4/src/test_utils.rs b/crates/net/discv4/src/test_utils.rs index d4930f204..412488ace 100644 --- a/crates/net/discv4/src/test_utils.rs +++ b/crates/net/discv4/src/test_utils.rs @@ -104,12 +104,12 @@ impl MockDiscovery { } /// Returns the local socket address associated with the service. - pub fn local_addr(&self) -> SocketAddr { + pub const fn local_addr(&self) -> SocketAddr { self.local_addr } /// Returns the local [`NodeRecord`] associated with the service. - pub fn local_enr(&self) -> NodeRecord { + pub const fn local_enr(&self) -> NodeRecord { self.local_enr } diff --git a/crates/net/discv5/src/config.rs b/crates/net/discv5/src/config.rs index 5d4d2dfad..01c0f0c45 100644 --- a/crates/net/discv5/src/config.rs +++ b/crates/net/discv5/src/config.rs @@ -154,7 +154,7 @@ impl ConfigBuilder { /// Set fork ID kv-pair to set in local [`Enr`](discv5::enr::Enr). This lets peers on discovery /// network know which chain this node belongs to. - pub fn fork(mut self, fork_key: &'static [u8], fork_id: ForkId) -> Self { + pub const fn fork(mut self, fork_key: &'static [u8], fork_id: ForkId) -> Self { self.fork = Some((fork_key, fork_id)); self } @@ -162,7 +162,7 @@ impl ConfigBuilder { /// Sets the tcp socket to advertise in the local [`Enr`](discv5::enr::Enr). The IP address of /// this socket will overwrite the discovery address of the same IP version, if one is /// configured. - pub fn tcp_socket(mut self, socket: SocketAddr) -> Self { + pub const fn tcp_socket(mut self, socket: SocketAddr) -> Self { self.tcp_socket = socket; self } @@ -176,20 +176,20 @@ impl ConfigBuilder { /// Sets the interval at which to run lookup queries, in order to fill kbuckets. Lookup queries /// are done periodically at the given interval for the whole run of the program. - pub fn lookup_interval(mut self, seconds: u64) -> Self { + pub const fn lookup_interval(mut self, seconds: u64) -> Self { self.lookup_interval = Some(seconds); self } /// Sets the interval at which to run boost lookup queries at start up. Queries will be started /// at this interval for the configured number of times after start up. - pub fn bootstrap_lookup_interval(mut self, seconds: u64) -> Self { + pub const fn bootstrap_lookup_interval(mut self, seconds: u64) -> Self { self.bootstrap_lookup_interval = Some(seconds); self } /// Sets the the number of times at which to run boost lookup queries to bootstrap the node. - pub fn bootstrap_lookup_countdown(mut self, counts: u64) -> Self { + pub const fn bootstrap_lookup_countdown(mut self, counts: u64) -> Self { self.bootstrap_lookup_countdown = Some(counts); self } @@ -310,13 +310,13 @@ impl Config { /// Returns the RLPx (TCP) socket contained in the [`discv5::Config`]. This socket will be /// advertised to peers in the local [`Enr`](discv5::enr::Enr). - pub fn rlpx_socket(&self) -> &SocketAddr { + pub const fn rlpx_socket(&self) -> &SocketAddr { &self.tcp_socket } } /// Returns the IPv4 discovery socket if one is configured. -pub fn ipv4(listen_config: &ListenConfig) -> Option { +pub const fn ipv4(listen_config: &ListenConfig) -> Option { match listen_config { ListenConfig::Ipv4 { ip, port } | ListenConfig::DualStack { ipv4: ip, ipv4_port: port, .. } => { @@ -327,7 +327,7 @@ pub fn ipv4(listen_config: &ListenConfig) -> Option { } /// Returns the IPv6 discovery socket if one is configured. -pub fn ipv6(listen_config: &ListenConfig) -> Option { +pub const fn ipv6(listen_config: &ListenConfig) -> Option { match listen_config { ListenConfig::Ipv4 { .. } => None, ListenConfig::Ipv6 { ip, port } | diff --git a/crates/net/discv5/src/filter.rs b/crates/net/discv5/src/filter.rs index 8c8e1f727..5f4f21bf8 100644 --- a/crates/net/discv5/src/filter.rs +++ b/crates/net/discv5/src/filter.rs @@ -19,7 +19,7 @@ pub enum FilterOutcome { impl FilterOutcome { /// Returns `true` for [`FilterOutcome::Ok`]. - pub fn is_ok(&self) -> bool { + pub const fn is_ok(&self) -> bool { matches!(self, Self::Ok) } } diff --git a/crates/net/discv5/src/lib.rs b/crates/net/discv5/src/lib.rs index 6f30244e3..c39102173 100644 --- a/crates/net/discv5/src/lib.rs +++ b/crates/net/discv5/src/lib.rs @@ -237,7 +237,7 @@ impl Discv5 { None } discv5::Event::SessionEstablished(enr, remote_socket) => { - // this branch is semantically similar to branches of + // this branch is semantically similar to branches of // `reth_discv4::DiscoveryUpdate`: `DiscoveryUpdate::Added(_)` and // `DiscoveryUpdate::DiscoveredAtCapacity(_) @@ -253,11 +253,11 @@ impl Discv5 { socket, node_id: _, } => { - // this branch is semantically similar to branches of + // this branch is semantically similar to branches of // `reth_discv4::DiscoveryUpdate`: `DiscoveryUpdate::Added(_)` and // `DiscoveryUpdate::DiscoveredAtCapacity(_) - // peer has been discovered as part of query, or, by an outgoing session (but peer + // peer has been discovered as part of query, or, by an outgoing session (but peer // is behind NAT and responds from a different socket) // NOTE: `discv5::Discv5` won't initiate a session with any peer with an @@ -390,12 +390,12 @@ impl Discv5 { //////////////////////////////////////////////////////////////////////////////////////////////// /// Returns the RLPx [`IpMode`] of the local node. - pub fn ip_mode(&self) -> IpMode { + pub const fn ip_mode(&self) -> IpMode { self.rlpx_ip_mode } /// Returns the key to use to identify the [`ForkId`] kv-pair on the [`Enr`](discv5::Enr). - pub fn fork_key(&self) -> Option<&[u8]> { + pub const fn fork_key(&self) -> Option<&[u8]> { self.fork_key } } @@ -813,12 +813,12 @@ mod test { impl Key { /// Construct a new `Key` by providing the raw 32 byte hash. - pub fn new_raw(preimage: T, hash: GenericArray) -> Self { + pub const fn new_raw(preimage: T, hash: GenericArray) -> Self { Self { preimage, hash } } /// Borrows the preimage of the key. - pub fn preimage(&self) -> &T { + pub const fn preimage(&self) -> &T { &self.preimage } diff --git a/crates/net/discv5/src/network_stack_id.rs b/crates/net/discv5/src/network_stack_id.rs index 7bfeff517..abb534158 100644 --- a/crates/net/discv5/src/network_stack_id.rs +++ b/crates/net/discv5/src/network_stack_id.rs @@ -21,7 +21,7 @@ impl NetworkStackId { pub const OPSTACK: &'static [u8] = b"opstack"; /// Returns the [`NetworkStackId`] that matches the given [`ChainSpec`]. - pub fn id(chain: &ChainSpec) -> Option<&'static [u8]> { + pub const fn id(chain: &ChainSpec) -> Option<&'static [u8]> { if chain.is_optimism() { return Some(Self::OPEL) } else if chain.is_eth() { diff --git a/crates/net/dns/src/resolver.rs b/crates/net/dns/src/resolver.rs index c77877055..870ea30d8 100644 --- a/crates/net/dns/src/resolver.rs +++ b/crates/net/dns/src/resolver.rs @@ -52,7 +52,7 @@ pub struct DnsResolver(TokioAsyncResolver); impl DnsResolver { /// Create a new resolver by wrapping the given [AsyncResolver] - pub fn new(resolver: TokioAsyncResolver) -> Self { + pub const fn new(resolver: TokioAsyncResolver) -> Self { Self(resolver) } diff --git a/crates/net/dns/src/sync.rs b/crates/net/dns/src/sync.rs index d33d0861c..4c6633667 100644 --- a/crates/net/dns/src/sync.rs +++ b/crates/net/dns/src/sync.rs @@ -41,11 +41,11 @@ impl SyncTree { } #[cfg(test)] - pub(crate) fn root(&self) -> &TreeRootEntry { + pub(crate) const fn root(&self) -> &TreeRootEntry { &self.root } - pub(crate) fn link(&self) -> &LinkEntry { + pub(crate) const fn link(&self) -> &LinkEntry { &self.link } @@ -156,7 +156,7 @@ pub(crate) enum ResolveKind { // === impl ResolveKind === impl ResolveKind { - pub(crate) fn is_link(&self) -> bool { + pub(crate) const fn is_link(&self) -> bool { matches!(self, Self::Link) } } diff --git a/crates/net/dns/src/tree.rs b/crates/net/dns/src/tree.rs index 1c8bb51cf..0491be423 100644 --- a/crates/net/dns/src/tree.rs +++ b/crates/net/dns/src/tree.rs @@ -199,7 +199,7 @@ impl BranchEntry { /// `n` bytes of base32-encoded data. /// See also #[inline(always)] - fn base32_no_padding_decoded_len(n: usize) -> usize { + const fn base32_no_padding_decoded_len(n: usize) -> usize { n * 5 / 8 } diff --git a/crates/net/downloaders/src/bodies/bodies.rs b/crates/net/downloaders/src/bodies/bodies.rs index d8f0bfcbb..e5042691e 100644 --- a/crates/net/downloaders/src/bodies/bodies.rs +++ b/crates/net/downloaders/src/bodies/bodies.rs @@ -125,7 +125,7 @@ where } /// Get the next expected block number for queueing. - fn next_expected_block_number(&self) -> BlockNumber { + const fn next_expected_block_number(&self) -> BlockNumber { match self.latest_queued_block_number { Some(num) => num + 1, None => *self.download_range.start(), @@ -151,7 +151,7 @@ where } /// Returns true if the size of buffered blocks is lower than the configured maximum - fn has_buffer_capacity(&self) -> bool { + const fn has_buffer_capacity(&self) -> bool { self.buffered_blocks_size_bytes < self.max_buffered_blocks_size_bytes } @@ -463,7 +463,7 @@ impl OrderedBodiesResponse { /// /// See [BlockResponse::size] #[inline] - fn size(&self) -> usize { + const fn size(&self) -> usize { self.size } } @@ -529,19 +529,19 @@ impl Default for BodiesDownloaderBuilder { impl BodiesDownloaderBuilder { /// Set request batch size on the downloader. - pub fn with_request_limit(mut self, request_limit: u64) -> Self { + pub const fn with_request_limit(mut self, request_limit: u64) -> Self { self.request_limit = request_limit; self } /// Set stream batch size on the downloader. - pub fn with_stream_batch_size(mut self, stream_batch_size: usize) -> Self { + pub const fn with_stream_batch_size(mut self, stream_batch_size: usize) -> Self { self.stream_batch_size = stream_batch_size; self } /// Set concurrent requests range on the downloader. - pub fn with_concurrent_requests_range( + pub const fn with_concurrent_requests_range( mut self, concurrent_requests_range: RangeInclusive, ) -> Self { @@ -550,7 +550,7 @@ impl BodiesDownloaderBuilder { } /// Set max buffered block bytes on the downloader. - pub fn with_max_buffered_blocks_size_bytes( + pub const fn with_max_buffered_blocks_size_bytes( mut self, max_buffered_blocks_size_bytes: usize, ) -> Self { diff --git a/crates/net/downloaders/src/file_client.rs b/crates/net/downloaders/src/file_client.rs index 462f935eb..84634b6b5 100644 --- a/crates/net/downloaders/src/file_client.rs +++ b/crates/net/downloaders/src/file_client.rs @@ -362,7 +362,7 @@ pub struct ChunkedFileReader { impl ChunkedFileReader { /// Returns the remaining file length. - pub fn file_len(&self) -> u64 { + pub const fn file_len(&self) -> u64 { self.file_byte_len } diff --git a/crates/net/downloaders/src/headers/reverse_headers.rs b/crates/net/downloaders/src/headers/reverse_headers.rs index 605123cb1..68f1a9113 100644 --- a/crates/net/downloaders/src/headers/reverse_headers.rs +++ b/crates/net/downloaders/src/headers/reverse_headers.rs @@ -576,7 +576,7 @@ where } /// Returns the request for the `sync_target` header. - fn get_sync_target_request(&self, start: BlockHashOrNumber) -> HeadersRequest { + const fn get_sync_target_request(&self, start: BlockHashOrNumber) -> HeadersRequest { HeadersRequest { start, limit: 1, direction: HeadersDirection::Falling } } @@ -974,7 +974,7 @@ struct HeadersResponseError { impl HeadersResponseError { /// Returns true if the error was caused by a closed channel to the network. - fn is_channel_closed(&self) -> bool { + const fn is_channel_closed(&self) -> bool { if let DownloadError::RequestError(ref err) = self.error { return err.is_channel_closed() } @@ -1001,17 +1001,17 @@ pub enum SyncTargetBlock { impl SyncTargetBlock { /// Create new instance from hash. - fn from_hash(hash: B256) -> Self { + const fn from_hash(hash: B256) -> Self { Self::Hash(hash) } /// Create new instance from number. - fn from_number(num: u64) -> Self { + const fn from_number(num: u64) -> Self { Self::Number(num) } /// Set the hash for the sync target. - fn with_hash(self, hash: B256) -> Self { + const fn with_hash(self, hash: B256) -> Self { match self { Self::Hash(_) => Self::Hash(hash), Self::Number(number) => Self::HashAndNumber { hash, number }, @@ -1020,7 +1020,7 @@ impl SyncTargetBlock { } /// Set a number on the instance. - fn with_number(self, number: u64) -> Self { + const fn with_number(self, number: u64) -> Self { match self { Self::Hash(hash) => Self::HashAndNumber { hash, number }, Self::Number(_) => Self::Number(number), @@ -1052,7 +1052,7 @@ impl SyncTargetBlock { } /// Return the hash of the target block, if it is set. - fn hash(&self) -> Option { + const fn hash(&self) -> Option { match self { Self::Hash(hash) => Some(*hash), Self::Number(_) => None, @@ -1061,7 +1061,7 @@ impl SyncTargetBlock { } /// Return the block number of the sync target, if it is set. - fn number(&self) -> Option { + const fn number(&self) -> Option { match self { Self::Hash(_) => None, Self::Number(number) => Some(*number), @@ -1118,7 +1118,7 @@ impl ReverseHeadersDownloaderBuilder { /// /// This determines the `limit` for a `GetBlockHeaders` requests, the number of headers we ask /// for. - pub fn request_limit(mut self, limit: u64) -> Self { + pub const fn request_limit(mut self, limit: u64) -> Self { self.request_limit = limit; self } @@ -1128,7 +1128,7 @@ impl ReverseHeadersDownloaderBuilder { /// This determines the number of headers the [ReverseHeadersDownloader] will yield on /// `Stream::next`. This will be the amount of headers the headers stage will commit at a /// time. - pub fn stream_batch_size(mut self, size: usize) -> Self { + pub const fn stream_batch_size(mut self, size: usize) -> Self { self.stream_batch_size = size; self } @@ -1137,7 +1137,7 @@ impl ReverseHeadersDownloaderBuilder { /// /// If there's capacity the [ReverseHeadersDownloader] will keep at least this many requests /// active at a time. - pub fn min_concurrent_requests(mut self, min_concurrent_requests: usize) -> Self { + pub const fn min_concurrent_requests(mut self, min_concurrent_requests: usize) -> Self { self.min_concurrent_requests = min_concurrent_requests; self } @@ -1145,7 +1145,7 @@ impl ReverseHeadersDownloaderBuilder { /// Set the max amount of concurrent requests. /// /// The downloader's concurrent requests won't exceed the given amount. - pub fn max_concurrent_requests(mut self, max_concurrent_requests: usize) -> Self { + pub const fn max_concurrent_requests(mut self, max_concurrent_requests: usize) -> Self { self.max_concurrent_requests = max_concurrent_requests; self } @@ -1156,7 +1156,7 @@ impl ReverseHeadersDownloaderBuilder { /// that arrive out of order. The total number of buffered headers is `request_limit * /// max_buffered_responses`. If the [ReverseHeadersDownloader]'s buffered responses exceeds this /// threshold it waits until there's capacity again before sending new requests. - pub fn max_buffered_responses(mut self, max_buffered_responses: usize) -> Self { + pub const fn max_buffered_responses(mut self, max_buffered_responses: usize) -> Self { self.max_buffered_responses = max_buffered_responses; self } diff --git a/crates/net/downloaders/src/test_utils/bodies_client.rs b/crates/net/downloaders/src/test_utils/bodies_client.rs index 9200b4f94..d131145f0 100644 --- a/crates/net/downloaders/src/test_utils/bodies_client.rs +++ b/crates/net/downloaders/src/test_utils/bodies_client.rs @@ -32,19 +32,19 @@ impl TestBodiesClient { self } - pub(crate) fn with_should_delay(mut self, should_delay: bool) -> Self { + pub(crate) const fn with_should_delay(mut self, should_delay: bool) -> Self { self.should_delay = should_delay; self } /// Instructs the client to respond with empty responses some portion of the time. Every /// `empty_mod` responses, the client will respond with an empty response. - pub(crate) fn with_empty_responses(mut self, empty_mod: u64) -> Self { + pub(crate) const fn with_empty_responses(mut self, empty_mod: u64) -> Self { self.empty_response_mod = Some(empty_mod); self } - pub(crate) fn with_max_batch_size(mut self, max_batch_size: usize) -> Self { + pub(crate) const fn with_max_batch_size(mut self, max_batch_size: usize) -> Self { self.max_batch_size = Some(max_batch_size); self } diff --git a/crates/net/ecies/src/stream.rs b/crates/net/ecies/src/stream.rs index 4538fc059..d2930166d 100644 --- a/crates/net/ecies/src/stream.rs +++ b/crates/net/ecies/src/stream.rs @@ -125,7 +125,7 @@ where } /// Get the remote id - pub fn remote_id(&self) -> PeerId { + pub const fn remote_id(&self) -> PeerId { self.remote_id } } diff --git a/crates/net/eth-wire-types/src/broadcast.rs b/crates/net/eth-wire-types/src/broadcast.rs index 86485e8e4..e413ab9ee 100644 --- a/crates/net/eth-wire-types/src/broadcast.rs +++ b/crates/net/eth-wire-types/src/broadcast.rs @@ -137,7 +137,7 @@ pub enum NewPooledTransactionHashes { impl NewPooledTransactionHashes { /// Returns the message [`EthVersion`]. - pub fn version(&self) -> EthVersion { + pub const fn version(&self) -> EthVersion { match self { Self::Eth66(_) => EthVersion::Eth66, Self::Eth68(_) => EthVersion::Eth68, @@ -145,7 +145,7 @@ impl NewPooledTransactionHashes { } /// Returns `true` if the payload is valid for the given version - pub fn is_valid_for_version(&self, version: EthVersion) -> bool { + pub const fn is_valid_for_version(&self, version: EthVersion) -> bool { match self { Self::Eth66(_) => { matches!(version, EthVersion::Eth67 | EthVersion::Eth66) @@ -165,7 +165,7 @@ impl NewPooledTransactionHashes { } /// Returns an immutable reference to transaction hashes. - pub fn hashes(&self) -> &Vec { + pub const fn hashes(&self) -> &Vec { match self { Self::Eth66(msg) => &msg.0, Self::Eth68(msg) => &msg.hashes, @@ -226,7 +226,7 @@ impl NewPooledTransactionHashes { } /// Returns an immutable reference to the inner type if this an eth68 announcement. - pub fn as_eth68(&self) -> Option<&NewPooledTransactionHashes68> { + pub const fn as_eth68(&self) -> Option<&NewPooledTransactionHashes68> { match self { Self::Eth66(_) => None, Self::Eth68(msg) => Some(msg), @@ -597,17 +597,17 @@ handle_mempool_data_map_impl!(PartiallyValidData, ); impl PartiallyValidData { /// Wraps raw data. - pub fn from_raw_data(data: HashMap, version: Option) -> Self { + pub const fn from_raw_data(data: HashMap, version: Option) -> Self { Self { data, version } } /// Wraps raw data with version [`EthVersion::Eth68`]. - pub fn from_raw_data_eth68(data: HashMap) -> Self { + pub const fn from_raw_data_eth68(data: HashMap) -> Self { Self::from_raw_data(data, Some(EthVersion::Eth68)) } /// Wraps raw data with version [`EthVersion::Eth66`]. - pub fn from_raw_data_eth66(data: HashMap) -> Self { + pub const fn from_raw_data_eth66(data: HashMap) -> Self { Self::from_raw_data(data, Some(EthVersion::Eth66)) } @@ -625,7 +625,7 @@ impl PartiallyValidData { /// Returns the version of the message this data was received in if different versions of the /// message exists, either [`Eth66`](EthVersion::Eth66) or [`Eth68`](EthVersion::Eth68). - pub fn msg_version(&self) -> Option { + pub const fn msg_version(&self) -> Option { self.version } diff --git a/crates/net/eth-wire-types/src/message.rs b/crates/net/eth-wire-types/src/message.rs index 2239353f2..d99e8560e 100644 --- a/crates/net/eth-wire-types/src/message.rs +++ b/crates/net/eth-wire-types/src/message.rs @@ -221,7 +221,7 @@ pub enum EthMessage { impl EthMessage { /// Returns the message's ID. - pub fn message_id(&self) -> EthMessageID { + pub const fn message_id(&self) -> EthMessageID { match self { Self::Status(_) => EthMessageID::Status, Self::NewBlockHashes(_) => EthMessageID::NewBlockHashes, @@ -306,7 +306,7 @@ pub enum EthBroadcastMessage { impl EthBroadcastMessage { /// Returns the message's ID. - pub fn message_id(&self) -> EthMessageID { + pub const fn message_id(&self) -> EthMessageID { match self { Self::NewBlock(_) => EthMessageID::NewBlock, Self::Transactions(_) => EthMessageID::Transactions, diff --git a/crates/net/eth-wire-types/src/status.rs b/crates/net/eth-wire-types/src/status.rs index a28f4ec45..e2dfb1712 100644 --- a/crates/net/eth-wire-types/src/status.rs +++ b/crates/net/eth-wire-types/src/status.rs @@ -184,42 +184,42 @@ pub struct StatusBuilder { impl StatusBuilder { /// Consumes the type and creates the actual [`Status`] message. - pub fn build(self) -> Status { + pub const fn build(self) -> Status { self.status } /// Sets the protocol version. - pub fn version(mut self, version: u8) -> Self { + pub const fn version(mut self, version: u8) -> Self { self.status.version = version; self } /// Sets the chain id. - pub fn chain(mut self, chain: Chain) -> Self { + pub const fn chain(mut self, chain: Chain) -> Self { self.status.chain = chain; self } /// Sets the total difficulty. - pub fn total_difficulty(mut self, total_difficulty: U256) -> Self { + pub const fn total_difficulty(mut self, total_difficulty: U256) -> Self { self.status.total_difficulty = total_difficulty; self } /// Sets the block hash. - pub fn blockhash(mut self, blockhash: B256) -> Self { + pub const fn blockhash(mut self, blockhash: B256) -> Self { self.status.blockhash = blockhash; self } /// Sets the genesis hash. - pub fn genesis(mut self, genesis: B256) -> Self { + pub const fn genesis(mut self, genesis: B256) -> Self { self.status.genesis = genesis; self } /// Sets the fork id. - pub fn forkid(mut self, forkid: ForkId) -> Self { + pub const fn forkid(mut self, forkid: ForkId) -> Self { self.status.forkid = forkid; self } diff --git a/crates/net/eth-wire/src/capability.rs b/crates/net/eth-wire/src/capability.rs index 657ee5b29..c781e21dd 100644 --- a/crates/net/eth-wire/src/capability.rs +++ b/crates/net/eth-wire/src/capability.rs @@ -53,7 +53,7 @@ pub struct Capability { impl Capability { /// Create a new `Capability` with the given name and version. - pub fn new(name: String, version: usize) -> Self { + pub const fn new(name: String, version: usize) -> Self { Self { name: Cow::Owned(name), version } } @@ -170,25 +170,25 @@ impl Capabilities { /// Whether the peer supports `eth` sub-protocol. #[inline] - pub fn supports_eth(&self) -> bool { + pub const fn supports_eth(&self) -> bool { self.eth_68 || self.eth_67 || self.eth_66 } /// Whether this peer supports eth v66 protocol. #[inline] - pub fn supports_eth_v66(&self) -> bool { + pub const fn supports_eth_v66(&self) -> bool { self.eth_66 } /// Whether this peer supports eth v67 protocol. #[inline] - pub fn supports_eth_v67(&self) -> bool { + pub const fn supports_eth_v67(&self) -> bool { self.eth_67 } /// Whether this peer supports eth v68 protocol. #[inline] - pub fn supports_eth_v68(&self) -> bool { + pub const fn supports_eth_v68(&self) -> bool { self.eth_68 } } @@ -287,7 +287,7 @@ impl SharedCapability { } /// Returns the capability. - pub fn capability(&self) -> Cow<'_, Capability> { + pub const fn capability(&self) -> Cow<'_, Capability> { match self { Self::Eth { version, .. } => Cow::Owned(Capability::eth(*version)), Self::UnknownCapability { cap, .. } => Cow::Borrowed(cap), @@ -305,12 +305,12 @@ impl SharedCapability { /// Returns true if the capability is eth. #[inline] - pub fn is_eth(&self) -> bool { + pub const fn is_eth(&self) -> bool { matches!(self, Self::Eth { .. }) } /// Returns the version of the capability. - pub fn version(&self) -> u8 { + pub const fn version(&self) -> u8 { match self { Self::Eth { version, .. } => *version as u8, Self::UnknownCapability { cap, .. } => cap.version as u8, @@ -318,7 +318,7 @@ impl SharedCapability { } /// Returns the eth version if it's the `eth` capability. - pub fn eth_version(&self) -> Option { + pub const fn eth_version(&self) -> Option { match self { Self::Eth { version, .. } => Some(*version), _ => None, @@ -329,7 +329,7 @@ impl SharedCapability { /// /// This represents the message ID offset for the first message of the eth capability in the /// message id space. - pub fn message_id_offset(&self) -> u8 { + pub const fn message_id_offset(&self) -> u8 { match self { Self::Eth { offset, .. } => *offset, Self::UnknownCapability { offset, .. } => *offset, @@ -338,12 +338,12 @@ impl SharedCapability { /// Returns the message ID offset of the current capability relative to the start of the /// reserved message id space: [`MAX_RESERVED_MESSAGE_ID`]. - pub fn relative_message_id_offset(&self) -> u8 { + pub const fn relative_message_id_offset(&self) -> u8 { self.message_id_offset() - MAX_RESERVED_MESSAGE_ID - 1 } /// Returns the number of protocol messages supported by this capability. - pub fn num_messages(&self) -> u8 { + pub const fn num_messages(&self) -> u8 { match self { Self::Eth { version: _version, .. } => EthMessageID::max() + 1, Self::UnknownCapability { messages, .. } => *messages, diff --git a/crates/net/eth-wire/src/errors/eth.rs b/crates/net/eth-wire/src/errors/eth.rs index c7b0718fc..89bad5174 100644 --- a/crates/net/eth-wire/src/errors/eth.rs +++ b/crates/net/eth-wire/src/errors/eth.rs @@ -43,7 +43,7 @@ pub enum EthStreamError { impl EthStreamError { /// Returns the [`DisconnectReason`] if the error is a disconnect message - pub fn as_disconnected(&self) -> Option { + pub const fn as_disconnected(&self) -> Option { if let Self::P2PStreamError(err) = self { err.as_disconnected() } else { @@ -52,7 +52,7 @@ impl EthStreamError { } /// Returns the [io::Error] if it was caused by IO - pub fn as_io(&self) -> Option<&io::Error> { + pub const fn as_io(&self) -> Option<&io::Error> { if let Self::P2PStreamError(P2PStreamError::Io(io)) = self { return Some(io) } diff --git a/crates/net/eth-wire/src/errors/p2p.rs b/crates/net/eth-wire/src/errors/p2p.rs index 83a39e2b6..6b11f497c 100644 --- a/crates/net/eth-wire/src/errors/p2p.rs +++ b/crates/net/eth-wire/src/errors/p2p.rs @@ -84,7 +84,7 @@ pub enum P2PStreamError { impl P2PStreamError { /// Returns the [`DisconnectReason`] if it is the `Disconnected` variant. - pub fn as_disconnected(&self) -> Option { + pub const fn as_disconnected(&self) -> Option { let reason = match self { Self::HandshakeError(P2PHandshakeError::Disconnected(reason)) => reason, Self::Disconnected(reason) => reason, diff --git a/crates/net/eth-wire/src/ethstream.rs b/crates/net/eth-wire/src/ethstream.rs index 8de509034..88d02ce67 100644 --- a/crates/net/eth-wire/src/ethstream.rs +++ b/crates/net/eth-wire/src/ethstream.rs @@ -34,7 +34,7 @@ pub struct UnauthedEthStream { impl UnauthedEthStream { /// Create a new `UnauthedEthStream` from a type `S` which implements `Stream` and `Sink`. - pub fn new(inner: S) -> Self { + pub const fn new(inner: S) -> Self { Self { inner } } @@ -197,19 +197,19 @@ impl EthStream { /// Creates a new unauthed [`EthStream`] from a provided stream. You will need /// to manually handshake a peer. #[inline] - pub fn new(version: EthVersion, inner: S) -> Self { + pub const fn new(version: EthVersion, inner: S) -> Self { Self { version, inner } } /// Returns the eth version. #[inline] - pub fn version(&self) -> EthVersion { + pub const fn version(&self) -> EthVersion { self.version } /// Returns the underlying stream. #[inline] - pub fn inner(&self) -> &S { + pub const fn inner(&self) -> &S { &self.inner } diff --git a/crates/net/eth-wire/src/hello.rs b/crates/net/eth-wire/src/hello.rs index f953c4aae..85dda8bfa 100644 --- a/crates/net/eth-wire/src/hello.rs +++ b/crates/net/eth-wire/src/hello.rs @@ -45,7 +45,7 @@ impl HelloMessageWithProtocols { /// let id = pk2id(&secret_key.public_key(SECP256K1)); /// let status = HelloMessageWithProtocols::builder(id).build(); /// ``` - pub fn builder(id: PeerId) -> HelloMessageBuilder { + pub const fn builder(id: PeerId) -> HelloMessageBuilder { HelloMessageBuilder::new(id) } @@ -127,7 +127,7 @@ impl HelloMessage { /// let id = pk2id(&secret_key.public_key(SECP256K1)); /// let status = HelloMessage::builder(id).build(); /// ``` - pub fn builder(id: PeerId) -> HelloMessageBuilder { + pub const fn builder(id: PeerId) -> HelloMessageBuilder { HelloMessageBuilder::new(id) } } @@ -152,12 +152,12 @@ pub struct HelloMessageBuilder { impl HelloMessageBuilder { /// Create a new builder to configure a [`HelloMessage`] - pub fn new(id: PeerId) -> Self { + pub const fn new(id: PeerId) -> Self { Self { protocol_version: None, client_version: None, protocols: None, port: None, id } } /// Sets the port the client is listening on - pub fn port(mut self, port: u16) -> Self { + pub const fn port(mut self, port: u16) -> Self { self.port = Some(port); self } @@ -181,7 +181,7 @@ impl HelloMessageBuilder { } /// Sets protocol version. - pub fn protocol_version(mut self, protocol_version: ProtocolVersion) -> Self { + pub const fn protocol_version(mut self, protocol_version: ProtocolVersion) -> Self { self.protocol_version = Some(protocol_version); self } diff --git a/crates/net/eth-wire/src/multiplex.rs b/crates/net/eth-wire/src/multiplex.rs index 82172f8d5..06c091548 100644 --- a/crates/net/eth-wire/src/multiplex.rs +++ b/crates/net/eth-wire/src/multiplex.rs @@ -64,7 +64,7 @@ impl RlpxProtocolMultiplexer { } /// Returns the [SharedCapabilities] of the underlying raw p2p stream - pub fn shared_capabilities(&self) -> &SharedCapabilities { + pub const fn shared_capabilities(&self) -> &SharedCapabilities { self.inner.shared_capabilities() } @@ -234,7 +234,7 @@ struct MultiplexInner { } impl MultiplexInner { - fn shared_capabilities(&self) -> &SharedCapabilities { + const fn shared_capabilities(&self) -> &SharedCapabilities { self.conn.shared_capabilities() } @@ -417,7 +417,7 @@ impl RlpxSatelliteStream { /// Returns the primary protocol. #[inline] - pub fn primary(&self) -> &Primary { + pub const fn primary(&self) -> &Primary { &self.primary.st } @@ -429,7 +429,7 @@ impl RlpxSatelliteStream { /// Returns the underlying [P2PStream]. #[inline] - pub fn inner(&self) -> &P2PStream { + pub const fn inner(&self) -> &P2PStream { &self.inner.conn } diff --git a/crates/net/eth-wire/src/p2pstream.rs b/crates/net/eth-wire/src/p2pstream.rs index 1523a3a35..719c7f173 100644 --- a/crates/net/eth-wire/src/p2pstream.rs +++ b/crates/net/eth-wire/src/p2pstream.rs @@ -74,12 +74,12 @@ pub struct UnauthedP2PStream { impl UnauthedP2PStream { /// Create a new `UnauthedP2PStream` from a type `S` which implements `Stream` and `Sink`. - pub fn new(inner: S) -> Self { + pub const fn new(inner: S) -> Self { Self { inner } } /// Returns a reference to the inner stream. - pub fn inner(&self) -> &S { + pub const fn inner(&self) -> &S { &self.inner } } @@ -275,7 +275,7 @@ impl P2PStream { } /// Returns a reference to the inner stream. - pub fn inner(&self) -> &S { + pub const fn inner(&self) -> &S { &self.inner } @@ -292,7 +292,7 @@ impl P2PStream { /// /// This includes all the shared capabilities that were negotiated during the handshake and /// their offsets based on the number of messages of each capability. - pub fn shared_capabilities(&self) -> &SharedCapabilities { + pub const fn shared_capabilities(&self) -> &SharedCapabilities { &self.shared_capabilities } @@ -663,7 +663,7 @@ pub enum P2PMessage { impl P2PMessage { /// Gets the [`P2PMessageID`] for the given message. - pub fn message_id(&self) -> P2PMessageID { + pub const fn message_id(&self) -> P2PMessageID { match self { Self::Hello(_) => P2PMessageID::Hello, Self::Disconnect(_) => P2PMessageID::Disconnect, diff --git a/crates/net/eth-wire/src/pinger.rs b/crates/net/eth-wire/src/pinger.rs index 1d1898abe..d93404c5f 100644 --- a/crates/net/eth-wire/src/pinger.rs +++ b/crates/net/eth-wire/src/pinger.rs @@ -58,7 +58,7 @@ impl Pinger { } /// Returns the current state of the pinger. - pub(crate) fn state(&self) -> PingState { + pub(crate) const fn state(&self) -> PingState { self.state } diff --git a/crates/net/eth-wire/src/test_utils.rs b/crates/net/eth-wire/src/test_utils.rs index 0783e4dad..19d893d0b 100644 --- a/crates/net/eth-wire/src/test_utils.rs +++ b/crates/net/eth-wire/src/test_utils.rs @@ -93,22 +93,22 @@ pub mod proto { impl TestProtoMessage { /// Returns the capability for the `test` protocol. - pub fn capability() -> Capability { + pub const fn capability() -> Capability { Capability::new_static("test", 1) } /// Returns the protocol for the `test` protocol. - pub fn protocol() -> Protocol { + pub const fn protocol() -> Protocol { Protocol::new(Self::capability(), 3) } /// Creates a ping message - pub fn ping() -> Self { + pub const fn ping() -> Self { Self { message_type: TestProtoMessageId::Ping, message: TestProtoMessageKind::Ping } } /// Creates a pong message - pub fn pong() -> Self { + pub const fn pong() -> Self { Self { message_type: TestProtoMessageId::Pong, message: TestProtoMessageKind::Pong } } diff --git a/crates/net/network-api/src/lib.rs b/crates/net/network-api/src/lib.rs index c197ecba5..87fc9c5f2 100644 --- a/crates/net/network-api/src/lib.rs +++ b/crates/net/network-api/src/lib.rs @@ -197,12 +197,12 @@ pub enum Direction { impl Direction { /// Returns `true` if this an incoming connection. - pub fn is_incoming(&self) -> bool { + pub const fn is_incoming(&self) -> bool { matches!(self, Self::Incoming) } /// Returns `true` if this an outgoing connection. - pub fn is_outgoing(&self) -> bool { + pub const fn is_outgoing(&self) -> bool { matches!(self, Self::Outgoing(_)) } } diff --git a/crates/net/network-api/src/reputation.rs b/crates/net/network-api/src/reputation.rs index 718e0e9ba..a24f5b93d 100644 --- a/crates/net/network-api/src/reputation.rs +++ b/crates/net/network-api/src/reputation.rs @@ -41,12 +41,12 @@ pub enum ReputationChangeKind { impl ReputationChangeKind { /// Returns true if the reputation change is a [ReputationChangeKind::Reset]. - pub fn is_reset(&self) -> bool { + pub const fn is_reset(&self) -> bool { matches!(self, Self::Reset) } /// Returns true if the reputation change is [ReputationChangeKind::Dropped]. - pub fn is_dropped(&self) -> bool { + pub const fn is_dropped(&self) -> bool { matches!(self, Self::Dropped) } } diff --git a/crates/net/network/src/builder.rs b/crates/net/network/src/builder.rs index ed74de94f..03e93bb6b 100644 --- a/crates/net/network/src/builder.rs +++ b/crates/net/network/src/builder.rs @@ -30,7 +30,7 @@ impl NetworkBuilder { } /// Returns the network manager. - pub fn network(&self) -> &NetworkManager { + pub const fn network(&self) -> &NetworkManager { &self.network } diff --git a/crates/net/network/src/config.rs b/crates/net/network/src/config.rs index 6a5c16777..61ac9fc3f 100644 --- a/crates/net/network/src/config.rs +++ b/crates/net/network/src/config.rs @@ -105,13 +105,13 @@ impl NetworkConfig { } /// Sets the address for the incoming RLPx connection listener. - pub fn set_listener_addr(mut self, listener_addr: SocketAddr) -> Self { + pub const fn set_listener_addr(mut self, listener_addr: SocketAddr) -> Self { self.listener_addr = listener_addr; self } /// Returns the address for the incoming RLPx connection listener. - pub fn listener_addr(&self) -> &SocketAddr { + pub const fn listener_addr(&self) -> &SocketAddr { &self.listener_addr } } @@ -218,7 +218,7 @@ impl NetworkConfigBuilder { } /// Sets the [`NetworkMode`]. - pub fn network_mode(mut self, network_mode: NetworkMode) -> Self { + pub const fn network_mode(mut self, network_mode: NetworkMode) -> Self { self.network_mode = network_mode; self } @@ -228,7 +228,7 @@ impl NetworkConfigBuilder { /// This is used to construct the appropriate [`ForkFilter`] and [`Status`] message. /// /// If not set, this defaults to the genesis specified by the current chain specification. - pub fn set_head(mut self, head: Head) -> Self { + pub const fn set_head(mut self, head: Head) -> Self { self.head = Some(head); self } @@ -263,12 +263,12 @@ impl NetworkConfigBuilder { } /// Sets a custom config for how sessions are handled. - pub fn sessions_config(mut self, config: SessionsConfig) -> Self { + pub const fn sessions_config(mut self, config: SessionsConfig) -> Self { self.sessions_config = Some(config); self } - pub fn transactions_manager_config(mut self, config: TransactionsManagerConfig) -> Self { + pub const fn transactions_manager_config(mut self, config: TransactionsManagerConfig) -> Self { self.transactions_manager_config = config; self } @@ -280,14 +280,14 @@ impl NetworkConfigBuilder { /// /// By default, both are on the same port: /// [DEFAULT_DISCOVERY_PORT](reth_discv4::DEFAULT_DISCOVERY_PORT) - pub fn set_addrs(self, addr: SocketAddr) -> Self { + pub const fn set_addrs(self, addr: SocketAddr) -> Self { self.listener_addr(addr).discovery_addr(addr) } /// Sets the socket address the network will listen on. /// /// By default, this is [DEFAULT_DISCOVERY_ADDRESS] - pub fn listener_addr(mut self, listener_addr: SocketAddr) -> Self { + pub const fn listener_addr(mut self, listener_addr: SocketAddr) -> Self { self.listener_addr = Some(listener_addr); self } @@ -301,7 +301,7 @@ impl NetworkConfigBuilder { } /// Sets the socket address the discovery network will listen on - pub fn discovery_addr(mut self, discovery_addr: SocketAddr) -> Self { + pub const fn discovery_addr(mut self, discovery_addr: SocketAddr) -> Self { self.discovery_addr = Some(discovery_addr); self } @@ -442,7 +442,7 @@ impl NetworkConfigBuilder { } /// Sets whether tx gossip is disabled. - pub fn disable_tx_gossip(mut self, disable_tx_gossip: bool) -> Self { + pub const fn disable_tx_gossip(mut self, disable_tx_gossip: bool) -> Self { self.tx_gossip_disabled = disable_tx_gossip; self } @@ -565,7 +565,7 @@ pub enum NetworkMode { impl NetworkMode { /// Returns true if network has entered proof-of-stake - pub fn is_stake(&self) -> bool { + pub const fn is_stake(&self) -> bool { matches!(self, Self::Stake) } } diff --git a/crates/net/network/src/discovery.rs b/crates/net/network/src/discovery.rs index bb456d4ea..8d268765e 100644 --- a/crates/net/network/src/discovery.rs +++ b/crates/net/network/src/discovery.rs @@ -179,7 +179,7 @@ impl Discovery { } /// Returns the id with which the local node identifies itself in the network - pub(crate) fn local_id(&self) -> PeerId { + pub(crate) const fn local_id(&self) -> PeerId { self.local_enr.id // local discv4 and discv5 have same id, since signed with same secret key } diff --git a/crates/net/network/src/error.rs b/crates/net/network/src/error.rs index 95cb5c630..702a57940 100644 --- a/crates/net/network/src/error.rs +++ b/crates/net/network/src/error.rs @@ -19,7 +19,7 @@ pub enum ServiceKind { impl ServiceKind { /// Returns the appropriate flags for each variant. - pub fn flags(&self) -> &'static str { + pub const fn flags(&self) -> &'static str { match self { Self::Listener(_) => "--port", Self::Discovery(_) => "--discovery.port", @@ -127,7 +127,7 @@ pub enum BackoffKind { impl BackoffKind { /// Returns true if the backoff is considered severe. - pub(crate) fn is_severe(&self) -> bool { + pub(crate) const fn is_severe(&self) -> bool { matches!(self, Self::Medium | Self::High) } } diff --git a/crates/net/network/src/fetch/mod.rs b/crates/net/network/src/fetch/mod.rs index 9844d2f91..d6d6d3efb 100644 --- a/crates/net/network/src/fetch/mod.rs +++ b/crates/net/network/src/fetch/mod.rs @@ -371,7 +371,7 @@ enum PeerState { impl PeerState { /// Returns true if the peer is currently idle. - fn is_idle(&self) -> bool { + const fn is_idle(&self) -> bool { matches!(self, Self::Idle) } @@ -421,7 +421,7 @@ pub(crate) enum DownloadRequest { impl DownloadRequest { /// Returns the corresponding state for a peer that handles the request. - fn peer_state(&self) -> PeerState { + const fn peer_state(&self) -> PeerState { match self { Self::GetBlockHeaders { .. } => PeerState::GetBlockHeaders, Self::GetBlockBodies { .. } => PeerState::GetBlockBodies, @@ -429,7 +429,7 @@ impl DownloadRequest { } /// Returns the requested priority of this request - fn get_priority(&self) -> &Priority { + const fn get_priority(&self) -> &Priority { match self { Self::GetBlockHeaders { priority, .. } => priority, Self::GetBlockBodies { priority, .. } => priority, @@ -437,7 +437,7 @@ impl DownloadRequest { } /// Returns `true` if this request is normal priority. - fn is_normal_priority(&self) -> bool { + const fn is_normal_priority(&self) -> bool { self.get_priority().is_normal() } } diff --git a/crates/net/network/src/listener.rs b/crates/net/network/src/listener.rs index 4cc219655..d0654042a 100644 --- a/crates/net/network/src/listener.rs +++ b/crates/net/network/src/listener.rs @@ -33,7 +33,7 @@ impl ConnectionListener { } /// Creates a new connection listener stream. - pub(crate) fn new(listener: TcpListener, local_address: SocketAddr) -> Self { + pub(crate) const fn new(listener: TcpListener, local_address: SocketAddr) -> Self { Self { local_address, incoming: TcpListenerStream { inner: listener } } } @@ -55,7 +55,7 @@ impl ConnectionListener { } /// Returns the socket address this listener listens on. - pub fn local_address(&self) -> SocketAddr { + pub const fn local_address(&self) -> SocketAddr { self.local_address } } diff --git a/crates/net/network/src/manager.rs b/crates/net/network/src/manager.rs index 3f7b77b42..a219b6492 100644 --- a/crates/net/network/src/manager.rs +++ b/crates/net/network/src/manager.rs @@ -137,7 +137,7 @@ impl NetworkManager { /// Returns the [`NetworkHandle`] that can be cloned and shared. /// /// The [`NetworkHandle`] can be used to interact with this [`NetworkManager`] - pub fn handle(&self) -> &NetworkHandle { + pub const fn handle(&self) -> &NetworkHandle { &self.handle } @@ -148,7 +148,7 @@ impl NetworkManager { } /// Returns the secret key used for authenticating sessions. - pub fn secret_key(&self) -> SecretKey { + pub const fn secret_key(&self) -> SecretKey { self.swarm.sessions().secret_key() } @@ -313,12 +313,12 @@ where } /// Create a [`NetworkBuilder`] to configure all components of the network - pub fn into_builder(self) -> NetworkBuilder { + pub const fn into_builder(self) -> NetworkBuilder { NetworkBuilder { network: self, transactions: (), request_handler: () } } /// Returns the [`SocketAddr`] that listens for incoming connections. - pub fn local_addr(&self) -> SocketAddr { + pub const fn local_addr(&self) -> SocketAddr { self.swarm.listener().local_address() } diff --git a/crates/net/network/src/message.rs b/crates/net/network/src/message.rs index 3a067cbfd..03068ee96 100644 --- a/crates/net/network/src/message.rs +++ b/crates/net/network/src/message.rs @@ -321,7 +321,7 @@ pub struct PeerRequestSender { impl PeerRequestSender { /// Constructs a new sender instance that's wired to a session - pub(crate) fn new(peer_id: PeerId, to_session_tx: mpsc::Sender) -> Self { + pub(crate) const fn new(peer_id: PeerId, to_session_tx: mpsc::Sender) -> Self { Self { peer_id, to_session_tx } } @@ -331,7 +331,7 @@ impl PeerRequestSender { } /// Returns the peer id of the remote peer. - pub fn peer_id(&self) -> &PeerId { + pub const fn peer_id(&self) -> &PeerId { &self.peer_id } } diff --git a/crates/net/network/src/peers/manager.rs b/crates/net/network/src/peers/manager.rs index e1ccb13be..5ff84d386 100644 --- a/crates/net/network/src/peers/manager.rs +++ b/crates/net/network/src/peers/manager.rs @@ -205,19 +205,19 @@ impl PeersManager { /// Returns the number of currently active inbound connections. #[inline] - pub(crate) fn num_inbound_connections(&self) -> usize { + pub(crate) const fn num_inbound_connections(&self) -> usize { self.connection_info.num_inbound } /// Returns the number of currently __active__ outbound connections. #[inline] - pub(crate) fn num_outbound_connections(&self) -> usize { + pub(crate) const fn num_outbound_connections(&self) -> usize { self.connection_info.num_outbound } /// Returns the number of currently pending outbound connections. #[inline] - pub(crate) fn num_pending_outbound_connections(&self) -> usize { + pub(crate) const fn num_pending_outbound_connections(&self) -> usize { self.connection_info.num_pending_out } @@ -838,7 +838,7 @@ impl PeersManager { } /// Returns the current network connection state. - pub fn connection_state(&self) -> &NetworkConnectionState { + pub const fn connection_state(&self) -> &NetworkConnectionState { &self.net_connection_state } @@ -948,13 +948,13 @@ pub struct ConnectionInfo { impl ConnectionInfo { /// Returns `true` if there's still capacity for a new outgoing connection. - fn has_out_capacity(&self) -> bool { + const fn has_out_capacity(&self) -> bool { self.num_pending_out < self.max_concurrent_outbound_dials && self.num_outbound < self.max_outbound } /// Returns `true` if there's still capacity for a new incoming connection. - fn has_in_capacity(&self) -> bool { + const fn has_in_capacity(&self) -> bool { self.num_inbound < self.max_inbound } @@ -1047,7 +1047,7 @@ impl Peer { } /// Returns the reputation of the peer - pub fn reputation(&self) -> i32 { + pub const fn reputation(&self) -> i32 { self.reputation } @@ -1102,12 +1102,12 @@ impl Peer { /// Returns true if the peer's reputation is below the banned threshold. #[inline] - fn is_banned(&self) -> bool { + const fn is_banned(&self) -> bool { is_banned_reputation(self.reputation) } #[inline] - fn is_backed_off(&self) -> bool { + const fn is_backed_off(&self) -> bool { self.backed_off } @@ -1119,7 +1119,7 @@ impl Peer { /// Returns whether this peer is trusted #[inline] - fn is_trusted(&self) -> bool { + const fn is_trusted(&self) -> bool { matches!(self.kind, PeerKind::Trusted) } } @@ -1169,25 +1169,25 @@ impl PeerConnectionState { /// Returns true if this is an active incoming connection. #[inline] - fn is_incoming(&self) -> bool { + const fn is_incoming(&self) -> bool { matches!(self, Self::In) } /// Returns whether we're currently connected with this peer #[inline] - fn is_connected(&self) -> bool { + const fn is_connected(&self) -> bool { matches!(self, Self::In | Self::Out | Self::PendingOut) } /// Returns if there's currently no connection to that peer. #[inline] - fn is_unconnected(&self) -> bool { + const fn is_unconnected(&self) -> bool { matches!(self, Self::Idle) } /// Returns true if there's currently an outbound dial to that peer. #[inline] - fn is_pending_out(&self) -> bool { + const fn is_pending_out(&self) -> bool { matches!(self, Self::PendingOut) } } @@ -1334,31 +1334,31 @@ impl PeersConfig { } /// Configure how long to ban bad peers - pub fn with_ban_duration(mut self, ban_duration: Duration) -> Self { + pub const fn with_ban_duration(mut self, ban_duration: Duration) -> Self { self.ban_duration = ban_duration; self } /// Maximum occupied slots for outbound connections. - pub fn with_max_pending_outbound(mut self, num_outbound: usize) -> Self { + pub const fn with_max_pending_outbound(mut self, num_outbound: usize) -> Self { self.connection_info.num_outbound = num_outbound; self } /// Maximum occupied slots for inbound connections. - pub fn with_max_pending_inbound(mut self, num_inbound: usize) -> Self { + pub const fn with_max_pending_inbound(mut self, num_inbound: usize) -> Self { self.connection_info.num_inbound = num_inbound; self } /// Maximum allowed outbound connections. - pub fn with_max_outbound(mut self, max_outbound: usize) -> Self { + pub const fn with_max_outbound(mut self, max_outbound: usize) -> Self { self.connection_info.max_outbound = max_outbound; self } /// Maximum allowed inbound connections with optional update. - pub fn with_max_inbound_opt(mut self, max_inbound: Option) -> Self { + pub const fn with_max_inbound_opt(mut self, max_inbound: Option) -> Self { if let Some(max_inbound) = max_inbound { self.connection_info.max_inbound = max_inbound; } @@ -1366,7 +1366,7 @@ impl PeersConfig { } /// Maximum allowed outbound connections with optional update. - pub fn with_max_outbound_opt(mut self, max_outbound: Option) -> Self { + pub const fn with_max_outbound_opt(mut self, max_outbound: Option) -> Self { if let Some(max_outbound) = max_outbound { self.connection_info.max_outbound = max_outbound; } @@ -1374,13 +1374,13 @@ impl PeersConfig { } /// Maximum allowed inbound connections. - pub fn with_max_inbound(mut self, max_inbound: usize) -> Self { + pub const fn with_max_inbound(mut self, max_inbound: usize) -> Self { self.connection_info.max_inbound = max_inbound; self } /// Maximum allowed concurrent outbound dials. - pub fn with_max_concurrent_dials(mut self, max_concurrent_outbound_dials: usize) -> Self { + pub const fn with_max_concurrent_dials(mut self, max_concurrent_outbound_dials: usize) -> Self { self.connection_info.max_concurrent_outbound_dials = max_concurrent_outbound_dials; self } @@ -1392,7 +1392,7 @@ impl PeersConfig { } /// Connect only to trusted nodes. - pub fn with_trusted_nodes_only(mut self, trusted_only: bool) -> Self { + pub const fn with_trusted_nodes_only(mut self, trusted_only: bool) -> Self { self.trusted_nodes_only = trusted_only; self } @@ -1404,19 +1404,22 @@ impl PeersConfig { } /// Configures the max allowed backoff count. - pub fn with_max_backoff_count(mut self, max_backoff_count: u8) -> Self { + pub const fn with_max_backoff_count(mut self, max_backoff_count: u8) -> Self { self.max_backoff_count = max_backoff_count; self } /// Configures how to weigh reputation changes. - pub fn with_reputation_weights(mut self, reputation_weights: ReputationChangeWeights) -> Self { + pub const fn with_reputation_weights( + mut self, + reputation_weights: ReputationChangeWeights, + ) -> Self { self.reputation_weights = reputation_weights; self } /// Configures how long to backoff peers that are we failed to connect to for non-fatal reasons - pub fn with_backoff_durations(mut self, backoff_durations: PeerBackoffDurations) -> Self { + pub const fn with_backoff_durations(mut self, backoff_durations: PeerBackoffDurations) -> Self { self.backoff_durations = backoff_durations; self } @@ -1477,7 +1480,7 @@ pub struct PeerBackoffDurations { impl PeerBackoffDurations { /// Returns the corresponding [`Duration`] - pub fn backoff(&self, kind: BackoffKind) -> Duration { + pub const fn backoff(&self, kind: BackoffKind) -> Duration { match kind { BackoffKind::Low => self.low, BackoffKind::Medium => self.medium, diff --git a/crates/net/network/src/peers/reputation.rs b/crates/net/network/src/peers/reputation.rs index ad87446d0..9d3ec256b 100644 --- a/crates/net/network/src/peers/reputation.rs +++ b/crates/net/network/src/peers/reputation.rs @@ -46,7 +46,7 @@ pub(crate) const MAX_TRUSTED_PEER_REPUTATION_CHANGE: Reputation = 2 * REPUTATION /// Returns `true` if the given reputation is below the [`BANNED_REPUTATION`] threshold #[inline] -pub(crate) fn is_banned_reputation(reputation: i32) -> bool { +pub(crate) const fn is_banned_reputation(reputation: i32) -> bool { reputation < BANNED_REPUTATION } @@ -122,7 +122,7 @@ pub(crate) struct ReputationChange(Reputation); impl ReputationChange { /// Helper type for easier conversion #[inline] - pub(crate) fn as_i32(self) -> Reputation { + pub(crate) const fn as_i32(self) -> Reputation { self.0 } } diff --git a/crates/net/network/src/session/active.rs b/crates/net/network/src/session/active.rs index 7fed5b311..91c44ca10 100644 --- a/crates/net/network/src/session/active.rs +++ b/crates/net/network/src/session/active.rs @@ -685,7 +685,7 @@ impl InflightRequest { /// Returns true if we're still waiting for a response #[inline] - fn is_waiting(&self) -> bool { + const fn is_waiting(&self) -> bool { matches!(self.request, RequestState::Waiting(_)) } diff --git a/crates/net/network/src/session/config.rs b/crates/net/network/src/session/config.rs index e285d2b7a..8385a3697 100644 --- a/crates/net/network/src/session/config.rs +++ b/crates/net/network/src/session/config.rs @@ -82,7 +82,7 @@ impl SessionsConfig { /// /// It is expected, that the background session task will stall if they outpace the manager. The /// buffer size provides backpressure on the network I/O. - pub fn with_session_event_buffer(mut self, n: usize) -> Self { + pub const fn with_session_event_buffer(mut self, n: usize) -> Self { self.session_event_buffer = n; self } @@ -119,25 +119,25 @@ pub struct SessionLimits { impl SessionLimits { /// Sets the maximum number of pending incoming sessions. - pub fn with_max_pending_inbound(mut self, limit: u32) -> Self { + pub const fn with_max_pending_inbound(mut self, limit: u32) -> Self { self.max_pending_inbound = Some(limit); self } /// Sets the maximum number of pending outbound sessions. - pub fn with_max_pending_outbound(mut self, limit: u32) -> Self { + pub const fn with_max_pending_outbound(mut self, limit: u32) -> Self { self.max_pending_outbound = Some(limit); self } /// Sets the maximum number of active inbound sessions. - pub fn with_max_established_inbound(mut self, limit: u32) -> Self { + pub const fn with_max_established_inbound(mut self, limit: u32) -> Self { self.max_established_inbound = Some(limit); self } /// Sets the maximum number of active outbound sessions. - pub fn with_max_established_outbound(mut self, limit: u32) -> Self { + pub const fn with_max_established_outbound(mut self, limit: u32) -> Self { self.max_established_outbound = Some(limit); self } @@ -161,7 +161,7 @@ pub struct SessionCounter { // === impl SessionCounter === impl SessionCounter { - pub(crate) fn new(limits: SessionLimits) -> Self { + pub(crate) const fn new(limits: SessionLimits) -> Self { Self { limits, pending_inbound: 0, @@ -212,15 +212,15 @@ impl SessionCounter { } } - pub(crate) fn ensure_pending_outbound(&self) -> Result<(), ExceedsSessionLimit> { + pub(crate) const fn ensure_pending_outbound(&self) -> Result<(), ExceedsSessionLimit> { Self::ensure(self.pending_outbound, self.limits.max_pending_outbound) } - pub(crate) fn ensure_pending_inbound(&self) -> Result<(), ExceedsSessionLimit> { + pub(crate) const fn ensure_pending_inbound(&self) -> Result<(), ExceedsSessionLimit> { Self::ensure(self.pending_inbound, self.limits.max_pending_inbound) } - fn ensure(current: u32, limit: Option) -> Result<(), ExceedsSessionLimit> { + const fn ensure(current: u32, limit: Option) -> Result<(), ExceedsSessionLimit> { if let Some(limit) = limit { if current >= limit { return Err(ExceedsSessionLimit(limit)) diff --git a/crates/net/network/src/session/conn.rs b/crates/net/network/src/session/conn.rs index a94b3406e..6b8d522aa 100644 --- a/crates/net/network/src/session/conn.rs +++ b/crates/net/network/src/session/conn.rs @@ -38,7 +38,7 @@ pub enum EthRlpxConnection { impl EthRlpxConnection { /// Returns the negotiated ETH version. #[inline] - pub(crate) fn version(&self) -> EthVersion { + pub(crate) const fn version(&self) -> EthVersion { match self { Self::EthOnly(conn) => conn.version(), Self::Satellite(conn) => conn.primary().version(), @@ -65,7 +65,7 @@ impl EthRlpxConnection { /// Returns access to the underlying stream. #[inline] - pub(crate) fn inner(&self) -> &P2PStream>> { + pub(crate) const fn inner(&self) -> &P2PStream>> { match self { Self::EthOnly(conn) => conn.inner(), Self::Satellite(conn) => conn.inner(), @@ -142,14 +142,14 @@ impl Sink for EthRlpxConnection { mod tests { use super::*; - fn assert_eth_stream() + const fn assert_eth_stream() where St: Stream> + Sink, { } #[test] - fn test_eth_stream_variants() { + const fn test_eth_stream_variants() { assert_eth_stream::(); assert_eth_stream::(); } diff --git a/crates/net/network/src/session/handle.rs b/crates/net/network/src/session/handle.rs index c48fff618..0d8964550 100644 --- a/crates/net/network/src/session/handle.rs +++ b/crates/net/network/src/session/handle.rs @@ -42,7 +42,7 @@ impl PendingSessionHandle { } /// Returns the direction of the pending session (inbound or outbound). - pub fn direction(&self) -> Direction { + pub const fn direction(&self) -> Direction { self.direction } } @@ -96,27 +96,27 @@ impl ActiveSessionHandle { } /// Returns the direction of the active session (inbound or outbound). - pub fn direction(&self) -> Direction { + pub const fn direction(&self) -> Direction { self.direction } /// Returns the assigned session id for this session. - pub fn session_id(&self) -> SessionId { + pub const fn session_id(&self) -> SessionId { self.session_id } /// Returns the negotiated eth version for this session. - pub fn version(&self) -> EthVersion { + pub const fn version(&self) -> EthVersion { self.version } /// Returns the identifier of the remote peer. - pub fn remote_id(&self) -> PeerId { + pub const fn remote_id(&self) -> PeerId { self.remote_id } /// Returns the timestamp when the session has been established. - pub fn established(&self) -> Instant { + pub const fn established(&self) -> Instant { self.established } @@ -131,7 +131,7 @@ impl ActiveSessionHandle { } /// Returns the address we're connected to. - pub fn remote_addr(&self) -> SocketAddr { + pub const fn remote_addr(&self) -> SocketAddr { self.remote_addr } diff --git a/crates/net/network/src/session/mod.rs b/crates/net/network/src/session/mod.rs index 5cbbc0dfe..caf857807 100644 --- a/crates/net/network/src/session/mod.rs +++ b/crates/net/network/src/session/mod.rs @@ -172,12 +172,12 @@ impl SessionManager { } /// Returns the current status of the session. - pub fn status(&self) -> Status { + pub const fn status(&self) -> Status { self.status } /// Returns the secret key used for authenticating sessions. - pub fn secret_key(&self) -> SecretKey { + pub const fn secret_key(&self) -> SecretKey { self.secret_key } @@ -753,7 +753,7 @@ pub enum PendingSessionHandshakeError { impl PendingSessionHandshakeError { /// Returns the [`DisconnectReason`] if the error is a disconnect message - pub fn as_disconnected(&self) -> Option { + pub const fn as_disconnected(&self) -> Option { match self { Self::Eth(eth_err) => eth_err.as_disconnected(), _ => None, diff --git a/crates/net/network/src/state.rs b/crates/net/network/src/state.rs index e5b477152..23b75f19a 100644 --- a/crates/net/network/src/state.rs +++ b/crates/net/network/src/state.rs @@ -101,7 +101,7 @@ where } /// Returns access to the [`PeersManager`] - pub(crate) fn peers(&self) -> &PeersManager { + pub(crate) const fn peers(&self) -> &PeersManager { &self.peers_manager } diff --git a/crates/net/network/src/swarm.rs b/crates/net/network/src/swarm.rs index 729c5ff8a..9dff7705e 100644 --- a/crates/net/network/src/swarm.rs +++ b/crates/net/network/src/swarm.rs @@ -63,7 +63,7 @@ pub(crate) struct Swarm { impl Swarm { /// Configures a new swarm instance. - pub(crate) fn new( + pub(crate) const fn new( incoming: ConnectionListener, sessions: SessionManager, state: NetworkState, @@ -77,7 +77,7 @@ impl Swarm { } /// Access to the state. - pub(crate) fn state(&self) -> &NetworkState { + pub(crate) const fn state(&self) -> &NetworkState { &self.state } @@ -87,12 +87,12 @@ impl Swarm { } /// Access to the [`ConnectionListener`]. - pub(crate) fn listener(&self) -> &ConnectionListener { + pub(crate) const fn listener(&self) -> &ConnectionListener { &self.incoming } /// Access to the [`SessionManager`]. - pub(crate) fn sessions(&self) -> &SessionManager { + pub(crate) const fn sessions(&self) -> &SessionManager { &self.sessions } @@ -275,7 +275,7 @@ where /// Checks if the node's network connection state is 'ShuttingDown' #[inline] - pub(crate) fn is_shutting_down(&self) -> bool { + pub(crate) const fn is_shutting_down(&self) -> bool { self.state().peers().connection_state().is_shutting_down() } @@ -442,12 +442,12 @@ pub enum NetworkConnectionState { impl NetworkConnectionState { /// Returns true if the node is active. - pub(crate) fn is_active(&self) -> bool { + pub(crate) const fn is_active(&self) -> bool { matches!(self, Self::Active) } /// Returns true if the node is shutting down. - pub(crate) fn is_shutting_down(&self) -> bool { + pub(crate) const fn is_shutting_down(&self) -> bool { 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 8fd3ac9c7..4616acc6b 100644 --- a/crates/net/network/src/test_utils/testnet.rs +++ b/crates/net/network/src/test_utils/testnet.rs @@ -364,7 +364,7 @@ where } /// The address that listens for incoming connections. - pub fn local_addr(&self) -> SocketAddr { + pub const fn local_addr(&self) -> SocketAddr { self.network.local_addr() } @@ -384,7 +384,7 @@ where } /// Returns the [`TestPool`] of this peer. - pub fn pool(&self) -> Option<&Pool> { + pub const fn pool(&self) -> Option<&Pool> { self.pool.as_ref() } @@ -508,17 +508,17 @@ impl PeerHandle { } /// Returns the [`TransactionsHandle`] of this peer. - pub fn transactions(&self) -> Option<&TransactionsHandle> { + pub const fn transactions(&self) -> Option<&TransactionsHandle> { self.transactions.as_ref() } /// Returns the [`TestPool`] of this peer. - pub fn pool(&self) -> Option<&Pool> { + pub const fn pool(&self) -> Option<&Pool> { self.pool.as_ref() } /// Returns the [`NetworkHandle`] of this peer. - pub fn network(&self) -> &NetworkHandle { + pub const fn network(&self) -> &NetworkHandle { &self.network } } @@ -598,7 +598,7 @@ pub struct NetworkEventStream { impl NetworkEventStream { /// Create a new [`NetworkEventStream`] from the given network event receiver stream. - pub fn new(inner: EventStream) -> Self { + pub const fn new(inner: EventStream) -> Self { Self { inner } } diff --git a/crates/net/network/src/transactions/fetcher.rs b/crates/net/network/src/transactions/fetcher.rs index 91ae18442..363e3c046 100644 --- a/crates/net/network/src/transactions/fetcher.rs +++ b/crates/net/network/src/transactions/fetcher.rs @@ -883,7 +883,7 @@ impl TransactionFetcher { /// Returns the approx number of transactions that a [`GetPooledTransactions`] request will /// have capacity for w.r.t. the given version of the protocol. - pub fn approx_capacity_get_pooled_transactions_req( + pub const fn approx_capacity_get_pooled_transactions_req( &self, announcement_version: EthVersion, ) -> usize { @@ -1093,7 +1093,7 @@ impl TxFetchMetadata { /// [`Eth68`](reth_eth_wire::EthVersion::Eth68) announcement. If the transaction hash has only /// been seen in [`Eth66`](reth_eth_wire::EthVersion::Eth66) announcements so far, this will /// return `None`. - pub fn tx_encoded_len(&self) -> Option { + pub const fn tx_encoded_len(&self) -> Option { self.tx_encoded_length } } @@ -1303,7 +1303,7 @@ pub struct TransactionFetcherInfo { impl TransactionFetcherInfo { /// Creates a new max - pub fn new( + pub const fn new( max_inflight_requests: usize, soft_limit_byte_size_pooled_transactions_response_on_pack_request: usize, soft_limit_byte_size_pooled_transactions_response: usize, diff --git a/crates/net/network/src/transactions/mod.rs b/crates/net/network/src/transactions/mod.rs index 545c6f3bb..48e32c088 100644 --- a/crates/net/network/src/transactions/mod.rs +++ b/crates/net/network/src/transactions/mod.rs @@ -1485,7 +1485,7 @@ enum TransactionSource { impl TransactionSource { /// Whether the transaction were sent as broadcast. - fn is_broadcast(&self) -> bool { + const fn is_broadcast(&self) -> bool { matches!(self, Self::Broadcast) } } diff --git a/crates/net/network/tests/it/main.rs b/crates/net/network/tests/it/main.rs index 1b4494abd..c23f93e0e 100644 --- a/crates/net/network/tests/it/main.rs +++ b/crates/net/network/tests/it/main.rs @@ -6,4 +6,4 @@ mod session; mod startup; mod txgossip; -fn main() {} +const fn main() {} diff --git a/crates/net/network/tests/it/multiplex.rs b/crates/net/network/tests/it/multiplex.rs index 650b75423..14481f0ce 100644 --- a/crates/net/network/tests/it/multiplex.rs +++ b/crates/net/network/tests/it/multiplex.rs @@ -54,17 +54,17 @@ mod proto { impl PingPongProtoMessage { /// Returns the capability for the `ping` protocol. - pub fn capability() -> Capability { + pub const fn capability() -> Capability { Capability::new_static("ping", 1) } /// Returns the protocol for the `test` protocol. - pub fn protocol() -> Protocol { + pub const fn protocol() -> Protocol { Protocol::new(Self::capability(), 4) } /// Creates a ping message - pub fn ping() -> Self { + pub const fn ping() -> Self { Self { message_type: PingPongProtoMessageId::Ping, message: PingPongProtoMessageKind::Ping, @@ -72,7 +72,7 @@ mod proto { } /// Creates a pong message - pub fn pong() -> Self { + pub const fn pong() -> Self { Self { message_type: PingPongProtoMessageId::Pong, message: PingPongProtoMessageKind::Pong, diff --git a/crates/net/p2p/src/bodies/response.rs b/crates/net/p2p/src/bodies/response.rs index 741745a43..ec30b4c09 100644 --- a/crates/net/p2p/src/bodies/response.rs +++ b/crates/net/p2p/src/bodies/response.rs @@ -11,7 +11,7 @@ pub enum BlockResponse { impl BlockResponse { /// Return the reference to the response header - pub fn header(&self) -> &SealedHeader { + pub const fn header(&self) -> &SealedHeader { match self { Self::Full(block) => &block.header, Self::Empty(header) => header, diff --git a/crates/net/p2p/src/error.rs b/crates/net/p2p/src/error.rs index 450d8ce97..3a7c79a8d 100644 --- a/crates/net/p2p/src/error.rs +++ b/crates/net/p2p/src/error.rs @@ -104,12 +104,12 @@ pub enum RequestError { impl RequestError { /// Indicates whether this error is retryable or fatal. - pub fn is_retryable(&self) -> bool { + pub const fn is_retryable(&self) -> bool { matches!(self, Self::Timeout | Self::ConnectionDropped) } /// Whether the error happened because the channel was closed. - pub fn is_channel_closed(&self) -> bool { + pub const fn is_channel_closed(&self) -> bool { matches!(self, Self::ChannelClosed) } } diff --git a/crates/net/p2p/src/full_block.rs b/crates/net/p2p/src/full_block.rs index 54c4731ff..0c0140686 100644 --- a/crates/net/p2p/src/full_block.rs +++ b/crates/net/p2p/src/full_block.rs @@ -121,7 +121,7 @@ where Client: BodiesClient + HeadersClient, { /// Returns the hash of the block being requested. - pub fn hash(&self) -> &B256 { + pub const fn hash(&self) -> &B256 { &self.hash } @@ -524,17 +524,17 @@ where /// Returns whether or not a bodies request has been started, returning false if there is no /// pending request. - fn has_bodies_request_started(&self) -> bool { + const fn has_bodies_request_started(&self) -> bool { self.request.bodies.is_some() } /// Returns the start hash for the request - pub fn start_hash(&self) -> B256 { + pub const fn start_hash(&self) -> B256 { self.start_hash } /// Returns the block count for the request - pub fn count(&self) -> u64 { + pub const fn count(&self) -> u64 { self.count } } diff --git a/crates/net/p2p/src/priority.rs b/crates/net/p2p/src/priority.rs index 38be9ead4..bfa12f507 100644 --- a/crates/net/p2p/src/priority.rs +++ b/crates/net/p2p/src/priority.rs @@ -11,12 +11,12 @@ pub enum Priority { impl Priority { /// Returns `true` if this is [Priority::High] - pub fn is_high(&self) -> bool { + pub const fn is_high(&self) -> bool { matches!(self, Self::High) } /// Returns `true` if this is [Priority::Normal] - pub fn is_normal(&self) -> bool { + pub const fn is_normal(&self) -> bool { matches!(self, Self::Normal) } } diff --git a/crates/net/p2p/src/sync.rs b/crates/net/p2p/src/sync.rs index 5b3dd62e3..0242b797e 100644 --- a/crates/net/p2p/src/sync.rs +++ b/crates/net/p2p/src/sync.rs @@ -44,7 +44,7 @@ impl SyncState { /// Whether the node is currently syncing. /// /// Note: this does not include keep-up sync when the state is idle. - pub fn is_syncing(&self) -> bool { + pub const fn is_syncing(&self) -> bool { !matches!(self, Self::Idle) } } diff --git a/crates/net/types/src/lib.rs b/crates/net/types/src/lib.rs index dfcd4a5c2..b0d841235 100644 --- a/crates/net/types/src/lib.rs +++ b/crates/net/types/src/lib.rs @@ -150,17 +150,17 @@ impl From<(PeerId, T)> for WithPeerId { impl WithPeerId { /// Wraps the value with the peerid. - pub fn new(peer: PeerId, value: T) -> Self { + pub const fn new(peer: PeerId, value: T) -> Self { Self(peer, value) } /// Get the peer id - pub fn peer_id(&self) -> PeerId { + pub const fn peer_id(&self) -> PeerId { self.0 } /// Get the underlying data - pub fn data(&self) -> &T { + pub const fn data(&self) -> &T { &self.1 } diff --git a/crates/net/types/src/node_record.rs b/crates/net/types/src/node_record.rs index f16d43dd1..898d0312c 100644 --- a/crates/net/types/src/node_record.rs +++ b/crates/net/types/src/node_record.rs @@ -73,19 +73,19 @@ impl NodeRecord { /// Creates a new record from a socket addr and peer id. #[allow(dead_code)] - pub fn new(addr: SocketAddr, id: PeerId) -> Self { + pub const fn new(addr: SocketAddr, id: PeerId) -> Self { Self { address: addr.ip(), tcp_port: addr.port(), udp_port: addr.port(), id } } /// The TCP socket address of this node #[must_use] - pub fn tcp_addr(&self) -> SocketAddr { + pub const fn tcp_addr(&self) -> SocketAddr { SocketAddr::new(self.address, self.tcp_port) } /// The UDP socket address of this node #[must_use] - pub fn udp_addr(&self) -> SocketAddr { + pub const fn udp_addr(&self) -> SocketAddr { SocketAddr::new(self.address, self.udp_port) } } diff --git a/crates/node-core/src/args/network.rs b/crates/node-core/src/args/network.rs index 115ec8517..a9ec0350f 100644 --- a/crates/node-core/src/args/network.rs +++ b/crates/node-core/src/args/network.rs @@ -196,7 +196,7 @@ impl NetworkArgs { /// Sets the p2p port to zero, to allow the OS to assign a random unused port when /// the network components bind to a socket. - pub fn with_unused_p2p_port(mut self) -> Self { + pub const fn with_unused_p2p_port(mut self) -> Self { self.port = 0; self } @@ -324,7 +324,7 @@ impl DiscoveryArgs { /// Set the discovery port to zero, to allow the OS to assign a random unused port when /// discovery binds to the socket. - pub fn with_unused_discovery_port(mut self) -> Self { + pub const fn with_unused_discovery_port(mut self) -> Self { self.port = 0; self } diff --git a/crates/node-core/src/args/rpc_server.rs b/crates/node-core/src/args/rpc_server.rs index 9bf433b7a..4c0c4cd16 100644 --- a/crates/node-core/src/args/rpc_server.rs +++ b/crates/node-core/src/args/rpc_server.rs @@ -177,19 +177,19 @@ pub struct RpcServerArgs { impl RpcServerArgs { /// Enables the HTTP-RPC server. - pub fn with_http(mut self) -> Self { + pub const fn with_http(mut self) -> Self { self.http = true; self } /// Enables the WS-RPC server. - pub fn with_ws(mut self) -> Self { + pub const fn with_ws(mut self) -> Self { self.ws = true; self } /// Enables the Auth IPC - pub fn with_auth_ipc(mut self) -> Self { + pub const fn with_auth_ipc(mut self) -> Self { self.auth_ipc = true; self } @@ -225,21 +225,21 @@ impl RpcServerArgs { /// Set the http port to zero, to allow the OS to assign a random unused port when the rpc /// server binds to a socket. - pub fn with_http_unused_port(mut self) -> Self { + pub const fn with_http_unused_port(mut self) -> Self { self.http_port = 0; self } /// Set the ws port to zero, to allow the OS to assign a random unused port when the rpc /// server binds to a socket. - pub fn with_ws_unused_port(mut self) -> Self { + pub const fn with_ws_unused_port(mut self) -> Self { self.ws_port = 0; self } /// Set the auth port to zero, to allow the OS to assign a random unused port when the rpc /// server binds to a socket. - pub fn with_auth_unused_port(mut self) -> Self { + pub const fn with_auth_unused_port(mut self) -> Self { self.auth_port = 0; self } diff --git a/crates/node-core/src/dirs.rs b/crates/node-core/src/dirs.rs index 86f6a3fd5..22bfab0dd 100644 --- a/crates/node-core/src/dirs.rs +++ b/crates/node-core/src/dirs.rs @@ -194,7 +194,7 @@ impl MaybePlatformPath { } /// Returns true if a custom path is set - pub fn is_some(&self) -> bool { + pub const fn is_some(&self) -> bool { self.0.is_some() } @@ -265,7 +265,7 @@ pub struct ChainPath(PlatformPath, Chain); impl ChainPath { /// Returns a new `ChainPath` given a `PlatformPath` and a `Chain`. - pub fn new(path: PlatformPath, chain: Chain) -> Self { + pub const fn new(path: PlatformPath, chain: Chain) -> Self { Self(path, chain) } diff --git a/crates/node-core/src/engine/engine_store.rs b/crates/node-core/src/engine/engine_store.rs index d59651ce9..c8d6146e9 100644 --- a/crates/node-core/src/engine/engine_store.rs +++ b/crates/node-core/src/engine/engine_store.rs @@ -49,7 +49,7 @@ impl EngineMessageStore { /// Creates a new [EngineMessageStore] at the given path. /// /// The path is expected to be a directory, where individual message JSON files will be stored. - pub fn new(path: PathBuf) -> Self { + pub const fn new(path: PathBuf) -> Self { Self { path } } diff --git a/crates/node-core/src/engine/skip_fcu.rs b/crates/node-core/src/engine/skip_fcu.rs index 6deb34263..7a76e8009 100644 --- a/crates/node-core/src/engine/skip_fcu.rs +++ b/crates/node-core/src/engine/skip_fcu.rs @@ -22,7 +22,7 @@ pub struct EngineSkipFcu { impl EngineSkipFcu { /// Creates new [EngineSkipFcu] stream wrapper. - pub fn new(stream: S, threshold: usize) -> Self { + pub const fn new(stream: S, threshold: usize) -> Self { Self { stream, threshold, diff --git a/crates/node-core/src/engine/skip_new_payload.rs b/crates/node-core/src/engine/skip_new_payload.rs index fdcb4aeec..084b0b781 100644 --- a/crates/node-core/src/engine/skip_new_payload.rs +++ b/crates/node-core/src/engine/skip_new_payload.rs @@ -23,7 +23,7 @@ pub struct EngineSkipNewPayload { impl EngineSkipNewPayload { /// Creates new [EngineSkipNewPayload] stream wrapper. - pub fn new(stream: S, threshold: usize) -> Self { + pub const fn new(stream: S, threshold: usize) -> Self { Self { stream, threshold, skipped: 0 } } } diff --git a/crates/node-core/src/metrics/prometheus_exporter.rs b/crates/node-core/src/metrics/prometheus_exporter.rs index 42b291e87..837347441 100644 --- a/crates/node-core/src/metrics/prometheus_exporter.rs +++ b/crates/node-core/src/metrics/prometheus_exporter.rs @@ -279,10 +279,10 @@ fn describe_io_stats() { } #[cfg(not(target_os = "linux"))] -fn collect_io_stats() {} +const fn collect_io_stats() {} #[cfg(not(target_os = "linux"))] -fn describe_io_stats() {} +const fn describe_io_stats() {} #[cfg(test)] mod tests { diff --git a/crates/node-core/src/node_config.rs b/crates/node-core/src/node_config.rs index 02b3ee985..41dbb18ad 100644 --- a/crates/node-core/src/node_config.rs +++ b/crates/node-core/src/node_config.rs @@ -177,13 +177,13 @@ impl NodeConfig { } /// Set the metrics address for the node - pub fn with_metrics(mut self, metrics: SocketAddr) -> Self { + pub const fn with_metrics(mut self, metrics: SocketAddr) -> Self { self.metrics = Some(metrics); self } /// Set the instance for the node - pub fn with_instance(mut self, instance: u16) -> Self { + pub const fn with_instance(mut self, instance: u16) -> Self { self.instance = instance; self } @@ -219,19 +219,19 @@ impl NodeConfig { } /// Set the database args for the node - pub fn with_db(mut self, db: DatabaseArgs) -> Self { + pub const fn with_db(mut self, db: DatabaseArgs) -> Self { self.db = db; self } /// Set the dev args for the node - pub fn with_dev(mut self, dev: DevArgs) -> Self { + pub const fn with_dev(mut self, dev: DevArgs) -> Self { self.dev = dev; self } /// Set the pruning args for the node - pub fn with_pruning(mut self, pruning: PruningArgs) -> Self { + pub const fn with_pruning(mut self, pruning: PruningArgs) -> Self { self.pruning = pruning; self } diff --git a/crates/node/builder/src/builder/mod.rs b/crates/node/builder/src/builder/mod.rs index 3fd29085e..0e948dfd2 100644 --- a/crates/node/builder/src/builder/mod.rs +++ b/crates/node/builder/src/builder/mod.rs @@ -141,14 +141,14 @@ pub struct NodeBuilder { impl NodeBuilder<()> { /// Create a new [`NodeBuilder`]. - pub fn new(config: NodeConfig) -> Self { + pub const fn new(config: NodeConfig) -> Self { Self { config, database: () } } } impl NodeBuilder { /// Returns a reference to the node builder's config. - pub fn config(&self) -> &NodeConfig { + pub const fn config(&self) -> &NodeConfig { &self.config } @@ -160,7 +160,7 @@ impl NodeBuilder { /// Preconfigure the builder with the context to launch the node. /// /// This provides the task executor and the data directory for the node. - pub fn with_launch_context( + pub const fn with_launch_context( self, task_executor: TaskExecutor, data_dir: ChainPath, @@ -221,12 +221,12 @@ pub struct WithLaunchContext { impl WithLaunchContext { /// Returns a reference to the task executor. - pub fn task_executor(&self) -> &TaskExecutor { + pub const fn task_executor(&self) -> &TaskExecutor { &self.task_executor } /// Returns a reference to the data directory. - pub fn data_dir(&self) -> &ChainPath { + pub const fn data_dir(&self) -> &ChainPath { &self.data_dir } } @@ -236,7 +236,7 @@ where DB: Database + DatabaseMetrics + DatabaseMetadata + Clone + Unpin + 'static, { /// Returns a reference to the node builder's config. - pub fn config(&self) -> &NodeConfig { + pub const fn config(&self) -> &NodeConfig { self.builder.config() } @@ -411,7 +411,7 @@ where /// Check that the builder can be launched /// /// This is useful when writing tests to ensure that the builder is configured correctly. - pub fn check_launch(self) -> Self { + pub const fn check_launch(self) -> Self { self } } @@ -434,7 +434,7 @@ pub struct BuilderContext { impl BuilderContext { /// Create a new instance of [BuilderContext] - pub fn new( + pub const fn new( head: Head, provider: Node::Provider, executor: TaskExecutor, @@ -446,31 +446,31 @@ impl BuilderContext { } /// Returns the configured provider to interact with the blockchain. - pub fn provider(&self) -> &Node::Provider { + pub const fn provider(&self) -> &Node::Provider { &self.provider } /// Returns the current head of the blockchain at launch. - pub fn head(&self) -> Head { + pub const fn head(&self) -> Head { self.head } /// Returns the config of the node. - pub fn config(&self) -> &NodeConfig { + pub const fn config(&self) -> &NodeConfig { &self.config } /// Returns the data dir of the node. /// /// This gives access to all relevant files and directories of the node's datadir. - pub fn data_dir(&self) -> &ChainPath { + pub const fn data_dir(&self) -> &ChainPath { &self.data_dir } /// Returns the executor of the node. /// /// This can be used to execute async tasks or functions during the setup. - pub fn task_executor(&self) -> &TaskExecutor { + pub const fn task_executor(&self) -> &TaskExecutor { &self.executor } diff --git a/crates/node/builder/src/builder/states.rs b/crates/node/builder/src/builder/states.rs index 103e4f174..fee2ab493 100644 --- a/crates/node/builder/src/builder/states.rs +++ b/crates/node/builder/src/builder/states.rs @@ -63,7 +63,7 @@ pub(crate) struct NodeTypesAdapter { impl NodeTypesAdapter { /// Create a new adapter from the given node types. - pub(crate) fn new(database: T::DB) -> Self { + pub(crate) const fn new(database: T::DB) -> Self { Self { database } } } @@ -223,7 +223,7 @@ impl> NodeBuilderWithComponents Self { + pub const fn check_launch(self) -> Self { self } } diff --git a/crates/node/builder/src/launch/common.rs b/crates/node/builder/src/launch/common.rs index 36cf47990..0f16369fd 100644 --- a/crates/node/builder/src/launch/common.rs +++ b/crates/node/builder/src/launch/common.rs @@ -40,7 +40,7 @@ impl LaunchContext { } /// Attaches a database to the launch context. - pub fn with(self, database: DB) -> LaunchContextWith { + pub const fn with(self, database: DB) -> LaunchContextWith { LaunchContextWith { inner: self, attachment: database } } @@ -156,12 +156,12 @@ impl LaunchContextWith { } /// Returns the data directory. - pub fn data_dir(&self) -> &ChainPath { + pub const fn data_dir(&self) -> &ChainPath { &self.inner.data_dir } /// Returns the task executor. - pub fn task_executor(&self) -> &TaskExecutor { + pub const fn task_executor(&self) -> &TaskExecutor { &self.inner.task_executor } @@ -267,7 +267,7 @@ impl LaunchContextWith> { } /// Returns true if the node is configured as --dev - pub fn is_dev(&self) -> bool { + pub const fn is_dev(&self) -> bool { self.node_config().dev.dev } @@ -357,7 +357,7 @@ where } /// Returns the configured ProviderFactory. - pub fn provider_factory(&self) -> &ProviderFactory { + pub const fn provider_factory(&self) -> &ProviderFactory { self.right() } diff --git a/crates/node/builder/src/launch/mod.rs b/crates/node/builder/src/launch/mod.rs index fec043c7f..2df6e7824 100644 --- a/crates/node/builder/src/launch/mod.rs +++ b/crates/node/builder/src/launch/mod.rs @@ -66,7 +66,7 @@ pub struct DefaultNodeLauncher { impl DefaultNodeLauncher { /// Create a new instance of the default node launcher. - pub fn new(task_executor: TaskExecutor, data_dir: ChainPath) -> Self { + pub const fn new(task_executor: TaskExecutor, data_dir: ChainPath) -> Self { Self { ctx: LaunchContext::new(task_executor, data_dir) } } } diff --git a/crates/node/builder/src/node.rs b/crates/node/builder/src/node.rs index 7831f29d0..9946f890c 100644 --- a/crates/node/builder/src/node.rs +++ b/crates/node/builder/src/node.rs @@ -64,12 +64,12 @@ impl FullNode { } /// Returns the [RpcServerHandle] to the started rpc server. - pub fn rpc_server_handle(&self) -> &RpcServerHandle { + pub const fn rpc_server_handle(&self) -> &RpcServerHandle { &self.rpc_server_handles.rpc } /// Returns the [AuthServerHandle] to the started authenticated engine API server. - pub fn auth_server_handle(&self) -> &AuthServerHandle { + pub const fn auth_server_handle(&self) -> &AuthServerHandle { &self.rpc_server_handles.auth } diff --git a/crates/node/builder/src/rpc.rs b/crates/node/builder/src/rpc.rs index 795d02dfd..81afe9bb1 100644 --- a/crates/node/builder/src/rpc.rs +++ b/crates/node/builder/src/rpc.rs @@ -220,12 +220,12 @@ pub struct RpcContext<'a, Node: FullNodeComponents> { impl<'a, Node: FullNodeComponents> RpcContext<'a, Node> { /// Returns the config of the node. - pub fn config(&self) -> &NodeConfig { + pub const fn config(&self) -> &NodeConfig { self.config } /// Returns a reference to the configured node. - pub fn node(&self) -> &Node { + pub const fn node(&self) -> &Node { &self.node } diff --git a/crates/node/events/src/node.rs b/crates/node/events/src/node.rs index 87da96a31..00d3517fc 100644 --- a/crates/node/events/src/node.rs +++ b/crates/node/events/src/node.rs @@ -56,7 +56,11 @@ struct NodeState { } impl NodeState { - fn new(db: DB, network: Option, latest_block: Option) -> Self { + const fn new( + db: DB, + network: Option, + latest_block: Option, + ) -> Self { Self { db, network, diff --git a/crates/optimism/evm/src/execute.rs b/crates/optimism/evm/src/execute.rs index aa99b018c..5ff5e3f43 100644 --- a/crates/optimism/evm/src/execute.rs +++ b/crates/optimism/evm/src/execute.rs @@ -378,7 +378,7 @@ pub struct OpBatchExecutor { impl OpBatchExecutor { /// Returns the receipts of the executed blocks. - pub fn receipts(&self) -> &Receipts { + pub const fn receipts(&self) -> &Receipts { self.batch_record.receipts() } diff --git a/crates/optimism/node/tests/e2e/main.rs b/crates/optimism/node/tests/e2e/main.rs index 221f8483d..5e0d022d2 100644 --- a/crates/optimism/node/tests/e2e/main.rs +++ b/crates/optimism/node/tests/e2e/main.rs @@ -4,4 +4,4 @@ mod p2p; #[cfg(feature = "optimism")] mod utils; -fn main() {} +const fn main() {} diff --git a/crates/optimism/node/tests/it/main.rs b/crates/optimism/node/tests/it/main.rs index 1aea2c212..573a94435 100644 --- a/crates/optimism/node/tests/it/main.rs +++ b/crates/optimism/node/tests/it/main.rs @@ -1,4 +1,4 @@ #[cfg(feature = "optimism")] mod builder; -fn main() {} +const fn main() {} diff --git a/crates/optimism/payload/src/builder.rs b/crates/optimism/payload/src/builder.rs index a6f3d83c4..6ad1203f8 100644 --- a/crates/optimism/payload/src/builder.rs +++ b/crates/optimism/payload/src/builder.rs @@ -45,18 +45,18 @@ impl OptimismPayloadBuilder { } /// Sets the rollup's compute pending block configuration option. - pub fn set_compute_pending_block(mut self, compute_pending_block: bool) -> Self { + pub const fn set_compute_pending_block(mut self, compute_pending_block: bool) -> Self { self.compute_pending_block = compute_pending_block; self } /// Enables the rollup's compute pending block configuration option. - pub fn compute_pending_block(self) -> Self { + pub const fn compute_pending_block(self) -> Self { self.set_compute_pending_block(true) } /// Returns the rollup's compute pending block configuration option. - pub fn is_compute_pending_block(&self) -> bool { + pub const fn is_compute_pending_block(&self) -> bool { self.compute_pending_block } diff --git a/crates/optimism/payload/src/payload.rs b/crates/optimism/payload/src/payload.rs index 0314bcc84..706b1c2bf 100644 --- a/crates/optimism/payload/src/payload.rs +++ b/crates/optimism/payload/src/payload.rs @@ -187,17 +187,17 @@ impl OptimismBuiltPayload { } /// Returns the identifier of the payload. - pub fn id(&self) -> PayloadId { + pub const fn id(&self) -> PayloadId { self.id } /// Returns the built block(sealed) - pub fn block(&self) -> &SealedBlock { + pub const fn block(&self) -> &SealedBlock { &self.block } /// Fees of the block - pub fn fees(&self) -> U256 { + pub const fn fees(&self) -> U256 { self.fees } diff --git a/crates/payload/basic/src/lib.rs b/crates/payload/basic/src/lib.rs index 71945b83a..759f59929 100644 --- a/crates/payload/basic/src/lib.rs +++ b/crates/payload/basic/src/lib.rs @@ -120,7 +120,7 @@ impl BasicPayloadJobGenerator &Tasks { + pub const fn tasks(&self) -> &Tasks { &self.executor } @@ -264,13 +264,13 @@ pub struct BasicPayloadJobGeneratorConfig { impl BasicPayloadJobGeneratorConfig { /// Sets the interval at which the job should build a new payload after the last. - pub fn interval(mut self, interval: Duration) -> Self { + pub const fn interval(mut self, interval: Duration) -> Self { self.interval = interval; self } /// Sets the deadline when this job should resolve. - pub fn deadline(mut self, deadline: Duration) -> Self { + pub const fn deadline(mut self, deadline: Duration) -> Self { self.deadline = deadline; self } @@ -799,7 +799,7 @@ pub struct WithdrawalsOutcome { impl WithdrawalsOutcome { /// No withdrawals pre shanghai - pub fn pre_shanghai() -> Self { + pub const fn pre_shanghai() -> Self { Self { withdrawals: None, withdrawals_root: None } } diff --git a/crates/payload/builder/src/service.rs b/crates/payload/builder/src/service.rs index 5228083ab..ec34849dd 100644 --- a/crates/payload/builder/src/service.rs +++ b/crates/payload/builder/src/service.rs @@ -110,7 +110,7 @@ where /// /// Note: this is only used internally by the [PayloadBuilderService] to manage the payload /// building flow See [PayloadBuilderService::poll] for implementation details. - pub fn new(to_service: mpsc::UnboundedSender>) -> Self { + pub const fn new(to_service: mpsc::UnboundedSender>) -> Self { Self { to_service } } diff --git a/crates/primitives/src/account.rs b/crates/primitives/src/account.rs index 1bc691ec1..786871948 100644 --- a/crates/primitives/src/account.rs +++ b/crates/primitives/src/account.rs @@ -24,7 +24,7 @@ pub struct Account { impl Account { /// Whether the account has bytecode. - pub fn has_bytecode(&self) -> bool { + pub const fn has_bytecode(&self) -> bool { self.bytecode_hash.is_some() } diff --git a/crates/primitives/src/chain/spec.rs b/crates/primitives/src/chain/spec.rs index e90b314e4..5c56fbecd 100644 --- a/crates/primitives/src/chain/spec.rs +++ b/crates/primitives/src/chain/spec.rs @@ -549,13 +549,13 @@ impl Default for ChainSpec { impl ChainSpec { /// Get information about the chain itself - pub fn chain(&self) -> Chain { + pub const fn chain(&self) -> Chain { self.chain } /// Returns `true` if this chain contains Ethereum configuration. #[inline] - pub fn is_eth(&self) -> bool { + pub const fn is_eth(&self) -> bool { matches!( self.chain.kind(), ChainKind::Named( @@ -573,7 +573,7 @@ impl ChainSpec { /// Returns `true` if this chain contains Optimism configuration. #[inline] - pub fn is_optimism(&self) -> bool { + pub const fn is_optimism(&self) -> bool { self.chain.is_optimism() } @@ -586,7 +586,7 @@ impl ChainSpec { /// Get the genesis block specification. /// /// To get the header for the genesis block, use [`Self::genesis_header`] instead. - pub fn genesis(&self) -> &Genesis { + pub const fn genesis(&self) -> &Genesis { &self.genesis } @@ -706,7 +706,7 @@ impl ChainSpec { } /// Get the timestamp of the genesis block. - pub fn genesis_timestamp(&self) -> u64 { + pub const fn genesis_timestamp(&self) -> u64 { self.genesis.timestamp } @@ -735,7 +735,7 @@ impl ChainSpec { } /// Returns the forks in this specification and their activation conditions. - pub fn hardforks(&self) -> &BTreeMap { + pub const fn hardforks(&self) -> &BTreeMap { &self.hardforks } @@ -1121,7 +1121,7 @@ impl ChainSpecBuilder { } /// Set the chain ID - pub fn chain(mut self, chain: Chain) -> Self { + pub const fn chain(mut self, chain: Chain) -> Self { self.chain = Some(chain); self } @@ -1346,7 +1346,7 @@ pub enum ForkCondition { impl ForkCondition { /// Returns true if the fork condition is timestamp based. - pub fn is_timestamp(&self) -> bool { + pub const fn is_timestamp(&self) -> bool { matches!(self, Self::Timestamp(_)) } @@ -1355,7 +1355,7 @@ impl ForkCondition { /// For TTD conditions, this will only return true if the activation block is already known. /// /// For timestamp conditions, this will always return false. - pub fn active_at_block(&self, current_block: BlockNumber) -> bool { + pub const fn active_at_block(&self, current_block: BlockNumber) -> bool { matches!(self, Self::Block(block) | Self::TTD { fork_block: Some(block), .. } if current_block >= *block) } @@ -1363,7 +1363,7 @@ impl ForkCondition { /// 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 { + pub const fn transitions_at_block(&self, current_block: BlockNumber) -> bool { matches!(self, Self::Block(block) if current_block == *block) } @@ -1384,7 +1384,7 @@ impl ForkCondition { /// Checks whether the fork condition is satisfied at the given timestamp. /// /// This will return false for any condition that is not timestamp-based. - pub fn active_at_timestamp(&self, timestamp: u64) -> bool { + pub const fn active_at_timestamp(&self, timestamp: u64) -> bool { matches!(self, Self::Timestamp(time) if timestamp >= *time) } @@ -1404,7 +1404,7 @@ impl ForkCondition { /// Get the total terminal difficulty for this fork condition. /// /// Returns `None` for fork conditions that are not TTD based. - pub fn ttd(&self) -> Option { + pub const fn ttd(&self) -> Option { match self { Self::TTD { total_difficulty, .. } => Some(*total_difficulty), _ => None, @@ -1412,7 +1412,7 @@ impl ForkCondition { } /// Returns the timestamp of the fork condition, if it is timestamp based. - pub fn as_timestamp(&self) -> Option { + pub const fn as_timestamp(&self) -> Option { match self { Self::Timestamp(timestamp) => Some(*timestamp), _ => None, @@ -1601,7 +1601,7 @@ pub struct DepositContract { } impl DepositContract { - fn new(address: Address, block: BlockNumber, topic: B256) -> Self { + const fn new(address: Address, block: BlockNumber, topic: B256) -> Self { Self { address, block, topic } } } diff --git a/crates/primitives/src/error.rs b/crates/primitives/src/error.rs index a6291cbbc..42257cc7b 100644 --- a/crates/primitives/src/error.rs +++ b/crates/primitives/src/error.rs @@ -30,7 +30,7 @@ impl From<(T, T)> for GotExpected { impl GotExpected { /// Creates a new error from a pair of values. #[inline] - pub fn new(got: T, expected: T) -> Self { + pub const fn new(got: T, expected: T) -> Self { Self { got, expected } } } diff --git a/crates/primitives/src/header.rs b/crates/primitives/src/header.rs index 7f48921fb..7ec106c3b 100644 --- a/crates/primitives/src/header.rs +++ b/crates/primitives/src/header.rs @@ -192,7 +192,7 @@ impl Header { /// Checks if the block's timestamp is in the past compared to the parent block's timestamp. /// /// Note: This check is relevant only pre-merge. - pub fn is_timestamp_in_past(&self, parent_timestamp: u64) -> bool { + pub const fn is_timestamp_in_past(&self, parent_timestamp: u64) -> bool { self.timestamp <= parent_timestamp } @@ -201,12 +201,12 @@ impl Header { /// Clock can drift but this can be consensus issue. /// /// Note: This check is relevant only pre-merge. - pub fn exceeds_allowed_future_timestamp(&self, present_timestamp: u64) -> bool { + pub const fn exceeds_allowed_future_timestamp(&self, present_timestamp: u64) -> bool { self.timestamp > present_timestamp + ALLOWED_FUTURE_BLOCK_TIME_SECONDS } /// Returns the parent block's number and hash - pub fn parent_num_hash(&self) -> BlockNumHash { + pub const fn parent_num_hash(&self) -> BlockNumHash { BlockNumHash { number: self.number.saturating_sub(1), hash: self.parent_hash } } @@ -272,7 +272,7 @@ impl Header { /// /// WARNING: This method does not perform validation whether the hash is correct. #[inline] - pub fn seal(self, hash: B256) -> SealedHeader { + pub const fn seal(self, hash: B256) -> SealedHeader { SealedHeader { header: self, hash } } @@ -618,7 +618,7 @@ impl SealedHeader { /// Returns the sealed Header fields. #[inline] - pub fn header(&self) -> &Header { + pub const fn header(&self) -> &Header { &self.header } @@ -970,12 +970,12 @@ pub enum HeadersDirection { impl HeadersDirection { /// Returns true for rising block numbers - pub fn is_rising(&self) -> bool { + pub const fn is_rising(&self) -> bool { matches!(self, Self::Rising) } /// Returns true for falling block numbers - pub fn is_falling(&self) -> bool { + pub const fn is_falling(&self) -> bool { matches!(self, Self::Falling) } @@ -985,7 +985,7 @@ impl HeadersDirection { /// /// [`HeadersDirection::Rising`] block numbers for `reverse == 0 == false` /// [`HeadersDirection::Falling`] block numbers for `reverse == 1 == true` - pub fn new(reverse: bool) -> Self { + pub const fn new(reverse: bool) -> Self { if reverse { Self::Falling } else { diff --git a/crates/primitives/src/prune/limiter.rs b/crates/primitives/src/prune/limiter.rs index 94adc1563..5927655ac 100644 --- a/crates/primitives/src/prune/limiter.rs +++ b/crates/primitives/src/prune/limiter.rs @@ -22,11 +22,11 @@ struct PruneDeletedEntriesLimit { } impl PruneDeletedEntriesLimit { - fn new(limit: usize) -> Self { + const fn new(limit: usize) -> Self { Self { limit, deleted: 0 } } - fn is_limit_reached(&self) -> bool { + const fn is_limit_reached(&self) -> bool { self.deleted >= self.limit } } diff --git a/crates/primitives/src/prune/mode.rs b/crates/primitives/src/prune/mode.rs index 46d38aa71..3911246dc 100644 --- a/crates/primitives/src/prune/mode.rs +++ b/crates/primitives/src/prune/mode.rs @@ -18,7 +18,7 @@ impl PruneMode { /// Prune blocks up to the specified block number. The specified block number is also pruned. /// /// This acts as `PruneMode::Before(block_number + 1)`. - pub fn before_inclusive(block_number: BlockNumber) -> Self { + pub const fn before_inclusive(block_number: BlockNumber) -> Self { Self::Before(block_number + 1) } @@ -45,7 +45,7 @@ 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 { + pub const fn should_prune(&self, block: BlockNumber, tip: BlockNumber) -> bool { match self { Self::Full => true, Self::Distance(distance) => { @@ -59,7 +59,7 @@ impl PruneMode { } /// Returns true if the prune mode is [`PruneMode::Full`]. - pub fn is_full(&self) -> bool { + pub const fn is_full(&self) -> bool { matches!(self, Self::Full) } } diff --git a/crates/primitives/src/prune/segment.rs b/crates/primitives/src/prune/segment.rs index d88cd0bef..23b867ee8 100644 --- a/crates/primitives/src/prune/segment.rs +++ b/crates/primitives/src/prune/segment.rs @@ -28,7 +28,7 @@ pub enum PruneSegment { impl PruneSegment { /// Returns minimum number of blocks to left in the database for this segment. - pub fn min_blocks(&self, purpose: PrunePurpose) -> u64 { + pub const fn min_blocks(&self, purpose: PrunePurpose) -> u64 { match self { Self::SenderRecovery | Self::TransactionLookup | Self::Headers | Self::Transactions => { 0 @@ -53,12 +53,12 @@ pub enum PrunePurpose { impl PrunePurpose { /// Returns true if the purpose is [`PrunePurpose::User`]. - pub fn is_user(self) -> bool { + pub const fn is_user(self) -> bool { matches!(self, Self::User) } /// Returns true if the purpose is [`PrunePurpose::StaticFile`]. - pub fn is_static_file(self) -> bool { + pub const fn is_static_file(self) -> bool { matches!(self, Self::StaticFile) } } diff --git a/crates/primitives/src/receipt.rs b/crates/primitives/src/receipt.rs index 1e9a2ac1f..a01e8542c 100644 --- a/crates/primitives/src/receipt.rs +++ b/crates/primitives/src/receipt.rs @@ -73,7 +73,7 @@ pub struct Receipts { impl Receipts { /// Create a new `Receipts` instance with an empty vector. - pub fn new() -> Self { + pub const fn new() -> Self { Self { receipt_vec: vec![] } } @@ -173,7 +173,7 @@ pub struct ReceiptWithBloom { impl ReceiptWithBloom { /// Create new [ReceiptWithBloom] - pub fn new(receipt: Receipt, bloom: Bloom) -> Self { + pub const fn new(receipt: Receipt, bloom: Bloom) -> Self { Self { receipt, bloom } } @@ -188,7 +188,7 @@ impl ReceiptWithBloom { } #[inline] - fn as_encoder(&self) -> ReceiptWithBloomEncoder<'_> { + const fn as_encoder(&self) -> ReceiptWithBloomEncoder<'_> { ReceiptWithBloomEncoder { receipt: &self.receipt, bloom: &self.bloom } } } @@ -430,7 +430,7 @@ pub struct ReceiptWithBloomRef<'a> { impl<'a> ReceiptWithBloomRef<'a> { /// Create new [ReceiptWithBloomRef] - pub fn new(receipt: &'a Receipt, bloom: Bloom) -> Self { + pub const fn new(receipt: &'a Receipt, bloom: Bloom) -> Self { Self { receipt, bloom } } @@ -440,7 +440,7 @@ impl<'a> ReceiptWithBloomRef<'a> { } #[inline] - fn as_encoder(&self) -> ReceiptWithBloomEncoder<'_> { + const fn as_encoder(&self) -> ReceiptWithBloomEncoder<'_> { ReceiptWithBloomEncoder { receipt: self.receipt, bloom: &self.bloom } } } diff --git a/crates/primitives/src/stage/checkpoints.rs b/crates/primitives/src/stage/checkpoints.rs index a82a77dee..d8e54a353 100644 --- a/crates/primitives/src/stage/checkpoints.rs +++ b/crates/primitives/src/stage/checkpoints.rs @@ -198,7 +198,7 @@ impl StageCheckpoint { } /// Sets the block number. - pub fn with_block_number(mut self, block_number: BlockNumber) -> Self { + pub const fn with_block_number(mut self, block_number: BlockNumber) -> Self { self.block_number = block_number; self } @@ -297,7 +297,7 @@ macro_rules! stage_unit_checkpoints { impl StageCheckpoint { $( #[doc = $fn_get_doc] - pub fn $fn_get_name(&self) -> Option<$checkpoint_ty> { +pub const fn $fn_get_name(&self) -> Option<$checkpoint_ty> { match self.stage_checkpoint { Some(StageUnitCheckpoint::$enum_variant(checkpoint)) => Some(checkpoint), _ => None, @@ -305,7 +305,7 @@ macro_rules! stage_unit_checkpoints { } #[doc = $fn_build_doc] - pub fn $fn_build_name( +pub const fn $fn_build_name( mut self, checkpoint: $checkpoint_ty, ) -> Self { diff --git a/crates/primitives/src/stage/id.rs b/crates/primitives/src/stage/id.rs index f6b8508e0..11ceb41e3 100644 --- a/crates/primitives/src/stage/id.rs +++ b/crates/primitives/src/stage/id.rs @@ -65,7 +65,7 @@ impl StageId { ]; /// Return stage id formatted as string. - pub fn as_str(&self) -> &str { + pub const fn as_str(&self) -> &str { match self { #[allow(deprecated)] Self::StaticFile => "StaticFile", @@ -86,17 +86,17 @@ impl StageId { } /// Returns true if it's a downloading stage [StageId::Headers] or [StageId::Bodies] - pub fn is_downloading_stage(&self) -> bool { + pub const fn is_downloading_stage(&self) -> bool { matches!(self, Self::Headers | Self::Bodies) } /// Returns `true` if it's [TransactionLookup](StageId::TransactionLookup) stage. - pub fn is_tx_lookup(&self) -> bool { + pub const fn is_tx_lookup(&self) -> bool { matches!(self, Self::TransactionLookup) } /// Returns true indicating if it's the finish stage [StageId::Finish] - pub fn is_finish(&self) -> bool { + pub const fn is_finish(&self) -> bool { matches!(self, Self::Finish) } } diff --git a/crates/primitives/src/stage/mod.rs b/crates/primitives/src/stage/mod.rs index 9976cf575..74f84409b 100644 --- a/crates/primitives/src/stage/mod.rs +++ b/crates/primitives/src/stage/mod.rs @@ -27,7 +27,7 @@ impl PipelineTarget { /// /// - `Some(BlockHash)`: The target block hash for forward synchronization. /// - `None`: If the target is for backward unwinding. - pub fn sync_target(self) -> Option { + pub const fn sync_target(self) -> Option { match self { Self::Sync(hash) => Some(hash), Self::Unwind(_) => None, @@ -40,7 +40,7 @@ impl PipelineTarget { /// /// - `Some(BlockNumber)`: The target block number for backward unwinding. /// - `None`: If the target is for forward synchronization. - pub fn unwind_target(self) -> Option { + pub const fn unwind_target(self) -> Option { match self { Self::Sync(_) => None, Self::Unwind(number) => Some(number), diff --git a/crates/primitives/src/storage.rs b/crates/primitives/src/storage.rs index 2e03424d2..d9f6a15d2 100644 --- a/crates/primitives/src/storage.rs +++ b/crates/primitives/src/storage.rs @@ -16,7 +16,7 @@ pub struct StorageEntry { impl StorageEntry { /// Create a new StorageEntry with given key and value. - pub fn new(key: B256, value: U256) -> Self { + pub const fn new(key: B256, value: U256) -> Self { Self { key, value } } } diff --git a/crates/primitives/src/transaction/eip1559.rs b/crates/primitives/src/transaction/eip1559.rs index 5da0cd881..ef6f9eb72 100644 --- a/crates/primitives/src/transaction/eip1559.rs +++ b/crates/primitives/src/transaction/eip1559.rs @@ -63,7 +63,7 @@ pub struct TxEip1559 { impl TxEip1559 { /// Returns the effective gas price for the given `base_fee`. - pub fn effective_gas_price(&self, base_fee: Option) -> u128 { + pub const fn effective_gas_price(&self, base_fee: Option) -> u128 { match base_fee { None => self.max_fee_per_gas, Some(base_fee) => { @@ -175,7 +175,7 @@ impl TxEip1559 { } /// Get transaction type - pub(crate) fn tx_type(&self) -> TxType { + pub(crate) const fn tx_type(&self) -> TxType { TxType::Eip1559 } diff --git a/crates/primitives/src/transaction/eip2930.rs b/crates/primitives/src/transaction/eip2930.rs index 0604a7888..672bb86b5 100644 --- a/crates/primitives/src/transaction/eip2930.rs +++ b/crates/primitives/src/transaction/eip2930.rs @@ -153,7 +153,7 @@ impl TxEip2930 { } /// Get transaction type - pub(crate) fn tx_type(&self) -> TxType { + pub(crate) const fn tx_type(&self) -> TxType { TxType::Eip2930 } diff --git a/crates/primitives/src/transaction/eip4844.rs b/crates/primitives/src/transaction/eip4844.rs index 885e457b8..d91490eb4 100644 --- a/crates/primitives/src/transaction/eip4844.rs +++ b/crates/primitives/src/transaction/eip4844.rs @@ -82,7 +82,7 @@ pub struct TxEip4844 { impl TxEip4844 { /// Returns the effective gas price for the given `base_fee`. - pub fn effective_gas_price(&self, base_fee: Option) -> u128 { + pub const fn effective_gas_price(&self, base_fee: Option) -> u128 { match base_fee { None => self.max_fee_per_gas, Some(base_fee) => { @@ -244,7 +244,7 @@ impl TxEip4844 { } /// Get transaction type - pub(crate) fn tx_type(&self) -> TxType { + pub(crate) const fn tx_type(&self) -> TxType { TxType::Eip4844 } diff --git a/crates/primitives/src/transaction/legacy.rs b/crates/primitives/src/transaction/legacy.rs index 448662a24..42e1e4b45 100644 --- a/crates/primitives/src/transaction/legacy.rs +++ b/crates/primitives/src/transaction/legacy.rs @@ -102,7 +102,7 @@ impl TxLegacy { } /// Get transaction type - pub(crate) fn tx_type(&self) -> TxType { + pub(crate) const fn tx_type(&self) -> TxType { TxType::Legacy } diff --git a/crates/primitives/src/transaction/mod.rs b/crates/primitives/src/transaction/mod.rs index 68c87a034..bb6fdad17 100644 --- a/crates/primitives/src/transaction/mod.rs +++ b/crates/primitives/src/transaction/mod.rs @@ -151,7 +151,7 @@ impl Transaction { } /// Get chain_id. - pub fn chain_id(&self) -> Option { + pub const fn chain_id(&self) -> Option { match self { Self::Legacy(TxLegacy { chain_id, .. }) => *chain_id, Self::Eip2930(TxEip2930 { chain_id, .. }) | @@ -176,7 +176,7 @@ impl Transaction { /// Gets the transaction's [`TxKind`], which is the address of the recipient or /// [`TxKind::Create`] if the transaction is a contract creation. - pub fn kind(&self) -> TxKind { + pub const fn kind(&self) -> TxKind { match self { Self::Legacy(TxLegacy { to, .. }) | Self::Eip2930(TxEip2930 { to, .. }) | @@ -196,7 +196,7 @@ impl Transaction { } /// Get the transaction's type - pub fn tx_type(&self) -> TxType { + pub const fn tx_type(&self) -> TxType { match self { Self::Legacy(legacy_tx) => legacy_tx.tx_type(), Self::Eip2930(access_list_tx) => access_list_tx.tx_type(), @@ -208,7 +208,7 @@ impl Transaction { } /// Gets the transaction's value field. - pub fn value(&self) -> U256 { + pub const fn value(&self) -> U256 { *match self { Self::Legacy(TxLegacy { value, .. }) | Self::Eip2930(TxEip2930 { value, .. }) | @@ -220,7 +220,7 @@ impl Transaction { } /// Get the transaction's nonce. - pub fn nonce(&self) -> u64 { + pub const fn nonce(&self) -> u64 { match self { Self::Legacy(TxLegacy { nonce, .. }) | Self::Eip2930(TxEip2930 { nonce, .. }) | @@ -235,7 +235,7 @@ impl Transaction { /// Returns the [AccessList] of the transaction. /// /// Returns `None` for legacy transactions. - pub fn access_list(&self) -> Option<&AccessList> { + pub const fn access_list(&self) -> Option<&AccessList> { match self { Self::Legacy(_) => None, Self::Eip2930(tx) => Some(&tx.access_list), @@ -247,7 +247,7 @@ impl Transaction { } /// Get the gas limit of the transaction. - pub fn gas_limit(&self) -> u64 { + pub const fn gas_limit(&self) -> u64 { match self { Self::Legacy(TxLegacy { gas_limit, .. }) | Self::Eip2930(TxEip2930 { gas_limit, .. }) | @@ -259,7 +259,7 @@ impl Transaction { } /// Returns true if the tx supports dynamic fees - pub fn is_dynamic_fee(&self) -> bool { + pub const fn is_dynamic_fee(&self) -> bool { match self { Self::Legacy(_) | Self::Eip2930(_) => false, Self::Eip1559(_) | Self::Eip4844(_) => true, @@ -271,7 +271,7 @@ impl Transaction { /// Max fee per gas for eip1559 transaction, for legacy transactions this is gas_price. /// /// This is also commonly referred to as the "Gas Fee Cap" (`GasFeeCap`). - pub fn max_fee_per_gas(&self) -> u128 { + pub const fn max_fee_per_gas(&self) -> u128 { match self { Self::Legacy(TxLegacy { gas_price, .. }) | Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, @@ -288,7 +288,7 @@ impl Transaction { /// is `None` /// /// This is also commonly referred to as the "Gas Tip Cap" (`GasTipCap`). - pub fn max_priority_fee_per_gas(&self) -> Option { + pub const fn max_priority_fee_per_gas(&self) -> Option { match self { Self::Legacy(_) | Self::Eip2930(_) => None, Self::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) | @@ -320,7 +320,7 @@ impl Transaction { /// Returns `None` for non-eip4844 transactions. /// /// This is also commonly referred to as the "Blob Gas Fee Cap" (`BlobGasFeeCap`). - pub fn max_fee_per_blob_gas(&self) -> Option { + pub const fn max_fee_per_blob_gas(&self) -> Option { match self { Self::Eip4844(TxEip4844 { max_fee_per_blob_gas, .. }) => Some(*max_fee_per_blob_gas), _ => None, @@ -343,7 +343,7 @@ impl Transaction { /// /// This is different than the `max_priority_fee_per_gas` method, which returns `None` for /// non-EIP-1559 transactions. - pub fn priority_fee_or_price(&self) -> u128 { + pub const fn priority_fee_or_price(&self) -> u128 { match self { Self::Legacy(TxLegacy { gas_price, .. }) | Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price, @@ -357,7 +357,7 @@ impl Transaction { /// Returns the effective gas price for the given base fee. /// /// If the transaction is a legacy or EIP2930 transaction, the gas price is returned. - pub fn effective_gas_price(&self, base_fee: Option) -> u128 { + pub const fn effective_gas_price(&self, base_fee: Option) -> u128 { match self { Self::Legacy(tx) => tx.gas_price, Self::Eip2930(tx) => tx.gas_price, @@ -400,7 +400,7 @@ impl Transaction { } /// Get the transaction's input field. - pub fn input(&self) -> &Bytes { + pub const fn input(&self) -> &Bytes { match self { Self::Legacy(TxLegacy { input, .. }) | Self::Eip2930(TxEip2930 { input, .. }) | @@ -414,7 +414,7 @@ impl Transaction { /// Returns the source hash of the transaction, which uniquely identifies its source. /// If not a deposit transaction, this will always return `None`. #[cfg(feature = "optimism")] - pub fn source_hash(&self) -> Option { + pub const fn source_hash(&self) -> Option { match self { Self::Deposit(TxDeposit { source_hash, .. }) => Some(*source_hash), _ => None, @@ -424,7 +424,7 @@ impl Transaction { /// Returns the amount of ETH locked up on L1 that will be minted on L2. If the transaction /// is not a deposit transaction, this will always return `None`. #[cfg(feature = "optimism")] - pub fn mint(&self) -> Option { + pub const fn mint(&self) -> Option { match self { Self::Deposit(TxDeposit { mint, .. }) => *mint, _ => None, @@ -434,7 +434,7 @@ impl Transaction { /// Returns whether or not the transaction is a system transaction. If the transaction /// is not a deposit transaction, this will always return `false`. #[cfg(feature = "optimism")] - pub fn is_system_transaction(&self) -> bool { + pub const fn is_system_transaction(&self) -> bool { match self { Self::Deposit(TxDeposit { is_system_transaction, .. }) => *is_system_transaction, _ => false, @@ -443,7 +443,7 @@ impl Transaction { /// Returns whether or not the transaction is an Optimism Deposited transaction. #[cfg(feature = "optimism")] - pub fn is_deposit(&self) -> bool { + pub const fn is_deposit(&self) -> bool { matches!(self, Self::Deposit(_)) } @@ -552,7 +552,7 @@ impl Transaction { } /// Returns the [TxLegacy] variant if the transaction is a legacy transaction. - pub fn as_legacy(&self) -> Option<&TxLegacy> { + pub const fn as_legacy(&self) -> Option<&TxLegacy> { match self { Self::Legacy(tx) => Some(tx), _ => None, @@ -560,7 +560,7 @@ impl Transaction { } /// Returns the [TxEip2930] variant if the transaction is an EIP-2930 transaction. - pub fn as_eip2930(&self) -> Option<&TxEip2930> { + pub const fn as_eip2930(&self) -> Option<&TxEip2930> { match self { Self::Eip2930(tx) => Some(tx), _ => None, @@ -568,7 +568,7 @@ impl Transaction { } /// Returns the [TxEip1559] variant if the transaction is an EIP-1559 transaction. - pub fn as_eip1559(&self) -> Option<&TxEip1559> { + pub const fn as_eip1559(&self) -> Option<&TxEip1559> { match self { Self::Eip1559(tx) => Some(tx), _ => None, @@ -576,7 +576,7 @@ impl Transaction { } /// Returns the [TxEip4844] variant if the transaction is an EIP-4844 transaction. - pub fn as_eip4844(&self) -> Option<&TxEip4844> { + pub const fn as_eip4844(&self) -> Option<&TxEip4844> { match self { Self::Eip4844(tx) => Some(tx), _ => None, @@ -984,17 +984,17 @@ impl AsRef for TransactionSigned { impl TransactionSigned { /// Transaction signature. - pub fn signature(&self) -> &Signature { + pub const fn signature(&self) -> &Signature { &self.signature } /// Transaction hash. Used to identify transaction. - pub fn hash(&self) -> TxHash { + pub const fn hash(&self) -> TxHash { self.hash } /// Reference to transaction hash. Used to identify transaction. - pub fn hash_ref(&self) -> &TxHash { + pub const fn hash_ref(&self) -> &TxHash { &self.hash } @@ -1520,7 +1520,7 @@ pub struct TransactionSignedEcRecovered { impl TransactionSignedEcRecovered { /// Signer of transaction recovered from signature - pub fn signer(&self) -> Address { + pub const fn signer(&self) -> Address { self.signer } diff --git a/crates/primitives/src/transaction/optimism.rs b/crates/primitives/src/transaction/optimism.rs index f553f2aa6..41d47506c 100644 --- a/crates/primitives/src/transaction/optimism.rs +++ b/crates/primitives/src/transaction/optimism.rs @@ -137,7 +137,7 @@ impl TxDeposit { } /// Get the transaction type - pub(crate) fn tx_type(&self) -> TxType { + pub(crate) const fn tx_type(&self) -> TxType { TxType::Deposit } } diff --git a/crates/primitives/src/transaction/pooled.rs b/crates/primitives/src/transaction/pooled.rs index 0c39c5251..4ab6e61fc 100644 --- a/crates/primitives/src/transaction/pooled.rs +++ b/crates/primitives/src/transaction/pooled.rs @@ -107,7 +107,7 @@ impl PooledTransactionsElement { } /// Reference to transaction hash. Used to identify transaction. - pub fn hash(&self) -> &TxHash { + pub const fn hash(&self) -> &TxHash { match self { Self::Legacy { hash, .. } | Self::Eip2930 { hash, .. } | Self::Eip1559 { hash, .. } => { hash @@ -117,7 +117,7 @@ impl PooledTransactionsElement { } /// Returns the signature of the transaction. - pub fn signature(&self) -> &Signature { + pub const fn signature(&self) -> &Signature { match self { Self::Legacy { signature, .. } | Self::Eip2930 { signature, .. } | @@ -127,7 +127,7 @@ impl PooledTransactionsElement { } /// Returns the transaction nonce. - pub fn nonce(&self) -> u64 { + pub const fn nonce(&self) -> u64 { match self { Self::Legacy { transaction, .. } => transaction.nonce, Self::Eip2930 { transaction, .. } => transaction.nonce, @@ -339,7 +339,7 @@ impl PooledTransactionsElement { } /// Returns the [TxLegacy] variant if the transaction is a legacy transaction. - pub fn as_legacy(&self) -> Option<&TxLegacy> { + pub const fn as_legacy(&self) -> Option<&TxLegacy> { match self { Self::Legacy { transaction, .. } => Some(transaction), _ => None, @@ -347,7 +347,7 @@ impl PooledTransactionsElement { } /// Returns the [TxEip2930] variant if the transaction is an EIP-2930 transaction. - pub fn as_eip2930(&self) -> Option<&TxEip2930> { + pub const fn as_eip2930(&self) -> Option<&TxEip2930> { match self { Self::Eip2930 { transaction, .. } => Some(transaction), _ => None, @@ -355,7 +355,7 @@ impl PooledTransactionsElement { } /// Returns the [TxEip1559] variant if the transaction is an EIP-1559 transaction. - pub fn as_eip1559(&self) -> Option<&TxEip1559> { + pub const fn as_eip1559(&self) -> Option<&TxEip1559> { match self { Self::Eip1559 { transaction, .. } => Some(transaction), _ => None, @@ -363,7 +363,7 @@ impl PooledTransactionsElement { } /// Returns the [TxEip4844] variant if the transaction is an EIP-4844 transaction. - pub fn as_eip4844(&self) -> Option<&TxEip4844> { + pub const fn as_eip4844(&self) -> Option<&TxEip4844> { match self { Self::BlobTransaction(tx) => Some(&tx.transaction), _ => None, @@ -384,7 +384,7 @@ impl PooledTransactionsElement { /// Returns `None` for non-eip4844 transactions. /// /// This is also commonly referred to as the "Blob Gas Fee Cap" (`BlobGasFeeCap`). - pub fn max_fee_per_blob_gas(&self) -> Option { + pub const fn max_fee_per_blob_gas(&self) -> Option { match self { Self::BlobTransaction(tx) => Some(tx.transaction.max_fee_per_blob_gas), _ => None, @@ -395,7 +395,7 @@ impl PooledTransactionsElement { /// is `None` /// /// This is also commonly referred to as the "Gas Tip Cap" (`GasTipCap`). - pub fn max_priority_fee_per_gas(&self) -> Option { + pub const fn max_priority_fee_per_gas(&self) -> Option { match self { Self::Legacy { .. } | Self::Eip2930 { .. } => None, Self::Eip1559 { transaction, .. } => Some(transaction.max_priority_fee_per_gas), @@ -406,7 +406,7 @@ impl PooledTransactionsElement { /// Max fee per gas for eip1559 transaction, for legacy transactions this is gas_price. /// /// This is also commonly referred to as the "Gas Fee Cap" (`GasFeeCap`). - pub fn max_fee_per_gas(&self) -> u128 { + pub const fn max_fee_per_gas(&self) -> u128 { match self { Self::Legacy { transaction, .. } => transaction.gas_price, Self::Eip2930 { transaction, .. } => transaction.gas_price, @@ -654,7 +654,7 @@ pub struct PooledTransactionsElementEcRecovered { impl PooledTransactionsElementEcRecovered { /// Signer of transaction recovered from signature - pub fn signer(&self) -> Address { + pub const fn signer(&self) -> Address { self.signer } @@ -676,7 +676,7 @@ impl PooledTransactionsElementEcRecovered { /// Create [`TransactionSignedEcRecovered`] from [`PooledTransactionsElement`] and [`Address`] /// of the signer. - pub fn from_signed_transaction( + pub const fn from_signed_transaction( transaction: PooledTransactionsElement, signer: Address, ) -> Self { diff --git a/crates/primitives/src/transaction/signature.rs b/crates/primitives/src/transaction/signature.rs index 29db729e9..c68a46b61 100644 --- a/crates/primitives/src/transaction/signature.rs +++ b/crates/primitives/src/transaction/signature.rs @@ -77,6 +77,7 @@ impl Signature { /// Output the `v` of the signature depends on chain_id #[inline] + #[allow(clippy::missing_const_for_fn)] pub fn v(&self, chain_id: Option) -> u64 { if let Some(chain_id) = chain_id { // EIP-155: v = {0, 1} + CHAIN_ID * 2 + 35 @@ -191,7 +192,7 @@ impl Signature { /// Calculates a heuristic for the in-memory size of the [Signature]. #[inline] - pub fn size(&self) -> usize { + pub const fn size(&self) -> usize { std::mem::size_of::() } } @@ -199,7 +200,7 @@ impl Signature { /// Outputs (odd_y_parity, chain_id) from the `v` value. /// This doesn't check validity of the `v` value for optimism. #[inline] -pub fn extract_chain_id(v: u64) -> alloy_rlp::Result<(bool, Option)> { +pub const fn extract_chain_id(v: u64) -> alloy_rlp::Result<(bool, Option)> { if v < 35 { // non-EIP-155 legacy scheme, v = 27 for even y-parity, v = 28 for odd y-parity if v != 27 && v != 28 { diff --git a/crates/primitives/src/transaction/variant.rs b/crates/primitives/src/transaction/variant.rs index a69356bb2..eb9e541f9 100644 --- a/crates/primitives/src/transaction/variant.rs +++ b/crates/primitives/src/transaction/variant.rs @@ -24,7 +24,7 @@ pub enum TransactionSignedVariant { impl TransactionSignedVariant { /// Returns the raw transaction object - pub fn as_raw(&self) -> &Transaction { + pub const fn as_raw(&self) -> &Transaction { match self { Self::SignedNoHash(tx) => &tx.transaction, Self::Signed(tx) => &tx.transaction, @@ -54,7 +54,7 @@ impl TransactionSignedVariant { /// Returns [TransactionSigned] type /// else None - pub fn as_signed(&self) -> Option<&TransactionSigned> { + pub const fn as_signed(&self) -> Option<&TransactionSigned> { match self { Self::Signed(tx) => Some(tx), _ => None, @@ -63,7 +63,7 @@ impl TransactionSignedVariant { /// Returns `TransactionSignedEcRecovered` type /// else None - pub fn as_signed_ec_recovered(&self) -> Option<&TransactionSignedEcRecovered> { + pub const fn as_signed_ec_recovered(&self) -> Option<&TransactionSignedEcRecovered> { match self { Self::SignedEcRecovered(tx) => Some(tx), _ => None, @@ -71,17 +71,17 @@ impl TransactionSignedVariant { } /// Returns true if the transaction is of [TransactionSigned] variant - pub fn is_signed(&self) -> bool { + pub const fn is_signed(&self) -> bool { matches!(self, Self::Signed(_)) } /// Returns true if the transaction is of [TransactionSignedNoHash] variant - pub fn is_signed_no_hash(&self) -> bool { + pub const fn is_signed_no_hash(&self) -> bool { matches!(self, Self::SignedNoHash(_)) } /// Returns true if the transaction is of [TransactionSignedEcRecovered] variant - pub fn is_signed_ec_recovered(&self) -> bool { + pub const fn is_signed_ec_recovered(&self) -> bool { matches!(self, Self::SignedEcRecovered(_)) } diff --git a/crates/primitives/src/trie/account.rs b/crates/primitives/src/trie/account.rs index b7bfa0923..055701dfc 100644 --- a/crates/primitives/src/trie/account.rs +++ b/crates/primitives/src/trie/account.rs @@ -65,7 +65,7 @@ impl From for TrieAccount { impl TrieAccount { /// Get account's storage root. - pub fn storage_root(&self) -> B256 { + pub const fn storage_root(&self) -> B256 { self.storage_root } } diff --git a/crates/prune/src/builder.rs b/crates/prune/src/builder.rs index 290b50724..8cf3e11bd 100644 --- a/crates/prune/src/builder.rs +++ b/crates/prune/src/builder.rs @@ -37,7 +37,7 @@ impl PrunerBuilder { } /// Sets the minimum pruning interval measured in blocks. - pub fn block_interval(mut self, block_interval: usize) -> Self { + pub const fn block_interval(mut self, block_interval: usize) -> Self { self.block_interval = block_interval; self } @@ -49,13 +49,13 @@ impl PrunerBuilder { } /// Sets the number of blocks that can be re-orged. - pub fn max_reorg_depth(mut self, max_reorg_depth: usize) -> Self { + pub const fn max_reorg_depth(mut self, max_reorg_depth: usize) -> Self { self.max_reorg_depth = max_reorg_depth; self } /// Sets the delete limit for pruner, per block. - pub fn prune_delete_limit(mut self, prune_delete_limit: usize) -> Self { + pub const fn prune_delete_limit(mut self, prune_delete_limit: usize) -> Self { self.prune_delete_limit = prune_delete_limit; self } @@ -64,7 +64,7 @@ impl PrunerBuilder { /// /// CAUTION: Account and Storage History prune segments treat this timeout as a soft limit, /// meaning they can go beyond it. - pub fn timeout(mut self, timeout: Duration) -> Self { + pub const fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } diff --git a/crates/prune/src/segments/account_history.rs b/crates/prune/src/segments/account_history.rs index 5811f3b11..ded3403ac 100644 --- a/crates/prune/src/segments/account_history.rs +++ b/crates/prune/src/segments/account_history.rs @@ -21,7 +21,7 @@ pub struct AccountHistory { } impl AccountHistory { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/headers.rs b/crates/prune/src/segments/headers.rs index c2c17914b..cf2db4216 100644 --- a/crates/prune/src/segments/headers.rs +++ b/crates/prune/src/segments/headers.rs @@ -25,7 +25,7 @@ pub struct Headers { } impl Headers { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/mod.rs b/crates/prune/src/segments/mod.rs index bfd3b5a8d..f79c1d2c0 100644 --- a/crates/prune/src/segments/mod.rs +++ b/crates/prune/src/segments/mod.rs @@ -188,7 +188,7 @@ pub(crate) struct PruneOutputCheckpoint { impl PruneOutputCheckpoint { /// Converts [PruneOutputCheckpoint] to [PruneCheckpoint] with the provided [PruneMode] - pub(crate) fn as_prune_checkpoint(&self, prune_mode: PruneMode) -> PruneCheckpoint { + pub(crate) const fn as_prune_checkpoint(&self, prune_mode: PruneMode) -> PruneCheckpoint { PruneCheckpoint { block_number: self.block_number, tx_number: self.tx_number, prune_mode } } } diff --git a/crates/prune/src/segments/receipts.rs b/crates/prune/src/segments/receipts.rs index 485b7dd68..de77204c0 100644 --- a/crates/prune/src/segments/receipts.rs +++ b/crates/prune/src/segments/receipts.rs @@ -16,7 +16,7 @@ pub struct Receipts { } impl Receipts { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/receipts_by_logs.rs b/crates/prune/src/segments/receipts_by_logs.rs index 211434bc0..2342224dd 100644 --- a/crates/prune/src/segments/receipts_by_logs.rs +++ b/crates/prune/src/segments/receipts_by_logs.rs @@ -16,7 +16,7 @@ pub struct ReceiptsByLogs { } impl ReceiptsByLogs { - pub fn new(config: ReceiptsLogPruneConfig) -> Self { + pub const fn new(config: ReceiptsLogPruneConfig) -> Self { Self { config } } } diff --git a/crates/prune/src/segments/sender_recovery.rs b/crates/prune/src/segments/sender_recovery.rs index 9dfcc85bb..e9eb2bf1b 100644 --- a/crates/prune/src/segments/sender_recovery.rs +++ b/crates/prune/src/segments/sender_recovery.rs @@ -13,7 +13,7 @@ pub struct SenderRecovery { } impl SenderRecovery { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/storage_history.rs b/crates/prune/src/segments/storage_history.rs index 6be6a24ff..3d0f18d97 100644 --- a/crates/prune/src/segments/storage_history.rs +++ b/crates/prune/src/segments/storage_history.rs @@ -25,7 +25,7 @@ pub struct StorageHistory { } impl StorageHistory { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/transaction_lookup.rs b/crates/prune/src/segments/transaction_lookup.rs index 898b30206..f22b321c6 100644 --- a/crates/prune/src/segments/transaction_lookup.rs +++ b/crates/prune/src/segments/transaction_lookup.rs @@ -14,7 +14,7 @@ pub struct TransactionLookup { } impl TransactionLookup { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/prune/src/segments/transactions.rs b/crates/prune/src/segments/transactions.rs index 3f881e06f..f2abe4468 100644 --- a/crates/prune/src/segments/transactions.rs +++ b/crates/prune/src/segments/transactions.rs @@ -13,7 +13,7 @@ pub struct Transactions { } impl Transactions { - pub fn new(mode: PruneMode) -> Self { + pub const fn new(mode: PruneMode) -> Self { Self { mode } } } diff --git a/crates/revm/src/batch.rs b/crates/revm/src/batch.rs index 4eb29eee7..0ca61c990 100644 --- a/crates/revm/src/batch.rs +++ b/crates/revm/src/batch.rs @@ -74,7 +74,7 @@ impl BlockBatchRecord { } /// Returns the recorded receipts. - pub fn receipts(&self) -> &Receipts { + pub const fn receipts(&self) -> &Receipts { &self.receipts } diff --git a/crates/rpc/ipc/src/server/mod.rs b/crates/rpc/ipc/src/server/mod.rs index 826f33ee7..5a154e6f7 100644 --- a/crates/rpc/ipc/src/server/mod.rs +++ b/crates/rpc/ipc/src/server/mod.rs @@ -588,31 +588,31 @@ impl Default for Builder { impl Builder { /// Set the maximum size of a request body in bytes. Default is 10 MiB. - pub fn max_request_body_size(mut self, size: u32) -> Self { + pub const fn max_request_body_size(mut self, size: u32) -> Self { self.settings.max_request_body_size = size; self } /// Set the maximum size of a response body in bytes. Default is 10 MiB. - pub fn max_response_body_size(mut self, size: u32) -> Self { + pub const fn max_response_body_size(mut self, size: u32) -> Self { self.settings.max_response_body_size = size; self } /// Set the maximum size of a log - pub fn max_log_length(mut self, size: u32) -> Self { + pub const fn max_log_length(mut self, size: u32) -> Self { self.settings.max_log_length = size; self } /// Set the maximum number of connections allowed. Default is 100. - pub fn max_connections(mut self, max: u32) -> Self { + pub const fn max_connections(mut self, max: u32) -> Self { self.settings.max_connections = max; self } /// Set the maximum number of connections allowed. Default is 1024. - pub fn max_subscriptions_per_connection(mut self, max: u32) -> Self { + pub const fn max_subscriptions_per_connection(mut self, max: u32) -> Self { self.settings.max_subscriptions_per_connection = max; self } @@ -634,7 +634,7 @@ impl Builder { /// # Panics /// /// Panics if the buffer capacity is 0. - pub fn set_message_buffer_capacity(mut self, c: u32) -> Self { + pub const fn set_message_buffer_capacity(mut self, c: u32) -> Self { self.settings.message_buffer_capacity = c; self } diff --git a/crates/rpc/ipc/src/server/rpc_service.rs b/crates/rpc/ipc/src/server/rpc_service.rs index 94e9ed2aa..edc615de3 100644 --- a/crates/rpc/ipc/src/server/rpc_service.rs +++ b/crates/rpc/ipc/src/server/rpc_service.rs @@ -36,7 +36,7 @@ pub(crate) enum RpcServiceCfg { impl RpcService { /// Create a new service. - pub(crate) fn new( + pub(crate) const fn new( methods: Methods, max_response_body_size: usize, conn_id: usize, diff --git a/crates/rpc/ipc/src/stream_codec.rs b/crates/rpc/ipc/src/stream_codec.rs index de6c4bf27..e6e035f1d 100644 --- a/crates/rpc/ipc/src/stream_codec.rs +++ b/crates/rpc/ipc/src/stream_codec.rs @@ -61,13 +61,13 @@ impl StreamCodec { } /// New custom stream codec - pub fn new(incoming_separator: Separator, outgoing_separator: Separator) -> Self { + pub const fn new(incoming_separator: Separator, outgoing_separator: Separator) -> Self { Self { incoming_separator, outgoing_separator } } } #[inline] -fn is_whitespace(byte: u8) -> bool { +const fn is_whitespace(byte: u8) -> bool { matches!(byte, 0x0D | 0x0A | 0x20 | 0x09) } diff --git a/crates/rpc/rpc-builder/src/auth.rs b/crates/rpc/rpc-builder/src/auth.rs index 853bf3768..70721ac10 100644 --- a/crates/rpc/rpc-builder/src/auth.rs +++ b/crates/rpc/rpc-builder/src/auth.rs @@ -170,12 +170,12 @@ pub struct AuthServerConfig { impl AuthServerConfig { /// Convenience function to create a new `AuthServerConfig`. - pub fn builder(secret: JwtSecret) -> AuthServerConfigBuilder { + pub const fn builder(secret: JwtSecret) -> AuthServerConfigBuilder { AuthServerConfigBuilder::new(secret) } /// Returns the address the server will listen on. - pub fn address(&self) -> SocketAddr { + pub const fn address(&self) -> SocketAddr { self.socket_addr } @@ -231,7 +231,7 @@ pub struct AuthServerConfigBuilder { impl AuthServerConfigBuilder { /// Create a new `AuthServerConfigBuilder` with the given `secret`. - pub fn new(secret: JwtSecret) -> Self { + pub const fn new(secret: JwtSecret) -> Self { Self { socket_addr: None, secret, @@ -242,19 +242,19 @@ impl AuthServerConfigBuilder { } /// Set the socket address for the server. - pub fn socket_addr(mut self, socket_addr: SocketAddr) -> Self { + pub const fn socket_addr(mut self, socket_addr: SocketAddr) -> Self { self.socket_addr = Some(socket_addr); self } /// Set the socket address for the server. - pub fn maybe_socket_addr(mut self, socket_addr: Option) -> Self { + pub const fn maybe_socket_addr(mut self, socket_addr: Option) -> Self { self.socket_addr = socket_addr; self } /// Set the secret for the server. - pub fn secret(mut self, secret: JwtSecret) -> Self { + pub const fn secret(mut self, secret: JwtSecret) -> Self { self.secret = secret; self } @@ -379,7 +379,7 @@ pub struct AuthServerHandle { impl AuthServerHandle { /// Returns the [`SocketAddr`] of the http server if started. - pub fn local_addr(&self) -> SocketAddr { + pub const fn local_addr(&self) -> SocketAddr { self.local_addr } diff --git a/crates/rpc/rpc-builder/src/error.rs b/crates/rpc/rpc-builder/src/error.rs index 1753b1fc9..b99132e59 100644 --- a/crates/rpc/rpc-builder/src/error.rs +++ b/crates/rpc/rpc-builder/src/error.rs @@ -17,7 +17,7 @@ pub enum ServerKind { impl ServerKind { /// Returns the appropriate flags for each variant. - pub fn flags(&self) -> &'static str { + pub const fn flags(&self) -> &'static str { match self { Self::Http(_) => "--http.port", Self::WS(_) => "--ws.port", diff --git a/crates/rpc/rpc-builder/src/eth.rs b/crates/rpc/rpc-builder/src/eth.rs index a4a144357..bb7523fc1 100644 --- a/crates/rpc/rpc-builder/src/eth.rs +++ b/crates/rpc/rpc-builder/src/eth.rs @@ -81,37 +81,37 @@ impl Default for EthConfig { impl EthConfig { /// Configures the caching layer settings - pub fn state_cache(mut self, cache: EthStateCacheConfig) -> Self { + pub const fn state_cache(mut self, cache: EthStateCacheConfig) -> Self { self.cache = cache; self } /// Configures the gas price oracle settings - pub fn gpo_config(mut self, gas_oracle_config: GasPriceOracleConfig) -> Self { + pub const fn gpo_config(mut self, gas_oracle_config: GasPriceOracleConfig) -> Self { self.gas_oracle = gas_oracle_config; self } /// Configures the maximum number of tracing requests - pub fn max_tracing_requests(mut self, max_requests: usize) -> Self { + pub const fn max_tracing_requests(mut self, max_requests: usize) -> Self { self.max_tracing_requests = max_requests; self } /// Configures the maximum block length to scan per `eth_getLogs` request - pub fn max_blocks_per_filter(mut self, max_blocks: u64) -> Self { + pub const fn max_blocks_per_filter(mut self, max_blocks: u64) -> Self { self.max_blocks_per_filter = max_blocks; self } /// Configures the maximum number of logs per response - pub fn max_logs_per_response(mut self, max_logs: usize) -> Self { + pub const fn max_logs_per_response(mut self, max_logs: usize) -> Self { self.max_logs_per_response = max_logs; self } /// Configures the maximum gas limit for `eth_call` and call tracing RPC methods - pub fn rpc_gas_cap(mut self, rpc_gas_cap: u64) -> Self { + pub const fn rpc_gas_cap(mut self, rpc_gas_cap: u64) -> Self { self.rpc_gas_cap = rpc_gas_cap; self } diff --git a/crates/rpc/rpc-builder/src/lib.rs b/crates/rpc/rpc-builder/src/lib.rs index a9dc85d46..f0ddf76dc 100644 --- a/crates/rpc/rpc-builder/src/lib.rs +++ b/crates/rpc/rpc-builder/src/lib.rs @@ -293,7 +293,7 @@ impl RpcModuleBuilder { /// Create a new instance of the builder - pub fn new( + pub const fn new( provider: Provider, pool: Pool, network: Network, @@ -571,7 +571,7 @@ impl RpcModuleConfig { RpcModuleConfigBuilder::default() } /// Returns a new RPC module config given the eth namespace config - pub fn new(eth: EthConfig) -> Self { + pub const fn new(eth: EthConfig) -> Self { Self { eth } } } @@ -586,7 +586,7 @@ pub struct RpcModuleConfigBuilder { impl RpcModuleConfigBuilder { /// Configures a custom eth namespace config - pub fn eth(mut self, eth: EthConfig) -> Self { + pub const fn eth(mut self, eth: EthConfig) -> Self { self.eth = Some(eth); self } @@ -952,22 +952,22 @@ impl } /// Returns a reference to the pool - pub fn pool(&self) -> &Pool { + pub const fn pool(&self) -> &Pool { &self.pool } /// Returns a reference to the events type - pub fn events(&self) -> &Events { + pub const fn events(&self) -> &Events { &self.events } /// Returns a reference to the tasks type - pub fn tasks(&self) -> &Tasks { + pub const fn tasks(&self) -> &Tasks { &self.executor } /// Returns a reference to the provider - pub fn provider(&self) -> &Provider { + pub const fn provider(&self) -> &Provider { &self.provider } @@ -1506,7 +1506,7 @@ impl RpcServerConfig { /// Configures the [SocketAddr] of the http server /// /// Default is [Ipv4Addr::LOCALHOST] and [DEFAULT_HTTP_RPC_PORT] - pub fn with_http_address(mut self, addr: SocketAddr) -> Self { + pub const fn with_http_address(mut self, addr: SocketAddr) -> Self { self.http_addr = Some(addr); self } @@ -1514,7 +1514,7 @@ impl RpcServerConfig { /// Configures the [SocketAddr] of the ws server /// /// Default is [Ipv4Addr::LOCALHOST] and [DEFAULT_WS_RPC_PORT] - pub fn with_ws_address(mut self, addr: SocketAddr) -> Self { + pub const fn with_ws_address(mut self, addr: SocketAddr) -> Self { self.ws_addr = Some(addr); self } @@ -1557,7 +1557,7 @@ impl RpcServerConfig { } /// Configures the JWT secret for authentication. - pub fn with_jwt_secret(mut self, secret: Option) -> Self { + pub const fn with_jwt_secret(mut self, secret: Option) -> Self { self.jwt_secret = secret; self } @@ -1565,19 +1565,19 @@ impl RpcServerConfig { /// Returns true if any server is configured. /// /// If no server is configured, no server will be be launched on [RpcServerConfig::start]. - pub fn has_server(&self) -> bool { + pub const fn has_server(&self) -> bool { self.http_server_config.is_some() || self.ws_server_config.is_some() || self.ipc_server_config.is_some() } /// Returns the [SocketAddr] of the http server - pub fn http_address(&self) -> Option { + pub const fn http_address(&self) -> Option { self.http_addr } /// Returns the [SocketAddr] of the ws server - pub fn ws_address(&self) -> Option { + pub const fn ws_address(&self) -> Option { self.ws_addr } @@ -1814,28 +1814,28 @@ impl TransportRpcModuleConfig { } /// Sets a custom [RpcModuleConfig] for the configured modules. - pub fn with_config(mut self, config: RpcModuleConfig) -> Self { + pub const fn with_config(mut self, config: RpcModuleConfig) -> Self { self.config = Some(config); self } /// Returns true if no transports are configured - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.http.is_none() && self.ws.is_none() && self.ipc.is_none() } /// Returns the [RpcModuleSelection] for the http transport - pub fn http(&self) -> Option<&RpcModuleSelection> { + pub const fn http(&self) -> Option<&RpcModuleSelection> { self.http.as_ref() } /// Returns the [RpcModuleSelection] for the ws transport - pub fn ws(&self) -> Option<&RpcModuleSelection> { + pub const fn ws(&self) -> Option<&RpcModuleSelection> { self.ws.as_ref() } /// Returns the [RpcModuleSelection] for the ipc transport - pub fn ipc(&self) -> Option<&RpcModuleSelection> { + pub const fn ipc(&self) -> Option<&RpcModuleSelection> { self.ipc.as_ref() } @@ -1871,7 +1871,7 @@ pub struct TransportRpcModules { impl TransportRpcModules { /// Returns the [TransportRpcModuleConfig] used to configure this instance. - pub fn module_config(&self) -> &TransportRpcModuleConfig { + pub const fn module_config(&self) -> &TransportRpcModuleConfig { &self.config } @@ -2025,16 +2025,16 @@ impl RpcServer { } /// Returns the [`SocketAddr`] of the http server if started. - pub fn http_local_addr(&self) -> Option { + pub const fn http_local_addr(&self) -> Option { self.ws_http.http_local_addr } /// Return the JwtSecret of the server - pub fn jwt(&self) -> Option { + pub const fn jwt(&self) -> Option { self.ws_http.jwt_secret } /// Returns the [`SocketAddr`] of the ws server if started. - pub fn ws_local_addr(&self) -> Option { + pub const fn ws_local_addr(&self) -> Option { self.ws_http.ws_local_addr } @@ -2123,12 +2123,12 @@ impl RpcServerHandle { }) } /// Returns the [`SocketAddr`] of the http server if started. - pub fn http_local_addr(&self) -> Option { + pub const fn http_local_addr(&self) -> Option { self.http_local_addr } /// Returns the [`SocketAddr`] of the ws server if started. - pub fn ws_local_addr(&self) -> Option { + pub const fn ws_local_addr(&self) -> Option { self.ws_local_addr } diff --git a/crates/rpc/rpc-builder/tests/it/http.rs b/crates/rpc/rpc-builder/tests/it/http.rs index 42fecb87d..99b54d594 100644 --- a/crates/rpc/rpc-builder/tests/it/http.rs +++ b/crates/rpc/rpc-builder/tests/it/http.rs @@ -86,7 +86,7 @@ impl RawRpcParamsBuilder { } /// Sets the ID for the JSON-RPC request. - pub fn set_id(mut self, id: i32) -> Self { + pub const fn set_id(mut self, id: i32) -> Self { self.id = id; self } diff --git a/crates/rpc/rpc-builder/tests/it/main.rs b/crates/rpc/rpc-builder/tests/it/main.rs index 6f9290d0f..65ddebb3f 100644 --- a/crates/rpc/rpc-builder/tests/it/main.rs +++ b/crates/rpc/rpc-builder/tests/it/main.rs @@ -4,4 +4,4 @@ mod serde; mod startup; pub mod utils; -fn main() {} +const fn main() {} diff --git a/crates/rpc/rpc-builder/tests/it/utils.rs b/crates/rpc/rpc-builder/tests/it/utils.rs index 819a3a863..5e6e1833d 100644 --- a/crates/rpc/rpc-builder/tests/it/utils.rs +++ b/crates/rpc/rpc-builder/tests/it/utils.rs @@ -19,7 +19,7 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use tokio::sync::mpsc::unbounded_channel; /// Localhost with port 0 so a free port is used. -pub fn test_address() -> SocketAddr { +pub const fn test_address() -> SocketAddr { SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) } diff --git a/crates/rpc/rpc-engine-api/tests/it/main.rs b/crates/rpc/rpc-engine-api/tests/it/main.rs index cf02e7098..fb4c7fa0d 100644 --- a/crates/rpc/rpc-engine-api/tests/it/main.rs +++ b/crates/rpc/rpc-engine-api/tests/it/main.rs @@ -1,3 +1,3 @@ mod payload; -fn main() {} +const fn main() {} diff --git a/crates/rpc/rpc-layer/src/auth_client_layer.rs b/crates/rpc/rpc-layer/src/auth_client_layer.rs index 1b57608a7..e1514ed5f 100644 --- a/crates/rpc/rpc-layer/src/auth_client_layer.rs +++ b/crates/rpc/rpc-layer/src/auth_client_layer.rs @@ -15,7 +15,7 @@ pub struct AuthClientLayer { impl AuthClientLayer { /// Create a new AuthClientLayer with the given `secret`. - pub fn new(secret: JwtSecret) -> Self { + pub const fn new(secret: JwtSecret) -> Self { Self { secret } } } @@ -36,7 +36,7 @@ pub struct AuthClientService { } impl AuthClientService { - fn new(secret: JwtSecret, inner: S) -> Self { + const fn new(secret: JwtSecret, inner: S) -> Self { Self { secret, inner } } } diff --git a/crates/rpc/rpc-layer/src/auth_layer.rs b/crates/rpc/rpc-layer/src/auth_layer.rs index bbf353f84..bf86d7d63 100644 --- a/crates/rpc/rpc-layer/src/auth_layer.rs +++ b/crates/rpc/rpc-layer/src/auth_layer.rs @@ -47,7 +47,7 @@ pub struct AuthLayer { impl AuthLayer { /// Creates an instance of [`AuthLayer`]. /// `validator` is a generic trait able to validate requests (see [`AuthValidator`]). - pub fn new(validator: V) -> Self { + pub const fn new(validator: V) -> Self { Self { validator } } } @@ -115,11 +115,11 @@ impl ResponseFuture where B: Body, { - fn future(future: F) -> Self { + const fn future(future: F) -> Self { Self { kind: Kind::Future { future } } } - fn invalid_auth(err_res: Response) -> Self { + const fn invalid_auth(err_res: Response) -> Self { Self { kind: Kind::Error { response: Some(err_res) } } } } diff --git a/crates/rpc/rpc-layer/src/jwt_validator.rs b/crates/rpc/rpc-layer/src/jwt_validator.rs index 5bed6135d..f1485be9c 100644 --- a/crates/rpc/rpc-layer/src/jwt_validator.rs +++ b/crates/rpc/rpc-layer/src/jwt_validator.rs @@ -16,7 +16,7 @@ impl JwtAuthValidator { /// Creates a new instance of [`JwtAuthValidator`]. /// Validation logics are implemented by the `secret` /// argument (see [`JwtSecret`]). - pub fn new(secret: JwtSecret) -> Self { + pub const fn new(secret: JwtSecret) -> Self { Self { secret } } } diff --git a/crates/rpc/rpc-testing-util/src/trace.rs b/crates/rpc/rpc-testing-util/src/trace.rs index 64c84c11b..c3df9832e 100644 --- a/crates/rpc/rpc-testing-util/src/trace.rs +++ b/crates/rpc/rpc-testing-util/src/trace.rs @@ -438,7 +438,7 @@ where /// /// * `client1` - The first RPC client. /// * `client2` - The second RPC client. - pub fn new(client1: C1, client2: C2) -> Self { + pub const fn new(client1: C1, client2: C2) -> Self { Self { client1, client2 } } @@ -519,7 +519,7 @@ mod tests { use reth_primitives::BlockNumberOrTag; use reth_rpc_types::trace::filter::TraceFilterMode; - fn assert_is_stream(_: &St) {} + const fn assert_is_stream(_: &St) {} #[tokio::test] async fn can_create_block_stream() { diff --git a/crates/rpc/rpc-testing-util/tests/it/main.rs b/crates/rpc/rpc-testing-util/tests/it/main.rs index 76f73cd8f..4f65af8f9 100644 --- a/crates/rpc/rpc-testing-util/tests/it/main.rs +++ b/crates/rpc/rpc-testing-util/tests/it/main.rs @@ -1,3 +1,3 @@ mod trace; -fn main() {} +const fn main() {} diff --git a/crates/rpc/rpc-types/src/mev.rs b/crates/rpc/rpc-types/src/mev.rs index 61e79fab1..ed5d79bb4 100644 --- a/crates/rpc/rpc-types/src/mev.rs +++ b/crates/rpc/rpc-types/src/mev.rs @@ -47,13 +47,13 @@ pub struct Inclusion { impl Inclusion { /// Creates a new inclusion with the given min block.. - pub fn at_block(block: u64) -> Self { + pub const fn at_block(block: u64) -> Self { Self { block, max_block: None } } /// Returns the block number of the first block the bundle is valid for. #[inline] - pub fn block_number(&self) -> u64 { + pub const fn block_number(&self) -> u64 { self.block } @@ -155,76 +155,76 @@ pub struct PrivacyHint { impl PrivacyHint { /// Sets the flag indicating inclusion of calldata and returns the modified PrivacyHint /// instance. - pub fn with_calldata(mut self) -> Self { + pub const fn with_calldata(mut self) -> Self { self.calldata = true; self } /// Sets the flag indicating inclusion of contract address and returns the modified PrivacyHint /// instance. - pub fn with_contract_address(mut self) -> Self { + pub const fn with_contract_address(mut self) -> Self { self.contract_address = true; self } /// Sets the flag indicating inclusion of logs and returns the modified PrivacyHint instance. - pub fn with_logs(mut self) -> Self { + pub const fn with_logs(mut self) -> Self { self.logs = true; self } /// Sets the flag indicating inclusion of function selector and returns the modified PrivacyHint /// instance. - pub fn with_function_selector(mut self) -> Self { + pub const fn with_function_selector(mut self) -> Self { self.function_selector = true; self } /// Sets the flag indicating inclusion of hash and returns the modified PrivacyHint instance. - pub fn with_hash(mut self) -> Self { + pub const fn with_hash(mut self) -> Self { self.hash = true; self } /// Sets the flag indicating inclusion of transaction hash and returns the modified PrivacyHint /// instance. - pub fn with_tx_hash(mut self) -> Self { + pub const fn with_tx_hash(mut self) -> Self { self.tx_hash = true; self } /// Checks if calldata inclusion flag is set. - pub fn has_calldata(&self) -> bool { + pub const fn has_calldata(&self) -> bool { self.calldata } /// Checks if contract address inclusion flag is set. - pub fn has_contract_address(&self) -> bool { + pub const fn has_contract_address(&self) -> bool { self.contract_address } /// Checks if logs inclusion flag is set. - pub fn has_logs(&self) -> bool { + pub const fn has_logs(&self) -> bool { self.logs } /// Checks if function selector inclusion flag is set. - pub fn has_function_selector(&self) -> bool { + pub const fn has_function_selector(&self) -> bool { self.function_selector } /// Checks if hash inclusion flag is set. - pub fn has_hash(&self) -> bool { + pub const fn has_hash(&self) -> bool { self.hash } /// Checks if transaction hash inclusion flag is set. - pub fn has_tx_hash(&self) -> bool { + pub const fn has_tx_hash(&self) -> bool { self.tx_hash } /// Calculates the number of hints set within the PrivacyHint instance. - fn num_hints(&self) -> usize { + const fn num_hints(&self) -> usize { let mut num_hints = 0; if self.calldata { num_hints += 1; @@ -456,7 +456,7 @@ pub struct PrivateTransactionPreferences { impl PrivateTransactionPreferences { /// Returns true if the preferences are empty. - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.validity.is_none() && self.privacy.is_none() } } diff --git a/crates/rpc/rpc-types/src/rpc.rs b/crates/rpc/rpc-types/src/rpc.rs index d754a23c8..4d7c08f6a 100644 --- a/crates/rpc/rpc-types/src/rpc.rs +++ b/crates/rpc/rpc-types/src/rpc.rs @@ -11,7 +11,7 @@ pub struct RpcModules { impl RpcModules { /// Create a new instance of RPCModules - pub fn new(module_map: HashMap) -> Self { + pub const fn new(module_map: HashMap) -> Self { Self { module_map } } diff --git a/crates/rpc/rpc/src/engine.rs b/crates/rpc/rpc/src/engine.rs index 7afe43136..63f3bfaab 100644 --- a/crates/rpc/rpc/src/engine.rs +++ b/crates/rpc/rpc/src/engine.rs @@ -24,7 +24,7 @@ pub struct EngineEthApi { impl EngineEthApi { /// Create a new `EngineEthApi` instance. - pub fn new(eth: Eth, eth_filter: EthFilter) -> Self { + pub const fn new(eth: Eth, eth_filter: EthFilter) -> Self { Self { eth, eth_filter } } } diff --git a/crates/rpc/rpc/src/eth/api/optimism.rs b/crates/rpc/rpc/src/eth/api/optimism.rs index 91ec45202..b5aa8c725 100644 --- a/crates/rpc/rpc/src/eth/api/optimism.rs +++ b/crates/rpc/rpc/src/eth/api/optimism.rs @@ -21,7 +21,7 @@ pub(crate) struct OptimismTxMeta { impl OptimismTxMeta { /// Creates a new [OptimismTxMeta]. - pub(crate) fn new( + pub(crate) const fn new( l1_block_info: Option, l1_fee: Option, l1_data_gas: Option, diff --git a/crates/rpc/rpc/src/eth/api/pending_block.rs b/crates/rpc/rpc/src/eth/api/pending_block.rs index a53542fa4..608c480b2 100644 --- a/crates/rpc/rpc/src/eth/api/pending_block.rs +++ b/crates/rpc/rpc/src/eth/api/pending_block.rs @@ -335,7 +335,7 @@ 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 { + pub(crate) const fn is_actual_pending(&self) -> bool { matches!(self, Self::ActualPending(_)) } diff --git a/crates/rpc/rpc/src/eth/error.rs b/crates/rpc/rpc/src/eth/error.rs index 42a8d3624..6e7aeb775 100644 --- a/crates/rpc/rpc/src/eth/error.rs +++ b/crates/rpc/rpc/src/eth/error.rs @@ -367,7 +367,7 @@ pub enum OptimismInvalidTransactionError { impl RpcInvalidTransactionError { /// Returns the rpc error code for this error. - fn error_code(&self) -> i32 { + const fn error_code(&self) -> i32 { match self { Self::InvalidChainId | Self::GasTooLow | Self::GasTooHigh => { EthRpcErrorCode::InvalidInput.code() @@ -380,7 +380,7 @@ impl RpcInvalidTransactionError { /// Converts the halt error /// /// Takes the configured gas limit of the transaction which is attached to the error - pub(crate) fn halt(reason: HaltReason, gas_limit: u64) -> Self { + pub(crate) const fn halt(reason: HaltReason, gas_limit: u64) -> Self { match reason { HaltReason::OutOfGas(err) => Self::out_of_gas(err, gas_limit), HaltReason::NonceOverflow => Self::NonceMaxValue, @@ -389,7 +389,7 @@ impl RpcInvalidTransactionError { } /// Converts the out of gas error - pub(crate) fn out_of_gas(reason: OutOfGasError, gas_limit: u64) -> Self { + pub(crate) const fn out_of_gas(reason: OutOfGasError, gas_limit: u64) -> Self { match reason { OutOfGasError::Basic => Self::BasicOutOfGas(gas_limit), OutOfGasError::Memory => Self::MemoryOutOfGas(gas_limit), @@ -508,7 +508,7 @@ impl RevertError { } } - fn error_code(&self) -> i32 { + const fn error_code(&self) -> i32 { EthRpcErrorCode::ExecutionError.code() } } diff --git a/crates/rpc/rpc/src/eth/filter.rs b/crates/rpc/rpc/src/eth/filter.rs index d0d7077e8..3a1a651ec 100644 --- a/crates/rpc/rpc/src/eth/filter.rs +++ b/crates/rpc/rpc/src/eth/filter.rs @@ -533,20 +533,20 @@ pub struct EthFilterConfig { impl EthFilterConfig { /// Sets the maximum number of blocks that a filter can scan for logs. - pub fn max_blocks_per_filter(mut self, num: u64) -> Self { + pub const fn max_blocks_per_filter(mut self, num: u64) -> Self { self.max_blocks_per_filter = Some(num); self } /// Sets the maximum number of logs that can be returned in a single response in `eth_getLogs` /// calls. - pub fn max_logs_per_response(mut self, num: usize) -> Self { + pub const fn max_logs_per_response(mut self, num: usize) -> Self { self.max_logs_per_response = Some(num); self } /// Sets how long a filter remains valid after the last poll before it will be removed. - pub fn stale_filter_ttl(mut self, duration: Duration) -> Self { + pub const fn stale_filter_ttl(mut self, duration: Duration) -> Self { self.stale_filter_ttl = duration; self } diff --git a/crates/rpc/rpc/src/eth/gas_oracle.rs b/crates/rpc/rpc/src/eth/gas_oracle.rs index 592c858d8..344020313 100644 --- a/crates/rpc/rpc/src/eth/gas_oracle.rs +++ b/crates/rpc/rpc/src/eth/gas_oracle.rs @@ -119,7 +119,7 @@ where } /// Returns the configuration of the gas price oracle. - pub fn config(&self) -> &GasPriceOracleConfig { + pub const fn config(&self) -> &GasPriceOracleConfig { &self.oracle_config } diff --git a/crates/rpc/rpc/src/eth/revm_utils.rs b/crates/rpc/rpc/src/eth/revm_utils.rs index f5b6545a0..3fc09da34 100644 --- a/crates/rpc/rpc/src/eth/revm_utils.rs +++ b/crates/rpc/rpc/src/eth/revm_utils.rs @@ -42,17 +42,17 @@ pub struct EvmOverrides { impl EvmOverrides { /// Creates a new instance with the given overrides - pub fn new(state: Option, block: Option>) -> Self { + pub const fn new(state: Option, block: Option>) -> Self { Self { state, block } } /// Creates a new instance with the given state overrides. - pub fn state(state: Option) -> Self { + pub const fn state(state: Option) -> Self { Self { state, block: None } } /// Returns `true` if the overrides contain state overrides. - pub fn has_state(&self) -> bool { + pub const fn has_state(&self) -> bool { self.state.is_some() } } diff --git a/crates/rpc/rpc/src/net.rs b/crates/rpc/rpc/src/net.rs index 2def768e5..8e6615a28 100644 --- a/crates/rpc/rpc/src/net.rs +++ b/crates/rpc/rpc/src/net.rs @@ -19,7 +19,7 @@ pub struct NetApi { impl NetApi { /// Returns a new instance with the given network and eth interface implementations - pub fn new(network: Net, eth: Eth) -> Self { + pub const fn new(network: Net, eth: Eth) -> Self { Self { network, eth } } } diff --git a/crates/rpc/rpc/src/otterscan.rs b/crates/rpc/rpc/src/otterscan.rs index 1682f6f88..f1343c46e 100644 --- a/crates/rpc/rpc/src/otterscan.rs +++ b/crates/rpc/rpc/src/otterscan.rs @@ -26,7 +26,7 @@ pub struct OtterscanApi { impl OtterscanApi { /// Creates a new instance of `Otterscan`. - pub fn new(eth: Eth) -> Self { + pub const fn new(eth: Eth) -> Self { Self { eth } } } diff --git a/crates/rpc/rpc/src/result.rs b/crates/rpc/rpc/src/result.rs index 406d59ce1..281680d90 100644 --- a/crates/rpc/rpc/src/result.rs +++ b/crates/rpc/rpc/src/result.rs @@ -154,7 +154,7 @@ mod tests { use super::*; use reth_errors::{RethError, RethResult}; - fn assert_rpc_result>() {} + const fn assert_rpc_result>() {} #[test] fn can_convert_rpc() { diff --git a/crates/rpc/rpc/src/txpool.rs b/crates/rpc/rpc/src/txpool.rs index aaef62f70..71c342225 100644 --- a/crates/rpc/rpc/src/txpool.rs +++ b/crates/rpc/rpc/src/txpool.rs @@ -21,7 +21,7 @@ pub struct TxPoolApi { impl TxPoolApi { /// Creates a new instance of `TxpoolApi`. - pub fn new(pool: Pool) -> Self { + pub const fn new(pool: Pool) -> Self { Self { pool } } } diff --git a/crates/rpc/rpc/src/web3.rs b/crates/rpc/rpc/src/web3.rs index e7dc9e6be..4ed94ac85 100644 --- a/crates/rpc/rpc/src/web3.rs +++ b/crates/rpc/rpc/src/web3.rs @@ -15,7 +15,7 @@ pub struct Web3Api { impl Web3Api { /// Creates a new instance of `Web3Api`. - pub fn new(network: N) -> Self { + pub const fn new(network: N) -> Self { Self { network } } } diff --git a/crates/stages/api/src/error.rs b/crates/stages/api/src/error.rs index 9b7565355..848b2570b 100644 --- a/crates/stages/api/src/error.rs +++ b/crates/stages/api/src/error.rs @@ -20,7 +20,7 @@ pub enum BlockErrorKind { impl BlockErrorKind { /// Returns `true` if the error is a state root error. - pub fn is_state_root_error(&self) -> bool { + pub const fn is_state_root_error(&self) -> bool { match self { Self::Validation(err) => err.is_state_root_error(), Self::Execution(err) => err.is_state_root_error(), @@ -134,7 +134,7 @@ pub enum StageError { impl StageError { /// If the error is fatal the pipeline will stop. - pub fn is_fatal(&self) -> bool { + pub const fn is_fatal(&self) -> bool { matches!( self, Self::Database(_) | diff --git a/crates/stages/api/src/pipeline/builder.rs b/crates/stages/api/src/pipeline/builder.rs index c05906725..27faba5b2 100644 --- a/crates/stages/api/src/pipeline/builder.rs +++ b/crates/stages/api/src/pipeline/builder.rs @@ -50,7 +50,7 @@ where /// Set the target block. /// /// Once this block is reached, the pipeline will stop. - pub fn with_max_block(mut self, block: BlockNumber) -> Self { + pub const fn with_max_block(mut self, block: BlockNumber) -> Self { self.max_block = Some(block); self } diff --git a/crates/stages/api/src/pipeline/ctrl.rs b/crates/stages/api/src/pipeline/ctrl.rs index dc19672bc..4d44f02c6 100644 --- a/crates/stages/api/src/pipeline/ctrl.rs +++ b/crates/stages/api/src/pipeline/ctrl.rs @@ -26,17 +26,17 @@ pub enum ControlFlow { impl ControlFlow { /// Whether the pipeline should continue executing stages. - pub fn should_continue(&self) -> bool { + pub const fn should_continue(&self) -> bool { matches!(self, Self::Continue { .. } | Self::NoProgress { .. }) } /// Returns true if the control flow is unwind. - pub fn is_unwind(&self) -> bool { + pub const fn is_unwind(&self) -> bool { matches!(self, Self::Unwind { .. }) } /// Returns the pipeline block number the stage reached, if the state is not `Unwind`. - pub fn block_number(&self) -> Option { + pub const fn block_number(&self) -> Option { match self { Self::Unwind { .. } => None, Self::Continue { block_number } => Some(*block_number), diff --git a/crates/stages/api/src/pipeline/mod.rs b/crates/stages/api/src/pipeline/mod.rs index c223c7192..e8c0cefd7 100644 --- a/crates/stages/api/src/pipeline/mod.rs +++ b/crates/stages/api/src/pipeline/mod.rs @@ -94,7 +94,7 @@ where /// Return the minimum block number achieved by /// any stage during the execution of the pipeline. - pub fn minimum_block_number(&self) -> Option { + pub const fn minimum_block_number(&self) -> Option { self.progress.minimum_block_number } diff --git a/crates/stages/api/src/pipeline/progress.rs b/crates/stages/api/src/pipeline/progress.rs index e47d4e89f..4bb184854 100644 --- a/crates/stages/api/src/pipeline/progress.rs +++ b/crates/stages/api/src/pipeline/progress.rs @@ -19,7 +19,7 @@ impl PipelineProgress { } /// Get next control flow step - pub(crate) fn next_ctrl(&self) -> ControlFlow { + pub(crate) const fn next_ctrl(&self) -> ControlFlow { match self.block_number { Some(block_number) => ControlFlow::Continue { block_number }, None => ControlFlow::NoProgress { block_number: None }, diff --git a/crates/stages/api/src/stage.rs b/crates/stages/api/src/stage.rs index 0bb03a8e0..b344fff83 100644 --- a/crates/stages/api/src/stage.rs +++ b/crates/stages/api/src/stage.rs @@ -51,7 +51,7 @@ impl ExecInput { } /// Return true if this is the first block range to execute. - pub fn is_first_range(&self) -> bool { + pub const fn is_first_range(&self) -> bool { self.checkpoint.is_none() } @@ -167,7 +167,7 @@ pub struct ExecOutput { impl ExecOutput { /// Mark the stage as done, checkpointing at the given place. - pub fn done(checkpoint: StageCheckpoint) -> Self { + pub const fn done(checkpoint: StageCheckpoint) -> Self { Self { checkpoint, done: true } } } diff --git a/crates/stages/stages/src/sets.rs b/crates/stages/stages/src/sets.rs index 1f88b29aa..4ba738bbf 100644 --- a/crates/stages/stages/src/sets.rs +++ b/crates/stages/stages/src/sets.rs @@ -262,7 +262,11 @@ pub struct OfflineStages { impl OfflineStages { /// Create a new set of offline stages with default values. - pub fn new(executor_factory: EF, stages_config: StageConfig, prune_modes: PruneModes) -> Self { + pub const fn new( + executor_factory: EF, + stages_config: StageConfig, + prune_modes: PruneModes, + ) -> Self { Self { executor_factory, stages_config, prune_modes } } } @@ -301,7 +305,11 @@ pub struct ExecutionStages { impl ExecutionStages { /// Create a new set of execution stages with default values. - pub fn new(executor_factory: E, stages_config: StageConfig, prune_modes: PruneModes) -> Self { + pub const fn new( + executor_factory: E, + stages_config: StageConfig, + prune_modes: PruneModes, + ) -> Self { Self { executor_factory, stages_config, prune_modes } } } diff --git a/crates/stages/stages/src/stages/bodies.rs b/crates/stages/stages/src/stages/bodies.rs index 19d9cdcf8..aecd2d5f8 100644 --- a/crates/stages/stages/src/stages/bodies.rs +++ b/crates/stages/stages/src/stages/bodies.rs @@ -68,7 +68,7 @@ pub struct BodyStage { impl BodyStage { /// Create new bodies stage from downloader. - pub fn new(downloader: D) -> Self { + pub const fn new(downloader: D) -> Self { Self { downloader, buffer: None } } } diff --git a/crates/stages/stages/src/stages/execution.rs b/crates/stages/stages/src/stages/execution.rs index cee62b3b3..2388d0d6f 100644 --- a/crates/stages/stages/src/stages/execution.rs +++ b/crates/stages/stages/src/stages/execution.rs @@ -81,7 +81,7 @@ pub struct ExecutionStage { impl ExecutionStage { /// Create new execution stage with specified config. - pub fn new( + pub const fn new( executor_provider: E, thresholds: ExecutionStageThresholds, external_clean_threshold: u64, diff --git a/crates/stages/stages/src/stages/hashing_account.rs b/crates/stages/stages/src/stages/hashing_account.rs index 3dcb4cd3b..fc1ab881b 100644 --- a/crates/stages/stages/src/stages/hashing_account.rs +++ b/crates/stages/stages/src/stages/hashing_account.rs @@ -44,7 +44,7 @@ pub struct AccountHashingStage { impl AccountHashingStage { /// Create new instance of [AccountHashingStage]. - pub fn new(config: HashingConfig, etl_config: EtlConfig) -> Self { + pub const fn new(config: HashingConfig, etl_config: EtlConfig) -> Self { Self { clean_threshold: config.clean_threshold, commit_threshold: config.commit_threshold, diff --git a/crates/stages/stages/src/stages/hashing_storage.rs b/crates/stages/stages/src/stages/hashing_storage.rs index 0ab52f32f..0e5f44bbd 100644 --- a/crates/stages/stages/src/stages/hashing_storage.rs +++ b/crates/stages/stages/src/stages/hashing_storage.rs @@ -45,7 +45,7 @@ pub struct StorageHashingStage { impl StorageHashingStage { /// Create new instance of [StorageHashingStage]. - pub fn new(config: HashingConfig, etl_config: EtlConfig) -> Self { + pub const fn new(config: HashingConfig, etl_config: EtlConfig) -> Self { Self { clean_threshold: config.clean_threshold, commit_threshold: config.commit_threshold, diff --git a/crates/stages/stages/src/stages/index_account_history.rs b/crates/stages/stages/src/stages/index_account_history.rs index 0bdc17967..7b41334aa 100644 --- a/crates/stages/stages/src/stages/index_account_history.rs +++ b/crates/stages/stages/src/stages/index_account_history.rs @@ -30,7 +30,7 @@ pub struct IndexAccountHistoryStage { impl IndexAccountHistoryStage { /// Create new instance of [IndexAccountHistoryStage]. - pub fn new( + pub const fn new( config: IndexHistoryConfig, etl_config: EtlConfig, prune_mode: Option, @@ -170,12 +170,12 @@ mod tests { const LAST_BLOCK_IN_FULL_SHARD: BlockNumber = NUM_OF_INDICES_IN_SHARD as BlockNumber; const MAX_BLOCK: BlockNumber = NUM_OF_INDICES_IN_SHARD as BlockNumber + 2; - fn acc() -> AccountBeforeTx { + const fn acc() -> AccountBeforeTx { AccountBeforeTx { address: ADDRESS, info: None } } /// Shard for account - fn shard(shard_index: u64) -> ShardedKey
{ + const fn shard(shard_index: u64) -> ShardedKey
{ ShardedKey { key: ADDRESS, highest_block_number: shard_index } } diff --git a/crates/stages/stages/src/stages/index_storage_history.rs b/crates/stages/stages/src/stages/index_storage_history.rs index 70a852001..0b3556396 100644 --- a/crates/stages/stages/src/stages/index_storage_history.rs +++ b/crates/stages/stages/src/stages/index_storage_history.rs @@ -34,7 +34,7 @@ pub struct IndexStorageHistoryStage { impl IndexStorageHistoryStage { /// Create new instance of [IndexStorageHistoryStage]. - pub fn new( + pub const fn new( config: IndexHistoryConfig, etl_config: EtlConfig, prune_mode: Option, @@ -179,17 +179,17 @@ mod tests { const LAST_BLOCK_IN_FULL_SHARD: BlockNumber = NUM_OF_INDICES_IN_SHARD as BlockNumber; const MAX_BLOCK: BlockNumber = NUM_OF_INDICES_IN_SHARD as BlockNumber + 2; - fn storage(key: B256) -> StorageEntry { + const fn storage(key: B256) -> StorageEntry { // Value is not used in indexing stage. StorageEntry { key, value: U256::ZERO } } - fn block_number_address(block_number: u64) -> BlockNumberAddress { + const fn block_number_address(block_number: u64) -> BlockNumberAddress { BlockNumberAddress((block_number, ADDRESS)) } /// Shard for account - fn shard(shard_index: u64) -> StorageShardedKey { + const fn shard(shard_index: u64) -> StorageShardedKey { StorageShardedKey { address: ADDRESS, sharded_key: ShardedKey { key: STORAGE_KEY, highest_block_number: shard_index }, diff --git a/crates/stages/stages/src/stages/merkle.rs b/crates/stages/stages/src/stages/merkle.rs index b4b7aec48..4286d4069 100644 --- a/crates/stages/stages/src/stages/merkle.rs +++ b/crates/stages/stages/src/stages/merkle.rs @@ -85,17 +85,17 @@ pub enum MerkleStage { impl MerkleStage { /// Stage default for the [MerkleStage::Execution]. - pub fn default_execution() -> Self { + pub const fn default_execution() -> Self { Self::Execution { clean_threshold: MERKLE_STAGE_DEFAULT_CLEAN_THRESHOLD } } /// Stage default for the [MerkleStage::Unwind]. - pub fn default_unwind() -> Self { + pub const fn default_unwind() -> Self { Self::Unwind } /// Create new instance of [MerkleStage::Execution]. - pub fn new_execution(clean_threshold: u64) -> Self { + pub const fn new_execution(clean_threshold: u64) -> Self { Self::Execution { clean_threshold } } diff --git a/crates/stages/stages/src/stages/sender_recovery.rs b/crates/stages/stages/src/stages/sender_recovery.rs index 28e3df51e..e66527106 100644 --- a/crates/stages/stages/src/stages/sender_recovery.rs +++ b/crates/stages/stages/src/stages/sender_recovery.rs @@ -43,7 +43,7 @@ pub struct SenderRecoveryStage { impl SenderRecoveryStage { /// Create new instance of [SenderRecoveryStage]. - pub fn new(config: SenderRecoveryConfig) -> Self { + pub const fn new(config: SenderRecoveryConfig) -> Self { Self { commit_threshold: config.commit_threshold } } } diff --git a/crates/stages/stages/src/stages/tx_lookup.rs b/crates/stages/stages/src/stages/tx_lookup.rs index 9f1704958..27e8e68cf 100644 --- a/crates/stages/stages/src/stages/tx_lookup.rs +++ b/crates/stages/stages/src/stages/tx_lookup.rs @@ -45,7 +45,7 @@ impl Default for TransactionLookupStage { impl TransactionLookupStage { /// Create new instance of [TransactionLookupStage]. - pub fn new( + pub const fn new( config: TransactionLookupConfig, etl_config: EtlConfig, prune_mode: Option, diff --git a/crates/stages/stages/src/stages/utils.rs b/crates/stages/stages/src/stages/utils.rs index be0ecc7f6..97cb5497e 100644 --- a/crates/stages/stages/src/stages/utils.rs +++ b/crates/stages/stages/src/stages/utils.rs @@ -238,7 +238,7 @@ pub(crate) enum LoadMode { } impl LoadMode { - fn is_flush(&self) -> bool { + const fn is_flush(&self) -> bool { matches!(self, Self::Flush) } } diff --git a/crates/stages/stages/src/test_utils/test_db.rs b/crates/stages/stages/src/test_utils/test_db.rs index 5998fc878..234aace74 100644 --- a/crates/stages/stages/src/test_utils/test_db.rs +++ b/crates/stages/stages/src/test_utils/test_db.rs @@ -436,11 +436,11 @@ pub enum StorageKind { impl StorageKind { #[allow(dead_code)] - fn is_database(&self) -> bool { + const fn is_database(&self) -> bool { matches!(self, Self::Database(_)) } - fn is_static(&self) -> bool { + const fn is_static(&self) -> bool { matches!(self, Self::Static) } diff --git a/crates/static-file-types/src/lib.rs b/crates/static-file-types/src/lib.rs index 26d249694..f78d61f69 100644 --- a/crates/static-file-types/src/lib.rs +++ b/crates/static-file-types/src/lib.rs @@ -36,7 +36,7 @@ pub struct HighestStaticFiles { impl HighestStaticFiles { /// Returns the highest static file if it exists for a segment - pub fn highest(&self, segment: StaticFileSegment) -> Option { + pub const fn highest(&self, segment: StaticFileSegment) -> Option { match segment { StaticFileSegment::Headers => self.headers, StaticFileSegment::Transactions => self.transactions, @@ -61,7 +61,7 @@ impl HighestStaticFiles { /// Each static file has a fixed number of blocks. This gives out the range where the requested /// block is positioned. Used for segment filename. -pub fn find_fixed_range(block: BlockNumber) -> SegmentRangeInclusive { +pub const fn find_fixed_range(block: BlockNumber) -> SegmentRangeInclusive { let start = (block / BLOCKS_PER_STATIC_FILE) * BLOCKS_PER_STATIC_FILE; SegmentRangeInclusive::new(start, start + BLOCKS_PER_STATIC_FILE - 1) } diff --git a/crates/static-file-types/src/segment.rs b/crates/static-file-types/src/segment.rs index d85d33dc2..a69fab525 100644 --- a/crates/static-file-types/src/segment.rs +++ b/crates/static-file-types/src/segment.rs @@ -133,7 +133,7 @@ impl StaticFileSegment { } /// Returns `true` if the segment is `StaticFileSegment::Headers`. - pub fn is_headers(&self) -> bool { + pub const fn is_headers(&self) -> bool { matches!(self, Self::Headers) } } @@ -156,7 +156,7 @@ pub struct SegmentHeader { impl SegmentHeader { /// Returns [`SegmentHeader`]. - pub fn new( + pub const fn new( expected_block_range: SegmentRangeInclusive, block_range: Option, tx_range: Option, @@ -166,27 +166,27 @@ impl SegmentHeader { } /// Returns the static file segment kind. - pub fn segment(&self) -> StaticFileSegment { + pub const fn segment(&self) -> StaticFileSegment { self.segment } /// Returns the block range. - pub fn block_range(&self) -> Option<&SegmentRangeInclusive> { + pub const fn block_range(&self) -> Option<&SegmentRangeInclusive> { self.block_range.as_ref() } /// Returns the transaction range. - pub fn tx_range(&self) -> Option<&SegmentRangeInclusive> { + pub const fn tx_range(&self) -> Option<&SegmentRangeInclusive> { self.tx_range.as_ref() } /// The expected block start of the segment. - pub fn expected_block_start(&self) -> BlockNumber { + pub const fn expected_block_start(&self) -> BlockNumber { self.expected_block_range.start() } /// The expected block end of the segment. - pub fn expected_block_end(&self) -> BlockNumber { + pub const fn expected_block_end(&self) -> BlockNumber { self.expected_block_range.end() } @@ -200,17 +200,17 @@ impl SegmentHeader { self.block_range.as_ref().map(|b| b.end()) } - /// Returns the first transaction number of the segment. + /// Returns the first transaction number of the segment. pub fn tx_start(&self) -> Option { self.tx_range.as_ref().map(|t| t.start()) } - /// Returns the last transaction number of the segment. + /// Returns the last transaction number of the segment. pub fn tx_end(&self) -> Option { self.tx_range.as_ref().map(|t| t.end()) } - /// Number of transactions. + /// Number of transactions. pub fn tx_len(&self) -> Option { self.tx_range.as_ref().map(|r| (r.end() + 1) - r.start()) } @@ -321,17 +321,17 @@ pub struct SegmentRangeInclusive { impl SegmentRangeInclusive { /// Creates a new [`SegmentRangeInclusive`] - pub fn new(start: u64, end: u64) -> Self { + pub const fn new(start: u64, end: u64) -> Self { Self { start, end } } /// Start of the inclusive range - pub fn start(&self) -> u64 { + pub const fn start(&self) -> u64 { self.start } /// End of the inclusive range - pub fn end(&self) -> u64 { + pub const fn end(&self) -> u64 { self.end } } diff --git a/crates/static-file/src/static_file_producer.rs b/crates/static-file/src/static_file_producer.rs index 1f9cfd129..549398e03 100644 --- a/crates/static-file/src/static_file_producer.rs +++ b/crates/static-file/src/static_file_producer.rs @@ -76,7 +76,7 @@ pub struct StaticFileTargets { impl StaticFileTargets { /// Returns `true` if any of the targets are [Some]. - pub fn any(&self) -> bool { + pub const fn any(&self) -> bool { self.headers.is_some() || self.receipts.is_some() || self.transactions.is_some() } diff --git a/crates/storage/db/benches/iai.rs b/crates/storage/db/benches/iai.rs index 5ba0f2b36..62e97d6ef 100644 --- a/crates/storage/db/benches/iai.rs +++ b/crates/storage/db/benches/iai.rs @@ -44,16 +44,16 @@ macro_rules! impl_iai_callgrind_inner { } #[allow(dead_code)] - pub fn $seqread() {} + pub const fn $seqread() {} #[allow(dead_code)] - pub fn $randread() {} + pub const fn $randread() {} #[allow(dead_code)] - pub fn $seqwrite() {} + pub const fn $seqwrite() {} #[allow(dead_code)] - pub fn $randwrite() {} + pub const fn $randwrite() {} library_benchmark_group!( diff --git a/crates/storage/db/src/abstraction/database_metrics.rs b/crates/storage/db/src/abstraction/database_metrics.rs index 10f0e476e..364bfc928 100644 --- a/crates/storage/db/src/abstraction/database_metrics.rs +++ b/crates/storage/db/src/abstraction/database_metrics.rs @@ -50,12 +50,12 @@ pub struct DatabaseMetadataValue { impl DatabaseMetadataValue { /// Creates a new [DatabaseMetadataValue] with the given freelist size. - pub fn new(freelist_size: Option) -> Self { + pub const fn new(freelist_size: Option) -> Self { Self { freelist_size } } /// Returns the freelist size, if available. - pub fn freelist_size(&self) -> Option { + pub const fn freelist_size(&self) -> Option { self.freelist_size } } diff --git a/crates/storage/db/src/implementation/mdbx/mod.rs b/crates/storage/db/src/implementation/mdbx/mod.rs index 6f19bd911..14d340fec 100644 --- a/crates/storage/db/src/implementation/mdbx/mod.rs +++ b/crates/storage/db/src/implementation/mdbx/mod.rs @@ -52,7 +52,7 @@ pub enum DatabaseEnvKind { impl DatabaseEnvKind { /// Returns `true` if the environment is read-write. - pub fn is_rw(&self) -> bool { + pub const fn is_rw(&self) -> bool { matches!(self, Self::RW) } } @@ -91,7 +91,7 @@ pub struct DatabaseArguments { impl DatabaseArguments { /// Create new database arguments with given client version. - pub fn new(client_version: ClientVersion) -> Self { + pub const fn new(client_version: ClientVersion) -> Self { Self { client_version, log_level: None, @@ -101,13 +101,13 @@ impl DatabaseArguments { } /// Set the log level. - pub fn with_log_level(mut self, log_level: Option) -> Self { + pub const fn with_log_level(mut self, log_level: Option) -> Self { self.log_level = log_level; self } /// Set the maximum duration of a read transaction. - pub fn with_max_read_transaction_duration( + pub const fn with_max_read_transaction_duration( mut self, max_read_transaction_duration: Option, ) -> Self { @@ -116,13 +116,13 @@ impl DatabaseArguments { } /// Set the mdbx exclusive flag. - pub fn with_exclusive(mut self, exclusive: Option) -> Self { + pub const fn with_exclusive(mut self, exclusive: Option) -> Self { self.exclusive = exclusive; self } /// Returns the client version if any. - pub fn client_version(&self) -> &ClientVersion { + pub const fn client_version(&self) -> &ClientVersion { &self.client_version } } diff --git a/crates/storage/db/src/implementation/mdbx/tx.rs b/crates/storage/db/src/implementation/mdbx/tx.rs index 184ca4d1c..962051832 100644 --- a/crates/storage/db/src/implementation/mdbx/tx.rs +++ b/crates/storage/db/src/implementation/mdbx/tx.rs @@ -45,7 +45,7 @@ pub struct Tx { impl Tx { /// Creates new `Tx` object with a `RO` or `RW` transaction. #[inline] - pub fn new(inner: Transaction) -> Self { + pub const fn new(inner: Transaction) -> Self { Self::new_inner(inner, None) } @@ -68,7 +68,7 @@ impl Tx { } #[inline] - fn new_inner(inner: Transaction, metrics_handler: Option>) -> Self { + const fn new_inner(inner: Transaction, metrics_handler: Option>) -> Self { // NOTE: These constants are needed to initialize `OnceCell` at compile-time, as array // initialization is not allowed with non-Copy types, and `const { }` blocks are not stable // yet. diff --git a/crates/storage/db/src/metrics.rs b/crates/storage/db/src/metrics.rs index 16d19beb5..2dd4be2ac 100644 --- a/crates/storage/db/src/metrics.rs +++ b/crates/storage/db/src/metrics.rs @@ -248,7 +248,7 @@ enum Labels { impl Labels { /// Converts each label variant into its corresponding string representation. - pub(crate) fn as_str(&self) -> &'static str { + pub(crate) const fn as_str(&self) -> &'static str { match self { Self::Table => "table", Self::TransactionMode => "mode", diff --git a/crates/storage/db/src/tables/models/accounts.rs b/crates/storage/db/src/tables/models/accounts.rs index 9549aa8e6..86d0b19f0 100644 --- a/crates/storage/db/src/tables/models/accounts.rs +++ b/crates/storage/db/src/tables/models/accounts.rs @@ -75,17 +75,17 @@ impl BlockNumberAddress { } /// Return the block number - pub fn block_number(&self) -> BlockNumber { + pub const fn block_number(&self) -> BlockNumber { self.0 .0 } /// Return the address - pub fn address(&self) -> Address { + pub const fn address(&self) -> Address { self.0 .1 } /// Consumes `Self` and returns [`BlockNumber`], [`Address`] - pub fn take(self) -> (BlockNumber, Address) { + pub const fn take(self) -> (BlockNumber, Address) { (self.0 .0, self.0 .1) } } diff --git a/crates/storage/db/src/tables/models/blocks.rs b/crates/storage/db/src/tables/models/blocks.rs index 62378612a..633c15d7a 100644 --- a/crates/storage/db/src/tables/models/blocks.rs +++ b/crates/storage/db/src/tables/models/blocks.rs @@ -28,14 +28,14 @@ pub struct StoredBlockBodyIndices { impl StoredBlockBodyIndices { /// Return the range of transaction ids for this block. - pub fn tx_num_range(&self) -> Range { + pub const fn tx_num_range(&self) -> Range { self.first_tx_num..self.first_tx_num + self.tx_count } /// Return the index of last transaction in this block unless the block /// is empty in which case it refers to the last transaction in a previous /// non-empty block - pub fn last_tx_num(&self) -> TxNumber { + pub const fn last_tx_num(&self) -> TxNumber { self.first_tx_num.saturating_add(self.tx_count).saturating_sub(1) } @@ -43,24 +43,24 @@ impl StoredBlockBodyIndices { /// /// Caution: If the block is empty, this is the number of the first transaction /// in the next non-empty block. - pub fn first_tx_num(&self) -> TxNumber { + pub const fn first_tx_num(&self) -> TxNumber { self.first_tx_num } /// Return the index of the next transaction after this block. - pub fn next_tx_num(&self) -> TxNumber { + pub const fn next_tx_num(&self) -> TxNumber { self.first_tx_num + self.tx_count } /// Return a flag whether the block is empty - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.tx_count == 0 } /// Return number of transaction inside block /// /// NOTE: This is not the same as the number of transitions. - pub fn tx_count(&self) -> NumTransactions { + pub const fn tx_count(&self) -> NumTransactions { self.tx_count } } diff --git a/crates/storage/db/src/tables/models/sharded_key.rs b/crates/storage/db/src/tables/models/sharded_key.rs index 3a55baeda..fdcae7551 100644 --- a/crates/storage/db/src/tables/models/sharded_key.rs +++ b/crates/storage/db/src/tables/models/sharded_key.rs @@ -34,13 +34,13 @@ impl AsRef for ShardedKey { impl ShardedKey { /// Creates a new `ShardedKey`. - pub fn new(key: T, highest_block_number: BlockNumber) -> Self { + pub const fn new(key: T, highest_block_number: BlockNumber) -> Self { Self { key, highest_block_number } } /// Creates a new key with the highest block number set to maximum. /// This is useful when we want to search the last value for a given key. - pub fn last(key: T) -> Self { + pub const fn last(key: T) -> Self { Self { key, highest_block_number: u64::MAX } } } diff --git a/crates/storage/db/src/tables/models/storage_sharded_key.rs b/crates/storage/db/src/tables/models/storage_sharded_key.rs index e0d9faa1f..19c82140f 100644 --- a/crates/storage/db/src/tables/models/storage_sharded_key.rs +++ b/crates/storage/db/src/tables/models/storage_sharded_key.rs @@ -32,13 +32,17 @@ pub struct StorageShardedKey { impl StorageShardedKey { /// Creates a new `StorageShardedKey`. - pub fn new(address: Address, storage_key: B256, highest_block_number: BlockNumber) -> Self { + pub const fn new( + address: Address, + storage_key: B256, + highest_block_number: BlockNumber, + ) -> Self { Self { address, sharded_key: ShardedKey { key: storage_key, highest_block_number } } } /// Creates a new key with the highest block number set to maximum. /// This is useful when we want to search the last value for a given key. - pub fn last(address: Address, storage_key: B256) -> Self { + pub const fn last(address: Address, storage_key: B256) -> Self { Self { address, sharded_key: ShardedKey { key: storage_key, highest_block_number: u64::MAX }, diff --git a/crates/storage/db/src/tables/raw.rs b/crates/storage/db/src/tables/raw.rs index 21bcc281c..0ece7b3ba 100644 --- a/crates/storage/db/src/tables/raw.rs +++ b/crates/storage/db/src/tables/raw.rs @@ -65,7 +65,7 @@ impl RawKey { } /// Returns the raw key as seen on the database. - pub fn raw_key(&self) -> &Vec { + pub const fn raw_key(&self) -> &Vec { &self.key } diff --git a/crates/storage/libmdbx-rs/src/cursor.rs b/crates/storage/libmdbx-rs/src/cursor.rs index 6cb4e6149..ae642a52b 100644 --- a/crates/storage/libmdbx-rs/src/cursor.rs +++ b/crates/storage/libmdbx-rs/src/cursor.rs @@ -55,7 +55,7 @@ where /// /// The caller **must** ensure that the pointer is not used after the /// lifetime of the cursor. - pub fn cursor(&self) -> *mut ffi::MDBX_cursor { + pub const fn cursor(&self) -> *mut ffi::MDBX_cursor { self.cursor } @@ -491,7 +491,7 @@ where } } -unsafe fn slice_to_val(slice: Option<&[u8]>) -> ffi::MDBX_val { +const unsafe fn slice_to_val(slice: Option<&[u8]>) -> ffi::MDBX_val { match slice { Some(slice) => { ffi::MDBX_val { iov_len: slice.len(), iov_base: slice.as_ptr() as *mut c_void } diff --git a/crates/storage/libmdbx-rs/src/database.rs b/crates/storage/libmdbx-rs/src/database.rs index 4e3a6c062..1c4739b2b 100644 --- a/crates/storage/libmdbx-rs/src/database.rs +++ b/crates/storage/libmdbx-rs/src/database.rs @@ -36,12 +36,12 @@ impl Database { Ok(Self::new_from_ptr(dbi, txn.env().clone())) } - pub(crate) fn new_from_ptr(dbi: ffi::MDBX_dbi, env: Environment) -> Self { + pub(crate) const fn new_from_ptr(dbi: ffi::MDBX_dbi, env: Environment) -> Self { Self { dbi, _env: Some(env) } } /// Opens the freelist database with DBI `0`. - pub fn freelist_db() -> Self { + pub const fn freelist_db() -> Self { Self { dbi: 0, _env: None } } @@ -49,7 +49,7 @@ impl Database { /// /// The caller **must** ensure that the handle is not used after the lifetime of the /// environment, or after the database has been closed. - pub fn dbi(&self) -> ffi::MDBX_dbi { + pub const fn dbi(&self) -> ffi::MDBX_dbi { self.dbi } } diff --git a/crates/storage/libmdbx-rs/src/environment.rs b/crates/storage/libmdbx-rs/src/environment.rs index c6d206435..32be47949 100644 --- a/crates/storage/libmdbx-rs/src/environment.rs +++ b/crates/storage/libmdbx-rs/src/environment.rs @@ -285,7 +285,7 @@ impl EnvironmentKind { } /// Additional flags required when opening the environment. - pub(crate) fn extra_flags(&self) -> ffi::MDBX_env_flags_t { + pub(crate) const fn extra_flags(&self) -> ffi::MDBX_env_flags_t { match self { Self::Default => ffi::MDBX_ENV_DEFAULTS, Self::WriteMap => ffi::MDBX_WRITEMAP, @@ -307,7 +307,7 @@ pub struct Stat(ffi::MDBX_stat); impl Stat { /// Create a new Stat with zero'd inner struct `ffi::MDB_stat`. - pub(crate) fn new() -> Self { + pub(crate) const fn new() -> Self { unsafe { Self(mem::zeroed()) } } @@ -320,37 +320,37 @@ impl Stat { impl Stat { /// Size of a database page. This is the same for all databases in the environment. #[inline] - pub fn page_size(&self) -> u32 { + pub const fn page_size(&self) -> u32 { self.0.ms_psize } /// Depth (height) of the B-tree. #[inline] - pub fn depth(&self) -> u32 { + pub const fn depth(&self) -> u32 { self.0.ms_depth } /// Number of internal (non-leaf) pages. #[inline] - pub fn branch_pages(&self) -> usize { + pub const fn branch_pages(&self) -> usize { self.0.ms_branch_pages as usize } /// Number of leaf pages. #[inline] - pub fn leaf_pages(&self) -> usize { + pub const fn leaf_pages(&self) -> usize { self.0.ms_leaf_pages as usize } /// Number of overflow pages. #[inline] - pub fn overflow_pages(&self) -> usize { + pub const fn overflow_pages(&self) -> usize { self.0.ms_overflow_pages as usize } /// Number of data items. #[inline] - pub fn entries(&self) -> usize { + pub const fn entries(&self) -> usize { self.0.ms_entries as usize } } @@ -360,7 +360,7 @@ impl Stat { pub struct GeometryInfo(ffi::MDBX_envinfo__bindgen_ty_1); impl GeometryInfo { - pub fn min(&self) -> u64 { + pub const fn min(&self) -> u64 { self.0.lower } } @@ -373,43 +373,43 @@ impl GeometryInfo { pub struct Info(ffi::MDBX_envinfo); impl Info { - pub fn geometry(&self) -> GeometryInfo { + pub const fn geometry(&self) -> GeometryInfo { GeometryInfo(self.0.mi_geo) } /// Size of memory map. #[inline] - pub fn map_size(&self) -> usize { + pub const fn map_size(&self) -> usize { self.0.mi_mapsize as usize } /// Last used page number #[inline] - pub fn last_pgno(&self) -> usize { + pub const fn last_pgno(&self) -> usize { self.0.mi_last_pgno as usize } /// Last transaction ID #[inline] - pub fn last_txnid(&self) -> usize { + pub const fn last_txnid(&self) -> usize { self.0.mi_recent_txnid as usize } /// Max reader slots in the environment #[inline] - pub fn max_readers(&self) -> usize { + pub const fn max_readers(&self) -> usize { self.0.mi_maxreaders as usize } /// Max reader slots used in the environment #[inline] - pub fn num_readers(&self) -> usize { + pub const fn num_readers(&self) -> usize { self.0.mi_numreaders as usize } /// Return the internal page ops metrics #[inline] - pub fn page_ops(&self) -> PageOps { + pub const fn page_ops(&self) -> PageOps { PageOps { newly: self.0.mi_pgop_stat.newly, cow: self.0.mi_pgop_stat.cow, @@ -857,7 +857,7 @@ pub(crate) mod read_transactions { #[cfg(feature = "read-tx-timeouts")] impl MaxReadTransactionDuration { - pub fn as_duration(&self) -> Option { + pub const fn as_duration(&self) -> Option { match self { 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 4776cc4ae..27d781e53 100644 --- a/crates/storage/libmdbx-rs/src/error.rs +++ b/crates/storage/libmdbx-rs/src/error.rs @@ -127,7 +127,7 @@ pub enum Error { impl Error { /// Converts a raw error code to an [Error]. - pub fn from_err_code(err_code: c_int) -> Self { + pub const fn from_err_code(err_code: c_int) -> Self { match err_code { ffi::MDBX_KEYEXIST => Self::KeyExist, ffi::MDBX_NOTFOUND => Self::NotFound, @@ -163,7 +163,7 @@ impl Error { } /// Converts an [Error] to the raw error code. - pub fn to_err_code(&self) -> i32 { + pub const fn to_err_code(&self) -> i32 { match self { Self::KeyExist => ffi::MDBX_KEYEXIST, Self::NotFound => ffi::MDBX_NOTFOUND, @@ -209,7 +209,7 @@ impl From for i32 { } #[inline] -pub(crate) fn mdbx_result(err_code: c_int) -> Result { +pub(crate) const fn mdbx_result(err_code: c_int) -> Result { match err_code { ffi::MDBX_SUCCESS => Ok(false), ffi::MDBX_RESULT_TRUE => Ok(true), diff --git a/crates/storage/libmdbx-rs/src/flags.rs b/crates/storage/libmdbx-rs/src/flags.rs index 843ae161c..883ed3faf 100644 --- a/crates/storage/libmdbx-rs/src/flags.rs +++ b/crates/storage/libmdbx-rs/src/flags.rs @@ -142,7 +142,7 @@ pub struct EnvironmentFlags { impl EnvironmentFlags { /// Configures the mdbx flags to use when opening the environment. - pub(crate) fn make_flags(&self) -> ffi::MDBX_env_flags_t { + pub(crate) const fn make_flags(&self) -> ffi::MDBX_env_flags_t { let mut flags = 0; if self.no_sub_dir { diff --git a/crates/storage/libmdbx-rs/src/transaction.rs b/crates/storage/libmdbx-rs/src/transaction.rs index 20fcddead..1bffc9f47 100644 --- a/crates/storage/libmdbx-rs/src/transaction.rs +++ b/crates/storage/libmdbx-rs/src/transaction.rs @@ -612,7 +612,7 @@ pub struct CommitLatency(ffi::MDBX_commit_latency); impl CommitLatency { /// Create a new CommitLatency with zero'd inner struct `ffi::MDBX_commit_latency`. - pub(crate) fn new() -> Self { + pub(crate) const fn new() -> Self { unsafe { Self(std::mem::zeroed()) } } @@ -626,56 +626,56 @@ impl CommitLatency { /// Duration of preparation (commit child transactions, update /// sub-databases records and cursors destroying). #[inline] - pub fn preparation(&self) -> Duration { + pub const fn preparation(&self) -> Duration { Self::time_to_duration(self.0.preparation) } /// Duration of GC update by wall clock. #[inline] - pub fn gc_wallclock(&self) -> Duration { + pub const fn gc_wallclock(&self) -> Duration { Self::time_to_duration(self.0.gc_wallclock) } /// Duration of internal audit if enabled. #[inline] - pub fn audit(&self) -> Duration { + pub const fn audit(&self) -> Duration { Self::time_to_duration(self.0.audit) } /// Duration of writing dirty/modified data pages to a filesystem, /// i.e. the summary duration of a `write()` syscalls during commit. #[inline] - pub fn write(&self) -> Duration { + pub const fn write(&self) -> Duration { Self::time_to_duration(self.0.write) } /// Duration of syncing written data to the disk/storage, i.e. /// the duration of a `fdatasync()` or a `msync()` syscall during commit. #[inline] - pub fn sync(&self) -> Duration { + pub const fn sync(&self) -> Duration { Self::time_to_duration(self.0.sync) } /// Duration of transaction ending (releasing resources). #[inline] - pub fn ending(&self) -> Duration { + pub const fn ending(&self) -> Duration { Self::time_to_duration(self.0.ending) } /// The total duration of a commit. #[inline] - pub fn whole(&self) -> Duration { + pub const fn whole(&self) -> Duration { Self::time_to_duration(self.0.whole) } /// User-mode CPU time spent on GC update. #[inline] - pub fn gc_cputime(&self) -> Duration { + pub const fn gc_cputime(&self) -> Duration { Self::time_to_duration(self.0.gc_cputime) } #[inline] - fn time_to_duration(time: u32) -> Duration { + const fn time_to_duration(time: u32) -> Duration { Duration::from_nanos(time as u64 * (1_000_000_000 / 65_536)) } } @@ -690,10 +690,10 @@ unsafe impl Sync for TransactionPtr {} mod tests { use super::*; - fn assert_send_sync() {} + const fn assert_send_sync() {} #[allow(dead_code)] - fn test_txn_send_sync() { + const fn test_txn_send_sync() { assert_send_sync::>(); assert_send_sync::>(); } diff --git a/crates/storage/nippy-jar/src/compression/zstd.rs b/crates/storage/nippy-jar/src/compression/zstd.rs index 5cf0dbee0..c55ca103a 100644 --- a/crates/storage/nippy-jar/src/compression/zstd.rs +++ b/crates/storage/nippy-jar/src/compression/zstd.rs @@ -40,7 +40,7 @@ pub struct Zstd { impl Zstd { /// Creates new [`Zstd`]. - pub fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self { + pub const fn new(use_dict: bool, max_dict_size: usize, columns: usize) -> Self { Self { state: if use_dict { ZstdState::PendingDictionary } else { ZstdState::Ready }, level: 0, @@ -51,7 +51,7 @@ impl Zstd { } } - pub fn with_level(mut self, level: i32) -> Self { + pub const fn with_level(mut self, level: i32) -> Self { self.level = level; self } @@ -321,7 +321,7 @@ pub(crate) enum ZstdDictionary<'a> { impl<'a> ZstdDictionary<'a> { /// Returns a reference to the expected `RawDictionary` - pub(crate) fn raw(&self) -> Option<&RawDictionary> { + pub(crate) const fn raw(&self) -> Option<&RawDictionary> { match self { ZstdDictionary::Raw(dict) => Some(dict), ZstdDictionary::Loaded(_) => None, @@ -329,7 +329,7 @@ impl<'a> ZstdDictionary<'a> { } /// Returns a reference to the expected `DecoderDictionary` - pub(crate) fn loaded(&self) -> Option<&DecoderDictionary<'_>> { + pub(crate) const fn loaded(&self) -> Option<&DecoderDictionary<'_>> { match self { ZstdDictionary::Raw(_) => None, ZstdDictionary::Loaded(dict) => Some(dict), diff --git a/crates/storage/nippy-jar/src/cursor.rs b/crates/storage/nippy-jar/src/cursor.rs index 541fcfa63..434c40a9a 100644 --- a/crates/storage/nippy-jar/src/cursor.rs +++ b/crates/storage/nippy-jar/src/cursor.rs @@ -53,12 +53,12 @@ impl<'a, H: NippyJarHeader> NippyJarCursor<'a, H> { } /// Returns a reference to the related [`NippyJar`] - pub fn jar(&self) -> &NippyJar { + pub const fn jar(&self) -> &NippyJar { self.jar } /// Returns current row index of the cursor - pub fn row_index(&self) -> u64 { + pub const fn row_index(&self) -> u64 { self.row } diff --git a/crates/storage/nippy-jar/src/lib.rs b/crates/storage/nippy-jar/src/lib.rs index 6a629702b..3258ebd10 100644 --- a/crates/storage/nippy-jar/src/lib.rs +++ b/crates/storage/nippy-jar/src/lib.rs @@ -153,7 +153,7 @@ impl NippyJar<()> { } /// Whether this [`NippyJar`] uses a [`InclusionFilters`] and [`Functions`]. - pub fn uses_filters(&self) -> bool { + pub const fn uses_filters(&self) -> bool { self.filter.is_some() && self.phf.is_some() } } @@ -207,17 +207,17 @@ impl NippyJar { } /// Gets a reference to the user header. - pub fn user_header(&self) -> &H { + pub const fn user_header(&self) -> &H { &self.user_header } /// Gets total columns in jar. - pub fn columns(&self) -> usize { + pub const fn columns(&self) -> usize { self.columns } /// Gets total rows in jar. - pub fn rows(&self) -> usize { + pub const fn rows(&self) -> usize { self.rows } @@ -232,7 +232,7 @@ impl NippyJar { } /// Gets a reference to the compressor. - pub fn compressor(&self) -> Option<&Compressors> { + pub const fn compressor(&self) -> Option<&Compressors> { self.compressor.as_ref() } @@ -543,7 +543,7 @@ impl DataReader { } /// Returns number of bytes that represent one offset. - pub fn offset_size(&self) -> u8 { + pub const fn offset_size(&self) -> u8 { self.offset_size } diff --git a/crates/storage/nippy-jar/src/phf/fmph.rs b/crates/storage/nippy-jar/src/phf/fmph.rs index 7a67ecd3b..a332c40cf 100644 --- a/crates/storage/nippy-jar/src/phf/fmph.rs +++ b/crates/storage/nippy-jar/src/phf/fmph.rs @@ -12,7 +12,7 @@ pub struct Fmph { } impl Fmph { - pub fn new() -> Self { + pub const fn new() -> Self { 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 f0a6507b4..328ddcb4d 100644 --- a/crates/storage/nippy-jar/src/phf/go_fmph.rs +++ b/crates/storage/nippy-jar/src/phf/go_fmph.rs @@ -12,7 +12,7 @@ pub struct GoFmph { } impl GoFmph { - pub fn new() -> Self { + pub const fn new() -> Self { Self { function: None } } } diff --git a/crates/storage/nippy-jar/src/writer.rs b/crates/storage/nippy-jar/src/writer.rs index bd56b4a6b..8bd47b1b4 100644 --- a/crates/storage/nippy-jar/src/writer.rs +++ b/crates/storage/nippy-jar/src/writer.rs @@ -71,7 +71,7 @@ impl NippyJarWriter { } /// Returns a reference to `H` of [`NippyJar`] - pub fn user_header(&self) -> &H { + pub const fn user_header(&self) -> &H { &self.jar.user_header } @@ -81,7 +81,7 @@ impl NippyJarWriter { } /// Gets total writer rows in jar. - pub fn rows(&self) -> usize { + pub const fn rows(&self) -> usize { self.jar.rows() } @@ -451,12 +451,12 @@ impl NippyJarWriter { } #[cfg(test)] - pub fn max_row_size(&self) -> usize { + pub const fn max_row_size(&self) -> usize { self.jar.max_row_size } #[cfg(test)] - pub fn column(&self) -> usize { + pub const fn column(&self) -> usize { self.column } diff --git a/crates/storage/provider/src/providers/bundle_state_provider.rs b/crates/storage/provider/src/providers/bundle_state_provider.rs index bc042b327..123c94308 100644 --- a/crates/storage/provider/src/providers/bundle_state_provider.rs +++ b/crates/storage/provider/src/providers/bundle_state_provider.rs @@ -18,7 +18,7 @@ pub struct BundleStateProvider impl BundleStateProvider { /// Create new bundle state provider - pub fn new(state_provider: SP, bundle_state_data_provider: BSDP) -> Self { + pub const fn new(state_provider: SP, bundle_state_data_provider: BSDP) -> Self { Self { state_provider, bundle_state_data_provider } } } diff --git a/crates/storage/provider/src/providers/consistent_view.rs b/crates/storage/provider/src/providers/consistent_view.rs index b95676813..18035f889 100644 --- a/crates/storage/provider/src/providers/consistent_view.rs +++ b/crates/storage/provider/src/providers/consistent_view.rs @@ -34,7 +34,7 @@ where Provider: DatabaseProviderFactory, { /// Creates new consistent database view. - pub fn new(provider: Provider, tip: Option) -> Self { + pub const fn new(provider: Provider, tip: Option) -> Self { Self { database: PhantomData, provider, tip } } diff --git a/crates/storage/provider/src/providers/database/metrics.rs b/crates/storage/provider/src/providers/database/metrics.rs index 57f67847d..c16ce385c 100644 --- a/crates/storage/provider/src/providers/database/metrics.rs +++ b/crates/storage/provider/src/providers/database/metrics.rs @@ -65,7 +65,7 @@ pub(crate) enum Action { } impl Action { - fn as_str(&self) -> &'static str { + const fn as_str(&self) -> &'static str { match self { Self::InsertStorageHashing => "insert storage hashing", Self::InsertAccountHashing => "insert account hashing", diff --git a/crates/storage/provider/src/providers/database/provider.rs b/crates/storage/provider/src/providers/database/provider.rs index 0a0d318e6..79f2960e7 100644 --- a/crates/storage/provider/src/providers/database/provider.rs +++ b/crates/storage/provider/src/providers/database/provider.rs @@ -108,7 +108,7 @@ pub struct DatabaseProvider { impl DatabaseProvider { /// Returns a static file provider - pub fn static_file_provider(&self) -> &StaticFileProvider { + pub const fn static_file_provider(&self) -> &StaticFileProvider { &self.static_file_provider } } @@ -311,7 +311,7 @@ impl DatabaseProvider { } /// Pass `DbTx` or `DbTxMut` immutable reference. - pub fn tx_ref(&self) -> &TX { + pub const fn tx_ref(&self) -> &TX { &self.tx } diff --git a/crates/storage/provider/src/providers/state/historical.rs b/crates/storage/provider/src/providers/state/historical.rs index f815c282d..e3a72077f 100644 --- a/crates/storage/provider/src/providers/state/historical.rs +++ b/crates/storage/provider/src/providers/state/historical.rs @@ -62,7 +62,7 @@ impl<'b, TX: DbTx> HistoricalStateProviderRef<'b, TX> { /// Create new StateProvider for historical block number and lowest block numbers at which /// account & storage histories are available. - pub fn new_with_lowest_available_blocks( + pub const fn new_with_lowest_available_blocks( tx: &'b TX, block_number: BlockNumber, lowest_available_blocks: LowestAvailableBlocks, @@ -339,7 +339,7 @@ impl HistoricalStateProvider { } /// Set the lowest block number at which the account history is available. - pub fn with_lowest_available_account_history_block_number( + pub const fn with_lowest_available_account_history_block_number( mut self, block_number: BlockNumber, ) -> Self { @@ -348,7 +348,7 @@ impl HistoricalStateProvider { } /// Set the lowest block number at which the storage history is available. - pub fn with_lowest_available_storage_history_block_number( + pub const fn with_lowest_available_storage_history_block_number( mut self, block_number: BlockNumber, ) -> Self { @@ -420,9 +420,9 @@ mod tests { const HIGHER_ADDRESS: Address = address!("0000000000000000000000000000000000000005"); const STORAGE: B256 = b256!("0000000000000000000000000000000000000000000000000000000000000001"); - fn assert_state_provider() {} + const fn assert_state_provider() {} #[allow(dead_code)] - fn assert_historical_state_provider() { + const fn assert_historical_state_provider() { assert_state_provider::>(); } diff --git a/crates/storage/provider/src/providers/state/latest.rs b/crates/storage/provider/src/providers/state/latest.rs index 5079a15d7..eae521abb 100644 --- a/crates/storage/provider/src/providers/state/latest.rs +++ b/crates/storage/provider/src/providers/state/latest.rs @@ -26,7 +26,7 @@ pub struct LatestStateProviderRef<'b, TX: DbTx> { impl<'b, TX: DbTx> LatestStateProviderRef<'b, TX> { /// Create new state provider - pub fn new(tx: &'b TX, static_file_provider: StaticFileProvider) -> Self { + pub const fn new(tx: &'b TX, static_file_provider: StaticFileProvider) -> Self { Self { tx, static_file_provider } } } @@ -130,7 +130,7 @@ pub struct LatestStateProvider { impl LatestStateProvider { /// Create new state provider - pub fn new(db: TX, static_file_provider: StaticFileProvider) -> Self { + pub const fn new(db: TX, static_file_provider: StaticFileProvider) -> Self { Self { db, static_file_provider } } @@ -148,9 +148,9 @@ delegate_provider_impls!(LatestStateProvider where [TX: DbTx]); mod tests { use super::*; - fn assert_state_provider() {} + const fn assert_state_provider() {} #[allow(dead_code)] - fn assert_latest_state_provider() { + const fn assert_latest_state_provider() { assert_state_provider::>(); } } diff --git a/crates/storage/provider/src/providers/static_file/mod.rs b/crates/storage/provider/src/providers/static_file/mod.rs index 9243afff9..4ea8c525d 100644 --- a/crates/storage/provider/src/providers/static_file/mod.rs +++ b/crates/storage/provider/src/providers/static_file/mod.rs @@ -42,7 +42,7 @@ impl LoadedJar { self.mmap_handle.clone() } - fn segment(&self) -> StaticFileSegment { + const fn segment(&self) -> StaticFileSegment { self.jar.user_header().segment() } } diff --git a/crates/storage/provider/src/providers/static_file/writer.rs b/crates/storage/provider/src/providers/static_file/writer.rs index 2a2fcf12a..7289da860 100644 --- a/crates/storage/provider/src/providers/static_file/writer.rs +++ b/crates/storage/provider/src/providers/static_file/writer.rs @@ -621,7 +621,7 @@ impl StaticFileProviderRW { #[cfg(any(test, feature = "test-utils"))] /// Helper function to access [`SegmentHeader`]. - pub fn user_header(&self) -> &SegmentHeader { + pub const fn user_header(&self) -> &SegmentHeader { self.writer.user_header() } } diff --git a/crates/storage/storage-api/src/block.rs b/crates/storage/storage-api/src/block.rs index 8b8ec5835..102716bb5 100644 --- a/crates/storage/storage-api/src/block.rs +++ b/crates/storage/storage-api/src/block.rs @@ -31,12 +31,12 @@ pub enum BlockSource { impl BlockSource { /// Returns `true` if the block source is `Pending` or `Any`. - pub fn is_pending(&self) -> bool { + pub const fn is_pending(&self) -> bool { matches!(self, Self::Pending | Self::Any) } /// Returns `true` if the block source is `Database` or `Any`. - pub fn is_database(&self) -> bool { + pub const fn is_database(&self) -> bool { matches!(self, Self::Database | Self::Any) } } diff --git a/crates/tasks/src/lib.rs b/crates/tasks/src/lib.rs index f6a853986..e0741fa09 100644 --- a/crates/tasks/src/lib.rs +++ b/crates/tasks/src/lib.rs @@ -297,12 +297,12 @@ pub struct TaskExecutor { impl TaskExecutor { /// Returns the [Handle] to the tokio runtime. - pub fn handle(&self) -> &Handle { + pub const fn handle(&self) -> &Handle { &self.handle } /// Returns the receiver of the shutdown signal. - pub fn on_shutdown_signal(&self) -> &Shutdown { + pub const fn on_shutdown_signal(&self) -> &Shutdown { &self.on_shutdown } diff --git a/crates/tasks/src/metrics.rs b/crates/tasks/src/metrics.rs index 6d414a774..c486fa681 100644 --- a/crates/tasks/src/metrics.rs +++ b/crates/tasks/src/metrics.rs @@ -41,7 +41,7 @@ impl fmt::Debug for IncCounterOnDrop { impl IncCounterOnDrop { /// Creates a new instance of `IncCounterOnDrop` with the given counter. - pub fn new(counter: Counter) -> Self { + pub const fn new(counter: Counter) -> Self { Self(counter) } } diff --git a/crates/tracing/src/lib.rs b/crates/tracing/src/lib.rs index 45a088a08..9d9f7eb30 100644 --- a/crates/tracing/src/lib.rs +++ b/crates/tracing/src/lib.rs @@ -140,7 +140,7 @@ impl LayerInfo { /// * `default_directive` - Directive for filtering log messages. /// * `filters` - Additional filtering parameters as a string. /// * `color` - Optional color configuration for the log messages. - pub fn new( + pub const fn new( format: LogFormat, default_directive: String, filters: String, diff --git a/crates/transaction-pool/tests/it/main.rs b/crates/transaction-pool/tests/it/main.rs index 7df04c18b..ead33a328 100644 --- a/crates/transaction-pool/tests/it/main.rs +++ b/crates/transaction-pool/tests/it/main.rs @@ -9,4 +9,4 @@ mod listeners; #[cfg(feature = "test-utils")] mod pending; -fn main() {} +const fn main() {} diff --git a/crates/trie/parallel/src/stats.rs b/crates/trie/parallel/src/stats.rs index e3d4d77a0..f8b37bcf5 100644 --- a/crates/trie/parallel/src/stats.rs +++ b/crates/trie/parallel/src/stats.rs @@ -12,17 +12,17 @@ pub struct ParallelTrieStats { impl ParallelTrieStats { /// Return general trie stats. - pub fn trie_stats(&self) -> TrieStats { + pub const fn trie_stats(&self) -> TrieStats { self.trie } /// The number of pre-computed storage roots. - pub fn precomputed_storage_roots(&self) -> u64 { + pub const fn precomputed_storage_roots(&self) -> u64 { self.precomputed_storage_roots } /// The number of added leaf nodes for which we did not precompute the storage root. - pub fn missed_leaves(&self) -> u64 { + pub const fn missed_leaves(&self) -> u64 { self.missed_leaves } } diff --git a/crates/trie/trie/src/hashed_cursor/default.rs b/crates/trie/trie/src/hashed_cursor/default.rs index 69ce1f4ff..e26dc48bf 100644 --- a/crates/trie/trie/src/hashed_cursor/default.rs +++ b/crates/trie/trie/src/hashed_cursor/default.rs @@ -54,7 +54,7 @@ pub struct DatabaseHashedStorageCursor { impl DatabaseHashedStorageCursor { /// Create new [DatabaseHashedStorageCursor]. - pub fn new(cursor: C, hashed_address: B256) -> Self { + pub const fn new(cursor: C, hashed_address: B256) -> Self { Self { cursor, hashed_address } } } diff --git a/crates/trie/trie/src/hashed_cursor/post_state.rs b/crates/trie/trie/src/hashed_cursor/post_state.rs index ed4fc1e2f..100ea131f 100644 --- a/crates/trie/trie/src/hashed_cursor/post_state.rs +++ b/crates/trie/trie/src/hashed_cursor/post_state.rs @@ -11,7 +11,7 @@ pub struct HashedPostStateCursorFactory<'a, CF> { impl<'a, CF> HashedPostStateCursorFactory<'a, CF> { /// Create a new factory. - pub fn new(cursor_factory: CF, post_state: &'a HashedPostStateSorted) -> Self { + pub const fn new(cursor_factory: CF, post_state: &'a HashedPostStateSorted) -> Self { Self { cursor_factory, post_state } } } @@ -51,7 +51,7 @@ pub struct HashedPostStateAccountCursor<'b, C> { impl<'b, C> HashedPostStateAccountCursor<'b, C> { /// Create new instance of [HashedPostStateAccountCursor]. - pub fn new(cursor: C, post_state: &'b HashedPostStateSorted) -> Self { + pub const fn new(cursor: C, post_state: &'b HashedPostStateSorted) -> Self { Self { cursor, post_state, last_account: None, post_state_account_index: 0 } } @@ -195,7 +195,11 @@ pub struct HashedPostStateStorageCursor<'b, C> { impl<'b, C> HashedPostStateStorageCursor<'b, C> { /// Create new instance of [HashedPostStateStorageCursor] for the given hashed address. - pub fn new(cursor: C, post_state: &'b HashedPostStateSorted, hashed_address: B256) -> Self { + pub const fn new( + cursor: C, + post_state: &'b HashedPostStateSorted, + hashed_address: B256, + ) -> Self { Self { cursor, post_state, hashed_address, last_slot: None, post_state_storage_index: 0 } } diff --git a/crates/trie/trie/src/node_iter.rs b/crates/trie/trie/src/node_iter.rs index 19cbd8996..ca544f9bb 100644 --- a/crates/trie/trie/src/node_iter.rs +++ b/crates/trie/trie/src/node_iter.rs @@ -15,7 +15,7 @@ pub struct TrieBranchNode { impl TrieBranchNode { /// Creates a new `TrieBranchNode`. - pub fn new(key: Nibbles, value: B256, children_are_in_trie: bool) -> Self { + pub const fn new(key: Nibbles, value: B256, children_are_in_trie: bool) -> Self { Self { key, value, children_are_in_trie } } } @@ -48,7 +48,7 @@ pub struct TrieNodeIter { impl TrieNodeIter { /// Creates a new [TrieNodeIter]. - pub fn new(walker: TrieWalker, hashed_cursor: H) -> Self { + pub const fn new(walker: TrieWalker, hashed_cursor: H) -> Self { Self { walker, hashed_cursor, @@ -60,7 +60,7 @@ impl TrieNodeIter { /// Sets the last iterated hashed key and returns the modified [TrieNodeIter]. /// This is used to resume iteration from the last checkpoint. - pub fn with_last_hashed_key(mut self, previous_hashed_key: B256) -> Self { + pub const fn with_last_hashed_key(mut self, previous_hashed_key: B256) -> Self { self.previous_hashed_key = Some(previous_hashed_key); self } diff --git a/crates/trie/trie/src/prefix_set/loader.rs b/crates/trie/trie/src/prefix_set/loader.rs index 10fbbadd4..49b516161 100644 --- a/crates/trie/trie/src/prefix_set/loader.rs +++ b/crates/trie/trie/src/prefix_set/loader.rs @@ -19,7 +19,7 @@ pub struct PrefixSetLoader<'a, TX>(&'a TX); impl<'a, TX> PrefixSetLoader<'a, TX> { /// Create a new loader. - pub fn new(tx: &'a TX) -> Self { + pub const fn new(tx: &'a TX) -> Self { Self(tx) } } diff --git a/crates/trie/trie/src/proof.rs b/crates/trie/trie/src/proof.rs index 3b212bd51..a8623c956 100644 --- a/crates/trie/trie/src/proof.rs +++ b/crates/trie/trie/src/proof.rs @@ -30,7 +30,7 @@ pub struct Proof<'a, TX, H> { impl<'a, TX> Proof<'a, TX, &'a TX> { /// Create a new [Proof] instance. - pub fn new(tx: &'a TX) -> Self { + pub const fn new(tx: &'a TX) -> Self { Self { tx, hashed_cursor_factory: tx } } } diff --git a/crates/trie/trie/src/stats.rs b/crates/trie/trie/src/stats.rs index 95541a6d4..f8e4b8685 100644 --- a/crates/trie/trie/src/stats.rs +++ b/crates/trie/trie/src/stats.rs @@ -10,17 +10,17 @@ pub struct TrieStats { impl TrieStats { /// Duration for root calculation. - pub fn duration(&self) -> Duration { + pub const fn duration(&self) -> Duration { self.duration } /// Number of leaves added to the hash builder during the calculation. - pub fn leaves_added(&self) -> u64 { + pub const fn leaves_added(&self) -> u64 { self.leaves_added } /// Number of branches added to the hash builder during the calculation. - pub fn branches_added(&self) -> u64 { + pub const fn branches_added(&self) -> u64 { self.branches_added } } diff --git a/crates/trie/trie/src/trie.rs b/crates/trie/trie/src/trie.rs index 0729776ef..6a054167d 100644 --- a/crates/trie/trie/src/trie.rs +++ b/crates/trie/trie/src/trie.rs @@ -49,13 +49,13 @@ impl StateRoot { } /// Set the threshold. - pub fn with_threshold(mut self, threshold: u64) -> Self { + pub const fn with_threshold(mut self, threshold: u64) -> Self { self.threshold = threshold; self } /// Set the threshold to maximum value so that intermediate progress is not returned. - pub fn with_no_threshold(mut self) -> Self { + pub const fn with_no_threshold(mut self) -> Self { self.threshold = u64::MAX; self } diff --git a/crates/trie/trie/src/trie_cursor/database_cursors.rs b/crates/trie/trie/src/trie_cursor/database_cursors.rs index c30cdb428..9eb180989 100644 --- a/crates/trie/trie/src/trie_cursor/database_cursors.rs +++ b/crates/trie/trie/src/trie_cursor/database_cursors.rs @@ -34,7 +34,7 @@ pub struct DatabaseAccountTrieCursor(C); impl DatabaseAccountTrieCursor { /// Create a new account trie cursor. - pub fn new(cursor: C) -> Self { + pub const fn new(cursor: C) -> Self { Self(cursor) } } @@ -76,7 +76,7 @@ pub struct DatabaseStorageTrieCursor { impl DatabaseStorageTrieCursor { /// Create a new storage trie cursor. - pub fn new(cursor: C, hashed_address: B256) -> Self { + pub const fn new(cursor: C, hashed_address: B256) -> Self { Self { cursor, hashed_address } } } diff --git a/crates/trie/trie/src/trie_cursor/subnode.rs b/crates/trie/trie/src/trie_cursor/subnode.rs index c8b77daea..e40c88c4f 100644 --- a/crates/trie/trie/src/trie_cursor/subnode.rs +++ b/crates/trie/trie/src/trie_cursor/subnode.rs @@ -69,7 +69,7 @@ impl CursorSubNode { /// Returns the full key of the current node. #[inline] - pub fn full_key(&self) -> &Nibbles { + pub const fn full_key(&self) -> &Nibbles { &self.full_key } @@ -114,7 +114,7 @@ impl CursorSubNode { /// Returns the next child index to visit. #[inline] - pub fn nibble(&self) -> i8 { + pub const fn nibble(&self) -> i8 { self.nibble } diff --git a/crates/trie/trie/src/updates.rs b/crates/trie/trie/src/updates.rs index 91fc63b10..6bccf0ad5 100644 --- a/crates/trie/trie/src/updates.rs +++ b/crates/trie/trie/src/updates.rs @@ -36,7 +36,7 @@ pub enum TrieOp { impl TrieOp { /// Returns `true` if the operation is an update. - pub fn is_update(&self) -> bool { + pub const fn is_update(&self) -> bool { 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 1f1b38ecd..fb71d1a86 100644 --- a/testing/ef-tests/src/cases/blockchain_test.rs +++ b/testing/ef-tests/src/cases/blockchain_test.rs @@ -20,7 +20,7 @@ pub struct BlockchainTests { impl BlockchainTests { /// Create a new handler for a subset of the blockchain test suite. - pub fn new(suite: String) -> Self { + pub const fn new(suite: String) -> Self { Self { suite } } }