Bump clap to 4.0.x and adjust to best practices (#12381)

* Bump clap to 3.2.22

* Replace `from_os_str` with `value_parser`

* Replace `from_str` and `try_from_str` with `value_parser`

* Move possible_values to the new format

* Remove unwanted print

* Add missing match branch

* Update clap to 4.0.9 and make it compile

* Replace deprecated `clap` macro with `command` and `value`

* Move remaining `clap` attributes to `arg`

* Remove no-op value_parsers

* Adjust value_parser for state_version

* Remove "deprecated" feature flag and bump to 4.0.11

* Improve range

Co-authored-by: Bastian Köcher <git@kchr.de>

* Apply suggestions

* Trigger CI

* Fix unused error warning

* Fix doc errors

* Fix ArgGroup naming conflict

* Change default_value to default_value_t

* Use 1.. instead of 0..

Co-authored-by: Bastian Köcher <git@kchr.de>
This commit is contained in:
Sebastian Kunert
2022-10-18 08:52:46 +02:00
committed by GitHub
parent ca15fe7e3d
commit f687db40f7
70 changed files with 434 additions and 443 deletions
+26 -34
View File
@@ -908,7 +908,7 @@ name = "chain-spec-builder"
version = "2.0.0" version = "2.0.0"
dependencies = [ dependencies = [
"ansi_term", "ansi_term",
"clap 3.1.18", "clap 4.0.11",
"node-cli", "node-cli",
"rand 0.8.5", "rand 0.8.5",
"sc-chain-spec", "sc-chain-spec",
@@ -979,41 +979,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"textwrap 0.11.0", "textwrap",
"unicode-width", "unicode-width",
] ]
[[package]] [[package]]
name = "clap" name = "clap"
version = "3.1.18" version = "4.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b" checksum = "4ed45cc2c62a3eff523e718d8576ba762c83a3146151093283ac62ae11933a73"
dependencies = [ dependencies = [
"atty", "atty",
"bitflags", "bitflags",
"clap_derive", "clap_derive",
"clap_lex", "clap_lex",
"indexmap", "once_cell",
"lazy_static",
"strsim", "strsim",
"termcolor", "termcolor",
"textwrap 0.15.0",
] ]
[[package]] [[package]]
name = "clap_complete" name = "clap_complete"
version = "3.0.2" version = "4.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a394f7ec0715b42a4e52b294984c27c9a61f77c8d82f7774c5198350be143f19" checksum = "11cba7abac9b56dfe2f035098cdb3a43946f276e6db83b72c4e692343f9aab9a"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
] ]
[[package]] [[package]]
name = "clap_derive" name = "clap_derive"
version = "3.1.18" version = "4.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "25320346e922cffe59c0bbc5410c8d8784509efb321488971081313cb1e1a33c" checksum = "db342ce9fda24fb191e2ed4e102055a4d381c1086a06630174cd8da8d5d917ce"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro-error", "proc-macro-error",
@@ -1024,9 +1022,9 @@ dependencies = [
[[package]] [[package]]
name = "clap_lex" name = "clap_lex"
version = "0.2.0" version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213" checksum = "0d4198f73e42b4936b35b5bb248d81d2b595ecb170da0bac7655c54eedfa8da8"
dependencies = [ dependencies = [
"os_str_bytes", "os_str_bytes",
] ]
@@ -2127,7 +2125,7 @@ dependencies = [
"Inflector", "Inflector",
"array-bytes", "array-bytes",
"chrono", "chrono",
"clap 3.1.18", "clap 4.0.11",
"comfy-table", "comfy-table",
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
@@ -2208,7 +2206,7 @@ dependencies = [
name = "frame-election-solution-type-fuzzer" name = "frame-election-solution-type-fuzzer"
version = "2.0.0-alpha.5" version = "2.0.0-alpha.5"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"frame-election-provider-solution-type", "frame-election-provider-solution-type",
"frame-election-provider-support", "frame-election-provider-support",
"frame-support", "frame-support",
@@ -4441,7 +4439,7 @@ name = "node-bench"
version = "0.9.0-dev" version = "0.9.0-dev"
dependencies = [ dependencies = [
"array-bytes", "array-bytes",
"clap 3.1.18", "clap 4.0.11",
"derive_more", "derive_more",
"fs_extra", "fs_extra",
"futures", "futures",
@@ -4480,7 +4478,7 @@ dependencies = [
"array-bytes", "array-bytes",
"assert_cmd", "assert_cmd",
"async-std", "async-std",
"clap 3.1.18", "clap 4.0.11",
"clap_complete", "clap_complete",
"criterion", "criterion",
"frame-benchmarking-cli", "frame-benchmarking-cli",
@@ -4597,7 +4595,7 @@ dependencies = [
name = "node-inspect" name = "node-inspect"
version = "0.9.0-dev" version = "0.9.0-dev"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"parity-scale-codec", "parity-scale-codec",
"sc-cli", "sc-cli",
"sc-client-api", "sc-client-api",
@@ -4656,7 +4654,7 @@ dependencies = [
name = "node-runtime-generate-bags" name = "node-runtime-generate-bags"
version = "3.0.0" version = "3.0.0"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"generate-bags", "generate-bags",
"kitchensink-runtime", "kitchensink-runtime",
] ]
@@ -4665,7 +4663,7 @@ dependencies = [
name = "node-template" name = "node-template"
version = "4.0.0-dev" version = "4.0.0-dev"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"frame-benchmarking", "frame-benchmarking",
"frame-benchmarking-cli", "frame-benchmarking-cli",
"frame-system", "frame-system",
@@ -6855,9 +6853,9 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.39" version = "1.0.46"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" checksum = "94e2ef8dbfc347b10c094890f778ee2e36ca9bb4262e86dc99cd217e35f3470b"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
@@ -7653,7 +7651,7 @@ version = "0.10.0-dev"
dependencies = [ dependencies = [
"array-bytes", "array-bytes",
"chrono", "chrono",
"clap 3.1.18", "clap 4.0.11",
"fdlimit", "fdlimit",
"futures", "futures",
"libp2p", "libp2p",
@@ -9762,7 +9760,7 @@ dependencies = [
name = "sp-npos-elections-fuzzer" name = "sp-npos-elections-fuzzer"
version = "2.0.0-alpha.5" version = "2.0.0-alpha.5"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"honggfuzz", "honggfuzz",
"parity-scale-codec", "parity-scale-codec",
"rand 0.8.5", "rand 0.8.5",
@@ -10259,7 +10257,7 @@ dependencies = [
name = "subkey" name = "subkey"
version = "2.0.2" version = "2.0.2"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"sc-cli", "sc-cli",
] ]
@@ -10287,7 +10285,7 @@ dependencies = [
name = "substrate-frame-cli" name = "substrate-frame-cli"
version = "4.0.0-dev" version = "4.0.0-dev"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"frame-support", "frame-support",
"frame-system", "frame-system",
"sc-cli", "sc-cli",
@@ -10617,12 +10615,6 @@ dependencies = [
"unicode-width", "unicode-width",
] ]
[[package]]
name = "textwrap"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.30" version = "1.0.30"
@@ -11033,7 +11025,7 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
name = "try-runtime-cli" name = "try-runtime-cli"
version = "0.10.0-dev" version = "0.10.0-dev"
dependencies = [ dependencies = [
"clap 3.1.18", "clap 4.0.11",
"frame-try-runtime", "frame-try-runtime",
"jsonrpsee", "jsonrpsee",
"log", "log",
+1 -1
View File
@@ -17,7 +17,7 @@ targets = ["x86_64-unknown-linux-gnu"]
name = "node-template" name = "node-template"
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", features = ["wasmtime"] } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", features = ["wasmtime"] }
sp-core = { version = "6.0.0", path = "../../../primitives/core" } sp-core = { version = "6.0.0", path = "../../../primitives/core" }
+3 -3
View File
@@ -2,7 +2,7 @@ use sc_cli::RunCmd;
#[derive(Debug, clap::Parser)] #[derive(Debug, clap::Parser)]
pub struct Cli { pub struct Cli {
#[clap(subcommand)] #[command(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[clap(flatten)] #[clap(flatten)]
@@ -12,7 +12,7 @@ pub struct Cli {
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]
pub enum Subcommand { pub enum Subcommand {
/// Key management cli utilities /// Key management cli utilities
#[clap(subcommand)] #[command(subcommand)]
Key(sc_cli::KeySubcommand), Key(sc_cli::KeySubcommand),
/// Build a chain specification. /// Build a chain specification.
@@ -37,7 +37,7 @@ pub enum Subcommand {
Revert(sc_cli::RevertCmd), Revert(sc_cli::RevertCmd),
/// Sub-commands concerned with benchmarking. /// Sub-commands concerned with benchmarking.
#[clap(subcommand)] #[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Try some command against runtime state. /// Try some command against runtime state.
+1 -1
View File
@@ -12,7 +12,7 @@ repository = "https://github.com/paritytech/substrate/"
[dependencies] [dependencies]
array-bytes = "4.1" array-bytes = "4.1"
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
log = "0.4.17" log = "0.4.17"
node-primitives = { version = "2.0.0", path = "../primitives" } node-primitives = { version = "2.0.0", path = "../primitives" }
node-testing = { version = "3.0.0-dev", path = "../testing" } node-testing = { version = "3.0.0-dev", path = "../testing" }
+5 -5
View File
@@ -43,18 +43,18 @@ use crate::{
}; };
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(name = "node-bench", about = "Node integration benchmarks")] #[command(name = "node-bench", about = "Node integration benchmarks")]
struct Opt { struct Opt {
/// Show list of all available benchmarks. /// Show list of all available benchmarks.
/// ///
/// Will output ("name", "path"). Benchmarks can then be filtered by path. /// Will output ("name", "path"). Benchmarks can then be filtered by path.
#[clap(short, long)] #[arg(short, long)]
list: bool, list: bool,
/// Machine readable json output. /// Machine readable json output.
/// ///
/// This also suppresses all regular output (except to stderr) /// This also suppresses all regular output (except to stderr)
#[clap(short, long)] #[arg(short, long)]
json: bool, json: bool,
/// Filter benchmarks. /// Filter benchmarks.
@@ -63,7 +63,7 @@ struct Opt {
filter: Option<String>, filter: Option<String>,
/// Number of transactions for block import with `custom` size. /// Number of transactions for block import with `custom` size.
#[clap(long)] #[arg(long)]
transactions: Option<usize>, transactions: Option<usize>,
/// Mode /// Mode
@@ -72,7 +72,7 @@ struct Opt {
/// ///
/// "profile" mode adds pauses between measurable runs, /// "profile" mode adds pauses between measurable runs,
/// so that actual interval can be selected in the profiler of choice. /// so that actual interval can be selected in the profiler of choice.
#[clap(short, long, default_value = "regular")] #[arg(short, long, default_value = "regular")]
mode: BenchmarkMode, mode: BenchmarkMode,
} }
+3 -3
View File
@@ -35,7 +35,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
# third-party dependencies # third-party dependencies
array-bytes = "4.1" array-bytes = "4.1"
clap = { version = "3.1.18", features = ["derive"], optional = true } clap = { version = "4.0.9", features = ["derive"], optional = true }
codec = { package = "parity-scale-codec", version = "3.0.0" } codec = { package = "parity-scale-codec", version = "3.0.0" }
serde = { version = "1.0.136", features = ["derive"] } serde = { version = "1.0.136", features = ["derive"] }
jsonrpsee = { version = "0.15.1", features = ["server"] } jsonrpsee = { version = "0.15.1", features = ["server"] }
@@ -136,8 +136,8 @@ remote-externalities = { path = "../../../utils/frame/remote-externalities" }
pallet-timestamp = { version = "4.0.0-dev", path = "../../../frame/timestamp" } pallet-timestamp = { version = "4.0.0-dev", path = "../../../frame/timestamp" }
[build-dependencies] [build-dependencies]
clap = { version = "3.1.18", optional = true } clap = { version = "4.0.9", optional = true }
clap_complete = { version = "3.0", optional = true } clap_complete = { version = "4.0.2", optional = true }
node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" } node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" }
frame-benchmarking-cli = { version = "4.0.0-dev", optional = true, path = "../../../utils/frame/benchmarking-cli" } frame-benchmarking-cli = { version = "4.0.0-dev", optional = true, path = "../../../utils/frame/benchmarking-cli" }
substrate-build-script-utils = { version = "3.0.0", optional = true, path = "../../../utils/build-script-utils" } substrate-build-script-utils = { version = "3.0.0", optional = true, path = "../../../utils/build-script-utils" }
+1 -1
View File
@@ -25,7 +25,7 @@ fn main() {
mod cli { mod cli {
include!("src/cli.rs"); include!("src/cli.rs");
use clap::{ArgEnum, CommandFactory}; use clap::{CommandFactory, ValueEnum};
use clap_complete::{generate_to, Shell}; use clap_complete::{generate_to, Shell};
use std::{env, fs, path::Path}; use std::{env, fs, path::Path};
use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed}; use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};
+5 -5
View File
@@ -20,7 +20,7 @@
#[derive(Debug, clap::Parser)] #[derive(Debug, clap::Parser)]
pub struct Cli { pub struct Cli {
/// Possible subcommand with parameters. /// Possible subcommand with parameters.
#[clap(subcommand)] #[command(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -34,7 +34,7 @@ pub struct Cli {
/// ///
/// The results are then printed out in the logs, and also sent as part of /// The results are then printed out in the logs, and also sent as part of
/// telemetry, if telemetry is enabled. /// telemetry, if telemetry is enabled.
#[clap(long)] #[arg(long)]
pub no_hardware_benchmarks: bool, pub no_hardware_benchmarks: bool,
} }
@@ -42,7 +42,7 @@ pub struct Cli {
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]
pub enum Subcommand { pub enum Subcommand {
/// The custom inspect subcommmand for decoding blocks and extrinsics. /// The custom inspect subcommmand for decoding blocks and extrinsics.
#[clap( #[command(
name = "inspect", name = "inspect",
about = "Decode given block or extrinsic using current native runtime." about = "Decode given block or extrinsic using current native runtime."
)] )]
@@ -50,7 +50,7 @@ pub enum Subcommand {
/// Sub-commands concerned with benchmarking. /// Sub-commands concerned with benchmarking.
/// The pallet benchmarking moved to the `pallet` sub-command. /// The pallet benchmarking moved to the `pallet` sub-command.
#[clap(subcommand)] #[command(subcommand)]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Try some command against runtime state. /// Try some command against runtime state.
@@ -62,7 +62,7 @@ pub enum Subcommand {
TryRuntime, TryRuntime,
/// Key management cli utilities /// Key management cli utilities
#[clap(subcommand)] #[command(subcommand)]
Key(sc_cli::KeySubcommand), Key(sc_cli::KeySubcommand),
/// Verify a signature for a message, provided on STDIN, with a given (public or secret) key. /// Verify a signature for a message, provided on STDIN, with a given (public or secret) key.
+1 -1
View File
@@ -12,7 +12,7 @@ repository = "https://github.com/paritytech/substrate/"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.1.6", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0" } codec = { package = "parity-scale-codec", version = "3.0.0" }
thiserror = "1.0" thiserror = "1.0"
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
+2 -2
View File
@@ -46,7 +46,7 @@ pub enum InspectSubCmd {
/// Can be either a block hash (no 0x prefix) or a number to retrieve existing block, /// Can be either a block hash (no 0x prefix) or a number to retrieve existing block,
/// or a 0x-prefixed bytes hex string, representing SCALE encoding of /// or a 0x-prefixed bytes hex string, representing SCALE encoding of
/// a block. /// a block.
#[clap(value_name = "HASH or NUMBER or BYTES")] #[arg(value_name = "HASH or NUMBER or BYTES")]
input: String, input: String,
}, },
/// Decode extrinsic with native version of runtime and print out the details. /// Decode extrinsic with native version of runtime and print out the details.
@@ -56,7 +56,7 @@ pub enum InspectSubCmd {
/// Can be either a block hash (no 0x prefix) or number and the index, in the form /// Can be either a block hash (no 0x prefix) or number and the index, in the form
/// of `{block}:{index}` or a 0x-prefixed bytes hex string, /// of `{block}:{index}` or a 0x-prefixed bytes hex string,
/// representing SCALE encoding of an extrinsic. /// representing SCALE encoding of an extrinsic.
#[clap(value_name = "BLOCK:INDEX or BYTES")] #[arg(value_name = "BLOCK:INDEX or BYTES")]
input: String, input: String,
}, },
} }
@@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
ansi_term = "0.12.1" ansi_term = "0.12.1"
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
rand = "0.8" rand = "0.8"
node-cli = { version = "3.0.0-dev", path = "../../node/cli" } node-cli = { version = "3.0.0-dev", path = "../../node/cli" }
sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" }
@@ -37,51 +37,51 @@ use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
/// A utility to easily create a testnet chain spec definition with a given set /// A utility to easily create a testnet chain spec definition with a given set
/// of authorities and endowed accounts and/or generate random accounts. /// of authorities and endowed accounts and/or generate random accounts.
#[derive(Parser)] #[derive(Parser)]
#[clap(rename_all = "kebab-case")] #[command(rename_all = "kebab-case")]
enum ChainSpecBuilder { enum ChainSpecBuilder {
/// Create a new chain spec with the given authorities, endowed and sudo /// Create a new chain spec with the given authorities, endowed and sudo
/// accounts. /// accounts.
New { New {
/// Authority key seed. /// Authority key seed.
#[clap(long, short, required = true)] #[arg(long, short, required = true)]
authority_seeds: Vec<String>, authority_seeds: Vec<String>,
/// Active nominators (SS58 format), each backing a random subset of the aforementioned /// Active nominators (SS58 format), each backing a random subset of the aforementioned
/// authorities. /// authorities.
#[clap(long, short, default_value = "0")] #[arg(long, short, default_value = "0")]
nominator_accounts: Vec<String>, nominator_accounts: Vec<String>,
/// Endowed account address (SS58 format). /// Endowed account address (SS58 format).
#[clap(long, short)] #[arg(long, short)]
endowed_accounts: Vec<String>, endowed_accounts: Vec<String>,
/// Sudo account address (SS58 format). /// Sudo account address (SS58 format).
#[clap(long, short)] #[arg(long, short)]
sudo_account: String, sudo_account: String,
/// The path where the chain spec should be saved. /// The path where the chain spec should be saved.
#[clap(long, short, default_value = "./chain_spec.json")] #[arg(long, short, default_value = "./chain_spec.json")]
chain_spec_path: PathBuf, chain_spec_path: PathBuf,
}, },
/// Create a new chain spec with the given number of authorities and endowed /// Create a new chain spec with the given number of authorities and endowed
/// accounts. Random keys will be generated as required. /// accounts. Random keys will be generated as required.
Generate { Generate {
/// The number of authorities. /// The number of authorities.
#[clap(long, short)] #[arg(long, short)]
authorities: usize, authorities: usize,
/// The number of nominators backing the aforementioned authorities. /// The number of nominators backing the aforementioned authorities.
/// ///
/// Will nominate a random subset of `authorities`. /// Will nominate a random subset of `authorities`.
#[clap(long, short, default_value = "0")] #[arg(long, short, default_value_t = 0)]
nominators: usize, nominators: usize,
/// The number of endowed accounts. /// The number of endowed accounts.
#[clap(long, short, default_value = "0")] #[arg(long, short, default_value_t = 0)]
endowed: usize, endowed: usize,
/// The path where the chain spec should be saved. /// The path where the chain spec should be saved.
#[clap(long, short, default_value = "./chain_spec.json")] #[arg(long, short, default_value = "./chain_spec.json")]
chain_spec_path: PathBuf, chain_spec_path: PathBuf,
/// Path to use when saving generated keystores for each authority. /// Path to use when saving generated keystores for each authority.
/// ///
/// At this path, a new folder will be created for each authority's /// At this path, a new folder will be created for each authority's
/// keystore named `auth-$i` where `i` is the authority index, i.e. /// keystore named `auth-$i` where `i` is the authority index, i.e.
/// `auth-0`, `auth-1`, etc. /// `auth-0`, `auth-1`, etc.
#[clap(long, short)] #[arg(long, short)]
keystore_path: Option<PathBuf>, keystore_path: Option<PathBuf>,
}, },
} }
+1 -1
View File
@@ -17,5 +17,5 @@ path = "src/main.rs"
name = "subkey" name = "subkey"
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
+1 -1
View File
@@ -23,7 +23,7 @@ use sc_cli::{
}; };
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[command(
name = "subkey", name = "subkey",
author = "Parity Team <admin@parity.io>", author = "Parity Team <admin@parity.io>",
about = "Utility for generating and restoring with Substrate keys", about = "Utility for generating and restoring with Substrate keys",
+1 -1
View File
@@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
array-bytes = "4.1" array-bytes = "4.1"
chrono = "0.4.10" chrono = "0.4.10"
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive", "string"] }
fdlimit = "0.2.1" fdlimit = "0.2.1"
futures = "0.3.21" futures = "0.3.21"
libp2p = "0.49.0" libp2p = "0.49.0"
+57 -63
View File
@@ -16,13 +16,13 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
//! Definitions of [`ArgEnum`] types. //! Definitions of [`ValueEnum`] types.
use clap::ArgEnum; use clap::{builder::PossibleValue, ValueEnum};
/// The instantiation strategy to use in compiled mode. /// The instantiation strategy to use in compiled mode.
#[derive(Debug, Clone, Copy, ArgEnum)] #[derive(Debug, Clone, Copy, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum WasmtimeInstantiationStrategy { pub enum WasmtimeInstantiationStrategy {
/// Pool the instances to avoid initializing everything from scratch /// Pool the instances to avoid initializing everything from scratch
/// on each instantiation. Use copy-on-write memory when possible. /// on each instantiation. Use copy-on-write memory when possible.
@@ -59,20 +59,22 @@ pub enum WasmExecutionMethod {
Compiled, Compiled,
} }
impl std::fmt::Display for WasmExecutionMethod { const INTERPRETED_NAME: &str = "interpreted-i-know-what-i-do";
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { impl clap::ValueEnum for WasmExecutionMethod {
Self::Interpreted => write!(f, "Interpreted"), /// All possible argument values, in display order.
Self::Compiled => write!(f, "Compiled"), fn value_variants<'a>() -> &'a [Self] {
let variants = &[Self::Interpreted, Self::Compiled];
if cfg!(feature = "wasmtime") {
variants
} else {
&variants[..1]
} }
} }
}
impl std::str::FromStr for WasmExecutionMethod { /// Parse an argument into `Self`.
type Err = String; fn from_str(s: &str, _: bool) -> Result<Self, String> {
if s.eq_ignore_ascii_case(INTERPRETED_NAME) {
fn from_str(s: &str) -> Result<Self, String> {
if s.eq_ignore_ascii_case("interpreted-i-know-what-i-do") {
Ok(Self::Interpreted) Ok(Self::Interpreted)
} else if s.eq_ignore_ascii_case("compiled") { } else if s.eq_ignore_ascii_case("compiled") {
#[cfg(feature = "wasmtime")] #[cfg(feature = "wasmtime")]
@@ -84,19 +86,29 @@ impl std::str::FromStr for WasmExecutionMethod {
Err("`Compiled` variant requires the `wasmtime` feature to be enabled".into()) Err("`Compiled` variant requires the `wasmtime` feature to be enabled".into())
} }
} else { } else {
Err(format!("Unknown variant `{}`, known variants: {:?}", s, Self::variants())) Err(format!("Unknown variant `{}`", s))
}
}
/// The canonical argument value.
///
/// The value is `None` for skipped variants.
fn to_possible_value(&self) -> Option<PossibleValue> {
match self {
#[cfg(feature = "wasmtime")]
WasmExecutionMethod::Compiled => Some(PossibleValue::new("compiled")),
#[cfg(not(feature = "wasmtime"))]
WasmExecutionMethod::Compiled => None,
WasmExecutionMethod::Interpreted => Some(PossibleValue::new(INTERPRETED_NAME)),
} }
} }
} }
impl WasmExecutionMethod { impl std::fmt::Display for WasmExecutionMethod {
/// Returns all the variants of this enum to be shown in the cli. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
pub fn variants() -> &'static [&'static str] { match self {
let variants = &["interpreted-i-know-what-i-do", "compiled"]; Self::Interpreted => write!(f, "Interpreted"),
if cfg!(feature = "wasmtime") { Self::Compiled => write!(f, "Compiled"),
variants
} else {
&variants[..1]
} }
} }
} }
@@ -133,15 +145,15 @@ pub fn execution_method_from_cli(
/// The default [`WasmExecutionMethod`]. /// The default [`WasmExecutionMethod`].
#[cfg(feature = "wasmtime")] #[cfg(feature = "wasmtime")]
pub const DEFAULT_WASM_EXECUTION_METHOD: &str = "compiled"; pub const DEFAULT_WASM_EXECUTION_METHOD: WasmExecutionMethod = WasmExecutionMethod::Compiled;
/// The default [`WasmExecutionMethod`]. /// The default [`WasmExecutionMethod`].
#[cfg(not(feature = "wasmtime"))] #[cfg(not(feature = "wasmtime"))]
pub const DEFAULT_WASM_EXECUTION_METHOD: &str = "interpreted-i-know-what-i-do"; pub const DEFAULT_WASM_EXECUTION_METHOD: WasmExecutionMethod = WasmExecutionMethod::Interpreted;
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum TracingReceiver { pub enum TracingReceiver {
/// Output the tracing records using the log. /// Output the tracing records using the log.
Log, Log,
@@ -156,16 +168,16 @@ impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
} }
/// The type of the node key. /// The type of the node key.
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum NodeKeyType { pub enum NodeKeyType {
/// Use ed25519. /// Use ed25519.
Ed25519, Ed25519,
} }
/// The crypto scheme to use. /// The crypto scheme to use.
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum CryptoScheme { pub enum CryptoScheme {
/// Use ed25519. /// Use ed25519.
Ed25519, Ed25519,
@@ -176,8 +188,8 @@ pub enum CryptoScheme {
} }
/// The type of the output format. /// The type of the output format.
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum OutputType { pub enum OutputType {
/// Output as json. /// Output as json.
Json, Json,
@@ -186,8 +198,8 @@ pub enum OutputType {
} }
/// How to execute blocks /// How to execute blocks
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum ExecutionStrategy { pub enum ExecutionStrategy {
/// Execute with native build (if available, WebAssembly otherwise). /// Execute with native build (if available, WebAssembly otherwise).
Native, Native,
@@ -212,8 +224,8 @@ impl Into<sc_client_api::ExecutionStrategy> for ExecutionStrategy {
/// Available RPC methods. /// Available RPC methods.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, ArgEnum)] #[derive(Debug, Copy, Clone, PartialEq, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum RpcMethods { pub enum RpcMethods {
/// Expose every RPC method only when RPC is listening on `localhost`, /// Expose every RPC method only when RPC is listening on `localhost`,
/// otherwise serve only safe RPC methods. /// otherwise serve only safe RPC methods.
@@ -235,7 +247,8 @@ impl Into<sc_service::config::RpcMethods> for RpcMethods {
} }
/// Database backend /// Database backend
#[derive(Debug, Clone, PartialEq, Copy)] #[derive(Debug, Clone, PartialEq, Copy, clap::ValueEnum)]
#[value(rename_all = "lower")]
pub enum Database { pub enum Database {
/// Facebooks RocksDB /// Facebooks RocksDB
#[cfg(feature = "rocksdb")] #[cfg(feature = "rocksdb")]
@@ -246,29 +259,10 @@ pub enum Database {
/// instance of ParityDb /// instance of ParityDb
Auto, Auto,
/// ParityDb. <https://github.com/paritytech/parity-db/> /// ParityDb. <https://github.com/paritytech/parity-db/>
#[value(name = "paritydb-experimental")]
ParityDbDeprecated, ParityDbDeprecated,
} }
impl std::str::FromStr for Database {
type Err = String;
fn from_str(s: &str) -> Result<Self, String> {
#[cfg(feature = "rocksdb")]
if s.eq_ignore_ascii_case("rocksdb") {
return Ok(Self::RocksDb)
}
if s.eq_ignore_ascii_case("paritydb-experimental") {
return Ok(Self::ParityDbDeprecated)
} else if s.eq_ignore_ascii_case("paritydb") {
return Ok(Self::ParityDb)
} else if s.eq_ignore_ascii_case("auto") {
Ok(Self::Auto)
} else {
Err(format!("Unknown variant `{}`, known variants: {:?}", s, Self::variants()))
}
}
}
impl Database { impl Database {
/// Returns all the variants of this enum to be shown in the cli. /// Returns all the variants of this enum to be shown in the cli.
pub const fn variants() -> &'static [&'static str] { pub const fn variants() -> &'static [&'static str] {
@@ -284,8 +278,8 @@ impl Database {
/// Whether off-chain workers are enabled. /// Whether off-chain workers are enabled.
#[allow(missing_docs)] #[allow(missing_docs)]
#[derive(Debug, Clone, ArgEnum)] #[derive(Debug, Clone, ValueEnum)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum OffchainWorkerEnabled { pub enum OffchainWorkerEnabled {
/// Always have offchain worker enabled. /// Always have offchain worker enabled.
Always, Always,
@@ -296,8 +290,8 @@ pub enum OffchainWorkerEnabled {
} }
/// Syncing mode. /// Syncing mode.
#[derive(Debug, Clone, Copy, ArgEnum, PartialEq)] #[derive(Debug, Clone, Copy, ValueEnum, PartialEq)]
#[clap(rename_all = "kebab-case")] #[value(rename_all = "kebab-case")]
pub enum SyncMode { pub enum SyncMode {
/// Full sync. Download end verify all blocks. /// Full sync. Download end verify all blocks.
Full, Full,
@@ -34,14 +34,14 @@ use std::io::Write;
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
pub struct BuildSpecCmd { pub struct BuildSpecCmd {
/// Force raw genesis storage output. /// Force raw genesis storage output.
#[clap(long)] #[arg(long)]
pub raw: bool, pub raw: bool,
/// Disable adding the default bootnode to the specification. /// Disable adding the default bootnode to the specification.
/// ///
/// By default the `/ip4/127.0.0.1/tcp/30333/p2p/NODE_PEER_ID` bootnode is added to the /// By default the `/ip4/127.0.0.1/tcp/30333/p2p/NODE_PEER_ID` bootnode is added to the
/// specification when no bootnode exists. /// specification when no bootnode exists.
#[clap(long)] #[arg(long)]
pub disable_default_bootnode: bool, pub disable_default_bootnode: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -30,13 +30,13 @@ use std::{fmt::Debug, str::FromStr, sync::Arc};
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
pub struct CheckBlockCmd { pub struct CheckBlockCmd {
/// Block hash or number /// Block hash or number
#[clap(value_name = "HASH or NUMBER")] #[arg(value_name = "HASH or NUMBER")]
pub input: BlockNumberOrHash, pub input: BlockNumberOrHash,
/// The default number of 64KB pages to ever allocate for Wasm execution. /// The default number of 64KB pages to ever allocate for Wasm execution.
/// ///
/// Don't alter this unless you know what you're doing. /// Don't alter this unless you know what you're doing.
#[clap(long, value_name = "COUNT")] #[arg(long, value_name = "COUNT")]
pub default_heap_pages: Option<u32>, pub default_heap_pages: Option<u32>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -32,23 +32,23 @@ use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc};
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
pub struct ExportBlocksCmd { pub struct ExportBlocksCmd {
/// Output file name or stdout if unspecified. /// Output file name or stdout if unspecified.
#[clap(parse(from_os_str))] #[arg()]
pub output: Option<PathBuf>, pub output: Option<PathBuf>,
/// Specify starting block number. /// Specify starting block number.
/// ///
/// Default is 1. /// Default is 1.
#[clap(long, value_name = "BLOCK")] #[arg(long, value_name = "BLOCK")]
pub from: Option<GenericNumber>, pub from: Option<GenericNumber>,
/// Specify last block number. /// Specify last block number.
/// ///
/// Default is best block. /// Default is best block.
#[clap(long, value_name = "BLOCK")] #[arg(long, value_name = "BLOCK")]
pub to: Option<GenericNumber>, pub to: Option<GenericNumber>,
/// Use binary output rather than JSON. /// Use binary output rather than JSON.
#[clap(long)] #[arg(long)]
pub binary: bool, pub binary: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -32,7 +32,7 @@ use std::{fmt::Debug, io::Write, str::FromStr, sync::Arc};
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
pub struct ExportStateCmd { pub struct ExportStateCmd {
/// Block hash or number. /// Block hash or number.
#[clap(value_name = "HASH or NUMBER")] #[arg(value_name = "HASH or NUMBER")]
pub input: Option<BlockNumberOrHash>, pub input: Option<BlockNumberOrHash>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -25,10 +25,10 @@ use clap::Parser;
/// The `generate` command /// The `generate` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[clap(name = "generate", about = "Generate a random account")] #[command(name = "generate", about = "Generate a random account")]
pub struct GenerateCmd { pub struct GenerateCmd {
/// The number of words in the phrase to generate. One of 12 (default), 15, 18, 21 and 24. /// The number of words in the phrase to generate. One of 12 (default), 15, 18, 21 and 24.
#[clap(short = 'w', long, value_name = "WORDS")] #[arg(short = 'w', long, value_name = "WORDS")]
words: Option<usize>, words: Option<usize>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -28,7 +28,7 @@ use std::{
/// The `generate-node-key` command /// The `generate-node-key` command
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[command(
name = "generate-node-key", name = "generate-node-key",
about = "Generate a random node key, write it to a file or stdout \ about = "Generate a random node key, write it to a file or stdout \
and write the corresponding peer-id to stderr" and write the corresponding peer-id to stderr"
@@ -37,13 +37,13 @@ pub struct GenerateNodeKeyCmd {
/// Name of file to save secret key to. /// Name of file to save secret key to.
/// ///
/// If not given, the secret key is printed to stdout. /// If not given, the secret key is printed to stdout.
#[clap(long)] #[arg(long)]
file: Option<PathBuf>, file: Option<PathBuf>,
/// The output is in raw binary format. /// The output is in raw binary format.
/// ///
/// If not given, the output is written as an hex encoded string. /// If not given, the output is written as an hex encoded string.
#[clap(long)] #[arg(long)]
bin: bool, bin: bool,
} }
@@ -37,17 +37,17 @@ use std::{
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct ImportBlocksCmd { pub struct ImportBlocksCmd {
/// Input file or stdin if unspecified. /// Input file or stdin if unspecified.
#[clap(parse(from_os_str))] #[arg()]
pub input: Option<PathBuf>, pub input: Option<PathBuf>,
/// The default number of 64KB pages to ever allocate for Wasm execution. /// The default number of 64KB pages to ever allocate for Wasm execution.
/// ///
/// Don't alter this unless you know what you're doing. /// Don't alter this unless you know what you're doing.
#[clap(long, value_name = "COUNT")] #[arg(long, value_name = "COUNT")]
pub default_heap_pages: Option<u32>, pub default_heap_pages: Option<u32>,
/// Try importing blocks from binary format rather than JSON. /// Try importing blocks from binary format rather than JSON.
#[clap(long)] #[arg(long)]
pub binary: bool, pub binary: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -29,16 +29,16 @@ use std::sync::Arc;
/// The `insert` command /// The `insert` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[clap(name = "insert", about = "Insert a key to the keystore of a node.")] #[command(name = "insert", about = "Insert a key to the keystore of a node.")]
pub struct InsertKeyCmd { pub struct InsertKeyCmd {
/// The secret key URI. /// The secret key URI.
/// If the value is a file, the file content is used as URI. /// If the value is a file, the file content is used as URI.
/// If not given, you will be prompted for the URI. /// If not given, you will be prompted for the URI.
#[clap(long)] #[arg(long)]
suri: Option<String>, suri: Option<String>,
/// Key type, examples: "gran", or "imon" /// Key type, examples: "gran", or "imon"
#[clap(long)] #[arg(long)]
key_type: String, key_type: String,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -50,7 +50,7 @@ pub struct InsertKeyCmd {
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
/// The cryptography scheme that should be used to generate the key out of the given URI. /// The cryptography scheme that should be used to generate the key out of the given URI.
#[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true)] #[arg(long, value_name = "SCHEME", value_enum, ignore_case = true)]
pub scheme: CryptoScheme, pub scheme: CryptoScheme,
} }
@@ -27,7 +27,7 @@ use std::str::FromStr;
/// The `inspect` command /// The `inspect` command
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[command(
name = "inspect", name = "inspect",
about = "Gets a public key and a SS58 address from the provided Secret URI" about = "Gets a public key and a SS58 address from the provided Secret URI"
)] )]
@@ -44,7 +44,7 @@ pub struct InspectKeyCmd {
uri: Option<String>, uri: Option<String>,
/// Is the given `uri` a hex encoded public key? /// Is the given `uri` a hex encoded public key?
#[clap(long)] #[arg(long)]
public: bool, public: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -72,7 +72,7 @@ pub struct InspectKeyCmd {
/// ///
/// If there is no derivation in `--uri`, the public key will be checked against the public key /// If there is no derivation in `--uri`, the public key will be checked against the public key
/// of `--uri` directly. /// of `--uri` directly.
#[clap(long, conflicts_with = "public")] #[arg(long, conflicts_with = "public")]
pub expect_public: Option<String>, pub expect_public: Option<String>,
} }
@@ -28,7 +28,7 @@ use std::{
/// The `inspect-node-key` command /// The `inspect-node-key` command
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap( #[command(
name = "inspect-node-key", name = "inspect-node-key",
about = "Load a node key from a file or stdin and print the corresponding peer-id." about = "Load a node key from a file or stdin and print the corresponding peer-id."
)] )]
@@ -36,18 +36,18 @@ pub struct InspectNodeKeyCmd {
/// Name of file to read the secret key from. /// Name of file to read the secret key from.
/// ///
/// If not given, the secret key is read from stdin (up to EOF). /// If not given, the secret key is read from stdin (up to EOF).
#[clap(long)] #[arg(long)]
file: Option<PathBuf>, file: Option<PathBuf>,
/// The input is in raw binary format. /// The input is in raw binary format.
/// ///
/// If not given, the input is read as an hex encoded string. /// If not given, the input is read as an hex encoded string.
#[clap(long)] #[arg(long)]
bin: bool, bin: bool,
/// This argument is deprecated and has no effect for this command. /// This argument is deprecated and has no effect for this command.
#[deprecated(note = "Network identifier is not used for node-key inspection")] #[deprecated(note = "Network identifier is not used for node-key inspection")]
#[clap(short = 'n', long = "network", value_name = "NETWORK", ignore_case = true)] #[arg(short = 'n', long = "network", value_name = "NETWORK", ignore_case = true)]
pub network_scheme: Option<String>, pub network_scheme: Option<String>,
} }
@@ -33,7 +33,7 @@ use std::{
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
pub struct PurgeChainCmd { pub struct PurgeChainCmd {
/// Skip interactive prompt by answering yes automatically. /// Skip interactive prompt by answering yes automatically.
#[clap(short = 'y')] #[arg(short = 'y')]
pub yes: bool, pub yes: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -31,7 +31,7 @@ use std::{fmt::Debug, str::FromStr, sync::Arc};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
pub struct RevertCmd { pub struct RevertCmd {
/// Number of blocks to revert. /// Number of blocks to revert.
#[clap(default_value = "256")] #[arg(default_value = "256")]
pub num: GenericNumber, pub num: GenericNumber,
#[allow(missing_docs)] #[allow(missing_docs)]
+40 -40
View File
@@ -42,12 +42,12 @@ pub struct RunCmd {
/// The node will be started with the authority role and actively /// The node will be started with the authority role and actively
/// participate in any consensus task that it can (e.g. depending on /// participate in any consensus task that it can (e.g. depending on
/// availability of local keys). /// availability of local keys).
#[clap(long)] #[arg(long)]
pub validator: bool, pub validator: bool,
/// Disable GRANDPA voter when running in validator mode, otherwise disable the GRANDPA /// Disable GRANDPA voter when running in validator mode, otherwise disable the GRANDPA
/// observer. /// observer.
#[clap(long)] #[arg(long)]
pub no_grandpa: bool, pub no_grandpa: bool,
/// Listen to all RPC interfaces. /// Listen to all RPC interfaces.
@@ -56,13 +56,13 @@ pub struct RunCmd {
/// proxy server to filter out dangerous methods. More details: /// proxy server to filter out dangerous methods. More details:
/// <https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs>. /// <https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs>.
/// Use `--unsafe-rpc-external` to suppress the warning if you understand the risks. /// Use `--unsafe-rpc-external` to suppress the warning if you understand the risks.
#[clap(long)] #[arg(long)]
pub rpc_external: bool, pub rpc_external: bool,
/// Listen to all RPC interfaces. /// Listen to all RPC interfaces.
/// ///
/// Same as `--rpc-external`. /// Same as `--rpc-external`.
#[clap(long)] #[arg(long)]
pub unsafe_rpc_external: bool, pub unsafe_rpc_external: bool,
/// RPC methods to expose. /// RPC methods to expose.
@@ -71,12 +71,12 @@ pub struct RunCmd {
/// - `safe`: Exposes only a safe subset of RPC methods, denying unsafe RPC methods. /// - `safe`: Exposes only a safe subset of RPC methods, denying unsafe RPC methods.
/// - `auto`: Acts as `safe` if RPC is served externally, e.g. when `--{rpc,ws}-external` is /// - `auto`: Acts as `safe` if RPC is served externally, e.g. when `--{rpc,ws}-external` is
/// passed, otherwise acts as `unsafe`. /// passed, otherwise acts as `unsafe`.
#[clap( #[arg(
long, long,
value_name = "METHOD SET", value_name = "METHOD SET",
arg_enum, value_enum,
ignore_case = true, ignore_case = true,
default_value = "auto", default_value_t = RpcMethods::Auto,
verbatim_doc_comment verbatim_doc_comment
)] )]
pub rpc_methods: RpcMethods, pub rpc_methods: RpcMethods,
@@ -87,59 +87,59 @@ pub struct RunCmd {
/// proxy server to filter out dangerous methods. More details: /// proxy server to filter out dangerous methods. More details:
/// <https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs>. /// <https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs>.
/// Use `--unsafe-ws-external` to suppress the warning if you understand the risks. /// Use `--unsafe-ws-external` to suppress the warning if you understand the risks.
#[clap(long)] #[arg(long)]
pub ws_external: bool, pub ws_external: bool,
/// Listen to all Websocket interfaces. /// Listen to all Websocket interfaces.
/// ///
/// Same as `--ws-external` but doesn't warn you about it. /// Same as `--ws-external` but doesn't warn you about it.
#[clap(long)] #[arg(long)]
pub unsafe_ws_external: bool, pub unsafe_ws_external: bool,
/// DEPRECATED, this has no affect anymore. Use `rpc_max_request_size` or /// DEPRECATED, this has no affect anymore. Use `rpc_max_request_size` or
/// `rpc_max_response_size` instead. /// `rpc_max_response_size` instead.
#[clap(long)] #[arg(long)]
pub rpc_max_payload: Option<usize>, pub rpc_max_payload: Option<usize>,
/// Set the the maximum RPC request payload size for both HTTP and WS in megabytes. /// Set the the maximum RPC request payload size for both HTTP and WS in megabytes.
/// Default is 15MiB. /// Default is 15MiB.
#[clap(long)] #[arg(long)]
pub rpc_max_request_size: Option<usize>, pub rpc_max_request_size: Option<usize>,
/// Set the the maximum RPC response payload size for both HTTP and WS in megabytes. /// Set the the maximum RPC response payload size for both HTTP and WS in megabytes.
/// Default is 15MiB. /// Default is 15MiB.
#[clap(long)] #[arg(long)]
pub rpc_max_response_size: Option<usize>, pub rpc_max_response_size: Option<usize>,
/// Set the the maximum concurrent subscriptions per connection. /// Set the the maximum concurrent subscriptions per connection.
/// Default is 1024. /// Default is 1024.
#[clap(long)] #[arg(long)]
pub rpc_max_subscriptions_per_connection: Option<usize>, pub rpc_max_subscriptions_per_connection: Option<usize>,
/// Expose Prometheus exporter on all interfaces. /// Expose Prometheus exporter on all interfaces.
/// ///
/// Default is local. /// Default is local.
#[clap(long)] #[arg(long)]
pub prometheus_external: bool, pub prometheus_external: bool,
/// DEPRECATED, IPC support has been removed. /// DEPRECATED, IPC support has been removed.
#[clap(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub ipc_path: Option<String>, pub ipc_path: Option<String>,
/// Specify HTTP RPC server TCP port. /// Specify HTTP RPC server TCP port.
#[clap(long, value_name = "PORT")] #[arg(long, value_name = "PORT")]
pub rpc_port: Option<u16>, pub rpc_port: Option<u16>,
/// Specify WebSockets RPC server TCP port. /// Specify WebSockets RPC server TCP port.
#[clap(long, value_name = "PORT")] #[arg(long, value_name = "PORT")]
pub ws_port: Option<u16>, pub ws_port: Option<u16>,
/// Maximum number of WS RPC server connections. /// Maximum number of WS RPC server connections.
#[clap(long, value_name = "COUNT")] #[arg(long, value_name = "COUNT")]
pub ws_max_connections: Option<usize>, pub ws_max_connections: Option<usize>,
/// DEPRECATED, this has no affect anymore. Use `rpc_max_response_size` instead. /// DEPRECATED, this has no affect anymore. Use `rpc_max_response_size` instead.
#[clap(long)] #[arg(long)]
pub ws_max_out_buffer_capacity: Option<usize>, pub ws_max_out_buffer_capacity: Option<usize>,
/// Specify browser Origins allowed to access the HTTP & WS RPC servers. /// Specify browser Origins allowed to access the HTTP & WS RPC servers.
@@ -148,29 +148,29 @@ pub struct RunCmd {
/// value). Value of `all` will disable origin validation. Default is to /// value). Value of `all` will disable origin validation. Default is to
/// allow localhost and <https://polkadot.js.org> origins. When running in /// allow localhost and <https://polkadot.js.org> origins. When running in
/// --dev mode the default is to allow all origins. /// --dev mode the default is to allow all origins.
#[clap(long, value_name = "ORIGINS", parse(from_str = parse_cors))] #[arg(long, value_name = "ORIGINS", value_parser = parse_cors)]
pub rpc_cors: Option<Cors>, pub rpc_cors: Option<Cors>,
/// Specify Prometheus exporter TCP Port. /// Specify Prometheus exporter TCP Port.
#[clap(long, value_name = "PORT")] #[arg(long, value_name = "PORT")]
pub prometheus_port: Option<u16>, pub prometheus_port: Option<u16>,
/// Do not expose a Prometheus exporter endpoint. /// Do not expose a Prometheus exporter endpoint.
/// ///
/// Prometheus metric endpoint is enabled by default. /// Prometheus metric endpoint is enabled by default.
#[clap(long)] #[arg(long)]
pub no_prometheus: bool, pub no_prometheus: bool,
/// The human-readable name for this node. /// The human-readable name for this node.
/// ///
/// The node name will be reported to the telemetry server, if enabled. /// The node name will be reported to the telemetry server, if enabled.
#[clap(long, value_name = "NAME")] #[arg(long, value_name = "NAME")]
pub name: Option<String>, pub name: Option<String>,
/// Disable connecting to the Substrate telemetry server. /// Disable connecting to the Substrate telemetry server.
/// ///
/// Telemetry is on by default on global chains. /// Telemetry is on by default on global chains.
#[clap(long)] #[arg(long)]
pub no_telemetry: bool, pub no_telemetry: bool,
/// The URL of the telemetry server to connect to. /// The URL of the telemetry server to connect to.
@@ -179,7 +179,7 @@ pub struct RunCmd {
/// telemetry endpoints. Verbosity levels range from 0-9, with 0 denoting /// telemetry endpoints. Verbosity levels range from 0-9, with 0 denoting
/// the least verbosity. /// the least verbosity.
/// Expected format is 'URL VERBOSITY', e.g. `--telemetry-url 'wss://foo/bar 0'`. /// Expected format is 'URL VERBOSITY', e.g. `--telemetry-url 'wss://foo/bar 0'`.
#[clap(long = "telemetry-url", value_name = "URL VERBOSITY", parse(try_from_str = parse_telemetry_endpoints))] #[arg(long = "telemetry-url", value_name = "URL VERBOSITY", value_parser = parse_telemetry_endpoints)]
pub telemetry_endpoints: Vec<(String, u8)>, pub telemetry_endpoints: Vec<(String, u8)>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -203,40 +203,40 @@ pub struct RunCmd {
pub pool_config: TransactionPoolParams, pub pool_config: TransactionPoolParams,
/// Shortcut for `--name Alice --validator` with session keys for `Alice` added to keystore. /// Shortcut for `--name Alice --validator` with session keys for `Alice` added to keystore.
#[clap(long, conflicts_with_all = &["bob", "charlie", "dave", "eve", "ferdie", "one", "two"])] #[arg(long, conflicts_with_all = &["bob", "charlie", "dave", "eve", "ferdie", "one", "two"])]
pub alice: bool, pub alice: bool,
/// Shortcut for `--name Bob --validator` with session keys for `Bob` added to keystore. /// Shortcut for `--name Bob --validator` with session keys for `Bob` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "charlie", "dave", "eve", "ferdie", "one", "two"])] #[arg(long, conflicts_with_all = &["alice", "charlie", "dave", "eve", "ferdie", "one", "two"])]
pub bob: bool, pub bob: bool,
/// Shortcut for `--name Charlie --validator` with session keys for `Charlie` added to /// Shortcut for `--name Charlie --validator` with session keys for `Charlie` added to
/// keystore. /// keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "dave", "eve", "ferdie", "one", "two"])] #[arg(long, conflicts_with_all = &["alice", "bob", "dave", "eve", "ferdie", "one", "two"])]
pub charlie: bool, pub charlie: bool,
/// Shortcut for `--name Dave --validator` with session keys for `Dave` added to keystore. /// Shortcut for `--name Dave --validator` with session keys for `Dave` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "eve", "ferdie", "one", "two"])] #[arg(long, conflicts_with_all = &["alice", "bob", "charlie", "eve", "ferdie", "one", "two"])]
pub dave: bool, pub dave: bool,
/// Shortcut for `--name Eve --validator` with session keys for `Eve` added to keystore. /// Shortcut for `--name Eve --validator` with session keys for `Eve` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "ferdie", "one", "two"])] #[arg(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "ferdie", "one", "two"])]
pub eve: bool, pub eve: bool,
/// Shortcut for `--name Ferdie --validator` with session keys for `Ferdie` added to keystore. /// Shortcut for `--name Ferdie --validator` with session keys for `Ferdie` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "one", "two"])] #[arg(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "one", "two"])]
pub ferdie: bool, pub ferdie: bool,
/// Shortcut for `--name One --validator` with session keys for `One` added to keystore. /// Shortcut for `--name One --validator` with session keys for `One` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "two"])] #[arg(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "two"])]
pub one: bool, pub one: bool,
/// Shortcut for `--name Two --validator` with session keys for `Two` added to keystore. /// Shortcut for `--name Two --validator` with session keys for `Two` added to keystore.
#[clap(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "one"])] #[arg(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "one"])]
pub two: bool, pub two: bool,
/// Enable authoring even when offline. /// Enable authoring even when offline.
#[clap(long)] #[arg(long)]
pub force_authoring: bool, pub force_authoring: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -246,11 +246,11 @@ pub struct RunCmd {
/// The size of the instances cache for each runtime. /// The size of the instances cache for each runtime.
/// ///
/// The default value is 8 and the values higher than 256 are ignored. /// The default value is 8 and the values higher than 256 are ignored.
#[clap(long)] #[arg(long)]
pub max_runtime_instances: Option<usize>, pub max_runtime_instances: Option<usize>,
/// Maximum number of different runtimes that can be cached. /// Maximum number of different runtimes that can be cached.
#[clap(long, default_value = "2")] #[arg(long, default_value_t = 2)]
pub runtime_cache_size: u8, pub runtime_cache_size: u8,
/// Run a temporary node. /// Run a temporary node.
@@ -262,7 +262,7 @@ pub struct RunCmd {
/// which includes: database, node key and keystore. /// which includes: database, node key and keystore.
/// ///
/// When `--dev` is given and no explicit `--base-path`, this option is implied. /// When `--dev` is given and no explicit `--base-path`, this option is implied.
#[clap(long, conflicts_with = "base-path")] #[arg(long, conflicts_with = "base_path")]
pub tmp: bool, pub tmp: bool,
} }
@@ -597,7 +597,7 @@ impl From<Cors> for Option<Vec<String>> {
} }
/// Parse cors origins. /// Parse cors origins.
fn parse_cors(s: &str) -> Cors { fn parse_cors(s: &str) -> Result<Cors> {
let mut is_all = false; let mut is_all = false;
let mut origins = Vec::new(); let mut origins = Vec::new();
for part in s.split(',') { for part in s.split(',') {
@@ -611,9 +611,9 @@ fn parse_cors(s: &str) -> Cors {
} }
if is_all { if is_all {
Cors::All Ok(Cors::All)
} else { } else {
Cors::List(origins) Ok(Cors::List(origins))
} }
} }
+4 -4
View File
@@ -23,21 +23,21 @@ use sp_core::crypto::SecretString;
/// The `sign` command /// The `sign` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[clap(name = "sign", about = "Sign a message, with a given (secret) key")] #[command(name = "sign", about = "Sign a message, with a given (secret) key")]
pub struct SignCmd { pub struct SignCmd {
/// The secret key URI. /// The secret key URI.
/// If the value is a file, the file content is used as URI. /// If the value is a file, the file content is used as URI.
/// If not given, you will be prompted for the URI. /// If not given, you will be prompted for the URI.
#[clap(long)] #[arg(long)]
suri: Option<String>, suri: Option<String>,
/// Message to sign, if not provided you will be prompted to /// Message to sign, if not provided you will be prompted to
/// pass the message via STDIN /// pass the message via STDIN
#[clap(long)] #[arg(long)]
message: Option<String>, message: Option<String>,
/// The message on STDIN is hex-encoded data /// The message on STDIN is hex-encoded data
#[clap(long)] #[arg(long)]
hex: bool, hex: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
+2 -2
View File
@@ -29,10 +29,10 @@ use utils::print_from_uri;
/// The `vanity` command /// The `vanity` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[clap(name = "vanity", about = "Generate a seed that provides a vanity address")] #[command(name = "vanity", about = "Generate a seed that provides a vanity address")]
pub struct VanityCmd { pub struct VanityCmd {
/// Desired pattern /// Desired pattern
#[clap(long, parse(try_from_str = assert_non_empty_string))] #[arg(long, value_parser = assert_non_empty_string)]
pattern: String, pattern: String,
#[allow(missing_docs)] #[allow(missing_docs)]
+3 -3
View File
@@ -24,7 +24,7 @@ use sp_core::crypto::{ByteArray, Ss58Codec};
/// The `verify` command /// The `verify` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[clap( #[command(
name = "verify", name = "verify",
about = "Verify a signature for a message, provided on STDIN, with a given (public or secret) key" about = "Verify a signature for a message, provided on STDIN, with a given (public or secret) key"
)] )]
@@ -39,11 +39,11 @@ pub struct VerifyCmd {
/// Message to verify, if not provided you will be prompted to /// Message to verify, if not provided you will be prompted to
/// pass the message via STDIN /// pass the message via STDIN
#[clap(long)] #[arg(long)]
message: Option<String>, message: Option<String>,
/// The message on STDIN is hex-encoded data /// The message on STDIN is hex-encoded data
#[clap(long)] #[arg(long)]
hex: bool, hex: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
+7 -11
View File
@@ -129,9 +129,9 @@ pub trait SubstrateCli: Sized {
let about = Self::description(); let about = Self::description();
let app = app let app = app
.name(name) .name(name)
.author(author.as_str()) .author(author)
.about(about.as_str()) .about(about)
.version(full_version.as_str()) .version(full_version)
.propagate_version(true) .propagate_version(true)
.args_conflicts_with_subcommands(true) .args_conflicts_with_subcommands(true)
.subcommand_negates_reqs(true); .subcommand_negates_reqs(true);
@@ -153,9 +153,9 @@ pub trait SubstrateCli: Sized {
/// ///
/// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
/// used. It will return a [`clap::Error`], where the [`clap::Error::kind`] is a /// used. It will return a [`clap::Error`], where the [`clap::Error::kind`] is a
/// [`clap::ErrorKind::DisplayHelp`] or [`clap::ErrorKind::DisplayVersion`] respectively. /// [`clap::error::ErrorKind::DisplayHelp`] or [`clap::error::ErrorKind::DisplayVersion`]
/// You must call [`clap::Error::exit`] or perform a [`std::process::exit`]. /// respectively. You must call [`clap::Error::exit`] or perform a [`std::process::exit`].
fn try_from_iter<I>(iter: I) -> clap::Result<Self> fn try_from_iter<I>(iter: I) -> clap::error::Result<Self>
where where
Self: Parser + Sized, Self: Parser + Sized,
I: IntoIterator, I: IntoIterator,
@@ -169,11 +169,7 @@ pub trait SubstrateCli: Sized {
let name = Self::executable_name(); let name = Self::executable_name();
let author = Self::author(); let author = Self::author();
let about = Self::description(); let about = Self::description();
let app = app let app = app.name(name).author(author).about(about).version(full_version);
.name(name)
.author(author.as_str())
.about(about.as_str())
.version(full_version.as_str());
let matches = app.try_get_matches_from(iter)?; let matches = app.try_get_matches_from(iter)?;
@@ -23,17 +23,11 @@ use clap::Args;
#[derive(Debug, Clone, PartialEq, Args)] #[derive(Debug, Clone, PartialEq, Args)]
pub struct DatabaseParams { pub struct DatabaseParams {
/// Select database backend to use. /// Select database backend to use.
#[clap( #[arg(long, alias = "db", value_name = "DB", value_enum)]
long,
alias = "db",
value_name = "DB",
ignore_case = true,
possible_values = Database::variants(),
)]
pub database: Option<Database>, pub database: Option<Database>,
/// Limit the memory the database cache can use. /// Limit the memory the database cache can use.
#[clap(long = "db-cache", value_name = "MiB")] #[arg(long = "db-cache", value_name = "MiB")]
pub database_cache_size: Option<usize>, pub database_cache_size: Option<usize>,
} }
@@ -42,12 +42,12 @@ pub struct ImportParams {
pub database_params: DatabaseParams, pub database_params: DatabaseParams,
/// Method for executing Wasm runtime code. /// Method for executing Wasm runtime code.
#[clap( #[arg(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = WasmExecutionMethod::variants(), value_enum,
ignore_case = true, ignore_case = true,
default_value = DEFAULT_WASM_EXECUTION_METHOD, default_value_t = DEFAULT_WASM_EXECUTION_METHOD,
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
@@ -64,18 +64,18 @@ pub struct ImportParams {
/// The `legacy-instance-reuse` strategy is deprecated and will /// The `legacy-instance-reuse` strategy is deprecated and will
/// be removed in the future. It should only be used in case of /// be removed in the future. It should only be used in case of
/// issues with the default instantiation strategy. /// issues with the default instantiation strategy.
#[clap( #[arg(
long, long,
value_name = "STRATEGY", value_name = "STRATEGY",
default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY,
arg_enum, value_enum,
)] )]
pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy, pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy,
/// Specify the path where local WASM runtimes are stored. /// Specify the path where local WASM runtimes are stored.
/// ///
/// These runtimes will override on-chain runtimes when the version matches. /// These runtimes will override on-chain runtimes when the version matches.
#[clap(long, value_name = "PATH", parse(from_os_str))] #[arg(long, value_name = "PATH")]
pub wasm_runtime_overrides: Option<PathBuf>, pub wasm_runtime_overrides: Option<PathBuf>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -85,13 +85,13 @@ pub struct ImportParams {
/// Specify the state cache size. /// Specify the state cache size.
/// ///
/// Providing `0` will disable the cache. /// Providing `0` will disable the cache.
#[clap(long, value_name = "Bytes", default_value = "67108864")] #[arg(long, value_name = "Bytes", default_value_t = 67108864)]
pub trie_cache_size: usize, pub trie_cache_size: usize,
/// DEPRECATED /// DEPRECATED
/// ///
/// Switch to `--trie-cache-size`. /// Switch to `--trie-cache-size`.
#[clap(long)] #[arg(long)]
state_cache_size: Option<usize>, state_cache_size: Option<usize>,
} }
@@ -156,39 +156,39 @@ impl ImportParams {
pub struct ExecutionStrategiesParams { pub struct ExecutionStrategiesParams {
/// The means of execution used when calling into the runtime for importing blocks as /// The means of execution used when calling into the runtime for importing blocks as
/// part of an initial sync. /// part of an initial sync.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution_syncing: Option<ExecutionStrategy>, pub execution_syncing: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime for general block import /// The means of execution used when calling into the runtime for general block import
/// (including locally authored blocks). /// (including locally authored blocks).
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution_import_block: Option<ExecutionStrategy>, pub execution_import_block: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while constructing blocks. /// The means of execution used when calling into the runtime while constructing blocks.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution_block_construction: Option<ExecutionStrategy>, pub execution_block_construction: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while using an off-chain worker. /// The means of execution used when calling into the runtime while using an off-chain worker.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution_offchain_worker: Option<ExecutionStrategy>, pub execution_offchain_worker: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while not syncing, importing or /// The means of execution used when calling into the runtime while not syncing, importing or
/// constructing blocks. /// constructing blocks.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution_other: Option<ExecutionStrategy>, pub execution_other: Option<ExecutionStrategy>,
/// The execution strategy that should be used by all execution contexts. /// The execution strategy that should be used by all execution contexts.
#[clap( #[arg(
long, long,
value_name = "STRATEGY", value_name = "STRATEGY",
arg_enum, value_enum,
ignore_case = true, ignore_case = true,
conflicts_with_all = &[ conflicts_with_all = &[
"execution-other", "execution_other",
"execution-offchain-worker", "execution_offchain_worker",
"execution-block-construction", "execution_block_construction",
"execution-import-block", "execution_import_block",
"execution-syncing", "execution_syncing",
] ]
)] )]
pub execution: Option<ExecutionStrategy>, pub execution: Option<ExecutionStrategy>,
@@ -32,32 +32,31 @@ const DEFAULT_KEYSTORE_CONFIG_PATH: &str = "keystore";
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct KeystoreParams { pub struct KeystoreParams {
/// Specify custom URIs to connect to for keystore-services /// Specify custom URIs to connect to for keystore-services
#[clap(long)] #[arg(long)]
pub keystore_uri: Option<String>, pub keystore_uri: Option<String>,
/// Specify custom keystore path. /// Specify custom keystore path.
#[clap(long, value_name = "PATH", parse(from_os_str))] #[arg(long, value_name = "PATH")]
pub keystore_path: Option<PathBuf>, pub keystore_path: Option<PathBuf>,
/// Use interactive shell for entering the password used by the keystore. /// Use interactive shell for entering the password used by the keystore.
#[clap(long, conflicts_with_all = &["password", "password-filename"])] #[arg(long, conflicts_with_all = &["password", "password_filename"])]
pub password_interactive: bool, pub password_interactive: bool,
/// Password used by the keystore. This allows appending an extra user-defined secret to the /// Password used by the keystore. This allows appending an extra user-defined secret to the
/// seed. /// seed.
#[clap( #[arg(
long, long,
parse(try_from_str = secret_string_from_str), value_parser = secret_string_from_str,
conflicts_with_all = &["password-interactive", "password-filename"] conflicts_with_all = &["password_interactive", "password_filename"]
)] )]
pub password: Option<SecretString>, pub password: Option<SecretString>,
/// File that contains the password used by the keystore. /// File that contains the password used by the keystore.
#[clap( #[arg(
long, long,
value_name = "PATH", value_name = "PATH",
parse(from_os_str), conflicts_with_all = &["password_interactive", "password"]
conflicts_with_all = &["password-interactive", "password"]
)] )]
pub password_filename: Option<PathBuf>, pub password_filename: Option<PathBuf>,
} }
+16 -6
View File
@@ -27,7 +27,7 @@ mod transaction_pool_params;
use crate::arg_enums::{CryptoScheme, OutputType}; use crate::arg_enums::{CryptoScheme, OutputType};
use clap::Args; use clap::Args;
use sp_core::crypto::Ss58AddressFormat; use sp_core::crypto::{Ss58AddressFormat, Ss58AddressFormatRegistry};
use sp_runtime::{ use sp_runtime::{
generic::BlockId, generic::BlockId,
traits::{Block as BlockT, NumberFor}, traits::{Block as BlockT, NumberFor},
@@ -40,6 +40,17 @@ pub use crate::params::{
transaction_pool_params::*, transaction_pool_params::*,
}; };
/// Parse Ss58AddressFormat
pub fn parse_ss58_address_format(x: &str) -> Result<Ss58AddressFormat, String> {
match Ss58AddressFormatRegistry::try_from(x) {
Ok(format_registry) => Ok(format_registry.into()),
Err(_) => Err(format!(
"Unable to parse variant. Known variants: {:?}",
Ss58AddressFormat::all_names()
)),
}
}
/// Wrapper type of `String` that holds an unsigned integer of arbitrary size, formatted as a /// Wrapper type of `String` that holds an unsigned integer of arbitrary size, formatted as a
/// decimal. /// decimal.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -118,7 +129,7 @@ impl BlockNumberOrHash {
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct CryptoSchemeFlag { pub struct CryptoSchemeFlag {
/// cryptography scheme /// cryptography scheme
#[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true, default_value = "sr25519")] #[arg(long, value_name = "SCHEME", value_enum, ignore_case = true, default_value_t = CryptoScheme::Sr25519)]
pub scheme: CryptoScheme, pub scheme: CryptoScheme,
} }
@@ -126,7 +137,7 @@ pub struct CryptoSchemeFlag {
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct OutputTypeFlag { pub struct OutputTypeFlag {
/// output format /// output format
#[clap(long, value_name = "FORMAT", arg_enum, ignore_case = true, default_value = "text")] #[arg(long, value_name = "FORMAT", value_enum, ignore_case = true, default_value_t = OutputType::Text)]
pub output_type: OutputType, pub output_type: OutputType,
} }
@@ -134,13 +145,12 @@ pub struct OutputTypeFlag {
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct NetworkSchemeFlag { pub struct NetworkSchemeFlag {
/// network address format /// network address format
#[clap( #[arg(
short = 'n', short = 'n',
long, long,
value_name = "NETWORK", value_name = "NETWORK",
possible_values = &Ss58AddressFormat::all_names()[..],
ignore_case = true, ignore_case = true,
parse(try_from_str = Ss58AddressFormat::try_from), value_parser = parse_ss58_address_format,
)] )]
pub network: Option<Ss58AddressFormat>, pub network: Option<Ss58AddressFormat>,
} }
@@ -33,11 +33,11 @@ use std::{borrow::Cow, path::PathBuf};
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct NetworkParams { pub struct NetworkParams {
/// Specify a list of bootnodes. /// Specify a list of bootnodes.
#[clap(long, value_name = "ADDR", multiple_values(true))] #[arg(long, value_name = "ADDR", num_args = 1..)]
pub bootnodes: Vec<MultiaddrWithPeerId>, pub bootnodes: Vec<MultiaddrWithPeerId>,
/// Specify a list of reserved node addresses. /// Specify a list of reserved node addresses.
#[clap(long, value_name = "ADDR", multiple_values(true))] #[arg(long, value_name = "ADDR", num_args = 1..)]
pub reserved_nodes: Vec<MultiaddrWithPeerId>, pub reserved_nodes: Vec<MultiaddrWithPeerId>,
/// Whether to only synchronize the chain with reserved nodes. /// Whether to only synchronize the chain with reserved nodes.
@@ -48,12 +48,12 @@ pub struct NetworkParams {
/// In particular, if you are a validator your node might still connect to other /// In particular, if you are a validator your node might still connect to other
/// validator nodes and collator nodes regardless of whether they are defined as /// validator nodes and collator nodes regardless of whether they are defined as
/// reserved nodes. /// reserved nodes.
#[clap(long)] #[arg(long)]
pub reserved_only: bool, pub reserved_only: bool,
/// The public address that other nodes will use to connect to it. /// The public address that other nodes will use to connect to it.
/// This can be used if there's a proxy in front of this node. /// This can be used if there's a proxy in front of this node.
#[clap(long, value_name = "PUBLIC_ADDR", multiple_values(true))] #[arg(long, value_name = "PUBLIC_ADDR", num_args = 1..)]
pub public_addr: Vec<Multiaddr>, pub public_addr: Vec<Multiaddr>,
/// Listen on this multiaddress. /// Listen on this multiaddress.
@@ -61,49 +61,49 @@ pub struct NetworkParams {
/// By default: /// By default:
/// If `--validator` is passed: `/ip4/0.0.0.0/tcp/<port>` and `/ip6/[::]/tcp/<port>`. /// If `--validator` is passed: `/ip4/0.0.0.0/tcp/<port>` and `/ip6/[::]/tcp/<port>`.
/// Otherwise: `/ip4/0.0.0.0/tcp/<port>/ws` and `/ip6/[::]/tcp/<port>/ws`. /// Otherwise: `/ip4/0.0.0.0/tcp/<port>/ws` and `/ip6/[::]/tcp/<port>/ws`.
#[clap(long, value_name = "LISTEN_ADDR", multiple_values(true))] #[arg(long, value_name = "LISTEN_ADDR", num_args = 1..)]
pub listen_addr: Vec<Multiaddr>, pub listen_addr: Vec<Multiaddr>,
/// Specify p2p protocol TCP port. /// Specify p2p protocol TCP port.
#[clap(long, value_name = "PORT", conflicts_with_all = &[ "listen-addr" ])] #[arg(long, value_name = "PORT", conflicts_with_all = &[ "listen_addr" ])]
pub port: Option<u16>, pub port: Option<u16>,
/// Always forbid connecting to private IPv4 addresses (as specified in /// Always forbid connecting to private IPv4 addresses (as specified in
/// [RFC1918](https://tools.ietf.org/html/rfc1918)), unless the address was passed with /// [RFC1918](https://tools.ietf.org/html/rfc1918)), unless the address was passed with
/// `--reserved-nodes` or `--bootnodes`. Enabled by default for chains marked as "live" in /// `--reserved-nodes` or `--bootnodes`. Enabled by default for chains marked as "live" in
/// their chain specifications. /// their chain specifications.
#[clap(long, conflicts_with_all = &["allow-private-ipv4"])] #[arg(long, conflicts_with_all = &["allow_private_ipv4"])]
pub no_private_ipv4: bool, pub no_private_ipv4: bool,
/// Always accept connecting to private IPv4 addresses (as specified in /// Always accept connecting to private IPv4 addresses (as specified in
/// [RFC1918](https://tools.ietf.org/html/rfc1918)). Enabled by default for chains marked as /// [RFC1918](https://tools.ietf.org/html/rfc1918)). Enabled by default for chains marked as
/// "local" in their chain specifications, or when `--dev` is passed. /// "local" in their chain specifications, or when `--dev` is passed.
#[clap(long, conflicts_with_all = &["no-private-ipv4"])] #[arg(long, conflicts_with_all = &["no_private_ipv4"])]
pub allow_private_ipv4: bool, pub allow_private_ipv4: bool,
/// Specify the number of outgoing connections we're trying to maintain. /// Specify the number of outgoing connections we're trying to maintain.
#[clap(long, value_name = "COUNT", default_value = "25")] #[arg(long, value_name = "COUNT", default_value_t = 25)]
pub out_peers: u32, pub out_peers: u32,
/// Maximum number of inbound full nodes peers. /// Maximum number of inbound full nodes peers.
#[clap(long, value_name = "COUNT", default_value = "25")] #[arg(long, value_name = "COUNT", default_value_t = 25)]
pub in_peers: u32, pub in_peers: u32,
/// Maximum number of inbound light nodes peers. /// Maximum number of inbound light nodes peers.
#[clap(long, value_name = "COUNT", default_value = "100")] #[arg(long, value_name = "COUNT", default_value_t = 100)]
pub in_peers_light: u32, pub in_peers_light: u32,
/// Disable mDNS discovery. /// Disable mDNS discovery.
/// ///
/// By default, the network will use mDNS to discover other nodes on the /// By default, the network will use mDNS to discover other nodes on the
/// local network. This disables it. Automatically implied when using --dev. /// local network. This disables it. Automatically implied when using --dev.
#[clap(long)] #[arg(long)]
pub no_mdns: bool, pub no_mdns: bool,
/// Maximum number of peers from which to ask for the same blocks in parallel. /// Maximum number of peers from which to ask for the same blocks in parallel.
/// ///
/// This allows downloading announced blocks from multiple peers. Decrease to save /// This allows downloading announced blocks from multiple peers. Decrease to save
/// traffic and risk increased latency. /// traffic and risk increased latency.
#[clap(long, value_name = "COUNT", default_value = "5")] #[arg(long, value_name = "COUNT", default_value_t = 5)]
pub max_parallel_downloads: u32, pub max_parallel_downloads: u32,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -114,7 +114,7 @@ pub struct NetworkParams {
/// ///
/// By default this option is `true` for `--dev` or when the chain type is /// By default this option is `true` for `--dev` or when the chain type is
/// `Local`/`Development` and false otherwise. /// `Local`/`Development` and false otherwise.
#[clap(long)] #[arg(long)]
pub discover_local: bool, pub discover_local: bool,
/// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in /// Require iterative Kademlia DHT queries to use disjoint paths for increased resiliency in
@@ -122,11 +122,11 @@ pub struct NetworkParams {
/// ///
/// See the S/Kademlia paper for more information on the high level design as well as its /// See the S/Kademlia paper for more information on the high level design as well as its
/// security improvements. /// security improvements.
#[clap(long)] #[arg(long)]
pub kademlia_disjoint_query_paths: bool, pub kademlia_disjoint_query_paths: bool,
/// Join the IPFS network and serve transactions over bitswap protocol. /// Join the IPFS network and serve transactions over bitswap protocol.
#[clap(long)] #[arg(long)]
pub ipfs_server: bool, pub ipfs_server: bool,
/// Blockchain syncing mode. /// Blockchain syncing mode.
@@ -135,11 +135,11 @@ pub struct NetworkParams {
/// - `fast`: Download blocks and the latest state only. /// - `fast`: Download blocks and the latest state only.
/// - `fast-unsafe`: Same as `fast`, but skip downloading state proofs. /// - `fast-unsafe`: Same as `fast`, but skip downloading state proofs.
/// - `warp`: Download the latest state and proof. /// - `warp`: Download the latest state and proof.
#[clap( #[arg(
long, long,
arg_enum, value_enum,
value_name = "SYNC_MODE", value_name = "SYNC_MODE",
default_value = "full", default_value_t = SyncMode::Full,
ignore_case = true, ignore_case = true,
verbatim_doc_comment verbatim_doc_comment
)] )]
@@ -46,7 +46,7 @@ pub struct NodeKeyParams {
/// WARNING: Secrets provided as command-line arguments are easily exposed. /// WARNING: Secrets provided as command-line arguments are easily exposed.
/// Use of this option should be limited to development and testing. To use /// Use of this option should be limited to development and testing. To use
/// an externally managed secret key, use `--node-key-file` instead. /// an externally managed secret key, use `--node-key-file` instead.
#[clap(long, value_name = "KEY")] #[arg(long, value_name = "KEY")]
pub node_key: Option<String>, pub node_key: Option<String>,
/// The type of secret key to use for libp2p networking. /// The type of secret key to use for libp2p networking.
@@ -66,7 +66,7 @@ pub struct NodeKeyParams {
/// ///
/// The node's secret key determines the corresponding public key and hence the /// The node's secret key determines the corresponding public key and hence the
/// node's peer ID in the context of libp2p. /// node's peer ID in the context of libp2p.
#[clap(long, value_name = "TYPE", arg_enum, ignore_case = true, default_value = "ed25519")] #[arg(long, value_name = "TYPE", value_enum, ignore_case = true, default_value_t = NodeKeyType::Ed25519)]
pub node_key_type: NodeKeyType, pub node_key_type: NodeKeyType,
/// The file from which to read the node's secret key to use for libp2p networking. /// The file from which to read the node's secret key to use for libp2p networking.
@@ -79,7 +79,7 @@ pub struct NodeKeyParams {
/// ///
/// If the file does not exist, it is created with a newly generated secret key of /// If the file does not exist, it is created with a newly generated secret key of
/// the chosen type. /// the chosen type.
#[clap(long, value_name = "FILE")] #[arg(long, value_name = "FILE")]
pub node_key_file: Option<PathBuf>, pub node_key_file: Option<PathBuf>,
} }
@@ -122,7 +122,7 @@ fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519S
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use clap::ArgEnum; use clap::ValueEnum;
use sc_network::config::identity::{ed25519, Keypair}; use sc_network::config::identity::{ed25519, Keypair};
use std::fs; use std::fs;
@@ -35,12 +35,12 @@ pub struct OffchainWorkerParams {
/// Should execute offchain workers on every block. /// Should execute offchain workers on every block.
/// ///
/// By default it's only enabled for nodes that are authoring new blocks. /// By default it's only enabled for nodes that are authoring new blocks.
#[clap( #[arg(
long = "offchain-worker", long = "offchain-worker",
value_name = "ENABLED", value_name = "ENABLED",
arg_enum, value_enum,
ignore_case = true, ignore_case = true,
default_value = "when-validating" default_value_t = OffchainWorkerEnabled::WhenValidating
)] )]
pub enabled: OffchainWorkerEnabled, pub enabled: OffchainWorkerEnabled,
@@ -48,7 +48,7 @@ pub struct OffchainWorkerParams {
/// ///
/// Enables a runtime to write directly to a offchain workers /// Enables a runtime to write directly to a offchain workers
/// DB during block import. /// DB during block import.
#[clap(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")] #[arg(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")]
pub indexing_enabled: bool, pub indexing_enabled: bool,
} }
@@ -28,7 +28,7 @@ pub struct PruningParams {
/// Default is to keep only the last 256 blocks, /// Default is to keep only the last 256 blocks,
/// otherwise, the state can be kept for all of the blocks (i.e 'archive'), /// otherwise, the state can be kept for all of the blocks (i.e 'archive'),
/// or for all of the canonical blocks (i.e 'archive-canonical'). /// or for all of the canonical blocks (i.e 'archive-canonical').
#[clap(alias = "pruning", long, value_name = "PRUNING_MODE")] #[arg(alias = "pruning", long, value_name = "PRUNING_MODE")]
pub state_pruning: Option<String>, pub state_pruning: Option<String>,
/// Specify the blocks pruning mode, a number of blocks to keep or 'archive'. /// Specify the blocks pruning mode, a number of blocks to keep or 'archive'.
/// ///
@@ -38,7 +38,7 @@ pub struct PruningParams {
/// or for the last N blocks (i.e a number). /// or for the last N blocks (i.e a number).
/// ///
/// NOTE: only finalized blocks are subject for removal! /// NOTE: only finalized blocks are subject for removal!
#[clap(alias = "keep-blocks", long, value_name = "COUNT")] #[arg(alias = "keep-blocks", long, value_name = "COUNT")]
pub blocks_pruning: Option<String>, pub blocks_pruning: Option<String>,
} }
@@ -28,25 +28,25 @@ pub struct SharedParams {
/// ///
/// It can be one of the predefined ones (dev, local, or staging) or it can be a path to a file /// It can be one of the predefined ones (dev, local, or staging) or it can be a path to a file
/// with the chainspec (such as one exported by the `build-spec` subcommand). /// with the chainspec (such as one exported by the `build-spec` subcommand).
#[clap(long, value_name = "CHAIN_SPEC")] #[arg(long, value_name = "CHAIN_SPEC")]
pub chain: Option<String>, pub chain: Option<String>,
/// Specify the development chain. /// Specify the development chain.
/// ///
/// This flag sets `--chain=dev`, `--force-authoring`, `--rpc-cors=all`, /// This flag sets `--chain=dev`, `--force-authoring`, `--rpc-cors=all`,
/// `--alice`, and `--tmp` flags, unless explicitly overridden. /// `--alice`, and `--tmp` flags, unless explicitly overridden.
#[clap(long, conflicts_with_all = &["chain"])] #[arg(long, conflicts_with_all = &["chain"])]
pub dev: bool, pub dev: bool,
/// Specify custom base path. /// Specify custom base path.
#[clap(long, short = 'd', value_name = "PATH", parse(from_os_str))] #[arg(long, short = 'd', value_name = "PATH")]
pub base_path: Option<PathBuf>, pub base_path: Option<PathBuf>,
/// Sets a custom logging filter. Syntax is <target>=<level>, e.g. -lsync=debug. /// Sets a custom logging filter. Syntax is <target>=<level>, e.g. -lsync=debug.
/// ///
/// Log levels (least to most verbose) are error, warn, info, debug, and trace. /// Log levels (least to most verbose) are error, warn, info, debug, and trace.
/// By default, all targets log `info`. The global log level can be set with -l<level>. /// By default, all targets log `info`. The global log level can be set with -l<level>.
#[clap(short = 'l', long, value_name = "LOG_PATTERN", multiple_values(true))] #[arg(short = 'l', long, value_name = "LOG_PATTERN", num_args = 1..)]
pub log: Vec<String>, pub log: Vec<String>,
/// Enable detailed log output. /// Enable detailed log output.
@@ -54,11 +54,11 @@ pub struct SharedParams {
/// This includes displaying the log target, log level and thread name. /// This includes displaying the log target, log level and thread name.
/// ///
/// This is automatically enabled when something is logged with any higher level than `info`. /// This is automatically enabled when something is logged with any higher level than `info`.
#[clap(long)] #[arg(long)]
pub detailed_log_output: bool, pub detailed_log_output: bool,
/// Disable log color output. /// Disable log color output.
#[clap(long)] #[arg(long)]
pub disable_log_color: bool, pub disable_log_color: bool,
/// Enable feature to dynamically update and reload the log filter. /// Enable feature to dynamically update and reload the log filter.
@@ -68,15 +68,15 @@ pub struct SharedParams {
/// ///
/// The `system_addLogFilter` and `system_resetLogFilter` RPCs will have no effect with this /// The `system_addLogFilter` and `system_resetLogFilter` RPCs will have no effect with this
/// option not being set. /// option not being set.
#[clap(long)] #[arg(long)]
pub enable_log_reloading: bool, pub enable_log_reloading: bool,
/// Sets a custom profiling filter. Syntax is the same as for logging: <target>=<level> /// Sets a custom profiling filter. Syntax is the same as for logging: <target>=<level>
#[clap(long, value_name = "TARGETS")] #[arg(long, value_name = "TARGETS")]
pub tracing_targets: Option<String>, pub tracing_targets: Option<String>,
/// Receiver to process tracing messages. /// Receiver to process tracing messages.
#[clap(long, value_name = "RECEIVER", arg_enum, ignore_case = true, default_value = "log")] #[arg(long, value_name = "RECEIVER", value_enum, ignore_case = true, default_value_t = TracingReceiver::Log)]
pub tracing_receiver: TracingReceiver, pub tracing_receiver: TracingReceiver,
} }
@@ -23,15 +23,15 @@ use sc_service::config::TransactionPoolOptions;
#[derive(Debug, Clone, Args)] #[derive(Debug, Clone, Args)]
pub struct TransactionPoolParams { pub struct TransactionPoolParams {
/// Maximum number of transactions in the transaction pool. /// Maximum number of transactions in the transaction pool.
#[clap(long, value_name = "COUNT", default_value = "8192")] #[arg(long, value_name = "COUNT", default_value_t = 8192)]
pub pool_limit: usize, pub pool_limit: usize,
/// Maximum number of kilobytes of all transactions stored in the pool. /// Maximum number of kilobytes of all transactions stored in the pool.
#[clap(long, value_name = "COUNT", default_value = "20480")] #[arg(long, value_name = "COUNT", default_value_t = 20480)]
pub pool_kbytes: usize, pub pool_kbytes: usize,
/// How long a transaction is banned for, if it is considered invalid. Defaults to 1800s. /// How long a transaction is banned for, if it is considered invalid. Defaults to 1800s.
#[clap(long, value_name = "SECONDS")] #[arg(long, value_name = "SECONDS")]
pub tx_ban_seconds: Option<u64>, pub tx_ban_seconds: Option<u64>,
} }
@@ -13,7 +13,7 @@ publish = false
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
honggfuzz = "0.5" honggfuzz = "0.5"
rand = { version = "0.8", features = ["std", "small_rng"] } rand = { version = "0.8", features = ["std", "small_rng"] }
@@ -14,7 +14,7 @@ publish = false
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
honggfuzz = "0.5" honggfuzz = "0.5"
rand = { version = "0.8", features = ["std", "small_rng"] } rand = { version = "0.8", features = ["std", "small_rng"] }
@@ -36,4 +36,4 @@ path = "src/phragmms_balancing.rs"
[[bin]] [[bin]]
name = "phragmen_pjr" name = "phragmen_pjr"
path = "src/phragmen_pjr.rs" path = "src/phragmen_pjr.rs"
@@ -68,18 +68,18 @@ fn main() {
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(author, version, about)] #[command(author, version, about)]
struct Opt { struct Opt {
/// How many candidates participate in this election /// How many candidates participate in this election
#[clap(short, long)] #[arg(short, long)]
candidates: Option<usize>, candidates: Option<usize>,
/// How many voters participate in this election /// How many voters participate in this election
#[clap(short, long)] #[arg(short, long)]
voters: Option<usize>, voters: Option<usize>,
/// Random seed to use in this election /// Random seed to use in this election
#[clap(long)] #[arg(long)]
seed: Option<u64>, seed: Option<u64>,
} }
+11
View File
@@ -19,6 +19,8 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
use core::fmt::Display;
#[cfg(feature = "std")] #[cfg(feature = "std")]
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sp_debug_derive::RuntimeDebug; use sp_debug_derive::RuntimeDebug;
@@ -412,6 +414,15 @@ pub enum StateVersion {
V1 = 1, V1 = 1,
} }
impl Display for StateVersion {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
StateVersion::V0 => f.write_str("0"),
StateVersion::V1 => f.write_str("1"),
}
}
}
impl Default for StateVersion { impl Default for StateVersion {
fn default() -> Self { fn default() -> Self {
StateVersion::V1 StateVersion::V1
@@ -10,7 +10,7 @@ homepage = "https://substrate.io"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
flate2 = "1.0" flate2 = "1.0"
fs_extra = "1" fs_extra = "1"
git2 = "0.8" git2 = "0.8"
@@ -29,10 +29,10 @@ type CargoToml = HashMap<String, toml::Value>;
#[derive(Parser)] #[derive(Parser)]
struct Options { struct Options {
/// The path to the `node-template` source. /// The path to the `node-template` source.
#[clap(parse(from_os_str))] #[arg()]
node_template: PathBuf, node_template: PathBuf,
/// The path where to output the generated `tar.gz` file. /// The path where to output the generated `tar.gz` file.
#[clap(parse(from_os_str))] #[arg()]
output: PathBuf, output: PathBuf,
} }
@@ -15,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
array-bytes = "4.1" array-bytes = "4.1"
chrono = "0.4" chrono = "0.4"
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.0.0" } codec = { package = "parity-scale-codec", version = "3.0.0" }
comfy-table = { version = "6.0.0", default-features = false } comfy-table = { version = "6.0.0", default-features = false }
handlebars = "4.2.2" handlebars = "4.2.2"
@@ -43,15 +43,15 @@ const LOG_TARGET: &'static str = "benchmark::block::weight";
#[derive(Debug, Default, Serialize, Clone, PartialEq, Args)] #[derive(Debug, Default, Serialize, Clone, PartialEq, Args)]
pub struct BenchmarkParams { pub struct BenchmarkParams {
/// Number of the first block to consider. /// Number of the first block to consider.
#[clap(long)] #[arg(long)]
pub from: u32, pub from: u32,
/// Last block number to consider. /// Last block number to consider.
#[clap(long)] #[arg(long)]
pub to: u32, pub to: u32,
/// Number of times that the benchmark should be repeated for each block. /// Number of times that the benchmark should be repeated for each block.
#[clap(long, default_value = "10")] #[arg(long, default_value_t = 10)]
pub repeat: u32, pub repeat: u32,
} }
@@ -71,7 +71,7 @@ pub struct BlockCmd {
/// Enable the Trie cache. /// Enable the Trie cache.
/// ///
/// This should only be used for performance analysis and not for final results. /// This should only be used for performance analysis and not for final results.
#[clap(long)] #[arg(long)]
pub enable_trie_cache: bool, pub enable_trie_cache: bool,
} }
@@ -43,17 +43,17 @@ use crate::shared::{StatSelect, Stats};
#[derive(Debug, Default, Serialize, Clone, PartialEq, Args)] #[derive(Debug, Default, Serialize, Clone, PartialEq, Args)]
pub struct BenchmarkParams { pub struct BenchmarkParams {
/// Rounds of warmups before measuring. /// Rounds of warmups before measuring.
#[clap(long, default_value = "10")] #[arg(long, default_value_t = 10)]
pub warmup: u32, pub warmup: u32,
/// How many times the benchmark should be repeated. /// How many times the benchmark should be repeated.
#[clap(long, default_value = "100")] #[arg(long, default_value_t = 100)]
pub repeat: u32, pub repeat: u32,
/// Maximal number of extrinsics that should be put into a block. /// Maximal number of extrinsics that should be put into a block.
/// ///
/// Only useful for debugging. /// Only useful for debugging.
#[clap(long)] #[arg(long)]
pub max_ext_per_block: Option<u32>, pub max_ext_per_block: Option<u32>,
} }
@@ -62,21 +62,21 @@ pub struct ExtrinsicParams {
/// List all available pallets and extrinsics. /// List all available pallets and extrinsics.
/// ///
/// The format is CSV with header `pallet, extrinsic`. /// The format is CSV with header `pallet, extrinsic`.
#[clap(long)] #[arg(long)]
pub list: bool, pub list: bool,
/// Pallet name of the extrinsic to benchmark. /// Pallet name of the extrinsic to benchmark.
#[clap(long, value_name = "PALLET", required_unless_present = "list")] #[arg(long, value_name = "PALLET", required_unless_present = "list")]
pub pallet: Option<String>, pub pallet: Option<String>,
/// Extrinsic to benchmark. /// Extrinsic to benchmark.
#[clap(long, value_name = "EXTRINSIC", required_unless_present = "list")] #[arg(long, value_name = "EXTRINSIC", required_unless_present = "list")]
pub extrinsic: Option<String>, pub extrinsic: Option<String>,
/// Enable the Trie cache. /// Enable the Trie cache.
/// ///
/// This should only be used for performance analysis and not for final results. /// This should only be used for performance analysis and not for final results.
#[clap(long)] #[arg(long)]
pub enable_trie_cache: bool, pub enable_trie_cache: bool,
} }
@@ -53,30 +53,30 @@ pub struct MachineCmd {
/// Do not return an error if any check fails. /// Do not return an error if any check fails.
/// ///
/// Should only be used for debugging. /// Should only be used for debugging.
#[clap(long)] #[arg(long)]
pub allow_fail: bool, pub allow_fail: bool,
/// Set a fault tolerance for passing a requirement. /// Set a fault tolerance for passing a requirement.
/// ///
/// 10% means that the test would pass even when only 90% score was archived. /// 10% means that the test would pass even when only 90% score was archived.
/// Can be used to mitigate outliers of the benchmarks. /// Can be used to mitigate outliers of the benchmarks.
#[clap(long, default_value = "10.0", value_name = "PERCENT")] #[arg(long, default_value_t = 10.0, value_name = "PERCENT")]
pub tolerance: f64, pub tolerance: f64,
/// Time limit for the verification benchmark. /// Time limit for the verification benchmark.
#[clap(long, default_value = "5.0", value_name = "SECONDS")] #[arg(long, default_value_t = 5.0, value_name = "SECONDS")]
pub verify_duration: f32, pub verify_duration: f32,
/// Time limit for the hash function benchmark. /// Time limit for the hash function benchmark.
#[clap(long, default_value = "5.0", value_name = "SECONDS")] #[arg(long, default_value_t = 5.0, value_name = "SECONDS")]
pub hash_duration: f32, pub hash_duration: f32,
/// Time limit for the memory benchmark. /// Time limit for the memory benchmark.
#[clap(long, default_value = "5.0", value_name = "SECONDS")] #[arg(long, default_value_t = 5.0, value_name = "SECONDS")]
pub memory_duration: f32, pub memory_duration: f32,
/// Time limit for each disk benchmark. /// Time limit for each disk benchmark.
#[clap(long, default_value = "5.0", value_name = "SECONDS")] #[arg(long, default_value_t = 5.0, value_name = "SECONDS")]
pub disk_duration: f32, pub disk_duration: f32,
} }
@@ -73,13 +73,13 @@ pub struct OverheadParams {
/// Add a header to the generated weight output file. /// Add a header to the generated weight output file.
/// ///
/// Good for adding LICENSE headers. /// Good for adding LICENSE headers.
#[clap(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub header: Option<PathBuf>, pub header: Option<PathBuf>,
/// Enable the Trie cache. /// Enable the Trie cache.
/// ///
/// This should only be used for performance analysis and not for final results. /// This should only be used for performance analysis and not for final results.
#[clap(long)] #[arg(long)]
pub enable_trie_cache: bool, pub enable_trie_cache: bool,
} }
@@ -27,69 +27,69 @@ use std::{fmt::Debug, path::PathBuf};
// Add a more relaxed parsing for pallet names by allowing pallet directory names with `-` to be // Add a more relaxed parsing for pallet names by allowing pallet directory names with `-` to be
// used like crate names with `_` // used like crate names with `_`
fn parse_pallet_name(pallet: &str) -> String { fn parse_pallet_name(pallet: &str) -> std::result::Result<String, String> {
pallet.replace("-", "_") Ok(pallet.replace("-", "_"))
} }
/// Benchmark the extrinsic weight of FRAME Pallets. /// Benchmark the extrinsic weight of FRAME Pallets.
#[derive(Debug, clap::Parser)] #[derive(Debug, clap::Parser)]
pub struct PalletCmd { pub struct PalletCmd {
/// Select a FRAME Pallet to benchmark, or `*` for all (in which case `extrinsic` must be `*`). /// Select a FRAME Pallet to benchmark, or `*` for all (in which case `extrinsic` must be `*`).
#[clap(short, long, parse(from_str = parse_pallet_name), required_unless_present_any = ["list", "json-input"])] #[arg(short, long, value_parser = parse_pallet_name, required_unless_present_any = ["list", "json_input"])]
pub pallet: Option<String>, pub pallet: Option<String>,
/// Select an extrinsic inside the pallet to benchmark, or `*` for all. /// Select an extrinsic inside the pallet to benchmark, or `*` for all.
#[clap(short, long, required_unless_present_any = ["list", "json-input"])] #[arg(short, long, required_unless_present_any = ["list", "json_input"])]
pub extrinsic: Option<String>, pub extrinsic: Option<String>,
/// Select how many samples we should take across the variable components. /// Select how many samples we should take across the variable components.
#[clap(short, long, default_value = "2")] #[arg(short, long, default_value_t = 2)]
pub steps: u32, pub steps: u32,
/// Indicates lowest values for each of the component ranges. /// Indicates lowest values for each of the component ranges.
#[clap(long = "low", use_value_delimiter = true)] #[arg(long = "low", value_delimiter = ',')]
pub lowest_range_values: Vec<u32>, pub lowest_range_values: Vec<u32>,
/// Indicates highest values for each of the component ranges. /// Indicates highest values for each of the component ranges.
#[clap(long = "high", use_value_delimiter = true)] #[arg(long = "high", value_delimiter = ',')]
pub highest_range_values: Vec<u32>, pub highest_range_values: Vec<u32>,
/// Select how many repetitions of this benchmark should run from within the wasm. /// Select how many repetitions of this benchmark should run from within the wasm.
#[clap(short, long, default_value = "1")] #[arg(short, long, default_value_t = 1)]
pub repeat: u32, pub repeat: u32,
/// Select how many repetitions of this benchmark should run from the client. /// Select how many repetitions of this benchmark should run from the client.
/// ///
/// NOTE: Using this alone may give slower results, but will afford you maximum Wasm memory. /// NOTE: Using this alone may give slower results, but will afford you maximum Wasm memory.
#[clap(long, default_value = "1")] #[arg(long, default_value_t = 1)]
pub external_repeat: u32, pub external_repeat: u32,
/// Print the raw results in JSON format. /// Print the raw results in JSON format.
#[clap(long = "json")] #[arg(long = "json")]
pub json_output: bool, pub json_output: bool,
/// Write the raw results in JSON format into the given file. /// Write the raw results in JSON format into the given file.
#[clap(long, conflicts_with = "json-output")] #[arg(long, conflicts_with = "json_output")]
pub json_file: Option<PathBuf>, pub json_file: Option<PathBuf>,
/// Don't print the median-slopes linear regression analysis. /// Don't print the median-slopes linear regression analysis.
#[clap(long)] #[arg(long)]
pub no_median_slopes: bool, pub no_median_slopes: bool,
/// Don't print the min-squares linear regression analysis. /// Don't print the min-squares linear regression analysis.
#[clap(long)] #[arg(long)]
pub no_min_squares: bool, pub no_min_squares: bool,
/// Output the benchmarks to a Rust file at the given path. /// Output the benchmarks to a Rust file at the given path.
#[clap(long)] #[arg(long)]
pub output: Option<PathBuf>, pub output: Option<PathBuf>,
/// Add a header file to your outputted benchmarks. /// Add a header file to your outputted benchmarks.
#[clap(long)] #[arg(long)]
pub header: Option<PathBuf>, pub header: Option<PathBuf>,
/// Path to Handlebars template file used for outputting benchmark results. (Optional) /// Path to Handlebars template file used for outputting benchmark results. (Optional)
#[clap(long)] #[arg(long)]
pub template: Option<PathBuf>, pub template: Option<PathBuf>,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -100,25 +100,25 @@ pub struct PalletCmd {
/// * min-squares (default) /// * min-squares (default)
/// * median-slopes /// * median-slopes
/// * max (max of min squares and median slopes for each value) /// * max (max of min squares and median slopes for each value)
#[clap(long)] #[arg(long)]
pub output_analysis: Option<String>, pub output_analysis: Option<String>,
/// Set the heap pages while running benchmarks. If not set, the default value from the client /// Set the heap pages while running benchmarks. If not set, the default value from the client
/// is used. /// is used.
#[clap(long)] #[arg(long)]
pub heap_pages: Option<u64>, pub heap_pages: Option<u64>,
/// Disable verification logic when running benchmarks. /// Disable verification logic when running benchmarks.
#[clap(long)] #[arg(long)]
pub no_verify: bool, pub no_verify: bool,
/// Display and run extra benchmarks that would otherwise not be needed for weight /// Display and run extra benchmarks that would otherwise not be needed for weight
/// construction. /// construction.
#[clap(long)] #[arg(long)]
pub extra: bool, pub extra: bool,
/// Estimate PoV size. /// Estimate PoV size.
#[clap(long)] #[arg(long)]
pub record_proof: bool, pub record_proof: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -126,50 +126,50 @@ pub struct PalletCmd {
pub shared_params: sc_cli::SharedParams, pub shared_params: sc_cli::SharedParams,
/// The execution strategy that should be used for benchmarks. /// The execution strategy that should be used for benchmarks.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true)]
pub execution: Option<ExecutionStrategy>, pub execution: Option<ExecutionStrategy>,
/// Method for executing Wasm runtime code. /// Method for executing Wasm runtime code.
#[clap( #[arg(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = WasmExecutionMethod::variants(), value_enum,
ignore_case = true, ignore_case = true,
default_value = DEFAULT_WASM_EXECUTION_METHOD, default_value_t = DEFAULT_WASM_EXECUTION_METHOD,
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
/// The WASM instantiation method to use. /// The WASM instantiation method to use.
/// ///
/// Only has an effect when `wasm-execution` is set to `compiled`. /// Only has an effect when `wasm-execution` is set to `compiled`.
#[clap( #[arg(
long = "wasm-instantiation-strategy", long = "wasm-instantiation-strategy",
value_name = "STRATEGY", value_name = "STRATEGY",
default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY,
arg_enum, value_enum,
)] )]
pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy, pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy,
/// Limit the memory the database cache can use. /// Limit the memory the database cache can use.
#[clap(long = "db-cache", value_name = "MiB", default_value = "1024")] #[arg(long = "db-cache", value_name = "MiB", default_value_t = 1024)]
pub database_cache_size: u32, pub database_cache_size: u32,
/// List the benchmarks that match your query rather than running them. /// List the benchmarks that match your query rather than running them.
/// ///
/// When nothing is provided, we list all benchmarks. /// When nothing is provided, we list all benchmarks.
#[clap(long)] #[arg(long)]
pub list: bool, pub list: bool,
/// If enabled, the storage info is not displayed in the output next to the analysis. /// If enabled, the storage info is not displayed in the output next to the analysis.
/// ///
/// This is independent of the storage info appearing in the *output file*. Use a Handlebar /// This is independent of the storage info appearing in the *output file*. Use a Handlebar
/// template for that purpose. /// template for that purpose.
#[clap(long)] #[arg(long)]
pub no_storage_info: bool, pub no_storage_info: bool,
/// A path to a `.json` file with existing benchmark results generated with `--json` or /// A path to a `.json` file with existing benchmark results generated with `--json` or
/// `--json-file`. When specified the benchmarks are not actually executed, and the data for /// `--json-file`. When specified the benchmarks are not actually executed, and the data for
/// the analysis is read from this file. /// the analysis is read from this file.
#[clap(long)] #[arg(long)]
pub json_input: Option<PathBuf>, pub json_input: Option<PathBuf>,
} }
@@ -95,22 +95,22 @@ pub fn check_build_profile() -> Result<(), String> {
/// Parameters to configure how the host info will be determined. /// Parameters to configure how the host info will be determined.
#[derive(Debug, Default, Serialize, Clone, PartialEq, Args)] #[derive(Debug, Default, Serialize, Clone, PartialEq, Args)]
#[clap(rename_all = "kebab-case")] #[command(rename_all = "kebab-case")]
pub struct HostInfoParams { pub struct HostInfoParams {
/// Manually override the hostname to use. /// Manually override the hostname to use.
#[clap(long)] #[arg(long)]
pub hostname_override: Option<String>, pub hostname_override: Option<String>,
/// Specify a fallback hostname if no-one could be detected automatically. /// Specify a fallback hostname if no-one could be detected automatically.
/// ///
/// Note: This only exists to make the `hostname` function infallible. /// Note: This only exists to make the `hostname` function infallible.
#[clap(long, default_value = "<UNKNOWN>")] #[arg(long, default_value = "<UNKNOWN>")]
pub hostname_fallback: String, pub hostname_fallback: String,
/// Specify a fallback CPU name if no-one could be detected automatically. /// Specify a fallback CPU name if no-one could be detected automatically.
/// ///
/// Note: This only exists to make the `cpuname` function infallible. /// Note: This only exists to make the `cpuname` function infallible.
#[clap(long, default_value = "<UNKNOWN>")] #[arg(long, default_value = "<UNKNOWN>")]
pub cpuname_fallback: String, pub cpuname_fallback: String,
} }
@@ -31,23 +31,23 @@ pub struct WeightParams {
/// File or directory to write the *weight* files to. /// File or directory to write the *weight* files to.
/// ///
/// For Substrate this should be `frame/support/src/weights`. /// For Substrate this should be `frame/support/src/weights`.
#[clap(long)] #[arg(long)]
pub weight_path: Option<PathBuf>, pub weight_path: Option<PathBuf>,
/// Select a specific metric to calculate the final weight output. /// Select a specific metric to calculate the final weight output.
#[clap(long = "metric", default_value = "average")] #[arg(long = "metric", default_value = "average")]
pub weight_metric: StatSelect, pub weight_metric: StatSelect,
/// Multiply the resulting weight with the given factor. Must be positive. /// Multiply the resulting weight with the given factor. Must be positive.
/// ///
/// Is applied before `weight_add`. /// Is applied before `weight_add`.
#[clap(long = "mul", default_value = "1")] #[arg(long = "mul", default_value_t = 1.0)]
pub weight_mul: f64, pub weight_mul: f64,
/// Add the given offset to the resulting weight. /// Add the given offset to the resulting weight.
/// ///
/// Is applied after `weight_mul`. /// Is applied after `weight_mul`.
#[clap(long = "add", default_value = "0")] #[arg(long = "add", default_value_t = 0)]
pub weight_add: u64, pub weight_add: u64,
} }
@@ -68,54 +68,54 @@ pub struct StorageParams {
pub hostinfo: HostInfoParams, pub hostinfo: HostInfoParams,
/// Skip the `read` benchmark. /// Skip the `read` benchmark.
#[clap(long)] #[arg(long)]
pub skip_read: bool, pub skip_read: bool,
/// Skip the `write` benchmark. /// Skip the `write` benchmark.
#[clap(long)] #[arg(long)]
pub skip_write: bool, pub skip_write: bool,
/// Specify the Handlebars template to use for outputting benchmark results. /// Specify the Handlebars template to use for outputting benchmark results.
#[clap(long)] #[arg(long)]
pub template_path: Option<PathBuf>, pub template_path: Option<PathBuf>,
/// Add a header to the generated weight output file. /// Add a header to the generated weight output file.
/// ///
/// Good for adding LICENSE headers. /// Good for adding LICENSE headers.
#[clap(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
pub header: Option<PathBuf>, pub header: Option<PathBuf>,
/// Path to write the raw 'read' results in JSON format to. Can be a file or directory. /// Path to write the raw 'read' results in JSON format to. Can be a file or directory.
#[clap(long)] #[arg(long)]
pub json_read_path: Option<PathBuf>, pub json_read_path: Option<PathBuf>,
/// Path to write the raw 'write' results in JSON format to. Can be a file or directory. /// Path to write the raw 'write' results in JSON format to. Can be a file or directory.
#[clap(long)] #[arg(long)]
pub json_write_path: Option<PathBuf>, pub json_write_path: Option<PathBuf>,
/// Rounds of warmups before measuring. /// Rounds of warmups before measuring.
#[clap(long, default_value = "1")] #[arg(long, default_value_t = 1)]
pub warmups: u32, pub warmups: u32,
/// The `StateVersion` to use. Substrate `--dev` should use `V1` and Polkadot `V0`. /// The `StateVersion` to use. Substrate `--dev` should use `V1` and Polkadot `V0`.
/// Selecting the wrong version can corrupt the DB. /// Selecting the wrong version can corrupt the DB.
#[clap(long, possible_values = ["0", "1"])] #[arg(long, value_parser = clap::value_parser!(u8).range(0..=1))]
pub state_version: u8, pub state_version: u8,
/// Trie cache size in bytes. /// Trie cache size in bytes.
/// ///
/// Providing `0` will disable the cache. /// Providing `0` will disable the cache.
#[clap(long, value_name = "Bytes", default_value = "67108864")] #[arg(long, value_name = "Bytes", default_value_t = 67108864)]
pub trie_cache_size: usize, pub trie_cache_size: usize,
/// Enable the Trie cache. /// Enable the Trie cache.
/// ///
/// This should only be used for performance analysis and not for final results. /// This should only be used for performance analysis and not for final results.
#[clap(long)] #[arg(long)]
pub enable_trie_cache: bool, pub enable_trie_cache: bool,
/// Include child trees in benchmark. /// Include child trees in benchmark.
#[clap(long)] #[arg(long)]
pub include_child_trees: bool, pub include_child_trees: bool,
} }
@@ -11,7 +11,7 @@ documentation = "https://docs.rs/substrate-frame-cli"
readme = "README.md" readme = "README.md"
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
frame-support = { version = "4.0.0-dev", path = "../../../frame/support" } frame-support = { version = "4.0.0-dev", path = "../../../frame/support" }
frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } frame-system = { version = "4.0.0-dev", path = "../../../frame/system" }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
@@ -28,31 +28,30 @@ use sp_runtime::traits::AccountIdConversion;
/// The `palletid` command /// The `palletid` command
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(name = "palletid", about = "Inspect a module ID address")] #[command(name = "palletid", about = "Inspect a module ID address")]
pub struct PalletIdCmd { pub struct PalletIdCmd {
/// The module ID used to derive the account /// The module ID used to derive the account
id: String, id: String,
/// network address format /// network address format
#[clap( #[arg(
long, long,
value_name = "NETWORK", value_name = "NETWORK",
possible_values = &Ss58AddressFormat::all_names()[..], value_parser = sc_cli::parse_ss58_address_format,
parse(try_from_str = Ss58AddressFormat::try_from),
ignore_case = true, ignore_case = true,
)] )]
pub network: Option<Ss58AddressFormat>, pub network: Option<Ss58AddressFormat>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[clap(flatten)] #[command(flatten)]
pub output_scheme: OutputTypeFlag, pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[clap(flatten)] #[command(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[clap(flatten)] #[command(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
} }
@@ -14,4 +14,4 @@ kitchensink-runtime = { version = "3.0.0-dev", path = "../../../../bin/node/runt
generate-bags = { version = "4.0.0-dev", path = "../" } generate-bags = { version = "4.0.0-dev", path = "../" }
# third-party # third-party
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
@@ -25,19 +25,19 @@ use std::path::PathBuf;
// #[clap(author, version, about)] // #[clap(author, version, about)]
struct Opt { struct Opt {
/// How many bags to generate. /// How many bags to generate.
#[clap(long, default_value = "200")] #[arg(long, default_value_t = 200)]
n_bags: usize, n_bags: usize,
/// Where to write the output. /// Where to write the output.
output: PathBuf, output: PathBuf,
/// The total issuance of the currency used to create `VoteWeight`. /// The total issuance of the currency used to create `VoteWeight`.
#[clap(short, long)] #[arg(short, long)]
total_issuance: u128, total_issuance: u128,
/// The minimum account balance (i.e. existential deposit) for the currency used to create /// The minimum account balance (i.e. existential deposit) for the currency used to create
/// `VoteWeight`. /// `VoteWeight`.
#[clap(short, long)] #[arg(short, long)]
minimum_balance: u128, minimum_balance: u128,
} }
@@ -13,7 +13,7 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.1.18", features = ["derive"] } clap = { version = "4.0.9", features = ["derive"] }
log = "0.4.17" log = "0.4.17"
parity-scale-codec = "3.0.0" parity-scale-codec = "3.0.0"
serde = "1.0.136" serde = "1.0.136"
@@ -33,11 +33,11 @@ use std::{fmt::Debug, str::FromStr};
#[derive(Debug, Clone, clap::Parser)] #[derive(Debug, Clone, clap::Parser)]
pub struct ExecuteBlockCmd { pub struct ExecuteBlockCmd {
/// Overwrite the wasm code in state or not. /// Overwrite the wasm code in state or not.
#[clap(long)] #[arg(long)]
overwrite_wasm_code: bool, overwrite_wasm_code: bool,
/// If set the state root check is disabled. /// If set the state root check is disabled.
#[clap(long)] #[arg(long)]
no_state_root_check: bool, no_state_root_check: bool,
/// Which try-state targets to execute when running this command. /// Which try-state targets to execute when running this command.
@@ -49,17 +49,16 @@ pub struct ExecuteBlockCmd {
/// `Staking, System`). /// `Staking, System`).
/// - `rr-[x]` where `[x]` is a number. Then, the given number of pallets are checked in a /// - `rr-[x]` where `[x]` is a number. Then, the given number of pallets are checked in a
/// round-robin fashion. /// round-robin fashion.
#[clap(long, default_value = "none")] #[arg(long, default_value = "none")]
try_state: frame_try_runtime::TryStateSelect, try_state: frame_try_runtime::TryStateSelect,
/// The block hash at which to fetch the block. /// The block hash at which to fetch the block.
/// ///
/// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// If the `live` state type is being used, then this can be omitted, and is equal to whatever
/// the `state::at` is. Only use this (with care) when combined with a snapshot. /// the `state::at` is. Only use this (with care) when combined with a snapshot.
#[clap( #[arg(
long, long,
multiple_values = false, value_parser = crate::parse::hash
parse(try_from_str = crate::parse::hash)
)] )]
block_at: Option<String>, block_at: Option<String>,
@@ -67,10 +66,9 @@ pub struct ExecuteBlockCmd {
/// ///
/// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// If the `live` state type is being used, then this can be omitted, and is equal to whatever
/// the `state::uri` is. Only use this (with care) when combined with a snapshot. /// the `state::uri` is. Only use this (with care) when combined with a snapshot.
#[clap( #[arg(
long, long,
multiple_values = false, value_parser = crate::parse::url
parse(try_from_str = crate::parse::url)
)] )]
block_ws_uri: Option<String>, block_ws_uri: Option<String>,
@@ -79,7 +77,7 @@ pub struct ExecuteBlockCmd {
/// For this command only, if the `live` is used, then state of the parent block is fetched. /// For this command only, if the `live` is used, then state of the parent block is fetched.
/// ///
/// If `block_at` is provided, then the [`State::Live::at`] is being ignored. /// If `block_at` is provided, then the [`State::Live::at`] is being ignored.
#[clap(subcommand)] #[command(subcommand)]
state: State, state: State,
} }
@@ -43,11 +43,11 @@ const UN_SUB: &str = "chain_unsubscribeFinalizedHeads";
#[derive(Debug, Clone, clap::Parser)] #[derive(Debug, Clone, clap::Parser)]
pub struct FollowChainCmd { pub struct FollowChainCmd {
/// The url to connect to. /// The url to connect to.
#[clap(short, long, parse(try_from_str = parse::url))] #[arg(short, long, value_parser = parse::url)]
uri: String, uri: String,
/// If set, then the state root check is enabled. /// If set, then the state root check is enabled.
#[clap(long)] #[arg(long)]
state_root_check: bool, state_root_check: bool,
/// Which try-state targets to execute when running this command. /// Which try-state targets to execute when running this command.
@@ -59,11 +59,11 @@ pub struct FollowChainCmd {
/// `Staking, System`). /// `Staking, System`).
/// - `rr-[x]` where `[x]` is a number. Then, the given number of pallets are checked in a /// - `rr-[x]` where `[x]` is a number. Then, the given number of pallets are checked in a
/// round-robin fashion. /// round-robin fashion.
#[clap(long, default_value = "none")] #[arg(long, default_value = "none")]
try_state: frame_try_runtime::TryStateSelect, try_state: frame_try_runtime::TryStateSelect,
/// If present, a single connection to a node will be kept and reused for fetching blocks. /// If present, a single connection to a node will be kept and reused for fetching blocks.
#[clap(long)] #[arg(long)]
keep_connection: bool, keep_connection: bool,
} }
@@ -31,17 +31,16 @@ use std::{fmt::Debug, str::FromStr};
#[derive(Debug, Clone, clap::Parser)] #[derive(Debug, Clone, clap::Parser)]
pub struct OffchainWorkerCmd { pub struct OffchainWorkerCmd {
/// Overwrite the wasm code in state or not. /// Overwrite the wasm code in state or not.
#[clap(long)] #[arg(long)]
overwrite_wasm_code: bool, overwrite_wasm_code: bool,
/// The block hash at which to fetch the header. /// The block hash at which to fetch the header.
/// ///
/// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// If the `live` state type is being used, then this can be omitted, and is equal to whatever
/// the `state::at` is. Only use this (with care) when combined with a snapshot. /// the `state::at` is. Only use this (with care) when combined with a snapshot.
#[clap( #[arg(
long, long,
multiple_values = false, value_parser = parse::hash
parse(try_from_str = parse::hash)
)] )]
header_at: Option<String>, header_at: Option<String>,
@@ -49,15 +48,14 @@ pub struct OffchainWorkerCmd {
/// ///
/// If the `live` state type is being used, then this can be omitted, and is equal to whatever /// If the `live` state type is being used, then this can be omitted, and is equal to whatever
/// the `state::uri` is. Only use this (with care) when combined with a snapshot. /// the `state::uri` is. Only use this (with care) when combined with a snapshot.
#[clap( #[arg(
long, long,
multiple_values = false, value_parser = parse::url
parse(try_from_str = parse::url)
)] )]
header_ws_uri: Option<String>, header_ws_uri: Option<String>,
/// The state type to use. /// The state type to use.
#[clap(subcommand)] #[command(subcommand)]
pub state: State, pub state: State,
} }
@@ -32,7 +32,7 @@ use crate::{
#[derive(Debug, Clone, clap::Parser)] #[derive(Debug, Clone, clap::Parser)]
pub struct OnRuntimeUpgradeCmd { pub struct OnRuntimeUpgradeCmd {
/// The state type to use. /// The state type to use.
#[clap(subcommand)] #[command(subcommand)]
pub state: State, pub state: State,
} }
@@ -385,6 +385,7 @@ pub enum Command {
/// Shared parameters of the `try-runtime` commands /// Shared parameters of the `try-runtime` commands
#[derive(Debug, Clone, clap::Parser)] #[derive(Debug, Clone, clap::Parser)]
#[group(skip)]
pub struct SharedParams { pub struct SharedParams {
/// Shared parameters of substrate cli. /// Shared parameters of substrate cli.
#[allow(missing_docs)] #[allow(missing_docs)]
@@ -392,41 +393,41 @@ pub struct SharedParams {
pub shared_params: sc_cli::SharedParams, pub shared_params: sc_cli::SharedParams,
/// The execution strategy that should be used. /// The execution strategy that should be used.
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true, default_value = "wasm")] #[arg(long, value_name = "STRATEGY", value_enum, ignore_case = true, default_value_t = ExecutionStrategy::Wasm)]
pub execution: ExecutionStrategy, pub execution: ExecutionStrategy,
/// Type of wasm execution used. /// Type of wasm execution used.
#[clap( #[arg(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = WasmExecutionMethod::variants(), value_enum,
ignore_case = true, ignore_case = true,
default_value = DEFAULT_WASM_EXECUTION_METHOD, default_value_t = DEFAULT_WASM_EXECUTION_METHOD,
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
/// The WASM instantiation method to use. /// The WASM instantiation method to use.
/// ///
/// Only has an effect when `wasm-execution` is set to `compiled`. /// Only has an effect when `wasm-execution` is set to `compiled`.
#[clap( #[arg(
long = "wasm-instantiation-strategy", long = "wasm-instantiation-strategy",
value_name = "STRATEGY", value_name = "STRATEGY",
default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY, default_value_t = DEFAULT_WASMTIME_INSTANTIATION_STRATEGY,
arg_enum, value_enum,
)] )]
pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy, pub wasmtime_instantiation_strategy: WasmtimeInstantiationStrategy,
/// The number of 64KB pages to allocate for Wasm execution. Defaults to /// The number of 64KB pages to allocate for Wasm execution. Defaults to
/// [`sc_service::Configuration.default_heap_pages`]. /// [`sc_service::Configuration.default_heap_pages`].
#[clap(long)] #[arg(long)]
pub heap_pages: Option<u64>, pub heap_pages: Option<u64>,
/// When enabled, the spec check will not panic, and instead only show a warning. /// When enabled, the spec check will not panic, and instead only show a warning.
#[clap(long)] #[arg(long)]
pub no_spec_check_panic: bool, pub no_spec_check_panic: bool,
/// State version that is used by the chain. /// State version that is used by the chain.
#[clap(long, default_value = "1", parse(try_from_str = parse::state_version))] #[arg(long, default_value_t = StateVersion::V1, value_parser = parse::state_version)]
pub state_version: StateVersion, pub state_version: StateVersion,
} }
@@ -438,7 +439,7 @@ pub struct TryRuntimeCmd {
#[clap(flatten)] #[clap(flatten)]
pub shared: SharedParams, pub shared: SharedParams,
#[clap(subcommand)] #[command(subcommand)]
pub command: Command, pub command: Command,
} }
@@ -449,17 +450,17 @@ pub enum State {
/// ///
/// This can be crated by passing a value to [`State::Live::snapshot_path`]. /// This can be crated by passing a value to [`State::Live::snapshot_path`].
Snap { Snap {
#[clap(short, long)] #[arg(short, long)]
snapshot_path: PathBuf, snapshot_path: PathBuf,
}, },
/// Use a live chain as the source of runtime state. /// Use a live chain as the source of runtime state.
Live { Live {
/// The url to connect to. /// The url to connect to.
#[clap( #[arg(
short, short,
long, long,
parse(try_from_str = parse::url), value_parser = parse::url,
)] )]
uri: String, uri: String,
@@ -467,21 +468,20 @@ pub enum State {
/// ///
/// If non provided, then the latest finalized head is used. This is particularly useful /// If non provided, then the latest finalized head is used. This is particularly useful
/// for [`Command::OnRuntimeUpgrade`]. /// for [`Command::OnRuntimeUpgrade`].
#[clap( #[arg(
short, short,
long, long,
multiple_values = false, value_parser = parse::hash,
parse(try_from_str = parse::hash),
)] )]
at: Option<String>, at: Option<String>,
/// An optional state snapshot file to WRITE to. Not written if set to `None`. /// An optional state snapshot file to WRITE to. Not written if set to `None`.
#[clap(short, long)] #[arg(short, long)]
snapshot_path: Option<PathBuf>, snapshot_path: Option<PathBuf>,
/// A pallet to scrape. Can be provided multiple times. If empty, entire chain state will /// A pallet to scrape. Can be provided multiple times. If empty, entire chain state will
/// be scraped. /// be scraped.
#[clap(short, long, multiple_values = true)] #[arg(short, long, num_args = 1..)]
pallet: Vec<String>, pallet: Vec<String>,
/// Fetch the child-keys as well. /// Fetch the child-keys as well.
@@ -489,7 +489,7 @@ pub enum State {
/// Default is `false`, if specific `--pallets` are specified, `true` otherwise. In other /// Default is `false`, if specific `--pallets` are specified, `true` otherwise. In other
/// words, if you scrape the whole state the child tree data is included out of the box. /// words, if you scrape the whole state the child tree data is included out of the box.
/// Otherwise, it must be enabled explicitly using this flag. /// Otherwise, it must be enabled explicitly using this flag.
#[clap(long)] #[arg(long)]
child_tree: bool, child_tree: bool,
}, },
} }