use clap3 instead of structopt (#10632)

* use clap3 instead of structopt

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* format

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* update ss58-registry and revert some nits

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* Fix clippy and doc

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* update clap to 3.0.7

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* Apply review suggestions

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* remove useless option long name

Signed-off-by: koushiro <koushiro.cqx@gmail.com>

* cargo fmt

Signed-off-by: koushiro <koushiro.cqx@gmail.com>
This commit is contained in:
Qinxuan Chen
2022-01-25 00:28:46 +08:00
committed by GitHub
parent d1ff02d31e
commit e327b734bc
66 changed files with 660 additions and 768 deletions
@@ -9,7 +9,7 @@ license = "GPL-3.0"
toml = "0.4" toml = "0.4"
tar = "0.4" tar = "0.4"
glob = "0.2" glob = "0.2"
structopt = "0.3" clap = { version = "3.0", features = ["derive"] }
tempfile = "3" tempfile = "3"
fs_extra = "1" fs_extra = "1"
git2 = "0.8" git2 = "0.8"
@@ -1,4 +1,4 @@
use structopt::StructOpt; use clap::Parser;
use std::{ use std::{
collections::HashMap, collections::HashMap,
@@ -26,13 +26,13 @@ const SUBSTRATE_GIT_URL: &str = "https://github.com/paritytech/substrate.git";
type CargoToml = HashMap<String, toml::Value>; type CargoToml = HashMap<String, toml::Value>;
#[derive(StructOpt)] #[derive(Parser)]
struct Options { struct Options {
/// The path to the `node-template` source. /// The path to the `node-template` source.
#[structopt(parse(from_os_str))] #[clap(parse(from_os_str))]
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.
#[structopt(parse(from_os_str))] #[clap(parse(from_os_str))]
output: PathBuf, output: PathBuf,
} }
@@ -209,7 +209,7 @@ fn build_and_test(path: &Path, cargo_tomls: &[PathBuf]) {
} }
fn main() { fn main() {
let options = Options::from_args(); let options = Options::parse();
let build_dir = tempfile::tempdir().expect("Creates temp build dir"); let build_dir = tempfile::tempdir().expect("Creates temp build dir");
@@ -261,8 +261,7 @@ fn main() {
// adding root rustfmt to node template build path // adding root rustfmt to node template build path
let node_template_rustfmt_toml_path = node_template_path.join("rustfmt.toml"); let node_template_rustfmt_toml_path = node_template_path.join("rustfmt.toml");
let root_rustfmt_toml = let root_rustfmt_toml = &options.node_template.join("../../rustfmt.toml");
&options.node_template.join("../../rustfmt.toml");
if root_rustfmt_toml.exists() { if root_rustfmt_toml.exists() {
fs::copy(&root_rustfmt_toml, &node_template_rustfmt_toml_path) fs::copy(&root_rustfmt_toml, &node_template_rustfmt_toml_path)
.expect("Copying rustfmt.toml."); .expect("Copying rustfmt.toml.");
+85 -67
View File
@@ -928,13 +928,13 @@ name = "chain-spec-builder"
version = "2.0.0" version = "2.0.0"
dependencies = [ dependencies = [
"ansi_term", "ansi_term",
"clap 3.0.7",
"node-cli", "node-cli",
"rand 0.7.3", "rand 0.8.4",
"sc-chain-spec", "sc-chain-spec",
"sc-keystore", "sc-keystore",
"sp-core", "sp-core",
"sp-keystore", "sp-keystore",
"structopt",
] ]
[[package]] [[package]]
@@ -996,13 +996,48 @@ version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [ dependencies = [
"ansi_term", "bitflags",
"textwrap 0.11.0",
"unicode-width",
]
[[package]]
name = "clap"
version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12e8611f9ae4e068fa3e56931fded356ff745e70987ff76924a6e0ab1c8ef2e3"
dependencies = [
"atty", "atty",
"bitflags", "bitflags",
"strsim 0.8.0", "clap_derive",
"textwrap", "indexmap",
"unicode-width", "lazy_static",
"vec_map", "os_str_bytes",
"strsim",
"termcolor",
"textwrap 0.14.2",
]
[[package]]
name = "clap_complete"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a394f7ec0715b42a4e52b294984c27c9a61f77c8d82f7774c5198350be143f19"
dependencies = [
"clap 3.0.7",
]
[[package]]
name = "clap_derive"
version = "3.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41a0645a430ec9136d2d701e54a95d557de12649a9dd7109ced3187e648ac824"
dependencies = [
"heck 0.4.0",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
] ]
[[package]] [[package]]
@@ -1256,7 +1291,7 @@ checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10"
dependencies = [ dependencies = [
"atty", "atty",
"cast", "cast",
"clap", "clap 2.34.0",
"criterion-plot", "criterion-plot",
"csv", "csv",
"futures 0.3.16", "futures 0.3.16",
@@ -1483,7 +1518,7 @@ dependencies = [
"ident_case", "ident_case",
"proc-macro2", "proc-macro2",
"quote", "quote",
"strsim 0.10.0", "strsim",
"syn", "syn",
] ]
@@ -1741,7 +1776,7 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595" checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595"
dependencies = [ dependencies = [
"heck", "heck 0.3.2",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn",
@@ -2020,6 +2055,7 @@ version = "4.0.0-dev"
dependencies = [ dependencies = [
"Inflector", "Inflector",
"chrono", "chrono",
"clap 3.0.7",
"frame-benchmarking", "frame-benchmarking",
"frame-support", "frame-support",
"handlebars", "handlebars",
@@ -2036,7 +2072,6 @@ dependencies = [
"sp-keystore", "sp-keystore",
"sp-runtime", "sp-runtime",
"sp-state-machine", "sp-state-machine",
"structopt",
] ]
[[package]] [[package]]
@@ -2450,7 +2485,6 @@ dependencies = [
"num-format", "num-format",
"pallet-staking", "pallet-staking",
"sp-io", "sp-io",
"structopt",
] ]
[[package]] [[package]]
@@ -2653,6 +2687,12 @@ dependencies = [
"unicode-segmentation", "unicode-segmentation",
] ]
[[package]]
name = "heck"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.1.18" version = "0.1.18"
@@ -4516,6 +4556,7 @@ dependencies = [
name = "node-bench" name = "node-bench"
version = "0.9.0-dev" version = "0.9.0-dev"
dependencies = [ dependencies = [
"clap 3.0.7",
"derive_more", "derive_more",
"fs_extra", "fs_extra",
"futures 0.3.16", "futures 0.3.16",
@@ -4545,7 +4586,6 @@ dependencies = [
"sp-timestamp", "sp-timestamp",
"sp-tracing", "sp-tracing",
"sp-trie", "sp-trie",
"structopt",
"tempfile", "tempfile",
] ]
@@ -4555,6 +4595,8 @@ version = "3.0.0-dev"
dependencies = [ dependencies = [
"assert_cmd", "assert_cmd",
"async-std", "async-std",
"clap 3.0.7",
"clap_complete",
"criterion", "criterion",
"frame-benchmarking-cli", "frame-benchmarking-cli",
"frame-system", "frame-system",
@@ -4576,7 +4618,7 @@ dependencies = [
"pallet-transaction-payment", "pallet-transaction-payment",
"parity-scale-codec", "parity-scale-codec",
"platforms", "platforms",
"rand 0.7.3", "rand 0.8.4",
"regex", "regex",
"remote-externalities", "remote-externalities",
"sc-authority-discovery", "sc-authority-discovery",
@@ -4622,7 +4664,6 @@ dependencies = [
"sp-transaction-pool", "sp-transaction-pool",
"sp-transaction-storage-proof", "sp-transaction-storage-proof",
"sp-trie", "sp-trie",
"structopt",
"substrate-build-script-utils", "substrate-build-script-utils",
"substrate-frame-cli", "substrate-frame-cli",
"tempfile", "tempfile",
@@ -4668,6 +4709,7 @@ dependencies = [
name = "node-inspect" name = "node-inspect"
version = "0.9.0-dev" version = "0.9.0-dev"
dependencies = [ dependencies = [
"clap 3.0.7",
"derive_more", "derive_more",
"parity-scale-codec", "parity-scale-codec",
"sc-cli", "sc-cli",
@@ -4677,7 +4719,6 @@ dependencies = [
"sp-blockchain", "sp-blockchain",
"sp-core", "sp-core",
"sp-runtime", "sp-runtime",
"structopt",
] ]
[[package]] [[package]]
@@ -4811,15 +4852,16 @@ dependencies = [
name = "node-runtime-generate-bags" name = "node-runtime-generate-bags"
version = "3.0.0" version = "3.0.0"
dependencies = [ dependencies = [
"clap 3.0.7",
"generate-bags", "generate-bags",
"node-runtime", "node-runtime",
"structopt",
] ]
[[package]] [[package]]
name = "node-template" name = "node-template"
version = "3.0.0" version = "3.0.0"
dependencies = [ dependencies = [
"clap 3.0.7",
"frame-benchmarking", "frame-benchmarking",
"frame-benchmarking-cli", "frame-benchmarking-cli",
"jsonrpc-core", "jsonrpc-core",
@@ -4848,7 +4890,6 @@ dependencies = [
"sp-finality-grandpa", "sp-finality-grandpa",
"sp-runtime", "sp-runtime",
"sp-timestamp", "sp-timestamp",
"structopt",
"substrate-build-script-utils", "substrate-build-script-utils",
"substrate-frame-rpc-system", "substrate-frame-rpc-system",
] ]
@@ -5140,6 +5181,15 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "os_str_bytes"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e22443d1643a904602595ba1cd8f7d896afe56d26712531c5ff73a15b2fbf64"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "output_vt100" name = "output_vt100"
version = "0.1.2" version = "0.1.2"
@@ -5323,7 +5373,6 @@ dependencies = [
name = "pallet-bags-list-remote-tests" name = "pallet-bags-list-remote-tests"
version = "4.0.0-dev" version = "4.0.0-dev"
dependencies = [ dependencies = [
"clap",
"frame-election-provider-support", "frame-election-provider-support",
"frame-support", "frame-support",
"frame-system", "frame-system",
@@ -5336,7 +5385,6 @@ dependencies = [
"sp-std", "sp-std",
"sp-storage", "sp-storage",
"sp-tracing", "sp-tracing",
"structopt",
"tokio", "tokio",
] ]
@@ -6912,7 +6960,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5" checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5"
dependencies = [ dependencies = [
"bytes 1.1.0", "bytes 1.1.0",
"heck", "heck 0.3.2",
"itertools", "itertools",
"lazy_static", "lazy_static",
"log 0.4.14", "log 0.4.14",
@@ -7695,6 +7743,7 @@ name = "sc-cli"
version = "0.10.0-dev" version = "0.10.0-dev"
dependencies = [ dependencies = [
"chrono", "chrono",
"clap 3.0.7",
"fdlimit", "fdlimit",
"futures 0.3.16", "futures 0.3.16",
"hex", "hex",
@@ -7721,7 +7770,6 @@ dependencies = [
"sp-panic-handler", "sp-panic-handler",
"sp-runtime", "sp-runtime",
"sp-version", "sp-version",
"structopt",
"tempfile", "tempfile",
"thiserror", "thiserror",
"tiny-bip39", "tiny-bip39",
@@ -9624,13 +9672,13 @@ 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.0.7",
"honggfuzz", "honggfuzz",
"parity-scale-codec", "parity-scale-codec",
"rand 0.7.3", "rand 0.8.4",
"scale-info", "scale-info",
"sp-npos-elections", "sp-npos-elections",
"sp-runtime", "sp-runtime",
"structopt",
] ]
[[package]] [[package]]
@@ -10001,9 +10049,9 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]] [[package]]
name = "ss58-registry" name = "ss58-registry"
version = "1.10.0" version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c83f0afe7e571565ef9aae7b0e4fb30fcaec4ebb9aea2f00489b772782aa03a4" checksum = "1230685dc82f8699110640244d361a7099c602f08bddc5c90765a5153b4881dc"
dependencies = [ dependencies = [
"Inflector", "Inflector",
"proc-macro2", "proc-macro2",
@@ -10038,42 +10086,12 @@ dependencies = [
"rand 0.8.4", "rand 0.8.4",
] ]
[[package]]
name = "strsim"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]] [[package]]
name = "strsim" name = "strsim"
version = "0.10.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "structopt"
version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40b9788f4202aa75c240ecc9c15c65185e6a39ccdeb0fd5d008b98825464c87c"
dependencies = [
"clap",
"lazy_static",
"structopt-derive",
]
[[package]]
name = "structopt-derive"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dcb5ae327f9cc13b68763b5749770cb9e048a99bd9dfdfa58d0cf05d5f64afe0"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "strum" name = "strum"
version = "0.22.0" version = "0.22.0"
@@ -10089,7 +10107,7 @@ version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb" checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb"
dependencies = [ dependencies = [
"heck", "heck 0.3.2",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn", "syn",
@@ -10101,7 +10119,7 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38" checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38"
dependencies = [ dependencies = [
"heck", "heck 0.3.2",
"proc-macro2", "proc-macro2",
"quote", "quote",
"rustversion", "rustversion",
@@ -10112,8 +10130,8 @@ dependencies = [
name = "subkey" name = "subkey"
version = "2.0.1" version = "2.0.1"
dependencies = [ dependencies = [
"clap 3.0.7",
"sc-cli", "sc-cli",
"structopt",
] ]
[[package]] [[package]]
@@ -10140,12 +10158,12 @@ dependencies = [
name = "substrate-frame-cli" name = "substrate-frame-cli"
version = "4.0.0-dev" version = "4.0.0-dev"
dependencies = [ dependencies = [
"clap 3.0.7",
"frame-support", "frame-support",
"frame-system", "frame-system",
"sc-cli", "sc-cli",
"sp-core", "sp-core",
"sp-runtime", "sp-runtime",
"structopt",
] ]
[[package]] [[package]]
@@ -10428,6 +10446,12 @@ dependencies = [
"unicode-width", "unicode-width",
] ]
[[package]]
name = "textwrap"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80"
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "1.0.30" version = "1.0.30"
@@ -10920,6 +10944,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.0.7",
"jsonrpsee", "jsonrpsee",
"log 0.4.14", "log 0.4.14",
"parity-scale-codec", "parity-scale-codec",
@@ -10936,7 +10961,6 @@ dependencies = [
"sp-runtime", "sp-runtime",
"sp-state-machine", "sp-state-machine",
"sp-version", "sp-version",
"structopt",
"zstd", "zstd",
] ]
@@ -11146,12 +11170,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eafc1b9b2dfc6f5529177b62cf806484db55b32dc7c9658a118e11bbeb33061d" checksum = "eafc1b9b2dfc6f5529177b62cf806484db55b32dc7c9658a118e11bbeb33061d"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.1.5" version = "0.1.5"
+2 -4
View File
@@ -17,7 +17,7 @@ targets = ["x86_64-unknown-linux-gnu"]
name = "node-template" name = "node-template"
[dependencies] [dependencies]
structopt = "0.3.25" clap = { version = "3.0", 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 = "4.1.0-dev", path = "../../../primitives/core" } sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
@@ -59,6 +59,4 @@ substrate-build-script-utils = { version = "3.0.0", path = "../../../utils/build
[features] [features]
default = [] default = []
runtime-benchmarks = [ runtime-benchmarks = ["node-template-runtime/runtime-benchmarks"]
"node-template-runtime/runtime-benchmarks",
]
+7 -6
View File
@@ -1,19 +1,20 @@
use sc_cli::RunCmd; use sc_cli::RunCmd;
use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Parser)]
pub struct Cli { pub struct Cli {
#[structopt(subcommand)] #[clap(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[structopt(flatten)] #[clap(flatten)]
pub run: RunCmd, pub run: RunCmd,
} }
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Subcommand)]
pub enum Subcommand { pub enum Subcommand {
/// Key management cli utilities /// Key management cli utilities
#[clap(subcommand)]
Key(sc_cli::KeySubcommand), Key(sc_cli::KeySubcommand),
/// Build a chain specification. /// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd), BuildSpec(sc_cli::BuildSpecCmd),
@@ -36,6 +37,6 @@ pub enum Subcommand {
Revert(sc_cli::RevertCmd), Revert(sc_cli::RevertCmd),
/// The custom benchmark subcommand benchmarking runtime pallets. /// The custom benchmark subcommand benchmarking runtime pallets.
#[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] #[clap(name = "benchmark", about = "Benchmark runtime pallets.")]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
} }
+2 -4
View File
@@ -9,6 +9,7 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
log = "0.4.8" log = "0.4.8"
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" }
@@ -18,7 +19,6 @@ sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" }
sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" }
serde = "1.0.132" serde = "1.0.132"
serde_json = "1.0.74" serde_json = "1.0.74"
structopt = "0.3"
derive_more = "0.99.16" derive_more = "0.99.16"
kvdb = "0.10.0" kvdb = "0.10.0"
kvdb-rocksdb = "0.14.0" kvdb-rocksdb = "0.14.0"
@@ -35,9 +35,7 @@ fs_extra = "1"
hex = "0.4.0" hex = "0.4.0"
rand = { version = "0.7.2", features = ["small_rng"] } rand = { version = "0.7.2", features = ["small_rng"] }
lazy_static = "1.4.0" lazy_static = "1.4.0"
parity-util-mem = { version = "0.10.2", default-features = false, features = [ parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] }
"primitive-types",
] }
parity-db = { version = "0.3" } parity-db = { version = "0.3" }
sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" } sc-transaction-pool = { version = "4.0.0-dev", path = "../../../client/transaction-pool" }
sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" } sc-transaction-pool-api = { version = "4.0.0-dev", path = "../../../client/transaction-pool/api" }
+8 -8
View File
@@ -28,7 +28,7 @@ mod tempdb;
mod trie; mod trie;
mod txpool; mod txpool;
use structopt::StructOpt; use clap::Parser;
use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile}; use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile};
@@ -42,19 +42,19 @@ use crate::{
txpool::PoolBenchmarkDescription, txpool::PoolBenchmarkDescription,
}; };
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt(name = "node-bench", about = "Node integration benchmarks")] #[clap(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.
#[structopt(short, long)] #[clap(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)
#[structopt(short, long)] #[clap(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.
#[structopt(long)] #[clap(long)]
transactions: Option<usize>, transactions: Option<usize>,
/// Mode /// Mode
@@ -72,12 +72,12 @@ 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.
#[structopt(short, long, default_value = "regular")] #[clap(short, long, default_value = "regular")]
mode: BenchmarkMode, mode: BenchmarkMode,
} }
fn main() { fn main() {
let opt = Opt::from_args(); let opt = Opt::parse();
if !opt.json { if !opt.json {
sp_tracing::try_init_simple(); sp_tracing::try_init_simple();
+10 -15
View File
@@ -34,13 +34,13 @@ crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
# third-party dependencies # third-party dependencies
clap = { version = "3.0", features = ["derive"], optional = true }
codec = { package = "parity-scale-codec", version = "2.0.0" } codec = { package = "parity-scale-codec", version = "2.0.0" }
serde = { version = "1.0.132", features = ["derive"] } serde = { version = "1.0.132", features = ["derive"] }
futures = "0.3.16" futures = "0.3.16"
hex-literal = "0.3.4" hex-literal = "0.3.4"
log = "0.4.8" log = "0.4.8"
rand = "0.7.2" rand = "0.8"
structopt = { version = "0.3.25", optional = true }
# primitives # primitives
sp-authority-discovery = { version = "4.0.0-dev", path = "../../../primitives/authority-discovery" } sp-authority-discovery = { version = "4.0.0-dev", path = "../../../primitives/authority-discovery" }
@@ -97,12 +97,8 @@ node-inspect = { version = "0.9.0-dev", optional = true, path = "../inspect" }
try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" } try-runtime-cli = { version = "0.10.0-dev", optional = true, path = "../../../utils/frame/try-runtime/cli" }
[target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies] [target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies]
node-executor = { version = "3.0.0-dev", path = "../executor", features = [ node-executor = { version = "3.0.0-dev", path = "../executor", features = ["wasmtime"] }
"wasmtime", sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = ["wasmtime"] }
] }
sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = [
"wasmtime",
] }
sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service", features = [ sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../client/service", features = [
"wasmtime", "wasmtime",
] } ] }
@@ -129,7 +125,7 @@ regex = "1"
platforms = "2.0" platforms = "2.0"
async-std = { version = "1.10.0", features = ["attributes"] } async-std = { version = "1.10.0", features = ["attributes"] }
soketto = "0.4.2" soketto = "0.4.2"
criterion = { version = "0.3.5", features = [ "async_tokio" ] } criterion = { version = "0.3.5", features = ["async_tokio"] }
tokio = { version = "1.15", features = ["macros", "time"] } tokio = { version = "1.15", features = ["macros", "time"] }
jsonrpsee-ws-client = "0.4.1" jsonrpsee-ws-client = "0.4.1"
wait-timeout = "0.2" wait-timeout = "0.2"
@@ -137,7 +133,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]
structopt = { version = "0.3.25", optional = true } clap = { version = "3.0", optional = true }
clap_complete = { version = "3.0", 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" }
@@ -155,14 +152,12 @@ cli = [
"frame-benchmarking-cli", "frame-benchmarking-cli",
"substrate-frame-cli", "substrate-frame-cli",
"sc-service/db", "sc-service/db",
"structopt", "clap",
"clap_complete",
"substrate-build-script-utils", "substrate-build-script-utils",
"try-runtime-cli", "try-runtime-cli",
] ]
runtime-benchmarks = [ runtime-benchmarks = ["node-runtime/runtime-benchmarks", "frame-benchmarking-cli"]
"node-runtime/runtime-benchmarks",
"frame-benchmarking-cli",
]
# Enable features that allow the runtime to be tried and debugged. Name might be subject to change # Enable features that allow the runtime to be tried and debugged. Name might be subject to change
# in the near future. # in the near future.
try-runtime = ["node-runtime/try-runtime", "try-runtime-cli"] try-runtime = ["node-runtime/try-runtime", "try-runtime-cli"]
+4 -4
View File
@@ -25,7 +25,8 @@ fn main() {
mod cli { mod cli {
include!("src/cli.rs"); include!("src/cli.rs");
use sc_cli::structopt::clap::Shell; use clap::{ArgEnum, IntoApp};
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};
@@ -37,9 +38,8 @@ mod cli {
} }
/// Build shell completion scripts for all known shells /// Build shell completion scripts for all known shells
/// Full list in https://github.com/kbknapp/clap-rs/blob/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9/src/app/parser.rs#L123
fn build_shell_completion() { fn build_shell_completion() {
for shell in &[Shell::Bash, Shell::Fish, Shell::Zsh, Shell::Elvish, Shell::PowerShell] { for shell in Shell::value_variants() {
build_completion(shell); build_completion(shell);
} }
} }
@@ -61,6 +61,6 @@ mod cli {
fs::create_dir(&path).ok(); fs::create_dir(&path).ok();
Cli::clap().gen_completions("substrate-node", *shell, &path); let _ = generate_to(*shell, &mut Cli::into_app(), "substrate-node", &path);
} }
} }
+15 -16
View File
@@ -16,35 +16,30 @@
// 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/>.
use sc_cli::{KeySubcommand, RunCmd, SignCmd, VanityCmd, VerifyCmd};
use structopt::StructOpt;
/// An overarching CLI command definition. /// An overarching CLI command definition.
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Parser)]
pub struct Cli { pub struct Cli {
/// Possible subcommand with parameters. /// Possible subcommand with parameters.
#[structopt(subcommand)] #[clap(subcommand)]
pub subcommand: Option<Subcommand>, pub subcommand: Option<Subcommand>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub run: RunCmd, pub run: sc_cli::RunCmd,
} }
/// Possible subcommands of the main binary. /// Possible subcommands of the main binary.
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Subcommand)]
pub enum Subcommand { pub enum Subcommand {
/// Key management cli utilities
Key(KeySubcommand),
/// The custom inspect subcommmand for decoding blocks and extrinsics. /// The custom inspect subcommmand for decoding blocks and extrinsics.
#[structopt( #[clap(
name = "inspect", name = "inspect",
about = "Decode given block or extrinsic using current native runtime." about = "Decode given block or extrinsic using current native runtime."
)] )]
Inspect(node_inspect::cli::InspectCmd), Inspect(node_inspect::cli::InspectCmd),
/// The custom benchmark subcommmand benchmarking runtime pallets. /// The custom benchmark subcommmand benchmarking runtime pallets.
#[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] #[clap(name = "benchmark", about = "Benchmark runtime pallets.")]
Benchmark(frame_benchmarking_cli::BenchmarkCmd), Benchmark(frame_benchmarking_cli::BenchmarkCmd),
/// Try some command against runtime state. /// Try some command against runtime state.
@@ -55,14 +50,18 @@ pub enum Subcommand {
#[cfg(not(feature = "try-runtime"))] #[cfg(not(feature = "try-runtime"))]
TryRuntime, TryRuntime,
/// Key management cli utilities
#[clap(subcommand)]
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.
Verify(VerifyCmd), Verify(sc_cli::VerifyCmd),
/// Generate a seed that provides a vanity address. /// Generate a seed that provides a vanity address.
Vanity(VanityCmd), Vanity(sc_cli::VanityCmd),
/// Sign a message, with a given (secret) key. /// Sign a message, with a given (secret) key.
Sign(SignCmd), Sign(sc_cli::SignCmd),
/// Build a chain specification. /// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd), BuildSpec(sc_cli::BuildSpecCmd),
+1 -1
View File
@@ -11,6 +11,7 @@ repository = "https://github.com/paritytech/substrate/"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "2.0.0" } codec = { package = "parity-scale-codec", version = "2.0.0" }
derive_more = "0.99" derive_more = "0.99"
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
@@ -20,4 +21,3 @@ sc-service = { version = "0.10.0-dev", default-features = false, path = "../../.
sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" } sp-blockchain = { version = "4.0.0-dev", path = "../../../primitives/blockchain" }
sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" }
structopt = "0.3.8"
+7 -9
View File
@@ -19,27 +19,25 @@
//! Structs to easily compose inspect sub-command for CLI. //! Structs to easily compose inspect sub-command for CLI.
use sc_cli::{ImportParams, SharedParams}; use sc_cli::{ImportParams, SharedParams};
use std::fmt::Debug;
use structopt::StructOpt;
/// The `inspect` command used to print decoded chain data. /// The `inspect` command used to print decoded chain data.
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Parser)]
pub struct InspectCmd { pub struct InspectCmd {
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(subcommand)]
pub command: InspectSubCmd, pub command: InspectSubCmd,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub import_params: ImportParams, pub import_params: ImportParams,
} }
/// A possible inspect sub-commands. /// A possible inspect sub-commands.
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Subcommand)]
pub enum InspectSubCmd { pub enum InspectSubCmd {
/// Decode block with native version of runtime and print out the details. /// Decode block with native version of runtime and print out the details.
Block { Block {
@@ -48,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.
#[structopt(value_name = "HASH or NUMBER or BYTES")] #[clap(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.
@@ -58,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.
#[structopt(value_name = "BLOCK:INDEX or BYTES")] #[clap(value_name = "BLOCK:INDEX or BYTES")]
input: String, input: String,
}, },
} }
@@ -15,10 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
ansi_term = "0.12.1" ansi_term = "0.12.1"
clap = { version = "3.0", features = ["derive"] }
rand = "0.8"
sc-keystore = { version = "4.0.0-dev", path = "../../../client/keystore" } sc-keystore = { version = "4.0.0-dev", path = "../../../client/keystore" }
sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" } sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" }
node-cli = { version = "3.0.0-dev", path = "../../node/cli" } node-cli = { version = "3.0.0-dev", path = "../../node/cli" }
sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" } sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" }
rand = "0.7.2"
structopt = "0.3.25"
@@ -23,8 +23,8 @@ use std::{
}; };
use ansi_term::Style; use ansi_term::Style;
use clap::Parser;
use rand::{distributions::Alphanumeric, rngs::OsRng, Rng}; use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
use structopt::StructOpt;
use node_cli::chain_spec::{self, AccountId}; use node_cli::chain_spec::{self, AccountId};
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
@@ -36,52 +36,52 @@ 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(StructOpt)] #[derive(Parser)]
#[structopt(rename_all = "kebab-case")] #[clap(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.
#[structopt(long, short, required = true)] #[clap(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.
#[structopt(long, short, default_value = "0")] #[clap(long, short, default_value = "0")]
nominator_accounts: Vec<String>, nominator_accounts: Vec<String>,
/// Endowed account address (SS58 format). /// Endowed account address (SS58 format).
#[structopt(long, short)] #[clap(long, short)]
endowed_accounts: Vec<String>, endowed_accounts: Vec<String>,
/// Sudo account address (SS58 format). /// Sudo account address (SS58 format).
#[structopt(long, short)] #[clap(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.
#[structopt(long, short, default_value = "./chain_spec.json")] #[clap(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.
#[structopt(long, short)] #[clap(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`.
#[structopt(long, short, default_value = "0")] #[clap(long, short, default_value = "0")]
nominators: usize, nominators: usize,
/// The number of endowed accounts. /// The number of endowed accounts.
#[structopt(long, short, default_value = "0")] #[clap(long, short, default_value = "0")]
endowed: usize, endowed: usize,
/// The path where the chain spec should be saved. /// The path where the chain spec should be saved.
#[structopt(long, short, default_value = "./chain_spec.json")] #[clap(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.
#[structopt(long, short)] #[clap(long, short)]
keystore_path: Option<PathBuf>, keystore_path: Option<PathBuf>,
}, },
} }
@@ -236,13 +236,15 @@ fn main() -> Result<(), String> {
the chain spec builder binary in `--release` mode.\n", the chain spec builder binary in `--release` mode.\n",
); );
let builder = ChainSpecBuilder::from_args(); let builder = ChainSpecBuilder::parse();
let chain_spec_path = builder.chain_spec_path().to_path_buf(); let chain_spec_path = builder.chain_spec_path().to_path_buf();
let (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) = match builder { let (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) = match builder {
ChainSpecBuilder::Generate { authorities, nominators, endowed, keystore_path, .. } => { ChainSpecBuilder::Generate { authorities, nominators, endowed, keystore_path, .. } => {
let authorities = authorities.max(1); let authorities = authorities.max(1);
let rand_str = || -> String { OsRng.sample_iter(&Alphanumeric).take(32).collect() }; let rand_str = || -> String {
OsRng.sample_iter(&Alphanumeric).take(32).map(char::from).collect()
};
let authority_seeds = (0..authorities).map(|_| rand_str()).collect::<Vec<_>>(); let authority_seeds = (0..authorities).map(|_| rand_str()).collect::<Vec<_>>();
let nominator_seeds = (0..nominators).map(|_| rand_str()).collect::<Vec<_>>(); let nominator_seeds = (0..nominators).map(|_| rand_str()).collect::<Vec<_>>();
+1 -1
View File
@@ -17,5 +17,5 @@ path = "src/main.rs"
name = "subkey" name = "subkey"
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
structopt = "0.3.25"
+4 -4
View File
@@ -16,14 +16,14 @@
// 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/>.
use clap::Parser;
use sc_cli::{ use sc_cli::{
Error, GenerateCmd, GenerateNodeKeyCmd, InspectKeyCmd, InspectNodeKeyCmd, SignCmd, VanityCmd, Error, GenerateCmd, GenerateNodeKeyCmd, InspectKeyCmd, InspectNodeKeyCmd, SignCmd, VanityCmd,
VerifyCmd, VerifyCmd,
}; };
use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt( #[clap(
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"
@@ -54,7 +54,7 @@ pub enum Subkey {
/// Run the subkey command, given the appropriate runtime. /// Run the subkey command, given the appropriate runtime.
pub fn run() -> Result<(), Error> { pub fn run() -> Result<(), Error> {
match Subkey::from_args() { match Subkey::parse() {
Subkey::GenerateNodeKey(cmd) => cmd.run(), Subkey::GenerateNodeKey(cmd) => cmd.run(),
Subkey::Generate(cmd) => cmd.run(), Subkey::Generate(cmd) => cmd.run(),
Subkey::Inspect(cmd) => cmd.run(), Subkey::Inspect(cmd) => cmd.run(),
+24 -25
View File
@@ -13,42 +13,41 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
log = "0.4.11" chrono = "0.4.10"
regex = "1.5.4" clap = { version = "3.0", features = ["derive"] }
tokio = { version = "1.15", features = [ "signal", "rt-multi-thread" ] }
futures = "0.3.9"
fdlimit = "0.2.1" fdlimit = "0.2.1"
libp2p = "0.40.0" futures = "0.3.9"
parity-scale-codec = "2.3.1"
hex = "0.4.2" hex = "0.4.2"
libp2p = "0.40.0"
log = "0.4.11"
names = { version = "0.12.0", default-features = false }
rand = "0.7.3" rand = "0.7.3"
tiny-bip39 = "0.8.2" regex = "1.5.4"
rpassword = "5.0.0"
serde = "1.0.132"
serde_json = "1.0.74" serde_json = "1.0.74"
sc-keystore = { version = "4.0.0-dev", path = "../keystore" } thiserror = "1.0.30"
sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" } tiny-bip39 = "0.8.2"
tokio = { version = "1.15", features = ["signal", "rt-multi-thread"] }
parity-scale-codec = "2.3.1"
sc-client-api = { version = "4.0.0-dev", path = "../api" } sc-client-api = { version = "4.0.0-dev", path = "../api" }
sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" } sc-keystore = { version = "4.0.0-dev", path = "../keystore" }
sc-network = { version = "0.10.0-dev", path = "../network" } sc-network = { version = "0.10.0-dev", path = "../network" }
sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" }
sc-utils = { version = "4.0.0-dev", path = "../utils" }
sp-version = { version = "4.0.0-dev", path = "../../primitives/version" }
sp-core = { version = "4.1.0-dev", path = "../../primitives/core" }
sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" }
sc-service = { version = "0.10.0-dev", default-features = false, path = "../service" } sc-service = { version = "0.10.0-dev", default-features = false, path = "../service" }
sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" } sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" }
sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" }
names = { version = "0.12.0", default-features = false }
structopt = "0.3.25"
sc-tracing = { version = "4.0.0-dev", path = "../tracing" } sc-tracing = { version = "4.0.0-dev", path = "../tracing" }
chrono = "0.4.10" sc-utils = { version = "4.0.0-dev", path = "../utils" }
serde = "1.0.132" sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" }
thiserror = "1.0.30" sp-core = { version = "4.1.0-dev", path = "../../primitives/core" }
rpassword = "5.0.0" sp-keyring = { version = "4.1.0-dev", path = "../../primitives/keyring" }
sp-keystore = { version = "0.10.0", path = "../../primitives/keystore" }
sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" }
sp-runtime = { version = "4.1.0-dev", path = "../../primitives/runtime" }
sp-version = { version = "4.0.0-dev", path = "../../primitives/version" }
[dev-dependencies] [dev-dependencies]
tempfile = "3.1.0" tempfile = "3.1.0"
[features] [features]
wasmtime = [ wasmtime = ["sc-service/wasmtime"]
"sc-service/wasmtime",
]
+66 -75
View File
@@ -18,7 +18,7 @@
// NOTE: we allow missing docs here because arg_enum! creates the function variants without doc // NOTE: we allow missing docs here because arg_enum! creates the function variants without doc
#![allow(missing_docs)] #![allow(missing_docs)]
use structopt::clap::arg_enum; use clap::ArgEnum;
/// How to execute Wasm runtime code. /// How to execute Wasm runtime code.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@@ -86,12 +86,11 @@ impl Into<sc_service::config::WasmExecutionMethod> for WasmExecutionMethod {
} }
} }
arg_enum! { #[allow(missing_docs)]
#[allow(missing_docs)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[clap(rename_all = "PascalCase")]
pub enum TracingReceiver { pub enum TracingReceiver {
Log, Log,
}
} }
impl Into<sc_tracing::TracingReceiver> for TracingReceiver { impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
@@ -102,44 +101,40 @@ impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
} }
} }
arg_enum! { #[allow(missing_docs)]
#[allow(missing_docs)] #[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[clap(rename_all = "PascalCase")]
pub enum NodeKeyType { pub enum NodeKeyType {
Ed25519 Ed25519,
}
} }
arg_enum! { #[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[clap(rename_all = "PascalCase")]
pub enum CryptoScheme { pub enum CryptoScheme {
Ed25519, Ed25519,
Sr25519, Sr25519,
Ecdsa, Ecdsa,
}
} }
arg_enum! { #[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[clap(rename_all = "PascalCase")]
pub enum OutputType { pub enum OutputType {
Json, Json,
Text, Text,
}
} }
arg_enum! { /// How to execute blocks
/// How to execute blocks #[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[clap(rename_all = "PascalCase")]
pub enum ExecutionStrategy { pub enum ExecutionStrategy {
// Execute with native build (if available, WebAssembly otherwise). // Execute with native build (if available, WebAssembly otherwise).
Native, Native,
// Only execute with the WebAssembly build. // Only execute with the WebAssembly build.
Wasm, Wasm,
// Execute with both native (where available) and WebAssembly builds. // Execute with both native (where available) and WebAssembly builds.
Both, Both,
// Execute with the native build if possible; if it fails, then execute with WebAssembly. // Execute with the native build if possible; if it fails, then execute with WebAssembly.
NativeElseWasm, NativeElseWasm,
}
} }
impl Into<sc_client_api::ExecutionStrategy> for ExecutionStrategy { impl Into<sc_client_api::ExecutionStrategy> for ExecutionStrategy {
@@ -165,19 +160,18 @@ impl ExecutionStrategy {
} }
} }
arg_enum! { /// Available RPC methods.
/// Available RPC methods. #[allow(missing_docs)]
#[allow(missing_docs)] #[derive(Debug, Copy, Clone, PartialEq, ArgEnum)]
#[derive(Debug, Copy, Clone, PartialEq)] #[clap(rename_all = "PascalCase")]
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.
Auto, Auto,
// Allow only a safe subset of RPC methods. // Allow only a safe subset of RPC methods.
Safe, Safe,
// Expose every RPC method (even potentially unsafe ones). // Expose every RPC method (even potentially unsafe ones).
Unsafe, Unsafe,
}
} }
impl Into<sc_service::config::RpcMethods> for RpcMethods { impl Into<sc_service::config::RpcMethods> for RpcMethods {
@@ -225,31 +219,28 @@ impl Database {
} }
} }
arg_enum! { /// 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)] #[clap(rename_all = "PascalCase")]
pub enum OffchainWorkerEnabled { pub enum OffchainWorkerEnabled {
Always, Always,
Never, Never,
WhenValidating, WhenValidating,
}
} }
arg_enum! { /// Syncing mode.
/// Syncing mode. #[derive(Debug, Clone, Copy, ArgEnum)]
#[allow(missing_docs)] #[clap(rename_all = "PascalCase")]
#[derive(Debug, Clone, Copy)] pub enum SyncMode {
pub enum SyncMode { // Full sync. Donwnload end verify all blocks.
// Full sync. Donwnload end verify all blocks. Full,
Full, // Download blocks without executing them. Download latest state with proofs.
// Download blocks without executing them. Download latest state with proofs. Fast,
Fast, // Download blocks without executing them. Download latest state without proofs.
// Download blocks without executing them. Download latest state without proofs. FastUnsafe,
FastUnsafe, // Prove finality and download the latest state.
// Prove finality and download the latest state. Warp,
Warp,
}
} }
impl Into<sc_network::config::SyncMode> for SyncMode { impl Into<sc_network::config::SyncMode> for SyncMode {
@@ -21,6 +21,7 @@ use crate::{
params::{NodeKeyParams, SharedParams}, params::{NodeKeyParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use log::info; use log::info;
use sc_network::config::build_multiaddr; use sc_network::config::build_multiaddr;
use sc_service::{ use sc_service::{
@@ -28,28 +29,27 @@ use sc_service::{
ChainSpec, ChainSpec,
}; };
use std::io::Write; use std::io::Write;
use structopt::StructOpt;
/// The `build-spec` command used to build a specification. /// The `build-spec` command used to build a specification.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct BuildSpecCmd { pub struct BuildSpecCmd {
/// Force raw genesis storage output. /// Force raw genesis storage output.
#[structopt(long = "raw")] #[clap(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.
#[structopt(long = "disable-default-bootnode")] #[clap(long)]
pub disable_default_bootnode: bool, pub disable_default_bootnode: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub node_key_params: NodeKeyParams, pub node_key_params: NodeKeyParams,
} }
@@ -21,30 +21,30 @@ use crate::{
params::{BlockNumberOrHash, ImportParams, SharedParams}, params::{BlockNumberOrHash, ImportParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use sc_client_api::{BlockBackend, HeaderBackend}; use sc_client_api::{BlockBackend, HeaderBackend};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, str::FromStr, sync::Arc}; use std::{fmt::Debug, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `check-block` command used to validate blocks. /// The `check-block` command used to validate blocks.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct CheckBlockCmd { pub struct CheckBlockCmd {
/// Block hash or number /// Block hash or number
#[structopt(value_name = "HASH or NUMBER")] #[clap(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.
#[structopt(long = "default-heap-pages", value_name = "COUNT")] #[clap(long, value_name = "COUNT")]
pub default_heap_pages: Option<u32>, pub default_heap_pages: Option<u32>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub import_params: ImportParams, pub import_params: ImportParams,
} }
@@ -21,46 +21,46 @@ use crate::{
params::{DatabaseParams, GenericNumber, PruningParams, SharedParams}, params::{DatabaseParams, GenericNumber, PruningParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use log::info; use log::info;
use sc_client_api::{BlockBackend, UsageProvider}; use sc_client_api::{BlockBackend, UsageProvider};
use sc_service::{chain_ops::export_blocks, config::DatabaseSource}; use sc_service::{chain_ops::export_blocks, config::DatabaseSource};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc}; use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `export-blocks` command used to export blocks. /// The `export-blocks` command used to export blocks.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct ExportBlocksCmd { pub struct ExportBlocksCmd {
/// Output file name or stdout if unspecified. /// Output file name or stdout if unspecified.
#[structopt(parse(from_os_str))] #[clap(parse(from_os_str))]
pub output: Option<PathBuf>, pub output: Option<PathBuf>,
/// Specify starting block number. /// Specify starting block number.
/// ///
/// Default is 1. /// Default is 1.
#[structopt(long = "from", value_name = "BLOCK")] #[clap(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.
#[structopt(long = "to", value_name = "BLOCK")] #[clap(long, value_name = "BLOCK")]
pub to: Option<GenericNumber>, pub to: Option<GenericNumber>,
/// Use binary output rather than JSON. /// Use binary output rather than JSON.
#[structopt(long)] #[clap(long)]
pub binary: bool, pub binary: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub pruning_params: PruningParams, pub pruning_params: PruningParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub database_params: DatabaseParams, pub database_params: DatabaseParams,
} }
@@ -21,26 +21,26 @@ use crate::{
params::{BlockNumberOrHash, PruningParams, SharedParams}, params::{BlockNumberOrHash, PruningParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use log::info; use log::info;
use sc_client_api::{StorageProvider, UsageProvider}; use sc_client_api::{StorageProvider, UsageProvider};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, io::Write, str::FromStr, sync::Arc}; use std::{fmt::Debug, io::Write, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `export-state` command used to export the state of a given block into /// The `export-state` command used to export the state of a given block into
/// a chain spec. /// a chain spec.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct ExportStateCmd { pub struct ExportStateCmd {
/// Block hash or number. /// Block hash or number.
#[structopt(value_name = "HASH or NUMBER")] #[clap(value_name = "HASH or NUMBER")]
pub input: Option<BlockNumberOrHash>, pub input: Option<BlockNumberOrHash>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub pruning_params: PruningParams, pub pruning_params: PruningParams,
} }
+10 -11
View File
@@ -21,30 +21,30 @@ use crate::{
NetworkSchemeFlag, OutputTypeFlag, NetworkSchemeFlag, OutputTypeFlag,
}; };
use bip39::{Language, Mnemonic, MnemonicType}; use bip39::{Language, Mnemonic, MnemonicType};
use structopt::StructOpt; use clap::Parser;
/// The `generate` command /// The `generate` command
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
#[structopt(name = "generate", about = "Generate a random account")] #[clap(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.
#[structopt(long, short = "w", value_name = "WORDS")] #[clap(short = 'w', long, value_name = "WORDS")]
words: Option<usize>, words: Option<usize>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub network_scheme: NetworkSchemeFlag, pub network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub output_scheme: OutputTypeFlag, pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
} }
@@ -78,12 +78,11 @@ impl GenerateCmd {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::GenerateCmd; use super::*;
use structopt::StructOpt;
#[test] #[test]
fn generate() { fn generate() {
let generate = GenerateCmd::from_iter(&["generate", "--password", "12345"]); let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]);
assert!(generate.run().is_ok()) assert!(generate.run().is_ok())
} }
} }
@@ -18,13 +18,13 @@
//! Implementation of the `generate-node-key` subcommand //! Implementation of the `generate-node-key` subcommand
use crate::Error; use crate::Error;
use clap::Parser;
use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey}; use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey};
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `generate-node-key` command /// The `generate-node-key` command
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt( #[clap(
name = "generate-node-key", name = "generate-node-key",
about = "Generate a random node libp2p key, save it to \ about = "Generate a random node libp2p key, save it to \
file or print it to stdout and print its peer ID to stderr" file or print it to stdout and print its peer ID to stderr"
@@ -33,7 +33,7 @@ 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.
#[structopt(long)] #[clap(long)]
file: Option<PathBuf>, file: Option<PathBuf>,
} }
@@ -66,7 +66,7 @@ mod tests {
fn generate_node_key() { fn generate_node_key() {
let mut file = Builder::new().prefix("keyfile").tempfile().unwrap(); let mut file = Builder::new().prefix("keyfile").tempfile().unwrap();
let file_path = file.path().display().to_string(); let file_path = file.path().display().to_string();
let generate = GenerateNodeKeyCmd::from_iter(&["generate-node-key", "--file", &file_path]); let generate = GenerateNodeKeyCmd::parse_from(&["generate-node-key", "--file", &file_path]);
assert!(generate.run().is_ok()); assert!(generate.run().is_ok());
let mut buf = String::new(); let mut buf = String::new();
assert!(file.read_to_string(&mut buf).is_ok()); assert!(file.read_to_string(&mut buf).is_ok());
@@ -21,6 +21,7 @@ use crate::{
params::{ImportParams, SharedParams}, params::{ImportParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use sc_client_api::HeaderBackend; use sc_client_api::HeaderBackend;
use sc_service::chain_ops::import_blocks; use sc_service::chain_ops::import_blocks;
use sp_runtime::traits::Block as BlockT; use sp_runtime::traits::Block as BlockT;
@@ -31,31 +32,30 @@ use std::{
path::PathBuf, path::PathBuf,
sync::Arc, sync::Arc,
}; };
use structopt::StructOpt;
/// The `import-blocks` command used to import blocks. /// The `import-blocks` command used to import blocks.
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
pub struct ImportBlocksCmd { pub struct ImportBlocksCmd {
/// Input file or stdin if unspecified. /// Input file or stdin if unspecified.
#[structopt(parse(from_os_str))] #[clap(parse(from_os_str))]
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.
#[structopt(long = "default-heap-pages", value_name = "COUNT")] #[clap(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.
#[structopt(long)] #[clap(long)]
pub binary: bool, pub binary: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub import_params: ImportParams, pub import_params: ImportParams,
} }
@@ -20,42 +20,37 @@
use crate::{ use crate::{
utils, with_crypto_scheme, CryptoScheme, Error, KeystoreParams, SharedParams, SubstrateCli, utils, with_crypto_scheme, CryptoScheme, Error, KeystoreParams, SharedParams, SubstrateCli,
}; };
use clap::Parser;
use sc_keystore::LocalKeystore; use sc_keystore::LocalKeystore;
use sc_service::config::{BasePath, KeystoreConfig}; use sc_service::config::{BasePath, KeystoreConfig};
use sp_core::crypto::{KeyTypeId, SecretString}; use sp_core::crypto::{KeyTypeId, SecretString};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr}; use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use std::{convert::TryFrom, sync::Arc}; use std::{convert::TryFrom, sync::Arc};
use structopt::StructOpt;
/// The `insert` command /// The `insert` command
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
#[structopt(name = "insert", about = "Insert a key to the keystore of a node.")] #[clap(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.
#[structopt(long)] #[clap(long)]
suri: Option<String>, suri: Option<String>,
/// Key type, examples: "gran", or "imon" /// Key type, examples: "gran", or "imon"
#[structopt(long)] #[clap(long)]
key_type: String, key_type: String,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
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.
#[structopt( #[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true)]
long,
value_name = "SCHEME",
possible_values = &CryptoScheme::variants(),
case_insensitive = true,
)]
pub scheme: CryptoScheme, pub scheme: CryptoScheme,
} }
@@ -100,7 +95,6 @@ mod tests {
use super::*; use super::*;
use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension}; use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension};
use sp_core::{sr25519::Pair, ByteArray, Pair as _}; use sp_core::{sr25519::Pair, ByteArray, Pair as _};
use structopt::StructOpt;
use tempfile::TempDir; use tempfile::TempDir;
struct Cli; struct Cli;
@@ -156,7 +150,7 @@ mod tests {
let path_str = format!("{}", path.path().display()); let path_str = format!("{}", path.path().display());
let (key, uri, _) = Pair::generate_with_phrase(None); let (key, uri, _) = Pair::generate_with_phrase(None);
let inspect = InsertKeyCmd::from_iter(&[ let inspect = InsertKeyCmd::parse_from(&[
"insert-key", "insert-key",
"-d", "-d",
&path_str, &path_str,
@@ -21,13 +21,13 @@ use crate::{
utils::{self, print_from_public, print_from_uri}, utils::{self, print_from_public, print_from_uri},
with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, NetworkSchemeFlag, OutputTypeFlag, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, NetworkSchemeFlag, OutputTypeFlag,
}; };
use clap::Parser;
use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec}; use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec};
use std::str::FromStr; use std::str::FromStr;
use structopt::StructOpt;
/// The `inspect` command /// The `inspect` command
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt( #[clap(
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,23 +44,23 @@ 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?
#[structopt(long)] #[clap(long)]
public: bool, public: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub network_scheme: NetworkSchemeFlag, pub network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub output_scheme: OutputTypeFlag, pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
/// Expect that `--uri` has the given public key/account-id. /// Expect that `--uri` has the given public key/account-id.
@@ -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.
#[structopt(long, conflicts_with = "public")] #[clap(long, conflicts_with = "public")]
pub expect_public: Option<String>, pub expect_public: Option<String>,
} }
@@ -158,7 +158,6 @@ mod tests {
use super::*; use super::*;
use sp_core::crypto::{ByteArray, Pair}; use sp_core::crypto::{ByteArray, Pair};
use sp_runtime::traits::IdentifyAccount; use sp_runtime::traits::IdentifyAccount;
use structopt::StructOpt;
#[test] #[test]
fn inspect() { fn inspect() {
@@ -166,10 +165,10 @@ mod tests {
"remember fiber forum demise paper uniform squirrel feel access exclude casual effort"; "remember fiber forum demise paper uniform squirrel feel access exclude casual effort";
let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5"; let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5";
let inspect = InspectKeyCmd::from_iter(&["inspect-key", words, "--password", "12345"]); let inspect = InspectKeyCmd::parse_from(&["inspect-key", words, "--password", "12345"]);
assert!(inspect.run().is_ok()); assert!(inspect.run().is_ok());
let inspect = InspectKeyCmd::from_iter(&["inspect-key", seed]); let inspect = InspectKeyCmd::parse_from(&["inspect-key", seed]);
assert!(inspect.run().is_ok()); assert!(inspect.run().is_ok());
} }
@@ -177,14 +176,14 @@ mod tests {
fn inspect_public_key() { fn inspect_public_key() {
let public = "0x12e76e0ae8ce41b6516cce52b3f23a08dcb4cfeed53c6ee8f5eb9f7367341069"; let public = "0x12e76e0ae8ce41b6516cce52b3f23a08dcb4cfeed53c6ee8f5eb9f7367341069";
let inspect = InspectKeyCmd::from_iter(&["inspect-key", "--public", public]); let inspect = InspectKeyCmd::parse_from(&["inspect-key", "--public", public]);
assert!(inspect.run().is_ok()); assert!(inspect.run().is_ok());
} }
#[test] #[test]
fn inspect_with_expected_public_key() { fn inspect_with_expected_public_key() {
let check_cmd = |seed, expected_public, success| { let check_cmd = |seed, expected_public, success| {
let inspect = InspectKeyCmd::from_iter(&[ let inspect = InspectKeyCmd::parse_from(&[
"inspect-key", "inspect-key",
"--expect-public", "--expect-public",
expected_public, expected_public,
@@ -18,23 +18,23 @@
//! Implementation of the `inspect-node-key` subcommand //! Implementation of the `inspect-node-key` subcommand
use crate::{Error, NetworkSchemeFlag}; use crate::{Error, NetworkSchemeFlag};
use clap::Parser;
use libp2p::identity::{ed25519, PublicKey}; use libp2p::identity::{ed25519, PublicKey};
use std::{fs, path::PathBuf}; use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `inspect-node-key` command /// The `inspect-node-key` command
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt( #[clap(
name = "inspect-node-key", name = "inspect-node-key",
about = "Print the peer ID corresponding to the node key in the given file." about = "Print the peer ID corresponding to the node key in the given file."
)] )]
pub struct InspectNodeKeyCmd { pub struct InspectNodeKeyCmd {
/// Name of file to read the secret key from. /// Name of file to read the secret key from.
#[structopt(long)] #[clap(long)]
file: PathBuf, file: PathBuf,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub network_scheme: NetworkSchemeFlag, pub network_scheme: NetworkSchemeFlag,
} }
@@ -63,11 +63,11 @@ mod tests {
fn inspect_node_key() { fn inspect_node_key() {
let path = tempfile::tempdir().unwrap().into_path().join("node-id").into_os_string(); let path = tempfile::tempdir().unwrap().into_path().join("node-id").into_os_string();
let path = path.to_str().unwrap(); let path = path.to_str().unwrap();
let cmd = GenerateNodeKeyCmd::from_iter(&["generate-node-key", "--file", path.clone()]); let cmd = GenerateNodeKeyCmd::parse_from(&["generate-node-key", "--file", path.clone()]);
assert!(cmd.run().is_ok()); assert!(cmd.run().is_ok());
let cmd = InspectNodeKeyCmd::from_iter(&["inspect-node-key", "--file", path]); let cmd = InspectNodeKeyCmd::parse_from(&["inspect-node-key", "--file", path]);
assert!(cmd.run().is_ok()); assert!(cmd.run().is_ok());
} }
} }
+2 -4
View File
@@ -17,16 +17,14 @@
//! Key related CLI utilities //! Key related CLI utilities
use crate::{Error, SubstrateCli};
use structopt::StructOpt;
use super::{ use super::{
generate::GenerateCmd, generate_node_key::GenerateNodeKeyCmd, insert_key::InsertKeyCmd, generate::GenerateCmd, generate_node_key::GenerateNodeKeyCmd, insert_key::InsertKeyCmd,
inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd, inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd,
}; };
use crate::{Error, SubstrateCli};
/// Key utilities for the cli. /// Key utilities for the cli.
#[derive(Debug, StructOpt)] #[derive(Debug, clap::Subcommand)]
pub enum KeySubcommand { pub enum KeySubcommand {
/// Generate a random node libp2p key, save it to file or print it to stdout /// Generate a random node libp2p key, save it to file or print it to stdout
/// and print its peer ID to stderr. /// and print its peer ID to stderr.
@@ -21,27 +21,27 @@ use crate::{
params::{DatabaseParams, SharedParams}, params::{DatabaseParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use sc_service::DatabaseSource; use sc_service::DatabaseSource;
use std::{ use std::{
fmt::Debug, fmt::Debug,
fs, fs,
io::{self, Write}, io::{self, Write},
}; };
use structopt::StructOpt;
/// The `purge-chain` command used to remove the whole chain. /// The `purge-chain` command used to remove the whole chain.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct PurgeChainCmd { pub struct PurgeChainCmd {
/// Skip interactive prompt by answering yes automatically. /// Skip interactive prompt by answering yes automatically.
#[structopt(short = "y")] #[clap(short = 'y')]
pub yes: bool, pub yes: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub database_params: DatabaseParams, pub database_params: DatabaseParams,
} }
@@ -21,25 +21,25 @@ use crate::{
params::{GenericNumber, PruningParams, SharedParams}, params::{GenericNumber, PruningParams, SharedParams},
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use sc_client_api::{Backend, UsageProvider}; use sc_client_api::{Backend, UsageProvider};
use sc_service::chain_ops::revert_chain; use sc_service::chain_ops::revert_chain;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, str::FromStr, sync::Arc}; use std::{fmt::Debug, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `revert` command used revert the chain to a previous state. /// The `revert` command used revert the chain to a previous state.
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
pub struct RevertCmd { pub struct RevertCmd {
/// Number of blocks to revert. /// Number of blocks to revert.
#[structopt(default_value = "256")] #[clap(default_value = "256")]
pub num: GenericNumber, pub num: GenericNumber,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub pruning_params: PruningParams, pub pruning_params: PruningParams,
} }
+50 -47
View File
@@ -25,6 +25,7 @@ use crate::{
}, },
CliConfiguration, CliConfiguration,
}; };
use clap::Parser;
use regex::Regex; use regex::Regex;
use sc_service::{ use sc_service::{
config::{BasePath, PrometheusConfig, TransactionPoolOptions}, config::{BasePath, PrometheusConfig, TransactionPoolOptions},
@@ -32,26 +33,25 @@ use sc_service::{
}; };
use sc_telemetry::TelemetryEndpoints; use sc_telemetry::TelemetryEndpoints;
use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use structopt::StructOpt;
/// The `run` command used to run a node. /// The `run` command used to run a node.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
pub struct RunCmd { pub struct RunCmd {
/// Enable validator mode. /// Enable validator mode.
/// ///
/// 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).
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub no_grandpa: bool, pub no_grandpa: bool,
/// Experimental: Run in light client mode. /// Experimental: Run in light client mode.
#[structopt(long = "light")] #[clap(long)]
pub light: bool, pub light: bool,
/// Listen to all RPC interfaces. /// Listen to all RPC interfaces.
@@ -60,13 +60,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/v3/runtime/custom-rpcs/#public-rpcs>. /// <https://docs.substrate.io/v3/runtime/custom-rpcs/#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.
#[structopt(long = "rpc-external")] #[clap(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`.
#[structopt(long)] #[clap(long)]
pub unsafe_rpc_external: bool, pub unsafe_rpc_external: bool,
/// RPC methods to expose. /// RPC methods to expose.
@@ -75,11 +75,11 @@ 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`.
#[structopt( #[clap(
long, long,
value_name = "METHOD SET", value_name = "METHOD SET",
possible_values = &RpcMethods::variants(), arg_enum,
case_insensitive = true, ignore_case = true,
default_value = "Auto", default_value = "Auto",
verbatim_doc_comment verbatim_doc_comment
)] )]
@@ -91,44 +91,44 @@ 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/v3/runtime/custom-rpcs/#public-rpcs>. /// <https://docs.substrate.io/v3/runtime/custom-rpcs/#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.
#[structopt(long = "ws-external")] #[clap(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.
#[structopt(long = "unsafe-ws-external")] #[clap(long)]
pub unsafe_ws_external: bool, pub unsafe_ws_external: bool,
/// Set the the maximum RPC payload size for both requests and responses (both http and ws), in /// Set the the maximum RPC payload size for both requests and responses (both http and ws), in
/// megabytes. Default is 15MiB. /// megabytes. Default is 15MiB.
#[structopt(long = "rpc-max-payload")] #[clap(long)]
pub rpc_max_payload: Option<usize>, pub rpc_max_payload: Option<usize>,
/// Expose Prometheus exporter on all interfaces. /// Expose Prometheus exporter on all interfaces.
/// ///
/// Default is local. /// Default is local.
#[structopt(long = "prometheus-external")] #[clap(long)]
pub prometheus_external: bool, pub prometheus_external: bool,
/// Specify IPC RPC server path /// Specify IPC RPC server path
#[structopt(long = "ipc-path", value_name = "PATH")] #[clap(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.
#[structopt(long = "rpc-port", value_name = "PORT")] #[clap(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.
#[structopt(long = "ws-port", value_name = "PORT")] #[clap(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.
#[structopt(long = "ws-max-connections", value_name = "COUNT")] #[clap(long, value_name = "COUNT")]
pub ws_max_connections: Option<usize>, pub ws_max_connections: Option<usize>,
/// Set the the maximum WebSocket output buffer size in MiB. Default is 16. /// Set the the maximum WebSocket output buffer size in MiB. Default is 16.
#[structopt(long = "ws-max-out-buffer-capacity")] #[clap(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.
@@ -137,29 +137,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.
#[structopt(long = "rpc-cors", value_name = "ORIGINS", parse(try_from_str = parse_cors))] #[clap(long, value_name = "ORIGINS", parse(from_str = parse_cors))]
pub rpc_cors: Option<Cors>, pub rpc_cors: Option<Cors>,
/// Specify Prometheus exporter TCP Port. /// Specify Prometheus exporter TCP Port.
#[structopt(long = "prometheus-port", value_name = "PORT")] #[clap(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.
#[structopt(long = "no-prometheus")] #[clap(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.
#[structopt(long = "name", value_name = "NAME")] #[clap(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.
#[structopt(long = "no-telemetry")] #[clap(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.
@@ -168,78 +168,78 @@ 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'`.
#[structopt(long = "telemetry-url", value_name = "URL VERBOSITY", parse(try_from_str = parse_telemetry_endpoints))] #[clap(long = "telemetry-url", value_name = "URL VERBOSITY", parse(try_from_str = parse_telemetry_endpoints))]
pub telemetry_endpoints: Vec<(String, u8)>, pub telemetry_endpoints: Vec<(String, u8)>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub offchain_worker_params: OffchainWorkerParams, pub offchain_worker_params: OffchainWorkerParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub shared_params: SharedParams, pub shared_params: SharedParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub import_params: ImportParams, pub import_params: ImportParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub network_params: NetworkParams, pub network_params: NetworkParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
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.
#[structopt(long, conflicts_with_all = &["bob", "charlie", "dave", "eve", "ferdie", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "charlie", "dave", "eve", "ferdie", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "dave", "eve", "ferdie", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "eve", "ferdie", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "ferdie", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "one", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "two"])] #[clap(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.
#[structopt(long, conflicts_with_all = &["alice", "bob", "charlie", "dave", "eve", "ferdie", "one"])] #[clap(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.
#[structopt(long = "force-authoring")] #[clap(long)]
pub force_authoring: bool, pub force_authoring: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
/// 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.
#[structopt(long)] #[clap(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.
#[structopt(long, default_value = "2")] #[clap(long, default_value = "2")]
pub runtime_cache_size: u8, pub runtime_cache_size: u8,
/// Run a temporary node. /// Run a temporary node.
@@ -251,7 +251,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.
#[structopt(long, conflicts_with = "base-path")] #[clap(long, conflicts_with = "base-path")]
pub tmp: bool, pub tmp: bool,
} }
@@ -562,8 +562,7 @@ fn parse_telemetry_endpoints(s: &str) -> std::result::Result<(String, u8), Telem
/// CORS setting /// CORS setting
/// ///
/// The type is introduced to overcome `Option<Option<T>>` /// The type is introduced to overcome `Option<Option<T>>` handling of `clap`.
/// handling of `structopt`.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Cors { pub enum Cors {
/// All hosts allowed. /// All hosts allowed.
@@ -582,7 +581,7 @@ impl From<Cors> for Option<Vec<String>> {
} }
/// Parse cors origins. /// Parse cors origins.
fn parse_cors(s: &str) -> std::result::Result<Cors, Box<dyn std::error::Error>> { fn parse_cors(s: &str) -> 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(',') {
@@ -595,7 +594,11 @@ fn parse_cors(s: &str) -> std::result::Result<Cors, Box<dyn std::error::Error>>
} }
} }
Ok(if is_all { Cors::All } else { Cors::List(origins) }) if is_all {
Cors::All
} else {
Cors::List(origins)
}
} }
#[cfg(test)] #[cfg(test)]
+10 -11
View File
@@ -18,34 +18,34 @@
//! Implementation of the `sign` subcommand //! Implementation of the `sign` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams}; use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams};
use clap::Parser;
use sp_core::crypto::SecretString; use sp_core::crypto::SecretString;
use structopt::StructOpt;
/// The `sign` command /// The `sign` command
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
#[structopt(name = "sign", about = "Sign a message, with a given (secret) key")] #[clap(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.
#[structopt(long)] #[clap(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
#[structopt(long)] #[clap(long)]
message: Option<String>, message: Option<String>,
/// The message on STDIN is hex-encoded data /// The message on STDIN is hex-encoded data
#[structopt(long)] #[clap(long)]
hex: bool, hex: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
} }
@@ -75,14 +75,13 @@ fn sign<P: sp_core::Pair>(
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::SignCmd; use super::*;
use structopt::StructOpt;
#[test] #[test]
fn sign() { fn sign() {
let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5"; let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5";
let sign = SignCmd::from_iter(&[ let sign = SignCmd::parse_from(&[
"sign", "sign",
"--suri", "--suri",
seed, seed,
+8 -9
View File
@@ -21,30 +21,30 @@
use crate::{ use crate::{
error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag, error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag,
}; };
use clap::Parser;
use rand::{rngs::OsRng, RngCore}; use rand::{rngs::OsRng, RngCore};
use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec}; use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec};
use sp_runtime::traits::IdentifyAccount; use sp_runtime::traits::IdentifyAccount;
use structopt::StructOpt;
use utils::print_from_uri; use utils::print_from_uri;
/// The `vanity` command /// The `vanity` command
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
#[structopt(name = "vanity", about = "Generate a seed that provides a vanity address")] #[clap(name = "vanity", about = "Generate a seed that provides a vanity address")]
pub struct VanityCmd { pub struct VanityCmd {
/// Desired pattern /// Desired pattern
#[structopt(long, parse(try_from_str = assert_non_empty_string))] #[clap(long, parse(try_from_str = assert_non_empty_string))]
pattern: String, pattern: String,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
network_scheme: NetworkSchemeFlag, network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
output_scheme: OutputTypeFlag, output_scheme: OutputTypeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
crypto_scheme: CryptoSchemeFlag, crypto_scheme: CryptoSchemeFlag,
} }
@@ -166,13 +166,12 @@ mod tests {
crypto::{default_ss58_version, Ss58AddressFormatRegistry, Ss58Codec}, crypto::{default_ss58_version, Ss58AddressFormatRegistry, Ss58Codec},
sr25519, Pair, sr25519, Pair,
}; };
use structopt::StructOpt;
#[cfg(feature = "bench")] #[cfg(feature = "bench")]
use test::Bencher; use test::Bencher;
#[test] #[test]
fn vanity() { fn vanity() {
let vanity = VanityCmd::from_iter(&["vanity", "--pattern", "j"]); let vanity = VanityCmd::parse_from(&["vanity", "--pattern", "j"]);
assert!(vanity.run().is_ok()); assert!(vanity.run().is_ok());
} }
+6 -6
View File
@@ -19,12 +19,12 @@
//! implementation of the `verify` subcommand //! implementation of the `verify` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag}; use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag};
use clap::Parser;
use sp_core::crypto::{ByteArray, Ss58Codec}; use sp_core::crypto::{ByteArray, Ss58Codec};
use structopt::StructOpt;
/// The `verify` command /// The `verify` command
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Parser)]
#[structopt( #[clap(
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,15 +39,15 @@ 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
#[structopt(long)] #[clap(long)]
message: Option<String>, message: Option<String>,
/// The message on STDIN is hex-encoded data /// The message on STDIN is hex-encoded data
#[structopt(long)] #[clap(long)]
hex: bool, hex: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
} }
+1 -1
View File
@@ -31,7 +31,7 @@ pub enum Error {
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error(transparent)] #[error(transparent)]
Cli(#[from] structopt::clap::Error), Cli(#[from] clap::Error),
#[error(transparent)] #[error(transparent)]
Service(#[from] sc_service::Error), Service(#[from] sc_service::Error),
+17 -40
View File
@@ -30,6 +30,8 @@ mod params;
mod runner; mod runner;
pub use arg_enums::*; pub use arg_enums::*;
pub use clap;
use clap::{AppSettings, FromArgMatches, IntoApp, Parser};
pub use commands::*; pub use commands::*;
pub use config::*; pub use config::*;
pub use error::*; pub use error::*;
@@ -39,12 +41,6 @@ use sc_service::Configuration;
pub use sc_service::{ChainSpec, Role}; pub use sc_service::{ChainSpec, Role};
pub use sc_tracing::logging::LoggerBuilder; pub use sc_tracing::logging::LoggerBuilder;
pub use sp_version::RuntimeVersion; pub use sp_version::RuntimeVersion;
use std::io::Write;
pub use structopt;
use structopt::{
clap::{self, AppSettings},
StructOpt,
};
/// Substrate client CLI /// Substrate client CLI
/// ///
@@ -103,7 +99,7 @@ pub trait SubstrateCli: Sized {
/// error message and quit the program in case of failure. /// error message and quit the program in case of failure.
fn from_args() -> Self fn from_args() -> Self
where where
Self: StructOpt + Sized, Self: Parser + Sized,
{ {
<Self as SubstrateCli>::from_iter(&mut std::env::args_os()) <Self as SubstrateCli>::from_iter(&mut std::env::args_os())
} }
@@ -120,11 +116,11 @@ pub trait SubstrateCli: Sized {
/// Print the error message and quit the program in case of failure. /// Print the error message and quit the program in case of failure.
fn from_iter<I>(iter: I) -> Self fn from_iter<I>(iter: I) -> Self
where where
Self: StructOpt + Sized, Self: Parser + Sized,
I: IntoIterator, I: IntoIterator,
I::Item: Into<std::ffi::OsString> + Clone, I::Item: Into<std::ffi::OsString> + Clone,
{ {
let app = <Self as StructOpt>::clap(); let app = <Self as IntoApp>::into_app();
let mut full_version = Self::impl_version(); let mut full_version = Self::impl_version();
full_version.push_str("\n"); full_version.push_str("\n");
@@ -137,34 +133,15 @@ pub trait SubstrateCli: Sized {
.author(author.as_str()) .author(author.as_str())
.about(about.as_str()) .about(about.as_str())
.version(full_version.as_str()) .version(full_version.as_str())
.settings(&[ .setting(
AppSettings::GlobalVersion, AppSettings::PropagateVersion |
AppSettings::ArgsNegateSubcommands, AppSettings::ArgsNegateSubcommands |
AppSettings::SubcommandsNegateReqs, AppSettings::SubcommandsNegateReqs,
AppSettings::ColoredHelp, );
]);
let matches = match app.get_matches_from_safe(iter) { let matches = app.try_get_matches_from(iter).unwrap_or_else(|e| e.exit());
Ok(matches) => matches,
Err(mut e) => {
// To support pipes, we can not use `writeln!` as any error
// results in a "broken pipe" error.
//
// Instead we write directly to `stdout` and ignore any error
// as we exit afterwards anyway.
e.message.extend("\n".chars());
if e.use_stderr() { <Self as FromArgMatches>::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())
let _ = std::io::stderr().write_all(e.message.as_bytes());
std::process::exit(1);
} else {
let _ = std::io::stdout().write_all(e.message.as_bytes());
std::process::exit(0);
}
},
};
<Self as StructOpt>::from_clap(&matches)
} }
/// Helper function used to parse the command line arguments. This is the equivalent of /// Helper function used to parse the command line arguments. This is the equivalent of
@@ -180,15 +157,15 @@ 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::HelpDisplayed`] or [`clap::ErrorKind::VersionDisplayed`] respectively. /// [`clap::ErrorKind::DisplayHelp`] or [`clap::ErrorKind::DisplayVersion`] respectively.
/// You must call [`clap::Error::exit`] or perform a [`std::process::exit`]. /// 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::Result<Self>
where where
Self: StructOpt + Sized, Self: Parser + Sized,
I: IntoIterator, I: IntoIterator,
I::Item: Into<std::ffi::OsString> + Clone, I::Item: Into<std::ffi::OsString> + Clone,
{ {
let app = <Self as StructOpt>::clap(); let app = <Self as IntoApp>::into_app();
let mut full_version = Self::impl_version(); let mut full_version = Self::impl_version();
full_version.push_str("\n"); full_version.push_str("\n");
@@ -202,9 +179,9 @@ pub trait SubstrateCli: Sized {
.about(about.as_str()) .about(about.as_str())
.version(full_version.as_str()); .version(full_version.as_str());
let matches = app.get_matches_from_safe(iter)?; let matches = app.try_get_matches_from(iter)?;
Ok(<Self as StructOpt>::from_clap(&matches)) <Self as FromArgMatches>::from_arg_matches(&matches)
} }
/// Returns the client ID: `{impl_name}/v{impl_version}` /// Returns the client ID: `{impl_name}/v{impl_version}`
@@ -17,24 +17,24 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::arg_enums::Database; use crate::arg_enums::Database;
use clap::Args;
use sc_service::TransactionStorageMode; use sc_service::TransactionStorageMode;
use structopt::StructOpt;
/// Parameters for block import. /// Parameters for block import.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct DatabaseParams { pub struct DatabaseParams {
/// Select database backend to use. /// Select database backend to use.
#[structopt( #[clap(
long, long,
alias = "db", alias = "db",
value_name = "DB", value_name = "DB",
case_insensitive = true, ignore_case = true,
possible_values = &Database::variants(), 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.
#[structopt(long = "db-cache", value_name = "MiB")] #[clap(long = "db-cache", value_name = "MiB")]
pub database_cache_size: Option<usize>, pub database_cache_size: Option<usize>,
/// Enable storage chain mode /// Enable storage chain mode
@@ -43,7 +43,7 @@ pub struct DatabaseParams {
/// If this is enabled, each transaction is stored separately in the /// If this is enabled, each transaction is stored separately in the
/// transaction database column and is only referenced by hash /// transaction database column and is only referenced by hash
/// in the block body column. /// in the block body column.
#[structopt(long)] #[clap(long)]
pub storage_chain: bool, pub storage_chain: bool,
} }
@@ -24,9 +24,9 @@ use crate::{
}, },
params::{DatabaseParams, PruningParams}, params::{DatabaseParams, PruningParams},
}; };
use clap::Args;
use sc_client_api::execution_extensions::ExecutionStrategies; use sc_client_api::execution_extensions::ExecutionStrategies;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::StructOpt;
#[cfg(feature = "wasmtime")] #[cfg(feature = "wasmtime")]
const WASM_METHOD_DEFAULT: &str = "Compiled"; const WASM_METHOD_DEFAULT: &str = "Compiled";
@@ -35,14 +35,14 @@ const WASM_METHOD_DEFAULT: &str = "Compiled";
const WASM_METHOD_DEFAULT: &str = "interpreted-i-know-what-i-do"; const WASM_METHOD_DEFAULT: &str = "interpreted-i-know-what-i-do";
/// Parameters for block import. /// Parameters for block import.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct ImportParams { pub struct ImportParams {
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub pruning_params: PruningParams, pub pruning_params: PruningParams,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub database_params: DatabaseParams, pub database_params: DatabaseParams,
/// Force start with unsafe pruning settings. /// Force start with unsafe pruning settings.
@@ -50,15 +50,15 @@ pub struct ImportParams {
/// When running as a validator it is highly recommended to disable state /// When running as a validator it is highly recommended to disable state
/// pruning (i.e. 'archive') which is the default. The node will refuse to /// pruning (i.e. 'archive') which is the default. The node will refuse to
/// start as a validator if pruning is enabled unless this option is set. /// start as a validator if pruning is enabled unless this option is set.
#[structopt(long = "unsafe-pruning")] #[clap(long)]
pub unsafe_pruning: bool, pub unsafe_pruning: bool,
/// Method for executing Wasm runtime code. /// Method for executing Wasm runtime code.
#[structopt( #[clap(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(), possible_values = WasmExecutionMethod::variants(),
case_insensitive = true, ignore_case = true,
default_value = WASM_METHOD_DEFAULT default_value = WASM_METHOD_DEFAULT
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
@@ -66,15 +66,15 @@ pub struct ImportParams {
/// 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.
#[structopt(long, value_name = "PATH", parse(from_os_str))] #[clap(long, value_name = "PATH", parse(from_os_str))]
pub wasm_runtime_overrides: Option<PathBuf>, pub wasm_runtime_overrides: Option<PathBuf>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub execution_strategies: ExecutionStrategiesParams, pub execution_strategies: ExecutionStrategiesParams,
/// Specify the state cache size. /// Specify the state cache size.
#[structopt(long = "state-cache-size", value_name = "Bytes", default_value = "67108864")] #[clap(long, value_name = "Bytes", default_value = "67108864")]
pub state_cache_size: usize, pub state_cache_size: usize,
} }
@@ -127,62 +127,37 @@ impl ImportParams {
} }
/// Execution strategies parameters. /// Execution strategies parameters.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
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.
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution-syncing",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = 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).
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution-import-block",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = 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.
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution-block-construction",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = 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.
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution-offchain-worker",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = 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.
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution-other",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = 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.
#[structopt( #[clap(
long = "execution", long,
value_name = "STRATEGY", value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(), arg_enum,
case_insensitive = true, ignore_case = true,
conflicts_with_all = &[ conflicts_with_all = &[
"execution-other", "execution-other",
"execution-offchain-worker", "execution-offchain-worker",
@@ -17,50 +17,47 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{error, error::Result}; use crate::{error, error::Result};
use clap::Args;
use sc_service::config::KeystoreConfig; use sc_service::config::KeystoreConfig;
use sp_core::crypto::SecretString; use sp_core::crypto::SecretString;
use std::{ use std::{
fs, fs,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use structopt::StructOpt;
/// default sub directory for the key store /// default sub directory for the key store
const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore"; const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore";
/// Parameters of the keystore /// Parameters of the keystore
#[derive(Debug, StructOpt, Clone)] #[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
#[structopt(long = "keystore-uri")] #[clap(long)]
pub keystore_uri: Option<String>, pub keystore_uri: Option<String>,
/// Specify custom keystore path. /// Specify custom keystore path.
#[structopt(long = "keystore-path", value_name = "PATH", parse(from_os_str))] #[clap(long, value_name = "PATH", parse(from_os_str))]
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.
#[structopt( #[clap(long, conflicts_with_all = &["password", "password-filename"])]
long = "password-interactive",
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.
#[structopt( #[clap(
long = "password", long,
parse(try_from_str = secret_string_from_str), parse(try_from_str = 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.
#[structopt( #[clap(
long = "password-filename", long,
value_name = "PATH", value_name = "PATH",
parse(from_os_str), 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>,
} }
+9 -21
View File
@@ -26,13 +26,13 @@ mod shared_params;
mod transaction_pool_params; mod transaction_pool_params;
use crate::arg_enums::{CryptoScheme, OutputType}; use crate::arg_enums::{CryptoScheme, OutputType};
use clap::Args;
use sp_core::crypto::Ss58AddressFormat; use sp_core::crypto::Ss58AddressFormat;
use sp_runtime::{ use sp_runtime::{
generic::BlockId, generic::BlockId,
traits::{Block as BlockT, NumberFor}, traits::{Block as BlockT, NumberFor},
}; };
use std::{convert::TryFrom, fmt::Debug, str::FromStr}; use std::{convert::TryFrom, fmt::Debug, str::FromStr};
use structopt::StructOpt;
pub use crate::params::{ pub use crate::params::{
database_params::*, import_params::*, keystore_params::*, network_params::*, database_params::*, import_params::*, keystore_params::*, network_params::*,
@@ -115,44 +115,32 @@ impl BlockNumberOrHash {
} }
/// Optional flag for specifying crypto algorithm /// Optional flag for specifying crypto algorithm
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct CryptoSchemeFlag { pub struct CryptoSchemeFlag {
/// cryptography scheme /// cryptography scheme
#[structopt( #[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true, default_value = "Sr25519")]
long,
value_name = "SCHEME",
possible_values = &CryptoScheme::variants(),
case_insensitive = true,
default_value = "Sr25519"
)]
pub scheme: CryptoScheme, pub scheme: CryptoScheme,
} }
/// Optional flag for specifying output type /// Optional flag for specifying output type
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct OutputTypeFlag { pub struct OutputTypeFlag {
/// output format /// output format
#[structopt( #[clap(long, value_name = "FORMAT", arg_enum, ignore_case = true, default_value = "Text")]
long,
value_name = "FORMAT",
possible_values = &OutputType::variants(),
case_insensitive = true,
default_value = "Text"
)]
pub output_type: OutputType, pub output_type: OutputType,
} }
/// Optional flag for specifying network scheme /// Optional flag for specifying network scheme
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct NetworkSchemeFlag { pub struct NetworkSchemeFlag {
/// network address format /// network address format
#[structopt( #[clap(
short = 'n',
long, long,
value_name = "NETWORK", value_name = "NETWORK",
short = "n",
possible_values = &Ss58AddressFormat::all_names()[..], possible_values = &Ss58AddressFormat::all_names()[..],
ignore_case = true,
parse(try_from_str = Ss58AddressFormat::try_from), parse(try_from_str = Ss58AddressFormat::try_from),
case_insensitive = true,
)] )]
pub network: Option<Ss58AddressFormat>, pub network: Option<Ss58AddressFormat>,
} }
@@ -17,6 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{arg_enums::SyncMode, params::node_key_params::NodeKeyParams}; use crate::{arg_enums::SyncMode, params::node_key_params::NodeKeyParams};
use clap::Args;
use sc_network::{ use sc_network::{
config::{ config::{
NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig, NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig,
@@ -28,17 +29,16 @@ use sc_service::{
ChainSpec, ChainType, ChainSpec, ChainType,
}; };
use std::{borrow::Cow, path::PathBuf}; use std::{borrow::Cow, path::PathBuf};
use structopt::StructOpt;
/// Parameters used to create the network configuration. /// Parameters used to create the network configuration.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct NetworkParams { pub struct NetworkParams {
/// Specify a list of bootnodes. /// Specify a list of bootnodes.
#[structopt(long = "bootnodes", value_name = "ADDR")] #[clap(long, value_name = "ADDR")]
pub bootnodes: Vec<MultiaddrWithPeerId>, pub bootnodes: Vec<MultiaddrWithPeerId>,
/// Specify a list of reserved node addresses. /// Specify a list of reserved node addresses.
#[structopt(long = "reserved-nodes", value_name = "ADDR")] #[clap(long, value_name = "ADDR")]
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.
@@ -49,12 +49,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.
#[structopt(long = "reserved-only")] #[clap(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.
#[structopt(long, value_name = "PUBLIC_ADDR")] #[clap(long, value_name = "PUBLIC_ADDR")]
pub public_addr: Vec<Multiaddr>, pub public_addr: Vec<Multiaddr>,
/// Listen on this multiaddress. /// Listen on this multiaddress.
@@ -62,60 +62,60 @@ 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`.
#[structopt(long = "listen-addr", value_name = "LISTEN_ADDR")] #[clap(long, value_name = "LISTEN_ADDR")]
pub listen_addr: Vec<Multiaddr>, pub listen_addr: Vec<Multiaddr>,
/// Specify p2p protocol TCP port. /// Specify p2p protocol TCP port.
#[structopt(long = "port", value_name = "PORT", conflicts_with_all = &[ "listen-addr" ])] #[clap(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.
#[structopt(long = "no-private-ipv4", conflicts_with_all = &["allow-private-ipv4"])] #[clap(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.
#[structopt(long = "allow-private-ipv4", conflicts_with_all = &["no-private-ipv4"])] #[clap(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.
#[structopt(long = "out-peers", value_name = "COUNT", default_value = "25")] #[clap(long, value_name = "COUNT", default_value = "25")]
pub out_peers: u32, pub out_peers: u32,
/// Maximum number of inbound full nodes peers. /// Maximum number of inbound full nodes peers.
#[structopt(long = "in-peers", value_name = "COUNT", default_value = "25")] #[clap(long, value_name = "COUNT", default_value = "25")]
pub in_peers: u32, pub in_peers: u32,
/// Maximum number of inbound light nodes peers. /// Maximum number of inbound light nodes peers.
#[structopt(long = "in-peers-light", value_name = "COUNT", default_value = "100")] #[clap(long, value_name = "COUNT", default_value = "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.
#[structopt(long = "no-mdns")] #[clap(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.
#[structopt(long = "max-parallel-downloads", value_name = "COUNT", default_value = "5")] #[clap(long, value_name = "COUNT", default_value = "5")]
pub max_parallel_downloads: u32, pub max_parallel_downloads: u32,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub node_key_params: NodeKeyParams, pub node_key_params: NodeKeyParams,
/// Enable peer discovery on local networks. /// Enable peer discovery on local networks.
/// ///
/// 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.
#[structopt(long)] #[clap(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
@@ -123,11 +123,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.
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub ipfs_server: bool, pub ipfs_server: bool,
/// Blockchain syncing mode. /// Blockchain syncing mode.
@@ -137,7 +137,7 @@ pub struct NetworkParams {
/// - `Fast`: Download blocks and the latest state only. /// - `Fast`: Download blocks and the latest state only.
/// ///
/// - `FastUnsafe`: Same as `Fast`, but skip downloading state proofs. /// - `FastUnsafe`: Same as `Fast`, but skip downloading state proofs.
#[structopt(long, value_name = "SYNC_MODE", default_value = "Full")] #[clap(long, arg_enum, value_name = "SYNC_MODE", default_value = "Full")]
pub sync: SyncMode, pub sync: SyncMode,
} }
@@ -16,10 +16,10 @@
// 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/>.
use clap::Args;
use sc_network::config::{identity::ed25519, NodeKeyConfig}; use sc_network::config::{identity::ed25519, NodeKeyConfig};
use sp_core::H256; use sp_core::H256;
use std::{path::PathBuf, str::FromStr}; use std::{path::PathBuf, str::FromStr};
use structopt::StructOpt;
use crate::{arg_enums::NodeKeyType, error}; use crate::{arg_enums::NodeKeyType, error};
@@ -30,7 +30,7 @@ const NODE_KEY_ED25519_FILE: &str = "secret_ed25519";
/// Parameters used to create the `NodeKeyConfig`, which determines the keypair /// Parameters used to create the `NodeKeyConfig`, which determines the keypair
/// used for libp2p networking. /// used for libp2p networking.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct NodeKeyParams { pub struct NodeKeyParams {
/// The secret key to use for libp2p networking. /// The secret key to use for libp2p networking.
/// ///
@@ -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.
#[structopt(long = "node-key", value_name = "KEY")] #[clap(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,13 +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.
#[structopt( #[clap(long, value_name = "TYPE", arg_enum, ignore_case = true, default_value = "Ed25519")]
long = "node-key-type",
value_name = "TYPE",
possible_values = &NodeKeyType::variants(),
case_insensitive = true,
default_value = "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.
@@ -85,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.
#[structopt(long = "node-key-file", value_name = "FILE")] #[clap(long, value_name = "FILE")]
pub node_key_file: Option<PathBuf>, pub node_key_file: Option<PathBuf>,
} }
@@ -128,14 +122,15 @@ 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 sc_network::config::identity::{ed25519, Keypair}; use sc_network::config::identity::{ed25519, Keypair};
use std::fs; use std::fs;
#[test] #[test]
fn test_node_key_config_input() { fn test_node_key_config_input() {
fn secret_input(net_config_dir: &PathBuf) -> error::Result<()> { fn secret_input(net_config_dir: &PathBuf) -> error::Result<()> {
NodeKeyType::variants().iter().try_for_each(|t| { NodeKeyType::value_variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap(); let node_key_type = *t;
let sk = match node_key_type { let sk = match node_key_type {
NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec(), NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec(),
}; };
@@ -194,8 +189,8 @@ mod tests {
where where
F: Fn(NodeKeyParams) -> error::Result<()>, F: Fn(NodeKeyParams) -> error::Result<()>,
{ {
NodeKeyType::variants().iter().try_for_each(|t| { NodeKeyType::value_variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap(); let node_key_type = *t;
f(NodeKeyParams { node_key_type, node_key: None, node_key_file: None }) f(NodeKeyParams { node_key_type, node_key: None, node_key_file: None })
}) })
} }
@@ -23,23 +23,23 @@
//! targeted at handling input parameter parsing providing //! targeted at handling input parameter parsing providing
//! a reasonable abstraction. //! a reasonable abstraction.
use clap::Args;
use sc_network::config::Role; use sc_network::config::Role;
use sc_service::config::OffchainWorkerConfig; use sc_service::config::OffchainWorkerConfig;
use structopt::StructOpt;
use crate::{error, OffchainWorkerEnabled}; use crate::{error, OffchainWorkerEnabled};
/// Offchain worker related parameters. /// Offchain worker related parameters.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct OffchainWorkerParams { 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.
#[structopt( #[clap(
long = "offchain-worker", long = "offchain-worker",
value_name = "ENABLED", value_name = "ENABLED",
possible_values = &OffchainWorkerEnabled::variants(), arg_enum,
case_insensitive = true, ignore_case = true,
default_value = "WhenValidating" default_value = "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.
#[structopt(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")] #[clap(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")]
pub indexing_enabled: bool, pub indexing_enabled: bool,
} }
@@ -17,23 +17,23 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::error; use crate::error;
use clap::Args;
use sc_service::{KeepBlocks, PruningMode, Role}; use sc_service::{KeepBlocks, PruningMode, Role};
use structopt::StructOpt;
/// Parameters to define the pruning mode /// Parameters to define the pruning mode
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct PruningParams { pub struct PruningParams {
/// Specify the state pruning mode, a number of blocks to keep or 'archive'. /// Specify the state pruning mode, a number of blocks to keep or 'archive'.
/// ///
/// Default is to keep all block states if the node is running as a /// Default is to keep all block states if the node is running as a
/// validator (i.e. 'archive'), otherwise state is only kept for the last /// validator (i.e. 'archive'), otherwise state is only kept for the last
/// 256 blocks. /// 256 blocks.
#[structopt(long = "pruning", value_name = "PRUNING_MODE")] #[clap(long, value_name = "PRUNING_MODE")]
pub pruning: Option<String>, pub pruning: Option<String>,
/// Specify the number of finalized blocks to keep in the database. /// Specify the number of finalized blocks to keep in the database.
/// ///
/// Default is to keep all blocks. /// Default is to keep all blocks.
#[structopt(long, value_name = "COUNT")] #[clap(long, value_name = "COUNT")]
pub keep_blocks: Option<u32>, pub keep_blocks: Option<u32>,
} }
@@ -17,36 +17,36 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::arg_enums::TracingReceiver; use crate::arg_enums::TracingReceiver;
use clap::Args;
use sc_service::config::BasePath; use sc_service::config::BasePath;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::StructOpt;
/// Shared parameters used by all `CoreParams`. /// Shared parameters used by all `CoreParams`.
#[derive(Debug, StructOpt, Clone)] #[derive(Debug, Clone, Args)]
pub struct SharedParams { pub struct SharedParams {
/// Specify the chain specification. /// Specify the chain specification.
/// ///
/// 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).
#[structopt(long, value_name = "CHAIN_SPEC")] #[clap(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.
#[structopt(long, conflicts_with_all = &["chain"])] #[clap(long, conflicts_with_all = &["chain"])]
pub dev: bool, pub dev: bool,
/// Specify custom base path. /// Specify custom base path.
#[structopt(long, short = "d", value_name = "PATH", parse(from_os_str))] #[clap(long, short = 'd', value_name = "PATH", parse(from_os_str))]
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>.
#[structopt(short = "l", long, value_name = "LOG_PATTERN")] #[clap(short = 'l', long, value_name = "LOG_PATTERN")]
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`.
#[structopt(long)] #[clap(long)]
pub detailed_log_output: bool, pub detailed_log_output: bool,
/// Disable log color output. /// Disable log color output.
#[structopt(long)] #[clap(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,21 +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.
#[structopt(long)] #[clap(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>
#[structopt(long = "tracing-targets", value_name = "TARGETS")] #[clap(long, value_name = "TARGETS")]
pub tracing_targets: Option<String>, pub tracing_targets: Option<String>,
/// Receiver to process tracing messages. /// Receiver to process tracing messages.
#[structopt( #[clap(long, value_name = "RECEIVER", arg_enum, ignore_case = true, default_value = "Log")]
long = "tracing-receiver",
value_name = "RECEIVER",
possible_values = &TracingReceiver::variants(),
case_insensitive = true,
default_value = "Log"
)]
pub tracing_receiver: TracingReceiver, pub tracing_receiver: TracingReceiver,
} }
@@ -16,18 +16,18 @@
// 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/>.
use clap::Args;
use sc_service::config::TransactionPoolOptions; use sc_service::config::TransactionPoolOptions;
use structopt::StructOpt;
/// Parameters used to create the pool configuration. /// Parameters used to create the pool configuration.
#[derive(Debug, StructOpt, Clone)] #[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.
#[structopt(long = "pool-limit", value_name = "COUNT", default_value = "8192")] #[clap(long, value_name = "COUNT", default_value = "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.
#[structopt(long = "pool-kbytes", value_name = "COUNT", default_value = "20480")] #[clap(long, value_name = "COUNT", default_value = "20480")]
pub pool_kbytes: usize, pub pool_kbytes: usize,
} }
@@ -31,7 +31,5 @@ sp-std = { path = "../../../primitives/std", version = "4.0.0" }
remote-externalities = { path = "../../../utils/frame/remote-externalities", version = "0.10.0-dev" } remote-externalities = { path = "../../../utils/frame/remote-externalities", version = "0.10.0-dev" }
# others # others
tokio = { version = "1", features = ["macros"] }
log = "0.4.14" log = "0.4.14"
structopt = "0.3.25" tokio = { version = "1", features = ["macros"] }
clap = "2.34.0"
+4 -12
View File
@@ -21,10 +21,7 @@ scale-info = { version = "1.0", default-features = false, features = ["derive"]
log = { version = "0.4.11", default-features = false } log = { version = "0.4.11", default-features = false }
serde = { version = "1.0.132", optional = true, features = ["derive"] } serde = { version = "1.0.132", optional = true, features = ["derive"] }
byteorder = { version = "1.3.2", default-features = false } byteorder = { version = "1.3.2", default-features = false }
primitive-types = { version = "0.10.1", default-features = false, features = [ primitive-types = { version = "0.10.1", default-features = false, features = ["codec", "scale-info"] }
"codec",
"scale-info"
] }
impl-serde = { version = "0.3.0", optional = true } impl-serde = { version = "0.3.0", optional = true }
wasmi = { version = "0.9.1", optional = true } wasmi = { version = "0.9.1", optional = true }
hash-db = { version = "0.15.2", default-features = false } hash-db = { version = "0.15.2", default-features = false }
@@ -43,19 +40,14 @@ sp-std = { version = "4.0.0", default-features = false, path = "../std" }
sp-debug-derive = { version = "4.0.0", default-features = false, path = "../debug-derive" } sp-debug-derive = { version = "4.0.0", default-features = false, path = "../debug-derive" }
sp-storage = { version = "4.0.0", default-features = false, path = "../storage" } sp-storage = { version = "4.0.0", default-features = false, path = "../storage" }
sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" } sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" }
parity-util-mem = { version = "0.10.2", default-features = false, features = [ parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] }
"primitive-types",
] }
futures = { version = "0.3.1", optional = true } futures = { version = "0.3.1", optional = true }
dyn-clonable = { version = "0.9.0", optional = true } dyn-clonable = { version = "0.9.0", optional = true }
thiserror = { version = "1.0.30", optional = true } thiserror = { version = "1.0.30", optional = true }
bitflags = "1.3" bitflags = "1.3"
# full crypto # full crypto
ed25519-dalek = { version = "1.0.1", default-features = false, features = [ ed25519-dalek = { version = "1.0.1", default-features = false, features = ["u64_backend", "alloc"], optional = true }
"u64_backend",
"alloc",
], optional = true }
blake2-rfc = { version = "0.2.18", default-features = false, optional = true } blake2-rfc = { version = "0.2.18", default-features = false, optional = true }
tiny-keccak = { version = "2.0.1", features = ["keccak"], optional = true } tiny-keccak = { version = "2.0.1", features = ["keccak"], optional = true }
schnorrkel = { version = "0.9.1", features = [ schnorrkel = { version = "0.9.1", features = [
@@ -67,7 +59,7 @@ hex = { version = "0.4", default-features = false, optional = true }
twox-hash = { version = "1.6.2", default-features = false, optional = true } twox-hash = { version = "1.6.2", default-features = false, optional = true }
libsecp256k1 = { version = "0.7", default-features = false, features = ["hmac", "static-context"], optional = true } libsecp256k1 = { version = "0.7", default-features = false, features = ["hmac", "static-context"], optional = true }
merlin = { version = "2.0", default-features = false, optional = true } merlin = { version = "2.0", default-features = false, optional = true }
ss58-registry = { version = "1.10.0", default-features = false } ss58-registry = { version = "1.11.0", default-features = false }
sp-core-hashing = { version = "4.0.0", path = "./hashing", default-features = false, optional = true } sp-core-hashing = { version = "4.0.0", path = "./hashing", default-features = false, optional = true }
sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../runtime-interface" } sp-runtime-interface = { version = "4.1.0-dev", default-features = false, path = "../runtime-interface" }
@@ -14,13 +14,14 @@ publish = false
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
honggfuzz = "0.5"
rand = { version = "0.8", features = ["std", "small_rng"] }
codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
scale-info = { version = "1.0", default-features = false, features = ["derive"] } scale-info = { version = "1.0", default-features = false, features = ["derive"] }
honggfuzz = "0.5"
rand = { version = "0.7.3", features = ["std", "small_rng"] }
sp-npos-elections = { version = "4.0.0-dev", path = ".." } sp-npos-elections = { version = "4.0.0-dev", path = ".." }
sp-runtime = { version = "4.1.0-dev", path = "../../runtime" } sp-runtime = { version = "4.1.0-dev", path = "../../runtime" }
structopt = "0.3.25"
[[bin]] [[bin]]
name = "reduce" name = "reduce"
@@ -68,7 +68,7 @@ pub fn generate_random_npos_inputs(
// always generate a sensible desired number of candidates: elections are uninteresting if we // always generate a sensible desired number of candidates: elections are uninteresting if we
// desire 0 candidates, or a number of candidates >= the actual number of candidates present // desire 0 candidates, or a number of candidates >= the actual number of candidates present
let rounds = rng.gen_range(1, candidate_count); let rounds = rng.gen_range(1..candidate_count);
// candidates are easy: just a completely random set of IDs // candidates are easy: just a completely random set of IDs
let mut candidates: Vec<AccountId> = Vec::with_capacity(candidate_count); let mut candidates: Vec<AccountId> = Vec::with_capacity(candidate_count);
@@ -95,7 +95,7 @@ pub fn generate_random_npos_inputs(
let vote_weight = rng.gen(); let vote_weight = rng.gen();
// it's not interesting if a voter chooses 0 or all candidates, so rule those cases out. // it's not interesting if a voter chooses 0 or all candidates, so rule those cases out.
let n_candidates_chosen = rng.gen_range(1, candidates.len()); let n_candidates_chosen = rng.gen_range(1..candidates.len());
let mut chosen_candidates = Vec::with_capacity(n_candidates_chosen); let mut chosen_candidates = Vec::with_capacity(n_candidates_chosen);
chosen_candidates.extend(candidates.choose_multiple(&mut rng, n_candidates_chosen)); chosen_candidates.extend(candidates.choose_multiple(&mut rng, n_candidates_chosen));
@@ -132,25 +132,25 @@ pub fn generate_random_npos_result(
(1..=target_count).for_each(|acc| { (1..=target_count).for_each(|acc| {
candidates.push(acc); candidates.push(acc);
let stake_var = rng.gen_range(ed, 100 * ed); let stake_var = rng.gen_range(ed..100 * ed);
stake_of.insert(acc, base_stake + stake_var); stake_of.insert(acc, base_stake + stake_var);
}); });
let mut voters = Vec::with_capacity(voter_count as usize); let mut voters = Vec::with_capacity(voter_count as usize);
(prefix..=(prefix + voter_count)).for_each(|acc| { (prefix..=(prefix + voter_count)).for_each(|acc| {
let edge_per_this_voter = rng.gen_range(1, candidates.len()); let edge_per_this_voter = rng.gen_range(1..candidates.len());
// all possible targets // all possible targets
let mut all_targets = candidates.clone(); let mut all_targets = candidates.clone();
// we remove and pop into `targets` `edge_per_this_voter` times. // we remove and pop into `targets` `edge_per_this_voter` times.
let targets = (0..edge_per_this_voter) let targets = (0..edge_per_this_voter)
.map(|_| { .map(|_| {
let upper = all_targets.len() - 1; let upper = all_targets.len() - 1;
let idx = rng.gen_range(0, upper); let idx = rng.gen_range(0..upper);
all_targets.remove(idx) all_targets.remove(idx)
}) })
.collect::<Vec<AccountId>>(); .collect::<Vec<AccountId>>();
let stake_var = rng.gen_range(ed, 100 * ed); let stake_var = rng.gen_range(ed..100 * ed);
let stake = base_stake + stake_var; let stake = base_stake + stake_var;
stake_of.insert(acc, stake); stake_of.insert(acc, stake);
voters.push((acc, stake, targets)); voters.push((acc, stake, targets));
@@ -42,7 +42,7 @@
use honggfuzz::fuzz; use honggfuzz::fuzz;
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
use structopt::StructOpt; use clap::Parser;
mod common; mod common;
use common::{generate_random_npos_inputs, to_range}; use common::{generate_random_npos_inputs, to_range};
@@ -67,24 +67,25 @@ fn main() {
} }
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[clap(author, version, about)]
struct Opt { struct Opt {
/// How many candidates participate in this election /// How many candidates participate in this election
#[structopt(short, long)] #[clap(short, long)]
candidates: Option<usize>, candidates: Option<usize>,
/// How many voters participate in this election /// How many voters participate in this election
#[structopt(short, long)] #[clap(short, long)]
voters: Option<usize>, voters: Option<usize>,
/// Random seed to use in this election /// Random seed to use in this election
#[structopt(long)] #[clap(long)]
seed: Option<u64>, seed: Option<u64>,
} }
#[cfg(not(fuzzing))] #[cfg(not(fuzzing))]
fn main() { fn main() {
let opt = Opt::from_args(); let opt = Opt::parse();
// candidates and voters by default use the maxima, which turn out to be one less than // candidates and voters by default use the maxima, which turn out to be one less than
// the constant. // the constant.
iteration( iteration(
@@ -79,8 +79,7 @@ fn generate_random_phragmen_assignment(
let mut targets_to_chose_from = all_targets.clone(); let mut targets_to_chose_from = all_targets.clone();
let targets_to_chose = if edge_per_voter_var > 0 { let targets_to_chose = if edge_per_voter_var > 0 {
rng.gen_range( rng.gen_range(
avg_edge_per_voter - edge_per_voter_var, avg_edge_per_voter - edge_per_voter_var..avg_edge_per_voter + edge_per_voter_var,
avg_edge_per_voter + edge_per_voter_var,
) )
} else { } else {
avg_edge_per_voter avg_edge_per_voter
@@ -89,11 +88,11 @@ fn generate_random_phragmen_assignment(
let distribution = (0..targets_to_chose) let distribution = (0..targets_to_chose)
.map(|_| { .map(|_| {
let target = let target =
targets_to_chose_from.remove(rng.gen_range(0, targets_to_chose_from.len())); targets_to_chose_from.remove(rng.gen_range(0..targets_to_chose_from.len()));
if winners.iter().all(|w| *w != target) { if winners.iter().all(|w| *w != target) {
winners.push(target.clone()); winners.push(target.clone());
} }
(target, rng.gen_range(1 * KSM, 100 * KSM)) (target, rng.gen_range(1 * KSM..100 * KSM))
}) })
.collect::<Vec<(AccountId, ExtendedBalance)>>(); .collect::<Vec<(AccountId, ExtendedBalance)>>();
@@ -25,7 +25,7 @@ sp-keystore = { version = "0.10.0", path = "../../../primitives/keystore" }
sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" }
sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" } sp-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" }
codec = { version = "2.0.0", package = "parity-scale-codec" } codec = { version = "2.0.0", package = "parity-scale-codec" }
structopt = "0.3.25" clap = { version = "3.0", features = ["derive"] }
chrono = "0.4" chrono = "0.4"
serde = "1.0.132" serde = "1.0.132"
handlebars = "4.1.6" handlebars = "4.1.6"
@@ -28,124 +28,119 @@ fn parse_pallet_name(pallet: &str) -> String {
} }
/// The `benchmark` command used to benchmark FRAME Pallets. /// The `benchmark` command used to benchmark FRAME Pallets.
#[derive(Debug, structopt::StructOpt)] #[derive(Debug, clap::Parser)]
pub struct BenchmarkCmd { pub struct BenchmarkCmd {
/// 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 `*`).
#[structopt(short, long, parse(from_str = parse_pallet_name), required_unless = "list")] #[clap(short, long, parse(from_str = parse_pallet_name), required_unless_present = "list")]
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.
#[structopt(short, long, required_unless = "list")] #[clap(short, long, required_unless_present = "list")]
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.
#[structopt(short, long, default_value = "1")] #[clap(short, long, default_value = "1")]
pub steps: u32, pub steps: u32,
/// Indicates lowest values for each of the component ranges. /// Indicates lowest values for each of the component ranges.
#[structopt(long = "low", use_delimiter = true)] #[clap(long = "low", use_delimiter = true)]
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.
#[structopt(long = "high", use_delimiter = true)] #[clap(long = "high", use_delimiter = true)]
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.
#[structopt(short, long, default_value = "1")] #[clap(short, long, default_value = "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.
#[structopt(long, default_value = "1")] #[clap(long, default_value = "1")]
pub external_repeat: u32, pub external_repeat: u32,
/// Print the raw results. /// Print the raw results.
#[structopt(long = "raw")] #[clap(long = "raw")]
pub raw_data: bool, pub raw_data: bool,
/// Don't print the median-slopes linear regression analysis. /// Don't print the median-slopes linear regression analysis.
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub output: Option<std::path::PathBuf>, pub output: Option<std::path::PathBuf>,
/// Add a header file to your outputted benchmarks /// Add a header file to your outputted benchmarks
#[structopt(long)] #[clap(long)]
pub header: Option<std::path::PathBuf>, pub header: Option<std::path::PathBuf>,
/// Path to Handlebars template file used for outputting benchmark results. (Optional) /// Path to Handlebars template file used for outputting benchmark results. (Optional)
#[structopt(long)] #[clap(long)]
pub template: Option<std::path::PathBuf>, pub template: Option<std::path::PathBuf>,
/// Which analysis function to use when outputting benchmarks: /// Which analysis function to use when outputting benchmarks:
/// * 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)
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub heap_pages: Option<u64>, pub heap_pages: Option<u64>,
/// Disable verification logic when running benchmarks. /// Disable verification logic when running benchmarks.
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub extra: bool, pub extra: bool,
/// Estimate PoV size. /// Estimate PoV size.
#[structopt(long)] #[clap(long)]
pub record_proof: bool, pub record_proof: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
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
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
long = "execution",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
pub execution: Option<ExecutionStrategy>, pub execution: Option<ExecutionStrategy>,
/// Method for executing Wasm runtime code. /// Method for executing Wasm runtime code.
#[structopt( #[clap(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(), possible_values = WasmExecutionMethod::variants(),
case_insensitive = true, ignore_case = true,
default_value = "compiled" default_value = "compiled"
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
/// Limit the memory the database cache can use. /// Limit the memory the database cache can use.
#[structopt(long = "db-cache", value_name = "MiB", default_value = "1024")] #[clap(long = "db-cache", value_name = "MiB", default_value = "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.
#[structopt(long)] #[clap(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.
#[structopt(long)] #[clap(long)]
pub no_storage_info: bool, pub no_storage_info: bool,
} }
@@ -11,10 +11,11 @@ documentation = "https://docs.rs/substrate-frame-cli"
readme = "README.md" readme = "README.md"
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" } sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" } sp-runtime = { version = "4.1.0-dev", path = "../../../primitives/runtime" }
structopt = "0.3.25"
frame-system = { version = "4.0.0-dev", path = "../../../frame/system" } frame-system = { version = "4.0.0-dev", path = "../../../frame/system" }
frame-support = { version = "4.0.0-dev", path = "../../../frame/support" } frame-support = { version = "4.0.0-dev", path = "../../../frame/support" }
@@ -17,6 +17,7 @@
//! Implementation of the `palletid` subcommand //! Implementation of the `palletid` subcommand
use clap::Parser;
use frame_support::PalletId; use frame_support::PalletId;
use sc_cli::{ use sc_cli::{
utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams,
@@ -24,35 +25,34 @@ use sc_cli::{
}; };
use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec}; use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec};
use sp_runtime::traits::AccountIdConversion; use sp_runtime::traits::AccountIdConversion;
use structopt::StructOpt;
/// The `palletid` command /// The `palletid` command
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
#[structopt(name = "palletid", about = "Inspect a module ID address")] #[clap(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
#[structopt( #[clap(
long, long,
value_name = "NETWORK", value_name = "NETWORK",
possible_values = &Ss58AddressFormat::all_names()[..], possible_values = &Ss58AddressFormat::all_names()[..],
parse(try_from_str = Ss58AddressFormat::try_from), parse(try_from_str = Ss58AddressFormat::try_from),
case_insensitive = true, ignore_case = true,
)] )]
pub network: Option<Ss58AddressFormat>, pub network: Option<Ss58AddressFormat>,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub output_scheme: OutputTypeFlag, pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag, pub crypto_scheme: CryptoSchemeFlag,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
pub keystore_params: KeystoreParams, pub keystore_params: KeystoreParams,
} }
@@ -23,4 +23,3 @@ sp-io = { version = "4.0.0", path = "../../../primitives/io" }
chrono = { version = "0.4.19" } chrono = { version = "0.4.19" }
git2 = { version = "0.13.25", default-features = false } git2 = { version = "0.13.25", default-features = false }
num-format = { version = "0.4.0" } num-format = { version = "0.4.0" }
structopt = "0.3.25"
@@ -14,4 +14,4 @@ node-runtime = { version = "3.0.0-dev", path = "../../../../bin/node/runtime" }
generate-bags = { version = "4.0.0-dev", path = "../" } generate-bags = { version = "4.0.0-dev", path = "../" }
# third-party # third-party
structopt = "0.3.25" clap = { version = "3.0", features = ["derive"] }
@@ -17,30 +17,31 @@
//! Make the set of bag thresholds to be used with pallet-bags-list. //! Make the set of bag thresholds to be used with pallet-bags-list.
use clap::Parser;
use generate_bags::generate_thresholds; use generate_bags::generate_thresholds;
use std::path::PathBuf; use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, Parser)]
// #[clap(author, version, about)]
struct Opt { struct Opt {
/// How many bags to generate. /// How many bags to generate.
#[structopt(long, default_value = "200")] #[clap(long, default_value = "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`.
#[structopt(short, long)] #[clap(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`.
#[structopt(short, long)] #[clap(short, long)]
minimum_balance: u128, minimum_balance: u128,
} }
fn main() -> Result<(), std::io::Error> { fn main() -> Result<(), std::io::Error> {
let Opt { n_bags, output, total_issuance, minimum_balance } = Opt::from_args(); let Opt { n_bags, output, total_issuance, minimum_balance } = Opt::parse();
generate_thresholds::<node_runtime::Runtime>(n_bags, &output, total_issuance, minimum_balance) generate_thresholds::<node_runtime::Runtime>(n_bags, &output, total_issuance, minimum_balance)
} }
@@ -13,10 +13,11 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"] targets = ["x86_64-unknown-linux-gnu"]
[dependencies] [dependencies]
clap = { version = "3.0", features = ["derive"] }
log = "0.4.8" log = "0.4.8"
parity-scale-codec = { version = "2.3.1" } parity-scale-codec = { version = "2.3.1" }
serde = "1.0.132" serde = "1.0.132"
structopt = "0.3.25" zstd = "0.9.0"
sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../../client/service" } sc-service = { version = "0.10.0-dev", default-features = false, path = "../../../../client/service" }
sc-cli = { version = "0.10.0-dev", path = "../../../../client/cli" } sc-cli = { version = "0.10.0-dev", path = "../../../../client/cli" }
@@ -31,6 +32,4 @@ sp-externalities = { version = "0.10.0", path = "../../../../primitives/external
sp-version = { version = "4.0.0-dev", path = "../../../../primitives/version" } sp-version = { version = "4.0.0-dev", path = "../../../../primitives/version" }
remote-externalities = { version = "0.10.0-dev", path = "../../remote-externalities" } remote-externalities = { version = "0.10.0-dev", path = "../../remote-externalities" }
jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"]} jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"] }
zstd = "0.9.0"
@@ -26,25 +26,25 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use std::{fmt::Debug, str::FromStr}; use std::{fmt::Debug, str::FromStr};
/// Configurations of the [`Command::ExecuteBlock`]. /// Configurations of the [`Command::ExecuteBlock`].
#[derive(Debug, Clone, structopt::StructOpt)] #[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.
#[structopt(long)] #[clap(long)]
overwrite_wasm_code: bool, overwrite_wasm_code: bool,
/// If set, then the state root check is disabled by the virtue of calling into /// If set, then the state root check is disabled by the virtue of calling into
/// `TryRuntime_execute_block_no_check` instead of /// `TryRuntime_execute_block_no_check` instead of
/// `Core_execute_block`. /// `Core_execute_block`.
#[structopt(long)] #[clap(long)]
no_check: bool, no_check: bool,
/// 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.
#[structopt( #[clap(
long, long,
multiple = false, multiple_values = false,
parse(try_from_str = crate::parse::hash) parse(try_from_str = crate::parse::hash)
)] )]
block_at: Option<String>, block_at: Option<String>,
@@ -53,9 +53,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.
#[structopt( #[clap(
long, long,
multiple = false, multiple_values = false,
parse(try_from_str = crate::parse::url) parse(try_from_str = crate::parse::url)
)] )]
block_ws_uri: Option<String>, block_ws_uri: Option<String>,
@@ -65,7 +65,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.
#[structopt(subcommand)] #[clap(subcommand)]
state: State, state: State,
} }
@@ -35,14 +35,10 @@ const SUB: &'static str = "chain_subscribeFinalizedHeads";
const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads"; const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads";
/// Configurations of the [`Command::FollowChain`]. /// Configurations of the [`Command::FollowChain`].
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Parser)]
pub struct FollowChainCmd { pub struct FollowChainCmd {
/// The url to connect to. /// The url to connect to.
#[structopt( #[clap(short, long, parse(try_from_str = parse::url))]
short,
long,
parse(try_from_str = parse::url),
)]
uri: String, uri: String,
} }
@@ -28,19 +28,19 @@ use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::{fmt::Debug, str::FromStr}; use std::{fmt::Debug, str::FromStr};
/// Configurations of the [`Command::OffchainWorker`]. /// Configurations of the [`Command::OffchainWorker`].
#[derive(Debug, Clone, structopt::StructOpt)] #[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.
#[structopt(long)] #[clap(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.
#[structopt( #[clap(
long, long,
multiple = false, multiple_values = false,
parse(try_from_str = parse::hash) parse(try_from_str = parse::hash)
)] )]
header_at: Option<String>, header_at: Option<String>,
@@ -49,15 +49,15 @@ 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.
#[structopt( #[clap(
long, long,
multiple = false, multiple_values = false,
parse(try_from_str = 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.
#[structopt(subcommand)] #[clap(subcommand)]
pub state: State, pub state: State,
} }
@@ -28,10 +28,10 @@ use crate::{
}; };
/// Configurations of the [`Command::OnRuntimeUpgrade`]. /// Configurations of the [`Command::OnRuntimeUpgrade`].
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Parser)]
pub struct OnRuntimeUpgradeCmd { pub struct OnRuntimeUpgradeCmd {
/// The state type to use. /// The state type to use.
#[structopt(subcommand)] #[clap(subcommand)]
pub state: State, pub state: State,
} }
@@ -293,7 +293,7 @@ pub(crate) mod parse;
pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli"; pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli";
/// Possible commands of `try-runtime`. /// Possible commands of `try-runtime`.
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Subcommand)]
pub enum Command { pub enum Command {
/// Execute the migrations of the "local runtime". /// Execute the migrations of the "local runtime".
/// ///
@@ -373,70 +373,64 @@ pub enum Command {
} }
/// Shared parameters of the `try-runtime` commands /// Shared parameters of the `try-runtime` commands
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Parser)]
pub struct SharedParams { pub struct SharedParams {
/// Shared parameters of substrate cli. /// Shared parameters of substrate cli.
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[clap(flatten)]
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.
#[structopt( #[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true, default_value = "Wasm")]
long = "execution",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
default_value = "Wasm",
)]
pub execution: ExecutionStrategy, pub execution: ExecutionStrategy,
/// Type of wasm execution used. /// Type of wasm execution used.
#[structopt( #[clap(
long = "wasm-execution", long = "wasm-execution",
value_name = "METHOD", value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(), possible_values = WasmExecutionMethod::variants(),
case_insensitive = true, ignore_case = true,
default_value = "Compiled" default_value = "Compiled"
)] )]
pub wasm_method: WasmExecutionMethod, pub wasm_method: WasmExecutionMethod,
/// 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`].
#[structopt(long)] #[clap(long)]
pub heap_pages: Option<u64>, pub heap_pages: Option<u64>,
/// When enabled, the spec name check will not panic, and instead only show a warning. /// When enabled, the spec name check will not panic, and instead only show a warning.
#[structopt(long)] #[clap(long)]
pub no_spec_name_check: bool, pub no_spec_name_check: bool,
} }
/// Our `try-runtime` command. /// Our `try-runtime` command.
/// ///
/// See [`Command`] for more info. /// See [`Command`] for more info.
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Parser)]
pub struct TryRuntimeCmd { pub struct TryRuntimeCmd {
#[structopt(flatten)] #[clap(flatten)]
pub shared: SharedParams, pub shared: SharedParams,
#[structopt(subcommand)] #[clap(subcommand)]
pub command: Command, pub command: Command,
} }
/// The source of runtime *state* to use. /// The source of runtime *state* to use.
#[derive(Debug, Clone, structopt::StructOpt)] #[derive(Debug, Clone, clap::Subcommand)]
pub enum State { pub enum State {
/// Use a state snapshot as the source of runtime state. /// Use a state snapshot as the source of runtime 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 {
#[structopt(short, long)] #[clap(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.
#[structopt( #[clap(
short, short,
long, long,
parse(try_from_str = parse::url), parse(try_from_str = parse::url),
@@ -447,20 +441,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`].
#[structopt( #[clap(
short, short,
long, long,
multiple = false, multiple_values = false,
parse(try_from_str = 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`.
#[structopt(short, long)] #[clap(short, long)]
snapshot_path: Option<PathBuf>, snapshot_path: Option<PathBuf>,
/// The pallets to scrape. If empty, entire chain state will be scraped. /// The pallets to scrape. If empty, entire chain state will be scraped.
#[structopt(short, long, require_delimiter = true)] #[clap(short, long, require_delimiter = true)]
pallets: Option<Vec<String>>, pallets: Option<Vec<String>>,
/// Fetch the child-keys as well. /// Fetch the child-keys as well.
@@ -468,7 +462,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.
#[structopt(long, require_delimiter = true)] #[clap(long, require_delimiter = true)]
child_tree: bool, child_tree: bool,
}, },
} }