From 76d0a35f5d993ae031f2962575077b83decb8756 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 17:24:10 +0800 Subject: [PATCH 01/15] feat: derive the edition from the workspace Cargo.toml --- Cargo.toml | 3 +++ crates/pallet-domains/Cargo.toml | 2 +- crates/pallet-rewards/Cargo.toml | 2 +- crates/pallet-runtime-configs/Cargo.toml | 2 +- crates/pallet-subspace-mmr/Cargo.toml | 2 +- crates/pallet-subspace/Cargo.toml | 2 +- crates/pallet-transaction-fees/Cargo.toml | 2 +- crates/sc-consensus-subspace-rpc/Cargo.toml | 2 +- crates/sc-consensus-subspace/Cargo.toml | 2 +- crates/sc-domains/Cargo.toml | 2 +- crates/sc-proof-of-time/Cargo.toml | 2 +- crates/sc-subspace-block-relay/Cargo.toml | 2 +- crates/sc-subspace-chain-specs/Cargo.toml | 2 +- crates/sp-consensus-subspace/Cargo.toml | 2 +- crates/sp-domains-fraud-proof/Cargo.toml | 2 +- crates/sp-domains/Cargo.toml | 2 +- crates/sp-objects/Cargo.toml | 2 +- crates/sp-subspace-mmr/Cargo.toml | 2 +- crates/subspace-archiving/Cargo.toml | 2 +- crates/subspace-core-primitives/Cargo.toml | 2 +- crates/subspace-erasure-coding/Cargo.toml | 2 +- crates/subspace-fake-runtime-api/Cargo.toml | 2 +- crates/subspace-farmer-components/Cargo.toml | 2 +- crates/subspace-farmer/Cargo.toml | 2 +- crates/subspace-gateway-rpc/Cargo.toml | 2 +- crates/subspace-gateway/Cargo.toml | 2 +- crates/subspace-malicious-operator/Cargo.toml | 2 +- crates/subspace-networking/Cargo.toml | 2 +- crates/subspace-node/Cargo.toml | 2 +- crates/subspace-proof-of-space/Cargo.toml | 2 +- crates/subspace-proof-of-time/Cargo.toml | 2 +- crates/subspace-rpc-primitives/Cargo.toml | 2 +- crates/subspace-runtime-primitives/Cargo.toml | 2 +- crates/subspace-runtime/Cargo.toml | 2 +- crates/subspace-service/Cargo.toml | 2 +- crates/subspace-verification/Cargo.toml | 2 +- domains/client/block-builder/Cargo.toml | 2 +- domains/client/block-preprocessor/Cargo.toml | 2 +- domains/client/consensus-relay-chain/Cargo.toml | 2 +- domains/client/cross-domain-message-gossip/Cargo.toml | 2 +- domains/client/domain-operator/Cargo.toml | 2 +- domains/client/eth-service/Cargo.toml | 2 +- domains/client/relayer/Cargo.toml | 2 +- domains/pallets/auto-id/Cargo.toml | 2 +- domains/pallets/block-fees/Cargo.toml | 2 +- domains/pallets/domain-check-weight/Cargo.toml | 2 +- domains/pallets/domain-id/Cargo.toml | 2 +- domains/pallets/domain-sudo/Cargo.toml | 2 +- domains/pallets/evm-tracker/Cargo.toml | 2 +- domains/pallets/executive/Cargo.toml | 2 +- domains/pallets/messenger/Cargo.toml | 2 +- domains/pallets/transporter/Cargo.toml | 2 +- domains/primitives/auto-id/Cargo.toml | 2 +- domains/primitives/block-fees/Cargo.toml | 2 +- domains/primitives/digests/Cargo.toml | 2 +- domains/primitives/domain-sudo/Cargo.toml | 2 +- domains/primitives/evm-tracker/Cargo.toml | 2 +- domains/primitives/executive/Cargo.toml | 2 +- domains/primitives/messenger-host-functions/Cargo.toml | 2 +- domains/primitives/messenger/Cargo.toml | 2 +- domains/primitives/runtime/Cargo.toml | 2 +- domains/runtime/auto-id/Cargo.toml | 2 +- domains/runtime/evm/Cargo.toml | 2 +- domains/service/Cargo.toml | 2 +- domains/test/pallets/storage_overlay_checks/Cargo.toml | 2 +- domains/test/primitives/Cargo.toml | 2 +- domains/test/runtime/auto-id/Cargo.toml | 2 +- domains/test/runtime/evm/Cargo.toml | 2 +- domains/test/service/Cargo.toml | 2 +- shared/sc-subspace-sync-common/Cargo.toml | 2 +- shared/subspace-data-retrieval/Cargo.toml | 2 +- shared/subspace-kzg/Cargo.toml | 2 +- shared/subspace-logging/Cargo.toml | 2 +- shared/subspace-metrics/Cargo.toml | 2 +- shared/subspace-proof-of-space-gpu/Cargo.toml | 2 +- test/subspace-test-client/Cargo.toml | 2 +- test/subspace-test-primitives/Cargo.toml | 2 +- test/subspace-test-runtime/Cargo.toml | 2 +- test/subspace-test-service/Cargo.toml | 2 +- 79 files changed, 81 insertions(+), 78 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6e50efaae45..e0e290fb425 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,6 @@ +[workspace.package] +edition = "2021" + [workspace] resolver = "2" members = [ diff --git a/crates/pallet-domains/Cargo.toml b/crates/pallet-domains/Cargo.toml index f6c621641f1..eeb390d2813 100644 --- a/crates/pallet-domains/Cargo.toml +++ b/crates/pallet-domains/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-domains" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/pallet-rewards/Cargo.toml b/crates/pallet-rewards/Cargo.toml index 9ce2f3ee70d..aefaf524d34 100644 --- a/crates/pallet-rewards/Cargo.toml +++ b/crates/pallet-rewards/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-rewards" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/pallet-runtime-configs/Cargo.toml b/crates/pallet-runtime-configs/Cargo.toml index 689753d84c3..87dad950ba6 100644 --- a/crates/pallet-runtime-configs/Cargo.toml +++ b/crates/pallet-runtime-configs/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-runtime-configs" version = "0.1.0" authors = ["Liu-Cheng Xu "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/pallet-subspace-mmr/Cargo.toml b/crates/pallet-subspace-mmr/Cargo.toml index 8f7345f8f4b..fbd7580dada 100644 --- a/crates/pallet-subspace-mmr/Cargo.toml +++ b/crates/pallet-subspace-mmr/Cargo.toml @@ -6,7 +6,7 @@ description = "Primitives for Subspace MMR" license = "0BSD" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/pallet-subspace/Cargo.toml b/crates/pallet-subspace/Cargo.toml index 4d51fa5cb3b..513641d37bc 100644 --- a/crates/pallet-subspace/Cargo.toml +++ b/crates/pallet-subspace/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-subspace" version = "0.1.0" authors = ["Parity Technologies ", "Subspace Labs "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/pallet-transaction-fees/Cargo.toml b/crates/pallet-transaction-fees/Cargo.toml index 5509b5a6d28..f7b17e6ddb0 100644 --- a/crates/pallet-transaction-fees/Cargo.toml +++ b/crates/pallet-transaction-fees/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-transaction-fees" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sc-consensus-subspace-rpc/Cargo.toml b/crates/sc-consensus-subspace-rpc/Cargo.toml index 1c576de3da3..25ca78bdaed 100644 --- a/crates/sc-consensus-subspace-rpc/Cargo.toml +++ b/crates/sc-consensus-subspace-rpc/Cargo.toml @@ -3,7 +3,7 @@ name = "sc-consensus-subspace-rpc" version = "0.1.0" authors = ["Parity Technologies ", "Subspace Labs "] description = "RPC extensions for the Subspace consensus algorithm" -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sc-consensus-subspace/Cargo.toml b/crates/sc-consensus-subspace/Cargo.toml index 02794b0e612..02bcd67ea95 100644 --- a/crates/sc-consensus-subspace/Cargo.toml +++ b/crates/sc-consensus-subspace/Cargo.toml @@ -3,7 +3,7 @@ name = "sc-consensus-subspace" version = "0.1.0" authors = ["Parity Technologies ", "Subspace Labs "] description = "Subspace consensus algorithm for substrate" -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sc-domains/Cargo.toml b/crates/sc-domains/Cargo.toml index b9d5c21016a..ac116dc694d 100644 --- a/crates/sc-domains/Cargo.toml +++ b/crates/sc-domains/Cargo.toml @@ -3,7 +3,7 @@ name = "sc-domains" version = "0.1.0" authors = ["Subspace Labs "] description = "Subspace service." -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sc-proof-of-time/Cargo.toml b/crates/sc-proof-of-time/Cargo.toml index 77fc5c8dc65..9fe054af200 100644 --- a/crates/sc-proof-of-time/Cargo.toml +++ b/crates/sc-proof-of-time/Cargo.toml @@ -4,7 +4,7 @@ description = "Subspace proof of time implementation" license = "0BSD" version = "0.1.0" authors = ["Rahul Subramaniyam "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/sc-subspace-block-relay/Cargo.toml b/crates/sc-subspace-block-relay/Cargo.toml index dd0bb15cde6..e054b0794ad 100644 --- a/crates/sc-subspace-block-relay/Cargo.toml +++ b/crates/sc-subspace-block-relay/Cargo.toml @@ -4,7 +4,7 @@ description = "Block relay implementation" license = "0BSD" version = "0.1.0" authors = ["Rahul Subramaniyam "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/sc-subspace-chain-specs/Cargo.toml b/crates/sc-subspace-chain-specs/Cargo.toml index d7cffbb13a1..f9dd841a578 100644 --- a/crates/sc-subspace-chain-specs/Cargo.toml +++ b/crates/sc-subspace-chain-specs/Cargo.toml @@ -4,7 +4,7 @@ description = "Chain specification data structures tailored for Subspace" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/sp-consensus-subspace/Cargo.toml b/crates/sp-consensus-subspace/Cargo.toml index bf339b03efb..c3a7c2c953a 100644 --- a/crates/sp-consensus-subspace/Cargo.toml +++ b/crates/sp-consensus-subspace/Cargo.toml @@ -3,7 +3,7 @@ name = "sp-consensus-subspace" version = "0.1.0" authors = ["Parity Technologies ", "Subspace Labs "] description = "Primitives for Subspace consensus" -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sp-domains-fraud-proof/Cargo.toml b/crates/sp-domains-fraud-proof/Cargo.toml index b37b33fc987..962ba36ad17 100644 --- a/crates/sp-domains-fraud-proof/Cargo.toml +++ b/crates/sp-domains-fraud-proof/Cargo.toml @@ -4,7 +4,7 @@ description = "Domains fraud proof primitves for Consensus chain" license = "0BSD" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/sp-domains/Cargo.toml b/crates/sp-domains/Cargo.toml index 2347b49f994..d5d8da24a3c 100644 --- a/crates/sp-domains/Cargo.toml +++ b/crates/sp-domains/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-domains" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sp-objects/Cargo.toml b/crates/sp-objects/Cargo.toml index 1fbc2da80a9..561b5cfc82b 100644 --- a/crates/sp-objects/Cargo.toml +++ b/crates/sp-objects/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-objects" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/sp-subspace-mmr/Cargo.toml b/crates/sp-subspace-mmr/Cargo.toml index 57c1918dd6a..81a7ef95f11 100644 --- a/crates/sp-subspace-mmr/Cargo.toml +++ b/crates/sp-subspace-mmr/Cargo.toml @@ -6,7 +6,7 @@ description = "Primitives for Subspace MMR" license = "0BSD" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-archiving/Cargo.toml b/crates/subspace-archiving/Cargo.toml index 955f497de0f..d311d3606d6 100644 --- a/crates/subspace-archiving/Cargo.toml +++ b/crates/subspace-archiving/Cargo.toml @@ -4,7 +4,7 @@ description = "Collection of modules used for dealing with archived state of Sub license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/benches", "/src", diff --git a/crates/subspace-core-primitives/Cargo.toml b/crates/subspace-core-primitives/Cargo.toml index 918a0ba7948..7e14c3fde16 100644 --- a/crates/subspace-core-primitives/Cargo.toml +++ b/crates/subspace-core-primitives/Cargo.toml @@ -4,7 +4,7 @@ description = "Core primitives for Subspace Network" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-erasure-coding/Cargo.toml b/crates/subspace-erasure-coding/Cargo.toml index 4dd954f7534..625a261abfe 100644 --- a/crates/subspace-erasure-coding/Cargo.toml +++ b/crates/subspace-erasure-coding/Cargo.toml @@ -4,7 +4,7 @@ description = "Polynomial erasure coding implementation used in Subspace Network license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-fake-runtime-api/Cargo.toml b/crates/subspace-fake-runtime-api/Cargo.toml index c28a452b881..26d562737ce 100644 --- a/crates/subspace-fake-runtime-api/Cargo.toml +++ b/crates/subspace-fake-runtime-api/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-fake-runtime-api" version = "0.1.0" authors = ["Subspace Labs "] description = "Fake subspace runtime API." -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-farmer-components/Cargo.toml b/crates/subspace-farmer-components/Cargo.toml index 3d102174429..1d6afbe3cba 100644 --- a/crates/subspace-farmer-components/Cargo.toml +++ b/crates/subspace-farmer-components/Cargo.toml @@ -4,7 +4,7 @@ description = "Farmer for the Subspace Network Blockchain" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-farmer/Cargo.toml b/crates/subspace-farmer/Cargo.toml index 161ad0f35c3..753a9ede4ea 100644 --- a/crates/subspace-farmer/Cargo.toml +++ b/crates/subspace-farmer/Cargo.toml @@ -4,7 +4,7 @@ description = "Farmer for the Subspace Network Blockchain" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-gateway-rpc/Cargo.toml b/crates/subspace-gateway-rpc/Cargo.toml index af7015da0f1..b67c19b5589 100644 --- a/crates/subspace-gateway-rpc/Cargo.toml +++ b/crates/subspace-gateway-rpc/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-gateway-rpc" version = "0.1.0" authors = ["Teor "] description = "A Subspace Network data gateway." -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-gateway/Cargo.toml b/crates/subspace-gateway/Cargo.toml index e5361163477..34e77010da6 100644 --- a/crates/subspace-gateway/Cargo.toml +++ b/crates/subspace-gateway/Cargo.toml @@ -6,7 +6,7 @@ authors = [ "Shamil Gadelshin " ] description = "A Subspace Network data gateway." -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-malicious-operator/Cargo.toml b/crates/subspace-malicious-operator/Cargo.toml index 5860487ea23..9757adc9523 100644 --- a/crates/subspace-malicious-operator/Cargo.toml +++ b/crates/subspace-malicious-operator/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-malicious-operator" version = "0.1.0" authors = ["Subspace Labs "] description = "A Subspace Network Blockchain node." -edition = "2021" +edition.workspace = true license = "0BSD" build = "build.rs" homepage = "https://subspace.network" diff --git a/crates/subspace-networking/Cargo.toml b/crates/subspace-networking/Cargo.toml index 8c0399ec61e..6c59e87228f 100644 --- a/crates/subspace-networking/Cargo.toml +++ b/crates/subspace-networking/Cargo.toml @@ -6,7 +6,7 @@ authors = [ "Shamil Gadelshin " ] description = "Networking functionality of Subspace Network, primarily used for DSN (Distributed Storage Network)" -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-node/Cargo.toml b/crates/subspace-node/Cargo.toml index 0be4485d143..abbf997f9a5 100644 --- a/crates/subspace-node/Cargo.toml +++ b/crates/subspace-node/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-node" version = "0.1.0" authors = ["Subspace Labs "] description = "A Subspace Network Blockchain node." -edition = "2021" +edition.workspace = true license = "0BSD" build = "build.rs" homepage = "https://subspace.network" diff --git a/crates/subspace-proof-of-space/Cargo.toml b/crates/subspace-proof-of-space/Cargo.toml index b55d2d4e282..65dbcb3165a 100644 --- a/crates/subspace-proof-of-space/Cargo.toml +++ b/crates/subspace-proof-of-space/Cargo.toml @@ -4,7 +4,7 @@ description = "Subspace proof of space implementation based on Chia" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/benches", "/src", diff --git a/crates/subspace-proof-of-time/Cargo.toml b/crates/subspace-proof-of-time/Cargo.toml index b8e35db31f2..e24657d1280 100644 --- a/crates/subspace-proof-of-time/Cargo.toml +++ b/crates/subspace-proof-of-time/Cargo.toml @@ -4,7 +4,7 @@ description = "Subspace proof of time implementation" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/crates/subspace-rpc-primitives/Cargo.toml b/crates/subspace-rpc-primitives/Cargo.toml index df6b2dca222..16218083094 100644 --- a/crates/subspace-rpc-primitives/Cargo.toml +++ b/crates/subspace-rpc-primitives/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-rpc-primitives" version = "0.1.0" authors = ["Subspace Labs "] description = "RPC primitives for Subspace Network" -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-runtime-primitives/Cargo.toml b/crates/subspace-runtime-primitives/Cargo.toml index e4783492b4b..a5bc9a9a171 100644 --- a/crates/subspace-runtime-primitives/Cargo.toml +++ b/crates/subspace-runtime-primitives/Cargo.toml @@ -4,7 +4,7 @@ description = "Runtime primitives for Subspace Network" license = "0BSD" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" include = [ diff --git a/crates/subspace-runtime/Cargo.toml b/crates/subspace-runtime/Cargo.toml index 32b79af5b16..10cecd7c0b4 100644 --- a/crates/subspace-runtime/Cargo.toml +++ b/crates/subspace-runtime/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-runtime" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-service/Cargo.toml b/crates/subspace-service/Cargo.toml index 311ce2aaed3..0c7c22596cb 100644 --- a/crates/subspace-service/Cargo.toml +++ b/crates/subspace-service/Cargo.toml @@ -3,7 +3,7 @@ name = "subspace-service" version = "0.1.0" authors = ["Subspace Labs "] description = "Subspace service." -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/crates/subspace-verification/Cargo.toml b/crates/subspace-verification/Cargo.toml index dc598093e0c..48b77407c5c 100644 --- a/crates/subspace-verification/Cargo.toml +++ b/crates/subspace-verification/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-verification" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/client/block-builder/Cargo.toml b/domains/client/block-builder/Cargo.toml index 18af0e7d470..5da0cc70dc9 100644 --- a/domains/client/block-builder/Cargo.toml +++ b/domains/client/block-builder/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-block-builder" version = "0.1.0" authors = ["Parity Technologies "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" homepage = "https://substrate.io" repository = "https://github.com/paritytech/substrate/" diff --git a/domains/client/block-preprocessor/Cargo.toml b/domains/client/block-preprocessor/Cargo.toml index 0984fe17d36..fcc7ce9a187 100644 --- a/domains/client/block-preprocessor/Cargo.toml +++ b/domains/client/block-preprocessor/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-block-preprocessor" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" description = "Domain block preprocessor" diff --git a/domains/client/consensus-relay-chain/Cargo.toml b/domains/client/consensus-relay-chain/Cargo.toml index 3e96f9c2314..79ef9997bce 100644 --- a/domains/client/consensus-relay-chain/Cargo.toml +++ b/domains/client/consensus-relay-chain/Cargo.toml @@ -3,7 +3,7 @@ name = "domain-client-consensus-relay-chain" description = "The relay-chain provided consensus algorithm" version = "0.1.0" authors = ["Parity Technologies "] -edition = "2021" +edition.workspace = true [dependencies] async-trait.workspace = true diff --git a/domains/client/cross-domain-message-gossip/Cargo.toml b/domains/client/cross-domain-message-gossip/Cargo.toml index acf556c1f28..712c68bc9e5 100644 --- a/domains/client/cross-domain-message-gossip/Cargo.toml +++ b/domains/client/cross-domain-message-gossip/Cargo.toml @@ -2,7 +2,7 @@ name = "cross-domain-message-gossip" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" description = "Subspace message relayer." diff --git a/domains/client/domain-operator/Cargo.toml b/domains/client/domain-operator/Cargo.toml index 65934e6e3d5..676b07b7314 100644 --- a/domains/client/domain-operator/Cargo.toml +++ b/domains/client/domain-operator/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-client-operator" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true [dependencies] async-trait.workspace = true diff --git a/domains/client/eth-service/Cargo.toml b/domains/client/eth-service/Cargo.toml index 2b59b2e9d4e..216e07378fa 100644 --- a/domains/client/eth-service/Cargo.toml +++ b/domains/client/eth-service/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-eth-service" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" description = "Ethereum compatible core component service" diff --git a/domains/client/relayer/Cargo.toml b/domains/client/relayer/Cargo.toml index b5d34b4a059..45cdd635983 100644 --- a/domains/client/relayer/Cargo.toml +++ b/domains/client/relayer/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-client-message-relayer" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" description = "Subspace message relayer." diff --git a/domains/pallets/auto-id/Cargo.toml b/domains/pallets/auto-id/Cargo.toml index d85495b89bc..9240e72d0f3 100644 --- a/domains/pallets/auto-id/Cargo.toml +++ b/domains/pallets/auto-id/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-auto-id" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/block-fees/Cargo.toml b/domains/pallets/block-fees/Cargo.toml index 527fa5294c8..ff4f65f484a 100644 --- a/domains/pallets/block-fees/Cargo.toml +++ b/domains/pallets/block-fees/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-block-fees" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/domain-check-weight/Cargo.toml b/domains/pallets/domain-check-weight/Cargo.toml index 94f9db7bdc3..77dd737ee2b 100644 --- a/domains/pallets/domain-check-weight/Cargo.toml +++ b/domains/pallets/domain-check-weight/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-check-weight" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/domain-id/Cargo.toml b/domains/pallets/domain-id/Cargo.toml index 05ae852cf3d..82d960b31df 100644 --- a/domains/pallets/domain-id/Cargo.toml +++ b/domains/pallets/domain-id/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-domain-id" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/domain-sudo/Cargo.toml b/domains/pallets/domain-sudo/Cargo.toml index c40c4860234..ee935af9b24 100644 --- a/domains/pallets/domain-sudo/Cargo.toml +++ b/domains/pallets/domain-sudo/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-domain-sudo" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/evm-tracker/Cargo.toml b/domains/pallets/evm-tracker/Cargo.toml index 4eaf12a005c..6025b7b6dc8 100644 --- a/domains/pallets/evm-tracker/Cargo.toml +++ b/domains/pallets/evm-tracker/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-evm-tracker" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/executive/Cargo.toml b/domains/pallets/executive/Cargo.toml index 62c3ed15145..d683f4d7165 100644 --- a/domains/pallets/executive/Cargo.toml +++ b/domains/pallets/executive/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-pallet-executive" version = "0.1.0" authors = ["Parity Technologies ", "Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace/" diff --git a/domains/pallets/messenger/Cargo.toml b/domains/pallets/messenger/Cargo.toml index 8b7d1e01bb4..2cfc072514c 100644 --- a/domains/pallets/messenger/Cargo.toml +++ b/domains/pallets/messenger/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-messenger" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/pallets/transporter/Cargo.toml b/domains/pallets/transporter/Cargo.toml index e8f247094d5..eac49820fb9 100644 --- a/domains/pallets/transporter/Cargo.toml +++ b/domains/pallets/transporter/Cargo.toml @@ -2,7 +2,7 @@ name = "pallet-transporter" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/auto-id/Cargo.toml b/domains/primitives/auto-id/Cargo.toml index 31ece1faf36..9c6d583fe85 100644 --- a/domains/primitives/auto-id/Cargo.toml +++ b/domains/primitives/auto-id/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-auto-id" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/block-fees/Cargo.toml b/domains/primitives/block-fees/Cargo.toml index 9ffb04fea12..e20b5a90a65 100644 --- a/domains/primitives/block-fees/Cargo.toml +++ b/domains/primitives/block-fees/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-block-fees" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/digests/Cargo.toml b/domains/primitives/digests/Cargo.toml index fb3c99a09d3..7a2d39818d0 100644 --- a/domains/primitives/digests/Cargo.toml +++ b/domains/primitives/digests/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-domain-digests" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/domain-sudo/Cargo.toml b/domains/primitives/domain-sudo/Cargo.toml index 1d384f625fa..edc353106a7 100644 --- a/domains/primitives/domain-sudo/Cargo.toml +++ b/domains/primitives/domain-sudo/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-domain-sudo" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/evm-tracker/Cargo.toml b/domains/primitives/evm-tracker/Cargo.toml index 4d0c8507ac7..00770b6dae1 100644 --- a/domains/primitives/evm-tracker/Cargo.toml +++ b/domains/primitives/evm-tracker/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-evm-tracker" version = "0.1.0" authors = ["Teor "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/executive/Cargo.toml b/domains/primitives/executive/Cargo.toml index b8d067baa50..bdb69e84314 100644 --- a/domains/primitives/executive/Cargo.toml +++ b/domains/primitives/executive/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-executive" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/messenger-host-functions/Cargo.toml b/domains/primitives/messenger-host-functions/Cargo.toml index ccce66351e3..3b8ab2a744e 100644 --- a/domains/primitives/messenger-host-functions/Cargo.toml +++ b/domains/primitives/messenger-host-functions/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-messenger-host-functions" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/messenger/Cargo.toml b/domains/primitives/messenger/Cargo.toml index b76ccb7c949..c2e562aaa17 100644 --- a/domains/primitives/messenger/Cargo.toml +++ b/domains/primitives/messenger/Cargo.toml @@ -2,7 +2,7 @@ name = "sp-messenger" version = "0.1.0" authors = ["Vedhavyas Singareddi "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/primitives/runtime/Cargo.toml b/domains/primitives/runtime/Cargo.toml index 9bb9a34342d..ea120c25bd6 100644 --- a/domains/primitives/runtime/Cargo.toml +++ b/domains/primitives/runtime/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-runtime-primitives" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/runtime/auto-id/Cargo.toml b/domains/runtime/auto-id/Cargo.toml index f66500bb81f..ff5e55d3ab4 100644 --- a/domains/runtime/auto-id/Cargo.toml +++ b/domains/runtime/auto-id/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Vedhavyas Singareddi"] license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace/" -edition = "2021" +edition.workspace = true description = "Subspace AutoId domain runtime" include = [ "/src", diff --git a/domains/runtime/evm/Cargo.toml b/domains/runtime/evm/Cargo.toml index 60f4004d016..f2e5b74ac20 100644 --- a/domains/runtime/evm/Cargo.toml +++ b/domains/runtime/evm/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Vedhavyas Singareddi, Liu-Cheng Xu "] -edition = "2021" +edition.workspace = true license = "0BSD" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/test/primitives/Cargo.toml b/domains/test/primitives/Cargo.toml index 050ad211e1a..161fa20d771 100644 --- a/domains/test/primitives/Cargo.toml +++ b/domains/test/primitives/Cargo.toml @@ -2,7 +2,7 @@ name = "domain-test-primitives" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/domains/test/runtime/auto-id/Cargo.toml b/domains/test/runtime/auto-id/Cargo.toml index 14ff2f261a7..fd322810ac2 100644 --- a/domains/test/runtime/auto-id/Cargo.toml +++ b/domains/test/runtime/auto-id/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Subspace Labs "] license = "Apache-2.0" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace/" -edition = "2021" +edition.workspace = true description = "Subspace AutoId domain test runtime" include = [ "/src", diff --git a/domains/test/runtime/evm/Cargo.toml b/domains/test/runtime/evm/Cargo.toml index ea878c8d59f..d14644c12cc 100644 --- a/domains/test/runtime/evm/Cargo.toml +++ b/domains/test/runtime/evm/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Vedhavyas Singareddi, Liu-Cheng Xu "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/shared/sc-subspace-sync-common/Cargo.toml b/shared/sc-subspace-sync-common/Cargo.toml index 1fa726cf098..b3a55a45e0e 100644 --- a/shared/sc-subspace-sync-common/Cargo.toml +++ b/shared/sc-subspace-sync-common/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "sc-subspace-sync-common" version = "0.1.0" -edition = "2021" +edition.workspace = true authors = [ "Shamil Gadelshin " ] diff --git a/shared/subspace-data-retrieval/Cargo.toml b/shared/subspace-data-retrieval/Cargo.toml index 907ad2dd591..215a2709a2f 100644 --- a/shared/subspace-data-retrieval/Cargo.toml +++ b/shared/subspace-data-retrieval/Cargo.toml @@ -4,7 +4,7 @@ description = "Fetching data from the archived history of the Subspace Distribut license = "0BSD" version = "0.1.0" authors = ["Teor "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/shared/subspace-kzg/Cargo.toml b/shared/subspace-kzg/Cargo.toml index 78b2cd56251..2af42d571ea 100644 --- a/shared/subspace-kzg/Cargo.toml +++ b/shared/subspace-kzg/Cargo.toml @@ -4,7 +4,7 @@ description = "KZG primitives for Subspace Network" license = "0BSD" version = "0.1.0" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/shared/subspace-logging/Cargo.toml b/shared/subspace-logging/Cargo.toml index 66121760f2e..4a235305452 100644 --- a/shared/subspace-logging/Cargo.toml +++ b/shared/subspace-logging/Cargo.toml @@ -4,7 +4,7 @@ description = "Ensure all logging uilities are centralized for the whole project license = "0BSD" version = "0.0.1" authors = ["Nazar Mokrynskyi "] -edition = "2021" +edition.workspace = true include = [ "/src", "/Cargo.toml", diff --git a/shared/subspace-metrics/Cargo.toml b/shared/subspace-metrics/Cargo.toml index 7cda04fce0d..5fab10e6050 100644 --- a/shared/subspace-metrics/Cargo.toml +++ b/shared/subspace-metrics/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "subspace-metrics" version = "0.1.0" -edition = "2021" +edition.workspace = true authors = [ "Shamil Gadelshin " ] diff --git a/shared/subspace-proof-of-space-gpu/Cargo.toml b/shared/subspace-proof-of-space-gpu/Cargo.toml index f7caa6035de..00d03058ddf 100644 --- a/shared/subspace-proof-of-space-gpu/Cargo.toml +++ b/shared/subspace-proof-of-space-gpu/Cargo.toml @@ -4,7 +4,7 @@ description = "Subspace proof of space implementation for GPU (low-level proving license = "0BSD" version = "0.1.0" authors = ["Supranational LLC"] -edition = "2021" +edition.workspace = true include = [ "/build.rs", "/src", diff --git a/test/subspace-test-client/Cargo.toml b/test/subspace-test-client/Cargo.toml index 974fa685de1..0cca88a62a5 100644 --- a/test/subspace-test-client/Cargo.toml +++ b/test/subspace-test-client/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-test-client" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/test/subspace-test-primitives/Cargo.toml b/test/subspace-test-primitives/Cargo.toml index a863070f19c..84e271249f9 100644 --- a/test/subspace-test-primitives/Cargo.toml +++ b/test/subspace-test-primitives/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-test-primitives" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/test/subspace-test-runtime/Cargo.toml b/test/subspace-test-runtime/Cargo.toml index 1a42e014387..aad4af1d407 100644 --- a/test/subspace-test-runtime/Cargo.toml +++ b/test/subspace-test-runtime/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-test-runtime" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" diff --git a/test/subspace-test-service/Cargo.toml b/test/subspace-test-service/Cargo.toml index f2d2f0f1844..e74fdb34b87 100644 --- a/test/subspace-test-service/Cargo.toml +++ b/test/subspace-test-service/Cargo.toml @@ -2,7 +2,7 @@ name = "subspace-test-service" version = "0.1.0" authors = ["Subspace Labs "] -edition = "2021" +edition.workspace = true license = "GPL-3.0-or-later" homepage = "https://subspace.network" repository = "https://github.com/autonomys/subspace" From c7266f8f496683ccf4f91528ce7cf9cb92e3204b Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 17:35:41 +0800 Subject: [PATCH 02/15] chore: update rust toolchain and edition --- Cargo.toml | 2 +- rust-toolchain.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e0e290fb425..a9e5182da73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace.package] -edition = "2021" +edition = "2024" [workspace] resolver = "2" diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 232933959e7..3ff4d6fb60d 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "nightly-2025-04-15" +channel = "nightly-2025-05-31" components = ["rust-src"] targets = ["wasm32-unknown-unknown"] profile = "default" From 01af654d2e3f0ae6a543eff260d3f44ee2e780b8 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 17:46:39 +0800 Subject: [PATCH 03/15] fix: set_var is unsafe now --- domains/runtime/auto-id/build.rs | 3 ++- domains/runtime/evm/build.rs | 3 ++- domains/test/runtime/auto-id/build.rs | 3 ++- domains/test/runtime/evm/build.rs | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/domains/runtime/auto-id/build.rs b/domains/runtime/auto-id/build.rs index 576b9026d63..7e8619df3ac 100644 --- a/domains/runtime/auto-id/build.rs +++ b/domains/runtime/auto-id/build.rs @@ -1,7 +1,8 @@ fn main() { #[cfg(feature = "std")] { - std::env::set_var("WASM_BUILD_TYPE", "release"); + // SAFETY: no concurrent writing or reading here, build scripts are single threaded. + unsafe { std::env::set_var("WASM_BUILD_TYPE", "release") }; substrate_wasm_builder::WasmBuilder::new() .with_current_project() .export_heap_base() diff --git a/domains/runtime/evm/build.rs b/domains/runtime/evm/build.rs index 576b9026d63..7e8619df3ac 100644 --- a/domains/runtime/evm/build.rs +++ b/domains/runtime/evm/build.rs @@ -1,7 +1,8 @@ fn main() { #[cfg(feature = "std")] { - std::env::set_var("WASM_BUILD_TYPE", "release"); + // SAFETY: no concurrent writing or reading here, build scripts are single threaded. + unsafe { std::env::set_var("WASM_BUILD_TYPE", "release") }; substrate_wasm_builder::WasmBuilder::new() .with_current_project() .export_heap_base() diff --git a/domains/test/runtime/auto-id/build.rs b/domains/test/runtime/auto-id/build.rs index 576b9026d63..7e8619df3ac 100644 --- a/domains/test/runtime/auto-id/build.rs +++ b/domains/test/runtime/auto-id/build.rs @@ -1,7 +1,8 @@ fn main() { #[cfg(feature = "std")] { - std::env::set_var("WASM_BUILD_TYPE", "release"); + // SAFETY: no concurrent writing or reading here, build scripts are single threaded. + unsafe { std::env::set_var("WASM_BUILD_TYPE", "release") }; substrate_wasm_builder::WasmBuilder::new() .with_current_project() .export_heap_base() diff --git a/domains/test/runtime/evm/build.rs b/domains/test/runtime/evm/build.rs index 576b9026d63..7e8619df3ac 100644 --- a/domains/test/runtime/evm/build.rs +++ b/domains/test/runtime/evm/build.rs @@ -1,7 +1,8 @@ fn main() { #[cfg(feature = "std")] { - std::env::set_var("WASM_BUILD_TYPE", "release"); + // SAFETY: no concurrent writing or reading here, build scripts are single threaded. + unsafe { std::env::set_var("WASM_BUILD_TYPE", "release") }; substrate_wasm_builder::WasmBuilder::new() .with_current_project() .export_heap_base() From ff6cdeaa2ba2b7ded95735dec9c0c199a66f7579 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 17:51:04 +0800 Subject: [PATCH 04/15] fix: remove the unnecessary binding modifier --- crates/subspace-service/src/mmr/request_handler.rs | 2 +- domains/pallets/messenger/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/subspace-service/src/mmr/request_handler.rs b/crates/subspace-service/src/mmr/request_handler.rs index a8daee0eba0..8c415c80245 100644 --- a/crates/subspace-service/src/mmr/request_handler.rs +++ b/crates/subspace-service/src/mmr/request_handler.rs @@ -225,7 +225,7 @@ where match self.seen_requests.get(&key) { Some(SeenRequestsValue::First) => {} - Some(SeenRequestsValue::Fulfilled(ref mut requests)) => { + Some(SeenRequestsValue::Fulfilled(requests)) => { *requests = requests.saturating_add(1); if *requests > MAX_NUMBER_OF_SAME_REQUESTS_PER_PEER { diff --git a/domains/pallets/messenger/src/lib.rs b/domains/pallets/messenger/src/lib.rs index 2cf7ca25f59..e84ac59a611 100644 --- a/domains/pallets/messenger/src/lib.rs +++ b/domains/pallets/messenger/src/lib.rs @@ -1564,7 +1564,7 @@ impl sp_domains::DomainBundleSubmitted for Pallet { // domain completely because in the invalid extrinsic root fraud proof the prover need // to generate a proof-of-empty-value for the domain. DomainChainAllowlistUpdate::::mutate(domain_id, |maybe_updates| { - if let Some(ref mut updates) = maybe_updates { + if let Some(updates) = maybe_updates { updates.clear(); } }); From 8e253d798c71b54fb7d1ad357132ea5ba7a66a44 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 17:52:45 +0800 Subject: [PATCH 05/15] fix: rename feature duration_constructors => duration_constructors_lite --- crates/sc-consensus-subspace/src/lib.rs | 2 +- crates/subspace-farmer/src/bin/subspace-farmer/main.rs | 2 +- crates/subspace-farmer/src/lib.rs | 2 +- crates/subspace-service/src/lib.rs | 2 +- domains/client/domain-operator/src/lib.rs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/sc-consensus-subspace/src/lib.rs b/crates/sc-consensus-subspace/src/lib.rs index 8b4f18210cd..8c763e8d79e 100644 --- a/crates/sc-consensus-subspace/src/lib.rs +++ b/crates/sc-consensus-subspace/src/lib.rs @@ -6,7 +6,7 @@ //! //! All of the modules here are crucial for consensus, open each module for specific details. -#![feature(let_chains, try_blocks, duration_constructors)] +#![feature(let_chains, try_blocks, duration_constructors_lite)] #![forbid(unsafe_code)] #![warn(missing_docs)] diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/main.rs b/crates/subspace-farmer/src/bin/subspace-farmer/main.rs index 7c9634f9e02..1f4dd60acf7 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/main.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/main.rs @@ -1,4 +1,4 @@ -#![feature(duration_constructors, type_changing_struct_update)] +#![feature(duration_constructors_lite, type_changing_struct_update)] mod commands; mod utils; diff --git a/crates/subspace-farmer/src/lib.rs b/crates/subspace-farmer/src/lib.rs index d4721bf7050..0591c255742 100644 --- a/crates/subspace-farmer/src/lib.rs +++ b/crates/subspace-farmer/src/lib.rs @@ -3,7 +3,7 @@ array_windows, assert_matches, btree_extract_if, - duration_constructors, + duration_constructors_lite, exact_size_is_empty, fmt_helpers_for_derive, future_join, diff --git a/crates/subspace-service/src/lib.rs b/crates/subspace-service/src/lib.rs index 450a47839b4..7154f2ab0d5 100644 --- a/crates/subspace-service/src/lib.rs +++ b/crates/subspace-service/src/lib.rs @@ -1,6 +1,6 @@ //! Service and ServiceFactory implementation. Specialized wrapper over substrate service. #![feature( - duration_constructors, + duration_constructors_lite, impl_trait_in_assoc_type, int_roundings, let_chains, diff --git a/domains/client/domain-operator/src/lib.rs b/domains/client/domain-operator/src/lib.rs index 99ac714ce31..c87d0895da4 100644 --- a/domains/client/domain-operator/src/lib.rs +++ b/domains/client/domain-operator/src/lib.rs @@ -62,7 +62,7 @@ array_windows, assert_matches, box_into_inner, - duration_constructors, + duration_constructors_lite, let_chains, more_qualified_paths )] From cd16809c17b38d618ca5050b25730b165c9ccb52 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 18:09:53 +0800 Subject: [PATCH 06/15] fix: capture more lifetime to adjusted the RPIT lifetime capture rules --- crates/subspace-farmer/src/farm/plotted_pieces.rs | 2 +- crates/subspace-farmer/src/single_disk_farm/farming.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/subspace-farmer/src/farm/plotted_pieces.rs b/crates/subspace-farmer/src/farm/plotted_pieces.rs index a16a8e65277..b9c4ae7cea6 100644 --- a/crates/subspace-farmer/src/farm/plotted_pieces.rs +++ b/crates/subspace-farmer/src/farm/plotted_pieces.rs @@ -61,7 +61,7 @@ where pub fn read_piece( &self, piece_index: PieceIndex, - ) -> Option> + 'static> { + ) -> Option> + use> { let piece_details = match self.pieces.get(&piece_index) { Some(piece_details) => piece_details .choose(&mut thread_rng()) diff --git a/crates/subspace-farmer/src/single_disk_farm/farming.rs b/crates/subspace-farmer/src/single_disk_farm/farming.rs index 9d55b6ac333..0951d7bbeb4 100644 --- a/crates/subspace-farmer/src/single_disk_farm/farming.rs +++ b/crates/subspace-farmer/src/single_disk_farm/farming.rs @@ -134,7 +134,8 @@ where ) -> Result< Vec<( SectorIndex, - impl ProvableSolutions, ProvingError>> + 'a, + impl ProvableSolutions, ProvingError>> + + use<'a, PosTable, Plot>, )>, AuditingError, > From fdb55dedfdeee914499a92e2dab55dfda210c423 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 18:15:51 +0800 Subject: [PATCH 07/15] fix: extern blocks must be unsafe --- shared/subspace-proof-of-space-gpu/src/cuda.rs | 2 +- shared/subspace-proof-of-space-gpu/src/rocm.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/shared/subspace-proof-of-space-gpu/src/cuda.rs b/shared/subspace-proof-of-space-gpu/src/cuda.rs index e8a53d03899..caf0ec9f380 100644 --- a/shared/subspace-proof-of-space-gpu/src/cuda.rs +++ b/shared/subspace-proof-of-space-gpu/src/cuda.rs @@ -10,7 +10,7 @@ use subspace_core_primitives::pos::{PosProof, PosSeed}; use subspace_core_primitives::ScalarBytes; use subspace_kzg::Scalar; -extern "C" { +unsafe extern "C" { /// # Returns /// * `usize` - The number of available GPUs. fn gpu_count() -> usize; diff --git a/shared/subspace-proof-of-space-gpu/src/rocm.rs b/shared/subspace-proof-of-space-gpu/src/rocm.rs index fe9298d4b79..e898c3417bc 100644 --- a/shared/subspace-proof-of-space-gpu/src/rocm.rs +++ b/shared/subspace-proof-of-space-gpu/src/rocm.rs @@ -10,7 +10,7 @@ use subspace_core_primitives::pos::{PosProof, PosSeed}; use subspace_core_primitives::ScalarBytes; use subspace_kzg::Scalar; -extern "C" { +unsafe extern "C" { /// # Returns /// * `usize` - The number of available GPUs. fn gpu_count() -> usize; From 543b3725af56139e26a6e0ba0e669b579c87ee8a Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 18:24:31 +0800 Subject: [PATCH 08/15] chore: run cargo -Zgitoxide -Zgit clippy --locked --all-targets --features runtime-benchmarks,cuda --fix --all -- -D warnings --- crates/pallet-domains/src/lib.rs | 10 +-- crates/pallet-rewards/src/lib.rs | 5 +- crates/pallet-subspace/src/lib.rs | 39 ++++------ crates/sc-consensus-subspace-rpc/src/lib.rs | 21 ++--- crates/sc-consensus-subspace/src/archiver.rs | 6 +- .../sc-consensus-subspace/src/block_import.rs | 5 +- .../sc-consensus-subspace/src/slot_worker.rs | 13 ++-- crates/sc-proof-of-time/src/lib.rs | 5 +- crates/sc-proof-of-time/src/source.rs | 5 +- crates/sc-proof-of-time/src/source/gossip.rs | 5 +- .../sc-proof-of-time/src/source/timekeeper.rs | 5 +- .../src/verification.rs | 8 +- crates/sp-domains/src/valued_trie.rs | 6 +- .../subspace-archiving/src/reconstructor.rs | 5 +- crates/subspace-core-primitives/src/tests.rs | 13 ++-- .../subspace-farmer/commands/cluster/cache.rs | 5 +- .../commands/cluster/farmer.rs | 5 +- .../src/bin/subspace-farmer/commands/farm.rs | 5 +- .../src/cluster/controller/caches.rs | 5 +- .../src/cluster/nats_client.rs | 5 +- .../subspace-farmer/src/farmer_cache/tests.rs | 20 ++--- .../src/farmer_piece_getter.rs | 5 +- .../node_client/caching_proxy_node_client.rs | 5 +- .../subspace-farmer/src/plotter/gpu/cuda.rs | 3 +- .../subspace-farmer/src/single_disk_farm.rs | 39 ++++------ .../src/single_disk_farm/plotting.rs | 5 +- crates/subspace-farmer/src/utils.rs | 8 +- .../src/malicious_bundle_producer.rs | 12 +-- .../src/malicious_bundle_tamper.rs | 5 +- .../subspace-networking/examples/benchmark.rs | 7 +- .../subspace-networking/examples/get-peers.rs | 5 +- .../subspace-networking/examples/metrics.rs | 5 +- .../examples/networking.rs | 5 +- .../examples/random-walker.rs | 7 +- .../subspace-networking/examples/requests.rs | 5 +- .../src/behavior/persistent_parameters.rs | 15 ++-- .../subspace-networking/src/behavior/tests.rs | 5 +- crates/subspace-networking/src/constructor.rs | 2 +- .../src/constructor/transport.rs | 5 +- crates/subspace-networking/src/node/tests.rs | 5 +- crates/subspace-networking/src/node_runner.rs | 10 +-- .../request_response_factory.rs | 8 +- .../src/protocols/reserved_peers.rs | 5 +- .../src/protocols/reserved_peers/tests.rs | 2 +- .../protocols/subspace_connection_limits.rs | 10 +-- crates/subspace-node/src/chain_spec.rs | 2 +- .../src/commands/run/consensus.rs | 7 +- crates/subspace-node/src/commands/shared.rs | 2 +- crates/subspace-proof-of-space/src/chia.rs | 6 +- .../subspace-proof-of-time/src/aes/x86_64.rs | 8 +- crates/subspace-service/src/lib.rs | 15 ++-- crates/subspace-service/src/sync_from_dsn.rs | 13 +--- .../src/sync_from_dsn/snap_sync.rs | 2 +- domains/client/block-preprocessor/src/lib.rs | 3 +- .../src/message_listener.rs | 9 +-- .../client/domain-operator/src/aux_schema.rs | 3 +- .../domain-operator/src/bundle_processor.rs | 2 +- .../domain-operator/src/domain_worker.rs | 10 +-- .../client/domain-operator/src/fraud_proof.rs | 3 +- .../client/domain-operator/src/snap_sync.rs | 2 +- domains/client/domain-operator/src/tests.rs | 77 +++++++------------ domains/pallets/block-fees/src/lib.rs | 4 +- domains/pallets/domain-sudo/src/lib.rs | 5 +- domains/pallets/executive/src/lib.rs | 7 +- domains/pallets/messenger/src/lib.rs | 10 +-- domains/runtime/auto-id/src/lib.rs | 2 +- domains/runtime/evm/src/lib.rs | 2 +- domains/test/runtime/auto-id/src/lib.rs | 2 +- domains/test/runtime/evm/src/lib.rs | 2 +- domains/test/service/src/keyring.rs | 2 +- shared/subspace-logging/src/lib.rs | 5 +- test/subspace-test-service/src/lib.rs | 8 +- 72 files changed, 234 insertions(+), 358 deletions(-) diff --git a/crates/pallet-domains/src/lib.rs b/crates/pallet-domains/src/lib.rs index 2fa69079f82..dafdb377e06 100644 --- a/crates/pallet-domains/src/lib.rs +++ b/crates/pallet-domains/src/lib.rs @@ -2210,11 +2210,10 @@ impl Pallet { // NOTE: during `validate_unsigned` this is implicitly checked within `is_proof_of_time_valid` since we // are using quick verification which will return `false` if the `proof-of-time` is not seem by the node // before. - if pre_dispatch { - if let Some(future_slot) = T::BlockSlot::future_slot(current_block_number) { + if pre_dispatch + && let Some(future_slot) = T::BlockSlot::future_slot(current_block_number) { ensure!(slot_number <= *future_slot, BundleError::SlotInTheFuture) } - } // Check if the bundle is built too long time ago and beyond `T::BundleLongevity` number of consensus blocks. let produced_after_block_number = @@ -2662,11 +2661,10 @@ impl Pallet { domain_id: DomainId, operator_id: &OperatorId, ) -> Result<(BalanceOf, BalanceOf), BundleError> { - if let Some(pending_election_params) = LastEpochStakingDistribution::::get(domain_id) { - if let Some(operator_stake) = pending_election_params.operators.get(operator_id) { + if let Some(pending_election_params) = LastEpochStakingDistribution::::get(domain_id) + && let Some(operator_stake) = pending_election_params.operators.get(operator_id) { return Ok((*operator_stake, pending_election_params.total_domain_stake)); } - } let domain_stake_summary = DomainStakingSummary::::get(domain_id).ok_or(BundleError::InvalidDomainId)?; let operator_stake = domain_stake_summary diff --git a/crates/pallet-rewards/src/lib.rs b/crates/pallet-rewards/src/lib.rs index 64b0ee087b3..e64b7a6beec 100644 --- a/crates/pallet-rewards/src/lib.rs +++ b/crates/pallet-rewards/src/lib.rs @@ -310,8 +310,8 @@ impl Pallet { } } - if let Some(block_author) = maybe_block_author { - if !block_reward.is_zero() { + if let Some(block_author) = maybe_block_author + && !block_reward.is_zero() { let _imbalance = T::Currency::deposit_creating(&block_author, block_reward); T::OnReward::on_reward(block_author.clone(), block_reward); @@ -320,7 +320,6 @@ impl Pallet { reward: block_reward, }); } - } if old_remaining_issuance != new_remaining_issuance { RemainingIssuance::::put(new_remaining_issuance); diff --git a/crates/pallet-subspace/src/lib.rs b/crates/pallet-subspace/src/lib.rs index 0095b3d64f1..0f0913af35c 100644 --- a/crates/pallet-subspace/src/lib.rs +++ b/crates/pallet-subspace/src/lib.rs @@ -788,15 +788,14 @@ impl Pallet { .voting_next .replace(next_voting_solution_range); - if let Some(solution_range_for_rewards) = EnableRewardsBelowSolutionRange::::get() { - if next_solution_range <= solution_range_for_rewards { + if let Some(solution_range_for_rewards) = EnableRewardsBelowSolutionRange::::get() + && next_solution_range <= solution_range_for_rewards { EnableRewardsBelowSolutionRange::::take(); let next_block_number = frame_system::Pallet::::current_block_number() + One::one(); EnableRewards::::put(next_block_number); } - } }); EraStartSlot::::put(current_slot); @@ -948,8 +947,8 @@ impl Pallet { ); // Update target slot for entropy injection once we know it - if let Some(entropy_source_block_number) = maybe_entropy_source_block_number { - if let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number) { + if let Some(entropy_source_block_number) = maybe_entropy_source_block_number + && let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number) { let target_slot = pre_digest .slot() .saturating_add(pot_entropy_injection_delay); @@ -965,7 +964,6 @@ impl Pallet { PotSlotIterations::::put(pot_slot_iterations); } } - } PotEntropy::::put(entropy.clone()); } @@ -1003,14 +1001,13 @@ impl Pallet { } // Clean up old values we'll no longer need - if let Some(entry) = entropy.first_entry() { - if let Some(target_slot) = entry.get().target_slot + if let Some(entry) = entropy.first_entry() + && let Some(target_slot) = entry.get().target_slot && target_slot < current_slot { entry.remove(); PotEntropy::::put(entropy); } - } } } @@ -1598,8 +1595,8 @@ fn check_vote( .as_ref() == Some(&key); - if !is_equivocating { - if let Some((_reward_address, signature)) = ParentBlockVoters::::get().get(&key) { + if !is_equivocating + && let Some((_reward_address, signature)) = ParentBlockVoters::::get().get(&key) { if signature != &signed_vote.signature { is_equivocating = true; } else { @@ -1607,10 +1604,9 @@ fn check_vote( return Err(CheckVoteError::DuplicateVote); } } - } - if !is_equivocating { - if let Some((_reward_address, signature)) = + if !is_equivocating + && let Some((_reward_address, signature)) = CurrentBlockVoters::::get().unwrap_or_default().get(&key) { if signature != &signed_vote.signature { @@ -1620,7 +1616,6 @@ fn check_vote( return Err(CheckVoteError::DuplicateVote); } } - } if pre_dispatch { // During `pre_dispatch` call put farmer into the list of reward receivers. @@ -1648,12 +1643,10 @@ fn check_vote( CurrentBlockAuthorInfo::::mutate(|maybe_info| { if let Some((public_key, _sector_index, _piece_offset, _chunk, _slot, reward_address)) = maybe_info - { - if public_key == &offender { + && public_key == &offender { // Revoke reward for block author reward_address.take(); } - } }); CurrentBlockVoters::::mutate(|current_reward_receivers| { @@ -1740,11 +1733,10 @@ impl subspace_runtime_primitives::FindBlockRewardAddress::get().and_then( |(_public_key, _sector_index, _piece_offset, _chunk, _slot, reward_address)| { // Rewards might be disabled, in which case no block reward - if let Some(height) = EnableRewards::::get() { - if frame_system::Pallet::::current_block_number() >= height { + if let Some(height) = EnableRewards::::get() + && frame_system::Pallet::::current_block_number() >= height { return reward_address; } - } None }, @@ -1755,8 +1747,8 @@ impl subspace_runtime_primitives::FindBlockRewardAddress subspace_runtime_primitives::FindVotingRewardAddresses for Pallet { fn find_voting_reward_addresses() -> Vec { // Rewards might be disabled, in which case no voting reward - if let Some(height) = EnableRewards::::get() { - if frame_system::Pallet::::current_block_number() >= height { + if let Some(height) = EnableRewards::::get() + && frame_system::Pallet::::current_block_number() >= height { // It is possible that this is called during initialization when current block // voters are already moved into parent block voters, handle it accordingly return CurrentBlockVoters::::get() @@ -1765,7 +1757,6 @@ impl subspace_runtime_primitives::FindVotingRewardAddresses bool { - if let Some(strategy) = &self.backoff_authoring_blocks { - if let Ok(chain_head_slot) = extract_pre_digest(chain_head).map(|digest| digest.slot()) + if let Some(strategy) = &self.backoff_authoring_blocks + && let Ok(chain_head_slot) = extract_pre_digest(chain_head).map(|digest| digest.slot()) { return strategy.should_backoff( *chain_head.number(), @@ -699,7 +698,6 @@ where self.logging_target(), ); } - } false } @@ -889,8 +887,7 @@ where } Err(ConsensusError::CannotSign(format!( - "Farmer didn't sign reward. Key: {:?}", - public_key + "Farmer didn't sign reward. Key: {public_key:?}" ))) } } diff --git a/crates/sc-proof-of-time/src/lib.rs b/crates/sc-proof-of-time/src/lib.rs index e3988ab3afa..69ef238e728 100644 --- a/crates/sc-proof-of-time/src/lib.rs +++ b/crates/sc-proof-of-time/src/lib.rs @@ -90,12 +90,11 @@ pub async fn start_slot_worker( } }, }; - if let Some(last_proven_slot) = maybe_last_proven_slot { - if last_proven_slot >= slot { + if let Some(last_proven_slot) = maybe_last_proven_slot + && last_proven_slot >= slot { // Already processed continue; } - } maybe_last_proven_slot.replace(slot); worker.0.on_proof(slot, checkpoints); diff --git a/crates/sc-proof-of-time/src/source.rs b/crates/sc-proof-of-time/src/source.rs index 4b1a652514f..8b07f27ad47 100644 --- a/crates/sc-proof-of-time/src/source.rs +++ b/crates/sc-proof-of-time/src/source.rs @@ -144,15 +144,14 @@ where .spawn(move || { let _guard = span.enter(); - if let Some(core) = timekeeper_cpu_cores.into_iter().next() { - if !core_affinity::set_for_current(CoreId { id: core }) { + if let Some(core) = timekeeper_cpu_cores.into_iter().next() + && !core_affinity::set_for_current(CoreId { id: core }) { warn!( %core, "Failed to set core affinity, timekeeper will run on random CPU \ core", ); } - } if let Err(error) = set_current_thread_priority(ThreadPriority::Max) { warn!( diff --git a/crates/sc-proof-of-time/src/source/gossip.rs b/crates/sc-proof-of-time/src/source/gossip.rs index a636fae30f7..2d227900cb9 100644 --- a/crates/sc-proof-of-time/src/source/gossip.rs +++ b/crates/sc-proof-of-time/src/source/gossip.rs @@ -266,8 +266,8 @@ where ); if let Some(proofs) = self.gossip_cache.get_or_insert(sender, Default::default) { - if proofs.len() == GOSSIP_CACHE_PER_PEER_SIZE { - if let Some(proof) = proofs.pop_front() { + if proofs.len() == GOSSIP_CACHE_PER_PEER_SIZE + && let Some(proof) = proofs.pop_front() { trace!( %sender, slot = %proof.slot, @@ -279,7 +279,6 @@ where .lock() .report(sender, rep::GOSSIP_TOO_MANY_PROOFS); } - } proofs.push_back(proof); return; } diff --git a/crates/sc-proof-of-time/src/source/timekeeper.rs b/crates/sc-proof-of-time/src/source/timekeeper.rs index 88b65dd48e0..280d15141cd 100644 --- a/crates/sc-proof-of-time/src/source/timekeeper.rs +++ b/crates/sc-proof-of-time/src/source/timekeeper.rs @@ -61,11 +61,10 @@ pub(super) fn run_timekeeper( ) .unwrap_or_else(|next_slot_input| next_slot_input); - if let Err(error) = proofs_sender.try_send(proof) { - if let Err(error) = block_on(proofs_sender.send(error.into_inner())) { + if let Err(error) = proofs_sender.try_send(proof) + && let Err(error) = block_on(proofs_sender.send(error.into_inner())) { debug!(%error, "Couldn't send checkpoints, channel is closed"); return Ok(()); } - } } } diff --git a/crates/sp-domains-fraud-proof/src/verification.rs b/crates/sp-domains-fraud-proof/src/verification.rs index 47fb088464f..f4dbce0f09b 100644 --- a/crates/sp-domains-fraud-proof/src/verification.rs +++ b/crates/sp-domains-fraud-proof/src/verification.rs @@ -627,13 +627,11 @@ where // Fast path to check if the fraud proof is targeting a bad receipt that claim a non-exist extrinsic // is invalid - if let Some(invalid_extrinsic_index) = targeted_invalid_bundle_entry.invalid_extrinsic_index() { - if let InvalidBundlesProofData::Bundle(bundle_with_proof) = proof_data { - if bundle_with_proof.bundle.extrinsics.len() as u32 <= invalid_extrinsic_index { + if let Some(invalid_extrinsic_index) = targeted_invalid_bundle_entry.invalid_extrinsic_index() + && let InvalidBundlesProofData::Bundle(bundle_with_proof) = proof_data + && bundle_with_proof.bundle.extrinsics.len() as u32 <= invalid_extrinsic_index { return Ok(()); } - } - } match &invalid_bundle_type { InvalidBundleType::OutOfRangeTx(extrinsic_index) => { diff --git a/crates/sp-domains/src/valued_trie.rs b/crates/sp-domains/src/valued_trie.rs index 7a607c1282f..e2ebb77005c 100644 --- a/crates/sp-domains/src/valued_trie.rs +++ b/crates/sp-domains/src/valued_trie.rs @@ -288,12 +288,12 @@ mod test { .iter() .zip(exts_length) .map(|(ext_hashed, ext_length)| { - let value = if ext_length <= 32 { + + if ext_length <= 32 { Value::Inline(ext_hashed) } else { Value::Node(ext_hashed) - }; - value + } }) .collect(); diff --git a/crates/subspace-archiving/src/reconstructor.rs b/crates/subspace-archiving/src/reconstructor.rs index 5e93c5d23d0..eafe33db8b3 100644 --- a/crates/subspace-archiving/src/reconstructor.rs +++ b/crates/subspace-archiving/src/reconstructor.rs @@ -213,14 +213,13 @@ impl Reconstructor { SegmentItem::ParentSegmentHeader(segment_header) => { let segment_index = segment_header.segment_index(); - if let Some(last_segment_index) = self.last_segment_index { - if last_segment_index != segment_index { + if let Some(last_segment_index) = self.last_segment_index + && last_segment_index != segment_index { return Err(ReconstructorError::IncorrectSegmentOrder { expected_segment_index: last_segment_index + SegmentIndex::ONE, actual_segment_index: segment_index + SegmentIndex::ONE, }); } - } self.last_segment_index .replace(segment_index + SegmentIndex::ONE); diff --git a/crates/subspace-core-primitives/src/tests.rs b/crates/subspace-core-primitives/src/tests.rs index c8a7e4433ef..bdb78c93e12 100644 --- a/crates/subspace-core-primitives/src/tests.rs +++ b/crates/subspace-core-primitives/src/tests.rs @@ -59,8 +59,7 @@ fn source_piece_index_conversion() { let next_source_piece_index = PieceIndex::new(next_source_piece_index); println!( - "{:?} {:?} {:?} {:?} {:?}", - piece_index, piece_position, source_position, segment_index, next_source_piece_index + "{piece_index:?} {piece_position:?} {source_position:?} {segment_index:?} {next_source_piece_index:?}" ); assert_eq!(piece_index.position(), piece_position); @@ -73,7 +72,7 @@ fn source_piece_index_conversion() { assert_eq!(piece_index.segment_index(), segment_index); assert_eq!(piece_index.next_source_index(), next_source_piece_index); - assert!(piece_index.is_source(), "{:?}", piece_index); + assert!(piece_index.is_source(), "{piece_index:?}"); if piece_position == 0 { assert_eq!(segment_index.first_piece_index(), piece_index); @@ -103,12 +102,12 @@ fn parity_piece_index_conversion() { let piece_index = PieceIndex::new(piece_index); let segment_index = SegmentIndex::new(segment_index); - println!("{:?} {:?} {:?}", piece_index, piece_position, segment_index,); + println!("{piece_index:?} {piece_position:?} {segment_index:?}",); assert_eq!(piece_index.position(), piece_position); assert_eq!(piece_index.segment_index(), segment_index); - assert!(!piece_index.is_source(), "{:?}", piece_index); + assert!(!piece_index.is_source(), "{piece_index:?}"); if piece_position as usize == ArchivedHistorySegment::NUM_PIECES - 1 { assert_eq!(segment_index.last_piece_index(), piece_index); @@ -138,7 +137,7 @@ fn parity_piece_index_position_panic() { for &(piece_index, piece_position, segment_index) in PARITY_PIECE_INDEX_TEST_CASES { let piece_index = PieceIndex::new(piece_index); - println!("{:?} {:?} {:?}", piece_index, piece_position, segment_index); + println!("{piece_index:?} {piece_position:?} {segment_index:?}"); // Always panics piece_index.source_position(); @@ -151,7 +150,7 @@ fn parity_piece_index_next_source_panic() { for &(piece_index, piece_position, segment_index) in PARITY_PIECE_INDEX_TEST_CASES { let piece_index = PieceIndex::new(piece_index); - println!("{:?} {:?} {:?}", piece_index, piece_position, segment_index); + println!("{piece_index:?} {piece_position:?} {segment_index:?}"); // Always panics piece_index.next_source_index(); diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs index 41f372d7a8c..cdf58d5106a 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs @@ -144,15 +144,14 @@ pub(super) async fn cache( } for cache in &disk_caches { - if !cache.directory.exists() { - if let Err(error) = fs::create_dir(&cache.directory) { + if !cache.directory.exists() + && let Err(error) = fs::create_dir(&cache.directory) { return Err(anyhow!( "Directory {} doesn't exist and can't be created: {}", cache.directory.display(), error )); } - } } None }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs index 7b9b852f47c..c49f15b4ce7 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs @@ -190,15 +190,14 @@ where } for farm in &disk_farms { - if !farm.directory.exists() { - if let Err(error) = fs::create_dir(&farm.directory) { + if !farm.directory.exists() + && let Err(error) = fs::create_dir(&farm.directory) { return Err(anyhow!( "Directory {} doesn't exist and can't be created: {}", farm.directory.display(), error )); } - } } None }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs index 14acaa5f1e6..bc29a3246d1 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs @@ -375,15 +375,14 @@ where } for farm in &disk_farms { - if !farm.directory.exists() { - if let Err(error) = fs::create_dir(&farm.directory) { + if !farm.directory.exists() + && let Err(error) = fs::create_dir(&farm.directory) { return Err(anyhow!( "Directory {} doesn't exist and can't be created: {}", farm.directory.display(), error )); } - } } None }; diff --git a/crates/subspace-farmer/src/cluster/controller/caches.rs b/crates/subspace-farmer/src/cluster/controller/caches.rs index 5b9d07abeed..b49e54c4959 100644 --- a/crates/subspace-farmer/src/cluster/controller/caches.rs +++ b/crates/subspace-farmer/src/cluster/controller/caches.rs @@ -143,12 +143,11 @@ pub async fn maintain_caches( let sync_finish_sender = Mutex::new(Some(sync_finish_sender)); let _handler_id = farmer_cache.on_sync_progress(Arc::new(move |&progress| { - if progress == 100.0 { - if let Some(sync_finish_sender) = sync_finish_sender.lock().take() { + if progress == 100.0 + && let Some(sync_finish_sender) = sync_finish_sender.lock().take() { // Result doesn't matter let _ = sync_finish_sender.send(()); } - } })); farmer_cache diff --git a/crates/subspace-farmer/src/cluster/nats_client.rs b/crates/subspace-farmer/src/cluster/nats_client.rs index ffee70c0741..1fa73f14f1b 100644 --- a/crates/subspace-farmer/src/cluster/nats_client.rs +++ b/crates/subspace-farmer/src/cluster/nats_client.rs @@ -856,11 +856,10 @@ impl NatsClient { loop { // Try to fill the buffer - if buffer.is_empty() { - if let Some(element) = response_stream.next().await { + if buffer.is_empty() + && let Some(element) = response_stream.next().await { buffer.push_back(element); } - } while buffer.encoded_size() < approximate_max_message_size && let Some(element) = response_stream.next().now_or_never().flatten() { diff --git a/crates/subspace-farmer/src/farmer_cache/tests.rs b/crates/subspace-farmer/src/farmer_cache/tests.rs index bfaba159592..244b292b3a6 100644 --- a/crates/subspace-farmer/src/farmer_cache/tests.rs +++ b/crates/subspace-farmer/src/farmer_cache/tests.rs @@ -213,11 +213,10 @@ async fn basic() { let sender = Mutex::new(Some(sender)); move |progress| { - if *progress == 100.0 { - if let Some(sender) = sender.lock().take() { + if *progress == 100.0 + && let Some(sender) = sender.lock().take() { sender.send(()).unwrap(); } - } } })) .detach(); @@ -429,11 +428,10 @@ async fn basic() { let sender = Mutex::new(Some(sender)); move |progress| { - if *progress == 100.0 { - if let Some(sender) = sender.lock().take() { + if *progress == 100.0 + && let Some(sender) = sender.lock().take() { sender.send(()).unwrap(); } - } } })) .detach(); @@ -525,11 +523,10 @@ async fn duplicate_indices() { let sender = Mutex::new(Some(sender)); move |progress| { - if *progress == 100.0 { - if let Some(sender) = sender.lock().take() { + if *progress == 100.0 + && let Some(sender) = sender.lock().take() { sender.send(()).unwrap(); } - } } })) .detach(); @@ -577,11 +574,10 @@ async fn duplicate_indices() { let sender = Mutex::new(Some(sender)); move |progress| { - if *progress == 100.0 { - if let Some(sender) = sender.lock().take() { + if *progress == 100.0 + && let Some(sender) = sender.lock().take() { sender.send(()).unwrap(); } - } } })) .detach(); diff --git a/crates/subspace-farmer/src/farmer_piece_getter.rs b/crates/subspace-farmer/src/farmer_piece_getter.rs index fe850f02237..ad284dfdc07 100644 --- a/crates/subspace-farmer/src/farmer_piece_getter.rs +++ b/crates/subspace-farmer/src/farmer_piece_getter.rs @@ -164,8 +164,8 @@ where .try_read() .and_then(|plotted_pieces| plotted_pieces.read_piece(piece_index)); - if let Some(read_piece_fut) = maybe_read_piece_fut { - if let Some(piece) = read_piece_fut.await { + if let Some(read_piece_fut) = maybe_read_piece_fut + && let Some(piece) = read_piece_fut.await { trace!(%piece_index, "Got piece from local plot successfully"); inner .farmer_caches @@ -173,7 +173,6 @@ where .await; return Some(piece); } - } // L1 piece acquisition trace!(%piece_index, "Getting piece from DSN L1."); diff --git a/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs b/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs index 6bb6a99862d..8d89b106fc3 100644 --- a/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs +++ b/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs @@ -62,11 +62,10 @@ impl SegmentHeaders { where NC: NodeClient, { - if let Some(last_synced) = &self.last_synced { - if last_synced.elapsed() < SEGMENT_HEADERS_SYNC_INTERVAL { + if let Some(last_synced) = &self.last_synced + && last_synced.elapsed() < SEGMENT_HEADERS_SYNC_INTERVAL { return Ok(()); } - } self.last_synced.replace(Instant::now()); let mut segment_index_offset = SegmentIndex::from(self.segment_headers.len() as u64); diff --git a/crates/subspace-farmer/src/plotter/gpu/cuda.rs b/crates/subspace-farmer/src/plotter/gpu/cuda.rs index 84af098f9d4..57633166313 100644 --- a/crates/subspace-farmer/src/plotter/gpu/cuda.rs +++ b/crates/subspace-farmer/src/plotter/gpu/cuda.rs @@ -101,8 +101,7 @@ impl CudaRecordsEncoder { } else { // We want to guarantee exit, rather than panicking in a panic handler. eprintln!( - "rayon panic handler called on non-rayon thread: {:?}", - panic_info + "rayon panic handler called on non-rayon thread: {panic_info:?}" ); } exit(1); diff --git a/crates/subspace-farmer/src/single_disk_farm.rs b/crates/subspace-farmer/src/single_disk_farm.rs index 7e939b21f35..53d40ffb086 100644 --- a/crates/subspace-farmer/src/single_disk_farm.rs +++ b/crates/subspace-farmer/src/single_disk_farm.rs @@ -1011,12 +1011,11 @@ impl SingleDiskFarm { return Ok(()); } - if let Some(plotting_delay) = plotting_delay { - if plotting_delay.await.is_err() { + if let Some(plotting_delay) = plotting_delay + && plotting_delay.await.is_err() { // Dropped before resolving return Ok(()); } - } plotting(plotting_options).await }; @@ -1587,7 +1586,7 @@ impl SingleDiskFarm { let metadata_header = PlotMetadataHeader::decode(&mut metadata_header_bytes.as_ref()) .map_err(|error| { - io::Error::other(format!("Failed to decode metadata header: {}", error)) + io::Error::other(format!("Failed to decode metadata header: {error}")) })?; if metadata_header.version != SingleDiskFarm::SUPPORTED_PLOT_VERSION { @@ -1610,7 +1609,7 @@ impl SingleDiskFarm { sectors_metadata.push( SectorMetadataChecksummed::decode(&mut sector_metadata_bytes.as_ref()).map_err( |error| { - io::Error::other(format!("Failed to decode sector metadata: {}", error)) + io::Error::other(format!("Failed to decode sector metadata: {error}")) }, )?, ); @@ -1890,8 +1889,8 @@ impl SingleDiskFarm { as SectorIndex; let metadata_header_bytes = metadata_header.encode(); - if !dry_run { - if let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { + if !dry_run + && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { return Err(SingleDiskFarmScrubError::FailedToWriteBytes { file: metadata_file_path, size: metadata_header_bytes.len() as u64, @@ -1899,7 +1898,6 @@ impl SingleDiskFarm { error, }); } - } } (metadata_file, metadata_header) @@ -1959,8 +1957,8 @@ impl SingleDiskFarm { metadata_header.plotted_sector_count = (plot_size / sector_size) as SectorIndex; let metadata_header_bytes = metadata_header.encode(); - if !dry_run { - if let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { + if !dry_run + && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { return Err(SingleDiskFarmScrubError::FailedToWriteBytes { file: plot_file_path, size: metadata_header_bytes.len() as u64, @@ -1968,7 +1966,6 @@ impl SingleDiskFarm { error, }); } - } } plot_file @@ -2159,8 +2156,8 @@ impl SingleDiskFarm { - offset_in_sector; let bytes = &mut scratch_buffer[..bytes_to_write]; - if !dry_run { - if let Err(error) = plot_file.write_all_at(bytes, offset) { + if !dry_run + && let Err(error) = plot_file.write_all_at(bytes, offset) { return Err( SingleDiskFarmScrubError::FailedToWriteBytes { file: plot_file_path.clone(), @@ -2170,7 +2167,6 @@ impl SingleDiskFarm { }, ); } - } hasher.update(bytes); } @@ -2179,8 +2175,8 @@ impl SingleDiskFarm { let checksum = *hasher.finalize().as_bytes(); let offset = u64::from(sector_index) * sector_size + sector_bytes_range.end as u64; - if !dry_run { - if let Err(error) = + if !dry_run + && let Err(error) = plot_file.write_all_at(&checksum, offset) { return Err( @@ -2192,7 +2188,6 @@ impl SingleDiskFarm { }, ); } - } } return Ok(()); @@ -2283,8 +2278,8 @@ impl SingleDiskFarm { "Failed to read cached piece, replacing with dummy element" ); - if !dry_run { - if let Err(error) = cache_file.write_all_at(&dummy_element, offset) { + if !dry_run + && let Err(error) = cache_file.write_all_at(&dummy_element, offset) { return Err(SingleDiskFarmScrubError::FailedToWriteBytes { file: file.clone(), size: u64::from(element_size), @@ -2292,7 +2287,6 @@ impl SingleDiskFarm { error, }); } - } return Ok(()); } @@ -2308,8 +2302,8 @@ impl SingleDiskFarm { "Cached piece checksum mismatch, replacing with dummy element" ); - if !dry_run { - if let Err(error) = cache_file.write_all_at(&dummy_element, offset) { + if !dry_run + && let Err(error) = cache_file.write_all_at(&dummy_element, offset) { return Err(SingleDiskFarmScrubError::FailedToWriteBytes { file: file.clone(), size: u64::from(element_size), @@ -2317,7 +2311,6 @@ impl SingleDiskFarm { error, }); } - } return Ok(()); } diff --git a/crates/subspace-farmer/src/single_disk_farm/plotting.rs b/crates/subspace-farmer/src/single_disk_farm/plotting.rs index a6b411d3ca6..9641d1b68a9 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plotting.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plotting.rs @@ -361,8 +361,8 @@ where } }; - if let Some(old_sector_metadata) = &maybe_old_sector_metadata { - if farmer_app_info.protocol_info.history_size <= old_sector_metadata.history_size { + if let Some(old_sector_metadata) = &maybe_old_sector_metadata + && farmer_app_info.protocol_info.history_size <= old_sector_metadata.history_size { if farmer_app_info.protocol_info.min_sector_lifetime == HistorySize::ONE { debug!( current_history_size = %farmer_app_info.protocol_info.history_size, @@ -382,7 +382,6 @@ where return PlotSingleSectorResult::Skipped; } } - } break farmer_app_info; }; diff --git a/crates/subspace-farmer/src/utils.rs b/crates/subspace-farmer/src/utils.rs index 540b87ec921..51dd498ab93 100644 --- a/crates/subspace-farmer/src/utils.rs +++ b/crates/subspace-farmer/src/utils.rs @@ -502,8 +502,7 @@ fn create_plotting_thread_pool_manager_thread_pool_pair( } else { // We want to guarantee exit, rather than panicking in a panic handler. eprintln!( - "rayon panic handler called on non-rayon thread: {:?}", - panic_info + "rayon panic handler called on non-rayon thread: {panic_info:?}" ); } exit(1); @@ -522,11 +521,10 @@ fn create_plotting_thread_pool_manager_thread_pool_pair( move || { cpu_core_set.pin_current_thread(); - if let Some(thread_priority) = thread_priority { - if let Err(error) = set_current_thread_priority(thread_priority) { + if let Some(thread_priority) = thread_priority + && let Err(error) = set_current_thread_priority(thread_priority) { warn!(%error, "Failed to set thread priority"); } - } drop(cpu_core_set); let _guard = handle.enter(); diff --git a/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs b/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs index 58054329411..e6c41ca6d87 100644 --- a/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs +++ b/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs @@ -212,11 +212,10 @@ where } // Periodically check the malicious operator status - if u64::from(slot) % 10 == 0 { - if let Err(err) = self.update_malicious_operator_status() { + if u64::from(slot) % 10 == 0 + && let Err(err) = self.update_malicious_operator_status() { tracing::error!(?err, "Failed to update malicious operator status"); } - } } } @@ -273,12 +272,10 @@ where .consensus_client .runtime_api() .operator(consensus_best_hash, *operator_id)? - { - if operator_signing_key == signing_key { + && operator_signing_key == signing_key { maybe_operator_id = Some(*operator_id); break; } - } } // If the `signing_key` is linked to a operator, the previous registration request succeeded, @@ -462,8 +459,7 @@ pub fn construct_signed_extrinsic( .sr25519_sign(OperatorPublicKey::ID, &public_key, e) })? .ok_or(format!( - "Failed to sign extrinsic, sudo key pair missing from keystore?, public_key {:?}", - public_key + "Failed to sign extrinsic, sudo key pair missing from keystore?, public_key {public_key:?}" ))? } }; diff --git a/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs b/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs index e6a50a633cf..adee97d87f6 100644 --- a/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs +++ b/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs @@ -101,12 +101,11 @@ where return Ok(()); } // If a bad receipt is already made for the same domain block, reuse it - if let Some(bad_receipts_at) = self.bad_receipts_cache.get(&receipt.domain_block_number) { - if let Some(previous_bad_receipt) = bad_receipts_at.get(&receipt.consensus_block_hash) { + if let Some(bad_receipts_at) = self.bad_receipts_cache.get(&receipt.domain_block_number) + && let Some(previous_bad_receipt) = bad_receipts_at.get(&receipt.consensus_block_hash) { *receipt = previous_bad_receipt.clone(); return Ok(()); } - } let random_seed = Random::seed(); let bad_receipt_type = match random_seed % 7 { diff --git a/crates/subspace-networking/examples/benchmark.rs b/crates/subspace-networking/examples/benchmark.rs index f356f503ce7..c1ed9dc25c8 100644 --- a/crates/subspace-networking/examples/benchmark.rs +++ b/crates/subspace-networking/examples/benchmark.rs @@ -363,11 +363,10 @@ pub async fn configure_dsn( let node_address_sender = Mutex::new(Some(node_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_address_sender) = node_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_address_sender) = node_address_sender.lock().take() { node_address_sender.send(address.clone()).unwrap(); } - } } })); @@ -389,7 +388,7 @@ pub async fn configure_dsn( drop(on_new_listener_handler); println!("Node ID is {}", node.id()); - println!("Node address {}", node_addr); + println!("Node address {node_addr}"); node } diff --git a/crates/subspace-networking/examples/get-peers.rs b/crates/subspace-networking/examples/get-peers.rs index 521bc00029a..cb4db5d42a0 100644 --- a/crates/subspace-networking/examples/get-peers.rs +++ b/crates/subspace-networking/examples/get-peers.rs @@ -25,11 +25,10 @@ async fn main() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/examples/metrics.rs b/crates/subspace-networking/examples/metrics.rs index a41e9607cad..fd809588e70 100644 --- a/crates/subspace-networking/examples/metrics.rs +++ b/crates/subspace-networking/examples/metrics.rs @@ -56,11 +56,10 @@ async fn main() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/examples/networking.rs b/crates/subspace-networking/examples/networking.rs index 8d36096744b..dd1b5aa3d56 100644 --- a/crates/subspace-networking/examples/networking.rs +++ b/crates/subspace-networking/examples/networking.rs @@ -30,11 +30,10 @@ async fn main() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/examples/random-walker.rs b/crates/subspace-networking/examples/random-walker.rs index 75e01151200..dee2df856e7 100644 --- a/crates/subspace-networking/examples/random-walker.rs +++ b/crates/subspace-networking/examples/random-walker.rs @@ -384,11 +384,10 @@ async fn configure_dsn( let node_address_sender = Mutex::new(Some(node_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_address_sender) = node_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_address_sender) = node_address_sender.lock().take() { node_address_sender.send(address.clone()).unwrap(); } - } } })); @@ -410,7 +409,7 @@ async fn configure_dsn( drop(on_new_listener_handler); println!("Node ID is {}", node.id()); - println!("Node address {}", node_addr); + println!("Node address {node_addr}"); node } diff --git a/crates/subspace-networking/examples/requests.rs b/crates/subspace-networking/examples/requests.rs index 4bf99eb62af..b452ee26257 100644 --- a/crates/subspace-networking/examples/requests.rs +++ b/crates/subspace-networking/examples/requests.rs @@ -49,11 +49,10 @@ async fn main() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/src/behavior/persistent_parameters.rs b/crates/subspace-networking/src/behavior/persistent_parameters.rs index f6454ee4773..f2d848328c2 100644 --- a/crates/subspace-networking/src/behavior/persistent_parameters.rs +++ b/crates/subspace-networking/src/behavior/persistent_parameters.rs @@ -312,8 +312,8 @@ pub struct KnownPeersManager { impl Drop for KnownPeersManager { fn drop(&mut self) { - if self.cache_need_saving { - if let Some(known_peers_slots) = &self.known_peers_slots { + if self.cache_need_saving + && let Some(known_peers_slots) = &self.known_peers_slots { known_peers_slots .lock() .write_to_inactive_slot(&EncodableKnownPeers::from_cache( @@ -321,7 +321,6 @@ impl Drop for KnownPeersManager { self.config.cache_size, )); } - } } } @@ -637,8 +636,8 @@ impl KnownPeersRegistry for KnownPeersManager { loop { (&mut self.networking_parameters_save_delay).await; - if let Some(known_peers_slots) = &self.known_peers_slots { - if self.cache_need_saving { + if let Some(known_peers_slots) = &self.known_peers_slots + && self.cache_need_saving { let known_peers = EncodableKnownPeers::from_cache(&self.known_peers, self.config.cache_size); let known_peers_slots = Arc::clone(known_peers_slots); @@ -655,7 +654,6 @@ impl KnownPeersRegistry for KnownPeersManager { self.cache_need_saving = false; } - } self.networking_parameters_save_delay = KnownPeersManager::default_delay(); } } @@ -689,11 +687,10 @@ pub(crate) fn remove_p2p_suffix(mut address: Multiaddr) -> Multiaddr { pub(crate) fn append_p2p_suffix(peer_id: PeerId, mut address: Multiaddr) -> Multiaddr { let last_protocol = address.pop(); - if let Some(protocol) = last_protocol { - if !matches!(protocol, Protocol::P2p(..)) { + if let Some(protocol) = last_protocol + && !matches!(protocol, Protocol::P2p(..)) { address.push(protocol) } - } address.push(Protocol::P2p(peer_id)); address diff --git a/crates/subspace-networking/src/behavior/tests.rs b/crates/subspace-networking/src/behavior/tests.rs index 0217f878213..050723c546e 100644 --- a/crates/subspace-networking/src/behavior/tests.rs +++ b/crates/subspace-networking/src/behavior/tests.rs @@ -200,11 +200,10 @@ async fn test_async_handler_works_with_pending_internal_future() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/src/constructor.rs b/crates/subspace-networking/src/constructor.rs index 32eb742ffe1..5eaded474f7 100644 --- a/crates/subspace-networking/src/constructor.rs +++ b/crates/subspace-networking/src/constructor.rs @@ -296,7 +296,7 @@ impl Config { .expect("Default config for gossipsub is always correct; qed") }); - let protocol_version = format!("/subspace/2/{}", protocol_version); + let protocol_version = format!("/subspace/2/{protocol_version}"); let identify = IdentifyConfig::new(protocol_version.clone(), keypair.public()); let temporary_ban_backoff = ExponentialBackoff { diff --git a/crates/subspace-networking/src/constructor/transport.rs b/crates/subspace-networking/src/constructor/transport.rs index 245b4217e5f..5aa288e6068 100644 --- a/crates/subspace-networking/src/constructor/transport.rs +++ b/crates/subspace-networking/src/constructor/transport.rs @@ -120,12 +120,11 @@ where { let temporary_bans = self.temporary_bans.lock(); for protocol in addr_iter { - if let Protocol::P2p(peer_id) = protocol { - if temporary_bans.is_banned(&peer_id) { + if let Protocol::P2p(peer_id) = protocol + && temporary_bans.is_banned(&peer_id) { let error = io::Error::other("Peer is temporarily banned"); return Err(TransportError::Other(error.into())); } - } } } diff --git a/crates/subspace-networking/src/node/tests.rs b/crates/subspace-networking/src/node/tests.rs index ac124b05c77..2be2d1220eb 100644 --- a/crates/subspace-networking/src/node/tests.rs +++ b/crates/subspace-networking/src/node/tests.rs @@ -40,11 +40,10 @@ async fn request_with_addresses() { let node_1_address_sender = Mutex::new(Some(node_1_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_1_address_sender) = node_1_address_sender.lock().take() { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { node_1_address_sender.send(address.clone()).unwrap(); } - } } })); diff --git a/crates/subspace-networking/src/node_runner.rs b/crates/subspace-networking/src/node_runner.rs index b7c4a39e85c..7344abe5c5a 100644 --- a/crates/subspace-networking/src/node_runner.rs +++ b/crates/subspace-networking/src/node_runner.rs @@ -1172,8 +1172,8 @@ impl NodeRunner { } async fn handle_gossipsub_event(&mut self, event: GossipsubEvent) { - if let GossipsubEvent::Message { message, .. } = event { - if let Some(senders) = self.topic_subscription_senders.get(&message.topic) { + if let GossipsubEvent::Message { message, .. } = event + && let Some(senders) = self.topic_subscription_senders.get(&message.topic) { let bytes = Bytes::from(message.data); for sender in senders.values() { @@ -1181,7 +1181,6 @@ impl NodeRunner { let _ = sender.unbounded_send(bytes.clone()); } } - } } async fn handle_request_response_event(&mut self, event: RequestResponseEvent) { @@ -1384,14 +1383,13 @@ impl NodeRunner { if entry.get().is_empty() { entry.remove_entry(); - if let Some(gossipsub) = self.swarm.behaviour_mut().gossipsub.as_mut() { - if !gossipsub.unsubscribe(&topic) { + if let Some(gossipsub) = self.swarm.behaviour_mut().gossipsub.as_mut() + && !gossipsub.unsubscribe(&topic) { warn!( "Can't unsubscribe from topic {topic} because subscription doesn't exist, \ this is a logic error in the subspace or swarm libraries" ); } - } } } else { error!( diff --git a/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs b/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs index 7cbfbf69623..2faacb7383d 100644 --- a/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs +++ b/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs @@ -666,9 +666,9 @@ impl NetworkBehaviour for RequestResponseFactoryBehaviour { None => continue, }; - if let Ok(payload) = result { - if let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) { - if protocol.send_response(inner_channel, Ok(payload)).is_err() { + if let Ok(payload) = result + && let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) + && protocol.send_response(inner_channel, Ok(payload)).is_err() { // Note: Failure is handled further below when receiving // `InboundFailure` event from `RequestResponse` behaviour. debug!( @@ -679,8 +679,6 @@ impl NetworkBehaviour for RequestResponseFactoryBehaviour { protocol_name, ); } - } - } } for rq_rs_runner in &mut self.request_handlers { diff --git a/crates/subspace-networking/src/protocols/reserved_peers.rs b/crates/subspace-networking/src/protocols/reserved_peers.rs index ebfbe7a5149..593d8d708f0 100644 --- a/crates/subspace-networking/src/protocols/reserved_peers.rs +++ b/crates/subspace-networking/src/protocols/reserved_peers.rs @@ -183,14 +183,13 @@ impl NetworkBehaviour for Behaviour { remaining_established, .. }) => { - if let Some(state) = self.reserved_peers_state.get_mut(&peer_id) { - if remaining_established == 0 { + if let Some(state) = self.reserved_peers_state.get_mut(&peer_id) + && remaining_established == 0 { state.connection_status = ConnectionStatus::NotConnected; debug!(%state.peer_id, "Reserved peer disconnected."); self.wake(); } - } } FromSwarm::DialFailure(DialFailure { peer_id: Some(peer_id), diff --git a/crates/subspace-networking/src/protocols/reserved_peers/tests.rs b/crates/subspace-networking/src/protocols/reserved_peers/tests.rs index 2de90e8cf82..769c3e555ca 100644 --- a/crates/subspace-networking/src/protocols/reserved_peers/tests.rs +++ b/crates/subspace-networking/src/protocols/reserved_peers/tests.rs @@ -160,7 +160,7 @@ async fn test_reserved_peers_dial_event() { let identity2 = Keypair::generate_ed25519(); let peer2_id = identity2.public().to_peer_id(); - let peer2_address = format!("/memory/0/p2p/{}", peer2_id); + let peer2_address = format!("/memory/0/p2p/{peer2_id}"); let mut peer1 = new_ephemeral( identity1, diff --git a/crates/subspace-networking/src/protocols/subspace_connection_limits.rs b/crates/subspace-networking/src/protocols/subspace_connection_limits.rs index 214d02e3ade..cd0c5d74e44 100644 --- a/crates/subspace-networking/src/protocols/subspace_connection_limits.rs +++ b/crates/subspace-networking/src/protocols/subspace_connection_limits.rs @@ -88,15 +88,14 @@ impl NetworkBehaviour for Behaviour { Protocol::Ip4(ip) => Some(IpAddr::V4(ip)), Protocol::Ip6(ip) => Some(IpAddr::V6(ip)), _ => None, - }) { - if self + }) + && self .incoming_allow_list .values() .any(|(ip_addresses, _attempts)| ip_addresses.contains(&ip_address)) { return Ok(()); } - } self.inner .handle_pending_inbound_connection(connection_id, local_addr, remote_addr) @@ -134,11 +133,10 @@ impl NetworkBehaviour for Behaviour { addresses: &[Multiaddr], effective_role: Endpoint, ) -> Result, ConnectionDenied> { - if let Some(peer) = &maybe_peer { - if self.incoming_allow_list.contains_key(peer) { + if let Some(peer) = &maybe_peer + && self.incoming_allow_list.contains_key(peer) { return Ok(Vec::new()); } - } self.inner.handle_pending_outbound_connection( connection_id, diff --git a/crates/subspace-node/src/chain_spec.rs b/crates/subspace-node/src/chain_spec.rs index ca4df1fef2f..e1a561b0c2d 100644 --- a/crates/subspace-node/src/chain_spec.rs +++ b/crates/subspace-node/src/chain_spec.rs @@ -96,7 +96,7 @@ pub fn mainnet_compiled() -> Result { .iter() .map(|address| { AccountId::from_ss58check(address) - .map_err(|_| format!("Invalid council SS58 address: {}", address)) + .map_err(|_| format!("Invalid council SS58 address: {address}")) }) .collect::, String>>()?; diff --git a/crates/subspace-node/src/commands/run/consensus.rs b/crates/subspace-node/src/commands/run/consensus.rs index 313e5611164..afbe0bb897b 100644 --- a/crates/subspace-node/src/commands/run/consensus.rs +++ b/crates/subspace-node/src/commands/run/consensus.rs @@ -356,7 +356,7 @@ impl FromStr for CreateObjectMappingConfig { impl fmt::Display for CreateObjectMappingConfig { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::Block(block) => write!(f, "{}", block), + Self::Block(block) => write!(f, "{block}"), Self::Yes => f.write_str("yes"), Self::No => f.write_str("no"), } @@ -621,8 +621,8 @@ pub(super) fn create_consensus_chain_configuration( let node_name = name.unwrap_or_else(generate_node_name); - if let StatePruningMode::Number(number) = pruning_params.state_pruning { - if number < MIN_STATE_PRUNING { + if let StatePruningMode::Number(number) = pruning_params.state_pruning + && number < MIN_STATE_PRUNING { // Do not return error because some users may in fact use lower values and we don't want // to break their setups, at least for now error!( @@ -630,7 +630,6 @@ pub(super) fn create_consensus_chain_configuration( node can break any time!" ); } - } let consensus_chain_config = SubstrateConfiguration { impl_name: env!("CARGO_PKG_NAME").to_string(), diff --git a/crates/subspace-node/src/commands/shared.rs b/crates/subspace-node/src/commands/shared.rs index 2b0fed6af10..ba6fcc18854 100644 --- a/crates/subspace-node/src/commands/shared.rs +++ b/crates/subspace-node/src/commands/shared.rs @@ -37,7 +37,7 @@ pub(super) fn derive_keypair( .map(|password| password.expose_secret().as_str()), ); - keypair_result.map_err(|err| Error::Input(format!("Invalid password {:?}", err))) + keypair_result.map_err(|err| Error::Input(format!("Invalid password {err:?}"))) } #[expect(clippy::result_large_err, reason = "Comes from Substrate")] diff --git a/crates/subspace-proof-of-space/src/chia.rs b/crates/subspace-proof-of-space/src/chia.rs index daee0ad5254..932a6cfc314 100644 --- a/crates/subspace-proof-of-space/src/chia.rs +++ b/crates/subspace-proof-of-space/src/chia.rs @@ -58,12 +58,12 @@ impl Table for ChiaTable { let mut challenge = [0; 32]; challenge[..mem::size_of::()].copy_from_slice(&challenge_index.to_le_bytes()); - let proof = self + + self .tables .find_proof(&challenge) .next() - .map(PosProof::from); - proof + .map(PosProof::from) } fn is_proof_valid(seed: &PosSeed, challenge_index: u32, proof: &PosProof) -> bool { diff --git a/crates/subspace-proof-of-time/src/aes/x86_64.rs b/crates/subspace-proof-of-time/src/aes/x86_64.rs index f1873ee8999..8c4bf4de47a 100644 --- a/crates/subspace-proof-of-time/src/aes/x86_64.rs +++ b/crates/subspace-proof-of-time/src/aes/x86_64.rs @@ -9,7 +9,7 @@ pub(super) unsafe fn create( seed: &[u8; 16], key: &[u8; 16], checkpoint_iterations: u32, -) -> PotCheckpoints { +) -> PotCheckpoints { unsafe { let mut checkpoints = PotCheckpoints::default(); let keys_reg = expand_key(key); @@ -38,7 +38,7 @@ pub(super) unsafe fn create( } checkpoints -} +}} // Below code copied with minor changes from following place under MIT/Apache-2.0 license by Artyom // Pavlov: @@ -69,7 +69,7 @@ macro_rules! expand_round { #[target_feature(enable = "aes")] #[inline] -unsafe fn expand_key(key: &[u8; 16]) -> RoundKeys { +unsafe fn expand_key(key: &[u8; 16]) -> RoundKeys { unsafe { // SAFETY: `RoundKeys` is a `[__m128i; 11]` which can be initialized // with all zeroes. let mut keys: RoundKeys = mem::zeroed(); @@ -89,4 +89,4 @@ unsafe fn expand_key(key: &[u8; 16]) -> RoundKeys { expand_round!(keys, 10, 0x36); keys -} +}} diff --git a/crates/subspace-service/src/lib.rs b/crates/subspace-service/src/lib.rs index 7154f2ab0d5..cdef0b7dc55 100644 --- a/crates/subspace-service/src/lib.rs +++ b/crates/subspace-service/src/lib.rs @@ -854,13 +854,11 @@ where let node_address_sender = Mutex::new(Some(node_address_sender)); move |address| { - if matches!(address.iter().next(), Some(Protocol::Ip4(_))) { - if let Some(node_address_sender) = node_address_sender.lock().take() { - if let Err(err) = node_address_sender.send(address.clone()) { + if matches!(address.iter().next(), Some(Protocol::Ip4(_))) + && let Some(node_address_sender) = node_address_sender.lock().take() + && let Err(err) = node_address_sender.send(address.clone()) { debug!(?err, "Couldn't send a node address to the channel."); } - } - } } })); @@ -1122,12 +1120,11 @@ where Some("sync-from-dsn"), Box::pin(async move { // Run snap-sync before DSN-sync. - if config.sync == ChainSyncMode::Snap { - if let Err(error) = snap_sync_task.in_current_span().await { + if config.sync == ChainSyncMode::Snap + && let Err(error) = snap_sync_task.in_current_span().await { error!(%error, "Snap sync exited with a fatal error"); return; } - } if let Err(error) = worker.await { error!(%error, "Sync from DSN exited with an error"); @@ -1384,7 +1381,7 @@ fn extract_confirmation_depth(chain_spec: &dyn ChainSpec) -> Option { let spec: serde_json::Value = serde_json::from_str(chain_spec.as_json(true).ok()?.as_str()).ok()?; let encoded_confirmation_depth = hex::decode( - spec.pointer(format!("/genesis/raw/top/{}", storage_key).as_str())? + spec.pointer(format!("/genesis/raw/top/{storage_key}").as_str())? .as_str()? .trim_start_matches("0x"), ) diff --git a/crates/subspace-service/src/sync_from_dsn.rs b/crates/subspace-service/src/sync_from_dsn.rs index 31385f45c4f..a798eb900e6 100644 --- a/crates/subspace-service/src/sync_from_dsn.rs +++ b/crates/subspace-service/src/sync_from_dsn.rs @@ -225,12 +225,10 @@ async fn create_imported_blocks_observer( Err(_timeout) => { if let Err(error) = notifications_sender.try_send(NotificationReason::NoImportedBlocks) - { - if error.is_disconnected() { + && error.is_disconnected() { // Receiving side was closed return; } - } } } } @@ -251,16 +249,13 @@ async fn create_substrate_network_observer( let was_online = last_online .map(|last_online| last_online.elapsed() < MIN_OFFLINE_PERIOD) .unwrap_or_default(); - if is_online && !was_online { - if let Err(error) = + if is_online && !was_online + && let Err(error) = notifications_sender.try_send(NotificationReason::WentOnlineSubstrate) - { - if error.is_disconnected() { + && error.is_disconnected() { // Receiving side was closed return; } - } - } if is_online { last_online.replace(Instant::now()); diff --git a/crates/subspace-service/src/sync_from_dsn/snap_sync.rs b/crates/subspace-service/src/sync_from_dsn/snap_sync.rs index 1c992ebae6f..f56d461f0e6 100644 --- a/crates/subspace-service/src/sync_from_dsn/snap_sync.rs +++ b/crates/subspace-service/src/sync_from_dsn/snap_sync.rs @@ -167,7 +167,7 @@ where { sync_segment_headers(segment_headers_store, node) .await - .map_err(|error| format!("Failed to sync segment headers: {}", error))?; + .map_err(|error| format!("Failed to sync segment headers: {error}"))?; let target_segment_index = { let last_segment_index = segment_headers_store diff --git a/domains/client/block-preprocessor/src/lib.rs b/domains/client/block-preprocessor/src/lib.rs index 3dc8aba1e9f..0b56fffdeca 100644 --- a/domains/client/block-preprocessor/src/lib.rs +++ b/domains/client/block-preprocessor/src/lib.rs @@ -271,8 +271,7 @@ where return Err(sp_blockchain::Error::RuntimeApiError( ApiError::Application( format!( - "Unexpected bundle in consensus block: {:?}, something must be wrong", - at_consensus_hash + "Unexpected bundle in consensus block: {at_consensus_hash:?}, something must be wrong" ) .into(), ), diff --git a/domains/client/cross-domain-message-gossip/src/message_listener.rs b/domains/client/cross-domain-message-gossip/src/message_listener.rs index 526c67253b6..55ec951df54 100644 --- a/domains/client/cross-domain-message-gossip/src/message_listener.rs +++ b/domains/client/cross-domain-message-gossip/src/message_listener.rs @@ -282,14 +282,13 @@ where if let Some(existing_channel_update) = maybe_existing_channel_detail { let maybe_block_hash = consensus_client.hash(existing_channel_update.block_number.into())?; - if let Some(block_hash) = maybe_block_hash { - if block_hash.as_ref() == existing_channel_update.block_hash.as_ref() + if let Some(block_hash) = maybe_block_hash + && block_hash.as_ref() == existing_channel_update.block_hash.as_ref() && header.state_root().as_ref() == existing_channel_update.state_root.as_ref() && existing_channel_update.block_number >= consensus_block_number { return Ok(()); } - } } let storage_key = StorageKey(api.channel_storage_key(best_hash, self_chain_id, channel_id)?); @@ -389,14 +388,12 @@ where // more the new block number, then don't update if let Ok((existing_block_hash, _)) = is_valid_domain_block_number(existing_channel_update.block_number) - { - if existing_block_hash.as_ref() == existing_channel_update.block_hash.as_ref() + && existing_block_hash.as_ref() == existing_channel_update.block_hash.as_ref() && domain_state_root.as_ref() == existing_channel_update.state_root.as_ref() && existing_channel_update.block_number >= domain_block_number { return Ok(()); } - } } let domain_runtime = runtime_api diff --git a/domains/client/domain-operator/src/aux_schema.rs b/domains/client/domain-operator/src/aux_schema.rs index fac748e9be2..a865dbf03a0 100644 --- a/domains/client/domain-operator/src/aux_schema.rs +++ b/domains/client/domain-operator/src/aux_schema.rs @@ -200,8 +200,7 @@ where domain_client .number(best_domain_hash)? .ok_or(sp_blockchain::Error::MissingHeader(format!( - "Block hash: {:?}", - best_domain_hash + "Block hash: {best_domain_hash:?}" )))?; let mut domain_hash_keys = get_tracked_domain_hash_keys::<_, Block, CBlock>(&**domain_client, best_domain_number)? diff --git a/domains/client/domain-operator/src/bundle_processor.rs b/domains/client/domain-operator/src/bundle_processor.rs index 009312d40df..d70948cac9b 100644 --- a/domains/client/domain-operator/src/bundle_processor.rs +++ b/domains/client/domain-operator/src/bundle_processor.rs @@ -246,7 +246,7 @@ where let domain_tip = domain_parent.0; if self.client.info().best_hash != domain_tip { let header = self.client.header(domain_tip)?.ok_or_else(|| { - sp_blockchain::Error::Backend(format!("Header for #{:?} not found", domain_tip)) + sp_blockchain::Error::Backend(format!("Header for #{domain_tip:?} not found")) })?; let block_origin = if self .domain_block_processor diff --git a/domains/client/domain-operator/src/domain_worker.rs b/domains/client/domain-operator/src/domain_worker.rs index ba5d3748eb8..12c2f225750 100644 --- a/domains/client/domain-operator/src/domain_worker.rs +++ b/domains/client/domain-operator/src/domain_worker.rs @@ -173,8 +173,8 @@ pub(super) async fn start_worker< } } Some(maybe_block_info) = throttled_block_import_notification_stream.next() => { - if let Some(block_info) = maybe_block_info { - if let Err(error) = bundle_processor + if let Some(block_info) = maybe_block_info + && let Err(error) = bundle_processor .clone() .process_bundles(( block_info.hash, @@ -189,7 +189,6 @@ pub(super) async fn start_worker< // TODO: more graceful shutdown. break; } - } } // In production the `acknowledgement_sender_stream` is an empty stream, it only set to // real stream in test @@ -209,8 +208,8 @@ pub(super) async fn start_worker< drop(new_slot_notification_stream); drop(acknowledgement_sender_stream); while let Some(maybe_block_info) = throttled_block_import_notification_stream.next().await { - if let Some(block_info) = maybe_block_info { - if let Err(error) = bundle_processor + if let Some(block_info) = maybe_block_info + && let Err(error) = bundle_processor .clone() .process_bundles((block_info.hash, block_info.number, block_info.is_new_best)) .instrument(span.clone()) @@ -221,7 +220,6 @@ pub(super) async fn start_worker< // TODO: more graceful shutdown. break; } - } } } } diff --git a/domains/client/domain-operator/src/fraud_proof.rs b/domains/client/domain-operator/src/fraud_proof.rs index 838deb8459e..d8bbba5fab6 100644 --- a/domains/client/domain-operator/src/fraud_proof.rs +++ b/domains/client/domain-operator/src/fraud_proof.rs @@ -657,8 +657,7 @@ where .block_number_from_id(&BlockId::Hash(domain_block_parent_hash))? .ok_or_else(|| { FraudProofError::Blockchain(sp_blockchain::Error::Backend(format!( - "unable to get block number for domain block:{:?}", - domain_block_parent_hash + "unable to get block number for domain block:{domain_block_parent_hash:?}" ))) })?; diff --git a/domains/client/domain-operator/src/snap_sync.rs b/domains/client/domain-operator/src/snap_sync.rs index b7fc9af6f19..d1de648f974 100644 --- a/domains/client/domain-operator/src/snap_sync.rs +++ b/domains/client/domain-operator/src/snap_sync.rs @@ -220,7 +220,7 @@ async fn get_last_confirmed_block( } Err(sp_blockchain::Error::Application( - format!("Failed to get block {}", block_number).into(), + format!("Failed to get block {block_number}").into(), )) } diff --git a/domains/client/domain-operator/src/tests.rs b/domains/client/domain-operator/src/tests.rs index 11d27dd4849..b029518fe99 100644 --- a/domains/client/domain-operator/src/tests.rs +++ b/domains/client/domain-operator/src/tests.rs @@ -1215,9 +1215,7 @@ async fn test_evm_domain_gas_estimates() { ), // The exact estimate is not important, but we want to know if it changes (53_408.into(), 53_408.into()), - "Incorrect EVM Create gas estimate: {:?} {:?}", - evm_call, - create_info, + "Incorrect EVM Create gas estimate: {evm_call:?} {create_info:?}", ); } pallet_evm::Call::call { @@ -1255,9 +1253,7 @@ async fn test_evm_domain_gas_estimates() { (call_info.used_gas.standard, call_info.used_gas.effective), // The exact estimate is not important, but we want to know if it changes (21_400.into(), 21_400.into()), - "Incorrect EVM Call gas estimate: {:?} {:?}", - evm_call, - call_info, + "Incorrect EVM Call gas estimate: {evm_call:?} {call_info:?}", ); } _ => panic!("Unexpected pallet_evm::Call type"), @@ -3032,12 +3028,11 @@ async fn test_true_invalid_bundles_inherent_extrinsic_proof_creation_and_verific // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -3142,12 +3137,11 @@ async fn test_false_invalid_bundles_inherent_extrinsic_proof_creation_and_verifi // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { assert!(!proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -3281,12 +3275,11 @@ async fn test_true_invalid_bundles_undecodeable_tx_proof_creation_and_verificati // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -3391,12 +3384,11 @@ async fn test_false_invalid_bundles_undecodeable_tx_proof_creation_and_verificat // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { assert!(!proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -3541,13 +3533,12 @@ async fn test_true_invalid_bundles_illegal_xdm_proof_creation_and_verification() // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); assert_eq!(extrinsic_index, 0); return true; } - } false }); @@ -3703,13 +3694,12 @@ async fn test_true_invalid_bundles_illegal_extrinsic_proof_creation_and_verifica // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); assert_eq!(extrinsic_index, 2); return true; } - } false }); @@ -3833,13 +3823,12 @@ async fn test_false_invalid_bundles_illegal_extrinsic_proof_creation_and_verific // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { assert!(!proof.is_good_invalid_fraud_proof); assert_eq!(extrinsic_index, 1); return true; } - } false }); @@ -3951,12 +3940,11 @@ async fn test_true_invalid_bundle_weight_proof_creation_and_verification() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -4059,12 +4047,11 @@ async fn test_false_invalid_bundle_weight_proof_creation_and_verification() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { assert!(!proof.is_good_invalid_fraud_proof); return true; } - } false }); @@ -4168,12 +4155,11 @@ async fn test_false_invalid_bundles_non_exist_extrinsic_proof_creation_and_verif // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundlesProofData::Bundle(_) = proof.proof_data { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundlesProofData::Bundle(_) = proof.proof_data { assert_eq!(fp.targeted_bad_receipt_hash(), bad_receipt_hash); return true; } - } false }); @@ -4856,8 +4842,7 @@ async fn test_valid_bundle_proof_generation_and_verification() { if let subspace_test_runtime::RuntimeCall::Domains( pallet_domains::Call::submit_fraud_proof { fraud_proof }, ) = ext.function - { - if let FraudProofVariant::ValidBundle(ref proof) = fraud_proof.proof { + && let FraudProofVariant::ValidBundle(ref proof) = fraud_proof.proof { // The fraud proof is targetting the `bad_receipt` assert_eq!( fraud_proof.bad_receipt_hash, @@ -4879,7 +4864,6 @@ async fn test_valid_bundle_proof_generation_and_verification() { break; } - } } // Produce a consensus block that contains the fraud proof, the fraud proof wil be verified @@ -6005,11 +5989,10 @@ async fn test_unordered_cross_domains_message_should_work() { while let Some(xdm) = reorder_xdm_receiver.next().await { if i % 3 == 0 { msg_buffer.push_back(xdm); - if let Some(xdm) = msg_buffer.pop_front() { - if i % 2 == 0 { + if let Some(xdm) = msg_buffer.pop_front() + && i % 2 == 0 { evm_domain_tx_pool_sink.unbounded_send(xdm).unwrap(); } - } } else { evm_domain_tx_pool_sink.unbounded_send(xdm).unwrap(); } @@ -7154,13 +7137,12 @@ async fn test_xdm_false_invalid_fraud_proof() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { assert!(!proof.is_good_invalid_fraud_proof); assert_eq!(extrinsic_index, 0); return true; } - } false }); @@ -7354,13 +7336,12 @@ async fn test_stale_fork_xdm_true_invalid_fraud_proof() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { - if let FraudProofVariant::InvalidBundles(proof) = &fp.proof { - if let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { + if let FraudProofVariant::InvalidBundles(proof) = &fp.proof + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { assert!(proof.is_good_invalid_fraud_proof); assert_eq!(extrinsic_index, 0); return true; } - } false }); diff --git a/domains/pallets/block-fees/src/lib.rs b/domains/pallets/block-fees/src/lib.rs index 3c748447f54..6b045296786 100644 --- a/domains/pallets/block-fees/src/lib.rs +++ b/domains/pallets/block-fees/src/lib.rs @@ -154,11 +154,9 @@ mod pallet { if let Call::set_next_consensus_chain_byte_fee { transaction_byte_fee, } = call - { - if transaction_byte_fee != &provided_transaction_byte_fee { + && transaction_byte_fee != &provided_transaction_byte_fee { return Err(InherentError::IncorrectConsensusChainByteFee); } - } Ok(()) } diff --git a/domains/pallets/domain-sudo/src/lib.rs b/domains/pallets/domain-sudo/src/lib.rs index 10826ced9fb..f4a086faf45 100644 --- a/domains/pallets/domain-sudo/src/lib.rs +++ b/domains/pallets/domain-sudo/src/lib.rs @@ -118,11 +118,10 @@ mod pallet { if let Some(encoded_call) = inherent_data.maybe_call { let runtime_call = Box::new(T::IntoRuntimeCall::runtime_call(encoded_call)); - if let Call::sudo { call } = call { - if call != &runtime_call { + if let Call::sudo { call } = call + && call != &runtime_call { return Err(InherentError::IncorrectRuntimeCall); } - } } else { return Err(InherentError::MissingRuntimeCall); } diff --git a/domains/pallets/executive/src/lib.rs b/domains/pallets/executive/src/lib.rs index c7a23893a74..270b984b069 100644 --- a/domains/pallets/executive/src/lib.rs +++ b/domains/pallets/executive/src/lib.rs @@ -159,11 +159,10 @@ mod pallet { .expect("Executive inherent data must be provided"); if let Some(provided_code) = inherent_data.maybe_code { - if let Call::set_code { code } = call { - if code != &provided_code { + if let Call::set_code { code } = call + && code != &provided_code { return Err(InherentError::IncorrectRuntimeCode); } - } } else { return Err(InherentError::MissingRuntimeCode); } @@ -318,7 +317,7 @@ where match ExecutiveConfig::ensure_inherents_are_first(block) { Ok(num) => num, - Err(i) => panic!("Invalid inherent position for extrinsic at index {}", i), + Err(i) => panic!("Invalid inherent position for extrinsic at index {i}"), } } diff --git a/domains/pallets/messenger/src/lib.rs b/domains/pallets/messenger/src/lib.rs index e84ac59a611..bdc2b9558c5 100644 --- a/domains/pallets/messenger/src/lib.rs +++ b/domains/pallets/messenger/src/lib.rs @@ -819,11 +819,10 @@ mod pallet { .expect("Messenger inherent data must be provided"); if let Some(provided_updates) = inherent_data.maybe_updates { - if let Call::update_domain_allowlist { updates } = call { - if updates != &provided_updates { + if let Call::update_domain_allowlist { updates } = call + && updates != &provided_updates { return Err(InherentError::IncorrectAllowlistUpdates); } - } } else { return Err(InherentError::MissingAllowlistUpdates); } @@ -923,13 +922,12 @@ mod pallet { // we always prefer latest opened channel. while let Some(channel_id) = next_channel_id.checked_sub(ChannelId::one()) { let message_count = OutboxMessageCount::::get((dst_chain_id, channel_id)); - if let Some(channel) = Channels::::get(dst_chain_id, channel_id) { - if channel.state == ChannelState::Open + if let Some(channel) = Channels::::get(dst_chain_id, channel_id) + && channel.state == ChannelState::Open && message_count < channel.max_outgoing_messages { return Some(channel_id); } - } next_channel_id = channel_id } diff --git a/domains/runtime/auto-id/src/lib.rs b/domains/runtime/auto-id/src/lib.rs index 7c2ec49ce15..459b47aba5c 100644 --- a/domains/runtime/auto-id/src/lib.rs +++ b/domains/runtime/auto-id/src/lib.rs @@ -964,7 +964,7 @@ impl_runtime_apis! { UncheckedExtrinsic::decode_with_depth_limit( MAX_CALL_RECURSION_DEPTH, &mut encoded.as_slice(), - ).map_err(|err| DecodeExtrinsicError(format!("{}", err))) + ).map_err(|err| DecodeExtrinsicError(format!("{err}"))) } fn decode_extrinsics_prefix( diff --git a/domains/runtime/evm/src/lib.rs b/domains/runtime/evm/src/lib.rs index 0b2c804febb..8d69af2da59 100644 --- a/domains/runtime/evm/src/lib.rs +++ b/domains/runtime/evm/src/lib.rs @@ -1393,7 +1393,7 @@ impl_runtime_apis! { UncheckedExtrinsic::decode_with_depth_limit( MAX_CALL_RECURSION_DEPTH, &mut encoded.as_slice(), - ).map_err(|err| DecodeExtrinsicError(format!("{}", err))) + ).map_err(|err| DecodeExtrinsicError(format!("{err}"))) } fn decode_extrinsics_prefix( diff --git a/domains/test/runtime/auto-id/src/lib.rs b/domains/test/runtime/auto-id/src/lib.rs index 5002a363f76..1435d2bec9f 100644 --- a/domains/test/runtime/auto-id/src/lib.rs +++ b/domains/test/runtime/auto-id/src/lib.rs @@ -960,7 +960,7 @@ impl_runtime_apis! { UncheckedExtrinsic::decode_with_depth_limit( MAX_CALL_RECURSION_DEPTH, &mut encoded.as_slice(), - ).map_err(|err| DecodeExtrinsicError(format!("{}", err))) + ).map_err(|err| DecodeExtrinsicError(format!("{err}"))) } fn decode_extrinsics_prefix( diff --git a/domains/test/runtime/evm/src/lib.rs b/domains/test/runtime/evm/src/lib.rs index 5a0fd07a28d..aadf1850d71 100644 --- a/domains/test/runtime/evm/src/lib.rs +++ b/domains/test/runtime/evm/src/lib.rs @@ -1419,7 +1419,7 @@ impl_runtime_apis! { UncheckedExtrinsic::decode_with_depth_limit( MAX_CALL_RECURSION_DEPTH, &mut encoded.as_slice(), - ).map_err(|err| DecodeExtrinsicError(format!("{}", err))) + ).map_err(|err| DecodeExtrinsicError(format!("{err}"))) } fn decode_extrinsics_prefix( diff --git a/domains/test/service/src/keyring.rs b/domains/test/service/src/keyring.rs index 9694c9a6078..f57b8917b1e 100644 --- a/domains/test/service/src/keyring.rs +++ b/domains/test/service/src/keyring.rs @@ -35,7 +35,7 @@ impl Keyring { /// Return seed string. pub fn to_seed(self) -> String { - format!("//{:?}", self) + format!("//{self:?}") } /// Return account id diff --git a/shared/subspace-logging/src/lib.rs b/shared/subspace-logging/src/lib.rs index 9e94f87ae46..104d1266709 100644 --- a/shared/subspace-logging/src/lib.rs +++ b/shared/subspace-logging/src/lib.rs @@ -26,9 +26,8 @@ pub fn init_logger() { // In production, this might be a bug in the logging setup. // In some tests, it is expected. eprintln!( - "Failed to initialize logger: {}. \ - This is expected when running nexttest test functions under `cargo test`.", - e + "Failed to initialize logger: {e}. \ + This is expected when running nexttest test functions under `cargo test`." ); } } diff --git a/test/subspace-test-service/src/lib.rs b/test/subspace-test-service/src/lib.rs index 803464cb6e8..8c69842f86b 100644 --- a/test/subspace-test-service/src/lib.rs +++ b/test/subspace-test-service/src/lib.rs @@ -782,11 +782,9 @@ impl MockConsensusNode { .expect("should be able to decode"); if let RuntimeCall::Domains(pallet_domains::Call::submit_bundle { opaque_bundle }) = ext.function - { - if opaque_bundle.sealed_header.slot_number() == *new_slot.0 { + && opaque_bundle.sealed_header.slot_number() == *new_slot.0 { return Some(opaque_bundle); } - } } None } @@ -878,11 +876,9 @@ impl MockConsensusNode { if let subspace_test_runtime::RuntimeCall::Domains( pallet_domains::Call::submit_fraud_proof { fraud_proof }, ) = ext.function - { - if fraud_proof_predicate(&fraud_proof) { + && fraud_proof_predicate(&fraud_proof) { return *fraud_proof; } - } } unreachable!() }) From 500f33a54dcf1bf73ac8ee50a70197768e8aa3c5 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Sun, 1 Jun 2025 13:19:43 +0000 Subject: [PATCH 09/15] chore: run cargo -Zgitoxide -Zgit clippy --locked --all-targets --features rocm --fix --all -- -D warnings --- crates/pallet-domains/src/lib.rs | 10 ++++------ crates/subspace-farmer/src/plotter/gpu/rocm.rs | 3 +-- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/crates/pallet-domains/src/lib.rs b/crates/pallet-domains/src/lib.rs index dafdb377e06..d44bed1ba30 100644 --- a/crates/pallet-domains/src/lib.rs +++ b/crates/pallet-domains/src/lib.rs @@ -1157,8 +1157,8 @@ mod pallet { // NOTE: Skip the following staking related operations when benchmarking the // `submit_bundle` call, these operations will be benchmarked separately. #[cfg(not(feature = "runtime-benchmarks"))] - if accepted_receipt_type == AcceptedReceiptType::NewHead { - if let Some(block_tree_node) = + if accepted_receipt_type == AcceptedReceiptType::NewHead + && let Some(block_tree_node) = prune_receipt::(domain_id, receipt_block_number) .map_err(Error::::from)? { @@ -1176,7 +1176,6 @@ mod pallet { ) .map_err(Error::::from)?; } - } #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))] let maybe_confirmed_domain_block_info = process_execution_receipt::( @@ -1772,8 +1771,8 @@ mod pallet { // NOTE: Skip the following staking related operations when benchmarking the // `submit_receipt` call, these operations will be benchmarked separately. #[cfg(not(feature = "runtime-benchmarks"))] - if accepted_receipt_type == AcceptedReceiptType::NewHead { - if let Some(block_tree_node) = + if accepted_receipt_type == AcceptedReceiptType::NewHead + && let Some(block_tree_node) = prune_receipt::(domain_id, receipt.domain_block_number) .map_err(Error::::from)? { @@ -1791,7 +1790,6 @@ mod pallet { ) .map_err(Error::::from)?; } - } #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))] let maybe_confirmed_domain_block_info = process_execution_receipt::( diff --git a/crates/subspace-farmer/src/plotter/gpu/rocm.rs b/crates/subspace-farmer/src/plotter/gpu/rocm.rs index db875b83e19..b5a85c6d11b 100644 --- a/crates/subspace-farmer/src/plotter/gpu/rocm.rs +++ b/crates/subspace-farmer/src/plotter/gpu/rocm.rs @@ -101,8 +101,7 @@ impl RocmRecordsEncoder { } else { // We want to guarantee exit, rather than panicking in a panic handler. eprintln!( - "rayon panic handler called on non-rayon thread: {:?}", - panic_info + "rayon panic handler called on non-rayon thread: {panic_info:?}" ); } exit(1); From 71f66d33955fcd05b4e5d27d6a3604f5b50ebd9b Mon Sep 17 00:00:00 2001 From: tediou5 Date: Sun, 1 Jun 2025 13:55:12 +0000 Subject: [PATCH 10/15] chore(clippy): replace clone with std::slice::from_ref --- crates/subspace-networking/src/node_runner.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/subspace-networking/src/node_runner.rs b/crates/subspace-networking/src/node_runner.rs index 7344abe5c5a..0f3aa89f760 100644 --- a/crates/subspace-networking/src/node_runner.rs +++ b/crates/subspace-networking/src/node_runner.rs @@ -491,7 +491,7 @@ impl NodeRunner { } ref event @ SwarmEvent::ExpiredListenAddr { ref address, .. } => { trace!(?event, "Local listener expired event."); - self.handle_remove_listeners(&[address.clone()]); + self.handle_remove_listeners(std::slice::from_ref(address)); } SwarmEvent::ConnectionEstablished { peer_id, From 5788435d79024ec28bda4a5c1cac304df8dfafd1 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 18:42:49 +0800 Subject: [PATCH 11/15] chore: cargo fmt --all --- crates/pallet-domains/src/benchmarking.rs | 22 +- crates/pallet-domains/src/block_tree.rs | 30 ++- .../pallet-domains/src/bundle_storage_fund.rs | 6 +- crates/pallet-domains/src/domain_registry.rs | 18 +- crates/pallet-domains/src/extensions.rs | 2 +- crates/pallet-domains/src/lib.rs | 133 +++++----- crates/pallet-domains/src/runtime_registry.rs | 14 +- crates/pallet-domains/src/staking.rs | 30 +-- crates/pallet-domains/src/staking_epoch.rs | 18 +- crates/pallet-domains/src/tests.rs | 12 +- crates/pallet-rewards/src/lib.rs | 21 +- crates/pallet-rewards/src/mock.rs | 2 +- crates/pallet-rewards/src/tests.rs | 2 +- crates/pallet-subspace-mmr/src/lib.rs | 2 +- crates/pallet-subspace/src/benchmarking.rs | 2 +- crates/pallet-subspace/src/extensions.rs | 6 +- crates/pallet-subspace/src/lib.rs | 134 +++++----- crates/pallet-subspace/src/mock.rs | 10 +- crates/pallet-subspace/src/tests.rs | 30 ++- crates/pallet-transaction-fees/src/lib.rs | 2 +- crates/sc-consensus-subspace-rpc/src/lib.rs | 35 +-- crates/sc-consensus-subspace/src/archiver.rs | 17 +- .../sc-consensus-subspace/src/block_import.rs | 23 +- .../sc-consensus-subspace/src/notification.rs | 2 +- .../sc-consensus-subspace/src/slot_worker.rs | 41 +-- crates/sc-consensus-subspace/src/verifier.rs | 8 +- .../src/domain_block_er/receipt_receiver.rs | 2 +- crates/sc-domains/src/lib.rs | 6 +- crates/sc-proof-of-time/src/lib.rs | 11 +- crates/sc-proof-of-time/src/source.rs | 25 +- crates/sc-proof-of-time/src/source/gossip.rs | 25 +- .../sc-proof-of-time/src/source/timekeeper.rs | 14 +- crates/sc-proof-of-time/src/verifier/tests.rs | 42 +-- .../src/consensus/relay.rs | 2 +- .../src/consensus/types.rs | 2 +- crates/sc-subspace-block-relay/src/lib.rs | 2 +- crates/sc-subspace-block-relay/src/utils.rs | 2 +- crates/sp-consensus-subspace/src/digests.rs | 4 +- crates/sp-consensus-subspace/src/lib.rs | 6 +- .../benches/fraud_proof_verification.rs | 108 ++++---- .../src/execution_prover.rs | 2 +- .../sp-domains-fraud-proof/src/fraud_proof.rs | 8 +- .../src/host_functions.rs | 8 +- crates/sp-domains-fraud-proof/src/lib.rs | 2 +- .../src/storage_proof.rs | 2 +- crates/sp-domains-fraud-proof/src/tests.rs | 79 +++--- .../src/verification.rs | 17 +- crates/sp-domains/src/core_api.rs | 4 +- crates/sp-domains/src/extrinsics.rs | 2 +- crates/sp-domains/src/lib.rs | 16 +- .../src/proof_provider_and_verifier.rs | 6 +- crates/sp-domains/src/storage.rs | 8 +- crates/sp-domains/src/test_ethereum_tx.rs | 2 +- crates/sp-domains/src/tests.rs | 4 +- crates/sp-domains/src/valued_trie.rs | 23 +- .../subspace-archiving/benches/archiving.rs | 4 +- crates/subspace-archiving/src/archiver.rs | 4 +- .../incremental_record_commitments.rs | 2 +- .../subspace-archiving/src/reconstructor.rs | 15 +- .../tests/integration/archiver.rs | 30 ++- .../tests/integration/reconstructor.rs | 2 +- crates/subspace-core-primitives/src/lib.rs | 2 +- .../subspace-core-primitives/src/objects.rs | 2 +- crates/subspace-core-primitives/src/pieces.rs | 2 +- crates/subspace-core-primitives/src/pos.rs | 2 +- crates/subspace-core-primitives/src/pot.rs | 2 +- .../subspace-core-primitives/src/sectors.rs | 4 +- .../subspace-core-primitives/src/segments.rs | 4 +- crates/subspace-core-primitives/src/tests.rs | 2 +- .../benches/commitments.rs | 2 +- crates/subspace-erasure-coding/src/lib.rs | 2 +- crates/subspace-fake-runtime-api/src/lib.rs | 2 +- .../benches/auditing.rs | 12 +- .../benches/plotting.rs | 10 +- .../benches/proving.rs | 10 +- .../benches/reading.rs | 14 +- .../src/auditing.rs | 2 +- .../src/plotting.rs | 12 +- .../subspace-farmer-components/src/proving.rs | 2 +- .../subspace-farmer-components/src/reading.rs | 8 +- .../subspace-farmer-components/src/sector.rs | 6 +- .../src/segment_reconstruction.rs | 2 +- .../bin/subspace-farmer/commands/benchmark.rs | 56 ++-- .../bin/subspace-farmer/commands/cluster.rs | 12 +- .../subspace-farmer/commands/cluster/cache.rs | 17 +- .../commands/cluster/controller.rs | 14 +- .../commands/cluster/farmer.rs | 27 +- .../commands/cluster/plotter.rs | 6 +- .../src/bin/subspace-farmer/commands/farm.rs | 39 +-- .../bin/subspace-farmer/commands/shared.rs | 2 +- .../commands/shared/network.rs | 10 +- crates/subspace-farmer/src/cluster/cache.rs | 4 +- .../subspace-farmer/src/cluster/controller.rs | 2 +- .../src/cluster/controller/caches.rs | 27 +- .../src/cluster/controller/farms.rs | 16 +- .../src/cluster/controller/stream_map.rs | 2 +- crates/subspace-farmer/src/cluster/farmer.rs | 10 +- .../src/cluster/nats_client.rs | 13 +- crates/subspace-farmer/src/cluster/plotter.rs | 10 +- .../subspace-farmer/src/disk_piece_cache.rs | 10 +- .../src/farm/plotted_pieces.rs | 2 +- crates/subspace-farmer/src/farmer_cache.rs | 16 +- .../src/farmer_cache/piece_cache_state.rs | 2 +- .../subspace-farmer/src/farmer_cache/tests.rs | 62 +++-- .../src/farmer_piece_getter.rs | 21 +- .../farmer_piece_getter/piece_validator.rs | 2 +- .../node_client/caching_proxy_node_client.rs | 13 +- crates/subspace-farmer/src/plotter.rs | 6 +- crates/subspace-farmer/src/plotter/cpu.rs | 14 +- .../src/plotter/cpu/metrics.rs | 2 +- crates/subspace-farmer/src/plotter/gpu.rs | 14 +- .../subspace-farmer/src/plotter/gpu/cuda.rs | 52 ++-- .../src/plotter/gpu/metrics.rs | 2 +- .../subspace-farmer/src/plotter/gpu/rocm.rs | 52 ++-- crates/subspace-farmer/src/plotter/pool.rs | 2 +- .../subspace-farmer/src/single_disk_farm.rs | 148 ++++++----- .../src/single_disk_farm/direct_io_file.rs | 2 +- .../src/single_disk_farm/farming.rs | 12 +- .../single_disk_farm/farming/rayon_files.rs | 2 +- .../src/single_disk_farm/metrics.rs | 2 +- .../src/single_disk_farm/piece_cache.rs | 2 +- .../src/single_disk_farm/piece_reader.rs | 6 +- .../src/single_disk_farm/plot_cache.rs | 2 +- .../src/single_disk_farm/plot_cache/tests.rs | 42 +-- .../src/single_disk_farm/plotted_sectors.rs | 6 +- .../src/single_disk_farm/plotting.rs | 45 ++-- crates/subspace-farmer/src/utils.rs | 17 +- crates/subspace-farmer/src/utils/ss58.rs | 2 +- crates/subspace-farmer/src/utils/tests.rs | 4 +- crates/subspace-gateway/src/commands.rs | 4 +- crates/subspace-gateway/src/commands/http.rs | 6 +- .../src/commands/http/server.rs | 2 +- .../subspace-gateway/src/commands/network.rs | 4 +- crates/subspace-gateway/src/commands/rpc.rs | 6 +- crates/subspace-gateway/src/main.rs | 2 +- .../subspace-gateway/src/piece_validator.rs | 2 +- .../src/bin/subspace-malicious-operator.rs | 2 +- .../src/chain_spec.rs | 2 +- crates/subspace-malicious-operator/src/lib.rs | 4 +- .../src/malicious_bundle_producer.rs | 20 +- .../src/malicious_bundle_tamper.rs | 9 +- .../src/malicious_domain_instance_starter.rs | 6 +- .../subspace-networking/examples/benchmark.rs | 15 +- .../subspace-networking/examples/get-peers.rs | 9 +- .../subspace-networking/examples/metrics.rs | 13 +- .../examples/networking.rs | 9 +- .../examples/random-walker.rs | 9 +- .../subspace-networking/examples/requests.rs | 9 +- crates/subspace-networking/src/behavior.rs | 4 +- .../src/behavior/persistent_parameters.rs | 63 ++--- .../subspace-networking/src/behavior/tests.rs | 47 ++-- .../src/bin/subspace-bootstrap-node/main.rs | 8 +- crates/subspace-networking/src/constructor.rs | 8 +- .../src/constructor/temporary_bans.rs | 2 +- .../src/constructor/transport.rs | 15 +- crates/subspace-networking/src/lib.rs | 4 +- crates/subspace-networking/src/node.rs | 2 +- crates/subspace-networking/src/node/tests.rs | 9 +- crates/subspace-networking/src/node_runner.rs | 30 ++- .../src/protocols/autonat_wrapper.rs | 2 +- .../handlers/cached_piece_by_index/tests.rs | 20 +- .../request_response_factory.rs | 49 ++-- .../request_response_factory/tests.rs | 4 +- .../src/protocols/reserved_peers.rs | 13 +- .../src/protocols/reserved_peers/tests.rs | 6 +- .../protocols/subspace_connection_limits.rs | 24 +- crates/subspace-networking/src/shared.rs | 4 +- .../src/utils/key_with_distance.rs | 2 +- .../src/utils/piece_provider.rs | 4 +- crates/subspace-node/src/chain_spec.rs | 4 +- crates/subspace-node/src/chain_spec_utils.rs | 4 +- crates/subspace-node/src/commands.rs | 6 +- .../subspace-node/src/commands/domain_key.rs | 4 +- crates/subspace-node/src/commands/run.rs | 12 +- .../src/commands/run/consensus.rs | 23 +- .../subspace-node/src/commands/run/domain.rs | 14 +- .../subspace-node/src/commands/run/shared.rs | 4 +- crates/subspace-node/src/commands/shared.rs | 2 +- .../src/domain/auto_id_chain_spec.rs | 2 +- crates/subspace-node/src/domain/cli.rs | 4 +- .../src/domain/evm_chain_spec.rs | 2 +- crates/subspace-proof-of-space/benches/pos.rs | 18 +- crates/subspace-proof-of-space/src/chia.rs | 4 +- crates/subspace-proof-of-space/src/chiapos.rs | 2 +- .../src/chiapos/table.rs | 10 +- .../src/chiapos/table/tests.rs | 6 +- .../src/chiapos/tables.rs | 6 +- crates/subspace-proof-of-space/src/shim.rs | 2 +- .../benches/pot-compare-cpu-cores.rs | 2 +- crates/subspace-proof-of-time/benches/pot.rs | 2 +- crates/subspace-proof-of-time/src/aes.rs | 2 +- .../subspace-proof-of-time/src/aes/x86_64.rs | 92 +++---- crates/subspace-runtime-primitives/src/lib.rs | 8 +- .../src/utility.rs | 2 +- crates/subspace-runtime/src/lib.rs | 38 +-- crates/subspace-service/src/config.rs | 8 +- crates/subspace-service/src/dsn.rs | 2 +- crates/subspace-service/src/lib.rs | 42 +-- crates/subspace-service/src/metrics.rs | 2 +- crates/subspace-service/src/mmr.rs | 2 +- crates/subspace-service/src/mmr/sync.rs | 6 +- crates/subspace-service/src/sync_from_dsn.rs | 31 ++- .../src/sync_from_dsn/import_blocks.rs | 10 +- .../src/sync_from_dsn/piece_validator.rs | 2 +- .../segment_header_downloader.rs | 2 +- .../src/sync_from_dsn/snap_sync.rs | 8 +- crates/subspace-service/src/task_spawner.rs | 6 +- crates/subspace-verification/src/lib.rs | 4 +- .../client/block-builder/src/custom_api.rs | 2 +- .../src/genesis_block_builder.rs | 6 +- domains/client/block-builder/src/lib.rs | 6 +- domains/client/block-preprocessor/src/lib.rs | 8 +- .../src/stateless_runtime.rs | 6 +- .../consensus-relay-chain/src/import_queue.rs | 2 +- .../src/aux_schema.rs | 4 +- .../src/gossip_worker.rs | 21 +- .../cross-domain-message-gossip/src/lib.rs | 8 +- .../src/message_listener.rs | 26 +- .../client/domain-operator/src/aux_schema.rs | 2 +- .../domain-operator/src/bundle_processor.rs | 4 +- .../src/bundle_producer_election_solver.rs | 12 +- .../src/domain_block_processor.rs | 8 +- .../src/domain_bundle_producer.rs | 2 +- .../src/domain_bundle_proposer.rs | 8 +- .../domain-operator/src/domain_worker.rs | 18 +- .../client/domain-operator/src/fraud_proof.rs | 12 +- domains/client/domain-operator/src/lib.rs | 10 +- .../client/domain-operator/src/operator.rs | 6 +- .../client/domain-operator/src/snap_sync.rs | 6 +- domains/client/domain-operator/src/tests.rs | 240 ++++++++++-------- domains/client/eth-service/src/provider.rs | 8 +- domains/client/eth-service/src/service.rs | 4 +- domains/client/relayer/src/lib.rs | 8 +- domains/client/relayer/src/worker.rs | 2 +- domains/pallets/auto-id/src/lib.rs | 2 +- domains/pallets/auto-id/src/tests.rs | 20 +- domains/pallets/block-fees/src/fees.rs | 2 +- domains/pallets/block-fees/src/lib.rs | 9 +- .../pallets/domain-check-weight/src/lib.rs | 2 +- domains/pallets/domain-sudo/src/lib.rs | 9 +- .../pallets/evm-tracker/src/check_nonce.rs | 4 +- .../evm-tracker/src/create_contract.rs | 4 +- domains/pallets/evm-tracker/src/lib.rs | 2 +- domains/pallets/executive/src/lib.rs | 60 ++--- domains/pallets/executive/src/mock.rs | 2 +- domains/pallets/executive/src/tests.rs | 2 +- domains/pallets/messenger/src/benchmarking.rs | 2 +- domains/pallets/messenger/src/extensions.rs | 6 +- .../extensions/benchmarking_from_domains.rs | 2 +- domains/pallets/messenger/src/fees.rs | 2 +- domains/pallets/messenger/src/lib.rs | 35 ++- domains/pallets/messenger/src/migrations.rs | 2 +- .../messenger/src/migrations/v1_to_v2.rs | 8 +- domains/pallets/messenger/src/mock.rs | 4 +- domains/pallets/messenger/src/tests.rs | 40 +-- .../pallets/transporter/src/benchmarking.rs | 2 +- domains/pallets/transporter/src/lib.rs | 2 +- domains/pallets/transporter/src/tests.rs | 4 +- domains/primitives/evm-tracker/src/lib.rs | 6 +- .../src/host_functions.rs | 4 +- .../messenger-host-functions/src/lib.rs | 2 +- .../src/runtime_interface.rs | 2 +- domains/primitives/messenger/src/endpoint.rs | 2 +- domains/primitives/messenger/src/messages.rs | 2 +- domains/primitives/runtime/src/lib.rs | 4 +- domains/runtime/auto-id/src/lib.rs | 22 +- domains/runtime/evm/src/lib.rs | 38 +-- domains/service/src/config.rs | 6 +- domains/service/src/domain.rs | 4 +- domains/service/src/lib.rs | 2 +- domains/service/src/network.rs | 6 +- domains/service/src/providers.rs | 2 +- domains/test/runtime/auto-id/src/lib.rs | 18 +- domains/test/runtime/evm/src/lib.rs | 29 ++- domains/test/service/src/domain.rs | 12 +- domains/test/service/src/keyring.rs | 2 +- .../src/snap_sync_engine.rs | 4 +- .../src/object_fetcher.rs | 8 +- .../src/object_fetcher/partial_object.rs | 6 +- .../src/object_fetcher/segment_header.rs | 2 +- .../src/object_fetcher/tests.rs | 4 +- .../src/piece_getter.rs | 2 +- shared/subspace-kzg/benches/kzg.rs | 4 +- shared/subspace-kzg/src/lib.rs | 6 +- shared/subspace-logging/src/lib.rs | 2 +- shared/subspace-metrics/src/lib.rs | 2 +- .../subspace-proof-of-space-gpu/src/cuda.rs | 2 +- .../src/cuda/tests.rs | 2 +- .../subspace-proof-of-space-gpu/src/rocm.rs | 2 +- .../src/rocm/tests.rs | 2 +- .../src/auto_id_domain_chain_spec.rs | 2 +- test/subspace-test-client/src/chain_spec.rs | 4 +- .../src/evm_domain_chain_spec.rs | 2 +- test/subspace-test-client/src/lib.rs | 6 +- test/subspace-test-runtime/src/lib.rs | 26 +- test/subspace-test-service/src/lib.rs | 41 +-- 296 files changed, 2006 insertions(+), 1853 deletions(-) diff --git a/crates/pallet-domains/src/benchmarking.rs b/crates/pallet-domains/src/benchmarking.rs index 630ef99c7da..d6d403abb7b 100644 --- a/crates/pallet-domains/src/benchmarking.rs +++ b/crates/pallet-domains/src/benchmarking.rs @@ -3,21 +3,21 @@ extern crate alloc; use super::*; -use crate::block_tree::{prune_receipt, BlockTreeNode}; +use crate::block_tree::{BlockTreeNode, prune_receipt}; use crate::bundle_storage_fund::refund_storage_fee; -use crate::domain_registry::{into_domain_config, DomainConfigParams}; +use crate::domain_registry::{DomainConfigParams, into_domain_config}; use crate::runtime_registry::DomainRuntimeUpgradeEntry; use crate::staking::{ - do_convert_previous_epoch_withdrawal, do_mark_operators_as_slashed, do_reward_operators, Error as StakingError, OperatorConfig, OperatorStatus, WithdrawStake, + do_convert_previous_epoch_withdrawal, do_mark_operators_as_slashed, do_reward_operators, }; use crate::staking_epoch::{ do_finalize_domain_current_epoch, do_finalize_domain_epoch_staking, do_slash_operator, operator_take_reward_tax_and_stake, }; use crate::{ - DomainBlockNumberFor, ExecutionReceiptOf, Pallet as Domains, RawOrigin as DomainOrigin, - MAX_NOMINATORS_TO_SLASH, + DomainBlockNumberFor, ExecutionReceiptOf, MAX_NOMINATORS_TO_SLASH, Pallet as Domains, + RawOrigin as DomainOrigin, }; #[cfg(not(feature = "std"))] use alloc::borrow::ToOwned; @@ -25,27 +25,27 @@ use alloc::borrow::ToOwned; use alloc::vec::Vec; use frame_benchmarking::v2::*; use frame_support::assert_ok; -use frame_support::traits::fungible::{Inspect, Mutate}; use frame_support::traits::Hooks; +use frame_support::traits::fungible::{Inspect, Mutate}; use frame_system::{Pallet as System, RawOrigin}; use hex_literal::hex; use pallet_subspace::BlockRandomness; use sp_consensus_slots::Slot; +use sp_core::H256; use sp_core::crypto::{Ss58Codec, UncheckedFrom}; use sp_core::sr25519::vrf::{VrfPreOutput, VrfProof, VrfSignature}; -use sp_core::H256; use sp_domains::merkle_tree::MerkleTree; use sp_domains::{ - dummy_opaque_bundle, BundleHeader, DomainId, ExecutionReceipt, OpaqueBundle, OperatorAllowList, - OperatorId, OperatorPublicKey, OperatorRewardSource, OperatorSignature, + BundleHeader, DomainId, EMPTY_EXTRINSIC_ROOT, ExecutionReceipt, OpaqueBundle, + OperatorAllowList, OperatorId, OperatorPublicKey, OperatorRewardSource, OperatorSignature, PermissionedActionAllowedBy, ProofOfElection, RuntimeType, SealedBundleHeader, - SealedSingletonReceipt, SingletonReceipt, EMPTY_EXTRINSIC_ROOT, + SealedSingletonReceipt, SingletonReceipt, dummy_opaque_bundle, }; use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_runtime::traits::{CheckedAdd, One, Zero}; use sp_std::collections::btree_set::BTreeSet; -use subspace_core_primitives::pot::PotOutput; use subspace_core_primitives::Randomness; +use subspace_core_primitives::pot::PotOutput; const SEED: u32 = 0; const MAX_NOMINATORS_TO_SLASH_WITHOUT_OPERATOR: u32 = MAX_NOMINATORS_TO_SLASH - 1; diff --git a/crates/pallet-domains/src/block_tree.rs b/crates/pallet-domains/src/block_tree.rs index 0c03bf35d01..bda1807b6e5 100644 --- a/crates/pallet-domains/src/block_tree.rs +++ b/crates/pallet-domains/src/block_tree.rs @@ -12,7 +12,7 @@ use crate::{ }; #[cfg(not(feature = "std"))] use alloc::vec::Vec; -use frame_support::{ensure, PalletError}; +use frame_support::{PalletError, ensure}; use frame_system::pallet_prelude::BlockNumberFor; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; @@ -629,9 +629,10 @@ pub(crate) fn prune_receipt( mod tests { use super::*; use crate::tests::{ - create_dummy_bundle_with_receipts, create_dummy_receipt, extend_block_tree, - extend_block_tree_from_zero, get_block_tree_node_at, new_test_ext_with_extensions, - register_genesis_domain, run_to_block, BlockTreePruningDepth, Domains, Test, + BlockTreePruningDepth, Domains, Test, create_dummy_bundle_with_receipts, + create_dummy_receipt, extend_block_tree, extend_block_tree_from_zero, + get_block_tree_node_at, new_test_ext_with_extensions, register_genesis_domain, + run_to_block, }; use crate::{FrozenDomains, RawOrigin as DomainOrigin}; use frame_support::dispatch::RawOrigin; @@ -781,11 +782,10 @@ mod tests { verify_execution_receipt::(domain_id, &pruned_receipt), Error::PrunedReceipt ); - assert!(ConsensusBlockHash::::get( - domain_id, - pruned_receipt.consensus_block_number, - ) - .is_none()); + assert!( + ConsensusBlockHash::::get(domain_id, pruned_receipt.consensus_block_number,) + .is_none() + ); }); } @@ -1091,11 +1091,13 @@ mod tests { let mut invalid_execution_trace_receipt = next_receipt; // Receipt with only one element in execution trace vector - invalid_execution_trace_receipt.execution_trace = vec![invalid_execution_trace_receipt - .execution_trace - .first() - .cloned() - .expect("First element should be there; qed")]; + invalid_execution_trace_receipt.execution_trace = vec![ + invalid_execution_trace_receipt + .execution_trace + .first() + .cloned() + .expect("First element should be there; qed"), + ]; assert_err!( verify_execution_receipt::(domain_id, &invalid_execution_trace_receipt), Error::InvalidExecutionTrace diff --git a/crates/pallet-domains/src/bundle_storage_fund.rs b/crates/pallet-domains/src/bundle_storage_fund.rs index e18f12bcc68..1ebbfcb53eb 100644 --- a/crates/pallet-domains/src/bundle_storage_fund.rs +++ b/crates/pallet-domains/src/bundle_storage_fund.rs @@ -3,15 +3,15 @@ use crate::staking::NewDeposit; use crate::staking_epoch::mint_into_treasury; use crate::{BalanceOf, Config, Event, HoldIdentifier, Operators, Pallet}; +use frame_support::PalletError; +use frame_support::traits::Get; use frame_support::traits::fungible::{Inspect, Mutate, MutateHold}; use frame_support::traits::tokens::{Fortitude, Precision, Preservation}; -use frame_support::traits::Get; -use frame_support::PalletError; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_domains::OperatorId; -use sp_runtime::traits::{AccountIdConversion, CheckedSub, Zero}; use sp_runtime::Perbill; +use sp_runtime::traits::{AccountIdConversion, CheckedSub, Zero}; use sp_std::collections::btree_map::BTreeMap; use subspace_runtime_primitives::StorageFee; diff --git a/crates/pallet-domains/src/domain_registry.rs b/crates/pallet-domains/src/domain_registry.rs index f6dc78a0e6a..80e2a44b5a9 100644 --- a/crates/pallet-domains/src/domain_registry.rs +++ b/crates/pallet-domains/src/domain_registry.rs @@ -8,8 +8,8 @@ use crate::pallet::{DomainStakingSummary, NextEVMChainId}; use crate::runtime_registry::DomainRuntimeInfo; use crate::staking::StakingSummary; use crate::{ - into_complete_raw_genesis, BalanceOf, Config, DomainHashingFor, DomainRegistry, - DomainSudoCalls, ExecutionReceiptOf, HoldIdentifier, NextDomainId, RuntimeRegistry, + BalanceOf, Config, DomainHashingFor, DomainRegistry, DomainSudoCalls, ExecutionReceiptOf, + HoldIdentifier, NextDomainId, RuntimeRegistry, into_complete_raw_genesis, }; #[cfg(not(feature = "std"))] use alloc::string::String; @@ -19,18 +19,18 @@ use domain_runtime_primitives::MultiAccountId; use frame_support::traits::fungible::{Inspect, Mutate, MutateHold}; use frame_support::traits::tokens::{Fortitude, Precision, Preservation}; use frame_support::weights::Weight; -use frame_support::{ensure, PalletError}; +use frame_support::{PalletError, ensure}; use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_core::Get; use sp_domains::{ - calculate_max_bundle_weight_and_size, derive_domain_block_hash, DomainBundleLimit, DomainId, - DomainRuntimeConfig, DomainSudoCall, DomainsDigestItem, DomainsTransfersTracker, - OnDomainInstantiated, OperatorAllowList, RuntimeId, RuntimeType, + DomainBundleLimit, DomainId, DomainRuntimeConfig, DomainSudoCall, DomainsDigestItem, + DomainsTransfersTracker, OnDomainInstantiated, OperatorAllowList, RuntimeId, RuntimeType, + calculate_max_bundle_weight_and_size, derive_domain_block_hash, }; -use sp_runtime::traits::{CheckedAdd, Zero}; use sp_runtime::DigestItem; +use sp_runtime::traits::{CheckedAdd, Zero}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -384,7 +384,7 @@ pub(crate) fn do_update_domain_allow_list( #[cfg(test)] mod tests { use super::*; - use crate::tests::{new_test_ext, Test, TEST_RUNTIME_APIS}; + use crate::tests::{TEST_RUNTIME_APIS, Test, new_test_ext}; use domain_runtime_primitives::{AccountId20, AccountId20Converter}; use frame_support::traits::Currency; use frame_support::{assert_err, assert_ok}; @@ -393,7 +393,7 @@ mod tests { use sp_domains::{EvmDomainRuntimeConfig, EvmType, PermissionedActionAllowedBy, RuntimeObject}; use sp_runtime::traits::Convert; use sp_std::vec; - use sp_version::{create_apis_vec, RuntimeVersion}; + use sp_version::{RuntimeVersion, create_apis_vec}; use subspace_runtime_primitives::SSC; type Balances = pallet_balances::Pallet; diff --git a/crates/pallet-domains/src/extensions.rs b/crates/pallet-domains/src/extensions.rs index d198092d09b..689b0960151 100644 --- a/crates/pallet-domains/src/extensions.rs +++ b/crates/pallet-domains/src/extensions.rs @@ -8,8 +8,8 @@ use frame_support::weights::Weight; use frame_system::pallet_prelude::RuntimeCallFor; use parity_scale_codec::{Decode, Encode}; use scale_info::prelude::fmt; -use sp_domains_fraud_proof::weights::fraud_proof_verification_weights; use sp_domains_fraud_proof::InvalidTransactionCode; +use sp_domains_fraud_proof::weights::fraud_proof_verification_weights; use sp_runtime::impl_tx_ext_default; use sp_runtime::traits::{ AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Get, Implication, diff --git a/crates/pallet-domains/src/lib.rs b/crates/pallet-domains/src/lib.rs index d44bed1ba30..4790dc8ad01 100644 --- a/crates/pallet-domains/src/lib.rs +++ b/crates/pallet-domains/src/lib.rs @@ -21,13 +21,13 @@ pub mod weights; extern crate alloc; -use crate::block_tree::{verify_execution_receipt, Error as BlockTreeError}; +use crate::block_tree::{Error as BlockTreeError, verify_execution_receipt}; use crate::bundle_storage_fund::{charge_bundle_storage_fee, storage_fund_account}; use crate::domain_registry::{DomainConfig, Error as DomainRegistryError}; use crate::runtime_registry::into_complete_raw_genesis; #[cfg(feature = "runtime-benchmarks")] pub use crate::staking::do_register_operator; -use crate::staking::{do_reward_operators, OperatorStatus}; +use crate::staking::{OperatorStatus, do_reward_operators}; use crate::staking_epoch::EpochTransitionResult; use crate::weights::WeightInfo; #[cfg(not(feature = "std"))] @@ -48,15 +48,15 @@ use frame_system::pallet_prelude::*; pub use pallet::*; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -use sp_consensus_subspace::consensus::is_proof_of_time_valid; use sp_consensus_subspace::WrappedPotOutput; +use sp_consensus_subspace::consensus::is_proof_of_time_valid; use sp_core::H256; use sp_domains::bundle_producer_election::BundleProducerElectionParams; use sp_domains::{ - ChainId, DomainBundleLimit, DomainId, DomainInstanceData, ExecutionReceipt, OpaqueBundle, - OperatorId, OperatorPublicKey, OperatorRewardSource, OperatorSignature, ProofOfElection, - RuntimeId, SealedSingletonReceipt, DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT, - EMPTY_EXTRINSIC_ROOT, + ChainId, DOMAIN_EXTRINSICS_SHUFFLING_SEED_SUBJECT, DomainBundleLimit, DomainId, + DomainInstanceData, EMPTY_EXTRINSIC_ROOT, ExecutionReceipt, OpaqueBundle, OperatorId, + OperatorPublicKey, OperatorRewardSource, OperatorSignature, ProofOfElection, RuntimeId, + SealedSingletonReceipt, }; use sp_domains_fraud_proof::fraud_proof::{ DomainRuntimeCodeAt, FraudProof, FraudProofVariant, InvalidBlockFeesProof, @@ -200,45 +200,46 @@ pub(crate) type StateRootOf = <::Hashing as Hash>: #[expect(clippy::useless_conversion, reason = "Macro-generated")] #[frame_support::pallet] mod pallet { + #[cfg(not(feature = "runtime-benchmarks"))] + use crate::DomainHashingFor; + #[cfg(not(feature = "runtime-benchmarks"))] + use crate::MAX_NOMINATORS_TO_SLASH; #[cfg(not(feature = "runtime-benchmarks"))] use crate::block_tree::AcceptedReceiptType; use crate::block_tree::{ - execution_receipt_type, process_execution_receipt, prune_receipt, Error as BlockTreeError, - ReceiptType, + Error as BlockTreeError, ReceiptType, execution_receipt_type, process_execution_receipt, + prune_receipt, }; + use crate::bundle_storage_fund::Error as BundleStorageFundError; #[cfg(not(feature = "runtime-benchmarks"))] use crate::bundle_storage_fund::refund_storage_fee; - use crate::bundle_storage_fund::Error as BundleStorageFundError; use crate::domain_registry::{ - do_instantiate_domain, do_update_domain_allow_list, DomainConfigParams, DomainObject, - Error as DomainRegistryError, + DomainConfigParams, DomainObject, Error as DomainRegistryError, do_instantiate_domain, + do_update_domain_allow_list, }; use crate::runtime_registry::{ + DomainRuntimeUpgradeEntry, Error as RuntimeRegistryError, ScheduledRuntimeUpgrade, do_register_runtime, do_schedule_runtime_upgrade, do_upgrade_runtimes, - register_runtime_at_genesis, DomainRuntimeUpgradeEntry, Error as RuntimeRegistryError, - ScheduledRuntimeUpgrade, + register_runtime_at_genesis, }; #[cfg(not(feature = "runtime-benchmarks"))] use crate::staking::do_reward_operators; use crate::staking::{ - do_deregister_operator, do_mark_operators_as_slashed, do_nominate_operator, - do_register_operator, do_unlock_funds, do_unlock_nominator, do_withdraw_stake, Deposit, - DomainEpoch, Error as StakingError, Operator, OperatorConfig, SharePrice, StakingSummary, - WithdrawStake, Withdrawal, + Deposit, DomainEpoch, Error as StakingError, Operator, OperatorConfig, SharePrice, + StakingSummary, WithdrawStake, Withdrawal, do_deregister_operator, + do_mark_operators_as_slashed, do_nominate_operator, do_register_operator, do_unlock_funds, + do_unlock_nominator, do_withdraw_stake, }; #[cfg(not(feature = "runtime-benchmarks"))] use crate::staking_epoch::do_slash_operator; - use crate::staking_epoch::{do_finalize_domain_current_epoch, Error as StakingEpochError}; + use crate::staking_epoch::{Error as StakingEpochError, do_finalize_domain_current_epoch}; use crate::storage_proof::InherentExtrinsicData; use crate::weights::WeightInfo; - #[cfg(not(feature = "runtime-benchmarks"))] - use crate::DomainHashingFor; - #[cfg(not(feature = "runtime-benchmarks"))] - use crate::MAX_NOMINATORS_TO_SLASH; use crate::{ BalanceOf, BlockSlot, BlockTreeNodeFor, DomainBlockNumberFor, ElectionVerificationParams, - ExecutionReceiptOf, FraudProofFor, HoldIdentifier, NominatorId, OpaqueBundleOf, RawOrigin, - ReceiptHashFor, SingletonReceiptOf, StateRootOf, MAX_BUNDLE_PER_BLOCK, STORAGE_VERSION, + ExecutionReceiptOf, FraudProofFor, HoldIdentifier, MAX_BUNDLE_PER_BLOCK, NominatorId, + OpaqueBundleOf, RawOrigin, ReceiptHashFor, STORAGE_VERSION, SingletonReceiptOf, + StateRootOf, }; #[cfg(not(feature = "std"))] use alloc::string::String; @@ -266,11 +267,11 @@ mod pallet { use sp_domains_fraud_proof::fraud_proof_runtime_interface::domain_runtime_call; use sp_domains_fraud_proof::storage_proof::{self, FraudProofStorageKeyProvider}; use sp_domains_fraud_proof::{InvalidTransactionCode, StatelessDomainRuntimeCall}; + use sp_runtime::Saturating; use sp_runtime::traits::{ AtLeast32BitUnsigned, BlockNumberProvider, CheckEqual, CheckedAdd, Header as HeaderT, MaybeDisplay, One, SimpleBitOps, Zero, }; - use sp_runtime::Saturating; use sp_std::boxed::Box; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -447,11 +448,7 @@ mod pallet { type MmrHash: Parameter + Member + Default + Clone; /// MMR proof verifier - type MmrProofVerifier: MmrProofVerifier< - Self::MmrHash, - BlockNumberFor, - StateRootOf, - >; + type MmrProofVerifier: MmrProofVerifier, StateRootOf>; /// Fraud proof storage key provider type FraudProofStorageKeyProvider: FraudProofStorageKeyProvider>; @@ -1161,21 +1158,21 @@ mod pallet { && let Some(block_tree_node) = prune_receipt::(domain_id, receipt_block_number) .map_err(Error::::from)? - { - actual_weight = - actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt( - block_tree_node.operator_ids.len() as u32, - )); - - let bad_receipt_hash = block_tree_node - .execution_receipt - .hash::>(); - do_mark_operators_as_slashed::( - block_tree_node.operator_ids.into_iter(), - SlashedReason::BadExecutionReceipt(bad_receipt_hash), - ) - .map_err(Error::::from)?; - } + { + actual_weight = + actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt( + block_tree_node.operator_ids.len() as u32, + )); + + let bad_receipt_hash = block_tree_node + .execution_receipt + .hash::>(); + do_mark_operators_as_slashed::( + block_tree_node.operator_ids.into_iter(), + SlashedReason::BadExecutionReceipt(bad_receipt_hash), + ) + .map_err(Error::::from)?; + } #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))] let maybe_confirmed_domain_block_info = process_execution_receipt::( @@ -1775,21 +1772,21 @@ mod pallet { && let Some(block_tree_node) = prune_receipt::(domain_id, receipt.domain_block_number) .map_err(Error::::from)? - { - actual_weight = - actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt( - block_tree_node.operator_ids.len() as u32, - )); - - let bad_receipt_hash = block_tree_node - .execution_receipt - .hash::>(); - do_mark_operators_as_slashed::( - block_tree_node.operator_ids.into_iter(), - SlashedReason::BadExecutionReceipt(bad_receipt_hash), - ) - .map_err(Error::::from)?; - } + { + actual_weight = + actual_weight.saturating_add(T::WeightInfo::handle_bad_receipt( + block_tree_node.operator_ids.len() as u32, + )); + + let bad_receipt_hash = block_tree_node + .execution_receipt + .hash::>(); + do_mark_operators_as_slashed::( + block_tree_node.operator_ids.into_iter(), + SlashedReason::BadExecutionReceipt(bad_receipt_hash), + ) + .map_err(Error::::from)?; + } #[cfg_attr(feature = "runtime-benchmarks", allow(unused_variables))] let maybe_confirmed_domain_block_info = process_execution_receipt::( @@ -2208,10 +2205,9 @@ impl Pallet { // NOTE: during `validate_unsigned` this is implicitly checked within `is_proof_of_time_valid` since we // are using quick verification which will return `false` if the `proof-of-time` is not seem by the node // before. - if pre_dispatch - && let Some(future_slot) = T::BlockSlot::future_slot(current_block_number) { - ensure!(slot_number <= *future_slot, BundleError::SlotInTheFuture) - } + if pre_dispatch && let Some(future_slot) = T::BlockSlot::future_slot(current_block_number) { + ensure!(slot_number <= *future_slot, BundleError::SlotInTheFuture) + } // Check if the bundle is built too long time ago and beyond `T::BundleLongevity` number of consensus blocks. let produced_after_block_number = @@ -2660,9 +2656,10 @@ impl Pallet { operator_id: &OperatorId, ) -> Result<(BalanceOf, BalanceOf), BundleError> { if let Some(pending_election_params) = LastEpochStakingDistribution::::get(domain_id) - && let Some(operator_stake) = pending_election_params.operators.get(operator_id) { - return Ok((*operator_stake, pending_election_params.total_domain_stake)); - } + && let Some(operator_stake) = pending_election_params.operators.get(operator_id) + { + return Ok((*operator_stake, pending_election_params.total_domain_stake)); + } let domain_stake_summary = DomainStakingSummary::::get(domain_id).ok_or(BundleError::InvalidDomainId)?; let operator_stake = domain_stake_summary diff --git a/crates/pallet-domains/src/runtime_registry.rs b/crates/pallet-domains/src/runtime_registry.rs index 21b64c21651..092c8c67c26 100644 --- a/crates/pallet-domains/src/runtime_registry.rs +++ b/crates/pallet-domains/src/runtime_registry.rs @@ -12,20 +12,20 @@ use alloc::string::String; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use domain_runtime_primitives::{AccountId20, EVMChainId, MultiAccountId, TryConvertBack}; -use frame_support::{ensure, PalletError}; -use frame_system::pallet_prelude::*; +use frame_support::{PalletError, ensure}; use frame_system::AccountInfo; +use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_core::crypto::AccountId32; use sp_core::Hasher; +use sp_core::crypto::AccountId32; use sp_domains::storage::{RawGenesis, StorageData, StorageKey}; use sp_domains::{ AutoIdDomainRuntimeConfig, DomainId, DomainRuntimeConfig, DomainsDigestItem, EvmDomainRuntimeConfig, RuntimeId, RuntimeObject, RuntimeType, }; -use sp_runtime::traits::{CheckedAdd, Zero}; use sp_runtime::DigestItem; +use sp_runtime::traits::{CheckedAdd, Zero}; use sp_std::vec; use sp_version::RuntimeVersion; @@ -393,12 +393,12 @@ pub(crate) fn do_upgrade_runtimes(at: BlockNumberFor) { #[cfg(test)] mod tests { + use crate::Error; use crate::pallet::{NextRuntimeId, RuntimeRegistry, ScheduledRuntimeUpgrades}; use crate::runtime_registry::Error as RuntimeRegistryError; use crate::tests::{ - new_test_ext, Domains, ReadRuntimeVersion, System, Test, TEST_RUNTIME_APIS, + Domains, ReadRuntimeVersion, System, TEST_RUNTIME_APIS, Test, new_test_ext, }; - use crate::Error; use domain_runtime_primitives::Hash; use frame_support::dispatch::RawOrigin; use frame_support::traits::OnInitialize; @@ -408,7 +408,7 @@ mod tests { use sp_domains::{DomainsDigestItem, RuntimeId, RuntimeObject, RuntimeType}; use sp_runtime::traits::BlockNumberProvider; use sp_runtime::{Digest, DispatchError}; - use sp_version::{create_apis_vec, RuntimeVersion}; + use sp_version::{RuntimeVersion, create_apis_vec}; #[test] fn create_domain_runtime() { diff --git a/crates/pallet-domains/src/staking.rs b/crates/pallet-domains/src/staking.rs index 2fa0e2b1123..50dbe3112a1 100644 --- a/crates/pallet-domains/src/staking.rs +++ b/crates/pallet-domains/src/staking.rs @@ -16,11 +16,11 @@ use crate::{ }; use frame_support::traits::fungible::{Inspect, MutateHold}; use frame_support::traits::tokens::{Fortitude, Precision, Preservation}; -use frame_support::{ensure, PalletError}; +use frame_support::{PalletError, ensure}; use frame_system::pallet_prelude::BlockNumberFor; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_core::{sr25519, Get}; +use sp_core::{Get, sr25519}; use sp_domains::{DomainId, EpochIndex, OperatorId, OperatorPublicKey, OperatorRewardSource}; use sp_runtime::traits::{CheckedAdd, CheckedSub, Zero}; use sp_runtime::{Perbill, Percent, Perquintill, Saturating}; @@ -1508,22 +1508,22 @@ pub(crate) mod tests { NominatorCount, OperatorIdOwner, Operators, PendingSlashes, Withdrawals, }; use crate::staking::{ - do_convert_previous_epoch_withdrawal, do_mark_operators_as_slashed, do_nominate_operator, - do_reward_operators, do_unlock_funds, do_withdraw_stake, DomainEpoch, - Error as StakingError, Operator, OperatorConfig, OperatorStatus, StakingSummary, - WithdrawStake, + DomainEpoch, Error as StakingError, Operator, OperatorConfig, OperatorStatus, + StakingSummary, WithdrawStake, do_convert_previous_epoch_withdrawal, + do_mark_operators_as_slashed, do_nominate_operator, do_reward_operators, do_unlock_funds, + do_withdraw_stake, }; use crate::staking_epoch::{do_finalize_domain_current_epoch, do_slash_operator}; - use crate::tests::{new_test_ext, ExistentialDeposit, RuntimeOrigin, Test}; + use crate::tests::{ExistentialDeposit, RuntimeOrigin, Test, new_test_ext}; use crate::{ - bundle_storage_fund, AllowedDefaultSharePriceEpoch, BalanceOf, Error, NominatorId, - OperatorEpochSharePrice, SlashedReason, MAX_NOMINATORS_TO_SLASH, + AllowedDefaultSharePriceEpoch, BalanceOf, Error, MAX_NOMINATORS_TO_SLASH, NominatorId, + OperatorEpochSharePrice, SlashedReason, bundle_storage_fund, }; - use frame_support::traits::fungible::Mutate; use frame_support::traits::Currency; + use frame_support::traits::fungible::Mutate; use frame_support::weights::Weight; use frame_support::{assert_err, assert_ok}; - use sp_core::{sr25519, Pair}; + use sp_core::{Pair, sr25519}; use sp_domains::{ DomainId, OperatorAllowList, OperatorId, OperatorPair, OperatorPublicKey, OperatorRewardSource, @@ -1551,8 +1551,8 @@ pub(crate) mod tests { ) -> (OperatorId, OperatorConfig>) { nominators.insert(operator_account, (operator_free_balance, operator_stake)); for nominator in &nominators { - Balances::set_balance(nominator.0, nominator.1 .0); - assert_eq!(Balances::usable_balance(nominator.0), nominator.1 .0); + Balances::set_balance(nominator.0, nominator.1.0); + assert_eq!(Balances::usable_balance(nominator.0), nominator.1.0); } nominators.remove(&operator_account); @@ -1609,7 +1609,7 @@ pub(crate) mod tests { let operator_id = NextOperatorId::::get() - 1; let mut expected_nominator_count = 0; for nominator in nominators { - if nominator.1 .1.is_zero() { + if nominator.1.1.is_zero() { continue; } @@ -1617,7 +1617,7 @@ pub(crate) mod tests { let res = Domains::nominate_operator( RuntimeOrigin::signed(nominator.0), operator_id, - nominator.1 .1, + nominator.1.1, ); assert_ok!(res); } diff --git a/crates/pallet-domains/src/staking_epoch.rs b/crates/pallet-domains/src/staking_epoch.rs index 4b537aef51b..7da06c564fe 100644 --- a/crates/pallet-domains/src/staking_epoch.rs +++ b/crates/pallet-domains/src/staking_epoch.rs @@ -6,24 +6,24 @@ use crate::pallet::{ Withdrawals, }; use crate::staking::{ - do_cleanup_operator, do_convert_previous_epoch_deposits, do_convert_previous_epoch_withdrawal, DomainEpoch, Error as TransitionError, OperatorStatus, SharePrice, WithdrawalInShares, + do_cleanup_operator, do_convert_previous_epoch_deposits, do_convert_previous_epoch_withdrawal, }; use crate::{ - bundle_storage_fund, BalanceOf, Config, DepositOnHold, ElectionVerificationParams, Event, - HoldIdentifier, OperatorEpochSharePrice, Pallet, + BalanceOf, Config, DepositOnHold, ElectionVerificationParams, Event, HoldIdentifier, + OperatorEpochSharePrice, Pallet, bundle_storage_fund, }; +use frame_support::PalletError; use frame_support::traits::fungible::{Inspect, Mutate, MutateHold}; use frame_support::traits::tokens::{ DepositConsequence, Fortitude, Precision, Provenance, Restriction, }; -use frame_support::PalletError; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_core::Get; use sp_domains::{DomainId, EpochIndex, OperatorId}; -use sp_runtime::traits::{CheckedAdd, CheckedSub, One, Zero}; use sp_runtime::Saturating; +use sp_runtime::traits::{CheckedAdd, CheckedSub, One, Zero}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -534,15 +534,15 @@ mod tests { Deposits, DomainStakingSummary, HeadDomainNumber, LastEpochStakingDistribution, NominatorCount, OperatorIdOwner, Operators, Withdrawals, }; - use crate::staking::tests::{register_operator, Share}; + use crate::staking::tests::{Share, register_operator}; use crate::staking::{ - do_deregister_operator, do_nominate_operator, do_reward_operators, do_unlock_nominator, - do_withdraw_stake, Error as TransitionError, WithdrawStake, + Error as TransitionError, WithdrawStake, do_deregister_operator, do_nominate_operator, + do_reward_operators, do_unlock_nominator, do_withdraw_stake, }; use crate::staking_epoch::{ do_finalize_domain_current_epoch, operator_take_reward_tax_and_stake, }; - use crate::tests::{new_test_ext, Test}; + use crate::tests::{Test, new_test_ext}; use crate::{BalanceOf, Config, HoldIdentifier, NominatorId}; #[cfg(not(feature = "std"))] use alloc::vec; diff --git a/crates/pallet-domains/src/tests.rs b/crates/pallet-domains/src/tests.rs index 87de94ee076..300d1074785 100644 --- a/crates/pallet-domains/src/tests.rs +++ b/crates/pallet-domains/src/tests.rs @@ -1,4 +1,4 @@ -use crate::block_tree::{verify_execution_receipt, BlockTreeNode}; +use crate::block_tree::{BlockTreeNode, verify_execution_receipt}; use crate::domain_registry::{DomainConfig, DomainConfigParams, DomainObject}; use crate::pallet::OperatorIdOwner; use crate::runtime_registry::ScheduledRuntimeUpgrade; @@ -11,13 +11,13 @@ use crate::{ RawOrigin as DomainOrigin, RuntimeRegistry, ScheduledRuntimeUpgrades, }; use core::mem; -use domain_runtime_primitives::opaque::Header as DomainHeader; use domain_runtime_primitives::BlockNumber as DomainBlockNumber; +use domain_runtime_primitives::opaque::Header as DomainHeader; use frame_support::dispatch::{DispatchInfo, RawOrigin}; use frame_support::traits::{ConstU64, Currency, Hooks, VariantCount}; use frame_support::weights::constants::ParityDbWeight; use frame_support::weights::{IdentityFee, Weight}; -use frame_support::{assert_err, assert_ok, derive_impl, parameter_types, PalletId}; +use frame_support::{PalletId, assert_err, assert_ok, derive_impl, parameter_types}; use frame_system::mocking::MockUncheckedExtrinsic; use frame_system::pallet_prelude::*; use pallet_subspace::NormalEraChange; @@ -33,7 +33,7 @@ use sp_domains::{ SealedBundleHeader, }; use sp_domains_fraud_proof::fraud_proof::FraudProof; -use sp_runtime::generic::{Preamble, EXTRINSIC_FORMAT_VERSION}; +use sp_runtime::generic::{EXTRINSIC_FORMAT_VERSION, Preamble}; use sp_runtime::traits::{ AccountIdConversion, BlakeTwo256, BlockNumberProvider, Bounded, ConstU16, Hash as HashT, IdentityLookup, One, Zero, @@ -41,14 +41,14 @@ use sp_runtime::traits::{ use sp_runtime::transaction_validity::TransactionValidityError; use sp_runtime::type_with_default::TypeWithDefault; use sp_runtime::{BuildStorage, OpaqueExtrinsic}; -use sp_version::{create_apis_vec, ApiId, RuntimeVersion}; +use sp_version::{ApiId, RuntimeVersion, create_apis_vec}; use std::num::NonZeroU64; use subspace_core_primitives::pieces::Piece; use subspace_core_primitives::segments::HistorySize; use subspace_core_primitives::solutions::SolutionRange; use subspace_core_primitives::{SlotNumber, U256 as P256}; use subspace_runtime_primitives::{ - ConsensusEventSegmentSize, HoldIdentifier, Moment, Nonce, StorageFee, SSC, + ConsensusEventSegmentSize, HoldIdentifier, Moment, Nonce, SSC, StorageFee, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; diff --git a/crates/pallet-rewards/src/lib.rs b/crates/pallet-rewards/src/lib.rs index e64b7a6beec..8e9fe0e1f17 100644 --- a/crates/pallet-rewards/src/lib.rs +++ b/crates/pallet-rewards/src/lib.rs @@ -20,8 +20,8 @@ use log::warn; pub use pallet::*; use serde::{Deserialize, Serialize}; use sp_core::U256; -use sp_runtime::traits::{CheckedSub, Zero}; use sp_runtime::Saturating; +use sp_runtime::traits::{CheckedSub, Zero}; use subspace_runtime_primitives::{BlockNumber, FindBlockRewardAddress, FindVotingRewardAddresses}; type BalanceOf = @@ -311,15 +311,16 @@ impl Pallet { } if let Some(block_author) = maybe_block_author - && !block_reward.is_zero() { - let _imbalance = T::Currency::deposit_creating(&block_author, block_reward); - T::OnReward::on_reward(block_author.clone(), block_reward); - - Self::deposit_event(Event::BlockReward { - block_author, - reward: block_reward, - }); - } + && !block_reward.is_zero() + { + let _imbalance = T::Currency::deposit_creating(&block_author, block_reward); + T::OnReward::on_reward(block_author.clone(), block_reward); + + Self::deposit_event(Event::BlockReward { + block_author, + reward: block_reward, + }); + } if old_remaining_issuance != new_remaining_issuance { RemainingIssuance::::put(new_remaining_issuance); diff --git a/crates/pallet-rewards/src/mock.rs b/crates/pallet-rewards/src/mock.rs index 2e026d76743..ff1f662a5c9 100644 --- a/crates/pallet-rewards/src/mock.rs +++ b/crates/pallet-rewards/src/mock.rs @@ -1,5 +1,5 @@ use frame_support::derive_impl; -use frame_support::traits::{ConstU128, ConstU32}; +use frame_support::traits::{ConstU32, ConstU128}; use sp_runtime::traits::parameter_types; use subspace_runtime_primitives::{ ConsensusEventSegmentSize, FindBlockRewardAddress, FindVotingRewardAddresses, RewardsEnabled, diff --git a/crates/pallet-rewards/src/tests.rs b/crates/pallet-rewards/src/tests.rs index df3ebd93ddf..377b56188ec 100644 --- a/crates/pallet-rewards/src/tests.rs +++ b/crates/pallet-rewards/src/tests.rs @@ -1,5 +1,5 @@ -use crate::mock::Test; use crate::RewardPoint; +use crate::mock::Test; type Pallet = crate::Pallet; diff --git a/crates/pallet-subspace-mmr/src/lib.rs b/crates/pallet-subspace-mmr/src/lib.rs index e6ccbc2d90f..f2b0b9851cf 100644 --- a/crates/pallet-subspace-mmr/src/lib.rs +++ b/crates/pallet-subspace-mmr/src/lib.rs @@ -12,8 +12,8 @@ use sp_subspace_mmr::{LeafDataV0, MmrLeaf}; #[frame_support::pallet] mod pallet { - use frame_support::pallet_prelude::*; use frame_support::Parameter; + use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::BlockNumberFor; use sp_core::H256; diff --git a/crates/pallet-subspace/src/benchmarking.rs b/crates/pallet-subspace/src/benchmarking.rs index 29c2b4b6c52..3eb1be99518 100644 --- a/crates/pallet-subspace/src/benchmarking.rs +++ b/crates/pallet-subspace/src/benchmarking.rs @@ -22,13 +22,13 @@ mod benchmarks { use sp_consensus_subspace::{SignedVote, Vote}; use sp_std::boxed::Box; use sp_std::num::NonZeroU32; + use subspace_core_primitives::PublicKey; use subspace_core_primitives::hashes::Blake3Hash; use subspace_core_primitives::pot::{PotCheckpoints, PotOutput}; use subspace_core_primitives::segments::{ ArchivedBlockProgress, LastArchivedBlock, SegmentHeader, SegmentIndex, }; use subspace_core_primitives::solutions::{RewardSignature, Solution, SolutionRange}; - use subspace_core_primitives::PublicKey; const SEED: u32 = 0; diff --git a/crates/pallet-subspace/src/extensions.rs b/crates/pallet-subspace/src/extensions.rs index 340a4213a08..f77efffb30e 100644 --- a/crates/pallet-subspace/src/extensions.rs +++ b/crates/pallet-subspace/src/extensions.rs @@ -7,12 +7,13 @@ pub mod weights; use crate::extensions::weights::WeightInfo; use crate::pallet::Call as SubspaceCall; use crate::{Config, Origin, Pallet as Subspace}; -use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight}; use frame_support::RuntimeDebugNoBound; +use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight}; use frame_system::pallet_prelude::{BlockNumberFor, RuntimeCallFor}; use parity_scale_codec::{Decode, Encode}; use scale_info::prelude::fmt; use sp_consensus_subspace::SignedVote; +use sp_runtime::DispatchResult; use sp_runtime::traits::{ AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication, PostDispatchInfoOf, TransactionExtension, ValidateResult, @@ -20,7 +21,6 @@ use sp_runtime::traits::{ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction, }; -use sp_runtime::DispatchResult; /// Trait to convert Runtime call to possible Subspace call. pub trait MaybeSubspaceCall @@ -135,7 +135,7 @@ where ValidTransaction::default(), ExtensionWeightData::Skipped, origin, - )) + )); } }; diff --git a/crates/pallet-subspace/src/lib.rs b/crates/pallet-subspace/src/lib.rs index 0f0913af35c..7062e747d74 100644 --- a/crates/pallet-subspace/src/lib.rs +++ b/crates/pallet-subspace/src/lib.rs @@ -37,13 +37,13 @@ use sp_consensus_subspace::digests::CompatibleDigestItem; use sp_consensus_subspace::{ PotParameters, PotParametersChange, SignedVote, Vote, WrappedPotOutput, }; +use sp_runtime::Weight; use sp_runtime::generic::DigestItem; use sp_runtime::traits::{BlockNumberProvider, CheckedSub, Hash, One, Zero}; use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionPriority, TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction, }; -use sp_runtime::Weight; use sp_std::collections::btree_map::BTreeMap; use sp_std::prelude::*; use subspace_core_primitives::pieces::PieceOffset; @@ -53,12 +53,12 @@ use subspace_core_primitives::segments::{ }; use subspace_core_primitives::solutions::{RewardSignature, SolutionRange}; use subspace_core_primitives::{ - BlockHash, PublicKey, ScalarBytes, SlotNumber, REWARD_SIGNING_CONTEXT, + BlockHash, PublicKey, REWARD_SIGNING_CONTEXT, ScalarBytes, SlotNumber, }; use subspace_runtime_primitives::CreateUnsigned; use subspace_verification::{ - check_reward_signature, derive_next_solution_range, derive_pot_entropy, PieceCheckParams, - VerifySolutionParams, + PieceCheckParams, VerifySolutionParams, check_reward_signature, derive_next_solution_range, + derive_pot_entropy, }; /// Trigger an era change, if any should take place. @@ -114,16 +114,16 @@ struct VoteVerificationData { #[frame_support::pallet] pub mod pallet { use super::{EraChangeTrigger, ExtensionWeightInfo, VoteVerificationData}; - use crate::weights::WeightInfo; use crate::RawOrigin; + use crate::weights::WeightInfo; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; use sp_consensus_slots::Slot; - use sp_consensus_subspace::digests::CompatibleDigestItem; - use sp_consensus_subspace::inherents::{InherentError, InherentType, INHERENT_IDENTIFIER}; use sp_consensus_subspace::SignedVote; - use sp_runtime::traits::One; + use sp_consensus_subspace::digests::CompatibleDigestItem; + use sp_consensus_subspace::inherents::{INHERENT_IDENTIFIER, InherentError, InherentType}; use sp_runtime::DigestItem; + use sp_runtime::traits::One; use sp_std::collections::btree_map::BTreeMap; use sp_std::num::NonZeroU32; use sp_std::prelude::*; @@ -789,13 +789,14 @@ impl Pallet { .replace(next_voting_solution_range); if let Some(solution_range_for_rewards) = EnableRewardsBelowSolutionRange::::get() - && next_solution_range <= solution_range_for_rewards { - EnableRewardsBelowSolutionRange::::take(); + && next_solution_range <= solution_range_for_rewards + { + EnableRewardsBelowSolutionRange::::take(); - let next_block_number = - frame_system::Pallet::::current_block_number() + One::one(); - EnableRewards::::put(next_block_number); - } + let next_block_number = + frame_system::Pallet::::current_block_number() + One::one(); + EnableRewards::::put(next_block_number); + } }); EraStartSlot::::put(current_slot); @@ -948,22 +949,23 @@ impl Pallet { // Update target slot for entropy injection once we know it if let Some(entropy_source_block_number) = maybe_entropy_source_block_number - && let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number) { - let target_slot = pre_digest - .slot() - .saturating_add(pot_entropy_injection_delay); - debug!("Pot entropy injection will happen at slot {target_slot:?}",); - entropy_value.target_slot.replace(target_slot); - - // Schedule PoT slot iterations update at the same slot as entropy - if let Some(update) = &mut pot_slot_iterations.update - && update.target_slot.is_none() - { - debug!("Scheduling PoT slots update to happen at slot {target_slot:?}"); - update.target_slot.replace(target_slot); - PotSlotIterations::::put(pot_slot_iterations); - } + && let Some(entropy_value) = entropy.get_mut(&entropy_source_block_number) + { + let target_slot = pre_digest + .slot() + .saturating_add(pot_entropy_injection_delay); + debug!("Pot entropy injection will happen at slot {target_slot:?}",); + entropy_value.target_slot.replace(target_slot); + + // Schedule PoT slot iterations update at the same slot as entropy + if let Some(update) = &mut pot_slot_iterations.update + && update.target_slot.is_none() + { + debug!("Scheduling PoT slots update to happen at slot {target_slot:?}"); + update.target_slot.replace(target_slot); + PotSlotIterations::::put(pot_slot_iterations); } + } PotEntropy::::put(entropy.clone()); } @@ -1003,11 +1005,11 @@ impl Pallet { // Clean up old values we'll no longer need if let Some(entry) = entropy.first_entry() && let Some(target_slot) = entry.get().target_slot - && target_slot < current_slot - { - entry.remove(); - PotEntropy::::put(entropy); - } + && target_slot < current_slot + { + entry.remove(); + PotEntropy::::put(entropy); + } } } @@ -1596,26 +1598,27 @@ fn check_vote( == Some(&key); if !is_equivocating - && let Some((_reward_address, signature)) = ParentBlockVoters::::get().get(&key) { - if signature != &signed_vote.signature { - is_equivocating = true; - } else { - // The same vote should never be included more than once - return Err(CheckVoteError::DuplicateVote); - } + && let Some((_reward_address, signature)) = ParentBlockVoters::::get().get(&key) + { + if signature != &signed_vote.signature { + is_equivocating = true; + } else { + // The same vote should never be included more than once + return Err(CheckVoteError::DuplicateVote); } + } if !is_equivocating && let Some((_reward_address, signature)) = CurrentBlockVoters::::get().unwrap_or_default().get(&key) - { - if signature != &signed_vote.signature { - is_equivocating = true; - } else { - // The same vote should never be included more than once - return Err(CheckVoteError::DuplicateVote); - } + { + if signature != &signed_vote.signature { + is_equivocating = true; + } else { + // The same vote should never be included more than once + return Err(CheckVoteError::DuplicateVote); } + } if pre_dispatch { // During `pre_dispatch` call put farmer into the list of reward receivers. @@ -1643,10 +1646,11 @@ fn check_vote( CurrentBlockAuthorInfo::::mutate(|maybe_info| { if let Some((public_key, _sector_index, _piece_offset, _chunk, _slot, reward_address)) = maybe_info - && public_key == &offender { - // Revoke reward for block author - reward_address.take(); - } + && public_key == &offender + { + // Revoke reward for block author + reward_address.take(); + } }); CurrentBlockVoters::::mutate(|current_reward_receivers| { @@ -1734,9 +1738,10 @@ impl subspace_runtime_primitives::FindBlockRewardAddress::get() - && frame_system::Pallet::::current_block_number() >= height { - return reward_address; - } + && frame_system::Pallet::::current_block_number() >= height + { + return reward_address; + } None }, @@ -1748,15 +1753,16 @@ impl subspace_runtime_primitives::FindVotingRewardAddresses Vec { // Rewards might be disabled, in which case no voting reward if let Some(height) = EnableRewards::::get() - && frame_system::Pallet::::current_block_number() >= height { - // It is possible that this is called during initialization when current block - // voters are already moved into parent block voters, handle it accordingly - return CurrentBlockVoters::::get() - .unwrap_or_else(ParentBlockVoters::::get) - .into_values() - .filter_map(|(reward_address, _signature)| reward_address) - .collect(); - } + && frame_system::Pallet::::current_block_number() >= height + { + // It is possible that this is called during initialization when current block + // voters are already moved into parent block voters, handle it accordingly + return CurrentBlockVoters::::get() + .unwrap_or_else(ParentBlockVoters::::get) + .into_values() + .filter_map(|(reward_address, _signature)| reward_address) + .collect(); + } Vec::new() } diff --git a/crates/pallet-subspace/src/mock.rs b/crates/pallet-subspace/src/mock.rs index 72b2f79055b..2420e9b9b46 100644 --- a/crates/pallet-subspace/src/mock.rs +++ b/crates/pallet-subspace/src/mock.rs @@ -1,7 +1,7 @@ //! Test utilities use crate::{self as pallet_subspace, AllowAuthoringBy, Config, EnableRewardsAt, NormalEraChange}; -use frame_support::traits::{ConstU128, ConstU16, OnInitialize}; +use frame_support::traits::{ConstU16, ConstU128, OnInitialize}; use frame_support::{derive_impl, parameter_types}; use futures::executor::block_on; use rand::Rng; @@ -10,8 +10,8 @@ use sp_consensus_slots::Slot; use sp_consensus_subspace::digests::{CompatibleDigestItem, PreDigest, PreDigestPotInfo}; use sp_consensus_subspace::{KzgExtension, PosExtension, PotExtension, SignedVote, Vote}; use sp_io::TestExternalities; -use sp_runtime::testing::{Digest, DigestItem, TestXt}; use sp_runtime::BuildStorage; +use sp_runtime::testing::{Digest, DigestItem, TestXt}; use std::marker::PhantomData; use std::num::{NonZeroU32, NonZeroU64, NonZeroUsize}; use std::simd::Simd; @@ -28,12 +28,12 @@ use subspace_core_primitives::segments::{ SegmentCommitment, SegmentHeader, SegmentIndex, }; use subspace_core_primitives::solutions::{RewardSignature, Solution, SolutionRange}; -use subspace_core_primitives::{BlockNumber, PublicKey, SlotNumber, REWARD_SIGNING_CONTEXT}; +use subspace_core_primitives::{BlockNumber, PublicKey, REWARD_SIGNING_CONTEXT, SlotNumber}; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::auditing::audit_sector_sync; -use subspace_farmer_components::plotting::{plot_sector, CpuRecordsEncoder, PlotSectorOptions}; +use subspace_farmer_components::plotting::{CpuRecordsEncoder, PlotSectorOptions, plot_sector}; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use subspace_proof_of_space::shim::ShimTable; use subspace_proof_of_space::{Table, TableGenerator}; diff --git a/crates/pallet-subspace/src/tests.rs b/crates/pallet-subspace/src/tests.rs index af6b54bd6d1..8a310a26802 100644 --- a/crates/pallet-subspace/src/tests.rs +++ b/crates/pallet-subspace/src/tests.rs @@ -1,14 +1,14 @@ //! Consensus extension module tests for Subspace consensus. use crate::mock::{ - allow_all_pot_extension, create_archived_segment, create_segment_header, create_signed_vote, - go_to_block, new_test_ext, progress_to_block, BlockAuthoringDelay, RuntimeEvent, RuntimeOrigin, - Subspace, System, Test, INITIAL_SOLUTION_RANGE, SLOT_PROBABILITY, + BlockAuthoringDelay, INITIAL_SOLUTION_RANGE, RuntimeEvent, RuntimeOrigin, SLOT_PROBABILITY, + Subspace, System, Test, allow_all_pot_extension, create_archived_segment, + create_segment_header, create_signed_vote, go_to_block, new_test_ext, progress_to_block, }; use crate::{ - pallet, AllowAuthoringByAnyone, Call, CheckVoteError, Config, CurrentBlockAuthorInfo, + AllowAuthoringByAnyone, Call, CheckVoteError, Config, CurrentBlockAuthorInfo, CurrentBlockVoters, EnableRewardsAt, ParentBlockAuthorInfo, ParentBlockVoters, - PotSlotIterations, PotSlotIterationsValue, SegmentCommitment, + PotSlotIterations, PotSlotIterationsValue, SegmentCommitment, pallet, }; use frame_support::{assert_err, assert_ok}; use frame_system::{EventRecord, Phase}; @@ -16,11 +16,11 @@ use rand::prelude::*; use schnorrkel::Keypair; use sp_consensus_slots::Slot; use sp_consensus_subspace::{PotExtension, SolutionRanges}; +use sp_runtime::DispatchError; use sp_runtime::traits::BlockNumberProvider; use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionPriority, TransactionSource, ValidTransaction, }; -use sp_runtime::DispatchError; use std::assert_matches::assert_matches; use std::collections::BTreeMap; use std::num::NonZeroU32; @@ -1439,14 +1439,16 @@ fn allow_authoring_by_anyone_works() { 1, ); // However authoring with a different public key panics (client error) - assert!(std::panic::catch_unwind(|| { - progress_to_block( - &keypair2, - frame_system::Pallet::::current_block_number() + 1, - 1, - ); - }) - .is_err()); + assert!( + std::panic::catch_unwind(|| { + progress_to_block( + &keypair2, + frame_system::Pallet::::current_block_number() + 1, + 1, + ); + }) + .is_err() + ); // Unlock authoring by anyone assert_err!( diff --git a/crates/pallet-transaction-fees/src/lib.rs b/crates/pallet-transaction-fees/src/lib.rs index 8c2d88194ec..008ce89288d 100644 --- a/crates/pallet-transaction-fees/src/lib.rs +++ b/crates/pallet-transaction-fees/src/lib.rs @@ -6,8 +6,8 @@ pub mod weights; -use frame_support::sp_runtime::traits::Zero; use frame_support::sp_runtime::SaturatedConversion; +use frame_support::sp_runtime::traits::Zero; use frame_support::traits::{Currency, Get}; use frame_support::weights::Weight; use frame_system::pallet_prelude::*; diff --git a/crates/sc-consensus-subspace-rpc/src/lib.rs b/crates/sc-consensus-subspace-rpc/src/lib.rs index 70bff5e14ff..6e84b57bcba 100644 --- a/crates/sc-consensus-subspace-rpc/src/lib.rs +++ b/crates/sc-consensus-subspace-rpc/src/lib.rs @@ -3,7 +3,7 @@ #![feature(try_blocks)] use futures::channel::mpsc; -use futures::{future, stream, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, future, stream}; use jsonrpsee::core::async_trait; use jsonrpsee::proc_macros::rpc; use jsonrpsee::types::{ErrorObject, ErrorObjectOwned}; @@ -11,16 +11,16 @@ use jsonrpsee::{Extensions, PendingSubscriptionSink}; use parking_lot::Mutex; use sc_client_api::{AuxStore, BlockBackend}; use sc_consensus_subspace::archiver::{ - recreate_genesis_segment, ArchivedSegmentNotification, ObjectMappingNotification, - SegmentHeadersStore, + ArchivedSegmentNotification, ObjectMappingNotification, SegmentHeadersStore, + recreate_genesis_segment, }; use sc_consensus_subspace::notification::SubspaceNotificationStream; use sc_consensus_subspace::slot_worker::{ NewSlotNotification, RewardSigningNotification, SubspaceSyncOracle, }; -use sc_rpc::utils::{BoundedVecDeque, PendingSubscription}; use sc_rpc::SubscriptionTaskExecutor; -use sc_rpc_api::{check_if_safe, UnsafeRpcError}; +use sc_rpc::utils::{BoundedVecDeque, PendingSubscription}; +use sc_rpc_api::{UnsafeRpcError, check_if_safe}; use sc_utils::mpsc::TracingUnboundedSender; use schnellru::{ByLength, LruMap}; use sp_api::{ApiError, ProvideRuntimeApi}; @@ -48,8 +48,8 @@ use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use subspace_networking::libp2p::Multiaddr; use subspace_rpc_primitives::{ - FarmerAppInfo, ObjectMappingResponse, RewardSignatureResponse, RewardSigningInfo, SlotInfo, - SolutionResponse, MAX_SEGMENT_HEADERS_PER_REQUEST, + FarmerAppInfo, MAX_SEGMENT_HEADERS_PER_REQUEST, ObjectMappingResponse, RewardSignatureResponse, + RewardSigningInfo, SlotInfo, SolutionResponse, }; use tracing::{debug, error, warn}; @@ -528,9 +528,10 @@ where // data structure `sc-consensus-subspace` expects let forward_signature_fut = async move { if let Ok(reward_signature) = response_receiver.await - && let Some(signature) = reward_signature.signature { - let _ = signature_sender.unbounded_send(signature); - } + && let Some(signature) = reward_signature.signature + { + let _ = signature_sender.unbounded_send(signature); + } }; // Run above future with timeout @@ -576,9 +577,10 @@ where let mut reward_signature_senders = reward_signature_senders.lock(); if reward_signature_senders.current_hash == reward_signature.hash.into() - && let Some(mut sender) = reward_signature_senders.senders.pop() { - let _ = sender.send(reward_signature); - } + && let Some(mut sender) = reward_signature_senders.senders.pop() + { + let _ = sender.send(reward_signature); + } Ok(()) } @@ -702,9 +704,10 @@ where if let Some(sender) = maybe_sender && let Err(error) = sender.unbounded_send(()) - && !error.is_closed() { - warn!("Failed to acknowledge archived segment: {error}"); - } + && !error.is_closed() + { + warn!("Failed to acknowledge archived segment: {error}"); + } debug!(%segment_index, "Acknowledged archived segment."); diff --git a/crates/sc-consensus-subspace/src/archiver.rs b/crates/sc-consensus-subspace/src/archiver.rs index d0a47d6c474..f61ecd72830 100644 --- a/crates/sc-consensus-subspace/src/archiver.rs +++ b/crates/sc-consensus-subspace/src/archiver.rs @@ -40,29 +40,29 @@ use parity_scale_codec::{Decode, Encode}; use parking_lot::RwLock; use rand::prelude::*; use rand_chacha::ChaCha8Rng; -use rayon::prelude::*; use rayon::ThreadPoolBuilder; +use rayon::prelude::*; use sc_client_api::{ AuxStore, Backend as BackendT, BlockBackend, BlockchainEvents, Finalizer, LockImportRun, }; -use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_INFO}; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender}; +use sc_telemetry::{CONSENSUS_INFO, TelemetryHandle, telemetry}; +use sc_utils::mpsc::{TracingUnboundedSender, tracing_unbounded}; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_consensus::SyncOracle; use sp_consensus_subspace::{SubspaceApi, SubspaceJustification}; use sp_objects::ObjectsApi; +use sp_runtime::Justifications; use sp_runtime::generic::SignedBlock; use sp_runtime::traits::{ Block as BlockT, BlockNumber as BlockNumberT, CheckedSub, Header, NumberFor, One, Zero, }; -use sp_runtime::Justifications; use std::error::Error; use std::future::Future; use std::num::NonZeroU32; use std::slice; -use std::sync::atomic::{AtomicU16, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU16, Ordering}; use std::time::Duration; use subspace_archiving::archiver::{Archiver, NewArchivedSegment}; use subspace_core_primitives::objects::{BlockObjectMapping, GlobalObject}; @@ -262,9 +262,10 @@ where if block_number == 1 { // If there is a segment index present, and we store monotonically increasing segment // headers, then the first header exists. - return vec![self - .get_segment_header(SegmentIndex::ZERO) - .expect("Segment headers are stored in monotonically increasing order; qed")]; + return vec![ + self.get_segment_header(SegmentIndex::ZERO) + .expect("Segment headers are stored in monotonically increasing order; qed"), + ]; } if last_segment_index == SegmentIndex::ZERO { diff --git a/crates/sc-consensus-subspace/src/block_import.rs b/crates/sc-consensus-subspace/src/block_import.rs index da3014bb01d..6691c1239de 100644 --- a/crates/sc-consensus-subspace/src/block_import.rs +++ b/crates/sc-consensus-subspace/src/block_import.rs @@ -13,27 +13,27 @@ use crate::archiver::SegmentHeadersStore; use crate::verifier::VerificationError; -use crate::{aux_schema, slot_worker, SubspaceLink}; -use futures::channel::mpsc; +use crate::{SubspaceLink, aux_schema, slot_worker}; use futures::StreamExt; -use sc_client_api::backend::AuxStore; +use futures::channel::mpsc; use sc_client_api::BlockBackend; +use sc_client_api::backend::AuxStore; +use sc_consensus::StateAction; use sc_consensus::block_import::{ BlockCheckParams, BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, }; -use sc_consensus::StateAction; use sc_proof_of_time::verifier::PotVerifier; use sp_api::{ApiError, ApiExt, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_blockchain::HeaderBackend; use sp_consensus_slots::Slot; use sp_consensus_subspace::digests::{ - extract_pre_digest, extract_subspace_digest_items, SubspaceDigestItems, + SubspaceDigestItems, extract_pre_digest, extract_subspace_digest_items, }; use sp_consensus_subspace::{PotNextSlotInput, SubspaceApi, SubspaceJustification}; use sp_inherents::{CreateInherentDataProviders, InherentDataProvider}; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, One}; use sp_runtime::Justifications; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, One}; use std::marker::PhantomData; use std::sync::Arc; use subspace_core_primitives::sectors::SectorId; @@ -41,7 +41,7 @@ use subspace_core_primitives::segments::{HistorySize, SegmentHeader, SegmentInde use subspace_core_primitives::solutions::SolutionRange; use subspace_core_primitives::{BlockNumber, PublicKey}; use subspace_proof_of_space::Table; -use subspace_verification::{calculate_block_weight, PieceCheckParams, VerifySolutionParams}; +use subspace_verification::{PieceCheckParams, VerifySolutionParams, calculate_block_weight}; use tracing::warn; /// Notification with number of the block that is about to be imported and acknowledgement sender @@ -333,10 +333,11 @@ where let pre_digest = &subspace_digest_items.pre_digest; if let Some(root_plot_public_key) = root_plot_public_key - && &pre_digest.solution().public_key != root_plot_public_key { - // Only root plot public key is allowed. - return Err(Error::OnlyRootPlotPublicKeyAllowed); - } + && &pre_digest.solution().public_key != root_plot_public_key + { + // Only root plot public key is allowed. + return Err(Error::OnlyRootPlotPublicKeyAllowed); + } let parent_header = self .client diff --git a/crates/sc-consensus-subspace/src/notification.rs b/crates/sc-consensus-subspace/src/notification.rs index 023debdb8e2..2ca08a54f9c 100644 --- a/crates/sc-consensus-subspace/src/notification.rs +++ b/crates/sc-consensus-subspace/src/notification.rs @@ -1,7 +1,7 @@ //! Utility module for handling Subspace client notifications. use parking_lot::Mutex; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; +use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender, tracing_unbounded}; use std::fmt; use std::sync::Arc; diff --git a/crates/sc-consensus-subspace/src/slot_worker.rs b/crates/sc-consensus-subspace/src/slot_worker.rs index 4f7e344457b..0cb6b983b85 100644 --- a/crates/sc-consensus-subspace/src/slot_worker.rs +++ b/crates/sc-consensus-subspace/src/slot_worker.rs @@ -15,8 +15,8 @@ //! to the base Substrate behavior where major syncing is assumed to not happen in case authoring is //! forced. -use crate::archiver::SegmentHeadersStore; use crate::SubspaceLink; +use crate::archiver::SegmentHeadersStore; use futures::channel::mpsc; use futures::{StreamExt, TryFutureExt}; use sc_client_api::AuxStore; @@ -25,18 +25,18 @@ use sc_consensus::{BoxBlockImport, JustificationSyncLink, StorageChanges}; use sc_consensus_slots::{ BackoffAuthoringBlocksStrategy, SimpleSlotWorker, SlotInfo, SlotLenienceType, SlotProportion, }; -use sc_proof_of_time::verifier::PotVerifier; use sc_proof_of_time::PotSlotWorker; +use sc_proof_of_time::verifier::PotVerifier; use sc_telemetry::TelemetryHandle; use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender}; +use sc_utils::mpsc::{TracingUnboundedSender, tracing_unbounded}; use schnorrkel::context::SigningContext; use sp_api::{ApiError, ApiExt, ProvideRuntimeApi}; use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata}; use sp_consensus::{BlockOrigin, Environment, Error as ConsensusError, Proposer, SyncOracle}; use sp_consensus_slots::Slot; use sp_consensus_subspace::digests::{ - extract_pre_digest, CompatibleDigestItem, PreDigest, PreDigestPotInfo, + CompatibleDigestItem, PreDigest, PreDigestPotInfo, extract_pre_digest, }; use sp_consensus_subspace::{ PotNextSlotInput, SignedVote, SubspaceApi, SubspaceJustification, Vote, @@ -48,15 +48,15 @@ use std::collections::BTreeMap; use std::future::Future; use std::marker::PhantomData; use std::pin::Pin; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use subspace_core_primitives::pot::{PotCheckpoints, PotOutput}; use subspace_core_primitives::sectors::SectorId; use subspace_core_primitives::solutions::{RewardSignature, Solution, SolutionRange}; use subspace_core_primitives::{BlockNumber, PublicKey, REWARD_SIGNING_CONTEXT}; use subspace_proof_of_space::Table; use subspace_verification::{ - check_reward_signature, verify_solution, PieceCheckParams, VerifySolutionParams, + PieceCheckParams, VerifySolutionParams, check_reward_signature, verify_solution, }; use tracing::{debug, error, info, warn}; @@ -500,11 +500,12 @@ where while let Some(solution) = solution_receiver.next().await { if let Some(root_plot_public_key) = &maybe_root_plot_public_key - && &solution.public_key != root_plot_public_key { - // Only root plot public key is allowed, no need to even try to claim block or - // vote. - continue; - } + && &solution.public_key != root_plot_public_key + { + // Only root plot public key is allowed, no need to even try to claim block or + // vote. + continue; + } let sector_id = SectorId::new( solution.public_key.hash(), @@ -689,15 +690,15 @@ where fn should_backoff(&self, slot: Slot, chain_head: &Block::Header) -> bool { if let Some(strategy) = &self.backoff_authoring_blocks && let Ok(chain_head_slot) = extract_pre_digest(chain_head).map(|digest| digest.slot()) - { - return strategy.should_backoff( - *chain_head.number(), - chain_head_slot, - self.client.info().finalized_number, - slot, - self.logging_target(), - ); - } + { + return strategy.should_backoff( + *chain_head.number(), + chain_head_slot, + self.client.info().finalized_number, + slot, + self.logging_target(), + ); + } false } diff --git a/crates/sc-consensus-subspace/src/verifier.rs b/crates/sc-consensus-subspace/src/verifier.rs index a5b14f70740..4df29b42e05 100644 --- a/crates/sc-consensus-subspace/src/verifier.rs +++ b/crates/sc-consensus-subspace/src/verifier.rs @@ -21,7 +21,7 @@ use sc_consensus::block_import::BlockImportParams; use sc_consensus::import_queue::Verifier; use sc_consensus_slots::check_equivocation; use sc_proof_of_time::verifier::PotVerifier; -use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_TRACE}; +use sc_telemetry::{CONSENSUS_TRACE, TelemetryHandle, telemetry}; use schnorrkel::context::SigningContext; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder as BlockBuilderApi; @@ -29,7 +29,7 @@ use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; use sp_consensus_slots::Slot; use sp_consensus_subspace::digests::{ - extract_subspace_digest_items, CompatibleDigestItem, PreDigest, SubspaceDigestItems, + CompatibleDigestItem, PreDigest, SubspaceDigestItems, extract_subspace_digest_items, }; use sp_consensus_subspace::{ChainConstants, PotNextSlotInput, SubspaceApi, SubspaceJustification}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; @@ -37,13 +37,13 @@ use sp_runtime::{DigestItem, Justifications}; use std::iter; use std::marker::PhantomData; use std::num::NonZeroUsize; -use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; use std::thread::available_parallelism; use subspace_core_primitives::{BlockNumber, PublicKey}; use subspace_kzg::Kzg; use subspace_proof_of_space::Table; -use subspace_verification::{check_reward_signature, verify_solution, VerifySolutionParams}; +use subspace_verification::{VerifySolutionParams, check_reward_signature, verify_solution}; use tokio::runtime::Handle; use tracing::{debug, info, trace, warn}; diff --git a/crates/sc-domains/src/domain_block_er/receipt_receiver.rs b/crates/sc-domains/src/domain_block_er/receipt_receiver.rs index a7d9fd489f5..32718f9729b 100644 --- a/crates/sc-domains/src/domain_block_er/receipt_receiver.rs +++ b/crates/sc-domains/src/domain_block_er/receipt_receiver.rs @@ -4,7 +4,7 @@ #![warn(missing_docs)] use crate::domain_block_er::execution_receipt_protocol::{ - generate_protocol_name, DomainBlockERRequest, DomainBlockERResponse, + DomainBlockERRequest, DomainBlockERResponse, generate_protocol_name, }; use domain_runtime_primitives::Balance; use futures::channel::oneshot; diff --git a/crates/sc-domains/src/lib.rs b/crates/sc-domains/src/lib.rs index e322eb533bd..e0cd5430c13 100644 --- a/crates/sc-domains/src/lib.rs +++ b/crates/sc-domains/src/lib.rs @@ -6,18 +6,18 @@ use sc_client_api::execution_extensions::ExtensionsFactory as ExtensionsFactoryT use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_core::traits::CodeExecutor; use sp_core::H256; +use sp_core::traits::CodeExecutor; use sp_domains::DomainsApi; +use sp_domains_fraud_proof::FraudProofApi; use sp_domains_fraud_proof::storage_proof::{ FraudProofStorageKeyProviderInstance, FraudProofStorageKeyRequest, }; -use sp_domains_fraud_proof::FraudProofApi; use sp_externalities::Extensions; use sp_messenger_host_functions::{MessengerApi, MessengerExtension, MessengerHostFunctionsImpl}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, One}; -use sp_subspace_mmr::host_functions::{MmrApi, SubspaceMmrExtension, SubspaceMmrHostFunctionsImpl}; use sp_subspace_mmr::ConsensusChainMmrLeafProof; +use sp_subspace_mmr::host_functions::{MmrApi, SubspaceMmrExtension, SubspaceMmrHostFunctionsImpl}; use std::marker::PhantomData; use std::sync::Arc; diff --git a/crates/sc-proof-of-time/src/lib.rs b/crates/sc-proof-of-time/src/lib.rs index 69ef238e728..a982eb79236 100644 --- a/crates/sc-proof-of-time/src/lib.rs +++ b/crates/sc-proof-of-time/src/lib.rs @@ -17,8 +17,8 @@ use sp_consensus_subspace::SubspaceApi; use sp_inherents::CreateInherentDataProviders; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; -use subspace_core_primitives::pot::PotCheckpoints; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::pot::PotCheckpoints; use tokio::sync::broadcast::error::RecvError; use tracing::{debug, error, info, trace}; @@ -91,10 +91,11 @@ pub async fn start_slot_worker( }, }; if let Some(last_proven_slot) = maybe_last_proven_slot - && last_proven_slot >= slot { - // Already processed - continue; - } + && last_proven_slot >= slot + { + // Already processed + continue; + } maybe_last_proven_slot.replace(slot); worker.0.on_proof(slot, checkpoints); diff --git a/crates/sc-proof-of-time/src/source.rs b/crates/sc-proof-of-time/src/source.rs index 8b07f27ad47..4222bfe7d57 100644 --- a/crates/sc-proof-of-time/src/source.rs +++ b/crates/sc-proof-of-time/src/source.rs @@ -4,12 +4,12 @@ mod timekeeper; use crate::source::gossip::{GossipProof, PotGossipWorker, ToGossipMessage}; use crate::source::state::{PotState, PotStateUpdateOutcome}; -use crate::source::timekeeper::{run_timekeeper, TimekeeperProof}; +use crate::source::timekeeper::{TimekeeperProof, run_timekeeper}; use crate::verifier::PotVerifier; use core_affinity::CoreId; use derive_more::{Deref, DerefMut}; use futures::channel::mpsc; -use futures::{select, StreamExt}; +use futures::{StreamExt, select}; use sc_client_api::BlockchainEvents; use sc_network::{NotificationService, PeerId}; use sc_network_gossip::{Network as GossipNetwork, Syncing as GossipSyncing}; @@ -24,11 +24,11 @@ use std::collections::HashSet; use std::marker::PhantomData; use std::sync::Arc; use std::thread; -use subspace_core_primitives::pot::PotCheckpoints; use subspace_core_primitives::PublicKey; -use thread_priority::{set_current_thread_priority, ThreadPriority}; +use subspace_core_primitives::pot::PotCheckpoints; +use thread_priority::{ThreadPriority, set_current_thread_priority}; use tokio::sync::broadcast; -use tracing::{debug, error, trace, warn, Span}; +use tracing::{Span, debug, error, trace, warn}; const LOCAL_PROOFS_CHANNEL_CAPACITY: usize = 10; const SLOTS_CHANNEL_CAPACITY: usize = 10; @@ -145,13 +145,14 @@ where let _guard = span.enter(); if let Some(core) = timekeeper_cpu_cores.into_iter().next() - && !core_affinity::set_for_current(CoreId { id: core }) { - warn!( - %core, - "Failed to set core affinity, timekeeper will run on random CPU \ - core", - ); - } + && !core_affinity::set_for_current(CoreId { id: core }) + { + warn!( + %core, + "Failed to set core affinity, timekeeper will run on random CPU \ + core", + ); + } if let Err(error) = set_current_thread_priority(ThreadPriority::Max) { warn!( diff --git a/crates/sc-proof-of-time/src/source/gossip.rs b/crates/sc-proof-of-time/src/source/gossip.rs index 2d227900cb9..aaf60737f25 100644 --- a/crates/sc-proof-of-time/src/source/gossip.rs +++ b/crates/sc-proof-of-time/src/source/gossip.rs @@ -267,18 +267,19 @@ where if let Some(proofs) = self.gossip_cache.get_or_insert(sender, Default::default) { if proofs.len() == GOSSIP_CACHE_PER_PEER_SIZE - && let Some(proof) = proofs.pop_front() { - trace!( - %sender, - slot = %proof.slot, - next_slot = %next_slot_input.slot, - "Too many proofs stored from peer", - ); - - self.engine - .lock() - .report(sender, rep::GOSSIP_TOO_MANY_PROOFS); - } + && let Some(proof) = proofs.pop_front() + { + trace!( + %sender, + slot = %proof.slot, + next_slot = %next_slot_input.slot, + "Too many proofs stored from peer", + ); + + self.engine + .lock() + .report(sender, rep::GOSSIP_TOO_MANY_PROOFS); + } proofs.push_back(proof); return; } diff --git a/crates/sc-proof-of-time/src/source/timekeeper.rs b/crates/sc-proof-of-time/src/source/timekeeper.rs index 280d15141cd..6607ce6ac08 100644 --- a/crates/sc-proof-of-time/src/source/timekeeper.rs +++ b/crates/sc-proof-of-time/src/source/timekeeper.rs @@ -1,8 +1,8 @@ use crate::source::state::PotState; use crate::verifier::PotVerifier; +use futures::SinkExt; use futures::channel::mpsc; use futures::executor::block_on; -use futures::SinkExt; use sp_consensus_slots::Slot; use std::num::NonZeroU32; use std::sync::Arc; @@ -33,8 +33,7 @@ pub(super) fn run_timekeeper( loop { trace!( "Proving for slot {} with {} iterations", - next_slot_input.slot, - next_slot_input.slot_iterations + next_slot_input.slot, next_slot_input.slot_iterations ); let checkpoints = subspace_proof_of_time::prove(next_slot_input.seed, next_slot_input.slot_iterations)?; @@ -62,9 +61,10 @@ pub(super) fn run_timekeeper( .unwrap_or_else(|next_slot_input| next_slot_input); if let Err(error) = proofs_sender.try_send(proof) - && let Err(error) = block_on(proofs_sender.send(error.into_inner())) { - debug!(%error, "Couldn't send checkpoints, channel is closed"); - return Ok(()); - } + && let Err(error) = block_on(proofs_sender.send(error.into_inner())) + { + debug!(%error, "Couldn't send checkpoints, channel is closed"); + return Ok(()); + } } } diff --git a/crates/sc-proof-of-time/src/verifier/tests.rs b/crates/sc-proof-of-time/src/verifier/tests.rs index 5289dde1d73..b2b54eab7d7 100644 --- a/crates/sc-proof-of-time/src/verifier/tests.rs +++ b/crates/sc-proof-of-time/src/verifier/tests.rs @@ -53,13 +53,15 @@ fn test_basic() { None )); // Invalid number of iterations - assert!(!verifier.verify_checkpoints( - genesis_seed, - slot_iterations - .checked_mul(NonZeroU32::new(2).unwrap()) - .unwrap(), - &checkpoints_1 - )); + assert!( + !verifier.verify_checkpoints( + genesis_seed, + slot_iterations + .checked_mul(NonZeroU32::new(2).unwrap()) + .unwrap(), + &checkpoints_1 + ) + ); let seed_1 = checkpoints_1.output().seed(); let checkpoints_2 = subspace_proof_of_time::prove(seed_1, slot_iterations).unwrap(); @@ -110,18 +112,20 @@ fn test_basic() { None )); // Invalid number of iterations - assert!(!verifier.is_output_valid( - PotNextSlotInput { - slot: Slot::from(1), - slot_iterations: slot_iterations - .checked_mul(NonZeroU32::new(2).unwrap()) - .unwrap(), - seed: genesis_seed, - }, - Slot::from(2), - checkpoints_2.output(), - None - )); + assert!( + !verifier.is_output_valid( + PotNextSlotInput { + slot: Slot::from(1), + slot_iterations: slot_iterations + .checked_mul(NonZeroU32::new(2).unwrap()) + .unwrap(), + seed: genesis_seed, + }, + Slot::from(2), + checkpoints_2.output(), + None + ) + ); } #[test] diff --git a/crates/sc-subspace-block-relay/src/consensus/relay.rs b/crates/sc-subspace-block-relay/src/consensus/relay.rs index a72fcc75982..53b59d64bac 100644 --- a/crates/sc-subspace-block-relay/src/consensus/relay.rs +++ b/crates/sc-subspace-block-relay/src/consensus/relay.rs @@ -479,7 +479,7 @@ where Ok(None) => { return Err(RelayError::BlockHeader(format!( "Missing header: {block_hash:?}" - ))) + ))); } Err(err) => return Err(RelayError::BlockHeader(format!("{block_hash:?}, {err:?}"))), }; diff --git a/crates/sc-subspace-block-relay/src/consensus/types.rs b/crates/sc-subspace-block-relay/src/consensus/types.rs index d914b41b4b1..5b43ca14612 100644 --- a/crates/sc-subspace-block-relay/src/consensus/types.rs +++ b/crates/sc-subspace-block-relay/src/consensus/types.rs @@ -17,9 +17,9 @@ use crate::utils::{RelayCounter, RelayCounterVec}; use derive_more::From; use parity_scale_codec::{Decode, Encode}; use sc_network_common::sync::message::{BlockAttributes, BlockData, BlockRequest}; +use sp_runtime::Justifications; use sp_runtime::generic::BlockId; use sp_runtime::traits::{Block as BlockT, NumberFor}; -use sp_runtime::Justifications; use subspace_runtime_primitives::{BlockHashFor, ExtrinsicFor, HeaderFor}; use substrate_prometheus_endpoint::{PrometheusError, Registry}; diff --git a/crates/sc-subspace-block-relay/src/lib.rs b/crates/sc-subspace-block-relay/src/lib.rs index fe459d5a8f6..a54fef86caa 100644 --- a/crates/sc-subspace-block-relay/src/lib.rs +++ b/crates/sc-subspace-block-relay/src/lib.rs @@ -5,5 +5,5 @@ mod protocol; mod types; mod utils; -pub use crate::consensus::relay::{build_consensus_relay, BlockRelayConfigurationError}; +pub use crate::consensus::relay::{BlockRelayConfigurationError, build_consensus_relay}; pub use crate::utils::NetworkWrapper; diff --git a/crates/sc-subspace-block-relay/src/utils.rs b/crates/sc-subspace-block-relay/src/utils.rs index b20202ed289..1c2ccaef105 100644 --- a/crates/sc-subspace-block-relay/src/utils.rs +++ b/crates/sc-subspace-block-relay/src/utils.rs @@ -10,7 +10,7 @@ use sc_network::{NetworkRequest, PeerId}; use std::collections::HashMap; use std::sync::Arc; use substrate_prometheus_endpoint::{ - register, Counter, CounterVec, Opts, PrometheusError, Registry, U64, + Counter, CounterVec, Opts, PrometheusError, Registry, U64, register, }; type NetworkRequestService = Arc; diff --git a/crates/sp-consensus-subspace/src/digests.rs b/crates/sp-consensus-subspace/src/digests.rs index 72f3b51dce3..80cef50b371 100644 --- a/crates/sp-consensus-subspace/src/digests.rs +++ b/crates/sp-consensus-subspace/src/digests.rs @@ -4,15 +4,15 @@ use crate::{ConsensusLog, PotParametersChange, SUBSPACE_ENGINE_ID}; use log::trace; use parity_scale_codec::{Decode, Encode}; use sp_consensus_slots::Slot; -use sp_runtime::traits::{Header as HeaderT, One, Zero}; use sp_runtime::DigestItem; +use sp_runtime::traits::{Header as HeaderT, One, Zero}; use sp_std::collections::btree_map::{BTreeMap, Entry}; use sp_std::fmt; use sp_std::num::NonZeroU32; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pot::PotOutput; use subspace_core_primitives::segments::{SegmentCommitment, SegmentIndex}; use subspace_core_primitives::solutions::{RewardSignature, Solution, SolutionRange}; -use subspace_core_primitives::PublicKey; /// A Subspace pre-runtime digest. This contains all data required to validate a block and for the /// Subspace runtime module. diff --git a/crates/sp-consensus-subspace/src/lib.rs b/crates/sp-consensus-subspace/src/lib.rs index 3c5be787b46..ba8e8fc6550 100644 --- a/crates/sp-consensus-subspace/src/lib.rs +++ b/crates/sp-consensus-subspace/src/lib.rs @@ -34,11 +34,11 @@ use subspace_core_primitives::{BlockHash, BlockNumber, PublicKey, SlotNumber}; #[cfg(feature = "std")] use subspace_kzg::Kzg; #[cfg(feature = "std")] -use subspace_proof_of_space::shim::ShimTable; -#[cfg(feature = "std")] use subspace_proof_of_space::PosTableType; #[cfg(feature = "std")] use subspace_proof_of_space::Table; +#[cfg(feature = "std")] +use subspace_proof_of_space::shim::ShimTable; use subspace_verification::VerifySolutionParams; /// The `ConsensusEngineId` of Subspace. @@ -475,9 +475,9 @@ pub trait Consensus { #[cfg(not(feature = "runtime-benchmarks"))] { use sp_externalities::ExternalitiesExt; + use subspace_proof_of_space::PosTableType; #[cfg(feature = "std")] use subspace_proof_of_space::chia::ChiaTable; - use subspace_proof_of_space::PosTableType; let pos_table_type = self .extension::() diff --git a/crates/sp-domains-fraud-proof/benches/fraud_proof_verification.rs b/crates/sp-domains-fraud-proof/benches/fraud_proof_verification.rs index 7165abc46da..807576ca438 100644 --- a/crates/sp-domains-fraud-proof/benches/fraud_proof_verification.rs +++ b/crates/sp-domains-fraud-proof/benches/fraud_proof_verification.rs @@ -1,8 +1,8 @@ -use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; use domain_runtime_primitives::opaque::Block as DomainBlock; use domain_test_service::EcdsaKeyring::{Alice, Bob}; use domain_test_service::Sr25519Keyring::{self, Ferdie}; -use domain_test_service::{EvmDomainNode, EVM_DOMAIN_ID}; +use domain_test_service::{EVM_DOMAIN_ID, EvmDomainNode}; use pallet_domains::OpaqueBundleOf; use parity_scale_codec::{Decode, Encode}; use sc_client_api::execution_extensions::ExtensionsFactory; @@ -10,7 +10,7 @@ use sc_client_api::{Backend, HeaderBackend}; use sc_domains::{ExtensionsFactory as DomainsExtensionFactory, FPStorageKeyProvider}; use sc_service::{BasePath, Role}; use sp_api::ProvideRuntimeApi; -use sp_core::{Pair as _, H256}; +use sp_core::{H256, Pair as _}; use sp_domains::merkle_tree::MerkleTree; use sp_domains::{ BundleValidity, ChainId, DomainsApi, ExecutionReceiptFor, InvalidBundleType, Transfers, @@ -19,16 +19,16 @@ use sp_domains_fraud_proof::fraud_proof::{DomainRuntimeCodeAt, FraudProof, Fraud use sp_domains_fraud_proof::storage_proof::{BasicStorageProof, DomainRuntimeCodeProof}; use sp_domains_fraud_proof::verification::*; use sp_domains_fraud_proof::{FraudProofExtension, FraudProofHostFunctionsImpl}; -use sp_runtime::traits::{BlakeTwo256, NumberFor}; use sp_runtime::OpaqueExtrinsic; +use sp_runtime::traits::{BlakeTwo256, NumberFor}; use sp_state_machine::{Ext, OverlayedChanges}; use sp_subspace_mmr::{ConsensusChainMmrLeafProof, MmrProofVerifier as _}; use std::collections::BTreeMap; use std::sync::Arc; use subspace_runtime_primitives::opaque::Block; use subspace_runtime_primitives::{Balance, BlockHashFor, BlockHashingFor, HeaderFor, SSC}; -use subspace_test_runtime::{mmr, MmrProofVerifier, Runtime, StorageKeyProvider}; -use subspace_test_service::{produce_block_with, produce_blocks, MockConsensusNode}; +use subspace_test_runtime::{MmrProofVerifier, Runtime, StorageKeyProvider, mmr}; +use subspace_test_service::{MockConsensusNode, produce_block_with, produce_blocks}; use tempfile::TempDir; use tokio::runtime::{Handle, Runtime as TokioRuntime}; @@ -204,8 +204,8 @@ fn mmr_proof_and_runtime_code_proof_verification(c: &mut Criterion) { async fn prepare_fraud_proof( tokio_handle: Handle, bad_receipt_maker: impl Fn(&mut ExecutionReceiptFor, Block, Balance>) - + Send - + 'static, + + Send + + 'static, ) -> ( (TempDir, MockConsensusNode, EvmDomainNode), TestExternalities, @@ -282,9 +282,11 @@ async fn prepare_fraud_proof( ) .await .unwrap(); - assert!(ferdie - .does_receipt_exist(bad_receipt.hash::()) - .unwrap()); + assert!( + ferdie + .does_receipt_exist(bad_receipt.hash::()) + .unwrap() + ); let fp: FraudProofFor = { let fp = wait_for_fraud_proof_fut.await; @@ -372,8 +374,8 @@ fn invalid_state_transition_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_state_transition_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_state_transition_fraud_proof::< Block, HeaderFor, _, @@ -383,7 +385,8 @@ fn invalid_state_transition_proof_verification(c: &mut Criterion) { &invalid_state_transition_proof, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -407,8 +410,8 @@ fn valid_bundle_proof_verification(c: &mut Criterion) { b.iter_batched( || (bad_receipt.clone(), domain_runtime_code.clone()), |(bad_receipt, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_valid_bundle_fraud_proof::< + assert!( + ext.execute_with(|| verify_valid_bundle_fraud_proof::< Block, HeaderFor, Balance, @@ -420,7 +423,8 @@ fn valid_bundle_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -444,8 +448,8 @@ fn invalid_domain_extrinsics_root_fraud_proof(c: &mut Criterion) { b.iter_batched( || (bad_receipt.clone(), domain_runtime_code.clone()), |(bad_receipt, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_domain_extrinsics_root_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_domain_extrinsics_root_fraud_proof::< Block, Balance, HeaderFor, @@ -459,7 +463,8 @@ fn invalid_domain_extrinsics_root_fraud_proof(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -489,8 +494,8 @@ fn invalid_domain_block_hash_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, invalid_domain_block_hash_fraud_proof)| { - assert!(ext - .execute_with(|| verify_invalid_domain_block_hash_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_domain_block_hash_fraud_proof::< Block, Balance, HeaderFor, @@ -501,7 +506,8 @@ fn invalid_domain_block_hash_fraud_proof_verification(c: &mut Criterion) { .clone(), bad_receipt_parent.domain_block_hash )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -523,8 +529,8 @@ fn invalid_block_fees_fraud_proof_verification(c: &mut Criterion) { b.iter_batched( || (bad_receipt.clone(), domain_runtime_code.clone()), |(bad_receipt, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_block_fees_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_block_fees_fraud_proof::< Block, NumberFor, BlockHashFor, @@ -535,7 +541,8 @@ fn invalid_block_fees_fraud_proof_verification(c: &mut Criterion) { &invalid_block_fees_fraud_proof.storage_proof.clone(), domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -562,8 +569,8 @@ fn invalid_transfers_fraud_proof_verification(c: &mut Criterion) { b.iter_batched( || (bad_receipt.clone(), domain_runtime_code.clone()), |(bad_receipt, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_transfers_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_transfers_fraud_proof::< Block, NumberFor, BlockHashFor, @@ -574,7 +581,8 @@ fn invalid_transfers_fraud_proof_verification(c: &mut Criterion) { &invalid_transfers_fraud_proof.storage_proof.clone(), domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -614,8 +622,8 @@ fn invalid_bundle_undecodable_tx_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -630,7 +638,8 @@ fn invalid_bundle_undecodable_tx_fraud_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -670,8 +679,8 @@ fn invalid_bundle_out_of_range_tx_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -686,7 +695,8 @@ fn invalid_bundle_out_of_range_tx_fraud_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -726,8 +736,8 @@ fn invalid_bundle_illegal_tx_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -742,7 +752,8 @@ fn invalid_bundle_illegal_tx_fraud_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -782,8 +793,8 @@ fn invalid_bundle_invalid_xdm_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -798,7 +809,8 @@ fn invalid_bundle_invalid_xdm_fraud_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -838,8 +850,8 @@ fn invalid_bundle_inherent_extrinsic_fraud_proof_verification(c: &mut Criterion) ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -854,7 +866,8 @@ fn invalid_bundle_inherent_extrinsic_fraud_proof_verification(c: &mut Criterion) consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) @@ -894,8 +907,8 @@ fn invalid_bundle_weight_fraud_proof_verification(c: &mut Criterion) { ) }, |(bad_receipt, bad_receipt_parent, domain_runtime_code)| { - assert!(ext - .execute_with(|| verify_invalid_bundles_fraud_proof::< + assert!( + ext.execute_with(|| verify_invalid_bundles_fraud_proof::< Block, HeaderFor, mmr::Hash, @@ -910,7 +923,8 @@ fn invalid_bundle_weight_fraud_proof_verification(c: &mut Criterion) { consensus_state_root, domain_runtime_code, )) - .is_ok()); + .is_ok() + ); }, BatchSize::SmallInput, ) diff --git a/crates/sp-domains-fraud-proof/src/execution_prover.rs b/crates/sp-domains-fraud-proof/src/execution_prover.rs index 7dadc50344a..250cc9a55d1 100644 --- a/crates/sp-domains-fraud-proof/src/execution_prover.rs +++ b/crates/sp-domains-fraud-proof/src/execution_prover.rs @@ -10,8 +10,8 @@ use sc_client_api::backend::Backend; use sp_api::StorageProof; use sp_core::traits::CodeExecutor; use sp_runtime::traits::{Block as BlockT, HashingFor}; -use sp_state_machine::backend::AsTrieBackend; use sp_state_machine::BackendTransaction; +use sp_state_machine::backend::AsTrieBackend; use std::marker::PhantomData; use std::sync::Arc; diff --git a/crates/sp-domains-fraud-proof/src/fraud_proof.rs b/crates/sp-domains-fraud-proof/src/fraud_proof.rs index 20fbc7e8b14..ba954fdca71 100644 --- a/crates/sp-domains-fraud-proof/src/fraud_proof.rs +++ b/crates/sp-domains-fraud-proof/src/fraud_proof.rs @@ -234,11 +234,9 @@ pub enum VerificationError { #[error("Failed to decode the return value of `initialize_block` and `apply_extrinsic`: {0}")] InitializeBlockOrApplyExtrinsicDecode(parity_scale_codec::Error), /// Failed to decode the storage root produced by verifying `initialize_block` or `apply_extrinsic`. - #[ - error( - "Failed to decode the storage root from verifying `initialize_block` and `apply_extrinsic`: {0}" - ) - ] + #[error( + "Failed to decode the storage root from verifying `initialize_block` and `apply_extrinsic`: {0}" + )] StorageRootDecode(parity_scale_codec::Error), /// Failed to decode the header produced by `finalize_block`. #[error("Failed to decode the header from verifying `finalize_block`: {0}")] diff --git a/crates/sp-domains-fraud-proof/src/host_functions.rs b/crates/sp-domains-fraud-proof/src/host_functions.rs index 007358414e6..2fed8859865 100644 --- a/crates/sp-domains-fraud-proof/src/host_functions.rs +++ b/crates/sp-domains-fraud-proof/src/host_functions.rs @@ -9,22 +9,22 @@ use crate::{ use alloc::vec::Vec; use domain_block_preprocessor::stateless_runtime::StatelessRuntime; use domain_runtime_primitives::{ - BlockNumber, CheckExtrinsicsValidityError, CHECK_EXTRINSICS_AND_DO_PRE_DISPATCH_METHOD_NAME, + BlockNumber, CHECK_EXTRINSICS_AND_DO_PRE_DISPATCH_METHOD_NAME, CheckExtrinsicsValidityError, }; use hash_db::{HashDB, Hasher}; use parity_scale_codec::{Codec, Decode, Encode}; -use sc_client_api::execution_extensions::ExtensionsFactory; use sc_client_api::BlockBackend; +use sc_client_api::execution_extensions::ExtensionsFactory; use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_core::traits::{CallContext, CodeExecutor, FetchRuntimeCode, RuntimeCode}; use sp_core::H256; +use sp_core::traits::{CallContext, CodeExecutor, FetchRuntimeCode, RuntimeCode}; use sp_domains::{BundleProducerElectionApi, DomainsApi, ExtrinsicDigest}; use sp_externalities::Extensions; use sp_messenger::MessengerApi; -use sp_runtime::traits::{Block as BlockT, Hash as HashT, HashingFor, NumberFor}; use sp_runtime::OpaqueExtrinsic; +use sp_runtime::traits::{Block as BlockT, Hash as HashT, HashingFor, NumberFor}; use sp_state_machine::{LayoutV1, OverlayedChanges, StateMachine, TrieBackend, TrieBackendBuilder}; use sp_trie::{MemoryDB, StorageProof}; use sp_weights::Weight; diff --git a/crates/sp-domains-fraud-proof/src/lib.rs b/crates/sp-domains-fraud-proof/src/lib.rs index c3dc23c0216..96bdb918865 100644 --- a/crates/sp-domains-fraud-proof/src/lib.rs +++ b/crates/sp-domains-fraud-proof/src/lib.rs @@ -37,9 +37,9 @@ pub use runtime_interface::fraud_proof_runtime_interface::HostFunctions; use scale_info::TypeInfo; use sp_core::H256; use sp_domains::{DomainAllowlistUpdates, PermissionedActionAllowedBy}; +use sp_runtime::OpaqueExtrinsic; use sp_runtime::traits::{Header as HeaderT, NumberFor}; use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity}; -use sp_runtime::OpaqueExtrinsic; use sp_runtime_interface::pass_by; use sp_runtime_interface::pass_by::PassBy; use subspace_core_primitives::U256; diff --git a/crates/sp-domains-fraud-proof/src/storage_proof.rs b/crates/sp-domains-fraud-proof/src/storage_proof.rs index 41f5cada2f8..4970c8e9d6c 100644 --- a/crates/sp-domains-fraud-proof/src/storage_proof.rs +++ b/crates/sp-domains-fraud-proof/src/storage_proof.rs @@ -1,8 +1,8 @@ use frame_support::PalletError; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; -use sp_core::storage::StorageKey; use sp_core::H256; +use sp_core::storage::StorageKey; use sp_domains::proof_provider_and_verifier::{ StorageProofVerifier, VerificationError as StorageProofVerificationError, }; diff --git a/crates/sp-domains-fraud-proof/src/tests.rs b/crates/sp-domains-fraud-proof/src/tests.rs index ac9f6fb672f..c123bc44d07 100644 --- a/crates/sp-domains-fraud-proof/src/tests.rs +++ b/crates/sp-domains-fraud-proof/src/tests.rs @@ -1,10 +1,10 @@ use domain_runtime_primitives::{Balance, CheckExtrinsicsValidityError}; -use domain_test_service::evm_domain_test_runtime::{ - Runtime as TestRuntime, RuntimeCall, Signature, UncheckedExtrinsic as EvmUncheckedExtrinsic, -}; use domain_test_service::EcdsaKeyring::{Alice, Charlie}; use domain_test_service::EvmDomainNode; use domain_test_service::Sr25519Keyring::Ferdie; +use domain_test_service::evm_domain_test_runtime::{ + Runtime as TestRuntime, RuntimeCall, Signature, UncheckedExtrinsic as EvmUncheckedExtrinsic, +}; use ethereum::TransactionV2 as EthereumTransaction; use evm_domain_test_runtime::construct_extrinsic_raw_payload; use fp_rpc::EthereumRuntimeRPCApi; @@ -14,14 +14,14 @@ use sc_client_api::{HeaderBackend, StorageProof}; use sc_service::{BasePath, Role}; use sp_api::{ApiExt, ProvideRuntimeApi, TransactionOutcome}; use sp_core::ecdsa::Pair; -use sp_core::{keccak_256, Pair as _, U256}; +use sp_core::{Pair as _, U256, keccak_256}; use sp_domains::core_api::DomainCoreApi; use sp_domains::test_ethereum::{generate_eip1559_tx, generate_eip2930_tx, generate_legacy_tx}; -use sp_domains::test_ethereum_tx::{address_build, AccountInfo}; +use sp_domains::test_ethereum_tx::{AccountInfo, address_build}; +use sp_runtime::OpaqueExtrinsic; use sp_runtime::traits::Zero; use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidityError}; -use sp_runtime::OpaqueExtrinsic; -use subspace_test_service::{produce_block_with, produce_blocks, MockConsensusNode}; +use subspace_test_service::{MockConsensusNode, produce_block_with, produce_blocks}; use tempfile::TempDir; // This function depends on the macro-constructed `TestRuntime::RuntimeCall` enum, so it can't be @@ -223,7 +223,8 @@ async fn domain_bundle_storage_proof_benchmark() { "Result: Storage proof nodes: {:?}, keys accessed: {:?}, Storage proof total size (in mem): {:?}, Storage proof total size (in wire): {:?}", storage_proof.iter_nodes().count(), recorded_keys.len(), - storage_proof.clone() + storage_proof + .clone() .into_iter_nodes() .collect::>>() .iter() @@ -372,35 +373,39 @@ async fn storage_change_of_the_same_runtime_instance_should_perserved_cross_runt // A runtime instance can rollback changes safely. let runtime_instance = alice.client.runtime_api(); - assert!(runtime_instance - .check_extrinsics_and_do_pre_dispatch( - best_hash, - vec![transfer_with_big_tip_1.clone().into()], - best_number, - best_hash, - ) - .unwrap() - .is_ok()); - - assert!(runtime_instance - .execute_in_transaction(|api| { - if commit_mode { - TransactionOutcome::Commit(api.check_extrinsics_and_do_pre_dispatch( - best_hash, - vec![transfer_with_big_tip_2.clone().into()], - best_number, - best_hash, - )) - } else { - TransactionOutcome::Rollback(api.check_extrinsics_and_do_pre_dispatch( - best_hash, - vec![transfer_with_big_tip_2.clone().into()], - best_number, - best_hash, - )) - } - }) - .is_ok()); + assert!( + runtime_instance + .check_extrinsics_and_do_pre_dispatch( + best_hash, + vec![transfer_with_big_tip_1.clone().into()], + best_number, + best_hash, + ) + .unwrap() + .is_ok() + ); + + assert!( + runtime_instance + .execute_in_transaction(|api| { + if commit_mode { + TransactionOutcome::Commit(api.check_extrinsics_and_do_pre_dispatch( + best_hash, + vec![transfer_with_big_tip_2.clone().into()], + best_number, + best_hash, + )) + } else { + TransactionOutcome::Rollback(api.check_extrinsics_and_do_pre_dispatch( + best_hash, + vec![transfer_with_big_tip_2.clone().into()], + best_number, + best_hash, + )) + } + }) + .is_ok() + ); assert_eq!( runtime_instance diff --git a/crates/sp-domains-fraud-proof/src/verification.rs b/crates/sp-domains-fraud-proof/src/verification.rs index f4dbce0f09b..5d49ddac520 100644 --- a/crates/sp-domains-fraud-proof/src/verification.rs +++ b/crates/sp-domains-fraud-proof/src/verification.rs @@ -7,23 +7,23 @@ use crate::fraud_proof::{ }; use crate::storage_proof::{self, *}; use crate::{ - fraud_proof_runtime_interface, DomainInherentExtrinsic, DomainInherentExtrinsicData, - DomainStorageKeyRequest, StatelessDomainRuntimeCall, + DomainInherentExtrinsic, DomainInherentExtrinsicData, DomainStorageKeyRequest, + StatelessDomainRuntimeCall, fraud_proof_runtime_interface, }; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use domain_runtime_primitives::BlockNumber; use hash_db::Hasher; use parity_scale_codec::{Decode, Encode}; -use sp_core::storage::StorageKey; use sp_core::H256; +use sp_core::storage::StorageKey; use sp_domains::extrinsics::deduplicate_and_shuffle_extrinsics; use sp_domains::proof_provider_and_verifier::StorageProofVerifier; use sp_domains::valued_trie::valued_ordered_trie_root; use sp_domains::{ BlockFees, BundleValidity, DomainId, ExecutionReceipt, ExtrinsicDigest, HeaderHashFor, - HeaderHashingFor, HeaderNumberFor, InboxedBundle, InvalidBundleType, RuntimeId, Transfers, - INITIAL_DOMAIN_TX_RANGE, + HeaderHashingFor, HeaderNumberFor, INITIAL_DOMAIN_TX_RANGE, InboxedBundle, InvalidBundleType, + RuntimeId, Transfers, }; use sp_runtime::generic::Digest; use sp_runtime::traits::{ @@ -629,9 +629,10 @@ where // is invalid if let Some(invalid_extrinsic_index) = targeted_invalid_bundle_entry.invalid_extrinsic_index() && let InvalidBundlesProofData::Bundle(bundle_with_proof) = proof_data - && bundle_with_proof.bundle.extrinsics.len() as u32 <= invalid_extrinsic_index { - return Ok(()); - } + && bundle_with_proof.bundle.extrinsics.len() as u32 <= invalid_extrinsic_index + { + return Ok(()); + } match &invalid_bundle_type { InvalidBundleType::OutOfRangeTx(extrinsic_index) => { diff --git a/crates/sp-domains/src/core_api.rs b/crates/sp-domains/src/core_api.rs index 2aaca0ba904..cda289f7717 100644 --- a/crates/sp-domains/src/core_api.rs +++ b/crates/sp-domains/src/core_api.rs @@ -5,11 +5,11 @@ use crate::{BlockFees, DomainAllowlistUpdates, Transfers}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use domain_runtime_primitives::{ - opaque, Balance, CheckExtrinsicsValidityError, DecodeExtrinsicError, + Balance, CheckExtrinsicsValidityError, DecodeExtrinsicError, opaque, }; +use sp_runtime::Digest; use sp_runtime::generic::Era; use sp_runtime::traits::NumberFor; -use sp_runtime::Digest; use sp_weights::Weight; use subspace_core_primitives::U256; use subspace_runtime_primitives::{ExtrinsicFor, Moment}; diff --git a/crates/sp-domains/src/extrinsics.rs b/crates/sp-domains/src/extrinsics.rs index 8d84bc561c2..9705f3a6485 100644 --- a/crates/sp-domains/src/extrinsics.rs +++ b/crates/sp-domains/src/extrinsics.rs @@ -4,8 +4,8 @@ extern crate alloc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use domain_runtime_primitives::opaque::AccountId; -use rand::seq::SliceRandom; use rand::SeedableRng; +use rand::seq::SliceRandom; use rand_chacha::ChaCha8Rng; use sp_state_machine::trace; use sp_std::collections::btree_map::BTreeMap; diff --git a/crates/sp-domains/src/lib.rs b/crates/sp-domains/src/lib.rs index 40228190ca7..7b99f31bd91 100644 --- a/crates/sp-domains/src/lib.rs +++ b/crates/sp-domains/src/lib.rs @@ -37,11 +37,11 @@ use hex_literal::hex; use parity_scale_codec::{Codec, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; +use sp_core::H256; use sp_core::crypto::KeyTypeId; use sp_core::sr25519::vrf::VrfSignature; #[cfg(any(feature = "std", feature = "runtime-benchmarks"))] use sp_core::sr25519::vrf::{VrfPreOutput, VrfProof}; -use sp_core::H256; use sp_runtime::generic::OpaqueDigestItemId; use sp_runtime::traits::{ BlakeTwo256, CheckedAdd, Hash as HashT, Header as HeaderT, NumberFor, Zero, @@ -56,7 +56,7 @@ use sp_version::RuntimeVersion; use sp_weights::Weight; #[cfg(feature = "std")] use std::collections::BTreeSet; -use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash}; use subspace_core_primitives::pot::PotOutput; use subspace_core_primitives::solutions::bidirectional_distance; use subspace_core_primitives::{Randomness, U256}; @@ -634,12 +634,12 @@ impl } impl< - Number: Encode + Zero, - Hash: Encode + Default, - DomainNumber: Encode + Zero, - DomainHash: Clone + Encode + Default, - Balance: Encode + Zero + Default, - > ExecutionReceipt + Number: Encode + Zero, + Hash: Encode + Default, + DomainNumber: Encode + Zero, + DomainHash: Clone + Encode + Default, + Balance: Encode + Zero + Default, +> ExecutionReceipt { /// Returns the hash of this execution receipt. pub fn hash>(&self) -> DomainHash { diff --git a/crates/sp-domains/src/proof_provider_and_verifier.rs b/crates/sp-domains/src/proof_provider_and_verifier.rs index ac1bd678ba7..1a8268c9b5d 100644 --- a/crates/sp-domains/src/proof_provider_and_verifier.rs +++ b/crates/sp-domains/src/proof_provider_and_verifier.rs @@ -14,12 +14,12 @@ use parity_scale_codec::{Compact, Decode, Encode}; use scale_info::TypeInfo; use sp_core::storage::StorageKey; #[cfg(feature = "std")] -use sp_state_machine::prove_read; -#[cfg(feature = "std")] use sp_state_machine::TrieBackendBuilder; +#[cfg(feature = "std")] +use sp_state_machine::prove_read; use sp_std::fmt::Debug; use sp_std::marker::PhantomData; -use sp_trie::{read_trie_value, LayoutV1, StorageProof}; +use sp_trie::{LayoutV1, StorageProof, read_trie_value}; #[cfg(feature = "std")] use std::collections::BTreeSet; #[cfg(feature = "std")] diff --git a/crates/sp-domains/src/storage.rs b/crates/sp-domains/src/storage.rs index d317cf82545..c2b2e6d4c36 100644 --- a/crates/sp-domains/src/storage.rs +++ b/crates/sp-domains/src/storage.rs @@ -2,8 +2,8 @@ extern crate alloc; use crate::{ - evm_chain_id_storage_key, evm_contract_creation_allowed_by_storage_key, - self_domain_id_storage_key, DomainId, PermissionedActionAllowedBy, + DomainId, PermissionedActionAllowedBy, evm_chain_id_storage_key, + evm_contract_creation_allowed_by_storage_key, self_domain_id_storage_key, }; #[cfg(not(feature = "std"))] use alloc::vec::Vec; @@ -11,13 +11,13 @@ use domain_runtime_primitives::{EVMChainId, EthereumAccountId}; use hash_db::Hasher; use parity_scale_codec::{Codec, Decode, Encode}; use scale_info::TypeInfo; -use sp_core::storage::{well_known_keys, ChildInfo}; +use sp_core::storage::{ChildInfo, well_known_keys}; #[cfg(feature = "std")] use sp_core::storage::{Storage, StorageChild}; use sp_runtime::StateVersion; use sp_state_machine::{Backend, TrieBackend, TrieBackendBuilder}; use sp_std::collections::btree_map::BTreeMap; -use sp_trie::{empty_trie_root, LayoutV0, MemoryDB}; +use sp_trie::{LayoutV0, MemoryDB, empty_trie_root}; /// Create a new empty instance of in-memory backend. /// diff --git a/crates/sp-domains/src/test_ethereum_tx.rs b/crates/sp-domains/src/test_ethereum_tx.rs index ea7eb66dc3e..591e727bf6a 100644 --- a/crates/sp-domains/src/test_ethereum_tx.rs +++ b/crates/sp-domains/src/test_ethereum_tx.rs @@ -11,7 +11,7 @@ pub use ethereum::{ use frame_support::parameter_types; use rlp::RlpStream; use sp_core::crypto::AccountId32; -use sp_core::{keccak_256, H160, H256, U256}; +use sp_core::{H160, H256, U256, keccak_256}; parameter_types! { // `490000` is the genesis evm domain chain id diff --git a/crates/sp-domains/src/tests.rs b/crates/sp-domains/src/tests.rs index 38c3b86cbb4..6795c3a7b1e 100644 --- a/crates/sp-domains/src/tests.rs +++ b/crates/sp-domains/src/tests.rs @@ -1,8 +1,8 @@ -use crate::{signer_in_tx_range, InvalidBundleType, EMPTY_EXTRINSIC_ROOT}; +use crate::{EMPTY_EXTRINSIC_ROOT, InvalidBundleType, signer_in_tx_range}; use num_traits::ops::wrapping::{WrappingAdd, WrappingSub}; use parity_scale_codec::Encode; -use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_runtime::OpaqueExtrinsic; +use sp_runtime::traits::{BlakeTwo256, Hash}; use subspace_core_primitives::U256; #[test] diff --git a/crates/sp-domains/src/valued_trie.rs b/crates/sp-domains/src/valued_trie.rs index e2ebb77005c..ed52b16d2df 100644 --- a/crates/sp-domains/src/valued_trie.rs +++ b/crates/sp-domains/src/valued_trie.rs @@ -8,8 +8,8 @@ use parity_scale_codec::{Compact, Encode}; use sp_std::cmp::max; use trie_db::node::Value; use trie_db::{ - nibble_ops, ChildReference, NibbleSlice, NodeCodec, ProcessEncodedNode, TrieHash, TrieLayout, - TrieRoot, + ChildReference, NibbleSlice, NodeCodec, ProcessEncodedNode, TrieHash, TrieLayout, TrieRoot, + nibble_ops, }; macro_rules! exponential_out { @@ -260,8 +260,8 @@ mod test { use parity_scale_codec::{Compact, Encode}; use rand::rngs::StdRng; use rand::{Rng, SeedableRng}; - use sp_core::storage::StorageKey; use sp_core::H256; + use sp_core::storage::StorageKey; use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_trie::{LayoutV1, StorageProof}; use trie_db::node::Value; @@ -288,7 +288,6 @@ mod test { .iter() .zip(exts_length) .map(|(ext_hashed, ext_length)| { - if ext_length <= 32 { Value::Inline(ext_hashed) } else { @@ -322,12 +321,14 @@ mod test { ); // Verifying the proof with a wrong root/key will fail - assert!(StorageProofVerifier::::get_bare_value( - &H256::random(), - storage_proof.clone(), - storage_key.clone(), - ) - .is_err()); + assert!( + StorageProofVerifier::::get_bare_value( + &H256::random(), + storage_proof.clone(), + storage_key.clone(), + ) + .is_err() + ); let storage_key = StorageKey(Compact(i as u32 + 1).encode()); let result = StorageProofVerifier::::get_bare_value( @@ -354,7 +355,7 @@ mod test { fn craft_valid_storage_proof_with_multiple_keys() -> (sp_core::H256, StorageProof) { use sp_state_machine::backend::Backend; - use sp_state_machine::{prove_read, InMemoryBackend}; + use sp_state_machine::{InMemoryBackend, prove_read}; let state_version = sp_runtime::StateVersion::V1; diff --git a/crates/subspace-archiving/benches/archiving.rs b/crates/subspace-archiving/benches/archiving.rs index 97a9423f91e..6d05a761196 100644 --- a/crates/subspace-archiving/benches/archiving.rs +++ b/crates/subspace-archiving/benches/archiving.rs @@ -1,5 +1,5 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use rand::{thread_rng, Rng}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; +use rand::{Rng, thread_rng}; use std::num::NonZeroUsize; use subspace_archiving::archiver::Archiver; use subspace_core_primitives::pieces::Record; diff --git a/crates/subspace-archiving/src/archiver.rs b/crates/subspace-archiving/src/archiver.rs index a87d3e09bbd..1c5ad1d44f7 100644 --- a/crates/subspace-archiving/src/archiver.rs +++ b/crates/subspace-archiving/src/archiver.rs @@ -3,7 +3,7 @@ mod incremental_record_commitments; extern crate alloc; use crate::archiver::incremental_record_commitments::{ - update_record_commitments, IncrementalRecordCommitmentsState, + IncrementalRecordCommitmentsState, update_record_commitments, }; use alloc::collections::VecDeque; #[cfg(not(feature = "std"))] @@ -14,7 +14,7 @@ use core::cmp::Ordering; use parity_scale_codec::{Compact, CompactLen, Decode, Encode, Input, Output}; #[cfg(feature = "parallel")] use rayon::prelude::*; -use subspace_core_primitives::hashes::{blake3_254_hash_to_scalar, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_254_hash_to_scalar}; use subspace_core_primitives::objects::{BlockObject, BlockObjectMapping, GlobalObject}; use subspace_core_primitives::pieces::RawRecord; use subspace_core_primitives::segments::{ diff --git a/crates/subspace-archiving/src/archiver/incremental_record_commitments.rs b/crates/subspace-archiving/src/archiver/incremental_record_commitments.rs index 74bf096887c..10b9f58cef2 100644 --- a/crates/subspace-archiving/src/archiver/incremental_record_commitments.rs +++ b/crates/subspace-archiving/src/archiver/incremental_record_commitments.rs @@ -8,8 +8,8 @@ use core::ops::{Deref, DerefMut}; use parity_scale_codec::{Encode, Output}; #[cfg(feature = "parallel")] use rayon::prelude::*; -use subspace_core_primitives::pieces::RawRecord; use subspace_core_primitives::ScalarBytes; +use subspace_core_primitives::pieces::RawRecord; use subspace_kzg::{Commitment, Kzg, Scalar}; /// State of incremental record commitments, encapsulated to hide implementation details and diff --git a/crates/subspace-archiving/src/reconstructor.rs b/crates/subspace-archiving/src/reconstructor.rs index eafe33db8b3..1ae3f3bdd9a 100644 --- a/crates/subspace-archiving/src/reconstructor.rs +++ b/crates/subspace-archiving/src/reconstructor.rs @@ -8,12 +8,12 @@ use alloc::string::String; use alloc::vec::Vec; use core::mem; use parity_scale_codec::Decode; +use subspace_core_primitives::BlockNumber; use subspace_core_primitives::pieces::{Piece, RawRecord}; use subspace_core_primitives::segments::{ ArchivedBlockProgress, ArchivedHistorySegment, LastArchivedBlock, RecordedHistorySegment, SegmentHeader, SegmentIndex, }; -use subspace_core_primitives::BlockNumber; use subspace_erasure_coding::ErasureCoding; use subspace_kzg::Scalar; @@ -214,12 +214,13 @@ impl Reconstructor { let segment_index = segment_header.segment_index(); if let Some(last_segment_index) = self.last_segment_index - && last_segment_index != segment_index { - return Err(ReconstructorError::IncorrectSegmentOrder { - expected_segment_index: last_segment_index + SegmentIndex::ONE, - actual_segment_index: segment_index + SegmentIndex::ONE, - }); - } + && last_segment_index != segment_index + { + return Err(ReconstructorError::IncorrectSegmentOrder { + expected_segment_index: last_segment_index + SegmentIndex::ONE, + actual_segment_index: segment_index + SegmentIndex::ONE, + }); + } self.last_segment_index .replace(segment_index + SegmentIndex::ONE); diff --git a/crates/subspace-archiving/tests/integration/archiver.rs b/crates/subspace-archiving/tests/integration/archiver.rs index ece5508734c..f2534c29573 100644 --- a/crates/subspace-archiving/tests/integration/archiver.rs +++ b/crates/subspace-archiving/tests/integration/archiver.rs @@ -1,5 +1,5 @@ use parity_scale_codec::{Compact, CompactLen, Decode, Encode}; -use rand::{thread_rng, Rng}; +use rand::{Rng, thread_rng}; #[cfg(feature = "parallel")] use rayon::prelude::*; use std::assert_matches::assert_matches; @@ -515,14 +515,16 @@ fn one_byte_smaller_segment() { ); // Cutting just one byte more is not sufficient to produce a segment, this is a protection // against code regressions - assert!(Archiver::new(kzg, erasure_coding) - .add_block( - vec![0u8; block_size - 1], - BlockObjectMapping::default(), - true - ) - .archived_segments - .is_empty()); + assert!( + Archiver::new(kzg, erasure_coding) + .add_block( + vec![0u8; block_size - 1], + BlockObjectMapping::default(), + true + ) + .archived_segments + .is_empty() + ); } #[test] @@ -549,10 +551,12 @@ fn spill_over_edge_case() { - Compact::compact_len(&(RecordedHistorySegment::SIZE as u32)) // We leave three bytes at the end intentionally - 3; - assert!(archiver - .add_block(vec![0u8; block_size], BlockObjectMapping::default(), true) - .archived_segments - .is_empty()); + assert!( + archiver + .add_block(vec![0u8; block_size], BlockObjectMapping::default(), true) + .archived_segments + .is_empty() + ); // Here we add one more block with internal length that takes 4 bytes in compact length // encoding + one more for enum variant, this should result in new segment being created, but diff --git a/crates/subspace-archiving/tests/integration/reconstructor.rs b/crates/subspace-archiving/tests/integration/reconstructor.rs index 706c65b4cf7..65b3de7732d 100644 --- a/crates/subspace-archiving/tests/integration/reconstructor.rs +++ b/crates/subspace-archiving/tests/integration/reconstructor.rs @@ -1,4 +1,4 @@ -use rand::{thread_rng, Rng}; +use rand::{Rng, thread_rng}; use std::assert_matches::assert_matches; use std::iter; use std::num::NonZeroUsize; diff --git a/crates/subspace-core-primitives/src/lib.rs b/crates/subspace-core-primitives/src/lib.rs index e2819fb142f..f36c96bfd84 100644 --- a/crates/subspace-core-primitives/src/lib.rs +++ b/crates/subspace-core-primitives/src/lib.rs @@ -24,7 +24,7 @@ pub mod solutions; #[cfg(test)] mod tests; -use crate::hashes::{blake3_hash, blake3_hash_list, Blake3Hash}; +use crate::hashes::{Blake3Hash, blake3_hash, blake3_hash_list}; use core::fmt; use derive_more::{Add, AsMut, AsRef, Deref, DerefMut, Display, Div, From, Into, Mul, Rem, Sub}; use num_traits::{WrappingAdd, WrappingSub}; diff --git a/crates/subspace-core-primitives/src/objects.rs b/crates/subspace-core-primitives/src/objects.rs index 9dd41b94389..89ca1c8901e 100644 --- a/crates/subspace-core-primitives/src/objects.rs +++ b/crates/subspace-core-primitives/src/objects.rs @@ -8,9 +8,9 @@ use crate::hashes::Blake3Hash; use crate::pieces::PieceIndex; use core::default::Default; use parity_scale_codec::{Decode, Encode}; +use scale_info::TypeInfo; use scale_info::prelude::vec; use scale_info::prelude::vec::Vec; -use scale_info::TypeInfo; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; diff --git a/crates/subspace-core-primitives/src/pieces.rs b/crates/subspace-core-primitives/src/pieces.rs index e7eb495629e..23bf07cc320 100644 --- a/crates/subspace-core-primitives/src/pieces.rs +++ b/crates/subspace-core-primitives/src/pieces.rs @@ -3,8 +3,8 @@ #[cfg(not(feature = "std"))] extern crate alloc; -use crate::segments::{ArchivedHistorySegment, RecordedHistorySegment, SegmentIndex}; use crate::ScalarBytes; +use crate::segments::{ArchivedHistorySegment, RecordedHistorySegment, SegmentIndex}; #[cfg(feature = "serde")] use ::serde::{Deserialize, Serialize}; #[cfg(feature = "serde")] diff --git a/crates/subspace-core-primitives/src/pos.rs b/crates/subspace-core-primitives/src/pos.rs index e7b9567ecb3..32a05209876 100644 --- a/crates/subspace-core-primitives/src/pos.rs +++ b/crates/subspace-core-primitives/src/pos.rs @@ -1,6 +1,6 @@ //! Proof of space-related data structures. -use crate::hashes::{blake3_hash, Blake3Hash}; +use crate::hashes::{Blake3Hash, blake3_hash}; use core::fmt; use derive_more::{Deref, DerefMut, From, Into}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; diff --git a/crates/subspace-core-primitives/src/pot.rs b/crates/subspace-core-primitives/src/pot.rs index c664f64b77d..743e4223500 100644 --- a/crates/subspace-core-primitives/src/pot.rs +++ b/crates/subspace-core-primitives/src/pot.rs @@ -1,7 +1,7 @@ //! Proof of time-related data structures. -use crate::hashes::{blake3_hash, blake3_hash_list, Blake3Hash}; use crate::Randomness; +use crate::hashes::{Blake3Hash, blake3_hash, blake3_hash_list}; use core::num::NonZeroU8; use core::str::FromStr; use core::{fmt, mem}; diff --git a/crates/subspace-core-primitives/src/sectors.rs b/crates/subspace-core-primitives/src/sectors.rs index c62643c37ff..d10f8e5050b 100644 --- a/crates/subspace-core-primitives/src/sectors.rs +++ b/crates/subspace-core-primitives/src/sectors.rs @@ -3,13 +3,13 @@ #[cfg(test)] mod tests; +use crate::U256; use crate::hashes::{ - blake3_hash_list, blake3_hash_list_with_key, blake3_hash_with_key, Blake3Hash, + Blake3Hash, blake3_hash_list, blake3_hash_list_with_key, blake3_hash_with_key, }; use crate::pieces::{PieceIndex, PieceOffset, Record}; use crate::pos::PosSeed; use crate::segments::{HistorySize, SegmentCommitment}; -use crate::U256; use core::hash::Hash; use core::iter::Step; use core::num::{NonZeroU64, TryFromIntError}; diff --git a/crates/subspace-core-primitives/src/segments.rs b/crates/subspace-core-primitives/src/segments.rs index 2c29c9dc193..675cfd6b3c4 100644 --- a/crates/subspace-core-primitives/src/segments.rs +++ b/crates/subspace-core-primitives/src/segments.rs @@ -3,9 +3,9 @@ #[cfg(not(feature = "std"))] extern crate alloc; -use crate::hashes::{blake3_hash, Blake3Hash}; -use crate::pieces::{FlatPieces, Piece, PieceIndex, RawRecord}; use crate::BlockNumber; +use crate::hashes::{Blake3Hash, blake3_hash}; +use crate::pieces::{FlatPieces, Piece, PieceIndex, RawRecord}; #[cfg(not(feature = "std"))] use alloc::boxed::Box; use core::array::TryFromSliceError; diff --git a/crates/subspace-core-primitives/src/tests.rs b/crates/subspace-core-primitives/src/tests.rs index bdb78c93e12..3464d5c73bc 100644 --- a/crates/subspace-core-primitives/src/tests.rs +++ b/crates/subspace-core-primitives/src/tests.rs @@ -1,6 +1,6 @@ +use crate::U256; use crate::pieces::PieceIndex; use crate::segments::{ArchivedHistorySegment, RecordedHistorySegment, SegmentIndex}; -use crate::U256; #[test] fn piece_distance_middle() { diff --git a/crates/subspace-erasure-coding/benches/commitments.rs b/crates/subspace-erasure-coding/benches/commitments.rs index 1d8c5244cf5..7a19e1a0b13 100644 --- a/crates/subspace-erasure-coding/benches/commitments.rs +++ b/crates/subspace-erasure-coding/benches/commitments.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use kzg::G1; use rust_kzg_blst::types::g1::FsG1; use std::num::NonZeroUsize; diff --git a/crates/subspace-erasure-coding/src/lib.rs b/crates/subspace-erasure-coding/src/lib.rs index 7ea884974e1..4567985f067 100644 --- a/crates/subspace-erasure-coding/src/lib.rs +++ b/crates/subspace-erasure-coding/src/lib.rs @@ -11,7 +11,7 @@ use alloc::sync::Arc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::num::NonZeroUsize; -use kzg::{FFTSettings, PolyRecover, DAS, FFTG1, G1}; +use kzg::{DAS, FFTG1, FFTSettings, G1, PolyRecover}; use rust_kzg_blst::types::fft_settings::FsFFTSettings; use rust_kzg_blst::types::g1::FsG1; use rust_kzg_blst::types::poly::FsPoly; diff --git a/crates/subspace-fake-runtime-api/src/lib.rs b/crates/subspace-fake-runtime-api/src/lib.rs index 128a181326e..bbc95da13f8 100644 --- a/crates/subspace-fake-runtime-api/src/lib.rs +++ b/crates/subspace-fake-runtime-api/src/lib.rs @@ -7,7 +7,7 @@ use domain_runtime_primitives::{ use frame_support::weights::Weight; use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges}; use sp_core::crypto::KeyTypeId; -use sp_core::{OpaqueMetadata, H256}; +use sp_core::{H256, OpaqueMetadata}; use sp_domains::bundle_producer_election::BundleProducerElectionParams; use sp_domains::{ DomainAllowlistUpdates, DomainId, DomainInstanceData, ExecutionReceiptFor, OperatorId, diff --git a/crates/subspace-farmer-components/benches/auditing.rs b/crates/subspace-farmer-components/benches/auditing.rs index 4fed8091483..3507496508e 100644 --- a/crates/subspace-farmer-components/benches/auditing.rs +++ b/crates/subspace-farmer-components/benches/auditing.rs @@ -1,4 +1,4 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; +use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main}; use futures::executor::block_on; use rand::prelude::*; use std::collections::HashSet; @@ -7,25 +7,25 @@ use std::io::Write; use std::num::{NonZeroU64, NonZeroUsize}; use std::{env, fs, slice}; use subspace_archiving::archiver::Archiver; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::hashes::Blake3Hash; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::sectors::SectorId; use subspace_core_primitives::segments::{HistorySize, RecordedHistorySegment}; use subspace_core_primitives::solutions::SolutionRange; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::auditing::audit_plot_sync; use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; use subspace_farmer_components::plotting::{ - plot_sector, CpuRecordsEncoder, PlotSectorOptions, PlottedSector, + CpuRecordsEncoder, PlotSectorOptions, PlottedSector, plot_sector, }; use subspace_farmer_components::sector::{ - sector_size, SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, + SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, sector_size, }; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; -use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::Table; +use subspace_proof_of_space::chia::ChiaTable; type PosTable = ChiaTable; diff --git a/crates/subspace-farmer-components/benches/plotting.rs b/crates/subspace-farmer-components/benches/plotting.rs index 0ce11286dc5..779794221c2 100644 --- a/crates/subspace-farmer-components/benches/plotting.rs +++ b/crates/subspace-farmer-components/benches/plotting.rs @@ -1,19 +1,19 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; +use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main}; use futures::executor::block_on; use rand::prelude::*; use std::env; use std::num::{NonZeroU64, NonZeroUsize}; use subspace_archiving::archiver::Archiver; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::segments::{HistorySize, RecordedHistorySegment}; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; -use subspace_farmer_components::plotting::{plot_sector, CpuRecordsEncoder, PlotSectorOptions}; -use subspace_farmer_components::sector::sector_size; use subspace_farmer_components::FarmerProtocolInfo; +use subspace_farmer_components::plotting::{CpuRecordsEncoder, PlotSectorOptions, plot_sector}; +use subspace_farmer_components::sector::sector_size; use subspace_kzg::Kzg; -use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::Table; +use subspace_proof_of_space::chia::ChiaTable; type PosTable = ChiaTable; diff --git a/crates/subspace-farmer-components/benches/proving.rs b/crates/subspace-farmer-components/benches/proving.rs index edc4211eaac..af1fd80c57a 100644 --- a/crates/subspace-farmer-components/benches/proving.rs +++ b/crates/subspace-farmer-components/benches/proving.rs @@ -1,6 +1,6 @@ #![feature(exact_size_is_empty)] -use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion, Throughput}; +use criterion::{BatchSize, Criterion, Throughput, black_box, criterion_group, criterion_main}; use futures::executor::block_on; use parking_lot::Mutex; use rand::prelude::*; @@ -11,24 +11,24 @@ use std::io::Write; use std::num::{NonZeroU64, NonZeroUsize}; use std::{env, fs, slice}; use subspace_archiving::archiver::Archiver; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::hashes::Blake3Hash; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::pos::PosSeed; use subspace_core_primitives::sectors::SectorId; use subspace_core_primitives::segments::{HistorySize, RecordedHistorySegment}; use subspace_core_primitives::solutions::SolutionRange; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::auditing::audit_plot_sync; use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; use subspace_farmer_components::plotting::{ - plot_sector, CpuRecordsEncoder, PlotSectorOptions, PlottedSector, + CpuRecordsEncoder, PlotSectorOptions, PlottedSector, plot_sector, }; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; use subspace_farmer_components::sector::{ - sector_size, SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, + SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, sector_size, }; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::{Table, TableGenerator}; diff --git a/crates/subspace-farmer-components/benches/reading.rs b/crates/subspace-farmer-components/benches/reading.rs index 6a1a602a7c1..c2b114fac6e 100644 --- a/crates/subspace-farmer-components/benches/reading.rs +++ b/crates/subspace-farmer-components/benches/reading.rs @@ -1,6 +1,6 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput}; -use futures::executor::block_on; +use criterion::{Criterion, Throughput, black_box, criterion_group, criterion_main}; use futures::FutureExt; +use futures::executor::block_on; use parking_lot::Mutex; use rand::prelude::*; use std::fs::OpenOptions; @@ -8,23 +8,23 @@ use std::io::Write; use std::num::{NonZeroU64, NonZeroUsize}; use std::{env, fs, slice}; use subspace_archiving::archiver::Archiver; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::{PieceOffset, Record}; use subspace_core_primitives::sectors::SectorId; use subspace_core_primitives::segments::{HistorySize, RecordedHistorySegment}; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; use subspace_farmer_components::plotting::{ - plot_sector, CpuRecordsEncoder, PlotSectorOptions, PlottedSector, + CpuRecordsEncoder, PlotSectorOptions, PlottedSector, plot_sector, }; -use subspace_farmer_components::reading::{read_piece, ReadSectorRecordChunksMode}; +use subspace_farmer_components::reading::{ReadSectorRecordChunksMode, read_piece}; use subspace_farmer_components::sector::{ - sector_size, SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, + SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, sector_size, }; use subspace_farmer_components::{FarmerProtocolInfo, ReadAt, ReadAtSync}; use subspace_kzg::Kzg; -use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::Table; +use subspace_proof_of_space::chia::ChiaTable; type PosTable = ChiaTable; diff --git a/crates/subspace-farmer-components/src/auditing.rs b/crates/subspace-farmer-components/src/auditing.rs index 5bb35197e25..c2f1893c513 100644 --- a/crates/subspace-farmer-components/src/auditing.rs +++ b/crates/subspace-farmer-components/src/auditing.rs @@ -5,7 +5,7 @@ //! [`plotting`](crate::plotting) module earlier. use crate::proving::SolutionCandidates; -use crate::sector::{sector_size, SectorContentsMap, SectorMetadataChecksummed}; +use crate::sector::{SectorContentsMap, SectorMetadataChecksummed, sector_size}; use crate::{ReadAtOffset, ReadAtSync}; use rayon::prelude::*; use std::collections::HashSet; diff --git a/crates/subspace-farmer-components/src/plotting.rs b/crates/subspace-farmer-components/src/plotting.rs index b408cf90b44..1e62feb2f59 100644 --- a/crates/subspace-farmer-components/src/plotting.rs +++ b/crates/subspace-farmer-components/src/plotting.rs @@ -6,26 +6,26 @@ //! Plotted sectors can be written to plot and later [`read`](crate::reading) and/or //! [`audited`](crate::auditing)/[`proven`](crate::proving) using other modules of this crate. +use crate::FarmerProtocolInfo; use crate::sector::{ - sector_record_chunks_size, sector_size, EncodedChunksUsed, RawSector, RecordMetadata, - SectorContentsMap, SectorMetadata, SectorMetadataChecksummed, + EncodedChunksUsed, RawSector, RecordMetadata, SectorContentsMap, SectorMetadata, + SectorMetadataChecksummed, sector_record_chunks_size, sector_size, }; use crate::segment_reconstruction::recover_missing_piece; -use crate::FarmerProtocolInfo; use async_lock::{Mutex as AsyncMutex, Semaphore}; use backoff::future::retry; use backoff::{Error as BackoffError, ExponentialBackoff}; use futures::stream::FuturesUnordered; -use futures::{select, StreamExt}; +use futures::{StreamExt, select}; use parity_scale_codec::{Decode, Encode}; use parking_lot::Mutex; use rayon::prelude::*; use std::collections::HashMap; use std::simd::Simd; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use subspace_core_primitives::hashes::{blake3_hash, blake3_hash_parallel, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash, blake3_hash_parallel}; use subspace_core_primitives::pieces::{Piece, PieceIndex, PieceOffset, Record}; use subspace_core_primitives::pos::PosSeed; use subspace_core_primitives::sectors::{SBucket, SectorId, SectorIndex}; diff --git a/crates/subspace-farmer-components/src/proving.rs b/crates/subspace-farmer-components/src/proving.rs index 0410586ab01..0dddfcb8dda 100644 --- a/crates/subspace-farmer-components/src/proving.rs +++ b/crates/subspace-farmer-components/src/proving.rs @@ -5,7 +5,7 @@ use crate::auditing::ChunkCandidate; use crate::reading::{ - read_record_metadata, read_sector_record_chunks, ReadSectorRecordChunksMode, ReadingError, + ReadSectorRecordChunksMode, ReadingError, read_record_metadata, read_sector_record_chunks, }; use crate::sector::{ SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, diff --git a/crates/subspace-farmer-components/src/reading.rs b/crates/subspace-farmer-components/src/reading.rs index 5a31e1a142a..948cadb6862 100644 --- a/crates/subspace-farmer-components/src/reading.rs +++ b/crates/subspace-farmer-components/src/reading.rs @@ -5,22 +5,22 @@ //! only used for cold storage purposes or when there is a need to prove a solution to consensus. use crate::sector::{ - sector_record_chunks_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, - SectorMetadataChecksummed, + RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, + sector_record_chunks_size, }; use crate::{ReadAt, ReadAtAsync, ReadAtSync}; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use std::str::FromStr; use std::{fmt, io}; +use subspace_core_primitives::ScalarBytes; use subspace_core_primitives::hashes::blake3_hash; use subspace_core_primitives::pieces::{Piece, PieceOffset, Record}; use subspace_core_primitives::sectors::{SBucket, SectorId}; -use subspace_core_primitives::ScalarBytes; use subspace_erasure_coding::ErasureCoding; use subspace_kzg::Scalar; use subspace_proof_of_space::{Table, TableGenerator}; diff --git a/crates/subspace-farmer-components/src/sector.rs b/crates/subspace-farmer-components/src/sector.rs index ee45cbb763b..694fa42f529 100644 --- a/crates/subspace-farmer-components/src/sector.rs +++ b/crates/subspace-farmer-components/src/sector.rs @@ -13,7 +13,7 @@ use std::mem::ManuallyDrop; use std::ops::{Deref, DerefMut}; use std::{mem, slice}; use subspace_core_primitives::checksum::Blake3Checksummed; -use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash}; use subspace_core_primitives::pieces::{PieceOffset, Record, RecordCommitment, RecordWitness}; use subspace_core_primitives::sectors::{SBucket, SectorIndex}; use subspace_core_primitives::segments::{HistorySize, SegmentIndex}; @@ -104,14 +104,14 @@ impl Deref for SectorMetadataChecksummed { #[inline] fn deref(&self) -> &Self::Target { - &self.0 .0 + &self.0.0 } } impl DerefMut for SectorMetadataChecksummed { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 .0 + &mut self.0.0 } } diff --git a/crates/subspace-farmer-components/src/segment_reconstruction.rs b/crates/subspace-farmer-components/src/segment_reconstruction.rs index e2d6915320a..118e9229e1a 100644 --- a/crates/subspace-farmer-components/src/segment_reconstruction.rs +++ b/crates/subspace-farmer-components/src/segment_reconstruction.rs @@ -2,7 +2,7 @@ use subspace_archiving::piece_reconstructor::{PiecesReconstructor, Reconstructor use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_data_retrieval::piece_getter::PieceGetter; use subspace_data_retrieval::segment_downloading::{ - download_segment_pieces, SegmentDownloadingError, + SegmentDownloadingError, download_segment_pieces, }; use subspace_erasure_coding::ErasureCoding; use subspace_kzg::Kzg; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/benchmark.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/benchmark.rs index 761c4841301..f5e4e1bcda1 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/benchmark.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/benchmark.rs @@ -1,7 +1,7 @@ use crate::PosTable; use anyhow::anyhow; use clap::{Parser, Subcommand}; -use criterion::{black_box, BatchSize, Criterion, Throughput}; +use criterion::{BatchSize, Criterion, Throughput, black_box}; use parking_lot::Mutex; use rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder}; use std::collections::HashSet; @@ -112,24 +112,25 @@ pub(crate) fn benchmark(benchmark_args: BenchmarkArgs) -> anyhow::Result<()> { } fn audit(audit_options: AuditOptions) -> anyhow::Result<()> { - let single_disk_farm_info = - match SingleDiskFarm::collect_summary(audit_options.disk_farm.clone()) { - SingleDiskFarmSummary::Found { info, directory: _ } => info, - SingleDiskFarmSummary::NotFound { directory } => { - return Err(anyhow!( - "No single disk farm info found, make sure {} is a valid path to the farm and \ + let single_disk_farm_info = match SingleDiskFarm::collect_summary( + audit_options.disk_farm.clone(), + ) { + SingleDiskFarmSummary::Found { info, directory: _ } => info, + SingleDiskFarmSummary::NotFound { directory } => { + return Err(anyhow!( + "No single disk farm info found, make sure {} is a valid path to the farm and \ process have permissions to access it", - directory.display() - )); - } - SingleDiskFarmSummary::Error { directory, error } => { - return Err(anyhow!( + directory.display() + )); + } + SingleDiskFarmSummary::Error { directory, error } => { + return Err(anyhow!( "Failed to open single disk farm info, make sure {} is a valid path to the farm \ and process have permissions to access it: {error}", directory.display() )); - } - }; + } + }; match single_disk_farm_info { SingleDiskFarmInfo::V0 { .. } => { @@ -291,24 +292,25 @@ where } fn prove(prove_options: ProveOptions) -> anyhow::Result<()> { - let single_disk_farm_info = - match SingleDiskFarm::collect_summary(prove_options.disk_farm.clone()) { - SingleDiskFarmSummary::Found { info, directory: _ } => info, - SingleDiskFarmSummary::NotFound { directory } => { - return Err(anyhow!( - "No single disk farm info found, make sure {} is a valid path to the farm and \ + let single_disk_farm_info = match SingleDiskFarm::collect_summary( + prove_options.disk_farm.clone(), + ) { + SingleDiskFarmSummary::Found { info, directory: _ } => info, + SingleDiskFarmSummary::NotFound { directory } => { + return Err(anyhow!( + "No single disk farm info found, make sure {} is a valid path to the farm and \ process have permissions to access it", - directory.display() - )); - } - SingleDiskFarmSummary::Error { directory, error } => { - return Err(anyhow!( + directory.display() + )); + } + SingleDiskFarmSummary::Error { directory, error } => { + return Err(anyhow!( "Failed to open single disk farm info, make sure {} is a valid path to the farm \ and process have permissions to access it: {error}", directory.display() )); - } - }; + } + }; match single_disk_farm_info { SingleDiskFarmInfo::V0 { .. } => { diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster.rs index cfd520d0530..721167de6a6 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster.rs @@ -3,17 +3,17 @@ mod controller; mod farmer; mod plotter; -use crate::commands::cluster::cache::{cache, CacheArgs}; -use crate::commands::cluster::controller::{controller, ControllerArgs}; -use crate::commands::cluster::farmer::{farmer, FarmerArgs}; -use crate::commands::cluster::plotter::{plotter, PlotterArgs}; +use crate::commands::cluster::cache::{CacheArgs, cache}; +use crate::commands::cluster::controller::{ControllerArgs, controller}; +use crate::commands::cluster::farmer::{FarmerArgs, farmer}; +use crate::commands::cluster::plotter::{PlotterArgs, plotter}; use crate::utils::shutdown_signal; use anyhow::anyhow; use async_nats::ServerAddr; use backoff::ExponentialBackoff; use clap::{Parser, Subcommand}; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use prometheus_client::registry::Registry; use std::env::current_exe; use std::mem; @@ -21,7 +21,7 @@ use std::net::SocketAddr; use std::time::Duration; use subspace_farmer::cluster::nats_client::NatsClient; use subspace_farmer::utils::AsyncJoinOnDrop; -use subspace_metrics::{start_prometheus_metrics_server, RegistryAdapter}; +use subspace_metrics::{RegistryAdapter, start_prometheus_metrics_server}; use subspace_proof_of_space::Table; const REQUEST_RETRY_MAX_ELAPSED_TIME: Duration = Duration::from_mins(1); diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs index cdf58d5106a..5c1bc67b5ea 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/cache.rs @@ -1,8 +1,8 @@ use anyhow::anyhow; use bytesize::ByteSize; use clap::Parser; -use futures::stream::FuturesUnordered; use futures::StreamExt; +use futures::stream::FuturesUnordered; use prometheus_client::registry::Registry; use std::fs; use std::future::Future; @@ -145,13 +145,14 @@ pub(super) async fn cache( for cache in &disk_caches { if !cache.directory.exists() - && let Err(error) = fs::create_dir(&cache.directory) { - return Err(anyhow!( - "Directory {} doesn't exist and can't be created: {}", - cache.directory.display(), - error - )); - } + && let Err(error) = fs::create_dir(&cache.directory) + { + return Err(anyhow!( + "Directory {} doesn't exist and can't be created: {}", + cache.directory.display(), + error + )); + } } None }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/controller.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/controller.rs index 3ab81d3c178..d1e9b2454fc 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/controller.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/controller.rs @@ -1,36 +1,36 @@ use crate::commands::cluster::cache::CACHE_IDENTIFICATION_BROADCAST_INTERVAL; use crate::commands::cluster::farmer::FARMER_IDENTIFICATION_BROADCAST_INTERVAL; use crate::commands::shared::derive_libp2p_keypair; -use crate::commands::shared::network::{configure_network, NetworkArgs}; +use crate::commands::shared::network::{NetworkArgs, configure_network}; use anyhow::anyhow; use async_lock::{RwLock as AsyncRwLock, Semaphore}; use backoff::ExponentialBackoff; use clap::{Parser, ValueHint}; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use prometheus_client::registry::Registry; use std::future::Future; use std::num::NonZeroUsize; use std::path::PathBuf; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::time::Duration; use subspace_farmer::cluster::controller::caches::maintain_caches; use subspace_farmer::cluster::controller::controller_service; -use subspace_farmer::cluster::controller::farms::{maintain_farms, FarmIndex}; +use subspace_farmer::cluster::controller::farms::{FarmIndex, maintain_farms}; use subspace_farmer::cluster::nats_client::NatsClient; use subspace_farmer::farm::plotted_pieces::PlottedPieces; use subspace_farmer::farmer_cache::{FarmerCache, FarmerCaches}; use subspace_farmer::farmer_piece_getter::piece_validator::SegmentCommitmentPieceValidator; use subspace_farmer::farmer_piece_getter::{DsnCacheRetryPolicy, FarmerPieceGetter}; +use subspace_farmer::node_client::NodeClient; use subspace_farmer::node_client::caching_proxy_node_client::CachingProxyNodeClient; use subspace_farmer::node_client::rpc_node_client::RpcNodeClient; -use subspace_farmer::node_client::NodeClient; use subspace_farmer::single_disk_farm::identity::Identity; -use subspace_farmer::utils::{run_future_in_dedicated_thread, AsyncJoinOnDrop}; +use subspace_farmer::utils::{AsyncJoinOnDrop, run_future_in_dedicated_thread}; use subspace_kzg::Kzg; use subspace_networking::utils::piece_provider::PieceProvider; -use tracing::{info, info_span, Instrument}; +use tracing::{Instrument, info, info_span}; /// Get piece retry attempts number. const PIECE_GETTER_MAX_RETRIES: u16 = 7; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs index c49f15b4ce7..71f9602129a 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/farmer.rs @@ -7,36 +7,36 @@ use backoff::ExponentialBackoff; use bytesize::ByteSize; use clap::Parser; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use parking_lot::Mutex; use prometheus_client::registry::Registry; use std::fs; use std::future::Future; use std::num::NonZeroUsize; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::time::Duration; -use subspace_core_primitives::pieces::Record; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::pieces::Record; use subspace_erasure_coding::ErasureCoding; use subspace_farmer::cluster::controller::ClusterNodeClient; use subspace_farmer::cluster::farmer::farmer_service; use subspace_farmer::cluster::nats_client::NatsClient; use subspace_farmer::cluster::plotter::ClusterPlotter; use subspace_farmer::farm::Farm; -use subspace_farmer::node_client::caching_proxy_node_client::CachingProxyNodeClient; use subspace_farmer::node_client::NodeClient; +use subspace_farmer::node_client::caching_proxy_node_client::CachingProxyNodeClient; use subspace_farmer::single_disk_farm::{ SingleDiskFarm, SingleDiskFarmError, SingleDiskFarmOptions, }; use subspace_farmer::utils::ss58::parse_ss58_reward_address; use subspace_farmer::utils::{ - recommended_number_of_farming_threads, run_future_in_dedicated_thread, AsyncJoinOnDrop, + AsyncJoinOnDrop, recommended_number_of_farming_threads, run_future_in_dedicated_thread, }; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; use subspace_kzg::Kzg; use subspace_proof_of_space::Table; -use tracing::{error, info, info_span, warn, Instrument}; +use tracing::{Instrument, error, info, info_span, warn}; const FARM_ERROR_PRINT_INTERVAL: Duration = Duration::from_secs(30); /// Interval between farmer self-identification broadcast messages @@ -191,13 +191,14 @@ where for farm in &disk_farms { if !farm.directory.exists() - && let Err(error) = fs::create_dir(&farm.directory) { - return Err(anyhow!( - "Directory {} doesn't exist and can't be created: {}", - farm.directory.display(), - error - )); - } + && let Err(error) = fs::create_dir(&farm.directory) + { + return Err(anyhow!( + "Directory {} doesn't exist and can't be created: {}", + farm.directory.display(), + error + )); + } } None }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/plotter.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/plotter.rs index a62d0430a5f..1f1c0ae3ec7 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/plotter.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/cluster/plotter.rs @@ -14,15 +14,15 @@ use subspace_erasure_coding::ErasureCoding; use subspace_farmer::cluster::controller::ClusterPieceGetter; use subspace_farmer::cluster::nats_client::NatsClient; use subspace_farmer::cluster::plotter::plotter_service; +use subspace_farmer::plotter::Plotter; use subspace_farmer::plotter::cpu::CpuPlotter; +#[cfg(feature = "_gpu")] +use subspace_farmer::plotter::gpu::GpuPlotter; #[cfg(feature = "cuda")] use subspace_farmer::plotter::gpu::cuda::CudaRecordsEncoder; #[cfg(feature = "rocm")] use subspace_farmer::plotter::gpu::rocm::RocmRecordsEncoder; -#[cfg(feature = "_gpu")] -use subspace_farmer::plotter::gpu::GpuPlotter; use subspace_farmer::plotter::pool::PoolPlotter; -use subspace_farmer::plotter::Plotter; use subspace_farmer::utils::{ create_plotting_thread_pool_manager, parse_cpu_cores_sets, thread_pool_core_indices, }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs index bc29a3246d1..3b7b1e444b0 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/farm.rs @@ -1,5 +1,5 @@ -use crate::commands::shared::network::{configure_network, NetworkArgs}; -use crate::commands::shared::{derive_libp2p_keypair, DiskFarm, PlottingThreadPriority}; +use crate::commands::shared::network::{NetworkArgs, configure_network}; +use crate::commands::shared::{DiskFarm, PlottingThreadPriority, derive_libp2p_keypair}; use crate::utils::shutdown_signal; use anyhow::anyhow; use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock, Semaphore}; @@ -8,7 +8,7 @@ use bytesize::ByteSize; use clap::{Parser, ValueHint}; use futures::channel::oneshot; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use parking_lot::Mutex; use prometheus_client::registry::Registry; use std::fs; @@ -18,8 +18,8 @@ use std::pin::pin; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; -use subspace_core_primitives::pieces::Record; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::pieces::Record; use subspace_data_retrieval::piece_getter::PieceGetter; use subspace_erasure_coding::ErasureCoding; use subspace_farmer::farm::plotted_pieces::PlottedPieces; @@ -27,34 +27,34 @@ use subspace_farmer::farm::{PlottedSectors, SectorPlottingDetails, SectorUpdate} use subspace_farmer::farmer_cache::{FarmerCache, FarmerCaches}; use subspace_farmer::farmer_piece_getter::piece_validator::SegmentCommitmentPieceValidator; use subspace_farmer::farmer_piece_getter::{DsnCacheRetryPolicy, FarmerPieceGetter}; +use subspace_farmer::node_client::NodeClient; use subspace_farmer::node_client::caching_proxy_node_client::CachingProxyNodeClient; use subspace_farmer::node_client::rpc_node_client::RpcNodeClient; -use subspace_farmer::node_client::NodeClient; +use subspace_farmer::plotter::Plotter; use subspace_farmer::plotter::cpu::CpuPlotter; +#[cfg(feature = "_gpu")] +use subspace_farmer::plotter::gpu::GpuPlotter; #[cfg(feature = "cuda")] use subspace_farmer::plotter::gpu::cuda::CudaRecordsEncoder; #[cfg(feature = "rocm")] use subspace_farmer::plotter::gpu::rocm::RocmRecordsEncoder; -#[cfg(feature = "_gpu")] -use subspace_farmer::plotter::gpu::GpuPlotter; use subspace_farmer::plotter::pool::PoolPlotter; -use subspace_farmer::plotter::Plotter; use subspace_farmer::single_disk_farm::identity::Identity; use subspace_farmer::single_disk_farm::{ SingleDiskFarm, SingleDiskFarmError, SingleDiskFarmOptions, }; use subspace_farmer::utils::ss58::parse_ss58_reward_address; use subspace_farmer::utils::{ - create_plotting_thread_pool_manager, parse_cpu_cores_sets, + AsyncJoinOnDrop, create_plotting_thread_pool_manager, parse_cpu_cores_sets, recommended_number_of_farming_threads, run_future_in_dedicated_thread, - thread_pool_core_indices, AsyncJoinOnDrop, + thread_pool_core_indices, }; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; use subspace_kzg::Kzg; -use subspace_metrics::{start_prometheus_metrics_server, RegistryAdapter}; +use subspace_metrics::{RegistryAdapter, start_prometheus_metrics_server}; use subspace_networking::utils::piece_provider::PieceProvider; use subspace_proof_of_space::Table; -use tracing::{error, info, info_span, warn, Instrument}; +use tracing::{Instrument, error, info, info_span, warn}; /// Get piece retry attempts number. const PIECE_GETTER_MAX_RETRIES: u16 = 7; @@ -376,13 +376,14 @@ where for farm in &disk_farms { if !farm.directory.exists() - && let Err(error) = fs::create_dir(&farm.directory) { - return Err(anyhow!( - "Directory {} doesn't exist and can't be created: {}", - farm.directory.display(), - error - )); - } + && let Err(error) = fs::create_dir(&farm.directory) + { + return Err(anyhow!( + "Directory {} doesn't exist and can't be created: {}", + farm.directory.display(), + error + )); + } } None }; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared.rs index 4991479320e..187fe937b2c 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; use std::str::FromStr; use subspace_farmer::single_disk_farm::{SingleDiskFarm, SingleDiskFarmSummary}; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; -use subspace_networking::libp2p::identity::{ed25519, Keypair}; +use subspace_networking::libp2p::identity::{Keypair, ed25519}; use thread_priority::ThreadPriority; use zeroize::Zeroizing; diff --git a/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared/network.rs b/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared/network.rs index 15939365892..9fe52ad69c7 100644 --- a/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared/network.rs +++ b/crates/subspace-farmer/src/bin/subspace-farmer/commands/shared/network.rs @@ -8,13 +8,13 @@ use std::hash::Hash; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::path::Path; use std::sync::{Arc, Weak}; +use subspace_farmer::KNOWN_PEERS_CACHE_SIZE; use subspace_farmer::farm::plotted_pieces::PlottedPieces; use subspace_farmer::farmer_cache::FarmerCaches; use subspace_farmer::node_client::NodeClientExt; -use subspace_farmer::KNOWN_PEERS_CACHE_SIZE; +use subspace_networking::libp2p::Multiaddr; use subspace_networking::libp2p::identity::Keypair; use subspace_networking::libp2p::multiaddr::Protocol; -use subspace_networking::libp2p::Multiaddr; use subspace_networking::protocols::request_response::handlers::cached_piece_by_index::{ CachedPieceByIndexRequest, CachedPieceByIndexRequestHandler, CachedPieceByIndexResponse, PieceResult, @@ -28,11 +28,11 @@ use subspace_networking::protocols::request_response::handlers::segment_header:: use subspace_networking::utils::multihash::ToMultihash; use subspace_networking::utils::strip_peer_id; use subspace_networking::{ - construct, Config, KademliaMode, KnownPeersManager, KnownPeersManagerConfig, Node, NodeRunner, - WeakNode, + Config, KademliaMode, KnownPeersManager, KnownPeersManagerConfig, Node, NodeRunner, WeakNode, + construct, }; use subspace_rpc_primitives::MAX_SEGMENT_HEADERS_PER_REQUEST; -use tracing::{debug, error, info, warn, Instrument}; +use tracing::{Instrument, debug, error, info, warn}; /// How many segment headers can be requested at a time. /// diff --git a/crates/subspace-farmer/src/cluster/cache.rs b/crates/subspace-farmer/src/cluster/cache.rs index ed950fdfb87..dde245eb583 100644 --- a/crates/subspace-farmer/src/cluster/cache.rs +++ b/crates/subspace-farmer/src/cluster/cache.rs @@ -16,7 +16,7 @@ use anyhow::anyhow; use async_trait::async_trait; use derive_more::{Display, From}; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select, stream}; use parity_scale_codec::{Decode, Encode, EncodeLike, Input, Output}; use std::collections::BTreeSet; use std::pin::Pin; @@ -24,7 +24,7 @@ use std::task::Poll; use std::time::{Duration, Instant}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use tokio::time::MissedTickBehavior; -use tracing::{debug, error, info, info_span, trace, warn, Instrument}; +use tracing::{Instrument, debug, error, info, info_span, trace, warn}; use ulid::Ulid; const MIN_CACHE_IDENTIFICATION_INTERVAL: Duration = Duration::from_secs(1); diff --git a/crates/subspace-farmer/src/cluster/controller.rs b/crates/subspace-farmer/src/cluster/controller.rs index ef2402cb246..169814a4482 100644 --- a/crates/subspace-farmer/src/cluster/controller.rs +++ b/crates/subspace-farmer/src/cluster/controller.rs @@ -23,7 +23,7 @@ use async_trait::async_trait; use futures::channel::mpsc; use futures::future::FusedFuture; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select, stream}; use parity_scale_codec::{Decode, Encode}; use parking_lot::Mutex; use rand::prelude::*; diff --git a/crates/subspace-farmer/src/cluster/controller/caches.rs b/crates/subspace-farmer/src/cluster/controller/caches.rs index b49e54c4959..7e3825f7eeb 100644 --- a/crates/subspace-farmer/src/cluster/controller/caches.rs +++ b/crates/subspace-farmer/src/cluster/controller/caches.rs @@ -9,18 +9,18 @@ use crate::cluster::cache::{ ClusterCacheDetailsRequest, ClusterCacheId, ClusterCacheIdentifyBroadcast, ClusterPieceCache, ClusterPieceCacheDetails, }; -use crate::cluster::controller::stream_map::StreamMap; use crate::cluster::controller::ClusterControllerCacheIdentifyBroadcast; +use crate::cluster::controller::stream_map::StreamMap; use crate::cluster::nats_client::NatsClient; use crate::farm::PieceCache; use crate::farmer_cache::FarmerCache; use anyhow::anyhow; use futures::channel::oneshot; use futures::future::FusedFuture; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use parking_lot::Mutex; -use std::future::{ready, Future}; -use std::pin::{pin, Pin}; +use std::future::{Future, ready}; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::time::MissedTickBehavior; @@ -110,10 +110,12 @@ pub async fn maintain_caches( let mut cache_reinitialization = (Box::pin(ready(())) as Pin>>).fuse(); - let cache_identify_subscription = pin!(nats_client - .subscribe_to_broadcasts::(Some(cache_group), None) - .await - .map_err(|error| anyhow!("Failed to subscribe to cache identify broadcast: {error}"))?); + let cache_identify_subscription = pin!( + nats_client + .subscribe_to_broadcasts::(Some(cache_group), None) + .await + .map_err(|error| anyhow!("Failed to subscribe to cache identify broadcast: {error}"))? + ); // Request cache to identify themselves if let Err(error) = nats_client @@ -144,10 +146,11 @@ pub async fn maintain_caches( let _handler_id = farmer_cache.on_sync_progress(Arc::new(move |&progress| { if progress == 100.0 - && let Some(sync_finish_sender) = sync_finish_sender.lock().take() { - // Result doesn't matter - let _ = sync_finish_sender.send(()); - } + && let Some(sync_finish_sender) = sync_finish_sender.lock().take() + { + // Result doesn't matter + let _ = sync_finish_sender.send(()); + } })); farmer_cache diff --git a/crates/subspace-farmer/src/cluster/controller/farms.rs b/crates/subspace-farmer/src/cluster/controller/farms.rs index a75c67c6025..42032d717be 100644 --- a/crates/subspace-farmer/src/cluster/controller/farms.rs +++ b/crates/subspace-farmer/src/cluster/controller/farms.rs @@ -4,8 +4,8 @@ //! about which pieces are plotted in which sectors of which farm up to date. Implementation //! automatically handles dynamic farm addition and removal, etc. -use crate::cluster::controller::stream_map::StreamMap; use crate::cluster::controller::ClusterControllerFarmerIdentifyBroadcast; +use crate::cluster::controller::stream_map::StreamMap; use crate::cluster::farmer::{ ClusterFarm, ClusterFarmerFarmDetails, ClusterFarmerFarmDetailsRequest, ClusterFarmerId, ClusterFarmerIdentifyBroadcast, @@ -16,7 +16,7 @@ use crate::farm::{Farm, FarmId, SectorPlottingDetails, SectorUpdate}; use anyhow::anyhow; use async_lock::RwLock as AsyncRwLock; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use parking_lot::Mutex; use std::collections::{HashMap, HashSet}; use std::mem; @@ -203,10 +203,14 @@ pub async fn maintain_farms( let mut farms_to_add_remove = StreamMap::default(); let mut farms = FuturesUnordered::new(); - let farmer_identify_subscription = pin!(nats_client - .subscribe_to_broadcasts::(None, None) - .await - .map_err(|error| anyhow!("Failed to subscribe to farmer identify broadcast: {error}"))?); + let farmer_identify_subscription = pin!( + nats_client + .subscribe_to_broadcasts::(None, None) + .await + .map_err(|error| anyhow!( + "Failed to subscribe to farmer identify broadcast: {error}" + ))? + ); // Request farmer to identify themselves if let Err(error) = nats_client diff --git a/crates/subspace-farmer/src/cluster/controller/stream_map.rs b/crates/subspace-farmer/src/cluster/controller/stream_map.rs index a9a6acce6b3..ea0da22f42c 100644 --- a/crates/subspace-farmer/src/cluster/controller/stream_map.rs +++ b/crates/subspace-farmer/src/cluster/controller/stream_map.rs @@ -113,8 +113,8 @@ where #[cfg(test)] mod tests { use crate::cluster::controller::stream_map::StreamMap; - use futures::stream::FusedStream; use futures::StreamExt; + use futures::stream::FusedStream; use std::task::Context; fn assert_is_terminated<'a, R: 'a>(stream_map: &StreamMap<'a, u16, R>) { diff --git a/crates/subspace-farmer/src/cluster/farmer.rs b/crates/subspace-farmer/src/cluster/farmer.rs index e4422d77554..f4b398eb165 100644 --- a/crates/subspace-farmer/src/cluster/farmer.rs +++ b/crates/subspace-farmer/src/cluster/farmer.rs @@ -22,10 +22,10 @@ use derive_more::{Display, From}; use event_listener_primitives::Bag; use futures::channel::mpsc; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select, stream}; use parity_scale_codec::{Decode, Encode, EncodeLike, Input, Output}; use std::future::Future; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::time::{Duration, Instant}; use subspace_core_primitives::pieces::{Piece, PieceOffset}; @@ -33,7 +33,7 @@ use subspace_core_primitives::sectors::SectorIndex; use subspace_farmer_components::plotting::PlottedSector; use subspace_rpc_primitives::SolutionResponse; use tokio::time::MissedTickBehavior; -use tracing::{debug, error, info_span, trace, warn, Instrument}; +use tracing::{Instrument, debug, error, info_span, trace, warn}; use ulid::Ulid; const BROADCAST_NOTIFICATIONS_BUFFER: usize = 1000; @@ -48,12 +48,12 @@ pub struct ClusterFarmerId(Ulid); impl Encode for ClusterFarmerId { #[inline] fn size_hint(&self) -> usize { - Encode::size_hint(&self.0 .0) + Encode::size_hint(&self.0.0) } #[inline] fn encode_to(&self, output: &mut O) { - Encode::encode_to(&self.0 .0, output) + Encode::encode_to(&self.0.0, output) } } diff --git a/crates/subspace-farmer/src/cluster/nats_client.rs b/crates/subspace-farmer/src/cluster/nats_client.rs index 1fa73f14f1b..b86b74a5ab5 100644 --- a/crates/subspace-farmer/src/cluster/nats_client.rs +++ b/crates/subspace-farmer/src/cluster/nats_client.rs @@ -19,11 +19,11 @@ use async_nats::{ Client, ConnectOptions, HeaderMap, HeaderValue, Message, PublishError, RequestError, RequestErrorKind, Subject, SubscribeError, Subscriber, ToServerAddrs, }; -use backoff::backoff::Backoff; use backoff::ExponentialBackoff; +use backoff::backoff::Backoff; use futures::channel::mpsc; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select}; use parity_scale_codec::{Decode, Encode}; use std::any::type_name; use std::collections::VecDeque; @@ -36,7 +36,7 @@ use std::task::{Context, Poll}; use std::time::Duration; use std::{fmt, mem}; use thiserror::Error; -use tracing::{debug, error, trace, warn, Instrument}; +use tracing::{Instrument, debug, error, trace, warn}; use ulid::Ulid; const EXPECTED_MESSAGE_SIZE: usize = 2 * 1024 * 1024; @@ -857,9 +857,10 @@ impl NatsClient { loop { // Try to fill the buffer if buffer.is_empty() - && let Some(element) = response_stream.next().await { - buffer.push_back(element); - } + && let Some(element) = response_stream.next().await + { + buffer.push_back(element); + } while buffer.encoded_size() < approximate_max_message_size && let Some(element) = response_stream.next().now_or_never().flatten() { diff --git a/crates/subspace-farmer/src/cluster/plotter.rs b/crates/subspace-farmer/src/cluster/plotter.rs index b1cfab45fb8..fc60e647e0d 100644 --- a/crates/subspace-farmer/src/cluster/plotter.rs +++ b/crates/subspace-farmer/src/cluster/plotter.rs @@ -12,15 +12,15 @@ use crate::utils::AsyncJoinOnDrop; use anyhow::anyhow; use async_nats::RequestErrorKind; use async_trait::async_trait; -use backoff::backoff::Backoff; use backoff::ExponentialBackoff; +use backoff::backoff::Backoff; use bytes::Bytes; use derive_more::Display; use event_listener_primitives::{Bag, HandlerId}; use futures::channel::mpsc; use futures::future::FusedFuture; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Sink, SinkExt, StreamExt}; +use futures::{FutureExt, Sink, SinkExt, StreamExt, select, stream}; use parity_scale_codec::{Decode, Encode}; use std::error::Error; use std::future::pending; @@ -29,14 +29,14 @@ use std::pin::pin; use std::sync::Arc; use std::task::Poll; use std::time::{Duration, Instant}; -use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::sectors::SectorIndex; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::plotting::PlottedSector; use subspace_farmer_components::sector::sector_size; -use subspace_farmer_components::FarmerProtocolInfo; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio::time::MissedTickBehavior; -use tracing::{debug, info, info_span, trace, warn, Instrument}; +use tracing::{Instrument, debug, info, info_span, trace, warn}; use ulid::Ulid; const FREE_CAPACITY_CHECK_INTERVAL: Duration = Duration::from_secs(1); diff --git a/crates/subspace-farmer/src/disk_piece_cache.rs b/crates/subspace-farmer/src/disk_piece_cache.rs index 26bead4f27a..b7b4587df84 100644 --- a/crates/subspace-farmer/src/disk_piece_cache.rs +++ b/crates/subspace-farmer/src/disk_piece_cache.rs @@ -7,27 +7,27 @@ mod tests; use crate::disk_piece_cache::metrics::DiskPieceCacheMetrics; use crate::farm; use crate::farm::{FarmError, PieceCacheId, PieceCacheOffset}; -use crate::single_disk_farm::direct_io_file::{DirectIoFile, DISK_SECTOR_SIZE}; +use crate::single_disk_farm::direct_io_file::{DISK_SECTOR_SIZE, DirectIoFile}; use crate::utils::AsyncJoinOnDrop; use async_trait::async_trait; use bytes::BytesMut; use futures::channel::mpsc; -use futures::{stream, SinkExt, Stream, StreamExt}; +use futures::{SinkExt, Stream, StreamExt, stream}; use parking_lot::Mutex; use prometheus_client::registry::Registry; use std::num::NonZeroU32; use std::path::Path; -use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; use std::task::Poll; use std::{fs, io}; -use subspace_core_primitives::hashes::{blake3_hash_list, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash_list}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_farmer_components::file_ext::FileExt; use thiserror::Error; use tokio::runtime::Handle; use tokio::task; -use tracing::{debug, info, warn, Span}; +use tracing::{Span, debug, info, warn}; /// How many pieces should be skipped before stopping to check the rest of contents, this allows to /// not miss most of the pieces after one or two corrupted pieces diff --git a/crates/subspace-farmer/src/farm/plotted_pieces.rs b/crates/subspace-farmer/src/farm/plotted_pieces.rs index b9c4ae7cea6..f09f3e21d93 100644 --- a/crates/subspace-farmer/src/farm/plotted_pieces.rs +++ b/crates/subspace-farmer/src/farm/plotted_pieces.rs @@ -4,8 +4,8 @@ use crate::farm::{FarmError, PieceReader}; use async_trait::async_trait; use rand::prelude::*; use rayon::prelude::*; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::fmt; use std::future::Future; use std::hash::Hash; diff --git a/crates/subspace-farmer/src/farmer_cache.rs b/crates/subspace-farmer/src/farmer_cache.rs index 41fccc13d7e..4f63c3b1105 100644 --- a/crates/subspace-farmer/src/farmer_cache.rs +++ b/crates/subspace-farmer/src/farmer_cache.rs @@ -18,7 +18,7 @@ use event_listener_primitives::{Bag, HandlerId}; use futures::channel::mpsc; use futures::future::{Either, FusedFuture}; use futures::stream::{FuturesOrdered, FuturesUnordered}; -use futures::{select, stream, FutureExt, SinkExt, Stream, StreamExt}; +use futures::{FutureExt, SinkExt, Stream, StreamExt, select, stream}; use parking_lot::{Mutex, RwLock}; use prometheus_client::registry::Registry; use rand::prelude::*; @@ -26,21 +26,21 @@ use rayon::prelude::*; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; use std::future::join; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::task::Poll; use std::time::Duration; use std::{fmt, mem}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_core_primitives::segments::{SegmentHeader, SegmentIndex}; use subspace_data_retrieval::piece_getter::PieceGetter; -use subspace_networking::libp2p::kad::RecordKey; +use subspace_networking::KeyWithDistance; use subspace_networking::libp2p::PeerId; +use subspace_networking::libp2p::kad::RecordKey; use subspace_networking::utils::multihash::ToMultihash; -use subspace_networking::KeyWithDistance; use tokio::sync::Semaphore; use tokio::task::yield_now; -use tracing::{debug, error, info, info_span, trace, warn, Instrument}; +use tracing::{Instrument, debug, error, info, info_span, trace, warn}; const WORKER_CHANNEL_CAPACITY: usize = 100; const SYNC_BATCH_SIZE: usize = 256; @@ -1487,11 +1487,7 @@ impl FarmerCache { .any(|found| async move { found }) .await; - if found { - None - } else { - Some(piece_index) - } + if found { None } else { Some(piece_index) } }) .collect::>() .filter_map(|maybe_piece_index| async move { maybe_piece_index }) diff --git a/crates/subspace-farmer/src/farmer_cache/piece_cache_state.rs b/crates/subspace-farmer/src/farmer_cache/piece_cache_state.rs index 140a7e9f27b..63cdedd861f 100644 --- a/crates/subspace-farmer/src/farmer_cache/piece_cache_state.rs +++ b/crates/subspace-farmer/src/farmer_cache/piece_cache_state.rs @@ -2,9 +2,9 @@ use crate::farmer_cache::{CacheBackend, CacheIndex, FarmerCacheOffset}; use std::collections::btree_map::Values; use std::collections::{BTreeMap, HashMap, VecDeque}; use subspace_core_primitives::pieces::PieceIndex; +use subspace_networking::KeyWithDistance; use subspace_networking::libp2p::PeerId; use subspace_networking::utils::multihash::ToMultihash; -use subspace_networking::KeyWithDistance; use tracing::{debug, trace}; #[derive(Debug, Default, Clone)] diff --git a/crates/subspace-farmer/src/farmer_cache/tests.rs b/crates/subspace-farmer/src/farmer_cache/tests.rs index 244b292b3a6..be88d23672f 100644 --- a/crates/subspace-farmer/src/farmer_cache/tests.rs +++ b/crates/subspace-farmer/src/farmer_cache/tests.rs @@ -1,5 +1,5 @@ use crate::disk_piece_cache::DiskPieceCache; -use crate::farmer_cache::{decode_piece_index_from_record_key, FarmerCache}; +use crate::farmer_cache::{FarmerCache, decode_piece_index_from_record_key}; use crate::node_client::NodeClient; use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; @@ -10,8 +10,8 @@ use rand::prelude::*; use std::collections::HashMap; use std::num::{NonZeroU32, NonZeroU64}; use std::pin::Pin; -use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_core_primitives::segments::{ @@ -214,9 +214,10 @@ async fn basic() { move |progress| { if *progress == 100.0 - && let Some(sender) = sender.lock().take() { - sender.send(()).unwrap(); - } + && let Some(sender) = sender.lock().take() + { + sender.send(()).unwrap(); + } } })) .detach(); @@ -264,10 +265,12 @@ async fn basic() { } // Other piece indices are not requested or cached - assert!(farmer_cache - .get_piece(PieceIndex::from(10).to_multihash()) - .await - .is_none()); + assert!( + farmer_cache + .get_piece(PieceIndex::from(10).to_multihash()) + .await + .is_none() + ); } // Update current segment header such that we keep-up after initial sync is triggered @@ -334,10 +337,12 @@ async fn basic() { for piece_index in requested_pieces { if !stored_pieces.contains(&piece_index) { // Other piece indices are not stored anymore - assert!(farmer_cache - .get_piece(PieceIndex::from(10).to_multihash()) - .await - .is_none()); + assert!( + farmer_cache + .get_piece(PieceIndex::from(10).to_multihash()) + .await + .is_none() + ); } } } @@ -400,10 +405,12 @@ async fn basic() { for piece_index in requested_pieces { if !stored_pieces.contains(&piece_index) { // Other piece indices are not stored anymore - assert!(farmer_cache - .get_piece(PieceIndex::from(10).to_multihash()) - .await - .is_none()); + assert!( + farmer_cache + .get_piece(PieceIndex::from(10).to_multihash()) + .await + .is_none() + ); } } } @@ -429,9 +436,10 @@ async fn basic() { move |progress| { if *progress == 100.0 - && let Some(sender) = sender.lock().take() { - sender.send(()).unwrap(); - } + && let Some(sender) = sender.lock().take() + { + sender.send(()).unwrap(); + } } })) .detach(); @@ -524,9 +532,10 @@ async fn duplicate_indices() { move |progress| { if *progress == 100.0 - && let Some(sender) = sender.lock().take() { - sender.send(()).unwrap(); - } + && let Some(sender) = sender.lock().take() + { + sender.send(()).unwrap(); + } } })) .detach(); @@ -575,9 +584,10 @@ async fn duplicate_indices() { move |progress| { if *progress == 100.0 - && let Some(sender) = sender.lock().take() { - sender.send(()).unwrap(); - } + && let Some(sender) = sender.lock().take() + { + sender.send(()).unwrap(); + } } })) .detach(); diff --git a/crates/subspace-farmer/src/farmer_piece_getter.rs b/crates/subspace-farmer/src/farmer_piece_getter.rs index ad284dfdc07..437b760704c 100644 --- a/crates/subspace-farmer/src/farmer_piece_getter.rs +++ b/crates/subspace-farmer/src/farmer_piece_getter.rs @@ -5,13 +5,13 @@ use crate::farmer_cache::FarmerCaches; use crate::node_client::NodeClient; use async_lock::RwLock as AsyncRwLock; use async_trait::async_trait; +use backoff::ExponentialBackoff; use backoff::backoff::Backoff; use backoff::future::retry; -use backoff::ExponentialBackoff; use futures::channel::mpsc; use futures::future::FusedFuture; use futures::stream::FuturesUnordered; -use futures::{stream, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, stream}; use std::fmt; use std::hash::Hash; use std::pin::Pin; @@ -165,14 +165,15 @@ where .and_then(|plotted_pieces| plotted_pieces.read_piece(piece_index)); if let Some(read_piece_fut) = maybe_read_piece_fut - && let Some(piece) = read_piece_fut.await { - trace!(%piece_index, "Got piece from local plot successfully"); - inner - .farmer_caches - .maybe_store_additional_piece(piece_index, &piece) - .await; - return Some(piece); - } + && let Some(piece) = read_piece_fut.await + { + trace!(%piece_index, "Got piece from local plot successfully"); + inner + .farmer_caches + .maybe_store_additional_piece(piece_index, &piece) + .await; + return Some(piece); + } // L1 piece acquisition trace!(%piece_index, "Getting piece from DSN L1."); diff --git a/crates/subspace-farmer/src/farmer_piece_getter/piece_validator.rs b/crates/subspace-farmer/src/farmer_piece_getter/piece_validator.rs index 8d45a7ffc1b..3d87ff455f7 100644 --- a/crates/subspace-farmer/src/farmer_piece_getter/piece_validator.rs +++ b/crates/subspace-farmer/src/farmer_piece_getter/piece_validator.rs @@ -4,9 +4,9 @@ use crate::node_client::NodeClient; use async_trait::async_trait; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_kzg::Kzg; +use subspace_networking::Node; use subspace_networking::libp2p::PeerId; use subspace_networking::utils::piece_provider::PieceValidator; -use subspace_networking::Node; use subspace_verification::is_piece_valid; use tracing::{error, warn}; diff --git a/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs b/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs index 8d89b106fc3..15ff37dd839 100644 --- a/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs +++ b/crates/subspace-farmer/src/node_client/caching_proxy_node_client.rs @@ -5,15 +5,15 @@ use crate::node_client::{NodeClient, NodeClientExt}; use crate::utils::AsyncJoinOnDrop; use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock}; use async_trait::async_trait; -use futures::{select, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select}; use std::pin::Pin; use std::sync::Arc; use std::time::{Duration, Instant}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_core_primitives::segments::{SegmentHeader, SegmentIndex}; use subspace_rpc_primitives::{ - FarmerAppInfo, RewardSignatureResponse, RewardSigningInfo, SlotInfo, SolutionResponse, - MAX_SEGMENT_HEADERS_PER_REQUEST, + FarmerAppInfo, MAX_SEGMENT_HEADERS_PER_REQUEST, RewardSignatureResponse, RewardSigningInfo, + SlotInfo, SolutionResponse, }; use tokio::sync::watch; use tokio_stream::wrappers::WatchStream; @@ -63,9 +63,10 @@ impl SegmentHeaders { NC: NodeClient, { if let Some(last_synced) = &self.last_synced - && last_synced.elapsed() < SEGMENT_HEADERS_SYNC_INTERVAL { - return Ok(()); - } + && last_synced.elapsed() < SEGMENT_HEADERS_SYNC_INTERVAL + { + return Ok(()); + } self.last_synced.replace(Instant::now()); let mut segment_index_offset = SegmentIndex::from(self.segment_headers.len() as u64); diff --git a/crates/subspace-farmer/src/plotter.rs b/crates/subspace-farmer/src/plotter.rs index e99e3d93fa6..a73d5ab7491 100644 --- a/crates/subspace-farmer/src/plotter.rs +++ b/crates/subspace-farmer/src/plotter.rs @@ -12,16 +12,16 @@ pub mod pool; use async_trait::async_trait; use bytes::Bytes; -use futures::channel::mpsc; use futures::Stream; +use futures::channel::mpsc; use std::fmt; use std::pin::Pin; use std::sync::Arc; use std::time::Duration; -use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::PublicKey; -use subspace_farmer_components::plotting::PlottedSector; +use subspace_core_primitives::sectors::SectorIndex; use subspace_farmer_components::FarmerProtocolInfo; +use subspace_farmer_components::plotting::PlottedSector; /// Sector plotting progress pub enum SectorPlottingProgress { diff --git a/crates/subspace-farmer/src/plotter/cpu.rs b/crates/subspace-farmer/src/plotter/cpu.rs index 1ee7981fc27..b84e9d0115c 100644 --- a/crates/subspace-farmer/src/plotter/cpu.rs +++ b/crates/subspace-farmer/src/plotter/cpu.rs @@ -12,7 +12,7 @@ use bytes::Bytes; use event_listener_primitives::{Bag, HandlerId}; use futures::channel::mpsc; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Sink, SinkExt, StreamExt}; +use futures::{FutureExt, Sink, SinkExt, StreamExt, select, stream}; use prometheus_client::registry::Registry; use std::any::type_name; use std::error::Error; @@ -21,23 +21,23 @@ use std::future::pending; use std::marker::PhantomData; use std::num::NonZeroUsize; use std::pin::pin; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::task::Poll; use std::time::Instant; -use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::sectors::SectorIndex; use subspace_data_retrieval::piece_getter::PieceGetter; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::plotting::{ - download_sector, encode_sector, write_sector, CpuRecordsEncoder, DownloadSectorOptions, - EncodeSectorOptions, PlottingError, + CpuRecordsEncoder, DownloadSectorOptions, EncodeSectorOptions, PlottingError, download_sector, + encode_sector, write_sector, }; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use subspace_proof_of_space::Table; use tokio::task::yield_now; -use tracing::{warn, Instrument}; +use tracing::{Instrument, warn}; /// Type alias used for event handlers pub type HandlerFn3 = Arc; diff --git a/crates/subspace-farmer/src/plotter/cpu/metrics.rs b/crates/subspace-farmer/src/plotter/cpu/metrics.rs index 17c9d6d1acc..290a31caf11 100644 --- a/crates/subspace-farmer/src/plotter/cpu/metrics.rs +++ b/crates/subspace-farmer/src/plotter/cpu/metrics.rs @@ -2,7 +2,7 @@ use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::gauge::Gauge; -use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; +use prometheus_client::metrics::histogram::{Histogram, exponential_buckets}; use prometheus_client::registry::{Registry, Unit}; use std::num::NonZeroUsize; use std::sync::atomic::{AtomicI64, AtomicU64}; diff --git a/crates/subspace-farmer/src/plotter/gpu.rs b/crates/subspace-farmer/src/plotter/gpu.rs index 9a901900c78..f75c81cf942 100644 --- a/crates/subspace-farmer/src/plotter/gpu.rs +++ b/crates/subspace-farmer/src/plotter/gpu.rs @@ -17,29 +17,29 @@ use bytes::Bytes; use event_listener_primitives::{Bag, HandlerId}; use futures::channel::mpsc; use futures::stream::FuturesUnordered; -use futures::{select, stream, FutureExt, Sink, SinkExt, StreamExt}; +use futures::{FutureExt, Sink, SinkExt, StreamExt, select, stream}; use prometheus_client::registry::Registry; use std::error::Error; use std::fmt; use std::future::pending; use std::num::TryFromIntError; use std::pin::pin; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::task::Poll; use std::time::Instant; -use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::sectors::SectorIndex; use subspace_data_retrieval::piece_getter::PieceGetter; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::plotting::{ - download_sector, encode_sector, write_sector, DownloadSectorOptions, EncodeSectorOptions, - PlottingError, RecordsEncoder, + DownloadSectorOptions, EncodeSectorOptions, PlottingError, RecordsEncoder, download_sector, + encode_sector, write_sector, }; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use tokio::task::yield_now; -use tracing::{warn, Instrument}; +use tracing::{Instrument, warn}; /// Type alias used for event handlers pub type HandlerFn3 = Arc; diff --git a/crates/subspace-farmer/src/plotter/gpu/cuda.rs b/crates/subspace-farmer/src/plotter/gpu/cuda.rs index 57633166313..6fd4457edc6 100644 --- a/crates/subspace-farmer/src/plotter/gpu/cuda.rs +++ b/crates/subspace-farmer/src/plotter/gpu/cuda.rs @@ -3,10 +3,10 @@ use crate::plotter::gpu::GpuRecordsEncoder; use async_lock::Mutex as AsyncMutex; use parking_lot::Mutex; -use rayon::{current_thread_index, ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder}; +use rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder, current_thread_index}; use std::process::exit; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use subspace_core_primitives::pieces::{PieceOffset, Record}; use subspace_core_primitives::sectors::SectorId; use subspace_farmer_components::plotting::RecordsEncoder; @@ -47,30 +47,32 @@ impl RecordsEncoder for CudaRecordsEncoder { let plotting_error = Mutex::new(None::); self.thread_pool.scope(|scope| { - scope.spawn_broadcast(|_scope, _ctx| loop { - // Take mutex briefly to make sure encoding is allowed right now - self.global_mutex.lock_blocking(); + scope.spawn_broadcast(|_scope, _ctx| { + loop { + // Take mutex briefly to make sure encoding is allowed right now + self.global_mutex.lock_blocking(); - // This instead of `while` above because otherwise mutex will be held for the - // duration of the loop and will limit concurrency to 1 record - let Some(((piece_offset, record), mut encoded_chunks_used)) = - iter.lock().next() - else { - return; - }; - let pos_seed = sector_id.derive_evaluation_seed(piece_offset); + // This instead of `while` above because otherwise mutex will be held for the + // duration of the loop and will limit concurrency to 1 record + let Some(((piece_offset, record), mut encoded_chunks_used)) = + iter.lock().next() + else { + return; + }; + let pos_seed = sector_id.derive_evaluation_seed(piece_offset); - if let Err(error) = self.cuda_device.generate_and_encode_pospace( - &pos_seed, - record, - encoded_chunks_used.iter_mut(), - ) { - plotting_error.lock().replace(error); - return; - } + if let Err(error) = self.cuda_device.generate_and_encode_pospace( + &pos_seed, + record, + encoded_chunks_used.iter_mut(), + ) { + plotting_error.lock().replace(error); + return; + } - if abort_early.load(Ordering::Relaxed) { - return; + if abort_early.load(Ordering::Relaxed) { + return; + } } }); }); @@ -100,9 +102,7 @@ impl CudaRecordsEncoder { eprintln!("panic on thread {}: {:?}", thread_name(index), panic_info); } else { // We want to guarantee exit, rather than panicking in a panic handler. - eprintln!( - "rayon panic handler called on non-rayon thread: {panic_info:?}" - ); + eprintln!("rayon panic handler called on non-rayon thread: {panic_info:?}"); } exit(1); }; diff --git a/crates/subspace-farmer/src/plotter/gpu/metrics.rs b/crates/subspace-farmer/src/plotter/gpu/metrics.rs index 07a689aa3b8..99cb664d53d 100644 --- a/crates/subspace-farmer/src/plotter/gpu/metrics.rs +++ b/crates/subspace-farmer/src/plotter/gpu/metrics.rs @@ -2,7 +2,7 @@ use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::gauge::Gauge; -use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; +use prometheus_client::metrics::histogram::{Histogram, exponential_buckets}; use prometheus_client::registry::{Registry, Unit}; use std::num::NonZeroUsize; use std::sync::atomic::{AtomicI64, AtomicU64}; diff --git a/crates/subspace-farmer/src/plotter/gpu/rocm.rs b/crates/subspace-farmer/src/plotter/gpu/rocm.rs index b5a85c6d11b..5efcf360d9f 100644 --- a/crates/subspace-farmer/src/plotter/gpu/rocm.rs +++ b/crates/subspace-farmer/src/plotter/gpu/rocm.rs @@ -3,10 +3,10 @@ use crate::plotter::gpu::GpuRecordsEncoder; use async_lock::Mutex as AsyncMutex; use parking_lot::Mutex; -use rayon::{current_thread_index, ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder}; +use rayon::{ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder, current_thread_index}; use std::process::exit; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use subspace_core_primitives::pieces::{PieceOffset, Record}; use subspace_core_primitives::sectors::SectorId; use subspace_farmer_components::plotting::RecordsEncoder; @@ -47,30 +47,32 @@ impl RecordsEncoder for RocmRecordsEncoder { let plotting_error = Mutex::new(None::); self.thread_pool.scope(|scope| { - scope.spawn_broadcast(|_scope, _ctx| loop { - // Take mutex briefly to make sure encoding is allowed right now - self.global_mutex.lock_blocking(); + scope.spawn_broadcast(|_scope, _ctx| { + loop { + // Take mutex briefly to make sure encoding is allowed right now + self.global_mutex.lock_blocking(); - // This instead of `while` above because otherwise mutex will be held for the - // duration of the loop and will limit concurrency to 1 record - let Some(((piece_offset, record), mut encoded_chunks_used)) = - iter.lock().next() - else { - return; - }; - let pos_seed = sector_id.derive_evaluation_seed(piece_offset); + // This instead of `while` above because otherwise mutex will be held for the + // duration of the loop and will limit concurrency to 1 record + let Some(((piece_offset, record), mut encoded_chunks_used)) = + iter.lock().next() + else { + return; + }; + let pos_seed = sector_id.derive_evaluation_seed(piece_offset); - if let Err(error) = self.rocm_device.generate_and_encode_pospace( - &pos_seed, - record, - encoded_chunks_used.iter_mut(), - ) { - plotting_error.lock().replace(error); - return; - } + if let Err(error) = self.rocm_device.generate_and_encode_pospace( + &pos_seed, + record, + encoded_chunks_used.iter_mut(), + ) { + plotting_error.lock().replace(error); + return; + } - if abort_early.load(Ordering::Relaxed) { - return; + if abort_early.load(Ordering::Relaxed) { + return; + } } }); }); @@ -100,9 +102,7 @@ impl RocmRecordsEncoder { eprintln!("panic on thread {}: {:?}", thread_name(index), panic_info); } else { // We want to guarantee exit, rather than panicking in a panic handler. - eprintln!( - "rayon panic handler called on non-rayon thread: {panic_info:?}" - ); + eprintln!("rayon panic handler called on non-rayon thread: {panic_info:?}"); } exit(1); }; diff --git a/crates/subspace-farmer/src/plotter/pool.rs b/crates/subspace-farmer/src/plotter/pool.rs index d4d6a1b00a0..16160c9d4a7 100644 --- a/crates/subspace-farmer/src/plotter/pool.rs +++ b/crates/subspace-farmer/src/plotter/pool.rs @@ -8,8 +8,8 @@ use futures::future; use std::any::type_name_of_val; use std::pin::pin; use std::time::Duration; -use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::sectors::SectorIndex; use subspace_farmer_components::FarmerProtocolInfo; use tracing::{error, trace}; diff --git a/crates/subspace-farmer/src/single_disk_farm.rs b/crates/subspace-farmer/src/single_disk_farm.rs index 53d40ffb086..d1c85c72c30 100644 --- a/crates/subspace-farmer/src/single_disk_farm.rs +++ b/crates/subspace-farmer/src/single_disk_farm.rs @@ -22,10 +22,10 @@ use crate::farm::{ }; use crate::node_client::NodeClient; use crate::plotter::Plotter; -use crate::single_disk_farm::direct_io_file::{DirectIoFile, DISK_SECTOR_SIZE}; +use crate::single_disk_farm::direct_io_file::{DISK_SECTOR_SIZE, DirectIoFile}; use crate::single_disk_farm::farming::rayon_files::RayonFiles; use crate::single_disk_farm::farming::{ - farming, slot_notification_forwarder, FarmingOptions, PlotAudit, + FarmingOptions, PlotAudit, farming, slot_notification_forwarder, }; use crate::single_disk_farm::identity::{Identity, IdentityError}; use crate::single_disk_farm::metrics::SingleDiskFarmMetrics; @@ -35,17 +35,17 @@ use crate::single_disk_farm::plot_cache::DiskPlotCache; use crate::single_disk_farm::plotted_sectors::SingleDiskPlottedSectors; pub use crate::single_disk_farm::plotting::PlottingError; use crate::single_disk_farm::plotting::{ - plotting, plotting_scheduler, PlottingOptions, PlottingSchedulerOptions, SectorPlottingOptions, + PlottingOptions, PlottingSchedulerOptions, SectorPlottingOptions, plotting, plotting_scheduler, }; use crate::single_disk_farm::reward_signing::reward_signing; -use crate::utils::{tokio_rayon_spawn_handler, AsyncJoinOnDrop}; -use crate::{farm, KNOWN_PEERS_CACHE_SIZE}; +use crate::utils::{AsyncJoinOnDrop, tokio_rayon_spawn_handler}; +use crate::{KNOWN_PEERS_CACHE_SIZE, farm}; use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock}; use async_trait::async_trait; use event_listener_primitives::{Bag, HandlerId}; use futures::channel::{mpsc, oneshot}; use futures::stream::FuturesUnordered; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; use parity_scale_codec::{Decode, Encode}; use parking_lot::Mutex; use prometheus_client::registry::Registry; @@ -61,20 +61,20 @@ use std::num::{NonZeroU32, NonZeroUsize}; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::str::FromStr; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Duration; use std::{fmt, fs, io, mem}; -use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash}; +use subspace_core_primitives::PublicKey; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash}; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::segments::{HistorySize, SegmentIndex}; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::file_ext::FileExt; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; -use subspace_farmer_components::sector::{sector_size, SectorMetadata, SectorMetadataChecksummed}; -use subspace_farmer_components::FarmerProtocolInfo; +use subspace_farmer_components::sector::{SectorMetadata, SectorMetadataChecksummed, sector_size}; use subspace_kzg::Kzg; use subspace_networking::KnownPeersManager; use subspace_proof_of_space::Table; @@ -83,7 +83,7 @@ use thiserror::Error; use tokio::runtime::Handle; use tokio::sync::broadcast; use tokio::task; -use tracing::{error, info, trace, warn, Instrument, Span}; +use tracing::{Instrument, Span, error, info, trace, warn}; // Refuse to compile on non-64-bit platforms, offsets may fail on those when converting from u64 to // usize depending on chain parameters @@ -490,9 +490,7 @@ pub enum SingleDiskFarmScrubError { error: IdentityError, }, /// Identity public key doesn't match public key in the disk farm info - #[error( - "Identity public key {identity} doesn't match public key in the disk farm info {info}" - )] + #[error("Identity public key {identity} doesn't match public key in the disk farm info {info}")] PublicKeyMismatch { /// Identity public key identity: PublicKey, @@ -1012,10 +1010,11 @@ impl SingleDiskFarm { } if let Some(plotting_delay) = plotting_delay - && plotting_delay.await.is_err() { - // Dropped before resolving - return Ok(()); - } + && plotting_delay.await.is_err() + { + // Dropped before resolving + return Ok(()); + } plotting(plotting_options).await }; @@ -1608,9 +1607,7 @@ impl SingleDiskFarm { )?; sectors_metadata.push( SectorMetadataChecksummed::decode(&mut sector_metadata_bytes.as_ref()).map_err( - |error| { - io::Error::other(format!("Failed to decode sector metadata: {error}")) - }, + |error| io::Error::other(format!("Failed to decode sector metadata: {error}")), )?, ); } @@ -1890,14 +1887,15 @@ impl SingleDiskFarm { let metadata_header_bytes = metadata_header.encode(); if !dry_run - && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { - return Err(SingleDiskFarmScrubError::FailedToWriteBytes { - file: metadata_file_path, - size: metadata_header_bytes.len() as u64, - offset: 0, - error, - }); - } + && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: metadata_file_path, + size: metadata_header_bytes.len() as u64, + offset: 0, + error, + }); + } } (metadata_file, metadata_header) @@ -1958,14 +1956,15 @@ impl SingleDiskFarm { let metadata_header_bytes = metadata_header.encode(); if !dry_run - && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) { - return Err(SingleDiskFarmScrubError::FailedToWriteBytes { - file: plot_file_path, - size: metadata_header_bytes.len() as u64, - offset: 0, - error, - }); - } + && let Err(error) = metadata_file.write_all_at(&metadata_header_bytes, 0) + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: plot_file_path, + size: metadata_header_bytes.len() as u64, + offset: 0, + error, + }); + } } plot_file @@ -2157,16 +2156,15 @@ impl SingleDiskFarm { let bytes = &mut scratch_buffer[..bytes_to_write]; if !dry_run - && let Err(error) = plot_file.write_all_at(bytes, offset) { - return Err( - SingleDiskFarmScrubError::FailedToWriteBytes { - file: plot_file_path.clone(), - size: scratch_buffer.len() as u64, - offset, - error, - }, - ); - } + && let Err(error) = plot_file.write_all_at(bytes, offset) + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: plot_file_path.clone(), + size: scratch_buffer.len() as u64, + offset, + error, + }); + } hasher.update(bytes); } @@ -2178,16 +2176,14 @@ impl SingleDiskFarm { if !dry_run && let Err(error) = plot_file.write_all_at(&checksum, offset) - { - return Err( - SingleDiskFarmScrubError::FailedToWriteBytes { - file: plot_file_path.clone(), - size: checksum.len() as u64, - offset, - error, - }, - ); - } + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: plot_file_path.clone(), + size: checksum.len() as u64, + offset, + error, + }); + } } return Ok(()); @@ -2278,15 +2274,15 @@ impl SingleDiskFarm { "Failed to read cached piece, replacing with dummy element" ); - if !dry_run - && let Err(error) = cache_file.write_all_at(&dummy_element, offset) { - return Err(SingleDiskFarmScrubError::FailedToWriteBytes { - file: file.clone(), - size: u64::from(element_size), - offset, - error, - }); - } + if !dry_run && let Err(error) = cache_file.write_all_at(&dummy_element, offset) + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: file.clone(), + size: u64::from(element_size), + offset, + error, + }); + } return Ok(()); } @@ -2302,15 +2298,15 @@ impl SingleDiskFarm { "Cached piece checksum mismatch, replacing with dummy element" ); - if !dry_run - && let Err(error) = cache_file.write_all_at(&dummy_element, offset) { - return Err(SingleDiskFarmScrubError::FailedToWriteBytes { - file: file.clone(), - size: u64::from(element_size), - offset, - error, - }); - } + if !dry_run && let Err(error) = cache_file.write_all_at(&dummy_element, offset) + { + return Err(SingleDiskFarmScrubError::FailedToWriteBytes { + file: file.clone(), + size: u64::from(element_size), + offset, + error, + }); + } return Ok(()); } diff --git a/crates/subspace-farmer/src/single_disk_farm/direct_io_file.rs b/crates/subspace-farmer/src/single_disk_farm/direct_io_file.rs index b568f5db0b2..ea55c6c58c4 100644 --- a/crates/subspace-farmer/src/single_disk_farm/direct_io_file.rs +++ b/crates/subspace-farmer/src/single_disk_farm/direct_io_file.rs @@ -5,8 +5,8 @@ use static_assertions::const_assert_eq; use std::fs::{File, OpenOptions}; use std::path::Path; use std::{io, mem}; -use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; use subspace_farmer_components::ReadAtSync; +use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; /// 4096 is as a relatively safe size due to sector size on SSDs commonly being 512 or 4096 bytes pub const DISK_SECTOR_SIZE: usize = 4096; diff --git a/crates/subspace-farmer/src/single_disk_farm/farming.rs b/crates/subspace-farmer/src/single_disk_farm/farming.rs index 0951d7bbeb4..1b23dd933b7 100644 --- a/crates/subspace-farmer/src/single_disk_farm/farming.rs +++ b/crates/subspace-farmer/src/single_disk_farm/farming.rs @@ -9,32 +9,32 @@ use crate::farm::{ AuditingDetails, FarmingError, FarmingNotification, ProvingDetails, ProvingResult, }; use crate::node_client::NodeClient; -use crate::single_disk_farm::metrics::SingleDiskFarmMetrics; use crate::single_disk_farm::Handlers; +use crate::single_disk_farm::metrics::SingleDiskFarmMetrics; use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock}; -use futures::channel::mpsc; use futures::StreamExt; +use futures::channel::mpsc; use parking_lot::Mutex; use rayon::ThreadPool; use std::collections::HashSet; use std::sync::Arc; use std::time::Instant; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::pos::PosSeed; use subspace_core_primitives::sectors::SectorIndex; use subspace_core_primitives::segments::{HistorySize, SegmentIndex}; use subspace_core_primitives::solutions::{Solution, SolutionRange}; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; -use subspace_farmer_components::auditing::{audit_plot_sync, AuditingError}; +use subspace_farmer_components::ReadAtSync; +use subspace_farmer_components::auditing::{AuditingError, audit_plot_sync}; use subspace_farmer_components::proving::{ProvableSolutions, ProvingError}; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; use subspace_farmer_components::sector::{SectorMetadata, SectorMetadataChecksummed}; -use subspace_farmer_components::ReadAtSync; use subspace_kzg::Kzg; use subspace_proof_of_space::{Table, TableGenerator}; use subspace_rpc_primitives::{SlotInfo, SolutionResponse}; -use tracing::{debug, error, info, trace, warn, Span}; +use tracing::{Span, debug, error, info, trace, warn}; /// How many non-fatal errors should happen in a row before farm is considered non-operational const NON_FATAL_ERROR_LIMIT: usize = 10; diff --git a/crates/subspace-farmer/src/single_disk_farm/farming/rayon_files.rs b/crates/subspace-farmer/src/single_disk_farm/farming/rayon_files.rs index 8f9e6563767..166920baf29 100644 --- a/crates/subspace-farmer/src/single_disk_farm/farming/rayon_files.rs +++ b/crates/subspace-farmer/src/single_disk_farm/farming/rayon_files.rs @@ -3,8 +3,8 @@ use std::fs::{File, OpenOptions}; use std::io; use std::path::Path; -use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; use subspace_farmer_components::ReadAtSync; +use subspace_farmer_components::file_ext::{FileExt, OpenOptionsExt}; /// Wrapper data structure for multiple files to be used with [`rayon`] thread pool, where the same /// file is opened multiple times, once for each thread for faster concurrent reads diff --git a/crates/subspace-farmer/src/single_disk_farm/metrics.rs b/crates/subspace-farmer/src/single_disk_farm/metrics.rs index f6123308c63..9df98bacb09 100644 --- a/crates/subspace-farmer/src/single_disk_farm/metrics.rs +++ b/crates/subspace-farmer/src/single_disk_farm/metrics.rs @@ -4,7 +4,7 @@ use crate::farm::{FarmId, FarmingError, ProvingResult}; use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::family::Family; use prometheus_client::metrics::gauge::Gauge; -use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; +use prometheus_client::metrics::histogram::{Histogram, exponential_buckets}; use prometheus_client::registry::{Registry, Unit}; use std::fmt; use std::sync::atomic::{AtomicI64, AtomicU64}; diff --git a/crates/subspace-farmer/src/single_disk_farm/piece_cache.rs b/crates/subspace-farmer/src/single_disk_farm/piece_cache.rs index 68d91da4ade..d8c67545cb6 100644 --- a/crates/subspace-farmer/src/single_disk_farm/piece_cache.rs +++ b/crates/subspace-farmer/src/single_disk_farm/piece_cache.rs @@ -4,7 +4,7 @@ use crate::disk_piece_cache::DiskPieceCache; use crate::farm; use crate::farm::{FarmError, PieceCacheId, PieceCacheOffset}; use async_trait::async_trait; -use futures::{stream, Stream}; +use futures::{Stream, stream}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; /// Dedicated piece cache stored on one disk, is used both to accelerate DSN queries and to plot diff --git a/crates/subspace-farmer/src/single_disk_farm/piece_reader.rs b/crates/subspace-farmer/src/single_disk_farm/piece_reader.rs index 76ffeb61523..392c57a77e1 100644 --- a/crates/subspace-farmer/src/single_disk_farm/piece_reader.rs +++ b/crates/subspace-farmer/src/single_disk_farm/piece_reader.rs @@ -9,13 +9,13 @@ use futures::{SinkExt, StreamExt}; use std::collections::HashSet; use std::future::Future; use std::sync::Arc; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::{Piece, PieceOffset}; use subspace_core_primitives::sectors::{SectorId, SectorIndex}; -use subspace_core_primitives::PublicKey; use subspace_erasure_coding::ErasureCoding; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; -use subspace_farmer_components::sector::{sector_size, SectorMetadataChecksummed}; -use subspace_farmer_components::{reading, ReadAt, ReadAtAsync, ReadAtSync}; +use subspace_farmer_components::sector::{SectorMetadataChecksummed, sector_size}; +use subspace_farmer_components::{ReadAt, ReadAtAsync, ReadAtSync, reading}; use subspace_proof_of_space::Table; use tracing::{error, warn}; diff --git a/crates/subspace-farmer/src/single_disk_farm/plot_cache.rs b/crates/subspace-farmer/src/single_disk_farm/plot_cache.rs index 1c2b53a846f..564393858ed 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plot_cache.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plot_cache.rs @@ -13,7 +13,7 @@ use parking_lot::RwLock; use std::collections::HashMap; use std::sync::{Arc, Weak}; use std::{io, mem}; -use subspace_core_primitives::hashes::{blake3_hash_list, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash_list}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_core_primitives::sectors::SectorIndex; use subspace_farmer_components::file_ext::FileExt; diff --git a/crates/subspace-farmer/src/single_disk_farm/plot_cache/tests.rs b/crates/subspace-farmer/src/single_disk_farm/plot_cache/tests.rs index 0fcb50f81eb..ae0afdb8c3a 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plot_cache/tests.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plot_cache/tests.rs @@ -1,5 +1,5 @@ use crate::farm::MaybePieceStoredResult; -use crate::single_disk_farm::direct_io_file::{DirectIoFile, DISK_SECTOR_SIZE}; +use crate::single_disk_farm::direct_io_file::{DISK_SECTOR_SIZE, DirectIoFile}; use crate::single_disk_farm::plot_cache::DiskPlotCache; use rand::prelude::*; use std::assert_matches::assert_matches; @@ -82,10 +82,12 @@ async fn basic() { usize::from(TARGET_SECTOR_COUNT), dummy_sector_metadata.clone(), ); - assert!(!disk_plot_cache - .try_store_piece(piece_index_0, &piece_0) - .await - .unwrap()); + assert!( + !disk_plot_cache + .try_store_piece(piece_index_0, &piece_0) + .await + .unwrap() + ); assert_matches!( disk_plot_cache.is_piece_maybe_stored(&record_key_0), MaybePieceStoredResult::No @@ -101,10 +103,12 @@ async fn basic() { ); // Successfully stores piece if not all sectors are plotted - assert!(disk_plot_cache - .try_store_piece(piece_index_0, &piece_0) - .await - .unwrap()); + assert!( + disk_plot_cache + .try_store_piece(piece_index_0, &piece_0) + .await + .unwrap() + ); assert_matches!( disk_plot_cache.is_piece_maybe_stored(&record_key_0), MaybePieceStoredResult::Yes @@ -116,10 +120,12 @@ async fn basic() { disk_plot_cache.is_piece_maybe_stored(&record_key_1), MaybePieceStoredResult::Vacant ); - assert!(disk_plot_cache - .try_store_piece(piece_index_1, &piece_1) - .await - .unwrap()); + assert!( + disk_plot_cache + .try_store_piece(piece_index_1, &piece_1) + .await + .unwrap() + ); assert_matches!( disk_plot_cache.is_piece_maybe_stored(&record_key_1), MaybePieceStoredResult::Yes @@ -130,10 +136,12 @@ async fn basic() { disk_plot_cache.is_piece_maybe_stored(&record_key_2), MaybePieceStoredResult::Vacant ); - assert!(disk_plot_cache - .try_store_piece(piece_index_2, &piece_2) - .await - .unwrap()); + assert!( + disk_plot_cache + .try_store_piece(piece_index_2, &piece_2) + .await + .unwrap() + ); assert_matches!( disk_plot_cache.is_piece_maybe_stored(&record_key_2), MaybePieceStoredResult::Yes diff --git a/crates/subspace-farmer/src/single_disk_farm/plotted_sectors.rs b/crates/subspace-farmer/src/single_disk_farm/plotted_sectors.rs index bd933488570..28996100eac 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plotted_sectors.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plotted_sectors.rs @@ -1,14 +1,14 @@ use crate::farm::{FarmError, PlottedSectors}; use async_lock::RwLock as AsyncRwLock; use async_trait::async_trait; -use futures::{stream, Stream}; +use futures::{Stream, stream}; use std::sync::Arc; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::PieceOffset; use subspace_core_primitives::sectors::SectorId; -use subspace_core_primitives::PublicKey; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::plotting::PlottedSector; use subspace_farmer_components::sector::SectorMetadataChecksummed; -use subspace_farmer_components::FarmerProtocolInfo; /// Getter for single disk plotted sectors #[derive(Debug)] diff --git a/crates/subspace-farmer/src/single_disk_farm/plotting.rs b/crates/subspace-farmer/src/single_disk_farm/plotting.rs index 9641d1b68a9..9fa6d5e03fa 100644 --- a/crates/subspace-farmer/src/single_disk_farm/plotting.rs +++ b/crates/subspace-farmer/src/single_disk_farm/plotting.rs @@ -9,7 +9,7 @@ use crate::single_disk_farm::{ use async_lock::{Mutex as AsyncMutex, RwLock as AsyncRwLock, Semaphore, SemaphoreGuard}; use futures::channel::{mpsc, oneshot}; use futures::stream::FuturesOrdered; -use futures::{select, FutureExt, SinkExt, StreamExt}; +use futures::{FutureExt, SinkExt, StreamExt, select}; use parity_scale_codec::Encode; use rand::prelude::*; use std::collections::HashSet; @@ -20,18 +20,18 @@ use std::ops::Range; use std::pin::pin; use std::sync::Arc; use std::time::{Duration, Instant}; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::hashes::Blake3Hash; use subspace_core_primitives::pieces::PieceOffset; use subspace_core_primitives::sectors::{SectorId, SectorIndex}; use subspace_core_primitives::segments::{HistorySize, SegmentHeader, SegmentIndex}; -use subspace_core_primitives::PublicKey; use subspace_farmer_components::file_ext::FileExt; use subspace_farmer_components::plotting::PlottedSector; use subspace_farmer_components::sector::SectorMetadataChecksummed; use thiserror::Error; use tokio::sync::watch; use tokio::task; -use tracing::{debug, info, info_span, trace, warn, Instrument}; +use tracing::{Instrument, debug, info, info_span, trace, warn}; const FARMER_APP_INFO_RETRY_INTERVAL: Duration = Duration::from_millis(500); const PLOTTING_RETRY_DELAY: Duration = Duration::from_secs(1); @@ -362,26 +362,27 @@ where }; if let Some(old_sector_metadata) = &maybe_old_sector_metadata - && farmer_app_info.protocol_info.history_size <= old_sector_metadata.history_size { - if farmer_app_info.protocol_info.min_sector_lifetime == HistorySize::ONE { - debug!( - current_history_size = %farmer_app_info.protocol_info.history_size, - old_sector_history_size = %old_sector_metadata.history_size, - "Latest protocol history size is not yet newer than old sector history \ - size, wait for a bit and try again" - ); - tokio::time::sleep(FARMER_APP_INFO_RETRY_INTERVAL).await; - continue; - } else { - debug!( - current_history_size = %farmer_app_info.protocol_info.history_size, - old_sector_history_size = %old_sector_metadata.history_size, - "Skipped sector plotting, likely redundant due to redundant archived \ - segment notification" - ); - return PlotSingleSectorResult::Skipped; - } + && farmer_app_info.protocol_info.history_size <= old_sector_metadata.history_size + { + if farmer_app_info.protocol_info.min_sector_lifetime == HistorySize::ONE { + debug!( + current_history_size = %farmer_app_info.protocol_info.history_size, + old_sector_history_size = %old_sector_metadata.history_size, + "Latest protocol history size is not yet newer than old sector history \ + size, wait for a bit and try again" + ); + tokio::time::sleep(FARMER_APP_INFO_RETRY_INTERVAL).await; + continue; + } else { + debug!( + current_history_size = %farmer_app_info.protocol_info.history_size, + old_sector_history_size = %old_sector_metadata.history_size, + "Skipped sector plotting, likely redundant due to redundant archived \ + segment notification" + ); + return PlotSingleSectorResult::Skipped; } + } break farmer_app_info; }; diff --git a/crates/subspace-farmer/src/utils.rs b/crates/subspace-farmer/src/utils.rs index 51dd498ab93..7f1d7d517b1 100644 --- a/crates/subspace-farmer/src/utils.rs +++ b/crates/subspace-farmer/src/utils.rs @@ -9,16 +9,16 @@ use futures::channel::oneshot; use futures::channel::oneshot::Canceled; use futures::future::Either; use rayon::{ - current_thread_index, ThreadBuilder, ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder, + ThreadBuilder, ThreadPool, ThreadPoolBuildError, ThreadPoolBuilder, current_thread_index, }; use std::future::Future; use std::num::NonZeroUsize; use std::ops::Deref; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::process::exit; use std::task::{Context, Poll}; use std::{fmt, io, iter, thread}; -use thread_priority::{set_current_thread_priority, ThreadPriority}; +use thread_priority::{ThreadPriority, set_current_thread_priority}; use tokio::runtime::Handle; use tokio::task; use tracing::{debug, warn}; @@ -501,9 +501,7 @@ fn create_plotting_thread_pool_manager_thread_pool_pair( eprintln!("panic on thread {}: {:?}", thread_name(index), panic_info); } else { // We want to guarantee exit, rather than panicking in a panic handler. - eprintln!( - "rayon panic handler called on non-rayon thread: {panic_info:?}" - ); + eprintln!("rayon panic handler called on non-rayon thread: {panic_info:?}"); } exit(1); }; @@ -522,9 +520,10 @@ fn create_plotting_thread_pool_manager_thread_pool_pair( move || { cpu_core_set.pin_current_thread(); if let Some(thread_priority) = thread_priority - && let Err(error) = set_current_thread_priority(thread_priority) { - warn!(%error, "Failed to set thread priority"); - } + && let Err(error) = set_current_thread_priority(thread_priority) + { + warn!(%error, "Failed to set thread priority"); + } drop(cpu_core_set); let _guard = handle.enter(); diff --git a/crates/subspace-farmer/src/utils/ss58.rs b/crates/subspace-farmer/src/utils/ss58.rs index 52c66ded7c9..a3866a078d2 100644 --- a/crates/subspace-farmer/src/utils/ss58.rs +++ b/crates/subspace-farmer/src/utils/ss58.rs @@ -2,8 +2,8 @@ //! `sp-core` into farmer application use base58::FromBase58; -use blake2::digest::typenum::U64; use blake2::digest::FixedOutput; +use blake2::digest::typenum::U64; use blake2::{Blake2b, Digest}; use ss58_registry::Ss58AddressFormat; use subspace_core_primitives::PublicKey; diff --git a/crates/subspace-farmer/src/utils/tests.rs b/crates/subspace-farmer/src/utils/tests.rs index 80a9db5ea83..a83a5878ce3 100644 --- a/crates/subspace-farmer/src/utils/tests.rs +++ b/crates/subspace-farmer/src/utils/tests.rs @@ -1,6 +1,6 @@ use crate::utils::{ - parse_cpu_cores_sets, run_future_in_dedicated_thread, thread_pool_core_indices_internal, - CpuCoreSet, + CpuCoreSet, parse_cpu_cores_sets, run_future_in_dedicated_thread, + thread_pool_core_indices_internal, }; use std::future; use std::num::NonZeroUsize; diff --git a/crates/subspace-gateway/src/commands.rs b/crates/subspace-gateway/src/commands.rs index 341000028a4..0466790f939 100644 --- a/crates/subspace-gateway/src/commands.rs +++ b/crates/subspace-gateway/src/commands.rs @@ -5,7 +5,7 @@ pub(crate) mod network; pub(crate) mod rpc; use crate::commands::http::HttpCommandOptions; -use crate::commands::network::{configure_network, NetworkArgs}; +use crate::commands::network::{NetworkArgs, configure_network}; use crate::commands::rpc::RpcCommandOptions; use crate::node_client::RpcNodeClient; use crate::piece_getter::DsnPieceGetter; @@ -17,8 +17,8 @@ use std::process::exit; use std::sync::Arc; use subspace_data_retrieval::object_fetcher::ObjectFetcher; use subspace_kzg::Kzg; -use subspace_networking::utils::piece_provider::PieceProvider; use subspace_networking::NodeRunner; +use subspace_networking::utils::piece_provider::PieceProvider; use tokio::signal; use tracing::{debug, warn}; diff --git a/crates/subspace-gateway/src/commands/http.rs b/crates/subspace-gateway/src/commands/http.rs index fceac970215..01781aa41a4 100644 --- a/crates/subspace-gateway/src/commands/http.rs +++ b/crates/subspace-gateway/src/commands/http.rs @@ -3,10 +3,10 @@ pub(crate) mod server; -use crate::commands::http::server::{start_server, ServerParameters}; -use crate::commands::{initialize_object_fetcher, shutdown_signal, GatewayOptions}; +use crate::commands::http::server::{ServerParameters, start_server}; +use crate::commands::{GatewayOptions, initialize_object_fetcher, shutdown_signal}; use clap::Parser; -use futures::{select, FutureExt}; +use futures::{FutureExt, select}; use tracing::info; /// Options for HTTP server. diff --git a/crates/subspace-gateway/src/commands/http/server.rs b/crates/subspace-gateway/src/commands/http/server.rs index 5d709209272..587df620be3 100644 --- a/crates/subspace-gateway/src/commands/http/server.rs +++ b/crates/subspace-gateway/src/commands/http/server.rs @@ -1,6 +1,6 @@ //! HTTP server which fetches objects from the DSN based on a hash, using a mapping indexer service. -use actix_web::{web, App, HttpResponse, HttpServer, Responder}; +use actix_web::{App, HttpResponse, HttpServer, Responder, web}; use std::sync::Arc; use subspace_core_primitives::hashes::Blake3Hash; use subspace_data_retrieval::object_fetcher::ObjectFetcher; diff --git a/crates/subspace-gateway/src/commands/network.rs b/crates/subspace-gateway/src/commands/network.rs index 96c2e0284b3..4f42bf0eccc 100644 --- a/crates/subspace-gateway/src/commands/network.rs +++ b/crates/subspace-gateway/src/commands/network.rs @@ -4,10 +4,10 @@ use crate::node_client::{NodeClient, RpcNodeClient}; use anyhow::anyhow; use clap::{Parser, ValueHint}; use subspace_networking::libp2p::kad::Mode; -use subspace_networking::libp2p::{identity, Multiaddr}; +use subspace_networking::libp2p::{Multiaddr, identity}; use subspace_networking::protocols::request_response::handlers::cached_piece_by_index::CachedPieceByIndexRequestHandler; use subspace_networking::protocols::request_response::handlers::piece_by_index::PieceByIndexRequestHandler; -use subspace_networking::{construct, Config, KademliaMode, Node, NodeRunner}; +use subspace_networking::{Config, KademliaMode, Node, NodeRunner, construct}; use tracing::{debug, info}; /// Configuration for network stack diff --git a/crates/subspace-gateway/src/commands/rpc.rs b/crates/subspace-gateway/src/commands/rpc.rs index 9c5de1cad5e..b4f6448fd5f 100644 --- a/crates/subspace-gateway/src/commands/rpc.rs +++ b/crates/subspace-gateway/src/commands/rpc.rs @@ -2,10 +2,10 @@ //! This command starts an RPC server to serve object requests from the DSN. pub(crate) mod server; -use crate::commands::rpc::server::{launch_rpc_server, RpcOptions, RPC_DEFAULT_PORT}; -use crate::commands::{initialize_object_fetcher, shutdown_signal, GatewayOptions}; +use crate::commands::rpc::server::{RPC_DEFAULT_PORT, RpcOptions, launch_rpc_server}; +use crate::commands::{GatewayOptions, initialize_object_fetcher, shutdown_signal}; use clap::Parser; -use futures::{select, FutureExt}; +use futures::{FutureExt, select}; use std::pin::pin; use subspace_gateway_rpc::{SubspaceGatewayRpc, SubspaceGatewayRpcConfig}; use tracing::info; diff --git a/crates/subspace-gateway/src/main.rs b/crates/subspace-gateway/src/main.rs index 70856c154aa..58804fdaa69 100644 --- a/crates/subspace-gateway/src/main.rs +++ b/crates/subspace-gateway/src/main.rs @@ -7,7 +7,7 @@ mod node_client; mod piece_getter; mod piece_validator; -use crate::commands::{raise_fd_limit, set_exit_on_panic, Command}; +use crate::commands::{Command, raise_fd_limit, set_exit_on_panic}; use clap::Parser; use subspace_logging::init_logger; use tracing::info; diff --git a/crates/subspace-gateway/src/piece_validator.rs b/crates/subspace-gateway/src/piece_validator.rs index b9944104e6f..0b404b56882 100644 --- a/crates/subspace-gateway/src/piece_validator.rs +++ b/crates/subspace-gateway/src/piece_validator.rs @@ -4,9 +4,9 @@ use crate::node_client::NodeClient; use async_trait::async_trait; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_kzg::Kzg; +use subspace_networking::Node; use subspace_networking::libp2p::PeerId; use subspace_networking::utils::piece_provider::PieceValidator; -use subspace_networking::Node; use subspace_verification::is_piece_valid; use tracing::{error, warn}; diff --git a/crates/subspace-malicious-operator/src/bin/subspace-malicious-operator.rs b/crates/subspace-malicious-operator/src/bin/subspace-malicious-operator.rs index 9eefd7208f3..114d88bf2c8 100644 --- a/crates/subspace-malicious-operator/src/bin/subspace-malicious-operator.rs +++ b/crates/subspace-malicious-operator/src/bin/subspace-malicious-operator.rs @@ -16,7 +16,7 @@ use sp_domains::DomainId; use sp_messenger::messages::ChainId; use std::collections::HashMap; use subspace_malicious_operator::malicious_domain_instance_starter::DomainInstanceStarter; -use subspace_malicious_operator::{create_malicious_operator_configuration, Cli, DomainCli}; +use subspace_malicious_operator::{Cli, DomainCli, create_malicious_operator_configuration}; use subspace_networking::libp2p::Multiaddr; use subspace_proof_of_space::chia::ChiaTable; use subspace_runtime::{Block, RuntimeApi}; diff --git a/crates/subspace-malicious-operator/src/chain_spec.rs b/crates/subspace-malicious-operator/src/chain_spec.rs index 09870bf695f..3f51b052d66 100644 --- a/crates/subspace-malicious-operator/src/chain_spec.rs +++ b/crates/subspace-malicious-operator/src/chain_spec.rs @@ -5,7 +5,7 @@ use parity_scale_codec::Encode; use sc_chain_spec::GenericChainSpec; use sc_service::ChainType; use sp_core::crypto::AccountId32; -use sp_core::{sr25519, Pair, Public}; +use sp_core::{Pair, Public, sr25519}; use sp_domains::storage::RawGenesis; use sp_domains::{ DomainRuntimeConfig, OperatorAllowList, OperatorPublicKey, PermissionedActionAllowedBy, diff --git a/crates/subspace-malicious-operator/src/lib.rs b/crates/subspace-malicious-operator/src/lib.rs index 134ef794c7f..09abea3dfe4 100644 --- a/crates/subspace-malicious-operator/src/lib.rs +++ b/crates/subspace-malicious-operator/src/lib.rs @@ -9,8 +9,8 @@ pub use chain_spec::create_domain_spec; use clap::Parser; use sc_chain_spec::GenericChainSpec; use sc_cli::{ - generate_node_name, ChainSpec, CliConfiguration, Role, RunCmd as SubstrateRunCmd, RunCmd, - SubstrateCli, + ChainSpec, CliConfiguration, Role, RunCmd as SubstrateRunCmd, RunCmd, SubstrateCli, + generate_node_name, }; use sc_service::config::{ ExecutorConfiguration, KeystoreConfig, NetworkConfiguration, RpcConfiguration, diff --git a/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs b/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs index e6c41ca6d87..418dc66f011 100644 --- a/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs +++ b/crates/subspace-malicious-operator/src/malicious_bundle_producer.rs @@ -8,8 +8,8 @@ use futures::{Stream, StreamExt, TryFutureExt}; use pallet_domains::OperatorConfig; use parity_scale_codec::Encode; use sc_client_api::{AuxStore, BlockBackend, HeaderBackend}; -use sc_service::config::KeystoreConfig; use sc_service::KeystoreContainer; +use sc_service::config::KeystoreConfig; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::tracing_unbounded; use sp_api::ProvideRuntimeApi; @@ -23,7 +23,7 @@ use sp_keyring::Sr25519Keyring; use sp_keystore::{Keystore, KeystorePtr}; use sp_messenger::MessengerApi; use sp_runtime::traits::NumberFor; -use sp_runtime::{generic, RuntimeAppPublic}; +use sp_runtime::{RuntimeAppPublic, generic}; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; use std::error::Error; use std::sync::Arc; @@ -213,9 +213,10 @@ where // Periodically check the malicious operator status if u64::from(slot) % 10 == 0 - && let Err(err) = self.update_malicious_operator_status() { - tracing::error!(?err, "Failed to update malicious operator status"); - } + && let Err(err) = self.update_malicious_operator_status() + { + tracing::error!(?err, "Failed to update malicious operator status"); + } } } @@ -272,10 +273,11 @@ where .consensus_client .runtime_api() .operator(consensus_best_hash, *operator_id)? - && operator_signing_key == signing_key { - maybe_operator_id = Some(*operator_id); - break; - } + && operator_signing_key == signing_key + { + maybe_operator_id = Some(*operator_id); + break; + } } // If the `signing_key` is linked to a operator, the previous registration request succeeded, diff --git a/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs b/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs index adee97d87f6..95811f6f7eb 100644 --- a/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs +++ b/crates/subspace-malicious-operator/src/malicious_bundle_tamper.rs @@ -102,10 +102,11 @@ where } // If a bad receipt is already made for the same domain block, reuse it if let Some(bad_receipts_at) = self.bad_receipts_cache.get(&receipt.domain_block_number) - && let Some(previous_bad_receipt) = bad_receipts_at.get(&receipt.consensus_block_hash) { - *receipt = previous_bad_receipt.clone(); - return Ok(()); - } + && let Some(previous_bad_receipt) = bad_receipts_at.get(&receipt.consensus_block_hash) + { + *receipt = previous_bad_receipt.clone(); + return Ok(()); + } let random_seed = Random::seed(); let bad_receipt_type = match random_seed % 7 { diff --git a/crates/subspace-malicious-operator/src/malicious_domain_instance_starter.rs b/crates/subspace-malicious-operator/src/malicious_domain_instance_starter.rs index 3ae3ddd9042..55ca1896819 100644 --- a/crates/subspace-malicious-operator/src/malicious_domain_instance_starter.rs +++ b/crates/subspace-malicious-operator/src/malicious_domain_instance_starter.rs @@ -1,10 +1,10 @@ -use crate::malicious_bundle_producer::MaliciousBundleProducer; use crate::DomainCli; +use crate::malicious_bundle_producer::MaliciousBundleProducer; use cross_domain_message_gossip::{ChainMsg, Message}; use domain_client_operator::snap_sync::ConsensusChainSyncParams; use domain_client_operator::{BootstrapResult, OperatorStreams}; -use domain_eth_service::provider::EthProvider; use domain_eth_service::DefaultEthConfig; +use domain_eth_service::provider::EthProvider; use domain_runtime_primitives::opaque::Block as DomainBlock; use domain_service::providers::DefaultProvider; use domain_service::{FullBackend, FullClient}; @@ -27,7 +27,7 @@ use sp_keystore::KeystorePtr; use std::sync::Arc; use subspace_runtime::RuntimeApi as CRuntimeApi; use subspace_runtime_primitives::opaque::Block as CBlock; -use subspace_runtime_primitives::{AccountId, HeaderFor, DOMAINS_BLOCK_PRUNING_DEPTH}; +use subspace_runtime_primitives::{AccountId, DOMAINS_BLOCK_PRUNING_DEPTH, HeaderFor}; use subspace_service::FullClient as CFullClient; /// `DomainInstanceStarter` used to start a domain instance node based on the given diff --git a/crates/subspace-networking/examples/benchmark.rs b/crates/subspace-networking/examples/benchmark.rs index c1ed9dc25c8..264cbe2a0da 100644 --- a/crates/subspace-networking/examples/benchmark.rs +++ b/crates/subspace-networking/examples/benchmark.rs @@ -1,18 +1,18 @@ use async_lock::Semaphore; -use backoff::future::retry; use backoff::ExponentialBackoff; +use backoff::future::retry; use clap::Parser; +use futures::StreamExt; use futures::channel::oneshot; use futures::future::pending; use futures::stream::FuturesUnordered; -use futures::StreamExt; +use libp2p::Multiaddr; use libp2p::identity::Keypair; use libp2p::multiaddr::Protocol; -use libp2p::Multiaddr; use parking_lot::Mutex; use std::error::Error; -use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; use std::time::{Duration, Instant}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_logging::init_logger; @@ -364,9 +364,10 @@ pub async fn configure_dsn( move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_address_sender) = node_address_sender.lock().take() { - node_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_address_sender) = node_address_sender.lock().take() + { + node_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/examples/get-peers.rs b/crates/subspace-networking/examples/get-peers.rs index cb4db5d42a0..4b3fc65c81a 100644 --- a/crates/subspace-networking/examples/get-peers.rs +++ b/crates/subspace-networking/examples/get-peers.rs @@ -1,5 +1,5 @@ -use futures::channel::oneshot; use futures::StreamExt; +use futures::channel::oneshot; use libp2p::multiaddr::Protocol; use parking_lot::Mutex; use std::sync::Arc; @@ -26,9 +26,10 @@ async fn main() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/examples/metrics.rs b/crates/subspace-networking/examples/metrics.rs index fd809588e70..3613f671c0c 100644 --- a/crates/subspace-networking/examples/metrics.rs +++ b/crates/subspace-networking/examples/metrics.rs @@ -1,14 +1,14 @@ use futures::channel::oneshot; -use futures::{select, FutureExt, StreamExt}; +use futures::{FutureExt, StreamExt, select}; +use libp2p::PeerId; use libp2p::metrics::Metrics; use libp2p::multiaddr::Protocol; -use libp2p::PeerId; use parking_lot::Mutex; use prometheus_client::registry::Registry; use std::sync::Arc; use std::time::Duration; use subspace_logging::init_logger; -use subspace_metrics::{start_prometheus_metrics_server, RegistryAdapter}; +use subspace_metrics::{RegistryAdapter, start_prometheus_metrics_server}; use subspace_networking::{Config, Node}; use tokio::signal; use tokio::time::sleep; @@ -57,9 +57,10 @@ async fn main() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/examples/networking.rs b/crates/subspace-networking/examples/networking.rs index dd1b5aa3d56..e1b20b18c98 100644 --- a/crates/subspace-networking/examples/networking.rs +++ b/crates/subspace-networking/examples/networking.rs @@ -1,7 +1,7 @@ #![feature(type_changing_struct_update)] -use futures::channel::oneshot; use futures::StreamExt; +use futures::channel::oneshot; use libp2p::gossipsub::Sha256Topic; use libp2p::multiaddr::Protocol; use parking_lot::Mutex; @@ -31,9 +31,10 @@ async fn main() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/examples/random-walker.rs b/crates/subspace-networking/examples/random-walker.rs index dee2df856e7..b1ad278d54d 100644 --- a/crates/subspace-networking/examples/random-walker.rs +++ b/crates/subspace-networking/examples/random-walker.rs @@ -1,7 +1,7 @@ use clap::Parser; +use futures::StreamExt; use futures::channel::oneshot; use futures::future::pending; -use futures::StreamExt; use libp2p::identity::Keypair; use libp2p::multiaddr::Protocol; use libp2p::{Multiaddr, PeerId}; @@ -385,9 +385,10 @@ async fn configure_dsn( move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_address_sender) = node_address_sender.lock().take() { - node_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_address_sender) = node_address_sender.lock().take() + { + node_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/examples/requests.rs b/crates/subspace-networking/examples/requests.rs index b452ee26257..deedc03eafb 100644 --- a/crates/subspace-networking/examples/requests.rs +++ b/crates/subspace-networking/examples/requests.rs @@ -5,10 +5,10 @@ use parking_lot::Mutex; use std::sync::Arc; use std::time::Duration; use subspace_logging::init_logger; +use subspace_networking::Config; use subspace_networking::protocols::request_response::handlers::generic_request_handler::{ GenericRequest, GenericRequestHandler, }; -use subspace_networking::Config; use tokio::time::sleep; #[derive(Encode, Decode)] @@ -50,9 +50,10 @@ async fn main() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/src/behavior.rs b/crates/subspace-networking/src/behavior.rs index 73d0c815b75..dbdabcc94a4 100644 --- a/crates/subspace-networking/src/behavior.rs +++ b/crates/subspace-networking/src/behavior.rs @@ -14,6 +14,7 @@ use crate::protocols::reserved_peers::{ }; use crate::protocols::subspace_connection_limits::Behaviour as ConnectionLimitsBehaviour; use derive_more::From; +use libp2p::PeerId; use libp2p::allow_block_list::{Behaviour as AllowBlockListBehaviour, BlockedPeers}; use libp2p::autonat::Event as AutonatEvent; use libp2p::connection_limits::ConnectionLimits; @@ -23,9 +24,8 @@ use libp2p::gossipsub::{ use libp2p::identify::{Behaviour as Identify, Config as IdentifyConfig, Event as IdentifyEvent}; use libp2p::kad::{Behaviour as Kademlia, Config as KademliaConfig, Event as KademliaEvent}; use libp2p::ping::{Behaviour as Ping, Event as PingEvent}; -use libp2p::swarm::behaviour::toggle::Toggle; use libp2p::swarm::NetworkBehaviour; -use libp2p::PeerId; +use libp2p::swarm::behaviour::toggle::Toggle; use std::convert::Infallible; use void::Void as VoidEvent; diff --git a/crates/subspace-networking/src/behavior/persistent_parameters.rs b/crates/subspace-networking/src/behavior/persistent_parameters.rs index f2d848328c2..d8fd089b50e 100644 --- a/crates/subspace-networking/src/behavior/persistent_parameters.rs +++ b/crates/subspace-networking/src/behavior/persistent_parameters.rs @@ -2,8 +2,8 @@ use crate::utils::{AsyncJoinOnDrop, Handler, HandlerFn}; use async_trait::async_trait; use event_listener_primitives::HandlerId; use fs2::FileExt; -use futures::future::{pending, Fuse}; use futures::FutureExt; +use futures::future::{Fuse, pending}; use libp2p::multiaddr::Protocol; use libp2p::{Multiaddr, PeerId}; use memmap2::{MmapMut, MmapOptions}; @@ -19,9 +19,9 @@ use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, SystemTime}; use std::{io, mem}; -use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash}; use thiserror::Error; -use tokio::time::{sleep, Sleep}; +use tokio::time::{Sleep, sleep}; use tracing::{debug, error, trace, warn}; /// Defines optional time for address dial failure @@ -313,14 +313,15 @@ pub struct KnownPeersManager { impl Drop for KnownPeersManager { fn drop(&mut self) { if self.cache_need_saving - && let Some(known_peers_slots) = &self.known_peers_slots { - known_peers_slots - .lock() - .write_to_inactive_slot(&EncodableKnownPeers::from_cache( - &self.known_peers, - self.config.cache_size, - )); - } + && let Some(known_peers_slots) = &self.known_peers_slots + { + known_peers_slots + .lock() + .write_to_inactive_slot(&EncodableKnownPeers::from_cache( + &self.known_peers, + self.config.cache_size, + )); + } } } @@ -637,23 +638,24 @@ impl KnownPeersRegistry for KnownPeersManager { (&mut self.networking_parameters_save_delay).await; if let Some(known_peers_slots) = &self.known_peers_slots - && self.cache_need_saving { - let known_peers = - EncodableKnownPeers::from_cache(&self.known_peers, self.config.cache_size); - let known_peers_slots = Arc::clone(known_peers_slots); - let write_known_peers_fut = - AsyncJoinOnDrop::new(tokio::task::spawn_blocking(move || { - known_peers_slots - .lock() - .write_to_inactive_slot(&known_peers); - })); - - if let Err(error) = write_known_peers_fut.await { - error!(%error, "Failed to write known peers"); - } - - self.cache_need_saving = false; + && self.cache_need_saving + { + let known_peers = + EncodableKnownPeers::from_cache(&self.known_peers, self.config.cache_size); + let known_peers_slots = Arc::clone(known_peers_slots); + let write_known_peers_fut = + AsyncJoinOnDrop::new(tokio::task::spawn_blocking(move || { + known_peers_slots + .lock() + .write_to_inactive_slot(&known_peers); + })); + + if let Err(error) = write_known_peers_fut.await { + error!(%error, "Failed to write known peers"); } + + self.cache_need_saving = false; + } self.networking_parameters_save_delay = KnownPeersManager::default_delay(); } } @@ -688,9 +690,10 @@ pub(crate) fn append_p2p_suffix(peer_id: PeerId, mut address: Multiaddr) -> Mult let last_protocol = address.pop(); if let Some(protocol) = last_protocol - && !matches!(protocol, Protocol::P2p(..)) { - address.push(protocol) - } + && !matches!(protocol, Protocol::P2p(..)) + { + address.push(protocol) + } address.push(Protocol::P2p(peer_id)); address diff --git a/crates/subspace-networking/src/behavior/tests.rs b/crates/subspace-networking/src/behavior/tests.rs index 050723c546e..1d29ce31009 100644 --- a/crates/subspace-networking/src/behavior/tests.rs +++ b/crates/subspace-networking/src/behavior/tests.rs @@ -42,14 +42,18 @@ async fn test_address_timed_removal_from_known_peers_cache() { assert_eq!(peers_cache.len(), 1); let addresses_from_cache = peers_cache.get(&peer_id).expect("PeerId present"); assert_eq!(addresses_from_cache.len(), 2); - assert!(addresses_from_cache - .peek(&addr1) - .expect("Address present") - .is_none()); - assert!(addresses_from_cache - .peek(&addr2) - .expect("Address present") - .is_none()); + assert!( + addresses_from_cache + .peek(&addr1) + .expect("Address present") + .is_none() + ); + assert!( + addresses_from_cache + .peek(&addr2) + .expect("Address present") + .is_none() + ); let removed_addresses = remove_known_peer_addresses_internal( &mut peers_cache, @@ -64,14 +68,18 @@ async fn test_address_timed_removal_from_known_peers_cache() { assert_eq!(removed_addresses.len(), 0); let addresses_from_cache = peers_cache.get(&peer_id).expect("PeerId present"); assert_eq!(addresses_from_cache.len(), 2); - assert!(addresses_from_cache - .peek(&addr1) - .expect("Address present") - .is_some()); - assert!(addresses_from_cache - .peek(&addr2) - .expect("Address present") - .is_some()); + assert!( + addresses_from_cache + .peek(&addr1) + .expect("Address present") + .is_some() + ); + assert!( + addresses_from_cache + .peek(&addr2) + .expect("Address present") + .is_some() + ); let removed_addresses = remove_known_peer_addresses_internal( &mut peers_cache, @@ -201,9 +209,10 @@ async fn test_async_handler_works_with_pending_internal_future() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/src/bin/subspace-bootstrap-node/main.rs b/crates/subspace-networking/src/bin/subspace-bootstrap-node/main.rs index 8e3f07ad18d..f012fb3fe43 100644 --- a/crates/subspace-networking/src/bin/subspace-bootstrap-node/main.rs +++ b/crates/subspace-networking/src/bin/subspace-bootstrap-node/main.rs @@ -3,10 +3,10 @@ #![feature(type_changing_struct_update)] use clap::Parser; -use futures::{select, FutureExt}; +use futures::{FutureExt, select}; use libp2p::identity::ed25519::Keypair; use libp2p::kad::Mode; -use libp2p::{identity, Multiaddr, PeerId}; +use libp2p::{Multiaddr, PeerId, identity}; use prometheus_client::registry::Registry; use serde::{Deserialize, Serialize}; use std::error::Error; @@ -16,9 +16,9 @@ use std::panic; use std::process::exit; use std::sync::Arc; use subspace_logging::init_logger; -use subspace_metrics::{start_prometheus_metrics_server, RegistryAdapter}; +use subspace_metrics::{RegistryAdapter, start_prometheus_metrics_server}; use subspace_networking::libp2p::multiaddr::Protocol; -use subspace_networking::{peer_id, Config, KademliaMode}; +use subspace_networking::{Config, KademliaMode, peer_id}; use tracing::{debug, info}; /// Size of the LRU cache for peers. diff --git a/crates/subspace-networking/src/constructor.rs b/crates/subspace-networking/src/constructor.rs index 5eaded474f7..527f56d82d8 100644 --- a/crates/subspace-networking/src/constructor.rs +++ b/crates/subspace-networking/src/constructor.rs @@ -12,7 +12,7 @@ use crate::protocols::request_response::request_response_factory::RequestHandler use crate::protocols::reserved_peers::Config as ReservedPeersConfig; use crate::shared::Shared; use crate::utils::rate_limiter::RateLimiter; -use crate::utils::{strip_peer_id, SubspaceMetrics}; +use crate::utils::{SubspaceMetrics, strip_peer_id}; use backoff::{ExponentialBackoff, SystemClock}; use futures::channel::mpsc; use libp2p::autonat::Config as AutonatConfig; @@ -24,13 +24,13 @@ use libp2p::gossipsub::{ use libp2p::identify::Config as IdentifyConfig; use libp2p::kad::store::RecordStore; use libp2p::kad::{ - store, BucketInserts, Config as KademliaConfig, Mode, ProviderRecord, Record, RecordKey, - StoreInserts, + BucketInserts, Config as KademliaConfig, Mode, ProviderRecord, Record, RecordKey, StoreInserts, + store, }; use libp2p::metrics::Metrics; use libp2p::multiaddr::Protocol; use libp2p::yamux::Config as YamuxConfig; -use libp2p::{identity, Multiaddr, PeerId, StreamProtocol, SwarmBuilder, TransportError}; +use libp2p::{Multiaddr, PeerId, StreamProtocol, SwarmBuilder, TransportError, identity}; use parking_lot::Mutex; use prometheus_client::registry::Registry; use std::borrow::Cow; diff --git a/crates/subspace-networking/src/constructor/temporary_bans.rs b/crates/subspace-networking/src/constructor/temporary_bans.rs index c0db3c80b37..54f8cbd8660 100644 --- a/crates/subspace-networking/src/constructor/temporary_bans.rs +++ b/crates/subspace-networking/src/constructor/temporary_bans.rs @@ -1,5 +1,5 @@ -use backoff::backoff::Backoff; use backoff::ExponentialBackoff; +use backoff::backoff::Backoff; use libp2p::PeerId; use schnellru::{ByLength, LruMap}; use std::ops::Add; diff --git a/crates/subspace-networking/src/constructor/transport.rs b/crates/subspace-networking/src/constructor/transport.rs index 5aa288e6068..57241b90144 100644 --- a/crates/subspace-networking/src/constructor/transport.rs +++ b/crates/subspace-networking/src/constructor/transport.rs @@ -1,13 +1,13 @@ use crate::constructor::temporary_bans::TemporaryBans; +use libp2p::core::Transport; use libp2p::core::multiaddr::{Multiaddr, Protocol}; use libp2p::core::muxing::StreamMuxerBox; use libp2p::core::transport::{Boxed, DialOpts, ListenerId, TransportError, TransportEvent}; -use libp2p::core::Transport; use libp2p::dns::tokio::Transport as TokioTransport; -use libp2p::tcp::tokio::Transport as TokioTcpTransport; use libp2p::tcp::Config as GenTcpConfig; +use libp2p::tcp::tokio::Transport as TokioTcpTransport; use libp2p::yamux::Config as YamuxConfig; -use libp2p::{core, identity, noise, PeerId}; +use libp2p::{PeerId, core, identity, noise}; use parking_lot::Mutex; use std::io; use std::pin::Pin; @@ -121,10 +121,11 @@ where let temporary_bans = self.temporary_bans.lock(); for protocol in addr_iter { if let Protocol::P2p(peer_id) = protocol - && temporary_bans.is_banned(&peer_id) { - let error = io::Error::other("Peer is temporarily banned"); - return Err(TransportError::Other(error.into())); - } + && temporary_bans.is_banned(&peer_id) + { + let error = io::Error::other("Peer is temporarily banned"); + return Err(TransportError::Other(error.into())); + } } } diff --git a/crates/subspace-networking/src/lib.rs b/crates/subspace-networking/src/lib.rs index 7e60f62d773..1186c66b0e9 100644 --- a/crates/subspace-networking/src/lib.rs +++ b/crates/subspace-networking/src/lib.rs @@ -27,9 +27,9 @@ pub use crate::node::{ GetClosestPeersError, Node, SendRequestError, SubscribeError, TopicSubscription, WeakNode, }; pub use crate::node_runner::NodeRunner; -pub use constructor::{construct, peer_id, Config, CreationError, KademliaMode}; +pub use constructor::{Config, CreationError, KademliaMode, construct, peer_id}; pub use libp2p; pub use shared::PeerDiscovered; +pub use utils::PeerAddress; pub use utils::key_with_distance::KeyWithDistance; pub use utils::multihash::Multihash; -pub use utils::PeerAddress; diff --git a/crates/subspace-networking/src/node.rs b/crates/subspace-networking/src/node.rs index a9823d58bb2..6e4ea29922c 100644 --- a/crates/subspace-networking/src/node.rs +++ b/crates/subspace-networking/src/node.rs @@ -4,8 +4,8 @@ mod tests; use crate::protocols::request_response::handlers::generic_request_handler::GenericRequest; use crate::protocols::request_response::request_response_factory; use crate::shared::{Command, CreatedSubscription, PeerDiscovered, Shared}; -use crate::utils::multihash::Multihash; use crate::utils::HandlerFn; +use crate::utils::multihash::Multihash; use bytes::Bytes; use event_listener_primitives::HandlerId; use futures::channel::{mpsc, oneshot}; diff --git a/crates/subspace-networking/src/node/tests.rs b/crates/subspace-networking/src/node/tests.rs index 2be2d1220eb..b3d863ca8bb 100644 --- a/crates/subspace-networking/src/node/tests.rs +++ b/crates/subspace-networking/src/node/tests.rs @@ -1,7 +1,7 @@ use crate::protocols::request_response::handlers::generic_request_handler::{ GenericRequest, GenericRequestHandler, }; -use crate::{construct, Config}; +use crate::{Config, construct}; use futures::channel::oneshot; use libp2p::multiaddr::Protocol; use parity_scale_codec::{Decode, Encode}; @@ -41,9 +41,10 @@ async fn request_with_addresses() { move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) - && let Some(node_1_address_sender) = node_1_address_sender.lock().take() { - node_1_address_sender.send(address.clone()).unwrap(); - } + && let Some(node_1_address_sender) = node_1_address_sender.lock().take() + { + node_1_address_sender.send(address.clone()).unwrap(); + } } })); diff --git a/crates/subspace-networking/src/node_runner.rs b/crates/subspace-networking/src/node_runner.rs index 0f3aa89f760..70efc8971f4 100644 --- a/crates/subspace-networking/src/node_runner.rs +++ b/crates/subspace-networking/src/node_runner.rs @@ -1,14 +1,14 @@ use crate::behavior::persistent_parameters::{ - append_p2p_suffix, remove_p2p_suffix, KnownPeersRegistry, PeerAddressRemovedEvent, + KnownPeersRegistry, PeerAddressRemovedEvent, append_p2p_suffix, remove_p2p_suffix, }; use crate::behavior::{Behavior, Event}; -use crate::constructor::temporary_bans::TemporaryBans; use crate::constructor::DummyRecordStore; +use crate::constructor::temporary_bans::TemporaryBans; use crate::protocols::request_response::request_response_factory::{ Event as RequestResponseEvent, IfDisconnected, }; use crate::shared::{Command, CreatedSubscription, PeerDiscovered, Shared}; -use crate::utils::{is_global_address_or_dns, strip_peer_id, SubspaceMetrics}; +use crate::utils::{SubspaceMetrics, is_global_address_or_dns, strip_peer_id}; use async_lock::Mutex as AsyncMutex; use bytes::Bytes; use event_listener_primitives::HandlerId; @@ -1173,14 +1173,15 @@ impl NodeRunner { async fn handle_gossipsub_event(&mut self, event: GossipsubEvent) { if let GossipsubEvent::Message { message, .. } = event - && let Some(senders) = self.topic_subscription_senders.get(&message.topic) { - let bytes = Bytes::from(message.data); + && let Some(senders) = self.topic_subscription_senders.get(&message.topic) + { + let bytes = Bytes::from(message.data); - for sender in senders.values() { - // Doesn't matter if receiver is still listening for messages or not. - let _ = sender.unbounded_send(bytes.clone()); - } + for sender in senders.values() { + // Doesn't matter if receiver is still listening for messages or not. + let _ = sender.unbounded_send(bytes.clone()); } + } } async fn handle_request_response_event(&mut self, event: RequestResponseEvent) { @@ -1384,12 +1385,13 @@ impl NodeRunner { entry.remove_entry(); if let Some(gossipsub) = self.swarm.behaviour_mut().gossipsub.as_mut() - && !gossipsub.unsubscribe(&topic) { - warn!( - "Can't unsubscribe from topic {topic} because subscription doesn't exist, \ + && !gossipsub.unsubscribe(&topic) + { + warn!( + "Can't unsubscribe from topic {topic} because subscription doesn't exist, \ this is a logic error in the subspace or swarm libraries" - ); - } + ); + } } } else { error!( diff --git a/crates/subspace-networking/src/protocols/autonat_wrapper.rs b/crates/subspace-networking/src/protocols/autonat_wrapper.rs index 0a467e29ce5..787f9f40e68 100644 --- a/crates/subspace-networking/src/protocols/autonat_wrapper.rs +++ b/crates/subspace-networking/src/protocols/autonat_wrapper.rs @@ -1,7 +1,7 @@ use crate::utils::is_global_address_or_dns; use libp2p::autonat::{Behaviour as Autonat, Config as AutonatConfig, Event as AutonatEvent}; -use libp2p::core::transport::PortUse; use libp2p::core::Endpoint; +use libp2p::core::transport::PortUse; use libp2p::multiaddr::Protocol; use libp2p::swarm::{ ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, diff --git a/crates/subspace-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs b/crates/subspace-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs index 1e6daeecd59..77b31bf731d 100644 --- a/crates/subspace-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs +++ b/crates/subspace-networking/src/protocols/request_response/handlers/cached_piece_by_index/tests.rs @@ -11,10 +11,12 @@ fn closest_peers_encoding() { let closest_peers = ClosestPeers::from(vec![ { let peer_id = PeerId::random(); - let addresses = vec![Multiaddr::from(IpAddr::V4(Ipv4Addr::LOCALHOST)) - .with(Protocol::Tcp(1234)) - .with_p2p(peer_id) - .unwrap()]; + let addresses = vec![ + Multiaddr::from(IpAddr::V4(Ipv4Addr::LOCALHOST)) + .with(Protocol::Tcp(1234)) + .with_p2p(peer_id) + .unwrap(), + ]; (peer_id, addresses) }, @@ -57,10 +59,12 @@ fn closest_peers_encoding() { { let closest_peers = ClosestPeers::from(vec![{ let peer_id = PeerId::random(); - let addresses = vec![Multiaddr::from(IpAddr::V4(Ipv4Addr::LOCALHOST)) - .with(Protocol::Tcp(1234)) - .with_p2p(PeerId::random()) - .unwrap()]; + let addresses = vec![ + Multiaddr::from(IpAddr::V4(Ipv4Addr::LOCALHOST)) + .with(Protocol::Tcp(1234)) + .with_p2p(PeerId::random()) + .unwrap(), + ]; (peer_id, addresses) }]); diff --git a/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs b/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs index 2faacb7383d..32ec5dbaa69 100644 --- a/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs +++ b/crates/subspace-networking/src/protocols/request_response/request_response_factory.rs @@ -40,6 +40,7 @@ mod tests; use async_trait::async_trait; use futures::channel::{mpsc, oneshot}; use futures::prelude::*; +use libp2p::StreamProtocol; use libp2p::core::transport::PortUse; use libp2p::core::{Endpoint, Multiaddr}; use libp2p::identity::PeerId; @@ -55,10 +56,9 @@ use libp2p::swarm::handler::multi::MultiHandler; use libp2p::swarm::{ ConnectionDenied, ConnectionId, NetworkBehaviour, THandlerInEvent, THandlerOutEvent, ToSwarm, }; -use libp2p::StreamProtocol; use std::borrow::Cow; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::pin::Pin; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; @@ -349,7 +349,7 @@ impl RequestResponseFactoryBehaviour { match protocols.entry(Cow::Borrowed(config.name)) { Entry::Vacant(e) => e.insert((rq_rp, config.inbound_queue)), Entry::Occupied(e) => { - return Err(RegisterError::DuplicateProtocol(e.key().clone())) + return Err(RegisterError::DuplicateProtocol(e.key().clone())); } }; @@ -668,17 +668,18 @@ impl NetworkBehaviour for RequestResponseFactoryBehaviour { if let Ok(payload) = result && let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) - && protocol.send_response(inner_channel, Ok(payload)).is_err() { - // Note: Failure is handled further below when receiving - // `InboundFailure` event from `RequestResponse` behaviour. - debug!( - %request_id, - "Failed to send response for request on protocol {} due to a \ - timeout or due to the connection to the peer being closed. \ - Dropping response", - protocol_name, - ); - } + && protocol.send_response(inner_channel, Ok(payload)).is_err() + { + // Note: Failure is handled further below when receiving + // `InboundFailure` event from `RequestResponse` behaviour. + debug!( + %request_id, + "Failed to send response for request on protocol {} due to a \ + timeout or due to the connection to the peer being closed. \ + Dropping response", + protocol_name, + ); + } } for rq_rs_runner in &mut self.request_handlers { @@ -713,7 +714,7 @@ impl NetworkBehaviour for RequestResponseFactoryBehaviour { peer_id, handler, event: ((*protocol).to_string(), event), - }) + }); } ToSwarm::CloseConnection { peer_id, @@ -722,22 +723,22 @@ impl NetworkBehaviour for RequestResponseFactoryBehaviour { return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection, - }) + }); } ToSwarm::NewExternalAddrCandidate(observed) => { - return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)) + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)); } ToSwarm::ExternalAddrConfirmed(addr) => { - return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)) + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)); } ToSwarm::ExternalAddrExpired(addr) => { - return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)) + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)); } ToSwarm::ListenOn { opts } => { - return Poll::Ready(ToSwarm::ListenOn { opts }) + return Poll::Ready(ToSwarm::ListenOn { opts }); } ToSwarm::RemoveListener { id } => { - return Poll::Ready(ToSwarm::RemoveListener { id }) + return Poll::Ready(ToSwarm::RemoveListener { id }); } event => { warn!( @@ -906,7 +907,9 @@ pub enum RequestFailure { NotConnected, #[error("Given protocol hasn't been registered.")] UnknownProtocol, - #[error("Remote has closed the substream before answering, thereby signaling that it considers the request as valid, but refused to answer it.")] + #[error( + "Remote has closed the substream before answering, thereby signaling that it considers the request as valid, but refused to answer it." + )] Refused, #[error("The remote replied, but the local node is no longer interested in the response.")] Obsolete, @@ -985,7 +988,7 @@ impl RequestResponseCodec for GenericCodec { Err(unsigned_varint::io::ReadError::Io(err)) if matches!(err.kind(), io::ErrorKind::UnexpectedEof) => { - return Ok(Err(())) + return Ok(Err(())); } Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidInput, err)), }; diff --git a/crates/subspace-networking/src/protocols/request_response/request_response_factory/tests.rs b/crates/subspace-networking/src/protocols/request_response/request_response_factory/tests.rs index 20916d93fee..17a80b9d7b3 100644 --- a/crates/subspace-networking/src/protocols/request_response/request_response_factory/tests.rs +++ b/crates/subspace-networking/src/protocols/request_response/request_response_factory/tests.rs @@ -3,13 +3,13 @@ use crate::protocols::request_response::request_response_factory::{ RequestFailure, RequestHandler, RequestResponseFactoryBehaviour, }; use async_trait::async_trait; +use futures::StreamExt; use futures::channel::{mpsc, oneshot}; use futures::stream::FuturesUnordered; -use futures::StreamExt; use libp2p::core::transport::{MemoryTransport, Transport}; use libp2p::core::upgrade; use libp2p::swarm::{Swarm, SwarmEvent}; -use libp2p::{noise, SwarmBuilder}; +use libp2p::{SwarmBuilder, noise}; use libp2p_swarm_test::SwarmExt; use std::time::Duration; use std::{io, iter}; diff --git a/crates/subspace-networking/src/protocols/reserved_peers.rs b/crates/subspace-networking/src/protocols/reserved_peers.rs index 593d8d708f0..be0f244fddb 100644 --- a/crates/subspace-networking/src/protocols/reserved_peers.rs +++ b/crates/subspace-networking/src/protocols/reserved_peers.rs @@ -5,6 +5,7 @@ mod tests; use futures::FutureExt; use futures_timer::Delay; use handler::Handler; +use libp2p::PeerId; use libp2p::core::transport::PortUse; use libp2p::core::{Endpoint, Multiaddr}; use libp2p::swarm::behaviour::{ConnectionEstablished, FromSwarm}; @@ -13,7 +14,6 @@ use libp2p::swarm::{ ConnectionClosed, ConnectionDenied, ConnectionId, DialFailure, NetworkBehaviour, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }; -use libp2p::PeerId; use std::collections::HashMap; use std::task::{Context, Poll, Waker}; use std::time::Duration; @@ -184,12 +184,13 @@ impl NetworkBehaviour for Behaviour { .. }) => { if let Some(state) = self.reserved_peers_state.get_mut(&peer_id) - && remaining_established == 0 { - state.connection_status = ConnectionStatus::NotConnected; + && remaining_established == 0 + { + state.connection_status = ConnectionStatus::NotConnected; - debug!(%state.peer_id, "Reserved peer disconnected."); - self.wake(); - } + debug!(%state.peer_id, "Reserved peer disconnected."); + self.wake(); + } } FromSwarm::DialFailure(DialFailure { peer_id: Some(peer_id), diff --git a/crates/subspace-networking/src/protocols/reserved_peers/tests.rs b/crates/subspace-networking/src/protocols/reserved_peers/tests.rs index 769c3e555ca..140706d77ae 100644 --- a/crates/subspace-networking/src/protocols/reserved_peers/tests.rs +++ b/crates/subspace-networking/src/protocols/reserved_peers/tests.rs @@ -1,12 +1,12 @@ use crate::protocols::reserved_peers::{Behaviour, Config}; -use futures::{select, FutureExt}; +use futures::{FutureExt, select}; +use libp2p::core::Transport; use libp2p::core::transport::MemoryTransport; use libp2p::core::upgrade::Version; -use libp2p::core::Transport; use libp2p::identity::Keypair; use libp2p::plaintext::Config as PlainTextConfig; use libp2p::swarm::{NetworkBehaviour, SwarmEvent}; -use libp2p::{yamux, Swarm, SwarmBuilder}; +use libp2p::{Swarm, SwarmBuilder, yamux}; use libp2p_swarm_test::SwarmExt; use std::time::Duration; use tokio::time::sleep; diff --git a/crates/subspace-networking/src/protocols/subspace_connection_limits.rs b/crates/subspace-networking/src/protocols/subspace_connection_limits.rs index cd0c5d74e44..52c3e31c34e 100644 --- a/crates/subspace-networking/src/protocols/subspace_connection_limits.rs +++ b/crates/subspace-networking/src/protocols/subspace_connection_limits.rs @@ -1,6 +1,6 @@ use libp2p::connection_limits::{Behaviour as ConnectionLimitsBehaviour, ConnectionLimits}; -use libp2p::core::transport::PortUse; use libp2p::core::Endpoint; +use libp2p::core::transport::PortUse; use libp2p::multiaddr::Protocol; use libp2p::swarm::{ ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent, @@ -88,14 +88,13 @@ impl NetworkBehaviour for Behaviour { Protocol::Ip4(ip) => Some(IpAddr::V4(ip)), Protocol::Ip6(ip) => Some(IpAddr::V6(ip)), _ => None, - }) - && self - .incoming_allow_list - .values() - .any(|(ip_addresses, _attempts)| ip_addresses.contains(&ip_address)) - { - return Ok(()); - } + }) && self + .incoming_allow_list + .values() + .any(|(ip_addresses, _attempts)| ip_addresses.contains(&ip_address)) + { + return Ok(()); + } self.inner .handle_pending_inbound_connection(connection_id, local_addr, remote_addr) @@ -134,9 +133,10 @@ impl NetworkBehaviour for Behaviour { effective_role: Endpoint, ) -> Result, ConnectionDenied> { if let Some(peer) = &maybe_peer - && self.incoming_allow_list.contains_key(peer) { - return Ok(Vec::new()); - } + && self.incoming_allow_list.contains_key(peer) + { + return Ok(Vec::new()); + } self.inner.handle_pending_outbound_connection( connection_id, diff --git a/crates/subspace-networking/src/shared.rs b/crates/subspace-networking/src/shared.rs index edde4d85867..68221464be2 100644 --- a/crates/subspace-networking/src/shared.rs +++ b/crates/subspace-networking/src/shared.rs @@ -2,17 +2,17 @@ //! queries, subscriptions, various events and shared information. use crate::protocols::request_response::request_response_factory::RequestFailure; +use crate::utils::Handler; use crate::utils::multihash::Multihash; use crate::utils::rate_limiter::RateLimiter; -use crate::utils::Handler; use bytes::Bytes; use futures::channel::{mpsc, oneshot}; use libp2p::gossipsub::{PublishError, Sha256Topic, SubscriptionError}; use libp2p::kad::{PeerRecord, RecordKey}; use libp2p::{Multiaddr, PeerId}; use parking_lot::Mutex; -use std::sync::atomic::AtomicUsize; use std::sync::Arc; +use std::sync::atomic::AtomicUsize; use tokio::sync::OwnedSemaphorePermit; /// Represents Kademlia events (RoutablePeer, PendingRoutablePeer, UnroutablePeer). diff --git a/crates/subspace-networking/src/utils/key_with_distance.rs b/crates/subspace-networking/src/utils/key_with_distance.rs index 0a1fd04e387..327d37ababa 100644 --- a/crates/subspace-networking/src/utils/key_with_distance.rs +++ b/crates/subspace-networking/src/utils/key_with_distance.rs @@ -1,6 +1,6 @@ +pub use libp2p::PeerId; use libp2p::kad::KBucketDistance; pub use libp2p::kad::RecordKey; -pub use libp2p::PeerId; use std::cmp::Ordering; use std::hash::Hash; diff --git a/crates/subspace-networking/src/utils/piece_provider.rs b/crates/subspace-networking/src/utils/piece_provider.rs index 37e0dc849e5..808cfa45a7a 100644 --- a/crates/subspace-networking/src/utils/piece_provider.rs +++ b/crates/subspace-networking/src/utils/piece_provider.rs @@ -15,7 +15,7 @@ use futures::channel::mpsc; use futures::future::FusedFuture; use futures::stream::FuturesUnordered; use futures::task::noop_waker_ref; -use futures::{stream, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, stream}; use libp2p::kad::{Behaviour as Kademlia, KBucketKey, RecordKey}; use libp2p::swarm::NetworkBehaviour; use libp2p::{Multiaddr, PeerId}; @@ -28,7 +28,7 @@ use std::sync::Arc; use std::task::{Context, Poll}; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use tokio_stream::StreamMap; -use tracing::{debug, trace, warn, Instrument}; +use tracing::{Instrument, debug, trace, warn}; /// Validates piece against using its commitment. #[async_trait] diff --git a/crates/subspace-node/src/chain_spec.rs b/crates/subspace-node/src/chain_spec.rs index e1a561b0c2d..d88fc1ea857 100644 --- a/crates/subspace-node/src/chain_spec.rs +++ b/crates/subspace-node/src/chain_spec.rs @@ -13,9 +13,9 @@ use sp_core::crypto::Ss58Codec; use sp_domains::{EvmType, PermissionedActionAllowedBy}; use sp_runtime::{BoundedVec, Percent}; use std::marker::PhantomData; -use std::num::{NonZeroU128, NonZeroU32}; -use subspace_core_primitives::pot::PotKey; +use std::num::{NonZeroU32, NonZeroU128}; use subspace_core_primitives::PublicKey; +use subspace_core_primitives::pot::PotKey; use subspace_runtime::{ AllowAuthoringBy, BalancesConfig, CouncilConfig, DemocracyConfig, DomainsConfig, EnableRewardsAt, RewardPoint, RewardsConfig, RuntimeConfigsConfig, RuntimeGenesisConfig, diff --git a/crates/subspace-node/src/chain_spec_utils.rs b/crates/subspace-node/src/chain_spec_utils.rs index 2658b5fdf7a..37225a67be4 100644 --- a/crates/subspace-node/src/chain_spec_utils.rs +++ b/crates/subspace-node/src/chain_spec_utils.rs @@ -2,10 +2,10 @@ use frame_support::traits::Get; use sc_network::config::MultiaddrWithPeerId; use sc_service::Properties; use sp_core::crypto::AccountId32; -use sp_core::{sr25519, Pair, Public}; +use sp_core::{Pair, Public, sr25519}; use sp_domains::DomainId; -use sp_runtime::traits::IdentifyAccount; use sp_runtime::MultiSigner; +use sp_runtime::traits::IdentifyAccount; use std::collections::HashMap; use subspace_runtime::SS58Prefix; use subspace_runtime_primitives::DECIMAL_PLACES; diff --git a/crates/subspace-node/src/commands.rs b/crates/subspace-node/src/commands.rs index d26e5217def..a0f4c68925d 100644 --- a/crates/subspace-node/src/commands.rs +++ b/crates/subspace-node/src/commands.rs @@ -4,8 +4,8 @@ mod shared; mod wipe; pub use domain_key::{ - create_domain_key, insert_domain_key, CreateDomainKeyOptions, InsertDomainKeyOptions, + CreateDomainKeyOptions, InsertDomainKeyOptions, create_domain_key, insert_domain_key, }; -pub use run::{run, RunOptions}; +pub use run::{RunOptions, run}; pub(crate) use shared::set_exit_on_panic; -pub use wipe::{wipe, WipeOptions}; +pub use wipe::{WipeOptions, wipe}; diff --git a/crates/subspace-node/src/commands/domain_key.rs b/crates/subspace-node/src/commands/domain_key.rs index edb3c99878c..440355d81c9 100644 --- a/crates/subspace-node/src/commands/domain_key.rs +++ b/crates/subspace-node/src/commands/domain_key.rs @@ -1,10 +1,10 @@ -use crate::commands::shared::{derive_keypair, store_key_in_keystore, KeystoreOptions}; +use crate::commands::shared::{KeystoreOptions, derive_keypair, store_key_in_keystore}; use bip39::Mnemonic; use clap::Parser; use sc_cli::{Error, KeystoreParams}; use sc_service::config::KeystoreConfig; -use sp_core::crypto::{ExposeSecret, SecretString}; use sp_core::Pair; +use sp_core::crypto::{ExposeSecret, SecretString}; use sp_domains::DomainId; use std::path::PathBuf; use subspace_logging::init_logger; diff --git a/crates/subspace-node/src/commands/run.rs b/crates/subspace-node/src/commands/run.rs index 84429111d2f..da5db6d857f 100644 --- a/crates/subspace-node/src/commands/run.rs +++ b/crates/subspace-node/src/commands/run.rs @@ -3,13 +3,13 @@ mod domain; mod shared; use crate::commands::run::consensus::{ - create_consensus_chain_configuration, ConsensusChainConfiguration, ConsensusChainOptions, + ConsensusChainConfiguration, ConsensusChainOptions, create_consensus_chain_configuration, }; use crate::commands::run::domain::{ - create_domain_configuration, run_domain, DomainOptions, DomainStartOptions, - MIN_PRUNING as DOMAINS_MIN_PRUNING, + DomainOptions, DomainStartOptions, MIN_PRUNING as DOMAINS_MIN_PRUNING, + create_domain_configuration, run_domain, }; -use crate::{set_default_ss58_version, Error, PosTable}; +use crate::{Error, PosTable, set_default_ss58_version}; use clap::Parser; use cross_domain_message_gossip::GossipWorkerBuilder; use domain_client_operator::fetch_domain_bootstrap_info; @@ -17,8 +17,8 @@ use domain_client_operator::snap_sync::{ BlockImportingAcknowledgement, ConsensusChainSyncParams, SnapSyncOrchestrator, }; use domain_runtime_primitives::opaque::Block as DomainBlock; -use futures::stream::StreamExt; use futures::FutureExt; +use futures::stream::StreamExt; use sc_cli::Signals; use sc_client_api::HeaderBackend; use sc_consensus_slots::SlotProportion; @@ -35,7 +35,7 @@ use sp_messenger::messages::ChainId; use std::env; use std::sync::Arc; use subspace_logging::init_logger; -use subspace_metrics::{start_prometheus_metrics_server, RegistryAdapter}; +use subspace_metrics::{RegistryAdapter, start_prometheus_metrics_server}; use subspace_runtime::{Block, RuntimeApi}; use subspace_service::config::ChainSyncMode; use tracing::{debug, error, info, info_span, warn}; diff --git a/crates/subspace-node/src/commands/run/consensus.rs b/crates/subspace-node/src/commands/run/consensus.rs index afbe0bb897b..29aa242e089 100644 --- a/crates/subspace-node/src/commands/run/consensus.rs +++ b/crates/subspace-node/src/commands/run/consensus.rs @@ -1,11 +1,11 @@ use crate::commands::run::shared::{RpcOptions, TrieCacheParams}; -use crate::{chain_spec, derive_pot_external_entropy, Error}; +use crate::{Error, chain_spec, derive_pot_external_entropy}; use clap::Parser; use prometheus_client::registry::Registry; use sc_chain_spec::GenericChainSpec; use sc_cli::{ - generate_node_name, Cors, NodeKeyParams, NodeKeyType, RpcMethods, RuntimeParams, - TelemetryParams, TransactionPoolParams, RPC_DEFAULT_PORT, + Cors, NodeKeyParams, NodeKeyType, RPC_DEFAULT_PORT, RpcMethods, RuntimeParams, TelemetryParams, + TransactionPoolParams, generate_node_name, }; use sc_consensus_subspace::archiver::CreateObjectMappings; use sc_network::config::{MultiaddrWithPeerId, NonReservedPeerMode, Role, SetConfig}; @@ -20,8 +20,8 @@ use std::num::NonZeroU32; use std::path::PathBuf; use std::str::FromStr; use subspace_core_primitives::BlockNumber; -use subspace_networking::libp2p::multiaddr::Protocol; use subspace_networking::libp2p::Multiaddr; +use subspace_networking::libp2p::multiaddr::Protocol; use subspace_service::config::{ ChainSyncMode, SubspaceConfiguration, SubspaceNetworking, SubstrateConfiguration, SubstrateNetworkConfiguration, SubstrateRpcConfiguration, @@ -622,14 +622,15 @@ pub(super) fn create_consensus_chain_configuration( let node_name = name.unwrap_or_else(generate_node_name); if let StatePruningMode::Number(number) = pruning_params.state_pruning - && number < MIN_STATE_PRUNING { - // Do not return error because some users may in fact use lower values and we don't want - // to break their setups, at least for now - error!( - "Do not set state pruning number below {MIN_STATE_PRUNING} for safety reasons, \ + && number < MIN_STATE_PRUNING + { + // Do not return error because some users may in fact use lower values and we don't want + // to break their setups, at least for now + error!( + "Do not set state pruning number below {MIN_STATE_PRUNING} for safety reasons, \ node can break any time!" - ); - } + ); + } let consensus_chain_config = SubstrateConfiguration { impl_name: env!("CARGO_PKG_NAME").to_string(), diff --git a/crates/subspace-node/src/commands/run/domain.rs b/crates/subspace-node/src/commands/run/domain.rs index 18a021bc81d..4563254870c 100644 --- a/crates/subspace-node/src/commands/run/domain.rs +++ b/crates/subspace-node/src/commands/run/domain.rs @@ -1,12 +1,12 @@ +use crate::Error; use crate::commands::run::consensus::{BlocksPruningMode, StatePruningMode}; use crate::commands::run::shared::{RpcOptions, TrieCacheParams}; -use crate::commands::shared::{store_key_in_keystore, KeystoreOptions}; -use crate::Error; +use crate::commands::shared::{KeystoreOptions, store_key_in_keystore}; use clap::Parser; use domain_client_operator::snap_sync::ConsensusChainSyncParams; use domain_client_operator::{BootstrapResult, DomainChainSyncOracle, OperatorStreams}; -use domain_eth_service::provider::EthProvider; use domain_eth_service::DefaultEthConfig; +use domain_eth_service::provider::EthProvider; use domain_runtime_primitives::opaque::Block as DomainBlock; use domain_service::config::{ SubstrateConfiguration, SubstrateNetworkConfiguration, SubstrateRpcConfiguration, @@ -17,15 +17,15 @@ use evm_domain_runtime::AccountId as AccountId20; use futures::StreamExt; use sc_chain_spec::{ChainType, GenericChainSpec, NoExtension, Properties}; use sc_cli::{ - Cors, KeystoreParams, RpcMethods, RuntimeParams, TransactionPoolParams, RPC_DEFAULT_PORT, + Cors, KeystoreParams, RPC_DEFAULT_PORT, RpcMethods, RuntimeParams, TransactionPoolParams, }; use sc_consensus_subspace::block_import::BlockImportingNotification; use sc_consensus_subspace::notification::SubspaceNotificationStream; -use sc_network::config::{MultiaddrWithPeerId, NonReservedPeerMode, SetConfig, TransportConfig}; use sc_network::NetworkPeers; +use sc_network::config::{MultiaddrWithPeerId, NonReservedPeerMode, SetConfig, TransportConfig}; use sc_proof_of_time::source::PotSlotInfo; -use sc_service::config::{ExecutorConfiguration, KeystoreConfig}; use sc_service::Configuration; +use sc_service::config::{ExecutorConfiguration, KeystoreConfig}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender}; use sp_api::ProvideRuntimeApi; @@ -39,7 +39,7 @@ use std::sync::Arc; use subspace_runtime::RuntimeApi as CRuntimeApi; use subspace_runtime_primitives::opaque::Block as CBlock; use subspace_runtime_primitives::{ - HeaderFor, DOMAINS_BLOCK_PRUNING_DEPTH, DOMAINS_PRUNING_DEPTH_MULTIPLIER, + DOMAINS_BLOCK_PRUNING_DEPTH, DOMAINS_PRUNING_DEPTH_MULTIPLIER, HeaderFor, }; use subspace_service::FullClient as CFullClient; use tokio::sync::broadcast::Receiver; diff --git a/crates/subspace-node/src/commands/run/shared.rs b/crates/subspace-node/src/commands/run/shared.rs index 47f51348560..8c9ad832c8f 100644 --- a/crates/subspace-node/src/commands/run/shared.rs +++ b/crates/subspace-node/src/commands/run/shared.rs @@ -1,7 +1,7 @@ use clap::Parser; use sc_cli::{ - Cors, RpcMethods, RPC_DEFAULT_MAX_CONNECTIONS, RPC_DEFAULT_MAX_SUBS_PER_CONN, - RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN, + Cors, RPC_DEFAULT_MAX_CONNECTIONS, RPC_DEFAULT_MAX_SUBS_PER_CONN, + RPC_DEFAULT_MESSAGE_CAPACITY_PER_CONN, RpcMethods, }; use sc_service::config::IpNetwork; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; diff --git a/crates/subspace-node/src/commands/shared.rs b/crates/subspace-node/src/commands/shared.rs index ba6fcc18854..2726d62cf76 100644 --- a/crates/subspace-node/src/commands/shared.rs +++ b/crates/subspace-node/src/commands/shared.rs @@ -1,9 +1,9 @@ use clap::Parser; use sc_cli::Error; use sc_keystore::LocalKeystore; +use sp_core::Pair as PairT; use sp_core::crypto::{ExposeSecret, SecretString}; use sp_core::sr25519::Pair; -use sp_core::Pair as PairT; use sp_domains::KEY_TYPE; use sp_keystore::Keystore; use std::panic; diff --git a/crates/subspace-node/src/domain/auto_id_chain_spec.rs b/crates/subspace-node/src/domain/auto_id_chain_spec.rs index 282cdef26df..2090bd22b8f 100644 --- a/crates/subspace-node/src/domain/auto_id_chain_spec.rs +++ b/crates/subspace-node/src/domain/auto_id_chain_spec.rs @@ -13,8 +13,8 @@ use sc_service::ChainType; use sp_core::crypto::{AccountId32, UncheckedFrom}; use sp_domains::storage::RawGenesis; use sp_domains::{DomainRuntimeConfig, OperatorAllowList, OperatorPublicKey, RuntimeType}; -use sp_runtime::traits::Convert; use sp_runtime::BuildStorage; +use sp_runtime::traits::Convert; use std::collections::BTreeSet; use subspace_runtime_primitives::{Balance, SSC}; diff --git a/crates/subspace-node/src/domain/cli.rs b/crates/subspace-node/src/domain/cli.rs index 69f1ec30dd2..dae06c2d4a2 100644 --- a/crates/subspace-node/src/domain/cli.rs +++ b/crates/subspace-node/src/domain/cli.rs @@ -1,8 +1,8 @@ use crate::commands::{CreateDomainKeyOptions, InsertDomainKeyOptions}; use crate::domain::{auto_id_chain_spec, evm_chain_spec}; use clap::{Parser, ValueEnum}; -use domain_runtime_primitives::opaque::Block as DomainBlock; use domain_runtime_primitives::MultiAccountId; +use domain_runtime_primitives::opaque::Block as DomainBlock; use parity_scale_codec::Encode; use sc_cli::{ BlockNumberOrHash, ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, @@ -19,9 +19,9 @@ use sp_domains::storage::RawGenesis; use sp_domains::{ DomainId, DomainRuntimeConfig, OperatorAllowList, OperatorId, OperatorPublicKey, RuntimeType, }; +use sp_runtime::DigestItem; use sp_runtime::generic::BlockId; use sp_runtime::traits::Header; -use sp_runtime::DigestItem; use std::io::Write; use std::path::Path; use subspace_runtime::Block; diff --git a/crates/subspace-node/src/domain/evm_chain_spec.rs b/crates/subspace-node/src/domain/evm_chain_spec.rs index 985e19a72bd..0b63de43680 100644 --- a/crates/subspace-node/src/domain/evm_chain_spec.rs +++ b/crates/subspace-node/src/domain/evm_chain_spec.rs @@ -16,8 +16,8 @@ use sp_domains::storage::RawGenesis; use sp_domains::{ EvmDomainRuntimeConfig, EvmType, OperatorAllowList, OperatorPublicKey, RuntimeType, }; -use sp_runtime::traits::Convert; use sp_runtime::BuildStorage; +use sp_runtime::traits::Convert; use std::collections::BTreeSet; use subspace_runtime_primitives::{Balance, SSC}; diff --git a/crates/subspace-proof-of-space/benches/pos.rs b/crates/subspace-proof-of-space/benches/pos.rs index 95166d09cbc..a0948def7a8 100644 --- a/crates/subspace-proof-of-space/benches/pos.rs +++ b/crates/subspace-proof-of-space/benches/pos.rs @@ -1,6 +1,6 @@ #![feature(const_trait_impl)] -use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; #[cfg(feature = "parallel")] use rayon::ThreadPoolBuilder; use subspace_core_primitives::pos::PosSeed; @@ -73,17 +73,21 @@ fn pos_bench( group.bench_function("proof/missing", |b| { b.iter(|| { - assert!(table - .find_proof(black_box(challenge_index_without_solution)) - .is_none()); + assert!( + table + .find_proof(black_box(challenge_index_without_solution)) + .is_none() + ); }); }); group.bench_function("proof/present", |b| { b.iter(|| { - assert!(table - .find_proof(black_box(challenge_index_with_solution)) - .is_some()); + assert!( + table + .find_proof(black_box(challenge_index_with_solution)) + .is_some() + ); }); }); diff --git a/crates/subspace-proof-of-space/src/chia.rs b/crates/subspace-proof-of-space/src/chia.rs index 932a6cfc314..96663ad6d1d 100644 --- a/crates/subspace-proof-of-space/src/chia.rs +++ b/crates/subspace-proof-of-space/src/chia.rs @@ -58,9 +58,7 @@ impl Table for ChiaTable { let mut challenge = [0; 32]; challenge[..mem::size_of::()].copy_from_slice(&challenge_index.to_le_bytes()); - - self - .tables + self.tables .find_proof(&challenge) .next() .map(PosProof::from) diff --git a/crates/subspace-proof-of-space/src/chiapos.rs b/crates/subspace-proof-of-space/src/chiapos.rs index c3641638682..13c0c393ace 100644 --- a/crates/subspace-proof-of-space/src/chiapos.rs +++ b/crates/subspace-proof-of-space/src/chiapos.rs @@ -5,8 +5,8 @@ mod table; mod tables; mod utils; -use crate::chiapos::table::metadata_size_bytes; pub use crate::chiapos::table::TablesCache; +use crate::chiapos::table::metadata_size_bytes; use crate::chiapos::tables::TablesGeneric; use crate::chiapos::utils::EvaluatableUsize; diff --git a/crates/subspace-proof-of-space/src/chiapos/table.rs b/crates/subspace-proof-of-space/src/chiapos/table.rs index 9532197fde2..5cd51a6f363 100644 --- a/crates/subspace-proof-of-space/src/chiapos/table.rs +++ b/crates/subspace-proof-of-space/src/chiapos/table.rs @@ -5,10 +5,10 @@ pub(super) mod types; #[cfg(not(feature = "std"))] extern crate alloc; +use crate::chiapos::Seed; use crate::chiapos::constants::{PARAM_B, PARAM_BC, PARAM_C, PARAM_EXT, PARAM_M}; use crate::chiapos::table::types::{Metadata, Position, X, Y}; use crate::chiapos::utils::EvaluatableUsize; -use crate::chiapos::Seed; #[cfg(not(feature = "std"))] use alloc::vec; #[cfg(not(feature = "std"))] @@ -16,8 +16,8 @@ use alloc::vec::Vec; use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek}; use chacha20::{ChaCha8, Key, Nonce}; use core::array; -use core::simd::num::SimdUint; use core::simd::Simd; +use core::simd::num::SimdUint; #[cfg(all(feature = "std", any(feature = "parallel", test)))] use parking_lot::Mutex; #[cfg(any(feature = "parallel", test))] @@ -292,11 +292,7 @@ fn find_matches( let (a, b) = left_targets .left_targets .split_at(left_targets.left_targets.len() / 2); - if parity == 0 { - a - } else { - b - } + if parity == 0 { a } else { b } }; for (&y, left_position) in left_bucket_ys.iter().zip(left_bucket_start_position..) { diff --git a/crates/subspace-proof-of-space/src/chiapos/table/tests.rs b/crates/subspace-proof-of-space/src/chiapos/table/tests.rs index dafbc2cb379..c8d5d3e8989 100644 --- a/crates/subspace-proof-of-space/src/chiapos/table/tests.rs +++ b/crates/subspace-proof-of-space/src/chiapos/table/tests.rs @@ -1,14 +1,14 @@ //! Tests translated into Rust from //! https://github.com/Chia-Network/chiapos/blob/a2049c5367fe60930533a995f7ffded538f04dc4/tests/test.cpp +use crate::chiapos::Seed; use crate::chiapos::constants::{PARAM_B, PARAM_BC, PARAM_C, PARAM_EXT}; use crate::chiapos::table::types::{Metadata, Position, X, Y}; use crate::chiapos::table::{ - calculate_left_targets, compute_f1, compute_f1_simd, compute_fn, find_matches, - metadata_size_bytes, partial_y, COMPUTE_F1_SIMD_FACTOR, + COMPUTE_F1_SIMD_FACTOR, calculate_left_targets, compute_f1, compute_f1_simd, compute_fn, + find_matches, metadata_size_bytes, partial_y, }; use crate::chiapos::utils::EvaluatableUsize; -use crate::chiapos::Seed; use bitvec::prelude::*; use std::collections::BTreeMap; diff --git a/crates/subspace-proof-of-space/src/chiapos/tables.rs b/crates/subspace-proof-of-space/src/chiapos/tables.rs index e8109373f6a..162bb04d879 100644 --- a/crates/subspace-proof-of-space/src/chiapos/tables.rs +++ b/crates/subspace-proof-of-space/src/chiapos/tables.rs @@ -4,11 +4,11 @@ mod tests; #[cfg(not(feature = "std"))] extern crate alloc; -use crate::chiapos::table::types::{Metadata, Position, X, Y}; pub use crate::chiapos::table::TablesCache; +use crate::chiapos::table::types::{Metadata, Position, X, Y}; use crate::chiapos::table::{ - compute_f1, compute_fn, has_match, metadata_size_bytes, partial_y, Table, - COMPUTE_F1_SIMD_FACTOR, + COMPUTE_F1_SIMD_FACTOR, Table, compute_f1, compute_fn, has_match, metadata_size_bytes, + partial_y, }; use crate::chiapos::utils::EvaluatableUsize; use crate::chiapos::{Challenge, Quality, Seed}; diff --git a/crates/subspace-proof-of-space/src/shim.rs b/crates/subspace-proof-of-space/src/shim.rs index 409269adc83..0d1366b4a30 100644 --- a/crates/subspace-proof-of-space/src/shim.rs +++ b/crates/subspace-proof-of-space/src/shim.rs @@ -3,9 +3,9 @@ use crate::{PosTableType, Table, TableGenerator}; use core::iter; +use subspace_core_primitives::U256; use subspace_core_primitives::hashes::blake3_hash; use subspace_core_primitives::pos::{PosProof, PosSeed}; -use subspace_core_primitives::U256; /// Subspace proof of space table generator. /// diff --git a/crates/subspace-proof-of-time/benches/pot-compare-cpu-cores.rs b/crates/subspace-proof-of-time/benches/pot-compare-cpu-cores.rs index ccc3c473bd5..c9046921d39 100644 --- a/crates/subspace-proof-of-time/benches/pot-compare-cpu-cores.rs +++ b/crates/subspace-proof-of-time/benches/pot-compare-cpu-cores.rs @@ -1,5 +1,5 @@ use core::num::NonZeroU32; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use rand_chacha::ChaCha8Rng; use rand_core::{RngCore, SeedableRng}; use std::hint::black_box; diff --git a/crates/subspace-proof-of-time/benches/pot.rs b/crates/subspace-proof-of-time/benches/pot.rs index 85f4eb6d870..040f5e416c2 100644 --- a/crates/subspace-proof-of-time/benches/pot.rs +++ b/crates/subspace-proof-of-time/benches/pot.rs @@ -1,5 +1,5 @@ use core::num::NonZeroU32; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use rand_chacha::ChaCha8Rng; use rand_core::{RngCore, SeedableRng}; use std::hint::black_box; diff --git a/crates/subspace-proof-of-time/src/aes.rs b/crates/subspace-proof-of-time/src/aes.rs index 6a7ad05ee39..969d47f163c 100644 --- a/crates/subspace-proof-of-time/src/aes.rs +++ b/crates/subspace-proof-of-time/src/aes.rs @@ -3,9 +3,9 @@ #[cfg(target_arch = "x86_64")] mod x86_64; +use aes::Aes128; use aes::cipher::array::Array; use aes::cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit}; -use aes::Aes128; use subspace_core_primitives::pot::{PotCheckpoints, PotKey, PotOutput, PotSeed}; /// Creates the AES based proof. diff --git a/crates/subspace-proof-of-time/src/aes/x86_64.rs b/crates/subspace-proof-of-time/src/aes/x86_64.rs index 8c4bf4de47a..2e0d21cb51e 100644 --- a/crates/subspace-proof-of-time/src/aes/x86_64.rs +++ b/crates/subspace-proof-of-time/src/aes/x86_64.rs @@ -9,36 +9,38 @@ pub(super) unsafe fn create( seed: &[u8; 16], key: &[u8; 16], checkpoint_iterations: u32, -) -> PotCheckpoints { unsafe { - let mut checkpoints = PotCheckpoints::default(); +) -> PotCheckpoints { + unsafe { + let mut checkpoints = PotCheckpoints::default(); - let keys_reg = expand_key(key); - let xor_key = _mm_xor_si128(keys_reg[10], keys_reg[0]); - let mut seed_reg = _mm_loadu_si128(seed.as_ptr() as *const __m128i); - seed_reg = _mm_xor_si128(seed_reg, keys_reg[0]); - for checkpoint in checkpoints.iter_mut() { - for _ in 0..checkpoint_iterations { - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[1]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[2]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[3]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[4]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[5]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[6]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[7]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[8]); - seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[9]); - seed_reg = _mm_aesenclast_si128(seed_reg, xor_key); + let keys_reg = expand_key(key); + let xor_key = _mm_xor_si128(keys_reg[10], keys_reg[0]); + let mut seed_reg = _mm_loadu_si128(seed.as_ptr() as *const __m128i); + seed_reg = _mm_xor_si128(seed_reg, keys_reg[0]); + for checkpoint in checkpoints.iter_mut() { + for _ in 0..checkpoint_iterations { + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[1]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[2]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[3]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[4]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[5]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[6]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[7]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[8]); + seed_reg = _mm_aesenc_si128(seed_reg, keys_reg[9]); + seed_reg = _mm_aesenclast_si128(seed_reg, xor_key); + } + + let checkpoint_reg = _mm_xor_si128(seed_reg, keys_reg[0]); + _mm_storeu_si128( + checkpoint.as_mut().as_mut_ptr() as *mut __m128i, + checkpoint_reg, + ); } - let checkpoint_reg = _mm_xor_si128(seed_reg, keys_reg[0]); - _mm_storeu_si128( - checkpoint.as_mut().as_mut_ptr() as *mut __m128i, - checkpoint_reg, - ); + checkpoints } - - checkpoints -}} +} // Below code copied with minor changes from following place under MIT/Apache-2.0 license by Artyom // Pavlov: @@ -69,24 +71,26 @@ macro_rules! expand_round { #[target_feature(enable = "aes")] #[inline] -unsafe fn expand_key(key: &[u8; 16]) -> RoundKeys { unsafe { - // SAFETY: `RoundKeys` is a `[__m128i; 11]` which can be initialized - // with all zeroes. - let mut keys: RoundKeys = mem::zeroed(); +unsafe fn expand_key(key: &[u8; 16]) -> RoundKeys { + unsafe { + // SAFETY: `RoundKeys` is a `[__m128i; 11]` which can be initialized + // with all zeroes. + let mut keys: RoundKeys = mem::zeroed(); - let k = _mm_loadu_si128(key.as_ptr() as *const __m128i); - keys[0] = k; + let k = _mm_loadu_si128(key.as_ptr() as *const __m128i); + keys[0] = k; - expand_round!(keys, 1, 0x01); - expand_round!(keys, 2, 0x02); - expand_round!(keys, 3, 0x04); - expand_round!(keys, 4, 0x08); - expand_round!(keys, 5, 0x10); - expand_round!(keys, 6, 0x20); - expand_round!(keys, 7, 0x40); - expand_round!(keys, 8, 0x80); - expand_round!(keys, 9, 0x1B); - expand_round!(keys, 10, 0x36); + expand_round!(keys, 1, 0x01); + expand_round!(keys, 2, 0x02); + expand_round!(keys, 3, 0x04); + expand_round!(keys, 4, 0x08); + expand_round!(keys, 5, 0x10); + expand_round!(keys, 6, 0x20); + expand_round!(keys, 7, 0x40); + expand_round!(keys, 8, 0x80); + expand_round!(keys, 9, 0x1B); + expand_round!(keys, 10, 0x36); - keys -}} + keys + } +} diff --git a/crates/subspace-runtime-primitives/src/lib.rs b/crates/subspace-runtime-primitives/src/lib.rs index 66fb3d58168..2be24891815 100644 --- a/crates/subspace-runtime-primitives/src/lib.rs +++ b/crates/subspace-runtime-primitives/src/lib.rs @@ -7,14 +7,14 @@ pub mod utility; #[cfg(not(feature = "std"))] extern crate alloc; -use crate::time::{BLOCKS_IN_AN_MINUTE, BLOCKS_IN_A_DAY}; +use crate::time::{BLOCKS_IN_A_DAY, BLOCKS_IN_AN_MINUTE}; #[cfg(not(feature = "std"))] use alloc::vec::Vec; use core::marker::PhantomData; use frame_support::pallet_prelude::Weight; use frame_support::traits::tokens; -use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND; use frame_support::weights::WeightToFee; +use frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND; use frame_support::{Deserialize, Serialize}; use frame_system::limits::BlockLength; use frame_system::offchain::CreateTransactionBase; @@ -117,9 +117,9 @@ parameter_types! { /// structures. pub mod opaque { use super::BlockNumber; + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; use sp_runtime::generic; use sp_runtime::traits::BlakeTwo256; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; /// Opaque block header type. pub type Header = generic::Header; @@ -319,8 +319,8 @@ pub mod tests_utils { use frame_support::weights::Weight; use frame_system::limits::BlockWeights; use pallet_transaction_payment::{Multiplier, MultiplierUpdate}; - use sp_runtime::traits::{Convert, Get}; use sp_runtime::BuildStorage; + use sp_runtime::traits::{Convert, Get}; use std::marker::PhantomData; pub struct FeeMultiplierUtils( diff --git a/crates/subspace-runtime-primitives/src/utility.rs b/crates/subspace-runtime-primitives/src/utility.rs index 6106b63d020..9335f3cc7fa 100644 --- a/crates/subspace-runtime-primitives/src/utility.rs +++ b/crates/subspace-runtime-primitives/src/utility.rs @@ -5,8 +5,8 @@ use frame_support::pallet_prelude::TypeInfo; use frame_system::pallet_prelude::RuntimeCallFor; use scale_info::prelude::collections::VecDeque; use scale_info::prelude::vec; -use sp_runtime::traits::{BlockNumberProvider, Get}; use sp_runtime::Vec; +use sp_runtime::traits::{BlockNumberProvider, Get}; /// Trait used to convert from a generated `RuntimeCall` type to `pallet_utility::Call`. pub trait MaybeUtilityCall diff --git a/crates/subspace-runtime/src/lib.rs b/crates/subspace-runtime/src/lib.rs index d86bb0166ad..1710470c794 100644 --- a/crates/subspace-runtime/src/lib.rs +++ b/crates/subspace-runtime/src/lib.rs @@ -32,22 +32,22 @@ use core::mem; use core::num::NonZeroU64; use domain_runtime_primitives::opaque::Header as DomainHeader; use domain_runtime_primitives::{ - maximum_domain_block_weight, AccountIdConverter, BlockNumber as DomainNumber, - EthereumAccountId, Hash as DomainHash, MAX_OUTGOING_MESSAGES, + AccountIdConverter, BlockNumber as DomainNumber, EthereumAccountId, Hash as DomainHash, + MAX_OUTGOING_MESSAGES, maximum_domain_block_weight, }; use frame_support::genesis_builder_helper::{build_state, get_preset}; use frame_support::inherent::ProvideInherent; use frame_support::traits::fungible::HoldConsideration; use frame_support::traits::{ - ConstU16, ConstU32, ConstU64, ConstU8, Currency, EitherOfDiverse, EqualPrivilegeOnly, + ConstU8, ConstU16, ConstU32, ConstU64, Currency, EitherOfDiverse, EqualPrivilegeOnly, Everything, Get, LinearStoragePrice, OnUnbalanced, Time, VariantCount, }; use frame_support::weights::constants::ParityDbWeight; use frame_support::weights::{ConstantMultiplier, Weight}; -use frame_support::{construct_runtime, parameter_types, PalletId}; +use frame_support::{PalletId, construct_runtime, parameter_types}; +use frame_system::EnsureRoot; use frame_system::limits::{BlockLength, BlockWeights}; use frame_system::pallet_prelude::RuntimeCallFor; -use frame_system::EnsureRoot; use pallet_collective::{EnsureMember, EnsureProportionAtLeast}; pub use pallet_rewards::RewardPoint; pub use pallet_subspace::{AllowAuthoringBy, EnableRewardsAt}; @@ -58,12 +58,12 @@ use sp_api::impl_runtime_apis; use sp_consensus_slots::{Slot, SlotDuration}; use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges, Vote}; use sp_core::crypto::KeyTypeId; -use sp_core::{ConstBool, OpaqueMetadata, H256}; +use sp_core::{ConstBool, H256, OpaqueMetadata}; use sp_domains::bundle_producer_election::BundleProducerElectionParams; use sp_domains::{ - ChannelId, DomainAllowlistUpdates, DomainId, DomainInstanceData, ExecutionReceiptFor, - OperatorId, OperatorPublicKey, OperatorRewardSource, PermissionedActionAllowedBy, - DOMAIN_STORAGE_FEE_MULTIPLIER, INITIAL_DOMAIN_TX_RANGE, + ChannelId, DOMAIN_STORAGE_FEE_MULTIPLIER, DomainAllowlistUpdates, DomainId, DomainInstanceData, + ExecutionReceiptFor, INITIAL_DOMAIN_TX_RANGE, OperatorId, OperatorPublicKey, + OperatorRewardSource, PermissionedActionAllowedBy, }; use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_domains_fraud_proof::storage_proof::{ @@ -75,20 +75,20 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, ConstU128, Keccak256, NumberFor, }; use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity}; use sp_runtime::type_with_default::TypeWithDefault; -use sp_runtime::{generic, AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill}; +use sp_runtime::{AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill, generic}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; use sp_std::marker::PhantomData; use sp_std::prelude::*; -use sp_subspace_mmr::subspace_mmr_runtime_interface::consensus_block_hash; use sp_subspace_mmr::ConsensusChainMmrLeafProof; +use sp_subspace_mmr::subspace_mmr_runtime_interface::consensus_block_hash; use sp_version::RuntimeVersion; use static_assertions::const_assert; use subspace_core_primitives::objects::BlockObjectMapping; @@ -97,19 +97,19 @@ use subspace_core_primitives::segments::{ HistorySize, SegmentCommitment, SegmentHeader, SegmentIndex, }; use subspace_core_primitives::solutions::{ - pieces_to_solution_range, solution_range_to_pieces, SolutionRange, + SolutionRange, pieces_to_solution_range, solution_range_to_pieces, }; use subspace_core_primitives::{PublicKey, Randomness, SlotNumber, U256}; use subspace_runtime_primitives::utility::{ DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall, }; use subspace_runtime_primitives::{ - maximum_normal_block_length, AccountId, Balance, BlockHashFor, BlockNumber, - ConsensusEventSegmentSize, ExtrinsicFor, FindBlockRewardAddress, Hash, HeaderFor, - HoldIdentifier, Moment, Nonce, Signature, SlowAdjustingFeeUpdate, TargetBlockFullness, - XdmAdjustedWeightToFee, XdmFeeMultipler, BLOCK_WEIGHT_FOR_2_SEC, DOMAINS_BLOCK_PRUNING_DEPTH, - MAX_BLOCK_LENGTH, MIN_REPLICATION_FACTOR, NORMAL_DISPATCH_RATIO, SHANNON, SLOT_PROBABILITY, - SSC, + AccountId, BLOCK_WEIGHT_FOR_2_SEC, Balance, BlockHashFor, BlockNumber, + ConsensusEventSegmentSize, DOMAINS_BLOCK_PRUNING_DEPTH, ExtrinsicFor, FindBlockRewardAddress, + Hash, HeaderFor, HoldIdentifier, MAX_BLOCK_LENGTH, MIN_REPLICATION_FACTOR, Moment, + NORMAL_DISPATCH_RATIO, Nonce, SHANNON, SLOT_PROBABILITY, SSC, Signature, + SlowAdjustingFeeUpdate, TargetBlockFullness, XdmAdjustedWeightToFee, XdmFeeMultipler, + maximum_normal_block_length, }; sp_runtime::impl_opaque_keys! { diff --git a/crates/subspace-service/src/config.rs b/crates/subspace-service/src/config.rs index b6bb2504782..c3a6d687d5c 100644 --- a/crates/subspace-service/src/config.rs +++ b/crates/subspace-service/src/config.rs @@ -2,8 +2,8 @@ use crate::dsn::DsnConfig; use sc_chain_spec::ChainSpec; use sc_consensus_subspace::archiver::CreateObjectMappings; use sc_network::config::{ - MultiaddrWithPeerId, NetworkBackendType, NetworkConfiguration, NodeKeyConfig, SetConfig, - SyncMode, TransportConfig, DEFAULT_KADEMLIA_REPLICATION_FACTOR, + DEFAULT_KADEMLIA_REPLICATION_FACTOR, MultiaddrWithPeerId, NetworkBackendType, + NetworkConfiguration, NodeKeyConfig, SetConfig, SyncMode, TransportConfig, }; use sc_service::config::{ ExecutorConfiguration, IpNetwork, KeystoreConfig, OffchainWorkerConfig, PrometheusConfig, @@ -21,11 +21,11 @@ use std::num::{NonZeroU32, NonZeroUsize}; use std::ops::Deref; use std::path::PathBuf; use std::str::FromStr; -use std::sync::atomic::AtomicBool; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use subspace_data_retrieval::piece_getter::PieceGetter; -use subspace_networking::libp2p::Multiaddr; use subspace_networking::Node; +use subspace_networking::libp2p::Multiaddr; use tokio::runtime::Handle; /// The default max request size in MB, copied from Substrate diff --git a/crates/subspace-service/src/dsn.rs b/crates/subspace-service/src/dsn.rs index 85d8d532560..ece6f24d81d 100644 --- a/crates/subspace-service/src/dsn.rs +++ b/crates/subspace-service/src/dsn.rs @@ -3,7 +3,7 @@ use std::collections::HashSet; use std::fs; use std::path::PathBuf; use subspace_networking::libp2p::kad::Mode; -use subspace_networking::libp2p::{identity, Multiaddr}; +use subspace_networking::libp2p::{Multiaddr, identity}; use subspace_networking::protocols::request_response::handlers::cached_piece_by_index::CachedPieceByIndexRequestHandler; use subspace_networking::protocols::request_response::handlers::piece_by_index::PieceByIndexRequestHandler; use subspace_networking::protocols::request_response::handlers::segment_header::SegmentHeaderBySegmentIndexesRequestHandler; diff --git a/crates/subspace-service/src/lib.rs b/crates/subspace-service/src/lib.rs index cdef0b7dc55..0e9c5685672 100644 --- a/crates/subspace-service/src/lib.rs +++ b/crates/subspace-service/src/lib.rs @@ -18,19 +18,19 @@ mod task_spawner; mod utils; use crate::config::{ChainSyncMode, SubspaceConfiguration, SubspaceNetworking}; -use crate::dsn::{create_dsn_instance, DsnConfigurationError}; +use crate::dsn::{DsnConfigurationError, create_dsn_instance}; use crate::metrics::NodeMetrics; use crate::mmr::request_handler::MmrRequestHandler; +use crate::sync_from_dsn::DsnPieceGetter; use crate::sync_from_dsn::piece_validator::SegmentCommitmentPieceValidator; use crate::sync_from_dsn::snap_sync::snap_sync; -use crate::sync_from_dsn::DsnPieceGetter; use async_lock::Semaphore; use core::sync::atomic::{AtomicU32, Ordering}; use cross_domain_message_gossip::xdm_gossip_peers_set_config; use domain_runtime_primitives::opaque::{Block as DomainBlock, Header as DomainHeader}; use frame_system_rpc_runtime_api::AccountNonceApi; -use futures::channel::oneshot; use futures::FutureExt; +use futures::channel::oneshot; use jsonrpsee::RpcModule; use pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi; use parity_scale_codec::Decode; @@ -47,9 +47,10 @@ use sc_consensus::{ DefaultImportQueue, ImportQueue, ImportResult, }; use sc_consensus_slots::SlotProportion; +use sc_consensus_subspace::SubspaceLink; use sc_consensus_subspace::archiver::{ - create_subspace_archiver, ArchivedSegmentNotification, ObjectMappingNotification, - SegmentHeadersStore, + ArchivedSegmentNotification, ObjectMappingNotification, SegmentHeadersStore, + create_subspace_archiver, }; use sc_consensus_subspace::block_import::{BlockImportingNotification, SubspaceBlockImport}; use sc_consensus_subspace::notification::SubspaceNotificationStream; @@ -58,9 +59,8 @@ use sc_consensus_subspace::slot_worker::{ SubspaceSyncOracle, }; use sc_consensus_subspace::verifier::{SubspaceVerifier, SubspaceVerifierOptions}; -use sc_consensus_subspace::SubspaceLink; -use sc_domains::domain_block_er::execution_receipt_protocol::DomainBlockERRequestHandler; use sc_domains::ExtensionsFactory as DomainsExtensionFactory; +use sc_domains::domain_block_er::execution_receipt_protocol::DomainBlockERRequestHandler; use sc_network::service::traits::NetworkService; use sc_network::{NetworkWorker, NotificationMetrics, NotificationService, Roles}; use sc_network_sync::block_relay_protocol::BlockRelayParams; @@ -71,11 +71,11 @@ use sc_proof_of_time::source::{PotSlotInfo, PotSourceWorker}; use sc_proof_of_time::verifier::PotVerifier; use sc_service::error::Error as ServiceError; use sc_service::{ - build_network_advanced, build_polkadot_syncing_strategy, BuildNetworkAdvancedParams, - Configuration, NetworkStarter, SpawnTasksParams, TaskManager, + BuildNetworkAdvancedParams, Configuration, NetworkStarter, SpawnTasksParams, TaskManager, + build_network_advanced, build_polkadot_syncing_strategy, }; use sc_subspace_block_relay::{ - build_consensus_relay, BlockRelayConfigurationError, NetworkWrapper, + BlockRelayConfigurationError, NetworkWrapper, build_consensus_relay, }; use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_transaction_pool::TransactionPoolHandle; @@ -89,10 +89,10 @@ use sp_consensus_subspace::digests::extract_pre_digest; use sp_consensus_subspace::{ KzgExtension, PosExtension, PotExtension, PotNextSlotInput, SubspaceApi, }; -use sp_core::offchain::storage::OffchainDb; +use sp_core::H256; use sp_core::offchain::OffchainDbExt; +use sp_core::offchain::storage::OffchainDb; use sp_core::traits::SpawnEssentialNamed; -use sp_core::H256; use sp_domains::storage::StorageKey; use sp_domains::{BundleProducerElectionApi, DomainsApi}; use sp_domains_fraud_proof::{FraudProofApi, FraudProofExtension, FraudProofHostFunctionsImpl}; @@ -122,7 +122,7 @@ use subspace_proof_of_space::Table; use subspace_runtime_primitives::opaque::Block; use subspace_runtime_primitives::{AccountId, Balance, BlockHashFor, Hash, Nonce}; use tokio::sync::broadcast; -use tracing::{debug, error, info, Instrument}; +use tracing::{Instrument, debug, error, info}; pub use utils::wait_for_block_import; // There are multiple places where it is assumed that node is running on 64-bit system, refuse to @@ -856,9 +856,10 @@ where move |address| { if matches!(address.iter().next(), Some(Protocol::Ip4(_))) && let Some(node_address_sender) = node_address_sender.lock().take() - && let Err(err) = node_address_sender.send(address.clone()) { - debug!(?err, "Couldn't send a node address to the channel."); - } + && let Err(err) = node_address_sender.send(address.clone()) + { + debug!(?err, "Couldn't send a node address to the channel."); + } } })); @@ -1121,10 +1122,11 @@ where Box::pin(async move { // Run snap-sync before DSN-sync. if config.sync == ChainSyncMode::Snap - && let Err(error) = snap_sync_task.in_current_span().await { - error!(%error, "Snap sync exited with a fatal error"); - return; - } + && let Err(error) = snap_sync_task.in_current_span().await + { + error!(%error, "Snap sync exited with a fatal error"); + return; + } if let Err(error) = worker.await { error!(%error, "Sync from DSN exited with an error"); diff --git a/crates/subspace-service/src/metrics.rs b/crates/subspace-service/src/metrics.rs index d838aea9a4e..ec6aae726da 100644 --- a/crates/subspace-service/src/metrics.rs +++ b/crates/subspace-service/src/metrics.rs @@ -5,7 +5,7 @@ use parity_scale_codec::Encode; use sc_client_api::{BlockBackend, BlockImportNotification, ImportNotifications}; use sp_runtime::traits::Block as BlockT; use std::sync::Arc; -use substrate_prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; +use substrate_prometheus_endpoint::{Counter, PrometheusError, Registry, U64, register}; pub struct NodeMetrics { client: Arc, diff --git a/crates/subspace-service/src/mmr.rs b/crates/subspace-service/src/mmr.rs index 42c85780d1e..f27a26966ab 100644 --- a/crates/subspace-service/src/mmr.rs +++ b/crates/subspace-service/src/mmr.rs @@ -1,6 +1,6 @@ use sp_core::H256; use sp_mmr_primitives::utils::NodesUtils; -use sp_mmr_primitives::{NodeIndex, INDEXING_PREFIX}; +use sp_mmr_primitives::{INDEXING_PREFIX, NodeIndex}; use subspace_runtime_primitives::opaque::Header; pub(crate) mod request_handler; diff --git a/crates/subspace-service/src/mmr/sync.rs b/crates/subspace-service/src/mmr/sync.rs index 384a4bf3bba..1553a06d0f6 100644 --- a/crates/subspace-service/src/mmr/sync.rs +++ b/crates/subspace-service/src/mmr/sync.rs @@ -1,5 +1,5 @@ use crate::mmr::get_offchain_key; -use crate::mmr::request_handler::{generate_protocol_name, MmrRequest, MmrResponse, MAX_MMR_ITEMS}; +use crate::mmr::request_handler::{MAX_MMR_ITEMS, MmrRequest, MmrResponse, generate_protocol_name}; use futures::channel::oneshot; use parity_scale_codec::{Decode, Encode}; use sc_network::{IfDisconnected, NetworkRequest, PeerId, RequestFailure}; @@ -8,10 +8,10 @@ use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_core::offchain::storage::OffchainDb; use sp_core::offchain::{DbExternalities, OffchainStorage, StorageKind}; -use sp_core::{Hasher, H256}; +use sp_core::{H256, Hasher}; use sp_mmr_primitives::mmr_lib::{MMRStoreReadOps, MMRStoreWriteOps}; use sp_mmr_primitives::utils::NodesUtils; -use sp_mmr_primitives::{mmr_lib, DataOrHash, MmrApi}; +use sp_mmr_primitives::{DataOrHash, MmrApi, mmr_lib}; use sp_runtime::traits::{Block as BlockT, Keccak256, NumberFor}; use sp_subspace_mmr::MmrLeaf; use std::cell::RefCell; diff --git a/crates/subspace-service/src/sync_from_dsn.rs b/crates/subspace-service/src/sync_from_dsn.rs index a798eb900e6..4d4b91989e3 100644 --- a/crates/subspace-service/src/sync_from_dsn.rs +++ b/crates/subspace-service/src/sync_from_dsn.rs @@ -7,28 +7,28 @@ use crate::sync_from_dsn::import_blocks::import_blocks_from_dsn; use crate::sync_from_dsn::segment_header_downloader::SegmentHeaderDownloader; use async_trait::async_trait; use futures::channel::mpsc; -use futures::{select, FutureExt, Stream, StreamExt}; +use futures::{FutureExt, Stream, StreamExt, select}; use sc_client_api::{AuxStore, BlockBackend, BlockchainEvents}; use sc_consensus::import_queue::ImportQueueService; use sc_consensus_subspace::archiver::SegmentHeadersStore; -use sc_network::service::traits::NetworkService; use sc_network::NetworkBlock; +use sc_network::service::traits::NetworkService; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_consensus_subspace::SubspaceApi; use sp_runtime::traits::{Block as BlockT, CheckedSub, NumberFor}; use std::fmt; use std::future::Future; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::time::{Duration, Instant}; +use subspace_core_primitives::PublicKey; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_core_primitives::segments::SegmentIndex; -use subspace_core_primitives::PublicKey; use subspace_data_retrieval::piece_getter::PieceGetter; use subspace_erasure_coding::ErasureCoding; -use subspace_networking::utils::piece_provider::{PieceProvider, PieceValidator}; use subspace_networking::Node; +use subspace_networking::utils::piece_provider::{PieceProvider, PieceValidator}; use tracing::{debug, info, warn}; /// How much time to wait for new block to be imported before timing out and starting sync from DSN @@ -225,10 +225,11 @@ async fn create_imported_blocks_observer( Err(_timeout) => { if let Err(error) = notifications_sender.try_send(NotificationReason::NoImportedBlocks) - && error.is_disconnected() { - // Receiving side was closed - return; - } + && error.is_disconnected() + { + // Receiving side was closed + return; + } } } } @@ -249,13 +250,15 @@ async fn create_substrate_network_observer( let was_online = last_online .map(|last_online| last_online.elapsed() < MIN_OFFLINE_PERIOD) .unwrap_or_default(); - if is_online && !was_online + if is_online + && !was_online && let Err(error) = notifications_sender.try_send(NotificationReason::WentOnlineSubstrate) - && error.is_disconnected() { - // Receiving side was closed - return; - } + && error.is_disconnected() + { + // Receiving side was closed + return; + } if is_online { last_online.replace(Instant::now()); diff --git a/crates/subspace-service/src/sync_from_dsn/import_blocks.rs b/crates/subspace-service/src/sync_from_dsn/import_blocks.rs index 7a4a2d9807a..0311289aac4 100644 --- a/crates/subspace-service/src/sync_from_dsn/import_blocks.rs +++ b/crates/subspace-service/src/sync_from_dsn/import_blocks.rs @@ -1,20 +1,20 @@ -use crate::sync_from_dsn::segment_header_downloader::SegmentHeaderDownloader; use crate::sync_from_dsn::PieceGetter; +use crate::sync_from_dsn::segment_header_downloader::SegmentHeaderDownloader; use sc_client_api::{AuxStore, BlockBackend, HeaderBackend}; -use sc_consensus::import_queue::ImportQueueService; use sc_consensus::IncomingBlock; -use sc_consensus_subspace::archiver::{decode_block, encode_block, SegmentHeadersStore}; +use sc_consensus::import_queue::ImportQueueService; +use sc_consensus_subspace::archiver::{SegmentHeadersStore, decode_block, encode_block}; use sc_service::Error; use sc_tracing::tracing::{debug, info, trace}; use sp_consensus::BlockOrigin; +use sp_runtime::Saturating; use sp_runtime::generic::SignedBlock; use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One}; -use sp_runtime::Saturating; use std::sync::{Arc, Mutex}; use std::time::Duration; use subspace_archiving::reconstructor::Reconstructor; -use subspace_core_primitives::segments::SegmentIndex; use subspace_core_primitives::BlockNumber; +use subspace_core_primitives::segments::SegmentIndex; use subspace_data_retrieval::segment_downloading::download_segment_pieces; use subspace_erasure_coding::ErasureCoding; use tokio::task; diff --git a/crates/subspace-service/src/sync_from_dsn/piece_validator.rs b/crates/subspace-service/src/sync_from_dsn/piece_validator.rs index beb5f632c29..4a17a6f1cf5 100644 --- a/crates/subspace-service/src/sync_from_dsn/piece_validator.rs +++ b/crates/subspace-service/src/sync_from_dsn/piece_validator.rs @@ -3,9 +3,9 @@ use sc_client_api::AuxStore; use sc_consensus_subspace::archiver::SegmentHeadersStore; use subspace_core_primitives::pieces::{Piece, PieceIndex}; use subspace_kzg::Kzg; +use subspace_networking::Node; use subspace_networking::libp2p::PeerId; use subspace_networking::utils::piece_provider::PieceValidator; -use subspace_networking::Node; use subspace_verification::is_piece_valid; use tracing::{error, warn}; diff --git a/crates/subspace-service/src/sync_from_dsn/segment_header_downloader.rs b/crates/subspace-service/src/sync_from_dsn/segment_header_downloader.rs index e29448a16ea..0f386927968 100644 --- a/crates/subspace-service/src/sync_from_dsn/segment_header_downloader.rs +++ b/crates/subspace-service/src/sync_from_dsn/segment_header_downloader.rs @@ -4,11 +4,11 @@ use std::error::Error; use std::pin::pin; use std::sync::Arc; use subspace_core_primitives::segments::{SegmentHeader, SegmentIndex}; +use subspace_networking::Node; use subspace_networking::libp2p::PeerId; use subspace_networking::protocols::request_response::handlers::segment_header::{ SegmentHeaderRequest, SegmentHeaderResponse, }; -use subspace_networking::Node; use tracing::{debug, error, trace, warn}; const SEGMENT_HEADER_NUMBER_PER_REQUEST: u64 = 1000; diff --git a/crates/subspace-service/src/sync_from_dsn/snap_sync.rs b/crates/subspace-service/src/sync_from_dsn/snap_sync.rs index f56d461f0e6..d1c869622cb 100644 --- a/crates/subspace-service/src/sync_from_dsn/snap_sync.rs +++ b/crates/subspace-service/src/sync_from_dsn/snap_sync.rs @@ -1,6 +1,6 @@ use crate::mmr::sync::MmrSync; -use crate::sync_from_dsn::segment_header_downloader::SegmentHeaderDownloader; use crate::sync_from_dsn::PieceGetter; +use crate::sync_from_dsn::segment_header_downloader::SegmentHeaderDownloader; use crate::utils::wait_for_block_import; use sc_client_api::{AuxStore, BlockchainEvents, ProofProvider}; use sc_consensus::import_queue::ImportQueueService; @@ -8,18 +8,18 @@ use sc_consensus::{ BlockImport, BlockImportParams, ForkChoiceStrategy, ImportedState, IncomingBlock, StateAction, StorageChanges, }; -use sc_consensus_subspace::archiver::{decode_block, SegmentHeadersStore}; +use sc_consensus_subspace::archiver::{SegmentHeadersStore, decode_block}; use sc_network::service::traits::NetworkService; use sc_network::{NetworkBlock, NetworkRequest, PeerId}; -use sc_network_sync::service::network::NetworkServiceHandle; use sc_network_sync::SyncingService; +use sc_network_sync::service::network::NetworkServiceHandle; use sc_subspace_sync_common::snap_sync_engine::SnapSyncingEngine; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; use sp_consensus_subspace::SubspaceApi; -use sp_core::offchain::OffchainStorage; use sp_core::H256; +use sp_core::offchain::OffchainStorage; use sp_mmr_primitives::MmrApi; use sp_objects::ObjectsApi; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; diff --git a/crates/subspace-service/src/task_spawner.rs b/crates/subspace-service/src/task_spawner.rs index a9fd2c37979..b41e468674c 100644 --- a/crates/subspace-service/src/task_spawner.rs +++ b/crates/subspace-service/src/task_spawner.rs @@ -17,12 +17,12 @@ use sc_client_api::{ BlockBackend, BlockchainEvents, ExecutorProvider, ProofProvider, StorageProvider, UsageProvider, }; -use sc_network::multiaddr::Protocol; use sc_network::Multiaddr; +use sc_network::multiaddr::Protocol; use sc_rpc_api::DenyUnsafe; use sc_service::{ - gen_rpc_module, init_telemetry, propagate_transaction_notifications, start_rpc_servers, Error, - MetricsService, RpcHandlers, SpawnTasksParams, + Error, MetricsService, RpcHandlers, SpawnTasksParams, gen_rpc_module, init_telemetry, + propagate_transaction_notifications, start_rpc_servers, }; use sc_transaction_pool_api::MaintainedTransactionPool; use sp_api::{CallApiAt, ProvideRuntimeApi}; diff --git a/crates/subspace-verification/src/lib.rs b/crates/subspace-verification/src/lib.rs index 5d48ac976da..031b57806fa 100644 --- a/crates/subspace-verification/src/lib.rs +++ b/crates/subspace-verification/src/lib.rs @@ -20,11 +20,11 @@ use core::mem; #[cfg(feature = "kzg")] use core::simd::Simd; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use schnorrkel::context::SigningContext; use schnorrkel::SignatureError; +use schnorrkel::context::SigningContext; #[cfg(feature = "kzg")] use subspace_core_primitives::hashes::blake3_254_hash_to_scalar; -use subspace_core_primitives::hashes::{blake3_hash_list, blake3_hash_with_key, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash_list, blake3_hash_with_key}; #[cfg(feature = "kzg")] use subspace_core_primitives::pieces::{PieceArray, Record, RecordWitness}; use subspace_core_primitives::pot::PotOutput; diff --git a/domains/client/block-builder/src/custom_api.rs b/domains/client/block-builder/src/custom_api.rs index 5f8a4c686db..011d338402c 100644 --- a/domains/client/block-builder/src/custom_api.rs +++ b/domains/client/block-builder/src/custom_api.rs @@ -2,7 +2,7 @@ use hash_db::{HashDB, Hasher, Prefix}; use parity_scale_codec::{Codec, Decode, Encode}; -use sc_client_api::{backend, ExecutorProvider, StateBackend}; +use sc_client_api::{ExecutorProvider, StateBackend, backend}; use sp_core::offchain::OffchainOverlayedChange; use sp_core::traits::{CallContext, CodeExecutor, FetchRuntimeCode}; use sp_inherents::InherentData; diff --git a/domains/client/block-builder/src/genesis_block_builder.rs b/domains/client/block-builder/src/genesis_block_builder.rs index e037bc74c65..3c2293080ac 100644 --- a/domains/client/block-builder/src/genesis_block_builder.rs +++ b/domains/client/block-builder/src/genesis_block_builder.rs @@ -1,16 +1,16 @@ //! Custom genesis block builder to inject correct genesis block. use hex_literal::hex; -use sc_chain_spec::{construct_genesis_block, resolve_state_version_from_wasm, BuildGenesisBlock}; +use sc_chain_spec::{BuildGenesisBlock, construct_genesis_block, resolve_state_version_from_wasm}; use sc_client_api::{Backend, BlockImportOperation}; use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_core::storage::Storage; use sp_core::H256; +use sp_core::storage::Storage; use sp_domains::{DomainId, DomainsApi}; -use sp_runtime::traits::{Block as BlockT, HashingFor}; use sp_runtime::BuildStorage; +use sp_runtime::traits::{Block as BlockT, HashingFor}; use std::marker::PhantomData; use std::sync::Arc; diff --git a/domains/client/block-builder/src/lib.rs b/domains/client/block-builder/src/lib.rs index 1cdbfde9fbf..54ce02af240 100644 --- a/domains/client/block-builder/src/lib.rs +++ b/domains/client/block-builder/src/lib.rs @@ -31,16 +31,16 @@ mod custom_api; mod genesis_block_builder; use crate::custom_api::{TrieBackendApi, TrieDeltaBackendFor}; -pub use custom_api::{create_delta_backend, CollectedStorageChanges, DeltaBackend}; +pub use custom_api::{CollectedStorageChanges, DeltaBackend, create_delta_backend}; pub use genesis_block_builder::CustomGenesisBlockBuilder; use parity_scale_codec::Encode; -use sc_client_api::{backend, ExecutorProvider}; +use sc_client_api::{ExecutorProvider, backend}; use sp_api::{ProvideRuntimeApi, TransactionOutcome}; pub use sp_block_builder::BlockBuilder as BlockBuilderApi; use sp_blockchain::{ApplyExtrinsicFailed, Error}; use sp_core::traits::CodeExecutor; -use sp_runtime::traits::{Block as BlockT, Hash, HashingFor, Header as HeaderT, NumberFor, One}; use sp_runtime::Digest; +use sp_runtime::traits::{Block as BlockT, Hash, HashingFor, Header as HeaderT, NumberFor, One}; use sp_state_machine::OverlayedChanges; use std::collections::VecDeque; use std::sync::Arc; diff --git a/domains/client/block-preprocessor/src/lib.rs b/domains/client/block-preprocessor/src/lib.rs index 0b56fffdeca..2cf274645bb 100644 --- a/domains/client/block-preprocessor/src/lib.rs +++ b/domains/client/block-preprocessor/src/lib.rs @@ -17,14 +17,14 @@ pub mod stateless_runtime; use crate::inherents::is_runtime_upgraded; use crate::stateless_runtime::StatelessRuntime; use domain_runtime_primitives::opaque::AccountId; -use domain_runtime_primitives::{opaque, CheckExtrinsicsValidityError}; +use domain_runtime_primitives::{CheckExtrinsicsValidityError, opaque}; use parity_scale_codec::Encode; -use sc_client_api::{backend, BlockBackend}; +use sc_client_api::{BlockBackend, backend}; use sc_executor::RuntimeVersionOf; use sp_api::{ApiError, ApiExt, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; -use sp_core::traits::{CodeExecutor, FetchRuntimeCode}; use sp_core::H256; +use sp_core::traits::{CodeExecutor, FetchRuntimeCode}; use sp_domains::core_api::DomainCoreApi; use sp_domains::extrinsics::deduplicate_and_shuffle_extrinsics; use sp_domains::{ @@ -34,8 +34,8 @@ use sp_domains::{ use sp_messenger::MessengerApi; use sp_mmr_primitives::MmrApi; use sp_runtime::traits::{Block as BlockT, Hash as HashT, NumberFor}; -use sp_state_machine::backend::AsTrieBackend; use sp_state_machine::LayoutV1; +use sp_state_machine::backend::AsTrieBackend; use sp_subspace_mmr::ConsensusChainMmrLeafProof; use sp_weights::Weight; use std::collections::VecDeque; diff --git a/domains/client/block-preprocessor/src/stateless_runtime.rs b/domains/client/block-preprocessor/src/stateless_runtime.rs index ea79e535515..b4f9ef6bf5e 100644 --- a/domains/client/block-preprocessor/src/stateless_runtime.rs +++ b/domains/client/block-preprocessor/src/stateless_runtime.rs @@ -1,21 +1,21 @@ use domain_runtime_primitives::opaque::AccountId; use domain_runtime_primitives::{ - opaque, Balance, CheckExtrinsicsValidityError, DecodeExtrinsicError, EthereumAccountId, + Balance, CheckExtrinsicsValidityError, DecodeExtrinsicError, EthereumAccountId, opaque, }; use parity_scale_codec::{Codec, Encode}; use sc_client_api::execution_extensions::ExtensionsFactory; use sc_executor::RuntimeVersionOf; use sp_api::{ApiError, Core}; -use sp_core::traits::{CallContext, CodeExecutor, FetchRuntimeCode, RuntimeCode}; use sp_core::Hasher; +use sp_core::traits::{CallContext, CodeExecutor, FetchRuntimeCode, RuntimeCode}; use sp_domain_sudo::DomainSudoApi; use sp_domains::core_api::DomainCoreApi; use sp_domains::{ChainId, ChannelId, DomainAllowlistUpdates, PermissionedActionAllowedBy}; use sp_evm_tracker::EvmTrackerApi; use sp_messenger::messages::MessageKey; use sp_messenger::{MessengerApi, RelayerApi}; -use sp_runtime::traits::{Block as BlockT, NumberFor}; use sp_runtime::Storage; +use sp_runtime::traits::{Block as BlockT, NumberFor}; use sp_state_machine::BasicExternalities; use sp_subspace_mmr::ConsensusChainMmrLeafProof; use sp_version::RuntimeVersion; diff --git a/domains/client/consensus-relay-chain/src/import_queue.rs b/domains/client/consensus-relay-chain/src/import_queue.rs index e75b9ceec98..d8d6e9dbf53 100644 --- a/domains/client/consensus-relay-chain/src/import_queue.rs +++ b/domains/client/consensus-relay-chain/src/import_queue.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . -use sc_consensus::import_queue::Verifier as VerifierT; use sc_consensus::BlockImportParams; +use sc_consensus::import_queue::Verifier as VerifierT; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use std::marker::PhantomData; diff --git a/domains/client/cross-domain-message-gossip/src/aux_schema.rs b/domains/client/cross-domain-message-gossip/src/aux_schema.rs index 4e046cd7895..56c20c3747c 100644 --- a/domains/client/cross-domain-message-gossip/src/aux_schema.rs +++ b/domains/client/cross-domain-message-gossip/src/aux_schema.rs @@ -3,8 +3,8 @@ use parity_scale_codec::{Decode, Encode}; use sc_client_api::backend::AuxStore; use sp_blockchain::{Error as ClientError, Info, Result as ClientResult}; -use sp_core::bytes::to_hex; use sp_core::H256; +use sp_core::bytes::to_hex; use sp_messenger::messages::{ChainId, ChannelId, ChannelState, Nonce}; use sp_messenger::{ChannelNonce, XdmId}; use sp_runtime::traits::{Block as BlockT, NumberFor}; @@ -93,8 +93,8 @@ where mod xdm_keys { use parity_scale_codec::Encode; use sp_domains::{ChainId, ChannelId}; - use sp_messenger::messages::MessageKey; use sp_messenger::XdmId; + use sp_messenger::messages::MessageKey; const XDM: &[u8] = b"xdm"; const XDM_RELAY: &[u8] = b"relay_msg"; diff --git a/domains/client/cross-domain-message-gossip/src/gossip_worker.rs b/domains/client/cross-domain-message-gossip/src/gossip_worker.rs index f197a1c9e88..f9de233dbd4 100644 --- a/domains/client/cross-domain-message-gossip/src/gossip_worker.rs +++ b/domains/client/cross-domain-message-gossip/src/gossip_worker.rs @@ -7,7 +7,7 @@ use sc_network_gossip::{ GossipEngine, MessageIntent, Syncing as GossipSyncing, ValidationResult, Validator, ValidatorContext, }; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; +use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender, tracing_unbounded}; use sp_api::StorageProof; use sp_consensus::SyncOracle; use sp_core::twox_256; @@ -164,15 +164,16 @@ fn topic() -> Block::Hash { impl GossipWorker { /// Starts the Gossip message worker. pub async fn run(mut self) { - let incoming_cross_chain_messages = pin!(self - .gossip_engine - .lock() - .messages_for(topic::()) - .filter_map(|notification| async move { - Message::decode(&mut ¬ification.message[..]) - .ok() - .map(|msg| (notification.sender, msg)) - })); + let incoming_cross_chain_messages = pin!( + self.gossip_engine + .lock() + .messages_for(topic::()) + .filter_map(|notification| async move { + Message::decode(&mut ¬ification.message[..]) + .ok() + .map(|msg| (notification.sender, msg)) + }) + ); let mut incoming_cross_chain_messages = incoming_cross_chain_messages.fuse(); loop { diff --git a/domains/client/cross-domain-message-gossip/src/lib.rs b/domains/client/cross-domain-message-gossip/src/lib.rs index 4c19607b65a..5273e94db66 100644 --- a/domains/client/cross-domain-message-gossip/src/lib.rs +++ b/domains/client/cross-domain-message-gossip/src/lib.rs @@ -6,11 +6,11 @@ mod gossip_worker; mod message_listener; pub use aux_schema::{ - get_channel_state, get_xdm_processed_block_number, set_channel_state, - set_xdm_message_processed_at, BlockId, ChannelDetail, + BlockId, ChannelDetail, get_channel_state, get_xdm_processed_block_number, set_channel_state, + set_xdm_message_processed_at, }; pub use gossip_worker::{ - xdm_gossip_peers_set_config, ChainMsg, ChainSink, ChannelUpdate, GossipWorker, - GossipWorkerBuilder, Message, MessageData, + ChainMsg, ChainSink, ChannelUpdate, GossipWorker, GossipWorkerBuilder, Message, MessageData, + xdm_gossip_peers_set_config, }; pub use message_listener::{can_allow_xdm_submission, start_cross_chain_message_listener}; diff --git a/domains/client/cross-domain-message-gossip/src/message_listener.rs b/domains/client/cross-domain-message-gossip/src/message_listener.rs index 55ec951df54..c68cfb6d549 100644 --- a/domains/client/cross-domain-message-gossip/src/message_listener.rs +++ b/domains/client/cross-domain-message-gossip/src/message_listener.rs @@ -1,6 +1,6 @@ use crate::aux_schema::{ - cleanup_chain_channel_storages, get_channel_state, get_xdm_processed_block_number, - set_channel_state, set_xdm_message_processed_at, BlockId, + BlockId, cleanup_chain_channel_storages, get_channel_state, get_xdm_processed_block_number, + set_channel_state, set_xdm_message_processed_at, }; use crate::gossip_worker::{ChannelUpdate, MessageData}; use crate::{ChainMsg, ChannelDetail}; @@ -18,7 +18,7 @@ use sp_consensus::SyncOracle; use sp_core::crypto::AccountId32; use sp_core::storage::StorageKey; use sp_core::traits::CodeExecutor; -use sp_core::{Hasher, H256}; +use sp_core::{H256, Hasher}; use sp_domains::proof_provider_and_verifier::{StorageProofVerifier, VerificationError}; use sp_domains::{DomainId, DomainsApi, RuntimeType}; use sp_messenger::messages::{ChainId, Channel, ChannelId}; @@ -284,11 +284,11 @@ where consensus_client.hash(existing_channel_update.block_number.into())?; if let Some(block_hash) = maybe_block_hash && block_hash.as_ref() == existing_channel_update.block_hash.as_ref() - && header.state_root().as_ref() == existing_channel_update.state_root.as_ref() - && existing_channel_update.block_number >= consensus_block_number - { - return Ok(()); - } + && header.state_root().as_ref() == existing_channel_update.state_root.as_ref() + && existing_channel_update.block_number >= consensus_block_number + { + return Ok(()); + } } let storage_key = StorageKey(api.channel_storage_key(best_hash, self_chain_id, channel_id)?); @@ -389,11 +389,11 @@ where if let Ok((existing_block_hash, _)) = is_valid_domain_block_number(existing_channel_update.block_number) && existing_block_hash.as_ref() == existing_channel_update.block_hash.as_ref() - && domain_state_root.as_ref() == existing_channel_update.state_root.as_ref() - && existing_channel_update.block_number >= domain_block_number - { - return Ok(()); - } + && domain_state_root.as_ref() == existing_channel_update.state_root.as_ref() + && existing_channel_update.block_number >= domain_block_number + { + return Ok(()); + } } let domain_runtime = runtime_api diff --git a/domains/client/domain-operator/src/aux_schema.rs b/domains/client/domain-operator/src/aux_schema.rs index a865dbf03a0..385d0de5ac1 100644 --- a/domains/client/domain-operator/src/aux_schema.rs +++ b/domains/client/domain-operator/src/aux_schema.rs @@ -5,10 +5,10 @@ use parity_scale_codec::{Decode, Encode}; use sc_client_api::backend::AuxStore; use sp_blockchain::{Error as ClientError, HeaderBackend, Result as ClientResult}; use sp_domains::InvalidBundleType; +use sp_runtime::Saturating; use sp_runtime::traits::{ Block as BlockT, CheckedMul, CheckedSub, NumberFor, One, SaturatedConversion, Zero, }; -use sp_runtime::Saturating; use std::collections::BTreeSet; use std::sync::Arc; use subspace_core_primitives::BlockNumber; diff --git a/domains/client/domain-operator/src/bundle_processor.rs b/domains/client/domain-operator/src/bundle_processor.rs index d70948cac9b..fc4df804ff5 100644 --- a/domains/client/domain-operator/src/bundle_processor.rs +++ b/domains/client/domain-operator/src/bundle_processor.rs @@ -1,7 +1,7 @@ +use crate::ExecutionReceiptFor; use crate::domain_block_processor::{ DomainBlockProcessor, PendingConsensusBlocks, ReceiptsChecker, }; -use crate::ExecutionReceiptFor; use domain_block_preprocessor::DomainBlockPreprocessor; use sc_client_api::{AuxStore, BlockBackend, ExecutorProvider, Finalizer, ProofProvider}; use sc_consensus::{BlockImportParams, ForkChoiceStrategy, StateAction}; @@ -9,8 +9,8 @@ use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus::BlockOrigin; -use sp_core::traits::CodeExecutor; use sp_core::H256; +use sp_core::traits::CodeExecutor; use sp_domain_digests::AsPredigest; use sp_domains::core_api::DomainCoreApi; use sp_domains::{DomainId, DomainsApi, ReceiptValidity}; diff --git a/domains/client/domain-operator/src/bundle_producer_election_solver.rs b/domains/client/domain-operator/src/bundle_producer_election_solver.rs index fdc99277ac0..0fcd2fc0ebd 100644 --- a/domains/client/domain-operator/src/bundle_producer_election_solver.rs +++ b/domains/client/domain-operator/src/bundle_producer_election_solver.rs @@ -1,16 +1,16 @@ use sp_api::ProvideRuntimeApi; use sp_consensus_slots::Slot; -use sp_core::bytes::to_hex; use sp_core::ByteArray; +use sp_core::bytes::to_hex; use sp_domains::bundle_producer_election::{ - calculate_threshold, is_below_threshold, make_transcript, BundleProducerElectionParams, + BundleProducerElectionParams, calculate_threshold, is_below_threshold, make_transcript, }; use sp_domains::{ BundleProducerElectionApi, DomainId, OperatorId, OperatorPublicKey, ProofOfElection, }; use sp_keystore::{Keystore, KeystorePtr}; -use sp_runtime::traits::Block as BlockT; use sp_runtime::RuntimeAppPublic; +use sp_runtime::traits::Block as BlockT; use std::marker::PhantomData; use std::sync::Arc; use subspace_core_primitives::pot::PotOutput; @@ -107,9 +107,9 @@ where } } else { log::warn!( - "Operator[{operator_id}]'s Signing key[{}] pair is not available in keystore.", - to_hex(operator_signing_key.as_slice(), false) - ); + "Operator[{operator_id}]'s Signing key[{}] pair is not available in keystore.", + to_hex(operator_signing_key.as_slice(), false) + ); return Ok(None); } } diff --git a/domains/client/domain-operator/src/domain_block_processor.rs b/domains/client/domain-operator/src/domain_block_processor.rs index a0c9c21c714..e54dfcab071 100644 --- a/domains/client/domain-operator/src/domain_block_processor.rs +++ b/domains/client/domain-operator/src/domain_block_processor.rs @@ -1,10 +1,10 @@ +use crate::ExecutionReceiptFor; use crate::aux_schema::BundleMismatchType; use crate::fraud_proof::FraudProofGenerator; use crate::utils::{DomainBlockImportNotification, DomainImportNotificationSinks}; -use crate::ExecutionReceiptFor; use domain_block_builder::{BlockBuilder, BuiltBlock, CollectedStorageChanges}; -use domain_block_preprocessor::inherents::get_inherent_data; use domain_block_preprocessor::PreprocessResult; +use domain_block_preprocessor::inherents::get_inherent_data; use parity_scale_codec::Encode; use sc_client_api::{AuxStore, BlockBackend, ExecutorProvider, Finalizer, ProofProvider}; use sc_consensus::{ @@ -16,13 +16,13 @@ use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::{HashAndNumber, HeaderBackend, HeaderMetadata}; use sp_consensus::{BlockOrigin, SyncOracle}; -use sp_core::traits::CodeExecutor; use sp_core::H256; +use sp_core::traits::CodeExecutor; use sp_domains::core_api::DomainCoreApi; use sp_domains::merkle_tree::MerkleTree; use sp_domains::{BundleValidity, DomainId, DomainsApi, ExecutionReceipt, HeaderHashingFor}; -use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_domains_fraud_proof::FraudProofApi; +use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_messenger::MessengerApi; use sp_mmr_primitives::MmrApi; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor, One, Zero}; diff --git a/domains/client/domain-operator/src/domain_bundle_producer.rs b/domains/client/domain-operator/src/domain_bundle_producer.rs index b168630611d..8de02efa0a2 100644 --- a/domains/client/domain-operator/src/domain_bundle_producer.rs +++ b/domains/client/domain-operator/src/domain_bundle_producer.rs @@ -1,7 +1,7 @@ +use crate::BundleSender; use crate::bundle_producer_election_solver::BundleProducerElectionSolver; use crate::domain_bundle_proposer::DomainBundleProposer; use crate::utils::OperatorSlotInfo; -use crate::BundleSender; use async_trait::async_trait; use parity_scale_codec::Decode; use sc_client_api::{AuxStore, BlockBackend}; diff --git a/domains/client/domain-operator/src/domain_bundle_proposer.rs b/domains/client/domain-operator/src/domain_bundle_proposer.rs index 642968f0577..3a06b641b2c 100644 --- a/domains/client/domain-operator/src/domain_bundle_proposer.rs +++ b/domains/client/domain-operator/src/domain_bundle_proposer.rs @@ -1,6 +1,6 @@ use crate::ExecutionReceiptFor; use domain_runtime_primitives::CheckExtrinsicsValidityError; -use futures::{select, FutureExt}; +use futures::{FutureExt, select}; use parity_scale_codec::Encode; use sc_client_api::{AuxStore, BlockBackend}; use sc_transaction_pool_api::InPoolTransaction; @@ -13,8 +13,8 @@ use sp_domains::{ ProofOfElection, }; use sp_messenger::MessengerApi; -use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor, One, Zero}; use sp_runtime::Percent; +use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor, One, Zero}; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; use sp_weights::Weight; use std::collections::HashSet; @@ -343,7 +343,9 @@ where parent_hash, )? { - tracing::warn!("Unexpected error when validating all the extrinsics at once: {transaction_validity_error:?}"); + tracing::warn!( + "Unexpected error when validating all the extrinsics at once: {transaction_validity_error:?}" + ); // Truncate to remove the invalid extrinsic (and any extrinsic after it), so only // the valid exrinsic will be used to construct bundle. diff --git a/domains/client/domain-operator/src/domain_worker.rs b/domains/client/domain-operator/src/domain_worker.rs index 12c2f225750..81c52765c66 100644 --- a/domains/client/domain-operator/src/domain_worker.rs +++ b/domains/client/domain-operator/src/domain_worker.rs @@ -29,8 +29,8 @@ use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder; use sp_blockchain::{HeaderBackend, HeaderMetadata}; -use sp_core::traits::{CodeExecutor, SpawnEssentialNamed}; use sp_core::H256; +use sp_core::traits::{CodeExecutor, SpawnEssentialNamed}; use sp_domains::core_api::DomainCoreApi; use sp_domains::{BundleProducerElectionApi, DomainsApi, OpaqueBundle, OperatorId}; use sp_domains_fraud_proof::FraudProofApi; @@ -38,11 +38,11 @@ use sp_messenger::MessengerApi; use sp_mmr_primitives::MmrApi; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; -use std::pin::{pin, Pin}; +use std::pin::{Pin, pin}; use std::sync::Arc; use std::task::{Context, Poll}; use subspace_runtime_primitives::{Balance, BlockHashFor, HeaderFor}; -use tracing::{info, Instrument}; +use tracing::{Instrument, info}; pub type OpaqueBundleFor = OpaqueBundle, BlockHashFor, HeaderFor, Balance>; @@ -214,12 +214,12 @@ pub(super) async fn start_worker< .process_bundles((block_info.hash, block_info.number, block_info.is_new_best)) .instrument(span.clone()) .await - { - tracing::error!(?error, "Failed to process consensus block"); - // Bring down the service as bundles processor is an essential task. - // TODO: more graceful shutdown. - break; - } + { + tracing::error!(?error, "Failed to process consensus block"); + // Bring down the service as bundles processor is an essential task. + // TODO: more graceful shutdown. + break; + } } } } diff --git a/domains/client/domain-operator/src/fraud_proof.rs b/domains/client/domain-operator/src/fraud_proof.rs index d8bbba5fab6..b68ef60b67e 100644 --- a/domains/client/domain-operator/src/fraud_proof.rs +++ b/domains/client/domain-operator/src/fraud_proof.rs @@ -1,21 +1,22 @@ -use crate::aux_schema::BundleMismatchType; use crate::ExecutionReceiptFor; +use crate::aux_schema::BundleMismatchType; use domain_block_builder::BlockBuilder; -use domain_runtime_primitives::opaque::AccountId; use domain_runtime_primitives::CheckExtrinsicsValidityError; +use domain_runtime_primitives::opaque::AccountId; use parity_scale_codec::{Decode, Encode}; use sc_client_api::{AuxStore, BlockBackend, ExecutorProvider, ProofProvider}; use sc_domains::FPStorageKeyProvider; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::HeaderBackend; -use sp_core::traits::CodeExecutor; use sp_core::H256; +use sp_core::traits::CodeExecutor; use sp_domain_digests::AsPredigest; use sp_domains::core_api::DomainCoreApi; use sp_domains::proof_provider_and_verifier::StorageProofProvider; use sp_domains::{ DomainId, DomainsApi, ExtrinsicDigest, HeaderHashingFor, InvalidBundleType, RuntimeId, }; +use sp_domains_fraud_proof::FraudProofApi; use sp_domains_fraud_proof::execution_prover::ExecutionProver; use sp_domains_fraud_proof::fraud_proof::{ ApplyExtrinsicMismatch, DomainRuntimeCodeAt, ExecutionPhase, FinalizeBlockMismatch, FraudProof, @@ -24,7 +25,6 @@ use sp_domains_fraud_proof::fraud_proof::{ InvalidTransfersProof, MmrRootProof, ValidBundleDigest, ValidBundleProof, }; use sp_domains_fraud_proof::storage_proof::{self, *}; -use sp_domains_fraud_proof::FraudProofApi; use sp_messenger::MessengerApi; use sp_mmr_primitives::MmrApi; use sp_runtime::generic::BlockId; @@ -45,9 +45,7 @@ pub enum TraceDiffType { /// Error type for fraud proof generation. #[derive(Debug, thiserror::Error)] pub enum FraudProofError { - #[error( - "Out of bounds extrinsic index for creating the fraud proof, got: {index}, max: {max}" - )] + #[error("Out of bounds extrinsic index for creating the fraud proof, got: {index}, max: {max}")] OutOfBoundsExtrinsicIndex { index: usize, max: usize }, #[error(transparent)] Blockchain(#[from] sp_blockchain::Error), diff --git a/domains/client/domain-operator/src/lib.rs b/domains/client/domain-operator/src/lib.rs index c87d0895da4..5bfc6c9e093 100644 --- a/domains/client/domain-operator/src/lib.rs +++ b/domains/client/domain-operator/src/lib.rs @@ -83,18 +83,18 @@ mod tests; mod utils; pub use self::aux_schema::load_execution_receipt; -pub use self::fetch_domain_bootstrap_info::{fetch_domain_bootstrap_info, BootstrapResult}; +pub use self::fetch_domain_bootstrap_info::{BootstrapResult, fetch_domain_bootstrap_info}; pub use self::operator::Operator; pub use self::utils::{DomainBlockImportNotification, OperatorSlotInfo}; pub use domain_worker::OpaqueBundleFor; -use futures::channel::mpsc; use futures::Stream; +use futures::channel::mpsc; use sc_client_api::{AuxStore, BlockImportNotification}; use sc_consensus::BoxBlockImport; use sc_network::service::traits::NetworkService; +use sc_network_sync::SyncingService; use sc_network_sync::block_relay_protocol::BlockDownloader; use sc_network_sync::service::network::NetworkServiceHandle; -use sc_network_sync::SyncingService; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::TracingUnboundedSender; use snap_sync::ConsensusChainSyncParams; @@ -104,11 +104,11 @@ use sp_consensus_slots::Slot; use sp_domain_digests::AsPredigest; use sp_domains::{Bundle, DomainId, ExecutionReceiptFor as ExecutionReceipt, OperatorId}; use sp_keystore::KeystorePtr; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use sp_runtime::DigestItem; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use std::marker::PhantomData; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use subspace_core_primitives::pot::PotOutput; use subspace_runtime_primitives::{Balance, BlockHashFor, ExtrinsicFor, HeaderFor}; diff --git a/domains/client/domain-operator/src/operator.rs b/domains/client/domain-operator/src/operator.rs index ba16de8112a..472eae2f02f 100644 --- a/domains/client/domain-operator/src/operator.rs +++ b/domains/client/domain-operator/src/operator.rs @@ -1,11 +1,11 @@ use crate::bundle_processor::BundleProcessor; use crate::domain_block_processor::{DomainBlockProcessor, ReceiptsChecker}; use crate::domain_bundle_producer::{ - uses_default_bundle_producer_params, BundleProducer, DomainBundleProducer, TestBundleProducer, + BundleProducer, DomainBundleProducer, TestBundleProducer, uses_default_bundle_producer_params, }; use crate::domain_bundle_proposer::DomainBundleProposer; use crate::fraud_proof::FraudProofGenerator; -use crate::snap_sync::{snap_sync, SyncParams}; +use crate::snap_sync::{SyncParams, snap_sync}; use crate::{NewSlotNotification, OperatorParams}; use futures::channel::mpsc; use futures::future::pending; @@ -18,8 +18,8 @@ use sc_consensus::BlockImport; use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::{HeaderBackend, HeaderMetadata}; -use sp_core::traits::{CodeExecutor, SpawnEssentialNamed}; use sp_core::H256; +use sp_core::traits::{CodeExecutor, SpawnEssentialNamed}; use sp_domains::core_api::DomainCoreApi; use sp_domains::{BundleProducerElectionApi, DomainsApi}; use sp_domains_fraud_proof::FraudProofApi; diff --git a/domains/client/domain-operator/src/snap_sync.rs b/domains/client/domain-operator/src/snap_sync.rs index d1de648f974..ced4023574e 100644 --- a/domains/client/domain-operator/src/snap_sync.rs +++ b/domains/client/domain-operator/src/snap_sync.rs @@ -9,21 +9,21 @@ use sc_network::PeerId; use sc_network_common::sync::message::{ BlockAttributes, BlockData, BlockRequest, Direction, FromBlock, }; +use sc_network_sync::SyncingService; use sc_network_sync::block_relay_protocol::BlockDownloader; use sc_network_sync::service::network::NetworkServiceHandle; -use sc_network_sync::SyncingService; use sc_subspace_sync_common::snap_sync_engine::SnapSyncingEngine; use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; use sp_domains::ExecutionReceiptFor; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Header, NumberFor}; use std::collections::HashSet; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::sync::broadcast; use tokio::time::sleep; -use tracing::{debug, error, trace, Instrument}; +use tracing::{Instrument, debug, error, trace}; /// Notification with number of the block that is about to be imported and acknowledgement sender /// that pauses block production until the previous block is acknowledged. diff --git a/domains/client/domain-operator/src/tests.rs b/domains/client/domain-operator/src/tests.rs index b029518fe99..87a63031bba 100644 --- a/domains/client/domain-operator/src/tests.rs +++ b/domains/client/domain-operator/src/tests.rs @@ -1,21 +1,21 @@ +use crate::OperatorSlotInfo; use crate::aux_schema::BundleMismatchType; use crate::domain_block_processor::{DomainBlockProcessor, PendingConsensusBlocks}; use crate::domain_bundle_producer::{BundleProducer, TestBundleProducer}; use crate::domain_bundle_proposer::DomainBundleProposer; use crate::fraud_proof::{FraudProofGenerator, TraceDiffType}; use crate::tests::TxPoolError::InvalidTransaction as TxPoolInvalidTransaction; -use crate::OperatorSlotInfo; use cross_domain_message_gossip::get_channel_state; use domain_block_builder::BlockBuilderApi; use domain_runtime_primitives::opaque::Block as DomainBlock; use domain_runtime_primitives::{AccountId20Converter, AccountIdConverter, Hash}; use domain_test_primitives::{OnchainStateApi, TimestampApi}; +use domain_test_service::EcdsaKeyring::{self, Alice, Bob, Charlie, Dave, Eve}; +use domain_test_service::Sr25519Keyring::{self, Alice as Sr25519Alice, Ferdie}; use domain_test_service::evm_domain_test_runtime::{ Header, Runtime as TestRuntime, RuntimeCall, UncheckedExtrinsic as EvmUncheckedExtrinsic, }; -use domain_test_service::EcdsaKeyring::{self, Alice, Bob, Charlie, Dave, Eve}; -use domain_test_service::Sr25519Keyring::{self, Alice as Sr25519Alice, Ferdie}; -use domain_test_service::{EvmDomainNode, AUTO_ID_DOMAIN_ID, EVM_DOMAIN_ID}; +use domain_test_service::{AUTO_ID_DOMAIN_ID, EVM_DOMAIN_ID, EvmDomainNode}; use ethereum::TransactionV2 as EthereumTransaction; use fp_rpc::EthereumRuntimeRPCApi; use futures::StreamExt; @@ -25,34 +25,34 @@ use parity_scale_codec::{Decode, Encode}; use sc_client_api::{Backend, BlockBackend, BlockchainEvents, HeaderBackend}; use sc_domains::generate_mmr_proof; use sc_service::{BasePath, Role}; -use sc_transaction_pool_api::error::Error as TxPoolError; use sc_transaction_pool_api::TransactionPool; +use sc_transaction_pool_api::error::Error as TxPoolError; use sc_utils::mpsc::tracing_unbounded; use sp_api::{ApiExt, Core, ProvideRuntimeApi, StorageProof}; use sp_blockchain::ApplyExtrinsicFailed; use sp_consensus::SyncOracle; use sp_core::storage::StateVersion; use sp_core::traits::{FetchRuntimeCode, SpawnEssentialNamed}; -use sp_core::{Pair, H160, H256, U256}; +use sp_core::{H160, H256, Pair, U256}; use sp_domain_digests::AsPredigest; use sp_domains::core_api::DomainCoreApi; use sp_domains::merkle_tree::MerkleTree; use sp_domains::test_ethereum::{ - generate_evm_account_list, generate_evm_domain_call, generate_legacy_tx, EvmAccountList, + EvmAccountList, generate_evm_account_list, generate_evm_domain_call, generate_legacy_tx, }; -use sp_domains::test_ethereum_tx::{address_build, contract_address, AccountInfo}; +use sp_domains::test_ethereum_tx::{AccountInfo, address_build, contract_address}; use sp_domains::{ BlockFees, Bundle, BundleValidity, ChainId, ChannelId, DomainsApi, HeaderHashingFor, InboxedBundle, InvalidBundleType, PermissionedActionAllowedBy, Transfers, }; +use sp_domains_fraud_proof::InvalidTransactionCode; use sp_domains_fraud_proof::fraud_proof::{ ApplyExtrinsicMismatch, ExecutionPhase, FinalizeBlockMismatch, FraudProofVariant, InvalidBlockFeesProof, InvalidBundlesProofData, InvalidDomainBlockHashProof, InvalidExtrinsicsRootProof, InvalidTransfersProof, }; -use sp_domains_fraud_proof::InvalidTransactionCode; -use sp_messenger::messages::{CrossDomainMessage, Proof}; use sp_messenger::MessengerApi; +use sp_messenger::messages::{CrossDomainMessage, Proof}; use sp_mmr_primitives::{EncodableOpaqueLeaf, LeafProof as MmrProof}; use sp_runtime::generic::{BlockId, DigestItem}; use sp_runtime::traits::{BlakeTwo256, Convert, Hash as HashT, Header as HeaderT, Zero}; @@ -72,10 +72,10 @@ use std::time::Duration; use subspace_core_primitives::pot::PotOutput; use subspace_runtime_primitives::opaque::Block as CBlock; use subspace_runtime_primitives::{Balance, BlockHashFor, HeaderFor, SSC}; -use subspace_test_primitives::{OnchainStateApi as _, DOMAINS_BLOCK_PRUNING_DEPTH}; +use subspace_test_primitives::{DOMAINS_BLOCK_PRUNING_DEPTH, OnchainStateApi as _}; use subspace_test_runtime::Runtime; use subspace_test_service::{ - produce_block_with, produce_blocks, produce_blocks_until, MockConsensusNode, + MockConsensusNode, produce_block_with, produce_blocks, produce_blocks_until, }; use tempfile::TempDir; use tracing::{error, info}; @@ -2436,9 +2436,11 @@ async fn test_bad_fraud_proof_is_rejected() { let valid_receipt_hash = valid_receipt.hash::(); assert_eq!(valid_receipt.execution_trace.len(), 5); - let mut fraud_proofs = vec![fraud_proof_generator - .generate_valid_bundle_proof(EVM_DOMAIN_ID, &valid_receipt, 0, valid_receipt_hash) - .unwrap()]; + let mut fraud_proofs = vec![ + fraud_proof_generator + .generate_valid_bundle_proof(EVM_DOMAIN_ID, &valid_receipt, 0, valid_receipt_hash) + .unwrap(), + ]; fraud_proofs.push( fraud_proof_generator @@ -2597,9 +2599,11 @@ async fn test_bad_invalid_state_transition_proof_is_rejected() { ); assert!(result_execution_phase.is_ok()); - assert!(result_execution_phase - .as_ref() - .is_ok_and(|maybe_execution_phase| maybe_execution_phase.is_some())); + assert!( + result_execution_phase + .as_ref() + .is_ok_and(|maybe_execution_phase| maybe_execution_phase.is_some()) + ); let execution_phase = result_execution_phase .expect("already checked for error above; qed") @@ -2725,8 +2729,8 @@ async fn test_short_trace_for_inherent_apply_extrinsic_proof_creation_and_verifi } #[tokio::test(flavor = "multi_thread")] -async fn test_short_trace_for_normal_ext_apply_extrinsic_proof_creation_and_verification_should_work( -) { +async fn test_short_trace_for_normal_ext_apply_extrinsic_proof_creation_and_verification_should_work() + { test_invalid_state_transition_proof_creation_and_verification(TraceDiffType::Shorter, 3).await } @@ -3029,10 +3033,11 @@ async fn test_true_invalid_bundles_inherent_extrinsic_proof_creation_and_verific // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - return true; - } + && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -3138,10 +3143,11 @@ async fn test_false_invalid_bundles_inherent_extrinsic_proof_creation_and_verifi // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type { - assert!(!proof.is_good_invalid_fraud_proof); - return true; - } + && let InvalidBundleType::InherentExtrinsic(_) = proof.invalid_bundle_type + { + assert!(!proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -3276,10 +3282,11 @@ async fn test_true_invalid_bundles_undecodeable_tx_proof_creation_and_verificati // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - return true; - } + && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -3385,10 +3392,11 @@ async fn test_false_invalid_bundles_undecodeable_tx_proof_creation_and_verificat // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type { - assert!(!proof.is_good_invalid_fraud_proof); - return true; - } + && let InvalidBundleType::UndecodableTx(_) = proof.invalid_bundle_type + { + assert!(!proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -3534,11 +3542,12 @@ async fn test_true_invalid_bundles_illegal_xdm_proof_creation_and_verification() // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - assert_eq!(extrinsic_index, 0); - return true; - } + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + assert_eq!(extrinsic_index, 0); + return true; + } false }); @@ -3695,11 +3704,12 @@ async fn test_true_invalid_bundles_illegal_extrinsic_proof_creation_and_verifica // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - assert_eq!(extrinsic_index, 2); - return true; - } + && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + assert_eq!(extrinsic_index, 2); + return true; + } false }); @@ -3824,11 +3834,12 @@ async fn test_false_invalid_bundles_illegal_extrinsic_proof_creation_and_verific // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type { - assert!(!proof.is_good_invalid_fraud_proof); - assert_eq!(extrinsic_index, 1); - return true; - } + && let InvalidBundleType::IllegalTx(extrinsic_index) = proof.invalid_bundle_type + { + assert!(!proof.is_good_invalid_fraud_proof); + assert_eq!(extrinsic_index, 1); + return true; + } false }); @@ -3941,10 +3952,11 @@ async fn test_true_invalid_bundle_weight_proof_creation_and_verification() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - return true; - } + && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -4048,10 +4060,11 @@ async fn test_false_invalid_bundle_weight_proof_creation_and_verification() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type { - assert!(!proof.is_good_invalid_fraud_proof); - return true; - } + && InvalidBundleType::InvalidBundleWeight == proof.invalid_bundle_type + { + assert!(!proof.is_good_invalid_fraud_proof); + return true; + } false }); @@ -4156,10 +4169,11 @@ async fn test_false_invalid_bundles_non_exist_extrinsic_proof_creation_and_verif // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundlesProofData::Bundle(_) = proof.proof_data { - assert_eq!(fp.targeted_bad_receipt_hash(), bad_receipt_hash); - return true; - } + && let InvalidBundlesProofData::Bundle(_) = proof.proof_data + { + assert_eq!(fp.targeted_bad_receipt_hash(), bad_receipt_hash); + return true; + } false }); @@ -4824,9 +4838,11 @@ async fn test_valid_bundle_proof_generation_and_verification() { ) .await .unwrap(); - assert!(ferdie - .does_receipt_exist(bad_receipt.hash::()) - .unwrap()); + assert!( + ferdie + .does_receipt_exist(bad_receipt.hash::()) + .unwrap() + ); // When the domain node operator processes the primary block that contains `bad_submit_bundle_tx`, // it will generate and submit a fraud proof @@ -4842,36 +4858,39 @@ async fn test_valid_bundle_proof_generation_and_verification() { if let subspace_test_runtime::RuntimeCall::Domains( pallet_domains::Call::submit_fraud_proof { fraud_proof }, ) = ext.function - && let FraudProofVariant::ValidBundle(ref proof) = fraud_proof.proof { - // The fraud proof is targetting the `bad_receipt` - assert_eq!( - fraud_proof.bad_receipt_hash, - bad_receipt.hash::>() - ); + && let FraudProofVariant::ValidBundle(ref proof) = fraud_proof.proof + { + // The fraud proof is targetting the `bad_receipt` + assert_eq!( + fraud_proof.bad_receipt_hash, + bad_receipt.hash::>() + ); - // If the fraud proof target a non-exist receipt then it is invalid - let mut bad_fraud_proof = fraud_proof.clone(); - bad_fraud_proof.bad_receipt_hash = H256::random(); - let ext = proof_to_tx(&ferdie, bad_fraud_proof); - assert!(ferdie.submit_transaction(ext).await.is_err()); + // If the fraud proof target a non-exist receipt then it is invalid + let mut bad_fraud_proof = fraud_proof.clone(); + bad_fraud_proof.bad_receipt_hash = H256::random(); + let ext = proof_to_tx(&ferdie, bad_fraud_proof); + assert!(ferdie.submit_transaction(ext).await.is_err()); - // If the fraud proof point to non-exist bundle then it is invalid - let (mut bad_fraud_proof, mut bad_proof) = (fraud_proof.clone(), proof.clone()); - bad_proof.bundle_with_proof.bundle_index = u32::MAX; - bad_fraud_proof.proof = FraudProofVariant::ValidBundle(bad_proof); - let ext = proof_to_tx(&ferdie, bad_fraud_proof); - assert!(ferdie.submit_transaction(ext).await.is_err()); + // If the fraud proof point to non-exist bundle then it is invalid + let (mut bad_fraud_proof, mut bad_proof) = (fraud_proof.clone(), proof.clone()); + bad_proof.bundle_with_proof.bundle_index = u32::MAX; + bad_fraud_proof.proof = FraudProofVariant::ValidBundle(bad_proof); + let ext = proof_to_tx(&ferdie, bad_fraud_proof); + assert!(ferdie.submit_transaction(ext).await.is_err()); - break; - } + break; + } } // Produce a consensus block that contains the fraud proof, the fraud proof wil be verified // and executed, and prune the bad receipt from the block tree ferdie.produce_blocks(1).await.unwrap(); - assert!(!ferdie - .does_receipt_exist(bad_receipt.hash::()) - .unwrap()); + assert!( + !ferdie + .does_receipt_exist(bad_receipt.hash::()) + .unwrap() + ); } // TODO: Add a new test which simulates a situation that an executor produces a fraud proof @@ -5990,9 +6009,10 @@ async fn test_unordered_cross_domains_message_should_work() { if i % 3 == 0 { msg_buffer.push_back(xdm); if let Some(xdm) = msg_buffer.pop_front() - && i % 2 == 0 { - evm_domain_tx_pool_sink.unbounded_send(xdm).unwrap(); - } + && i % 2 == 0 + { + evm_domain_tx_pool_sink.unbounded_send(xdm).unwrap(); + } } else { evm_domain_tx_pool_sink.unbounded_send(xdm).unwrap(); } @@ -6512,9 +6532,11 @@ async fn test_bad_receipt_chain() { let runtime_api = ferdie.client.runtime_api(); for receipt_hash in &bad_receipt_descendants { assert!(ferdie.does_receipt_exist(*receipt_hash).unwrap()); - assert!(runtime_api - .is_bad_er_pending_to_prune(ferdie_best_hash, EVM_DOMAIN_ID, *receipt_hash) - .unwrap()); + assert!( + runtime_api + .is_bad_er_pending_to_prune(ferdie_best_hash, EVM_DOMAIN_ID, *receipt_hash) + .unwrap() + ); } // There should be a receipt gap @@ -7138,11 +7160,12 @@ async fn test_xdm_false_invalid_fraud_proof() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { - assert!(!proof.is_good_invalid_fraud_proof); - assert_eq!(extrinsic_index, 0); - return true; - } + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type + { + assert!(!proof.is_good_invalid_fraud_proof); + assert_eq!(extrinsic_index, 0); + return true; + } false }); @@ -7337,11 +7360,12 @@ async fn test_stale_fork_xdm_true_invalid_fraud_proof() { // Wait for the fraud proof that targets the bad ER let wait_for_fraud_proof_fut = ferdie.wait_for_fraud_proof(move |fp| { if let FraudProofVariant::InvalidBundles(proof) = &fp.proof - && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type { - assert!(proof.is_good_invalid_fraud_proof); - assert_eq!(extrinsic_index, 0); - return true; - } + && let InvalidBundleType::InvalidXDM(extrinsic_index) = proof.invalid_bundle_type + { + assert!(proof.is_good_invalid_fraud_proof); + assert_eq!(extrinsic_index, 0); + return true; + } false }); @@ -7857,9 +7881,11 @@ async fn test_xdm_transfer_below_existential_deposit() { .unwrap(); if channel_nonce.relay_response_msg_nonce == Some(U256::from(0)) { let post_ferdie_free_balance = ferdie.free_balance(ferdie.key.to_account_id()); - assert!(alice - .free_balance(EcdsaKeyring::One.to_account_id()) - .is_zero()); + assert!( + alice + .free_balance(EcdsaKeyring::One.to_account_id()) + .is_zero() + ); assert_eq!(post_ferdie_free_balance, pre_ferdie_free_balance); true } else { diff --git a/domains/client/eth-service/src/provider.rs b/domains/client/eth-service/src/provider.rs index c3833f99e29..29060bdf38b 100644 --- a/domains/client/eth-service/src/provider.rs +++ b/domains/client/eth-service/src/provider.rs @@ -1,12 +1,12 @@ -use crate::rpc::{create_eth_rpc, EthDeps}; +use crate::rpc::{EthDeps, create_eth_rpc}; use crate::service::{ - new_frontier_partial, spawn_frontier_tasks, EthConfiguration, FrontierPartialComponents, + EthConfiguration, FrontierPartialComponents, new_frontier_partial, spawn_frontier_tasks, }; use clap::Parser; use domain_runtime_primitives::{Balance, Nonce}; +use domain_service::FullClient; use domain_service::providers::{BlockImportProvider, DefaultProvider, RpcProvider}; use domain_service::rpc::FullDeps; -use domain_service::FullClient; use fc_consensus::FrontierBlockImport; use fc_rpc::EthConfig; use fc_storage::StorageOverrideHandler; @@ -23,8 +23,8 @@ use serde::de::DeserializeOwned; use sp_api::{ApiExt, CallApiAt, ConstructRuntimeApi, Core, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use sp_core::traits::SpawnEssentialNamed; use sp_core::H256; +use sp_core::traits::SpawnEssentialNamed; use sp_inherents::CreateInherentDataProviders; use sp_runtime::traits::Block as BlockT; use std::env; diff --git a/domains/client/eth-service/src/service.rs b/domains/client/eth-service/src/service.rs index c4d0f85c431..abdca4d0573 100644 --- a/domains/client/eth-service/src/service.rs +++ b/domains/client/eth-service/src/service.rs @@ -1,9 +1,9 @@ -use fc_mapping_sync::kv::MappingSyncWorker; use fc_mapping_sync::SyncStrategy; +use fc_mapping_sync::kv::MappingSyncWorker; use fc_rpc::EthTask; pub use fc_rpc_core::types::{FeeHistoryCache, FeeHistoryCacheLimit, FilterPool}; use fc_storage::StorageOverride; -use futures::{future, StreamExt}; +use futures::{StreamExt, future}; use sc_client_api::{BlockchainEvents, StorageProvider}; use sc_network_sync::SyncingService; use sc_service::error::Error as ServiceError; diff --git a/domains/client/relayer/src/lib.rs b/domains/client/relayer/src/lib.rs index cca75a366ff..a6761a0b868 100644 --- a/domains/client/relayer/src/lib.rs +++ b/domains/client/relayer/src/lib.rs @@ -7,12 +7,12 @@ mod aux_schema; pub mod worker; use crate::aux_schema::{ - get_last_processed_nonces, set_channel_inbox_response_processed_state, - set_channel_outbox_processed_state, ChannelProcessedState, + ChannelProcessedState, get_last_processed_nonces, set_channel_inbox_response_processed_state, + set_channel_outbox_processed_state, }; use async_channel::TrySendError; use cross_domain_message_gossip::{ - get_channel_state, ChannelDetail, Message as GossipMessage, MessageData as GossipMessageData, + ChannelDetail, Message as GossipMessage, MessageData as GossipMessageData, get_channel_state, }; use parity_scale_codec::{Codec, Encode}; use rand::seq::SliceRandom; @@ -27,8 +27,8 @@ use sp_messenger::messages::{ }; use sp_messenger::{MessengerApi, RelayerApi}; use sp_mmr_primitives::MmrApi; -use sp_runtime::traits::{Block as BlockT, CheckedSub, Header as HeaderT, NumberFor, One}; use sp_runtime::ArithmeticError; +use sp_runtime::traits::{Block as BlockT, CheckedSub, Header as HeaderT, NumberFor, One}; use sp_subspace_mmr::ConsensusChainMmrLeafProof; use std::cmp::max; use std::marker::PhantomData; diff --git a/domains/client/relayer/src/worker.rs b/domains/client/relayer/src/worker.rs index db88c8cb599..eead49727e1 100644 --- a/domains/client/relayer/src/worker.rs +++ b/domains/client/relayer/src/worker.rs @@ -8,8 +8,8 @@ use sp_domains::{DomainId, DomainsApi}; use sp_messenger::messages::ChainId; use sp_messenger::{MessengerApi, RelayerApi}; use sp_mmr_primitives::MmrApi; -use sp_runtime::traits::{CheckedSub, NumberFor, One, Zero}; use sp_runtime::SaturatedConversion; +use sp_runtime::traits::{CheckedSub, NumberFor, One, Zero}; use std::sync::Arc; pub async fn gossip_channel_updates( diff --git a/domains/pallets/auto-id/src/lib.rs b/domains/pallets/auto-id/src/lib.rs index 4ce52451c79..3ea71973a8d 100644 --- a/domains/pallets/auto-id/src/lib.rs +++ b/domains/pallets/auto-id/src/lib.rs @@ -39,7 +39,7 @@ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_auto_id::auto_id_runtime_interface::{decode_tbs_certificate, verify_signature}; use sp_auto_id::{DerVec, SignatureVerificationRequest, Validity}; -use sp_core::{blake2_256, H256, U256}; +use sp_core::{H256, U256, blake2_256}; #[cfg(feature = "std")] use std::collections::BTreeSet; use subspace_runtime_primitives::Moment; diff --git a/domains/pallets/auto-id/src/tests.rs b/domains/pallets/auto-id/src/tests.rs index 7bbabec1872..f1e8a68c3ba 100644 --- a/domains/pallets/auto-id/src/tests.rs +++ b/domains/pallets/auto-id/src/tests.rs @@ -14,9 +14,9 @@ use ring::rand::SystemRandom; use ring::signature::RsaKeyPair; use sp_auto_id::{DerVec, Validity}; use sp_core::bytes::to_hex; -use sp_core::{blake2_256, H256, U256}; -use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; +use sp_core::{H256, U256, blake2_256}; use sp_runtime::BuildStorage; +use sp_runtime::traits::{BlakeTwo256, IdentityLookup}; use std::sync::Arc; use subspace_runtime_primitives::{DomainEventSegmentSize, Moment}; use x509_parser::der_parser::asn1_rs::ToDer; @@ -395,9 +395,11 @@ fn test_self_revoke_certificate() { ) .unwrap(); let auto_id = AutoIds::::get(auto_id_identifier).unwrap(); - assert!(CertificateRevocationList::::get(auto_id_identifier) - .unwrap() - .contains(&auto_id.certificate.serial())); + assert!( + CertificateRevocationList::::get(auto_id_identifier) + .unwrap() + .contains(&auto_id.certificate.serial()) + ); assert_eq!(auto_id.certificate.nonce(), U256::one()); @@ -458,9 +460,11 @@ fn test_revoke_leaf_certificate() { Pallet::::revoke_certificate(RawOrigin::Signed(1).into(), leaf_id, signature) .unwrap(); - assert!(CertificateRevocationList::::get(issuer_id) - .unwrap() - .contains(&leaf_auto_id.certificate.serial())); + assert!( + CertificateRevocationList::::get(issuer_id) + .unwrap() + .contains(&leaf_auto_id.certificate.serial()) + ); // revoking the same certificate again should fail let signing_data = CertificateAction { diff --git a/domains/pallets/block-fees/src/fees.rs b/domains/pallets/block-fees/src/fees.rs index 6ed2de1e580..68193f8d4b8 100644 --- a/domains/pallets/block-fees/src/fees.rs +++ b/domains/pallets/block-fees/src/fees.rs @@ -3,9 +3,9 @@ use frame_support::traits::fungible::Inspect; use frame_support::traits::tokens::WithdrawConsequence; use frame_support::traits::{Currency, ExistenceRequirement, Imbalance, WithdrawReasons}; use parity_scale_codec::Encode; +use sp_runtime::Saturating; use sp_runtime::traits::{DispatchInfoOf, PostDispatchInfoOf, Zero}; use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidityError}; -use sp_runtime::Saturating; use sp_std::marker::PhantomData; pub struct LiquidityInfo { diff --git a/domains/pallets/block-fees/src/lib.rs b/domains/pallets/block-fees/src/lib.rs index 6b045296786..288ea6963f5 100644 --- a/domains/pallets/block-fees/src/lib.rs +++ b/domains/pallets/block-fees/src/lib.rs @@ -33,7 +33,7 @@ mod pallet { use frame_system::pallet_prelude::*; use parity_scale_codec::{Codec, MaxEncodedLen}; use scale_info::TypeInfo; - use sp_block_fees::{InherentError, InherentType, INHERENT_IDENTIFIER}; + use sp_block_fees::{INHERENT_IDENTIFIER, InherentError, InherentType}; use sp_domains::{BlockFees, ChainId}; use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize, Saturating}; use sp_runtime::{FixedPointOperand, SaturatedConversion}; @@ -154,9 +154,10 @@ mod pallet { if let Call::set_next_consensus_chain_byte_fee { transaction_byte_fee, } = call - && transaction_byte_fee != &provided_transaction_byte_fee { - return Err(InherentError::IncorrectConsensusChainByteFee); - } + && transaction_byte_fee != &provided_transaction_byte_fee + { + return Err(InherentError::IncorrectConsensusChainByteFee); + } Ok(()) } diff --git a/domains/pallets/domain-check-weight/src/lib.rs b/domains/pallets/domain-check-weight/src/lib.rs index 3c1a25c77df..49dfd85f97a 100644 --- a/domains/pallets/domain-check-weight/src/lib.rs +++ b/domains/pallets/domain-check-weight/src/lib.rs @@ -21,6 +21,7 @@ use frame_system::limits::BlockWeights; use frame_system::{Config, ConsumedWeight}; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; +use sp_runtime::DispatchResult; use sp_runtime::traits::{ DispatchInfoOf, DispatchOriginOf, Dispatchable, PostDispatchInfoOf, TransactionExtension, ValidateResult, @@ -28,7 +29,6 @@ use sp_runtime::traits::{ use sp_runtime::transaction_validity::{ TransactionSource, TransactionValidity, TransactionValidityError, }; -use sp_runtime::DispatchResult; use sp_weights::Weight; /// Wrapper of [`frame_system::CheckWeight`] diff --git a/domains/pallets/domain-sudo/src/lib.rs b/domains/pallets/domain-sudo/src/lib.rs index f4a086faf45..da09e283348 100644 --- a/domains/pallets/domain-sudo/src/lib.rs +++ b/domains/pallets/domain-sudo/src/lib.rs @@ -31,7 +31,7 @@ mod pallet { use frame_support::traits::UnfilteredDispatchable; use frame_system::ensure_none; use frame_system::pallet_prelude::OriginFor; - use sp_domain_sudo::{InherentError, InherentType, IntoRuntimeCall, INHERENT_IDENTIFIER}; + use sp_domain_sudo::{INHERENT_IDENTIFIER, InherentError, InherentType, IntoRuntimeCall}; #[pallet::config] pub trait Config: frame_system::Config { @@ -119,9 +119,10 @@ mod pallet { if let Some(encoded_call) = inherent_data.maybe_call { let runtime_call = Box::new(T::IntoRuntimeCall::runtime_call(encoded_call)); if let Call::sudo { call } = call - && call != &runtime_call { - return Err(InherentError::IncorrectRuntimeCall); - } + && call != &runtime_call + { + return Err(InherentError::IncorrectRuntimeCall); + } } else { return Err(InherentError::MissingRuntimeCall); } diff --git a/domains/pallets/evm-tracker/src/check_nonce.rs b/domains/pallets/evm-tracker/src/check_nonce.rs index 9c79c937797..e664a554bee 100644 --- a/domains/pallets/evm-tracker/src/check_nonce.rs +++ b/domains/pallets/evm-tracker/src/check_nonce.rs @@ -4,19 +4,19 @@ use alloc::vec; use core::cmp::max; use core::fmt; use core::result::Result; +use frame_support::RuntimeDebugNoBound; use frame_support::dispatch::DispatchInfo; use frame_support::pallet_prelude::{ InvalidTransaction, TransactionLongevity, TransactionValidityError, TypeInfo, ValidTransaction, Weight, }; use frame_support::sp_runtime::traits::{DispatchInfoOf, One, TransactionExtension}; -use frame_support::RuntimeDebugNoBound; use parity_scale_codec::{Decode, Encode}; +use sp_runtime::DispatchResult; use sp_runtime::traits::{ AsSystemOriginSigner, Dispatchable, PostDispatchInfoOf, ValidateResult, Zero, }; use sp_runtime::transaction_validity::TransactionSource; -use sp_runtime::DispatchResult; #[cfg(feature = "std")] use std::vec; diff --git a/domains/pallets/evm-tracker/src/create_contract.rs b/domains/pallets/evm-tracker/src/create_contract.rs index 27730dcd3b1..addae1300b6 100644 --- a/domains/pallets/evm-tracker/src/create_contract.rs +++ b/domains/pallets/evm-tracker/src/create_contract.rs @@ -1,7 +1,7 @@ //! Contract creation allow list implementations use crate::traits::{AccountIdFor, MaybeIntoEthCall, MaybeIntoEvmCall}; -use domain_runtime_primitives::{EthereumAccountId, ERR_CONTRACT_CREATION_NOT_ALLOWED}; +use domain_runtime_primitives::{ERR_CONTRACT_CREATION_NOT_ALLOWED, EthereumAccountId}; use frame_support::pallet_prelude::{PhantomData, TypeInfo}; use frame_system::pallet_prelude::{OriginFor, RuntimeCallFor}; use pallet_ethereum::{Transaction as EthereumTransaction, TransactionAction}; @@ -17,7 +17,7 @@ use sp_runtime::transaction_validity::{ ValidTransaction, }; use sp_weights::Weight; -use subspace_runtime_primitives::utility::{nested_call_iter, MaybeNestedCall}; +use subspace_runtime_primitives::utility::{MaybeNestedCall, nested_call_iter}; /// Rejects contracts that can't be created under the current allow list. /// Returns false if the call is a contract call, and the account is *not* allowed to call it. diff --git a/domains/pallets/evm-tracker/src/lib.rs b/domains/pallets/evm-tracker/src/lib.rs index 00c8a8f5198..866a4887f22 100644 --- a/domains/pallets/evm-tracker/src/lib.rs +++ b/domains/pallets/evm-tracker/src/lib.rs @@ -38,7 +38,7 @@ mod pallet { use frame_system::pallet_prelude::*; use sp_core::U256; use sp_domains::PermissionedActionAllowedBy; - use sp_evm_tracker::{InherentError, InherentType, INHERENT_IDENTIFIER}; + use sp_evm_tracker::{INHERENT_IDENTIFIER, InherentError, InherentType}; #[pallet::config] pub trait Config: frame_system::Config {} diff --git a/domains/pallets/executive/src/lib.rs b/domains/pallets/executive/src/lib.rs index 270b984b069..27f5b7faf19 100644 --- a/domains/pallets/executive/src/lib.rs +++ b/domains/pallets/executive/src/lib.rs @@ -93,9 +93,9 @@ mod pallet { use frame_support::pallet_prelude::*; use frame_support::traits::fungible::Mutate; use frame_support::weights::WeightToFee; - use frame_system::pallet_prelude::*; use frame_system::SetCode; - use sp_executive::{InherentError, InherentType, INHERENT_IDENTIFIER}; + use frame_system::pallet_prelude::*; + use sp_executive::{INHERENT_IDENTIFIER, InherentError, InherentType}; #[pallet::config] pub trait Config: frame_system::Config { @@ -160,9 +160,10 @@ mod pallet { if let Some(provided_code) = inherent_data.maybe_code { if let Call::set_code { code } = call - && code != &provided_code { - return Err(InherentError::IncorrectRuntimeCode); - } + && code != &provided_code + { + return Err(InherentError::IncorrectRuntimeCode); + } } else { return Err(InherentError::MissingRuntimeCode); } @@ -208,18 +209,18 @@ pub struct Executive< ); impl< - ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst>, - Context: Default, - UnsignedValidator, - AllPalletsWithSystem: OnRuntimeUpgrade - + BeforeAllRuntimeMigrations - + OnInitialize> - + OnIdle> - + OnFinalize> - + OffchainWorker> - + OnPoll>, - COnRuntimeUpgrade: OnRuntimeUpgrade, - > ExecuteBlock> + ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst>, + Context: Default, + UnsignedValidator, + AllPalletsWithSystem: OnRuntimeUpgrade + + BeforeAllRuntimeMigrations + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker> + + OnPoll>, + COnRuntimeUpgrade: OnRuntimeUpgrade, +> ExecuteBlock> for Executive< ExecutiveConfig, Context, @@ -247,19 +248,18 @@ where } impl< - ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst>, - Context: Default, - UnsignedValidator, - AllPalletsWithSystem: OnRuntimeUpgrade - + BeforeAllRuntimeMigrations - + OnInitialize> - + OnIdle> - + OnFinalize> - + OffchainWorker> - + OnPoll>, - COnRuntimeUpgrade: OnRuntimeUpgrade, - > - Executive + ExecutiveConfig: Config + frame_system::Config + EnsureInherentsAreFirst>, + Context: Default, + UnsignedValidator, + AllPalletsWithSystem: OnRuntimeUpgrade + + BeforeAllRuntimeMigrations + + OnInitialize> + + OnIdle> + + OnFinalize> + + OffchainWorker> + + OnPoll>, + COnRuntimeUpgrade: OnRuntimeUpgrade, +> Executive where ExtrinsicOf: Checkable + Codec, CheckedOf, Context>: Applyable + GetDispatchInfo, diff --git a/domains/pallets/executive/src/mock.rs b/domains/pallets/executive/src/mock.rs index 05537ba1736..890a15512d7 100644 --- a/domains/pallets/executive/src/mock.rs +++ b/domains/pallets/executive/src/mock.rs @@ -11,8 +11,8 @@ use frame_support::weights::IdentityFee; use frame_support::{derive_impl, parameter_types}; use frame_system::mocking::MockUncheckedExtrinsic; use pallet_balances::AccountData; -use sp_runtime::transaction_validity::TransactionValidityError; use sp_runtime::BuildStorage; +use sp_runtime::transaction_validity::TransactionValidityError; use subspace_runtime_primitives::DomainEventSegmentSize; type Block = frame_system::mocking::MockBlock; diff --git a/domains/pallets/executive/src/tests.rs b/domains/pallets/executive/src/tests.rs index 65820d8ef06..48c782fb107 100644 --- a/domains/pallets/executive/src/tests.rs +++ b/domains/pallets/executive/src/tests.rs @@ -1,4 +1,4 @@ -use crate::mock::{new_test_ext, Executive, RuntimeOrigin}; +use crate::mock::{Executive, RuntimeOrigin, new_test_ext}; use frame_support::assert_ok; use parity_scale_codec::Encode; use sp_version::RuntimeVersion; diff --git a/domains/pallets/messenger/src/benchmarking.rs b/domains/pallets/messenger/src/benchmarking.rs index 886afb52bac..c2f0193d5ab 100644 --- a/domains/pallets/messenger/src/benchmarking.rs +++ b/domains/pallets/messenger/src/benchmarking.rs @@ -10,8 +10,8 @@ use alloc::vec; use alloc::vec::Vec; use frame_benchmarking::v2::*; use frame_support::assert_ok; -use frame_support::traits::fungible::Mutate; use frame_support::traits::Get; +use frame_support::traits::fungible::Mutate; use frame_system::RawOrigin; use sp_messenger::endpoint::{ CollectedFee, Endpoint, EndpointRequest, EndpointRequestWithCollectedFee, diff --git a/domains/pallets/messenger/src/extensions.rs b/domains/pallets/messenger/src/extensions.rs index 12f10ec0645..3be3dc85840 100644 --- a/domains/pallets/messenger/src/extensions.rs +++ b/domains/pallets/messenger/src/extensions.rs @@ -15,13 +15,14 @@ use crate::{ XDM_TRANSACTION_LONGEVITY, }; use core::cmp::Ordering; -use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight}; use frame_support::RuntimeDebugNoBound; +use frame_support::pallet_prelude::{PhantomData, TypeInfo, Weight}; use frame_system::pallet_prelude::RuntimeCallFor; use parity_scale_codec::{Decode, Encode}; use scale_info::prelude::fmt; -use sp_messenger::messages::{Message, Nonce, Proof}; use sp_messenger::MAX_FUTURE_ALLOWED_NONCES; +use sp_messenger::messages::{Message, Nonce, Proof}; +use sp_runtime::DispatchResult; use sp_runtime::traits::{ AsSystemOriginSigner, DispatchInfoOf, DispatchOriginOf, Dispatchable, Implication, PostDispatchInfoOf, TransactionExtension, ValidateResult, @@ -30,7 +31,6 @@ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidityError, ValidTransaction, ValidTransactionBuilder, }; -use sp_runtime::DispatchResult; use sp_subspace_mmr::MmrProofVerifier; /// Trait to convert Runtime call to possible Messenger call. diff --git a/domains/pallets/messenger/src/extensions/benchmarking_from_domains.rs b/domains/pallets/messenger/src/extensions/benchmarking_from_domains.rs index 4bd70e8f397..7c80094855a 100644 --- a/domains/pallets/messenger/src/extensions/benchmarking_from_domains.rs +++ b/domains/pallets/messenger/src/extensions/benchmarking_from_domains.rs @@ -1,6 +1,6 @@ //! Benchmarking for `pallet-messenger` extensions. -use crate::extensions::benchmarking_from_consensus::{set_channel_init_state, RelayMessage}; +use crate::extensions::benchmarking_from_consensus::{RelayMessage, set_channel_init_state}; use crate::{Config, Pallet as Messenger, ValidatedRelayMessage}; use frame_benchmarking::v2::*; use frame_support::dispatch::{DispatchInfo, PostDispatchInfo}; diff --git a/domains/pallets/messenger/src/fees.rs b/domains/pallets/messenger/src/fees.rs index e099c5f53c2..2d4af870f9c 100644 --- a/domains/pallets/messenger/src/fees.rs +++ b/domains/pallets/messenger/src/fees.rs @@ -7,9 +7,9 @@ use frame_support::traits::fungible::{Balanced, Mutate}; use frame_support::traits::tokens::{Fortitude, Precision, Preservation}; use frame_support::weights::WeightToFee; use sp_core::Get; +use sp_messenger::OnXDMRewards; use sp_messenger::endpoint::{CollectedFee, Endpoint}; use sp_messenger::messages::{ChainId, ChannelId, MessageId, Nonce}; -use sp_messenger::OnXDMRewards; use sp_runtime::traits::{CheckedAdd, CheckedMul, CheckedSub, Zero}; use sp_runtime::{DispatchError, DispatchResult, Saturating}; diff --git a/domains/pallets/messenger/src/lib.rs b/domains/pallets/messenger/src/lib.rs index bdc2b9558c5..588e6eccd53 100644 --- a/domains/pallets/messenger/src/lib.rs +++ b/domains/pallets/messenger/src/lib.rs @@ -44,12 +44,12 @@ use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_core::U256; use sp_domains::{DomainAllowlistUpdates, DomainId}; +use sp_messenger::MAX_FUTURE_ALLOWED_NONCES; use sp_messenger::messages::{ ChainId, Channel, ChannelId, ChannelState, CrossDomainMessage, Message, Nonce, }; -use sp_messenger::MAX_FUTURE_ALLOWED_NONCES; -use sp_runtime::traits::Hash; use sp_runtime::DispatchError; +use sp_runtime::traits::Hash; use subspace_runtime_primitives::CreateUnsigned; /// Transaction validity for a given validated XDM extrinsic. @@ -150,8 +150,8 @@ mod pallet { use crate::weights::WeightInfo; use crate::{ BalanceOf, ChainAllowlistUpdate, Channel, ChannelId, ChannelState, CloseChannelBy, - HoldIdentifier, Nonce, OutboxMessageResult, RawOrigin, StateRootOf, ValidatedRelayMessage, - STORAGE_VERSION, U256, + HoldIdentifier, Nonce, OutboxMessageResult, RawOrigin, STORAGE_VERSION, StateRootOf, U256, + ValidatedRelayMessage, }; #[cfg(not(feature = "std"))] use alloc::boxed::Box; @@ -179,8 +179,8 @@ mod pallet { RequestResponse, VersionedPayload, }; use sp_messenger::{ - ChannelNonce, DomainRegistration, InherentError, InherentType, NoteChainTransfer, - OnXDMRewards, StorageKeys, INHERENT_IDENTIFIER, + ChannelNonce, DomainRegistration, INHERENT_IDENTIFIER, InherentError, InherentType, + NoteChainTransfer, OnXDMRewards, StorageKeys, }; use sp_runtime::traits::Zero; use sp_runtime::{ArithmeticError, Perbill, Saturating}; @@ -195,7 +195,7 @@ mod pallet { type SelfChainId: Get; /// function to fetch endpoint response handler by Endpoint. fn get_endpoint_handler(endpoint: &Endpoint) - -> Option>>; + -> Option>>; /// Currency type pallet uses for fees and deposits. type Currency: Mutate + InspectHold @@ -217,11 +217,7 @@ mod pallet { /// Hash type of MMR type MmrHash: Parameter + Member + Default + Clone; /// MMR proof verifier - type MmrProofVerifier: MmrProofVerifier< - Self::MmrHash, - BlockNumberFor, - StateRootOf, - >; + type MmrProofVerifier: MmrProofVerifier, StateRootOf>; /// Storage key provider. type StorageKeys: StorageKeys; /// Domain owner provider. @@ -820,9 +816,10 @@ mod pallet { if let Some(provided_updates) = inherent_data.maybe_updates { if let Call::update_domain_allowlist { updates } = call - && updates != &provided_updates { - return Err(InherentError::IncorrectAllowlistUpdates); - } + && updates != &provided_updates + { + return Err(InherentError::IncorrectAllowlistUpdates); + } } else { return Err(InherentError::MissingAllowlistUpdates); } @@ -924,10 +921,10 @@ mod pallet { let message_count = OutboxMessageCount::::get((dst_chain_id, channel_id)); if let Some(channel) = Channels::::get(dst_chain_id, channel_id) && channel.state == ChannelState::Open - && message_count < channel.max_outgoing_messages - { - return Some(channel_id); - } + && message_count < channel.max_outgoing_messages + { + return Some(channel_id); + } next_channel_id = channel_id } diff --git a/domains/pallets/messenger/src/migrations.rs b/domains/pallets/messenger/src/migrations.rs index f10adb0b5cc..3a2d98afac2 100644 --- a/domains/pallets/messenger/src/migrations.rs +++ b/domains/pallets/messenger/src/migrations.rs @@ -2,5 +2,5 @@ mod v0_to_v1; mod v1_to_v2; pub use v0_to_v1::VersionCheckedMigrateDomainsV0ToV1; -pub(crate) use v1_to_v2::migrate_channels::{get_channel, get_channels_and_states}; pub use v1_to_v2::VersionCheckedMigrateDomainsV1ToV2; +pub(crate) use v1_to_v2::migrate_channels::{get_channel, get_channels_and_states}; diff --git a/domains/pallets/messenger/src/migrations/v1_to_v2.rs b/domains/pallets/messenger/src/migrations/v1_to_v2.rs index 383c6706689..bc466a6478a 100644 --- a/domains/pallets/messenger/src/migrations/v1_to_v2.rs +++ b/domains/pallets/messenger/src/migrations/v1_to_v2.rs @@ -11,7 +11,7 @@ use frame_support::migrations::VersionedMigration; use frame_support::pallet_prelude::{Decode, Encode, OptionQuery, TypeInfo}; use frame_support::traits::UncheckedOnRuntimeUpgrade; use frame_support::weights::Weight; -use frame_support::{storage_alias, Identity}; +use frame_support::{Identity, storage_alias}; use sp_domains::{ChainId, ChannelId}; use sp_messenger::messages::{Channel as ChannelV1, ChannelState, Nonce}; @@ -111,8 +111,8 @@ pub(crate) mod migrate_channels { }) } - pub(crate) fn get_channels_and_states( - ) -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> { + pub(crate) fn get_channels_and_states() + -> Vec<(ChainId, ChannelId, ChannelStateWithNonce)> { let keys: Vec<(ChainId, ChannelId)> = ChannelStorageV1::::iter_keys().collect(); keys.into_iter() .filter_map(|(chain_id, channel_id)| { @@ -138,7 +138,7 @@ pub(crate) mod migrate_channels { mod tests { use super::migrate_channels::Channels; use super::*; - use crate::mock::chain_a::{new_test_ext, Runtime}; + use crate::mock::chain_a::{Runtime, new_test_ext}; use frame_support::weights::RuntimeDbWeight; use sp_runtime::traits::Get; diff --git a/domains/pallets/messenger/src/mock.rs b/domains/pallets/messenger/src/mock.rs index 29fa705d9da..224a848ccf3 100644 --- a/domains/pallets/messenger/src/mock.rs +++ b/domains/pallets/messenger/src/mock.rs @@ -6,10 +6,10 @@ use sp_core::storage::StorageKey; use sp_domains::DomainId; use sp_messenger::endpoint::{EndpointHandler, EndpointRequest, EndpointResponse}; use sp_messenger::messages::ChainId; -use sp_runtime::traits::BlakeTwo256; use sp_runtime::DispatchResult; +use sp_runtime::traits::BlakeTwo256; use sp_state_machine::backend::Backend; -use sp_state_machine::{prove_read, InMemoryBackend}; +use sp_state_machine::{InMemoryBackend, prove_read}; use sp_trie::StorageProof; pub(crate) type Balance = u64; diff --git a/domains/pallets/messenger/src/tests.rs b/domains/pallets/messenger/src/tests.rs index 9eaa5aa9fdc..58f272f7a42 100644 --- a/domains/pallets/messenger/src/tests.rs +++ b/domains/pallets/messenger/src/tests.rs @@ -1,10 +1,10 @@ use crate::mock::chain_a::{ - new_test_ext as new_chain_a_ext, Messenger, Runtime, RuntimeEvent, RuntimeOrigin, System, - USER_ACCOUNT, + Messenger, Runtime, RuntimeEvent, RuntimeOrigin, System, USER_ACCOUNT, + new_test_ext as new_chain_a_ext, }; use crate::mock::{ - chain_a, chain_b, consensus_chain, storage_proof_of_inbox_message_responses, - storage_proof_of_outbox_messages, AccountId, Balance, TestExternalities, + AccountId, Balance, TestExternalities, chain_a, chain_b, consensus_chain, + storage_proof_of_inbox_message_responses, storage_proof_of_outbox_messages, }; use crate::pallet::OutboxMessageCount; use crate::{ @@ -18,8 +18,8 @@ use frame_support::{assert_err, assert_ok}; use pallet_transporter::Location; use sp_core::storage::StorageKey; use sp_core::{Blake2Hasher, H256}; -use sp_domains::proof_provider_and_verifier::{StorageProofVerifier, VerificationError}; use sp_domains::DomainAllowlistUpdates; +use sp_domains::proof_provider_and_verifier::{StorageProofVerifier, VerificationError}; use sp_messenger::endpoint::{Endpoint, EndpointPayload, EndpointRequest, Sender}; use sp_messenger::messages::{ BlockMessagesQuery, ChainId, ChannelOpenParamsV1, CrossDomainMessage, MessageWeightTag, @@ -877,11 +877,13 @@ fn initiate_transfer_on_chain(chain_a_ext: &mut TestExternalities) { channel_id: U256::zero(), nonce: U256::one(), })); - assert!(chain_a::Transporter::outgoing_transfers( - chain_b::SelfChainId::get(), - (U256::zero(), U256::one()), + assert!( + chain_a::Transporter::outgoing_transfers( + chain_b::SelfChainId::get(), + (U256::zero(), U256::one()), + ) + .is_some() ) - .is_some()) }) } @@ -902,11 +904,13 @@ fn verify_transfer_on_chain( message_id: (U256::zero(), U256::one()), }, )); - assert!(chain_a::Transporter::outgoing_transfers( - chain_b::SelfChainId::get(), - (U256::zero(), U256::one()), + assert!( + chain_a::Transporter::outgoing_transfers( + chain_b::SelfChainId::get(), + (U256::zero(), U256::one()), + ) + .is_none() ) - .is_none()) }); // chain a should have @@ -1036,11 +1040,13 @@ fn test_transport_funds_between_chains_if_dst_chain_disallows_after_message_is_s err: Error::::ChainNotAllowed.into(), }, )); - assert!(chain_a::Transporter::outgoing_transfers( - chain_b::SelfChainId::get(), - (U256::zero(), U256::one()), + assert!( + chain_a::Transporter::outgoing_transfers( + chain_b::SelfChainId::get(), + (U256::zero(), U256::one()), + ) + .is_none() ) - .is_none()) }); // chain_b should not have successful event from transporter diff --git a/domains/pallets/transporter/src/benchmarking.rs b/domains/pallets/transporter/src/benchmarking.rs index 6a3a8b10fba..316d38f4a1e 100644 --- a/domains/pallets/transporter/src/benchmarking.rs +++ b/domains/pallets/transporter/src/benchmarking.rs @@ -7,8 +7,8 @@ use frame_system::RawOrigin; use sp_messenger::endpoint::{ Endpoint, EndpointHandler as EndpointHandlerT, EndpointRequest, Sender, }; -use sp_runtime::traits::{Bounded, Convert}; use sp_runtime::DispatchError; +use sp_runtime::traits::{Bounded, Convert}; use sp_std::marker::PhantomData; #[cfg(test)] diff --git a/domains/pallets/transporter/src/lib.rs b/domains/pallets/transporter/src/lib.rs index 6d145237202..d39ce1d92e1 100644 --- a/domains/pallets/transporter/src/lib.rs +++ b/domains/pallets/transporter/src/lib.rs @@ -38,9 +38,9 @@ pub use pallet::*; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_domains::{DomainId, DomainsTransfersTracker, SkipBalanceChecks, Transfers}; +use sp_messenger::NoteChainTransfer; use sp_messenger::endpoint::EndpointResponse; use sp_messenger::messages::ChainId; -use sp_messenger::NoteChainTransfer; use sp_runtime::traits::{CheckedAdd, CheckedSub, Get}; use sp_std::vec; diff --git a/domains/pallets/transporter/src/tests.rs b/domains/pallets/transporter/src/tests.rs index 5b678c1ab3e..577150b1a19 100644 --- a/domains/pallets/transporter/src/tests.rs +++ b/domains/pallets/transporter/src/tests.rs @@ -1,6 +1,6 @@ use crate::mock::{ - new_test_ext, AccountId, Balance, Balances, MockAccountIdConverter, MockRuntime, RuntimeEvent, - RuntimeOrigin, SelfChainId, SelfEndpointId, System, Transporter, USER_ACCOUNT, + AccountId, Balance, Balances, MockAccountIdConverter, MockRuntime, RuntimeEvent, RuntimeOrigin, + SelfChainId, SelfEndpointId, System, Transporter, USER_ACCOUNT, new_test_ext, }; use crate::{EndpointHandler, Error, Location, Transfer}; use frame_support::dispatch::DispatchResult; diff --git a/domains/primitives/evm-tracker/src/lib.rs b/domains/primitives/evm-tracker/src/lib.rs index 25917a5e269..0513df7b84d 100644 --- a/domains/primitives/evm-tracker/src/lib.rs +++ b/domains/primitives/evm-tracker/src/lib.rs @@ -1,17 +1,17 @@ //! Inherents for EVM tracker #![cfg_attr(not(feature = "std"), no_std)] -use domain_runtime_primitives::{maximum_domain_block_weight, Balance, EthereumAccountId}; +use domain_runtime_primitives::{Balance, EthereumAccountId, maximum_domain_block_weight}; use frame_support::parameter_types; -use frame_support::sp_runtime::app_crypto::sp_core::U256; use frame_support::sp_runtime::Perbill; +use frame_support::sp_runtime::app_crypto::sp_core::U256; use parity_scale_codec::{Decode, Encode}; use sp_domains::PermissionedActionAllowedBy; #[cfg(feature = "std")] use sp_inherents::{Error, InherentData}; use sp_inherents::{InherentIdentifier, IsFatalError}; -use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND; use sp_weights::Weight; +use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND; /// Current approximation of the gas/s consumption considering /// EVM execution over compiled WASM (on 4.4Ghz CPU). diff --git a/domains/primitives/messenger-host-functions/src/host_functions.rs b/domains/primitives/messenger-host-functions/src/host_functions.rs index 8b152c83b5f..7e4d2b8568f 100644 --- a/domains/primitives/messenger-host-functions/src/host_functions.rs +++ b/domains/primitives/messenger-host-functions/src/host_functions.rs @@ -3,11 +3,11 @@ use domain_block_preprocessor::stateless_runtime::StatelessRuntime; use sc_executor::RuntimeVersionOf; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_core::traits::CodeExecutor; use sp_core::H256; +use sp_core::traits::CodeExecutor; use sp_domains::{DomainId, DomainsApi}; -use sp_messenger::messages::ChainId; pub use sp_messenger::MessengerApi; +use sp_messenger::messages::ChainId; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use std::marker::PhantomData; use std::sync::Arc; diff --git a/domains/primitives/messenger-host-functions/src/lib.rs b/domains/primitives/messenger-host-functions/src/lib.rs index d64c468803c..3a82be09b6d 100644 --- a/domains/primitives/messenger-host-functions/src/lib.rs +++ b/domains/primitives/messenger-host-functions/src/lib.rs @@ -27,9 +27,9 @@ extern crate alloc; #[cfg(feature = "std")] pub use host_functions::{MessengerApi, MessengerExtension, MessengerHostFunctionsImpl}; use parity_scale_codec::{Decode, Encode}; -pub use runtime_interface::messenger_runtime_interface::get_storage_key; #[cfg(feature = "std")] pub use runtime_interface::messenger_runtime_interface::HostFunctions; +pub use runtime_interface::messenger_runtime_interface::get_storage_key; use scale_info::TypeInfo; use sp_domains::DomainId; use sp_messenger::messages::{ChainId, MessageKey}; diff --git a/domains/primitives/messenger-host-functions/src/runtime_interface.rs b/domains/primitives/messenger-host-functions/src/runtime_interface.rs index f855e560143..e1026e40e02 100644 --- a/domains/primitives/messenger-host-functions/src/runtime_interface.rs +++ b/domains/primitives/messenger-host-functions/src/runtime_interface.rs @@ -1,6 +1,6 @@ +use crate::StorageKeyRequest; #[cfg(feature = "std")] use crate::host_functions::MessengerExtension; -use crate::StorageKeyRequest; #[cfg(not(feature = "std"))] use alloc::vec::Vec; #[cfg(feature = "std")] diff --git a/domains/primitives/messenger/src/endpoint.rs b/domains/primitives/messenger/src/endpoint.rs index e66e6494cbe..7544cc826ed 100644 --- a/domains/primitives/messenger/src/endpoint.rs +++ b/domains/primitives/messenger/src/endpoint.rs @@ -3,8 +3,8 @@ extern crate alloc; #[cfg(not(feature = "std"))] use alloc::vec::Vec; -use frame_support::weights::Weight; use frame_support::Parameter; +use frame_support::weights::Weight; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_domains::ChainId; diff --git a/domains/primitives/messenger/src/messages.rs b/domains/primitives/messenger/src/messages.rs index 1a2590671b3..e2be2d80df9 100644 --- a/domains/primitives/messenger/src/messages.rs +++ b/domains/primitives/messenger/src/messages.rs @@ -7,8 +7,8 @@ use alloc::vec::Vec; use parity_scale_codec::{Decode, Encode}; use scale_info::TypeInfo; pub use sp_domains::{ChainId, ChannelId}; -use sp_runtime::app_crypto::sp_core::U256; use sp_runtime::DispatchError; +use sp_runtime::app_crypto::sp_core::U256; use sp_subspace_mmr::ConsensusChainMmrLeafProof; use sp_trie::StorageProof; diff --git a/domains/primitives/runtime/src/lib.rs b/domains/primitives/runtime/src/lib.rs index ef2d5ff3728..8623d46d403 100644 --- a/domains/primitives/runtime/src/lib.rs +++ b/domains/primitives/runtime/src/lib.rs @@ -37,8 +37,8 @@ use sp_runtime::traits::transaction_extension::TransactionExtension; use sp_runtime::traits::{Convert, Dispatchable, IdentifyAccount, Verify}; use sp_runtime::transaction_validity::TransactionValidityError; use sp_runtime::{MultiAddress, MultiSignature, Perbill, Perquintill}; -use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND; use sp_weights::Weight; +use sp_weights::constants::WEIGHT_REF_TIME_PER_SECOND; pub use subspace_runtime_primitives::HoldIdentifier; use subspace_runtime_primitives::{MAX_BLOCK_LENGTH, SHANNON}; @@ -274,9 +274,9 @@ pub mod opaque { use crate::BlockNumber; #[cfg(not(feature = "std"))] use alloc::vec::Vec; + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; use sp_runtime::generic; use sp_runtime::traits::BlakeTwo256; - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; /// Opaque block header type. pub type Header = generic::Header; diff --git a/domains/runtime/auto-id/src/lib.rs b/domains/runtime/auto-id/src/lib.rs index 459b47aba5c..dbbf6c1cf00 100644 --- a/domains/runtime/auto-id/src/lib.rs +++ b/domains/runtime/auto-id/src/lib.rs @@ -14,13 +14,13 @@ use alloc::borrow::Cow; use alloc::format; use core::mem; use domain_runtime_primitives::opaque::Header; -pub use domain_runtime_primitives::{ - block_weights, maximum_block_length, opaque, Balance, BlockNumber, Hash, Nonce, - EXISTENTIAL_DEPOSIT, MAX_OUTGOING_MESSAGES, -}; use domain_runtime_primitives::{ - AccountId, Address, CheckExtrinsicsValidityError, DecodeExtrinsicError, HoldIdentifier, - Signature, TargetBlockFullness, ERR_BALANCE_OVERFLOW, SLOT_DURATION, + AccountId, Address, CheckExtrinsicsValidityError, DecodeExtrinsicError, ERR_BALANCE_OVERFLOW, + HoldIdentifier, SLOT_DURATION, Signature, TargetBlockFullness, +}; +pub use domain_runtime_primitives::{ + Balance, BlockNumber, EXISTENTIAL_DEPOSIT, Hash, MAX_OUTGOING_MESSAGES, Nonce, block_weights, + maximum_block_length, opaque, }; use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo}; use frame_support::genesis_builder_helper::{build_state, get_preset}; @@ -46,7 +46,7 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble}; use sp_runtime::traits::{ @@ -57,7 +57,7 @@ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, }; use sp_runtime::type_with_default::TypeWithDefault; -use sp_runtime::{generic, impl_opaque_keys, ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode}; +use sp_runtime::{ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode, generic, impl_opaque_keys}; pub use sp_runtime::{MultiAddress, Perbill, Permill}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -72,8 +72,8 @@ use static_assertions::const_assert; use subspace_runtime_primitives::utility::DefaultNonceProvider; use subspace_runtime_primitives::{ BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor, - Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, - XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SHANNON, SSC, + Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SHANNON, SSC, + SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler, }; /// Block type as expected by this runtime. @@ -645,7 +645,7 @@ pub fn extract_signer( fn extrinsic_era(extrinsic: &ExtrinsicFor) -> Option { match &extrinsic.preamble { Preamble::Bare(_) | Preamble::General(_, _) => None, - Preamble::Signed(_, _, extra) => Some(extra.4 .0), + Preamble::Signed(_, _, extra) => Some(extra.4.0), } } diff --git a/domains/runtime/evm/src/lib.rs b/domains/runtime/evm/src/lib.rs index 8d69af2da59..8e98ab1d2d8 100644 --- a/domains/runtime/evm/src/lib.rs +++ b/domains/runtime/evm/src/lib.rs @@ -16,15 +16,15 @@ use alloc::borrow::Cow; use alloc::format; use core::mem; use domain_runtime_primitives::opaque::Header; -pub use domain_runtime_primitives::{ - block_weights, maximum_block_length, maximum_domain_block_weight, opaque, Balance, BlockNumber, - EthereumAccountId as AccountId, EthereumSignature as Signature, Hash, Nonce, - EXISTENTIAL_DEPOSIT, -}; use domain_runtime_primitives::{ - AccountId20, CheckExtrinsicsValidityError, DecodeExtrinsicError, HoldIdentifier, - TargetBlockFullness, DEFAULT_EXTENSION_VERSION, ERR_BALANCE_OVERFLOW, - ERR_CONTRACT_CREATION_NOT_ALLOWED, ERR_NONCE_OVERFLOW, MAX_OUTGOING_MESSAGES, SLOT_DURATION, + AccountId20, CheckExtrinsicsValidityError, DEFAULT_EXTENSION_VERSION, DecodeExtrinsicError, + ERR_BALANCE_OVERFLOW, ERR_CONTRACT_CREATION_NOT_ALLOWED, ERR_NONCE_OVERFLOW, HoldIdentifier, + MAX_OUTGOING_MESSAGES, SLOT_DURATION, TargetBlockFullness, +}; +pub use domain_runtime_primitives::{ + Balance, BlockNumber, EXISTENTIAL_DEPOSIT, EthereumAccountId as AccountId, + EthereumSignature as Signature, Hash, Nonce, block_weights, maximum_block_length, + maximum_domain_block_weight, opaque, }; use fp_self_contained::{CheckedSignature, SelfContainedCall}; use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo}; @@ -49,13 +49,13 @@ use pallet_evm::{ Account as EVMAccount, EnsureAddressNever, EnsureAddressRoot, FeeCalculator, IdentityAddressMapping, Runner, }; -use pallet_evm_tracker::create_contract::{is_create_contract_allowed, CheckContractCreation}; +use pallet_evm_tracker::create_contract::{CheckContractCreation, is_create_contract_allowed}; use pallet_evm_tracker::traits::{MaybeIntoEthCall, MaybeIntoEvmCall}; use pallet_transporter::EndpointHandler; use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use sp_api::impl_runtime_apis; use sp_core::crypto::KeyTypeId; -use sp_core::{Get, OpaqueMetadata, H160, H256, U256}; +use sp_core::{Get, H160, H256, OpaqueMetadata, U256}; use sp_domains::{ ChannelId, DomainAllowlistUpdates, DomainId, PermissionedActionAllowedBy, Transfers, }; @@ -68,7 +68,7 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble}; use sp_runtime::traits::{ @@ -80,11 +80,11 @@ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, }; use sp_runtime::{ - generic, impl_opaque_keys, ApplyExtrinsicResult, ConsensusEngineId, Digest, - ExtrinsicInclusionMode, + ApplyExtrinsicResult, ConsensusEngineId, Digest, ExtrinsicInclusionMode, generic, + impl_opaque_keys, }; pub use sp_runtime::{MultiAddress, Perbill, Permill}; -use sp_std::cmp::{max, Ordering}; +use sp_std::cmp::{Ordering, max}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; use sp_std::marker::PhantomData; @@ -98,8 +98,8 @@ use static_assertions::const_assert; use subspace_runtime_primitives::utility::{MaybeNestedCall, MaybeUtilityCall}; use subspace_runtime_primitives::{ BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor, - Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, - XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SHANNON, SSC, + Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SHANNON, SSC, + SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler, }; /// The address format for describing accounts. @@ -959,7 +959,7 @@ pub fn extract_signer( fn extrinsic_era(extrinsic: &ExtrinsicFor) -> Option { match &extrinsic.0.preamble { Preamble::Bare(_) | Preamble::General(_, _) => None, - Preamble::Signed(_, _, extra) => Some(extra.4 .0), + Preamble::Signed(_, _, extra) => Some(extra.4.0), } } @@ -1070,7 +1070,7 @@ fn check_transaction_and_do_pre_dispatch_inner( extra.2, extra.3, extra.4, - pallet_evm_tracker::CheckNonce::from(extra.5 .0), + pallet_evm_tracker::CheckNonce::from(extra.5.0), extra.6, extra.7.clone(), extra.8, @@ -1095,7 +1095,7 @@ fn check_transaction_and_do_pre_dispatch_inner( extra.2, extra.3, extra.4, - pallet_evm_tracker::CheckNonce::from(extra.5 .0), + pallet_evm_tracker::CheckNonce::from(extra.5.0), extra.6, extra.7.clone(), extra.8, diff --git a/domains/service/src/config.rs b/domains/service/src/config.rs index 6de98431155..85b6f689ba6 100644 --- a/domains/service/src/config.rs +++ b/domains/service/src/config.rs @@ -1,7 +1,7 @@ use sc_chain_spec::ChainSpec; use sc_network::config::{ - MultiaddrWithPeerId, NetworkBackendType, NetworkConfiguration, NodeKeyConfig, SetConfig, - SyncMode, TransportConfig, DEFAULT_KADEMLIA_REPLICATION_FACTOR, + DEFAULT_KADEMLIA_REPLICATION_FACTOR, MultiaddrWithPeerId, NetworkBackendType, + NetworkConfiguration, NodeKeyConfig, SetConfig, SyncMode, TransportConfig, }; use sc_rpc_server::RpcEndpoint; use sc_service::config::{ @@ -16,8 +16,8 @@ use sc_telemetry::TelemetryEndpoints; use std::net::SocketAddr; use std::num::{NonZeroU32, NonZeroUsize}; use std::path::PathBuf; -use std::sync::atomic::AtomicBool; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use tokio::runtime::Handle; /// The default max request size in MB, copied from Substrate diff --git a/domains/service/src/domain.rs b/domains/service/src/domain.rs index 6598e9474cd..00570b03e27 100644 --- a/domains/service/src/domain.rs +++ b/domains/service/src/domain.rs @@ -9,8 +9,8 @@ use domain_client_operator::snap_sync::ConsensusChainSyncParams; use domain_client_operator::{Operator, OperatorParams, OperatorStreams}; use domain_runtime_primitives::opaque::{Block, Header}; use domain_runtime_primitives::{Balance, Hash}; -use futures::channel::mpsc; use futures::Stream; +use futures::channel::mpsc; use pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi; use sc_client_api::{ AuxStore, BlockBackend, BlockImportNotification, BlockchainEvents, ExecutorProvider, @@ -27,7 +27,7 @@ use sc_service::{ use sc_telemetry::{Telemetry, TelemetryWorker, TelemetryWorkerHandle}; use sc_transaction_pool::{BasicPool, FullChainApi}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver}; +use sc_utils::mpsc::{TracingUnboundedReceiver, tracing_unbounded}; use serde::de::DeserializeOwned; use sp_api::{ApiExt, ConstructRuntimeApi, Metadata, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder; diff --git a/domains/service/src/lib.rs b/domains/service/src/lib.rs index b871778bb94..7f36c93ac82 100644 --- a/domains/service/src/lib.rs +++ b/domains/service/src/lib.rs @@ -6,7 +6,7 @@ pub mod network; pub mod providers; pub mod rpc; -pub use self::domain::{new_full, DomainOperator, DomainParams, FullPool, NewFull}; +pub use self::domain::{DomainOperator, DomainParams, FullPool, NewFull, new_full}; use sc_domains::RuntimeExecutor; use sc_service::TFullClient; diff --git a/domains/service/src/network.rs b/domains/service/src/network.rs index 61b44185008..03033bcffaa 100644 --- a/domains/service/src/network.rs +++ b/domains/service/src/network.rs @@ -2,18 +2,18 @@ use sc_client_api::{AuxStore, BlockBackend, BlockchainEvents, ProofProvider}; use sc_consensus::ImportQueue; use sc_network::NetworkBackend; use sc_network_common::role::Roles; +use sc_network_sync::SyncingService; use sc_network_sync::block_relay_protocol::{BlockDownloader, BlockRelayParams}; use sc_network_sync::engine::SyncingEngine; use sc_network_sync::service::network::{NetworkServiceHandle, NetworkServiceProvider}; -use sc_network_sync::SyncingService; use sc_service::{ - build_default_block_downloader, build_network_advanced, build_polkadot_syncing_strategy, BuildNetworkAdvancedParams, BuildNetworkParams, Error, NetworkStarter, + build_default_block_downloader, build_network_advanced, build_polkadot_syncing_strategy, }; use sc_transaction_pool_api::TransactionPool; use sc_utils::mpsc::TracingUnboundedSender; -use sp_api::ProvideRuntimeApi; use sp_api::__private::BlockT; +use sp_api::ProvideRuntimeApi; use sp_blockchain::{HeaderBackend, HeaderMetadata}; use sp_consensus::block_validation::{Chain, DefaultBlockAnnounceValidator}; use sp_runtime::traits::BlockIdTo; diff --git a/domains/service/src/providers.rs b/domains/service/src/providers.rs index ead07e124cb..fa16b9127ba 100644 --- a/domains/service/src/providers.rs +++ b/domains/service/src/providers.rs @@ -1,5 +1,5 @@ -use crate::rpc::FullDeps; use crate::FullClient; +use crate::rpc::FullDeps; use domain_runtime_primitives::{Balance, Nonce}; use jsonrpsee::RpcModule; use parity_scale_codec::{Decode, Encode}; diff --git a/domains/test/runtime/auto-id/src/lib.rs b/domains/test/runtime/auto-id/src/lib.rs index 1435d2bec9f..fd3f50e26d8 100644 --- a/domains/test/runtime/auto-id/src/lib.rs +++ b/domains/test/runtime/auto-id/src/lib.rs @@ -15,12 +15,12 @@ use alloc::format; use core::mem; use domain_runtime_primitives::opaque::Header; pub use domain_runtime_primitives::{ - block_weights, maximum_block_length, opaque, AccountId, Address, Balance, BlockNumber, Hash, - Nonce, Signature, EXISTENTIAL_DEPOSIT, MAX_OUTGOING_MESSAGES, + AccountId, Address, Balance, BlockNumber, EXISTENTIAL_DEPOSIT, Hash, MAX_OUTGOING_MESSAGES, + Nonce, Signature, block_weights, maximum_block_length, opaque, }; use domain_runtime_primitives::{ - CheckExtrinsicsValidityError, DecodeExtrinsicError, HoldIdentifier, TargetBlockFullness, - ERR_BALANCE_OVERFLOW, SLOT_DURATION, + CheckExtrinsicsValidityError, DecodeExtrinsicError, ERR_BALANCE_OVERFLOW, HoldIdentifier, + SLOT_DURATION, TargetBlockFullness, }; use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo}; use frame_support::genesis_builder_helper::{build_state, get_preset}; @@ -46,7 +46,7 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble}; use sp_runtime::traits::{ @@ -57,7 +57,7 @@ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, }; use sp_runtime::type_with_default::TypeWithDefault; -use sp_runtime::{generic, impl_opaque_keys, ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode}; +use sp_runtime::{ApplyExtrinsicResult, Digest, ExtrinsicInclusionMode, generic, impl_opaque_keys}; pub use sp_runtime::{MultiAddress, Perbill, Permill}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -72,8 +72,8 @@ use static_assertions::const_assert; use subspace_runtime_primitives::utility::DefaultNonceProvider; use subspace_runtime_primitives::{ BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor, - Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, - XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SSC, + Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SSC, + SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler, }; /// Block type as expected by this runtime. @@ -604,7 +604,7 @@ pub fn extract_signer( fn extrinsic_era(extrinsic: &ExtrinsicFor) -> Option { match &extrinsic.preamble { Preamble::Bare(_) | Preamble::General(_, _) => None, - Preamble::Signed(_, _, extra) => Some(extra.4 .0), + Preamble::Signed(_, _, extra) => Some(extra.4.0), } } diff --git a/domains/test/runtime/evm/src/lib.rs b/domains/test/runtime/evm/src/lib.rs index aadf1850d71..60a67b43a7d 100644 --- a/domains/test/runtime/evm/src/lib.rs +++ b/domains/test/runtime/evm/src/lib.rs @@ -17,13 +17,14 @@ use alloc::format; use core::mem; pub use domain_runtime_primitives::opaque::Header; use domain_runtime_primitives::{ - block_weights, maximum_block_length, AccountId20, EthereumAccountId, TargetBlockFullness, - DEFAULT_EXTENSION_VERSION, ERR_BALANCE_OVERFLOW, ERR_CONTRACT_CREATION_NOT_ALLOWED, - ERR_NONCE_OVERFLOW, EXISTENTIAL_DEPOSIT, MAX_OUTGOING_MESSAGES, SLOT_DURATION, + AccountId20, DEFAULT_EXTENSION_VERSION, ERR_BALANCE_OVERFLOW, + ERR_CONTRACT_CREATION_NOT_ALLOWED, ERR_NONCE_OVERFLOW, EXISTENTIAL_DEPOSIT, EthereumAccountId, + MAX_OUTGOING_MESSAGES, SLOT_DURATION, TargetBlockFullness, block_weights, maximum_block_length, }; pub use domain_runtime_primitives::{ - opaque, Balance, BlockNumber, CheckExtrinsicsValidityError, DecodeExtrinsicError, + Balance, BlockNumber, CheckExtrinsicsValidityError, DecodeExtrinsicError, EthereumAccountId as AccountId, EthereumSignature as Signature, Hash, HoldIdentifier, Nonce, + opaque, }; use fp_self_contained::{CheckedSignature, SelfContainedCall}; use frame_support::dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo}; @@ -53,7 +54,7 @@ use pallet_transporter::EndpointHandler; use parity_scale_codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use sp_api::impl_runtime_apis; use sp_core::crypto::KeyTypeId; -use sp_core::{Get, OpaqueMetadata, H160, H256, U256}; +use sp_core::{Get, H160, H256, OpaqueMetadata, U256}; use sp_domains::{DomainAllowlistUpdates, DomainId, PermissionedActionAllowedBy, Transfers}; use sp_evm_tracker::{ BlockGasLimit, GasLimitPovSizeRatio, GasPerByte, StorageFeeRatio, WeightPerGas, @@ -64,7 +65,7 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::generic::{Era, ExtrinsicFormat, Preamble, SignedPayload}; use sp_runtime::traits::{ @@ -76,11 +77,11 @@ use sp_runtime::transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, }; use sp_runtime::{ - generic, impl_opaque_keys, ApplyExtrinsicResult, ConsensusEngineId, Digest, - ExtrinsicInclusionMode, SaturatedConversion, + ApplyExtrinsicResult, ConsensusEngineId, Digest, ExtrinsicInclusionMode, SaturatedConversion, + generic, impl_opaque_keys, }; pub use sp_runtime::{MultiAddress, Perbill, Permill}; -use sp_std::cmp::{max, Ordering}; +use sp_std::cmp::{Ordering, max}; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; use sp_std::marker::PhantomData; @@ -94,8 +95,8 @@ use static_assertions::const_assert; use subspace_runtime_primitives::utility::{MaybeNestedCall, MaybeUtilityCall}; use subspace_runtime_primitives::{ BlockHashFor, BlockNumber as ConsensusBlockNumber, DomainEventSegmentSize, ExtrinsicFor, - Hash as ConsensusBlockHash, HeaderFor, Moment, SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, - XdmFeeMultipler, MAX_CALL_RECURSION_DEPTH, SHANNON, SSC, + Hash as ConsensusBlockHash, HeaderFor, MAX_CALL_RECURSION_DEPTH, Moment, SHANNON, SSC, + SlowAdjustingFeeUpdate, XdmAdjustedWeightToFee, XdmFeeMultipler, }; /// The address format for describing accounts. @@ -1035,7 +1036,7 @@ pub fn extract_signer( fn extrinsic_era(extrinsic: &ExtrinsicFor) -> Option { match &extrinsic.0.preamble { Preamble::Bare(_) | Preamble::General(_, _) => None, - Preamble::Signed(_, _, extra) => Some(extra.4 .0), + Preamble::Signed(_, _, extra) => Some(extra.4.0), } } @@ -1135,7 +1136,7 @@ fn check_transaction_and_do_pre_dispatch_inner( extra.2, extra.3, extra.4, - pallet_evm_tracker::CheckNonce::from(extra.5 .0), + pallet_evm_tracker::CheckNonce::from(extra.5.0), extra.6, extra.7.clone(), extra.8, @@ -1160,7 +1161,7 @@ fn check_transaction_and_do_pre_dispatch_inner( extra.2, extra.3, extra.4, - pallet_evm_tracker::CheckNonce::from(extra.5 .0), + pallet_evm_tracker::CheckNonce::from(extra.5.0), extra.6, extra.7.clone(), extra.8, diff --git a/domains/test/service/src/domain.rs b/domains/test/service/src/domain.rs index c704e9b6a63..56ed109c182 100644 --- a/domains/test/service/src/domain.rs +++ b/domains/test/service/src/domain.rs @@ -3,16 +3,16 @@ use crate::chain_spec::create_domain_spec; use crate::{ - construct_extrinsic_generic, node_config, BalanceOf, DomainRuntime, EcdsaKeyring, - Sr25519Keyring, UncheckedExtrinsicFor, AUTO_ID_DOMAIN_ID, EVM_DOMAIN_ID, + AUTO_ID_DOMAIN_ID, BalanceOf, DomainRuntime, EVM_DOMAIN_ID, EcdsaKeyring, Sr25519Keyring, + UncheckedExtrinsicFor, construct_extrinsic_generic, node_config, }; use cross_domain_message_gossip::ChainMsg; use domain_client_operator::snap_sync::ConsensusChainSyncParams; -use domain_client_operator::{fetch_domain_bootstrap_info, BootstrapResult, OperatorStreams}; +use domain_client_operator::{BootstrapResult, OperatorStreams, fetch_domain_bootstrap_info}; use domain_runtime_primitives::opaque::Block; use domain_runtime_primitives::{Balance, EthereumAccountId}; -use domain_service::providers::DefaultProvider; use domain_service::FullClient; +use domain_service::providers::DefaultProvider; use domain_test_primitives::{EvmOnchainStateApi, OnchainStateApi}; use frame_support::dispatch::{DispatchInfo, PostDispatchInfo}; use frame_system::pallet_prelude::{BlockNumberFor, RuntimeCallFor}; @@ -25,7 +25,7 @@ use sc_network_sync::SyncingService; use sc_service::config::MultiaddrWithPeerId; use sc_service::{BasePath, Role, RpcHandlers, TFullBackend, TaskManager, TransactionPool}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender}; +use sc_utils::mpsc::{TracingUnboundedSender, tracing_unbounded}; use sp_api::{ApiExt, ConstructRuntimeApi, Metadata, ProvideRuntimeApi}; use sp_block_builder::BlockBuilder; use sp_blockchain::HashAndNumber; @@ -36,8 +36,8 @@ use sp_domains::{DomainId, OperatorId, PermissionedActionAllowedBy}; use sp_messenger::messages::{ChainId, ChannelId}; use sp_messenger::{MessengerApi, RelayerApi}; use sp_offchain::OffchainWorkerApi; -use sp_runtime::traits::{AsSystemOriginSigner, Dispatchable, NumberFor}; use sp_runtime::OpaqueExtrinsic; +use sp_runtime::traits::{AsSystemOriginSigner, Dispatchable, NumberFor}; use sp_session::SessionKeys; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; use std::future::Future; diff --git a/domains/test/service/src/keyring.rs b/domains/test/service/src/keyring.rs index f57b8917b1e..9c75ea94727 100644 --- a/domains/test/service/src/keyring.rs +++ b/domains/test/service/src/keyring.rs @@ -1,7 +1,7 @@ //! Set of test accounts. use fp_account::AccountId20; use sp_core::ecdsa::{Pair, Public, Signature}; -use sp_core::{ecdsa, keccak_256, Pair as PairT}; +use sp_core::{Pair as PairT, ecdsa, keccak_256}; #[allow(missing_docs)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/shared/sc-subspace-sync-common/src/snap_sync_engine.rs b/shared/sc-subspace-sync-common/src/snap_sync_engine.rs index 7ece16e1351..389027eb932 100644 --- a/shared/sc-subspace-sync-common/src/snap_sync_engine.rs +++ b/shared/sc-subspace-sync-common/src/snap_sync_engine.rs @@ -1,8 +1,8 @@ //! `SyncingEngine` is the actor responsible for syncing Substrate chain //! to tip and keep the blockchain up to date with network updates. -use futures::channel::oneshot; use futures::StreamExt; +use futures::channel::oneshot; use sc_client_api::ProofProvider; use sc_consensus::IncomingBlock; use sc_network::types::ProtocolName; @@ -10,8 +10,8 @@ use sc_network::{OutboundFailure, PeerId, RequestFailure}; use sc_network_sync::pending_responses::{PendingResponses, ResponseEvent}; use sc_network_sync::service::network::NetworkServiceHandle; use sc_network_sync::state_request_handler::generate_protocol_name; -use sc_network_sync::strategy::state::StateStrategy; use sc_network_sync::strategy::SyncingAction; +use sc_network_sync::strategy::state::StateStrategy; use sc_network_sync::types::BadPeer; use sp_blockchain::{Error as ClientError, HeaderBackend}; use sp_runtime::traits::{Block as BlockT, NumberFor}; diff --git a/shared/subspace-data-retrieval/src/object_fetcher.rs b/shared/subspace-data-retrieval/src/object_fetcher.rs index 1ab02a1ba06..3cc962e7e6f 100644 --- a/shared/subspace-data-retrieval/src/object_fetcher.rs +++ b/shared/subspace-data-retrieval/src/object_fetcher.rs @@ -2,7 +2,7 @@ use crate::object_fetcher::partial_object::{PartialObject, RawPieceData}; use crate::object_fetcher::segment_header::{ - max_segment_header_encoded_size, min_segment_header_encoded_size, MAX_SEGMENT_PADDING, + MAX_SEGMENT_PADDING, max_segment_header_encoded_size, min_segment_header_encoded_size, }; use crate::piece_fetcher::download_pieces; use crate::piece_getter::PieceGetter; @@ -119,9 +119,9 @@ pub enum Error { /// Supplied piece offset is inside the minimum segment header size #[error( - "Piece offset is inside the segment header, min size of segment header: {}, object: {mapping:?}", - min_segment_header_encoded_size(), - )] + "Piece offset is inside the segment header, min size of segment header: {}, object: {mapping:?}", + min_segment_header_encoded_size() + )] PieceOffsetInSegmentHeader { mapping: GlobalObject }, /// Segment decoding error diff --git a/shared/subspace-data-retrieval/src/object_fetcher/partial_object.rs b/shared/subspace-data-retrieval/src/object_fetcher/partial_object.rs index bd3265fa754..4c06b19fbf2 100644 --- a/shared/subspace-data-retrieval/src/object_fetcher/partial_object.rs +++ b/shared/subspace-data-retrieval/src/object_fetcher/partial_object.rs @@ -15,14 +15,14 @@ //! before the object length is known, and before each new piece is added to the partial object. //! - `PartialObject` is used to store the partial object data after the object length is known. -use crate::object_fetcher::segment_header::{strip_segment_header, MAX_SEGMENT_PADDING}; -use crate::object_fetcher::{decode_data_length, Error, MAX_ENCODED_LENGTH_SIZE}; +use crate::object_fetcher::segment_header::{MAX_SEGMENT_PADDING, strip_segment_header}; +use crate::object_fetcher::{Error, MAX_ENCODED_LENGTH_SIZE, decode_data_length}; use parity_scale_codec::{Decode, Input}; use std::cmp::min; use std::collections::BTreeSet; use std::fmt; use std::fmt::Formatter; -use subspace_core_primitives::hashes::{blake3_hash, Blake3Hash}; +use subspace_core_primitives::hashes::{Blake3Hash, blake3_hash}; use subspace_core_primitives::objects::GlobalObject; use subspace_core_primitives::pieces::{PieceIndex, RawRecord}; use subspace_core_primitives::segments::RecordedHistorySegment; diff --git a/shared/subspace-data-retrieval/src/object_fetcher/segment_header.rs b/shared/subspace-data-retrieval/src/object_fetcher/segment_header.rs index 2ccadb80e1e..a5e1bc1e587 100644 --- a/shared/subspace-data-retrieval/src/object_fetcher/segment_header.rs +++ b/shared/subspace-data-retrieval/src/object_fetcher/segment_header.rs @@ -3,7 +3,7 @@ //! This module implements segment header stripping. Segment headers are stripped from pieces //! before they are used to reconstruct objects. -use crate::object_fetcher::{decode_data_length, Error}; +use crate::object_fetcher::{Error, decode_data_length}; use parity_scale_codec::{Decode, Encode, Input, IoReader}; use std::io::Cursor; use subspace_archiving::archiver::SegmentItem; diff --git a/shared/subspace-data-retrieval/src/object_fetcher/tests.rs b/shared/subspace-data-retrieval/src/object_fetcher/tests.rs index dc6e0bc31f2..cd8ef19d394 100644 --- a/shared/subspace-data-retrieval/src/object_fetcher/tests.rs +++ b/shared/subspace-data-retrieval/src/object_fetcher/tests.rs @@ -4,10 +4,10 @@ use super::*; use crate::object_fetcher::partial_object::PADDING_BYTE_VALUE; use crate::piece_getter::get_pieces_individually; use async_trait::async_trait; -use futures::lock::Mutex; use futures::Stream; +use futures::lock::Mutex; use parity_scale_codec::{Compact, CompactLen, Encode}; -use rand::{thread_rng, RngCore}; +use rand::{RngCore, thread_rng}; use std::collections::HashMap; use std::fmt::Debug; use std::iter; diff --git a/shared/subspace-data-retrieval/src/piece_getter.rs b/shared/subspace-data-retrieval/src/piece_getter.rs index aa07410f913..3cd7da137f1 100644 --- a/shared/subspace-data-retrieval/src/piece_getter.rs +++ b/shared/subspace-data-retrieval/src/piece_getter.rs @@ -1,7 +1,7 @@ //! Getting object pieces from the Subspace Distributed Storage Network, or various caches. use async_trait::async_trait; -use futures::{stream, Stream, StreamExt}; +use futures::{Stream, StreamExt, stream}; use std::fmt; use std::future::Future; use std::sync::Arc; diff --git a/shared/subspace-kzg/benches/kzg.rs b/shared/subspace-kzg/benches/kzg.rs index 351faed3abf..fb11bbf850e 100644 --- a/shared/subspace-kzg/benches/kzg.rs +++ b/shared/subspace-kzg/benches/kzg.rs @@ -1,6 +1,6 @@ -use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use subspace_core_primitives::pieces::RawRecord; +use criterion::{Criterion, black_box, criterion_group, criterion_main}; use subspace_core_primitives::ScalarBytes; +use subspace_core_primitives::pieces::RawRecord; use subspace_kzg::{Kzg, Scalar}; fn criterion_benchmark(c: &mut Criterion) { diff --git a/shared/subspace-kzg/src/lib.rs b/shared/subspace-kzg/src/lib.rs index c55a296f71a..669851f7735 100644 --- a/shared/subspace-kzg/src/lib.rs +++ b/shared/subspace-kzg/src/lib.rs @@ -5,8 +5,8 @@ mod tests; extern crate alloc; -use alloc::collections::btree_map::Entry; use alloc::collections::BTreeMap; +use alloc::collections::btree_map::Entry; #[cfg(not(feature = "std"))] use alloc::string::{String, ToString}; use alloc::sync::Arc; @@ -15,7 +15,7 @@ use alloc::vec::Vec; use core::mem; use derive_more::{AsMut, AsRef, Deref, DerefMut, From, Into}; use kzg::eip_4844::{BYTES_PER_G1, BYTES_PER_G2}; -use kzg::{FFTFr, FFTSettings, Fr, KZGSettings, G1, G2}; +use kzg::{FFTFr, FFTSettings, Fr, G1, G2, KZGSettings}; #[cfg(feature = "std")] use parking_lot::Mutex; use rust_kzg_blst::types::fft_settings::FsFFTSettings; @@ -27,10 +27,10 @@ use rust_kzg_blst::types::poly::FsPoly; #[cfg(not(feature = "std"))] use spin::Mutex; use static_assertions::const_assert_eq; +use subspace_core_primitives::ScalarBytes; use subspace_core_primitives::pieces::{RecordCommitment, RecordWitness}; use subspace_core_primitives::segments::SegmentCommitment; use subspace_core_primitives::solutions::ChunkWitness; -use subspace_core_primitives::ScalarBytes; use tracing::debug; /// Embedded KZG settings as bytes, too big for `no_std` in most cases diff --git a/shared/subspace-logging/src/lib.rs b/shared/subspace-logging/src/lib.rs index 104d1266709..6fe8117c24e 100644 --- a/shared/subspace-logging/src/lib.rs +++ b/shared/subspace-logging/src/lib.rs @@ -1,7 +1,7 @@ use tracing::level_filters::LevelFilter; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; -use tracing_subscriber::{fmt, EnvFilter, Layer}; +use tracing_subscriber::{EnvFilter, Layer, fmt}; pub fn init_logger() { // TODO: Workaround for https://github.com/tokio-rs/tracing/issues/2214, also on diff --git a/shared/subspace-metrics/src/lib.rs b/shared/subspace-metrics/src/lib.rs index a2a57d07497..4834e231e79 100644 --- a/shared/subspace-metrics/src/lib.rs +++ b/shared/subspace-metrics/src/lib.rs @@ -6,7 +6,7 @@ use actix_web::http::StatusCode; use actix_web::web::Data; -use actix_web::{get, App, HttpResponse, HttpServer}; +use actix_web::{App, HttpResponse, HttpServer, get}; use prometheus::{Registry as SubstrateRegistry, TextEncoder}; use prometheus_client::encoding::text::encode; use prometheus_client::registry::Registry as PrometheusClientRegistry; diff --git a/shared/subspace-proof-of-space-gpu/src/cuda.rs b/shared/subspace-proof-of-space-gpu/src/cuda.rs index caf0ec9f380..63292027200 100644 --- a/shared/subspace-proof-of-space-gpu/src/cuda.rs +++ b/shared/subspace-proof-of-space-gpu/src/cuda.rs @@ -5,9 +5,9 @@ mod tests; use rust_kzg_blst::types::fr::FsFr; use std::ops::DerefMut; +use subspace_core_primitives::ScalarBytes; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::pos::{PosProof, PosSeed}; -use subspace_core_primitives::ScalarBytes; use subspace_kzg::Scalar; unsafe extern "C" { diff --git a/shared/subspace-proof-of-space-gpu/src/cuda/tests.rs b/shared/subspace-proof-of-space-gpu/src/cuda/tests.rs index 38d18bbd17a..df1009b2720 100644 --- a/shared/subspace-proof-of-space-gpu/src/cuda/tests.rs +++ b/shared/subspace-proof-of-space-gpu/src/cuda/tests.rs @@ -8,8 +8,8 @@ use subspace_core_primitives::segments::HistorySize; use subspace_erasure_coding::ErasureCoding; use subspace_farmer_components::plotting::{CpuRecordsEncoder, RecordsEncoder}; use subspace_farmer_components::sector::SectorContentsMap; -use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::Table; +use subspace_proof_of_space::chia::ChiaTable; type PosTable = ChiaTable; diff --git a/shared/subspace-proof-of-space-gpu/src/rocm.rs b/shared/subspace-proof-of-space-gpu/src/rocm.rs index e898c3417bc..3b9987e0cd1 100644 --- a/shared/subspace-proof-of-space-gpu/src/rocm.rs +++ b/shared/subspace-proof-of-space-gpu/src/rocm.rs @@ -5,9 +5,9 @@ mod tests; use rust_kzg_blst::types::fr::FsFr; use std::ops::DerefMut; +use subspace_core_primitives::ScalarBytes; use subspace_core_primitives::pieces::Record; use subspace_core_primitives::pos::{PosProof, PosSeed}; -use subspace_core_primitives::ScalarBytes; use subspace_kzg::Scalar; unsafe extern "C" { diff --git a/shared/subspace-proof-of-space-gpu/src/rocm/tests.rs b/shared/subspace-proof-of-space-gpu/src/rocm/tests.rs index 3b690aaa710..a5cc6c0d3c2 100644 --- a/shared/subspace-proof-of-space-gpu/src/rocm/tests.rs +++ b/shared/subspace-proof-of-space-gpu/src/rocm/tests.rs @@ -8,8 +8,8 @@ use subspace_core_primitives::segments::HistorySize; use subspace_erasure_coding::ErasureCoding; use subspace_farmer_components::plotting::{CpuRecordsEncoder, RecordsEncoder}; use subspace_farmer_components::sector::SectorContentsMap; -use subspace_proof_of_space::chia::ChiaTable; use subspace_proof_of_space::Table; +use subspace_proof_of_space::chia::ChiaTable; type PosTable = ChiaTable; diff --git a/test/subspace-test-client/src/auto_id_domain_chain_spec.rs b/test/subspace-test-client/src/auto_id_domain_chain_spec.rs index b451186bc77..71e20046482 100644 --- a/test/subspace-test-client/src/auto_id_domain_chain_spec.rs +++ b/test/subspace-test-client/src/auto_id_domain_chain_spec.rs @@ -6,7 +6,7 @@ use domain_runtime_primitives::AccountIdConverter; use parity_scale_codec::Encode; use sc_chain_spec::{ChainType, GenericChainSpec, NoExtension}; use sp_core::crypto::AccountId32; -use sp_core::{sr25519, Pair, Public}; +use sp_core::{Pair, Public, sr25519}; use sp_domains::storage::RawGenesis; use sp_domains::{ DomainRuntimeConfig, GenesisDomain, OperatorAllowList, OperatorPublicKey, RuntimeType, diff --git a/test/subspace-test-client/src/chain_spec.rs b/test/subspace-test-client/src/chain_spec.rs index 168e777e2fd..92bf98e5156 100644 --- a/test/subspace-test-client/src/chain_spec.rs +++ b/test/subspace-test-client/src/chain_spec.rs @@ -1,12 +1,12 @@ //! Chain specification for the test runtime. use sc_chain_spec::{ChainType, GenericChainSpec}; -use sp_core::{sr25519, Pair, Public}; +use sp_core::{Pair, Public, sr25519}; use sp_domains::{EvmType, PermissionedActionAllowedBy}; use sp_runtime::traits::{IdentifyAccount, Verify}; use std::marker::PhantomData; use std::num::NonZeroU32; -use subspace_runtime_primitives::{AccountId, Balance, Signature, SSC}; +use subspace_runtime_primitives::{AccountId, Balance, SSC, Signature}; use subspace_test_runtime::{ AllowAuthoringBy, BalancesConfig, DomainsConfig, EnableRewardsAt, RewardsConfig, RuntimeGenesisConfig, SubspaceConfig, SudoConfig, SystemConfig, WASM_BINARY, diff --git a/test/subspace-test-client/src/evm_domain_chain_spec.rs b/test/subspace-test-client/src/evm_domain_chain_spec.rs index b4aac4c81b5..6b63556372d 100644 --- a/test/subspace-test-client/src/evm_domain_chain_spec.rs +++ b/test/subspace-test-client/src/evm_domain_chain_spec.rs @@ -7,7 +7,7 @@ use evm_domain_test_runtime::{ }; use parity_scale_codec::Encode; use sc_chain_spec::{ChainType, GenericChainSpec, NoExtension}; -use sp_core::{ecdsa, Pair, Public}; +use sp_core::{Pair, Public, ecdsa}; use sp_domains::storage::RawGenesis; use sp_domains::{ DomainId, EvmDomainRuntimeConfig, EvmType, GenesisDomain, OperatorAllowList, OperatorPublicKey, diff --git a/test/subspace-test-client/src/lib.rs b/test/subspace-test-client/src/lib.rs index 0cf710b79ed..917cc727754 100644 --- a/test/subspace-test-client/src/lib.rs +++ b/test/subspace-test-client/src/lib.rs @@ -22,8 +22,8 @@ pub mod auto_id_domain_chain_spec; pub mod chain_spec; pub mod evm_domain_chain_spec; -use futures::executor::block_on; use futures::StreamExt; +use futures::executor::block_on; use sc_client_api::{BlockBackend, HeaderBackend}; use sc_consensus_subspace::archiver::encode_block; use sc_consensus_subspace::notification::SubspaceNotificationStream; @@ -41,12 +41,12 @@ use subspace_core_primitives::segments::{HistorySize, SegmentIndex}; use subspace_core_primitives::solutions::{RewardSignature, Solution}; use subspace_core_primitives::{PublicKey, REWARD_SIGNING_CONTEXT}; use subspace_erasure_coding::ErasureCoding; +use subspace_farmer_components::FarmerProtocolInfo; use subspace_farmer_components::auditing::audit_sector_sync; use subspace_farmer_components::plotting::{ - plot_sector, CpuRecordsEncoder, PlotSectorOptions, PlottedSector, + CpuRecordsEncoder, PlotSectorOptions, PlottedSector, plot_sector, }; use subspace_farmer_components::reading::ReadSectorRecordChunksMode; -use subspace_farmer_components::FarmerProtocolInfo; use subspace_kzg::Kzg; use subspace_proof_of_space::{Table, TableGenerator}; use subspace_runtime_primitives::opaque::Block; diff --git a/test/subspace-test-runtime/src/lib.rs b/test/subspace-test-runtime/src/lib.rs index 5f7ea04422b..0e02707c1b5 100644 --- a/test/subspace-test-runtime/src/lib.rs +++ b/test/subspace-test-runtime/src/lib.rs @@ -48,12 +48,12 @@ use frame_support::inherent::ProvideInherent; use frame_support::traits::fungible::Inspect; use frame_support::traits::tokens::WithdrawConsequence; use frame_support::traits::{ - ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Currency, Everything, ExistenceRequirement, + ConstU8, ConstU16, ConstU32, ConstU64, ConstU128, Currency, Everything, ExistenceRequirement, Get, Imbalance, Time, VariantCount, WithdrawReasons, }; use frame_support::weights::constants::{ParityDbWeight, WEIGHT_REF_TIME_PER_SECOND}; use frame_support::weights::{ConstantMultiplier, Weight}; -use frame_support::{construct_runtime, parameter_types, PalletId}; +use frame_support::{PalletId, construct_runtime, parameter_types}; use frame_system::limits::{BlockLength, BlockWeights}; use frame_system::pallet_prelude::{OriginFor, RuntimeCallFor}; use pallet_balances::NegativeImbalance; @@ -66,12 +66,12 @@ use sp_api::impl_runtime_apis; use sp_consensus_slots::{Slot, SlotDuration}; use sp_consensus_subspace::{ChainConstants, PotParameters, SignedVote, SolutionRanges, Vote}; use sp_core::crypto::KeyTypeId; -use sp_core::{OpaqueMetadata, H256}; +use sp_core::{H256, OpaqueMetadata}; use sp_domains::bundle_producer_election::BundleProducerElectionParams; use sp_domains::{ - DomainAllowlistUpdates, DomainId, DomainInstanceData, ExecutionReceiptFor, OpaqueBundle, - OpaqueBundles, OperatorId, OperatorPublicKey, OperatorRewardSource, - PermissionedActionAllowedBy, DOMAIN_STORAGE_FEE_MULTIPLIER, INITIAL_DOMAIN_TX_RANGE, + DOMAIN_STORAGE_FEE_MULTIPLIER, DomainAllowlistUpdates, DomainId, DomainInstanceData, + ExecutionReceiptFor, INITIAL_DOMAIN_TX_RANGE, OpaqueBundle, OpaqueBundles, OperatorId, + OperatorPublicKey, OperatorRewardSource, PermissionedActionAllowedBy, }; use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_domains_fraud_proof::storage_proof::{ @@ -83,7 +83,7 @@ use sp_messenger::messages::{ CrossDomainMessage, MessageId, MessageKey, MessagesWithStorageKey, Nonce as XdmNonce, }; use sp_messenger::{ChannelNonce, XdmId}; -use sp_messenger_host_functions::{get_storage_key, StorageKeyRequest}; +use sp_messenger_host_functions::{StorageKeyRequest, get_storage_key}; use sp_mmr_primitives::EncodableOpaqueLeaf; use sp_runtime::traits::{ AccountIdConversion, AccountIdLookup, AsSystemOriginSigner, BlakeTwo256, ConstBool, @@ -96,8 +96,8 @@ use sp_runtime::transaction_validity::{ }; use sp_runtime::type_with_default::TypeWithDefault; use sp_runtime::{ - generic, impl_tx_ext_default, AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, - Perbill, + AccountId32, ApplyExtrinsicResult, ExtrinsicInclusionMode, Perbill, generic, + impl_tx_ext_default, }; use sp_std::collections::btree_map::BTreeMap; use sp_std::collections::btree_set::BTreeSet; @@ -112,15 +112,15 @@ use subspace_core_primitives::segments::{ HistorySize, SegmentCommitment, SegmentHeader, SegmentIndex, }; use subspace_core_primitives::solutions::SolutionRange; -use subspace_core_primitives::{hashes, PublicKey, Randomness, SlotNumber, U256}; +use subspace_core_primitives::{PublicKey, Randomness, SlotNumber, U256, hashes}; use subspace_runtime_primitives::utility::{ - nested_call_iter, DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall, + DefaultNonceProvider, MaybeMultisigCall, MaybeNestedCall, MaybeUtilityCall, nested_call_iter, }; use subspace_runtime_primitives::{ AccountId, Balance, BlockHashFor, BlockNumber, ConsensusEventSegmentSize, ExtrinsicFor, - FindBlockRewardAddress, Hash, HeaderFor, HoldIdentifier, Moment, Nonce, Signature, + FindBlockRewardAddress, Hash, HeaderFor, HoldIdentifier, MAX_BLOCK_LENGTH, + MAX_CALL_RECURSION_DEPTH, MIN_REPLICATION_FACTOR, Moment, Nonce, SHANNON, SSC, Signature, SlowAdjustingFeeUpdate, TargetBlockFullness, XdmAdjustedWeightToFee, XdmFeeMultipler, - MAX_BLOCK_LENGTH, MAX_CALL_RECURSION_DEPTH, MIN_REPLICATION_FACTOR, SHANNON, SSC, }; use subspace_test_primitives::DOMAINS_BLOCK_PRUNING_DEPTH; diff --git a/test/subspace-test-service/src/lib.rs b/test/subspace-test-service/src/lib.rs index 8c69842f86b..f77cf231bd8 100644 --- a/test/subspace-test-service/src/lib.rs +++ b/test/subspace-test-service/src/lib.rs @@ -18,7 +18,7 @@ #![warn(missing_docs, unused_crate_dependencies)] -use cross_domain_message_gossip::{xdm_gossip_peers_set_config, GossipWorkerBuilder}; +use cross_domain_message_gossip::{GossipWorkerBuilder, xdm_gossip_peers_set_config}; use domain_runtime_primitives::opaque::{Block as DomainBlock, Header as DomainHeader}; use frame_system::pallet_prelude::BlockNumberFor; use futures::channel::mpsc; @@ -37,7 +37,7 @@ use sc_domains::ExtensionsFactory as DomainsExtensionFactory; use sc_network::config::{NetworkConfiguration, TransportConfig}; use sc_network::service::traits::NetworkService; use sc_network::{ - multiaddr, NetworkWorker, NotificationMetrics, NotificationService, ReputationChange, + NetworkWorker, NotificationMetrics, NotificationService, ReputationChange, multiaddr, }; use sc_service::config::{ DatabaseSource, ExecutorConfiguration, KeystoreConfig, MultiaddrWithPeerId, @@ -50,19 +50,19 @@ use sc_service::{ use sc_transaction_pool::{BasicPool, FullChainApi, Options}; use sc_transaction_pool_api::error::{Error as TxPoolError, IntoPoolError}; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool, TransactionSource}; -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; +use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender, tracing_unbounded}; use sp_api::{ApiExt, ProvideRuntimeApi}; use sp_blockchain::{HashAndNumber, HeaderBackend}; use sp_consensus::{BlockOrigin, Error as ConsensusError}; use sp_consensus_slots::Slot; use sp_consensus_subspace::digests::{ - extract_pre_digest, CompatibleDigestItem, PreDigest, PreDigestPotInfo, + CompatibleDigestItem, PreDigest, PreDigestPotInfo, extract_pre_digest, }; use sp_consensus_subspace::{PotExtension, SubspaceApi}; -use sp_core::offchain::storage::OffchainDb; +use sp_core::H256; use sp_core::offchain::OffchainDbExt; +use sp_core::offchain::storage::OffchainDb; use sp_core::traits::{CodeExecutor, SpawnEssentialNamed}; -use sp_core::H256; use sp_domains::{BundleProducerElectionApi, ChainId, DomainsApi, OpaqueBundle}; use sp_domains_fraud_proof::fraud_proof::FraudProof; use sp_domains_fraud_proof::{FraudProofExtension, FraudProofHostFunctionsImpl}; @@ -76,7 +76,7 @@ use sp_runtime::generic::{Digest, SignedPayload}; use sp_runtime::traits::{ BlakeTwo256, Block as BlockT, Hash as HashT, Header as HeaderT, NumberFor, }; -use sp_runtime::{generic, DigestItem, MultiAddress, OpaqueExtrinsic, SaturatedConversion}; +use sp_runtime::{DigestItem, MultiAddress, OpaqueExtrinsic, SaturatedConversion, generic}; use sp_subspace_mmr::host_functions::{SubspaceMmrExtension, SubspaceMmrHostFunctionsImpl}; use sp_timestamp::Timestamp; use std::collections::HashMap; @@ -94,11 +94,11 @@ use subspace_runtime_primitives::{ AccountId, Balance, BlockHashFor, ExtrinsicFor, Hash, HeaderFor, Signature, }; use subspace_service::{FullSelectChain, RuntimeExecutor}; -use subspace_test_client::{chain_spec, Backend, Client}; +use subspace_test_client::{Backend, Client, chain_spec}; use subspace_test_primitives::OnchainStateApi; use subspace_test_runtime::{ - DisablePallets, Runtime, RuntimeApi, RuntimeCall, SignedExtra, UncheckedExtrinsic, - SLOT_DURATION, + DisablePallets, Runtime, RuntimeApi, RuntimeCall, SLOT_DURATION, SignedExtra, + UncheckedExtrinsic, }; use substrate_frame_rpc_system::AccountNonceApi; use substrate_test_client::{RpcHandlersExt, RpcTransactionError, RpcTransactionOutput}; @@ -698,7 +698,9 @@ impl MockConsensusNode { return (slot, bundle); } } - panic!("Failed to produce bundle after {MAX_PRODUCE_BUNDLE_TRY:?} tries, something must be wrong"); + panic!( + "Failed to produce bundle after {MAX_PRODUCE_BUNDLE_TRY:?} tries, something must be wrong" + ); } /// Subscribe the new slot notification @@ -782,9 +784,10 @@ impl MockConsensusNode { .expect("should be able to decode"); if let RuntimeCall::Domains(pallet_domains::Call::submit_bundle { opaque_bundle }) = ext.function - && opaque_bundle.sealed_header.slot_number() == *new_slot.0 { - return Some(opaque_bundle); - } + && opaque_bundle.sealed_header.slot_number() == *new_slot.0 + { + return Some(opaque_bundle); + } } None } @@ -876,9 +879,10 @@ impl MockConsensusNode { if let subspace_test_runtime::RuntimeCall::Domains( pallet_domains::Call::submit_fraud_proof { fraud_proof }, ) = ext.function - && fraud_proof_predicate(&fraud_proof) { - return *fraud_proof; - } + && fraud_proof_predicate(&fraud_proof) + { + return *fraud_proof; + } } unreachable!() }) @@ -1195,7 +1199,8 @@ fn log_new_block(block: &Block, used_time_ms: u128) { block.header().hash(), block.header().parent_hash(), block.extrinsics().len(), - block.extrinsics() + block + .extrinsics() .iter() .map(|xt| BlakeTwo256::hash_of(xt).to_string()) .collect::>() From ad37d83ee59daf073b3de0bdea18c0aa97280c00 Mon Sep 17 00:00:00 2001 From: tediou5 Date: Fri, 16 May 2025 18:52:31 +0800 Subject: [PATCH 12/15] feat: remove let_chains feature --- crates/pallet-domains/src/lib.rs | 2 +- crates/pallet-subspace/src/lib.rs | 2 +- crates/sc-consensus-subspace/src/lib.rs | 2 +- crates/sc-proof-of-time/src/lib.rs | 2 -- crates/sp-consensus-subspace/src/lib.rs | 1 - crates/subspace-farmer/src/lib.rs | 1 - crates/subspace-service/src/lib.rs | 1 - domains/client/block-builder/src/lib.rs | 1 - domains/client/block-preprocessor/src/lib.rs | 1 - domains/client/cross-domain-message-gossip/src/lib.rs | 1 - domains/client/domain-operator/src/lib.rs | 1 - domains/client/relayer/src/lib.rs | 1 - domains/pallets/messenger/src/lib.rs | 2 +- shared/subspace-data-retrieval/src/lib.rs | 2 +- 14 files changed, 5 insertions(+), 15 deletions(-) diff --git a/crates/pallet-domains/src/lib.rs b/crates/pallet-domains/src/lib.rs index 4790dc8ad01..de644741919 100644 --- a/crates/pallet-domains/src/lib.rs +++ b/crates/pallet-domains/src/lib.rs @@ -1,7 +1,7 @@ //! Pallet Domains #![cfg_attr(not(feature = "std"), no_std)] -#![feature(array_windows, let_chains, variant_count)] +#![feature(array_windows, variant_count)] #[cfg(feature = "runtime-benchmarks")] mod benchmarking; diff --git a/crates/pallet-subspace/src/lib.rs b/crates/pallet-subspace/src/lib.rs index 7062e747d74..3d12dba3880 100644 --- a/crates/pallet-subspace/src/lib.rs +++ b/crates/pallet-subspace/src/lib.rs @@ -1,6 +1,6 @@ #![doc = include_str!("../README.md")] #![cfg_attr(not(feature = "std"), no_std)] -#![feature(array_chunks, assert_matches, let_chains, portable_simd)] +#![feature(array_chunks, assert_matches, portable_simd)] #![warn(unused_must_use, unsafe_code, unused_variables)] #[cfg(not(feature = "std"))] diff --git a/crates/sc-consensus-subspace/src/lib.rs b/crates/sc-consensus-subspace/src/lib.rs index 8c763e8d79e..1b71d4e6542 100644 --- a/crates/sc-consensus-subspace/src/lib.rs +++ b/crates/sc-consensus-subspace/src/lib.rs @@ -6,7 +6,7 @@ //! //! All of the modules here are crucial for consensus, open each module for specific details. -#![feature(let_chains, try_blocks, duration_constructors_lite)] +#![feature(try_blocks, duration_constructors_lite)] #![forbid(unsafe_code)] #![warn(missing_docs)] diff --git a/crates/sc-proof-of-time/src/lib.rs b/crates/sc-proof-of-time/src/lib.rs index a982eb79236..27aa67bd1ac 100644 --- a/crates/sc-proof-of-time/src/lib.rs +++ b/crates/sc-proof-of-time/src/lib.rs @@ -1,7 +1,5 @@ //! Subspace proof of time implementation. -#![feature(let_chains)] - mod slots; pub mod source; pub mod verifier; diff --git a/crates/sp-consensus-subspace/src/lib.rs b/crates/sp-consensus-subspace/src/lib.rs index ba8e8fc6550..321b0dc92df 100644 --- a/crates/sp-consensus-subspace/src/lib.rs +++ b/crates/sp-consensus-subspace/src/lib.rs @@ -2,7 +2,6 @@ #![forbid(unsafe_code, missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] -#![feature(let_chains)] extern crate alloc; diff --git a/crates/subspace-farmer/src/lib.rs b/crates/subspace-farmer/src/lib.rs index 0591c255742..c706c347bb3 100644 --- a/crates/subspace-farmer/src/lib.rs +++ b/crates/subspace-farmer/src/lib.rs @@ -10,7 +10,6 @@ impl_trait_in_assoc_type, int_roundings, iter_collect_into, - let_chains, never_type, result_flattening, trait_alias, diff --git a/crates/subspace-service/src/lib.rs b/crates/subspace-service/src/lib.rs index 0e9c5685672..05c22ff160b 100644 --- a/crates/subspace-service/src/lib.rs +++ b/crates/subspace-service/src/lib.rs @@ -3,7 +3,6 @@ duration_constructors_lite, impl_trait_in_assoc_type, int_roundings, - let_chains, type_alias_impl_trait, type_changing_struct_update )] diff --git a/domains/client/block-builder/src/lib.rs b/domains/client/block-builder/src/lib.rs index 54ce02af240..626e5d8e583 100644 --- a/domains/client/block-builder/src/lib.rs +++ b/domains/client/block-builder/src/lib.rs @@ -25,7 +25,6 @@ //! initialize a block, to push extrinsics and to finalize a block. #![warn(missing_docs)] -#![feature(let_chains)] mod custom_api; mod genesis_block_builder; diff --git a/domains/client/block-preprocessor/src/lib.rs b/domains/client/block-preprocessor/src/lib.rs index 2cf274645bb..0abba42adf0 100644 --- a/domains/client/block-preprocessor/src/lib.rs +++ b/domains/client/block-preprocessor/src/lib.rs @@ -9,7 +9,6 @@ //! 5. Push back the potential new domain runtime extrisnic. #![warn(rust_2018_idioms)] -#![feature(let_chains)] pub mod inherents; pub mod stateless_runtime; diff --git a/domains/client/cross-domain-message-gossip/src/lib.rs b/domains/client/cross-domain-message-gossip/src/lib.rs index 5273e94db66..290999b16e0 100644 --- a/domains/client/cross-domain-message-gossip/src/lib.rs +++ b/domains/client/cross-domain-message-gossip/src/lib.rs @@ -1,4 +1,3 @@ -#![feature(let_chains)] #![warn(rust_2018_idioms)] mod aux_schema; diff --git a/domains/client/domain-operator/src/lib.rs b/domains/client/domain-operator/src/lib.rs index 5bfc6c9e093..c69e51b0292 100644 --- a/domains/client/domain-operator/src/lib.rs +++ b/domains/client/domain-operator/src/lib.rs @@ -63,7 +63,6 @@ assert_matches, box_into_inner, duration_constructors_lite, - let_chains, more_qualified_paths )] diff --git a/domains/client/relayer/src/lib.rs b/domains/client/relayer/src/lib.rs index a6761a0b868..1398b49900e 100644 --- a/domains/client/relayer/src/lib.rs +++ b/domains/client/relayer/src/lib.rs @@ -1,4 +1,3 @@ -#![feature(let_chains)] #![warn(rust_2018_idioms)] // TODO: Restore once https://github.com/rust-lang/rust/issues/122105 is resolved // #![deny(unused_crate_dependencies)] diff --git a/domains/pallets/messenger/src/lib.rs b/domains/pallets/messenger/src/lib.rs index 588e6eccd53..dcc13194db3 100644 --- a/domains/pallets/messenger/src/lib.rs +++ b/domains/pallets/messenger/src/lib.rs @@ -18,7 +18,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #![forbid(unsafe_code)] #![warn(rust_2018_idioms)] -#![feature(let_chains, variant_count, if_let_guard)] +#![feature(variant_count, if_let_guard)] #[cfg(feature = "runtime-benchmarks")] mod benchmarking; diff --git a/shared/subspace-data-retrieval/src/lib.rs b/shared/subspace-data-retrieval/src/lib.rs index 28b2a86d0eb..5a983f19b79 100644 --- a/shared/subspace-data-retrieval/src/lib.rs +++ b/shared/subspace-data-retrieval/src/lib.rs @@ -1,6 +1,6 @@ //! Fetching data from the archived history of the Subspace Distributed Storage Network. -#![feature(exact_size_is_empty, let_chains, trusted_len)] +#![feature(exact_size_is_empty, trusted_len)] pub mod object_fetcher; pub mod piece_fetcher; From 272b30bd4bec93664cc7d16fcced5ae3eb14d31a Mon Sep 17 00:00:00 2001 From: teor Date: Mon, 2 Jun 2025 13:59:25 +1000 Subject: [PATCH 13/15] Fix another slice::from_ref and some dead code --- crates/subspace-networking/src/node_runner.rs | 4 ++-- domains/pallets/messenger/src/mock.rs | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/subspace-networking/src/node_runner.rs b/crates/subspace-networking/src/node_runner.rs index 70efc8971f4..92872539104 100644 --- a/crates/subspace-networking/src/node_runner.rs +++ b/crates/subspace-networking/src/node_runner.rs @@ -34,12 +34,12 @@ use nohash_hasher::IntMap; use parking_lot::Mutex; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; -use std::fmt; use std::net::IpAddr; use std::pin::Pin; use std::sync::atomic::Ordering; use std::sync::{Arc, Weak}; use std::time::Duration; +use std::{fmt, slice}; use tokio::sync::OwnedSemaphorePermit; use tokio::task::yield_now; use tokio::time::Sleep; @@ -491,7 +491,7 @@ impl NodeRunner { } ref event @ SwarmEvent::ExpiredListenAddr { ref address, .. } => { trace!(?event, "Local listener expired event."); - self.handle_remove_listeners(std::slice::from_ref(address)); + self.handle_remove_listeners(slice::from_ref(address)); } SwarmEvent::ConnectionEstablished { peer_id, diff --git a/domains/pallets/messenger/src/mock.rs b/domains/pallets/messenger/src/mock.rs index 224a848ccf3..879cde7d6d1 100644 --- a/domains/pallets/messenger/src/mock.rs +++ b/domains/pallets/messenger/src/mock.rs @@ -211,6 +211,7 @@ macro_rules! impl_runtime { pub(crate) type MessageId = (ChannelId, Nonce); +#[allow(dead_code)] pub struct MockEndpoint {} impl EndpointHandler for MockEndpoint { @@ -309,12 +310,14 @@ pub(crate) fn storage_proof_of_domain_state_root( backend: InMemoryBackend, domain_id: DomainId, ) -> (StateRootOf, StorageKey, StorageProof) { + use core::slice; + let key = pallet_domains::LatestConfirmedDomainExecutionReceipt::::hashed_key_for(domain_id); let storage_key = StorageKey(key); let state_version = sp_runtime::StateVersion::default(); let root = backend.storage_root(std::iter::empty(), state_version).0; let proof = StorageProof::new( - prove_read(backend, &[storage_key.clone()]) + prove_read(backend, slice::from_ref(&storage_key)) .unwrap() .iter_nodes() .cloned(), From dc3b82ee87b496b85946ecd0a18adec182405602 Mon Sep 17 00:00:00 2001 From: teor Date: Mon, 2 Jun 2025 12:00:40 +1000 Subject: [PATCH 14/15] Remove extra newline in subspace-gateway/Cargo.toml --- crates/subspace-gateway/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/subspace-gateway/Cargo.toml b/crates/subspace-gateway/Cargo.toml index 34e77010da6..07bc7412eaf 100644 --- a/crates/subspace-gateway/Cargo.toml +++ b/crates/subspace-gateway/Cargo.toml @@ -42,4 +42,3 @@ subspace-rpc-primitives.workspace = true subspace-verification = { workspace = true, features = ["kzg"] } tokio = { workspace = true, features = ["rt-multi-thread", "signal", "macros"] } tracing.workspace = true - From 62e7ae5ac5625c3383326f4d81872c6ca32e25de Mon Sep 17 00:00:00 2001 From: teor Date: Mon, 2 Jun 2025 14:00:30 +1000 Subject: [PATCH 15/15] Use rustfmt 2024 edition --- rustfmt.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rustfmt.toml b/rustfmt.toml index c7e69dea017..ebd7dde759f 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,2 +1,2 @@ -edition = "2021" +edition = "2024" imports_granularity = "Module"