diff --git a/bridges/bin/runtime-common/src/lib.rs b/bridges/bin/runtime-common/src/lib.rs index 2722f6f1c6d14..bf0bfd8c8455b 100644 --- a/bridges/bin/runtime-common/src/lib.rs +++ b/bridges/bin/runtime-common/src/lib.rs @@ -178,7 +178,7 @@ mod tests { impl BridgeRuntimeFilterCall for FirstFilterCall { fn validate(call: &MockCall) -> TransactionValidity { if call.data <= 1 { - return InvalidTransaction::Custom(1).into() + return InvalidTransaction::Custom(1).into(); } Ok(ValidTransaction { priority: 1, ..Default::default() }) @@ -189,7 +189,7 @@ mod tests { impl BridgeRuntimeFilterCall for SecondFilterCall { fn validate(call: &MockCall) -> TransactionValidity { if call.data <= 2 { - return InvalidTransaction::Custom(2).into() + return InvalidTransaction::Custom(2).into(); } Ok(ValidTransaction { priority: 2, ..Default::default() }) diff --git a/bridges/bin/runtime-common/src/messages.rs b/bridges/bin/runtime-common/src/messages.rs index 4aca53f3b9836..e8337bc4a0c8d 100644 --- a/bridges/bin/runtime-common/src/messages.rs +++ b/bridges/bin/runtime-common/src/messages.rs @@ -174,7 +174,7 @@ pub mod source { // transaction also contains signatures and signed extensions. Because of this, we reserve // 1/3 of the the maximal extrinsic size for this data. if payload.len() > maximal_message_size::() as usize { - return Err(VerificationError::MessageTooLarge) + return Err(VerificationError::MessageTooLarge); } Ok(()) @@ -299,7 +299,7 @@ pub mod target { // receiving proofs where end < begin is ok (if proof includes outbound lane state) let messages_in_the_proof = nonces_range.checked_len().unwrap_or(0); if messages_in_the_proof != MessageNonce::from(messages_count) { - return Err(VerificationError::MessagesCountMismatch) + return Err(VerificationError::MessagesCountMismatch); } // Read messages first. All messages that are claimed to be in the proof must @@ -322,7 +322,7 @@ pub mod target { // Now we may actually check if the proof is empty or not. if proved_lane_messages.lane_state.is_none() && proved_lane_messages.messages.is_empty() { - return Err(VerificationError::EmptyMessageProof) + return Err(VerificationError::EmptyMessageProof); } // check that the storage proof doesn't have any untouched trie nodes diff --git a/bridges/bin/runtime-common/src/messages_benchmarking.rs b/bridges/bin/runtime-common/src/messages_benchmarking.rs index 0c7a9ad1a83d6..f6d9a29402ed4 100644 --- a/bridges/bin/runtime-common/src/messages_benchmarking.rs +++ b/bridges/bin/runtime-common/src/messages_benchmarking.rs @@ -53,7 +53,7 @@ fn prepare_inbound_message( // if we don't need a correct message, then we may just return some random blob if !params.is_successful_dispatch_expected { - return vec![0u8; expected_size] + return vec![0u8; expected_size]; } // else let's prepare successful message. diff --git a/bridges/bin/runtime-common/src/messages_call_ext.rs b/bridges/bin/runtime-common/src/messages_call_ext.rs index fb07f7b6dd691..81d9cec42e3dc 100644 --- a/bridges/bin/runtime-common/src/messages_call_ext.rs +++ b/bridges/bin/runtime-common/src/messages_call_ext.rs @@ -83,7 +83,7 @@ impl ReceiveMessagesProofInfo { fn is_obsolete(&self, is_dispatcher_active: bool) -> bool { // if dispatcher is inactive, we don't accept any delivery transactions if !is_dispatcher_active { - return true + return true; } // transactions with zero bundled nonces are not allowed, unless they're message @@ -96,7 +96,7 @@ impl ReceiveMessagesProofInfo { // or if we can't accept new messages at all self.unrewarded_relayers.free_message_slots == 0; - return !empty_transactions_allowed + return !empty_transactions_allowed; } // otherwise we require bundled messages to continue stored range @@ -160,7 +160,7 @@ impl, I: 'static> CallHelper { // so if relayer slots are released, then message slots are also // released return post_occupation.free_message_slots > - info.unrewarded_relayers.free_message_slots + info.unrewarded_relayers.free_message_slots; } inbound_lane_data.last_delivered_nonce() == *info.base.bundled_range.end() @@ -245,7 +245,7 @@ impl< best_stored_nonce: inbound_lane_data.last_delivered_nonce(), }, unrewarded_relayers: unrewarded_relayers_occupation::(&inbound_lane_data), - }) + }); } None @@ -269,7 +269,7 @@ impl< bundled_range: outbound_lane_data.latest_received_nonce + 1..= relayers_state.last_delivered_nonce, best_stored_nonce: outbound_lane_data.latest_received_nonce, - })) + })); } None @@ -277,11 +277,11 @@ impl< fn call_info(&self) -> Option { if let Some(info) = self.receive_messages_proof_info() { - return Some(CallInfo::ReceiveMessagesProof(info)) + return Some(CallInfo::ReceiveMessagesProof(info)); } if let Some(info) = self.receive_messages_delivery_proof_info() { - return Some(CallInfo::ReceiveMessagesDeliveryProof(info)) + return Some(CallInfo::ReceiveMessagesDeliveryProof(info)); } None @@ -307,7 +307,7 @@ impl< proof_info ); - return sp_runtime::transaction_validity::InvalidTransaction::Call.into() + return sp_runtime::transaction_validity::InvalidTransaction::Call.into(); }, Some(CallInfo::ReceiveMessagesProof(proof_info)) if proof_info.is_obsolete(T::MessageDispatch::is_active()) => @@ -318,7 +318,7 @@ impl< proof_info ); - return sp_runtime::transaction_validity::InvalidTransaction::Stale.into() + return sp_runtime::transaction_validity::InvalidTransaction::Stale.into(); }, Some(CallInfo::ReceiveMessagesDeliveryProof(proof_info)) if proof_info.is_obsolete() => @@ -329,7 +329,7 @@ impl< proof_info, ); - return sp_runtime::transaction_validity::InvalidTransaction::Stale.into() + return sp_runtime::transaction_validity::InvalidTransaction::Stale.into(); }, _ => {}, } diff --git a/bridges/bin/runtime-common/src/messages_xcm_extension.rs b/bridges/bin/runtime-common/src/messages_xcm_extension.rs index e3da6155f08a1..5c5418f980643 100644 --- a/bridges/bin/runtime-common/src/messages_xcm_extension.rs +++ b/bridges/bin/runtime-common/src/messages_xcm_extension.rs @@ -96,7 +96,7 @@ impl< return MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: XcmBlobMessageDispatchResult::InvalidPayload, - } + }; }, }; let dispatch_level_result = match BlobDispatcher::dispatch_blob(payload) { @@ -210,18 +210,18 @@ impl LocalXcmQueueManager { ) { // skip if we dont want to handle congestion if !H::supports_congestion_detection() { - return + return; } // if we have already sent the congestion signal, we don't want to do anything if Self::is_congested_signal_sent(sender_and_lane.lane) { - return + return; } // if the bridge queue is not congested, we don't want to do anything let is_congested = enqueued_messages > OUTBOUND_LANE_CONGESTED_THRESHOLD; if !is_congested { - return + return; } log::info!( @@ -250,18 +250,18 @@ impl LocalXcmQueueManager { ) { // skip if we dont want to handle congestion if !H::supports_congestion_detection() { - return + return; } // if we have not sent the congestion signal before, we don't want to do anything if !Self::is_congested_signal_sent(sender_and_lane.lane) { - return + return; } // if the bridge queue is still congested, we don't want to do anything let is_congested = enqueued_messages > OUTBOUND_LANE_UNCONGESTED_THRESHOLD; if is_congested { - return + return; } log::info!( diff --git a/bridges/bin/runtime-common/src/refund_relayer_extension.rs b/bridges/bin/runtime-common/src/refund_relayer_extension.rs index bfcb82ad166c3..4a7d961980738 100644 --- a/bridges/bin/runtime-common/src/refund_relayer_extension.rs +++ b/bridges/bin/runtime-common/src/refund_relayer_extension.rs @@ -345,7 +345,7 @@ where relayer, e, ); - return slash_relayer_if_delivery_result + return slash_relayer_if_delivery_result; } // check if relay chain state has been updated @@ -361,7 +361,7 @@ where ::Id::get(), relayer, ); - return slash_relayer_if_delivery_result + return slash_relayer_if_delivery_result; } // there's a conflict between how bridge GRANDPA pallet works and a `utility.batchAll` @@ -393,7 +393,7 @@ where // do additional check if !Self::additional_call_result_check(&relayer, &call_info) { - return slash_relayer_if_delivery_result + return slash_relayer_if_delivery_result; } // regarding the tip - refund that happens here (at this side of the bridge) isn't the whole @@ -449,7 +449,7 @@ where >>::MaxUnconfirmedMessagesAtInboundLane::get( ); if bundled_messages > max_unconfirmed_messages_in_confirmation_tx { - return None + return None; } Some(bundled_messages) @@ -516,7 +516,7 @@ where // we only boost priority if relayer has staked required balance if !RelayersPallet::::is_registration_active(who) { - return Ok(Default::default()) + return Ok(Default::default()); } // compute priority boost @@ -722,7 +722,7 @@ where Msgs::Id::get(), relayer, ); - return false + return false; } } diff --git a/bridges/modules/grandpa/src/call_ext.rs b/bridges/modules/grandpa/src/call_ext.rs index e3c778b480baa..814e22ad01f05 100644 --- a/bridges/modules/grandpa/src/call_ext.rs +++ b/bridges/modules/grandpa/src/call_ext.rs @@ -91,7 +91,7 @@ impl, I: 'static> SubmitFinalityProofHelper { best_finalized, ); - return Err(Error::::OldHeader) + return Err(Error::::OldHeader); } if let Some(current_set_id) = current_set_id { @@ -104,7 +104,7 @@ impl, I: 'static> SubmitFinalityProofHelper { actual_set_id, ); - return Err(Error::::InvalidAuthoritySetId) + return Err(Error::::InvalidAuthoritySetId); } } @@ -135,7 +135,7 @@ pub trait CallSubType, I: 'static>: finality_target, justification, None, - )) + )); } else if let Some(crate::Call::::submit_finality_proof_ex { finality_target, justification, @@ -146,7 +146,7 @@ pub trait CallSubType, I: 'static>: finality_target, justification, Some(*current_set_id), - )) + )); } None @@ -165,7 +165,7 @@ pub trait CallSubType, I: 'static>: }; if Pallet::::ensure_not_halted().is_err() { - return InvalidTransaction::Call.into() + return InvalidTransaction::Call.into(); } match SubmitFinalityProofHelper::::check_obsolete( diff --git a/bridges/modules/grandpa/src/lib.rs b/bridges/modules/grandpa/src/lib.rs index ce2c47da954fa..4ea0d27be7ae6 100644 --- a/bridges/modules/grandpa/src/lib.rs +++ b/bridges/modules/grandpa/src/lib.rs @@ -523,7 +523,7 @@ pub mod pallet { next_authorities, ); - return Ok(Some(next_authorities.into())) + return Ok(Some(next_authorities.into())); }; Ok(None) @@ -656,7 +656,7 @@ where if let Event::::UpdatedBestFinalizedHeader { grandpa_info, .. } = event.event.try_into().ok()? { - return Some(grandpa_info) + return Some(grandpa_info); } None }) diff --git a/bridges/modules/messages/src/inbound_lane.rs b/bridges/modules/messages/src/inbound_lane.rs index 966ec939e70e2..7db34e81848a8 100644 --- a/bridges/modules/messages/src/inbound_lane.rs +++ b/bridges/modules/messages/src/inbound_lane.rs @@ -133,10 +133,10 @@ impl InboundLane { if outbound_lane_data.latest_received_nonce > last_delivered_nonce { // this is something that should never happen if proofs are correct - return None + return None; } if outbound_lane_data.latest_received_nonce <= data.last_confirmed_nonce { - return None + return None; } let new_confirmed_nonce = outbound_lane_data.latest_received_nonce; @@ -173,18 +173,18 @@ impl InboundLane { ) -> ReceivalResult { let mut data = self.storage.get_or_init_data(); if Some(nonce) != data.last_delivered_nonce().checked_add(1) { - return ReceivalResult::InvalidNonce + return ReceivalResult::InvalidNonce; } // if there are more unrewarded relayer entries than we may accept, reject this message if data.relayers.len() as MessageNonce >= self.storage.max_unrewarded_relayer_entries() { - return ReceivalResult::TooManyUnrewardedRelayers + return ReceivalResult::TooManyUnrewardedRelayers; } // if there are more unconfirmed messages than we may accept, reject this message let unconfirmed_messages_count = nonce.saturating_sub(data.last_confirmed_nonce); if unconfirmed_messages_count > self.storage.max_unconfirmed_messages() { - return ReceivalResult::TooManyUnconfirmedMessages + return ReceivalResult::TooManyUnconfirmedMessages; } // then, dispatch message diff --git a/bridges/modules/messages/src/lib.rs b/bridges/modules/messages/src/lib.rs index a86cb326cf040..33e711f081f31 100644 --- a/bridges/modules/messages/src/lib.rs +++ b/bridges/modules/messages/src/lib.rs @@ -195,7 +195,7 @@ pub mod pallet { // we'll need at least to read outbound lane state, kill a message and update lane state let db_weight = T::DbWeight::get(); if !remaining_weight.all_gte(db_weight.reads_writes(1, 2)) { - return Weight::zero() + return Weight::zero(); } // messages from lane with index `i` in `ActiveOutboundLanes` are pruned when @@ -762,7 +762,7 @@ fn ensure_normal_operating_mode, I: 'static>() -> Result<(), Error< if PalletOperatingMode::::get() == MessagesOperatingMode::Basic(BasicOperatingMode::Normal) { - return Ok(()) + return Ok(()); } Err(Error::::NotOperatingNormally) diff --git a/bridges/modules/messages/src/outbound_lane.rs b/bridges/modules/messages/src/outbound_lane.rs index 431c2cfb7eef3..8e6136838f225 100644 --- a/bridges/modules/messages/src/outbound_lane.rs +++ b/bridges/modules/messages/src/outbound_lane.rs @@ -110,10 +110,10 @@ impl OutboundLane { end: latest_delivered_nonce, }; if confirmed_messages.total_messages() == 0 { - return Ok(None) + return Ok(None); } if confirmed_messages.end > data.latest_generated_nonce { - return Err(ReceivalConfirmationError::FailedToConfirmFutureMessages) + return Err(ReceivalConfirmationError::FailedToConfirmFutureMessages); } if confirmed_messages.total_messages() > max_allowed_messages { // that the relayer has declared correct number of messages that the proof contains (it @@ -127,7 +127,7 @@ impl OutboundLane { confirmed_messages.total_messages(), max_allowed_messages, ); - return Err(ReceivalConfirmationError::TryingToConfirmMoreMessagesThanExpected) + return Err(ReceivalConfirmationError::TryingToConfirmMoreMessagesThanExpected); } ensure_unrewarded_relayers_are_correct(confirmed_messages.end, relayers)?; @@ -182,18 +182,18 @@ fn ensure_unrewarded_relayers_are_correct( // unrewarded relayer entry must have at least 1 unconfirmed message // (guaranteed by the `InboundLane::receive_message()`) if entry.messages.end < entry.messages.begin { - return Err(ReceivalConfirmationError::EmptyUnrewardedRelayerEntry) + return Err(ReceivalConfirmationError::EmptyUnrewardedRelayerEntry); } // every entry must confirm range of messages that follows previous entry range // (guaranteed by the `InboundLane::receive_message()`) if expected_entry_begin != Some(entry.messages.begin) { - return Err(ReceivalConfirmationError::NonConsecutiveUnrewardedRelayerEntries) + return Err(ReceivalConfirmationError::NonConsecutiveUnrewardedRelayerEntries); } expected_entry_begin = entry.messages.end.checked_add(1); // entry can't confirm messages larger than `inbound_lane_data.latest_received_nonce()` // (guaranteed by the `InboundLane::receive_message()`) if entry.messages.end > latest_received_nonce { - return Err(ReceivalConfirmationError::FailedToConfirmFutureMessages) + return Err(ReceivalConfirmationError::FailedToConfirmFutureMessages); } } diff --git a/bridges/modules/parachains/src/call_ext.rs b/bridges/modules/parachains/src/call_ext.rs index da91a40a23223..17fc692ebf311 100644 --- a/bridges/modules/parachains/src/call_ext.rs +++ b/bridges/modules/parachains/src/call_ext.rs @@ -58,7 +58,7 @@ impl, I: 'static> SubmitParachainHeadsHelper { stored_best_head.best_head_hash.at_relay_block_number, update.at_relay_block_number ); - return true + return true; } if stored_best_head.best_head_hash.head_hash == update.para_head_hash { @@ -71,7 +71,7 @@ impl, I: 'static> SubmitParachainHeadsHelper { stored_best_head.best_head_hash.at_relay_block_number, update.at_relay_block_number ); - return true + return true; } false @@ -109,7 +109,7 @@ pub trait CallSubType, I: 'static>: at_relay_block_number: at_relay_block.0, para_id, para_head_hash, - }) + }); } } @@ -143,11 +143,11 @@ pub trait CallSubType, I: 'static>: }; if Pallet::::ensure_not_halted().is_err() { - return InvalidTransaction::Call.into() + return InvalidTransaction::Call.into(); } if SubmitParachainHeadsHelper::::is_obsolete(&update) { - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } Ok(ValidTransaction::default()) diff --git a/bridges/modules/parachains/src/lib.rs b/bridges/modules/parachains/src/lib.rs index 1363a637604d1..4b42e0a0e8da9 100644 --- a/bridges/modules/parachains/src/lib.rs +++ b/bridges/modules/parachains/src/lib.rs @@ -379,7 +379,7 @@ pub mod pallet { }, ); Self::deposit_event(Event::MissingParachainHead { parachain }); - continue + continue; }, Err(e) => { log::trace!( @@ -389,7 +389,7 @@ pub mod pallet { e, ); Self::deposit_event(Event::MissingParachainHead { parachain }); - continue + continue; }, }; @@ -410,7 +410,7 @@ pub mod pallet { parachain_head_hash, actual_parachain_head_hash, }); - continue + continue; } // convert from parachain head into stored parachain head data @@ -424,7 +424,7 @@ pub mod pallet { parachain, ); Self::deposit_event(Event::UntrackedParachainRejected { parachain }); - continue + continue; }, }; @@ -561,7 +561,7 @@ pub mod pallet { parachain, parachain_head_hash: new_head_hash, }); - return Err(()) + return Err(()); } // verify that the parachain head data size is <= `MaxParaHeadDataSize` @@ -584,7 +584,7 @@ pub mod pallet { parachain_head_size: e.value_size as _, }); - return Err(()) + return Err(()); }, }; diff --git a/bridges/modules/relayers/src/lib.rs b/bridges/modules/relayers/src/lib.rs index ce66c9df48e01..de6402bbd9b26 100644 --- a/bridges/modules/relayers/src/lib.rs +++ b/bridges/modules/relayers/src/lib.rs @@ -223,7 +223,7 @@ pub mod pallet { // registration is inactive if relayer stake is less than required if registration.stake < Self::required_stake() { - return false + return false; } // registration is inactive if it ends soon @@ -231,7 +231,7 @@ pub mod pallet { .valid_till .saturating_sub(frame_system::Pallet::::block_number()); if remaining_lease <= Self::required_registration_lease() { - return false + return false; } true @@ -253,7 +253,7 @@ pub mod pallet { relayer, ); - return + return; }, }; @@ -308,7 +308,7 @@ pub mod pallet { reward: T::Reward, ) { if reward.is_zero() { - return + return; } RelayerRewards::::mutate( diff --git a/bridges/modules/xcm-bridge-hub-router/src/lib.rs b/bridges/modules/xcm-bridge-hub-router/src/lib.rs index f219be78f9e1b..046dc6bb8c979 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/lib.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/lib.rs @@ -120,18 +120,18 @@ pub mod pallet { // if the channel with sibling/child bridge hub is suspended, we don't change // anything if T::WithBridgeHubChannel::is_congested() { - return T::WeightInfo::on_initialize_when_congested() + return T::WeightInfo::on_initialize_when_congested(); } // if bridge has reported congestion, we don't change anything let mut bridge = Self::bridge(); if bridge.is_congested { - return T::WeightInfo::on_initialize_when_congested() + return T::WeightInfo::on_initialize_when_congested(); } // if fee factor is already minimal, we don't change anything if bridge.delivery_fee_factor == MINIMAL_DELIVERY_FEE_FACTOR { - return T::WeightInfo::on_initialize_when_congested() + return T::WeightInfo::on_initialize_when_congested(); } let previous_factor = bridge.delivery_fee_factor; @@ -198,7 +198,7 @@ pub mod pallet { // if outbound queue is not congested AND bridge has not reported congestion, do // nothing if !is_channel_with_bridge_hub_congested && !is_bridge_congested { - return Err(()) + return Err(()); } // ok - we need to increase the fee factor, let's do that @@ -247,7 +247,7 @@ impl, I: 'static> ExporterFor for Pallet { bridged_network, network, ); - return None + return None; } } @@ -262,7 +262,7 @@ impl, I: 'static> ExporterFor for Pallet { network, remote_location, ); - return None + return None; }; // take `base_fee` from `T::Brides`, but it has to be the same `T::FeeAsset` @@ -281,7 +281,7 @@ impl, I: 'static> ExporterFor for Pallet { network, remote_location, ); - return None + return None; }, }, None => 0, @@ -332,7 +332,7 @@ impl, I: 'static> SendXcm for Pallet { // bridge doesn't support oversized/overweight messages now. So it is better to drop such // messages here than at the bridge hub. Let's check the message size. if message_size > HARD_MESSAGE_SIZE_LIMIT { - return Err(SendError::ExceedsMaxMessageSize) + return Err(SendError::ExceedsMaxMessageSize); } // We need to ensure that the known `dest`'s XCM version can comprehend the current `xcm` diff --git a/bridges/modules/xcm-bridge-hub-router/src/mock.rs b/bridges/modules/xcm-bridge-hub-router/src/mock.rs index 6dbfba5f6fdc1..96befed1aa2c4 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/mock.rs @@ -92,7 +92,7 @@ impl> GetVersion { fn get_version_for(dest: &Location) -> Option { if LocationValue::contains(dest) { - return None + return None; } Some(XCM_VERSION) } diff --git a/bridges/primitives/header-chain/src/justification/verification/mod.rs b/bridges/primitives/header-chain/src/justification/verification/mod.rs index c71149bf9c28e..46f5aeb6f7408 100644 --- a/bridges/primitives/header-chain/src/justification/verification/mod.rs +++ b/bridges/primitives/header-chain/src/justification/verification/mod.rs @@ -93,14 +93,14 @@ impl AncestryChain
{ precommit_target_number: &Header::Number, ) -> Option> { if precommit_target_number < &self.base.number() { - return None + return None; } let mut route = vec![]; let mut current_hash = *precommit_target_hash; loop { if current_hash == self.base.hash() { - break + break; } current_hash = match self.parent_hash_of(¤t_hash) { @@ -109,7 +109,7 @@ impl AncestryChain
{ if is_visited_before { // If the current header has been visited in a previous call, it is a // descendent of `base` (we assume that the previous call was successful). - return Some(route) + return Some(route); } route.push(current_hash); @@ -243,7 +243,7 @@ trait JustificationVerifier { if (justification.commit.target_hash, justification.commit.target_number) != finalized_target { - return Err(Error::InvalidJustificationTarget) + return Err(Error::InvalidJustificationTarget); } let threshold = context.voter_set.threshold().get(); @@ -260,7 +260,7 @@ trait JustificationVerifier { let action = self.process_redundant_vote(precommit_idx).map_err(Error::Precommit)?; if matches!(action, IterationFlow::Skip) { - continue + continue; } } @@ -273,14 +273,14 @@ trait JustificationVerifier { .process_known_authority_vote(precommit_idx, signed) .map_err(Error::Precommit)?; if matches!(action, IterationFlow::Skip) { - continue + continue; } authority_info }, None => { self.process_unknown_authority_vote(precommit_idx).map_err(Error::Precommit)?; - continue + continue; }, }; @@ -292,7 +292,7 @@ trait JustificationVerifier { .process_unrelated_ancestry_vote(precommit_idx) .map_err(Error::Precommit)?; if matches!(action, IterationFlow::Skip) { - continue + continue; } } @@ -306,7 +306,7 @@ trait JustificationVerifier { &mut signature_buffer, ) { self.process_invalid_signature_vote(precommit_idx).map_err(Error::Precommit)?; - continue + continue; } // now we can count the vote since we know that it is valid @@ -320,7 +320,7 @@ trait JustificationVerifier { // check that the cumulative weight of validators that voted for the justification target // (or one of its descendents) is larger than the required threshold. if cumulative_weight < threshold { - return Err(Error::TooLowCumulativeWeight) + return Err(Error::TooLowCumulativeWeight); } // check that there are no extra headers in the justification diff --git a/bridges/primitives/header-chain/src/justification/verification/optimizer.rs b/bridges/primitives/header-chain/src/justification/verification/optimizer.rs index 3f1e6ab670ca6..fd7d624276403 100644 --- a/bridges/primitives/header-chain/src/justification/verification/optimizer.rs +++ b/bridges/primitives/header-chain/src/justification/verification/optimizer.rs @@ -80,7 +80,7 @@ impl JustificationVerifier
for JustificationOptimizer JustificationVerifier
for StrictJustificationVerif // inside `finality-grandpa` crate (mostly related to reporting equivocations). // But the only thing that we care about is that only first vote from the // authority is accepted - return Err(PrecommitError::DuplicateAuthorityVote) + return Err(PrecommitError::DuplicateAuthorityVote); } Ok(IterationFlow::Run) diff --git a/bridges/primitives/header-chain/tests/implementation_match.rs b/bridges/primitives/header-chain/tests/implementation_match.rs index 1f61f91ff4bbf..512715923abf9 100644 --- a/bridges/primitives/header-chain/tests/implementation_match.rs +++ b/bridges/primitives/header-chain/tests/implementation_match.rs @@ -56,7 +56,7 @@ impl finality_grandpa::Chain for AncestryChain { let mut current_hash = block; loop { if current_hash == base { - break + break; } match self.0.parent_hash_of(¤t_hash) { Some(parent_hash) => { diff --git a/bridges/primitives/parachains/src/lib.rs b/bridges/primitives/parachains/src/lib.rs index 692bbd99ecef3..c87c3f1ff6076 100644 --- a/bridges/primitives/parachains/src/lib.rs +++ b/bridges/primitives/parachains/src/lib.rs @@ -137,7 +137,7 @@ impl ParaStoredHeaderDataBuilder for SingleParaStoredHeaderDataBui return Some(ParaStoredHeaderData( StoredHeaderData { number: *header.number(), state_root: *header.state_root() } .encode(), - )) + )); } None } diff --git a/bridges/primitives/runtime/src/storage_proof.rs b/bridges/primitives/runtime/src/storage_proof.rs index 1b706aa66c16f..128d644ebc73a 100644 --- a/bridges/primitives/runtime/src/storage_proof.rs +++ b/bridges/primitives/runtime/src/storage_proof.rs @@ -75,12 +75,12 @@ where let proof_nodes_count = proof.len(); let proof = StorageProof::new(proof); if proof_nodes_count != proof.iter_nodes().count() { - return Err(Error::DuplicateNodesInProof) + return Err(Error::DuplicateNodesInProof); } let db = proof.into_memory_db(); if !db.contains(&root, EMPTY_PREFIX) { - return Err(Error::StorageRootMismatch) + return Err(Error::StorageRootMismatch); } let recorder = Recorder::default(); diff --git a/bridges/snowbridge/pallets/ethereum-client/src/impls.rs b/bridges/snowbridge/pallets/ethereum-client/src/impls.rs index 300431d87707d..b652662093cb7 100644 --- a/bridges/snowbridge/pallets/ethereum-client/src/impls.rs +++ b/bridges/snowbridge/pallets/ethereum-client/src/impls.rs @@ -31,7 +31,7 @@ impl Verifier for Pallet { proof.block_hash, err ); - return Err(err) + return Err(err); }, }; @@ -56,7 +56,7 @@ impl Verifier for Pallet { "💫 Event log not found in receipt for transaction at index {} in block {}", proof.tx_index, proof.block_hash, ); - return Err(LogNotFound) + return Err(LogNotFound); } log::info!( diff --git a/bridges/snowbridge/pallets/ethereum-client/src/lib.rs b/bridges/snowbridge/pallets/ethereum-client/src/lib.rs index a54d4a05ac584..4b115c55b0c76 100644 --- a/bridges/snowbridge/pallets/ethereum-client/src/lib.rs +++ b/bridges/snowbridge/pallets/ethereum-client/src/lib.rs @@ -597,7 +597,7 @@ pub mod pallet { let state = >::get(block_root) .ok_or(Error::::ExpectedFinalizedHeaderNotStored)?; if update.header.slot != state.slot { - return Err(Error::::ExpectedFinalizedHeaderNotStored.into()) + return Err(Error::::ExpectedFinalizedHeaderNotStored.into()); } }, } @@ -787,16 +787,16 @@ pub mod pallet { /// Returns the fork version based on the current epoch. pub(super) fn select_fork_version(fork_versions: &ForkVersions, epoch: u64) -> ForkVersion { if epoch >= fork_versions.deneb.epoch { - return fork_versions.deneb.version + return fork_versions.deneb.version; } if epoch >= fork_versions.capella.epoch { - return fork_versions.capella.version + return fork_versions.capella.version; } if epoch >= fork_versions.bellatrix.epoch { - return fork_versions.bellatrix.version + return fork_versions.bellatrix.version; } if epoch >= fork_versions.altair.epoch { - return fork_versions.altair.version + return fork_versions.altair.version; } fork_versions.genesis.version } diff --git a/bridges/snowbridge/pallets/inbound-queue/src/lib.rs b/bridges/snowbridge/pallets/inbound-queue/src/lib.rs index bdc21fcf03702..b915195bea47a 100644 --- a/bridges/snowbridge/pallets/inbound-queue/src/lib.rs +++ b/bridges/snowbridge/pallets/inbound-queue/src/lib.rs @@ -251,7 +251,7 @@ pub mod pallet { // Verify message nonce >::try_mutate(envelope.channel_id, |nonce| -> DispatchResult { if *nonce == u64::MAX { - return Err(Error::::MaxNonceReached.into()) + return Err(Error::::MaxNonceReached.into()); } if envelope.nonce != nonce.saturating_add(1) { Err(Error::::InvalidNonce.into()) diff --git a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs index 110f611c67660..2665d4e4e96e1 100644 --- a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs +++ b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs @@ -197,7 +197,7 @@ impl StaticLookup for MockChannelLookup { if channel_id != hex!("c173fac324158e77fb5840738a1a541f633cbec8884c6a601c567d2b376a0539").into() { - return None + return None; } Some(Channel { agent_id: H256::zero(), para_id: ASSET_HUB_PARAID.into() }) } diff --git a/bridges/snowbridge/pallets/outbound-queue/merkle-tree/src/lib.rs b/bridges/snowbridge/pallets/outbound-queue/merkle-tree/src/lib.rs index 8c91ccd04d9a6..78bdb3fb51d6a 100644 --- a/bridges/snowbridge/pallets/outbound-queue/merkle-tree/src/lib.rs +++ b/bridges/snowbridge/pallets/outbound-queue/merkle-tree/src/lib.rs @@ -235,7 +235,7 @@ where L: Into>, { if leaf_index >= number_of_leaves { - return false + return false; } let leaf_hash = match leaf.into() { @@ -315,7 +315,7 @@ where "[merkelize_row] Next: {:?}", next.iter().map(hex::encode).collect::>() ); - return Err(next) + return Err(next); }, } } diff --git a/bridges/snowbridge/pallets/outbound-queue/src/api.rs b/bridges/snowbridge/pallets/outbound-queue/src/api.rs index 44d63f1e2d23f..1b067d4e41208 100644 --- a/bridges/snowbridge/pallets/outbound-queue/src/api.rs +++ b/bridges/snowbridge/pallets/outbound-queue/src/api.rs @@ -12,7 +12,7 @@ where T: Config, { if !MessageLeaves::::exists() { - return None + return None; } let proof = merkle_proof::<::Hashing, _>(MessageLeaves::::stream_iter(), leaf_index); diff --git a/bridges/snowbridge/pallets/outbound-queue/src/lib.rs b/bridges/snowbridge/pallets/outbound-queue/src/lib.rs index 9e949a4791a8a..d596cd9fabd01 100644 --- a/bridges/snowbridge/pallets/outbound-queue/src/lib.rs +++ b/bridges/snowbridge/pallets/outbound-queue/src/lib.rs @@ -270,7 +270,7 @@ pub mod pallet { pub(crate) fn commit() { let count = MessageLeaves::::decode_len().unwrap_or_default() as u64; if count == 0 { - return + return; } // Create merkle root of messages diff --git a/bridges/snowbridge/pallets/outbound-queue/src/process_message_impl.rs b/bridges/snowbridge/pallets/outbound-queue/src/process_message_impl.rs index 731aa6fa6d5ca..0c861da6a361f 100644 --- a/bridges/snowbridge/pallets/outbound-queue/src/process_message_impl.rs +++ b/bridges/snowbridge/pallets/outbound-queue/src/process_message_impl.rs @@ -18,7 +18,7 @@ impl ProcessMessage for Pallet { ) -> Result { let weight = T::WeightInfo::do_process_message(); if meter.try_consume(weight).is_err() { - return Err(ProcessMessageError::Overweight(weight)) + return Err(ProcessMessageError::Overweight(weight)); } Self::do_process_message(origin, message) } diff --git a/bridges/snowbridge/primitives/beacon/src/merkle_proof.rs b/bridges/snowbridge/primitives/beacon/src/merkle_proof.rs index a6ee6e9452c39..047ea41bd2f01 100644 --- a/bridges/snowbridge/primitives/beacon/src/merkle_proof.rs +++ b/bridges/snowbridge/primitives/beacon/src/merkle_proof.rs @@ -14,7 +14,7 @@ pub fn verify_merkle_branch( ) -> bool { // verify the proof length if branch.len() != depth { - return false + return false; } // verify the computed merkle root root == compute_merkle_root(leaf, branch, index) diff --git a/bridges/snowbridge/primitives/beacon/src/receipt.rs b/bridges/snowbridge/primitives/beacon/src/receipt.rs index 0588f3f73f715..d6cf5b2f905d2 100644 --- a/bridges/snowbridge/primitives/beacon/src/receipt.rs +++ b/bridges/snowbridge/primitives/beacon/src/receipt.rs @@ -28,7 +28,7 @@ fn apply_merkle_proof(proof: &[Vec]) -> Option<(H256, Vec)> { let final_hash: Option<[u8; 32]> = iter.try_fold(keccak_256(first_bytes), |acc, x| { let node: Box = x.as_slice().try_into().ok()?; if (*node).contains_hash(acc.into()) { - return Some(keccak_256(x)) + return Some(keccak_256(x)); } None }); diff --git a/bridges/snowbridge/primitives/beacon/src/serde_utils.rs b/bridges/snowbridge/primitives/beacon/src/serde_utils.rs index 07f5cbe724ed9..7e4688d298b19 100644 --- a/bridges/snowbridge/primitives/beacon/src/serde_utils.rs +++ b/bridges/snowbridge/primitives/beacon/src/serde_utils.rs @@ -118,7 +118,7 @@ impl<'de, const LENGTH: usize> serde::de::Visitor<'de> for HexVisitor { Err(e) => return Err(serde::de::Error::custom(e.to_string())), }; if decoded.len() != LENGTH { - return Err(serde::de::Error::custom("publickey expected to be 48 characters")) + return Err(serde::de::Error::custom("publickey expected to be 48 characters")); } let data: Self::Value = decoded diff --git a/bridges/snowbridge/primitives/core/src/inbound.rs b/bridges/snowbridge/primitives/core/src/inbound.rs index 4b04470ad0261..b43bff054fdb8 100644 --- a/bridges/snowbridge/primitives/core/src/inbound.rs +++ b/bridges/snowbridge/primitives/core/src/inbound.rs @@ -56,7 +56,7 @@ pub struct Log { impl Log { pub fn validate(&self) -> Result<(), LogValidationError> { if self.topics.len() > MAX_TOPICS { - return Err(LogValidationError::TooManyTopics) + return Err(LogValidationError::TooManyTopics); } Ok(()) } diff --git a/bridges/snowbridge/primitives/core/src/pricing.rs b/bridges/snowbridge/primitives/core/src/pricing.rs index 33aeda6d15c47..03a86bd4f7081 100644 --- a/bridges/snowbridge/primitives/core/src/pricing.rs +++ b/bridges/snowbridge/primitives/core/src/pricing.rs @@ -32,16 +32,16 @@ where { pub fn validate(&self) -> Result<(), InvalidPricingParameters> { if self.exchange_rate == FixedU128::zero() { - return Err(InvalidPricingParameters) + return Err(InvalidPricingParameters); } if self.fee_per_gas == U256::zero() { - return Err(InvalidPricingParameters) + return Err(InvalidPricingParameters); } if self.rewards.local.is_zero() { - return Err(InvalidPricingParameters) + return Err(InvalidPricingParameters); } if self.rewards.remote.is_zero() { - return Err(InvalidPricingParameters) + return Err(InvalidPricingParameters); } Ok(()) } diff --git a/bridges/snowbridge/primitives/ethereum/src/header.rs b/bridges/snowbridge/primitives/ethereum/src/header.rs index f0b51f8c79de8..d471e665c5c87 100644 --- a/bridges/snowbridge/primitives/ethereum/src/header.rs +++ b/bridges/snowbridge/primitives/ethereum/src/header.rs @@ -105,7 +105,7 @@ impl Header { let final_hash: Option<[u8; 32]> = iter.try_fold(keccak_256(first_bytes), |acc, x| { let node: Box = x.as_slice().try_into().ok()?; if (*node).contains_hash(acc.into()) { - return Some(keccak_256(x)) + return Some(keccak_256(x)); } None }); @@ -140,7 +140,7 @@ impl Header { fn decoded_seal_field(&self, index: usize, max_len: usize) -> Option { let bytes: Bytes = rlp::decode(self.seal.get(index)?).ok()?; if bytes.len() > max_len { - return None + return None; } Some(bytes) } diff --git a/bridges/snowbridge/primitives/ethereum/src/receipt.rs b/bridges/snowbridge/primitives/ethereum/src/receipt.rs index 665a93dbb1e21..6bbe84c1b1e84 100644 --- a/bridges/snowbridge/primitives/ethereum/src/receipt.rs +++ b/bridges/snowbridge/primitives/ethereum/src/receipt.rs @@ -55,7 +55,7 @@ impl rlp::Decodable for Receipt { 1 | 2 => { let receipt_rlp = &rlp::Rlp::new(&data[1..]); if !receipt_rlp.is_list() { - return Err(rlp::DecoderError::RlpExpectedToBeList) + return Err(rlp::DecoderError::RlpExpectedToBeList); } Self::decode_list(&rlp::Rlp::new(&data[1..])) }, diff --git a/bridges/snowbridge/primitives/router/src/outbound/mod.rs b/bridges/snowbridge/primitives/router/src/outbound/mod.rs index ddc36ce8cb61b..9490e84c19945 100644 --- a/bridges/snowbridge/primitives/router/src/outbound/mod.rs +++ b/bridges/snowbridge/primitives/router/src/outbound/mod.rs @@ -48,13 +48,13 @@ where if network != expected_network { log::trace!(target: "xcm::ethereum_blob_exporter", "skipped due to unmatched bridge network {network:?}."); - return Err(SendError::NotApplicable) + return Err(SendError::NotApplicable); } let dest = destination.take().ok_or(SendError::MissingArgument)?; if dest != Here { log::trace!(target: "xcm::ethereum_blob_exporter", "skipped due to unmatched remote destination {dest:?}."); - return Err(SendError::NotApplicable) + return Err(SendError::NotApplicable); } let (local_net, local_sub) = universal_source @@ -71,14 +71,14 @@ where if Ok(local_net) != universal_location.global_consensus() { log::trace!(target: "xcm::ethereum_blob_exporter", "skipped due to unmatched relay network {local_net:?}."); - return Err(SendError::NotApplicable) + return Err(SendError::NotApplicable); } let para_id = match local_sub.as_slice() { [Parachain(para_id)] => *para_id, _ => { log::error!(target: "xcm::ethereum_blob_exporter", "could not get parachain id from universal source '{local_sub:?}'."); - return Err(SendError::MissingArgument) + return Err(SendError::MissingArgument); }, }; @@ -98,7 +98,7 @@ where Some(id) => id, None => { log::error!(target: "xcm::ethereum_blob_exporter", "unroutable due to not being able to create agent id. '{source_location:?}'"); - return Err(SendError::Unroutable) + return Err(SendError::Unroutable); }, }; @@ -180,7 +180,7 @@ impl<'a, Call> XcmConverter<'a, Call> { // All xcm instructions must be consumed before exit. if self.next().is_ok() { - return Err(XcmConverterError::EndOfXcmMessageExpected) + return Err(XcmConverterError::EndOfXcmMessageExpected); } Ok(result) @@ -225,12 +225,12 @@ impl<'a, Call> XcmConverter<'a, Call> { // Make sure there are reserved assets. if reserve_assets.len() == 0 { - return Err(NoReserveAssets) + return Err(NoReserveAssets); } // Check the the deposit asset filter matches what was reserved. if reserve_assets.inner().iter().any(|asset| !deposit_assets.matches(asset)) { - return Err(FilterDoesNotConsumeAllAssets) + return Err(FilterDoesNotConsumeAllAssets); } // We only support a single asset at a time. @@ -241,17 +241,18 @@ impl<'a, Call> XcmConverter<'a, Call> { if let Some(fee_asset) = fee_asset { // The fee asset must be the same as the reserve asset. if fee_asset.id != reserve_asset.id || fee_asset.fun > reserve_asset.fun { - return Err(InvalidFeeAsset) + return Err(InvalidFeeAsset); } } let (token, amount) = match reserve_asset { - Asset { id: AssetId(inner_location), fun: Fungible(amount) } => + Asset { id: AssetId(inner_location), fun: Fungible(amount) } => { match inner_location.unpack() { (0, [AccountKey20 { network, key }]) if self.network_matches(network) => Some((H160(*key), *amount)), _ => None, - }, + } + }, _ => None, } .ok_or(AssetResolutionFailed)?; diff --git a/bridges/snowbridge/runtime/runtime-common/src/lib.rs b/bridges/snowbridge/runtime/runtime-common/src/lib.rs index aae45520ff4bd..2c371c6efa413 100644 --- a/bridges/snowbridge/runtime/runtime-common/src/lib.rs +++ b/bridges/snowbridge/runtime/runtime-common/src/lib.rs @@ -67,7 +67,7 @@ impl {}, _ => { println!("Aborted"); - return Ok(()) + return Ok(()); }, } } diff --git a/cumulus/client/collator/src/lib.rs b/cumulus/client/collator/src/lib.rs index 83249186f626f..6a9e7f1ec8991 100644 --- a/cumulus/client/collator/src/lib.rs +++ b/cumulus/client/collator/src/lib.rs @@ -95,13 +95,13 @@ where error = ?e, "Could not decode the head data." ); - return None + return None; }, }; let last_head_hash = last_head.hash(); if !self.service.check_block_status(last_head_hash, &last_head) { - return None + return None; } tracing::info!( @@ -214,7 +214,7 @@ pub mod relay_chain_driven { CollationRequest { relay_parent, pvd: validation_data, sender: this_tx }; if stream_tx.send(request).await.is_err() { - return None + return None; } this_rx.await.ok().flatten() diff --git a/cumulus/client/collator/src/service.rs b/cumulus/client/collator/src/service.rs index c06be006fc17f..7db13ab5aaaa2 100644 --- a/cumulus/client/collator/src/service.rs +++ b/cumulus/client/collator/src/service.rs @@ -192,7 +192,7 @@ where target: LOG_TARGET, "Could not fetch `CollectCollationInfo` runtime api version." ); - return Ok(None) + return Ok(None); }, }; @@ -228,7 +228,7 @@ where Ok(proof) => proof, Err(e) => { tracing::error!(target: "cumulus-collator", "Failed to compact proof: {:?}", e); - return None + return None; }, }; diff --git a/cumulus/client/consensus/aura/src/collators/basic.rs b/cumulus/client/consensus/aura/src/collators/basic.rs index 8740b06005d65..139fb422db6b1 100644 --- a/cumulus/client/consensus/aura/src/collators/basic.rs +++ b/cumulus/client/consensus/aura/src/collators/basic.rs @@ -169,7 +169,7 @@ where let parent_hash = parent_header.hash(); if !collator.collator_service().check_block_status(parent_hash, &parent_header) { - continue + continue; } let relay_parent_header = @@ -203,7 +203,7 @@ where // With https://github.com/paritytech/polkadot-sdk/issues/3168 this implementation will be // obsolete and also the underlying issue will be fixed. if last_processed_slot >= *claim.slot() { - continue + continue; } let (parachain_inherent_data, other_inherent_data) = try_request!( diff --git a/cumulus/client/consensus/aura/src/collators/lookahead.rs b/cumulus/client/consensus/aura/src/collators/lookahead.rs index a9f33173d832a..67d88bd4af391 100644 --- a/cumulus/client/consensus/aura/src/collators/lookahead.rs +++ b/cumulus/client/consensus/aura/src/collators/lookahead.rs @@ -163,7 +163,7 @@ where "Failed to initialize consensus: no relay chain import notification stream" ); - return + return; }, }; @@ -192,7 +192,7 @@ where "Para is not scheduled on any core, skipping import notification", ); - continue + continue; } let max_pov_size = match params @@ -208,7 +208,7 @@ where Ok(Some(pvd)) => pvd.max_pov_size, Err(err) => { tracing::error!(target: crate::LOG_TARGET, ?err, "Failed to gather information from relay-client"); - continue + continue; }, }; @@ -237,7 +237,7 @@ where "Could not fetch potential parents to build upon" ); - continue + continue; }, Ok(x) => x, }; @@ -257,7 +257,7 @@ where Ok(sd) => sd, Err(err) => { tracing::error!(target: crate::LOG_TARGET, ?err, "Failed to acquire parachain slot duration"); - return None + return None; }, }; tracing::debug!(target: crate::LOG_TARGET, ?slot_duration, ?block_hash, "Parachain slot duration acquired"); @@ -339,7 +339,7 @@ where { Err(err) => { tracing::error!(target: crate::LOG_TARGET, ?err); - break + break; }, Ok(x) => x, }; @@ -348,7 +348,7 @@ where { None => { tracing::error!(target: crate::LOG_TARGET, ?parent_hash, "Could not fetch validation code hash"); - break + break; }, Some(v) => v, }; @@ -398,11 +398,11 @@ where }, Ok(None) => { tracing::debug!(target: crate::LOG_TARGET, "No block proposal"); - break + break; }, Err(err) => { tracing::error!(target: crate::LOG_TARGET, ?err); - break + break; }, } } @@ -436,7 +436,7 @@ where // collator against chains which have not yet upgraded their runtime. if parent_hash != included_block { if !runtime_api.can_build_upon(parent_hash, included_block, slot).ok()? { - return None + return None; } } @@ -494,7 +494,7 @@ async fn is_para_scheduled( ?relay_parent, "Failed to query availability cores runtime API", ); - return false + return false; }, Err(oneshot::Canceled) => { tracing::error!( @@ -502,7 +502,7 @@ async fn is_para_scheduled( ?relay_parent, "Sender for availability cores runtime request dropped", ); - return false + return false; }, }; diff --git a/cumulus/client/consensus/aura/src/equivocation_import_queue.rs b/cumulus/client/consensus/aura/src/equivocation_import_queue.rs index 5cd65ed5546ba..c2b11c2e2e430 100644 --- a/cumulus/client/consensus/aura/src/equivocation_import_queue.rs +++ b/cumulus/client/consensus/aura/src/equivocation_import_queue.rs @@ -97,7 +97,7 @@ where // This is done for example when gap syncing and it is expected that the block after the gap // was checked/chosen properly, e.g. by warp syncing to this block using a finality proof. if block_params.state_action.skip_execution_checks() || block_params.with_state() { - return Ok(block_params) + return Ok(block_params); } let post_hash = block_params.header.hash(); @@ -136,7 +136,7 @@ where return Err(format!( "Rejecting block {:?} due to excessive equivocations at slot", post_hash, - )) + )); } }, Err(aura_internal::SealVerificationError::Deferred(hdr, slot)) => { @@ -152,7 +152,7 @@ where return Err(format!( "Rejecting block ({:?}) from future slot {:?}", post_hash, slot - )) + )); }, Err(e) => return Err(format!( diff --git a/cumulus/client/consensus/aura/src/lib.rs b/cumulus/client/consensus/aura/src/lib.rs index 8e4bc658e44bf..e78143a50e028 100644 --- a/cumulus/client/consensus/aura/src/lib.rs +++ b/cumulus/client/consensus/aura/src/lib.rs @@ -240,7 +240,7 @@ where // With https://github.com/paritytech/polkadot-sdk/issues/3168 this implementation will be // obsolete and also the underlying issue will be fixed. if self.last_slot_processed.fetch_max(*info.slot, Ordering::Relaxed) >= *info.slot { - return None + return None; } let res = self.aura_worker.lock().await.on_slot(info).await?; diff --git a/cumulus/client/consensus/common/src/level_monitor.rs b/cumulus/client/consensus/common/src/level_monitor.rs index 270e3f57ae5a3..f0ce263d843d8 100644 --- a/cumulus/client/consensus/common/src/level_monitor.rs +++ b/cumulus/client/consensus/common/src/level_monitor.rs @@ -117,7 +117,7 @@ where "Could not fetch header metadata for leaf: {leaf:?}", ); - continue + continue; }; self.import_counter = self.import_counter.max(meta.number); @@ -127,7 +127,7 @@ where self.freshness.insert(meta.hash, meta.number); self.levels.entry(meta.number).or_default().insert(meta.hash); if meta.number <= self.lowest_level { - break + break; } meta = match self.backend.blockchain().header_metadata(meta.parent) { @@ -139,7 +139,7 @@ where "Could not fetch header metadata for parent: {:?}", meta.parent, ); - break + break; }, } } @@ -169,7 +169,7 @@ where pub fn enforce_limit(&mut self, number: NumberFor) { let level_len = self.levels.get(&number).map(|l| l.len()).unwrap_or_default(); if level_len < self.level_limit { - return + return; } // Sort leaves by freshness only once (less fresh first) and keep track of @@ -274,7 +274,7 @@ where "Unable getting route to any leaf from {:?} (this is a bug)", blk_hash, ); - continue + continue; }, }; @@ -302,7 +302,7 @@ where target_info = Some(candidate_info); if early_stop { // We will never find a candidate with an worst freshest leaf than this. - break + break; } } } @@ -324,7 +324,7 @@ where log::debug!(target: LOG_TARGET, "Removing block (@{}) {:?}", number, hash); if let Err(err) = self.backend.remove_leaf_block(hash) { log::debug!(target: LOG_TARGET, "Remove not possible for {}: {}", hash, err); - return false + return false; } self.levels.get_mut(&number).map(|level| level.remove(&hash)); self.freshness.remove(&hash); @@ -355,7 +355,7 @@ where let to_skip = leaves.len() - target.freshest_leaf_idx; leaves.iter().enumerate().rev().skip(to_skip).for_each(|(leaf_idx, leaf_hash)| { if invalidated_leaves.contains(&leaf_idx) { - return + return; } match sp_blockchain::tree_route(self.backend.blockchain(), target_hash, *leaf_hash) { Ok(route) if route.retracted().is_empty() => { diff --git a/cumulus/client/consensus/common/src/lib.rs b/cumulus/client/consensus/common/src/lib.rs index cebe34e7ea588..b576e3b587dab 100644 --- a/cumulus/client/consensus/common/src/lib.rs +++ b/cumulus/client/consensus/common/src/lib.rs @@ -297,7 +297,7 @@ pub async fn find_potential_parents( if let Some(required_session) = required_session { // Respect the relay-chain rule not to cross session boundaries. if session != required_session { - break + break; } } else { required_session = Some(session); @@ -308,7 +308,7 @@ pub async fn find_potential_parents( // don't iterate back into the genesis block. if header.number == 1 { - break + break; } } @@ -385,7 +385,7 @@ pub async fn find_potential_parents( } if !is_potential || child_depth > params.max_depth { - continue + continue; } // push children onto search frontier. @@ -398,7 +398,7 @@ pub async fn find_potential_parents( }; if params.ignore_alternative_branches && !aligned_with_pending { - continue + continue; } let header = match client.blockchain().header(child) { diff --git a/cumulus/client/consensus/common/src/parachain_consensus.rs b/cumulus/client/consensus/common/src/parachain_consensus.rs index b4b315bb32be6..122e4aed7b3c7 100644 --- a/cumulus/client/consensus/common/src/parachain_consensus.rs +++ b/cumulus/client/consensus/common/src/parachain_consensus.rs @@ -53,7 +53,7 @@ fn handle_new_finalized_head( error = ?err, "Could not decode parachain header while following finalized heads.", ); - return + return; }, }; @@ -101,7 +101,7 @@ where Ok(finalized_heads_stream) => finalized_heads_stream.fuse(), Err(err) => { tracing::error!(target: LOG_TARGET, error = ?err, "Unable to retrieve finalized heads stream."); - return + return; }, }; @@ -233,7 +233,7 @@ async fn follow_new_best( Ok(best_heads_stream) => best_heads_stream.fuse(), Err(err) => { tracing::error!(target: LOG_TARGET, error = ?err, "Unable to retrieve best heads stream."); - return + return; }, }; @@ -310,12 +310,12 @@ async fn handle_new_block_imported( }; let unset_hash = if notification.header.number() < unset_best_header.number() { - return + return; } else if notification.header.number() == unset_best_header.number() { let unset_hash = unset_best_header.hash(); if unset_hash != notification.hash { - return + return; } else { unset_hash } @@ -364,7 +364,7 @@ async fn handle_new_best_parachain_head( error = ?err, "Could not decode Parachain header while following best heads.", ); - return + return; }, }; @@ -450,7 +450,7 @@ async fn import_block_as_new_best( "Skipping importing block as new best block, because there already exists a \ best block with an higher number", ); - return + return; } // Make it the new best block diff --git a/cumulus/client/consensus/common/src/tests.rs b/cumulus/client/consensus/common/src/tests.rs index 597d1ab2acc2c..6e34e0b997c74 100644 --- a/cumulus/client/consensus/common/src/tests.rs +++ b/cumulus/client/consensus/common/src/tests.rs @@ -131,7 +131,7 @@ impl RelayChainInterface for Relaychain { _ => &inner.relay_chain_hash_to_header, }; let Some(parent_head) = relay_to_header.get(&hash).map(|head| head.encode().into()) else { - return Ok(None) + return Ok(None); }; Ok(Some(PersistedValidationData { parent_head, ..Default::default() })) } @@ -367,7 +367,7 @@ fn follow_new_best_works() { loop { Delay::new(Duration::from_millis(100)).await; if block.hash() == client.usage_info().chain.best_hash { - break + break; } } }; @@ -420,7 +420,7 @@ fn follow_new_best_with_dummy_recovery_works() { status => { assert_eq!(block.hash(), client.usage_info().chain.best_hash); assert_eq!(status, BlockStatus::InChainWithState); - break + break; }, } } @@ -468,7 +468,7 @@ fn follow_finalized_works() { loop { Delay::new(Duration::from_millis(100)).await; if block.hash() == client.usage_info().chain.finalized_hash { - break + break; } } }; @@ -515,7 +515,7 @@ fn follow_finalized_does_not_stop_on_unknown_block() { loop { Delay::new(Duration::from_millis(100)).await; if block.hash() == client.usage_info().chain.finalized_hash { - break + break; } } }; @@ -560,7 +560,7 @@ fn follow_new_best_sets_best_after_it_is_imported() { loop { Delay::new(Duration::from_millis(100)).await; if block.hash() == client.usage_info().chain.best_hash { - break + break; } } @@ -585,7 +585,7 @@ fn follow_new_best_sets_best_after_it_is_imported() { loop { Delay::new(Duration::from_millis(100)).await; if unknown_block.hash() == client.usage_info().chain.best_hash { - break + break; } } }; diff --git a/cumulus/client/consensus/relay-chain/src/import_queue.rs b/cumulus/client/consensus/relay-chain/src/import_queue.rs index f44f440932437..81c5f000e06db 100644 --- a/cumulus/client/consensus/relay-chain/src/import_queue.rs +++ b/cumulus/client/consensus/relay-chain/src/import_queue.rs @@ -64,7 +64,7 @@ where // This is done for example when gap syncing and it is expected that the block after the gap // was checked/chosen properly, e.g. by warp syncing to this block using a finality proof. if block_params.state_action.skip_execution_checks() || block_params.with_state() { - return Ok(block_params) + return Ok(block_params); } if let Some(inner_body) = block_params.body.take() { diff --git a/cumulus/client/consensus/relay-chain/src/lib.rs b/cumulus/client/consensus/relay-chain/src/lib.rs index fc395a9d9573f..b5f61844f3a41 100644 --- a/cumulus/client/consensus/relay-chain/src/lib.rs +++ b/cumulus/client/consensus/relay-chain/src/lib.rs @@ -205,7 +205,7 @@ where "Error importing build block.", ); - return None + return None; } Some(ParachainCandidate { block, proof }) diff --git a/cumulus/client/network/src/lib.rs b/cumulus/client/network/src/lib.rs index ebd557b805c5d..96e19eccc10fe 100644 --- a/cumulus/client/network/src/lib.rs +++ b/cumulus/client/network/src/lib.rs @@ -95,7 +95,7 @@ impl BlockAnnounceData { h } else { tracing::debug!(target: LOG_TARGET, "`CompactStatement` isn't the candidate variant!",); - return Err(Validation::Failure { disconnect: true }) + return Err(Validation::Failure { disconnect: true }); }; if *candidate_hash != self.receipt.hash() { @@ -103,7 +103,7 @@ impl BlockAnnounceData { target: LOG_TARGET, "Receipt candidate hash doesn't match candidate hash in statement", ); - return Err(Validation::Failure { disconnect: true }) + return Err(Validation::Failure { disconnect: true }); } if HeadData(encoded_header).hash() != self.receipt.descriptor.para_head { @@ -111,7 +111,7 @@ impl BlockAnnounceData { target: LOG_TARGET, "Receipt para head hash doesn't match the hash of the header in the block announcement", ); - return Err(Validation::Failure { disconnect: true }) + return Err(Validation::Failure { disconnect: true }); } Ok(()) @@ -150,7 +150,7 @@ impl BlockAnnounceData { "Block announcement justification signer is a validator index out of bound", ); - return Ok(Validation::Failure { disconnect: true }) + return Ok(Validation::Failure { disconnect: true }); }, }; @@ -161,7 +161,7 @@ impl BlockAnnounceData { "Block announcement justification signature is invalid.", ); - return Ok(Validation::Failure { disconnect: true }) + return Ok(Validation::Failure { disconnect: true }); } Ok(Validation::Success { is_new_best: true }) @@ -175,7 +175,7 @@ impl TryFrom<&'_ CollationSecondedSignal> for BlockAnnounceData { let receipt = if let Statement::Seconded(receipt) = signal.statement.payload() { receipt.to_plain() } else { - return Err(()) + return Err(()); }; Ok(BlockAnnounceData { @@ -349,11 +349,11 @@ where .unwrap_or(false); if relay_chain_is_syncing { - return Ok(Validation::Success { is_new_best: false }) + return Ok(Validation::Success { is_new_best: false }); } if data.is_empty() { - return block_announce_validator.handle_empty_block_announce_data(header).await + return block_announce_validator.handle_empty_block_announce_data(header).await; } let block_announce_data = match BlockAnnounceData::decode_all(&mut data.as_slice()) { @@ -366,7 +366,7 @@ where }; if let Err(e) = block_announce_data.validate(header_encoded) { - return Ok(e) + return Ok(e); } let relay_parent = block_announce_data.receipt.descriptor.relay_parent; @@ -447,7 +447,7 @@ async fn wait_to_announce( block = ?block_hash, "Wait to announce stopped, because sender was dropped.", ); - return + return; }, }; diff --git a/cumulus/client/network/src/tests.rs b/cumulus/client/network/src/tests.rs index e03f470753bb6..54bdf6f81bbf2 100644 --- a/cumulus/client/network/src/tests.rs +++ b/cumulus/client/network/src/tests.rs @@ -248,7 +248,7 @@ impl RelayChainInterface for DummyRelayChainInterface { if let Some(hash) = self.relay_client.hash(num)? { hash } else { - return Ok(None) + return Ok(None); }, }; let header = self.relay_client.header(hash)?; diff --git a/cumulus/client/pov-recovery/src/active_candidate_recovery.rs b/cumulus/client/pov-recovery/src/active_candidate_recovery.rs index 2c635320ff4ae..e418077922d1a 100644 --- a/cumulus/client/pov-recovery/src/active_candidate_recovery.rs +++ b/cumulus/client/pov-recovery/src/active_candidate_recovery.rs @@ -97,7 +97,7 @@ impl ActiveCandidateRecovery { loop { if let Some(res) = self.recoveries.next().await { self.candidates.remove(&res.0); - return res + return res; } else { futures::pending!() } diff --git a/cumulus/client/pov-recovery/src/lib.rs b/cumulus/client/pov-recovery/src/lib.rs index 32aba6c8993a6..e20436175c907 100644 --- a/cumulus/client/pov-recovery/src/lib.rs +++ b/cumulus/client/pov-recovery/src/lib.rs @@ -193,7 +193,7 @@ impl RecoveryQueue { loop { if self.signaling_queue.next().await.is_some() { if let Some(hash) = self.recovery_queue.pop_front() { - return hash + return hash; } else { tracing::error!( target: LOG_TARGET, @@ -277,18 +277,18 @@ where error = ?e, "Failed to decode parachain header from pending candidate", ); - return + return; }, }; if *header.number() <= self.parachain_client.usage_info().chain.finalized_number { - return + return; } let hash = header.hash(); if self.candidates.contains_key(&hash) { - return + return; } tracing::debug!(target: LOG_TARGET, block_hash = ?hash, "Adding outstanding candidate"); @@ -356,7 +356,7 @@ where if self.candidates_in_retry.insert(block_hash) { tracing::debug!(target: LOG_TARGET, ?block_hash, "Recovery failed, retrying."); self.candidate_recovery_queue.push_recovery(block_hash); - return + return; } else { tracing::warn!( target: LOG_TARGET, @@ -365,7 +365,7 @@ where ); self.candidates_in_retry.remove(&block_hash); self.reset_candidate(block_hash); - return + return; }, }; @@ -376,7 +376,7 @@ where tracing::debug!(target: LOG_TARGET, ?error, "Failed to decompress PoV"); self.reset_candidate(block_hash); - return + return; }, }; @@ -390,7 +390,7 @@ where ); self.reset_candidate(block_hash); - return + return; }, }; @@ -415,7 +415,7 @@ where ); self.waiting_for_parent.entry(parent).or_default().push(block); - return + return; } else { tracing::debug!( target: LOG_TARGET, @@ -425,7 +425,7 @@ where ); self.reset_candidate(block_hash); - return + return; } }, Err(error) => { @@ -437,7 +437,7 @@ where ); self.reset_candidate(block_hash); - return + return; }, // Any other status is fine to "ignore/accept" _ => (), @@ -497,7 +497,7 @@ where block_hash = ?hash, "Cound not recover. Block was never announced as candidate" ); - return + return; }, }; @@ -517,12 +517,12 @@ where for hash in to_recover { self.clear_waiting_recovery(&hash); } - return + return; }, } if kind == RecoveryKind::Simple { - break + break; } hash = candidate.parent_hash; @@ -547,7 +547,7 @@ where Ok(pending_candidate_stream) => pending_candidate_stream.fuse(), Err(err) => { tracing::error!(target: LOG_TARGET, error = ?err, "Unable to retrieve pending candidate stream."); - return + return; }, }; @@ -629,7 +629,7 @@ async fn pending_candidates( relay_hash = ?hash, "Skipping candidate due to sync.", ); - return None + return None; } let pending_availability_result = client_for_closure diff --git a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs index 866214fe2c526..b536e18da527b 100644 --- a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs +++ b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs @@ -94,7 +94,7 @@ impl RelayChainInterface for RelayChainInProcessInterface { if let Some(hash) = self.full_client.hash(num)? { hash } else { - return Ok(None) + return Ok(None); }, }; let header = self.full_client.header(hash)?; @@ -256,7 +256,7 @@ pub fn check_block_in_chain( let _lock = backend.get_import_lock().read(); if backend.blockchain().status(hash)? == BlockStatus::InChain { - return Ok(BlockCheckStatus::InChain) + return Ok(BlockCheckStatus::InChain); } let listener = client.import_notification_stream(); diff --git a/cumulus/client/relay-chain-minimal-node/src/network.rs b/cumulus/client/relay-chain-minimal-node/src/network.rs index 95785063c1aeb..b8f8e37eb4111 100644 --- a/cumulus/client/relay-chain-minimal-node/src/network.rs +++ b/cumulus/client/relay-chain-minimal-node/src/network.rs @@ -104,7 +104,7 @@ pub(crate) fn build_collator_network( ); // This `return` might seem unnecessary, but we don't want to make it look like // everything is working as normal even though the user is clearly misusing the API. - return + return; } network_worker.run().await; diff --git a/cumulus/client/relay-chain-rpc-interface/src/lib.rs b/cumulus/client/relay-chain-rpc-interface/src/lib.rs index 96f8fc8b55633..9754aa24317fc 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/lib.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/lib.rs @@ -87,12 +87,13 @@ impl RelayChainInterface for RelayChainRpcInterface { async fn header(&self, block_id: BlockId) -> RelayChainResult> { let hash = match block_id { BlockId::Hash(hash) => hash, - BlockId::Number(num) => + BlockId::Number(num) => { if let Some(hash) = self.rpc_client.chain_get_block_hash(Some(num)).await? { hash } else { - return Ok(None) - }, + return Ok(None); + } + }, }; let header = self.rpc_client.chain_get_header(Some(hash)).await?; @@ -202,7 +203,7 @@ impl RelayChainInterface for RelayChainRpcInterface { let mut head_stream = self.rpc_client.get_imported_heads_stream()?; if self.rpc_client.chain_get_header(Some(wait_for_hash)).await?.is_some() { - return Ok(()) + return Ok(()); } let mut timeout = futures_timer::Delay::new(Duration::from_secs(TIMEOUT_IN_SECONDS)).fuse(); diff --git a/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs b/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs index 9a49b60281b3c..90662649e2de9 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs @@ -196,7 +196,7 @@ impl LightClientRpcWorker { target: LOG_TARGET, "Unable to initialize new heads subscription" ); - return + return; }; let Ok(mut finalized_head_subscription) = @@ -212,7 +212,7 @@ impl LightClientRpcWorker { target: LOG_TARGET, "Unable to initialize finalized heads subscription" ); - return + return; }; let Ok(mut all_head_subscription) = Option { // This is already validated on CLI side, just defensive here if (url.scheme() != "ws" && url.scheme() != "wss") || url.host_str().is_none() { tracing::warn!(target: LOG_TARGET, ?url, "Non-WebSocket URL or missing host."); - return None + return None; } // Either we have a user-supplied port or use the default for 'ws' or 'wss' here @@ -118,7 +118,7 @@ async fn connect_next_available_rpc_server( impl ClientManager { pub async fn new(urls: Vec) -> Result { if urls.is_empty() { - return Err(()) + return Err(()); } let active_client = connect_next_available_rpc_server(&urls, 0).await?; Ok(Self { urls, active_client: active_client.1, active_index: active_client.0 }) @@ -205,7 +205,7 @@ impl ClientManager { // the websocket connection is dead and requires a restart. // Other errors should be forwarded to the request caller. if let Err(JsonRpseeError::RestartNeeded(_)) = resp { - return Err(RpcDispatcherMessage::Request(method, params, response_sender)) + return Err(RpcDispatcherMessage::Request(method, params, response_sender)); } if let Err(err) = response_sender.send(resp) { @@ -267,7 +267,7 @@ impl ReconnectingWebsocketWorker { } if client_manager.connect_to_new_rpc_server().await.is_err() { - return Err("Unable to find valid external RPC server, shutting down.".to_string()) + return Err("Unable to find valid external RPC server, shutting down.".to_string()); }; for item in requests_to_retry.into_iter() { @@ -300,11 +300,11 @@ impl ReconnectingWebsocketWorker { let urls = std::mem::take(&mut self.ws_urls); let Ok(mut client_manager) = ClientManager::new(urls).await else { tracing::error!(target: LOG_TARGET, "No valid RPC url found. Stopping RPC worker."); - return + return; }; let Ok(mut subscriptions) = client_manager.get_subscriptions().await else { tracing::error!(target: LOG_TARGET, "Unable to fetch subscriptions on initial connection."); - return + return; }; let mut imported_blocks_cache = LruMap::new(ByLength::new(40)); @@ -330,7 +330,7 @@ impl ReconnectingWebsocketWorker { message, "Unable to reconnect, stopping worker." ); - return + return; }, } should_reconnect = ConnectionStatus::Connected; diff --git a/cumulus/client/service/src/lib.rs b/cumulus/client/service/src/lib.rs index 950e59aff24ec..0849ad31f19b3 100644 --- a/cumulus/client/service/src/lib.rs +++ b/cumulus/client/service/src/lib.rs @@ -571,7 +571,7 @@ where finalized_header.hash() ); let _ = sender.send(finalized_header); - return Ok(()) + return Ok(()); } } diff --git a/cumulus/pallets/aura-ext/src/consensus_hook.rs b/cumulus/pallets/aura-ext/src/consensus_hook.rs index 089ab5c3198b9..c0c09e139d01b 100644 --- a/cumulus/pallets/aura-ext/src/consensus_hook.rs +++ b/cumulus/pallets/aura-ext/src/consensus_hook.rs @@ -110,7 +110,7 @@ impl< // can never author when the unincluded segment is full. if size_after_included >= C { - return false + return false; } if last_slot == new_slot { diff --git a/cumulus/pallets/collator-selection/src/lib.rs b/cumulus/pallets/collator-selection/src/lib.rs index 7449f4d68c7ea..62e2e247cf0d6 100644 --- a/cumulus/pallets/collator-selection/src/lib.rs +++ b/cumulus/pallets/collator-selection/src/lib.rs @@ -400,7 +400,7 @@ pub mod pallet { Self::deposit_event(Event::InvalidInvulnerableSkipped { account_id: account_id.clone(), }); - continue + continue; } // else condition passes; key is registered }, @@ -409,7 +409,7 @@ pub mod pallet { Self::deposit_event(Event::InvalidInvulnerableSkipped { account_id: account_id.clone(), }); - continue + continue; }, } @@ -684,7 +684,7 @@ pub mod pallet { ); T::Currency::unreserve(&who, old_deposit - new_deposit); } else { - return Err(Error::::IdenticalDeposit.into()) + return Err(Error::::IdenticalDeposit.into()); } // Update the deposit and insert the candidate in the correct spot in the list. diff --git a/cumulus/pallets/dmp-queue/src/lib.rs b/cumulus/pallets/dmp-queue/src/lib.rs index 79cc4bc895ec2..95a8bdb70db39 100644 --- a/cumulus/pallets/dmp-queue/src/lib.rs +++ b/cumulus/pallets/dmp-queue/src/lib.rs @@ -156,7 +156,7 @@ pub mod pallet { if meter.try_consume(Self::on_idle_weight()).is_err() { log::debug!(target: LOG, "Not enough weight for on_idle. {} < {}", Self::on_idle_weight(), limit); - return meter.consumed() + return meter.consumed(); } let state = MigrationStatus::::get(); diff --git a/cumulus/pallets/dmp-queue/src/migration.rs b/cumulus/pallets/dmp-queue/src/migration.rs index 349635cce547d..cafbcacfc3988 100644 --- a/cumulus/pallets/dmp-queue/src/migration.rs +++ b/cumulus/pallets/dmp-queue/src/migration.rs @@ -79,13 +79,13 @@ pub(crate) fn migrate_page(p: PageCounter) -> Result<(), ()> { log::debug!(target: LOG, "Migrating page #{p} with {} messages ...", page.len()); if page.is_empty() { log::error!(target: LOG, "Page #{p}: EMPTY - storage corrupted?"); - return Err(()) + return Err(()); } for (m, (block, msg)) in page.iter().enumerate() { let Ok(bound) = BoundedVec::::try_from(msg.clone()) else { log::error!(target: LOG, "[Page {p}] Message #{m}: TOO LONG - dropping"); - continue + continue; }; T::DmpSink::handle_message(bound.as_bounded_slice()); @@ -99,11 +99,11 @@ pub(crate) fn migrate_page(p: PageCounter) -> Result<(), ()> { pub(crate) fn migrate_overweight(i: OverweightIndex) -> Result<(), ()> { let Some((block, msg)) = Overweight::::take(i) else { log::error!(target: LOG, "[Overweight {i}] Message: EMPTY - storage corrupted?"); - return Err(()) + return Err(()); }; let Ok(bound) = BoundedVec::::try_from(msg) else { log::error!(target: LOG, "[Overweight {i}] Message: TOO LONG - dropping"); - return Err(()) + return Err(()); }; T::DmpSink::handle_message(bound.as_bounded_slice()); diff --git a/cumulus/pallets/parachain-system/proc-macro/src/lib.rs b/cumulus/pallets/parachain-system/proc-macro/src/lib.rs index 8ab5d81efdcf4..57059b1d7ed9a 100644 --- a/cumulus/pallets/parachain-system/proc-macro/src/lib.rs +++ b/cumulus/pallets/parachain-system/proc-macro/src/lib.rs @@ -69,7 +69,7 @@ impl Parse for Input { } else if lookahead.peek(keywords::CheckInherents) { parse_inner::(input, &mut check_inherents)?; } else { - return Err(lookahead.error()) + return Err(lookahead.error()); } } diff --git a/cumulus/pallets/parachain-system/src/lib.rs b/cumulus/pallets/parachain-system/src/lib.rs index 5a0fa57fb171c..f102eac3a7b48 100644 --- a/cumulus/pallets/parachain-system/src/lib.rs +++ b/cumulus/pallets/parachain-system/src/lib.rs @@ -273,7 +273,7 @@ pub mod pallet { false, "host configuration is promised to set until `on_finalize`; qed", ); - return + return; }, }; @@ -288,7 +288,7 @@ pub mod pallet { "relevant messaging state is promised to be set until `on_finalize`; \ qed", ); - return + return; }, }; @@ -308,7 +308,7 @@ pub mod pallet { "relevant messaging state is promised to be set until `on_finalize`; \ qed", ); - return (0, 0) + return (0, 0); }, }; @@ -973,11 +973,11 @@ pub mod pallet { provides: vec![hash.as_ref().to_vec()], longevity: TransactionLongevity::max_value(), propagate: true, - }) + }); } } if let Call::set_validation_data { .. } = call { - return Ok(Default::default()) + return Ok(Default::default()); } Err(InvalidTransaction::Call.into()) } @@ -1042,7 +1042,7 @@ impl GetChannelInfo for Pallet { let channels = match Self::relevant_messaging_state() { None => { log::warn!("calling `get_channel_status` with no RelevantMessagingState?!"); - return ChannelStatus::Closed + return ChannelStatus::Closed; }, Some(d) => d.egress_channels, }; @@ -1059,7 +1059,7 @@ impl GetChannelInfo for Pallet { let meta = &channels[index].1; if meta.msg_count + 1 > meta.max_capacity { // The channel is at its capacity. Skip it for now. - return ChannelStatus::Full + return ChannelStatus::Full; } let max_size_now = meta.max_total_size - meta.total_size; let max_size_ever = meta.max_message_size; @@ -1562,7 +1562,7 @@ impl Pallet { // However, changing this setting is expected to be rare. if let Some(cfg) = Self::host_configuration() { if message_len > cfg.max_upward_message_size as usize { - return Err(MessageSendError::TooBig) + return Err(MessageSendError::TooBig); } let threshold = cfg.max_upward_queue_size.saturating_div(ump_constants::THRESHOLD_FACTOR); diff --git a/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs b/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs index 5519d1521ea6d..1ef768d74d4b0 100644 --- a/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs +++ b/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs @@ -168,7 +168,7 @@ impl RelayChainStateProof { ) -> Result { let db = proof.into_memory_db::>(); if !db.contains(&relay_parent_storage_root, EMPTY_PREFIX) { - return Err(Error::RootMismatch) + return Err(Error::RootMismatch); } let trie_backend = TrieBackendBuilder::new(db, relay_parent_storage_root).build(); diff --git a/cumulus/pallets/parachain-system/src/unincluded_segment.rs b/cumulus/pallets/parachain-system/src/unincluded_segment.rs index 1e83a945c4ee3..ed67ade4af2bf 100644 --- a/cumulus/pallets/parachain-system/src/unincluded_segment.rs +++ b/cumulus/pallets/parachain-system/src/unincluded_segment.rs @@ -160,7 +160,7 @@ impl HrmpChannelUpdate { recipient, messages_remaining: limits.messages_remaining, messages_submitted: new.msg_count, - }) + }); } new.total_bytes = new.total_bytes.saturating_add(other.total_bytes); if new.total_bytes > limits.bytes_remaining { @@ -168,7 +168,7 @@ impl HrmpChannelUpdate { recipient, bytes_remaining: limits.bytes_remaining, bytes_submitted: new.total_bytes, - }) + }); } Ok(new) @@ -209,14 +209,14 @@ impl UsedBandwidth { return Err(BandwidthUpdateError::UmpMessagesOverflow { messages_remaining: limits.ump_messages_remaining, messages_submitted: new.ump_msg_count, - }) + }); } new.ump_total_bytes = new.ump_total_bytes.saturating_add(other.ump_total_bytes); if new.ump_total_bytes > limits.ump_bytes_remaining { return Err(BandwidthUpdateError::UmpBytesOverflow { bytes_remaining: limits.ump_bytes_remaining, bytes_submitted: new.ump_total_bytes, - }) + }); } for (id, channel) in other.hrmp_outgoing.iter() { @@ -337,7 +337,7 @@ impl SegmentTracker { limits: &OutboundBandwidthLimits, ) -> Result<(), BandwidthUpdateError> { if self.consumed_go_ahead_signal.is_some() && block.consumed_go_ahead_signal.is_some() { - return Err(BandwidthUpdateError::UpgradeGoAheadAlreadyProcessed) + return Err(BandwidthUpdateError::UpgradeGoAheadAlreadyProcessed); } if let Some(watermark) = self.hrmp_watermark.as_ref() { if let HrmpWatermarkUpdate::Trunk(new) = new_watermark { @@ -345,7 +345,7 @@ impl SegmentTracker { return Err(BandwidthUpdateError::InvalidHrmpWatermark { submitted: new, latest: *watermark, - }) + }); } } } diff --git a/cumulus/pallets/xcmp-queue/src/bridging.rs b/cumulus/pallets/xcmp-queue/src/bridging.rs index 9db4b6e74c398..40f2fde42304b 100644 --- a/cumulus/pallets/xcmp-queue/src/bridging.rs +++ b/cumulus/pallets/xcmp-queue/src/bridging.rs @@ -32,7 +32,7 @@ impl, Runtime: crate::Config> // receive congestion reports from the bridge hub. So we assume the bridge pipeline is // congested too if pallet::Pallet::::is_inbound_channel_suspended(SiblingBridgeHubParaId::get()) { - return true + return true; } // if the outbound channel with recipient is suspended, it means that one of further @@ -58,11 +58,11 @@ impl, Runtime: crate::Config> let Some((outbound_state, queued_pages)) = pallet::Pallet::::outbound_channel_state(sibling_bridge_hub_id) else { - return false + return false; }; // suspended channel => it is congested if outbound_state == OutboundState::Suspended { - return true + return true; } // It takes some time for target parachain to suspend inbound channel with the target BH and @@ -77,7 +77,7 @@ impl, Runtime: crate::Config> const MAX_QUEUED_PAGES_BEFORE_DEACTIVATION: u16 = 4; if queued_pages > MAX_QUEUED_PAGES_BEFORE_DEACTIVATION { - return true + return true; } false diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 5b900769622af..ff3851360de1d 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -252,7 +252,7 @@ pub mod pallet { Self::on_idle_weight(), limit ); - return meter.consumed() + return meter.consumed(); } migration::v3::lazy_migrate_inbound_queue::(); @@ -469,7 +469,7 @@ impl Pallet { .checked_add(format_size) .ok_or(MessageSendError::TooBig)?; if size_to_check > max_message_size { - return Err(MessageSendError::TooBig) + return Err(MessageSendError::TooBig); } let mut all_channels = >::get(); @@ -498,10 +498,10 @@ impl Pallet { ) != Ok(format) { defensive!("Bad format in outbound queue; dropping message"); - return None + return None; } if page.len() + encoded_fragment.len() > max_message_size { - return None + return None; } page.extend_from_slice(&encoded_fragment[..]); Some(page.len()) @@ -594,7 +594,7 @@ impl Pallet { ) -> Result<(), ()> { if meter.try_consume(T::WeightInfo::enqueue_xcmp_message()).is_err() { defensive!("Out of weight: cannot enqueue XCMP messages; dropping msg"); - return Err(()) + return Err(()); } let QueueConfigData { drop_threshold, .. } = >::get(); @@ -605,7 +605,7 @@ impl Pallet { // This should not happen since the channel should have been suspended in // [`on_queue_changed`]. log::error!("XCMP queue for sibling {:?} is full; dropping messages.", sender); - return Err(()) + return Err(()); } T::XcmpQueue::enqueue_message(xcm.as_bounded_slice(), sender); @@ -621,12 +621,12 @@ impl Pallet { meter: &mut WeightMeter, ) -> Result>, ()> { if data.is_empty() { - return Err(()) + return Err(()); } if meter.try_consume(T::WeightInfo::take_first_concatenated_xcm()).is_err() { defensive!("Out of weight; could not decode all; dropping"); - return Err(()) + return Err(()); } let xcm = VersionedXcm::<()>::decode_with_depth_limit(MAX_XCM_DECODE_DEPTH, data) @@ -683,7 +683,7 @@ impl OnQueueChanged for Pallet { impl QueuePausedQuery for Pallet { fn is_paused(para: &ParaId) -> bool { if !QueueSuspended::::get() { - return false + return false; } // Make an exception for the superuser queue: @@ -710,7 +710,7 @@ impl XcmpMessageHandler for Pallet { Ok(f) => f, Err(_) => { defensive!("Unknown XCMP message format - dropping"); - continue + continue; }, }; @@ -725,7 +725,7 @@ impl XcmpMessageHandler for Pallet { .is_err() { defensive!("Not enough weight to process signals - dropping"); - break + break; } match ChannelSignal::decode(&mut data) { @@ -733,7 +733,7 @@ impl XcmpMessageHandler for Pallet { Ok(ChannelSignal::Resume) => Self::resume_channel(sender), Err(_) => { defensive!("Undecodable channel signal - dropping"); - break + break; }, } }, @@ -742,7 +742,7 @@ impl XcmpMessageHandler for Pallet { let Ok(xcm) = Self::take_first_concatenated_xcm(&mut data, &mut meter) else { defensive!("HRMP inbound decode stream broke; page will be dropped.",); - break + break; }; if let Err(()) = Self::enqueue_xcmp_message(sender, xcm, &mut meter) { @@ -750,12 +750,12 @@ impl XcmpMessageHandler for Pallet { "Could not enqueue XCMP messages. Used weight: ", meter.consumed_ratio() ); - break + break; } }, XcmpMessageFormat::ConcatenatedEncodedBlob => { defensive!("Blob messages are unhandled - dropping"); - continue + continue; }, } } @@ -791,7 +791,7 @@ impl XcmpMessageSource for Pallet { >::remove(para_id); } *status = OutboundChannelDetails::new(para_id); - continue + continue; }, ChannelStatus::Full => continue, ChannelStatus::Ready(n, e) => (n, e), @@ -801,7 +801,7 @@ impl XcmpMessageSource for Pallet { if result.len() == max_message_count { // We check this condition in the beginning of the loop so that we don't include // a message where the limit is 0. - break + break; } let page = if signals_exist { @@ -814,11 +814,11 @@ impl XcmpMessageSource for Pallet { page } else { defensive!("Signals should fit into a single page"); - continue + continue; } } else if outbound_state == OutboundState::Suspended { // Signals are exempt from suspension. - continue + continue; } else if last_index > first_index { let page = >::get(para_id, first_index); if page.len() < max_size_now { @@ -826,10 +826,10 @@ impl XcmpMessageSource for Pallet { first_index += 1; page } else { - continue + continue; } } else { - continue + continue; }; if first_index == last_index { first_index = 0; diff --git a/cumulus/pallets/xcmp-queue/src/migration.rs b/cumulus/pallets/xcmp-queue/src/migration.rs index 6c86c3011d238..3a27ba43ed6af 100644 --- a/cumulus/pallets/xcmp-queue/src/migration.rs +++ b/cumulus/pallets/xcmp-queue/src/migration.rs @@ -212,12 +212,12 @@ pub mod v3 { pub fn lazy_migrate_inbound_queue() { let Some(mut states) = v3::InboundXcmpStatus::::get() else { log::debug!(target: LOG, "Lazy migration finished: item gone"); - return + return; }; let Some(ref mut next) = states.first_mut() else { log::debug!(target: LOG, "Lazy migration finished: item empty"); v3::InboundXcmpStatus::::kill(); - return + return; }; log::debug!( "Migrating inbound HRMP channel with sibling {:?}, msgs left {}.", @@ -228,7 +228,7 @@ pub mod v3 { let Some((block_number, format)) = next.message_metadata.pop() else { states.remove(0); v3::InboundXcmpStatus::::put(states); - return + return; }; if format != XcmpMessageFormat::ConcatenatedVersionedXcm { log::warn!(target: LOG, @@ -237,19 +237,19 @@ pub mod v3 { ); v3::InboundXcmpMessages::::remove(&next.sender, &block_number); v3::InboundXcmpStatus::::put(states); - return + return; } let Some(msg) = v3::InboundXcmpMessages::::take(&next.sender, &block_number) else { defensive!("Storage corrupted: HRMP message missing:", (next.sender, block_number)); v3::InboundXcmpStatus::::put(states); - return + return; }; let Ok(msg): Result, _> = msg.try_into() else { log::error!(target: LOG, "Message dropped: too big"); v3::InboundXcmpStatus::::put(states); - return + return; }; // Finally! We have a proper message. @@ -276,7 +276,7 @@ pub mod v4 { pre.drop_threshold == pre_default.drop_threshold && pre.resume_threshold == pre_default.resume_threshold { - return QueueConfigData::default() + return QueueConfigData::default(); } // If the previous values are not the default ones, let's leave them as they are. diff --git a/cumulus/pallets/xcmp-queue/src/mock.rs b/cumulus/pallets/xcmp-queue/src/mock.rs index 08ab58ce81604..be750dd223d17 100644 --- a/cumulus/pallets/xcmp-queue/src/mock.rs +++ b/cumulus/pallets/xcmp-queue/src/mock.rs @@ -290,7 +290,7 @@ pub struct MockedChannelInfo; impl GetChannelInfo for MockedChannelInfo { fn get_channel_status(id: ParaId) -> ChannelStatus { if id == HRMP_PARA_ID.into() { - return ChannelStatus::Ready(usize::MAX, usize::MAX) + return ChannelStatus::Ready(usize::MAX, usize::MAX); } ParachainSystem::get_channel_status(id) @@ -304,7 +304,7 @@ impl GetChannelInfo for MockedChannelInfo { max_message_size: u32::MAX, msg_count: 0, total_size: 0, - }) + }); } ParachainSystem::get_channel_info(id) diff --git a/cumulus/parachains/common/src/impls.rs b/cumulus/parachains/common/src/impls.rs index 957538b7cdadb..cc44a08703566 100644 --- a/cumulus/parachains/common/src/impls.rs +++ b/cumulus/parachains/common/src/impls.rs @@ -154,7 +154,7 @@ where Some(a) => a, None => { log::warn!("Failed to convert root origin into account id"); - return + return; }, }; let treasury_account: AccountIdOf = TreasuryAccount::get(); diff --git a/cumulus/parachains/common/src/xcm_config.rs b/cumulus/parachains/common/src/xcm_config.rs index 15b090923d501..3e67c21bf0acc 100644 --- a/cumulus/parachains/common/src/xcm_config.rs +++ b/cumulus/parachains/common/src/xcm_config.rs @@ -92,7 +92,7 @@ impl, Runtime: parachain_info::Config let self_para_id: u32 = parachain_info::Pallet::::get().into(); if let (0, [Parachain(para_id)]) = l.unpack() { if *para_id == self_para_id { - return false + return false; } } matches!(l.unpack(), (1, [])) || SystemParachainMatcher::contains(l) diff --git a/cumulus/parachains/pallets/collective-content/src/lib.rs b/cumulus/parachains/pallets/collective-content/src/lib.rs index 7a685858accb6..0b1d8f29d5850 100644 --- a/cumulus/parachains/pallets/collective-content/src/lib.rs +++ b/cumulus/parachains/pallets/collective-content/src/lib.rs @@ -198,7 +198,7 @@ pub mod pallet { Self::deposit_event(Event::::AnnouncementRemoved { cid }); if now >= expire_at { - return Ok(Pays::No.into()) + return Ok(Pays::No.into()); } Ok(Pays::Yes.into()) } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 2584dbdf31062..4680fdceeb252 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -278,7 +278,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index 50865c0006117..1e2c3101cbeda 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -290,7 +290,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs index a9fd79bf939f5..9e3221b0a1627 100644 --- a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs +++ b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs @@ -44,7 +44,7 @@ where ) -> sp_std::result::Result { let origin_location = EnsureXcm::::try_origin(origin.clone())?; if !IsForeign::contains(asset_location, &origin_location) { - return Err(origin) + return Err(origin); } let latest_location: Location = origin_location.clone().try_into().map_err(|_| origin.clone())?; diff --git a/cumulus/parachains/runtimes/assets/common/src/matching.rs b/cumulus/parachains/runtimes/assets/common/src/matching.rs index 478bba4565dc1..7477c79e9be1a 100644 --- a/cumulus/parachains/runtimes/assets/common/src/matching.rs +++ b/cumulus/parachains/runtimes/assets/common/src/matching.rs @@ -52,8 +52,9 @@ impl, L: TryFrom + TryInto + Clone> // here we check if sibling match a.unpack() { - (1, interior) => - matches!(interior.first(), Some(Parachain(sibling_para_id)) if sibling_para_id.ne(&u32::from(SelfParaId::get()))), + (1, interior) => { + matches!(interior.first(), Some(Parachain(sibling_para_id)) if sibling_para_id.ne(&u32::from(SelfParaId::get()))) + }, _ => false, } } @@ -121,7 +122,7 @@ impl, Reserves: ContainsPair for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } @@ -473,7 +473,7 @@ impl< } } - return Assets::new() + return Assets::new(); } fee @@ -489,7 +489,7 @@ impl, FeeHandler: HandleFee> FeeManager fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool { let Some(loc) = origin else { return false }; if let Export { network, destination: Here } = fee_reason { - return !(network == EthereumNetwork::get()) + return !(network == EthereumNetwork::get()); } WaivedLocations::contains(loc) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index e18df6feda827..8bc41d555ffe5 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -132,7 +132,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/tracks.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/tracks.rs index d4a2d3bbf1c7b..932a55d7122de 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/tracks.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/tracks.rs @@ -259,7 +259,7 @@ impl pallet_referenda::TracksInfo for TracksInfo { // It is important that this is not available in production! let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); if &root == id { - return Ok(constants::MASTER_AMBASSADOR_TIER_9) + return Ok(constants::MASTER_AMBASSADOR_TIER_9); } } diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/tracks.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/tracks.rs index 099bdf4cf7539..81065ddd57375 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/tracks.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/tracks.rs @@ -496,7 +496,7 @@ impl pallet_referenda::TracksInfo for TracksInfo { // It is important that this is not available in production! let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); if &root == id { - return Ok(tracks::GRAND_MASTERS) + return Ok(tracks::GRAND_MASTERS); } } diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs index caf0cddec664a..9503866da0b50 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs @@ -91,7 +91,7 @@ pub struct EqualOrGreatestRootCmp; impl PrivilegeCmp for EqualOrGreatestRootCmp { fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { if left == right { - return Some(Ordering::Equal) + return Some(Ordering::Equal); } match (left, right) { // Root is greater than anything. diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs index cc25cbda0a427..50b3893fff06b 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs @@ -153,7 +153,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs index 37bb8809dabac..fd6c4c7664b01 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs @@ -152,7 +152,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs index 3adef5fb7cf6b..cc0b38674af4f 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs @@ -139,7 +139,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs index e75b048b3b32a..41974b0f18445 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs @@ -167,7 +167,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs index ee0691fd99684..8dd88a5440d2b 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs @@ -174,7 +174,7 @@ impl Contains for SafeCallFilter { #[cfg(feature = "runtime-benchmarks")] { if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { - return true + return true; } } diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index b4eb57fcb66f4..b5c261922e647 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -272,7 +272,7 @@ where loop { let block_number = frame_system::Pallet::::block_number(); if block_number >= n.into() { - break + break; } // Set the new block number and author diff --git a/cumulus/polkadot-parachain/src/service.rs b/cumulus/polkadot-parachain/src/service.rs index 553975b01a80d..22bbee289db91 100644 --- a/cumulus/polkadot-parachain/src/service.rs +++ b/cumulus/polkadot-parachain/src/service.rs @@ -1564,7 +1564,7 @@ where Err(e) => { log::error!("Could not decode the head data: {e}"); request.complete(None); - continue + continue; }, }; @@ -1577,7 +1577,7 @@ where { // Respond to this request before transitioning to Aura. request.complete(None); - break + break; } } @@ -1586,7 +1586,7 @@ where Ok(d) => d, Err(e) => { log::error!("Could not get Aura slot duration: {e}"); - return + return; }, }; @@ -1713,7 +1713,7 @@ where Err(e) => { log::error!("Could not decode the head data: {e}"); request.complete(None); - continue + continue; }, }; @@ -1726,7 +1726,7 @@ where { // Respond to this request before transitioning to Aura. request.complete(None); - break + break; } } diff --git a/cumulus/polkadot-parachain/tests/common.rs b/cumulus/polkadot-parachain/tests/common.rs index 20926ddd91db5..b5111e03525b0 100644 --- a/cumulus/polkadot-parachain/tests/common.rs +++ b/cumulus/polkadot-parachain/tests/common.rs @@ -43,7 +43,7 @@ pub fn wait_for(child: &mut Child, secs: u64) -> Result { let result = wait_timeout::ChildExt::wait_timeout(child, Duration::from_secs(secs - 5)) .map_err(|_| ())?; if let Some(exit_status) = result { - return Ok(exit_status) + return Ok(exit_status); } } eprintln!("Took too long to exit (> {} seconds). Killing...", secs); diff --git a/cumulus/primitives/utility/src/lib.rs b/cumulus/primitives/utility/src/lib.rs index 0d8921227429c..e07579ce5930f 100644 --- a/cumulus/primitives/utility/src/lib.rs +++ b/cumulus/primitives/utility/src/lib.rs @@ -143,7 +143,7 @@ impl< // Make sure we dont enter twice if self.0.is_some() { - return Err(XcmError::NotWithdrawable) + return Err(XcmError::NotWithdrawable); } // We take the very first asset from payment @@ -398,7 +398,7 @@ impl< let swap_asset = fungibles_asset.clone().into(); if Target::get().eq(&swap_asset) { // current trader is not applicable. - return Err(XcmError::FeesNotMet) + return Err(XcmError::FeesNotMet); } let credit_in = Fungibles::issue(fungibles_asset, balance); @@ -423,7 +423,7 @@ impl< "`total_fee.asset` must be equal to `credit_out.asset`", (self.total_fee.asset(), credit_out.asset()) ); - return Err(XcmError::FeesNotMet) + return Err(XcmError::FeesNotMet); }, _ => (), }; @@ -443,18 +443,18 @@ impl< ); if self.total_fee.peek().is_zero() { // noting yet paid to refund. - return None + return None; } let mut refund_asset = if let Some(asset) = &self.last_fee_asset { // create an initial zero refund in the asset used in the last `buy_weight`. (asset.clone(), Fungible(0)).into() } else { - return None + return None; }; let refund_amount = WeightToFee::weight_to_fee(&weight); if refund_amount >= self.total_fee.peek() { // not enough was paid to refund the `weight`. - return None + return None; } let refund_swap_asset = FungiblesAssetMatcher::matches_fungibles(&refund_asset) @@ -478,7 +478,7 @@ impl< (self.total_fee.asset(), refund.asset()) ); }); - return None + return None; }, }; @@ -515,7 +515,7 @@ impl< { fn drop(&mut self) { if self.total_fee.peek().is_zero() { - return + return; } let total_fee = self.total_fee.extract(self.total_fee.peek()); OnUnbalanced::on_unbalanced(total_fee); diff --git a/docs/sdk/src/guides/your_first_pallet/mod.rs b/docs/sdk/src/guides/your_first_pallet/mod.rs index 29cdda36ed15b..ea23af51ec9d8 100644 --- a/docs/sdk/src/guides/your_first_pallet/mod.rs +++ b/docs/sdk/src/guides/your_first_pallet/mod.rs @@ -365,7 +365,7 @@ pub mod pallet { // ensure sender has enough balance, and if so, calculate what is left after `amount`. let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; if sender_balance < amount { - return Err("InsufficientBalance".into()) + return Err("InsufficientBalance".into()); } let reminder = sender_balance - amount; diff --git a/polkadot/cli/src/command.rs b/polkadot/cli/src/command.rs index f71891ecde34c..3ff4f78ab7a42 100644 --- a/polkadot/cli/src/command.rs +++ b/polkadot/cli/src/command.rs @@ -294,7 +294,7 @@ pub fn run() -> Result<()> { #[cfg(not(feature = "pyroscope"))] if cli.run.pyroscope_server.is_some() { - return Err(Error::PyroscopeNotCompiledIn) + return Err(Error::PyroscopeNotCompiledIn); } match &cli.subcommand { diff --git a/polkadot/erasure-coding/src/lib.rs b/polkadot/erasure-coding/src/lib.rs index e5155df4beba9..3652eab547691 100644 --- a/polkadot/erasure-coding/src/lib.rs +++ b/polkadot/erasure-coding/src/lib.rs @@ -100,10 +100,10 @@ impl From for Error { /// Obtain a threshold of chunks that should be enough to recover the data. pub const fn recovery_threshold(n_validators: usize) -> Result { if n_validators > MAX_VALIDATORS { - return Err(Error::TooManyValidators) + return Err(Error::TooManyValidators); } if n_validators <= 1 { - return Err(Error::NotEnoughValidators) + return Err(Error::NotEnoughValidators); } let needed = n_validators.saturating_sub(1) / 3; @@ -117,7 +117,7 @@ fn code_params(n_validators: usize) -> Result { let k_wanted = recovery_threshold(n_wanted)?; if n_wanted > MAX_VALIDATORS as usize { - return Err(Error::TooManyValidators) + return Err(Error::TooManyValidators); } CodeParams::derive_parameters(n_wanted, k_wanted).map_err(|e| match e { @@ -142,7 +142,7 @@ pub fn obtain_chunks(n_validators: usize, data: &T) -> Result> = vec![None; n_validators]; for (chunk_data, chunk_idx) in chunks.into_iter().take(n_validators) { if chunk_data.len() % 2 != 0 { - return Err(Error::UnevenLength) + return Err(Error::UnevenLength); } received_shards[chunk_idx] = Some(WrappedShard::new(chunk_data.to_vec())); diff --git a/polkadot/node/collation-generation/src/lib.rs b/polkadot/node/collation-generation/src/lib.rs index cfa75d7b44119..6de486bf461c0 100644 --- a/polkadot/node/collation-generation/src/lib.rs +++ b/polkadot/node/collation-generation/src/lib.rs @@ -206,7 +206,7 @@ async fn handle_new_activations( // https://paritytech.github.io/polkadot-sdk/book/node/collators/collation-generation.html if config.collator.is_none() { - return Ok(()) + return Ok(()); } let _overall_timer = metrics.time_new_activations(); @@ -242,7 +242,7 @@ async fn handle_new_activations( if let Some(scheduled) = occupied_core.next_up_on_available { (scheduled, OccupiedCoreAssumption::Included) } else { - continue + continue; } }, _ => { @@ -252,7 +252,7 @@ async fn handle_new_activations( relay_parent = ?relay_parent, "core is occupied. Keep going.", ); - continue + continue; }, }, CoreState::Free => { @@ -261,7 +261,7 @@ async fn handle_new_activations( core_idx = %core_idx, "core is free. Keep going.", ); - continue + continue; }, }; @@ -274,7 +274,7 @@ async fn handle_new_activations( their_para = %scheduled_core.para_id, "core is not assigned to our para. Keep going.", ); - continue + continue; } // we get validation data and validation code synchronously for each core instead of @@ -300,7 +300,7 @@ async fn handle_new_activations( their_para = %scheduled_core.para_id, "validation data is not available", ); - continue + continue; }, }; @@ -322,7 +322,7 @@ async fn handle_new_activations( their_para = %scheduled_core.para_id, "validation code hash is not found.", ); - continue + continue; }, }; @@ -346,7 +346,7 @@ async fn handle_new_activations( para_id = %scheduled_core.para_id, "collator returned no collation on collate", ); - return + return; }, }; @@ -411,7 +411,7 @@ async fn handle_submit_collation( our_para = %config.para_id, "No validation data for para - does it exist at this relay-parent?", ); - return Ok(()) + return Ok(()); }, }; @@ -487,7 +487,7 @@ async fn construct_and_distribute_receipt( "PoV exceeded maximum size" ); - return + return; } pov @@ -512,7 +512,7 @@ async fn construct_and_distribute_receipt( err = ?err, "failed to calculate erasure root", ); - return + return; }, }; diff --git a/polkadot/node/core/approval-voting/src/approval_checking.rs b/polkadot/node/core/approval-voting/src/approval_checking.rs index 0aa6102fbd6d2..29b4d255fd300 100644 --- a/polkadot/node/core/approval-voting/src/approval_checking.rs +++ b/polkadot/node/core/approval-voting/src/approval_checking.rs @@ -116,7 +116,7 @@ pub fn check_approval( // honest node approves, the candidate should be approved. let approvals = candidate.approvals(); if 3 * approvals.count_ones() > approvals.len() { - return Check::ApprovedOneThird + return Check::ApprovedOneThird; } match required { @@ -203,7 +203,7 @@ impl State { return TranchesToApproveResult { required_tranches: RequiredTranches::All, total_observed_no_shows: self.total_observed_no_shows, - } + }; } // If we have enough assignments and all no-shows are covered, we have reached the number @@ -217,7 +217,7 @@ impl State { last_assignment_tick: self.last_assignment_tick, }, total_observed_no_shows: self.total_observed_no_shows, - } + }; } // We're pending more assignments and should look at more tranches. @@ -365,7 +365,7 @@ fn count_no_shows( let has_approved = if let Some(approved) = approvals.get(v_index.0 as usize) { *approved } else { - return false + return false; }; let is_no_show = !has_approved && no_show_at <= drifted_tick_now; diff --git a/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs index 6021b44c2765f..f7ba22a006c15 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs @@ -378,7 +378,7 @@ fn canonicalize_works() { assert!(load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &c_hash) .unwrap() .is_none()); - continue + continue; }, Some(i) => ( load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &c_hash) @@ -403,7 +403,7 @@ fn canonicalize_works() { assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash) .unwrap() .is_none()); - continue + continue; }, Some(i) => (load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), diff --git a/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs index 08c65461bca80..36ffdfcc3be1a 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs @@ -373,7 +373,7 @@ fn canonicalize_works() { assert!(load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash) .unwrap() .is_none()); - continue + continue; }, Some(i) => ( load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash).unwrap().unwrap(), @@ -396,7 +396,7 @@ fn canonicalize_works() { assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &hash) .unwrap() .is_none()); - continue + continue; }, Some(i) => (load_block_entry(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), diff --git a/polkadot/node/core/approval-voting/src/backend.rs b/polkadot/node/core/approval-voting/src/backend.rs index 9ce25334c0fad..9427cf6e659d9 100644 --- a/polkadot/node/core/approval-voting/src/backend.rs +++ b/polkadot/node/core/approval-voting/src/backend.rs @@ -159,7 +159,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub fn load_blocks_at_height(&self, height: &BlockNumber) -> SubsystemResult> { if let Some(val) = self.blocks_at_height.get(&height) { - return Ok(val.clone().unwrap_or_default()) + return Ok(val.clone().unwrap_or_default()); } self.inner.load_blocks_at_height(height) @@ -167,7 +167,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub fn load_block_entry(&self, hash: &Hash) -> SubsystemResult> { if let Some(val) = self.block_entries.get(&hash) { - return Ok(val.clone()) + return Ok(val.clone()); } self.inner.load_block_entry(hash) @@ -178,7 +178,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { candidate_hash: &CandidateHash, ) -> SubsystemResult> { if let Some(val) = self.candidate_entries.get(&candidate_hash) { - return Ok(val.clone()) + return Ok(val.clone()); } self.inner.load_candidate_entry(candidate_hash) diff --git a/polkadot/node/core/approval-voting/src/criteria.rs b/polkadot/node/core/approval-voting/src/criteria.rs index 1ebea2641b621..6027d2b2c19f9 100644 --- a/polkadot/node/core/approval-voting/src/criteria.rs +++ b/polkadot/node/core/approval-voting/src/criteria.rs @@ -340,7 +340,7 @@ pub fn compute_assignments( "Not producing assignments because config is degenerate", ); - return HashMap::new() + return HashMap::new(); } let (index, assignments_key): (ValidatorIndex, AssignmentPair) = { @@ -360,7 +360,7 @@ pub fn compute_assignments( match key { None => { gum::trace!(target: LOG_TARGET, "No assignment key"); - return HashMap::new() + return HashMap::new(); }, Some(k) => k, } @@ -674,7 +674,7 @@ pub(crate) fn check_assignment_cert( if claimed_core_indices.count_ones() == 0 || claimed_core_indices.count_ones() != backing_groups.len() { - return Err(InvalidAssignment(Reason::InvalidArguments)) + return Err(InvalidAssignment(Reason::InvalidArguments)); } // Check that the validator was not part of the backing group @@ -682,14 +682,14 @@ pub(crate) fn check_assignment_cert( for (claimed_core, backing_group) in claimed_core_indices.iter_ones().zip(backing_groups.iter()) { if claimed_core >= config.n_cores as usize { - return Err(InvalidAssignment(Reason::CoreIndexOutOfBounds)) + return Err(InvalidAssignment(Reason::CoreIndexOutOfBounds)); } let is_in_backing = is_in_backing_group(&config.validator_groups, validator_index, *backing_group); if is_in_backing { - return Err(InvalidAssignment(Reason::IsInBackingGroup)) + return Err(InvalidAssignment(Reason::IsInBackingGroup)); } } @@ -702,7 +702,7 @@ pub(crate) fn check_assignment_cert( AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => { // Check that claimed core bitfield match the one from certificate. if &claimed_core_indices != core_bitfield { - return Err(InvalidAssignment(Reason::VRFModuloCoreIndexMismatch)) + return Err(InvalidAssignment(Reason::VRFModuloCoreIndexMismatch)); } let (vrf_in_out, _) = public @@ -733,7 +733,7 @@ pub(crate) fn check_assignment_cert( vrf_modulo_cores = ?resulting_cores, "Assignment claimed cores mismatch", ); - return Err(InvalidAssignment(Reason::VRFModuloCoreIndexMismatch)) + return Err(InvalidAssignment(Reason::VRFModuloCoreIndexMismatch)); } } @@ -741,7 +741,7 @@ pub(crate) fn check_assignment_cert( }, AssignmentCertKindV2::RelayVRFModulo { sample } => { if *sample >= config.relay_vrf_modulo_samples { - return Err(InvalidAssignment(Reason::SampleOutOfBounds)) + return Err(InvalidAssignment(Reason::SampleOutOfBounds)); } // Enforce claimed candidates is 1. @@ -751,7 +751,7 @@ pub(crate) fn check_assignment_cert( ?claimed_core_indices, "`RelayVRFModulo` assignment must always claim 1 core", ); - return Err(InvalidAssignment(Reason::InvalidArguments)) + return Err(InvalidAssignment(Reason::InvalidArguments)); } let (vrf_in_out, _) = public @@ -785,11 +785,11 @@ pub(crate) fn check_assignment_cert( ?claimed_core_indices, "`RelayVRFDelay` assignment must always claim 1 core", ); - return Err(InvalidAssignment(Reason::InvalidArguments)) + return Err(InvalidAssignment(Reason::InvalidArguments)); } if core_index.0 != first_claimed_core_index { - return Err(InvalidAssignment(Reason::VRFDelayCoreIndexMismatch)) + return Err(InvalidAssignment(Reason::VRFDelayCoreIndexMismatch)); } let (vrf_in_out, _) = public diff --git a/polkadot/node/core/approval-voting/src/import.rs b/polkadot/node/core/approval-voting/src/import.rs index 7a56e9fd11293..196fc15445400 100644 --- a/polkadot/node/core/approval-voting/src/import.rs +++ b/polkadot/node/core/approval-voting/src/import.rs @@ -173,7 +173,7 @@ async fn imported_block_info( block_hash, ); - return Err(ImportedBlockInfoError::BlockAlreadyFinalized) + return Err(ImportedBlockInfoError::BlockAlreadyFinalized); } session_index @@ -265,7 +265,7 @@ async fn imported_block_info( block_hash, ); - return Err(ImportedBlockInfoError::VrfInfoUnavailable) + return Err(ImportedBlockInfoError::VrfInfoUnavailable); }, } }; @@ -357,12 +357,12 @@ pub(crate) async fn handle_new_head( e, ); // May be a better way of handling errors here. - return Ok(Vec::new()) + return Ok(Vec::new()); }, Ok(None) => { gum::warn!(target: LOG_TARGET, "Missing header for new head {}", head); // May be a better way of handling warnings here. - return Ok(Vec::new()) + return Ok(Vec::new()); }, Ok(Some(h)) => h, } @@ -384,7 +384,7 @@ pub(crate) async fn handle_new_head( .await?; if new_blocks.is_empty() { - return Ok(Vec::new()) + return Ok(Vec::new()); } let mut approval_meta: Vec = Vec::with_capacity(new_blocks.len()); @@ -424,7 +424,7 @@ pub(crate) async fn handle_new_head( ); } - return Ok(Vec::new()) + return Ok(Vec::new()); }, }; } diff --git a/polkadot/node/core/approval-voting/src/lib.rs b/polkadot/node/core/approval-voting/src/lib.rs index 456ae319787b0..47d539d89779e 100644 --- a/polkadot/node/core/approval-voting/src/lib.rs +++ b/polkadot/node/core/approval-voting/src/lib.rs @@ -558,7 +558,7 @@ impl Wakeups { ) { if let Some(prev) = self.reverse_wakeups.get(&(block_hash, candidate_hash)) { if prev <= &tick { - return + return; } // we are replacing previous wakeup with an earlier one. @@ -734,7 +734,7 @@ impl CurrentlyCheckingSet { .unwrap_or_default(); approvals_cache .insert(approval_state.candidate_hash, approval_state.approval_outcome); - return (out, approval_state) + return (out, approval_state); } } @@ -1078,7 +1078,7 @@ where ) .await? { - break + break; } if !overlayed_db.is_empty() { @@ -1175,7 +1175,7 @@ async fn handle_actions( } => { // Don't launch approval work if the node is syncing. if let Mode::Syncing(_) = *mode { - continue + continue; } let mut launch_approval_span = state @@ -1340,7 +1340,7 @@ fn distribution_messages_for_activation( None => { gum::warn!(target: LOG_TARGET, ?block_hash, "Missing block entry"); - continue + continue; }, }; @@ -1369,7 +1369,7 @@ fn distribution_messages_for_activation( "Missing candidate entry", ); - continue + continue; }, }; @@ -1456,7 +1456,7 @@ fn distribution_messages_for_activation( "Failed to create assignment bitfield", ); // If we didn't send assignment, we don't send approval. - continue + continue; }, } if signatures_queued @@ -1651,7 +1651,7 @@ async fn handle_from_overseer( }, Err(e) => { let _ = res.send(None); - return Err(e) + return Err(e); }, } @@ -1695,7 +1695,7 @@ async fn get_approval_signatures_for_candidate( ?candidate_hash, "Sent back empty votes because the candidate was not found in db." ); - return Ok(()) + return Ok(()); }, Some(e) => e, }; @@ -1718,7 +1718,7 @@ async fn get_approval_signatures_for_candidate( ?hash, "Block entry for assignment missing." ); - continue + continue; }, Some(e) => e, }; @@ -1850,7 +1850,7 @@ async fn handle_approved_ancestor( span.add_uint_tag("leaf-number", target_number as u64); span.add_uint_tag("lower-bound", lower_bound as u64); if target_number <= lower_bound { - return Ok(None) + return Ok(None); } // request ancestors up to but not including the lower bound, @@ -1898,7 +1898,7 @@ async fn handle_approved_ancestor( lower_bound, lower_bound, ); - return Ok(None) + return Ok(None); }, Some(b) => b, }; @@ -1958,7 +1958,7 @@ async fn handle_approved_ancestor( "Missing expected candidate in DB", ); - continue + continue; }, Some(c_entry) => match c_entry.approval_entry(&block_hash) { None => { @@ -2237,7 +2237,7 @@ where candidate_indices.len(), )), Vec::new(), - )) + )); } // The Compact VRF modulo assignment cert has multiple core assignments. @@ -2302,7 +2302,7 @@ where format!("{:?}", InvalidAssignmentReason::NullAssignment), )), Vec::new(), - )) + )); } // Check the assignment certificate. @@ -2334,7 +2334,7 @@ where let too_far_in_future = current_tranche + TICK_TOO_FAR_IN_FUTURE as DelayTranche; if tranche >= too_far_in_future { - return Ok((AssignmentCheckResult::TooFarInFuture, Vec::new())) + return Ok((AssignmentCheckResult::TooFarInFuture, Vec::new())); } tranche @@ -2445,7 +2445,7 @@ where macro_rules! respond_early { ($e: expr) => {{ let t = with_response($e); - return Ok((Vec::new(), t)) + return Ok((Vec::new(), t)); }}; } let mut span = state @@ -2689,7 +2689,7 @@ where // so we can early exit as long at the candidate is already concluded under the // block i.e. we don't need more approvals. if candidate_approved_in_block { - return Vec::new() + return Vec::new(); } } @@ -2771,7 +2771,7 @@ where "No approval entry for approval under block", ); - return Vec::new() + return Vec::new(); }; { @@ -3159,7 +3159,7 @@ async fn launch_approval( metrics_guard.take().on_approval_invalid(); }, } - return ApprovalState::failed(validator_index, candidate_hash) + return ApprovalState::failed(validator_index, candidate_hash); }, }; drop(request_validation_data_span); @@ -3179,7 +3179,7 @@ async fn launch_approval( // No dispute necessary, as this indicates that the chain is not behaving // according to expectations. metrics_guard.take().on_approval_unavailable(); - return ApprovalState::failed(validator_index, candidate_hash) + return ApprovalState::failed(validator_index, candidate_hash); }, }; @@ -3205,7 +3205,7 @@ async fn launch_approval( gum::trace!(target: LOG_TARGET, ?candidate_hash, ?para_id, "Candidate Valid"); let _ = metrics_guard.take(); - return ApprovalState::approved(validator_index, candidate_hash) + return ApprovalState::approved(validator_index, candidate_hash); }, Ok(Ok(ValidationResult::Invalid(reason))) => { gum::warn!( @@ -3223,7 +3223,7 @@ async fn launch_approval( candidate.clone(), ); metrics_guard.take().on_approval_invalid(); - return ApprovalState::failed(validator_index, candidate_hash) + return ApprovalState::failed(validator_index, candidate_hash); }, Ok(Err(e)) => { gum::error!( @@ -3235,7 +3235,7 @@ async fn launch_approval( ); metrics_guard.take().on_approval_error(); drop(request_validation_result_span); - return ApprovalState::failed(validator_index, candidate_hash) + return ApprovalState::failed(validator_index, candidate_hash); }, } }; @@ -3272,7 +3272,7 @@ async fn issue_approval( None => { // not a cause for alarm - just lost a race with pruning, most likely. metrics.on_approval_stale(); - return Ok(Vec::new()) + return Ok(Vec::new()); }, }; @@ -3287,7 +3287,7 @@ async fn issue_approval( ); metrics.on_approval_error(); - return Ok(Vec::new()) + return Ok(Vec::new()); }, Some(idx) => idx, }; @@ -3304,7 +3304,7 @@ async fn issue_approval( ); metrics.on_approval_error(); - return Ok(Vec::new()) + return Ok(Vec::new()); }, }; @@ -3319,7 +3319,7 @@ async fn issue_approval( ); metrics.on_approval_error(); - return Ok(Vec::new()) + return Ok(Vec::new()); }, }; @@ -3420,7 +3420,7 @@ async fn maybe_create_signature( target: LOG_TARGET, "Could not find block that needs signature {:}", block_hash ); - return Ok(None) + return Ok(None); }, }; @@ -3458,7 +3458,7 @@ async fn maybe_create_signature( target: LOG_TARGET, "Could not retrieve the session" ); - return Ok(None) + return Ok(None); }, }; @@ -3473,7 +3473,7 @@ async fn maybe_create_signature( ); metrics.on_approval_error(); - return Ok(None) + return Ok(None); }, }; @@ -3493,7 +3493,7 @@ async fn maybe_create_signature( ); metrics.on_approval_error(); - return Ok(None) + return Ok(None); }, }; metrics.on_approval_coalesce(candidates_hashes.len() as u32); diff --git a/polkadot/node/core/approval-voting/src/ops.rs b/polkadot/node/core/approval-voting/src/ops.rs index 2a8fdba5aa364..cd4457993ddef 100644 --- a/polkadot/node/core/approval-voting/src/ops.rs +++ b/polkadot/node/core/approval-voting/src/ops.rs @@ -217,7 +217,7 @@ pub fn add_block_entry( let mut blocks_at_height = store.load_blocks_at_height(&number)?; if blocks_at_height.contains(&entry.block_hash()) { // seems we already have a block entry for this block. nothing to do here. - return Ok(Vec::new()) + return Ok(Vec::new()); } blocks_at_height.push(entry.block_hash()); @@ -370,7 +370,7 @@ pub fn revert_to( if child_entry.parent_hash() != hash { return Err(SubsystemError::Context( "revert below last finalized block or corrupted storage".to_string(), - )) + )); } (children, children_height) diff --git a/polkadot/node/core/approval-voting/src/persisted_entries.rs b/polkadot/node/core/approval-voting/src/persisted_entries.rs index ef47bdb2213a1..86d6566711b61 100644 --- a/polkadot/node/core/approval-voting/src/persisted_entries.rs +++ b/polkadot/node/core/approval-voting/src/persisted_entries.rs @@ -162,7 +162,7 @@ impl ApprovalEntry { ) -> Option<(AssignmentCertV2, ValidatorIndex, DelayTranche)> { let our = self.our_assignment.as_mut().and_then(|a| { if a.triggered() { - return None + return None; } a.mark_triggered(); diff --git a/polkadot/node/core/approval-voting/src/tests.rs b/polkadot/node/core/approval-voting/src/tests.rs index 9220e84a2554a..5c6ddbe9ffd8a 100644 --- a/polkadot/node/core/approval-voting/src/tests.rs +++ b/polkadot/node/core/approval-voting/src/tests.rs @@ -2463,7 +2463,7 @@ fn approved_ancestor_test( assert_eq!(rx.await, Ok(AssignmentCheckResult::Accepted)); if skip_approval(i as BlockNumber + 1) { - continue + continue; } let rx = check_and_import_approval( @@ -3033,7 +3033,7 @@ where let debug = false; if debug { step_until_done(&clock).await; - return virtual_overseer + return virtual_overseer; } futures_timer::Delay::new(Duration::from_millis(200)).await; @@ -3071,7 +3071,7 @@ async fn step_until_done(clock: &MockClock) { relevant_ticks.push(tick); clock.set_tick(tick); } else { - break + break; } } } diff --git a/polkadot/node/core/av-store/src/lib.rs b/polkadot/node/core/av-store/src/lib.rs index ef7dcecac0755..2068ef36ba01a 100644 --- a/polkadot/node/core/av-store/src/lib.rs +++ b/polkadot/node/core/av-store/src/lib.rs @@ -326,7 +326,7 @@ fn pruning_range(now: impl Into) -> (Vec, Vec) { fn decode_unfinalized_key(s: &[u8]) -> Result<(BlockNumber, Hash, CandidateHash), CodecError> { if !s.starts_with(UNFINALIZED_PREFIX) { - return Err("missing magic string".into()) + return Err("missing magic string".into()); } <(BEBlockNumber, Hash, CandidateHash)>::decode(&mut &s[UNFINALIZED_PREFIX.len()..]) @@ -335,7 +335,7 @@ fn decode_unfinalized_key(s: &[u8]) -> Result<(BlockNumber, Hash, CandidateHash) fn decode_pruning_key(s: &[u8]) -> Result<(Duration, CandidateHash), CodecError> { if !s.starts_with(PRUNE_BY_TIME_PREFIX) { - return Err("missing magic string".into()) + return Err("missing magic string".into()); } <(BETimestamp, CandidateHash)>::decode(&mut &s[PRUNE_BY_TIME_PREFIX.len()..]) @@ -566,12 +566,12 @@ async fn run(mut subsystem: AvailabilityStoreSubsystem, mut ctx: Contex Err(e) => { e.trace(); if e.is_fatal() { - break + break; } }, Ok(true) => { gum::info!(target: LOG_TARGET, "received `Conclude` signal, exiting"); - break + break; }, Ok(false) => continue, } @@ -847,13 +847,13 @@ fn note_block_included( within.insert(i, be_block); State::Unfinalized(at, within) } else { - return Ok(()) + return Ok(()); } }, State::Finalized(_at) => { // This should never happen as a candidate would have to be included after // finality. - return Ok(()) + return Ok(()); }, }; @@ -912,7 +912,7 @@ async fn process_block_finalized( }; if batch_num < next_possible_batch { - continue + continue; } // sanity. next_possible_batch = batch_num + 1; @@ -931,7 +931,7 @@ async fn process_block_finalized( "Failed to retrieve finalized block number.", ); - break + break; }, Ok(None) => { gum::warn!( @@ -941,7 +941,7 @@ async fn process_block_finalized( batch_num, ); - break + break; }, Ok(Some(h)) => h, } @@ -1019,7 +1019,7 @@ fn update_blocks_at_finalized_height( candidate_hash, ); - continue + continue; }, Some(c) => c, }; @@ -1182,7 +1182,7 @@ fn process_message( }, Err(e) => { let _ = tx.send(Err(())); - return Err(e) + return Err(e); }, } }, @@ -1211,7 +1211,7 @@ fn process_message( }, Err(Error::InvalidErasureRoot) => { let _ = tx.send(Err(StoreAvailableDataError::InvalidErasureRoot)); - return Err(Error::InvalidErasureRoot) + return Err(Error::InvalidErasureRoot); }, Err(e) => { // We do not bubble up internal errors to caller subsystems, instead the @@ -1219,7 +1219,7 @@ fn process_message( // // We bubble up the specific error here so `av-store` logs still tell what // happend. - return Err(e.into()) + return Err(e.into()); }, } }, @@ -1277,7 +1277,7 @@ fn store_available_data( let mut meta = match load_meta(&subsystem.db, &subsystem.config, &candidate_hash)? { Some(m) => { if m.data_available { - return Ok(()) // already stored. + return Ok(()); // already stored. } m @@ -1307,7 +1307,7 @@ fn store_available_data( let branches = erasure::branches(chunks.as_ref()); if branches.root() != expected_erasure_root { - return Err(Error::InvalidErasureRoot) + return Err(Error::InvalidErasureRoot); } drop(erasure_span); diff --git a/polkadot/node/core/av-store/src/tests.rs b/polkadot/node/core/av-store/src/tests.rs index 652bf2a3fda48..97fca77c854da 100644 --- a/polkadot/node/core/av-store/src/tests.rs +++ b/polkadot/node/core/av-store/src/tests.rs @@ -1136,7 +1136,7 @@ async fn has_all_chunks( if query_chunk(virtual_overseer, candidate_hash, ValidatorIndex(i)).await.is_some() != expect_present { - return false + return false; } } true diff --git a/polkadot/node/core/backing/src/lib.rs b/polkadot/node/core/backing/src/lib.rs index 98bbd6232add4..c6dc0d30d7f43 100644 --- a/polkadot/node/core/backing/src/lib.rs +++ b/polkadot/node/core/backing/src/lib.rs @@ -474,7 +474,7 @@ fn table_attested_to_backed( "Logic error: Validity vote from table does not correspond to group", ); - return None + return None; } } vote_positions.sort_by_key(|(_orig, pos_in_group)| *pos_in_group); @@ -674,7 +674,7 @@ async fn validate_and_make_available( )) .await .map_err(Error::BackgroundValidationMpsc)?; - return Ok(()) + return Ok(()); }, Err(err) => return Err(err), Ok(pov) => pov, @@ -846,7 +846,7 @@ async fn handle_active_leaves_update( Some((leaf, LeafHasProspectiveParachains::Disabled)) => { // defensive in this case - for enabled, this manifests as an error. if state.per_leaf.contains_key(&leaf.hash) { - return Ok(()) + return Ok(()); } state.per_leaf.insert( @@ -947,14 +947,14 @@ async fn handle_active_leaves_update( "Failed to load implicit view for leaf." ); - return Ok(()) + return Ok(()); }, }; // add entries in `per_relay_parent`. for all new relay-parents. for maybe_new in fresh_relay_parents { if state.per_relay_parent.contains_key(&maybe_new) { - continue + continue; } let mode = match state.per_leaf.get(&maybe_new) { @@ -1000,7 +1000,7 @@ async fn construct_per_relay_parent_state( // We can't do candidate validation work if we don't have the // requisite runtime API data. But these errors should not take // down the node. - return Ok(None) + return Ok(None); }, } }; @@ -1051,7 +1051,7 @@ async fn construct_per_relay_parent_state( "Cannot participate in candidate backing", ); - return Ok(None) + return Ok(None); }, }; @@ -1062,14 +1062,15 @@ async fn construct_per_relay_parent_state( for (idx, core) in cores.into_iter().enumerate() { let core_para_id = match core { CoreState::Scheduled(scheduled) => scheduled.para_id, - CoreState::Occupied(occupied) => + CoreState::Occupied(occupied) => { if mode.is_enabled() { // Async backing makes it legal to build on top of // occupied core. occupied.candidate_descriptor.para_id } else { - continue - }, + continue; + } + }, CoreState::Free => continue, }; @@ -1134,7 +1135,7 @@ async fn seconding_sanity_check( let allowed_parents_for_para = implicit_view.known_allowed_relay_parents_under(head, Some(candidate_para)); if !allowed_parents_for_para.unwrap_or_default().contains(&candidate_relay_parent) { - continue + continue; } let (tx, rx) = oneshot::channel(); @@ -1169,7 +1170,7 @@ async fn seconding_sanity_check( .map_or(false, |occupied| occupied.contains_key(&0)) { // The leaf is already occupied. - return SecondingAllowed::No + return SecondingAllowed::No; } responses.push_back(futures::future::ok((vec![0], head, leaf_state)).boxed()); } @@ -1177,7 +1178,7 @@ async fn seconding_sanity_check( } if responses.is_empty() { - return SecondingAllowed::No + return SecondingAllowed::No; } while let Some(response) = responses.next().await { @@ -1188,7 +1189,7 @@ async fn seconding_sanity_check( "Failed to reach prospective parachains subsystem for hypothetical frontiers", ); - return SecondingAllowed::No + return SecondingAllowed::No; }, Ok((depths, head, leaf_state)) => { for depth in &depths { @@ -1205,7 +1206,7 @@ async fn seconding_sanity_check( "Refusing to second candidate at depth - already occupied." ); - return SecondingAllowed::No + return SecondingAllowed::No; } } @@ -1287,7 +1288,7 @@ async fn handle_validated_candidate_command( } = outputs; if rp_state.issued_statements.contains(&candidate_hash) { - return Ok(()) + return Ok(()); } let receipt = CommittedCandidateReceipt { @@ -1307,7 +1308,7 @@ async fn handle_validated_candidate_command( // counter. That requires a major primitives format upgrade, so for now // we just rule out trivial cycles. if parent_head_data_hash == receipt.commitments.head_data.hash() { - return Ok(()) + return Ok(()); } let hypothetical_candidate = HypotheticalCandidate::Complete { candidate_hash, @@ -1362,7 +1363,7 @@ async fn handle_validated_candidate_command( )) .await; - return Ok(()) + return Ok(()); } if let Some(stmt) = res? { @@ -1387,7 +1388,7 @@ async fn handle_validated_candidate_command( "Missing `per_leaf` for known active leaf." ); - continue + continue; }, Some(d) => d, }; @@ -1562,11 +1563,11 @@ async fn import_statement( "Could not reach the Prospective Parachains subsystem." ); - return Err(Error::RejectedByProspectiveParachains) + return Err(Error::RejectedByProspectiveParachains); }, Ok(membership) => if membership.is_empty() { - return Err(Error::RejectedByProspectiveParachains) + return Err(Error::RejectedByProspectiveParachains); }, } @@ -1759,18 +1760,18 @@ async fn kick_off_validation_work( match rp_state.table_context.local_validator_is_disabled() { Some(true) => { gum::info!(target: LOG_TARGET, "We are disabled - don't kick off validation"); - return Ok(()) + return Ok(()); }, Some(false) => {}, // we are not disabled - move on None => { gum::debug!(target: LOG_TARGET, "We are not a validator - don't kick off validation"); - return Ok(()) + return Ok(()); }, } let candidate_hash = attesting.candidate.hash(); if rp_state.issued_statements.contains(&candidate_hash) { - return Ok(()) + return Ok(()); } gum::debug!( @@ -1821,7 +1822,7 @@ async fn maybe_validate_and_import( "Received statement for unknown relay-parent" ); - return Ok(()) + return Ok(()); }, }; @@ -1832,7 +1833,7 @@ async fn maybe_validate_and_import( sender_validator_idx = ?statement.validator_index(), "Not importing statement because the sender is disabled" ); - return Ok(()) + return Ok(()); } let res = import_statement(ctx, rp_state, &mut state.per_candidate, &statement).await; @@ -1846,7 +1847,7 @@ async fn maybe_validate_and_import( "Statement rejected by prospective parachains." ); - return Ok(()) + return Ok(()); } let summary = res?; @@ -1860,7 +1861,7 @@ async fn maybe_validate_and_import( let candidate_hash = summary.candidate; if Some(summary.group_id) != rp_state.assignment { - return Ok(()) + return Ok(()); } let attesting = match statement.payload() { StatementWithPVD::Seconded(receipt, _) => { @@ -1881,20 +1882,20 @@ async fn maybe_validate_and_import( if let Some(attesting) = rp_state.fallbacks.get_mut(candidate_hash) { let our_index = rp_state.table_context.validator.as_ref().map(|v| v.index()); if our_index == Some(statement.validator_index()) { - return Ok(()) + return Ok(()); } if rp_state.awaiting_validation.contains(candidate_hash) { // Job already running: attesting.backing.push(statement.validator_index()); - return Ok(()) + return Ok(()); } else { // No job, so start another with current validator: attesting.from_validator = statement.validator_index(); attesting.clone() } } else { - return Ok(()) + return Ok(()); } }, }; @@ -1979,7 +1980,7 @@ async fn handle_second_message( "Candidate backing was asked to second candidate with wrong PVD", ); - return Ok(()) + return Ok(()); } let rp_state = match state.per_relay_parent.get_mut(&relay_parent) { @@ -1991,7 +1992,7 @@ async fn handle_second_message( "We were asked to second a candidate outside of our view." ); - return Ok(()) + return Ok(()); }, Some(r) => r, }; @@ -2000,7 +2001,7 @@ async fn handle_second_message( // validator but defensively use `unwrap_or(false)` to continue processing in this case. if rp_state.table_context.local_validator_is_disabled().unwrap_or(false) { gum::warn!(target: LOG_TARGET, "Local validator is disabled. Don't validate and second"); - return Ok(()) + return Ok(()); } // Sanity check that candidate is from our assignment. @@ -2012,7 +2013,7 @@ async fn handle_second_message( "Subsystem asked to second for para outside of our assignment", ); - return Ok(()) + return Ok(()); } // If the message is a `CandidateBackingMessage::Second`, sign and dispatch a @@ -2077,7 +2078,7 @@ fn handle_get_backed_candidates_message( ?candidate_hash, "Requested candidate's relay parent is out of view", ); - return None + return None; }, }; rp_state diff --git a/polkadot/node/core/backing/src/tests/prospective_parachains.rs b/polkadot/node/core/backing/src/tests/prospective_parachains.rs index 578f21bef6651..45b3ad1d3caf1 100644 --- a/polkadot/node/core/backing/src/tests/prospective_parachains.rs +++ b/polkadot/node/core/backing/src/tests/prospective_parachains.rs @@ -99,7 +99,7 @@ async fn activate_leaf( // reuse the message. if !matches!(&msg, AllMessages::ChainApi(ChainApiMessage::BlockHeader(..))) { next_overseer_message.replace(msg); - break + break; } assert_matches!( @@ -1372,7 +1372,7 @@ fn concurrent_dependent_candidates() { backed_statements.insert(hash); if backed_statements.len() == 2 { - break + break; } }, AllMessages::RuntimeApi(RuntimeApiMessage::Request( diff --git a/polkadot/node/core/bitfield-signing/src/lib.rs b/polkadot/node/core/bitfield-signing/src/lib.rs index 0fc0bb3d27887..2b967ce496c7e 100644 --- a/polkadot/node/core/bitfield-signing/src/lib.rs +++ b/polkadot/node/core/bitfield-signing/src/lib.rs @@ -290,7 +290,7 @@ where Err(Error::Runtime(runtime_err)) => { // Don't take down the node on runtime API errors. gum::warn!(target: LOG_TARGET, err = ?runtime_err, "Encountered a runtime API error"); - return Ok(()) + return Ok(()); }, Err(err) => return Err(err), Ok(bitfield) => bitfield, @@ -307,7 +307,7 @@ where target: LOG_TARGET, "Key was found at construction, but while signing it could not be found.", ); - return Ok(()) + return Ok(()); }, }; diff --git a/polkadot/node/core/candidate-validation/src/lib.rs b/polkadot/node/core/candidate-validation/src/lib.rs index bf6e09fd1b69b..bf0a871c36f2d 100644 --- a/polkadot/node/core/candidate-validation/src/lib.rs +++ b/polkadot/node/core/candidate-validation/src/lib.rs @@ -361,7 +361,7 @@ where ?validation_code_hash, "precheck: requested validation code is not found on-chain!", ); - return PreCheckOutcome::Failed + return PreCheckOutcome::Failed; }, }; @@ -382,7 +382,7 @@ where ?validation_code_hash, "precheck: failed to acquire executor params for the session, thus voting against.", ); - return PreCheckOutcome::Invalid + return PreCheckOutcome::Invalid; }; let timeout = pvf_prep_timeout(&executor_params, PvfPrepKind::Precheck); @@ -399,7 +399,7 @@ where ), Err(e) => { gum::debug!(target: LOG_TARGET, err=?e, "precheck: cannot decompress validation code"); - return PreCheckOutcome::Invalid + return PreCheckOutcome::Invalid; }, }; @@ -606,7 +606,7 @@ async fn validate_candidate_exhaustive( &validation_code_hash, ) { gum::info!(target: LOG_TARGET, ?para_id, "Invalid candidate (basic checks)"); - return Ok(ValidationResult::Invalid(e)) + return Ok(ValidationResult::Invalid(e)); } let raw_validation_code = match sp_maybe_compressed_blob::decompress( @@ -619,7 +619,7 @@ async fn validate_candidate_exhaustive( // Code already passed pre-checking, if decompression fails now this most likley means // some local corruption happened. - return Err(ValidationFailed("Code decompression failed".to_string())) + return Err(ValidationFailed("Code decompression failed".to_string())); }, }; metrics.observe_code_size(raw_validation_code.len()); @@ -632,7 +632,7 @@ async fn validate_candidate_exhaustive( gum::info!(target: LOG_TARGET, ?para_id, err=?e, "Invalid candidate (PoV code)"); // If the PoV is invalid, the candidate certainly is. - return Ok(ValidationResult::Invalid(InvalidCandidate::PoVDecompressionFailure)) + return Ok(ValidationResult::Invalid(InvalidCandidate::PoVDecompressionFailure)); }, }; metrics.observe_pov_size(raw_block_data.0.len(), false); @@ -709,7 +709,7 @@ async fn validate_candidate_exhaustive( ); Err(ValidationFailed(e.to_string())) }, - Ok(res) => + Ok(res) => { if res.head_data.hash() != candidate_receipt.descriptor.para_head { gum::info!(target: LOG_TARGET, ?para_id, "Invalid candidate (para_head)"); Ok(ValidationResult::Invalid(InvalidCandidate::ParaHeadHashMismatch)) @@ -735,7 +735,8 @@ async fn validate_candidate_exhaustive( } else { Ok(ValidationResult::Valid(outputs, persisted_validation_data)) } - }, + } + }, } } @@ -777,7 +778,7 @@ trait ValidationBackend { let mut validation_result = self.validate_candidate(pvf.clone(), exec_timeout, params.encode()).await; if validation_result.is_ok() { - return validation_result + return validation_result; } // Allow limited retries for each kind of error. @@ -787,7 +788,7 @@ trait ValidationBackend { loop { // Stop retrying if we exceeded the timeout. if total_time_start.elapsed() + retry_delay > exec_timeout { - break + break; } match validation_result { @@ -798,21 +799,21 @@ trait ValidationBackend { if num_death_retries_left > 0 { num_death_retries_left -= 1; } else { - break + break; }, Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::JobError(_))) => if num_job_error_retries_left > 0 { num_job_error_retries_left -= 1; } else { - break + break; }, Err(ValidationError::Internal(_)) => if num_internal_retries_left > 0 { num_internal_retries_left -= 1; } else { - break + break; }, Ok(_) | Err(ValidationError::Invalid(_) | ValidationError::Preparation(_)) => break, @@ -864,7 +865,7 @@ impl ValidationBackend for ValidationHost { "cannot send pvf to the validation host, it might have shut down: {:?}", err )) - .into()) + .into()); } rx.await.map_err(|_| { @@ -878,7 +879,7 @@ impl ValidationBackend for ValidationHost { let (tx, rx) = oneshot::channel(); if let Err(err) = self.precheck_pvf(pvf, tx).await { // Return an IO error if there was an error communicating with the host. - return Err(PrepareError::IoErr(err)) + return Err(PrepareError::IoErr(err)); } let precheck_result = rx.await.map_err(|err| PrepareError::IoErr(err.to_string()))?; @@ -899,19 +900,19 @@ fn perform_basic_checks( let encoded_pov_size = pov.encoded_size(); if encoded_pov_size > max_pov_size as usize { - return Err(InvalidCandidate::ParamsTooLarge(encoded_pov_size as u64)) + return Err(InvalidCandidate::ParamsTooLarge(encoded_pov_size as u64)); } if pov_hash != candidate.pov_hash { - return Err(InvalidCandidate::PoVHashMismatch) + return Err(InvalidCandidate::PoVHashMismatch); } if *validation_code_hash != candidate.validation_code_hash { - return Err(InvalidCandidate::CodeHashMismatch) + return Err(InvalidCandidate::CodeHashMismatch); } if let Err(()) = candidate.check_collator_signature() { - return Err(InvalidCandidate::BadSignature) + return Err(InvalidCandidate::BadSignature); } Ok(()) @@ -928,7 +929,7 @@ fn perform_basic_checks( /// unresponsive and will be killed. fn pvf_prep_timeout(executor_params: &ExecutorParams, kind: PvfPrepKind) -> Duration { if let Some(timeout) = executor_params.pvf_prep_timeout(kind) { - return timeout + return timeout; } match kind { PvfPrepKind::Precheck => DEFAULT_PRECHECK_PREPARATION_TIMEOUT, @@ -948,7 +949,7 @@ fn pvf_prep_timeout(executor_params: &ExecutorParams, kind: PvfPrepKind) -> Dura /// considered executable by approval checkers or dispute participants. fn pvf_exec_timeout(executor_params: &ExecutorParams, kind: PvfExecKind) -> Duration { if let Some(timeout) = executor_params.pvf_exec_timeout(kind) { - return timeout + return timeout; } match kind { PvfExecKind::Backing => DEFAULT_BACKING_EXECUTION_TIMEOUT, diff --git a/polkadot/node/core/candidate-validation/src/tests.rs b/polkadot/node/core/candidate-validation/src/tests.rs index f646f8535495b..1107858046526 100644 --- a/polkadot/node/core/candidate-validation/src/tests.rs +++ b/polkadot/node/core/candidate-validation/src/tests.rs @@ -726,7 +726,7 @@ fn candidate_validation_retry_on_error_helper( ExecutorParams::default(), exec_kind, &Default::default(), - )) + )); } #[test] diff --git a/polkadot/node/core/chain-selection/src/backend.rs b/polkadot/node/core/chain-selection/src/backend.rs index 71fa55ac65756..40e642e8b5264 100644 --- a/polkadot/node/core/chain-selection/src/backend.rs +++ b/polkadot/node/core/chain-selection/src/backend.rs @@ -94,7 +94,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub(super) fn load_block_entry(&self, hash: &Hash) -> Result, Error> { if let Some(val) = self.block_entries.get(&hash) { - return Ok(val.clone()) + return Ok(val.clone()); } self.inner.load_block_entry(hash) @@ -102,7 +102,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub(super) fn load_blocks_by_number(&self, number: BlockNumber) -> Result, Error> { if let Some(val) = self.blocks_by_number.get(&number) { - return Ok(val.as_ref().map_or(Vec::new(), Clone::clone)) + return Ok(val.as_ref().map_or(Vec::new(), Clone::clone)); } self.inner.load_blocks_by_number(number) @@ -110,7 +110,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub(super) fn load_leaves(&self) -> Result { if let Some(ref set) = self.leaves { - return Ok(set.clone()) + return Ok(set.clone()); } self.inner.load_leaves() @@ -118,7 +118,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { pub(super) fn load_stagnant_at(&self, timestamp: Timestamp) -> Result, Error> { if let Some(val) = self.stagnant_at.get(×tamp) { - return Ok(val.as_ref().map_or(Vec::new(), Clone::clone)) + return Ok(val.as_ref().map_or(Vec::new(), Clone::clone)); } self.inner.load_stagnant_at(timestamp) @@ -196,7 +196,7 @@ fn contains_ancestor(backend: &impl Backend, head: Hash, ancestor: Hash) -> Resu let mut current_hash = head; loop { if current_hash == ancestor { - return Ok(true) + return Ok(true); } match backend.load_block_entry(¤t_hash)? { Some(e) => current_hash = e.parent_hash, @@ -228,7 +228,7 @@ pub(super) fn find_best_leaf_containing( let leaves = backend.load_leaves()?; for leaf in leaves.into_hashes_descending() { if contains_ancestor(backend, leaf, required)? { - return Ok(Some(leaf)) + return Ok(Some(leaf)); } } diff --git a/polkadot/node/core/chain-selection/src/db_backend/v1.rs b/polkadot/node/core/chain-selection/src/db_backend/v1.rs index 7c7144bb763df..f38474fd5168c 100644 --- a/polkadot/node/core/chain-selection/src/db_backend/v1.rs +++ b/polkadot/node/core/chain-selection/src/db_backend/v1.rs @@ -236,12 +236,13 @@ impl Backend for DbBackend { let val = stagnant_at_iter .filter_map(|r| match r { - Ok((k, v)) => + Ok((k, v)) => { match (decode_stagnant_at_key(&mut &k[..]), >::decode(&mut &v[..]).ok()) { (Some(at), Some(stagnant_at)) => Some(Ok((at, stagnant_at))), _ => None, - }, + } + }, Err(e) => Some(Err(e)), }) .enumerate() @@ -370,10 +371,10 @@ fn stagnant_at_key(timestamp: Timestamp) -> [u8; 14 + 8] { fn decode_block_height_key(key: &[u8]) -> Option { if key.len() != 15 + 4 { - return None + return None; } if !key.starts_with(BLOCK_HEIGHT_PREFIX) { - return None + return None; } let mut bytes = [0; 4]; @@ -383,10 +384,10 @@ fn decode_block_height_key(key: &[u8]) -> Option { fn decode_stagnant_at_key(key: &[u8]) -> Option { if key.len() != 14 + 8 { - return None + return None; } if !key.starts_with(STAGNANT_AT_PREFIX) { - return None + return None; } let mut bytes = [0; 8]; diff --git a/polkadot/node/core/chain-selection/src/lib.rs b/polkadot/node/core/chain-selection/src/lib.rs index aa5bb9548ad24..24d938836a89c 100644 --- a/polkadot/node/core/chain-selection/src/lib.rs +++ b/polkadot/node/core/chain-selection/src/lib.rs @@ -144,11 +144,11 @@ impl LeafEntrySet { let mut pos = None; for (i, e) in self.inner.iter().enumerate() { if e == &new { - return + return; } if e < &new { pos = Some(i); - break + break; } } @@ -397,11 +397,11 @@ async fn run( Err(e) => { e.trace(); // All errors are considered fatal right now: - break + break; }, Ok(()) => { gum::info!(target: LOG_TARGET, "received `Conclude` signal, exiting"); - break + break; }, } } @@ -499,7 +499,7 @@ async fn fetch_finalized( Ok(number) => number, Err(err) => { gum::warn!(target: LOG_TARGET, ?err, "Fetching finalized number failed"); - return Ok(None) + return Ok(None); }, }; @@ -568,7 +568,7 @@ async fn handle_active_leaf( let header = match fetch_header(sender, hash).await? { None => { gum::warn!(target: LOG_TARGET, ?hash, "Missing header for new head"); - return Ok(Vec::new()) + return Ok(Vec::new()); }, Some(h) => h, }; @@ -597,7 +597,7 @@ async fn handle_active_leaf( // If we don't know the weight, we can't import the block. // And none of its descendants either. - break + break; }, Some(w) => w, }; diff --git a/polkadot/node/core/chain-selection/src/tests.rs b/polkadot/node/core/chain-selection/src/tests.rs index cf021c0efeb06..9cfc62f3025c6 100644 --- a/polkadot/node/core/chain-selection/src/tests.rs +++ b/polkadot/node/core/chain-selection/src/tests.rs @@ -171,7 +171,7 @@ impl Backend for TestBackend { // Early return if empty because empty writes shouldn't // trigger wakeups (they happen on an interval) if ops.is_empty() { - return Ok(()) + return Ok(()); } let mut inner = self.inner.lock(); @@ -511,7 +511,7 @@ async fn import_all_blocks_into( // Last weight has been returned. Time to go. if h == head_hash { - break + break; } }, _ => panic!("unexpected message"), diff --git a/polkadot/node/core/chain-selection/src/tree.rs b/polkadot/node/core/chain-selection/src/tree.rs index b4aba30368a62..86945e374dbc8 100644 --- a/polkadot/node/core/chain-selection/src/tree.rs +++ b/polkadot/node/core/chain-selection/src/tree.rs @@ -111,7 +111,7 @@ fn propagate_viability_update( // Furthermore, in such cases, the set of viable leaves // does not change at all. backend.write_block_entry(base); - return Ok(()) + return Ok(()); } let mut viable_leaves = backend.load_leaves()?; @@ -147,7 +147,7 @@ fn propagate_viability_update( "Missing expected block entry" ); - continue + continue; }, Some(entry) => entry, }, @@ -222,7 +222,7 @@ fn propagate_viability_update( // // Furthermore, if the set of viable leaves is empty, the // finalized block is implicitly the viable leaf. - continue + continue; }, Some(entry) => if entry.children.len() == pivot_count { @@ -265,7 +265,7 @@ fn load_ancestor( ancestor_number: BlockNumber, ) -> Result, Error> { if block_number <= ancestor_number { - return Ok(None) + return Ok(None); } let mut current_hash = block_hash; @@ -466,7 +466,7 @@ pub(super) fn finalize_block<'a, B: Backend + 'a>( None => { // This implies that there are no unfinalized blocks and hence nothing // to update. - return Ok(backend) + return Ok(backend); }, Some(e) => e, }; @@ -717,7 +717,7 @@ pub(super) fn revert_to<'a, B: Backend + 'a>( // The parent is expected to be the last finalized block. if block.parent_hash != hash { - return Err(ChainApiError::from("Can't revert below last finalized block").into()) + return Err(ChainApiError::from("Can't revert below last finalized block").into()); } // The weight is set to the one of the first child. Even though this is diff --git a/polkadot/node/core/dispute-coordinator/src/backend.rs b/polkadot/node/core/dispute-coordinator/src/backend.rs index cf0bdd4043ca2..d5a0a22f1a326 100644 --- a/polkadot/node/core/dispute-coordinator/src/backend.rs +++ b/polkadot/node/core/dispute-coordinator/src/backend.rs @@ -94,7 +94,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { /// Load the earliest session, if any. pub fn load_earliest_session(&self) -> FatalResult> { if let Some(val) = self.earliest_session { - return Ok(Some(val)) + return Ok(Some(val)); } self.inner.load_earliest_session() @@ -103,7 +103,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { /// Load the recent disputes, if any. pub fn load_recent_disputes(&self) -> FatalResult> { if let Some(val) = &self.recent_disputes { - return Ok(Some(val.clone())) + return Ok(Some(val.clone())); } self.inner.load_recent_disputes() @@ -116,7 +116,7 @@ impl<'a, B: 'a + Backend> OverlayedBackend<'a, B> { candidate_hash: &CandidateHash, ) -> FatalResult> { if let Some(val) = self.candidate_votes.get(&(session, *candidate_hash)) { - return Ok(val.clone()) + return Ok(val.clone()); } self.inner.load_candidate_votes(session, candidate_hash) diff --git a/polkadot/node/core/dispute-coordinator/src/import.rs b/polkadot/node/core/dispute-coordinator/src/import.rs index 278561d5d00c1..1af845a7756b9 100644 --- a/polkadot/node/core/dispute-coordinator/src/import.rs +++ b/polkadot/node/core/dispute-coordinator/src/import.rs @@ -137,7 +137,7 @@ impl OwnVoteState { fn new(votes: &CandidateVotes, env: &CandidateEnvironment) -> Self { let controlled_indices = env.controlled_indices(); if controlled_indices.is_empty() { - return Self::CannotVote + return Self::CannotVote; } let our_valid_votes = controlled_indices @@ -295,7 +295,7 @@ impl CandidateVoteState { "Validator index doesn't match claimed key", ); - continue + continue; } if statement.candidate_hash() != &expected_candidate_hash { gum::error!( @@ -306,7 +306,7 @@ impl CandidateVoteState { ?expected_candidate_hash, "Vote is for unexpected candidate!", ); - continue + continue; } if statement.session_index() != env.session_index() { gum::error!( @@ -317,7 +317,7 @@ impl CandidateVoteState { ?expected_candidate_hash, "Vote is for unexpected session!", ); - continue + continue; } match statement.statement() { @@ -619,7 +619,7 @@ fn find_controlled_validator_indices( let mut controlled = HashSet::new(); for (index, validator) in validators.iter().enumerate() { if keystore.key_pair::(validator).ok().flatten().is_none() { - continue + continue; } controlled.insert(ValidatorIndex(index as _)); diff --git a/polkadot/node/core/dispute-coordinator/src/initialized.rs b/polkadot/node/core/dispute-coordinator/src/initialized.rs index a1bcc1f01707c..c28919946f27d 100644 --- a/polkadot/node/core/dispute-coordinator/src/initialized.rs +++ b/polkadot/node/core/dispute-coordinator/src/initialized.rs @@ -169,7 +169,7 @@ impl Initialized { self.run_until_error(&mut ctx, &mut backend, &mut initial_data, &*clock).await; if let Ok(()) = res { gum::info!(target: LOG_TARGET, "received `Conclude` signal, exiting"); - return Ok(()) + return Ok(()); } log_error(res)?; } @@ -411,7 +411,7 @@ impl Initialized { ?session_index, "Couldn't find blocks in the session for an unapplied slash", ); - return + return; } // Find a relay block that we can use @@ -468,7 +468,7 @@ impl Initialized { // If we found a parent that we can use, stop searching. // If one key ownership was resolved successfully, all of them should be. debug_assert_eq!(key_ownership_proofs.len(), pending.keys.len()); - break + break; } } @@ -591,7 +591,7 @@ impl Initialized { let ScrapedOnChainVotes { session, backing_validators_per_candidate, disputes } = votes; if backing_validators_per_candidate.is_empty() && disputes.is_empty() { - return Ok(()) + return Ok(()); } // Scraped on-chain backing votes for the candidates with @@ -612,7 +612,7 @@ impl Initialized { ?err, "Could not retrieve session info from RuntimeInfo", ); - return Ok(()) + return Ok(()); }, }; @@ -724,7 +724,7 @@ impl Initialized { ?err, "Could not retrieve session info for recently concluded dispute" ); - continue + continue; }, }; @@ -760,7 +760,7 @@ impl Initialized { .collect::>(); if statements.is_empty() { gum::debug!(target: LOG_TARGET, "Skipping empty from chain dispute import"); - continue + continue; } let import_result = self .handle_import_statements( @@ -942,7 +942,7 @@ impl Initialized { gum::trace!(target: LOG_TARGET, ?statements, "In handle import statements"); if self.session_is_ancient(session) { // It is not valid to participate in an ancient dispute (spam?) or too new. - return Ok(ImportStatementsResult::InvalidImport) + return Ok(ImportStatementsResult::InvalidImport); } let candidate_hash = candidate_receipt.hash(); @@ -959,7 +959,7 @@ impl Initialized { ?candidate_hash, "Cannot obtain relay parent without `CandidateReceipt` available!" ); - return Ok(ImportStatementsResult::InvalidImport) + return Ok(ImportStatementsResult::InvalidImport); }, }, }; @@ -980,7 +980,7 @@ impl Initialized { "We are lacking a `SessionInfo` for handling import of statements." ); - return Ok(ImportStatementsResult::InvalidImport) + return Ok(ImportStatementsResult::InvalidImport); }, Some(env) => env, }; @@ -1015,7 +1015,7 @@ impl Initialized { ?candidate_hash, "Cannot import votes, without `CandidateReceipt` available!" ); - return Ok(ImportStatementsResult::InvalidImport) + return Ok(ImportStatementsResult::InvalidImport); }, }; @@ -1114,7 +1114,7 @@ impl Initialized { .chain(self.offchain_disabled_validators.iter(session)) { if d.len() == byzantine_threshold { - break + break; } d.insert(v); } @@ -1171,7 +1171,7 @@ impl Initialized { invalid_voters = ?import_result.new_invalid_voters(), "Rejecting import because of full spam slots." ); - return Ok(ImportStatementsResult::InvalidImport) + return Ok(ImportStatementsResult::InvalidImport); } } @@ -1239,7 +1239,7 @@ impl Initialized { ?session, "Could not find pub key in `SessionInfo` for our own approval vote!" ); - continue + continue; }, Some(k) => k, }; @@ -1449,7 +1449,7 @@ impl Initialized { "Missing info for session which has an active dispute", ); - return Ok(()) + return Ok(()); }, Some(env) => env, }; @@ -1471,7 +1471,7 @@ impl Initialized { let controlled_indices = env.controlled_indices(); for index in controlled_indices { if voted_indices.contains(&index) { - continue + continue; } let keystore = self.keystore.clone() as Arc<_>; @@ -1507,7 +1507,7 @@ impl Initialized { match make_dispute_message(env.session_info(), &votes, statement.clone(), *index) { Err(err) => { gum::debug!(target: LOG_TARGET, ?err, "Creating dispute message failed."); - continue + continue; }, Ok(dispute_message) => dispute_message, }; @@ -1551,7 +1551,7 @@ impl Initialized { } fn session_is_ancient(&self, session_idx: SessionIndex) -> bool { - return session_idx < self.highest_session_seen.saturating_sub(DISPUTE_WINDOW.get() - 1) + return session_idx < self.highest_session_seen.saturating_sub(DISPUTE_WINDOW.get() - 1); } } @@ -1628,9 +1628,9 @@ fn determine_undisputed_chain( for (i, BlockDescription { session, candidates, .. }) in block_descriptions.iter().enumerate() { if candidates.iter().any(|c| is_possibly_invalid(*session, *c)) { if i == 0 { - return Ok((base_number, base_hash)) + return Ok((base_number, base_hash)); } else { - return Ok((base_number + i as BlockNumber, block_descriptions[i - 1].block_hash)) + return Ok((base_number + i as BlockNumber, block_descriptions[i - 1].block_hash)); } } } diff --git a/polkadot/node/core/dispute-coordinator/src/lib.rs b/polkadot/node/core/dispute-coordinator/src/lib.rs index c3038fc0953c6..f125eb0894944 100644 --- a/polkadot/node/core/dispute-coordinator/src/lib.rs +++ b/polkadot/node/core/dispute-coordinator/src/lib.rs @@ -215,7 +215,7 @@ impl DisputeCoordinatorSubsystem { Ok(None) => continue, Err(e) => { e.split()?.log(); - continue + continue; }, }; @@ -240,7 +240,7 @@ impl DisputeCoordinatorSubsystem { Ok(v) => v, Err(e) => { e.split()?.log(); - continue + continue; }, }; if !overlay_db.is_empty() { @@ -261,7 +261,7 @@ impl DisputeCoordinatorSubsystem { gaps_in_cache, ), backend, - ))) + ))); } } @@ -294,7 +294,7 @@ impl DisputeCoordinatorSubsystem { .flatten(), Err(e) => { gum::error!(target: LOG_TARGET, "Failed initial load of recent disputes: {:?}", e); - return Err(e.into()) + return Err(e.into()); }, }; @@ -320,7 +320,7 @@ impl DisputeCoordinatorSubsystem { "Can't cache SessionInfo during subsystem initialization. Skipping session." ); gap_in_cache = true; - continue + continue; }; } @@ -351,7 +351,7 @@ impl DisputeCoordinatorSubsystem { "We are lacking a `SessionInfo` for handling db votes on startup." ); - continue + continue; }, Some(env) => env, }; @@ -366,7 +366,7 @@ impl DisputeCoordinatorSubsystem { "Failed initial load of candidate votes: {:?}", e ); - continue + continue; }, }; let vote_state = CandidateVoteState::new(votes, &env, now); @@ -438,7 +438,7 @@ async fn wait_for_first_leaf(ctx: &mut Context) -> Result return Ok(None), FromOrchestra::Signal(OverseerSignal::ActiveLeaves(update)) => { if let Some(activated) = update.activated { - return Ok(Some(activated)) + return Ok(Some(activated)); } }, FromOrchestra::Signal(OverseerSignal::BlockFinalized(_, _)) => {}, @@ -500,7 +500,7 @@ async fn send_dispute_messages( session_index = ?env.session_index(), "Could not find our own key in `SessionInfo`" ); - continue + continue; }; let our_vote_signed = SignedDisputeStatement::new_checked( kind.clone(), @@ -516,7 +516,7 @@ async fn send_dispute_messages( target: LOG_TARGET, "Checking our own signature failed - db corruption?" ); - continue + continue; }, }; let dispute_message = match make_dispute_message( @@ -527,7 +527,7 @@ async fn send_dispute_messages( ) { Err(err) => { gum::debug!(target: LOG_TARGET, ?err, "Creating dispute message failed."); - continue + continue; }, Ok(dispute_message) => dispute_message, }; diff --git a/polkadot/node/core/dispute-coordinator/src/participation/mod.rs b/polkadot/node/core/dispute-coordinator/src/participation/mod.rs index 05ea7323af141..e143995d68af5 100644 --- a/polkadot/node/core/dispute-coordinator/src/participation/mod.rs +++ b/polkadot/node/core/dispute-coordinator/src/participation/mod.rs @@ -165,13 +165,13 @@ impl Participation { // Participation already running - we can ignore that request, discarding its timer: if self.running_participations.contains(req.candidate_hash()) { req.discard_timer(); - return Ok(()) + return Ok(()); } // Available capacity - participate right away (if we already have a recent block): if let Some((_, h)) = self.recent_block { if self.running_participations.len() < MAX_PARALLEL_PARTICIPATIONS { self.fork_participation(ctx, req, h)?; - return Ok(()) + return Ok(()); } } // Out of capacity/no recent block yet - queue: @@ -247,7 +247,7 @@ impl Participation { if let Some(req) = self.queue.dequeue() { self.fork_participation(ctx, req, recent_head)?; } else { - break + break; } } Ok(()) @@ -317,7 +317,7 @@ async fn participate( req.candidate_hash(), ); send_result(&mut result_sender, req, ParticipationOutcome::Error).await; - return + return; }, Ok(Ok(data)) => data, Ok(Err(RecoveryError::Invalid)) => { @@ -330,7 +330,7 @@ async fn participate( // the available data was recovered but it is invalid, therefore we'll // vote negatively for the candidate dispute send_result(&mut result_sender, req, ParticipationOutcome::Invalid).await; - return + return; }, Ok(Err(RecoveryError::Unavailable)) | Ok(Err(RecoveryError::ChannelClosed)) => { gum::debug!( @@ -340,7 +340,7 @@ async fn participate( "Can't fetch availability data in participation" ); send_result(&mut result_sender, req, ParticipationOutcome::Unavailable).await; - return + return; }, }; @@ -363,12 +363,12 @@ async fn participate( ); send_result(&mut result_sender, req, ParticipationOutcome::Error).await; - return + return; }, Err(err) => { gum::warn!(target: LOG_TARGET, ?err, "Error when fetching validation code."); send_result(&mut result_sender, req, ParticipationOutcome::Error).await; - return + return; }, }; @@ -401,7 +401,7 @@ async fn participate( req.candidate_hash(), ); send_result(&mut result_sender, req, ParticipationOutcome::Error).await; - return + return; }, Ok(Err(err)) => { gum::warn!( diff --git a/polkadot/node/core/dispute-coordinator/src/participation/queues/mod.rs b/polkadot/node/core/dispute-coordinator/src/participation/queues/mod.rs index d9e86def168c9..55b26a69c692f 100644 --- a/polkadot/node/core/dispute-coordinator/src/participation/queues/mod.rs +++ b/polkadot/node/core/dispute-coordinator/src/participation/queues/mod.rs @@ -208,11 +208,11 @@ impl Queues { pub fn dequeue(&mut self) -> Option { if let Some(req) = self.pop_priority() { self.metrics.report_priority_queue_size(self.priority.len() as u64); - return Some(req.1) + return Some(req.1); } if let Some(req) = self.pop_best_effort() { self.metrics.report_best_effort_queue_size(self.best_effort.len() as u64); - return Some(req.1) + return Some(req.1); } None } @@ -234,7 +234,7 @@ impl Queues { comparator: CandidateComparator, ) -> std::result::Result<(), QueueError> { if self.priority.len() >= PRIORITY_QUEUE_SIZE { - return Err(QueueError::PriorityFull) + return Err(QueueError::PriorityFull); } if let Some(request) = self.best_effort.remove(&comparator) { self.priority.insert(comparator, request); @@ -265,7 +265,7 @@ impl Queues { ) -> std::result::Result<(), QueueError> { if priority.is_priority() { if self.priority.len() >= PRIORITY_QUEUE_SIZE { - return Err(QueueError::PriorityFull) + return Err(QueueError::PriorityFull); } // Remove any best effort entry, using it to replace our new // request. @@ -291,10 +291,10 @@ impl Queues { if self.priority.contains_key(&comparator) { // The candidate is already in priority queue - don't // add in in best effort too. - return Ok(()) + return Ok(()); } if self.best_effort.len() >= BEST_EFFORT_QUEUE_SIZE { - return Err(QueueError::BestEffortFull) + return Err(QueueError::BestEffortFull); } // Keeping old request if any. match self.best_effort.entry(comparator) { @@ -315,12 +315,12 @@ impl Queues { /// Get best from the best effort queue. fn pop_best_effort(&mut self) -> Option<(CandidateComparator, ParticipationRequest)> { - return Self::pop_impl(&mut self.best_effort) + return Self::pop_impl(&mut self.best_effort); } /// Get best priority queue entry. fn pop_priority(&mut self) -> Option<(CandidateComparator, ParticipationRequest)> { - return Self::pop_impl(&mut self.priority) + return Self::pop_impl(&mut self.priority); } // `pop_best_effort` and `pop_priority` do the same but on different `BTreeMap`s. This function @@ -457,7 +457,7 @@ impl Ord for CandidateComparator { // Ditto Ordering::Greater }, - } + }; } } diff --git a/polkadot/node/core/dispute-coordinator/src/scraping/mod.rs b/polkadot/node/core/dispute-coordinator/src/scraping/mod.rs index fdf39cff0f2ef..eec77c1c10181 100644 --- a/polkadot/node/core/dispute-coordinator/src/scraping/mod.rs +++ b/polkadot/node/core/dispute-coordinator/src/scraping/mod.rs @@ -396,7 +396,7 @@ impl ChainScraper { // If head_number <= target_ancestor + 1 the ancestry will be empty. if self.last_observed_blocks.get(&head).is_some() || head_number <= target_ancestor + 1 { - return Ok(ancestors) + return Ok(ancestors); } loop { @@ -413,7 +413,7 @@ impl ChainScraper { hashes.len(), head_number, ); - return Ok(ancestors) + return Ok(ancestors); }, }; // The reversed order is parent, grandparent, etc. excluding the head. @@ -426,7 +426,7 @@ impl ChainScraper { block_number <= target_ancestor || ancestors.len() >= Self::ANCESTRY_SIZE_LIMIT as usize { - return Ok(ancestors) + return Ok(ancestors); } ancestors.push(*hash); @@ -440,7 +440,7 @@ impl ChainScraper { None => break, } } - return Ok(ancestors) + return Ok(ancestors); } pub fn get_blocks_including_candidate( diff --git a/polkadot/node/core/dispute-coordinator/src/spam_slots.rs b/polkadot/node/core/dispute-coordinator/src/spam_slots.rs index fd2f65b1bc8ee..c789282d7e671 100644 --- a/polkadot/node/core/dispute-coordinator/src/spam_slots.rs +++ b/polkadot/node/core/dispute-coordinator/src/spam_slots.rs @@ -95,7 +95,7 @@ impl SpamSlots { ) -> bool { let spam_vote_count = self.slots.entry((session, validator)).or_default(); if *spam_vote_count >= MAX_SPAM_VOTES { - return false + return false; } let validators = self.unconfirmed.entry((session, candidate)).or_default(); diff --git a/polkadot/node/core/dispute-coordinator/src/tests.rs b/polkadot/node/core/dispute-coordinator/src/tests.rs index af384256c4f71..0f5634c951f8f 100644 --- a/polkadot/node/core/dispute-coordinator/src/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/tests.rs @@ -442,7 +442,7 @@ impl TestState { }, } } - return sent_disputes + return sent_disputes; } async fn handle_resume_sync( diff --git a/polkadot/node/core/prospective-parachains/src/fragment_tree.rs b/polkadot/node/core/prospective-parachains/src/fragment_tree.rs index 04ee42a9de062..bd3f649092ac1 100644 --- a/polkadot/node/core/prospective-parachains/src/fragment_tree.rs +++ b/polkadot/node/core/prospective-parachains/src/fragment_tree.rs @@ -146,11 +146,11 @@ impl CandidateStorage { let candidate_hash = candidate.hash(); if self.by_candidate_hash.contains_key(&candidate_hash) { - return Err(CandidateStorageInsertionError::CandidateAlreadyKnown(candidate_hash)) + return Err(CandidateStorageInsertionError::CandidateAlreadyKnown(candidate_hash)); } if persisted_validation_data.hash() != candidate.descriptor.persisted_validation_data_hash { - return Err(CandidateStorageInsertionError::PersistedValidationDataMismatch) + return Err(CandidateStorageInsertionError::PersistedValidationDataMismatch); } let parent_head_hash = persisted_validation_data.parent_head.hash(); @@ -370,11 +370,11 @@ impl Scope { let mut prev = relay_parent.number; for ancestor in ancestors { if prev == 0 { - return Err(UnexpectedAncestor { number: ancestor.number, prev }) + return Err(UnexpectedAncestor { number: ancestor.number, prev }); } else if ancestor.number != prev - 1 { - return Err(UnexpectedAncestor { number: ancestor.number, prev }) + return Err(UnexpectedAncestor { number: ancestor.number, prev }); } else if prev == base_constraints.min_relay_parent_number { - break + break; } else { prev = ancestor.number; ancestors_by_hash.insert(ancestor.hash, ancestor.clone()); @@ -406,7 +406,7 @@ impl Scope { /// Get the ancestor of the fragment tree by hash. pub fn ancestor_by_hash(&self, hash: &Hash) -> Option { if hash == &self.relay_parent.hash { - return Some(self.relay_parent.clone()) + return Some(self.relay_parent.clone()); } self.ancestors_by_hash.get(hash).map(|info| info.clone()) @@ -626,7 +626,7 @@ impl FragmentTree { if candidate_storage.get(candidate_hash).map_or(true, |candidate_entry| { !matches!(candidate_entry.state, CandidateState::Backed) }) { - return false + return false; } parent_pointer = node.parent; } @@ -653,7 +653,7 @@ impl FragmentTree { if !backed_in_path_only { // if known. if let Some(depths) = self.candidates.get(&hash) { - return depths.iter_ones().collect() + return depths.iter_ones().collect(); } } @@ -664,7 +664,7 @@ impl FragmentTree { } else if let Some(info) = self.scope.ancestors_by_hash.get(&candidate_relay_parent) { info.clone() } else { - return Vec::new() + return Vec::new(); }; let max_depth = self.scope.max_depth; @@ -694,11 +694,11 @@ impl FragmentTree { }; if child_depth > max_depth { - continue + continue; } if earliest_rp.number > candidate_relay_parent.number { - continue + continue; } let child_constraints = @@ -711,14 +711,14 @@ impl FragmentTree { "Failed to apply modifications", ); - continue + continue; }, Ok(c) => c, }; let parent_head_hash = candidate.parent_head_data_hash(); if parent_head_hash != child_constraints.required_parent.hash() { - continue + continue; } // We do additional checks for complete candidates. @@ -741,7 +741,7 @@ impl FragmentTree { ) .is_err() { - continue + continue; } } @@ -782,7 +782,7 @@ impl FragmentTree { if let Some(next_node) = self.node_candidate_child(node, &required_step) { node = next_node; } else { - return vec![] + return vec![]; }; } @@ -870,7 +870,7 @@ impl FragmentTree { // Short-circuit the search if we've found the right length. Otherwise, we'll // search for a max. if result.len() == expected_count as usize { - return result + return result; } else if best_result.len() < result.len() { best_result = result; } @@ -887,7 +887,7 @@ impl FragmentTree { let sweep_start = self.nodes.len(); if Some(sweep_start) == last_sweep_start { - break + break; } let parents: Vec = if let Some(last_start) = last_sweep_start { @@ -922,7 +922,7 @@ impl FragmentTree { }; if child_depth > self.scope.max_depth { - continue + continue; } let child_constraints = @@ -935,7 +935,7 @@ impl FragmentTree { "Failed to apply modifications", ); - continue + continue; }, Ok(c) => c, }; @@ -976,12 +976,12 @@ impl FragmentTree { }); if relay_parent.number < min_relay_parent_number { - continue // relay parent moved backwards. + continue; // relay parent moved backwards. } // don't add candidates where the parent already has it as a child. if self.node_has_candidate_child(parent_pointer, &candidate.candidate_hash) { - continue + continue; } let fragment = { @@ -1008,7 +1008,7 @@ impl FragmentTree { "Failed to instantiate fragment", ); - continue + continue; }, } }; diff --git a/polkadot/node/core/prospective-parachains/src/lib.rs b/polkadot/node/core/prospective-parachains/src/lib.rs index 6e6915b92728c..b20a28746bb44 100644 --- a/polkadot/node/core/prospective-parachains/src/lib.rs +++ b/polkadot/node/core/prospective-parachains/src/lib.rs @@ -206,7 +206,7 @@ async fn handle_active_leaves_update( ); // Not a part of any allowed ancestry. - return Ok(()) + return Ok(()); }; let mut pending_availability = HashSet::new(); @@ -225,7 +225,7 @@ async fn handle_active_leaves_update( // `update.activated` is an option, but we can use this // to exit the 'loop' and skip this block without skipping // pruning logic. - continue + continue; }, Some(info) => info, }; @@ -253,7 +253,7 @@ async fn handle_active_leaves_update( "Failed to get inclusion backing state." ); - continue + continue; }, }; @@ -340,7 +340,7 @@ fn prune_view_candidate_storage(view: &mut View, metrics: &Metrics) { view.candidate_storage.retain(|para_id, storage| { if !live_paras.contains(¶_id) { - return false + return false; } storage.retain(|h| live_candidates.contains(&h)); @@ -383,7 +383,7 @@ async fn preprocess_candidates_pending_availability( "Had to stop processing pending candidates early due to missing info.", ); - break + break; }, Some(b) => b, }; @@ -437,7 +437,7 @@ async fn handle_candidate_introduced( ); let _ = tx.send(Vec::new()); - return Ok(()) + return Ok(()); }, Some(storage) => storage, }; @@ -447,7 +447,7 @@ async fn handle_candidate_introduced( Err(CandidateStorageInsertionError::CandidateAlreadyKnown(c)) => { // Candidate known - return existing fragment tree membership. let _ = tx.send(fragment_tree_membership(&view.active_leaves, para, c)); - return Ok(()) + return Ok(()); }, Err(CandidateStorageInsertionError::PersistedValidationDataMismatch) => { // We can't log the candidate hash without either doing more ~expensive @@ -461,7 +461,7 @@ async fn handle_candidate_introduced( ); let _ = tx.send(Vec::new()); - return Ok(()) + return Ok(()); }, }; @@ -494,7 +494,7 @@ fn handle_candidate_seconded(view: &mut View, para: ParaId, candidate_hash: Cand "Received instruction to second unknown candidate", ); - return + return; }, Some(storage) => storage, }; @@ -507,7 +507,7 @@ fn handle_candidate_seconded(view: &mut View, para: ParaId, candidate_hash: Cand "Received instruction to second unknown candidate", ); - return + return; } storage.mark_seconded(&candidate_hash); @@ -529,7 +529,7 @@ async fn handle_candidate_backed( "Received instruction to back unknown candidate", ); - return Ok(()) + return Ok(()); }, Some(storage) => storage, }; @@ -542,7 +542,7 @@ async fn handle_candidate_backed( "Received instruction to back unknown candidate", ); - return Ok(()) + return Ok(()); } if storage.is_backed(&candidate_hash) { @@ -553,7 +553,7 @@ async fn handle_candidate_backed( "Received redundant instruction to mark candidate as backed", ); - return Ok(()) + return Ok(()); } storage.mark_backed(&candidate_hash); @@ -578,7 +578,7 @@ fn answer_get_backable_candidates( ); let _ = tx.send(vec![]); - return + return; }, Some(d) => d, }; @@ -593,7 +593,7 @@ fn answer_get_backable_candidates( ); let _ = tx.send(vec![]); - return + return; }, Some(tree) => tree, }; @@ -608,7 +608,7 @@ fn answer_get_backable_candidates( ); let _ = tx.send(vec![]); - return + return; }, Some(s) => s, }; @@ -766,7 +766,7 @@ fn answer_prospective_validation_data_request( let storage = match view.candidate_storage.get(&request.para_id) { None => { let _ = tx.send(None); - return + return; }, Some(s) => s, }; @@ -782,7 +782,7 @@ fn answer_prospective_validation_data_request( .filter_map(|x| x.fragment_trees.get(&request.para_id)) { if head_data.is_some() && relay_parent_info.is_some() && max_pov_size.is_some() { - break + break; } if relay_parent_info.is_none() { relay_parent_info = @@ -888,7 +888,7 @@ async fn fetch_ancestry( ancestors: usize, ) -> JfyiErrorResult> { if ancestors == 0 { - return Ok(Vec::new()) + return Ok(Vec::new()); } let (tx, rx) = oneshot::channel(); @@ -916,7 +916,7 @@ async fn fetch_ancestry( ); // Return, however far we got. - break + break; }, Some(info) => info, }; @@ -933,7 +933,7 @@ async fn fetch_ancestry( if session == required_session { block_info.push(info); } else { - break + break; } } @@ -947,7 +947,7 @@ async fn fetch_block_header_with_cache( relay_hash: Hash, ) -> JfyiErrorResult> { if let Some(h) = cache.get(&relay_hash) { - return Ok(Some(h.clone())) + return Ok(Some(h.clone())); } let (tx, rx) = oneshot::channel(); diff --git a/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs b/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs index cb55ce39bc89f..55f7251aa17ba 100644 --- a/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs +++ b/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs @@ -215,7 +215,7 @@ where onchain_state } else { // onchain knows nothing about this dispute - add all votes - return (session_index, candidate_hash, votes) + return (session_index, candidate_hash, votes); }; votes.valid.retain(|validator_idx, (statement_kind, _)| { @@ -251,7 +251,7 @@ where "vote_selection DisputeCoordinatorMessage::QueryCandidateVotes counter", ); - return result + return result; } result.insert((session_index, candidate_hash), selected_votes); @@ -425,13 +425,13 @@ fn is_vote_worth_to_keep( if in_validators_for && in_validators_against { // The validator has double voted and runtime knows about this. Ignore this vote. - return false + return false; } if offchain_vote && in_validators_against || !offchain_vote && in_validators_for { // offchain vote differs from the onchain vote // we need this vote to punish the offending validator - return true + return true; } // The vote is valid. Return true if it is not seen onchain. diff --git a/polkadot/node/core/provisioner/src/lib.rs b/polkadot/node/core/provisioner/src/lib.rs index 51f768d782e0b..7af075914ab22 100644 --- a/polkadot/node/core/provisioner/src/lib.rs +++ b/polkadot/node/core/provisioner/src/lib.rs @@ -500,7 +500,7 @@ fn select_availability_bitfields( 'a: for bitfield in bitfields.iter().cloned() { if bitfield.payload().0.len() != cores.len() { gum::debug!(target: LOG_TARGET, ?leaf_hash, "dropping bitfield due to length mismatch"); - continue + continue; } let is_better = selected @@ -514,7 +514,7 @@ fn select_availability_bitfields( ?leaf_hash, "dropping bitfield due to duplication - the better one is kept" ); - continue + continue; } for (idx, _) in cores.iter().enumerate().filter(|v| !v.1.is_occupied()) { @@ -526,7 +526,7 @@ fn select_availability_bitfields( ?leaf_hash, "dropping invalid bitfield - bit is set for an unoccupied core" ); - continue 'a + continue 'a; } } @@ -575,16 +575,16 @@ async fn select_candidate_hashes_from_tracked( if let Some(ref scheduled_core) = occupied_core.next_up_on_available { (scheduled_core, OccupiedCoreAssumption::Included) } else { - continue + continue; } } else { if occupied_core.time_out_at != block_number { - continue + continue; } if let Some(ref scheduled_core) = occupied_core.next_up_on_time_out { (scheduled_core, OccupiedCoreAssumption::TimedOut) } else { - continue + continue; } } }, @@ -664,17 +664,17 @@ async fn request_backable_candidates( // https://github.com/paritytech/polkadot/issues/5492 (scheduled_core.para_id, vec![occupied_core.candidate_hash]) } else { - continue + continue; } } else { if occupied_core.time_out_at != block_number { - continue + continue; } if let Some(ref scheduled_core) = occupied_core.next_up_on_time_out { // Candidate's availability timed out, practically same as scheduled. (scheduled_core.para_id, Vec::new()) } else { - continue + continue; } } }, @@ -760,7 +760,7 @@ async fn select_candidates( candidates.retain(|c| { if c.candidate.commitments.new_validation_code.is_some() { if with_validation_code { - return false + return false; } with_validation_code = true; @@ -851,7 +851,7 @@ fn bitfields_indicate_availability( availability_len, ); - return false + return false; }, Some(mut bit_mut) => *bit_mut |= bitfield.payload().0[core_idx], } diff --git a/polkadot/node/core/provisioner/src/tests.rs b/polkadot/node/core/provisioner/src/tests.rs index b26df8ddb9104..4d0f8960196a9 100644 --- a/polkadot/node/core/provisioner/src/tests.rs +++ b/polkadot/node/core/provisioner/src/tests.rs @@ -382,8 +382,9 @@ mod select_candidates { let _ = tx.send(candidates_iter.next().map_or_else(Vec::new, |c| vec![c])); }, - ProspectiveParachainsMode::Disabled => - panic!("unexpected prospective parachains request"), + ProspectiveParachainsMode::Disabled => { + panic!("unexpected prospective parachains request") + }, } }, _ => panic!("Unexpected message: {:?}", from_job), diff --git a/polkadot/node/core/pvf-checker/src/lib.rs b/polkadot/node/core/pvf-checker/src/lib.rs index ae0fae6b4f9f7..08de49cc2918c 100644 --- a/polkadot/node/core/pvf-checker/src/lib.rs +++ b/polkadot/node/core/pvf-checker/src/lib.rs @@ -208,7 +208,7 @@ async fn handle_pvf_check( ?validation_code_hash, "received judgement for an unknown (or removed) PVF hash", ); - return + return; }, } @@ -276,7 +276,7 @@ async fn handle_leaves_update( { None => { // None indicates that the pre-checking runtime API is not supported. - return + return; }, Some(e) => e, }; @@ -418,7 +418,7 @@ async fn check_signing_credentials( "error occured during requesting validators: {:?}", e ); - return None + return None; }, }; @@ -459,7 +459,7 @@ async fn sign_and_submit_pvf_check_statement( "already voted for this validation code", ); metrics.on_vote_duplicate(); - return + return; } voted.insert(validation_code_hash); @@ -484,7 +484,7 @@ async fn sign_and_submit_pvf_check_statement( ?validation_code_hash, "private key for signing is not available", ); - return + return; }, Err(e) => { gum::warn!( @@ -495,7 +495,7 @@ async fn sign_and_submit_pvf_check_statement( "error signing the statement: {:?}", e, ); - return + return; }, }; diff --git a/polkadot/node/core/pvf/common/src/worker/mod.rs b/polkadot/node/core/pvf/common/src/worker/mod.rs index d7c95d9e7047f..7cfdce7e86339 100644 --- a/polkadot/node/core/pvf/common/src/worker/mod.rs +++ b/polkadot/node/core/pvf/common/src/worker/mod.rs @@ -63,22 +63,22 @@ macro_rules! decl_worker_main { let args = std::env::args().collect::>(); if args.len() == 1 { print_help($expected_command); - return + return; } match args[1].as_ref() { "--help" | "-h" => { print_help($expected_command); - return + return; }, "--version" | "-v" => { println!("{}", $worker_version); - return + return; }, // Useful for debugging. --version is used for version checks. "--full-version" => { println!("{}", get_full_version()); - return + return; }, "--check-can-enable-landlock" => { @@ -142,7 +142,7 @@ macro_rules! decl_worker_main { "test-sleep" => { std::thread::sleep(std::time::Duration::from_secs(5)); - return + return; }, subcommand => { @@ -198,7 +198,7 @@ pub fn pipe2_cloexec() -> io::Result<(libc::c_int, libc::c_int)> { let mut fds: [libc::c_int; 2] = [0; 2]; let res = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }; if res != 0 { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } Ok((fds[0], fds[1])) } @@ -208,15 +208,15 @@ pub fn pipe2_cloexec() -> io::Result<(libc::c_int, libc::c_int)> { let mut fds: [libc::c_int; 2] = [0; 2]; let res = unsafe { libc::pipe(fds.as_mut_ptr()) }; if res != 0 { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } let res = unsafe { libc::fcntl(fds[0], libc::F_SETFD, libc::FD_CLOEXEC) }; if res != 0 { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } let res = unsafe { libc::fcntl(fds[1], libc::F_SETFD, libc::FD_CLOEXEC) }; if res != 0 { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } Ok((fds[0], fds[1])) } @@ -349,8 +349,9 @@ pub fn run_worker( let entries: io::Result> = std::fs::read_dir(&worker_info.worker_dir_path) .and_then(|d| d.map(|res| res.map(|e| e.file_name())).collect()); match entries { - Ok(entries) => - gum::trace!(target: LOG_TARGET, ?worker_info, "content of worker dir: {:?}", entries), + Ok(entries) => { + gum::trace!(target: LOG_TARGET, ?worker_info, "content of worker dir: {:?}", entries) + }, Err(err) => { let err = format!("Could not read worker dir: {}", err.to_string()); worker_shutdown_error(worker_info, &err); @@ -501,7 +502,7 @@ pub fn cpu_time_monitor_loop( } } - return Some(cpu_time_elapsed) + return Some(cpu_time_elapsed); } } @@ -645,7 +646,7 @@ pub mod thread { let mut flag = lock.lock().unwrap(); if !flag.is_pending() { // Someone else already triggered the condvar. - return + return; } *flag = outcome; cvar.notify_all(); diff --git a/polkadot/node/core/pvf/common/src/worker/security/change_root.rs b/polkadot/node/core/pvf/common/src/worker/security/change_root.rs index 9ec66906819f1..d8cd449bdc273 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/change_root.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/change_root.rs @@ -92,7 +92,7 @@ fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { unsafe { // 1. `unshare` the user and the mount namespaces. if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) < 0 { - return Err("unshare user and mount namespaces") + return Err("unshare user and mount namespaces"); } // 2. Setup mounts. @@ -108,7 +108,7 @@ fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { ptr::null(), ) < 0 { - return Err("mount MS_PRIVATE") + return Err("mount MS_PRIVATE"); } // Ensure that the new root is a mount point. let additional_flags = @@ -128,18 +128,18 @@ fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { ptr::null(), // ignored when MS_BIND is used ) < 0 { - return Err("mount MS_BIND") + return Err("mount MS_BIND"); } // 3. `pivot_root` to the artifact directory. if libc::chdir(worker_dir_path_c.as_ptr()) < 0 { - return Err("chdir to worker dir path") + return Err("chdir to worker dir path"); } if libc::syscall(libc::SYS_pivot_root, cstr_ptr!("."), cstr_ptr!(".")) < 0 { - return Err("pivot_root") + return Err("pivot_root"); } if libc::umount2(cstr_ptr!("."), libc::MNT_DETACH) < 0 { - return Err("umount the old root mount point") + return Err("umount the old root mount point"); } } @@ -152,13 +152,15 @@ fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { // Do some assertions. if env::current_dir()? != Path::new("/") { - return Err(Error::AssertionFailed("expected current dir after pivot_root to be `/`".into())) + return Err(Error::AssertionFailed( + "expected current dir after pivot_root to be `/`".into(), + )); } env::set_current_dir("..")?; if env::current_dir()? != Path::new("/") { return Err(Error::AssertionFailed( "expected not to be able to break out of new root by doing `..`".into(), - )) + )); } Ok(()) diff --git a/polkadot/node/core/pvf/common/src/worker/security/landlock.rs b/polkadot/node/core/pvf/common/src/worker/security/landlock.rs index 10d00a0e2c66c..054f8e27d1907 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/landlock.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/landlock.rs @@ -95,8 +95,9 @@ pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { WorkerKind::Execute => { vec![(worker_info.worker_dir_path.to_owned(), AccessFs::ReadFile.into())] }, - WorkerKind::CheckPivotRoot => - panic!("this should only be passed for checking pivot_root; qed"), + WorkerKind::CheckPivotRoot => { + panic!("this should only be passed for checking pivot_root; qed") + }, }; gum::trace!( @@ -144,14 +145,14 @@ where let mut rules = path_beneath_rules(paths, access_bits).peekable(); if rules.peek().is_none() { // `path_beneath_rules` silently ignores missing paths, so check for it manually. - return Err(Error::InvalidExceptionPath(fs_path.as_ref().to_owned())) + return Err(Error::InvalidExceptionPath(fs_path.as_ref().to_owned())); } ruleset = ruleset.add_rules(rules)?; } let status = ruleset.restrict_self()?; if !matches!(status.ruleset, RulesetStatus::FullyEnforced) { - return Err(Error::NotFullyEnabled(status.ruleset)) + return Err(Error::NotFullyEnabled(status.ruleset)); } Ok(()) @@ -166,7 +167,7 @@ mod tests { fn restricted_thread_cannot_read_file() { // TODO: This would be nice: . if check_can_fully_enable().is_err() { - return + return; } // Restricted thread cannot read from FS. @@ -231,7 +232,7 @@ mod tests { fn restricted_thread_cannot_write_file() { // TODO: This would be nice: . if check_can_fully_enable().is_err() { - return + return; } // Restricted thread cannot write to FS. @@ -290,7 +291,7 @@ mod tests { fn restricted_thread_can_truncate_file() { // TODO: This would be nice: . if check_can_fully_enable().is_err() { - return + return; } // Restricted thread can truncate file. diff --git a/polkadot/node/core/pvf/common/src/worker/security/mod.rs b/polkadot/node/core/pvf/common/src/worker/security/mod.rs index 72d47235d47a4..16e2634dc3389 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/mod.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/mod.rs @@ -54,12 +54,12 @@ pub fn check_env_vars_were_cleared(worker_info: &WorkerInfo) -> bool { // randomness for malicious code. It should be removed in the job process, which does no // logging. if key == "RUST_LOG" { - continue + continue; } // An exception for MacOS. This is not a secure platform anyway, so we let it slide. #[cfg(target_os = "macos")] if key == "__CF_USER_TEXT_ENCODING" { - continue + continue; } gum::error!( diff --git a/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs b/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs index f6100d236c8bd..780f845fe9817 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs @@ -162,7 +162,7 @@ mod tests { fn sandboxed_thread_cannot_use_sockets() { // TODO: This would be nice: . if check_can_fully_enable().is_err() { - return + return; } let handle = thread::spawn(|| { diff --git a/polkadot/node/core/pvf/execute-worker/src/lib.rs b/polkadot/node/core/pvf/execute-worker/src/lib.rs index 0cfa5a786946c..eb26006e44a25 100644 --- a/polkadot/node/core/pvf/execute-worker/src/lib.rs +++ b/polkadot/node/core/pvf/execute-worker/src/lib.rs @@ -148,7 +148,7 @@ pub fn worker_entrypoint( InternalValidationError::CouldNotOpenFile(err.to_string()), ); send_response(&mut stream, response)?; - continue + continue; }, }; @@ -159,7 +159,7 @@ pub fn worker_entrypoint( Err(errno) => { let response = internal_error_from_errno("getrusage before", errno); send_response(&mut stream, response)?; - continue + continue; }, }; let stream_fd = stream.as_raw_fd(); @@ -419,8 +419,9 @@ fn handle_child_process( )), Err(e) => Err(JobError::CpuTimeMonitorThread(stringify_panic_payload(e))), }, - WaitOutcome::Pending => - unreachable!("we run wait_while until the outcome is no longer pending; qed"), + WaitOutcome::Pending => { + unreachable!("we run wait_while until the outcome is no longer pending; qed") + }, }; send_child_response(&mut pipe_write, response); @@ -526,7 +527,7 @@ fn handle_parent_process( cpu_tv.as_millis(), timeout.as_millis(), ); - return Ok(WorkerResponse::JobTimedOut) + return Ok(WorkerResponse::JobTimedOut); } match status { @@ -544,7 +545,7 @@ fn handle_parent_process( return Ok(WorkerResponse::JobError(format!( "unexpected exit status: {}", exit_status - ))) + ))); } Ok(WorkerResponse::Ok { result_descriptor, duration: cpu_tv }) @@ -600,7 +601,7 @@ fn get_total_cpu_usage(rusage: Usage) -> Duration { let micros = (((rusage.user_time().tv_sec() + rusage.system_time().tv_sec()) * 1_000_000) + (rusage.system_time().tv_usec() + rusage.user_time().tv_usec()) as i64) as u64; - return Duration::from_micros(micros) + return Duration::from_micros(micros); } /// Get a job response. diff --git a/polkadot/node/core/pvf/prepare-worker/src/lib.rs b/polkadot/node/core/pvf/prepare-worker/src/lib.rs index 82a56107ef535..51878f7f01be0 100644 --- a/polkadot/node/core/pvf/prepare-worker/src/lib.rs +++ b/polkadot/node/core/pvf/prepare-worker/src/lib.rs @@ -235,7 +235,7 @@ pub fn worker_entrypoint( Err(errno) => { let result = Err(error_from_errno("getrusage before", errno)); send_response(&mut stream, result)?; - continue + continue; }, }; @@ -592,8 +592,9 @@ fn handle_child_process( Ok(None) => Err(PrepareError::IoErr("error communicating over closed channel".into())), Err(err) => Err(PrepareError::IoErr(stringify_panic_payload(err))), }, - WaitOutcome::Pending => - unreachable!("we run wait_while until the outcome is no longer pending; qed"), + WaitOutcome::Pending => { + unreachable!("we run wait_while until the outcome is no longer pending; qed") + }, }; send_child_response(&mut pipe_write, result); @@ -660,7 +661,7 @@ fn handle_parent_process( cpu_tv.as_millis(), timeout.as_millis(), ); - return Err(PrepareError::TimedOut) + return Err(PrepareError::TimedOut); } match status { @@ -677,7 +678,7 @@ fn handle_parent_process( return Err(PrepareError::JobError(format!( "unexpected exit status: {}", exit_status - ))) + ))); } // Write the serialized artifact into a temp file. @@ -696,7 +697,7 @@ fn handle_parent_process( ); // Write to the temp file created by the host. if let Err(err) = fs::write(temp_artifact_dest, &artifact) { - return Err(PrepareError::IoErr(err.to_string())) + return Err(PrepareError::IoErr(err.to_string())); }; let checksum = blake3::hash(&artifact.as_ref()).to_hex().to_string(); @@ -741,7 +742,7 @@ fn get_total_cpu_usage(rusage: Usage) -> Duration { let micros = (((rusage.user_time().tv_sec() + rusage.system_time().tv_sec()) * 1_000_000) + (rusage.system_time().tv_usec() + rusage.user_time().tv_usec()) as i64) as u64; - return Duration::from_micros(micros) + return Duration::from_micros(micros); } /// Get a job response. diff --git a/polkadot/node/core/pvf/prepare-worker/src/memory_stats.rs b/polkadot/node/core/pvf/prepare-worker/src/memory_stats.rs index 5f577b0901c25..b1cfd8e472c78 100644 --- a/polkadot/node/core/pvf/prepare-worker/src/memory_stats.rs +++ b/polkadot/node/core/pvf/prepare-worker/src/memory_stats.rs @@ -114,7 +114,7 @@ pub mod memory_tracker { match thread::wait_for_threads_with_timeout(&condvar, POLL_INTERVAL) { Some(_outcome) => { update_stats()?; - return Ok(max_stats) + return Ok(max_stats); }, None => continue, } @@ -166,7 +166,7 @@ pub mod max_rss_stat { // SAFETY: `result` is a valid pointer, so calling this is safe. if unsafe { getrusage(RUSAGE_THREAD, result.as_mut_ptr()) } == -1 { - return Err(io::Error::last_os_error()) + return Err(io::Error::last_os_error()); } // SAFETY: `result` was successfully initialized by `getrusage`. diff --git a/polkadot/node/core/pvf/src/execute/queue.rs b/polkadot/node/core/pvf/src/execute/queue.rs index aa91d11781fc6..e46e51cdfa3de 100644 --- a/polkadot/node/core/pvf/src/execute/queue.rs +++ b/polkadot/node/core/pvf/src/execute/queue.rs @@ -221,7 +221,7 @@ impl Queue { for (i, job) in self.queue.iter().enumerate() { if worker_data.executor_params_hash == job.executor_params.hash() { (worker, job_index) = (Some(finished_worker), i); - break + break; } } } @@ -245,7 +245,7 @@ impl Queue { if worker.is_none() && !self.workers.can_afford_one_more() { // Bad luck, no worker slot can be used to execute the job - return + return; } let job = self.queue.remove(job_index).expect("Job is just checked to be in queue; qed"); @@ -400,7 +400,7 @@ fn handle_job_finish( if let Some(idle_worker) = idle_worker { if let Some(data) = queue.workers.running.get_mut(worker) { data.idle = Some(idle_worker); - return queue.try_assign_next_job(Some(worker)) + return queue.try_assign_next_job(Some(worker)); } } else { // Note it's possible that the worker was purged already by `purge_dead` diff --git a/polkadot/node/core/pvf/src/execute/worker_interface.rs b/polkadot/node/core/pvf/src/execute/worker_interface.rs index 9f7738f00e699..1b6a7b764df09 100644 --- a/polkadot/node/core/pvf/src/execute/worker_interface.rs +++ b/polkadot/node/core/pvf/src/execute/worker_interface.rs @@ -140,7 +140,7 @@ pub async fn start_work( ?error, "failed to send an execute request", ); - return Outcome::WorkerIntfErr + return Outcome::WorkerIntfErr; } // We use a generous timeout here. This is in addition to the one in the child process, in @@ -224,7 +224,7 @@ async fn handle_response( ); // Return a timeout error. - return WorkerResponse::JobTimedOut + return WorkerResponse::JobTimedOut; } } @@ -260,7 +260,7 @@ where ); return Outcome::InternalError { err: InternalValidationError::CouldNotCreateLink(format!("{:?}", err)), - } + }; } let worker_dir_path = worker_dir.path().to_owned(); @@ -280,7 +280,7 @@ where err: format!("{:?}", err), path: worker_dir_path.to_str().map(String::from), }, - } + }; } outcome diff --git a/polkadot/node/core/pvf/src/host.rs b/polkadot/node/core/pvf/src/host.rs index ae9fdc7d2dea8..1dbd7ab280890 100644 --- a/polkadot/node/core/pvf/src/host.rs +++ b/polkadot/node/core/pvf/src/host.rs @@ -716,7 +716,7 @@ async fn handle_prepare_done( // thus the artifact cannot be unknown, only preparing; // qed. never!("an unknown artifact was prepared: {:?}", artifact_id); - return Ok(()) + return Ok(()); }, Some(ArtifactState::Prepared { .. }) => { // before sending request to prepare, the artifact is inserted with `preparing` state; @@ -725,13 +725,13 @@ async fn handle_prepare_done( // thus the artifact cannot be prepared, only preparing; // qed. never!("the artifact is already prepared: {:?}", artifact_id); - return Ok(()) + return Ok(()); }, Some(ArtifactState::FailedToProcess { .. }) => { // The reasoning is similar to the above, the artifact cannot be // processed at this point. never!("the artifact is already processed unsuccessfully: {:?}", artifact_id); - return Ok(()) + return Ok(()); }, Some(state @ ArtifactState::Preparing { .. }) => state, }; @@ -746,7 +746,7 @@ async fn handle_prepare_done( num_failures } else { never!("The reasoning is similar to the above, the artifact can only be preparing at this point; qed"); - return Ok(()) + return Ok(()); }; // It's finally time to dispatch all the execution requests that were waiting for this artifact @@ -758,14 +758,14 @@ async fn handle_prepare_done( if result_tx.is_canceled() { // Preparation could've taken quite a bit of time and the requester may be not // interested in execution anymore, in which case we just skip the request. - continue + continue; } let path = match &result { Ok(success) => success.path.clone(), Err(error) => { let _ = result_tx.send(Err(ValidationError::from(error.clone()))); - continue + continue; }, }; @@ -887,7 +887,7 @@ fn can_retry_prepare_after_failure( ) -> bool { if error.is_deterministic() { // This error is considered deterministic, so it will probably be reproducible. Don't retry. - return false + return false; } // Retry if the retry cooldown has elapsed and if we have already retried less than @@ -1103,7 +1103,7 @@ pub(crate) mod tests { } if let Poll::Ready(r) = futures::poll!(&mut *fut) { - break r + break r; } if futures::poll!(&mut *task).is_ready() { diff --git a/polkadot/node/core/pvf/src/prepare/pool.rs b/polkadot/node/core/pvf/src/prepare/pool.rs index 4e11f977c9e7d..d322ba002622c 100644 --- a/polkadot/node/core/pvf/src/prepare/pool.rs +++ b/polkadot/node/core/pvf/src/prepare/pool.rs @@ -190,7 +190,7 @@ async fn purge_dead( // The idle token is missing, meaning this worker is now occupied: skip it. This is // because the worker process is observed by the work task and should it reach the // deadline or be terminated it will be handled by the corresponding mux event. - continue + continue; } if let Poll::Ready(()) = futures::poll!(&mut data.handle) { @@ -474,7 +474,7 @@ fn handle_concluded_no_rip( None => { // Perhaps the worker was killed meanwhile and the result is no longer relevant. We // already send `Rip` when purging if we detect that the worker is dead. - return Ok(()) + return Ok(()); }, Some(data) => data, }; diff --git a/polkadot/node/core/pvf/src/prepare/queue.rs b/polkadot/node/core/pvf/src/prepare/queue.rs index c7bfa2f3b21ba..dcef0fb706d91 100644 --- a/polkadot/node/core/pvf/src/prepare/queue.rs +++ b/polkadot/node/core/pvf/src/prepare/queue.rs @@ -191,7 +191,7 @@ impl Queue { macro_rules! break_if_fatal { ($expr:expr) => { if let Err(Fatal) = $expr { - break + break; } }; } @@ -245,7 +245,7 @@ async fn handle_enqueue( "duplicate `enqueue` command received for {:?}", artifact_id, ); - return Ok(()) + return Ok(()); } let job = queue.jobs.insert(JobData { priority, pvf, worker: None }); @@ -306,7 +306,7 @@ async fn handle_worker_concluded( // Assume the conditions holds, then this never is not hit; // qed. never!("never_none, {}", stringify!($expr)); - return Ok(()) + return Ok(()); }, } }; @@ -514,7 +514,7 @@ mod tests { } if let Poll::Ready(r) = futures::poll!(&mut *fut) { - break r + break r; } if futures::poll!(&mut *task).is_ready() { diff --git a/polkadot/node/core/pvf/src/prepare/worker_interface.rs b/polkadot/node/core/pvf/src/prepare/worker_interface.rs index d64ee1510cad7..953f3316b9f6d 100644 --- a/polkadot/node/core/pvf/src/prepare/worker_interface.rs +++ b/polkadot/node/core/pvf/src/prepare/worker_interface.rs @@ -141,7 +141,7 @@ pub async fn start_work( "failed to send a prepare request: {:?}", err, ); - return Outcome::Unreachable + return Outcome::Unreachable; } // Wait for the result from the worker, keeping in mind that there may be a timeout, the @@ -231,7 +231,7 @@ async fn handle_response( preparation_timeout.as_millis(), tmp_file.display(), ); - return Outcome::TimedOut + return Outcome::TimedOut; } // The file name should uniquely identify the artifact even across restarts. In case the cache @@ -311,7 +311,7 @@ where return Outcome::CreateTmpFileErr { worker: IdleWorker { stream, pid, worker_dir }, err: format!("{:?}", err), - } + }; }; let worker_dir_path = worker_dir.path().to_owned(); @@ -326,7 +326,7 @@ where "failed to clear worker cache after the job: {:?}", err, ); - return Outcome::ClearWorkerDir { err: format!("{:?}", err) } + return Outcome::ClearWorkerDir { err: format!("{:?}", err) }; } outcome diff --git a/polkadot/node/core/pvf/src/security.rs b/polkadot/node/core/pvf/src/security.rs index 733ef18bcadb4..1ffaa9b18ad0b 100644 --- a/polkadot/node/core/pvf/src/security.rs +++ b/polkadot/node/core/pvf/src/security.rs @@ -51,7 +51,7 @@ pub async fn check_security_status(config: &Config) -> Result()?; @@ -233,7 +233,7 @@ impl Parse for FmtGroup { }; if !input.is_empty() { - return Err(syn::Error::new(input.span(), "Unexpected data, expected closing `)`.")) + return Err(syn::Error::new(input.span(), "Unexpected data, expected closing `)`.")); } Ok(Self { format_str, maybe_comma, rest }) @@ -319,12 +319,12 @@ impl Parse for Args { if input.fork().parse::().is_ok() { values.push_value(input.parse::()?); } else { - break + break; } if input.peek(Token![,]) { values.push_punct(input.parse::()?); } else { - break + break; } } diff --git a/polkadot/node/gum/src/lib.rs b/polkadot/node/gum/src/lib.rs index dad5887af2243..78b8d08d4cca5 100644 --- a/polkadot/node/gum/src/lib.rs +++ b/polkadot/node/gum/src/lib.rs @@ -169,7 +169,7 @@ impl Freq { // Two attempts is not enough to call something as frequent. if self.ema.count < 3 { - return false + return false; } let rate = 1000.0 / self.ema.current; // Current EMA represents interval in ms diff --git a/polkadot/node/malus/src/variants/common.rs b/polkadot/node/malus/src/variants/common.rs index 011fcc80e3733..f9394151c56b3 100644 --- a/polkadot/node/malus/src/variants/common.rs +++ b/polkadot/node/malus/src/variants/common.rs @@ -298,7 +298,7 @@ where exec_kind, response_sender, }, - }) + }); } // Create the fake response with probability `p` if the `PoV` is malicious, // where 'p' defaults to 100% for suggest-garbage-candidate variant. @@ -418,7 +418,7 @@ where exec_kind, response_sender, }, - }) + }); } // If the `PoV` is malicious, back the candidate with some probability `p`, // where 'p' defaults to 100% for suggest-garbage-candidate variant. diff --git a/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs b/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs index b3555ba2f5beb..881a681c2713e 100644 --- a/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs +++ b/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs @@ -89,7 +89,7 @@ where return Some(FromOrchestra::Signal(OverseerSignal::BlockFinalized( finalized_hash, finalized_height, - ))) + ))); } let dispute_offset = self.dispute_offset; @@ -119,7 +119,7 @@ where target: MALUS, "😈 Seems the target is not yet finalized! Nothing to dispute." ); - return // Early return from the async block + return; // Early return from the async block }, }; @@ -133,14 +133,14 @@ where target: MALUS, "😈 Failed to fetch candidate events: {:?}", e ); - return // Early return from the async block + return; // Early return from the async block }, Err(e) => { gum::error!( target: MALUS, "😈 Failed to fetch candidate events: {:?}", e ); - return // Early return from the async block + return; // Early return from the async block }, }; @@ -156,7 +156,7 @@ where target: MALUS, "😈 No candidate included event found! Nothing to dispute." ); - return // Early return from the async block + return; // Early return from the async block }, }; @@ -178,7 +178,7 @@ where target: MALUS, "😈 Failed to fetch session index for candidate." ); - return // Early return from the async block + return; // Early return from the async block }, }; gum::info!( diff --git a/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs b/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs index 22b44ddd1dc35..0d38ecabdb4f7 100644 --- a/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs +++ b/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs @@ -151,7 +151,7 @@ where ); sender.send(None).expect("channel is still open"); - return + return; }, Ok(None) => { gum::debug!( @@ -161,7 +161,7 @@ where ); sender.send(None).expect("channel is still open"); - return + return; }, Ok(Some(c)) => c, } diff --git a/polkadot/node/metrics/src/metronome.rs b/polkadot/node/metrics/src/metronome.rs index a379062c9cb1f..6a07cb3f27964 100644 --- a/polkadot/node/metrics/src/metronome.rs +++ b/polkadot/node/metrics/src/metronome.rs @@ -55,10 +55,10 @@ impl futures::Stream for Metronome { }, MetronomeState::Snooze => { if !Pin::new(&mut self.delay).poll(cx).is_ready() { - break + break; } self.state = MetronomeState::SetAlarm; - return Poll::Ready(Some(())) + return Poll::Ready(Some(())); }, } } diff --git a/polkadot/node/metrics/src/runtime/mod.rs b/polkadot/node/metrics/src/runtime/mod.rs index 7cd24b01c117f..8bf6511ed6481 100644 --- a/polkadot/node/metrics/src/runtime/mod.rs +++ b/polkadot/node/metrics/src/runtime/mod.rs @@ -79,7 +79,7 @@ impl RuntimeMetricsProvider { hashmap .entry(counter.name.to_owned()) .or_insert(register(Counter::new(counter.name, counter.description)?, &self.0)?); - return Ok(()) + return Ok(()); }) } @@ -92,7 +92,7 @@ impl RuntimeMetricsProvider { )?, &self.0, )?); - return Ok(()) + return Ok(()); }) } @@ -159,7 +159,7 @@ impl sc_tracing::TraceHandler for RuntimeMetricsProvider { .unwrap_or(&String::default()) .ne("metrics") { - return + return; } if let Some(update_op_bs58) = event.values.string_values.get("params") { @@ -203,7 +203,7 @@ impl RuntimeMetricsProvider { const SKIP_CHARS: &'static str = " { update_op: "; if SKIP_CHARS.len() < event_params.len() { if SKIP_CHARS.eq_ignore_ascii_case(&event_params[..SKIP_CHARS.len()]) { - return bs58::decode(&event_params[SKIP_CHARS.len()..].as_bytes()).into_vec().ok() + return bs58::decode(&event_params[SKIP_CHARS.len()..].as_bytes()).into_vec().ok(); } } @@ -216,7 +216,7 @@ impl RuntimeMetricsProvider { pub fn logger_hook() -> impl FnOnce(&mut sc_cli::LoggerBuilder, &sc_service::Configuration) -> () { |logger_builder, config| { if config.prometheus_registry().is_none() { - return + return; } let registry = config.prometheus_registry().cloned().unwrap(); let metrics_provider = RuntimeMetricsProvider::new(registry); diff --git a/polkadot/node/network/approval-distribution/src/lib.rs b/polkadot/node/network/approval-distribution/src/lib.rs index f4e40270160cb..ff55599b4109e 100644 --- a/polkadot/node/network/approval-distribution/src/lib.rs +++ b/polkadot/node/network/approval-distribution/src/lib.rs @@ -197,10 +197,10 @@ impl ApprovalEntry { pub fn includes_approval_candidates(&self, approval: &IndirectSignedApprovalVoteV2) -> bool { for candidate_index in approval.candidate_indices.iter_ones() { if self.assignment_claimed_candidates.bit_at((candidate_index).as_bit_index()) { - return true + return true; } } - return false + return false; } // Records a new approval. Returns error if the claimed candidate is not found or we already @@ -214,16 +214,16 @@ impl ApprovalEntry { // - check claimed candidate // - check for duplicate approval if self.validator_index != approval.validator { - return Err(ApprovalEntryError::InvalidValidatorIndex) + return Err(ApprovalEntryError::InvalidValidatorIndex); } // We need at least one of the candidates in the approval to be in this assignment if !self.includes_approval_candidates(&approval) { - return Err(ApprovalEntryError::InvalidCandidateIndex) + return Err(ApprovalEntryError::InvalidCandidateIndex); } if self.approvals.contains_key(&approval.candidate_indices) { - return Err(ApprovalEntryError::DuplicateApproval) + return Err(ApprovalEntryError::DuplicateApproval); } self.approvals.insert(approval.candidate_indices.clone(), approval.clone()); @@ -550,7 +550,7 @@ impl BlockEntry { let mut peers_randomly_routed_to = HashSet::new(); if self.candidates.len() < approval.candidate_indices.len() as usize { - return Err(ApprovalEntryError::CandidateIndexOutOfBounds) + return Err(ApprovalEntryError::CandidateIndexOutOfBounds); } // First determine all assignments bitfields that might be covered by this approval @@ -581,7 +581,7 @@ impl BlockEntry { return Err(ApprovalEntryError::AssignmentsFollowedDifferentPaths( required_routing, approval_entry.routing_info().required_routing, - )) + )); } } else { required_routing = Some(approval_entry.routing_info().required_routing) @@ -900,7 +900,7 @@ impl State { ) { if local_index.is_none() { // this subsystem only matters to validators. - return + return; } self.topologies.insert_topology(session, topology, local_index); @@ -951,7 +951,7 @@ impl State { pending.push((peer_id, PendingMessage::Assignment(assignment, claimed_indices))); - continue + continue; } self.import_and_circulate_assignment( @@ -996,7 +996,7 @@ impl State { pending.push((peer_id, PendingMessage::Approval(approval_vote))); - continue + continue; } self.import_and_circulate_approval( @@ -1227,7 +1227,7 @@ impl State { } } metrics.on_assignment_invalid_block(); - return + return; }, }; @@ -1270,7 +1270,7 @@ impl State { "We sent the message to the peer while peer was sending it to us. Known race condition.", ); } - return + return; } }, hash_map::Entry::Vacant(_) => { @@ -1305,7 +1305,7 @@ impl State { peer_knowledge.received.insert(message_subject, message_kind); } metrics.on_assignment_good_known(); - return + return; } let (tx, rx) = oneshot::channel(); @@ -1322,7 +1322,7 @@ impl State { Ok(result) => result, Err(_) => { gum::debug!(target: LOG_TARGET, "The approval voting subsystem is down"); - return + return; }, }; drop(timer); @@ -1363,7 +1363,7 @@ impl State { ); metrics.on_assignment_duplicatevoting(); - return + return; }, AssignmentCheckResult::TooFarInFuture => { gum::debug!( @@ -1381,7 +1381,7 @@ impl State { .await; metrics.on_assignment_far(); - return + return; }, AssignmentCheckResult::Bad(error) => { gum::info!( @@ -1399,7 +1399,7 @@ impl State { ) .await; metrics.on_assignment_bad(); - return + return; }, } } else { @@ -1410,7 +1410,7 @@ impl State { ?message_subject, "Importing locally an already known assignment", ); - return + return; } else { gum::debug!( target: LOG_TARGET, @@ -1461,7 +1461,7 @@ impl State { // Filter destination peers for peer in peers_to_filter.into_iter() { if Some(peer) == source_peer { - continue + continue; } if let Some(true) = topology @@ -1469,11 +1469,11 @@ impl State { .map(|t| t.local_grid_neighbors().route_to_peer(required_routing, &peer)) { peers.push(peer); - continue + continue; } if !topology.map(|topology| topology.is_validator(&peer)).unwrap_or(false) { - continue + continue; } // Note: at this point, we haven't received the message from any peers @@ -1538,7 +1538,7 @@ impl State { ); modify_reputation(reputation, ctx.sender(), peer_id, COST_UNEXPECTED_MESSAGE).await; metrics.on_approval_unknown_assignment(); - return false + return false; } } @@ -1567,7 +1567,7 @@ impl State { .await; metrics.on_approval_duplicate(); } - return false + return false; } }, hash_map::Entry::Vacant(_) => { @@ -1649,7 +1649,7 @@ impl State { metrics.on_approval_recent_outdated(); } } - return + return; }, }; @@ -1669,7 +1669,7 @@ impl State { ) .await { - return + return; } let (tx, rx) = oneshot::channel(); @@ -1682,7 +1682,7 @@ impl State { Ok(result) => result, Err(_) => { gum::debug!(target: LOG_TARGET, "The approval voting subsystem is down"); - return + return; }, }; drop(timer); @@ -1728,7 +1728,7 @@ impl State { "Got a bad approval from peer", ); metrics.on_approval_bad(); - return + return; }, } } else { @@ -1741,7 +1741,7 @@ impl State { target: LOG_TARGET, "Importing locally an already known approval", ); - return + return; } else { gum::debug!( target: LOG_TARGET, @@ -1762,7 +1762,7 @@ impl State { "Possible bug: Vote import failed", ); metrics.on_approval_bug(); - return + return; }, }; @@ -1777,7 +1777,7 @@ impl State { let peer_filter = move |peer| { if Some(peer) == source_peer.as_ref() { - return false + return false; } // Here we're leaning on a few behaviors of assignment propagation: @@ -1844,7 +1844,7 @@ impl State { ?hash, "`get_approval_signatures`: could not find block entry for given hash!" ); - continue + continue; }, Some(e) => e, }; @@ -1903,7 +1903,7 @@ impl State { // authorithy-id mapping we have to retry sending the messages that should be sent // to it for all un-finalized blocks. if entry.known_by.contains_key(&peer_id) && !retry_known_blocks { - break + break; } let peer_knowledge = entry.known_by.entry(peer_id).or_default(); @@ -1927,7 +1927,7 @@ impl State { .map(|topology| topology.is_validator(peer_id)) .unwrap_or(false) { - return false + return false; } let route_random = @@ -1941,7 +1941,7 @@ impl State { }; if !peer_filter(&peer_id) { - continue + continue; } } @@ -2040,7 +2040,7 @@ impl State { age, "Aggression not enabled", ); - return + return; } gum::debug!(target: LOG_TARGET, min_age, max_age, "Aggression enabled",); @@ -2092,7 +2092,7 @@ impl State { lag = ?self.approval_checking_lag, "Encountered old block pending gossip topology", ); - return *required_routing + return *required_routing; } let mut new_required_routing = *required_routing; @@ -2285,7 +2285,7 @@ async fn adjust_required_routing_and_propagate - gum::warn_if_frequent!(freq: warn_freq, max_rate: gum::Times::PerHour(100), target: LOG_TARGET, error = ?jfyi, ctx), + JfyiError::Runtime(_) => { + gum::warn_if_frequent!(freq: warn_freq, max_rate: gum::Times::PerHour(100), target: LOG_TARGET, error = ?jfyi, ctx) + }, } Ok(()) }, diff --git a/polkadot/node/network/availability-distribution/src/lib.rs b/polkadot/node/network/availability-distribution/src/lib.rs index c62ce1dd981a9..0bde2e41c995c 100644 --- a/polkadot/node/network/availability-distribution/src/lib.rs +++ b/polkadot/node/network/availability-distribution/src/lib.rs @@ -130,7 +130,7 @@ impl AvailabilityDistributionSubsystem { Either::Right(from_task) => { let from_task = from_task.ok_or(FatalError::RequesterExhausted)?; ctx.send_message(from_task).await; - continue + continue; }, }; match message { diff --git a/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs b/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs index 4e23030aa4990..7268827b44204 100644 --- a/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs +++ b/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs @@ -117,11 +117,11 @@ async fn do_fetch_pov( Ok(PoVFetchingResponse::PoV(pov)) => pov, Ok(PoVFetchingResponse::NoSuchPoV) => { metrics.on_fetched_pov(NOT_FOUND); - return Err(Error::NoSuchPoV) + return Err(Error::NoSuchPoV); }, Err(err) => { metrics.on_fetched_pov(FAILED); - return Err(err) + return Err(err); }, }; if pov.hash() == pov_hash { @@ -237,7 +237,7 @@ mod tests { ProtocolName::from(""), ))) .unwrap(); - break + break; }, msg => gum::debug!(target: LOG_TARGET, msg = ?msg, "Received msg"), } diff --git a/polkadot/node/network/availability-distribution/src/requester/fetch_task/mod.rs b/polkadot/node/network/availability-distribution/src/requester/fetch_task/mod.rs index 191ee2acd973b..4d8f22a794743 100644 --- a/polkadot/node/network/availability-distribution/src/requester/fetch_task/mod.rs +++ b/polkadot/node/network/availability-distribution/src/requester/fetch_task/mod.rs @@ -156,7 +156,7 @@ impl FetchTaskConfig { // Don't run tasks for our backing group: if session_info.our_group == Some(core.group_responsible) { - return FetchTaskConfig { live_in, prepared_running: None } + return FetchTaskConfig { live_in, prepared_running: None }; } let prepared_running = RunningTask { @@ -285,11 +285,11 @@ impl RunningTask { "Node seems to be shutting down, canceling fetch task" ); self.metrics.on_fetch(FAILED); - return + return; }, Err(TaskError::PeerError) => { bad_validators.push(validator); - continue + continue; }, }; // We drop the span here, so that the span is not active while we recombine the chunk. @@ -312,7 +312,7 @@ impl RunningTask { "Validator did not have our chunk" ); bad_validators.push(validator); - continue + continue; }, }; // We drop the span so that the span is not active whilst we validate and store the @@ -326,13 +326,13 @@ impl RunningTask { // Data genuine? if !self.validate_chunk(&validator, &chunk) { bad_validators.push(validator); - continue + continue; } // Ok, let's store it and be happy: self.store_chunk(chunk).await; succeeded = true; - break + break; } span.add_int_tag("tries", count as _); if succeeded { @@ -439,13 +439,13 @@ impl RunningTask { error = ?e, "Failed to calculate chunk merkle proof", ); - return false + return false; }, }; let erasure_chunk_hash = BlakeTwo256::hash(&chunk.chunk); if anticipated_hash != erasure_chunk_hash { gum::warn!(target: LOG_TARGET, origin = ?validator, "Received chunk does not match merkle tree"); - return false + return false; } true } diff --git a/polkadot/node/network/availability-distribution/src/requester/fetch_task/tests.rs b/polkadot/node/network/availability-distribution/src/requester/fetch_task/tests.rs index a5a81082e39ad..ac47136a67396 100644 --- a/polkadot/node/network/availability-distribution/src/requester/fetch_task/tests.rs +++ b/polkadot/node/network/availability-distribution/src/requester/fetch_task/tests.rs @@ -255,7 +255,7 @@ impl TestRun { .send(response.map(|r| (r.encode(), ProtocolName::from("")))) .expect("Sending response should succeed"); } - return (valid_responses == 0) && self.valid_chunks.is_empty() + return (valid_responses == 0) && self.valid_chunks.is_empty(); }, AllMessages::AvailabilityStore(AvailabilityStoreMessage::StoreChunk { chunk, @@ -264,11 +264,11 @@ impl TestRun { }) => { assert!(self.valid_chunks.contains(&chunk.chunk)); tx.send(Ok(())).expect("Answering fetching task should work"); - return true + return true; }, _ => { gum::debug!(target: LOG_TARGET, "Unexpected message"); - return false + return false; }, } } diff --git a/polkadot/node/network/availability-distribution/src/requester/mod.rs b/polkadot/node/network/availability-distribution/src/requester/mod.rs index 97e80d696e7ef..eee7718b728df 100644 --- a/polkadot/node/network/availability-distribution/src/requester/mod.rs +++ b/polkadot/node/network/availability-distribution/src/requester/mod.rs @@ -262,7 +262,7 @@ impl Stream for Requester { Poll::Ready(Some(FromFetchTask::Message(m))) => return Poll::Ready(Some(m)), Poll::Ready(Some(FromFetchTask::Concluded(Some(bad_boys)))) => { self.session_cache.report_bad_log(bad_boys); - continue + continue; }, Poll::Ready(Some(FromFetchTask::Concluded(None))) => continue, Poll::Ready(Some(FromFetchTask::Failed(candidate_hash))) => { @@ -302,7 +302,7 @@ where Some(parent) => runtime.get_session_index_for_child(sender, *parent).await?, None => { // No first element, i.e. empty. - return Ok((0, ancestors)) + return Ok((0, ancestors)); }, }; @@ -314,7 +314,7 @@ where if session_index == head_session_index { session_ancestry_len += 1; } else { - break + break; } } diff --git a/polkadot/node/network/availability-distribution/src/requester/session_cache.rs b/polkadot/node/network/availability-distribution/src/requester/session_cache.rs index 8a48e19c2827d..47ed94e68d846 100644 --- a/polkadot/node/network/availability-distribution/src/requester/session_cache.rs +++ b/polkadot/node/network/availability-distribution/src/requester/session_cache.rs @@ -106,7 +106,7 @@ impl SessionCache { { if let Some(o_info) = self.session_info_cache.get(&session_index) { gum::trace!(target: LOG_TARGET, session_index, "Got session from lru"); - return Ok(Some(with_info(o_info))) + return Ok(Some(with_info(o_info))); } if let Some(info) = @@ -209,8 +209,8 @@ impl SessionCache { .collect(); let info = SessionInfo { validator_groups, our_index, session_index, our_group }; - return Ok(Some(info)) + return Ok(Some(info)); } - return Ok(None) + return Ok(None); } } diff --git a/polkadot/node/network/availability-distribution/src/requester/tests.rs b/polkadot/node/network/availability-distribution/src/requester/tests.rs index 2f5d900b037e3..8e73ca7d0a267 100644 --- a/polkadot/node/network/availability-distribution/src/requester/tests.rs +++ b/polkadot/node/network/availability-distribution/src/requester/tests.rs @@ -85,7 +85,7 @@ fn spawn_virtual_overseer( loop { let msg = ctx_handle.try_recv().await; if msg.is_none() { - break + break; } match msg.unwrap() { AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendRequests(..)) => {}, diff --git a/polkadot/node/network/availability-distribution/src/responder.rs b/polkadot/node/network/availability-distribution/src/responder.rs index 54b188f7f01fc..55f96fbbba8f6 100644 --- a/polkadot/node/network/availability-distribution/src/responder.rs +++ b/polkadot/node/network/availability-distribution/src/responder.rs @@ -56,7 +56,7 @@ pub async fn run_pov_receiver( error = ?fatal, "Shutting down POV receiver." ); - return + return; }, Ok(Err(jfyi)) => { gum::debug!(target: LOG_TARGET, error = ?jfyi, "Error decoding incoming PoV request."); @@ -84,7 +84,7 @@ pub async fn run_chunk_receiver( error = ?fatal, "Shutting down chunk receiver." ); - return + return; }, Ok(Err(jfyi)) => { gum::debug!( diff --git a/polkadot/node/network/availability-recovery/src/futures_undead.rs b/polkadot/node/network/availability-recovery/src/futures_undead.rs index 04ef3e749399f..90ecd268110d8 100644 --- a/polkadot/node/network/availability-recovery/src/futures_undead.rs +++ b/polkadot/node/network/availability-recovery/src/futures_undead.rs @@ -116,7 +116,7 @@ impl Stream for FuturesUndead { // Cleanup in case we became completely empty: if self.inner.len() == 0 { *self = Self::new(); - return Poll::Ready(Some(v)) + return Poll::Ready(Some(v)); } let first_live = match self.first_live { diff --git a/polkadot/node/network/availability-recovery/src/lib.rs b/polkadot/node/network/availability-recovery/src/lib.rs index fb8064878f4f6..4e8b662128e74 100644 --- a/polkadot/node/network/availability-recovery/src/lib.rs +++ b/polkadot/node/network/availability-recovery/src/lib.rs @@ -153,7 +153,7 @@ fn is_chunk_valid(params: &RecoveryParams, chunk: &ErasureChunk) -> bool { error = ?e, "Invalid Merkle proof", ); - return false + return false; }, }; let erasure_chunk_hash = BlakeTwo256::hash(&chunk.chunk); @@ -164,7 +164,7 @@ fn is_chunk_valid(params: &RecoveryParams, chunk: &ErasureChunk) -> bool { validator_index = ?chunk.index, "Merkle proof mismatch" ); - return false + return false; } true } @@ -200,7 +200,7 @@ fn reconstructed_data_matches_root( err = ?e, "Failed to obtain chunks", ); - return false + return false; }, }; @@ -245,7 +245,7 @@ impl Future for RecoveryHandle { "All receivers for available data dropped.", ); - return Poll::Ready(None) + return Poll::Ready(None); } let remote = &mut self.remote; @@ -421,14 +421,14 @@ async fn handle_recover( "Error responding with an availability recovery result", ); } - return Ok(()) + return Ok(()); } if let Some(i) = state.ongoing_recoveries.iter_mut().find(|i| i.candidate_hash == candidate_hash) { i.awaiting.push(response_sender); - return Ok(()) + return Ok(()); } let _span = span.child("not-cached"); @@ -851,7 +851,7 @@ async fn erasure_task_thread( target: LOG_TARGET, "Erasure task channel closed. Node shutting down ?", ); - break + break; }, } diff --git a/polkadot/node/network/availability-recovery/src/task.rs b/polkadot/node/network/availability-recovery/src/task.rs index c300c221da5c6..51e0977a6e00c 100644 --- a/polkadot/node/network/availability-recovery/src/task.rs +++ b/polkadot/node/network/availability-recovery/src/task.rs @@ -223,7 +223,7 @@ impl State { } })); } else { - break + break; } } @@ -337,7 +337,7 @@ impl State { threshold = ?params.threshold, "Can conclude availability for a candidate", ); - break + break; } } @@ -397,7 +397,7 @@ where /// in-order and return whenever the first one recovers the full `AvailableData`. pub async fn run(mut self) -> Result { if let Some(data) = self.in_availability_store().await { - return Ok(data) + return Ok(data); } self.params.metrics.on_recovery_started(); @@ -423,18 +423,18 @@ where "Recovery strategy `{}` did not conclude. Trying the next one.", current_strategy.display_name(), ); - continue + continue; }, Err(err) => { match &err { RecoveryError::Invalid => self.params.metrics.on_recovery_invalid(), _ => self.params.metrics.on_recovery_failed(), } - return Err(err) + return Err(err); }, Ok(data) => { self.params.metrics.on_recovery_succeeded(data.encoded_size()); - return Ok(data) + return Ok(data); }, } } @@ -536,7 +536,7 @@ impl RecoveryStrategy "Received full data", ); - return Ok(data) + return Ok(data); }, None => { gum::debug!( @@ -758,7 +758,7 @@ impl RecoveryStrategy // Do this before requesting any chunks because we may have enough of them coming from // past RecoveryStrategies. if state.chunk_count() >= common_params.threshold { - return self.attempt_recovery(state, common_params).await + return self.attempt_recovery(state, common_params).await; } if Self::is_unavailable( @@ -778,7 +778,7 @@ impl RecoveryStrategy "Data recovery from chunks is not possible", ); - return Err(RecoveryError::Unavailable) + return Err(RecoveryError::Unavailable); } let desired_requests_count = diff --git a/polkadot/node/network/bitfield-distribution/src/lib.rs b/polkadot/node/network/bitfield-distribution/src/lib.rs index 029401e0bd514..f2153526bb43c 100644 --- a/polkadot/node/network/bitfield-distribution/src/lib.rs +++ b/polkadot/node/network/bitfield-distribution/src/lib.rs @@ -378,14 +378,14 @@ async fn handle_bitfield_distribution( "Not supposed to work on relay parent related data", ); - return + return; }; let session_idx = job_data.signing_context.session_index; let validator_set = &job_data.validator_set; if validator_set.is_empty() { gum::debug!(target: LOG_TARGET, ?relay_parent, "validator set is empty"); - return + return; } let validator_index = signed_availability.validator_index(); @@ -393,7 +393,7 @@ async fn handle_bitfield_distribution( validator.clone() } else { gum::debug!(target: LOG_TARGET, validator_index = ?validator_index.0, "Could not find a validator for index"); - return + return; }; let msg = BitfieldGossipMessage { relay_parent, signed_availability }; @@ -573,7 +573,7 @@ async fn process_incoming_peer_message( COST_NOT_IN_VIEW, ) .await; - return + return; } // Ignore anything the overseer did not tell this subsystem to work on. @@ -589,7 +589,7 @@ async fn process_incoming_peer_message( COST_NOT_IN_VIEW, ) .await; - return + return; }; let validator_index = bitfield.unchecked_validator_index(); @@ -613,7 +613,7 @@ async fn process_incoming_peer_message( COST_MISSING_PEER_SESSION_KEY, ) .await; - return + return; } // Use the (untrusted) validator index provided by the signed payload @@ -630,7 +630,7 @@ async fn process_incoming_peer_message( COST_VALIDATOR_INDEX_INVALID, ) .await; - return + return; }; // Check if the peer already sent us a message for the validator denoted in the message earlier. @@ -650,7 +650,7 @@ async fn process_incoming_peer_message( COST_PEER_DUPLICATE_MESSAGE, ) .await; - return + return; }; let one_per_validator = &mut (job_data.one_per_validator); @@ -672,7 +672,7 @@ async fn process_incoming_peer_message( ) .await; } - return + return; } let signed_availability = match bitfield.try_into_checked(&signing_context, &validator) { Err(_) => { @@ -684,7 +684,7 @@ async fn process_incoming_peer_message( COST_SIGNATURE_INVALID, ) .await; - return + return; }, Ok(bitfield) => bitfield, }; @@ -781,7 +781,7 @@ async fn handle_network_msg( None => { // For peers which are currently unknown, we'll send topology-related // messages to them when they connect and send their first view update. - continue + continue; }, }; @@ -852,7 +852,7 @@ async fn handle_peer_view_change( "Attempted to update peer view for unknown peer." ); - return + return; }, Some(pd) => pd, }; @@ -870,7 +870,7 @@ async fn handle_peer_view_change( if !lucky { gum::trace!(target: LOG_TARGET, ?origin, "Peer view change is ignored"); - return + return; } // Send all messages we've seen before and the peer is now interested @@ -911,7 +911,7 @@ async fn send_tracked_gossip_message( let job_data = if let Some(job_data) = state.per_relay_parent.get_mut(&message.relay_parent) { job_data } else { - return + return; }; let _span = job_data.span.child("gossip"); diff --git a/polkadot/node/network/bridge/src/network.rs b/polkadot/node/network/bridge/src/network.rs index 21bed019256ac..929ab8a7ebc51 100644 --- a/polkadot/node/network/bridge/src/network.rs +++ b/polkadot/node/network/bridge/src/network.rs @@ -152,7 +152,7 @@ fn send_message( M: Encode + Clone, { if peers.is_empty() { - return + return; } let message = { @@ -307,7 +307,7 @@ impl Network for Arc> { }, Ok(_) => {}, } - return + return; }, Some(peer_id) => peer_id, }; diff --git a/polkadot/node/network/bridge/src/rx/mod.rs b/polkadot/node/network/bridge/src/rx/mod.rs index 11ac73259e3a1..d2e9c84892fee 100644 --- a/polkadot/node/network/bridge/src/rx/mod.rs +++ b/polkadot/node/network/bridge/src/rx/mod.rs @@ -181,7 +181,7 @@ async fn handle_validation_message( ?peer, "Failed to determine peer role for validation protocol", ); - return + return; }, }; @@ -200,7 +200,7 @@ async fn handle_validation_message( "Unknown fallback", ); - return + return; }, Some((p2, v2)) => { if p2 != peer_set { @@ -212,7 +212,7 @@ async fn handle_validation_message( "Fallback mismatched peer-set", ); - return + return; } (p2, v2) @@ -237,7 +237,7 @@ async fn handle_validation_message( ?role, "Message sink not available for peer", ); - return + return; }, } @@ -442,7 +442,7 @@ async fn handle_collation_message( ?peer, "Failed to determine peer role for validation protocol", ); - return + return; }, }; @@ -461,7 +461,7 @@ async fn handle_collation_message( "Unknown fallback", ); - return + return; }, Some((p2, v2)) => { if p2 != peer_set { @@ -473,7 +473,7 @@ async fn handle_collation_message( "Fallback mismatched peer-set", ); - return + return; } (p2, v2) @@ -499,7 +499,7 @@ async fn handle_collation_message( role = ?role, "Message sink not available for peer", ); - return + return; }, } @@ -945,7 +945,7 @@ fn update_our_view( Some(ref v) if v.check_heads_eq(&new_view) => return, None if live_heads.is_empty() => { shared.local_view = Some(new_view); - return + return; }, _ => { shared.local_view = Some(new_view.clone()); @@ -1050,7 +1050,7 @@ fn handle_peer_messages>( let message = match WireMessage::::decode_all(&mut message.as_ref()) { Err(_) => { reports.push(MALFORMED_MESSAGE_COST); - continue + continue; }, Ok(m) => m, }; @@ -1061,12 +1061,12 @@ fn handle_peer_messages>( new_view.finalized_number < peer_data.view.finalized_number { reports.push(MALFORMED_VIEW_COST); - continue + continue; } else if new_view.is_empty() { reports.push(EMPTY_VIEW_COST); - continue + continue; } else if new_view == peer_data.view { - continue + continue; } else { peer_data.view = new_view; diff --git a/polkadot/node/network/bridge/src/rx/tests.rs b/polkadot/node/network/bridge/src/rx/tests.rs index 6847b8a7e24db..5a39911b45779 100644 --- a/polkadot/node/network/bridge/src/rx/tests.rs +++ b/polkadot/node/network/bridge/src/rx/tests.rs @@ -487,7 +487,7 @@ async fn await_peer_connections( if shared.validation_peers.len() == num_validation_peers && shared.collation_peers.len() == num_collation_peers { - break + break; } } diff --git a/polkadot/node/network/bridge/src/tx/mod.rs b/polkadot/node/network/bridge/src/tx/mod.rs index d5be6f01c3373..69e1ccd09a1eb 100644 --- a/polkadot/node/network/bridge/src/tx/mod.rs +++ b/polkadot/node/network/bridge/src/tx/mod.rs @@ -343,7 +343,7 @@ where ) .await; - return (network_service, ads) + return (network_service, ads); }, NetworkBridgeTxMessage::ConnectToResolvedValidators { validator_addrs, peer_set } => { gum::trace!( @@ -360,7 +360,7 @@ where let network_service = validator_discovery .on_resolved_request(all_addrs, peer_set, network_service) .await; - return (network_service, authority_discovery_service) + return (network_service, authority_discovery_service); }, } (network_service, authority_discovery_service) diff --git a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs index 8fb0bb2154445..2fe0e1830ca9e 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs @@ -163,9 +163,9 @@ impl ValidatorGroup { .get(candidate_hash) .map_or(true, |advertised| !advertised[validator_index]) { - return ShouldAdvertiseTo::Yes + return ShouldAdvertiseTo::Yes; } else { - return ShouldAdvertiseTo::AlreadyAdvertised + return ShouldAdvertiseTo::AlreadyAdvertised; } } @@ -362,7 +362,7 @@ async fn distribute_collation( candidate_hash = ?candidate_hash, "Candidate relay parent is out of our view", ); - return Ok(()) + return Ok(()); }, }; let relay_parent_mode = per_relay_parent.prospective_parachains_mode; @@ -380,7 +380,7 @@ async fn distribute_collation( "The limit of {} collations per relay parent is already reached", collations_limit, ); - return Ok(()) + return Ok(()); } // We have already seen collation for this relay parent. @@ -391,7 +391,7 @@ async fn distribute_collation( ?candidate_hash, "Already seen this candidate", ); - return Ok(()) + return Ok(()); } // Determine which core the para collated-on is assigned to. @@ -406,7 +406,7 @@ async fn distribute_collation( "looks like no core is assigned to {} at {}", id, candidate_relay_parent, ); - return Ok(()) + return Ok(()); }, }; @@ -424,7 +424,7 @@ async fn distribute_collation( "there are no validators assigned to core", ); - return Ok(()) + return Ok(()); } // It's important to insert new collation interests **before** @@ -519,19 +519,20 @@ async fn determine_core( for (idx, core) in cores.iter().enumerate() { let core_para_id = match core { CoreState::Scheduled(scheduled) => Some(scheduled.para_id), - CoreState::Occupied(occupied) => + CoreState::Occupied(occupied) => { if relay_parent_mode.is_enabled() { // With async backing we don't care about the core state, // it is only needed for figuring our validators group. Some(occupied.candidate_descriptor.para_id) } else { None - }, + } + }, CoreState::Free => None, }; if core_para_id == Some(para_id) { - return Ok(Some(((idx as u32).into(), cores.len()))) + return Ok(Some(((idx as u32).into(), cores.len()))); } } @@ -679,7 +680,7 @@ async fn advertise_collation( peer_id = %peer, "Skipping advertising to validator, incorrect network protocol version", ); - return + return; } } @@ -699,7 +700,7 @@ async fn advertise_collation( reason = ?should_advertise, "Not advertising collation" ); - continue + continue; }, } @@ -947,7 +948,7 @@ async fn handle_incoming_peer_message( candidate_hash = ?&statement.payload().candidate_hash(), "Seconded statement relay parent is out of our view", ); - return Ok(()) + return Ok(()); }, }; match relay_parent.collations.get(&statement.payload().candidate_hash()) { @@ -1005,7 +1006,7 @@ async fn handle_incoming_request( "received a `RequestCollation` for a relay parent out of our view", ); - return Ok(()) + return Ok(()); }, }; let mode = per_relay_parent.prospective_parachains_mode; @@ -1024,7 +1025,7 @@ async fn handle_incoming_request( "Collation request version is invalid", ); - return Ok(()) + return Ok(()); }, }; let (receipt, pov) = if let Some(collation) = collation { @@ -1037,7 +1038,7 @@ async fn handle_incoming_request( "received a `RequestCollation` for a relay parent we don't have collation stored.", ); - return Ok(()) + return Ok(()); }; state.metrics.on_collation_sent_requested(); @@ -1059,7 +1060,7 @@ async fn handle_incoming_request( COST_APPARENT_FLOOD.into(), ) .await; - return Ok(()) + return Ok(()); } if waiting.collation_fetch_active { @@ -1126,7 +1127,7 @@ async fn handle_peer_view_change( new_leaf = ?added, "New leaf in peer's view is unknown", ); - continue + continue; }, }; @@ -1177,7 +1178,7 @@ async fn handle_network_msg( ?err, "Unsupported protocol version" ); - return Ok(()) + return Ok(()); }, }; state diff --git a/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs index 1b1194c727067..b9c7d3d1c846b 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs @@ -424,7 +424,7 @@ async fn distribute_collation_with_receipt( ))) .unwrap(); // This call is mandatory - we are done: - break + break; }, other => panic!("Unexpected message received: {:?}", other), } diff --git a/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs b/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs index fd9d7a746ebe4..0753445c70355 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs @@ -91,7 +91,7 @@ async fn update_view( Some(msg) => msg, None => { // We're done. - return + return; }, }; @@ -102,7 +102,7 @@ async fn update_view( ) { // Ancestry has already been cached for this leaf. next_overseer_message.replace(msg); - break + break; } assert_matches!( diff --git a/polkadot/node/network/collator-protocol/src/collator_side/validators_buffer.rs b/polkadot/node/network/collator-protocol/src/collator_side/validators_buffer.rs index 5b88efc99d830..dd56e18727847 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/validators_buffer.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/validators_buffer.rs @@ -119,7 +119,7 @@ impl ValidatorGroupsBuffer { validators: &[AuthorityDiscoveryId], ) { if validators.is_empty() { - return + return; } match self.group_infos.iter().enumerate().find(|(_, group)| { diff --git a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs index d6f34fc81b825..5b232a7a639ba 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs @@ -201,12 +201,13 @@ impl CollationStatus { /// Downgrades to `Waiting`, but only if `self != Seconded`. fn back_to_waiting(&mut self, relay_parent_mode: ProspectiveParachainsMode) { match self { - Self::Seconded => + Self::Seconded => { if relay_parent_mode.is_enabled() { // With async backing enabled it's allowed to // second more candidates. *self = Self::Waiting - }, + } + }, _ => *self = Self::Waiting, } } @@ -258,7 +259,7 @@ impl Collations { ?finished_one, "Not proceeding to the next collation - has already been done." ); - return None + return None; } } self.status.back_to_waiting(relay_parent_mode); @@ -272,8 +273,9 @@ impl Collations { } else { self.waiting_queue.pop_front() }, - CollationStatus::WaitingOnValidation | CollationStatus::Fetching => - unreachable!("We have reset the status above!"), + CollationStatus::WaitingOnValidation | CollationStatus::Fetching => { + unreachable!("We have reset the status above!") + }, } } @@ -344,7 +346,7 @@ impl Future for CollationFetchRequest { pending_collation: self.pending_collation, }, Err(CollationFetchError::Cancelled), - )) + )); } let res = self.from_collator.poll_unpin(cx).map(|res| { diff --git a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs index 48ad3c711a6db..27473a69c36f4 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs @@ -237,13 +237,13 @@ impl PeerData { active_leaves, state.para_id, ) { - return Err(InsertAdvertisementError::OutOfOurView) + return Err(InsertAdvertisementError::OutOfOurView); } match (relay_parent_mode, candidate_hash) { (ProspectiveParachainsMode::Disabled, candidate_hash) => { if state.advertisements.contains_key(&on_relay_parent) { - return Err(InsertAdvertisementError::Duplicate) + return Err(InsertAdvertisementError::Duplicate); } state .advertisements @@ -259,14 +259,14 @@ impl PeerData { .get(&on_relay_parent) .map_or(false, |candidates| candidates.contains(&candidate_hash)) { - return Err(InsertAdvertisementError::Duplicate) + return Err(InsertAdvertisementError::Duplicate); } let candidates = state.advertisements.entry(on_relay_parent).or_default(); if candidates.len() > max_candidate_depth { - return Err(InsertAdvertisementError::PeerLimitReached) + return Err(InsertAdvertisementError::PeerLimitReached); } candidates.insert(candidate_hash); } else { @@ -279,7 +279,7 @@ impl PeerData { } if state.advertisements.contains_key(&on_relay_parent) { - return Err(InsertAdvertisementError::Duplicate) + return Err(InsertAdvertisementError::Duplicate); } state .advertisements @@ -508,7 +508,7 @@ where None => { gum::trace!(target: LOG_TARGET, ?relay_parent, "Not a validator"); - return Ok(()) + return Ok(()); }, }; @@ -687,7 +687,7 @@ async fn request_collation( peer_protocol_version: CollationVersion, ) -> std::result::Result<(), FetchError> { if state.collation_requests_cancel_handles.contains_key(&pending_collation) { - return Err(FetchError::AlreadyRequested) + return Err(FetchError::AlreadyRequested); } let PendingCollation { relay_parent, para_id, peer_id, prospective_candidate, .. } = @@ -786,7 +786,7 @@ async fn process_incoming_peer_message( COST_UNEXPECTED_MESSAGE, ) .await; - return + return; } let peer_data = match state.peer_data.get_mut(&origin) { @@ -805,7 +805,7 @@ async fn process_incoming_peer_message( COST_UNEXPECTED_MESSAGE, ) .await; - return + return; }, }; @@ -823,7 +823,7 @@ async fn process_incoming_peer_message( COST_UNEXPECTED_MESSAGE, ) .await; - return + return; } if !signature.verify(&*protocol_v1::declare_signature_payload(&origin), &collator_id) { @@ -840,7 +840,7 @@ async fn process_incoming_peer_message( COST_INVALID_SIGNATURE, ) .await; - return + return; } if state.current_assignments.contains_key(¶_id) { @@ -873,7 +873,7 @@ async fn process_incoming_peer_message( disconnect_peer(ctx.sender(), origin).await; } }, - Versioned::V1(V1::AdvertiseCollation(relay_parent)) => + Versioned::V1(V1::AdvertiseCollation(relay_parent)) => { if let Err(err) = handle_advertisement(ctx.sender(), state, relay_parent, origin, None).await { @@ -888,7 +888,8 @@ async fn process_incoming_peer_message( if let Some(rep) = err.reputation_changes() { modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await; } - }, + } + }, Versioned::V2(V2::AdvertiseCollation { relay_parent, candidate_hash, @@ -898,7 +899,7 @@ async fn process_incoming_peer_message( relay_parent, candidate_hash, parent_head_data_hash, - }) => + }) => { if let Err(err) = handle_advertisement( ctx.sender(), state, @@ -920,7 +921,8 @@ async fn process_incoming_peer_message( if let Some(rep) = err.reputation_changes() { modify_reputation(&mut state.reputation, ctx.sender(), origin, rep).await; } - }, + } + }, Versioned::V1(V1::CollationSeconded(..)) | Versioned::V2(V2::CollationSeconded(..)) | Versioned::V3(V2::CollationSeconded(..)) => { @@ -1074,7 +1076,7 @@ where if peer_data.version == CollationVersion::V1 && !state.active_leaves.contains_key(&relay_parent) { - return Err(AdvertisementError::ProtocolMisuse) + return Err(AdvertisementError::ProtocolMisuse); } let per_relay_parent = state @@ -1090,7 +1092,7 @@ where // Check if this is assigned to us. if assignment.current.map_or(true, |id| id != collator_para_id) { - return Err(AdvertisementError::InvalidAssignment) + return Err(AdvertisementError::InvalidAssignment); } // Always insert advertisements that pass all the checks for spam protection. @@ -1106,7 +1108,7 @@ where .map_err(AdvertisementError::Invalid)?; if !per_relay_parent.collations.is_seconded_limit_reached(relay_parent_mode) { - return Err(AdvertisementError::SecondedLimitReached) + return Err(AdvertisementError::SecondedLimitReached); } if let Some((candidate_hash, parent_head_data_hash)) = prospective_candidate { @@ -1142,7 +1144,7 @@ where candidate_hash, }); - return Ok(()) + return Ok(()); } } @@ -1204,7 +1206,7 @@ where ?prospective_candidate, "Candidate relay parent went out of view for valid advertisement", ); - return Ok(()) + return Ok(()); }, }; let relay_parent_mode = per_relay_parent.prospective_parachains_mode; @@ -1223,7 +1225,7 @@ where ?relay_parent, "Limit of seconded collations reached for valid advertisement", ); - return Ok(()) + return Ok(()); } let pending_collation = @@ -1423,7 +1425,7 @@ async fn handle_network_msg( ?err, "Unsupported protocol version" ); - return Ok(()) + return Ok(()); }, }; state.peer_data.entry(peer_id).or_insert_with(|| PeerData { @@ -1505,7 +1507,7 @@ async fn process_msg( relay_parent = %parent, "Seconded message received with a `Valid` statement", ); - return + return; }, }; let fetched_collation = FetchedCollation::from(&receipt.to_plain()); @@ -1573,7 +1575,7 @@ async fn process_msg( candidate = ?candidate_receipt.hash(), "Reported invalid candidate for unknown `pending_candidate`!", ); - return + return; }, Entry::Vacant(_) => return, }; @@ -1745,7 +1747,7 @@ async fn dequeue_next_collation_and_fetch( "Failed to request a collation, dequeueing next one", ); } else { - break + break; } } } @@ -1811,7 +1813,7 @@ async fn kick_off_seconding( relay_parent = ?relay_parent, "Fetched collation for a parent out of view", ); - return Ok(()) + return Ok(()); }, }; let collations = &mut per_relay_parent.collations; @@ -1844,7 +1846,7 @@ async fn kick_off_seconding( .await?, _ => { // `handle_advertisement` checks for protocol mismatch. - return Ok(()) + return Ok(()); }, } .ok_or(SecondingError::PersistedValidationDataNotFound)?; @@ -1910,7 +1912,7 @@ async fn handle_collation_fetch_response( peer_id = ?pending_collation.peer_id, "Request was cancelled from the validator side" ); - return Err(None) + return Err(None); }, Err(CollationFetchError::Request(req_error)) => Err(req_error), Ok(resp) => Ok(resp), diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs index 1ba6389212cc5..daff115aaa50d 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs @@ -1367,7 +1367,7 @@ fn delay_reputation_change() { match overseer_recv(&mut virtual_overseer).await { AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::DisconnectPeer(_, _)) => { gum::trace!("`Disconnecting inactive peer` message skipped"); - continue + continue; }, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer( ReportPeerMessage::Batch(v), @@ -1377,7 +1377,7 @@ fn delay_reputation_change() { add_reputation(&mut expected_change, peer_b, rep); } assert_eq!(v, expected_change); - break + break; }, _ => panic!("Message should be either `DisconnectPeer` or `ReportPeer`"), } diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs index 23963e65554eb..1463899f8582e 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs @@ -147,7 +147,7 @@ pub(super) async fn update_view( if !matches!(&msg, AllMessages::ChainApi(ChainApiMessage::BlockHeader(..))) { // Ancestry has already been cached for this leaf. next_overseer_message.replace(msg); - break + break; } assert_matches!( diff --git a/polkadot/node/network/dispute-distribution/src/receiver/batches/mod.rs b/polkadot/node/network/dispute-distribution/src/receiver/batches/mod.rs index 76c7683d1574a..c337cc1e01b1a 100644 --- a/polkadot/node/network/dispute-distribution/src/receiver/batches/mod.rs +++ b/polkadot/node/network/dispute-distribution/src/receiver/batches/mod.rs @@ -99,7 +99,7 @@ impl Batches { candidate_receipt: CandidateReceipt, ) -> JfyiResult { if self.batches.len() >= MAX_BATCHES { - return Err(JfyiError::MaxBatchLimitReached) + return Err(JfyiError::MaxBatchLimitReached); } debug_assert!(candidate_hash == candidate_receipt.hash()); let result = match self.batches.entry(candidate_hash) { diff --git a/polkadot/node/network/dispute-distribution/src/receiver/batches/waiting_queue.rs b/polkadot/node/network/dispute-distribution/src/receiver/batches/waiting_queue.rs index 9a5e665a57560..129a54b1896d0 100644 --- a/polkadot/node/network/dispute-distribution/src/receiver/batches/waiting_queue.rs +++ b/polkadot/node/network/dispute-distribution/src/receiver/batches/waiting_queue.rs @@ -90,7 +90,7 @@ impl WaitingQueue { let next_waiting = self.pending_wakes.peek(); let is_ready = next_waiting.map_or(false, |p| p.ready_at <= now); if is_ready { - return + return; } self.timer = next_waiting.map(|p| Delay::new(p.ready_at.duration_since(now))); diff --git a/polkadot/node/network/dispute-distribution/src/receiver/mod.rs b/polkadot/node/network/dispute-distribution/src/receiver/mod.rs index 2b3fc45983a98..1935168c64b82 100644 --- a/polkadot/node/network/dispute-distribution/src/receiver/mod.rs +++ b/polkadot/node/network/dispute-distribution/src/receiver/mod.rs @@ -187,7 +187,7 @@ where error = ?fatal, "Shutting down" ); - return + return; }, } } @@ -240,7 +240,7 @@ where poll_fn(|ctx| { // In case of Ready(None), we want to wait for pending requests: if let Poll::Ready(Some(v)) = self.pending_imports.poll_next_unpin(ctx) { - return Poll::Ready(Ok(MuxedMessage::ConfirmedImport(v?))) + return Poll::Ready(Ok(MuxedMessage::ConfirmedImport(v?))); } let rate_limited = self.peer_queues.pop_reqs(); @@ -248,13 +248,13 @@ where // We poll rate_limit before batches, so we don't unnecessarily delay importing to // batches. if let Poll::Ready(reqs) = rate_limited.poll(ctx) { - return Poll::Ready(Ok(MuxedMessage::WakePeerQueuesPopReqs(reqs))) + return Poll::Ready(Ok(MuxedMessage::WakePeerQueuesPopReqs(reqs))); } let ready_batches = self.batches.check_batches(); pin_mut!(ready_batches); if let Poll::Ready(ready_batches) = ready_batches.poll(ctx) { - return Poll::Ready(Ok(MuxedMessage::WakeCheckBatches(ready_batches))) + return Poll::Ready(Ok(MuxedMessage::WakeCheckBatches(ready_batches))); } let next_req = self.receiver.recv(|| vec![COST_INVALID_REQUEST]); @@ -263,7 +263,7 @@ where return match r { Err(e) => Poll::Ready(Err(incoming::Error::from(e).into())), Ok(v) => Poll::Ready(Ok(MuxedMessage::NewRequest(v))), - } + }; } Poll::Pending }) @@ -293,7 +293,7 @@ where sent_feedback: None, }) .map_err(|_| JfyiError::SendResponses(vec![peer]))?; - return Err(JfyiError::NotAValidator(peer).into()) + return Err(JfyiError::NotAValidator(peer).into()); }, Some(auth_id) => auth_id, }; @@ -312,7 +312,7 @@ where sent_feedback: None, }) .map_err(|_| JfyiError::SendResponses(vec![peer]))?; - return Err(JfyiError::AuthorityFlooding(authority_id)) + return Err(JfyiError::AuthorityFlooding(authority_id)); } Ok(()) } @@ -349,7 +349,7 @@ where }) .map_err(|_| JfyiError::SetPeerReputation(peer))?; - return Err(From::from(JfyiError::InvalidSignature(peer))) + return Err(From::from(JfyiError::InvalidSignature(peer))); }, Ok(votes) => votes, }; @@ -401,7 +401,7 @@ where sent_feedback: None, }) .map_err(|_| JfyiError::SendResponses(vec![peer]))?; - return Err(From::from(JfyiError::RedundantMessage(peer))) + return Err(From::from(JfyiError::RedundantMessage(peer))); } }, } @@ -426,7 +426,7 @@ where candidate_hash = ?candidate_receipt.hash(), "Not importing empty batch" ); - return + return; }, Some(vote) => (vote.0.session_index(), *vote.0.candidate_hash()), }; diff --git a/polkadot/node/network/dispute-distribution/src/receiver/peer_queues.rs b/polkadot/node/network/dispute-distribution/src/receiver/peer_queues.rs index bc58c019713b5..02c662bb8f2ff 100644 --- a/polkadot/node/network/dispute-distribution/src/receiver/peer_queues.rs +++ b/polkadot/node/network/dispute-distribution/src/receiver/peer_queues.rs @@ -71,7 +71,7 @@ impl PeerQueues { Entry::Vacant(vacant) => vacant.insert(VecDeque::new()), Entry::Occupied(occupied) => { if occupied.get().len() >= PEER_QUEUE_CAPACITY { - return Err((occupied.key().clone(), req)) + return Err((occupied.key().clone(), req)); } occupied.into_mut() }, diff --git a/polkadot/node/network/dispute-distribution/src/sender/mod.rs b/polkadot/node/network/dispute-distribution/src/sender/mod.rs index f4acc72318ad4..0a9bac92950ca 100644 --- a/polkadot/node/network/dispute-distribution/src/sender/mod.rs +++ b/polkadot/node/network/dispute-distribution/src/sender/mod.rs @@ -133,7 +133,7 @@ impl DisputeSender { match self.disputes.entry(candidate_hash) { Entry::Occupied(_) => { gum::trace!(target: LOG_TARGET, ?candidate_hash, "Dispute sending already active."); - return Ok(()) + return Ok(()); }, Entry::Vacant(vacant) => { self.rate_limit.limit("in start_sender", candidate_hash).await; @@ -174,7 +174,7 @@ impl DisputeSender { ?result, "Received `FromSendingTask::Finished` for non existing dispute." ); - return Ok(()) + return Ok(()); }, Some(task) => task, }; diff --git a/polkadot/node/network/dispute-distribution/src/sender/send_task.rs b/polkadot/node/network/dispute-distribution/src/sender/send_task.rs index 18c66066d162e..0dcc37acb282e 100644 --- a/polkadot/node/network/dispute-distribution/src/sender/send_task.rs +++ b/polkadot/node/network/dispute-distribution/src/sender/send_task.rs @@ -214,7 +214,7 @@ impl SendTask { ?result, "Received `FromSendingTask::Finished` for non existing task." ); - return + return; }, Some(status) => status, }; diff --git a/polkadot/node/network/dispute-distribution/src/tests/mock.rs b/polkadot/node/network/dispute-distribution/src/tests/mock.rs index e6a49f14c094c..64230bf5140e7 100644 --- a/polkadot/node/network/dispute-distribution/src/tests/mock.rs +++ b/polkadot/node/network/dispute-distribution/src/tests/mock.rs @@ -226,7 +226,7 @@ impl AuthorityDiscovery for MockAuthorityDiscovery { ?result, "Returning authority ids for peer id" ); - return Some(result) + return Some(result); } } diff --git a/polkadot/node/network/gossip-support/src/lib.rs b/polkadot/node/network/gossip-support/src/lib.rs index e9cb8a4de1c47..9febbecb030b0 100644 --- a/polkadot/node/network/gossip-support/src/lib.rs +++ b/polkadot/node/network/gossip-support/src/lib.rs @@ -215,7 +215,7 @@ where "Failed to get session info.", ); - continue + continue; }, }; @@ -537,7 +537,7 @@ fn ensure_i_am_an_authority( ) -> Result { for (i, v) in authorities.iter().enumerate() { if Keystore::has_keys(&**keystore, &[(v.to_raw_vec(), AuthorityDiscoveryId::ID)]) { - return Ok(i) + return Ok(i); } } Err(util::Error::NotAValidator) diff --git a/polkadot/node/network/protocol/src/grid_topology.rs b/polkadot/node/network/protocol/src/grid_topology.rs index 3c4372a27a2c4..a04ad0f5c5a63 100644 --- a/polkadot/node/network/protocol/src/grid_topology.rs +++ b/polkadot/node/network/protocol/src/grid_topology.rs @@ -114,7 +114,7 @@ impl SessionGridTopology { /// Returns `None` if the validator index is out of bounds. pub fn compute_grid_neighbors_for(&self, v: ValidatorIndex) -> Option { if self.shuffled_indices.len() != self.canonical_shuffling.len() { - return None + return None; } let shuffled_val_index = *self.shuffled_indices.get(v.0 as usize)?; @@ -157,7 +157,7 @@ fn matrix_neighbors( len: usize, ) -> Option, impl Iterator>> { if val_index >= len { - return None + return None; } // e.g. for size 11 the matrix would be @@ -214,7 +214,7 @@ impl GridNeighbors { local: bool, ) -> RequiredRouting { if local { - return RequiredRouting::GridXY + return RequiredRouting::GridXY; } let grid_x = self.validator_indices_x.contains(&originator); @@ -233,7 +233,7 @@ impl GridNeighbors { /// we're meant to send the message to. pub fn required_routing_by_peer_id(&self, originator: PeerId, local: bool) -> RequiredRouting { if local { - return RequiredRouting::GridXY + return RequiredRouting::GridXY; } let grid_x = self.peers_x.contains(&originator); @@ -443,11 +443,11 @@ impl SessionBoundGridTopologyStorage { pub fn get_topology(&self, idx: SessionIndex) -> Option<&SessionGridTopologyEntry> { if let Some(prev_topology) = &self.prev_topology { if idx == prev_topology.session_index { - return Some(&prev_topology.entry) + return Some(&prev_topology.entry); } } if self.current_topology.session_index == idx { - return Some(&self.current_topology.entry) + return Some(&self.current_topology.entry); } None diff --git a/polkadot/node/network/protocol/src/peer_set.rs b/polkadot/node/network/protocol/src/peer_set.rs index cb329607ad612..df14e2a4145db 100644 --- a/polkadot/node/network/protocol/src/peer_set.rs +++ b/polkadot/node/network/protocol/src/peer_set.rs @@ -258,7 +258,7 @@ impl TryFrom for ValidationVersion { fn try_from(p: ProtocolVersion) -> Result { for v in Self::iter() { if v as u32 == p.0 { - return Ok(v) + return Ok(v); } } @@ -272,7 +272,7 @@ impl TryFrom for CollationVersion { fn try_from(p: ProtocolVersion) -> Result { for v in Self::iter() { if v as u32 == p.0 { - return Ok(v) + return Ok(v); } } diff --git a/polkadot/node/network/protocol/src/request_response/incoming/mod.rs b/polkadot/node/network/protocol/src/request_response/incoming/mod.rs index 4455448386728..356771e3052ba 100644 --- a/polkadot/node/network/protocol/src/request_response/incoming/mod.rs +++ b/polkadot/node/network/protocol/src/request_response/incoming/mod.rs @@ -96,9 +96,9 @@ where }; if let Err(_) = pending_response.send(response) { - return Err(JfyiError::DecodingErrorNoReputationChange(peer, err)) + return Err(JfyiError::DecodingErrorNoReputationChange(peer, err)); } - return Err(JfyiError::DecodingError(peer, err)) + return Err(JfyiError::DecodingError(peer, err)); }, }; Ok(Self::new(peer, payload, pending_response)) diff --git a/polkadot/node/network/protocol/src/request_response/mod.rs b/polkadot/node/network/protocol/src/request_response/mod.rs index a67d83aff0c92..b2cd640b1b137 100644 --- a/polkadot/node/network/protocol/src/request_response/mod.rs +++ b/polkadot/node/network/protocol/src/request_response/mod.rs @@ -216,7 +216,7 @@ impl Protocol { request_timeout: CHUNK_REQUEST_TIMEOUT, inbound_queue: tx, }, - Protocol::CollationFetchingV1 | Protocol::CollationFetchingV2 => + Protocol::CollationFetchingV1 | Protocol::CollationFetchingV2 => { RequestResponseConfig { name, fallback_names: legacy_names, @@ -225,7 +225,8 @@ impl Protocol { // Taken from initial implementation in collator protocol: request_timeout: POV_REQUEST_TIMEOUT_CONNECTED, inbound_queue: tx, - }, + } + }, Protocol::PoVFetchingV1 => RequestResponseConfig { name, fallback_names: legacy_names, diff --git a/polkadot/node/network/statement-distribution/src/error.rs b/polkadot/node/network/statement-distribution/src/error.rs index a712ab6da436f..333ec61e4aaab 100644 --- a/polkadot/node/network/statement-distribution/src/error.rs +++ b/polkadot/node/network/statement-distribution/src/error.rs @@ -122,10 +122,12 @@ pub fn log_error( match result.into_nested()? { Err(jfyi) => { match jfyi { - JfyiError::RequestedUnannouncedCandidate(_, _) => - gum::warn!(target: LOG_TARGET, error = %jfyi, ctx), - _ => - gum::warn_if_frequent!(freq: warn_freq, max_rate: gum::Times::PerHour(100), target: LOG_TARGET, error = %jfyi, ctx), + JfyiError::RequestedUnannouncedCandidate(_, _) => { + gum::warn!(target: LOG_TARGET, error = %jfyi, ctx) + }, + _ => { + gum::warn_if_frequent!(freq: warn_freq, max_rate: gum::Times::PerHour(100), target: LOG_TARGET, error = %jfyi, ctx) + }, } Ok(()) }, diff --git a/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs b/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs index e22883f893760..baf225847f5f4 100644 --- a/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs +++ b/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs @@ -198,7 +198,7 @@ fn note_hash( h: CandidateHash, ) -> bool { if observed.contains(&h) { - return true + return true; } observed.try_push(h).is_ok() @@ -289,7 +289,7 @@ impl PeerRelayParentKnowledge { self.received_statements.contains(fingerprint); if already_known { - return false + return false; } match fingerprint.0 { @@ -326,7 +326,7 @@ impl PeerRelayParentKnowledge { // We don't check `sent_statements` because a statement could be in-flight from both // sides at the same time. if self.received_statements.contains(fingerprint) { - return Err(COST_DUPLICATE_STATEMENT) + return Err(COST_DUPLICATE_STATEMENT); } let (candidate_hash, fresh) = match fingerprint.0 { @@ -338,14 +338,14 @@ impl PeerRelayParentKnowledge { .note_remote(*h); if !allowed_remote { - return Err(COST_UNEXPECTED_STATEMENT_REMOTE) + return Err(COST_UNEXPECTED_STATEMENT_REMOTE); } (h, !self.is_known_candidate(h)) }, CompactStatement::Valid(ref h) => { if !self.is_known_candidate(h) { - return Err(COST_UNEXPECTED_STATEMENT_UNKNOWN_CANDIDATE) + return Err(COST_UNEXPECTED_STATEMENT_UNKNOWN_CANDIDATE); } (h, false) @@ -357,7 +357,7 @@ impl PeerRelayParentKnowledge { self.received_message_count.entry(*candidate_hash).or_insert(0); if *received_per_candidate >= max_message_count { - return Err(COST_APPARENT_FLOOD) + return Err(COST_APPARENT_FLOOD); } *received_per_candidate += 1; @@ -371,7 +371,7 @@ impl PeerRelayParentKnowledge { /// Note a received large statement metadata. fn receive_large_statement(&mut self) -> std::result::Result<(), Rep> { if self.large_statement_count >= MAX_LARGE_STATEMENTS_PER_SENDER { - return Err(COST_APPARENT_FLOOD) + return Err(COST_APPARENT_FLOOD); } self.large_statement_count += 1; Ok(()) @@ -388,7 +388,7 @@ impl PeerRelayParentKnowledge { // We don't check `sent_statements` because a statement could be in-flight from both // sides at the same time. if self.received_statements.contains(fingerprint) { - return Err(COST_DUPLICATE_STATEMENT) + return Err(COST_DUPLICATE_STATEMENT); } let candidate_hash = match fingerprint.0 { @@ -399,14 +399,14 @@ impl PeerRelayParentKnowledge { .map_or(true, |r| r.is_wanted_candidate(h)); if !allowed_remote { - return Err(COST_UNEXPECTED_STATEMENT_REMOTE) + return Err(COST_UNEXPECTED_STATEMENT_REMOTE); } h }, CompactStatement::Valid(ref h) => { if !self.is_known_candidate(&h) { - return Err(COST_UNEXPECTED_STATEMENT_UNKNOWN_CANDIDATE) + return Err(COST_UNEXPECTED_STATEMENT_UNKNOWN_CANDIDATE); } h @@ -720,7 +720,7 @@ impl ActiveHeadData { ?statement, "Extra statement is ignored" ); - return NotedStatement::NotUseful + return NotedStatement::NotUseful; } self.candidates.insert(h); @@ -758,7 +758,7 @@ impl ActiveHeadData { ?statement, "Statement for unknown candidate" ); - return NotedStatement::NotUseful + return NotedStatement::NotUseful; } if let Some(old) = self.statements.insert(comparator.clone(), statement) { @@ -812,7 +812,7 @@ impl ActiveHeadData { ?statement, "Extra statement is ignored", ); - return Err(DeniedStatement::NotUseful) + return Err(DeniedStatement::NotUseful); } if self.statements.contains_key(&comparator) { @@ -822,7 +822,7 @@ impl ActiveHeadData { ?statement, "Known statement", ); - return Err(DeniedStatement::UsefulButKnown) + return Err(DeniedStatement::UsefulButKnown); } }, CompactStatement::Valid(h) => { @@ -833,7 +833,7 @@ impl ActiveHeadData { ?statement, "Statement for unknown candidate", ); - return Err(DeniedStatement::NotUseful) + return Err(DeniedStatement::NotUseful); } if self.statements.contains_key(&comparator) { @@ -843,7 +843,7 @@ impl ActiveHeadData { ?statement, "Known statement", ); - return Err(DeniedStatement::UsefulButKnown) + return Err(DeniedStatement::UsefulButKnown); } }, } @@ -988,7 +988,7 @@ fn is_statement_large(statement: &SignedFullStatement) -> (bool, Option) let size = statement.as_unchecked().encoded_size(); // Runtime upgrades will always be large and even if not - no harm done. if committed.commitments.new_validation_code.is_some() { - return (true, Some(size)) + return (true, Some(size)); } // Half max size seems to be a good threshold to start not using notifications: @@ -1157,7 +1157,7 @@ async fn send_statements_about( for statement in active_head.statements_about(candidate_hash) { let fingerprint = statement.fingerprint(); if !peer_data.can_send(&relay_parent, &fingerprint) { - continue + continue; } peer_data.send(&relay_parent, &fingerprint); let payload = v1_statement_message(relay_parent, statement.statement.clone(), metrics); @@ -1193,7 +1193,7 @@ async fn send_statements( for statement in active_head.statements() { let fingerprint = statement.fingerprint(); if !peer_data.can_send(&relay_parent, &fingerprint) { - continue + continue; } peer_data.send(&relay_parent, &fingerprint); let payload = v1_statement_message(relay_parent, statement.statement.clone(), metrics); @@ -1248,7 +1248,7 @@ async fn retrieve_statement_from_message<'a, Context>( // Immediately return any Seconded statement: let message = if let protocol_v1::StatementDistributionMessage::Statement(h, s) = message { if let Statement::Seconded(_) = s.unchecked_payload() { - return Some(s) + return Some(s); } protocol_v1::StatementDistributionMessage::Statement(h, s) } else { @@ -1290,7 +1290,7 @@ async fn retrieve_statement_from_message<'a, Context>( protocol_v1::StatementDistributionMessage::Statement(_, s) => { // We can now immediately return any statements (should only be // `Statement::Valid` ones, but we don't care at this point.) - return Some(s) + return Some(s); }, protocol_v1::StatementDistributionMessage::LargeStatement(metadata) => return Some(UncheckedSignedFullStatement::new( @@ -1322,7 +1322,7 @@ async fn retrieve_statement_from_message<'a, Context>( // No fetch in progress, safe to return any statement immediately (we don't // bother about normal network jitter which might cause `Valid` statements to // arrive early for now.). - return Some(s) + return Some(s); }, } }, @@ -1349,7 +1349,7 @@ async fn launch_request( let result = ctx.spawn("large-statement-fetcher", task.boxed()); if let Err(err) = result { gum::error!(target: LOG_TARGET, ?err, "Spawning task failed."); - return None + return None; } let available_peers = { let mut m = IndexMap::new(); @@ -1480,7 +1480,7 @@ async fn handle_incoming_message<'a, Context>( "Legacy statement-distribution code received unintended v2 message" ); - return None + return None; }, }; @@ -1499,7 +1499,7 @@ async fn handle_incoming_message<'a, Context>( modify_reputation(reputation, ctx.sender(), peer, COST_UNEXPECTED_STATEMENT).await; } - return None + return None; }, }; @@ -1507,7 +1507,7 @@ async fn handle_incoming_message<'a, Context>( if let Err(rep) = peer_data.receive_large_statement(&relay_parent) { gum::debug!(target: LOG_TARGET, ?peer, ?message, ?rep, "Unexpected large statement.",); modify_reputation(reputation, ctx.sender(), peer, rep).await; - return None + return None; } } @@ -1561,7 +1561,7 @@ async fn handle_incoming_message<'a, Context>( }, } - return None + return None; } let checked_compact = { @@ -1580,7 +1580,7 @@ async fn handle_incoming_message<'a, Context>( .expect("checked in `check_can_receive` above; qed"); modify_reputation(reputation, ctx.sender(), peer, BENEFIT_VALID_STATEMENT).await; - return None + return None; }, } @@ -1589,7 +1589,7 @@ async fn handle_incoming_message<'a, Context>( Err(statement) => { gum::debug!(target: LOG_TARGET, ?peer, ?statement, "Invalid statement signature"); modify_reputation(reputation, ctx.sender(), peer, COST_INVALID_SIGNATURE).await; - return None + return None; }, Ok(statement) => statement, } @@ -1622,7 +1622,7 @@ async fn handle_incoming_message<'a, Context>( "Full statement had bad payload." ); modify_reputation(reputation, ctx.sender(), peer, COST_WRONG_HASH).await; - return None + return None; }, Ok(statement) => statement, }; @@ -1747,7 +1747,7 @@ async fn update_peer_view_and_maybe_send_unlocked( for new in new_view.iter().copied() { peer_data.view_knowledge.insert(new, Default::default()); if !lucky { - continue + continue; } if let Some(active_head) = active_heads.get(&new) { send_statements(peer, peer_data, ctx, new, active_head, metrics).await; @@ -1788,7 +1788,7 @@ pub(crate) async fn handle_network_update( ?protocol_version, "unknown protocol version, ignoring" ); - return + return; }, }; @@ -1930,7 +1930,7 @@ pub(crate) async fn handle_responder_message( return Err(JfyiError::RequestedUnannouncedCandidate( requesting_peer, candidate_hash, - )) + )); } let active_head = @@ -1986,7 +1986,7 @@ pub(crate) async fn handle_requester_message( Some(LargeStatementStatus::Fetching(info)) => info, Some(LargeStatementStatus::FetchedOrShared(_)) => { // We are no longer interested in the data. - return Ok(()) + return Ok(()); }, None => return Err(JfyiError::NoSuchLargeStatementStatus(relay_parent, candidate_hash)), @@ -2035,7 +2035,7 @@ pub(crate) async fn handle_requester_message( Some(LargeStatementStatus::FetchedOrShared(_)) => { // This task is going to die soon - no need to send it anything. gum::debug!(target: LOG_TARGET, "Zombie task wanted more peers."); - return Ok(()) + return Ok(()); }, None => return Err(JfyiError::NoSuchLargeStatementStatus(relay_parent, candidate_hash)), @@ -2147,7 +2147,7 @@ pub(crate) async fn share_local_statement( .into_iter() .filter_map(|i| { if Some(*i) == validator_info.our_index { - return None + return None; } let authority_id = &session_info.discovery_keys[i.0 as usize]; state.authorities.get(authority_id).map(|p| *p) diff --git a/polkadot/node/network/statement-distribution/src/legacy_v1/requester.rs b/polkadot/node/network/statement-distribution/src/legacy_v1/requester.rs index 8a8a8f3d624a8..77a2471b4c9dd 100644 --- a/polkadot/node/network/statement-distribution/src/legacy_v1/requester.rs +++ b/polkadot/node/network/statement-distribution/src/legacy_v1/requester.rs @@ -118,7 +118,7 @@ pub async fn fetch( ?err, "Sending request failed, node might be shutting down - exiting." ); - return + return; } metrics.on_sent_request(); @@ -139,7 +139,7 @@ pub async fn fetch( ); } // We want to get rid of this peer: - continue + continue; } if let Err(err) = sender @@ -162,7 +162,7 @@ pub async fn fetch( metrics.on_received_response(true); // We are done now. - return + return; }, Err(err) => { gum::debug!( @@ -220,7 +220,7 @@ async fn try_get_new_peers( ?err, "Failed sending background task message, subsystem probably moved on." ); - return Err(()) + return Err(()); } match rx.timeout(RETRY_TIMEOUT).await.transpose() { diff --git a/polkadot/node/network/statement-distribution/src/legacy_v1/responder.rs b/polkadot/node/network/statement-distribution/src/legacy_v1/responder.rs index 81e226c4ff895..8d1d5ea79bbae 100644 --- a/polkadot/node/network/statement-distribution/src/legacy_v1/responder.rs +++ b/polkadot/node/network/statement-distribution/src/legacy_v1/responder.rs @@ -79,11 +79,11 @@ pub async fn respond( Ok(Ok(v)) => v, Err(fatal) => { gum::debug!(target: LOG_TARGET, error = ?fatal, "Shutting down request responder"); - return + return; }, Ok(Err(jfyi)) => { gum::debug!(target: LOG_TARGET, error = ?jfyi, "Decoding request failed"); - continue + continue; }, }; @@ -98,7 +98,7 @@ pub async fn respond( .await { gum::debug!(target: LOG_TARGET, ?err, "Shutting down responder"); - return + return; } let response = match rx.await { Err(err) => { diff --git a/polkadot/node/network/statement-distribution/src/v2/candidates.rs b/polkadot/node/network/statement-distribution/src/v2/candidates.rs index ad56ad4a2365b..7f11efe1ec017 100644 --- a/polkadot/node/network/statement-distribution/src/v2/candidates.rs +++ b/polkadot/node/network/statement-distribution/src/v2/candidates.rs @@ -103,20 +103,20 @@ impl Candidates { match entry { CandidateState::Confirmed(ref c) => { if c.relay_parent() != claimed_relay_parent { - return Err(BadAdvertisement) + return Err(BadAdvertisement); } if c.group_index() != claimed_group_index { - return Err(BadAdvertisement) + return Err(BadAdvertisement); } if let Some((claimed_parent_hash, claimed_id)) = claimed_parent_hash_and_id { if c.parent_head_data_hash() != claimed_parent_hash { - return Err(BadAdvertisement) + return Err(BadAdvertisement); } if c.para_id() != claimed_id { - return Err(BadAdvertisement) + return Err(BadAdvertisement); } } }, diff --git a/polkadot/node/network/statement-distribution/src/v2/cluster.rs b/polkadot/node/network/statement-distribution/src/v2/cluster.rs index 619114de9670c..2f5d2ca38c5e7 100644 --- a/polkadot/node/network/statement-distribution/src/v2/cluster.rs +++ b/polkadot/node/network/statement-distribution/src/v2/cluster.rs @@ -104,7 +104,7 @@ impl ClusterTracker { /// Instantiate a new `ClusterTracker` tracker. Fails if `cluster_validators` is empty pub fn new(cluster_validators: Vec, seconding_limit: usize) -> Option { if cluster_validators.is_empty() { - return None + return None; } Some(ClusterTracker { validators: cluster_validators, @@ -124,11 +124,11 @@ impl ClusterTracker { statement: CompactStatement, ) -> Result { if !self.is_in_group(sender) || !self.is_in_group(originator) { - return Err(RejectIncoming::NotInGroup) + return Err(RejectIncoming::NotInGroup); } if self.they_sent(sender, Knowledge::Specific(statement.clone(), originator)) { - return Err(RejectIncoming::Duplicate) + return Err(RejectIncoming::Duplicate); } match statement { @@ -151,7 +151,7 @@ impl ClusterTracker { .count(); if other_seconded_for_orig_from_remote == self.seconding_limit { - return Err(RejectIncoming::ExcessiveSeconded) + return Err(RejectIncoming::ExcessiveSeconded); } // at this point, it doesn't seem like the remote has done anything wrong. @@ -163,7 +163,7 @@ impl ClusterTracker { }, CompactStatement::Valid(candidate_hash) => { if !self.knows_candidate(sender, candidate_hash) { - return Err(RejectIncoming::CandidateUnknown) + return Err(RejectIncoming::CandidateUnknown); } Ok(Accept::Ok) @@ -240,11 +240,11 @@ impl ClusterTracker { statement: CompactStatement, ) -> Result<(), RejectOutgoing> { if !self.is_in_group(target) || !self.is_in_group(originator) { - return Err(RejectOutgoing::NotInGroup) + return Err(RejectOutgoing::NotInGroup); } if self.they_know_statement(target, originator, statement.clone()) { - return Err(RejectOutgoing::Known) + return Err(RejectOutgoing::Known); } match statement { @@ -252,14 +252,14 @@ impl ClusterTracker { // we send the same `Seconded` statements to all our peers, and only the first `k` // from each originator. if !self.seconded_already_or_within_limit(originator, candidate_hash) { - return Err(RejectOutgoing::ExcessiveSeconded) + return Err(RejectOutgoing::ExcessiveSeconded); } Ok(()) }, CompactStatement::Valid(candidate_hash) => { if !self.knows_candidate(target, candidate_hash) { - return Err(RejectOutgoing::CandidateUnknown) + return Err(RejectOutgoing::CandidateUnknown); } Ok(()) diff --git a/polkadot/node/network/statement-distribution/src/v2/grid.rs b/polkadot/node/network/statement-distribution/src/v2/grid.rs index 24d846c840e00..e0684e5f5890a 100644 --- a/polkadot/node/network/statement-distribution/src/v2/grid.rs +++ b/polkadot/node/network/statement-distribution/src/v2/grid.rs @@ -133,7 +133,7 @@ pub fn build_session_topology<'a>( None => { gum::warn!(target: LOG_TARGET, ?our_index, "our index unrecognized in topology?"); - return view + return view; }, Some(n) => n, }; @@ -167,7 +167,7 @@ pub fn build_session_topology<'a>( .cloned(), ); - continue + continue; } if our_neighbors.validator_indices_y.contains(&group_val) { @@ -180,7 +180,7 @@ pub fn build_session_topology<'a>( .cloned(), ); - continue + continue; } // If they don't share a slice with us, we don't send to anybody @@ -193,7 +193,7 @@ pub fn build_session_topology<'a>( "validator index unrecognized in topology?" ); - continue + continue; }, Some(n) => n, }; @@ -202,7 +202,7 @@ pub fn build_session_topology<'a>( for potential_link in &their_neighbors.validator_indices_x { if our_neighbors.validator_indices_y.contains(potential_link) { sub_view.receiving.insert(*potential_link); - break // one max + break; // one max } } @@ -210,7 +210,7 @@ pub fn build_session_topology<'a>( for potential_link in &their_neighbors.validator_indices_y { if our_neighbors.validator_indices_x.contains(potential_link) { sub_view.receiving.insert(*potential_link); - break // one max + break; // one max } } } @@ -293,7 +293,7 @@ impl GridTracker { }; if !manifest_allowed { - return Err(ManifestImportError::Disallowed) + return Err(ManifestImportError::Disallowed); } let (group_size, backing_threshold) = @@ -305,18 +305,18 @@ impl GridTracker { let remote_knowledge = manifest.statement_knowledge.clone(); if !remote_knowledge.has_len(group_size) { - return Err(ManifestImportError::Malformed) + return Err(ManifestImportError::Malformed); } if !remote_knowledge.has_seconded() { - return Err(ManifestImportError::Malformed) + return Err(ManifestImportError::Malformed); } // ensure votes are sufficient to back. let votes = remote_knowledge.backing_validators(); if votes < backing_threshold { - return Err(ManifestImportError::Insufficient) + return Err(ManifestImportError::Insufficient); } self.received.entry(sender).or_default().import_received( @@ -388,7 +388,7 @@ impl GridTracker { { if claimed_group_index != group_index { // This is misbehavior, but is handled more comprehensively elsewhere - continue + continue; } let statement_filter = self @@ -591,7 +591,7 @@ impl GridTracker { }; if !known.note_fresh_statement(in_group, kind) { - return + return; } // Add to `pending_statements` for all validators we communicate with @@ -773,11 +773,11 @@ impl ReceivedManifests { { let prev = e.get(); if prev.claimed_group_index != manifest_summary.claimed_group_index { - return Err(ManifestImportError::Conflicting) + return Err(ManifestImportError::Conflicting); } if prev.claimed_parent_hash != manifest_summary.claimed_parent_hash { - return Err(ManifestImportError::Conflicting) + return Err(ManifestImportError::Conflicting); } if !manifest_summary @@ -785,7 +785,7 @@ impl ReceivedManifests { .seconded_in_group .contains(&prev.statement_knowledge.seconded_in_group) { - return Err(ManifestImportError::Conflicting) + return Err(ManifestImportError::Conflicting); } if !manifest_summary @@ -793,7 +793,7 @@ impl ReceivedManifests { .validated_in_group .contains(&prev.statement_knowledge.validated_in_group) { - return Err(ManifestImportError::Conflicting) + return Err(ManifestImportError::Conflicting); } let mut fresh_seconded = @@ -809,7 +809,7 @@ impl ReceivedManifests { ); if !within_limits { - return Err(ManifestImportError::Overflow) + return Err(ManifestImportError::Overflow); } } @@ -851,7 +851,7 @@ fn updating_ensure_within_seconding_limit( new_seconded: &BitSlice, ) -> bool { if seconding_limit == 0 { - return false + return false; } // due to the check above, if this was non-existent this function will @@ -860,7 +860,7 @@ fn updating_ensure_within_seconding_limit( for i in new_seconded.iter_ones() { if counts[i] == seconding_limit { - return false + return false; } } @@ -979,7 +979,7 @@ impl KnownBackedCandidate { statement_kind: StatementKind, ) -> Vec<(ValidatorIndex, bool)> { if group_index != self.group_index { - return Vec::new() + return Vec::new(); } self.mutual_knowledge @@ -1008,7 +1008,7 @@ impl KnownBackedCandidate { statement_kind: StatementKind, ) -> Vec { if group_index != self.group_index { - return Vec::new() + return Vec::new(); } self.mutual_knowledge diff --git a/polkadot/node/network/statement-distribution/src/v2/mod.rs b/polkadot/node/network/statement-distribution/src/v2/mod.rs index dc29c19a48e33..bc13f40805ab6 100644 --- a/polkadot/node/network/statement-distribution/src/v2/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/mod.rs @@ -380,7 +380,7 @@ impl PeerState { // under an active leaf. fn reconcile_active_leaf(&mut self, leaf_hash: Hash, implicit: &[Hash]) -> Vec { if !self.view.contains(&leaf_hash) { - return Vec::new() + return Vec::new(); } let mut v = Vec::with_capacity(implicit.len()); @@ -424,7 +424,7 @@ pub(crate) async fn handle_network_update( let versioned_protocol = if protocol_version != ValidationVersion::V2.into() && protocol_version != ValidationVersion::V3.into() { - return + return; } else { protocol_version.try_into().expect("Qed, we checked above") }; @@ -612,7 +612,7 @@ pub(crate) async fn handle_active_leaves_update( "No session info available for current session" ); - continue + continue; }, Some(s) => s, }; @@ -649,7 +649,7 @@ pub(crate) async fn handle_active_leaves_update( } if state.per_relay_parent.contains_key(&new_relay_parent) { - continue + continue; } // New leaf: fetch info from runtime API and initialize @@ -738,7 +738,7 @@ fn find_active_validator_state( seconding_limit: usize, ) -> Option { if groups.all().is_empty() { - return None + return None; } let our_group = groups.by_validator_index(validator_index)?; @@ -930,7 +930,7 @@ async fn send_pending_cluster_statements( .into_iter() .filter_map(|(originator, compact)| { if !candidates.is_confirmed(compact.candidate_hash()) { - return None + return None; } let res = pending_statement_network_message( @@ -950,7 +950,7 @@ async fn send_pending_cluster_statements( .collect::>(); if network_messages.is_empty() { - return + return; } ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(network_messages)) @@ -1109,7 +1109,7 @@ async fn send_pending_grid_messages( } if messages.is_empty() { - return + return; } ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(messages)).await; } @@ -1165,7 +1165,7 @@ pub(crate) async fn share_local_statement( }; if local_index != statement.validator_index() { - return Err(JfyiError::InvalidShare) + return Err(JfyiError::InvalidShare); } if is_seconded && @@ -1177,11 +1177,11 @@ pub(crate) async fn share_local_statement( limit = ?per_relay_parent.seconding_limit, "Local node has issued too many `Seconded` statements", ); - return Err(JfyiError::InvalidShare) + return Err(JfyiError::InvalidShare); } if local_assignment != Some(expected_para) || relay_parent != expected_relay_parent { - return Err(JfyiError::InvalidShare) + return Err(JfyiError::InvalidShare); } let mut post_confirmation = None; @@ -1211,7 +1211,7 @@ pub(crate) async fn share_local_statement( statement = ?compact_statement.payload(), "Candidate backing issued redundant statement?", ); - return Err(JfyiError::InvalidShare) + return Err(JfyiError::InvalidShare); }, Ok(true) => {}, } @@ -1490,7 +1490,7 @@ async fn handle_incoming_statement( let peer_state = match state.peers.get(&peer) { None => { // sanity: should be impossible. - return + return; }, Some(p) => p, }; @@ -1505,7 +1505,7 @@ async fn handle_incoming_statement( COST_UNEXPECTED_STATEMENT_MISSING_KNOWLEDGE, ) .await; - return + return; }, Some(p) => p, }; @@ -1518,7 +1518,7 @@ async fn handle_incoming_statement( "Missing expected session info.", ); - return + return; }, Some(s) => s, }; @@ -1537,7 +1537,7 @@ async fn handle_incoming_statement( ) .await; } - return + return; }, Some(l) => l, }; @@ -1553,7 +1553,7 @@ async fn handle_incoming_statement( COST_UNEXPECTED_STATEMENT_VALIDATOR_NOT_FOUND, ) .await; - return + return; }, }; @@ -1565,7 +1565,7 @@ async fn handle_incoming_statement( "Ignoring a statement from disabled validator." ); modify_reputation(reputation, ctx.sender(), peer, COST_DISABLED_VALIDATOR).await; - return + return; } let (active, cluster_sender_index) = { @@ -1606,7 +1606,7 @@ async fn handle_incoming_statement( Ok(None) => return, Err(rep) => { modify_reputation(reputation, ctx.sender(), peer, rep).await; - return + return; }, } } else { @@ -1641,7 +1641,7 @@ async fn handle_incoming_statement( Ok(s) => s, Err(rep) => { modify_reputation(reputation, ctx.sender(), peer, rep).await; - return + return; }, } } else { @@ -1658,7 +1658,7 @@ async fn handle_incoming_statement( COST_UNEXPECTED_STATEMENT_INVALID_SENDER, ) .await; - return + return; } }; @@ -1686,7 +1686,7 @@ async fn handle_incoming_statement( COST_UNEXPECTED_STATEMENT_BAD_ADVERTISE, ) .await; - return + return; } } @@ -1721,7 +1721,7 @@ async fn handle_incoming_statement( "Error - accepted message from unknown validator." ); - return + return; }, Ok(known) => known, }; @@ -1797,7 +1797,7 @@ fn handle_cluster_statement( Err(ClusterRejectIncoming::NotInGroup) => { // sanity: shouldn't be possible; we already filtered this // out above. - return Err(COST_UNEXPECTED_STATEMENT_NOT_IN_GROUP) + return Err(COST_UNEXPECTED_STATEMENT_NOT_IN_GROUP); }, } }; @@ -1937,7 +1937,7 @@ async fn provide_candidate_to_grid( "Cannot handle backable candidate due to lack of topology", ); - return + return; }, }; @@ -1952,7 +1952,7 @@ async fn provide_candidate_to_grid( "Handled backed candidate with unknown group?", ); - return + return; }, Some(g) => g.len(), }; @@ -1995,7 +1995,7 @@ async fn provide_candidate_to_grid( if peers.get(&p).map_or(false, |d| d.knows_relay_parent(&relay_parent)) { (p, peers.get(&p).expect("Qed, was checked above").protocol_version.into()) } else { - continue + continue; }, }; @@ -2160,7 +2160,7 @@ async fn fragment_tree_update_inner( for (hypo, membership) in frontier { // skip parablocks outside of the frontier if membership.is_empty() { - continue + continue; } for (leaf_hash, _) in membership { @@ -2270,7 +2270,7 @@ async fn handle_incoming_manifest_common<'a, Context>( COST_UNEXPECTED_MANIFEST_MISSING_KNOWLEDGE, ) .await; - return None + return None; }, Some(s) => s, }; @@ -2291,7 +2291,7 @@ async fn handle_incoming_manifest_common<'a, Context>( ) .await; } - return None + return None; }, Some(x) => x, }; @@ -2304,7 +2304,7 @@ async fn handle_incoming_manifest_common<'a, Context>( if expected_group != Some(manifest_summary.claimed_group_index) { modify_reputation(reputation, ctx.sender(), peer, COST_MALFORMED_MANIFEST).await; - return None + return None; } let grid_topology = match per_session.grid_view.as_ref() { @@ -2328,7 +2328,7 @@ async fn handle_incoming_manifest_common<'a, Context>( COST_UNEXPECTED_MANIFEST_PEER_UNKNOWN, ) .await; - return None + return None; }, Some(s) => s, }; @@ -2354,24 +2354,24 @@ async fn handle_incoming_manifest_common<'a, Context>( Ok(x) => x, Err(grid::ManifestImportError::Conflicting) => { modify_reputation(reputation, ctx.sender(), peer, COST_CONFLICTING_MANIFEST).await; - return None + return None; }, Err(grid::ManifestImportError::Overflow) => { modify_reputation(reputation, ctx.sender(), peer, COST_EXCESSIVE_SECONDED).await; - return None + return None; }, Err(grid::ManifestImportError::Insufficient) => { modify_reputation(reputation, ctx.sender(), peer, COST_INSUFFICIENT_MANIFEST).await; - return None + return None; }, Err(grid::ManifestImportError::Malformed) => { modify_reputation(reputation, ctx.sender(), peer, COST_MALFORMED_MANIFEST).await; - return None + return None; }, Err(grid::ManifestImportError::Disallowed) => { modify_reputation(reputation, ctx.sender(), peer, COST_UNEXPECTED_MANIFEST_DISALLOWED) .await; - return None + return None; }, }; @@ -2384,7 +2384,7 @@ async fn handle_incoming_manifest_common<'a, Context>( Some((claimed_parent_hash, para_id)), ) { modify_reputation(reputation, ctx.sender(), peer, COST_INACCURATE_ADVERTISEMENT).await; - return None + return None; } if acknowledge { @@ -2598,7 +2598,7 @@ fn acknowledgement_and_statement_messages( "Bug ValidationVersion::V1 should not be used in statement-distribution v2, legacy should have handled this" ); - return Vec::new() + return Vec::new(); }, }; @@ -2656,7 +2656,7 @@ async fn handle_incoming_acknowledgement( COST_UNEXPECTED_ACKNOWLEDGEMENT_UNKNOWN_CANDIDATE, ) .await; - return + return; }, } }; @@ -2736,7 +2736,7 @@ pub(crate) async fn handle_backed_candidate_message( "Received backed candidate notification for unknown or unconfirmed", ); - return + return; }, Some(c) => c, }; @@ -2868,7 +2868,7 @@ async fn apply_post_confirmation( #[overseer::contextbounds(StatementDistribution, prefix=self::overseer)] pub(crate) async fn dispatch_requests(ctx: &mut Context, state: &mut State) { if !state.request_manager.has_pending_requests() { - return + return; } let peers = &state.peers; @@ -2887,7 +2887,7 @@ pub(crate) async fn dispatch_requests(ctx: &mut Context, state: &mut St // but have surely sent us some. if let Some(active) = local_validator.active.as_ref() { if active.cluster_tracker.knows_candidate(validator_id, identifier.candidate_hash) { - return Some(StatementFilter::blank(active.cluster_tracker.targets().len())) + return Some(StatementFilter::blank(active.cluster_tracker.targets().len())); } } @@ -2896,7 +2896,7 @@ pub(crate) async fn dispatch_requests(ctx: &mut Context, state: &mut St .advertised_statements(validator_id, &identifier.candidate_hash); if let Some(f) = filter { - return Some(f) + return Some(f); } } @@ -3046,7 +3046,7 @@ pub(crate) async fn handle_response( "Response incomplete. Retrying" ); - return + return; }, requests::CandidateRequestStatus::Complete { candidate, @@ -3083,7 +3083,7 @@ pub(crate) async fn handle_response( "Candidate re-confirmed by request/response: logic error", ); - return + return; } }; @@ -3096,7 +3096,7 @@ pub(crate) async fn handle_response( // hypothetical frontier of the fragment tree. Later, when it is, // we will import statements. if !confirmed.is_importable(None) { - return + return; } let relay_parent_state = match state.per_relay_parent.get_mut(&relay_parent) { @@ -3192,7 +3192,7 @@ pub(crate) fn answer_request(state: &mut State, message: ResponderMessage) { sent_feedback: None, }); - return + return; } // check peer is allowed to request the candidate (i.e. they're in the cluster or we've sent @@ -3210,12 +3210,12 @@ pub(crate) fn answer_request(state: &mut State, message: ResponderMessage) { { validator_id = Some(v); is_cluster = true; - break + break; } if local_validator.grid_tracker.can_request(v, *candidate_hash) { validator_id = Some(v); - break + break; } } @@ -3228,7 +3228,7 @@ pub(crate) fn answer_request(state: &mut State, message: ResponderMessage) { sent_feedback: None, }); - return + return; }, } }; @@ -3284,7 +3284,7 @@ pub(crate) fn answer_request(state: &mut State, message: ResponderMessage) { ?group_index, "Dropping a request from a grid peer because the backing threshold is no longer met." ); - return + return; } } @@ -3346,11 +3346,11 @@ pub(crate) async fn respond_task( Ok(Ok(v)) => v, Err(fatal) => { gum::debug!(target: LOG_TARGET, error = ?fatal, "Shutting down request responder"); - return + return; }, Ok(Err(jfyi)) => { gum::debug!(target: LOG_TARGET, error = ?jfyi, "Decoding request failed"); - continue + continue; }, }; @@ -3360,7 +3360,7 @@ pub(crate) async fn respond_task( .await { gum::debug!(target: LOG_TARGET, ?err, "Shutting down responder"); - return + return; } pending_out.push(pending_sent_rx); } diff --git a/polkadot/node/network/statement-distribution/src/v2/requests.rs b/polkadot/node/network/statement-distribution/src/v2/requests.rs index bed3d5c18ae2b..1caa468c1ab15 100644 --- a/polkadot/node/network/statement-distribution/src/v2/requests.rs +++ b/polkadot/node/network/statement-distribution/src/v2/requests.rs @@ -101,13 +101,13 @@ pub struct RequestedCandidate { impl RequestedCandidate { fn is_pending(&self) -> bool { if self.in_flight { - return false + return false; } if let Some(next_retry_time) = self.next_retry_time { let can_retry = Instant::now() >= next_retry_time; if !can_retry { - return false + return false; } } @@ -278,7 +278,7 @@ impl RequestManager { pub fn has_pending_requests(&self) -> bool { for (_id, entry) in &self.requests { if entry.is_pending() { - return true + return true; } } @@ -316,7 +316,7 @@ impl RequestManager { peer_advertised: impl Fn(&CandidateIdentifier, &PeerId) -> Option, ) -> Option> { if response_manager.len() >= MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS as usize { - return None + return None; } let mut res = None; @@ -335,19 +335,19 @@ impl RequestManager { "Missing entry for priority queue member", ); - continue + continue; }, Some(e) => e, }; if !entry.is_pending() { - continue + continue; } let props = match request_props(&id) { None => { cleanup_outdated.push((i, id.clone())); - continue + continue; }, Some(s) => s, }; @@ -390,7 +390,7 @@ impl RequestManager { entry.in_flight = true; res = Some(request); - break + break; } for (priority_index, identifier) in cleanup_outdated.into_iter().rev() { @@ -469,7 +469,7 @@ fn find_request_target_with_update( let mut filter = match peer_advertised(candidate_identifier, p) { None => { prune.push(i); - continue + continue; }, Some(f) => f, }; @@ -478,7 +478,7 @@ fn find_request_target_with_update( filter.mask_valid(&props.unwanted_mask.validated_in_group); if seconded_and_sufficient(&filter, props.backing_threshold) { target = Some((i, *p)); - break + break; } } @@ -596,7 +596,7 @@ impl UnhandledResponse { requested_peer, reputation_changes: vec![(requested_peer, COST_IMPROPERLY_DECODED_RESPONSE)], request_status: CandidateRequestStatus::Incomplete, - } + }; }, Err(e @ RequestError::NetworkError(_) | e @ RequestError::Canceled(_)) => { gum::trace!( @@ -609,7 +609,7 @@ impl UnhandledResponse { requested_peer, reputation_changes: vec![], request_status: CandidateRequestStatus::Incomplete, - } + }; }, Ok(response) => response, }; @@ -671,24 +671,24 @@ fn validate_complete_response( // note: roughly ascending cost of operations { if response.candidate_receipt.descriptor.relay_parent != identifier.relay_parent { - return invalid_candidate_output() + return invalid_candidate_output(); } if response.candidate_receipt.descriptor.persisted_validation_data_hash != response.persisted_validation_data.hash() { - return invalid_candidate_output() + return invalid_candidate_output(); } if !allowed_para_lookup( response.candidate_receipt.descriptor.para_id, identifier.group_index, ) { - return invalid_candidate_output() + return invalid_candidate_output(); } if response.candidate_receipt.hash() != identifier.candidate_hash { - return invalid_candidate_output() + return invalid_candidate_output(); } } @@ -711,7 +711,7 @@ fn validate_complete_response( Some(i) => i, None => { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; }, }; @@ -720,7 +720,7 @@ fn validate_complete_response( &identifier.candidate_hash { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; } // filter out duplicates or statements outside the mask. @@ -730,36 +730,36 @@ fn validate_complete_response( CompactStatement::Seconded(_) => { if unwanted_mask.seconded_in_group[i] { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; } if received_filter.seconded_in_group[i] { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; } }, CompactStatement::Valid(_) => { if unwanted_mask.validated_in_group[i] { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; } if received_filter.validated_in_group[i] { rep_changes.push((requested_peer, COST_UNREQUESTED_RESPONSE_STATEMENT)); - continue + continue; } }, } if disabled_mask.get(i).map_or(false, |x| *x) { - continue + continue; } let validator_public = match validator_key_lookup(unchecked_statement.unchecked_validator_index()) { None => { rep_changes.push((requested_peer, COST_INVALID_SIGNATURE)); - continue + continue; }, Some(p) => p, }; @@ -768,7 +768,7 @@ fn validate_complete_response( match unchecked_statement.try_into_checked(&signing_context, &validator_public) { Err(_) => { rep_changes.push((requested_peer, COST_INVALID_SIGNATURE)); - continue + continue; }, Ok(checked) => checked, }; @@ -789,7 +789,7 @@ fn validate_complete_response( // Only accept responses which are sufficient, according to our // required backing threshold. if !seconded_and_sufficient(&received_filter, backing_threshold) { - return invalid_candidate_output() + return invalid_candidate_output(); } statements @@ -846,7 +846,7 @@ fn insert_or_update_priority( // expected identifier. if priority_sorted[prev_index].0 == new_priority { // unchanged. - return prev_index + return prev_index; } else { priority_sorted.remove(prev_index); } diff --git a/polkadot/node/network/statement-distribution/src/v2/statement_store.rs b/polkadot/node/network/statement-distribution/src/v2/statement_store.rs index 022461e55511c..51bfdd8ac7d65 100644 --- a/polkadot/node/network/statement-distribution/src/v2/statement_store.rs +++ b/polkadot/node/network/statement-distribution/src/v2/statement_store.rs @@ -112,7 +112,7 @@ impl StatementStore { e.get_mut().known_by_backing = true; } - return Ok(false) + return Ok(false); }, HEntry::Vacant(e) => { e.insert(StoredStatement { statement, known_by_backing: origin.is_local() }); @@ -134,7 +134,7 @@ impl StatementStore { "groups passed into `insert` differ from those used at store creation" ); - return Err(Error::ValidatorUnknown) + return Err(Error::ValidatorUnknown); }, }; diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs index 82986a0330ec2..d8942fdb37d02 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs @@ -657,7 +657,7 @@ async fn handle_leaf_activation( } tx.send(hypothetical_frontier).unwrap(); // this is the last expected runtime api call - break + break; }, msg => panic!("unexpected runtime API call: {msg:?}"), } diff --git a/polkadot/node/overseer/examples/minimal-example.rs b/polkadot/node/overseer/examples/minimal-example.rs index 857cdba673db2..50787a24669f8 100644 --- a/polkadot/node/overseer/examples/minimal-example.rs +++ b/polkadot/node/overseer/examples/minimal-example.rs @@ -56,12 +56,12 @@ impl Subsystem1 { if let FromOrchestra::Communication { msg } = msg { gum::info!("msg {:?}", msg); } - continue 'louy + continue 'louy; }, Ok(None) => (), Err(_) => { gum::info!("exiting"); - break 'louy + break 'louy; }, } @@ -120,14 +120,14 @@ impl Subsystem2 { match ctx.try_recv().await { Ok(Some(msg)) => { gum::info!("Subsystem2 received message {:?}", msg); - continue + continue; }, Ok(None) => { pending!(); }, Err(_) => { gum::info!("exiting"); - return + return; }, } } diff --git a/polkadot/node/overseer/src/dummy.rs b/polkadot/node/overseer/src/dummy.rs index fc5f0070773b7..79d2403e309f2 100644 --- a/polkadot/node/overseer/src/dummy.rs +++ b/polkadot/node/overseer/src/dummy.rs @@ -44,7 +44,7 @@ where "Discarding a message sent from overseer {:?}", overseer_msg ); - continue + continue; }, } } diff --git a/polkadot/node/overseer/src/lib.rs b/polkadot/node/overseer/src/lib.rs index e16a3fd27ab3d..2940d7806a7a3 100644 --- a/polkadot/node/overseer/src/lib.rs +++ b/polkadot/node/overseer/src/lib.rs @@ -682,8 +682,9 @@ where ); metrics.memory_stats_snapshot(memory_stats_snapshot); }, - Err(e) => - gum::debug!(target: LOG_TARGET, "Failed to obtain memory stats: {:?}", e), + Err(e) => { + gum::debug!(target: LOG_TARGET, "Failed to obtain memory stats: {:?}", e) + }, }), Err(_) => { gum::debug!( @@ -795,7 +796,7 @@ where hash_map::Entry::Vacant(entry) => entry.insert(block.number), hash_map::Entry::Occupied(entry) => { debug_assert_eq!(*entry.get(), block.number); - return Ok(()) + return Ok(()); }, }; @@ -863,7 +864,7 @@ where parent_hash: Option, ) -> Option> { if !self.supports_parachains.head_supports_parachains(hash).await { - return None + return None; } self.metrics.on_head_activated(); diff --git a/polkadot/node/overseer/src/tests.rs b/polkadot/node/overseer/src/tests.rs index 0494274367d95..99f92c11fe412 100644 --- a/polkadot/node/overseer/src/tests.rs +++ b/polkadot/node/overseer/src/tests.rs @@ -65,7 +65,7 @@ where Ok(FromOrchestra::Communication { .. }) => { let _ = sender.send(i).await; i += 1; - continue + continue; }, Ok(FromOrchestra::Signal(OverseerSignal::Conclude)) => return Ok(()), Err(_) => return Ok(()), @@ -111,7 +111,7 @@ where }) .await; c += 1; - continue + continue; } match ctx.try_recv().await { Ok(Some(FromOrchestra::Signal(OverseerSignal::Conclude))) => break, @@ -320,7 +320,7 @@ where Ok(Some(FromOrchestra::Signal(OverseerSignal::Conclude))) => break, Ok(Some(FromOrchestra::Signal(s))) => { sender.send(s).await.unwrap(); - continue + continue; }, Ok(Some(_)) => continue, Err(_) => break, @@ -352,7 +352,7 @@ where Ok(Some(FromOrchestra::Signal(OverseerSignal::Conclude))) => break, Ok(Some(FromOrchestra::Signal(s))) => { sender.send(s).await.unwrap(); - continue + continue; }, Ok(Some(_)) => continue, Err(_) => break, @@ -770,15 +770,15 @@ where match ctx.try_recv().await { Ok(Some(FromOrchestra::Signal(OverseerSignal::Conclude))) => { self.stop_signals_received.fetch_add(1, atomic::Ordering::SeqCst); - break + break; }, Ok(Some(FromOrchestra::Signal(_))) => { self.signals_received.fetch_add(1, atomic::Ordering::SeqCst); - continue + continue; }, Ok(Some(FromOrchestra::Communication { .. })) => { self.msgs_received.fetch_add(1, atomic::Ordering::SeqCst); - continue + continue; }, Err(_) => (), _ => (), @@ -1053,7 +1053,7 @@ fn overseer_all_subsystems_receive_signals_and_messages() { } else if r > NUM_SUBSYSTEMS_MESSAGED { panic!("too many messages received??"); } else { - break + break; } }, Some(_) => panic!("exited too early"), diff --git a/polkadot/node/primitives/src/approval.rs b/polkadot/node/primitives/src/approval.rs index f2a79e025affe..5e6714be2958e 100644 --- a/polkadot/node/primitives/src/approval.rs +++ b/polkadot/node/primitives/src/approval.rs @@ -202,7 +202,7 @@ pub mod v1 { vrf_pre_output: sig.pre_output.clone(), slot, authority_index, - }) + }); } } @@ -341,7 +341,7 @@ pub mod v2 { fn try_from(mut value: Vec) -> Result { if value.is_empty() { - return Err(BitfieldError::NullAssignment) + return Err(BitfieldError::NullAssignment); } let initial_bitfield = @@ -501,7 +501,7 @@ pub mod v2 { if value.candidate_indices.count_ones() != 1 { return Err(ApprovalConversionError::MoreThanOneCandidate( value.candidate_indices.count_ones(), - )) + )); } Ok(Self { block_hash: value.block_hash, @@ -552,7 +552,7 @@ mod test { // Test 0 bits. for index in 0..max_index { if candidate_indices.contains(&BitIndex(index as usize)) { - continue + continue; } assert!(!bitfield.bit_at(BitIndex(index as usize))); } diff --git a/polkadot/node/primitives/src/disputes/message.rs b/polkadot/node/primitives/src/disputes/message.rs index 31fe73a7ba1c4..bce13ecce4e14 100644 --- a/polkadot/node/primitives/src/disputes/message.rs +++ b/polkadot/node/primitives/src/disputes/message.rs @@ -128,12 +128,12 @@ impl DisputeMessage { let candidate_hash = *valid_statement.candidate_hash(); // Check statements concern same candidate: if candidate_hash != *invalid_statement.candidate_hash() { - return Err(Error::CandidateHashMismatch) + return Err(Error::CandidateHashMismatch); } let session_index = valid_statement.session_index(); if session_index != invalid_statement.session_index() { - return Err(Error::SessionIndexMismatch) + return Err(Error::SessionIndexMismatch); } let valid_id = session_info @@ -146,15 +146,15 @@ impl DisputeMessage { .ok_or(Error::InvalidStatementInvalidValidatorIndex)?; if valid_id != valid_statement.validator_public() { - return Err(Error::InvalidValidKey) + return Err(Error::InvalidValidKey); } if invalid_id != invalid_statement.validator_public() { - return Err(Error::InvalidInvalidKey) + return Err(Error::InvalidInvalidKey); } if candidate_receipt.hash() != candidate_hash { - return Err(Error::InvalidCandidateReceipt) + return Err(Error::InvalidCandidateReceipt); } let valid_kind = match valid_statement.statement() { diff --git a/polkadot/node/primitives/src/lib.rs b/polkadot/node/primitives/src/lib.rs index 6e3eefbcbe8c7..d9c626dbcad96 100644 --- a/polkadot/node/primitives/src/lib.rs +++ b/polkadot/node/primitives/src/lib.rs @@ -235,8 +235,9 @@ pub enum StatementWithPVD { impl std::fmt::Debug for StatementWithPVD { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - StatementWithPVD::Seconded(seconded, _) => - write!(f, "Seconded: {:?}", seconded.descriptor), + StatementWithPVD::Seconded(seconded, _) => { + write!(f, "Seconded: {:?}", seconded.descriptor) + }, StatementWithPVD::Valid(hash) => write!(f, "Valid: {:?}", hash), } } @@ -570,7 +571,7 @@ impl TryFrom>> for Proof { fn try_from(input: Vec>) -> Result { if input.len() > MERKLE_PROOF_MAX_DEPTH { - return Err(Self::Error::MerkleProofDepthExceeded(input.len())) + return Err(Self::Error::MerkleProofDepthExceeded(input.len())); } let mut out = Vec::new(); for element in input.into_iter() { diff --git a/polkadot/node/service/src/grandpa_support.rs b/polkadot/node/service/src/grandpa_support.rs index 729dbfde5c76b..4dc617af54b6f 100644 --- a/polkadot/node/service/src/grandpa_support.rs +++ b/polkadot/node/service/src/grandpa_support.rs @@ -47,7 +47,7 @@ where } if *target_header.number() == target_number { - return Ok((target_hash, target_number)) + return Ok((target_hash, target_number)); } target_hash = *target_header.parent_hash(); diff --git a/polkadot/node/service/src/lib.rs b/polkadot/node/service/src/lib.rs index 6dcdec07ca84b..847773a909ffe 100644 --- a/polkadot/node/service/src/lib.rs +++ b/polkadot/node/service/src/lib.rs @@ -1352,7 +1352,7 @@ pub fn new_chain_ops( } else if config.chain_spec.is_kusama() { chain_ops!(config, jaeger_agent, None) } else if config.chain_spec.is_westend() { - return chain_ops!(config, jaeger_agent, None) + return chain_ops!(config, jaeger_agent, None); } else { chain_ops!(config, jaeger_agent, None) } @@ -1398,7 +1398,7 @@ pub fn revert_backend( let revertible = blocks.min(best_number - finalized); if revertible == 0 { - return Ok(()) + return Ok(()); } let number = best_number - revertible; diff --git a/polkadot/node/service/src/parachains_db/upgrade.rs b/polkadot/node/service/src/parachains_db/upgrade.rs index d22eebb5c8d4e..2251c9908290a 100644 --- a/polkadot/node/service/src/parachains_db/upgrade.rs +++ b/polkadot/node/service/src/parachains_db/upgrade.rs @@ -85,7 +85,7 @@ pub(crate) fn try_upgrade_db( remove_file_lock(&db_path); if version == target_version { - return Ok(()) + return Ok(()); } } @@ -440,7 +440,7 @@ pub fn remove_file_lock(path: &std::path::Path) { Err(error) => match error.kind() { ErrorKind::WouldBlock => { sleep(Duration::from_millis(100)); - continue + continue; }, _ => return, }, diff --git a/polkadot/node/service/src/relay_chain_selection.rs b/polkadot/node/service/src/relay_chain_selection.rs index 5fae6a96de4ea..eaced24a304d7 100644 --- a/polkadot/node/service/src/relay_chain_selection.rs +++ b/polkadot/node/service/src/relay_chain_selection.rs @@ -416,7 +416,7 @@ where "`finality_target` max number is less than target number", ); } - return Ok(target_hash) + return Ok(target_hash); } // find the current number. let subchain_header = self.block_header(subchain_head)?; @@ -504,7 +504,7 @@ where subchain_number, "Mismatch of anticipated block descriptions and block number difference.", ); - return Ok(target_hash) + return Ok(target_hash); } // 3. Constrain according to disputes: let (tx, rx) = oneshot::channel(); @@ -541,7 +541,7 @@ where // are not finalizing something that is being disputed or has been concluded // as invalid. We will be conservative here and not vote for finality above // the ancestor passed in. - return Ok(target_hash) + return Ok(target_hash); }, }; (lag, subchain_head) diff --git a/polkadot/node/service/src/tests.rs b/polkadot/node/service/src/tests.rs index 26c8083185d84..fd9f0e82bb2bf 100644 --- a/polkadot/node/service/src/tests.rs +++ b/polkadot/node/service/src/tests.rs @@ -160,7 +160,7 @@ impl TestChainStorage { while let Some(block) = self.blocks_by_hash.get(&block_hash) { if minimum_block_number >= block.number { - break + break; } if !self.approved_blocks.contains(&block_hash) { highest_approved_ancestor = None; @@ -192,7 +192,7 @@ impl TestChainStorage { highest_approved_block_hash: Hash, ) -> Option { if self.disputed_blocks.is_empty() { - return Some(highest_approved_block_hash) + return Some(highest_approved_block_hash); } let mut undisputed_chain = Some(highest_approved_block_hash); @@ -203,7 +203,7 @@ impl TestChainStorage { undisputed_chain = Some(*next); } if block.number() == &base_blocknumber { - break + break; } block_hash = *next; } @@ -359,7 +359,7 @@ async fn test_skeleton( ); if best_chain_containing_block.is_none() { - return + return; } gum::trace!("approved ancestor response: {:?}", undisputed_chain); diff --git a/polkadot/node/service/src/workers.rs b/polkadot/node/service/src/workers.rs index b35bb8302fdc4..7d2893b534879 100644 --- a/polkadot/node/service/src/workers.rs +++ b/polkadot/node/service/src/workers.rs @@ -63,14 +63,14 @@ pub fn determine_workers_paths( given_workers_path, current_exe_path, workers_names, - }) + }); } else if workers_paths.len() > 1 { log::warn!("multiple sets of worker binaries found ({:?})", workers_paths,); } let (prep_worker_path, exec_worker_path) = workers_paths.swap_remove(0); if !prep_worker_path.is_executable() || !exec_worker_path.is_executable() { - return Err(Error::InvalidWorkerBinaries { prep_worker_path, exec_worker_path }) + return Err(Error::InvalidWorkerBinaries { prep_worker_path, exec_worker_path }); } // Do the version check. @@ -81,7 +81,7 @@ pub fn determine_workers_paths( worker_version, node_version, worker_path: prep_worker_path, - }) + }); } let worker_version = polkadot_node_core_pvf::get_worker_version(&exec_worker_path)?; @@ -90,7 +90,7 @@ pub fn determine_workers_paths( worker_version, node_version, worker_path: exec_worker_path, - }) + }); } } else { log::warn!("Skipping node/worker version checks. This could result in incorrect behavior in PVF workers."); @@ -109,7 +109,7 @@ fn list_workers_paths( log::trace!("Using explicitly provided workers path {:?}", path); if path.is_executable() { - return Ok(vec![(path.clone(), path)]) + return Ok(vec![(path.clone(), path)]); } let (prep_worker, exec_worker) = build_worker_paths(path, workers_names); @@ -119,7 +119,7 @@ fn list_workers_paths( Ok(vec![(prep_worker, exec_worker)]) } else { Ok(vec![]) - } + }; } // Workers path not provided, check all possible valid locations. diff --git a/polkadot/node/subsystem-bench/src/approval/message_generator.rs b/polkadot/node/subsystem-bench/src/approval/message_generator.rs index a710340132476..55092ca7c8654 100644 --- a/polkadot/node/subsystem-bench/src/approval/message_generator.rs +++ b/polkadot/node/subsystem-bench/src/approval/message_generator.rs @@ -336,10 +336,12 @@ impl PeerMessagesGenerator { let assigned_cores = match &assignment.cert().kind { approval::v2::AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield } => core_bitfield.iter_ones().map(|val| CoreIndex::from(val as u32)).collect_vec(), - approval::v2::AssignmentCertKindV2::RelayVRFDelay { core_index } => - vec![*core_index], - approval::v2::AssignmentCertKindV2::RelayVRFModulo { sample: _ } => - vec![core_index], + approval::v2::AssignmentCertKindV2::RelayVRFDelay { core_index } => { + vec![*core_index] + }, + approval::v2::AssignmentCertKindV2::RelayVRFModulo { sample: _ } => { + vec![core_index] + }, }; let bitfiled: CoreBitfield = assigned_cores.clone().try_into().unwrap(); diff --git a/polkadot/node/subsystem-bench/src/approval/test_message.rs b/polkadot/node/subsystem-bench/src/approval/test_message.rs index 8aaabc3426c80..dab2c93ff837d 100644 --- a/polkadot/node/subsystem-bench/src/approval/test_message.rs +++ b/polkadot/node/subsystem-bench/src/approval/test_message.rs @@ -139,7 +139,7 @@ impl TestMessageInfo { if self.is_approval() { match &self.msg { protocol_v3::ApprovalDistributionMessage::Assignments(_) => todo!(), - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => + protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => { for approval in approvals { for candidate_index in approval.candidate_indices.iter_ones() { state @@ -150,7 +150,8 @@ impl TestMessageInfo { .unwrap() .store(true, std::sync::atomic::Ordering::SeqCst); } - }, + } + }, } } } @@ -179,18 +180,20 @@ impl TestMessageInfo { pub fn candidate_indices(&self) -> HashSet { let mut unique_candidate_indicies = HashSet::new(); match &self.msg { - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) => + protocol_v3::ApprovalDistributionMessage::Assignments(assignments) => { for (_assignment, candidate_indices) in assignments { for candidate_index in candidate_indices.iter_ones() { unique_candidate_indicies.insert(candidate_index); } - }, - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => + } + }, + protocol_v3::ApprovalDistributionMessage::Approvals(approvals) => { for approval in approvals { for candidate_index in approval.candidate_indices.iter_ones() { unique_candidate_indicies.insert(candidate_index); } - }, + } + }, } unique_candidate_indicies } diff --git a/polkadot/node/subsystem-bench/src/core/display.rs b/polkadot/node/subsystem-bench/src/core/display.rs index 13a349382e2fd..af975b4775115 100644 --- a/polkadot/node/subsystem-bench/src/core/display.rs +++ b/polkadot/node/subsystem-bench/src/core/display.rs @@ -110,11 +110,11 @@ impl Display for TestMetric { fn check_metric_family(mf: &MetricFamily) -> bool { if mf.get_metric().is_empty() { gum::error!(target: LOG_TARGET, "MetricFamily has no metrics: {:?}", mf); - return false + return false; } if mf.get_name().is_empty() { gum::error!(target: LOG_TARGET, "MetricFamily has no name: {:?}", mf); - return false + return false; } true @@ -125,7 +125,7 @@ pub fn parse_metrics(registry: &Registry) -> MetricCollection { let mut test_metrics = Vec::new(); for mf in metric_families { if !check_metric_family(&mf) { - continue + continue; } let name: String = mf.get_name().into(); diff --git a/polkadot/node/subsystem-bench/src/core/environment.rs b/polkadot/node/subsystem-bench/src/core/environment.rs index ca4c41cf45f99..4f24fcd850eb5 100644 --- a/polkadot/node/subsystem-bench/src/core/environment.rs +++ b/polkadot/node/subsystem-bench/src/core/environment.rs @@ -343,7 +343,7 @@ impl TestEnvironment { gum::debug!(target: LOG_TARGET, metric_name, current_value, "Waiting for metric"); if condition(current_value) { - break + break; } // Check value every 50ms. tokio::time::sleep(std::time::Duration::from_millis(50)).await; diff --git a/polkadot/node/subsystem-bench/src/core/mock/av_store.rs b/polkadot/node/subsystem-bench/src/core/mock/av_store.rs index 0a7725c91e042..c256aaf14a828 100644 --- a/polkadot/node/subsystem-bench/src/core/mock/av_store.rs +++ b/polkadot/node/subsystem-bench/src/core/mock/av_store.rs @@ -168,7 +168,7 @@ impl MockAvailabilityStore { match msg { orchestra::FromOrchestra::Signal(signal) => if signal == OverseerSignal::Conclude { - return + return; }, orchestra::FromOrchestra::Communication { msg } => match msg { AvailabilityStoreMessage::QueryAvailableData(candidate_hash, tx) => { diff --git a/polkadot/node/subsystem-bench/src/core/mock/chain_api.rs b/polkadot/node/subsystem-bench/src/core/mock/chain_api.rs index bee15c3cefdfb..53530cb56dba5 100644 --- a/polkadot/node/subsystem-bench/src/core/mock/chain_api.rs +++ b/polkadot/node/subsystem-bench/src/core/mock/chain_api.rs @@ -67,7 +67,7 @@ impl MockChainApi { match msg { orchestra::FromOrchestra::Signal(signal) => if signal == OverseerSignal::Conclude { - return + return; }, orchestra::FromOrchestra::Communication { msg } => { gum::debug!(target: LOG_TARGET, msg=?msg, "recv message"); diff --git a/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs b/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs index 4682c7ec79ae3..e5237d97aa7b2 100644 --- a/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs +++ b/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs @@ -100,7 +100,7 @@ impl MockNetworkBridgeTx { match subsystem_message { orchestra::FromOrchestra::Signal(signal) => if signal == OverseerSignal::Conclude { - return + return; }, orchestra::FromOrchestra::Communication { msg } => match msg { NetworkBridgeTxMessage::SendRequests(requests, _if_disconnected) => { @@ -115,7 +115,7 @@ impl MockNetworkBridgeTx { .into_response_sender() .send(Err(RequestFailure::NotConnected)) .expect("send never fails"); - continue + continue; } let peer_message = diff --git a/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs b/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs index 0dd76efcbaf0d..0ff92083c2a4e 100644 --- a/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs +++ b/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs @@ -133,7 +133,7 @@ impl MockRuntimeApi { match msg { orchestra::FromOrchestra::Signal(signal) => if signal == OverseerSignal::Conclude { - return + return; }, orchestra::FromOrchestra::Communication { msg } => { gum::debug!(target: LOG_TARGET, msg=?msg, "recv message"); diff --git a/polkadot/node/subsystem-bench/src/core/network.rs b/polkadot/node/subsystem-bench/src/core/network.rs index e9124726d7c06..f0c994f4737fc 100644 --- a/polkadot/node/subsystem-bench/src/core/network.rs +++ b/polkadot/node/subsystem-bench/src/core/network.rs @@ -134,7 +134,7 @@ impl RateLimit { self.credits -= amount as isize; if self.credits >= 0 { - return + return; } while self.credits < 0 { @@ -370,7 +370,7 @@ impl NetworkInterface { tx_network.inc_sent(size); } else { gum::info!(target: LOG_TARGET, "Downlink channel closed, network interface task exiting"); - break + break; } } } @@ -861,7 +861,7 @@ impl NetworkEmulatorHandle { if !dst_peer.is_connected() { gum::warn!(target: LOG_TARGET, "Attempted to send message from a peer not connected to our node, operation ignored"); - return Err(EmulatedPeerError::NotConnected) + return Err(EmulatedPeerError::NotConnected); } dst_peer.handle().send_message(message); @@ -878,7 +878,7 @@ impl NetworkEmulatorHandle { if !dst_peer.is_connected() { gum::warn!(target: LOG_TARGET, "Attempted to send request from a peer not connected to our node, operation ignored"); - return Err(EmulatedPeerError::NotConnected) + return Err(EmulatedPeerError::NotConnected); } dst_peer.handle().send_request(request); diff --git a/polkadot/node/subsystem-bench/src/subsystem-bench.rs b/polkadot/node/subsystem-bench/src/subsystem-bench.rs index 0803f175474e6..80efe8167de26 100644 --- a/polkadot/node/subsystem-bench/src/subsystem-bench.rs +++ b/polkadot/node/subsystem-bench/src/subsystem-bench.rs @@ -135,7 +135,7 @@ impl BenchCli { fn launch(self) -> eyre::Result<()> { let is_valgrind_running = valgrind::is_valgrind_running(); if !is_valgrind_running && self.cache_misses { - return valgrind::relaunch_in_valgrind_mode() + return valgrind::relaunch_in_valgrind_mode(); } let agent_running = if self.profile { diff --git a/polkadot/node/subsystem-test-helpers/src/lib.rs b/polkadot/node/subsystem-test-helpers/src/lib.rs index 6c1ac86c4507b..1d64b306ce431 100644 --- a/polkadot/node/subsystem-test-helpers/src/lib.rs +++ b/polkadot/node/subsystem-test-helpers/src/lib.rs @@ -210,7 +210,7 @@ where async fn try_recv(&mut self) -> Result>, ()> { if let Some(msg) = self.message_buffer.pop_front() { - return Ok(Some(msg)) + return Ok(Some(msg)); } match poll!(self.rx.next()) { Poll::Ready(Some(msg)) => Ok(Some(msg)), @@ -221,7 +221,7 @@ where async fn recv(&mut self) -> SubsystemResult> { if let Some(msg) = self.message_buffer.pop_front() { - return Ok(msg) + return Ok(msg); } self.rx .next() @@ -237,7 +237,7 @@ where .await .ok_or_else(|| SubsystemError::Context("Receiving end closed".to_owned()))?; if let FromOrchestra::Signal(sig) = msg { - return Ok(sig) + return Ok(sig); } else { self.message_buffer.push_back(msg) } diff --git a/polkadot/node/subsystem-util/src/backing_implicit_view.rs b/polkadot/node/subsystem-util/src/backing_implicit_view.rs index a14536a17666c..15d041a478167 100644 --- a/polkadot/node/subsystem-util/src/backing_implicit_view.rs +++ b/polkadot/node/subsystem-util/src/backing_implicit_view.rs @@ -65,7 +65,7 @@ impl AllowedRelayParents { }; if base_number < para_min { - return &[] + return &[]; } let diff = base_number - para_min; @@ -128,7 +128,7 @@ impl View { Sender: SubsystemSender, { if self.leaves.contains_key(&leaf_hash) { - return Err(FetchError::AlreadyKnown) + return Err(FetchError::AlreadyKnown); } let res = fetch_fresh_leaf_and_insert_ancestry( @@ -163,7 +163,7 @@ impl View { let mut removed = Vec::new(); if self.leaves.remove(&leaf_hash).is_none() { - return removed + return removed; } // Prune everything before the minimum out of all leaves, @@ -368,7 +368,7 @@ where ancestry.push(next_ancestor_hash); if next_ancestor_number == 0 { - break + break; } next_ancestor_number -= 1; diff --git a/polkadot/node/subsystem-util/src/database.rs b/polkadot/node/subsystem-util/src/database.rs index be5110c4aaba7..379a817c3eae9 100644 --- a/polkadot/node/subsystem-util/src/database.rs +++ b/polkadot/node/subsystem-util/src/database.rs @@ -61,7 +61,7 @@ pub mod kvdb_impl { if let DBOp::DeletePrefix { col, .. } = op { if !self.is_indexed_column(*col) { pass = false; - break + break; } } } @@ -184,14 +184,14 @@ pub mod paritydb_impl { prefix: &'a [u8], ) -> Box> + 'a> { if prefix.len() == 0 { - return self.iter(col) + return self.iter(col); } let mut iter = match self.db.iter(col as u8) { Ok(iter) => iter, Err(e) => return Box::new(std::iter::once(map_err(Err(e)))), }; if let Err(e) = iter.seek(prefix) { - return Box::new(std::iter::once(map_err(Err(e)))) + return Box::new(std::iter::once(map_err(Err(e)))); } Box::new(std::iter::from_fn(move || { iter.next().transpose().and_then(|r| { @@ -210,7 +210,7 @@ pub mod paritydb_impl { if let Some((prefix_iter, col, prefix)) = current_prefix_iter { if let Some((key, _value)) = handle_err(prefix_iter.next()) { if key.starts_with(prefix) { - return Some((*col, key.to_vec(), None)) + return Some((*col, key.to_vec(), None)); } } *current_prefix_iter = None; @@ -225,9 +225,9 @@ pub mod paritydb_impl { let mut iter = handle_err(self.db.iter(col)); handle_err(iter.seek(&prefix[..])); *current_prefix_iter = Some((iter, col, prefix.to_vec())); - continue + continue; }, - } + }; }); // Locking is required due to possible racy change of the content of a deleted prefix. diff --git a/polkadot/node/subsystem-util/src/determine_new_blocks.rs b/polkadot/node/subsystem-util/src/determine_new_blocks.rs index 9ffb5d9757f89..877371555529a 100644 --- a/polkadot/node/subsystem-util/src/determine_new_blocks.rs +++ b/polkadot/node/subsystem-util/src/determine_new_blocks.rs @@ -52,7 +52,7 @@ where let before_relevant = header.number < min_block_needed; if already_known || before_relevant { - return Ok(Vec::new()) + return Ok(Vec::new()); } } @@ -61,7 +61,7 @@ where // Early exit if the parent hash is in the DB or no further blocks // are needed. if is_known(&header.parent_hash)? || header.number == min_block_needed { - return Ok(ancestry) + return Ok(ancestry); } 'outer: loop { @@ -133,7 +133,7 @@ where // be skipped. Any failure at this stage means we'll just ignore those blocks // as the chain DB has failed us. if batch_headers.len() != batch_hashes.len() { - break 'outer + break 'outer; } batch_headers }; @@ -145,13 +145,13 @@ where let is_terminating = header.number == min_block_needed; if is_known || !is_relevant { - break 'outer + break 'outer; } ancestry.push((hash, header)); if is_terminating { - break 'outer + break 'outer; } } } diff --git a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs index c7b91bffb3d70..d22b2928908ef 100644 --- a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs +++ b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs @@ -267,7 +267,7 @@ impl Constraints { if let Some(HrmpWatermarkUpdate::Trunk(hrmp_watermark)) = modifications.hrmp_watermark { // head updates are always valid. if self.hrmp_inbound.valid_watermarks.iter().all(|w| w != &hrmp_watermark) { - return Err(ModificationError::DisallowedHrmpWatermark(hrmp_watermark)) + return Err(ModificationError::DisallowedHrmpWatermark(hrmp_watermark)); } } @@ -290,7 +290,7 @@ impl Constraints { messages_submitted: outbound_hrmp_mod.messages_submitted, })?; } else { - return Err(ModificationError::NoSuchHrmpChannel(*id)) + return Err(ModificationError::NoSuchHrmpChannel(*id)); } } @@ -317,7 +317,7 @@ impl Constraints { })?; if self.future_validation_code.is_none() && modifications.code_upgrade_applied { - return Err(ModificationError::AppliedNonexistentCodeUpgrade) + return Err(ModificationError::AppliedNonexistentCodeUpgrade); } Ok(()) @@ -348,7 +348,7 @@ impl Constraints { }, HrmpWatermarkUpdate::Trunk(n) => { // Trunk update landing on disallowed watermark is not OK. - return Err(ModificationError::DisallowedHrmpWatermark(*n)) + return Err(ModificationError::DisallowedHrmpWatermark(*n)); }, }, } @@ -374,7 +374,7 @@ impl Constraints { messages_submitted: outbound_hrmp_mod.messages_submitted, })?; } else { - return Err(ModificationError::NoSuchHrmpChannel(*id)) + return Err(ModificationError::NoSuchHrmpChannel(*id)); } } @@ -397,7 +397,7 @@ impl Constraints { return Err(ModificationError::DmpMessagesUnderflow { messages_remaining: new.dmp_remaining_messages.len(), messages_processed: modifications.dmp_messages_processed, - }) + }); } else { new.dmp_remaining_messages = new.dmp_remaining_messages[modifications.dmp_messages_processed..].to_vec(); @@ -664,7 +664,7 @@ impl<'a> Fragment<'a> { if last >= message.recipient { return Err( FragmentValidityError::HrmpMessagesDescendingOrDuplicate(i), - ) + ); } } @@ -753,21 +753,21 @@ fn validate_against_constraints( return Err(FragmentValidityError::PersistedValidationDataMismatch( expected_pvd, candidate.persisted_validation_data.clone(), - )) + )); } if constraints.validation_code_hash != candidate.validation_code_hash { return Err(FragmentValidityError::ValidationCodeMismatch( constraints.validation_code_hash, candidate.validation_code_hash, - )) + )); } if relay_parent.number < constraints.min_relay_parent_number { return Err(FragmentValidityError::RelayParentTooOld( constraints.min_relay_parent_number, relay_parent.number, - )) + )); } if candidate.commitments.new_validation_code.is_some() { @@ -788,7 +788,7 @@ fn validate_against_constraints( return Err(FragmentValidityError::CodeSizeTooLarge( constraints.max_code_size, announced_code_size, - )) + )); } if modifications.dmp_messages_processed == 0 { @@ -797,7 +797,7 @@ fn validate_against_constraints( .get(0) .map_or(false, |&msg_sent_at| msg_sent_at <= relay_parent.number) { - return Err(FragmentValidityError::DmpAdvancementRule) + return Err(FragmentValidityError::DmpAdvancementRule); } } @@ -805,14 +805,14 @@ fn validate_against_constraints( return Err(FragmentValidityError::HrmpMessagesPerCandidateOverflow { messages_allowed: constraints.max_hrmp_num_per_candidate, messages_submitted: candidate.commitments.horizontal_messages.len(), - }) + }); } if candidate.commitments.upward_messages.len() > constraints.max_ump_num_per_candidate { return Err(FragmentValidityError::UmpMessagesPerCandidateOverflow { messages_allowed: constraints.max_ump_num_per_candidate, messages_submitted: candidate.commitments.upward_messages.len(), - }) + }); } constraints diff --git a/polkadot/node/subsystem-util/src/lib.rs b/polkadot/node/subsystem-util/src/lib.rs index f13beb3502fc2..90a571fc0f542 100644 --- a/polkadot/node/subsystem-util/src/lib.rs +++ b/polkadot/node/subsystem-util/src/lib.rs @@ -370,7 +370,7 @@ pub fn signing_key_and_index<'a>( ) -> Option<(ValidatorId, ValidatorIndex)> { for (i, v) in validators.into_iter().enumerate() { if keystore.has_keys(&[(v.to_raw_vec(), ValidatorId::ID)]) { - return Some((v.clone(), ValidatorIndex(i as _))) + return Some((v.clone(), ValidatorIndex(i as _))); } } None @@ -427,7 +427,7 @@ pub fn choose_random_subset_with_rng bool, R: rand::Rng>( if i >= min || v.len() <= i { v.truncate(i); - return + return; } v[i..].shuffle(rng); diff --git a/polkadot/node/subsystem-util/src/runtime/mod.rs b/polkadot/node/subsystem-util/src/runtime/mod.rs index 481625acb3219..22ddbc62039c5 100644 --- a/polkadot/node/subsystem-util/src/runtime/mod.rs +++ b/polkadot/node/subsystem-util/src/runtime/mod.rs @@ -292,9 +292,9 @@ impl RuntimeInfo { }) }); let info = ValidatorInfo { our_index: Some(our_index), our_group }; - return Ok(info) + return Ok(info); } - return Ok(ValidatorInfo { our_index: None, our_group: None }) + return Ok(ValidatorInfo { our_index: None, our_group: None }); } /// Get our `ValidatorIndex`. @@ -307,7 +307,7 @@ impl RuntimeInfo { let keystore = self.keystore.as_ref()?; for (i, v) in validators.iter().enumerate() { if Keystore::has_keys(&**keystore, &[(v.to_raw_vec(), ValidatorId::ID)]) { - return Some(ValidatorIndex(i as u32)) + return Some(ValidatorIndex(i as u32)); } } None diff --git a/polkadot/node/test/service/src/lib.rs b/polkadot/node/test/service/src/lib.rs index d0669b2afbde6..56e0ca2a46b2a 100644 --- a/polkadot/node/test/service/src/lib.rs +++ b/polkadot/node/test/service/src/lib.rs @@ -342,7 +342,7 @@ impl PolkadotTestNode { while let Some(notification) = import_notification_stream.next().await { blocks.insert(notification.hash); if blocks.len() == count { - break + break; } } } diff --git a/polkadot/node/tracking-allocator/src/lib.rs b/polkadot/node/tracking-allocator/src/lib.rs index 33f110ce71197..3f9bd67e6a53b 100644 --- a/polkadot/node/tracking-allocator/src/lib.rs +++ b/polkadot/node/tracking-allocator/src/lib.rs @@ -59,7 +59,7 @@ impl Spinlock { .compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed) .is_ok() { - return SpinlockGuard { lock: self } + return SpinlockGuard { lock: self }; } // We failed to acquire the lock; wait until it's unlocked. // diff --git a/polkadot/node/zombienet-backchannel/src/lib.rs b/polkadot/node/zombienet-backchannel/src/lib.rs index fa9218d2d3502..98de416a1cc79 100644 --- a/polkadot/node/zombienet-backchannel/src/lib.rs +++ b/polkadot/node/zombienet-backchannel/src/lib.rs @@ -98,7 +98,7 @@ impl ZombienetBackchannel { backchannel_port.parse::().map_err(|_| BackchannelError::InvalidPort)?; // validate non empty string for host if backchannel_host.trim().is_empty() { - return Err(BackchannelError::InvalidHost) + return Err(BackchannelError::InvalidHost); }; let ws_url = format!("ws://{}:{}/ws", backchannel_host, backchannel_port); @@ -118,7 +118,7 @@ impl ZombienetBackchannel { Ok(backchannel_item) => if tx1.send(backchannel_item).is_err() { gum::error!(target: ZOMBIENET, "Error sending through the channel"); - return + return; }, Err(_) => { gum::error!(target: ZOMBIENET, "Invalid payload received"); @@ -141,7 +141,7 @@ impl ZombienetBackchannel { }); *zombienet_bkc = Some(ZombienetBackchannel { broadcast_tx: tx, ws_tx: tx_relay }); - return Ok(()) + return Ok(()); } Err(BackchannelError::AlreadyInitialized) diff --git a/polkadot/parachain/test-parachains/adder/collator/src/lib.rs b/polkadot/parachain/test-parachains/adder/collator/src/lib.rs index 5f62ae34caefa..b71030d714f85 100644 --- a/polkadot/parachain/test-parachains/adder/collator/src/lib.rs +++ b/polkadot/parachain/test-parachains/adder/collator/src/lib.rs @@ -222,7 +222,7 @@ impl Collator { let current_block = self.state.lock().unwrap().best_block; if start_block + blocks <= current_block { - return + return; } } } @@ -238,7 +238,7 @@ impl Collator { Delay::new(Duration::from_secs(1)).await; if seconded <= seconded_collations.load(Ordering::Relaxed) { - return + return; } } } diff --git a/polkadot/parachain/test-parachains/adder/src/lib.rs b/polkadot/parachain/test-parachains/adder/src/lib.rs index 4cf1ba8ac971d..c27d6e76d6fa0 100644 --- a/polkadot/parachain/test-parachains/adder/src/lib.rs +++ b/polkadot/parachain/test-parachains/adder/src/lib.rs @@ -93,7 +93,7 @@ pub fn execute( assert_eq!(parent_hash, parent_head.hash()); if hash_state(block_data.state) != parent_head.post_state { - return Err(StateMismatch) + return Err(StateMismatch); } let new_state = block_data.state.wrapping_add(block_data.add); diff --git a/polkadot/parachain/test-parachains/undying/collator/src/lib.rs b/polkadot/parachain/test-parachains/undying/collator/src/lib.rs index 3c869233182f8..a7fd4c4104863 100644 --- a/polkadot/parachain/test-parachains/undying/collator/src/lib.rs +++ b/polkadot/parachain/test-parachains/undying/collator/src/lib.rs @@ -233,7 +233,7 @@ impl Collator { let parent = match HeadData::decode(&mut &validation_data.parent_head.0[..]) { Err(err) => { log::error!("Requested to build on top of malformed head-data: {:?}", err); - return futures::future::ready(None).boxed() + return futures::future::ready(None).boxed(); }, Ok(p) => p, }; @@ -241,7 +241,7 @@ impl Collator { let (block_data, head_data) = match state.lock().unwrap().advance(parent.clone()) { Err(err) => { log::error!("Unable to build on top of {:?}: {:?}", parent, err); - return futures::future::ready(None).boxed() + return futures::future::ready(None).boxed(); }, Ok(x) => x, }; @@ -310,7 +310,7 @@ impl Collator { let current_block = self.state.lock().unwrap().best_block; if start_block + blocks <= current_block { - return + return; } } } @@ -326,7 +326,7 @@ impl Collator { Delay::new(Duration::from_secs(1)).await; if seconded <= seconded_collations.load(Ordering::Relaxed) { - return + return; } } } diff --git a/polkadot/parachain/test-parachains/undying/src/lib.rs b/polkadot/parachain/test-parachains/undying/src/lib.rs index abd88726b7fcb..f4969687455a2 100644 --- a/polkadot/parachain/test-parachains/undying/src/lib.rs +++ b/polkadot/parachain/test-parachains/undying/src/lib.rs @@ -141,7 +141,7 @@ pub fn execute( hash_state(&block_data.state), parent_head.post_state, ); - return Err(StateMismatch) + return Err(StateMismatch); } // We need to clone the block data as the fn will mutate it's state. diff --git a/polkadot/primitives/src/v6/executor_params.rs b/polkadot/primitives/src/v6/executor_params.rs index 112a529f62b05..26c8e2326a199 100644 --- a/polkadot/primitives/src/v6/executor_params.rs +++ b/polkadot/primitives/src/v6/executor_params.rs @@ -178,7 +178,7 @@ impl ExecutorParams { for param in &self.0 { if let ExecutorParam::PvfPrepTimeout(k, timeout) = param { if kind == *k { - return Some(Duration::from_millis(*timeout)) + return Some(Duration::from_millis(*timeout)); } } } @@ -190,7 +190,7 @@ impl ExecutorParams { for param in &self.0 { if let ExecutorParam::PvfExecTimeout(k, timeout) = param { if kind == *k { - return Some(Duration::from_millis(*timeout)) + return Some(Duration::from_millis(*timeout)); } } } @@ -201,7 +201,7 @@ impl ExecutorParams { pub fn prechecking_max_memory(&self) -> Option { for param in &self.0 { if let ExecutorParam::PrecheckingMaxMemory(limit) = param { - return Some(*limit) + return Some(*limit); } } None @@ -217,7 +217,7 @@ impl ExecutorParams { macro_rules! check { ($param:ident, $val:expr $(,)?) => { if seen.contains_key($param) { - return Err(DuplicatedParam($param)) + return Err(DuplicatedParam($param)); } seen.insert($param, $val as u64); }; @@ -225,10 +225,10 @@ impl ExecutorParams { // should check existence before range ($param:ident, $val:expr, $out_of_limit:expr $(,)?) => { if seen.contains_key($param) { - return Err(DuplicatedParam($param)) + return Err(DuplicatedParam($param)); } if $out_of_limit { - return Err(OutsideLimit($param)) + return Err(OutsideLimit($param)); } seen.insert($param, $val as u64); }; @@ -292,7 +292,7 @@ impl ExecutorParams { seen.get("StackNativeMax").or(Some(&(DEFAULT_NATIVE_STACK_MAX as u64))), ) { if *nm < 128 * *lm { - return Err(IncompatibleValues("StackLogicalMax", "StackNativeMax")) + return Err(IncompatibleValues("StackLogicalMax", "StackNativeMax")); } } @@ -303,7 +303,7 @@ impl ExecutorParams { .or(Some(&DEFAULT_LENIENT_PREPARATION_TIMEOUT_MS)), ) { if *precheck >= *lenient { - return Err(IncompatibleValues("PvfPrepKind::Precheck", "PvfPrepKind::Prepare")) + return Err(IncompatibleValues("PvfPrepKind::Precheck", "PvfPrepKind::Prepare")); } } @@ -313,7 +313,7 @@ impl ExecutorParams { .or(Some(&DEFAULT_APPROVAL_EXECUTION_TIMEOUT_MS)), ) { if *backing >= *approval { - return Err(IncompatibleValues("PvfExecKind::Backing", "PvfExecKind::Approval")) + return Err(IncompatibleValues("PvfExecKind::Backing", "PvfExecKind::Approval")); } } diff --git a/polkadot/primitives/src/v6/metrics.rs b/polkadot/primitives/src/v6/metrics.rs index 97f7678e43737..1f0ab6843a08f 100644 --- a/polkadot/primitives/src/v6/metrics.rs +++ b/polkadot/primitives/src/v6/metrics.rs @@ -42,7 +42,7 @@ pub struct RuntimeMetricUpdate { } fn vec_to_str<'a>(v: &'a Vec, default: &'static str) -> &'a str { - return sp_std::str::from_utf8(v).unwrap_or(default) + return sp_std::str::from_utf8(v).unwrap_or(default); } impl RuntimeMetricLabels { diff --git a/polkadot/primitives/src/v6/mod.rs b/polkadot/primitives/src/v6/mod.rs index 4938d20d2d1bd..92d70a4f4a9e3 100644 --- a/polkadot/primitives/src/v6/mod.rs +++ b/polkadot/primitives/src/v6/mod.rs @@ -753,11 +753,11 @@ pub fn check_candidate_backing + Clone + Encode>( validator_lookup: impl Fn(usize) -> Option, ) -> Result { if backed.validator_indices.len() != group_len { - return Err(()) + return Err(()); } if backed.validity_votes.len() > group_len { - return Err(()) + return Err(()); } // this is known, even in runtime, to be blake2-256. @@ -778,12 +778,12 @@ pub fn check_candidate_backing + Clone + Encode>( if sig.verify(&payload[..], &validator_id) { signed += 1; } else { - return Err(()) + return Err(()); } } if signed != backed.validity_votes.len() { - return Err(()) + return Err(()); } Ok(signed) @@ -857,10 +857,10 @@ impl GroupRotationInfo { /// `core_index` should be less than `cores`, which is capped at `u32::max()`. pub fn group_for_core(&self, core_index: CoreIndex, cores: usize) -> GroupIndex { if self.group_rotation_frequency == 0 { - return GroupIndex(core_index.0) + return GroupIndex(core_index.0); } if cores == 0 { - return GroupIndex(0) + return GroupIndex(0); } let cores = sp_std::cmp::min(cores, u32::MAX as usize); @@ -879,10 +879,10 @@ impl GroupRotationInfo { /// `core_index` should be less than `cores`, which is capped at `u32::max()`. pub fn core_for_group(&self, group_index: GroupIndex, cores: usize) -> CoreIndex { if self.group_rotation_frequency == 0 { - return CoreIndex(group_index.0) + return CoreIndex(group_index.0); } if cores == 0 { - return CoreIndex(0) + return CoreIndex(0); } let cores = sp_std::cmp::min(cores, u32::MAX as usize); @@ -1617,7 +1617,7 @@ impl parity_scale_codec::Decode for CompactStatement { ) -> Result { let maybe_magic = <[u8; 4]>::decode(input)?; if maybe_magic != BACKING_STATEMENT_MAGIC { - return Err(parity_scale_codec::Error::from("invalid magic string")) + return Err(parity_scale_codec::Error::from("invalid magic string")); } Ok(match CompactStatementInner::decode(input)? { diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index 3419e3497f7d4..69334bf8c996a 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -245,7 +245,7 @@ pub mod pallet { if let Some((lease_period, first_block)) = Self::lease_period_index(n) { // If we're beginning a new lease period then handle that. if first_block { - return Self::manage_lease_period_start(lease_period) + return Self::manage_lease_period_start(lease_period); } } diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index 46ab673a7a0cb..4d8b4ff288821 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -342,10 +342,10 @@ impl Auctioneer> for Pallet { let sample_length = T::SampleLength::get().max(One::one()); let sample = after_early_end / sample_length; let sub_sample = after_early_end % sample_length; - return AuctionStatus::EndingPeriod(sample, sub_sample) + return AuctionStatus::EndingPeriod(sample, sub_sample); } else { // This is safe because of the comparison operator above - return AuctionStatus::VrfDelay(after_early_end - ending_period) + return AuctionStatus::VrfDelay(after_early_end - ending_period); } } @@ -562,7 +562,7 @@ impl Pallet { #[allow(deprecated)] Winning::::remove_all(None); AuctionInfo::::kill(); - return Some((res, lease_period_index)) + return Some((res, lease_period_index)); } } } @@ -789,11 +789,11 @@ mod tests { let (current_lease_period, _) = Self::lease_period_index(now).ok_or(LeaseError::NoLeasePeriod)?; if period_begin < current_lease_period { - return Err(LeaseError::AlreadyEnded) + return Err(LeaseError::AlreadyEnded); } for period in period_begin..(period_begin + period_count) { if leases.contains_key(&(para, period)) { - return Err(LeaseError::AlreadyLeased) + return Err(LeaseError::AlreadyLeased); } leases.insert((para, period), LeaseData { leaser: *leaser, amount }); } diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 86550ea8b4ebf..4e41fcae09352 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -557,7 +557,7 @@ impl Pallet { let vesting = Vesting::::get(&signer); if vesting.is_some() && T::VestingSchedule::vesting_balance(&dest).is_some() { - return Err(Error::::VestedBalanceExists.into()) + return Err(Error::::VestedBalanceExists.into()); } // We first need to deposit the balance to ensure that the account exists. diff --git a/polkadot/runtime/common/src/crowdloan/migration.rs b/polkadot/runtime/common/src/crowdloan/migration.rs index 5133c14ada927..a9bd1a1e4e423 100644 --- a/polkadot/runtime/common/src/crowdloan/migration.rs +++ b/polkadot/runtime/common/src/crowdloan/migration.rs @@ -118,7 +118,7 @@ pub mod crowdloan_index_migration { for (who, _amount) in leases.iter().flatten() { if *who == old_fund_account { found_lease_deposit = true; - break + break; } } if found_lease_deposit { diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 7d1b892dfa7fc..6026e0caff7ee 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -533,7 +533,7 @@ pub mod pallet { if refund_count >= T::RemoveKeysLimit::get() { // Not everyone was able to be refunded this time around. all_refunded = false; - break + break; } CurrencyOf::::transfer(&fund_account, &who, balance, AllowDeath)?; CurrencyOf::::reactivate(balance); @@ -1029,15 +1029,15 @@ mod tests { let ending_period = ending_period(); if after_early_end < ending_period { - return AuctionStatus::EndingPeriod(after_early_end, 0) + return AuctionStatus::EndingPeriod(after_early_end, 0); } else { let after_end = after_early_end - ending_period; // Optional VRF delay if after_end < vrf_delay() { - return AuctionStatus::VrfDelay(after_end) + return AuctionStatus::VrfDelay(after_end); } else { // VRF delay is done, so we just end the auction - return AuctionStatus::NotStarted + return AuctionStatus::NotStarted; } } } @@ -1122,7 +1122,7 @@ mod tests { for i in 0.. { let para: ParaId = i.into(); if TestRegistrar::::is_registered(para) { - continue + continue; } assert_ok!(TestRegistrar::::register( 1, @@ -1130,7 +1130,7 @@ mod tests { dummy_head_data(), dummy_validation_code() )); - return para + return para; } unreachable!() } diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 5450c4309e407..f1c71b1fb40af 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -315,7 +315,7 @@ pub mod pallet { // early, since swapping the same id would otherwise be a noop. if id == other { PendingSwap::::remove(id); - return Ok(()) + return Ok(()); } // Sanity check that `id` is even a para. @@ -343,7 +343,7 @@ pub mod pallet { // data. T::OnSwap::on_swap(id, other); } else { - return Err(Error::::CannotSwap.into()) + return Err(Error::::CannotSwap.into()); } Self::deposit_event(Event::::Swapped { para_id: id, other_id: other }); PendingSwap::::remove(other); @@ -1549,7 +1549,7 @@ mod benchmarking { frame_system::Origin::::Root.into(), validation_code, )); - return para + return para; } fn para_origin(id: u32) -> ParaOrigin { diff --git a/polkadot/runtime/common/src/slots/migration.rs b/polkadot/runtime/common/src/slots/migration.rs index 4b499ca7c7bd8..6f03df56788bd 100644 --- a/polkadot/runtime/common/src/slots/migration.rs +++ b/polkadot/runtime/common/src/slots/migration.rs @@ -40,7 +40,7 @@ pub mod slots_crowdloan_index_migration { "para_id={:?}, old_fund_account={:?}, fund_id={:?}, leases={:?}", para_id, old_fund_account, crowdloan.fund_index, leases, ); - break + break; } } } diff --git a/polkadot/runtime/common/src/slots/mod.rs b/polkadot/runtime/common/src/slots/mod.rs index 51bd0ba4debe6..142bb16f9744f 100644 --- a/polkadot/runtime/common/src/slots/mod.rs +++ b/polkadot/runtime/common/src/slots/mod.rs @@ -150,7 +150,7 @@ pub mod pallet { if let Some((lease_period, first_block)) = Self::lease_period_index(n) { // If we're beginning a new lease period then handle that. if first_block { - return Self::manage_lease_period_start(lease_period) + return Self::manage_lease_period_start(lease_period); } } @@ -238,7 +238,7 @@ impl Pallet { let mut parachains = Vec::new(); for (para, mut lease_periods) in Leases::::iter() { if lease_periods.is_empty() { - continue + continue; } // ^^ should never be empty since we would have deleted the entry otherwise. @@ -382,7 +382,7 @@ impl Leaser> for Pallet { // attempt. // // We bail, not giving any lease and leave it for governance to sort out. - return Err(LeaseError::AlreadyLeased) + return Err(LeaseError::AlreadyLeased); } } else if d.len() == i { // Doesn't exist. This is usual. @@ -489,7 +489,7 @@ impl Leaser> for Pallet { for slot in offset..=offset + period_count { if let Some(Some(_)) = leases.get(slot) { // If there exists any lease period, we exit early and return true. - return true + return true; } } diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 7f1100a13619a..71e39120fd616 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -111,7 +111,7 @@ where *id } else { *dest = Some(d); - return Err(NotApplicable) + return Err(NotApplicable); }; // Downward message passing. diff --git a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs index 9da81dc816cab..3e1d5aafd6e70 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs @@ -356,30 +356,30 @@ impl Pallet { let Some(queue) = descriptor.queue else { // No queue. - return + return; }; let mut next_scheduled = queue.first; if next_scheduled > now { // Not yet ready. - return + return; } // Update is needed: let update = loop { let Some(update) = CoreSchedules::::take((next_scheduled, core_idx)) else { - break None + break None; }; // Still good? if update.end_hint.map_or(true, |e| e > now) { - break Some(update) + break Some(update); } // Move on if possible: if let Some(n) = update.next_schedule { next_scheduled = n; } else { - break None + break None; } }; diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs index 1b746e88694c9..c2a69fc9eb01b 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs @@ -213,7 +213,7 @@ pub mod pallet { Pallet::::deposit_event(Event::::SpotTrafficSet { traffic: new_traffic, }); - return T::DbWeight::get().reads_writes(2, 1) + return T::DbWeight::get().reads_writes(2, 1); } }, Err(SpotTrafficCalculationErr::QueueCapacityIsZero) => { @@ -386,12 +386,12 @@ where ) -> Result { // Return early if queue has no capacity. if queue_capacity == 0 { - return Err(SpotTrafficCalculationErr::QueueCapacityIsZero) + return Err(SpotTrafficCalculationErr::QueueCapacityIsZero); } // Return early if queue size is greater than capacity. if queue_size > queue_capacity { - return Err(SpotTrafficCalculationErr::QueueSizeLargerThanCapacity) + return Err(SpotTrafficCalculationErr::QueueSizeLargerThanCapacity); } // (queue_size / queue_capacity) - target_queue_utilisation @@ -472,7 +472,7 @@ where target: LOG_TARGET, "Failed to fetch the on demand queue size, returning the max size." ); - return config.on_demand_queue_max_size + return config.on_demand_queue_max_size; }, } } @@ -552,14 +552,14 @@ impl Pallet { } // Record no longer valid para_ids. invalidated_para_id_indexes.push(index); - return false + return false; }); // Collect the popped value. let popped = pos.and_then(|p: usize| { if let Some(assignment) = queue.remove(p) { Pallet::::increase_affinity(assignment.para_id, core_idx); - return Some(assignment) + return Some(assignment); }; None }); diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs b/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs index 8404700780c84..128dfff066e48 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs @@ -178,8 +178,9 @@ fn spot_traffic_can_decrease() { Perbill::from_percent(100), Perbill::from_percent(100), ) { - Ok(new_traffic) => - assert_eq!(new_traffic, FixedU128::from_inner(50_000_000_000_000_000_000u128)), + Ok(new_traffic) => { + assert_eq!(new_traffic, FixedU128::from_inner(50_000_000_000_000_000_000u128)) + }, _ => panic!("Error"), } } diff --git a/polkadot/runtime/parachains/src/configuration.rs b/polkadot/runtime/parachains/src/configuration.rs index 7cc5b31fc8fd1..4a6e7e8b36cc0 100644 --- a/polkadot/runtime/parachains/src/configuration.rs +++ b/polkadot/runtime/parachains/src/configuration.rs @@ -374,77 +374,77 @@ where use InconsistentError::*; if self.group_rotation_frequency.is_zero() { - return Err(ZeroGroupRotationFrequency) + return Err(ZeroGroupRotationFrequency); } if self.paras_availability_period.is_zero() { - return Err(ZeroParasAvailabilityPeriod) + return Err(ZeroParasAvailabilityPeriod); } if self.no_show_slots.is_zero() { - return Err(ZeroNoShowSlots) + return Err(ZeroNoShowSlots); } if self.max_code_size > MAX_CODE_SIZE { - return Err(MaxCodeSizeExceedHardLimit { max_code_size: self.max_code_size }) + return Err(MaxCodeSizeExceedHardLimit { max_code_size: self.max_code_size }); } if self.max_head_data_size > MAX_HEAD_DATA_SIZE { return Err(MaxHeadDataSizeExceedHardLimit { max_head_data_size: self.max_head_data_size, - }) + }); } if self.max_pov_size > MAX_POV_SIZE { - return Err(MaxPovSizeExceedHardLimit { max_pov_size: self.max_pov_size }) + return Err(MaxPovSizeExceedHardLimit { max_pov_size: self.max_pov_size }); } if self.minimum_validation_upgrade_delay <= self.paras_availability_period { return Err(MinimumValidationUpgradeDelayLessThanChainAvailabilityPeriod { minimum_validation_upgrade_delay: self.minimum_validation_upgrade_delay.clone(), paras_availability_period: self.paras_availability_period.clone(), - }) + }); } if self.validation_upgrade_delay <= 1.into() { return Err(ValidationUpgradeDelayIsTooLow { validation_upgrade_delay: self.validation_upgrade_delay.clone(), - }) + }); } if self.max_upward_message_size > crate::inclusion::MAX_UPWARD_MESSAGE_SIZE_BOUND { return Err(MaxUpwardMessageSizeExceeded { max_message_size: self.max_upward_message_size, - }) + }); } if self.hrmp_max_message_num_per_candidate > MAX_HORIZONTAL_MESSAGE_NUM { return Err(MaxHorizontalMessageNumExceeded { max_message_num: self.hrmp_max_message_num_per_candidate, - }) + }); } if self.max_upward_message_num_per_candidate > MAX_UPWARD_MESSAGE_NUM { return Err(MaxUpwardMessageNumExceeded { max_message_num: self.max_upward_message_num_per_candidate, - }) + }); } if self.hrmp_max_parachain_outbound_channels > crate::hrmp::HRMP_MAX_OUTBOUND_CHANNELS_BOUND { - return Err(MaxHrmpOutboundChannelsExceeded) + return Err(MaxHrmpOutboundChannelsExceeded); } if self.hrmp_max_parachain_inbound_channels > crate::hrmp::HRMP_MAX_INBOUND_CHANNELS_BOUND { - return Err(MaxHrmpInboundChannelsExceeded) + return Err(MaxHrmpInboundChannelsExceeded); } if self.minimum_backing_votes.is_zero() { - return Err(ZeroMinimumBackingVotes) + return Err(ZeroMinimumBackingVotes); } if let Err(inner) = self.executor_params.check_consistency() { - return Err(InconsistentExecutorParams { inner }) + return Err(InconsistentExecutorParams { inner }); } Ok(()) @@ -1301,7 +1301,7 @@ impl Pallet { // No pending configuration changes, so we're done. if pending_configs.is_empty() { - return SessionChangeOutcome { prev_config, new_config: None } + return SessionChangeOutcome { prev_config, new_config: None }; } let (mut past_and_present, future) = pending_configs @@ -1415,7 +1415,7 @@ impl Pallet { "Configuration change rejected due to invalid configuration: {:?}", e, ); - return Err(Error::::InvalidNewValue.into()) + return Err(Error::::InvalidNewValue.into()); } else { // The configuration was already broken, so we can as well proceed with the update. // You cannot break something that is already broken. diff --git a/polkadot/runtime/parachains/src/coretime/migration.rs b/polkadot/runtime/parachains/src/coretime/migration.rs index 9bc0a20ef5b4a..0f8bc474f962a 100644 --- a/polkadot/runtime/parachains/src/coretime/migration.rs +++ b/polkadot/runtime/parachains/src/coretime/migration.rs @@ -82,7 +82,7 @@ mod v_coretime { // we already have executed the migration. Some(key) if key.starts_with(&name_hash) => { log::info!("`MigrateToCoretime` already executed!"); - return true + return true; }, // Any other key/no key means that we did not yet have migrated. None | Some(_) => return false, @@ -99,7 +99,7 @@ mod v_coretime { { fn on_runtime_upgrade() -> Weight { if Self::already_migrated() { - return Weight::zero() + return Weight::zero(); } log::info!("Migrating existing parachains to coretime."); @@ -109,7 +109,7 @@ mod v_coretime { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::DispatchError> { if Self::already_migrated() { - return Ok(Vec::new()) + return Ok(Vec::new()); } let legacy_paras = paras::Parachains::::get(); @@ -127,7 +127,7 @@ mod v_coretime { #[cfg(feature = "try-runtime")] fn post_upgrade(state: Vec) -> Result<(), sp_runtime::DispatchError> { if state.is_empty() { - return Ok(()) + return Ok(()); } log::trace!("Running post_upgrade()"); diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index c2383dad30538..16ff0089c002f 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -868,7 +868,7 @@ impl Pallet { let config = >::config(); if notification.session_index <= config.dispute_period + 1 { - return + return; } let pruning_target = notification.session_index - config.dispute_period - 1; @@ -960,7 +960,7 @@ impl Pallet { let dispute_state = { if let Some(dispute_state) = >::get(&set.session, &set.candidate_hash) { if dispute_state.concluded_at.as_ref().map_or(false, |c| c < &oldest_accepted) { - return StatementSetFilter::RemoveAll + return StatementSetFilter::RemoveAll; } dispute_state @@ -987,7 +987,7 @@ impl Pallet { let validator_public = match session_info.validators.get(*validator_index) { None => { filter.remove_index(i); - continue + continue; }, Some(v) => v, }; @@ -998,7 +998,7 @@ impl Pallet { Ok(u) => u, Err(_) => { filter.remove_index(i); - continue + continue; }, }; @@ -1027,7 +1027,7 @@ impl Pallet { importer.undo(undo); filter.remove_index(i); - continue + continue; }; } @@ -1038,14 +1038,14 @@ impl Pallet { if summary.state.validators_for.count_ones() == 0 || summary.state.validators_against.count_ones() == 0 { - return StatementSetFilter::RemoveAll + return StatementSetFilter::RemoveAll; } // Reject disputes containing less votes than needed for confirmation. if (summary.state.validators_for.clone() | &summary.state.validators_against).count_ones() <= byzantine_threshold(summary.state.validators_for.len()) { - return StatementSetFilter::RemoveAll + return StatementSetFilter::RemoveAll; } filter @@ -1210,7 +1210,7 @@ impl Pallet { included_in: BlockNumberFor, ) { if included_in.is_zero() { - return + return; } let revert_to = included_in - One::one(); @@ -1292,7 +1292,7 @@ fn check_signature( if approval_multiple_candidates_enabled && candidates.contains(&candidate_hash) { ApprovalVoteMultipleCandidates(candidates).signing_payload(session) } else { - return Err(()) + return Err(()); }, DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), diff --git a/polkadot/runtime/parachains/src/disputes/slashing.rs b/polkadot/runtime/parachains/src/disputes/slashing.rs index 9b2b7a48dc8b3..dcbacb887caa7 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing.rs @@ -205,7 +205,7 @@ where ).map(|full_id| (id, full_id)) }) .collect::>>(); - return Some(fully_identified) + return Some(fully_identified); } None } @@ -220,16 +220,16 @@ where // sanity check for the current implementation if kind == SlashingOffenceKind::AgainstValid { debug_assert!(false, "should only slash ForInvalid disputes"); - return + return; } let losers: BTreeSet<_> = losers.into_iter().collect(); if losers.is_empty() { - return + return; } let backers: BTreeSet<_> = backers.into_iter().collect(); let to_punish: Vec = losers.intersection(&backers).cloned().collect(); if to_punish.is_empty() { - return + return; } let session_info = crate::session_info::Pallet::::session_info(session_index); @@ -251,7 +251,7 @@ where // This is the first time we report an offence for this dispute, // so it is not a duplicate. let _ = T::HandleReports::report_offence(offence); - return + return; } let keys = to_punish @@ -477,7 +477,7 @@ pub mod pallet { let try_remove = |v: &mut Option| -> Result<(), DispatchError> { let pending = v.as_mut().ok_or(Error::::InvalidCandidateHash)?; if pending.kind != dispute_proof.kind { - return Err(Error::::InvalidCandidateHash.into()) + return Err(Error::::InvalidCandidateHash.into()); } match pending.keys.entry(dispute_proof.validator_index) { @@ -546,7 +546,7 @@ impl Pallet { let config = >::config(); if session_index <= config.dispute_period + 1 { - return + return; } let old_session = session_index - config.dispute_period - 1; @@ -582,7 +582,7 @@ impl Pallet { "rejecting unsigned transaction because it is not local/in-block." ); - return InvalidTransaction::Call.into() + return InvalidTransaction::Call.into(); }, } diff --git a/polkadot/runtime/parachains/src/disputes/tests.rs b/polkadot/runtime/parachains/src/disputes/tests.rs index 1f3f00132d680..fc19d418e1fc8 100644 --- a/polkadot/runtime/parachains/src/disputes/tests.rs +++ b/polkadot/runtime/parachains/src/disputes/tests.rs @@ -70,12 +70,12 @@ fn contains_duplicates_in_sorted_iter< if let Some(mut previous) = iter.next() { while let Some(current) = iter.next() { if check_equal(previous, current) { - return true + return true; } previous = current; } } - return false + return false; } // All arguments for `initializer::on_new_session` diff --git a/polkadot/runtime/parachains/src/dmp.rs b/polkadot/runtime/parachains/src/dmp.rs index 15147e9210e21..460c9f8563265 100644 --- a/polkadot/runtime/parachains/src/dmp.rs +++ b/polkadot/runtime/parachains/src/dmp.rs @@ -191,12 +191,12 @@ impl Pallet { ) -> Result<(), QueueDownwardMessageError> { let serialized_len = msg.len() as u32; if serialized_len > config.max_downward_message_size { - return Err(QueueDownwardMessageError::ExceedsMaxMessageSize) + return Err(QueueDownwardMessageError::ExceedsMaxMessageSize); } // Hard limit on Queue size if Self::dmq_length(*para) > Self::dmq_max_length(config.max_downward_message_size) { - return Err(QueueDownwardMessageError::ExceedsMaxMessageSize) + return Err(QueueDownwardMessageError::ExceedsMaxMessageSize); } Ok(()) @@ -217,12 +217,12 @@ impl Pallet { ) -> Result<(), QueueDownwardMessageError> { let serialized_len = msg.len() as u32; if serialized_len > config.max_downward_message_size { - return Err(QueueDownwardMessageError::ExceedsMaxMessageSize) + return Err(QueueDownwardMessageError::ExceedsMaxMessageSize); } // Hard limit on Queue size if Self::dmq_length(para) > Self::dmq_max_length(config.max_downward_message_size) { - return Err(QueueDownwardMessageError::ExceedsMaxMessageSize) + return Err(QueueDownwardMessageError::ExceedsMaxMessageSize); } let inbound = @@ -267,7 +267,7 @@ impl Pallet { // sanity: if dmq_length is >0 this should always be 'Some'. if contents.get(0).map_or(false, |msg| msg.sent_at <= relay_parent_number) { - return Err(ProcessedDownwardMessagesAcceptanceErr::AdvancementRule) + return Err(ProcessedDownwardMessagesAcceptanceErr::AdvancementRule); } } @@ -279,7 +279,7 @@ impl Pallet { return Err(ProcessedDownwardMessagesAcceptanceErr::Underflow { processed_downward_messages, dmq_length, - }) + }); } Ok(()) diff --git a/polkadot/runtime/parachains/src/hrmp.rs b/polkadot/runtime/parachains/src/hrmp.rs index 42592d9d9f149..367a8dc89b5d3 100644 --- a/polkadot/runtime/parachains/src/hrmp.rs +++ b/polkadot/runtime/parachains/src/hrmp.rs @@ -779,7 +779,7 @@ pub mod pallet { if current_sender_deposit == new_sender_deposit && current_recipient_deposit == new_recipient_deposit { - return Ok(()) + return Ok(()); } // sender @@ -827,7 +827,7 @@ pub mod pallet { channel.sender_deposit = new_sender_deposit; channel.recipient_deposit = new_recipient_deposit; } else { - return Err(Error::::OpenHrmpChannelDoesntExist.into()) + return Err(Error::::OpenHrmpChannelDoesntExist.into()); } Ok(()) })?; @@ -937,7 +937,7 @@ impl Pallet { Some(req_data) => req_data, None => { // Can't normally happen but no need to panic. - continue + continue; }, }; @@ -995,7 +995,7 @@ impl Pallet { fn process_hrmp_open_channel_requests(config: &HostConfiguration>) { let mut open_req_channels = HrmpOpenChannelRequestsList::::get(); if open_req_channels.is_empty() { - return + return; } // iterate the vector starting from the end making our way to the beginning. This way we @@ -1004,7 +1004,7 @@ impl Pallet { loop { // bail if we've iterated over all items. if idx == 0 { - break + break; } idx -= 1; @@ -1116,14 +1116,14 @@ impl Pallet { // (b) However, a parachain cannot read into "the future", therefore the watermark should // not be greater than the relay-chain context block which the parablock refers to. if new_hrmp_watermark == relay_chain_parent_number { - return Ok(()) + return Ok(()); } if new_hrmp_watermark > relay_chain_parent_number { return Err(HrmpWatermarkAcceptanceErr::AheadRelayParent { new_watermark: new_hrmp_watermark, relay_chain_parent_number, - }) + }); } if let Some(last_watermark) = HrmpWatermarks::::get(&recipient) { @@ -1131,7 +1131,7 @@ impl Pallet { return Err(HrmpWatermarkAcceptanceErr::AdvancementRule { new_watermark: new_hrmp_watermark, last_watermark, - }) + }); } } @@ -1146,7 +1146,7 @@ impl Pallet { { return Err(HrmpWatermarkAcceptanceErr::LandsOnBlockWithNoMessages { new_watermark: new_hrmp_watermark, - }) + }); } Ok(()) } @@ -1168,7 +1168,7 @@ impl Pallet { return Err(OutboundHrmpAcceptanceErr::MoreMessagesThanPermitted { sent: out_hrmp_msgs.len() as u32, permitted: config.hrmp_max_message_num_per_candidate, - }) + }); } let mut last_recipient = None::; @@ -1198,7 +1198,7 @@ impl Pallet { idx, msg_size, max_size: channel.max_message_size, - }) + }); } let new_total_size = channel.total_size + out_msg.data.len() as u32; @@ -1207,7 +1207,7 @@ impl Pallet { idx, total_size: new_total_size, limit: channel.max_total_size, - }) + }); } let new_msg_count = channel.msg_count + 1; @@ -1216,7 +1216,7 @@ impl Pallet { idx, count: new_msg_count, limit: channel.max_capacity, - }) + }); } } @@ -1230,7 +1230,7 @@ impl Pallet { for recipient in recipients { let Some(channel) = HrmpChannels::::get(&HrmpChannelId { sender, recipient }) else { - continue + continue; }; remaining.push(( recipient, @@ -1320,7 +1320,7 @@ impl Pallet { None => { // apparently, that since acceptance of this candidate the recipient was // offboarded and the channel no longer exists. - continue + continue; }, }; diff --git a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs index 2cb49c88d437c..34b4369153dc7 100644 --- a/polkadot/runtime/parachains/src/hrmp/benchmarking.rs +++ b/polkadot/runtime/parachains/src/hrmp/benchmarking.rs @@ -101,24 +101,24 @@ where )); if matches!(until, ParachainSetupStep::Requested) { - return output + return output; } assert_ok!(Hrmp::::hrmp_accept_open_channel(recipient_origin.into(), sender)); if matches!(until, ParachainSetupStep::Accepted) { - return output + return output; } Hrmp::::process_hrmp_open_channel_requests(&Configuration::::config()); if matches!(until, ParachainSetupStep::Established) { - return output + return output; } let channel_id = HrmpChannelId { sender, recipient }; assert_ok!(Hrmp::::hrmp_close_channel(sender_origin.clone().into(), channel_id)); if matches!(until, ParachainSetupStep::CloseRequested) { // NOTE: this is just for expressiveness, otherwise the if-statement is 100% useless. - return output + return output; } output diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index 90af9cde00a8f..929a8acc1a80e 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -530,7 +530,7 @@ impl Pallet { // which in turn happens in case of a disputed candidate. // A malicious one might include arbitrary indices, but they are represented // by `None` values and will be sorted out in the next if case. - continue + continue; }; // defensive check - this is constructed by loading the availability bitfield @@ -568,7 +568,7 @@ impl Pallet { "Inclusion::process_bitfields: PendingAvailability and PendingAvailabilityCommitments are out of sync, did someone mess with the storage?", ); - continue + continue; }, }; @@ -613,7 +613,7 @@ impl Pallet { ensure!(candidates.len() <= scheduled.len(), Error::::UnscheduledCandidate); if scheduled.is_empty() { - return Ok(ProcessedCandidates::default()) + return Ok(ProcessedCandidates::default()); } let minimum_backing_votes = configuration::Pallet::::config().minimum_backing_votes; @@ -674,7 +674,7 @@ impl Pallet { // We don't want to error out here because it will // brick the relay-chain. So we return early without // doing anything. - return Ok(ProcessedCandidates::default()) + return Ok(ProcessedCandidates::default()); }, Ok(rpn) => rpn, }; @@ -944,7 +944,7 @@ impl Pallet { return Err(UmpAcceptanceCheckErr::MoreMessagesThanPermitted { sent: additional_msgs, permitted: config.max_upward_message_num_per_candidate, - }) + }); } let (para_queue_count, mut para_queue_size) = Self::relay_dispatch_queue_size(para); @@ -953,7 +953,7 @@ impl Pallet { return Err(UmpAcceptanceCheckErr::CapacityExceeded { count: para_queue_count.saturating_add(additional_msgs).into(), limit: config.max_upward_queue_count.into(), - }) + }); } for (idx, msg) in upward_messages.into_iter().enumerate() { @@ -963,7 +963,7 @@ impl Pallet { idx: idx as u32, msg_size, max_size: config.max_upward_message_size, - }) + }); } // make sure that the queue is not overfilled. // we do it here only once since returning false invalidates the whole relay-chain @@ -972,7 +972,7 @@ impl Pallet { return Err(UmpAcceptanceCheckErr::TotalSizeExceeded { total_size: para_queue_size.saturating_add(msg_size).into(), limit: config.max_upward_queue_size.into(), - }) + }); } para_queue_size.saturating_accrue(msg_size); } @@ -1007,7 +1007,7 @@ impl Pallet { ) -> Weight { let count = messages.len() as u32; if count == 0 { - return Weight::zero() + return Weight::zero(); } T::MessageQueue::enqueue_messages( diff --git a/polkadot/runtime/parachains/src/inclusion/tests.rs b/polkadot/runtime/parachains/src/inclusion/tests.rs index 557b7b71a9e32..7e2c85ae1c8dc 100644 --- a/polkadot/runtime/parachains/src/inclusion/tests.rs +++ b/polkadot/runtime/parachains/src/inclusion/tests.rs @@ -784,7 +784,7 @@ fn supermajority_bitfields_trigger_availability() { a_available.clone() } else { // sign nothing. - return None + return None; }; Some( diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 1925ca19501ac..1dcf56b9753b5 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -621,7 +621,7 @@ impl ProcessMessage for TestProcessMessage { Err(_) => return Err(ProcessMessageError::Corrupt), // same as the real `ProcessMessage` }; if meter.try_consume(required).is_err() { - return Err(ProcessMessageError::Overweight(required)) + return Err(ProcessMessageError::Overweight(required)); } let mut processed = Processed::get(); diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index 39371391b1f09..93e8986b071c2 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -1006,12 +1006,12 @@ pub mod pallet { vote.age, &cfg, ); - return Ok(()) + return Ok(()); } if CodeByHash::::contains_key(&code_hash) { // There is no vote, but the code exists. Nothing to do here. - return Ok(()) + return Ok(()); } // At this point the code is unknown and there is no PVF pre-checking vote for it, so we @@ -1062,9 +1062,9 @@ pub mod pallet { let validators = shared::Pallet::::active_validator_keys(); let current_session = shared::Pallet::::session_index(); if stmt.session_index < current_session { - return Err(Error::::PvfCheckStatementStale.into()) + return Err(Error::::PvfCheckStatementStale.into()); } else if stmt.session_index > current_session { - return Err(Error::::PvfCheckStatementFuture.into()) + return Err(Error::::PvfCheckStatementFuture.into()); } let validator_index = stmt.validator_index.0 as usize; let validator_public = validators @@ -1160,9 +1160,9 @@ pub mod pallet { let current_session = shared::Pallet::::session_index(); if stmt.session_index < current_session { - return InvalidTransaction::Stale.into() + return InvalidTransaction::Stale.into(); } else if stmt.session_index > current_session { - return InvalidTransaction::Future.into() + return InvalidTransaction::Future.into(); } let validator_index = stmt.validator_index.0 as usize; @@ -1174,7 +1174,7 @@ pub mod pallet { let signing_payload = stmt.signing_payload(); if !signature.verify(&signing_payload[..], &validator_public) { - return InvalidTransaction::BadProof.into() + return InvalidTransaction::BadProof.into(); } let active_vote = match PvfActiveVoteMap::::get(&stmt.subject) { @@ -1410,7 +1410,7 @@ impl Pallet { let code_retention_period = config.code_retention_period; if now <= code_retention_period { let weight = T::DbWeight::get().reads_writes(1, 0); - return weight + return weight; } // The height of any changes we no longer should keep around. @@ -1540,7 +1540,7 @@ impl Pallet { "The PvfActiveVoteMap is out of sync with PvfActiveVoteList!", ); debug_assert!(false); - continue + continue; }, }; @@ -1800,7 +1800,7 @@ impl Pallet { if let Some(future_code_hash) = FutureCodeHash::::get(&id) { let active_prechecking = PvfActiveVoteList::::get(); if active_prechecking.contains(&future_code_hash) { - return Err(Error::::CannotOffboard.into()) + return Err(Error::::CannotOffboard.into()); } } @@ -1825,7 +1825,7 @@ impl Pallet { }); if ::QueueFootprinter::message_count(UmpQueueId::Para(id)) != 0 { - return Err(Error::::CannotOffboard.into()) + return Err(Error::::CannotOffboard.into()); } Ok(()) @@ -1900,7 +1900,7 @@ impl Pallet { let new_code_len = new_code.0.len(); if new_code_len < MIN_CODE_SIZE as usize || new_code_len > cfg.max_code_size as usize { log::warn!(target: LOG_TARGET, "attempted to schedule an upgrade with invalid new validation code",); - return weight + return weight; } // Enacting this should be prevented by the `can_upgrade_validation_code` @@ -1914,7 +1914,7 @@ impl Pallet { // NOTE: we cannot set `UpgradeGoAheadSignal` signal here since this will be reset by // the following call `note_new_head` log::warn!(target: LOG_TARGET, "ended up scheduling an upgrade while one is pending",); - return weight + return weight; } let code_hash = new_code.hash(); @@ -1931,7 +1931,7 @@ impl Pallet { target: LOG_TARGET, "para tried to upgrade to the same code. Abort the upgrade", ); - return weight + return weight; } // This is the start of the upgrade process. Prevent any further attempts at upgrading. @@ -2059,7 +2059,7 @@ impl Pallet { new_code_hash } else { log::error!(target: LOG_TARGET, "Missing future code hash for {:?}", &id); - return T::DbWeight::get().reads_writes(3, 1 + 3) + return T::DbWeight::get().reads_writes(3, 1 + 3); }; let maybe_prior_code_hash = CurrentCodeHash::::get(&id); CurrentCodeHash::::insert(&id, &new_code_hash); @@ -2200,7 +2200,7 @@ impl Pallet { let refs = CodeByHashRefs::::get(code_hash); if refs == 0 { log::error!(target: LOG_TARGET, "Code refs is already zero for {:?}", code_hash); - return weight + return weight; } if refs <= 1 { weight += T::DbWeight::get().writes(2); diff --git a/polkadot/runtime/parachains/src/paras_inherent/misc.rs b/polkadot/runtime/parachains/src/paras_inherent/misc.rs index dac9e6e256d0e..a1ab44474095b 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/misc.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/misc.rs @@ -61,7 +61,7 @@ where previous } else { // empty is always sorted - return true + return true; }; while let Some(cursor) = iter.next() { match cmp(&previous, &cursor) { diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index 81e092f0a991c..ff46c8c62c712 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -298,7 +298,7 @@ impl Pallet { Ok(None) => return None, Err(_) => { log::warn!(target: LOG_TARGET, "ParachainsInherentData failed to decode"); - return None + return None; }, }; match Self::process_inherent_data( @@ -518,7 +518,7 @@ impl Pallet { }; // The relay chain we are currently on is invalid. Proceed no further on parachains. - return Ok((processed, Some(checked_disputes_sets_consumed_weight).into())) + return Ok((processed, Some(checked_disputes_sets_consumed_weight).into())); } // Contains the disputes that are concluded in the current session only, @@ -690,7 +690,7 @@ fn random_sel Weight>( weight_limit: Weight, ) -> (Weight, Vec) { if selectables.is_empty() { - return (Weight::zero(), Vec::new()) + return (Weight::zero(), Vec::new()); } // all indices that are not part of the preferred set let mut indices = (0..selectables.len()) @@ -707,7 +707,7 @@ fn random_sel Weight>( if let Some(item) = selectables.get(preferred_idx) { let updated = weight_acc.saturating_add(weight_fn(item)); if updated.any_gt(weight_limit) { - continue + continue; } weight_acc = updated; picked_indices.push(preferred_idx); @@ -720,7 +720,7 @@ fn random_sel Weight>( let updated = weight_acc.saturating_add(weight_fn(item)); if updated.any_gt(weight_limit) { - continue + continue; } weight_acc = updated; @@ -765,7 +765,7 @@ fn apply_weight_limit( // candidates + bitfields fit into the block if max_consumable_weight.all_gte(total) { - return total + return total; } // Prefer code upgrades, they tend to be large and hence stand no chance to be picked @@ -797,7 +797,7 @@ fn apply_weight_limit( // fill the remaining space with candidates let total_consumed = acc_candidate_weight.saturating_add(total_bitfields_weight); - return total_consumed + return total_consumed; } candidates.clear(); @@ -845,7 +845,7 @@ pub(crate) fn sanitize_bitfields( // This is a system logic error that should never occur, but we want to handle it gracefully // so we just drop all bitfields log::error!(target: LOG_TARGET, "BUG: disputed_bitfield != expected_bits"); - return vec![] + return vec![]; } let all_zeros = BitVec::::repeat(false, expected_bits); @@ -859,7 +859,7 @@ pub(crate) fn sanitize_bitfields( unchecked_bitfield.unchecked_payload().0.len(), expected_bits, ); - continue + continue; } if unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone() != @@ -870,7 +870,7 @@ pub(crate) fn sanitize_bitfields( "bitfield contains disputed cores: {:?}", unchecked_bitfield.unchecked_payload().0.clone() & disputed_bitfield.0.clone() ); - continue + continue; } let validator_index = unchecked_bitfield.unchecked_validator_index(); @@ -882,7 +882,7 @@ pub(crate) fn sanitize_bitfields( last_index.as_ref().map(|x| x.0), validator_index.0 ); - continue + continue; } if unchecked_bitfield.unchecked_validator_index().0 as usize >= validators.len() { @@ -892,7 +892,7 @@ pub(crate) fn sanitize_bitfields( validator_index.0, validators.len(), ); - continue + continue; } let validator_public = &validators[validator_index.0 as usize]; @@ -1080,7 +1080,7 @@ fn filter_backed_statements_from_disabled_validators Pallet { let session_start_block = >::get(); if at < session_start_block { - return None + return None; } let validator_groups = ValidatorGroups::::get(); if core.0 as usize >= validator_groups.len() { - return None + return None; } let rotations_since_session_start: BlockNumberFor = @@ -579,7 +579,7 @@ impl Pallet { // This can only happen on new sessions at which we move all assignments back to the // provider. Hence, there's nothing we need to do here. if ValidatorGroups::::decode_len().map_or(true, |l| l == 0) { - return + return; } // If there exists a core, ensure we schedule at least one job onto it. let n_lookahead = Self::claimqueue_lookahead().max(1); @@ -602,7 +602,7 @@ impl Pallet { Self::add_to_claimqueue(core_idx, entry); // The claim has been added back into the claimqueue. // Do not pop another assignment for the core. - continue + continue; } else { // Consider timed out assignments for on demand parachains as concluded for // the assignment provider diff --git a/polkadot/runtime/parachains/src/shared.rs b/polkadot/runtime/parachains/src/shared.rs index bdaffcd505f8e..eafcb38f7b7ae 100644 --- a/polkadot/runtime/parachains/src/shared.rs +++ b/polkadot/runtime/parachains/src/shared.rs @@ -103,7 +103,7 @@ impl if let Some(prev) = prev { if prev > number { - return None + return None; } } diff --git a/polkadot/runtime/rococo/src/governance/fellowship.rs b/polkadot/runtime/rococo/src/governance/fellowship.rs index a589b768afde2..8ab6cca806cdf 100644 --- a/polkadot/runtime/rococo/src/governance/fellowship.rs +++ b/polkadot/runtime/rococo/src/governance/fellowship.rs @@ -266,7 +266,7 @@ impl pallet_referenda::TracksInfo for TracksInfo { // It is important that this is not available in production! let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); if &root == id { - return Ok(9) + return Ok(9); } } diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 45f27312697ca..c870d1a2af55f 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -217,7 +217,7 @@ pub struct OriginPrivilegeCmp; impl PrivilegeCmp for OriginPrivilegeCmp { fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { if left == right { - return Some(Ordering::Equal) + return Some(Ordering::Equal); } match (left, right) { @@ -1489,11 +1489,11 @@ pub mod migrations { let now = frame_system::Pallet::::block_number(); let lease = slots::Pallet::::lease(para); if lease.is_empty() { - return None + return None; } // Lease not yet started, ignore: if lease.iter().any(Option::is_none) { - return None + return None; } let (index, _) = as Leaser>::lease_period_index(now)?; @@ -1555,7 +1555,7 @@ pub mod migrations { fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::warn!(target: "runtime::session_keys", "Skipping session keys migration pre-upgrade check due to spec version (already applied?)"); - return Ok(Vec::new()) + return Ok(Vec::new()); } log::info!(target: "runtime::session_keys", "Collecting pre-upgrade session keys state"); @@ -1584,7 +1584,7 @@ pub mod migrations { fn on_runtime_upgrade() -> Weight { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::info!("Skipping session keys upgrade: already applied"); - return ::DbWeight::get().reads(1) + return ::DbWeight::get().reads(1); } log::trace!("Upgrading session keys"); Session::upgrade_keys::(transform_session_keys); @@ -1597,7 +1597,7 @@ pub mod migrations { ) -> Result<(), sp_runtime::TryRuntimeError> { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::warn!(target: "runtime::session_keys", "Skipping session keys migration post-upgrade check due to spec version (already applied?)"); - return Ok(()) + return Ok(()); } let key_ids = SessionKeys::key_ids(); @@ -2454,7 +2454,7 @@ mod remote_tests { #[tokio::test] async fn run_migrations() { if var("RUN_MIGRATION_TESTS").is_err() { - return + return; } sp_tracing::try_init_simple(); diff --git a/polkadot/runtime/rococo/src/validator_manager.rs b/polkadot/runtime/rococo/src/validator_manager.rs index 0677ba7fbb2b2..5347fe791f8a5 100644 --- a/polkadot/runtime/rococo/src/validator_manager.rs +++ b/polkadot/runtime/rococo/src/validator_manager.rs @@ -102,7 +102,7 @@ pub mod pallet { impl pallet_session::SessionManager for Pallet { fn new_session(new_index: SessionIndex) -> Option> { if new_index <= 1 { - return None + return None; } let mut validators = Session::::validators(); diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 166c2d0d96e06..59a995f8303d2 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -1569,7 +1569,7 @@ pub mod migrations { fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::warn!(target: "runtime::session_keys", "Skipping session keys migration pre-upgrade check due to spec version (already applied?)"); - return Ok(Vec::new()) + return Ok(Vec::new()); } log::info!(target: "runtime::session_keys", "Collecting pre-upgrade session keys state"); @@ -1598,7 +1598,7 @@ pub mod migrations { fn on_runtime_upgrade() -> Weight { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::warn!("Skipping session keys upgrade: already applied"); - return ::DbWeight::get().reads(1) + return ::DbWeight::get().reads(1); } log::info!("Upgrading session keys"); Session::upgrade_keys::(transform_session_keys); @@ -1611,7 +1611,7 @@ pub mod migrations { ) -> Result<(), sp_runtime::TryRuntimeError> { if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { log::warn!(target: "runtime::session_keys", "Skipping session keys migration post-upgrade check due to spec version (already applied?)"); - return Ok(()) + return Ok(()); } let key_ids = SessionKeys::key_ids(); @@ -2483,7 +2483,7 @@ mod remote_tests { #[tokio::test] async fn run_migrations() { if var("RUN_MIGRATION_TESTS").is_err() { - return + return; } sp_tracing::try_init_simple(); diff --git a/polkadot/statement-table/src/generic.rs b/polkadot/statement-table/src/generic.rs index 22bffde5acc11..65e05c079d194 100644 --- a/polkadot/statement-table/src/generic.rs +++ b/polkadot/statement-table/src/generic.rs @@ -250,7 +250,7 @@ impl CandidateData { ) -> Option> { let valid_votes = self.validity_votes.len(); if valid_votes < validity_threshold { - return None + return None; } let validity_votes = self @@ -396,7 +396,7 @@ impl Table { statement: Statement::Seconded(candidate), sender: authority, }, - })) + })); } // check that authority hasn't already specified another candidate. @@ -427,7 +427,7 @@ impl Table { return Err(Misbehavior::MultipleCandidates(MultipleCandidates { first: (old_candidate, old_sig.clone()), second: (candidate, signature.clone()), - })) + })); } false @@ -490,7 +490,7 @@ impl Table { sender: from, statement: Statement::Valid(digest), }, - })) + })); } // check for double votes. @@ -518,7 +518,7 @@ impl Table { }) } else { Ok(None) - } + }; }, Entry::Vacant(vacant) => { vacant.insert(vote); diff --git a/polkadot/tests/benchmark_block.rs b/polkadot/tests/benchmark_block.rs index 99f95ef611a48..109d5fbd57fd4 100644 --- a/polkadot/tests/benchmark_block.rs +++ b/polkadot/tests/benchmark_block.rs @@ -88,7 +88,7 @@ fn benchmark_block(runtime: &str, base_path: &Path, block: u32) -> Result<(), St .map_err(|e| format!("command failed: {:?}", e))?; if !status.success() { - return Err("Command failed".into()) + return Err("Command failed".into()); } Ok(()) diff --git a/polkadot/tests/benchmark_extrinsic.rs b/polkadot/tests/benchmark_extrinsic.rs index 529eb29362d4d..63e52c2efd577 100644 --- a/polkadot/tests/benchmark_extrinsic.rs +++ b/polkadot/tests/benchmark_extrinsic.rs @@ -50,7 +50,7 @@ fn benchmark_extrinsic(runtime: &str, pallet: &str, extrinsic: &str) -> Result<( .map_err(|e| format!("command failed: {:?}", e))?; if !status.success() { - return Err("Command failed".into()) + return Err("Command failed".into()); } Ok(()) diff --git a/polkadot/tests/benchmark_overhead.rs b/polkadot/tests/benchmark_overhead.rs index b0912225347df..64bc36ab297b2 100644 --- a/polkadot/tests/benchmark_overhead.rs +++ b/polkadot/tests/benchmark_overhead.rs @@ -57,7 +57,7 @@ fn benchmark_overhead(runtime: &str) -> Result<(), String> { .map_err(|e| format!("command failed: {:?}", e))?; if !status.success() { - return Err("Command failed".into()) + return Err("Command failed".into()); } // Weight files have been created. diff --git a/polkadot/tests/common.rs b/polkadot/tests/common.rs index 15721c990e01b..e86a4ff318650 100644 --- a/polkadot/tests/common.rs +++ b/polkadot/tests/common.rs @@ -38,7 +38,7 @@ pub async fn wait_n_finalized_blocks(n: usize, url: &str) { if let Ok(block) = ChainApi::<(), Hash, Header, Block>::finalized_head(&rpc).await { built_blocks.insert(block); if built_blocks.len() > n { - break + break; } }; diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 586c275ae980f..95872eb7802c0 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -788,7 +788,7 @@ pub mod pallet { if Self::request_version_notify(dest).is_ok() { // TODO: correct weights. weight_used.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); - break + break; } } } @@ -2093,7 +2093,7 @@ impl Pallet { } weight_used.saturating_accrue(sv_migrate_weight); if weight_used.any_gte(weight_cutoff) { - return (weight_used, Some(stage)) + return (weight_used, Some(stage)); } } } @@ -2107,7 +2107,7 @@ impl Pallet { } weight_used.saturating_accrue(vn_migrate_weight); if weight_used.any_gte(weight_cutoff) { - return (weight_used, Some(stage)) + return (weight_used, Some(stage)); } } } @@ -2129,7 +2129,7 @@ impl Pallet { // We don't early return here since we need to be certain that we // make some progress. weight_used.saturating_accrue(vnt_already_notified_weight); - continue + continue; }, }; let response = Response::Version(xcm_version); @@ -2155,7 +2155,7 @@ impl Pallet { weight_used.saturating_accrue(vnt_notify_weight); if weight_used.any_gte(weight_cutoff) { let last = Some(iter.last_raw_key().into()); - return (weight_used, Some(NotifyCurrentTargets(last))) + return (weight_used, Some(NotifyCurrentTargets(last))); } } stage = MigrateAndNotifyOldTargets; @@ -2173,9 +2173,9 @@ impl Pallet { }); weight_used.saturating_accrue(vnt_migrate_fail_weight); if weight_used.any_gte(weight_cutoff) { - return (weight_used, Some(stage)) + return (weight_used, Some(stage)); } - continue + continue; }, }; @@ -2216,7 +2216,7 @@ impl Pallet { weight_used.saturating_accrue(vnt_notify_migrate_weight); } if weight_used.any_gte(weight_cutoff) { - return (weight_used, Some(stage)) + return (weight_used, Some(stage)); } } } @@ -2415,7 +2415,7 @@ impl Pallet { // if migration has been already scheduled, everything is ok and data will be eventually // migrated if CurrentMigration::::exists() { - return Ok(()) + return Ok(()); } // if migration has NOT been scheduled yet, we need to check all operational data @@ -2712,7 +2712,7 @@ impl VersionChangeNotifier for Pallet { impl DropAssets for Pallet { fn drop_assets(origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight { if assets.is_empty() { - return Weight::zero() + return Weight::zero(); } let versioned = VersionedAssets::from(Assets::from(assets)); let hash = BlakeTwo256::hash_of(&(&origin, &versioned)); @@ -2755,7 +2755,7 @@ impl ClaimAssets for Pallet { origin: origin.clone(), assets: versioned, }); - return true + return true; } } @@ -2801,7 +2801,7 @@ impl OnResponse for Pallet { query_id, expected_location: Some(o), }); - return Weight::zero() + return Weight::zero(); }, _ => { Self::deposit_event(Event::InvalidResponder { @@ -2810,7 +2810,7 @@ impl OnResponse for Pallet { expected_location: None, }); // TODO #3735: Correct weight for this. - return Weight::zero() + return Weight::zero(); }, }; // TODO #3735: Check max_weight is correct. @@ -2843,7 +2843,7 @@ impl OnResponse for Pallet { origin: origin.clone(), query_id, }); - return Weight::zero() + return Weight::zero(); }, }; if querier.map_or(true, |q| q != &match_querier) { @@ -2853,7 +2853,7 @@ impl OnResponse for Pallet { expected_querier: match_querier, maybe_actual_querier: querier.cloned(), }); - return Weight::zero() + return Weight::zero(); } } let responder = match Location::try_from(responder) { @@ -2863,7 +2863,7 @@ impl OnResponse for Pallet { origin: origin.clone(), query_id, }); - return Weight::zero() + return Weight::zero(); }, }; if origin != responder { @@ -2872,7 +2872,7 @@ impl OnResponse for Pallet { query_id, expected_location: Some(responder), }); - return Weight::zero() + return Weight::zero(); } return match maybe_notify { Some((pallet_index, call_index)) => { @@ -2894,7 +2894,7 @@ impl OnResponse for Pallet { max_budgeted_weight: max_weight, }; Self::deposit_event(e); - return Weight::zero() + return Weight::zero(); } let dispatch_origin = Origin::Response(origin.clone()).into(); match call.dispatch(dispatch_origin) { @@ -2931,7 +2931,7 @@ impl OnResponse for Pallet { Queries::::insert(query_id, QueryStatus::Ready { response, at }); Weight::zero() }, - } + }; }, _ => { let e = Event::UnexpectedResponse { origin: origin.clone(), query_id }; diff --git a/polkadot/xcm/pallet-xcm/src/migration.rs b/polkadot/xcm/pallet-xcm/src/migration.rs index 018436aa3c93a..82e3a70a92f7a 100644 --- a/polkadot/xcm/pallet-xcm/src/migration.rs +++ b/polkadot/xcm/pallet-xcm/src/migration.rs @@ -41,7 +41,7 @@ pub mod v1 { if StorageVersion::get::>() != 0 { log::warn!("skipping v1, should be removed"); - return weight + return weight; } weight.saturating_accrue(T::DbWeight::get().writes(1)); diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index 004a73ca6ab23..78381d20e1a5d 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -172,7 +172,7 @@ impl SendXcm for TestSendXcm { msg: &mut Option>, ) -> SendResult<(Location, Xcm<()>)> { if FAIL_SEND_XCM.with(|q| *q.borrow()) { - return Err(SendError::Transport("Intentional send failure used in tests")) + return Err(SendError::Transport("Intentional send failure used in tests")); } let pair = (dest.take().unwrap(), msg.take().unwrap()); Ok((pair, Assets::new())) @@ -221,10 +221,10 @@ impl SendXcm for TestPaidForPara3000SendXcm { ) -> SendResult<(Location, Xcm<()>)> { if let Some(dest) = dest.as_ref() { if !dest.eq(&Para3000Location::get()) { - return Err(SendError::NotApplicable) + return Err(SendError::NotApplicable); } } else { - return Err(SendError::NotApplicable) + return Err(SendError::NotApplicable); } let pair = (dest.take().unwrap(), msg.take().unwrap()); diff --git a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs index 27be5cce14585..4ccb0450554bb 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs @@ -341,7 +341,7 @@ fn local_asset_reserve_and_local_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } // Alice spent amount assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - SEND_AMOUNT); @@ -489,7 +489,7 @@ fn destination_asset_reserve_and_local_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let mut last_events = last_events(3).into_iter(); @@ -784,7 +784,7 @@ fn local_asset_reserve_and_destination_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let weight = BaseXcmWeight::get() * 3; @@ -946,7 +946,7 @@ fn destination_asset_reserve_and_destination_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let weight = BaseXcmWeight::get() * 2; @@ -1524,7 +1524,7 @@ fn remote_asset_reserve_and_remote_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } assert!(matches!( @@ -1671,7 +1671,7 @@ fn local_asset_reserve_and_teleported_fee_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let weight = BaseXcmWeight::get() * 3; @@ -1841,7 +1841,7 @@ fn destination_asset_reserve_and_teleported_fee_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let weight = BaseXcmWeight::get() * 4; @@ -2319,7 +2319,7 @@ fn teleport_asset_using_local_fee_reserve_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let mut last_events = last_events(3).into_iter(); @@ -2488,7 +2488,7 @@ fn teleported_asset_using_destination_reserve_fee_call( assert_eq!(result, expected_result); if expected_result.is_err() { // short-circuit here for tests where we expect failure - return + return; } let weight = BaseXcmWeight::get() * 4; diff --git a/polkadot/xcm/procedural/src/v2.rs b/polkadot/xcm/procedural/src/v2.rs index 6878f7755cc70..9aa92ff3f83b6 100644 --- a/polkadot/xcm/procedural/src/v2.rs +++ b/polkadot/xcm/procedural/src/v2.rs @@ -23,7 +23,7 @@ pub mod multilocation { pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. @@ -189,7 +189,7 @@ pub mod junctions { pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } let from_slice_syntax = generate_conversion_from_slice_syntax(); diff --git a/polkadot/xcm/procedural/src/v3.rs b/polkadot/xcm/procedural/src/v3.rs index f0556d5a8d447..7ebcb82909c41 100644 --- a/polkadot/xcm/procedural/src/v3.rs +++ b/polkadot/xcm/procedural/src/v3.rs @@ -25,7 +25,7 @@ pub mod multilocation { pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } let from_tuples = generate_conversion_from_tuples(8, 8); @@ -123,7 +123,7 @@ pub mod junctions { pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. diff --git a/polkadot/xcm/procedural/src/v4.rs b/polkadot/xcm/procedural/src/v4.rs index 5f5e10d3081b3..c8db9403f7f0e 100644 --- a/polkadot/xcm/procedural/src/v4.rs +++ b/polkadot/xcm/procedural/src/v4.rs @@ -28,7 +28,7 @@ pub mod location { /// - (Parent, Parachain(1000), AccountId32 { .. }).into() pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } let from_tuples = generate_conversion_from_tuples(8, 8); @@ -127,7 +127,7 @@ pub mod junctions { pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + return Err(syn::Error::new(Span::call_site(), "No arguments expected")); } // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. diff --git a/polkadot/xcm/procedural/tests/ui.rs b/polkadot/xcm/procedural/tests/ui.rs index b3469b520eb77..a30f4d7dee5dc 100644 --- a/polkadot/xcm/procedural/tests/ui.rs +++ b/polkadot/xcm/procedural/tests/ui.rs @@ -21,7 +21,7 @@ fn ui() { // Only run the ui tests when `RUN_UI_TESTS` is set. if std::env::var("RUN_UI_TESTS").is_err() { - return + return; } // As trybuild is using `cargo check`, we don't need the real WASM binaries. diff --git a/polkadot/xcm/src/v2/multiasset.rs b/polkadot/xcm/src/v2/multiasset.rs index 5681e9ef8a447..ced99936c88f1 100644 --- a/polkadot/xcm/src/v2/multiasset.rs +++ b/polkadot/xcm/src/v2/multiasset.rs @@ -389,7 +389,7 @@ impl MultiAssets { /// `From::>::from` which is infallible. pub fn from_sorted_and_deduplicated(r: Vec) -> Result { if r.is_empty() { - return Ok(Self(Vec::new())) + return Ok(Self(Vec::new())); } r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&MultiAsset, ()> { if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { @@ -431,7 +431,7 @@ impl MultiAssets { for asset in self.0.iter_mut().filter(|x| x.id == a.id) { if let Fungibility::Fungible(ref mut balance) = asset.fun { *balance = balance.saturating_add(*amount); - return + return; } } } diff --git a/polkadot/xcm/src/v2/multilocation.rs b/polkadot/xcm/src/v2/multilocation.rs index 60aa1f6ceadf0..ca351d44cc58c 100644 --- a/polkadot/xcm/src/v2/multilocation.rs +++ b/polkadot/xcm/src/v2/multilocation.rs @@ -201,7 +201,7 @@ impl MultiLocation { pub fn at(&self, i: usize) -> Option<&Junction> { let num_parents = self.parents as usize; if i < num_parents { - return None + return None; } self.interior.at(i - num_parents) } @@ -211,7 +211,7 @@ impl MultiLocation { pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { let num_parents = self.parents as usize; if i < num_parents { - return None + return None; } self.interior.at_mut(i - num_parents) } @@ -249,7 +249,7 @@ impl MultiLocation { /// ``` pub fn match_and_split(&self, prefix: &MultiLocation) -> Option<&Junction> { if self.parents != prefix.parents { - return None + return None; } self.interior.match_and_split(&prefix.interior) } @@ -267,7 +267,7 @@ impl MultiLocation { /// ``` pub fn starts_with(&self, prefix: &MultiLocation) -> bool { if self.parents != prefix.parents { - return false + return false; } self.interior.starts_with(&prefix.interior) } @@ -285,7 +285,7 @@ impl MultiLocation { /// ``` pub fn append_with(&mut self, suffix: Junctions) -> Result<(), Junctions> { if self.interior.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { - return Err(suffix) + return Err(suffix); } for j in suffix.into_iter() { self.interior.push(j).expect("Already checked the sum of the len()s; qed") @@ -310,12 +310,12 @@ impl MultiLocation { let prepend_interior = prefix.interior.len().saturating_sub(self.parents as usize); let final_interior = self.interior.len().saturating_add(prepend_interior); if final_interior > MAX_JUNCTIONS { - return Err(prefix) + return Err(prefix); } let suffix_parents = (self.parents as usize).saturating_sub(prefix.interior.len()); let final_parents = (prefix.parents as usize).saturating_add(suffix_parents); if final_parents > 255 { - return Err(prefix) + return Err(prefix); } // cancel out the final item on the prefix interior for one of the suffix's parents. @@ -394,7 +394,7 @@ impl MultiLocation { pub fn simplify(&mut self, context: &Junctions) { if context.len() < self.parents as usize { // Not enough context - return + return; } while self.parents > 0 { let maybe = context.at(context.len() - (self.parents as usize)); @@ -513,7 +513,7 @@ impl<'a> Iterator for JunctionsRefIterator<'a> { type Item = &'a Junction; fn next(&mut self) -> Option<&'a Junction> { if self.next.saturating_add(self.back) >= self.junctions.len() { - return None + return None; } let result = self.junctions.at(self.next); @@ -528,7 +528,7 @@ impl<'a> DoubleEndedIterator for JunctionsRefIterator<'a> { // checked_sub here, because if the result is less than 0, we end iteration let index = self.junctions.len().checked_sub(next_back)?; if self.next > index { - return None + return None; } self.back = next_back; @@ -843,7 +843,7 @@ impl Junctions { /// ``` pub fn match_and_split(&self, prefix: &Junctions) -> Option<&Junction> { if prefix.len() + 1 != self.len() || !self.starts_with(prefix) { - return None + return None; } self.at(prefix.len()) } @@ -862,7 +862,7 @@ impl Junctions { /// ``` pub fn starts_with(&self, prefix: &Junctions) -> bool { if self.len() < prefix.len() { - return false + return false; } prefix.iter().zip(self.iter()).all(|(l, r)| l == r) } diff --git a/polkadot/xcm/src/v3/junction.rs b/polkadot/xcm/src/v3/junction.rs index e9e51941b1ac0..5431ed33256e5 100644 --- a/polkadot/xcm/src/v3/junction.rs +++ b/polkadot/xcm/src/v3/junction.rs @@ -188,7 +188,7 @@ impl TryFrom for BodyId { r.copy_from_slice(&n[..]); Self::Moniker(r) } else { - return Err(()) + return Err(()); }, Index(n) => Self::Index(n), Executive => Self::Executive, diff --git a/polkadot/xcm/src/v3/junctions.rs b/polkadot/xcm/src/v3/junctions.rs index 9748e81fa55f5..da401108c662c 100644 --- a/polkadot/xcm/src/v3/junctions.rs +++ b/polkadot/xcm/src/v3/junctions.rs @@ -112,7 +112,7 @@ impl<'a> Iterator for JunctionsRefIterator<'a> { type Item = &'a Junction; fn next(&mut self) -> Option<&'a Junction> { if self.next.saturating_add(self.back) >= self.junctions.len() { - return None + return None; } let result = self.junctions.at(self.next); @@ -127,7 +127,7 @@ impl<'a> DoubleEndedIterator for JunctionsRefIterator<'a> { // checked_sub here, because if the result is less than 0, we end iteration let index = self.junctions.len().checked_sub(next_back)?; if self.next > index { - return None + return None; } self.back = next_back; @@ -275,7 +275,7 @@ impl Junctions { /// junctions in `self`, implying that relative refers into a different global consensus. pub fn within_global(mut self, relative: MultiLocation) -> Result { if self.len() <= relative.parents as usize { - return Err(()) + return Err(()); } for _ in 0..relative.parents { self.take_last(); @@ -468,7 +468,7 @@ impl Junctions { pub fn append_with(&mut self, suffix: impl Into) -> Result<(), Junctions> { let suffix = suffix.into(); if self.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { - return Err(suffix) + return Err(suffix); } for j in suffix.into_iter() { self.push(j).expect("Already checked the sum of the len()s; qed") @@ -596,14 +596,14 @@ impl Junctions { /// ``` pub fn match_and_split(&self, prefix: &Junctions) -> Option<&Junction> { if prefix.len() + 1 != self.len() { - return None + return None; } for i in 0..prefix.len() { if prefix.at(i) != self.at(i) { - return None + return None; } } - return self.at(prefix.len()) + return self.at(prefix.len()); } pub fn starts_with(&self, prefix: &Junctions) -> bool { diff --git a/polkadot/xcm/src/v3/mod.rs b/polkadot/xcm/src/v3/mod.rs index d4e2da07a25ac..1298a874bc2a2 100644 --- a/polkadot/xcm/src/v3/mod.rs +++ b/polkadot/xcm/src/v3/mod.rs @@ -91,7 +91,7 @@ impl Decode for Xcm { instructions_count::with(|count| { *count = count.saturating_add(number_of_instructions as u8); if *count > MAX_INSTRUCTIONS_TO_DECODE { - return Err(CodecError::from("Max instructions exceeded")) + return Err(CodecError::from("Max instructions exceeded")); } Ok(()) }) diff --git a/polkadot/xcm/src/v3/multiasset.rs b/polkadot/xcm/src/v3/multiasset.rs index f9041ecd81bac..182bb20b7461f 100644 --- a/polkadot/xcm/src/v3/multiasset.rs +++ b/polkadot/xcm/src/v3/multiasset.rs @@ -738,7 +738,7 @@ impl MultiAssets { /// `From::>::from` which is infallible. pub fn from_sorted_and_deduplicated(r: Vec) -> Result { if r.is_empty() { - return Ok(Self(Vec::new())) + return Ok(Self(Vec::new())); } r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&MultiAsset, ()> { if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { @@ -780,7 +780,7 @@ impl MultiAssets { match (&a.fun, &mut asset.fun) { (Fungibility::Fungible(amount), Fungibility::Fungible(balance)) => { *balance = balance.saturating_add(*amount); - return + return; }, (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) if inst1 == inst2 => diff --git a/polkadot/xcm/src/v3/multilocation.rs b/polkadot/xcm/src/v3/multilocation.rs index c588b924ac708..9c6136992de61 100644 --- a/polkadot/xcm/src/v3/multilocation.rs +++ b/polkadot/xcm/src/v3/multilocation.rs @@ -233,7 +233,7 @@ impl MultiLocation { pub fn at(&self, i: usize) -> Option<&Junction> { let num_parents = self.parents as usize; if i < num_parents { - return None + return None; } self.interior.at(i - num_parents) } @@ -243,7 +243,7 @@ impl MultiLocation { pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { let num_parents = self.parents as usize; if i < num_parents { - return None + return None; } self.interior.at_mut(i - num_parents) } @@ -281,7 +281,7 @@ impl MultiLocation { /// ``` pub fn match_and_split(&self, prefix: &MultiLocation) -> Option<&Junction> { if self.parents != prefix.parents { - return None + return None; } self.interior.match_and_split(&prefix.interior) } @@ -345,12 +345,12 @@ impl MultiLocation { let prepend_interior = prefix.interior.len().saturating_sub(self.parents as usize); let final_interior = self.interior.len().saturating_add(prepend_interior); if final_interior > super::junctions::MAX_JUNCTIONS { - return Err(prefix) + return Err(prefix); } let suffix_parents = (self.parents as usize).saturating_sub(prefix.interior.len()); let final_parents = (prefix.parents as usize).saturating_add(suffix_parents); if final_parents > 255 { - return Err(prefix) + return Err(prefix); } // cancel out the final item on the prefix interior for one of the suffix's parents. @@ -437,7 +437,7 @@ impl MultiLocation { pub fn simplify(&mut self, context: &Junctions) { if context.len() < self.parents as usize { // Not enough context - return + return; } while self.parents > 0 { let maybe = context.at(context.len() - (self.parents as usize)); @@ -458,7 +458,7 @@ impl MultiLocation { while let Some(j) = clone.last() { if matches!(j, Junction::Parachain(_) | Junction::GlobalConsensus(_)) { // return chain subsection - return clone + return clone; } else { (clone, _) = clone.split_last_interior(); } diff --git a/polkadot/xcm/src/v3/traits.rs b/polkadot/xcm/src/v3/traits.rs index cfe387df1a86c..86a58de07abe5 100644 --- a/polkadot/xcm/src/v3/traits.rs +++ b/polkadot/xcm/src/v3/traits.rs @@ -281,7 +281,7 @@ pub trait ExecuteXcm { }; let xcm_weight = pre.weight_of(); if xcm_weight.any_gt(weight_limit) { - return Outcome::Error(Error::WeightLimitReached(xcm_weight)) + return Outcome::Error(Error::WeightLimitReached(xcm_weight)); } Self::execute(origin, pre, id, weight_credit) } @@ -326,7 +326,7 @@ pub trait ExecuteXcm { }; let xcm_weight = pre.weight_of(); if xcm_weight.any_gt(weight_limit) { - return Outcome::Error(Error::WeightLimitReached(xcm_weight)) + return Outcome::Error(Error::WeightLimitReached(xcm_weight)); } Self::execute(origin, pre, &mut hash, weight_credit) } diff --git a/polkadot/xcm/src/v4/asset.rs b/polkadot/xcm/src/v4/asset.rs index bdff0c272306a..778815d32e44c 100644 --- a/polkadot/xcm/src/v4/asset.rs +++ b/polkadot/xcm/src/v4/asset.rs @@ -636,7 +636,7 @@ impl Assets { /// `From::>::from` which is infallible. pub fn from_sorted_and_deduplicated(r: Vec) -> Result { if r.is_empty() { - return Ok(Self(Vec::new())) + return Ok(Self(Vec::new())); } r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&Asset, ()> { if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { @@ -678,7 +678,7 @@ impl Assets { match (&a.fun, &mut asset.fun) { (Fungibility::Fungible(amount), Fungibility::Fungible(balance)) => { *balance = balance.saturating_add(*amount); - return + return; }, (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) if inst1 == inst2 => diff --git a/substrate/client/service/test/src/lib.rs b/substrate/client/service/test/src/lib.rs index 9b88300bf5304..8c1c9a10a1816 100644 --- a/substrate/client/service/test/src/lib.rs +++ b/substrate/client/service/test/src/lib.rs @@ -29,7 +29,7 @@ use sc_network::{ use sc_network_sync::SyncingService; use sc_service::{ client::Client, - config::{BasePath, DatabaseSource, KeystoreConfig}, + config::{BasePath, DatabaseSource, KeystoreConfig, RpcBatchRequestConfig}, BlocksPruning, ChainSpecExtension, Configuration, Error, GenericChainSpec, Role, RuntimeGenesis, SpawnTaskHandle, TaskManager, }; @@ -254,6 +254,7 @@ fn node_config< rpc_max_subs_per_conn: Default::default(), rpc_port: 9944, rpc_message_buffer_capacity: Default::default(), + rpc_batch_config: RpcBatchRequestConfig::Unlimited, prometheus_config: None, telemetry_endpoints: None, default_heap_pages: None,