From ad1ae9405a6cb60c48988b94be4cc84d491a4700 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 1 Dec 2021 13:49:09 +0100 Subject: [PATCH 1/4] Enable off-chain indexing for Rialto & Millau nodes --- deployments/networks/millau.yml | 5 +++++ deployments/networks/rialto.yml | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/deployments/networks/millau.yml b/deployments/networks/millau.yml index 001f3a06094..15bd8316f73 100644 --- a/deployments/networks/millau.yml +++ b/deployments/networks/millau.yml @@ -17,6 +17,7 @@ services: - --alice - --node-key=0f900c89f4e626f4a217302ab8c7d213737d00627115f318ad6fb169717ac8e0 - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external environment: @@ -35,6 +36,7 @@ services: - --bob - --node-key=db383639ff2905d79f8e936fd5dc4416ef46b514b2f83823ec3c42753d7557bb - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -50,6 +52,7 @@ services: - --bootnodes=/dns4/millau-node-alice/tcp/30333/p2p/12D3KooWFqiV73ipQ1jpfVmCfLqBCp8G9PLH3zPkY9EhmdrSGA4H - --charlie - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -65,6 +68,7 @@ services: - --bootnodes=/dns4/millau-node-alice/tcp/30333/p2p/12D3KooWFqiV73ipQ1jpfVmCfLqBCp8G9PLH3zPkY9EhmdrSGA4H - --dave - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -80,6 +84,7 @@ services: - --bootnodes=/dns4/millau-node-alice/tcp/30333/p2p/12D3KooWFqiV73ipQ1jpfVmCfLqBCp8G9PLH3zPkY9EhmdrSGA4H - --eve - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: diff --git a/deployments/networks/rialto.yml b/deployments/networks/rialto.yml index 9b902a1ca28..7dfe7fcc10b 100644 --- a/deployments/networks/rialto.yml +++ b/deployments/networks/rialto.yml @@ -17,6 +17,7 @@ services: - --alice - --node-key=79cf382988364291a7968ae7825c01f68c50d679796a8983237d07fe0ccf363b - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external environment: @@ -35,6 +36,7 @@ services: - --bob - --node-key=4f9d0146dd9b7b3bf5a8089e3880023d1df92057f89e96e07bb4d8c2ead75bbd - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -50,6 +52,7 @@ services: - --bootnodes=/dns4/rialto-node-alice/tcp/30333/p2p/12D3KooWMF6JvV319a7kJn5pqkKbhR3fcM2cvK5vCbYZHeQhYzFE - --charlie - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -65,6 +68,7 @@ services: - --bootnodes=/dns4/rialto-node-alice/tcp/30333/p2p/12D3KooWMF6JvV319a7kJn5pqkKbhR3fcM2cvK5vCbYZHeQhYzFE - --dave - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: @@ -80,6 +84,7 @@ services: - --bootnodes=/dns4/rialto-node-alice/tcp/30333/p2p/12D3KooWMF6JvV319a7kJn5pqkKbhR3fcM2cvK5vCbYZHeQhYzFE - --eve - --rpc-cors=all + - --enable-offchain-indexing=true - --unsafe-rpc-external - --unsafe-ws-external ports: From 62ba20ca3c753f0f6527d3ae924a92ec0cccc8ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 1 Dec 2021 14:03:15 +0100 Subject: [PATCH 2/4] cargo fmt --all --- bin/millau/node/src/command.rs | 23 ++++---- bin/millau/node/src/service.rs | 7 ++- bin/millau/runtime/src/rialto_messages.rs | 11 ++-- bin/rialto-parachain/node/src/command.rs | 25 ++++---- bin/rialto-parachain/node/src/service.rs | 2 +- bin/rialto/node/src/command.rs | 27 ++++----- bin/rialto/node/src/service.rs | 2 +- bin/rialto/runtime/src/millau_messages.rs | 5 +- bin/runtime-common/src/messages.rs | 29 +++++----- .../src/messages_benchmarking.rs | 2 +- fuzz/storage-proof/src/main.rs | 2 +- modules/dispatch/src/lib.rs | 38 ++++++------ modules/grandpa/src/lib.rs | 10 ++-- modules/messages/src/inbound_lane.rs | 16 ++--- modules/messages/src/instant_payments.rs | 4 +- modules/messages/src/lib.rs | 49 ++++++++-------- modules/messages/src/mock.rs | 11 ++-- modules/messages/src/outbound_lane.rs | 24 ++++---- modules/messages/src/weights_ext.rs | 14 ++--- modules/shift-session-manager/src/lib.rs | 2 +- modules/token-swap/src/lib.rs | 35 +++++------ primitives/header-chain/src/justification.rs | 20 +++---- .../tests/implementation_match.rs | 4 +- primitives/messages/src/lib.rs | 2 +- primitives/runtime/src/lib.rs | 15 +++-- primitives/runtime/src/storage_proof.rs | 2 +- relays/bin-substrate/src/chains/kusama.rs | 7 ++- relays/bin-substrate/src/chains/millau.rs | 19 +++--- relays/bin-substrate/src/chains/polkadot.rs | 7 ++- relays/bin-substrate/src/chains/rialto.rs | 19 +++--- .../src/chains/rialto_parachain.rs | 5 +- relays/bin-substrate/src/chains/rococo.rs | 7 ++- relays/bin-substrate/src/chains/wococo.rs | 7 ++- relays/bin-substrate/src/cli/encode_call.rs | 15 ++--- relays/bin-substrate/src/cli/init_bridge.rs | 14 ++--- relays/bin-substrate/src/cli/mod.rs | 14 ++--- .../src/cli/register_parachain.rs | 6 +- relays/bin-substrate/src/cli/relay_headers.rs | 14 ++--- .../src/cli/resubmit_transactions.rs | 40 +++++++------ relays/bin-substrate/src/cli/send_message.rs | 2 +- relays/bin-substrate/src/cli/swap_tokens.rs | 58 ++++++++++--------- relays/client-substrate/src/client.rs | 15 ++--- .../client-substrate/src/finality_source.rs | 6 +- relays/client-substrate/src/guard.rs | 6 +- .../src/metrics/float_storage_value.rs | 4 +- relays/finality/src/finality_loop.rs | 46 ++++++++------- .../src/conversion_rate_update.rs | 10 ++-- .../src/headers_initialize.rs | 4 +- .../lib-substrate-relay/src/messages_lane.rs | 4 +- .../src/messages_source.rs | 10 ++-- .../src/on_demand_headers.rs | 21 +++---- relays/messages/src/message_lane_loop.rs | 26 ++++----- relays/messages/src/message_race_delivery.rs | 26 ++++----- relays/messages/src/message_race_loop.rs | 10 ++-- relays/messages/src/message_race_strategy.rs | 15 ++--- .../relay_strategy/enforcement_strategy.rs | 20 ++++--- .../src/relay_strategy/rational_strategy.rs | 10 ++-- relays/utils/src/lib.rs | 10 ++-- relays/utils/src/metrics.rs | 8 +-- relays/utils/src/metrics/float_json_value.rs | 2 +- relays/utils/src/metrics/global.rs | 4 +- relays/utils/src/relay_loop.rs | 15 ++--- 62 files changed, 468 insertions(+), 419 deletions(-) diff --git a/bin/millau/node/src/command.rs b/bin/millau/node/src/command.rs index 4dbf9575dfe..63545ec9e61 100644 --- a/bin/millau/node/src/command.rs +++ b/bin/millau/node/src/command.rs @@ -77,7 +77,7 @@ pub fn run() -> sc_cli::Result<()> { )); match &cli.subcommand { - Some(Subcommand::Benchmark(cmd)) => + Some(Subcommand::Benchmark(cmd)) => { if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -88,7 +88,8 @@ pub fn run() -> sc_cli::Result<()> { You can enable it with `--features runtime-benchmarks`." ); Ok(()) - }, + } + } Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), @@ -96,7 +97,7 @@ pub fn run() -> sc_cli::Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, + } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { @@ -104,21 +105,21 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) - }, + } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = new_partial(&config)?; Ok((cmd.run(client, config.database), task_manager)) }) - }, + } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = new_partial(&config)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) - }, + } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { @@ -126,28 +127,28 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) - }, + } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.database)) - }, + } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, backend, .. } = new_partial(&config)?; Ok((cmd.run(client, backend), task_manager)) }) - }, + } Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; runner .sync_run(|config| cmd.run::(config)) - }, + } None => { let runner = cli.create_runner(&cli.run)?; runner.run_node_until_exit(|config| async move { service::new_full(config).map_err(sc_cli::Error::Service) }) - }, + } } } diff --git a/bin/millau/node/src/service.rs b/bin/millau/node/src/service.rs index b01c0bfca90..233e2a3fbed 100644 --- a/bin/millau/node/src/service.rs +++ b/bin/millau/node/src/service.rs @@ -89,7 +89,7 @@ pub fn new_partial( ServiceError, > { if config.keystore_remote.is_some() { - return Err(ServiceError::Other(format!("Remote Keystores are not supported."))) + return Err(ServiceError::Other(format!("Remote Keystores are not supported."))); } let telemetry = config @@ -201,11 +201,12 @@ pub fn new_full(mut config: Configuration) -> Result if let Some(url) = &config.keystore_remote { match remote_keystore(url) { Ok(k) => keystore_container.set_remote_keystore(k), - Err(e) => + Err(e) => { return Err(ServiceError::Other(format!( "Error hooking up remote keystore for {}: {}", url, e - ))), + ))) + } }; } diff --git a/bin/millau/runtime/src/rialto_messages.rs b/bin/millau/runtime/src/rialto_messages.rs index 6d9677c45cf..99d61476b79 100644 --- a/bin/millau/runtime/src/rialto_messages.rs +++ b/bin/millau/runtime/src/rialto_messages.rs @@ -116,9 +116,9 @@ impl messages::ThisChainWithMessages for Millau { type Call = crate::Call; fn is_outbound_lane_enabled(lane: &LaneId) -> bool { - *lane == [0, 0, 0, 0] || - *lane == [0, 0, 0, 1] || - *lane == crate::TokenSwapMessagesLane::get() + *lane == [0, 0, 0, 0] + || *lane == [0, 0, 0, 1] + || *lane == crate::TokenSwapMessagesLane::get() } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { @@ -284,8 +284,9 @@ pub enum MillauToRialtoMessagesParameter { impl MessagesParameter for MillauToRialtoMessagesParameter { fn save(&self) { match *self { - MillauToRialtoMessagesParameter::RialtoToMillauConversionRate(ref conversion_rate) => - RialtoToMillauConversionRate::set(conversion_rate), + MillauToRialtoMessagesParameter::RialtoToMillauConversionRate(ref conversion_rate) => { + RialtoToMillauConversionRate::set(conversion_rate) + } } } } diff --git a/bin/rialto-parachain/node/src/command.rs b/bin/rialto-parachain/node/src/command.rs index e4f52cc026a..419291bb927 100644 --- a/bin/rialto-parachain/node/src/command.rs +++ b/bin/rialto-parachain/node/src/command.rs @@ -161,27 +161,27 @@ pub fn run() -> Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, + } Some(Subcommand::CheckBlock(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) - }, + } Some(Subcommand::ExportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, config.database) )) - }, + } Some(Subcommand::ExportState(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, config.chain_spec) )) - }, + } Some(Subcommand::ImportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) - }, + } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; @@ -200,12 +200,12 @@ pub fn run() -> Result<()> { cmd.run(config, polkadot_config) }) - }, + } Some(Subcommand::Revert(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, components.backend) )) - }, + } Some(Subcommand::ExportGenesisState(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); @@ -229,7 +229,7 @@ pub fn run() -> Result<()> { } Ok(()) - }, + } Some(Subcommand::ExportGenesisWasm(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); @@ -250,8 +250,8 @@ pub fn run() -> Result<()> { } Ok(()) - }, - Some(Subcommand::Benchmark(cmd)) => + } + Some(Subcommand::Benchmark(cmd)) => { if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -260,7 +260,8 @@ pub fn run() -> Result<()> { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into()) - }, + } + } None => { let runner = cli.create_runner(&cli.run.normalize())?; @@ -299,7 +300,7 @@ pub fn run() -> Result<()> { .map(|r| r.0) .map_err(Into::into) }) - }, + } } } diff --git a/bin/rialto-parachain/node/src/service.rs b/bin/rialto-parachain/node/src/service.rs index bd3afca3074..fdc213f82b5 100644 --- a/bin/rialto-parachain/node/src/service.rs +++ b/bin/rialto-parachain/node/src/service.rs @@ -246,7 +246,7 @@ where ) -> Result>, sc_service::Error>, { if matches!(parachain_config.role, Role::Light) { - return Err("Light client not supported!".into()) + return Err("Light client not supported!".into()); } let parachain_config = prepare_node_config(parachain_config); diff --git a/bin/rialto/node/src/command.rs b/bin/rialto/node/src/command.rs index 7be615a5776..0456fda7e96 100644 --- a/bin/rialto/node/src/command.rs +++ b/bin/rialto/node/src/command.rs @@ -75,7 +75,7 @@ pub fn run() -> sc_cli::Result<()> { )); match &cli.subcommand { - Some(Subcommand::Benchmark(cmd)) => + Some(Subcommand::Benchmark(cmd)) => { if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -86,7 +86,8 @@ pub fn run() -> sc_cli::Result<()> { You can enable it with `--features runtime-benchmarks`." ); Ok(()) - }, + } + } Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), @@ -94,7 +95,7 @@ pub fn run() -> sc_cli::Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - }, + } Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -102,7 +103,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, import_queue), task_manager)) }) - }, + } Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -110,7 +111,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, config.database), task_manager)) }) - }, + } Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -118,7 +119,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) - }, + } Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -126,11 +127,11 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, import_queue), task_manager)) }) - }, + } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.database)) - }, + } Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -138,13 +139,13 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, backend), task_manager)) }) - }, + } Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { cmd.run::(config) }) - }, + } Some(Subcommand::PvfPrepareWorker(cmd)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_colors(false); @@ -152,7 +153,7 @@ pub fn run() -> sc_cli::Result<()> { polkadot_node_core_pvf::prepare_worker_entrypoint(&cmd.socket_path); Ok(()) - }, + } Some(crate::cli::Subcommand::PvfExecuteWorker(cmd)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_colors(false); @@ -160,7 +161,7 @@ pub fn run() -> sc_cli::Result<()> { polkadot_node_core_pvf::execute_worker_entrypoint(&cmd.socket_path); Ok(()) - }, + } None => { let runner = cli.create_runner(&cli.run)?; @@ -181,7 +182,7 @@ pub fn run() -> sc_cli::Result<()> { .map_err(service_error), } }) - }, + } } } diff --git a/bin/rialto/node/src/service.rs b/bin/rialto/node/src/service.rs index 3349b09edb9..7dbc2c072ff 100644 --- a/bin/rialto/node/src/service.rs +++ b/bin/rialto/node/src/service.rs @@ -344,7 +344,7 @@ where // Only consider leaves that are in maximum an uncle of the best block. if number < best_block.number().saturating_sub(1) || hash == best_block.hash() { - return None + return None; } let parent_hash = client.header(&BlockId::Hash(hash)).ok()??.parent_hash; diff --git a/bin/rialto/runtime/src/millau_messages.rs b/bin/rialto/runtime/src/millau_messages.rs index 13a1c6b06ec..52f9e0212ee 100644 --- a/bin/rialto/runtime/src/millau_messages.rs +++ b/bin/rialto/runtime/src/millau_messages.rs @@ -282,8 +282,9 @@ pub enum RialtoToMillauMessagesParameter { impl MessagesParameter for RialtoToMillauMessagesParameter { fn save(&self) { match *self { - RialtoToMillauMessagesParameter::MillauToRialtoConversionRate(ref conversion_rate) => - MillauToRialtoConversionRate::set(conversion_rate), + RialtoToMillauMessagesParameter::MillauToRialtoConversionRate(ref conversion_rate) => { + MillauToRialtoConversionRate::set(conversion_rate) + } } } } diff --git a/bin/runtime-common/src/messages.rs b/bin/runtime-common/src/messages.rs index b34cbb85540..03faa2714ab 100644 --- a/bin/runtime-common/src/messages.rs +++ b/bin/runtime-common/src/messages.rs @@ -299,7 +299,7 @@ pub mod source { ) -> Result<(), Self::Error> { // reject message if lane is blocked if !ThisChain::::is_outbound_lane_enabled(lane) { - return Err(OUTBOUND_LANE_DISABLED) + return Err(OUTBOUND_LANE_DISABLED); } // reject message if there are too many pending messages at this lane @@ -308,7 +308,7 @@ pub mod source { .latest_generated_nonce .saturating_sub(lane_outbound_data.latest_received_nonce); if pending_messages > max_pending_messages { - return Err(TOO_MANY_PENDING_MESSAGES) + return Err(TOO_MANY_PENDING_MESSAGES); } // Do the dispatch-specific check. We assume that the target chain uses @@ -321,7 +321,7 @@ pub mod source { // compare with actual fee paid if *delivery_and_dispatch_fee < minimal_fee_in_this_tokens { - return Err(TOO_LOW_FEE) + return Err(TOO_LOW_FEE); } Ok(()) @@ -343,7 +343,7 @@ pub mod source { ) -> Result<(), &'static str> { let weight_limits = BridgedChain::::message_weight_limits(&payload.call); if !weight_limits.contains(&payload.weight.into()) { - return Err("Incorrect message weight declared") + return Err("Incorrect message weight declared"); } // The maximal size of extrinsic at Substrate-based chain depends on the @@ -357,7 +357,7 @@ pub mod source { // transaction also contains signatures and signed extensions. Because of this, we reserve // 1/3 of the the maximal extrinsic weight for this data. if payload.call.len() > maximal_message_size::() as usize { - return Err("The message is too large to be sent over the lane") + return Err("The message is too large to be sent over the lane"); } Ok(()) @@ -646,13 +646,16 @@ pub mod target { fn from(err: MessageProofError) -> &'static str { match err { MessageProofError::Empty => "Messages proof is empty", - MessageProofError::MessagesCountMismatch => - "Declared messages count doesn't match actual value", + MessageProofError::MessagesCountMismatch => { + "Declared messages count doesn't match actual value" + } MessageProofError::MissingRequiredMessage => "Message is missing from the proof", - MessageProofError::FailedToDecodeMessage => - "Failed to decode message from the proof", - MessageProofError::FailedToDecodeOutboundLaneState => - "Failed to decode outbound lane data from the proof", + MessageProofError::FailedToDecodeMessage => { + "Failed to decode message from the proof" + } + MessageProofError::FailedToDecodeOutboundLaneState => { + "Failed to decode outbound lane data from the proof" + } MessageProofError::Custom(err) => err, } } @@ -718,7 +721,7 @@ pub mod target { // (this bounds maximal capacity of messages vec below) let messages_in_the_proof = nonces_difference.saturating_add(1); if messages_in_the_proof != MessageNonce::from(messages_count) { - return Err(MessageProofError::MessagesCountMismatch) + return Err(MessageProofError::MessagesCountMismatch); } messages_in_the_proof @@ -757,7 +760,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(MessageProofError::Empty) + return Err(MessageProofError::Empty); } // We only support single lane messages in this schema diff --git a/bin/runtime-common/src/messages_benchmarking.rs b/bin/runtime-common/src/messages_benchmarking.rs index 217560e1143..c288d234dea 100644 --- a/bin/runtime-common/src/messages_benchmarking.rs +++ b/bin/runtime-common/src/messages_benchmarking.rs @@ -218,7 +218,7 @@ fn grow_trie(mut root: H::Out, mdb: &mut MemoryDB, trie_size: Proo .expect("record_all_keys should not fail in benchmarks"); let size: usize = proof_recorder.drain().into_iter().map(|n| n.data.len()).sum(); if size > minimal_trie_size as _ { - return root + return root; } let mut trie = TrieDBMut::::from_existing(mdb, &mut root) diff --git a/fuzz/storage-proof/src/main.rs b/fuzz/storage-proof/src/main.rs index 42636a65c3d..433d054cd4e 100644 --- a/fuzz/storage-proof/src/main.rs +++ b/fuzz/storage-proof/src/main.rs @@ -57,7 +57,7 @@ fn transform_into_unique(input_vec: Vec<(Vec, Vec)>) -> Vec<(Vec, Ve fn run_fuzzer() { fuzz!(|input_vec: Vec<(Vec, Vec)>| { if input_vec.is_empty() { - return + return; } let unique_input_vec = transform_into_unique(input_vec); let (root, craft_known_storage_proof) = craft_known_storage_proof(unique_input_vec.clone()); diff --git a/modules/dispatch/src/lib.rs b/modules/dispatch/src/lib.rs index f467bab0d94..65b469dc4f0 100644 --- a/modules/dispatch/src/lib.rs +++ b/modules/dispatch/src/lib.rs @@ -173,8 +173,8 @@ impl, I: 'static> MessageDispatch dispatch_result: false, unspent_weight: 0, dispatch_fee_paid_during_dispatch: false, - } - }, + }; + } }; // verify spec version @@ -199,7 +199,7 @@ impl, I: 'static> MessageDispatch expected_version, message.spec_version, )); - return dispatch_result + return dispatch_result; } // now that we have spec version checked, let's decode the call @@ -213,8 +213,8 @@ impl, I: 'static> MessageDispatch id, ); Self::deposit_event(Event::MessageCallDecodeFailed(source_chain, id)); - return dispatch_result - }, + return dispatch_result; + } }; // prepare dispatch origin @@ -225,7 +225,7 @@ impl, I: 'static> MessageDispatch let target_id = T::AccountIdConverter::convert(hex_id); log::trace!(target: "runtime::bridge-dispatch", "Root Account: {:?}", &target_id); target_id - }, + } CallOrigin::TargetAccount(source_account_id, target_public, target_signature) => { let digest = account_ownership_digest( &call, @@ -246,19 +246,19 @@ impl, I: 'static> MessageDispatch target_signature, ); Self::deposit_event(Event::MessageSignatureMismatch(source_chain, id)); - return dispatch_result + return dispatch_result; } log::trace!(target: "runtime::bridge-dispatch", "Target Account: {:?}", &target_account); target_account - }, + } CallOrigin::SourceAccount(source_account_id) => { let hex_id = derive_account_id(source_chain, SourceAccount::Account(source_account_id)); let target_id = T::AccountIdConverter::convert(hex_id); log::trace!(target: "runtime::bridge-dispatch", "Source Account: {:?}", &target_id); target_id - }, + } }; // filter the call @@ -271,7 +271,7 @@ impl, I: 'static> MessageDispatch call, ); Self::deposit_event(Event::MessageCallRejected(source_chain, id)); - return dispatch_result + return dispatch_result; } // verify weight @@ -294,14 +294,14 @@ impl, I: 'static> MessageDispatch expected_weight, message.weight, )); - return dispatch_result + return dispatch_result; } // pay dispatch fee right before dispatch let pay_dispatch_fee_at_target_chain = message.dispatch_fee_payment == DispatchFeePayment::AtTargetChain; - if pay_dispatch_fee_at_target_chain && - pay_dispatch_fee(&origin_account, message.weight).is_err() + if pay_dispatch_fee_at_target_chain + && pay_dispatch_fee(&origin_account, message.weight).is_err() { log::trace!( target: "runtime::bridge-dispatch", @@ -316,7 +316,7 @@ impl, I: 'static> MessageDispatch origin_account, message.weight, )); - return dispatch_result + return dispatch_result; } dispatch_result.dispatch_fee_paid_during_dispatch = pay_dispatch_fee_at_target_chain; @@ -377,19 +377,19 @@ where CallOrigin::SourceRoot => { ensure!(sender_origin == &RawOrigin::Root, BadOrigin); Ok(None) - }, + } CallOrigin::TargetAccount(ref source_account_id, _, _) => { ensure!(sender_origin == &RawOrigin::Signed(source_account_id.clone()), BadOrigin); Ok(Some(source_account_id.clone())) - }, + } CallOrigin::SourceAccount(ref source_account_id) => { ensure!( - sender_origin == &RawOrigin::Signed(source_account_id.clone()) || - sender_origin == &RawOrigin::Root, + sender_origin == &RawOrigin::Signed(source_account_id.clone()) + || sender_origin == &RawOrigin::Root, BadOrigin ); Ok(Some(source_account_id.clone())) - }, + } } } diff --git a/modules/grandpa/src/lib.rs b/modules/grandpa/src/lib.rs index cbc85da3025..1446c3696f5 100644 --- a/modules/grandpa/src/lib.rs +++ b/modules/grandpa/src/lib.rs @@ -149,7 +149,7 @@ pub mod pallet { finality_target, ); fail!(>::NotInitialized); - }, + } }; // We do a quick check here to ensure that our header chain is making progress and isn't @@ -220,11 +220,11 @@ pub mod pallet { Some(new_owner) => { PalletOwner::::put(&new_owner); log::info!(target: "runtime::bridge-grandpa", "Setting pallet Owner to: {:?}", new_owner); - }, + } None => { PalletOwner::::kill(); log::info!(target: "runtime::bridge-grandpa", "Removed Owner of pallet."); - }, + } } Ok(().into()) @@ -514,7 +514,9 @@ pub mod pallet { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == >::get().as_ref() => - Ok(()), + { + Ok(()) + } _ => Err(BadOrigin), } } diff --git a/modules/messages/src/inbound_lane.rs b/modules/messages/src/inbound_lane.rs index 00875bb878a..94d9c4b7ee5 100644 --- a/modules/messages/src/inbound_lane.rs +++ b/modules/messages/src/inbound_lane.rs @@ -81,10 +81,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; @@ -108,8 +108,8 @@ impl InboundLane { .dispatch_results .split_off((new_confirmed_nonce + 1 - entry.messages.begin) as _); entry.messages.begin = new_confirmed_nonce + 1; - }, - _ => {}, + } + _ => {} } self.storage.set_data(data); @@ -127,18 +127,18 @@ impl InboundLane { let mut data = self.storage.data(); let is_correct_message = nonce == data.last_delivered_nonce() + 1; if !is_correct_message { - 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 @@ -155,7 +155,7 @@ impl InboundLane { Some(entry) if entry.relayer == *relayer_at_bridged_chain => { entry.messages.note_dispatched_message(dispatch_result.dispatch_result); false - }, + } _ => true, }; if push_new { diff --git a/modules/messages/src/instant_payments.rs b/modules/messages/src/instant_payments.rs index c145687af99..23b0df41074 100644 --- a/modules/messages/src/instant_payments.rs +++ b/modules/messages/src/instant_payments.rs @@ -171,7 +171,7 @@ fn pay_relayers_rewards( // If delivery confirmation is submitted by this relayer, let's add confirmation fee // from other relayers to this relayer reward. confirmation_relayer_reward = confirmation_relayer_reward.saturating_add(reward.reward); - continue + continue; } pay_relayer_reward::(relayer_fund_account, &relayer, relayer_reward); @@ -195,7 +195,7 @@ fn pay_relayer_reward( Currency: CurrencyT, { if reward.is_zero() { - return + return; } let pay_result = Currency::transfer( diff --git a/modules/messages/src/lib.rs b/modules/messages/src/lib.rs index 119869d81e9..f7b641f57eb 100644 --- a/modules/messages/src/lib.rs +++ b/modules/messages/src/lib.rs @@ -223,11 +223,11 @@ pub mod pallet { Some(new_owner) => { PalletOwner::::put(&new_owner); log::info!(target: "runtime::bridge-messages", "Setting pallet Owner to: {:?}", new_owner); - }, + } None => { PalletOwner::::kill(); log::info!(target: "runtime::bridge-messages", "Removed Owner of pallet."); - }, + } } Ok(()) } @@ -444,7 +444,7 @@ pub mod pallet { dispatch_weight, dispatch_weight_left, ); - break + break; } total_messages += 1; @@ -468,10 +468,10 @@ pub mod pallet { dispatch_result.unspent_weight, !dispatch_result.dispatch_fee_paid_during_dispatch, ) - }, - ReceivalResult::InvalidNonce | - ReceivalResult::TooManyUnrewardedRelayers | - ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), + } + ReceivalResult::InvalidNonce + | ReceivalResult::TooManyUnrewardedRelayers + | ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), }; let unspent_weight = sp_std::cmp::min(unspent_weight, dispatch_weight); @@ -548,10 +548,10 @@ pub mod pallet { // (we only care about total number of entries and messages, because this affects call // weight) ensure!( - total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) == - relayers_state.total_messages && - lane_data.relayers.len() as MessageNonce == - relayers_state.unrewarded_relayer_entries, + total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) + == relayers_state.total_messages + && lane_data.relayers.len() as MessageNonce + == relayers_state.unrewarded_relayer_entries, Error::::InvalidUnrewardedRelayersState ); @@ -563,8 +563,9 @@ pub mod pallet { last_delivered_nonce, &lane_data.relayers, ) { - ReceivalConfirmationResult::ConfirmedMessages(confirmed_messages) => - Some(confirmed_messages), + ReceivalConfirmationResult::ConfirmedMessages(confirmed_messages) => { + Some(confirmed_messages) + } ReceivalConfirmationResult::NoNewConfirmations => None, ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected( to_confirm_messages_count, @@ -577,7 +578,7 @@ pub mod pallet { ); fail!(Error::::TryingToConfirmMoreMessagesThanExpected); - }, + } error => { log::trace!( target: "runtime::bridge-messages", @@ -586,7 +587,7 @@ pub mod pallet { ); fail!(Error::::InvalidUnrewardedRelayers); - }, + } }; if let Some(confirmed_messages) = confirmed_messages { @@ -607,7 +608,7 @@ pub mod pallet { difference, ); actual_weight = actual_weight.saturating_sub(difference); - }, + } None => { debug_assert!( false, @@ -620,7 +621,7 @@ pub mod pallet { preliminary_callback_overhead, actual_callback_weight, ); - }, + } } // emit 'delivered' event @@ -950,7 +951,7 @@ fn send_message, I: 'static>( difference, ); actual_weight = actual_weight.saturating_sub(difference); - }, + } None => { debug_assert!(false, "T::OnMessageAccepted callback consumed too much weight."); log::error!( @@ -960,7 +961,7 @@ fn send_message, I: 'static>( single_message_callback_overhead, actual_callback_weight, ); - }, + } } // message sender pays for pruning at most `MaxMessagesToPruneAtOnce` messages @@ -991,7 +992,9 @@ fn ensure_owner_or_root, I: 'static>(origin: T::Origin) -> Result<( Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == Pallet::::module_owner().as_ref() => - Ok(()), + { + Ok(()) + } _ => Err(BadOrigin), } } @@ -1072,7 +1075,7 @@ impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage< we have no recursive borrows; qed", ) = Some(data.clone()); data - }, + } } } @@ -2314,8 +2317,8 @@ mod tests { let weight_when_max_messages_are_pruned = send_regular_message(); assert_eq!( weight_when_max_messages_are_pruned, - when_zero_messages_are_pruned + - crate::mock::DbWeight::get().writes(max_messages_to_prune), + when_zero_messages_are_pruned + + crate::mock::DbWeight::get().writes(max_messages_to_prune), ); }); } diff --git a/modules/messages/src/mock.rs b/modules/messages/src/mock.rs index a333c95bb58..55047609b4d 100644 --- a/modules/messages/src/mock.rs +++ b/modules/messages/src/mock.rs @@ -159,8 +159,9 @@ pub enum TestMessagesParameter { impl MessagesParameter for TestMessagesParameter { fn save(&self) { match *self { - TestMessagesParameter::TokenConversionRate(conversion_rate) => - TokenConversionRate::set(&conversion_rate), + TestMessagesParameter::TokenConversionRate(conversion_rate) => { + TokenConversionRate::set(&conversion_rate) + } } } } @@ -323,8 +324,8 @@ impl TestMessageDeliveryAndDispatchPayment { /// Returns true if given fee has been paid by given submitter. pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool { - frame_support::storage::unhashed::get(b":message-fee:") == - Some((Sender::Signed(submitter), fee)) + frame_support::storage::unhashed::get(b":message-fee:") + == Some((Sender::Signed(submitter), fee)) } /// Returns true if given relayer has been rewarded with given balance. The reward-paid flag is @@ -346,7 +347,7 @@ impl MessageDeliveryAndDispatchPayment _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) { - return Err(TEST_ERROR) + return Err(TEST_ERROR); } frame_support::storage::unhashed::put(b":message-fee:", &(submitter, fee)); diff --git a/modules/messages/src/outbound_lane.rs b/modules/messages/src/outbound_lane.rs index c05437596db..c7f6b136478 100644 --- a/modules/messages/src/outbound_lane.rs +++ b/modules/messages/src/outbound_lane.rs @@ -107,10 +107,10 @@ impl OutboundLane { ) -> ReceivalConfirmationResult { let mut data = self.storage.data(); if latest_delivered_nonce <= data.latest_received_nonce { - return ReceivalConfirmationResult::NoNewConfirmations + return ReceivalConfirmationResult::NoNewConfirmations; } if latest_delivered_nonce > data.latest_generated_nonce { - return ReceivalConfirmationResult::FailedToConfirmFutureMessages + return ReceivalConfirmationResult::FailedToConfirmFutureMessages; } if latest_delivered_nonce - data.latest_received_nonce > max_allowed_messages { // that the relayer has declared correct number of messages that the proof contains (it @@ -120,7 +120,7 @@ impl OutboundLane { // weight formula accounts, so we can't allow that. return ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected( latest_delivered_nonce - data.latest_received_nonce, - ) + ); } let dispatch_results = match extract_dispatch_results( @@ -150,8 +150,8 @@ impl OutboundLane { let mut pruned_messages = 0; let mut anything_changed = false; let mut data = self.storage.data(); - while pruned_messages < max_messages_to_prune && - data.oldest_unpruned_nonce <= data.latest_received_nonce + while pruned_messages < max_messages_to_prune + && data.oldest_unpruned_nonce <= data.latest_received_nonce { self.storage.remove_message(&data.oldest_unpruned_nonce); @@ -188,14 +188,14 @@ fn extract_dispatch_results( // 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(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry) + return Err(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry); } // every entry must confirm range of messages that follows previous entry range // (guaranteed by the `InboundLane::receive_message()`) if let Some(last_entry_end) = last_entry_end { let expected_entry_begin = last_entry_end.checked_add(1); if expected_entry_begin != Some(entry.messages.begin) { - return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries) + return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries); } } last_entry_end = Some(entry.messages.end); @@ -205,14 +205,14 @@ fn extract_dispatch_results( // technically this will be detected in the next loop iteration as // `InvalidNumberOfDispatchResults` but to guarantee safety of loop operations below // this is detected now - return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages) + return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages); } // entry must have single dispatch result for every message // (guaranteed by the `InboundLane::receive_message()`) - if entry.messages.dispatch_results.len() as MessageNonce != - entry.messages.end - entry.messages.begin + 1 + if entry.messages.dispatch_results.len() as MessageNonce + != entry.messages.end - entry.messages.begin + 1 { - return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults) + return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults); } // now we know that the entry is valid @@ -222,7 +222,7 @@ fn extract_dispatch_results( let new_messages_end = sp_std::cmp::min(entry.messages.end, latest_received_nonce); let new_messages_range = new_messages_begin..=new_messages_end; if new_messages_range.is_empty() { - continue + continue; } // now we know that entry brings new confirmations diff --git a/modules/messages/src/weights_ext.rs b/modules/messages/src/weights_ext.rs index fef09c6cebe..f83fc364cbb 100644 --- a/modules/messages/src/weights_ext.rs +++ b/modules/messages/src/weights_ext.rs @@ -61,8 +61,8 @@ pub fn ensure_weights_are_correct( 0, ); assert!( - actual_single_regular_message_delivery_tx_weight <= - expected_default_message_delivery_tx_weight, + actual_single_regular_message_delivery_tx_weight + <= expected_default_message_delivery_tx_weight, "Default message delivery transaction weight {} is larger than expected weight {}", actual_single_regular_message_delivery_tx_weight, expected_default_message_delivery_tx_weight, @@ -94,8 +94,8 @@ pub fn ensure_weights_are_correct( db_weight, ); assert!( - actual_messages_delivery_confirmation_tx_weight <= - expected_messages_delivery_confirmation_tx_weight, + actual_messages_delivery_confirmation_tx_weight + <= expected_messages_delivery_confirmation_tx_weight, "Messages delivery confirmation transaction weight {} is larger than expected weight {}", actual_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight, @@ -359,9 +359,9 @@ pub trait WeightInfoExt: WeightInfo { /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { let proof_size_in_bytes = proof_size as Weight; - let byte_weight = (Self::receive_single_message_proof_16_kb() - - Self::receive_single_message_proof_1_kb()) / - (15 * 1024); + let byte_weight = (Self::receive_single_message_proof_16_kb() + - Self::receive_single_message_proof_1_kb()) + / (15 * 1024); proof_size_in_bytes * byte_weight } diff --git a/modules/shift-session-manager/src/lib.rs b/modules/shift-session-manager/src/lib.rs index 06d0b3fb0f8..db4631e2753 100644 --- a/modules/shift-session-manager/src/lib.rs +++ b/modules/shift-session-manager/src/lib.rs @@ -54,7 +54,7 @@ impl pallet_session::SessionManager for Pallet { fn new_session(session_index: sp_staking::SessionIndex) -> Option> { // we don't want to add even more fields to genesis config => just return None if session_index == 0 || session_index == 1 { - return None + return None; } // the idea that on first call (i.e. when session 1 ends) we're reading current diff --git a/modules/token-swap/src/lib.rs b/modules/token-swap/src/lib.rs index 43fa13ba4bd..580427bf0ea 100644 --- a/modules/token-swap/src/lib.rs +++ b/modules/token-swap/src/lib.rs @@ -305,7 +305,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToTransferToSwapAccount, - )) + )); } // the transfer message is sent over the bridge. The message is supposed to be a @@ -339,8 +339,8 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToSendTransferMessage, - )) - }, + )); + } }; // remember that we have started the swap @@ -348,7 +348,7 @@ pub mod pallet { let insert_swap_result = PendingSwaps::::try_mutate(swap_hash, |maybe_state| { if maybe_state.is_some() { - return Err(()) + return Err(()); } *maybe_state = Some(TokenSwapState::Started); @@ -363,7 +363,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::SwapAlreadyStarted, - )) + )); } log::trace!( @@ -414,12 +414,13 @@ pub mod pallet { Some(TokenSwapState::Confirmed) => { let is_claim_allowed = match swap.swap_type { TokenSwapType::TemporaryTargetAccountAtBridgedChain => true, - TokenSwapType::LockClaimUntilBlock(block_number, _) => - block_number < frame_system::Pallet::::block_number(), + TokenSwapType::LockClaimUntilBlock(block_number, _) => { + block_number < frame_system::Pallet::::block_number() + } }; ensure!(is_claim_allowed, Error::::SwapIsTemporaryLocked); - }, + } Some(TokenSwapState::Failed) => fail!(Error::::SwapIsFailed), None => fail!(Error::::SwapIsInactive), } @@ -455,7 +456,7 @@ pub mod pallet { // we allow canceling swap even before lock period is over - the // `source_account_at_this_chain` has already paid for nothing and it is up to // him to decide whether he want to try again - }, + } None => fail!(Error::::SwapIsInactive), } @@ -529,7 +530,7 @@ pub mod pallet { fn on_messages_delivered(lane: &LaneId, delivered_messages: &DeliveredMessages) -> Weight { // we're only interested in our lane messages if *lane != T::OutboundMessageLaneId::get() { - return 0 + return 0; } // so now we're dealing with our lane messages. Ideally we'll have dedicated lane @@ -609,7 +610,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToTransferFromSwapAccount.into(), - )) + )); } log::trace!( @@ -841,8 +842,8 @@ mod tests { test_swap().source_balance_at_this_chain + SWAP_DELIVERY_AND_DISPATCH_FEE, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event == - crate::mock::Event::TokenSwap(crate::Event::SwapStarted( + frame_system::Pallet::::events().iter().any(|e| e.event + == crate::mock::Event::TokenSwap(crate::Event::SwapStarted( swap_hash, MESSAGE_NONCE, ))), @@ -974,8 +975,8 @@ mod tests { test_swap().source_balance_at_this_chain, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event == - crate::mock::Event::TokenSwap(crate::Event::SwapClaimed(swap_hash,))), + frame_system::Pallet::::events().iter().any(|e| e.event + == crate::mock::Event::TokenSwap(crate::Event::SwapClaimed(swap_hash,))), "Missing SwapClaimed event: {:?}", frame_system::Pallet::::events(), ); @@ -1078,8 +1079,8 @@ mod tests { THIS_CHAIN_ACCOUNT_BALANCE - SWAP_DELIVERY_AND_DISPATCH_FEE, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event == - crate::mock::Event::TokenSwap(crate::Event::SwapCanceled(swap_hash,))), + frame_system::Pallet::::events().iter().any(|e| e.event + == crate::mock::Event::TokenSwap(crate::Event::SwapCanceled(swap_hash,))), "Missing SwapCanceled event: {:?}", frame_system::Pallet::::events(), ); diff --git a/primitives/header-chain/src/justification.rs b/primitives/header-chain/src/justification.rs index 9f8e9662ea0..ea368546813 100644 --- a/primitives/header-chain/src/justification.rs +++ b/primitives/header-chain/src/justification.rs @@ -92,7 +92,7 @@ where { // ensure that it is justification for the expected header if (justification.commit.target_hash, justification.commit.target_number) != finalized_target { - return Err(Error::InvalidJustificationTarget) + return Err(Error::InvalidJustificationTarget); } let mut chain = AncestryChain::new(&justification.votes_ancestries); @@ -106,8 +106,8 @@ where None => { // just ignore precommit from unknown authority as // `finality_grandpa::import_precommit` does - continue - }, + continue; + } }; // check if authority has already voted in the same round. @@ -116,14 +116,14 @@ where // `finality-grandpa` crate (mostly related to reporing equivocations). But the only thing // that we care about is that only first vote from the authority is accepted if !votes.insert(signed.id.clone()) { - continue + continue; } // everything below this line can't just `continue`, because state is already altered // all precommits must be for block higher than the target if signed.precommit.target_number < justification.commit.target_number { - return Err(Error::PrecommitIsNotCommitDescendant) + return Err(Error::PrecommitIsNotCommitDescendant); } // all precommits must be for target block descendents chain = chain @@ -151,13 +151,13 @@ where authorities_set_id, &mut signature_buffer, ) { - return Err(Error::InvalidAuthoritySignature) + return Err(Error::InvalidAuthoritySignature); } } // check that there are no extra headers in the justification if !chain.unvisited.is_empty() { - return Err(Error::ExtraHeadersInVotesAncestries) + return Err(Error::ExtraHeadersInVotesAncestries); } // check that the cumulative weight of validators voted for the justification target (or one @@ -203,7 +203,7 @@ impl AncestryChain
{ let mut current_hash = *precommit_target; loop { if current_hash == *commit_target { - break + break; } let is_visited_before = !self.unvisited.remove(¤t_hash); @@ -214,11 +214,11 @@ impl AncestryChain
{ // container `is_visited_before` means that it has been visited before in // some of previous calls => since we assume that previous call has finished // with `true`, this also will be finished with `true` - return Ok(self) + return Ok(self); } *parent_hash - }, + } None => return Err(Error::PrecommitIsNotCommitDescendant), }; } diff --git a/primitives/header-chain/tests/implementation_match.rs b/primitives/header-chain/tests/implementation_match.rs index 51275bbd645..f33261fb52b 100644 --- a/primitives/header-chain/tests/implementation_match.rs +++ b/primitives/header-chain/tests/implementation_match.rs @@ -53,13 +53,13 @@ impl finality_grandpa::Chain for AncestryChain { let mut current_hash = block; loop { if current_hash == base { - break + break; } match self.0.parents.get(¤t_hash).cloned() { Some(parent_hash) => { current_hash = parent_hash; route.push(current_hash); - }, + } _ => return Err(finality_grandpa::Error::NotDescendent), } } diff --git a/primitives/messages/src/lib.rs b/primitives/messages/src/lib.rs index abefe8d789b..d2a61b8a7d2 100644 --- a/primitives/messages/src/lib.rs +++ b/primitives/messages/src/lib.rs @@ -316,7 +316,7 @@ pub fn total_unrewarded_messages( } else { Some(0) } - }, + } _ => Some(0), } } diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index 051dc1f43c0..dea577a844b 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -109,10 +109,12 @@ where AccountId: Encode, { match id { - SourceAccount::Root => - (ROOT_ACCOUNT_DERIVATION_PREFIX, bridge_id).using_encoded(blake2_256), - SourceAccount::Account(id) => - (ACCOUNT_DERIVATION_PREFIX, bridge_id, id).using_encoded(blake2_256), + SourceAccount::Root => { + (ROOT_ACCOUNT_DERIVATION_PREFIX, bridge_id).using_encoded(blake2_256) + } + SourceAccount::Account(id) => { + (ACCOUNT_DERIVATION_PREFIX, bridge_id, id).using_encoded(blake2_256) + } } .into() } @@ -186,8 +188,9 @@ impl, BlockHash: Copy> TransactionEra sp_runtime::generic::Era { match *self { TransactionEra::Immortal => sp_runtime::generic::Era::immortal(), - TransactionEra::Mortal(header_id, period) => - sp_runtime::generic::Era::mortal(period as _, header_id.0.into()), + TransactionEra::Mortal(header_id, period) => { + sp_runtime::generic::Era::mortal(period as _, header_id.0.into()) + } } } diff --git a/primitives/runtime/src/storage_proof.rs b/primitives/runtime/src/storage_proof.rs index 9cc5b48ebd9..7d9ddbda2db 100644 --- a/primitives/runtime/src/storage_proof.rs +++ b/primitives/runtime/src/storage_proof.rs @@ -42,7 +42,7 @@ where pub fn new(root: H::Out, proof: StorageProof) -> Result { let db = proof.into_memory_db(); if !db.contains(&root, EMPTY_PREFIX) { - return Err(Error::StorageRootMismatch) + return Err(Error::StorageRootMismatch); } let checker = StorageProofChecker { root, db }; diff --git a/relays/bin-substrate/src/chains/kusama.rs b/relays/bin-substrate/src/chains/kusama.rs index b12d23f2a56..3e9ae7b09fa 100644 --- a/relays/bin-substrate/src/chains/kusama.rs +++ b/relays/bin-substrate/src/chains/kusama.rs @@ -48,7 +48,7 @@ impl CliEncodeCall for Kusama { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::KUSAMA_TO_POLKADOT_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -57,12 +57,13 @@ impl CliEncodeCall for Kusama { lane.0, payload, fee.0, ), ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } _ => anyhow::bail!("Unsupported Kusama call: {:?}", call), }) } diff --git a/relays/bin-substrate/src/chains/millau.rs b/relays/bin-substrate/src/chains/millau.rs index 755d7cc4430..c6259c171bf 100644 --- a/relays/bin-substrate/src/chains/millau.rs +++ b/relays/bin-substrate/src/chains/millau.rs @@ -47,16 +47,18 @@ impl CliEncodeCall for Millau { fn encode_call(call: &Call) -> anyhow::Result { Ok(match call { Call::Raw { data } => Decode::decode(&mut &*data.0)?, - Call::Remark { remark_payload, .. } => + Call::Remark { remark_payload, .. } => { millau_runtime::Call::System(millau_runtime::SystemCall::remark { remark: remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), - }), - Call::Transfer { recipient, amount } => + }) + } + Call::Transfer { recipient, amount } => { millau_runtime::Call::Balances(millau_runtime::BalancesCall::transfer { dest: recipient.raw_id(), value: amount.cast(), - }), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + }) + } + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::MILLAU_TO_RIALTO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -67,12 +69,13 @@ impl CliEncodeCall for Millau { delivery_and_dispatch_fee: fee.cast(), }, ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } }) } @@ -128,7 +131,7 @@ impl CliChain for Millau { &call, DispatchFeePayment::AtSourceChain, )) - }, + } } } } diff --git a/relays/bin-substrate/src/chains/polkadot.rs b/relays/bin-substrate/src/chains/polkadot.rs index 7b6256d1749..e0f3c964264 100644 --- a/relays/bin-substrate/src/chains/polkadot.rs +++ b/relays/bin-substrate/src/chains/polkadot.rs @@ -48,7 +48,7 @@ impl CliEncodeCall for Polkadot { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::POLKADOT_TO_KUSAMA_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -57,12 +57,13 @@ impl CliEncodeCall for Polkadot { lane.0, payload, fee.0, ), ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } _ => anyhow::bail!("Unsupported Polkadot call: {:?}", call), }) } diff --git a/relays/bin-substrate/src/chains/rialto.rs b/relays/bin-substrate/src/chains/rialto.rs index 2d873a24ba7..b425898df1f 100644 --- a/relays/bin-substrate/src/chains/rialto.rs +++ b/relays/bin-substrate/src/chains/rialto.rs @@ -47,16 +47,18 @@ impl CliEncodeCall for Rialto { fn encode_call(call: &Call) -> anyhow::Result { Ok(match call { Call::Raw { data } => Decode::decode(&mut &*data.0)?, - Call::Remark { remark_payload, .. } => + Call::Remark { remark_payload, .. } => { rialto_runtime::Call::System(rialto_runtime::SystemCall::remark { remark: remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), - }), - Call::Transfer { recipient, amount } => + }) + } + Call::Transfer { recipient, amount } => { rialto_runtime::Call::Balances(rialto_runtime::BalancesCall::transfer { dest: recipient.raw_id().into(), value: amount.0, - }), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + }) + } + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::RIALTO_TO_MILLAU_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -67,12 +69,13 @@ impl CliEncodeCall for Rialto { delivery_and_dispatch_fee: fee.0, }, ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } }) } @@ -127,7 +130,7 @@ impl CliChain for Rialto { &call, DispatchFeePayment::AtSourceChain, )) - }, + } } } } diff --git a/relays/bin-substrate/src/chains/rialto_parachain.rs b/relays/bin-substrate/src/chains/rialto_parachain.rs index edd4ca36285..48ebd3602db 100644 --- a/relays/bin-substrate/src/chains/rialto_parachain.rs +++ b/relays/bin-substrate/src/chains/rialto_parachain.rs @@ -45,8 +45,9 @@ impl CliEncodeCall for RialtoParachain { value: amount.0, }, ), - Call::BridgeSendMessage { .. } => - anyhow::bail!("Bridge messages are not (yet) supported here",), + Call::BridgeSendMessage { .. } => { + anyhow::bail!("Bridge messages are not (yet) supported here",) + } }) } diff --git a/relays/bin-substrate/src/chains/rococo.rs b/relays/bin-substrate/src/chains/rococo.rs index 4df60f89faa..0a27e8b177a 100644 --- a/relays/bin-substrate/src/chains/rococo.rs +++ b/relays/bin-substrate/src/chains/rococo.rs @@ -44,7 +44,7 @@ impl CliEncodeCall for Rococo { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::ROCOCO_TO_WOCOCO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -53,12 +53,13 @@ impl CliEncodeCall for Rococo { lane.0, payload, fee.0, ), ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } _ => anyhow::bail!("The call is not supported"), }) } diff --git a/relays/bin-substrate/src/chains/wococo.rs b/relays/bin-substrate/src/chains/wococo.rs index 328397d14ba..9d7ace41a8a 100644 --- a/relays/bin-substrate/src/chains/wococo.rs +++ b/relays/bin-substrate/src/chains/wococo.rs @@ -38,7 +38,7 @@ impl CliEncodeCall for Wococo { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { match *bridge_instance_index { bridge::WOCOCO_TO_ROCOCO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -47,12 +47,13 @@ impl CliEncodeCall for Wococo { lane.0, payload, fee.0, ), ) - }, + } _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - }, + } + } _ => anyhow::bail!("The call is not supported"), }) } diff --git a/relays/bin-substrate/src/cli/encode_call.rs b/relays/bin-substrate/src/cli/encode_call.rs index e17854662e5..9429436fbf5 100644 --- a/relays/bin-substrate/src/cli/encode_call.rs +++ b/relays/bin-substrate/src/cli/encode_call.rs @@ -129,8 +129,8 @@ pub(crate) fn preprocess_call {}, - Call::Remark { ref remark_size, ref mut remark_payload } => + Call::Raw { .. } => {} + Call::Remark { ref remark_size, ref mut remark_payload } => { if remark_payload.is_none() { *remark_payload = Some(HexBytes(generate_remark_payload( remark_size, @@ -139,13 +139,14 @@ pub(crate) fn preprocess_call { recipient.enforce_chain::(); - }, + } Call::BridgeSendMessage { ref mut bridge_instance_index, .. } => { *bridge_instance_index = bridge_instance; - }, + } }; } @@ -286,8 +287,8 @@ mod tests { let info = err.info.unwrap(); assert!( - info.contains(&"remark-payload".to_string()) | - info.contains(&"remark-size".to_string()) + info.contains(&"remark-payload".to_string()) + | info.contains(&"remark-size".to_string()) ) } diff --git a/relays/bin-substrate/src/cli/init_bridge.rs b/relays/bin-substrate/src/cli/init_bridge.rs index ffda0b12008..39757ad6cf0 100644 --- a/relays/bin-substrate/src/cli/init_bridge.rs +++ b/relays/bin-substrate/src/cli/init_bridge.rs @@ -70,7 +70,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::RialtoToMillau => { type Source = relay_rialto_client::Rialto; type Target = relay_millau_client::Millau; @@ -88,7 +88,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::WestendToMillau => { type Source = relay_westend_client::Westend; type Target = relay_millau_client::Millau; @@ -110,7 +110,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::RococoToWococo => { type Source = relay_rococo_client::Rococo; type Target = relay_wococo_client::Wococo; @@ -126,7 +126,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::WococoToRococo => { type Source = relay_wococo_client::Wococo; type Target = relay_rococo_client::Rococo; @@ -142,7 +142,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::KusamaToPolkadot => { type Source = relay_kusama_client::Kusama; type Target = relay_polkadot_client::Polkadot; @@ -158,7 +158,7 @@ macro_rules! select_bridge { } $generic - }, + } InitBridgeName::PolkadotToKusama => { type Source = relay_polkadot_client::Polkadot; type Target = relay_kusama_client::Kusama; @@ -174,7 +174,7 @@ macro_rules! select_bridge { } $generic - }, + } } }; } diff --git a/relays/bin-substrate/src/cli/mod.rs b/relays/bin-substrate/src/cli/mod.rs index f1180059b99..252eb0c720a 100644 --- a/relays/bin-substrate/src/cli/mod.rs +++ b/relays/bin-substrate/src/cli/mod.rs @@ -104,15 +104,15 @@ impl Command { use relay_utils::initialize::{initialize_logger, initialize_relay}; match self { - Self::RelayHeaders(_) | - Self::RelayMessages(_) | - Self::RelayHeadersAndMessages(_) | - Self::InitBridge(_) => { + Self::RelayHeaders(_) + | Self::RelayMessages(_) + | Self::RelayHeadersAndMessages(_) + | Self::InitBridge(_) => { initialize_relay(); - }, + } _ => { initialize_logger(false); - }, + } } } @@ -359,7 +359,7 @@ where fn from_str(s: &str) -> Result { if s.to_lowercase() == "max" { - return Ok(ExplicitOrMaximal::Maximal) + return Ok(ExplicitOrMaximal::Maximal); } V::from_str(s) diff --git a/relays/bin-substrate/src/cli/register_parachain.rs b/relays/bin-substrate/src/cli/register_parachain.rs index fecc431148e..3e7d4e2a3cb 100644 --- a/relays/bin-substrate/src/cli/register_parachain.rs +++ b/relays/bin-substrate/src/cli/register_parachain.rs @@ -84,7 +84,7 @@ macro_rules! select_bridge { use bp_rialto::{PARAS_PALLET_NAME, PARAS_REGISTRAR_PALLET_NAME}; $generic - }, + } } }; } @@ -278,10 +278,10 @@ async fn wait_para_state( })?; if para_state == to_state { log::info!(target: "bridge", "Parachain state is now: {:?}", to_state); - return Ok(()) + return Ok(()); } if !from_states.contains(¶_state) { - return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state)) + return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state)); } log::info!(target: "bridge", "Parachain state: {:?}. Waiting for {:?}", para_state, to_state); diff --git a/relays/bin-substrate/src/cli/relay_headers.rs b/relays/bin-substrate/src/cli/relay_headers.rs index 82c55965a99..ef1905a0daf 100644 --- a/relays/bin-substrate/src/cli/relay_headers.rs +++ b/relays/bin-substrate/src/cli/relay_headers.rs @@ -66,49 +66,49 @@ macro_rules! select_bridge { type Finality = crate::chains::millau_headers_to_rialto::MillauFinalityToRialto; $generic - }, + } RelayHeadersBridge::RialtoToMillau => { type Source = relay_rialto_client::Rialto; type Target = relay_millau_client::Millau; type Finality = crate::chains::rialto_headers_to_millau::RialtoFinalityToMillau; $generic - }, + } RelayHeadersBridge::WestendToMillau => { type Source = relay_westend_client::Westend; type Target = relay_millau_client::Millau; type Finality = crate::chains::westend_headers_to_millau::WestendFinalityToMillau; $generic - }, + } RelayHeadersBridge::RococoToWococo => { type Source = relay_rococo_client::Rococo; type Target = relay_wococo_client::Wococo; type Finality = crate::chains::rococo_headers_to_wococo::RococoFinalityToWococo; $generic - }, + } RelayHeadersBridge::WococoToRococo => { type Source = relay_wococo_client::Wococo; type Target = relay_rococo_client::Rococo; type Finality = crate::chains::wococo_headers_to_rococo::WococoFinalityToRococo; $generic - }, + } RelayHeadersBridge::KusamaToPolkadot => { type Source = relay_kusama_client::Kusama; type Target = relay_polkadot_client::Polkadot; type Finality = crate::chains::kusama_headers_to_polkadot::KusamaFinalityToPolkadot; $generic - }, + } RelayHeadersBridge::PolkadotToKusama => { type Source = relay_polkadot_client::Polkadot; type Target = relay_kusama_client::Kusama; type Finality = crate::chains::polkadot_headers_to_kusama::PolkadotFinalityToKusama; $generic - }, + } } }; } diff --git a/relays/bin-substrate/src/cli/resubmit_transactions.rs b/relays/bin-substrate/src/cli/resubmit_transactions.rs index 64663d7e8ec..9b62b89b39f 100644 --- a/relays/bin-substrate/src/cli/resubmit_transactions.rs +++ b/relays/bin-substrate/src/cli/resubmit_transactions.rs @@ -92,19 +92,19 @@ macro_rules! select_bridge { type TargetSign = relay_millau_client::Millau; $generic - }, + } RelayChain::Kusama => { type Target = relay_kusama_client::Kusama; type TargetSign = relay_kusama_client::Kusama; $generic - }, + } RelayChain::Polkadot => { type Target = relay_polkadot_client::Polkadot; type TargetSign = relay_polkadot_client::Polkadot; $generic - }, + } } }; } @@ -154,10 +154,12 @@ impl PrioritySelectionStrategy { context: &Context, ) -> Result, SubstrateError> { match *self { - PrioritySelectionStrategy::MakeItBestTransaction => - read_previous_block_best_priority::(client, context).await, - PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction => - select_priority_from_queue::(client, context).await, + PrioritySelectionStrategy::MakeItBestTransaction => { + read_previous_block_best_priority::(client, context).await + } + PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction => { + select_priority_from_queue::(client, context).await + } } } } @@ -228,8 +230,8 @@ async fn run_until_connection_lost C::NAME, error, ); - return Err(FailedClient::Target) - }, + return Err(FailedClient::Target); + } }; } } @@ -248,8 +250,8 @@ async fn run_loop_iteration>( Some(original_transaction) => original_transaction, None => { log::trace!(target: "bridge", "No {} transactions from required signer in the txpool", C::NAME); - return Ok(context) - }, + return Ok(context); + } }; let original_transaction_hash = C::Hasher::hash(&original_transaction.encode()); let context = context.notice_transaction(original_transaction_hash); @@ -264,7 +266,7 @@ async fn run_loop_iteration>( context.stalled_for, context.stalled_for_limit, ); - return Ok(context) + return Ok(context); } // select priority for updated transaction @@ -273,8 +275,8 @@ async fn run_loop_iteration>( Some(target_priority) => target_priority, None => { log::trace!(target: "bridge", "Failed to select target priority"); - return Ok(context) - }, + return Ok(context); + } }; // update transaction tip @@ -291,7 +293,7 @@ async fn run_loop_iteration>( if !is_updated { log::trace!(target: "bridge", "{} transaction tip can not be updated. Reached limit?", C::NAME); - return Ok(context) + return Ok(context); } let updated_transaction = updated_transaction.encode(); @@ -319,10 +321,10 @@ async fn lookup_signer_transaction let pending_transaction = S::SignedTransaction::decode(&mut &pending_transaction.0[..]) .map_err(SubstrateError::ResponseParseFailed)?; if !S::is_signed_by(key_pair, &pending_transaction) { - continue + continue; } - return Ok(Some(pending_transaction)) + return Ok(Some(pending_transaction)); } Ok(None) @@ -377,7 +379,7 @@ fn select_transaction_from_queue( context: &Context, ) -> Option { if queued_transactions.is_empty() { - return None + return None; } // the more times we resubmit transaction (`context.resubmitted`), the closer we move @@ -414,7 +416,7 @@ async fn update_transaction_tip>( while current_priority < target_priority { let next_tip = unsigned_tx.tip + tip_step; if next_tip > tip_limit { - break + break; } log::trace!( diff --git a/relays/bin-substrate/src/cli/send_message.rs b/relays/bin-substrate/src/cli/send_message.rs index 3e77ad83429..4673cbab516 100644 --- a/relays/bin-substrate/src/cli/send_message.rs +++ b/relays/bin-substrate/src/cli/send_message.rs @@ -139,7 +139,7 @@ impl SendMessage { target_origin_public.into(), digest_signature.into(), ) - }, + } }, &target_call, *dispatch_fee_payment, diff --git a/relays/bin-substrate/src/cli/swap_tokens.rs b/relays/bin-substrate/src/cli/swap_tokens.rs index dbe46f46907..fb49c83dc88 100644 --- a/relays/bin-substrate/src/cli/swap_tokens.rs +++ b/relays/bin-substrate/src/cli/swap_tokens.rs @@ -121,7 +121,7 @@ macro_rules! select_bridge { const TARGET_TO_SOURCE_LANE_ID: bp_messages::LaneId = [0, 0, 0, 0]; $generic - }, + } } }; } @@ -269,12 +269,13 @@ impl SwapTokens { let intermediate_balances = read_account_balances(&accounts, &source_client, &target_client).await?; log::info!(target: "bridge", "Intermediate balances: {:?}", intermediate_balances); - }, - Some(token_swap_state) => + } + Some(token_swap_state) => { return Err(anyhow::format_err!( "Fresh token swap has unexpected state: {:?}", token_swap_state, - )), + )) + } None => return Err(anyhow::format_err!("Failed to start token swap")), }; @@ -293,23 +294,26 @@ impl SwapTokens { let is_transfer_succeeded = match token_swap_state { Some(bp_token_swap::TokenSwapState::Started) => { unreachable!("wait_until_token_swap_state_is_changed only returns if state is not Started; qed",) - }, - None => - return Err(anyhow::format_err!("Fresh token swap has disappeared unexpectedly")), + } + None => { + return Err(anyhow::format_err!( + "Fresh token swap has disappeared unexpectedly" + )) + } Some(bp_token_swap::TokenSwapState::Confirmed) => { log::info!( target: "bridge", "Transfer has been successfully dispatched at the target chain. Swap can be claimed", ); true - }, + } Some(bp_token_swap::TokenSwapState::Failed) => { log::info!( target: "bridge", "Transfer has been dispatched with an error at the target chain. Swap can be canceled", ); false - }, + } }; // by this time: (1) token swap account has been created and (2) if transfer has been @@ -403,7 +407,7 @@ impl SwapTokens { return Err(anyhow::format_err!( "Confirmed token swap state has been changed to {:?} unexpectedly", token_swap_state - )) + )); } } else { log::info!(target: "bridge", "Cancelling the swap"); @@ -487,8 +491,9 @@ impl SwapTokens { source_client: &Client, ) -> anyhow::Result>> { match self.swap_type { - TokenSwapType::NoLock => - Ok(bp_token_swap::TokenSwapType::TemporaryTargetAccountAtBridgedChain), + TokenSwapType::NoLock => { + Ok(bp_token_swap::TokenSwapType::TemporaryTargetAccountAtBridgedChain) + } TokenSwapType::LockUntilBlock { blocks_before_expire, ref swap_nonce } => { let blocks_before_expire: BlockNumberOf = blocks_before_expire.into(); let current_source_block_number = *source_client.best_header().await?.number(); @@ -498,7 +503,7 @@ impl SwapTokens { U256::from(random::()).overflowing_mul(U256::from(random::())).0 }), )) - }, + } } } } @@ -580,16 +585,17 @@ pub(crate) async fn wait_until_transaction_is_finalized( loop { let transaction_status = subscription.next().await?; match transaction_status { - Some(TransactionStatusOf::::FinalityTimeout(_)) | - Some(TransactionStatusOf::::Usurped(_)) | - Some(TransactionStatusOf::::Dropped) | - Some(TransactionStatusOf::::Invalid) | - None => + Some(TransactionStatusOf::::FinalityTimeout(_)) + | Some(TransactionStatusOf::::Usurped(_)) + | Some(TransactionStatusOf::::Dropped) + | Some(TransactionStatusOf::::Invalid) + | None => { return Err(anyhow::format_err!( "We've been waiting for finalization of {} transaction, but it now has the {:?} status", C::NAME, transaction_status, - )), + )) + } Some(TransactionStatusOf::::Finalized(block_hash)) => { log::trace!( target: "bridge", @@ -597,8 +603,8 @@ pub(crate) async fn wait_until_transaction_is_finalized( C::NAME, block_hash, ); - return Ok(block_hash) - }, + return Ok(block_hash); + } _ => { log::trace!( target: "bridge", @@ -606,7 +612,7 @@ pub(crate) async fn wait_until_transaction_is_finalized( C::NAME, transaction_status, ); - }, + } } } } @@ -628,7 +634,7 @@ async fn wait_until_token_swap_state_is_changed( let token_swap_state = read_token_swap_state(client, best_block_hash, swap_state_storage_key).await?; match token_swap_state { - Some(new_token_swap_state) if new_token_swap_state == previous_token_swap_state => {}, + Some(new_token_swap_state) if new_token_swap_state == previous_token_swap_state => {} _ => { log::trace!( target: "bridge", @@ -636,8 +642,8 @@ async fn wait_until_token_swap_state_is_changed( previous_token_swap_state, token_swap_state, ); - return Ok(token_swap_state) - }, + return Ok(token_swap_state); + } } } } @@ -654,7 +660,7 @@ async fn wait_until_swap_unlocked( let best_block = client.best_finalized_header_number().await?; let best_block_hash = client.block_hash_by_number(best_block).await?; if best_block >= required_block_number { - return Ok(()) + return Ok(()); } log::trace!(target: "bridge", "Skipping {} block {}/{}", C::NAME, best_block, best_block_hash); diff --git a/relays/client-substrate/src/client.rs b/relays/client-substrate/src/client.rs index 1902875c938..2d39200ce28 100644 --- a/relays/client-substrate/src/client.rs +++ b/relays/client-substrate/src/client.rs @@ -554,10 +554,11 @@ impl Subscription { ) { loop { match subscription.next().await { - Ok(Some(item)) => + Ok(Some(item)) => { if sender.send(Some(item)).await.is_err() { - break - }, + break; + } + } Ok(None) => { log::trace!( target: "bridge", @@ -566,8 +567,8 @@ impl Subscription { item_type, ); let _ = sender.send(None).await; - break - }, + break; + } Err(e) => { log::trace!( target: "bridge", @@ -577,8 +578,8 @@ impl Subscription { e, ); let _ = sender.send(None).await; - break - }, + break; + } } } } diff --git a/relays/client-substrate/src/finality_source.rs b/relays/client-substrate/src/finality_source.rs index 98526de178c..89141e4bd20 100644 --- a/relays/client-substrate/src/finality_source.rs +++ b/relays/client-substrate/src/finality_source.rs @@ -159,11 +159,11 @@ where Ok(j) => j, Err(err) => { log_error(format!("decode failed with error {:?}", err)); - continue - }, + continue; + } }; - return Some((justification, subscription)) + return Some((justification, subscription)); } }, ) diff --git a/relays/client-substrate/src/guard.rs b/relays/client-substrate/src/guard.rs index a064e362340..0b738dc2b84 100644 --- a/relays/client-substrate/src/guard.rs +++ b/relays/client-substrate/src/guard.rs @@ -78,7 +78,7 @@ pub fn abort_on_spec_version_change( ); env.abort().await; - }, + } Err(error) => log::warn!( target: "bridge-guard", "Failed to read {} runtime version: {}. Relay may need to be stopped manually", @@ -140,7 +140,7 @@ pub fn abort_when_account_balance_decreased( env.abort().await; } - }, + } Err(error) => { log::warn!( target: "bridge-guard", @@ -149,7 +149,7 @@ pub fn abort_when_account_balance_decreased( account_id, error, ); - }, + } }; env.sleep(conditions_check_delay::()).await; diff --git a/relays/client-substrate/src/metrics/float_storage_value.rs b/relays/client-substrate/src/metrics/float_storage_value.rs index 7dccf82b6f8..53a9381d1b8 100644 --- a/relays/client-substrate/src/metrics/float_storage_value.rs +++ b/relays/client-substrate/src/metrics/float_storage_value.rs @@ -90,8 +90,8 @@ where .await .map(|maybe_storage_value| { maybe_storage_value.or(self.maybe_default_value).map(|storage_value| { - storage_value.into_inner().unique_saturated_into() as f64 / - T::DIV.unique_saturated_into() as f64 + storage_value.into_inner().unique_saturated_into() as f64 + / T::DIV.unique_saturated_into() as f64 }) }) .map_err(drop); diff --git a/relays/finality/src/finality_loop.rs b/relays/finality/src/finality_loop.rs index 320b44d310f..5030c215f9a 100644 --- a/relays/finality/src/finality_loop.rs +++ b/relays/finality/src/finality_loop.rs @@ -258,12 +258,12 @@ async fn run_until_connection_lost( last_transaction = updated_last_transaction; retry_backoff.reset(); sync_params.tick - }, + } Err(error) => { log::error!(target: "bridge", "Finality sync loop iteration has failed with error: {:?}", error); error.fail_if_connection_error()?; retry_backoff.next_backoff().unwrap_or(relay_utils::relay_loop::RECONNECT_DELAY) - }, + } }; if finality_proofs_stream.needs_restart { log::warn!(target: "bridge", "{} finality proofs stream is being restarted", P::SOURCE_NAME); @@ -319,9 +319,9 @@ where P::TARGET_NAME, ); - return Err(Error::Stalled) + return Err(Error::Stalled); } else { - return Ok(Some(last_transaction)) + return Ok(Some(last_transaction)); } } @@ -354,7 +354,7 @@ where .await .map_err(Error::Target)?; Ok(Some(new_transaction)) - }, + } None => Ok(None), } } @@ -391,15 +391,17 @@ where ) .await?; let (mut unjustified_headers, mut selected_finality_proof) = match selected_finality_proof { - SelectedFinalityProof::Mandatory(header, finality_proof) => - return Ok(Some((header, finality_proof))), + SelectedFinalityProof::Mandatory(header, finality_proof) => { + return Ok(Some((header, finality_proof))) + } _ if sync_params.only_mandatory_headers => { // we are not reading finality proofs from the stream, so eventually it'll break // but we don't care about transient proofs at all, so it is acceptable - return Ok(None) - }, - SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) => - (unjustified_headers, Some((header, finality_proof))), + return Ok(None); + } + SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) => { + (unjustified_headers, Some((header, finality_proof))) + } SelectedFinalityProof::None(unjustified_headers) => (unjustified_headers, None), }; @@ -467,17 +469,17 @@ pub(crate) async fn read_missing_headers< match (is_mandatory, finality_proof) { (true, Some(finality_proof)) => { log::trace!(target: "bridge", "Header {:?} is mandatory", header_number); - return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)) - }, + return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)); + } (true, None) => return Err(Error::MissingMandatoryFinalityProof(header.number())), (false, Some(finality_proof)) => { log::trace!(target: "bridge", "Header {:?} has persistent finality proof", header_number); unjustified_headers.clear(); selected_finality_proof = Some((header, finality_proof)); - }, + } (false, None) => { unjustified_headers.push(header); - }, + } } header_number = header_number + One::one(); @@ -514,8 +516,8 @@ pub(crate) fn read_finality_proofs_from_stream< Some(Some(finality_proof)) => finality_proof, Some(None) => { finality_proofs_stream.needs_restart = true; - break - }, + break; + } None => break, }; @@ -555,7 +557,7 @@ pub(crate) fn select_better_recent_finality_proof( P::SOURCE_NAME, selected_finality_proof.as_ref().map(|(h, _)| h.number()), ); - return selected_finality_proof + return selected_finality_proof; } const NOT_EMPTY_PROOF: &str = "we have checked that the vec is not empty; qed"; @@ -594,7 +596,7 @@ pub(crate) fn select_better_recent_finality_proof( if has_selected_finality_proof { "improved" } else { "not improved" }, ); if !has_selected_finality_proof { - return selected_finality_proof + return selected_finality_proof; } // now remove all obsolete headers and extract selected header @@ -630,15 +632,15 @@ fn print_sync_progress( let (prev_time, prev_best_number_at_target) = progress_context; let now = Instant::now(); - let need_update = now - prev_time > Duration::from_secs(10) || - prev_best_number_at_target + let need_update = now - prev_time > Duration::from_secs(10) + || prev_best_number_at_target .map(|prev_best_number_at_target| { best_number_at_target.saturating_sub(prev_best_number_at_target) > 10.into() }) .unwrap_or(true); if !need_update { - return (prev_time, prev_best_number_at_target) + return (prev_time, prev_best_number_at_target); } log::info!( diff --git a/relays/lib-substrate-relay/src/conversion_rate_update.rs b/relays/lib-substrate-relay/src/conversion_rate_update.rs index 93458457d34..3f728c85a35 100644 --- a/relays/lib-substrate-relay/src/conversion_rate_update.rs +++ b/relays/lib-substrate-relay/src/conversion_rate_update.rs @@ -61,10 +61,10 @@ pub fn run_conversion_rate_update_loop< match submit_conversion_rate_future.await { Ok(()) => { transaction_status = TransactionStatus::Submitted(prev_conversion_rate); - }, + } Err(error) => { log::trace!(target: "bridge", "Failed to submit conversion rate update transaction: {:?}", error); - }, + } } } } @@ -96,11 +96,11 @@ async fn maybe_select_new_conversion_rate( { // the rate has not been changed => we won't submit any transactions until it is // accepted, or the rate is changed by someone else - return None + return None; } *transaction_status = TransactionStatus::Idle; - }, + } } let left_to_base_conversion_rate = (*left_to_base_conversion_rate.read().await)?; @@ -112,7 +112,7 @@ async fn maybe_select_new_conversion_rate( (actual_left_to_right_conversion_rate - left_to_right_stored_conversion_rate).abs(); let rate_difference_ratio = rate_difference / left_to_right_stored_conversion_rate; if rate_difference_ratio < max_difference_ratio { - return None + return None; } Some((left_to_right_stored_conversion_rate, actual_left_to_right_conversion_rate)) diff --git a/relays/lib-substrate-relay/src/headers_initialize.rs b/relays/lib-substrate-relay/src/headers_initialize.rs index 2e802c4cb21..3b2a602bf3a 100644 --- a/relays/lib-substrate-relay/src/headers_initialize.rs +++ b/relays/lib-substrate-relay/src/headers_initialize.rs @@ -191,7 +191,7 @@ async fn prepare_initialization_data( .is_ok(); if is_valid_set_id { - break + break; } initial_authorities_set_id += 1; @@ -200,7 +200,7 @@ async fn prepare_initialization_data( // there can't be more authorities set changes than headers => if we have reached // `initial_block_number` and still have not found correct value of // `initial_authorities_set_id`, then something else is broken => fail - return Err(Error::GuessInitialAuthorities(SourceChain::NAME, initial_header_number)) + return Err(Error::GuessInitialAuthorities(SourceChain::NAME, initial_header_number)); } } diff --git a/relays/lib-substrate-relay/src/messages_lane.rs b/relays/lib-substrate-relay/src/messages_lane.rs index 6cadb64754a..35977d764b7 100644 --- a/relays/lib-substrate-relay/src/messages_lane.rs +++ b/relays/lib-substrate-relay/src/messages_lane.rs @@ -225,8 +225,8 @@ pub fn select_delivery_transaction_limits( // this is actually prevented by external logic if nonces.is_empty() { - return Ok(weights_map) + return Ok(weights_map); } // check if last nonce is missing - loop below is not checking this let last_nonce_is_missing = weights.last().map(|details| details.nonce != *nonces.end()).unwrap_or(true); if last_nonce_is_missing { - return make_missing_nonce_error(*nonces.end()) + return make_missing_nonce_error(*nonces.end()); } let mut expected_nonce = *nonces.start(); @@ -401,13 +401,13 @@ fn make_message_details_map( C::NAME, expected_nonce..details.nonce, ); - }, + } (false, false) => { // some nonces are missing from the middle/tail of the range // // this is critical error, because we can't miss any nonces - return make_missing_nonce_error(expected_nonce) - }, + return make_missing_nonce_error(expected_nonce); + } } weights_map.insert( diff --git a/relays/lib-substrate-relay/src/on_demand_headers.rs b/relays/lib-substrate-relay/src/on_demand_headers.rs index ee141866eb9..70bbab18a0f 100644 --- a/relays/lib-substrate-relay/src/on_demand_headers.rs +++ b/relays/lib-substrate-relay/src/on_demand_headers.rs @@ -175,7 +175,7 @@ async fn background_task( &mut finality_target, ) .await; - continue + continue; } // read best finalized source header number from target @@ -193,7 +193,7 @@ async fn background_task( &mut finality_target, ) .await; - continue + continue; } // submit mandatory header if some headers are missing @@ -224,8 +224,8 @@ async fn background_task( // there are no (or we don't need to relay them) mandatory headers in the range // => to avoid scanning the same headers over and over again, remember that latest_non_mandatory_at_source = mandatory_scan_range.1; - }, - Err(e) => + } + Err(e) => { if e.is_connection_error() { relay_utils::relay_loop::reconnect_failed_client( FailedClient::Source, @@ -234,8 +234,9 @@ async fn background_task( &mut finality_target, ) .await; - continue - }, + continue; + } + } } } @@ -298,12 +299,12 @@ async fn mandatory_headers_scan_range( .checked_sub(&best_finalized_source_header_at_target) .unwrap_or_else(Zero::zero); if current_headers_difference <= maximal_headers_difference { - return None + return None; } // if relay is already asked to sync headers, don't do anything yet if required_header_number > best_finalized_source_header_at_target { - return None + return None; } Some(( @@ -341,7 +342,7 @@ where // less than our `mandatory_source_header_number` before logging anything let mut required_header_number = required_header_number.lock().await; if *required_header_number >= mandatory_source_header_number { - return Ok(false) + return Ok(false); } log::trace!( @@ -421,7 +422,7 @@ where let header: SyncHeader = finality_source.client().header_by_number(current).await?.into(); if header.is_mandatory() { - return Ok(Some(current)) + return Ok(Some(current)); } current += One::one(); diff --git a/relays/messages/src/message_lane_loop.rs b/relays/messages/src/message_lane_loop.rs index 6cdb2b1aa5a..df7916f6a60 100644 --- a/relays/messages/src/message_lane_loop.rs +++ b/relays/messages/src/message_lane_loop.rs @@ -566,7 +566,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError) + return Err(TestError); } Ok(data.source_state.clone()) } @@ -578,7 +578,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.source_latest_generated_nonce)) } @@ -699,7 +699,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok(data.target_state.clone()) } @@ -711,7 +711,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.target_latest_received_nonce)) } @@ -737,7 +737,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } Ok((id, data.target_latest_confirmed_received_nonce)) } @@ -758,7 +758,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError) + return Err(TestError); } data.target_state.best_self = HeaderId(data.target_state.best_self.0 + 1, data.target_state.best_self.1 + 1); @@ -786,9 +786,9 @@ pub(crate) mod tests { total_dispatch_weight: Weight, total_size: u32, ) -> Result { - Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + - total_dispatch_weight + - total_size as TestSourceChainBalance) + Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + + total_dispatch_weight + + total_size as TestSourceChainBalance) } } @@ -906,8 +906,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new target headers at source node if data.target_to_source_header_required.is_some() { assert!( - data.source_state.best_finalized_peer_at_best_self.0 < - data.target_state.best_self.0 + data.source_state.best_finalized_peer_at_best_self.0 + < data.target_state.best_self.0 ); data.target_to_source_header_required = None; } @@ -926,8 +926,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new source headers at target node if data.source_to_target_header_required.is_some() { assert!( - data.target_state.best_finalized_peer_at_best_self.0 < - data.source_state.best_self.0 + data.target_state.best_finalized_peer_at_best_self.0 + < data.source_state.best_self.0 ); data.source_to_target_header_required = None; } diff --git a/relays/messages/src/message_race_delivery.rs b/relays/messages/src/message_race_delivery.rs index dc994364f17..0371ccc556d 100644 --- a/relays/messages/src/message_race_delivery.rs +++ b/relays/messages/src/message_race_delivery.rs @@ -442,8 +442,8 @@ where self.max_unconfirmed_nonces_at_target, ); - return None - }, + return None; + } _ => (), } @@ -462,8 +462,8 @@ where // "unrewarded relayers" set. If we are unable to prove new rewards to the target node, then // we should wait for confirmations race. let unrewarded_relayer_entries_limit_reached = - target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries >= - self.max_unrewarded_relayer_entries_at_target; + target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries + >= self.max_unrewarded_relayer_entries_at_target; if unrewarded_relayer_entries_limit_reached { // so there are already too many unrewarded relayer entries in the set // @@ -471,10 +471,10 @@ where // be paid let number_of_rewards_being_proved = latest_confirmed_nonce_at_source.saturating_sub(latest_confirmed_nonce_at_target); - let enough_rewards_being_proved = number_of_rewards_being_proved >= - target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; + let enough_rewards_being_proved = number_of_rewards_being_proved + >= target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; if !enough_rewards_being_proved { - return None + return None; } } @@ -577,10 +577,10 @@ mod tests { const DEFAULT_DISPATCH_WEIGHT: Weight = 1; const DEFAULT_SIZE: u32 = 1; - const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + - BASE_MESSAGE_DELIVERY_TRANSACTION_COST + - DEFAULT_DISPATCH_WEIGHT + - (DEFAULT_SIZE as TestSourceChainBalance); + const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + + BASE_MESSAGE_DELIVERY_TRANSACTION_COST + + DEFAULT_DISPATCH_WEIGHT + + (DEFAULT_SIZE as TestSourceChainBalance); type TestRaceState = RaceState; type TestStrategy = @@ -720,8 +720,8 @@ mod tests { // we need to wait until confirmations will be delivered by receiving race strategy.latest_confirmed_nonces_at_source = vec![( header_id(1), - strategy.target_nonces.as_ref().unwrap().latest_nonce - - strategy.max_unconfirmed_nonces_at_target, + strategy.target_nonces.as_ref().unwrap().latest_nonce + - strategy.max_unconfirmed_nonces_at_target, )] .into_iter() .collect(); diff --git a/relays/messages/src/message_race_loop.rs b/relays/messages/src/message_race_loop.rs index a7254f70ee4..bbb3890a509 100644 --- a/relays/messages/src/message_race_loop.rs +++ b/relays/messages/src/message_race_loop.rs @@ -439,10 +439,10 @@ pub async fn run, TC: TargetClient

>( strategy, ); - return Err(FailedClient::Both) - } else if race_state.nonces_to_submit.is_none() && - race_state.nonces_submitted.is_none() && - strategy.is_empty() + return Err(FailedClient::Both); + } else if race_state.nonces_to_submit.is_none() + && race_state.nonces_submitted.is_none() + && strategy.is_empty() { stall_countdown = Instant::now(); } @@ -551,7 +551,7 @@ where let need_update = now_time.saturating_duration_since(prev_time) > Duration::from_secs(10); if !need_update { - return prev_time + return prev_time; } let now_best_nonce_at_source = strategy.best_at_source(); diff --git a/relays/messages/src/message_race_strategy.rs b/relays/messages/src/message_race_strategy.rs index 9b9091b979f..37f0cefa119 100644 --- a/relays/messages/src/message_race_strategy.rs +++ b/relays/messages/src/message_race_strategy.rs @@ -111,12 +111,12 @@ impl< // if we have already selected nonces that we want to submit, do nothing if race_state.nonces_to_submit.is_some() { - return None + return None; } // if we already submitted some nonces, do nothing if race_state.nonces_submitted.is_some() { - return None + return None; } // 1) we want to deliver all nonces, starting from `target_nonce + 1` @@ -140,7 +140,7 @@ impl< while let Some((queued_at, queued_range)) = self.source_queue.pop_front() { if let Some(range_to_requeue) = queued_range.greater_than(nonce) { self.source_queue.push_front((queued_at, range_to_requeue)); - break + break; } } } @@ -195,8 +195,9 @@ impl< fn best_at_source(&self) -> Option { let best_in_queue = self.source_queue.back().map(|(_, range)| range.end()); match (best_in_queue, self.best_target_nonce) { - (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => - Some(best_in_queue), + (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => { + Some(best_in_queue) + } (_, Some(best_target_nonce)) => Some(best_target_nonce), (_, None) => None, } @@ -239,7 +240,7 @@ impl< if let Some(best_target_nonce) = self.best_target_nonce { if nonce < best_target_nonce { - return + return; } } @@ -249,7 +250,7 @@ impl< }); if let Some((at_block, subrange)) = maybe_subrange { self.source_queue.push_front((at_block, subrange)); - break + break; } } diff --git a/relays/messages/src/relay_strategy/enforcement_strategy.rs b/relays/messages/src/relay_strategy/enforcement_strategy.rs index 1e9ef5bdbf8..3ee88c639ef 100644 --- a/relays/messages/src/relay_strategy/enforcement_strategy.rs +++ b/relays/messages/src/relay_strategy/enforcement_strategy.rs @@ -107,7 +107,9 @@ impl EnforcementStrategy { let new_selected_weight = match selected_weight.checked_add(details.dispatch_weight) { Some(new_selected_weight) if new_selected_weight <= reference.max_messages_weight_in_single_batch => - new_selected_weight, + { + new_selected_weight + } new_selected_weight if selected_count == 0 => { log::warn!( target: "bridge", @@ -117,7 +119,7 @@ impl EnforcementStrategy { reference.max_messages_weight_in_single_batch, ); new_selected_weight.unwrap_or(Weight::MAX) - }, + } _ => break, }; @@ -125,7 +127,9 @@ impl EnforcementStrategy { let new_selected_size = match relay_reference.selected_size.checked_add(details.size) { Some(new_selected_size) if new_selected_size <= reference.max_messages_size_in_single_batch => - new_selected_size, + { + new_selected_size + } new_selected_size if selected_count == 0 => { log::warn!( target: "bridge", @@ -135,14 +139,14 @@ impl EnforcementStrategy { reference.max_messages_size_in_single_batch, ); new_selected_size.unwrap_or(u32::MAX) - }, + } _ => break, }; // limit number of messages in the batch let new_selected_count = selected_count + 1; if new_selected_count > reference.max_messages_in_this_batch { - break + break; } relay_reference.selected_size = new_selected_size; @@ -160,7 +164,7 @@ impl EnforcementStrategy { DispatchFeePayment::AtSourceChain => { new_selected_prepaid_nonces += 1; relay_reference.selected_unpaid_weight.saturating_add(details.dispatch_weight) - }, + } DispatchFeePayment::AtTargetChain => relay_reference.selected_unpaid_weight, }; relay_reference.selected_prepaid_nonces = new_selected_prepaid_nonces; @@ -197,8 +201,8 @@ impl EnforcementStrategy { } if hard_selected_count != 0 { - if relay_reference.selected_reward != P::SourceChainBalance::zero() && - relay_reference.selected_cost != P::SourceChainBalance::zero() + if relay_reference.selected_reward != P::SourceChainBalance::zero() + && relay_reference.selected_cost != P::SourceChainBalance::zero() { log::trace!( target: "bridge", diff --git a/relays/messages/src/relay_strategy/rational_strategy.rs b/relays/messages/src/relay_strategy/rational_strategy.rs index fd0a1ffafc8..a44ce661316 100644 --- a/relays/messages/src/relay_strategy/rational_strategy.rs +++ b/relays/messages/src/relay_strategy/rational_strategy.rs @@ -54,8 +54,8 @@ impl RelayStrategy for RationalStrategy { let delivery_transaction_cost = match reference .lane_target_client .estimate_delivery_transaction_in_source_tokens( - reference.hard_selected_begin_nonce..= - (reference.hard_selected_begin_nonce + reference.index as MessageNonce), + reference.hard_selected_begin_nonce + ..=(reference.hard_selected_begin_nonce + reference.index as MessageNonce), reference.selected_prepaid_nonces, reference.selected_unpaid_weight, reference.selected_size as u32, @@ -69,8 +69,8 @@ impl RelayStrategy for RationalStrategy { "Failed to estimate delivery transaction cost: {:?}. No nonces selected for delivery", err, ); - return false - }, + return false; + } }; // if it is the first message that makes reward less than cost, let's log it @@ -114,7 +114,7 @@ impl RelayStrategy for RationalStrategy { if reference.total_reward >= reference.total_cost { reference.selected_reward = reference.total_reward; reference.selected_cost = reference.total_cost; - return true + return true; } false diff --git a/relays/utils/src/lib.rs b/relays/utils/src/lib.rs index a335be79124..01bc08680dc 100644 --- a/relays/utils/src/lib.rs +++ b/relays/utils/src/lib.rs @@ -161,12 +161,12 @@ pub fn format_ids(mut ids: impl ExactSizeIterator { let id0 = ids.next().expect(NTH_PROOF); let id_last = ids.last().expect(NTH_PROOF); format!("{}:[{:?} ... {:?}]", len, id0, id_last) - }, + } } } @@ -243,7 +243,7 @@ where on_success(result); retry_backoff.reset(); ProcessFutureResult::Success - }, + } Err(error) if error.is_connection_error() => { log::error!( target: "bridge", @@ -255,7 +255,7 @@ where retry_backoff.reset(); go_offline_future.set(go_offline(CONNECTION_ERROR_DELAY).fuse()); ProcessFutureResult::ConnectionFailed - }, + } Err(error) => { let retry_delay = retry_backoff.next_backoff().unwrap_or(CONNECTION_ERROR_DELAY); log::error!( @@ -268,6 +268,6 @@ where go_offline_future.set(go_offline(retry_delay).fuse()); ProcessFutureResult::Failed - }, + } } } diff --git a/relays/utils/src/metrics.rs b/relays/utils/src/metrics.rs index 805fe70bfe8..a0ff46865ad 100644 --- a/relays/utils/src/metrics.rs +++ b/relays/utils/src/metrics.rs @@ -72,7 +72,7 @@ pub trait StandaloneMetric: Metric { Ok(()) => { self.spawn(); Ok(()) - }, + } Err(PrometheusError::AlreadyReg) => Ok(()), Err(e) => Err(e), } @@ -140,7 +140,7 @@ pub fn set_gauge_value, E: Debug>( value, ); value - }, + } Ok(None) => { log::warn!( target: "bridge-metrics", @@ -148,7 +148,7 @@ pub fn set_gauge_value, E: Debug>( gauge.desc().first().map(|d| &d.fq_name), ); Default::default() - }, + } Err(error) => { log::warn!( target: "bridge-metrics", @@ -157,6 +157,6 @@ pub fn set_gauge_value, E: Debug>( error, ); Default::default() - }, + } }) } diff --git a/relays/utils/src/metrics/float_json_value.rs b/relays/utils/src/metrics/float_json_value.rs index 7535cbef986..569acc4297e 100644 --- a/relays/utils/src/metrics/float_json_value.rs +++ b/relays/utils/src/metrics/float_json_value.rs @@ -112,7 +112,7 @@ fn parse_service_response(json_path: &str, response: &str) -> error::Result .and_then(|v| v.as_f64()) .ok_or_else(|| Error::MissingResponseValue(response.to_owned()))?; if !selected_value.is_normal() || selected_value < 0.0 { - return Err(Error::ParseFloat(selected_value)) + return Err(Error::ParseFloat(selected_value)); } Ok(selected_value) diff --git a/relays/utils/src/metrics/global.rs b/relays/utils/src/metrics/global.rs index df90a2c4823..5e94dd9d2b4 100644 --- a/relays/utils/src/metrics/global.rs +++ b/relays/utils/src/metrics/global.rs @@ -102,13 +102,13 @@ impl StandaloneMetric for GlobalMetrics { 0f64 }); self.process_memory_usage_bytes.set(memory_usage); - }, + } _ => { log::warn!( target: "bridge-metrics", "Failed to refresh process information. Metrics may show obsolete values", ); - }, + } } } diff --git a/relays/utils/src/relay_loop.rs b/relays/utils/src/relay_loop.rs index a992aaaf57e..6b42c771f27 100644 --- a/relays/utils/src/relay_loop.rs +++ b/relays/utils/src/relay_loop.rs @@ -129,14 +129,15 @@ impl Loop { match result { Ok(()) => break, - Err(failed_client) => + Err(failed_client) => { reconnect_failed_client( failed_client, self.reconnect_delay, &mut self.source_client, &mut self.target_client, ) - .await, + .await + } } log::debug!(target: "bridge", "Restarting relay loop"); @@ -224,8 +225,8 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue - }, + continue; + } } } if failed_client == FailedClient::Both || failed_client == FailedClient::Target { @@ -238,11 +239,11 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue - }, + continue; + } } } - break + break; } } From 1a19aea097279cd496e64c830eb8aea576dcc9ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 1 Dec 2021 14:13:51 +0100 Subject: [PATCH 3/4] cargo +nightly fmt --all --- bin/millau/node/src/command.rs | 23 ++++---- bin/millau/node/src/service.rs | 7 +-- bin/millau/runtime/src/rialto_messages.rs | 11 ++-- bin/rialto-parachain/node/src/command.rs | 25 ++++---- bin/rialto-parachain/node/src/service.rs | 2 +- bin/rialto/node/src/command.rs | 27 +++++---- bin/rialto/node/src/service.rs | 2 +- bin/rialto/runtime/src/millau_messages.rs | 5 +- bin/runtime-common/src/messages.rs | 29 +++++----- .../src/messages_benchmarking.rs | 2 +- fuzz/storage-proof/src/main.rs | 2 +- modules/dispatch/src/lib.rs | 38 ++++++------ modules/grandpa/src/lib.rs | 10 ++-- modules/messages/src/inbound_lane.rs | 16 ++--- modules/messages/src/instant_payments.rs | 4 +- modules/messages/src/lib.rs | 49 ++++++++-------- modules/messages/src/mock.rs | 11 ++-- modules/messages/src/outbound_lane.rs | 24 ++++---- modules/messages/src/weights_ext.rs | 14 ++--- modules/shift-session-manager/src/lib.rs | 2 +- modules/token-swap/src/lib.rs | 35 ++++++----- primitives/header-chain/src/justification.rs | 20 +++---- .../tests/implementation_match.rs | 4 +- primitives/messages/src/lib.rs | 2 +- primitives/runtime/src/lib.rs | 15 ++--- primitives/runtime/src/storage_proof.rs | 2 +- relays/bin-substrate/src/chains/kusama.rs | 7 +-- relays/bin-substrate/src/chains/millau.rs | 19 +++--- relays/bin-substrate/src/chains/polkadot.rs | 7 +-- relays/bin-substrate/src/chains/rialto.rs | 19 +++--- .../src/chains/rialto_parachain.rs | 2 +- relays/bin-substrate/src/chains/rococo.rs | 7 +-- relays/bin-substrate/src/chains/wococo.rs | 7 +-- relays/bin-substrate/src/cli/encode_call.rs | 15 +++-- relays/bin-substrate/src/cli/init_bridge.rs | 14 ++--- relays/bin-substrate/src/cli/mod.rs | 14 ++--- .../src/cli/register_parachain.rs | 6 +- relays/bin-substrate/src/cli/relay_headers.rs | 14 ++--- .../src/cli/resubmit_transactions.rs | 40 ++++++------- relays/bin-substrate/src/cli/send_message.rs | 2 +- relays/bin-substrate/src/cli/swap_tokens.rs | 58 +++++++++---------- relays/client-substrate/src/client.rs | 15 +++-- .../client-substrate/src/finality_source.rs | 6 +- relays/client-substrate/src/guard.rs | 6 +- .../src/metrics/float_storage_value.rs | 4 +- relays/finality/src/finality_loop.rs | 46 +++++++-------- .../src/conversion_rate_update.rs | 10 ++-- .../src/headers_initialize.rs | 4 +- .../lib-substrate-relay/src/messages_lane.rs | 4 +- .../src/messages_source.rs | 10 ++-- .../src/on_demand_headers.rs | 21 ++++--- relays/messages/src/message_lane_loop.rs | 26 ++++----- relays/messages/src/message_race_delivery.rs | 24 ++++---- relays/messages/src/message_race_loop.rs | 10 ++-- relays/messages/src/message_race_strategy.rs | 15 +++-- .../relay_strategy/enforcement_strategy.rs | 20 +++---- .../src/relay_strategy/rational_strategy.rs | 10 ++-- relays/utils/src/lib.rs | 10 ++-- relays/utils/src/metrics.rs | 8 +-- relays/utils/src/metrics/float_json_value.rs | 2 +- relays/utils/src/metrics/global.rs | 4 +- relays/utils/src/relay_loop.rs | 15 +++-- 62 files changed, 417 insertions(+), 465 deletions(-) diff --git a/bin/millau/node/src/command.rs b/bin/millau/node/src/command.rs index 63545ec9e61..4dbf9575dfe 100644 --- a/bin/millau/node/src/command.rs +++ b/bin/millau/node/src/command.rs @@ -77,7 +77,7 @@ pub fn run() -> sc_cli::Result<()> { )); match &cli.subcommand { - Some(Subcommand::Benchmark(cmd)) => { + Some(Subcommand::Benchmark(cmd)) => if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -88,8 +88,7 @@ pub fn run() -> sc_cli::Result<()> { You can enable it with `--features runtime-benchmarks`." ); Ok(()) - } - } + }, Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), @@ -97,7 +96,7 @@ pub fn run() -> sc_cli::Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - } + }, Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { @@ -105,21 +104,21 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) - } + }, Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = new_partial(&config)?; Ok((cmd.run(client, config.database), task_manager)) }) - } + }, Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, .. } = new_partial(&config)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) - } + }, Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { @@ -127,28 +126,28 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&config)?; Ok((cmd.run(client, import_queue), task_manager)) }) - } + }, Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.database)) - } + }, Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { client, task_manager, backend, .. } = new_partial(&config)?; Ok((cmd.run(client, backend), task_manager)) }) - } + }, Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; runner .sync_run(|config| cmd.run::(config)) - } + }, None => { let runner = cli.create_runner(&cli.run)?; runner.run_node_until_exit(|config| async move { service::new_full(config).map_err(sc_cli::Error::Service) }) - } + }, } } diff --git a/bin/millau/node/src/service.rs b/bin/millau/node/src/service.rs index 233e2a3fbed..b01c0bfca90 100644 --- a/bin/millau/node/src/service.rs +++ b/bin/millau/node/src/service.rs @@ -89,7 +89,7 @@ pub fn new_partial( ServiceError, > { if config.keystore_remote.is_some() { - return Err(ServiceError::Other(format!("Remote Keystores are not supported."))); + return Err(ServiceError::Other(format!("Remote Keystores are not supported."))) } let telemetry = config @@ -201,12 +201,11 @@ pub fn new_full(mut config: Configuration) -> Result if let Some(url) = &config.keystore_remote { match remote_keystore(url) { Ok(k) => keystore_container.set_remote_keystore(k), - Err(e) => { + Err(e) => return Err(ServiceError::Other(format!( "Error hooking up remote keystore for {}: {}", url, e - ))) - } + ))), }; } diff --git a/bin/millau/runtime/src/rialto_messages.rs b/bin/millau/runtime/src/rialto_messages.rs index 99d61476b79..6d9677c45cf 100644 --- a/bin/millau/runtime/src/rialto_messages.rs +++ b/bin/millau/runtime/src/rialto_messages.rs @@ -116,9 +116,9 @@ impl messages::ThisChainWithMessages for Millau { type Call = crate::Call; fn is_outbound_lane_enabled(lane: &LaneId) -> bool { - *lane == [0, 0, 0, 0] - || *lane == [0, 0, 0, 1] - || *lane == crate::TokenSwapMessagesLane::get() + *lane == [0, 0, 0, 0] || + *lane == [0, 0, 0, 1] || + *lane == crate::TokenSwapMessagesLane::get() } fn maximal_pending_messages_at_outbound_lane() -> MessageNonce { @@ -284,9 +284,8 @@ pub enum MillauToRialtoMessagesParameter { impl MessagesParameter for MillauToRialtoMessagesParameter { fn save(&self) { match *self { - MillauToRialtoMessagesParameter::RialtoToMillauConversionRate(ref conversion_rate) => { - RialtoToMillauConversionRate::set(conversion_rate) - } + MillauToRialtoMessagesParameter::RialtoToMillauConversionRate(ref conversion_rate) => + RialtoToMillauConversionRate::set(conversion_rate), } } } diff --git a/bin/rialto-parachain/node/src/command.rs b/bin/rialto-parachain/node/src/command.rs index 419291bb927..e4f52cc026a 100644 --- a/bin/rialto-parachain/node/src/command.rs +++ b/bin/rialto-parachain/node/src/command.rs @@ -161,27 +161,27 @@ pub fn run() -> Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - } + }, Some(Subcommand::CheckBlock(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) - } + }, Some(Subcommand::ExportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, config.database) )) - } + }, Some(Subcommand::ExportState(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, config.chain_spec) )) - } + }, Some(Subcommand::ImportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) - } + }, Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; @@ -200,12 +200,12 @@ pub fn run() -> Result<()> { cmd.run(config, polkadot_config) }) - } + }, Some(Subcommand::Revert(cmd)) => { construct_async_run!(|components, cli, cmd, config| Ok( cmd.run(components.client, components.backend) )) - } + }, Some(Subcommand::ExportGenesisState(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); @@ -229,7 +229,7 @@ pub fn run() -> Result<()> { } Ok(()) - } + }, Some(Subcommand::ExportGenesisWasm(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); @@ -250,8 +250,8 @@ pub fn run() -> Result<()> { } Ok(()) - } - Some(Subcommand::Benchmark(cmd)) => { + }, + Some(Subcommand::Benchmark(cmd)) => if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -260,8 +260,7 @@ pub fn run() -> Result<()> { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`." .into()) - } - } + }, None => { let runner = cli.create_runner(&cli.run.normalize())?; @@ -300,7 +299,7 @@ pub fn run() -> Result<()> { .map(|r| r.0) .map_err(Into::into) }) - } + }, } } diff --git a/bin/rialto-parachain/node/src/service.rs b/bin/rialto-parachain/node/src/service.rs index fdc213f82b5..bd3afca3074 100644 --- a/bin/rialto-parachain/node/src/service.rs +++ b/bin/rialto-parachain/node/src/service.rs @@ -246,7 +246,7 @@ where ) -> Result>, sc_service::Error>, { if matches!(parachain_config.role, Role::Light) { - return Err("Light client not supported!".into()); + return Err("Light client not supported!".into()) } let parachain_config = prepare_node_config(parachain_config); diff --git a/bin/rialto/node/src/command.rs b/bin/rialto/node/src/command.rs index 0456fda7e96..7be615a5776 100644 --- a/bin/rialto/node/src/command.rs +++ b/bin/rialto/node/src/command.rs @@ -75,7 +75,7 @@ pub fn run() -> sc_cli::Result<()> { )); match &cli.subcommand { - Some(Subcommand::Benchmark(cmd)) => { + Some(Subcommand::Benchmark(cmd)) => if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; @@ -86,8 +86,7 @@ pub fn run() -> sc_cli::Result<()> { You can enable it with `--features runtime-benchmarks`." ); Ok(()) - } - } + }, Some(Subcommand::Key(cmd)) => cmd.run(&cli), Some(Subcommand::Sign(cmd)) => cmd.run(), Some(Subcommand::Verify(cmd)) => cmd.run(), @@ -95,7 +94,7 @@ pub fn run() -> sc_cli::Result<()> { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) - } + }, Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -103,7 +102,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, import_queue), task_manager)) }) - } + }, Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -111,7 +110,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, config.database), task_manager)) }) - } + }, Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -119,7 +118,7 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) - } + }, Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -127,11 +126,11 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, import_queue), task_manager)) }) - } + }, Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.database)) - } + }, Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|mut config| { @@ -139,13 +138,13 @@ pub fn run() -> sc_cli::Result<()> { new_partial(&mut config).map_err(service_error)?; Ok((cmd.run(client, backend), task_manager)) }) - } + }, Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { cmd.run::(config) }) - } + }, Some(Subcommand::PvfPrepareWorker(cmd)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_colors(false); @@ -153,7 +152,7 @@ pub fn run() -> sc_cli::Result<()> { polkadot_node_core_pvf::prepare_worker_entrypoint(&cmd.socket_path); Ok(()) - } + }, Some(crate::cli::Subcommand::PvfExecuteWorker(cmd)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_colors(false); @@ -161,7 +160,7 @@ pub fn run() -> sc_cli::Result<()> { polkadot_node_core_pvf::execute_worker_entrypoint(&cmd.socket_path); Ok(()) - } + }, None => { let runner = cli.create_runner(&cli.run)?; @@ -182,7 +181,7 @@ pub fn run() -> sc_cli::Result<()> { .map_err(service_error), } }) - } + }, } } diff --git a/bin/rialto/node/src/service.rs b/bin/rialto/node/src/service.rs index 7dbc2c072ff..3349b09edb9 100644 --- a/bin/rialto/node/src/service.rs +++ b/bin/rialto/node/src/service.rs @@ -344,7 +344,7 @@ where // Only consider leaves that are in maximum an uncle of the best block. if number < best_block.number().saturating_sub(1) || hash == best_block.hash() { - return None; + return None } let parent_hash = client.header(&BlockId::Hash(hash)).ok()??.parent_hash; diff --git a/bin/rialto/runtime/src/millau_messages.rs b/bin/rialto/runtime/src/millau_messages.rs index 52f9e0212ee..13a1c6b06ec 100644 --- a/bin/rialto/runtime/src/millau_messages.rs +++ b/bin/rialto/runtime/src/millau_messages.rs @@ -282,9 +282,8 @@ pub enum RialtoToMillauMessagesParameter { impl MessagesParameter for RialtoToMillauMessagesParameter { fn save(&self) { match *self { - RialtoToMillauMessagesParameter::MillauToRialtoConversionRate(ref conversion_rate) => { - MillauToRialtoConversionRate::set(conversion_rate) - } + RialtoToMillauMessagesParameter::MillauToRialtoConversionRate(ref conversion_rate) => + MillauToRialtoConversionRate::set(conversion_rate), } } } diff --git a/bin/runtime-common/src/messages.rs b/bin/runtime-common/src/messages.rs index 03faa2714ab..b34cbb85540 100644 --- a/bin/runtime-common/src/messages.rs +++ b/bin/runtime-common/src/messages.rs @@ -299,7 +299,7 @@ pub mod source { ) -> Result<(), Self::Error> { // reject message if lane is blocked if !ThisChain::::is_outbound_lane_enabled(lane) { - return Err(OUTBOUND_LANE_DISABLED); + return Err(OUTBOUND_LANE_DISABLED) } // reject message if there are too many pending messages at this lane @@ -308,7 +308,7 @@ pub mod source { .latest_generated_nonce .saturating_sub(lane_outbound_data.latest_received_nonce); if pending_messages > max_pending_messages { - return Err(TOO_MANY_PENDING_MESSAGES); + return Err(TOO_MANY_PENDING_MESSAGES) } // Do the dispatch-specific check. We assume that the target chain uses @@ -321,7 +321,7 @@ pub mod source { // compare with actual fee paid if *delivery_and_dispatch_fee < minimal_fee_in_this_tokens { - return Err(TOO_LOW_FEE); + return Err(TOO_LOW_FEE) } Ok(()) @@ -343,7 +343,7 @@ pub mod source { ) -> Result<(), &'static str> { let weight_limits = BridgedChain::::message_weight_limits(&payload.call); if !weight_limits.contains(&payload.weight.into()) { - return Err("Incorrect message weight declared"); + return Err("Incorrect message weight declared") } // The maximal size of extrinsic at Substrate-based chain depends on the @@ -357,7 +357,7 @@ pub mod source { // transaction also contains signatures and signed extensions. Because of this, we reserve // 1/3 of the the maximal extrinsic weight for this data. if payload.call.len() > maximal_message_size::() as usize { - return Err("The message is too large to be sent over the lane"); + return Err("The message is too large to be sent over the lane") } Ok(()) @@ -646,16 +646,13 @@ pub mod target { fn from(err: MessageProofError) -> &'static str { match err { MessageProofError::Empty => "Messages proof is empty", - MessageProofError::MessagesCountMismatch => { - "Declared messages count doesn't match actual value" - } + MessageProofError::MessagesCountMismatch => + "Declared messages count doesn't match actual value", MessageProofError::MissingRequiredMessage => "Message is missing from the proof", - MessageProofError::FailedToDecodeMessage => { - "Failed to decode message from the proof" - } - MessageProofError::FailedToDecodeOutboundLaneState => { - "Failed to decode outbound lane data from the proof" - } + MessageProofError::FailedToDecodeMessage => + "Failed to decode message from the proof", + MessageProofError::FailedToDecodeOutboundLaneState => + "Failed to decode outbound lane data from the proof", MessageProofError::Custom(err) => err, } } @@ -721,7 +718,7 @@ pub mod target { // (this bounds maximal capacity of messages vec below) let messages_in_the_proof = nonces_difference.saturating_add(1); if messages_in_the_proof != MessageNonce::from(messages_count) { - return Err(MessageProofError::MessagesCountMismatch); + return Err(MessageProofError::MessagesCountMismatch) } messages_in_the_proof @@ -760,7 +757,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(MessageProofError::Empty); + return Err(MessageProofError::Empty) } // We only support single lane messages in this schema diff --git a/bin/runtime-common/src/messages_benchmarking.rs b/bin/runtime-common/src/messages_benchmarking.rs index c288d234dea..217560e1143 100644 --- a/bin/runtime-common/src/messages_benchmarking.rs +++ b/bin/runtime-common/src/messages_benchmarking.rs @@ -218,7 +218,7 @@ fn grow_trie(mut root: H::Out, mdb: &mut MemoryDB, trie_size: Proo .expect("record_all_keys should not fail in benchmarks"); let size: usize = proof_recorder.drain().into_iter().map(|n| n.data.len()).sum(); if size > minimal_trie_size as _ { - return root; + return root } let mut trie = TrieDBMut::::from_existing(mdb, &mut root) diff --git a/fuzz/storage-proof/src/main.rs b/fuzz/storage-proof/src/main.rs index 433d054cd4e..42636a65c3d 100644 --- a/fuzz/storage-proof/src/main.rs +++ b/fuzz/storage-proof/src/main.rs @@ -57,7 +57,7 @@ fn transform_into_unique(input_vec: Vec<(Vec, Vec)>) -> Vec<(Vec, Ve fn run_fuzzer() { fuzz!(|input_vec: Vec<(Vec, Vec)>| { if input_vec.is_empty() { - return; + return } let unique_input_vec = transform_into_unique(input_vec); let (root, craft_known_storage_proof) = craft_known_storage_proof(unique_input_vec.clone()); diff --git a/modules/dispatch/src/lib.rs b/modules/dispatch/src/lib.rs index 65b469dc4f0..f467bab0d94 100644 --- a/modules/dispatch/src/lib.rs +++ b/modules/dispatch/src/lib.rs @@ -173,8 +173,8 @@ impl, I: 'static> MessageDispatch dispatch_result: false, unspent_weight: 0, dispatch_fee_paid_during_dispatch: false, - }; - } + } + }, }; // verify spec version @@ -199,7 +199,7 @@ impl, I: 'static> MessageDispatch expected_version, message.spec_version, )); - return dispatch_result; + return dispatch_result } // now that we have spec version checked, let's decode the call @@ -213,8 +213,8 @@ impl, I: 'static> MessageDispatch id, ); Self::deposit_event(Event::MessageCallDecodeFailed(source_chain, id)); - return dispatch_result; - } + return dispatch_result + }, }; // prepare dispatch origin @@ -225,7 +225,7 @@ impl, I: 'static> MessageDispatch let target_id = T::AccountIdConverter::convert(hex_id); log::trace!(target: "runtime::bridge-dispatch", "Root Account: {:?}", &target_id); target_id - } + }, CallOrigin::TargetAccount(source_account_id, target_public, target_signature) => { let digest = account_ownership_digest( &call, @@ -246,19 +246,19 @@ impl, I: 'static> MessageDispatch target_signature, ); Self::deposit_event(Event::MessageSignatureMismatch(source_chain, id)); - return dispatch_result; + return dispatch_result } log::trace!(target: "runtime::bridge-dispatch", "Target Account: {:?}", &target_account); target_account - } + }, CallOrigin::SourceAccount(source_account_id) => { let hex_id = derive_account_id(source_chain, SourceAccount::Account(source_account_id)); let target_id = T::AccountIdConverter::convert(hex_id); log::trace!(target: "runtime::bridge-dispatch", "Source Account: {:?}", &target_id); target_id - } + }, }; // filter the call @@ -271,7 +271,7 @@ impl, I: 'static> MessageDispatch call, ); Self::deposit_event(Event::MessageCallRejected(source_chain, id)); - return dispatch_result; + return dispatch_result } // verify weight @@ -294,14 +294,14 @@ impl, I: 'static> MessageDispatch expected_weight, message.weight, )); - return dispatch_result; + return dispatch_result } // pay dispatch fee right before dispatch let pay_dispatch_fee_at_target_chain = message.dispatch_fee_payment == DispatchFeePayment::AtTargetChain; - if pay_dispatch_fee_at_target_chain - && pay_dispatch_fee(&origin_account, message.weight).is_err() + if pay_dispatch_fee_at_target_chain && + pay_dispatch_fee(&origin_account, message.weight).is_err() { log::trace!( target: "runtime::bridge-dispatch", @@ -316,7 +316,7 @@ impl, I: 'static> MessageDispatch origin_account, message.weight, )); - return dispatch_result; + return dispatch_result } dispatch_result.dispatch_fee_paid_during_dispatch = pay_dispatch_fee_at_target_chain; @@ -377,19 +377,19 @@ where CallOrigin::SourceRoot => { ensure!(sender_origin == &RawOrigin::Root, BadOrigin); Ok(None) - } + }, CallOrigin::TargetAccount(ref source_account_id, _, _) => { ensure!(sender_origin == &RawOrigin::Signed(source_account_id.clone()), BadOrigin); Ok(Some(source_account_id.clone())) - } + }, CallOrigin::SourceAccount(ref source_account_id) => { ensure!( - sender_origin == &RawOrigin::Signed(source_account_id.clone()) - || sender_origin == &RawOrigin::Root, + sender_origin == &RawOrigin::Signed(source_account_id.clone()) || + sender_origin == &RawOrigin::Root, BadOrigin ); Ok(Some(source_account_id.clone())) - } + }, } } diff --git a/modules/grandpa/src/lib.rs b/modules/grandpa/src/lib.rs index 1446c3696f5..cbc85da3025 100644 --- a/modules/grandpa/src/lib.rs +++ b/modules/grandpa/src/lib.rs @@ -149,7 +149,7 @@ pub mod pallet { finality_target, ); fail!(>::NotInitialized); - } + }, }; // We do a quick check here to ensure that our header chain is making progress and isn't @@ -220,11 +220,11 @@ pub mod pallet { Some(new_owner) => { PalletOwner::::put(&new_owner); log::info!(target: "runtime::bridge-grandpa", "Setting pallet Owner to: {:?}", new_owner); - } + }, None => { PalletOwner::::kill(); log::info!(target: "runtime::bridge-grandpa", "Removed Owner of pallet."); - } + }, } Ok(().into()) @@ -514,9 +514,7 @@ pub mod pallet { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == >::get().as_ref() => - { - Ok(()) - } + Ok(()), _ => Err(BadOrigin), } } diff --git a/modules/messages/src/inbound_lane.rs b/modules/messages/src/inbound_lane.rs index 94d9c4b7ee5..00875bb878a 100644 --- a/modules/messages/src/inbound_lane.rs +++ b/modules/messages/src/inbound_lane.rs @@ -81,10 +81,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; @@ -108,8 +108,8 @@ impl InboundLane { .dispatch_results .split_off((new_confirmed_nonce + 1 - entry.messages.begin) as _); entry.messages.begin = new_confirmed_nonce + 1; - } - _ => {} + }, + _ => {}, } self.storage.set_data(data); @@ -127,18 +127,18 @@ impl InboundLane { let mut data = self.storage.data(); let is_correct_message = nonce == data.last_delivered_nonce() + 1; if !is_correct_message { - 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 @@ -155,7 +155,7 @@ impl InboundLane { Some(entry) if entry.relayer == *relayer_at_bridged_chain => { entry.messages.note_dispatched_message(dispatch_result.dispatch_result); false - } + }, _ => true, }; if push_new { diff --git a/modules/messages/src/instant_payments.rs b/modules/messages/src/instant_payments.rs index 23b0df41074..c145687af99 100644 --- a/modules/messages/src/instant_payments.rs +++ b/modules/messages/src/instant_payments.rs @@ -171,7 +171,7 @@ fn pay_relayers_rewards( // If delivery confirmation is submitted by this relayer, let's add confirmation fee // from other relayers to this relayer reward. confirmation_relayer_reward = confirmation_relayer_reward.saturating_add(reward.reward); - continue; + continue } pay_relayer_reward::(relayer_fund_account, &relayer, relayer_reward); @@ -195,7 +195,7 @@ fn pay_relayer_reward( Currency: CurrencyT, { if reward.is_zero() { - return; + return } let pay_result = Currency::transfer( diff --git a/modules/messages/src/lib.rs b/modules/messages/src/lib.rs index f7b641f57eb..119869d81e9 100644 --- a/modules/messages/src/lib.rs +++ b/modules/messages/src/lib.rs @@ -223,11 +223,11 @@ pub mod pallet { Some(new_owner) => { PalletOwner::::put(&new_owner); log::info!(target: "runtime::bridge-messages", "Setting pallet Owner to: {:?}", new_owner); - } + }, None => { PalletOwner::::kill(); log::info!(target: "runtime::bridge-messages", "Removed Owner of pallet."); - } + }, } Ok(()) } @@ -444,7 +444,7 @@ pub mod pallet { dispatch_weight, dispatch_weight_left, ); - break; + break } total_messages += 1; @@ -468,10 +468,10 @@ pub mod pallet { dispatch_result.unspent_weight, !dispatch_result.dispatch_fee_paid_during_dispatch, ) - } - ReceivalResult::InvalidNonce - | ReceivalResult::TooManyUnrewardedRelayers - | ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), + }, + ReceivalResult::InvalidNonce | + ReceivalResult::TooManyUnrewardedRelayers | + ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), }; let unspent_weight = sp_std::cmp::min(unspent_weight, dispatch_weight); @@ -548,10 +548,10 @@ pub mod pallet { // (we only care about total number of entries and messages, because this affects call // weight) ensure!( - total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) - == relayers_state.total_messages - && lane_data.relayers.len() as MessageNonce - == relayers_state.unrewarded_relayer_entries, + total_unrewarded_messages(&lane_data.relayers).unwrap_or(MessageNonce::MAX) == + relayers_state.total_messages && + lane_data.relayers.len() as MessageNonce == + relayers_state.unrewarded_relayer_entries, Error::::InvalidUnrewardedRelayersState ); @@ -563,9 +563,8 @@ pub mod pallet { last_delivered_nonce, &lane_data.relayers, ) { - ReceivalConfirmationResult::ConfirmedMessages(confirmed_messages) => { - Some(confirmed_messages) - } + ReceivalConfirmationResult::ConfirmedMessages(confirmed_messages) => + Some(confirmed_messages), ReceivalConfirmationResult::NoNewConfirmations => None, ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected( to_confirm_messages_count, @@ -578,7 +577,7 @@ pub mod pallet { ); fail!(Error::::TryingToConfirmMoreMessagesThanExpected); - } + }, error => { log::trace!( target: "runtime::bridge-messages", @@ -587,7 +586,7 @@ pub mod pallet { ); fail!(Error::::InvalidUnrewardedRelayers); - } + }, }; if let Some(confirmed_messages) = confirmed_messages { @@ -608,7 +607,7 @@ pub mod pallet { difference, ); actual_weight = actual_weight.saturating_sub(difference); - } + }, None => { debug_assert!( false, @@ -621,7 +620,7 @@ pub mod pallet { preliminary_callback_overhead, actual_callback_weight, ); - } + }, } // emit 'delivered' event @@ -951,7 +950,7 @@ fn send_message, I: 'static>( difference, ); actual_weight = actual_weight.saturating_sub(difference); - } + }, None => { debug_assert!(false, "T::OnMessageAccepted callback consumed too much weight."); log::error!( @@ -961,7 +960,7 @@ fn send_message, I: 'static>( single_message_callback_overhead, actual_callback_weight, ); - } + }, } // message sender pays for pruning at most `MaxMessagesToPruneAtOnce` messages @@ -992,9 +991,7 @@ fn ensure_owner_or_root, I: 'static>(origin: T::Origin) -> Result<( Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) if Some(signer) == Pallet::::module_owner().as_ref() => - { - Ok(()) - } + Ok(()), _ => Err(BadOrigin), } } @@ -1075,7 +1072,7 @@ impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage< we have no recursive borrows; qed", ) = Some(data.clone()); data - } + }, } } @@ -2317,8 +2314,8 @@ mod tests { let weight_when_max_messages_are_pruned = send_regular_message(); assert_eq!( weight_when_max_messages_are_pruned, - when_zero_messages_are_pruned - + crate::mock::DbWeight::get().writes(max_messages_to_prune), + when_zero_messages_are_pruned + + crate::mock::DbWeight::get().writes(max_messages_to_prune), ); }); } diff --git a/modules/messages/src/mock.rs b/modules/messages/src/mock.rs index 55047609b4d..a333c95bb58 100644 --- a/modules/messages/src/mock.rs +++ b/modules/messages/src/mock.rs @@ -159,9 +159,8 @@ pub enum TestMessagesParameter { impl MessagesParameter for TestMessagesParameter { fn save(&self) { match *self { - TestMessagesParameter::TokenConversionRate(conversion_rate) => { - TokenConversionRate::set(&conversion_rate) - } + TestMessagesParameter::TokenConversionRate(conversion_rate) => + TokenConversionRate::set(&conversion_rate), } } } @@ -324,8 +323,8 @@ impl TestMessageDeliveryAndDispatchPayment { /// Returns true if given fee has been paid by given submitter. pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool { - frame_support::storage::unhashed::get(b":message-fee:") - == Some((Sender::Signed(submitter), fee)) + frame_support::storage::unhashed::get(b":message-fee:") == + Some((Sender::Signed(submitter), fee)) } /// Returns true if given relayer has been rewarded with given balance. The reward-paid flag is @@ -347,7 +346,7 @@ impl MessageDeliveryAndDispatchPayment _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { if frame_support::storage::unhashed::get(b":reject-message-fee:") == Some(true) { - return Err(TEST_ERROR); + return Err(TEST_ERROR) } frame_support::storage::unhashed::put(b":message-fee:", &(submitter, fee)); diff --git a/modules/messages/src/outbound_lane.rs b/modules/messages/src/outbound_lane.rs index c7f6b136478..c05437596db 100644 --- a/modules/messages/src/outbound_lane.rs +++ b/modules/messages/src/outbound_lane.rs @@ -107,10 +107,10 @@ impl OutboundLane { ) -> ReceivalConfirmationResult { let mut data = self.storage.data(); if latest_delivered_nonce <= data.latest_received_nonce { - return ReceivalConfirmationResult::NoNewConfirmations; + return ReceivalConfirmationResult::NoNewConfirmations } if latest_delivered_nonce > data.latest_generated_nonce { - return ReceivalConfirmationResult::FailedToConfirmFutureMessages; + return ReceivalConfirmationResult::FailedToConfirmFutureMessages } if latest_delivered_nonce - data.latest_received_nonce > max_allowed_messages { // that the relayer has declared correct number of messages that the proof contains (it @@ -120,7 +120,7 @@ impl OutboundLane { // weight formula accounts, so we can't allow that. return ReceivalConfirmationResult::TryingToConfirmMoreMessagesThanExpected( latest_delivered_nonce - data.latest_received_nonce, - ); + ) } let dispatch_results = match extract_dispatch_results( @@ -150,8 +150,8 @@ impl OutboundLane { let mut pruned_messages = 0; let mut anything_changed = false; let mut data = self.storage.data(); - while pruned_messages < max_messages_to_prune - && data.oldest_unpruned_nonce <= data.latest_received_nonce + while pruned_messages < max_messages_to_prune && + data.oldest_unpruned_nonce <= data.latest_received_nonce { self.storage.remove_message(&data.oldest_unpruned_nonce); @@ -188,14 +188,14 @@ fn extract_dispatch_results( // 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(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry); + return Err(ReceivalConfirmationResult::EmptyUnrewardedRelayerEntry) } // every entry must confirm range of messages that follows previous entry range // (guaranteed by the `InboundLane::receive_message()`) if let Some(last_entry_end) = last_entry_end { let expected_entry_begin = last_entry_end.checked_add(1); if expected_entry_begin != Some(entry.messages.begin) { - return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries); + return Err(ReceivalConfirmationResult::NonConsecutiveUnrewardedRelayerEntries) } } last_entry_end = Some(entry.messages.end); @@ -205,14 +205,14 @@ fn extract_dispatch_results( // technically this will be detected in the next loop iteration as // `InvalidNumberOfDispatchResults` but to guarantee safety of loop operations below // this is detected now - return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages); + return Err(ReceivalConfirmationResult::FailedToConfirmFutureMessages) } // entry must have single dispatch result for every message // (guaranteed by the `InboundLane::receive_message()`) - if entry.messages.dispatch_results.len() as MessageNonce - != entry.messages.end - entry.messages.begin + 1 + if entry.messages.dispatch_results.len() as MessageNonce != + entry.messages.end - entry.messages.begin + 1 { - return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults); + return Err(ReceivalConfirmationResult::InvalidNumberOfDispatchResults) } // now we know that the entry is valid @@ -222,7 +222,7 @@ fn extract_dispatch_results( let new_messages_end = sp_std::cmp::min(entry.messages.end, latest_received_nonce); let new_messages_range = new_messages_begin..=new_messages_end; if new_messages_range.is_empty() { - continue; + continue } // now we know that entry brings new confirmations diff --git a/modules/messages/src/weights_ext.rs b/modules/messages/src/weights_ext.rs index f83fc364cbb..fef09c6cebe 100644 --- a/modules/messages/src/weights_ext.rs +++ b/modules/messages/src/weights_ext.rs @@ -61,8 +61,8 @@ pub fn ensure_weights_are_correct( 0, ); assert!( - actual_single_regular_message_delivery_tx_weight - <= expected_default_message_delivery_tx_weight, + actual_single_regular_message_delivery_tx_weight <= + expected_default_message_delivery_tx_weight, "Default message delivery transaction weight {} is larger than expected weight {}", actual_single_regular_message_delivery_tx_weight, expected_default_message_delivery_tx_weight, @@ -94,8 +94,8 @@ pub fn ensure_weights_are_correct( db_weight, ); assert!( - actual_messages_delivery_confirmation_tx_weight - <= expected_messages_delivery_confirmation_tx_weight, + actual_messages_delivery_confirmation_tx_weight <= + expected_messages_delivery_confirmation_tx_weight, "Messages delivery confirmation transaction weight {} is larger than expected weight {}", actual_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight, @@ -359,9 +359,9 @@ pub trait WeightInfoExt: WeightInfo { /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { let proof_size_in_bytes = proof_size as Weight; - let byte_weight = (Self::receive_single_message_proof_16_kb() - - Self::receive_single_message_proof_1_kb()) - / (15 * 1024); + let byte_weight = (Self::receive_single_message_proof_16_kb() - + Self::receive_single_message_proof_1_kb()) / + (15 * 1024); proof_size_in_bytes * byte_weight } diff --git a/modules/shift-session-manager/src/lib.rs b/modules/shift-session-manager/src/lib.rs index db4631e2753..06d0b3fb0f8 100644 --- a/modules/shift-session-manager/src/lib.rs +++ b/modules/shift-session-manager/src/lib.rs @@ -54,7 +54,7 @@ impl pallet_session::SessionManager for Pallet { fn new_session(session_index: sp_staking::SessionIndex) -> Option> { // we don't want to add even more fields to genesis config => just return None if session_index == 0 || session_index == 1 { - return None; + return None } // the idea that on first call (i.e. when session 1 ends) we're reading current diff --git a/modules/token-swap/src/lib.rs b/modules/token-swap/src/lib.rs index 580427bf0ea..43fa13ba4bd 100644 --- a/modules/token-swap/src/lib.rs +++ b/modules/token-swap/src/lib.rs @@ -305,7 +305,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToTransferToSwapAccount, - )); + )) } // the transfer message is sent over the bridge. The message is supposed to be a @@ -339,8 +339,8 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToSendTransferMessage, - )); - } + )) + }, }; // remember that we have started the swap @@ -348,7 +348,7 @@ pub mod pallet { let insert_swap_result = PendingSwaps::::try_mutate(swap_hash, |maybe_state| { if maybe_state.is_some() { - return Err(()); + return Err(()) } *maybe_state = Some(TokenSwapState::Started); @@ -363,7 +363,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::SwapAlreadyStarted, - )); + )) } log::trace!( @@ -414,13 +414,12 @@ pub mod pallet { Some(TokenSwapState::Confirmed) => { let is_claim_allowed = match swap.swap_type { TokenSwapType::TemporaryTargetAccountAtBridgedChain => true, - TokenSwapType::LockClaimUntilBlock(block_number, _) => { - block_number < frame_system::Pallet::::block_number() - } + TokenSwapType::LockClaimUntilBlock(block_number, _) => + block_number < frame_system::Pallet::::block_number(), }; ensure!(is_claim_allowed, Error::::SwapIsTemporaryLocked); - } + }, Some(TokenSwapState::Failed) => fail!(Error::::SwapIsFailed), None => fail!(Error::::SwapIsInactive), } @@ -456,7 +455,7 @@ pub mod pallet { // we allow canceling swap even before lock period is over - the // `source_account_at_this_chain` has already paid for nothing and it is up to // him to decide whether he want to try again - } + }, None => fail!(Error::::SwapIsInactive), } @@ -530,7 +529,7 @@ pub mod pallet { fn on_messages_delivered(lane: &LaneId, delivered_messages: &DeliveredMessages) -> Weight { // we're only interested in our lane messages if *lane != T::OutboundMessageLaneId::get() { - return 0; + return 0 } // so now we're dealing with our lane messages. Ideally we'll have dedicated lane @@ -610,7 +609,7 @@ pub mod pallet { return sp_runtime::TransactionOutcome::Rollback(Err( Error::::FailedToTransferFromSwapAccount.into(), - )); + )) } log::trace!( @@ -842,8 +841,8 @@ mod tests { test_swap().source_balance_at_this_chain + SWAP_DELIVERY_AND_DISPATCH_FEE, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event - == crate::mock::Event::TokenSwap(crate::Event::SwapStarted( + frame_system::Pallet::::events().iter().any(|e| e.event == + crate::mock::Event::TokenSwap(crate::Event::SwapStarted( swap_hash, MESSAGE_NONCE, ))), @@ -975,8 +974,8 @@ mod tests { test_swap().source_balance_at_this_chain, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event - == crate::mock::Event::TokenSwap(crate::Event::SwapClaimed(swap_hash,))), + frame_system::Pallet::::events().iter().any(|e| e.event == + crate::mock::Event::TokenSwap(crate::Event::SwapClaimed(swap_hash,))), "Missing SwapClaimed event: {:?}", frame_system::Pallet::::events(), ); @@ -1079,8 +1078,8 @@ mod tests { THIS_CHAIN_ACCOUNT_BALANCE - SWAP_DELIVERY_AND_DISPATCH_FEE, ); assert!( - frame_system::Pallet::::events().iter().any(|e| e.event - == crate::mock::Event::TokenSwap(crate::Event::SwapCanceled(swap_hash,))), + frame_system::Pallet::::events().iter().any(|e| e.event == + crate::mock::Event::TokenSwap(crate::Event::SwapCanceled(swap_hash,))), "Missing SwapCanceled event: {:?}", frame_system::Pallet::::events(), ); diff --git a/primitives/header-chain/src/justification.rs b/primitives/header-chain/src/justification.rs index ea368546813..9f8e9662ea0 100644 --- a/primitives/header-chain/src/justification.rs +++ b/primitives/header-chain/src/justification.rs @@ -92,7 +92,7 @@ where { // ensure that it is justification for the expected header if (justification.commit.target_hash, justification.commit.target_number) != finalized_target { - return Err(Error::InvalidJustificationTarget); + return Err(Error::InvalidJustificationTarget) } let mut chain = AncestryChain::new(&justification.votes_ancestries); @@ -106,8 +106,8 @@ where None => { // just ignore precommit from unknown authority as // `finality_grandpa::import_precommit` does - continue; - } + continue + }, }; // check if authority has already voted in the same round. @@ -116,14 +116,14 @@ where // `finality-grandpa` crate (mostly related to reporing equivocations). But the only thing // that we care about is that only first vote from the authority is accepted if !votes.insert(signed.id.clone()) { - continue; + continue } // everything below this line can't just `continue`, because state is already altered // all precommits must be for block higher than the target if signed.precommit.target_number < justification.commit.target_number { - return Err(Error::PrecommitIsNotCommitDescendant); + return Err(Error::PrecommitIsNotCommitDescendant) } // all precommits must be for target block descendents chain = chain @@ -151,13 +151,13 @@ where authorities_set_id, &mut signature_buffer, ) { - return Err(Error::InvalidAuthoritySignature); + return Err(Error::InvalidAuthoritySignature) } } // check that there are no extra headers in the justification if !chain.unvisited.is_empty() { - return Err(Error::ExtraHeadersInVotesAncestries); + return Err(Error::ExtraHeadersInVotesAncestries) } // check that the cumulative weight of validators voted for the justification target (or one @@ -203,7 +203,7 @@ impl AncestryChain

{ let mut current_hash = *precommit_target; loop { if current_hash == *commit_target { - break; + break } let is_visited_before = !self.unvisited.remove(¤t_hash); @@ -214,11 +214,11 @@ impl AncestryChain
{ // container `is_visited_before` means that it has been visited before in // some of previous calls => since we assume that previous call has finished // with `true`, this also will be finished with `true` - return Ok(self); + return Ok(self) } *parent_hash - } + }, None => return Err(Error::PrecommitIsNotCommitDescendant), }; } diff --git a/primitives/header-chain/tests/implementation_match.rs b/primitives/header-chain/tests/implementation_match.rs index f33261fb52b..51275bbd645 100644 --- a/primitives/header-chain/tests/implementation_match.rs +++ b/primitives/header-chain/tests/implementation_match.rs @@ -53,13 +53,13 @@ impl finality_grandpa::Chain for AncestryChain { let mut current_hash = block; loop { if current_hash == base { - break; + break } match self.0.parents.get(¤t_hash).cloned() { Some(parent_hash) => { current_hash = parent_hash; route.push(current_hash); - } + }, _ => return Err(finality_grandpa::Error::NotDescendent), } } diff --git a/primitives/messages/src/lib.rs b/primitives/messages/src/lib.rs index d2a61b8a7d2..abefe8d789b 100644 --- a/primitives/messages/src/lib.rs +++ b/primitives/messages/src/lib.rs @@ -316,7 +316,7 @@ pub fn total_unrewarded_messages( } else { Some(0) } - } + }, _ => Some(0), } } diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index dea577a844b..051dc1f43c0 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -109,12 +109,10 @@ where AccountId: Encode, { match id { - SourceAccount::Root => { - (ROOT_ACCOUNT_DERIVATION_PREFIX, bridge_id).using_encoded(blake2_256) - } - SourceAccount::Account(id) => { - (ACCOUNT_DERIVATION_PREFIX, bridge_id, id).using_encoded(blake2_256) - } + SourceAccount::Root => + (ROOT_ACCOUNT_DERIVATION_PREFIX, bridge_id).using_encoded(blake2_256), + SourceAccount::Account(id) => + (ACCOUNT_DERIVATION_PREFIX, bridge_id, id).using_encoded(blake2_256), } .into() } @@ -188,9 +186,8 @@ impl, BlockHash: Copy> TransactionEra sp_runtime::generic::Era { match *self { TransactionEra::Immortal => sp_runtime::generic::Era::immortal(), - TransactionEra::Mortal(header_id, period) => { - sp_runtime::generic::Era::mortal(period as _, header_id.0.into()) - } + TransactionEra::Mortal(header_id, period) => + sp_runtime::generic::Era::mortal(period as _, header_id.0.into()), } } diff --git a/primitives/runtime/src/storage_proof.rs b/primitives/runtime/src/storage_proof.rs index 7d9ddbda2db..9cc5b48ebd9 100644 --- a/primitives/runtime/src/storage_proof.rs +++ b/primitives/runtime/src/storage_proof.rs @@ -42,7 +42,7 @@ where pub fn new(root: H::Out, proof: StorageProof) -> Result { let db = proof.into_memory_db(); if !db.contains(&root, EMPTY_PREFIX) { - return Err(Error::StorageRootMismatch); + return Err(Error::StorageRootMismatch) } let checker = StorageProofChecker { root, db }; diff --git a/relays/bin-substrate/src/chains/kusama.rs b/relays/bin-substrate/src/chains/kusama.rs index 3e9ae7b09fa..b12d23f2a56 100644 --- a/relays/bin-substrate/src/chains/kusama.rs +++ b/relays/bin-substrate/src/chains/kusama.rs @@ -48,7 +48,7 @@ impl CliEncodeCall for Kusama { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::KUSAMA_TO_POLKADOT_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -57,13 +57,12 @@ impl CliEncodeCall for Kusama { lane.0, payload, fee.0, ), ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, _ => anyhow::bail!("Unsupported Kusama call: {:?}", call), }) } diff --git a/relays/bin-substrate/src/chains/millau.rs b/relays/bin-substrate/src/chains/millau.rs index c6259c171bf..755d7cc4430 100644 --- a/relays/bin-substrate/src/chains/millau.rs +++ b/relays/bin-substrate/src/chains/millau.rs @@ -47,18 +47,16 @@ impl CliEncodeCall for Millau { fn encode_call(call: &Call) -> anyhow::Result { Ok(match call { Call::Raw { data } => Decode::decode(&mut &*data.0)?, - Call::Remark { remark_payload, .. } => { + Call::Remark { remark_payload, .. } => millau_runtime::Call::System(millau_runtime::SystemCall::remark { remark: remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), - }) - } - Call::Transfer { recipient, amount } => { + }), + Call::Transfer { recipient, amount } => millau_runtime::Call::Balances(millau_runtime::BalancesCall::transfer { dest: recipient.raw_id(), value: amount.cast(), - }) - } - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + }), + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::MILLAU_TO_RIALTO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -69,13 +67,12 @@ impl CliEncodeCall for Millau { delivery_and_dispatch_fee: fee.cast(), }, ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, }) } @@ -131,7 +128,7 @@ impl CliChain for Millau { &call, DispatchFeePayment::AtSourceChain, )) - } + }, } } } diff --git a/relays/bin-substrate/src/chains/polkadot.rs b/relays/bin-substrate/src/chains/polkadot.rs index e0f3c964264..7b6256d1749 100644 --- a/relays/bin-substrate/src/chains/polkadot.rs +++ b/relays/bin-substrate/src/chains/polkadot.rs @@ -48,7 +48,7 @@ impl CliEncodeCall for Polkadot { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::POLKADOT_TO_KUSAMA_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -57,13 +57,12 @@ impl CliEncodeCall for Polkadot { lane.0, payload, fee.0, ), ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, _ => anyhow::bail!("Unsupported Polkadot call: {:?}", call), }) } diff --git a/relays/bin-substrate/src/chains/rialto.rs b/relays/bin-substrate/src/chains/rialto.rs index b425898df1f..2d873a24ba7 100644 --- a/relays/bin-substrate/src/chains/rialto.rs +++ b/relays/bin-substrate/src/chains/rialto.rs @@ -47,18 +47,16 @@ impl CliEncodeCall for Rialto { fn encode_call(call: &Call) -> anyhow::Result { Ok(match call { Call::Raw { data } => Decode::decode(&mut &*data.0)?, - Call::Remark { remark_payload, .. } => { + Call::Remark { remark_payload, .. } => rialto_runtime::Call::System(rialto_runtime::SystemCall::remark { remark: remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), - }) - } - Call::Transfer { recipient, amount } => { + }), + Call::Transfer { recipient, amount } => rialto_runtime::Call::Balances(rialto_runtime::BalancesCall::transfer { dest: recipient.raw_id().into(), value: amount.0, - }) - } - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + }), + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::RIALTO_TO_MILLAU_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -69,13 +67,12 @@ impl CliEncodeCall for Rialto { delivery_and_dispatch_fee: fee.0, }, ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, }) } @@ -130,7 +127,7 @@ impl CliChain for Rialto { &call, DispatchFeePayment::AtSourceChain, )) - } + }, } } } diff --git a/relays/bin-substrate/src/chains/rialto_parachain.rs b/relays/bin-substrate/src/chains/rialto_parachain.rs index 48ebd3602db..9adcad22319 100644 --- a/relays/bin-substrate/src/chains/rialto_parachain.rs +++ b/relays/bin-substrate/src/chains/rialto_parachain.rs @@ -47,7 +47,7 @@ impl CliEncodeCall for RialtoParachain { ), Call::BridgeSendMessage { .. } => { anyhow::bail!("Bridge messages are not (yet) supported here",) - } + }, }) } diff --git a/relays/bin-substrate/src/chains/rococo.rs b/relays/bin-substrate/src/chains/rococo.rs index 0a27e8b177a..4df60f89faa 100644 --- a/relays/bin-substrate/src/chains/rococo.rs +++ b/relays/bin-substrate/src/chains/rococo.rs @@ -44,7 +44,7 @@ impl CliEncodeCall for Rococo { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::ROCOCO_TO_WOCOCO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -53,13 +53,12 @@ impl CliEncodeCall for Rococo { lane.0, payload, fee.0, ), ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, _ => anyhow::bail!("The call is not supported"), }) } diff --git a/relays/bin-substrate/src/chains/wococo.rs b/relays/bin-substrate/src/chains/wococo.rs index 9d7ace41a8a..328397d14ba 100644 --- a/relays/bin-substrate/src/chains/wococo.rs +++ b/relays/bin-substrate/src/chains/wococo.rs @@ -38,7 +38,7 @@ impl CliEncodeCall for Wococo { remark_payload.as_ref().map(|x| x.0.clone()).unwrap_or_default(), ), ), - Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => { + Call::BridgeSendMessage { lane, payload, fee, bridge_instance_index } => match *bridge_instance_index { bridge::WOCOCO_TO_ROCOCO_INDEX => { let payload = Decode::decode(&mut &*payload.0)?; @@ -47,13 +47,12 @@ impl CliEncodeCall for Wococo { lane.0, payload, fee.0, ), ) - } + }, _ => anyhow::bail!( "Unsupported target bridge pallet with instance index: {}", bridge_instance_index ), - } - } + }, _ => anyhow::bail!("The call is not supported"), }) } diff --git a/relays/bin-substrate/src/cli/encode_call.rs b/relays/bin-substrate/src/cli/encode_call.rs index 9429436fbf5..e17854662e5 100644 --- a/relays/bin-substrate/src/cli/encode_call.rs +++ b/relays/bin-substrate/src/cli/encode_call.rs @@ -129,8 +129,8 @@ pub(crate) fn preprocess_call {} - Call::Remark { ref remark_size, ref mut remark_payload } => { + Call::Raw { .. } => {}, + Call::Remark { ref remark_size, ref mut remark_payload } => if remark_payload.is_none() { *remark_payload = Some(HexBytes(generate_remark_payload( remark_size, @@ -139,14 +139,13 @@ pub(crate) fn preprocess_call { recipient.enforce_chain::(); - } + }, Call::BridgeSendMessage { ref mut bridge_instance_index, .. } => { *bridge_instance_index = bridge_instance; - } + }, }; } @@ -287,8 +286,8 @@ mod tests { let info = err.info.unwrap(); assert!( - info.contains(&"remark-payload".to_string()) - | info.contains(&"remark-size".to_string()) + info.contains(&"remark-payload".to_string()) | + info.contains(&"remark-size".to_string()) ) } diff --git a/relays/bin-substrate/src/cli/init_bridge.rs b/relays/bin-substrate/src/cli/init_bridge.rs index 39757ad6cf0..ffda0b12008 100644 --- a/relays/bin-substrate/src/cli/init_bridge.rs +++ b/relays/bin-substrate/src/cli/init_bridge.rs @@ -70,7 +70,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::RialtoToMillau => { type Source = relay_rialto_client::Rialto; type Target = relay_millau_client::Millau; @@ -88,7 +88,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::WestendToMillau => { type Source = relay_westend_client::Westend; type Target = relay_millau_client::Millau; @@ -110,7 +110,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::RococoToWococo => { type Source = relay_rococo_client::Rococo; type Target = relay_wococo_client::Wococo; @@ -126,7 +126,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::WococoToRococo => { type Source = relay_wococo_client::Wococo; type Target = relay_rococo_client::Rococo; @@ -142,7 +142,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::KusamaToPolkadot => { type Source = relay_kusama_client::Kusama; type Target = relay_polkadot_client::Polkadot; @@ -158,7 +158,7 @@ macro_rules! select_bridge { } $generic - } + }, InitBridgeName::PolkadotToKusama => { type Source = relay_polkadot_client::Polkadot; type Target = relay_kusama_client::Kusama; @@ -174,7 +174,7 @@ macro_rules! select_bridge { } $generic - } + }, } }; } diff --git a/relays/bin-substrate/src/cli/mod.rs b/relays/bin-substrate/src/cli/mod.rs index 252eb0c720a..f1180059b99 100644 --- a/relays/bin-substrate/src/cli/mod.rs +++ b/relays/bin-substrate/src/cli/mod.rs @@ -104,15 +104,15 @@ impl Command { use relay_utils::initialize::{initialize_logger, initialize_relay}; match self { - Self::RelayHeaders(_) - | Self::RelayMessages(_) - | Self::RelayHeadersAndMessages(_) - | Self::InitBridge(_) => { + Self::RelayHeaders(_) | + Self::RelayMessages(_) | + Self::RelayHeadersAndMessages(_) | + Self::InitBridge(_) => { initialize_relay(); - } + }, _ => { initialize_logger(false); - } + }, } } @@ -359,7 +359,7 @@ where fn from_str(s: &str) -> Result { if s.to_lowercase() == "max" { - return Ok(ExplicitOrMaximal::Maximal); + return Ok(ExplicitOrMaximal::Maximal) } V::from_str(s) diff --git a/relays/bin-substrate/src/cli/register_parachain.rs b/relays/bin-substrate/src/cli/register_parachain.rs index 3e7d4e2a3cb..fecc431148e 100644 --- a/relays/bin-substrate/src/cli/register_parachain.rs +++ b/relays/bin-substrate/src/cli/register_parachain.rs @@ -84,7 +84,7 @@ macro_rules! select_bridge { use bp_rialto::{PARAS_PALLET_NAME, PARAS_REGISTRAR_PALLET_NAME}; $generic - } + }, } }; } @@ -278,10 +278,10 @@ async fn wait_para_state( })?; if para_state == to_state { log::info!(target: "bridge", "Parachain state is now: {:?}", to_state); - return Ok(()); + return Ok(()) } if !from_states.contains(¶_state) { - return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state)); + return Err(anyhow::format_err!("Invalid parachain lifecycle: {:?}", para_state)) } log::info!(target: "bridge", "Parachain state: {:?}. Waiting for {:?}", para_state, to_state); diff --git a/relays/bin-substrate/src/cli/relay_headers.rs b/relays/bin-substrate/src/cli/relay_headers.rs index ef1905a0daf..82c55965a99 100644 --- a/relays/bin-substrate/src/cli/relay_headers.rs +++ b/relays/bin-substrate/src/cli/relay_headers.rs @@ -66,49 +66,49 @@ macro_rules! select_bridge { type Finality = crate::chains::millau_headers_to_rialto::MillauFinalityToRialto; $generic - } + }, RelayHeadersBridge::RialtoToMillau => { type Source = relay_rialto_client::Rialto; type Target = relay_millau_client::Millau; type Finality = crate::chains::rialto_headers_to_millau::RialtoFinalityToMillau; $generic - } + }, RelayHeadersBridge::WestendToMillau => { type Source = relay_westend_client::Westend; type Target = relay_millau_client::Millau; type Finality = crate::chains::westend_headers_to_millau::WestendFinalityToMillau; $generic - } + }, RelayHeadersBridge::RococoToWococo => { type Source = relay_rococo_client::Rococo; type Target = relay_wococo_client::Wococo; type Finality = crate::chains::rococo_headers_to_wococo::RococoFinalityToWococo; $generic - } + }, RelayHeadersBridge::WococoToRococo => { type Source = relay_wococo_client::Wococo; type Target = relay_rococo_client::Rococo; type Finality = crate::chains::wococo_headers_to_rococo::WococoFinalityToRococo; $generic - } + }, RelayHeadersBridge::KusamaToPolkadot => { type Source = relay_kusama_client::Kusama; type Target = relay_polkadot_client::Polkadot; type Finality = crate::chains::kusama_headers_to_polkadot::KusamaFinalityToPolkadot; $generic - } + }, RelayHeadersBridge::PolkadotToKusama => { type Source = relay_polkadot_client::Polkadot; type Target = relay_kusama_client::Kusama; type Finality = crate::chains::polkadot_headers_to_kusama::PolkadotFinalityToKusama; $generic - } + }, } }; } diff --git a/relays/bin-substrate/src/cli/resubmit_transactions.rs b/relays/bin-substrate/src/cli/resubmit_transactions.rs index 9b62b89b39f..64663d7e8ec 100644 --- a/relays/bin-substrate/src/cli/resubmit_transactions.rs +++ b/relays/bin-substrate/src/cli/resubmit_transactions.rs @@ -92,19 +92,19 @@ macro_rules! select_bridge { type TargetSign = relay_millau_client::Millau; $generic - } + }, RelayChain::Kusama => { type Target = relay_kusama_client::Kusama; type TargetSign = relay_kusama_client::Kusama; $generic - } + }, RelayChain::Polkadot => { type Target = relay_polkadot_client::Polkadot; type TargetSign = relay_polkadot_client::Polkadot; $generic - } + }, } }; } @@ -154,12 +154,10 @@ impl PrioritySelectionStrategy { context: &Context, ) -> Result, SubstrateError> { match *self { - PrioritySelectionStrategy::MakeItBestTransaction => { - read_previous_block_best_priority::(client, context).await - } - PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction => { - select_priority_from_queue::(client, context).await - } + PrioritySelectionStrategy::MakeItBestTransaction => + read_previous_block_best_priority::(client, context).await, + PrioritySelectionStrategy::MakeItBetterThanQueuedTransaction => + select_priority_from_queue::(client, context).await, } } } @@ -230,8 +228,8 @@ async fn run_until_connection_lost C::NAME, error, ); - return Err(FailedClient::Target); - } + return Err(FailedClient::Target) + }, }; } } @@ -250,8 +248,8 @@ async fn run_loop_iteration>( Some(original_transaction) => original_transaction, None => { log::trace!(target: "bridge", "No {} transactions from required signer in the txpool", C::NAME); - return Ok(context); - } + return Ok(context) + }, }; let original_transaction_hash = C::Hasher::hash(&original_transaction.encode()); let context = context.notice_transaction(original_transaction_hash); @@ -266,7 +264,7 @@ async fn run_loop_iteration>( context.stalled_for, context.stalled_for_limit, ); - return Ok(context); + return Ok(context) } // select priority for updated transaction @@ -275,8 +273,8 @@ async fn run_loop_iteration>( Some(target_priority) => target_priority, None => { log::trace!(target: "bridge", "Failed to select target priority"); - return Ok(context); - } + return Ok(context) + }, }; // update transaction tip @@ -293,7 +291,7 @@ async fn run_loop_iteration>( if !is_updated { log::trace!(target: "bridge", "{} transaction tip can not be updated. Reached limit?", C::NAME); - return Ok(context); + return Ok(context) } let updated_transaction = updated_transaction.encode(); @@ -321,10 +319,10 @@ async fn lookup_signer_transaction let pending_transaction = S::SignedTransaction::decode(&mut &pending_transaction.0[..]) .map_err(SubstrateError::ResponseParseFailed)?; if !S::is_signed_by(key_pair, &pending_transaction) { - continue; + continue } - return Ok(Some(pending_transaction)); + return Ok(Some(pending_transaction)) } Ok(None) @@ -379,7 +377,7 @@ fn select_transaction_from_queue( context: &Context, ) -> Option { if queued_transactions.is_empty() { - return None; + return None } // the more times we resubmit transaction (`context.resubmitted`), the closer we move @@ -416,7 +414,7 @@ async fn update_transaction_tip>( while current_priority < target_priority { let next_tip = unsigned_tx.tip + tip_step; if next_tip > tip_limit { - break; + break } log::trace!( diff --git a/relays/bin-substrate/src/cli/send_message.rs b/relays/bin-substrate/src/cli/send_message.rs index 4673cbab516..3e77ad83429 100644 --- a/relays/bin-substrate/src/cli/send_message.rs +++ b/relays/bin-substrate/src/cli/send_message.rs @@ -139,7 +139,7 @@ impl SendMessage { target_origin_public.into(), digest_signature.into(), ) - } + }, }, &target_call, *dispatch_fee_payment, diff --git a/relays/bin-substrate/src/cli/swap_tokens.rs b/relays/bin-substrate/src/cli/swap_tokens.rs index fb49c83dc88..dbe46f46907 100644 --- a/relays/bin-substrate/src/cli/swap_tokens.rs +++ b/relays/bin-substrate/src/cli/swap_tokens.rs @@ -121,7 +121,7 @@ macro_rules! select_bridge { const TARGET_TO_SOURCE_LANE_ID: bp_messages::LaneId = [0, 0, 0, 0]; $generic - } + }, } }; } @@ -269,13 +269,12 @@ impl SwapTokens { let intermediate_balances = read_account_balances(&accounts, &source_client, &target_client).await?; log::info!(target: "bridge", "Intermediate balances: {:?}", intermediate_balances); - } - Some(token_swap_state) => { + }, + Some(token_swap_state) => return Err(anyhow::format_err!( "Fresh token swap has unexpected state: {:?}", token_swap_state, - )) - } + )), None => return Err(anyhow::format_err!("Failed to start token swap")), }; @@ -294,26 +293,23 @@ impl SwapTokens { let is_transfer_succeeded = match token_swap_state { Some(bp_token_swap::TokenSwapState::Started) => { unreachable!("wait_until_token_swap_state_is_changed only returns if state is not Started; qed",) - } - None => { - return Err(anyhow::format_err!( - "Fresh token swap has disappeared unexpectedly" - )) - } + }, + None => + return Err(anyhow::format_err!("Fresh token swap has disappeared unexpectedly")), Some(bp_token_swap::TokenSwapState::Confirmed) => { log::info!( target: "bridge", "Transfer has been successfully dispatched at the target chain. Swap can be claimed", ); true - } + }, Some(bp_token_swap::TokenSwapState::Failed) => { log::info!( target: "bridge", "Transfer has been dispatched with an error at the target chain. Swap can be canceled", ); false - } + }, }; // by this time: (1) token swap account has been created and (2) if transfer has been @@ -407,7 +403,7 @@ impl SwapTokens { return Err(anyhow::format_err!( "Confirmed token swap state has been changed to {:?} unexpectedly", token_swap_state - )); + )) } } else { log::info!(target: "bridge", "Cancelling the swap"); @@ -491,9 +487,8 @@ impl SwapTokens { source_client: &Client, ) -> anyhow::Result>> { match self.swap_type { - TokenSwapType::NoLock => { - Ok(bp_token_swap::TokenSwapType::TemporaryTargetAccountAtBridgedChain) - } + TokenSwapType::NoLock => + Ok(bp_token_swap::TokenSwapType::TemporaryTargetAccountAtBridgedChain), TokenSwapType::LockUntilBlock { blocks_before_expire, ref swap_nonce } => { let blocks_before_expire: BlockNumberOf = blocks_before_expire.into(); let current_source_block_number = *source_client.best_header().await?.number(); @@ -503,7 +498,7 @@ impl SwapTokens { U256::from(random::()).overflowing_mul(U256::from(random::())).0 }), )) - } + }, } } } @@ -585,17 +580,16 @@ pub(crate) async fn wait_until_transaction_is_finalized( loop { let transaction_status = subscription.next().await?; match transaction_status { - Some(TransactionStatusOf::::FinalityTimeout(_)) - | Some(TransactionStatusOf::::Usurped(_)) - | Some(TransactionStatusOf::::Dropped) - | Some(TransactionStatusOf::::Invalid) - | None => { + Some(TransactionStatusOf::::FinalityTimeout(_)) | + Some(TransactionStatusOf::::Usurped(_)) | + Some(TransactionStatusOf::::Dropped) | + Some(TransactionStatusOf::::Invalid) | + None => return Err(anyhow::format_err!( "We've been waiting for finalization of {} transaction, but it now has the {:?} status", C::NAME, transaction_status, - )) - } + )), Some(TransactionStatusOf::::Finalized(block_hash)) => { log::trace!( target: "bridge", @@ -603,8 +597,8 @@ pub(crate) async fn wait_until_transaction_is_finalized( C::NAME, block_hash, ); - return Ok(block_hash); - } + return Ok(block_hash) + }, _ => { log::trace!( target: "bridge", @@ -612,7 +606,7 @@ pub(crate) async fn wait_until_transaction_is_finalized( C::NAME, transaction_status, ); - } + }, } } } @@ -634,7 +628,7 @@ async fn wait_until_token_swap_state_is_changed( let token_swap_state = read_token_swap_state(client, best_block_hash, swap_state_storage_key).await?; match token_swap_state { - Some(new_token_swap_state) if new_token_swap_state == previous_token_swap_state => {} + Some(new_token_swap_state) if new_token_swap_state == previous_token_swap_state => {}, _ => { log::trace!( target: "bridge", @@ -642,8 +636,8 @@ async fn wait_until_token_swap_state_is_changed( previous_token_swap_state, token_swap_state, ); - return Ok(token_swap_state); - } + return Ok(token_swap_state) + }, } } } @@ -660,7 +654,7 @@ async fn wait_until_swap_unlocked( let best_block = client.best_finalized_header_number().await?; let best_block_hash = client.block_hash_by_number(best_block).await?; if best_block >= required_block_number { - return Ok(()); + return Ok(()) } log::trace!(target: "bridge", "Skipping {} block {}/{}", C::NAME, best_block, best_block_hash); diff --git a/relays/client-substrate/src/client.rs b/relays/client-substrate/src/client.rs index 2d39200ce28..1902875c938 100644 --- a/relays/client-substrate/src/client.rs +++ b/relays/client-substrate/src/client.rs @@ -554,11 +554,10 @@ impl Subscription { ) { loop { match subscription.next().await { - Ok(Some(item)) => { + Ok(Some(item)) => if sender.send(Some(item)).await.is_err() { - break; - } - } + break + }, Ok(None) => { log::trace!( target: "bridge", @@ -567,8 +566,8 @@ impl Subscription { item_type, ); let _ = sender.send(None).await; - break; - } + break + }, Err(e) => { log::trace!( target: "bridge", @@ -578,8 +577,8 @@ impl Subscription { e, ); let _ = sender.send(None).await; - break; - } + break + }, } } } diff --git a/relays/client-substrate/src/finality_source.rs b/relays/client-substrate/src/finality_source.rs index 89141e4bd20..98526de178c 100644 --- a/relays/client-substrate/src/finality_source.rs +++ b/relays/client-substrate/src/finality_source.rs @@ -159,11 +159,11 @@ where Ok(j) => j, Err(err) => { log_error(format!("decode failed with error {:?}", err)); - continue; - } + continue + }, }; - return Some((justification, subscription)); + return Some((justification, subscription)) } }, ) diff --git a/relays/client-substrate/src/guard.rs b/relays/client-substrate/src/guard.rs index 0b738dc2b84..a064e362340 100644 --- a/relays/client-substrate/src/guard.rs +++ b/relays/client-substrate/src/guard.rs @@ -78,7 +78,7 @@ pub fn abort_on_spec_version_change( ); env.abort().await; - } + }, Err(error) => log::warn!( target: "bridge-guard", "Failed to read {} runtime version: {}. Relay may need to be stopped manually", @@ -140,7 +140,7 @@ pub fn abort_when_account_balance_decreased( env.abort().await; } - } + }, Err(error) => { log::warn!( target: "bridge-guard", @@ -149,7 +149,7 @@ pub fn abort_when_account_balance_decreased( account_id, error, ); - } + }, }; env.sleep(conditions_check_delay::()).await; diff --git a/relays/client-substrate/src/metrics/float_storage_value.rs b/relays/client-substrate/src/metrics/float_storage_value.rs index 53a9381d1b8..7dccf82b6f8 100644 --- a/relays/client-substrate/src/metrics/float_storage_value.rs +++ b/relays/client-substrate/src/metrics/float_storage_value.rs @@ -90,8 +90,8 @@ where .await .map(|maybe_storage_value| { maybe_storage_value.or(self.maybe_default_value).map(|storage_value| { - storage_value.into_inner().unique_saturated_into() as f64 - / T::DIV.unique_saturated_into() as f64 + storage_value.into_inner().unique_saturated_into() as f64 / + T::DIV.unique_saturated_into() as f64 }) }) .map_err(drop); diff --git a/relays/finality/src/finality_loop.rs b/relays/finality/src/finality_loop.rs index 5030c215f9a..320b44d310f 100644 --- a/relays/finality/src/finality_loop.rs +++ b/relays/finality/src/finality_loop.rs @@ -258,12 +258,12 @@ async fn run_until_connection_lost( last_transaction = updated_last_transaction; retry_backoff.reset(); sync_params.tick - } + }, Err(error) => { log::error!(target: "bridge", "Finality sync loop iteration has failed with error: {:?}", error); error.fail_if_connection_error()?; retry_backoff.next_backoff().unwrap_or(relay_utils::relay_loop::RECONNECT_DELAY) - } + }, }; if finality_proofs_stream.needs_restart { log::warn!(target: "bridge", "{} finality proofs stream is being restarted", P::SOURCE_NAME); @@ -319,9 +319,9 @@ where P::TARGET_NAME, ); - return Err(Error::Stalled); + return Err(Error::Stalled) } else { - return Ok(Some(last_transaction)); + return Ok(Some(last_transaction)) } } @@ -354,7 +354,7 @@ where .await .map_err(Error::Target)?; Ok(Some(new_transaction)) - } + }, None => Ok(None), } } @@ -391,17 +391,15 @@ where ) .await?; let (mut unjustified_headers, mut selected_finality_proof) = match selected_finality_proof { - SelectedFinalityProof::Mandatory(header, finality_proof) => { - return Ok(Some((header, finality_proof))) - } + SelectedFinalityProof::Mandatory(header, finality_proof) => + return Ok(Some((header, finality_proof))), _ if sync_params.only_mandatory_headers => { // we are not reading finality proofs from the stream, so eventually it'll break // but we don't care about transient proofs at all, so it is acceptable - return Ok(None); - } - SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) => { - (unjustified_headers, Some((header, finality_proof))) - } + return Ok(None) + }, + SelectedFinalityProof::Regular(unjustified_headers, header, finality_proof) => + (unjustified_headers, Some((header, finality_proof))), SelectedFinalityProof::None(unjustified_headers) => (unjustified_headers, None), }; @@ -469,17 +467,17 @@ pub(crate) async fn read_missing_headers< match (is_mandatory, finality_proof) { (true, Some(finality_proof)) => { log::trace!(target: "bridge", "Header {:?} is mandatory", header_number); - return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)); - } + return Ok(SelectedFinalityProof::Mandatory(header, finality_proof)) + }, (true, None) => return Err(Error::MissingMandatoryFinalityProof(header.number())), (false, Some(finality_proof)) => { log::trace!(target: "bridge", "Header {:?} has persistent finality proof", header_number); unjustified_headers.clear(); selected_finality_proof = Some((header, finality_proof)); - } + }, (false, None) => { unjustified_headers.push(header); - } + }, } header_number = header_number + One::one(); @@ -516,8 +514,8 @@ pub(crate) fn read_finality_proofs_from_stream< Some(Some(finality_proof)) => finality_proof, Some(None) => { finality_proofs_stream.needs_restart = true; - break; - } + break + }, None => break, }; @@ -557,7 +555,7 @@ pub(crate) fn select_better_recent_finality_proof( P::SOURCE_NAME, selected_finality_proof.as_ref().map(|(h, _)| h.number()), ); - return selected_finality_proof; + return selected_finality_proof } const NOT_EMPTY_PROOF: &str = "we have checked that the vec is not empty; qed"; @@ -596,7 +594,7 @@ pub(crate) fn select_better_recent_finality_proof( if has_selected_finality_proof { "improved" } else { "not improved" }, ); if !has_selected_finality_proof { - return selected_finality_proof; + return selected_finality_proof } // now remove all obsolete headers and extract selected header @@ -632,15 +630,15 @@ fn print_sync_progress( let (prev_time, prev_best_number_at_target) = progress_context; let now = Instant::now(); - let need_update = now - prev_time > Duration::from_secs(10) - || prev_best_number_at_target + let need_update = now - prev_time > Duration::from_secs(10) || + prev_best_number_at_target .map(|prev_best_number_at_target| { best_number_at_target.saturating_sub(prev_best_number_at_target) > 10.into() }) .unwrap_or(true); if !need_update { - return (prev_time, prev_best_number_at_target); + return (prev_time, prev_best_number_at_target) } log::info!( diff --git a/relays/lib-substrate-relay/src/conversion_rate_update.rs b/relays/lib-substrate-relay/src/conversion_rate_update.rs index 3f728c85a35..93458457d34 100644 --- a/relays/lib-substrate-relay/src/conversion_rate_update.rs +++ b/relays/lib-substrate-relay/src/conversion_rate_update.rs @@ -61,10 +61,10 @@ pub fn run_conversion_rate_update_loop< match submit_conversion_rate_future.await { Ok(()) => { transaction_status = TransactionStatus::Submitted(prev_conversion_rate); - } + }, Err(error) => { log::trace!(target: "bridge", "Failed to submit conversion rate update transaction: {:?}", error); - } + }, } } } @@ -96,11 +96,11 @@ async fn maybe_select_new_conversion_rate( { // the rate has not been changed => we won't submit any transactions until it is // accepted, or the rate is changed by someone else - return None; + return None } *transaction_status = TransactionStatus::Idle; - } + }, } let left_to_base_conversion_rate = (*left_to_base_conversion_rate.read().await)?; @@ -112,7 +112,7 @@ async fn maybe_select_new_conversion_rate( (actual_left_to_right_conversion_rate - left_to_right_stored_conversion_rate).abs(); let rate_difference_ratio = rate_difference / left_to_right_stored_conversion_rate; if rate_difference_ratio < max_difference_ratio { - return None; + return None } Some((left_to_right_stored_conversion_rate, actual_left_to_right_conversion_rate)) diff --git a/relays/lib-substrate-relay/src/headers_initialize.rs b/relays/lib-substrate-relay/src/headers_initialize.rs index 3b2a602bf3a..2e802c4cb21 100644 --- a/relays/lib-substrate-relay/src/headers_initialize.rs +++ b/relays/lib-substrate-relay/src/headers_initialize.rs @@ -191,7 +191,7 @@ async fn prepare_initialization_data( .is_ok(); if is_valid_set_id { - break; + break } initial_authorities_set_id += 1; @@ -200,7 +200,7 @@ async fn prepare_initialization_data( // there can't be more authorities set changes than headers => if we have reached // `initial_block_number` and still have not found correct value of // `initial_authorities_set_id`, then something else is broken => fail - return Err(Error::GuessInitialAuthorities(SourceChain::NAME, initial_header_number)); + return Err(Error::GuessInitialAuthorities(SourceChain::NAME, initial_header_number)) } } diff --git a/relays/lib-substrate-relay/src/messages_lane.rs b/relays/lib-substrate-relay/src/messages_lane.rs index 35977d764b7..6cadb64754a 100644 --- a/relays/lib-substrate-relay/src/messages_lane.rs +++ b/relays/lib-substrate-relay/src/messages_lane.rs @@ -225,8 +225,8 @@ pub fn select_delivery_transaction_limits( // this is actually prevented by external logic if nonces.is_empty() { - return Ok(weights_map); + return Ok(weights_map) } // check if last nonce is missing - loop below is not checking this let last_nonce_is_missing = weights.last().map(|details| details.nonce != *nonces.end()).unwrap_or(true); if last_nonce_is_missing { - return make_missing_nonce_error(*nonces.end()); + return make_missing_nonce_error(*nonces.end()) } let mut expected_nonce = *nonces.start(); @@ -401,13 +401,13 @@ fn make_message_details_map( C::NAME, expected_nonce..details.nonce, ); - } + }, (false, false) => { // some nonces are missing from the middle/tail of the range // // this is critical error, because we can't miss any nonces - return make_missing_nonce_error(expected_nonce); - } + return make_missing_nonce_error(expected_nonce) + }, } weights_map.insert( diff --git a/relays/lib-substrate-relay/src/on_demand_headers.rs b/relays/lib-substrate-relay/src/on_demand_headers.rs index 70bbab18a0f..ee141866eb9 100644 --- a/relays/lib-substrate-relay/src/on_demand_headers.rs +++ b/relays/lib-substrate-relay/src/on_demand_headers.rs @@ -175,7 +175,7 @@ async fn background_task( &mut finality_target, ) .await; - continue; + continue } // read best finalized source header number from target @@ -193,7 +193,7 @@ async fn background_task( &mut finality_target, ) .await; - continue; + continue } // submit mandatory header if some headers are missing @@ -224,8 +224,8 @@ async fn background_task( // there are no (or we don't need to relay them) mandatory headers in the range // => to avoid scanning the same headers over and over again, remember that latest_non_mandatory_at_source = mandatory_scan_range.1; - } - Err(e) => { + }, + Err(e) => if e.is_connection_error() { relay_utils::relay_loop::reconnect_failed_client( FailedClient::Source, @@ -234,9 +234,8 @@ async fn background_task( &mut finality_target, ) .await; - continue; - } - } + continue + }, } } @@ -299,12 +298,12 @@ async fn mandatory_headers_scan_range( .checked_sub(&best_finalized_source_header_at_target) .unwrap_or_else(Zero::zero); if current_headers_difference <= maximal_headers_difference { - return None; + return None } // if relay is already asked to sync headers, don't do anything yet if required_header_number > best_finalized_source_header_at_target { - return None; + return None } Some(( @@ -342,7 +341,7 @@ where // less than our `mandatory_source_header_number` before logging anything let mut required_header_number = required_header_number.lock().await; if *required_header_number >= mandatory_source_header_number { - return Ok(false); + return Ok(false) } log::trace!( @@ -422,7 +421,7 @@ where let header: SyncHeader = finality_source.client().header_by_number(current).await?.into(); if header.is_mandatory() { - return Ok(Some(current)); + return Ok(Some(current)) } current += One::one(); diff --git a/relays/messages/src/message_lane_loop.rs b/relays/messages/src/message_lane_loop.rs index df7916f6a60..6cdb2b1aa5a 100644 --- a/relays/messages/src/message_lane_loop.rs +++ b/relays/messages/src/message_lane_loop.rs @@ -566,7 +566,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError); + return Err(TestError) } Ok(data.source_state.clone()) } @@ -578,7 +578,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_source_fails { - return Err(TestError); + return Err(TestError) } Ok((id, data.source_latest_generated_nonce)) } @@ -699,7 +699,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError); + return Err(TestError) } Ok(data.target_state.clone()) } @@ -711,7 +711,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError); + return Err(TestError) } Ok((id, data.target_latest_received_nonce)) } @@ -737,7 +737,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError); + return Err(TestError) } Ok((id, data.target_latest_confirmed_received_nonce)) } @@ -758,7 +758,7 @@ pub(crate) mod tests { let mut data = self.data.lock(); (self.tick)(&mut *data); if data.is_target_fails { - return Err(TestError); + return Err(TestError) } data.target_state.best_self = HeaderId(data.target_state.best_self.0 + 1, data.target_state.best_self.1 + 1); @@ -786,9 +786,9 @@ pub(crate) mod tests { total_dispatch_weight: Weight, total_size: u32, ) -> Result { - Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) - + total_dispatch_weight - + total_size as TestSourceChainBalance) + Ok(BASE_MESSAGE_DELIVERY_TRANSACTION_COST * (nonces.end() - nonces.start() + 1) + + total_dispatch_weight + + total_size as TestSourceChainBalance) } } @@ -906,8 +906,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new target headers at source node if data.target_to_source_header_required.is_some() { assert!( - data.source_state.best_finalized_peer_at_best_self.0 - < data.target_state.best_self.0 + data.source_state.best_finalized_peer_at_best_self.0 < + data.target_state.best_self.0 ); data.target_to_source_header_required = None; } @@ -926,8 +926,8 @@ pub(crate) mod tests { // headers relay must only be started when we need new source headers at target node if data.source_to_target_header_required.is_some() { assert!( - data.target_state.best_finalized_peer_at_best_self.0 - < data.source_state.best_self.0 + data.target_state.best_finalized_peer_at_best_self.0 < + data.source_state.best_self.0 ); data.source_to_target_header_required = None; } diff --git a/relays/messages/src/message_race_delivery.rs b/relays/messages/src/message_race_delivery.rs index 0371ccc556d..b36d5bda38e 100644 --- a/relays/messages/src/message_race_delivery.rs +++ b/relays/messages/src/message_race_delivery.rs @@ -442,7 +442,7 @@ where self.max_unconfirmed_nonces_at_target, ); - return None; + return None } _ => (), } @@ -462,8 +462,8 @@ where // "unrewarded relayers" set. If we are unable to prove new rewards to the target node, then // we should wait for confirmations race. let unrewarded_relayer_entries_limit_reached = - target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries - >= self.max_unrewarded_relayer_entries_at_target; + target_nonces.nonces_data.unrewarded_relayers.unrewarded_relayer_entries >= + self.max_unrewarded_relayer_entries_at_target; if unrewarded_relayer_entries_limit_reached { // so there are already too many unrewarded relayer entries in the set // @@ -471,10 +471,10 @@ where // be paid let number_of_rewards_being_proved = latest_confirmed_nonce_at_source.saturating_sub(latest_confirmed_nonce_at_target); - let enough_rewards_being_proved = number_of_rewards_being_proved - >= target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; + let enough_rewards_being_proved = number_of_rewards_being_proved >= + target_nonces.nonces_data.unrewarded_relayers.messages_in_oldest_entry; if !enough_rewards_being_proved { - return None; + return None } } @@ -577,10 +577,10 @@ mod tests { const DEFAULT_DISPATCH_WEIGHT: Weight = 1; const DEFAULT_SIZE: u32 = 1; - const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST - + BASE_MESSAGE_DELIVERY_TRANSACTION_COST - + DEFAULT_DISPATCH_WEIGHT - + (DEFAULT_SIZE as TestSourceChainBalance); + const DEFAULT_REWARD: TestSourceChainBalance = CONFIRMATION_TRANSACTION_COST + + BASE_MESSAGE_DELIVERY_TRANSACTION_COST + + DEFAULT_DISPATCH_WEIGHT + + (DEFAULT_SIZE as TestSourceChainBalance); type TestRaceState = RaceState; type TestStrategy = @@ -720,8 +720,8 @@ mod tests { // we need to wait until confirmations will be delivered by receiving race strategy.latest_confirmed_nonces_at_source = vec![( header_id(1), - strategy.target_nonces.as_ref().unwrap().latest_nonce - - strategy.max_unconfirmed_nonces_at_target, + strategy.target_nonces.as_ref().unwrap().latest_nonce - + strategy.max_unconfirmed_nonces_at_target, )] .into_iter() .collect(); diff --git a/relays/messages/src/message_race_loop.rs b/relays/messages/src/message_race_loop.rs index bbb3890a509..a7254f70ee4 100644 --- a/relays/messages/src/message_race_loop.rs +++ b/relays/messages/src/message_race_loop.rs @@ -439,10 +439,10 @@ pub async fn run, TC: TargetClient

>( strategy, ); - return Err(FailedClient::Both); - } else if race_state.nonces_to_submit.is_none() - && race_state.nonces_submitted.is_none() - && strategy.is_empty() + return Err(FailedClient::Both) + } else if race_state.nonces_to_submit.is_none() && + race_state.nonces_submitted.is_none() && + strategy.is_empty() { stall_countdown = Instant::now(); } @@ -551,7 +551,7 @@ where let need_update = now_time.saturating_duration_since(prev_time) > Duration::from_secs(10); if !need_update { - return prev_time; + return prev_time } let now_best_nonce_at_source = strategy.best_at_source(); diff --git a/relays/messages/src/message_race_strategy.rs b/relays/messages/src/message_race_strategy.rs index 37f0cefa119..9b9091b979f 100644 --- a/relays/messages/src/message_race_strategy.rs +++ b/relays/messages/src/message_race_strategy.rs @@ -111,12 +111,12 @@ impl< // if we have already selected nonces that we want to submit, do nothing if race_state.nonces_to_submit.is_some() { - return None; + return None } // if we already submitted some nonces, do nothing if race_state.nonces_submitted.is_some() { - return None; + return None } // 1) we want to deliver all nonces, starting from `target_nonce + 1` @@ -140,7 +140,7 @@ impl< while let Some((queued_at, queued_range)) = self.source_queue.pop_front() { if let Some(range_to_requeue) = queued_range.greater_than(nonce) { self.source_queue.push_front((queued_at, range_to_requeue)); - break; + break } } } @@ -195,9 +195,8 @@ impl< fn best_at_source(&self) -> Option { let best_in_queue = self.source_queue.back().map(|(_, range)| range.end()); match (best_in_queue, self.best_target_nonce) { - (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => { - Some(best_in_queue) - } + (Some(best_in_queue), Some(best_target_nonce)) if best_in_queue > best_target_nonce => + Some(best_in_queue), (_, Some(best_target_nonce)) => Some(best_target_nonce), (_, None) => None, } @@ -240,7 +239,7 @@ impl< if let Some(best_target_nonce) = self.best_target_nonce { if nonce < best_target_nonce { - return; + return } } @@ -250,7 +249,7 @@ impl< }); if let Some((at_block, subrange)) = maybe_subrange { self.source_queue.push_front((at_block, subrange)); - break; + break } } diff --git a/relays/messages/src/relay_strategy/enforcement_strategy.rs b/relays/messages/src/relay_strategy/enforcement_strategy.rs index 3ee88c639ef..1e9ef5bdbf8 100644 --- a/relays/messages/src/relay_strategy/enforcement_strategy.rs +++ b/relays/messages/src/relay_strategy/enforcement_strategy.rs @@ -107,9 +107,7 @@ impl EnforcementStrategy { let new_selected_weight = match selected_weight.checked_add(details.dispatch_weight) { Some(new_selected_weight) if new_selected_weight <= reference.max_messages_weight_in_single_batch => - { - new_selected_weight - } + new_selected_weight, new_selected_weight if selected_count == 0 => { log::warn!( target: "bridge", @@ -119,7 +117,7 @@ impl EnforcementStrategy { reference.max_messages_weight_in_single_batch, ); new_selected_weight.unwrap_or(Weight::MAX) - } + }, _ => break, }; @@ -127,9 +125,7 @@ impl EnforcementStrategy { let new_selected_size = match relay_reference.selected_size.checked_add(details.size) { Some(new_selected_size) if new_selected_size <= reference.max_messages_size_in_single_batch => - { - new_selected_size - } + new_selected_size, new_selected_size if selected_count == 0 => { log::warn!( target: "bridge", @@ -139,14 +135,14 @@ impl EnforcementStrategy { reference.max_messages_size_in_single_batch, ); new_selected_size.unwrap_or(u32::MAX) - } + }, _ => break, }; // limit number of messages in the batch let new_selected_count = selected_count + 1; if new_selected_count > reference.max_messages_in_this_batch { - break; + break } relay_reference.selected_size = new_selected_size; @@ -164,7 +160,7 @@ impl EnforcementStrategy { DispatchFeePayment::AtSourceChain => { new_selected_prepaid_nonces += 1; relay_reference.selected_unpaid_weight.saturating_add(details.dispatch_weight) - } + }, DispatchFeePayment::AtTargetChain => relay_reference.selected_unpaid_weight, }; relay_reference.selected_prepaid_nonces = new_selected_prepaid_nonces; @@ -201,8 +197,8 @@ impl EnforcementStrategy { } if hard_selected_count != 0 { - if relay_reference.selected_reward != P::SourceChainBalance::zero() - && relay_reference.selected_cost != P::SourceChainBalance::zero() + if relay_reference.selected_reward != P::SourceChainBalance::zero() && + relay_reference.selected_cost != P::SourceChainBalance::zero() { log::trace!( target: "bridge", diff --git a/relays/messages/src/relay_strategy/rational_strategy.rs b/relays/messages/src/relay_strategy/rational_strategy.rs index a44ce661316..fd0a1ffafc8 100644 --- a/relays/messages/src/relay_strategy/rational_strategy.rs +++ b/relays/messages/src/relay_strategy/rational_strategy.rs @@ -54,8 +54,8 @@ impl RelayStrategy for RationalStrategy { let delivery_transaction_cost = match reference .lane_target_client .estimate_delivery_transaction_in_source_tokens( - reference.hard_selected_begin_nonce - ..=(reference.hard_selected_begin_nonce + reference.index as MessageNonce), + reference.hard_selected_begin_nonce..= + (reference.hard_selected_begin_nonce + reference.index as MessageNonce), reference.selected_prepaid_nonces, reference.selected_unpaid_weight, reference.selected_size as u32, @@ -69,8 +69,8 @@ impl RelayStrategy for RationalStrategy { "Failed to estimate delivery transaction cost: {:?}. No nonces selected for delivery", err, ); - return false; - } + return false + }, }; // if it is the first message that makes reward less than cost, let's log it @@ -114,7 +114,7 @@ impl RelayStrategy for RationalStrategy { if reference.total_reward >= reference.total_cost { reference.selected_reward = reference.total_reward; reference.selected_cost = reference.total_cost; - return true; + return true } false diff --git a/relays/utils/src/lib.rs b/relays/utils/src/lib.rs index 01bc08680dc..a335be79124 100644 --- a/relays/utils/src/lib.rs +++ b/relays/utils/src/lib.rs @@ -161,12 +161,12 @@ pub fn format_ids(mut ids: impl ExactSizeIterator { let id0 = ids.next().expect(NTH_PROOF); let id_last = ids.last().expect(NTH_PROOF); format!("{}:[{:?} ... {:?}]", len, id0, id_last) - } + }, } } @@ -243,7 +243,7 @@ where on_success(result); retry_backoff.reset(); ProcessFutureResult::Success - } + }, Err(error) if error.is_connection_error() => { log::error!( target: "bridge", @@ -255,7 +255,7 @@ where retry_backoff.reset(); go_offline_future.set(go_offline(CONNECTION_ERROR_DELAY).fuse()); ProcessFutureResult::ConnectionFailed - } + }, Err(error) => { let retry_delay = retry_backoff.next_backoff().unwrap_or(CONNECTION_ERROR_DELAY); log::error!( @@ -268,6 +268,6 @@ where go_offline_future.set(go_offline(retry_delay).fuse()); ProcessFutureResult::Failed - } + }, } } diff --git a/relays/utils/src/metrics.rs b/relays/utils/src/metrics.rs index a0ff46865ad..805fe70bfe8 100644 --- a/relays/utils/src/metrics.rs +++ b/relays/utils/src/metrics.rs @@ -72,7 +72,7 @@ pub trait StandaloneMetric: Metric { Ok(()) => { self.spawn(); Ok(()) - } + }, Err(PrometheusError::AlreadyReg) => Ok(()), Err(e) => Err(e), } @@ -140,7 +140,7 @@ pub fn set_gauge_value, E: Debug>( value, ); value - } + }, Ok(None) => { log::warn!( target: "bridge-metrics", @@ -148,7 +148,7 @@ pub fn set_gauge_value, E: Debug>( gauge.desc().first().map(|d| &d.fq_name), ); Default::default() - } + }, Err(error) => { log::warn!( target: "bridge-metrics", @@ -157,6 +157,6 @@ pub fn set_gauge_value, E: Debug>( error, ); Default::default() - } + }, }) } diff --git a/relays/utils/src/metrics/float_json_value.rs b/relays/utils/src/metrics/float_json_value.rs index 569acc4297e..7535cbef986 100644 --- a/relays/utils/src/metrics/float_json_value.rs +++ b/relays/utils/src/metrics/float_json_value.rs @@ -112,7 +112,7 @@ fn parse_service_response(json_path: &str, response: &str) -> error::Result .and_then(|v| v.as_f64()) .ok_or_else(|| Error::MissingResponseValue(response.to_owned()))?; if !selected_value.is_normal() || selected_value < 0.0 { - return Err(Error::ParseFloat(selected_value)); + return Err(Error::ParseFloat(selected_value)) } Ok(selected_value) diff --git a/relays/utils/src/metrics/global.rs b/relays/utils/src/metrics/global.rs index 5e94dd9d2b4..df90a2c4823 100644 --- a/relays/utils/src/metrics/global.rs +++ b/relays/utils/src/metrics/global.rs @@ -102,13 +102,13 @@ impl StandaloneMetric for GlobalMetrics { 0f64 }); self.process_memory_usage_bytes.set(memory_usage); - } + }, _ => { log::warn!( target: "bridge-metrics", "Failed to refresh process information. Metrics may show obsolete values", ); - } + }, } } diff --git a/relays/utils/src/relay_loop.rs b/relays/utils/src/relay_loop.rs index 6b42c771f27..a992aaaf57e 100644 --- a/relays/utils/src/relay_loop.rs +++ b/relays/utils/src/relay_loop.rs @@ -129,15 +129,14 @@ impl Loop { match result { Ok(()) => break, - Err(failed_client) => { + Err(failed_client) => reconnect_failed_client( failed_client, self.reconnect_delay, &mut self.source_client, &mut self.target_client, ) - .await - } + .await, } log::debug!(target: "bridge", "Restarting relay loop"); @@ -225,8 +224,8 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue; - } + continue + }, } } if failed_client == FailedClient::Both || failed_client == FailedClient::Target { @@ -239,11 +238,11 @@ pub async fn reconnect_failed_client( reconnect_delay.as_secs(), error, ); - continue; - } + continue + }, } } - break; + break } } From dde4449345438830bdc03baec0f2487aaba6170b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 1 Dec 2021 15:39:01 +0100 Subject: [PATCH 4/4] fmt is weird. --- relays/messages/src/message_race_delivery.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relays/messages/src/message_race_delivery.rs b/relays/messages/src/message_race_delivery.rs index b36d5bda38e..dc994364f17 100644 --- a/relays/messages/src/message_race_delivery.rs +++ b/relays/messages/src/message_race_delivery.rs @@ -443,7 +443,7 @@ where ); return None - } + }, _ => (), }