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"
tar = "0.4"
glob = "0.2"
structopt = "0.3"
clap = { version = "3.0", features = ["derive"] }
tempfile = "3"
fs_extra = "1"
git2 = "0.8"
@@ -1,4 +1,4 @@
use structopt::StructOpt;
use clap::Parser;
use std::{
collections::HashMap,
@@ -26,13 +26,13 @@ const SUBSTRATE_GIT_URL: &str = "https://github.com/paritytech/substrate.git";
type CargoToml = HashMap<String, toml::Value>;
#[derive(StructOpt)]
#[derive(Parser)]
struct Options {
/// The path to the `node-template` source.
#[structopt(parse(from_os_str))]
#[clap(parse(from_os_str))]
node_template: PathBuf,
/// The path where to output the generated `tar.gz` file.
#[structopt(parse(from_os_str))]
#[clap(parse(from_os_str))]
output: PathBuf,
}
@@ -209,7 +209,7 @@ fn build_and_test(path: &Path, cargo_tomls: &[PathBuf]) {
}
fn main() {
let options = Options::from_args();
let options = Options::parse();
let build_dir = tempfile::tempdir().expect("Creates temp build dir");
@@ -261,8 +261,7 @@ fn main() {
// adding root rustfmt to node template build path
let node_template_rustfmt_toml_path = node_template_path.join("rustfmt.toml");
let root_rustfmt_toml =
&options.node_template.join("../../rustfmt.toml");
let root_rustfmt_toml = &options.node_template.join("../../rustfmt.toml");
if root_rustfmt_toml.exists() {
fs::copy(&root_rustfmt_toml, &node_template_rustfmt_toml_path)
.expect("Copying rustfmt.toml.");
+85 -67
View File
@@ -928,13 +928,13 @@ name = "chain-spec-builder"
version = "2.0.0"
dependencies = [
"ansi_term",
"clap 3.0.7",
"node-cli",
"rand 0.7.3",
"rand 0.8.4",
"sc-chain-spec",
"sc-keystore",
"sp-core",
"sp-keystore",
"structopt",
]
[[package]]
@@ -996,13 +996,48 @@ version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
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",
"bitflags",
"strsim 0.8.0",
"textwrap",
"unicode-width",
"vec_map",
"clap_derive",
"indexmap",
"lazy_static",
"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]]
@@ -1256,7 +1291,7 @@ checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10"
dependencies = [
"atty",
"cast",
"clap",
"clap 2.34.0",
"criterion-plot",
"csv",
"futures 0.3.16",
@@ -1483,7 +1518,7 @@ dependencies = [
"ident_case",
"proc-macro2",
"quote",
"strsim 0.10.0",
"strsim",
"syn",
]
@@ -1741,7 +1776,7 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c5f0096a91d210159eceb2ff5e1c4da18388a170e1e3ce948aac9c8fdbbf595"
dependencies = [
"heck",
"heck 0.3.2",
"proc-macro2",
"quote",
"syn",
@@ -2020,6 +2055,7 @@ version = "4.0.0-dev"
dependencies = [
"Inflector",
"chrono",
"clap 3.0.7",
"frame-benchmarking",
"frame-support",
"handlebars",
@@ -2036,7 +2072,6 @@ dependencies = [
"sp-keystore",
"sp-runtime",
"sp-state-machine",
"structopt",
]
[[package]]
@@ -2450,7 +2485,6 @@ dependencies = [
"num-format",
"pallet-staking",
"sp-io",
"structopt",
]
[[package]]
@@ -2653,6 +2687,12 @@ dependencies = [
"unicode-segmentation",
]
[[package]]
name = "heck"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2540771e65fc8cb83cd6e8a237f70c319bd5c29f78ed1084ba5d50eeac86f7f9"
[[package]]
name = "hermit-abi"
version = "0.1.18"
@@ -4516,6 +4556,7 @@ dependencies = [
name = "node-bench"
version = "0.9.0-dev"
dependencies = [
"clap 3.0.7",
"derive_more",
"fs_extra",
"futures 0.3.16",
@@ -4545,7 +4586,6 @@ dependencies = [
"sp-timestamp",
"sp-tracing",
"sp-trie",
"structopt",
"tempfile",
]
@@ -4555,6 +4595,8 @@ version = "3.0.0-dev"
dependencies = [
"assert_cmd",
"async-std",
"clap 3.0.7",
"clap_complete",
"criterion",
"frame-benchmarking-cli",
"frame-system",
@@ -4576,7 +4618,7 @@ dependencies = [
"pallet-transaction-payment",
"parity-scale-codec",
"platforms",
"rand 0.7.3",
"rand 0.8.4",
"regex",
"remote-externalities",
"sc-authority-discovery",
@@ -4622,7 +4664,6 @@ dependencies = [
"sp-transaction-pool",
"sp-transaction-storage-proof",
"sp-trie",
"structopt",
"substrate-build-script-utils",
"substrate-frame-cli",
"tempfile",
@@ -4668,6 +4709,7 @@ dependencies = [
name = "node-inspect"
version = "0.9.0-dev"
dependencies = [
"clap 3.0.7",
"derive_more",
"parity-scale-codec",
"sc-cli",
@@ -4677,7 +4719,6 @@ dependencies = [
"sp-blockchain",
"sp-core",
"sp-runtime",
"structopt",
]
[[package]]
@@ -4811,15 +4852,16 @@ dependencies = [
name = "node-runtime-generate-bags"
version = "3.0.0"
dependencies = [
"clap 3.0.7",
"generate-bags",
"node-runtime",
"structopt",
]
[[package]]
name = "node-template"
version = "3.0.0"
dependencies = [
"clap 3.0.7",
"frame-benchmarking",
"frame-benchmarking-cli",
"jsonrpc-core",
@@ -4848,7 +4890,6 @@ dependencies = [
"sp-finality-grandpa",
"sp-runtime",
"sp-timestamp",
"structopt",
"substrate-build-script-utils",
"substrate-frame-rpc-system",
]
@@ -5140,6 +5181,15 @@ dependencies = [
"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]]
name = "output_vt100"
version = "0.1.2"
@@ -5323,7 +5373,6 @@ dependencies = [
name = "pallet-bags-list-remote-tests"
version = "4.0.0-dev"
dependencies = [
"clap",
"frame-election-provider-support",
"frame-support",
"frame-system",
@@ -5336,7 +5385,6 @@ dependencies = [
"sp-std",
"sp-storage",
"sp-tracing",
"structopt",
"tokio",
]
@@ -6912,7 +6960,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5"
dependencies = [
"bytes 1.1.0",
"heck",
"heck 0.3.2",
"itertools",
"lazy_static",
"log 0.4.14",
@@ -7695,6 +7743,7 @@ name = "sc-cli"
version = "0.10.0-dev"
dependencies = [
"chrono",
"clap 3.0.7",
"fdlimit",
"futures 0.3.16",
"hex",
@@ -7721,7 +7770,6 @@ dependencies = [
"sp-panic-handler",
"sp-runtime",
"sp-version",
"structopt",
"tempfile",
"thiserror",
"tiny-bip39",
@@ -9624,13 +9672,13 @@ dependencies = [
name = "sp-npos-elections-fuzzer"
version = "2.0.0-alpha.5"
dependencies = [
"clap 3.0.7",
"honggfuzz",
"parity-scale-codec",
"rand 0.7.3",
"rand 0.8.4",
"scale-info",
"sp-npos-elections",
"sp-runtime",
"structopt",
]
[[package]]
@@ -10001,9 +10049,9 @@ checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "ss58-registry"
version = "1.10.0"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c83f0afe7e571565ef9aae7b0e4fb30fcaec4ebb9aea2f00489b772782aa03a4"
checksum = "1230685dc82f8699110640244d361a7099c602f08bddc5c90765a5153b4881dc"
dependencies = [
"Inflector",
"proc-macro2",
@@ -10038,42 +10086,12 @@ dependencies = [
"rand 0.8.4",
]
[[package]]
name = "strsim"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "strum"
version = "0.22.0"
@@ -10089,7 +10107,7 @@ version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "339f799d8b549e3744c7ac7feb216383e4005d94bdb22561b3ab8f3b808ae9fb"
dependencies = [
"heck",
"heck 0.3.2",
"proc-macro2",
"quote",
"syn",
@@ -10101,7 +10119,7 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bb0dc7ee9c15cea6199cde9a127fa16a4c5819af85395457ad72d68edc85a38"
dependencies = [
"heck",
"heck 0.3.2",
"proc-macro2",
"quote",
"rustversion",
@@ -10112,8 +10130,8 @@ dependencies = [
name = "subkey"
version = "2.0.1"
dependencies = [
"clap 3.0.7",
"sc-cli",
"structopt",
]
[[package]]
@@ -10140,12 +10158,12 @@ dependencies = [
name = "substrate-frame-cli"
version = "4.0.0-dev"
dependencies = [
"clap 3.0.7",
"frame-support",
"frame-system",
"sc-cli",
"sp-core",
"sp-runtime",
"structopt",
]
[[package]]
@@ -10428,6 +10446,12 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80"
[[package]]
name = "thiserror"
version = "1.0.30"
@@ -10920,6 +10944,7 @@ checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
name = "try-runtime-cli"
version = "0.10.0-dev"
dependencies = [
"clap 3.0.7",
"jsonrpsee",
"log 0.4.14",
"parity-scale-codec",
@@ -10936,7 +10961,6 @@ dependencies = [
"sp-runtime",
"sp-state-machine",
"sp-version",
"structopt",
"zstd",
]
@@ -11146,12 +11170,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eafc1b9b2dfc6f5529177b62cf806484db55b32dc7c9658a118e11bbeb33061d"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.1.5"
+2 -4
View File
@@ -17,7 +17,7 @@ targets = ["x86_64-unknown-linux-gnu"]
name = "node-template"
[dependencies]
structopt = "0.3.25"
clap = { version = "3.0", features = ["derive"] }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli", features = ["wasmtime"] }
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]
default = []
runtime-benchmarks = [
"node-template-runtime/runtime-benchmarks",
]
runtime-benchmarks = ["node-template-runtime/runtime-benchmarks"]
+7 -6
View File
@@ -1,19 +1,20 @@
use sc_cli::RunCmd;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Parser)]
pub struct Cli {
#[structopt(subcommand)]
#[clap(subcommand)]
pub subcommand: Option<Subcommand>,
#[structopt(flatten)]
#[clap(flatten)]
pub run: RunCmd,
}
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/// Key management cli utilities
#[clap(subcommand)]
Key(sc_cli::KeySubcommand),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
@@ -36,6 +37,6 @@ pub enum Subcommand {
Revert(sc_cli::RevertCmd),
/// 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),
}
+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
[dependencies]
clap = { version = "3.0", features = ["derive"] }
log = "0.4.8"
node-primitives = { version = "2.0.0", path = "../primitives" }
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" }
serde = "1.0.132"
serde_json = "1.0.74"
structopt = "0.3"
derive_more = "0.99.16"
kvdb = "0.10.0"
kvdb-rocksdb = "0.14.0"
@@ -35,9 +35,7 @@ fs_extra = "1"
hex = "0.4.0"
rand = { version = "0.7.2", features = ["small_rng"] }
lazy_static = "1.4.0"
parity-util-mem = { version = "0.10.2", default-features = false, features = [
"primitive-types",
] }
parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] }
parity-db = { version = "0.3" }
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" }
+8 -8
View File
@@ -28,7 +28,7 @@ mod tempdb;
mod trie;
mod txpool;
use structopt::StructOpt;
use clap::Parser;
use node_testing::bench::{BlockType, DatabaseType as BenchDataBaseType, KeyTypes, Profile};
@@ -42,19 +42,19 @@ use crate::{
txpool::PoolBenchmarkDescription,
};
#[derive(Debug, StructOpt)]
#[structopt(name = "node-bench", about = "Node integration benchmarks")]
#[derive(Debug, Parser)]
#[clap(name = "node-bench", about = "Node integration benchmarks")]
struct Opt {
/// Show list of all available benchmarks.
///
/// Will output ("name", "path"). Benchmarks can then be filtered by path.
#[structopt(short, long)]
#[clap(short, long)]
list: bool,
/// Machine readable json output.
///
/// This also suppresses all regular output (except to stderr)
#[structopt(short, long)]
#[clap(short, long)]
json: bool,
/// Filter benchmarks.
@@ -63,7 +63,7 @@ struct Opt {
filter: Option<String>,
/// Number of transactions for block import with `custom` size.
#[structopt(long)]
#[clap(long)]
transactions: Option<usize>,
/// Mode
@@ -72,12 +72,12 @@ struct Opt {
///
/// "profile" mode adds pauses between measurable runs,
/// 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,
}
fn main() {
let opt = Opt::from_args();
let opt = Opt::parse();
if !opt.json {
sp_tracing::try_init_simple();
+10 -15
View File
@@ -34,13 +34,13 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
# third-party dependencies
clap = { version = "3.0", features = ["derive"], optional = true }
codec = { package = "parity-scale-codec", version = "2.0.0" }
serde = { version = "1.0.132", features = ["derive"] }
futures = "0.3.16"
hex-literal = "0.3.4"
log = "0.4.8"
rand = "0.7.2"
structopt = { version = "0.3.25", optional = true }
rand = "0.8"
# primitives
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" }
[target.'cfg(any(target_arch="x86_64", target_arch="aarch64"))'.dependencies]
node-executor = { version = "3.0.0-dev", path = "../executor", features = [
"wasmtime",
] }
sc-cli = { version = "0.10.0-dev", optional = true, path = "../../../client/cli", features = [
"wasmtime",
] }
node-executor = { version = "3.0.0-dev", path = "../executor", 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 = [
"wasmtime",
] }
@@ -129,7 +125,7 @@ regex = "1"
platforms = "2.0"
async-std = { version = "1.10.0", features = ["attributes"] }
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"] }
jsonrpsee-ws-client = "0.4.1"
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" }
[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" }
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" }
@@ -155,14 +152,12 @@ cli = [
"frame-benchmarking-cli",
"substrate-frame-cli",
"sc-service/db",
"structopt",
"clap",
"clap_complete",
"substrate-build-script-utils",
"try-runtime-cli",
]
runtime-benchmarks = [
"node-runtime/runtime-benchmarks",
"frame-benchmarking-cli",
]
runtime-benchmarks = ["node-runtime/runtime-benchmarks", "frame-benchmarking-cli"]
# Enable features that allow the runtime to be tried and debugged. Name might be subject to change
# in the near future.
try-runtime = ["node-runtime/try-runtime", "try-runtime-cli"]
+4 -4
View File
@@ -25,7 +25,8 @@ fn main() {
mod cli {
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 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
/// Full list in https://github.com/kbknapp/clap-rs/blob/e9d0562a1dc5dfe731ed7c767e6cee0af08f0cf9/src/app/parser.rs#L123
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);
}
}
@@ -61,6 +61,6 @@ mod cli {
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
// 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.
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Parser)]
pub struct Cli {
/// Possible subcommand with parameters.
#[structopt(subcommand)]
#[clap(subcommand)]
pub subcommand: Option<Subcommand>,
#[allow(missing_docs)]
#[structopt(flatten)]
pub run: RunCmd,
#[clap(flatten)]
pub run: sc_cli::RunCmd,
}
/// Possible subcommands of the main binary.
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
/// Key management cli utilities
Key(KeySubcommand),
/// The custom inspect subcommmand for decoding blocks and extrinsics.
#[structopt(
#[clap(
name = "inspect",
about = "Decode given block or extrinsic using current native runtime."
)]
Inspect(node_inspect::cli::InspectCmd),
/// 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),
/// Try some command against runtime state.
@@ -55,14 +50,18 @@ pub enum Subcommand {
#[cfg(not(feature = "try-runtime"))]
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(VerifyCmd),
Verify(sc_cli::VerifyCmd),
/// Generate a seed that provides a vanity address.
Vanity(VanityCmd),
Vanity(sc_cli::VanityCmd),
/// Sign a message, with a given (secret) key.
Sign(SignCmd),
Sign(sc_cli::SignCmd),
/// Build a chain specification.
BuildSpec(sc_cli::BuildSpecCmd),
+1 -1
View File
@@ -11,6 +11,7 @@ repository = "https://github.com/paritytech/substrate/"
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
clap = { version = "3.0", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "2.0.0" }
derive_more = "0.99"
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-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
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.
use sc_cli::{ImportParams, SharedParams};
use std::fmt::Debug;
use structopt::StructOpt;
/// The `inspect` command used to print decoded chain data.
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Parser)]
pub struct InspectCmd {
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(subcommand)]
pub command: InspectSubCmd,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub import_params: ImportParams,
}
/// A possible inspect sub-commands.
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Subcommand)]
pub enum InspectSubCmd {
/// Decode block with native version of runtime and print out the details.
Block {
@@ -48,7 +46,7 @@ pub enum InspectSubCmd {
/// 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
/// a block.
#[structopt(value_name = "HASH or NUMBER or BYTES")]
#[clap(value_name = "HASH or NUMBER or BYTES")]
input: String,
},
/// 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
/// of `{block}:{index}` or a 0x-prefixed bytes hex string,
/// representing SCALE encoding of an extrinsic.
#[structopt(value_name = "BLOCK:INDEX or BYTES")]
#[clap(value_name = "BLOCK:INDEX or BYTES")]
input: String,
},
}
@@ -15,10 +15,11 @@ targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
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-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" }
node-cli = { version = "3.0.0-dev", path = "../../node/cli" }
sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
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 clap::Parser;
use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
use structopt::StructOpt;
use node_cli::chain_spec::{self, AccountId};
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
/// of authorities and endowed accounts and/or generate random accounts.
#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case")]
#[derive(Parser)]
#[clap(rename_all = "kebab-case")]
enum ChainSpecBuilder {
/// Create a new chain spec with the given authorities, endowed and sudo
/// accounts.
New {
/// Authority key seed.
#[structopt(long, short, required = true)]
#[clap(long, short, required = true)]
authority_seeds: Vec<String>,
/// Active nominators (SS58 format), each backing a random subset of the aforementioned
/// authorities.
#[structopt(long, short, default_value = "0")]
#[clap(long, short, default_value = "0")]
nominator_accounts: Vec<String>,
/// Endowed account address (SS58 format).
#[structopt(long, short)]
#[clap(long, short)]
endowed_accounts: Vec<String>,
/// Sudo account address (SS58 format).
#[structopt(long, short)]
#[clap(long, short)]
sudo_account: String,
/// 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,
},
/// Create a new chain spec with the given number of authorities and endowed
/// accounts. Random keys will be generated as required.
Generate {
/// The number of authorities.
#[structopt(long, short)]
#[clap(long, short)]
authorities: usize,
/// The number of nominators backing the aforementioned authorities.
///
/// Will nominate a random subset of `authorities`.
#[structopt(long, short, default_value = "0")]
#[clap(long, short, default_value = "0")]
nominators: usize,
/// The number of endowed accounts.
#[structopt(long, short, default_value = "0")]
#[clap(long, short, default_value = "0")]
endowed: usize,
/// 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,
/// Path to use when saving generated keystores for each authority.
///
/// 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.
/// `auth-0`, `auth-1`, etc.
#[structopt(long, short)]
#[clap(long, short)]
keystore_path: Option<PathBuf>,
},
}
@@ -236,13 +236,15 @@ fn main() -> Result<(), String> {
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 (authority_seeds, nominator_accounts, endowed_accounts, sudo_account) = match builder {
ChainSpecBuilder::Generate { authorities, nominators, endowed, keystore_path, .. } => {
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 nominator_seeds = (0..nominators).map(|_| rand_str()).collect::<Vec<_>>();
+1 -1
View File
@@ -17,5 +17,5 @@ path = "src/main.rs"
name = "subkey"
[dependencies]
clap = { version = "3.0", features = ["derive"] }
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
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Parser;
use sc_cli::{
Error, GenerateCmd, GenerateNodeKeyCmd, InspectKeyCmd, InspectNodeKeyCmd, SignCmd, VanityCmd,
VerifyCmd,
};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
#[derive(Debug, Parser)]
#[clap(
name = "subkey",
author = "Parity Team <admin@parity.io>",
about = "Utility for generating and restoring with Substrate keys"
@@ -54,7 +54,7 @@ pub enum Subkey {
/// Run the subkey command, given the appropriate runtime.
pub fn run() -> Result<(), Error> {
match Subkey::from_args() {
match Subkey::parse() {
Subkey::GenerateNodeKey(cmd) => cmd.run(),
Subkey::Generate(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"]
[dependencies]
log = "0.4.11"
regex = "1.5.4"
tokio = { version = "1.15", features = [ "signal", "rt-multi-thread" ] }
futures = "0.3.9"
chrono = "0.4.10"
clap = { version = "3.0", features = ["derive"] }
fdlimit = "0.2.1"
libp2p = "0.40.0"
parity-scale-codec = "2.3.1"
futures = "0.3.9"
hex = "0.4.2"
libp2p = "0.40.0"
log = "0.4.11"
names = { version = "0.12.0", default-features = false }
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"
sc-keystore = { version = "4.0.0-dev", path = "../keystore" }
sp-panic-handler = { version = "4.0.0", path = "../../primitives/panic-handler" }
thiserror = "1.0.30"
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" }
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" }
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-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" }
chrono = "0.4.10"
serde = "1.0.132"
thiserror = "1.0.30"
rpassword = "5.0.0"
sc-utils = { version = "4.0.0-dev", path = "../utils" }
sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" }
sp-core = { version = "4.1.0-dev", path = "../../primitives/core" }
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]
tempfile = "3.1.0"
[features]
wasmtime = [
"sc-service/wasmtime",
]
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
#![allow(missing_docs)]
use structopt::clap::arg_enum;
use clap::ArgEnum;
/// How to execute Wasm runtime code.
#[derive(Debug, Clone, Copy)]
@@ -86,12 +86,11 @@ impl Into<sc_service::config::WasmExecutionMethod> for WasmExecutionMethod {
}
}
arg_enum! {
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TracingReceiver {
Log,
}
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum TracingReceiver {
Log,
}
impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
@@ -102,44 +101,40 @@ impl Into<sc_tracing::TracingReceiver> for TracingReceiver {
}
}
arg_enum! {
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum NodeKeyType {
Ed25519
}
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum NodeKeyType {
Ed25519,
}
arg_enum! {
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CryptoScheme {
Ed25519,
Sr25519,
Ecdsa,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum CryptoScheme {
Ed25519,
Sr25519,
Ecdsa,
}
arg_enum! {
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum OutputType {
Json,
Text,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum OutputType {
Json,
Text,
}
arg_enum! {
/// How to execute blocks
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionStrategy {
// Execute with native build (if available, WebAssembly otherwise).
Native,
// Only execute with the WebAssembly build.
Wasm,
// Execute with both native (where available) and WebAssembly builds.
Both,
// Execute with the native build if possible; if it fails, then execute with WebAssembly.
NativeElseWasm,
}
/// How to execute blocks
#[derive(Debug, Copy, Clone, PartialEq, Eq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum ExecutionStrategy {
// Execute with native build (if available, WebAssembly otherwise).
Native,
// Only execute with the WebAssembly build.
Wasm,
// Execute with both native (where available) and WebAssembly builds.
Both,
// Execute with the native build if possible; if it fails, then execute with WebAssembly.
NativeElseWasm,
}
impl Into<sc_client_api::ExecutionStrategy> for ExecutionStrategy {
@@ -165,19 +160,18 @@ impl ExecutionStrategy {
}
}
arg_enum! {
/// Available RPC methods.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum RpcMethods {
// Expose every RPC method only when RPC is listening on `localhost`,
// otherwise serve only safe RPC methods.
Auto,
// Allow only a safe subset of RPC methods.
Safe,
// Expose every RPC method (even potentially unsafe ones).
Unsafe,
}
/// Available RPC methods.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum RpcMethods {
// Expose every RPC method only when RPC is listening on `localhost`,
// otherwise serve only safe RPC methods.
Auto,
// Allow only a safe subset of RPC methods.
Safe,
// Expose every RPC method (even potentially unsafe ones).
Unsafe,
}
impl Into<sc_service::config::RpcMethods> for RpcMethods {
@@ -225,31 +219,28 @@ impl Database {
}
}
arg_enum! {
/// Whether off-chain workers are enabled.
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub enum OffchainWorkerEnabled {
Always,
Never,
WhenValidating,
}
/// Whether off-chain workers are enabled.
#[allow(missing_docs)]
#[derive(Debug, Clone, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum OffchainWorkerEnabled {
Always,
Never,
WhenValidating,
}
arg_enum! {
/// Syncing mode.
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy)]
pub enum SyncMode {
// Full sync. Donwnload end verify all blocks.
Full,
// Download blocks without executing them. Download latest state with proofs.
Fast,
// Download blocks without executing them. Download latest state without proofs.
FastUnsafe,
// Prove finality and download the latest state.
Warp,
}
/// Syncing mode.
#[derive(Debug, Clone, Copy, ArgEnum)]
#[clap(rename_all = "PascalCase")]
pub enum SyncMode {
// Full sync. Donwnload end verify all blocks.
Full,
// Download blocks without executing them. Download latest state with proofs.
Fast,
// Download blocks without executing them. Download latest state without proofs.
FastUnsafe,
// Prove finality and download the latest state.
Warp,
}
impl Into<sc_network::config::SyncMode> for SyncMode {
@@ -21,6 +21,7 @@ use crate::{
params::{NodeKeyParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use log::info;
use sc_network::config::build_multiaddr;
use sc_service::{
@@ -28,28 +29,27 @@ use sc_service::{
ChainSpec,
};
use std::io::Write;
use structopt::StructOpt;
/// The `build-spec` command used to build a specification.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct BuildSpecCmd {
/// Force raw genesis storage output.
#[structopt(long = "raw")]
#[clap(long)]
pub raw: bool,
/// 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
/// specification when no bootnode exists.
#[structopt(long = "disable-default-bootnode")]
#[clap(long)]
pub disable_default_bootnode: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub node_key_params: NodeKeyParams,
}
@@ -21,30 +21,30 @@ use crate::{
params::{BlockNumberOrHash, ImportParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use sc_client_api::{BlockBackend, HeaderBackend};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `check-block` command used to validate blocks.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct CheckBlockCmd {
/// Block hash or number
#[structopt(value_name = "HASH or NUMBER")]
#[clap(value_name = "HASH or NUMBER")]
pub input: BlockNumberOrHash,
/// The default number of 64KB pages to ever allocate for Wasm execution.
///
/// 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>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub import_params: ImportParams,
}
@@ -21,46 +21,46 @@ use crate::{
params::{DatabaseParams, GenericNumber, PruningParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use log::info;
use sc_client_api::{BlockBackend, UsageProvider};
use sc_service::{chain_ops::export_blocks, config::DatabaseSource};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `export-blocks` command used to export blocks.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct ExportBlocksCmd {
/// Output file name or stdout if unspecified.
#[structopt(parse(from_os_str))]
#[clap(parse(from_os_str))]
pub output: Option<PathBuf>,
/// Specify starting block number.
///
/// Default is 1.
#[structopt(long = "from", value_name = "BLOCK")]
#[clap(long, value_name = "BLOCK")]
pub from: Option<GenericNumber>,
/// Specify last block number.
///
/// Default is best block.
#[structopt(long = "to", value_name = "BLOCK")]
#[clap(long, value_name = "BLOCK")]
pub to: Option<GenericNumber>,
/// Use binary output rather than JSON.
#[structopt(long)]
#[clap(long)]
pub binary: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub pruning_params: PruningParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub database_params: DatabaseParams,
}
@@ -21,26 +21,26 @@ use crate::{
params::{BlockNumberOrHash, PruningParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use log::info;
use sc_client_api::{StorageProvider, UsageProvider};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
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
/// a chain spec.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct ExportStateCmd {
/// Block hash or number.
#[structopt(value_name = "HASH or NUMBER")]
#[clap(value_name = "HASH or NUMBER")]
pub input: Option<BlockNumberOrHash>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub pruning_params: PruningParams,
}
+10 -11
View File
@@ -21,30 +21,30 @@ use crate::{
NetworkSchemeFlag, OutputTypeFlag,
};
use bip39::{Language, Mnemonic, MnemonicType};
use structopt::StructOpt;
use clap::Parser;
/// The `generate` command
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "generate", about = "Generate a random account")]
#[derive(Debug, Clone, Parser)]
#[clap(name = "generate", about = "Generate a random account")]
pub struct GenerateCmd {
/// 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>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag,
}
@@ -78,12 +78,11 @@ impl GenerateCmd {
#[cfg(test)]
mod tests {
use super::GenerateCmd;
use structopt::StructOpt;
use super::*;
#[test]
fn generate() {
let generate = GenerateCmd::from_iter(&["generate", "--password", "12345"]);
let generate = GenerateCmd::parse_from(&["generate", "--password", "12345"]);
assert!(generate.run().is_ok())
}
}
@@ -18,13 +18,13 @@
//! Implementation of the `generate-node-key` subcommand
use crate::Error;
use clap::Parser;
use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey};
use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `generate-node-key` command
#[derive(Debug, StructOpt)]
#[structopt(
#[derive(Debug, Parser)]
#[clap(
name = "generate-node-key",
about = "Generate a random node libp2p key, save it to \
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.
///
/// If not given, the secret key is printed to stdout.
#[structopt(long)]
#[clap(long)]
file: Option<PathBuf>,
}
@@ -66,7 +66,7 @@ mod tests {
fn generate_node_key() {
let mut file = Builder::new().prefix("keyfile").tempfile().unwrap();
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());
let mut buf = String::new();
assert!(file.read_to_string(&mut buf).is_ok());
@@ -21,6 +21,7 @@ use crate::{
params::{ImportParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use sc_client_api::HeaderBackend;
use sc_service::chain_ops::import_blocks;
use sp_runtime::traits::Block as BlockT;
@@ -31,31 +32,30 @@ use std::{
path::PathBuf,
sync::Arc,
};
use structopt::StructOpt;
/// The `import-blocks` command used to import blocks.
#[derive(Debug, StructOpt)]
#[derive(Debug, Parser)]
pub struct ImportBlocksCmd {
/// Input file or stdin if unspecified.
#[structopt(parse(from_os_str))]
#[clap(parse(from_os_str))]
pub input: Option<PathBuf>,
/// The default number of 64KB pages to ever allocate for Wasm execution.
///
/// 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>,
/// Try importing blocks from binary format rather than JSON.
#[structopt(long)]
#[clap(long)]
pub binary: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub import_params: ImportParams,
}
@@ -20,42 +20,37 @@
use crate::{
utils, with_crypto_scheme, CryptoScheme, Error, KeystoreParams, SharedParams, SubstrateCli,
};
use clap::Parser;
use sc_keystore::LocalKeystore;
use sc_service::config::{BasePath, KeystoreConfig};
use sp_core::crypto::{KeyTypeId, SecretString};
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
use std::{convert::TryFrom, sync::Arc};
use structopt::StructOpt;
/// The `insert` command
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "insert", about = "Insert a key to the keystore of a node.")]
#[derive(Debug, Clone, Parser)]
#[clap(name = "insert", about = "Insert a key to the keystore of a node.")]
pub struct InsertKeyCmd {
/// The secret key URI.
/// If the value is a file, the file content is used as URI.
/// If not given, you will be prompted for the URI.
#[structopt(long)]
#[clap(long)]
suri: Option<String>,
/// Key type, examples: "gran", or "imon"
#[structopt(long)]
#[clap(long)]
key_type: String,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
/// The cryptography scheme that should be used to generate the key out of the given URI.
#[structopt(
long,
value_name = "SCHEME",
possible_values = &CryptoScheme::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true)]
pub scheme: CryptoScheme,
}
@@ -100,7 +95,6 @@ mod tests {
use super::*;
use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension};
use sp_core::{sr25519::Pair, ByteArray, Pair as _};
use structopt::StructOpt;
use tempfile::TempDir;
struct Cli;
@@ -156,7 +150,7 @@ mod tests {
let path_str = format!("{}", path.path().display());
let (key, uri, _) = Pair::generate_with_phrase(None);
let inspect = InsertKeyCmd::from_iter(&[
let inspect = InsertKeyCmd::parse_from(&[
"insert-key",
"-d",
&path_str,
@@ -21,13 +21,13 @@ use crate::{
utils::{self, print_from_public, print_from_uri},
with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, NetworkSchemeFlag, OutputTypeFlag,
};
use clap::Parser;
use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec};
use std::str::FromStr;
use structopt::StructOpt;
/// The `inspect` command
#[derive(Debug, StructOpt)]
#[structopt(
#[derive(Debug, Parser)]
#[clap(
name = "inspect",
about = "Gets a public key and a SS58 address from the provided Secret URI"
)]
@@ -44,23 +44,23 @@ pub struct InspectKeyCmd {
uri: Option<String>,
/// Is the given `uri` a hex encoded public key?
#[structopt(long)]
#[clap(long)]
public: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag,
/// 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
/// of `--uri` directly.
#[structopt(long, conflicts_with = "public")]
#[clap(long, conflicts_with = "public")]
pub expect_public: Option<String>,
}
@@ -158,7 +158,6 @@ mod tests {
use super::*;
use sp_core::crypto::{ByteArray, Pair};
use sp_runtime::traits::IdentifyAccount;
use structopt::StructOpt;
#[test]
fn inspect() {
@@ -166,10 +165,10 @@ mod tests {
"remember fiber forum demise paper uniform squirrel feel access exclude casual effort";
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());
let inspect = InspectKeyCmd::from_iter(&["inspect-key", seed]);
let inspect = InspectKeyCmd::parse_from(&["inspect-key", seed]);
assert!(inspect.run().is_ok());
}
@@ -177,14 +176,14 @@ mod tests {
fn inspect_public_key() {
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());
}
#[test]
fn inspect_with_expected_public_key() {
let check_cmd = |seed, expected_public, success| {
let inspect = InspectKeyCmd::from_iter(&[
let inspect = InspectKeyCmd::parse_from(&[
"inspect-key",
"--expect-public",
expected_public,
@@ -18,23 +18,23 @@
//! Implementation of the `inspect-node-key` subcommand
use crate::{Error, NetworkSchemeFlag};
use clap::Parser;
use libp2p::identity::{ed25519, PublicKey};
use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `inspect-node-key` command
#[derive(Debug, StructOpt)]
#[structopt(
#[derive(Debug, Parser)]
#[clap(
name = "inspect-node-key",
about = "Print the peer ID corresponding to the node key in the given file."
)]
pub struct InspectNodeKeyCmd {
/// Name of file to read the secret key from.
#[structopt(long)]
#[clap(long)]
file: PathBuf,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub network_scheme: NetworkSchemeFlag,
}
@@ -63,11 +63,11 @@ mod tests {
fn inspect_node_key() {
let path = tempfile::tempdir().unwrap().into_path().join("node-id").into_os_string();
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());
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());
}
}
+2 -4
View File
@@ -17,16 +17,14 @@
//! Key related CLI utilities
use crate::{Error, SubstrateCli};
use structopt::StructOpt;
use super::{
generate::GenerateCmd, generate_node_key::GenerateNodeKeyCmd, insert_key::InsertKeyCmd,
inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd,
};
use crate::{Error, SubstrateCli};
/// Key utilities for the cli.
#[derive(Debug, StructOpt)]
#[derive(Debug, clap::Subcommand)]
pub enum KeySubcommand {
/// Generate a random node libp2p key, save it to file or print it to stdout
/// and print its peer ID to stderr.
@@ -21,27 +21,27 @@ use crate::{
params::{DatabaseParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use sc_service::DatabaseSource;
use std::{
fmt::Debug,
fs,
io::{self, Write},
};
use structopt::StructOpt;
/// The `purge-chain` command used to remove the whole chain.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct PurgeChainCmd {
/// Skip interactive prompt by answering yes automatically.
#[structopt(short = "y")]
#[clap(short = 'y')]
pub yes: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub database_params: DatabaseParams,
}
@@ -21,25 +21,25 @@ use crate::{
params::{GenericNumber, PruningParams, SharedParams},
CliConfiguration,
};
use clap::Parser;
use sc_client_api::{Backend, UsageProvider};
use sc_service::chain_ops::revert_chain;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `revert` command used revert the chain to a previous state.
#[derive(Debug, StructOpt)]
#[derive(Debug, Parser)]
pub struct RevertCmd {
/// Number of blocks to revert.
#[structopt(default_value = "256")]
#[clap(default_value = "256")]
pub num: GenericNumber,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub pruning_params: PruningParams,
}
+50 -47
View File
@@ -25,6 +25,7 @@ use crate::{
},
CliConfiguration,
};
use clap::Parser;
use regex::Regex;
use sc_service::{
config::{BasePath, PrometheusConfig, TransactionPoolOptions},
@@ -32,26 +33,25 @@ use sc_service::{
};
use sc_telemetry::TelemetryEndpoints;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use structopt::StructOpt;
/// The `run` command used to run a node.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Parser)]
pub struct RunCmd {
/// Enable validator mode.
///
/// The node will be started with the authority role and actively
/// participate in any consensus task that it can (e.g. depending on
/// availability of local keys).
#[structopt(long)]
#[clap(long)]
pub validator: bool,
/// Disable GRANDPA voter when running in validator mode, otherwise disable the GRANDPA
/// observer.
#[structopt(long)]
#[clap(long)]
pub no_grandpa: bool,
/// Experimental: Run in light client mode.
#[structopt(long = "light")]
#[clap(long)]
pub light: bool,
/// Listen to all RPC interfaces.
@@ -60,13 +60,13 @@ pub struct RunCmd {
/// proxy server to filter out dangerous methods. More details:
/// <https://docs.substrate.io/v3/runtime/custom-rpcs/#public-rpcs>.
/// Use `--unsafe-rpc-external` to suppress the warning if you understand the risks.
#[structopt(long = "rpc-external")]
#[clap(long)]
pub rpc_external: bool,
/// Listen to all RPC interfaces.
///
/// Same as `--rpc-external`.
#[structopt(long)]
#[clap(long)]
pub unsafe_rpc_external: bool,
/// RPC methods to expose.
@@ -75,11 +75,11 @@ pub struct RunCmd {
/// - `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
/// passed, otherwise acts as `Unsafe`.
#[structopt(
#[clap(
long,
value_name = "METHOD SET",
possible_values = &RpcMethods::variants(),
case_insensitive = true,
arg_enum,
ignore_case = true,
default_value = "Auto",
verbatim_doc_comment
)]
@@ -91,44 +91,44 @@ pub struct RunCmd {
/// proxy server to filter out dangerous methods. More details:
/// <https://docs.substrate.io/v3/runtime/custom-rpcs/#public-rpcs>.
/// Use `--unsafe-ws-external` to suppress the warning if you understand the risks.
#[structopt(long = "ws-external")]
#[clap(long)]
pub ws_external: bool,
/// Listen to all Websocket interfaces.
///
/// Same as `--ws-external` but doesn't warn you about it.
#[structopt(long = "unsafe-ws-external")]
#[clap(long)]
pub unsafe_ws_external: bool,
/// Set the the maximum RPC payload size for both requests and responses (both http and ws), in
/// megabytes. Default is 15MiB.
#[structopt(long = "rpc-max-payload")]
#[clap(long)]
pub rpc_max_payload: Option<usize>,
/// Expose Prometheus exporter on all interfaces.
///
/// Default is local.
#[structopt(long = "prometheus-external")]
#[clap(long)]
pub prometheus_external: bool,
/// Specify IPC RPC server path
#[structopt(long = "ipc-path", value_name = "PATH")]
#[clap(long, value_name = "PATH")]
pub ipc_path: Option<String>,
/// Specify HTTP RPC server TCP port.
#[structopt(long = "rpc-port", value_name = "PORT")]
#[clap(long, value_name = "PORT")]
pub rpc_port: Option<u16>,
/// Specify WebSockets RPC server TCP port.
#[structopt(long = "ws-port", value_name = "PORT")]
#[clap(long, value_name = "PORT")]
pub ws_port: Option<u16>,
/// 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>,
/// 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>,
/// 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
/// allow localhost and <https://polkadot.js.org> origins. When running in
/// --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>,
/// Specify Prometheus exporter TCP Port.
#[structopt(long = "prometheus-port", value_name = "PORT")]
#[clap(long, value_name = "PORT")]
pub prometheus_port: Option<u16>,
/// Do not expose a Prometheus exporter endpoint.
///
/// Prometheus metric endpoint is enabled by default.
#[structopt(long = "no-prometheus")]
#[clap(long)]
pub no_prometheus: bool,
/// The human-readable name for this node.
///
/// 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>,
/// Disable connecting to the Substrate telemetry server.
///
/// Telemetry is on by default on global chains.
#[structopt(long = "no-telemetry")]
#[clap(long)]
pub no_telemetry: bool,
/// 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
/// the least verbosity.
/// 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)>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub offchain_worker_params: OffchainWorkerParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: SharedParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub import_params: ImportParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub network_params: NetworkParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub pool_config: TransactionPoolParams,
/// 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,
/// 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,
/// Shortcut for `--name Charlie --validator` with session keys for `Charlie` added to
/// 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,
/// 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,
/// 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,
/// 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,
/// 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,
/// 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,
/// Enable authoring even when offline.
#[structopt(long = "force-authoring")]
#[clap(long)]
pub force_authoring: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
/// The size of the instances cache for each runtime.
///
/// The default value is 8 and the values higher than 256 are ignored.
#[structopt(long)]
#[clap(long)]
pub max_runtime_instances: Option<usize>,
/// Maximum number of different runtimes that can be cached.
#[structopt(long, default_value = "2")]
#[clap(long, default_value = "2")]
pub runtime_cache_size: u8,
/// Run a temporary node.
@@ -251,7 +251,7 @@ pub struct RunCmd {
/// which includes: database, node key and keystore.
///
/// 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,
}
@@ -562,8 +562,7 @@ fn parse_telemetry_endpoints(s: &str) -> std::result::Result<(String, u8), Telem
/// CORS setting
///
/// The type is introduced to overcome `Option<Option<T>>`
/// handling of `structopt`.
/// The type is introduced to overcome `Option<Option<T>>` handling of `clap`.
#[derive(Clone, Debug)]
pub enum Cors {
/// All hosts allowed.
@@ -582,7 +581,7 @@ impl From<Cors> for Option<Vec<String>> {
}
/// 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 origins = Vec::new();
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)]
+10 -11
View File
@@ -18,34 +18,34 @@
//! Implementation of the `sign` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams};
use clap::Parser;
use sp_core::crypto::SecretString;
use structopt::StructOpt;
/// The `sign` command
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "sign", about = "Sign a message, with a given (secret) key")]
#[derive(Debug, Clone, Parser)]
#[clap(name = "sign", about = "Sign a message, with a given (secret) key")]
pub struct SignCmd {
/// The secret key URI.
/// If the value is a file, the file content is used as URI.
/// If not given, you will be prompted for the URI.
#[structopt(long)]
#[clap(long)]
suri: Option<String>,
/// Message to sign, if not provided you will be prompted to
/// pass the message via STDIN
#[structopt(long)]
#[clap(long)]
message: Option<String>,
/// The message on STDIN is hex-encoded data
#[structopt(long)]
#[clap(long)]
hex: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag,
}
@@ -75,14 +75,13 @@ fn sign<P: sp_core::Pair>(
#[cfg(test)]
mod test {
use super::SignCmd;
use structopt::StructOpt;
use super::*;
#[test]
fn sign() {
let seed = "0xad1fb77243b536b90cfe5f0d351ab1b1ac40e3890b41dc64f766ee56340cfca5";
let sign = SignCmd::from_iter(&[
let sign = SignCmd::parse_from(&[
"sign",
"--suri",
seed,
+8 -9
View File
@@ -21,30 +21,30 @@
use crate::{
error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag,
};
use clap::Parser;
use rand::{rngs::OsRng, RngCore};
use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec};
use sp_runtime::traits::IdentifyAccount;
use structopt::StructOpt;
use utils::print_from_uri;
/// The `vanity` command
#[derive(Debug, StructOpt, Clone)]
#[structopt(name = "vanity", about = "Generate a seed that provides a vanity address")]
#[derive(Debug, Clone, Parser)]
#[clap(name = "vanity", about = "Generate a seed that provides a vanity address")]
pub struct VanityCmd {
/// Desired pattern
#[structopt(long, parse(try_from_str = assert_non_empty_string))]
#[clap(long, parse(try_from_str = assert_non_empty_string))]
pattern: String,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
network_scheme: NetworkSchemeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
output_scheme: OutputTypeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
crypto_scheme: CryptoSchemeFlag,
}
@@ -166,13 +166,12 @@ mod tests {
crypto::{default_ss58_version, Ss58AddressFormatRegistry, Ss58Codec},
sr25519, Pair,
};
use structopt::StructOpt;
#[cfg(feature = "bench")]
use test::Bencher;
#[test]
fn vanity() {
let vanity = VanityCmd::from_iter(&["vanity", "--pattern", "j"]);
let vanity = VanityCmd::parse_from(&["vanity", "--pattern", "j"]);
assert!(vanity.run().is_ok());
}
+6 -6
View File
@@ -19,12 +19,12 @@
//! implementation of the `verify` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag};
use clap::Parser;
use sp_core::crypto::{ByteArray, Ss58Codec};
use structopt::StructOpt;
/// The `verify` command
#[derive(Debug, StructOpt, Clone)]
#[structopt(
#[derive(Debug, Clone, Parser)]
#[clap(
name = "verify",
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
/// pass the message via STDIN
#[structopt(long)]
#[clap(long)]
message: Option<String>,
/// The message on STDIN is hex-encoded data
#[structopt(long)]
#[clap(long)]
hex: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag,
}
+1 -1
View File
@@ -31,7 +31,7 @@ pub enum Error {
Io(#[from] std::io::Error),
#[error(transparent)]
Cli(#[from] structopt::clap::Error),
Cli(#[from] clap::Error),
#[error(transparent)]
Service(#[from] sc_service::Error),
+17 -40
View File
@@ -30,6 +30,8 @@ mod params;
mod runner;
pub use arg_enums::*;
pub use clap;
use clap::{AppSettings, FromArgMatches, IntoApp, Parser};
pub use commands::*;
pub use config::*;
pub use error::*;
@@ -39,12 +41,6 @@ use sc_service::Configuration;
pub use sc_service::{ChainSpec, Role};
pub use sc_tracing::logging::LoggerBuilder;
pub use sp_version::RuntimeVersion;
use std::io::Write;
pub use structopt;
use structopt::{
clap::{self, AppSettings},
StructOpt,
};
/// Substrate client CLI
///
@@ -103,7 +99,7 @@ pub trait SubstrateCli: Sized {
/// error message and quit the program in case of failure.
fn from_args() -> Self
where
Self: StructOpt + Sized,
Self: Parser + Sized,
{
<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.
fn from_iter<I>(iter: I) -> Self
where
Self: StructOpt + Sized,
Self: Parser + Sized,
I: IntoIterator,
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();
full_version.push_str("\n");
@@ -137,34 +133,15 @@ pub trait SubstrateCli: Sized {
.author(author.as_str())
.about(about.as_str())
.version(full_version.as_str())
.settings(&[
AppSettings::GlobalVersion,
AppSettings::ArgsNegateSubcommands,
AppSettings::SubcommandsNegateReqs,
AppSettings::ColoredHelp,
]);
.setting(
AppSettings::PropagateVersion |
AppSettings::ArgsNegateSubcommands |
AppSettings::SubcommandsNegateReqs,
);
let matches = match app.get_matches_from_safe(iter) {
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());
let matches = app.try_get_matches_from(iter).unwrap_or_else(|e| e.exit());
if e.use_stderr() {
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)
<Self as FromArgMatches>::from_arg_matches(&matches).unwrap_or_else(|e| e.exit())
}
/// 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
/// 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`].
fn try_from_iter<I>(iter: I) -> clap::Result<Self>
where
Self: StructOpt + Sized,
Self: Parser + Sized,
I: IntoIterator,
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();
full_version.push_str("\n");
@@ -202,9 +179,9 @@ pub trait SubstrateCli: Sized {
.about(about.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}`
@@ -17,24 +17,24 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::arg_enums::Database;
use clap::Args;
use sc_service::TransactionStorageMode;
use structopt::StructOpt;
/// Parameters for block import.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct DatabaseParams {
/// Select database backend to use.
#[structopt(
#[clap(
long,
alias = "db",
value_name = "DB",
case_insensitive = true,
possible_values = &Database::variants(),
ignore_case = true,
possible_values = Database::variants(),
)]
pub database: Option<Database>,
/// 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>,
/// Enable storage chain mode
@@ -43,7 +43,7 @@ pub struct DatabaseParams {
/// If this is enabled, each transaction is stored separately in the
/// transaction database column and is only referenced by hash
/// in the block body column.
#[structopt(long)]
#[clap(long)]
pub storage_chain: bool,
}
@@ -24,9 +24,9 @@ use crate::{
},
params::{DatabaseParams, PruningParams},
};
use clap::Args;
use sc_client_api::execution_extensions::ExecutionStrategies;
use std::path::PathBuf;
use structopt::StructOpt;
#[cfg(feature = "wasmtime")]
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";
/// Parameters for block import.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct ImportParams {
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub pruning_params: PruningParams,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub database_params: DatabaseParams,
/// 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
/// 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.
#[structopt(long = "unsafe-pruning")]
#[clap(long)]
pub unsafe_pruning: bool,
/// Method for executing Wasm runtime code.
#[structopt(
#[clap(
long = "wasm-execution",
value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(),
case_insensitive = true,
possible_values = WasmExecutionMethod::variants(),
ignore_case = true,
default_value = WASM_METHOD_DEFAULT
)]
pub wasm_method: WasmExecutionMethod,
@@ -66,15 +66,15 @@ pub struct ImportParams {
/// Specify the path where local WASM runtimes are stored.
///
/// 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>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub execution_strategies: ExecutionStrategiesParams,
/// 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,
}
@@ -127,62 +127,37 @@ impl ImportParams {
}
/// Execution strategies parameters.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct ExecutionStrategiesParams {
/// The means of execution used when calling into the runtime for importing blocks as
/// part of an initial sync.
#[structopt(
long = "execution-syncing",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution_syncing: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime for general block import
/// (including locally authored blocks).
#[structopt(
long = "execution-import-block",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution_import_block: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while constructing blocks.
#[structopt(
long = "execution-block-construction",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution_block_construction: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while using an off-chain worker.
#[structopt(
long = "execution-offchain-worker",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution_offchain_worker: Option<ExecutionStrategy>,
/// The means of execution used when calling into the runtime while not syncing, importing or
/// constructing blocks.
#[structopt(
long = "execution-other",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution_other: Option<ExecutionStrategy>,
/// The execution strategy that should be used by all execution contexts.
#[structopt(
long = "execution",
#[clap(
long,
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
arg_enum,
ignore_case = true,
conflicts_with_all = &[
"execution-other",
"execution-offchain-worker",
@@ -17,50 +17,47 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{error, error::Result};
use clap::Args;
use sc_service::config::KeystoreConfig;
use sp_core::crypto::SecretString;
use std::{
fs,
path::{Path, PathBuf},
};
use structopt::StructOpt;
/// default sub directory for the key store
const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore";
/// Parameters of the keystore
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct KeystoreParams {
/// Specify custom URIs to connect to for keystore-services
#[structopt(long = "keystore-uri")]
#[clap(long)]
pub keystore_uri: Option<String>,
/// 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>,
/// Use interactive shell for entering the password used by the keystore.
#[structopt(
long = "password-interactive",
conflicts_with_all = &[ "password", "password-filename" ]
)]
#[clap(long, conflicts_with_all = &["password", "password-filename"])]
pub password_interactive: bool,
/// Password used by the keystore. This allows appending an extra user-defined secret to the
/// seed.
#[structopt(
long = "password",
#[clap(
long,
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>,
/// File that contains the password used by the keystore.
#[structopt(
long = "password-filename",
#[clap(
long,
value_name = "PATH",
parse(from_os_str),
conflicts_with_all = &[ "password-interactive", "password" ]
conflicts_with_all = &["password-interactive", "password"]
)]
pub password_filename: Option<PathBuf>,
}
+9 -21
View File
@@ -26,13 +26,13 @@ mod shared_params;
mod transaction_pool_params;
use crate::arg_enums::{CryptoScheme, OutputType};
use clap::Args;
use sp_core::crypto::Ss58AddressFormat;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, NumberFor},
};
use std::{convert::TryFrom, fmt::Debug, str::FromStr};
use structopt::StructOpt;
pub use crate::params::{
database_params::*, import_params::*, keystore_params::*, network_params::*,
@@ -115,44 +115,32 @@ impl BlockNumberOrHash {
}
/// Optional flag for specifying crypto algorithm
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct CryptoSchemeFlag {
/// cryptography scheme
#[structopt(
long,
value_name = "SCHEME",
possible_values = &CryptoScheme::variants(),
case_insensitive = true,
default_value = "Sr25519"
)]
#[clap(long, value_name = "SCHEME", arg_enum, ignore_case = true, default_value = "Sr25519")]
pub scheme: CryptoScheme,
}
/// Optional flag for specifying output type
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct OutputTypeFlag {
/// output format
#[structopt(
long,
value_name = "FORMAT",
possible_values = &OutputType::variants(),
case_insensitive = true,
default_value = "Text"
)]
#[clap(long, value_name = "FORMAT", arg_enum, ignore_case = true, default_value = "Text")]
pub output_type: OutputType,
}
/// Optional flag for specifying network scheme
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct NetworkSchemeFlag {
/// network address format
#[structopt(
#[clap(
short = 'n',
long,
value_name = "NETWORK",
short = "n",
possible_values = &Ss58AddressFormat::all_names()[..],
ignore_case = true,
parse(try_from_str = Ss58AddressFormat::try_from),
case_insensitive = true,
)]
pub network: Option<Ss58AddressFormat>,
}
@@ -17,6 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{arg_enums::SyncMode, params::node_key_params::NodeKeyParams};
use clap::Args;
use sc_network::{
config::{
NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig,
@@ -28,17 +29,16 @@ use sc_service::{
ChainSpec, ChainType,
};
use std::{borrow::Cow, path::PathBuf};
use structopt::StructOpt;
/// Parameters used to create the network configuration.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct NetworkParams {
/// Specify a list of bootnodes.
#[structopt(long = "bootnodes", value_name = "ADDR")]
#[clap(long, value_name = "ADDR")]
pub bootnodes: Vec<MultiaddrWithPeerId>,
/// Specify a list of reserved node addresses.
#[structopt(long = "reserved-nodes", value_name = "ADDR")]
#[clap(long, value_name = "ADDR")]
pub reserved_nodes: Vec<MultiaddrWithPeerId>,
/// 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
/// validator nodes and collator nodes regardless of whether they are defined as
/// reserved nodes.
#[structopt(long = "reserved-only")]
#[clap(long)]
pub reserved_only: bool,
/// 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.
#[structopt(long, value_name = "PUBLIC_ADDR")]
#[clap(long, value_name = "PUBLIC_ADDR")]
pub public_addr: Vec<Multiaddr>,
/// Listen on this multiaddress.
@@ -62,60 +62,60 @@ pub struct NetworkParams {
/// By default:
/// 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`.
#[structopt(long = "listen-addr", value_name = "LISTEN_ADDR")]
#[clap(long, value_name = "LISTEN_ADDR")]
pub listen_addr: Vec<Multiaddr>,
/// 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>,
/// Always forbid connecting to private IPv4 addresses (as specified in
/// [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
/// 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,
/// Always accept connecting to private IPv4 addresses (as specified in
/// [RFC1918](https://tools.ietf.org/html/rfc1918)). Enabled by default for chains marked as
/// "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,
/// 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,
/// 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,
/// 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,
/// Disable mDNS discovery.
///
/// By default, the network will use mDNS to discover other nodes on the
/// local network. This disables it. Automatically implied when using --dev.
#[structopt(long = "no-mdns")]
#[clap(long)]
pub no_mdns: bool,
/// 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
/// 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,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub node_key_params: NodeKeyParams,
/// Enable peer discovery on local networks.
///
/// By default this option is `true` for `--dev` or when the chain type is
/// `Local`/`Development` and false otherwise.
#[structopt(long)]
#[clap(long)]
pub discover_local: bool,
/// 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
/// security improvements.
#[structopt(long)]
#[clap(long)]
pub kademlia_disjoint_query_paths: bool,
/// Join the IPFS network and serve transactions over bitswap protocol.
#[structopt(long)]
#[clap(long)]
pub ipfs_server: bool,
/// Blockchain syncing mode.
@@ -137,7 +137,7 @@ pub struct NetworkParams {
/// - `Fast`: Download blocks and the latest state only.
///
/// - `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,
}
@@ -16,10 +16,10 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Args;
use sc_network::config::{identity::ed25519, NodeKeyConfig};
use sp_core::H256;
use std::{path::PathBuf, str::FromStr};
use structopt::StructOpt;
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
/// used for libp2p networking.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct NodeKeyParams {
/// 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.
/// Use of this option should be limited to development and testing. To use
/// 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>,
/// 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
/// node's peer ID in the context of libp2p.
#[structopt(
long = "node-key-type",
value_name = "TYPE",
possible_values = &NodeKeyType::variants(),
case_insensitive = true,
default_value = "Ed25519"
)]
#[clap(long, value_name = "TYPE", arg_enum, ignore_case = true, default_value = "Ed25519")]
pub node_key_type: NodeKeyType,
/// 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
/// the chosen type.
#[structopt(long = "node-key-file", value_name = "FILE")]
#[clap(long, value_name = "FILE")]
pub node_key_file: Option<PathBuf>,
}
@@ -128,14 +122,15 @@ fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519S
#[cfg(test)]
mod tests {
use super::*;
use clap::ArgEnum;
use sc_network::config::identity::{ed25519, Keypair};
use std::fs;
#[test]
fn test_node_key_config_input() {
fn secret_input(net_config_dir: &PathBuf) -> error::Result<()> {
NodeKeyType::variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap();
NodeKeyType::value_variants().iter().try_for_each(|t| {
let node_key_type = *t;
let sk = match node_key_type {
NodeKeyType::Ed25519 => ed25519::SecretKey::generate().as_ref().to_vec(),
};
@@ -194,8 +189,8 @@ mod tests {
where
F: Fn(NodeKeyParams) -> error::Result<()>,
{
NodeKeyType::variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap();
NodeKeyType::value_variants().iter().try_for_each(|t| {
let node_key_type = *t;
f(NodeKeyParams { node_key_type, node_key: None, node_key_file: None })
})
}
@@ -23,23 +23,23 @@
//! targeted at handling input parameter parsing providing
//! a reasonable abstraction.
use clap::Args;
use sc_network::config::Role;
use sc_service::config::OffchainWorkerConfig;
use structopt::StructOpt;
use crate::{error, OffchainWorkerEnabled};
/// Offchain worker related parameters.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct OffchainWorkerParams {
/// Should execute offchain workers on every block.
///
/// By default it's only enabled for nodes that are authoring new blocks.
#[structopt(
#[clap(
long = "offchain-worker",
value_name = "ENABLED",
possible_values = &OffchainWorkerEnabled::variants(),
case_insensitive = true,
arg_enum,
ignore_case = true,
default_value = "WhenValidating"
)]
pub enabled: OffchainWorkerEnabled,
@@ -48,7 +48,7 @@ pub struct OffchainWorkerParams {
///
/// Enables a runtime to write directly to a offchain workers
/// 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,
}
@@ -17,23 +17,23 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::error;
use clap::Args;
use sc_service::{KeepBlocks, PruningMode, Role};
use structopt::StructOpt;
/// Parameters to define the pruning mode
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct PruningParams {
/// 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
/// validator (i.e. 'archive'), otherwise state is only kept for the last
/// 256 blocks.
#[structopt(long = "pruning", value_name = "PRUNING_MODE")]
#[clap(long, value_name = "PRUNING_MODE")]
pub pruning: Option<String>,
/// Specify the number of finalized blocks to keep in the database.
///
/// Default is to keep all blocks.
#[structopt(long, value_name = "COUNT")]
#[clap(long, value_name = "COUNT")]
pub keep_blocks: Option<u32>,
}
@@ -17,36 +17,36 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::arg_enums::TracingReceiver;
use clap::Args;
use sc_service::config::BasePath;
use std::path::PathBuf;
use structopt::StructOpt;
/// Shared parameters used by all `CoreParams`.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct SharedParams {
/// 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
/// 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>,
/// Specify the development chain.
///
/// This flag sets `--chain=dev`, `--force-authoring`, `--rpc-cors=all`,
/// `--alice`, and `--tmp` flags, unless explicitly overridden.
#[structopt(long, conflicts_with_all = &["chain"])]
#[clap(long, conflicts_with_all = &["chain"])]
pub dev: bool,
/// 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>,
/// 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.
/// 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>,
/// Enable detailed log output.
@@ -54,11 +54,11 @@ pub struct SharedParams {
/// 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`.
#[structopt(long)]
#[clap(long)]
pub detailed_log_output: bool,
/// Disable log color output.
#[structopt(long)]
#[clap(long)]
pub disable_log_color: bool,
/// 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
/// option not being set.
#[structopt(long)]
#[clap(long)]
pub enable_log_reloading: bool,
/// 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>,
/// Receiver to process tracing messages.
#[structopt(
long = "tracing-receiver",
value_name = "RECEIVER",
possible_values = &TracingReceiver::variants(),
case_insensitive = true,
default_value = "Log"
)]
#[clap(long, value_name = "RECEIVER", arg_enum, ignore_case = true, default_value = "Log")]
pub tracing_receiver: TracingReceiver,
}
@@ -16,18 +16,18 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Args;
use sc_service::config::TransactionPoolOptions;
use structopt::StructOpt;
/// Parameters used to create the pool configuration.
#[derive(Debug, StructOpt, Clone)]
#[derive(Debug, Clone, Args)]
pub struct TransactionPoolParams {
/// 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,
/// 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,
}
@@ -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" }
# others
tokio = { version = "1", features = ["macros"] }
log = "0.4.14"
structopt = "0.3.25"
clap = "2.34.0"
tokio = { version = "1", features = ["macros"] }
+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 }
serde = { version = "1.0.132", optional = true, features = ["derive"] }
byteorder = { version = "1.3.2", default-features = false }
primitive-types = { version = "0.10.1", default-features = false, features = [
"codec",
"scale-info"
] }
primitive-types = { version = "0.10.1", default-features = false, features = ["codec", "scale-info"] }
impl-serde = { version = "0.3.0", optional = true }
wasmi = { version = "0.9.1", optional = true }
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-storage = { version = "4.0.0", default-features = false, path = "../storage" }
sp-externalities = { version = "0.10.0", optional = true, path = "../externalities" }
parity-util-mem = { version = "0.10.2", default-features = false, features = [
"primitive-types",
] }
parity-util-mem = { version = "0.10.2", default-features = false, features = ["primitive-types"] }
futures = { version = "0.3.1", optional = true }
dyn-clonable = { version = "0.9.0", optional = true }
thiserror = { version = "1.0.30", optional = true }
bitflags = "1.3"
# full crypto
ed25519-dalek = { version = "1.0.1", default-features = false, features = [
"u64_backend",
"alloc",
], optional = true }
ed25519-dalek = { version = "1.0.1", default-features = false, features = ["u64_backend", "alloc"], optional = true }
blake2-rfc = { version = "0.2.18", default-features = false, optional = true }
tiny-keccak = { version = "2.0.1", features = ["keccak"], optional = true }
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 }
libsecp256k1 = { version = "0.7", default-features = false, features = ["hmac", "static-context"], 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-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"]
[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"] }
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-runtime = { version = "4.1.0-dev", path = "../../runtime" }
structopt = "0.3.25"
[[bin]]
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
// 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
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();
// 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);
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| {
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);
});
let mut voters = Vec::with_capacity(voter_count as usize);
(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
let mut all_targets = candidates.clone();
// we remove and pop into `targets` `edge_per_this_voter` times.
let targets = (0..edge_per_this_voter)
.map(|_| {
let upper = all_targets.len() - 1;
let idx = rng.gen_range(0, upper);
let idx = rng.gen_range(0..upper);
all_targets.remove(idx)
})
.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;
stake_of.insert(acc, stake);
voters.push((acc, stake, targets));
@@ -42,7 +42,7 @@
use honggfuzz::fuzz;
#[cfg(not(fuzzing))]
use structopt::StructOpt;
use clap::Parser;
mod common;
use common::{generate_random_npos_inputs, to_range};
@@ -67,24 +67,25 @@ fn main() {
}
#[cfg(not(fuzzing))]
#[derive(Debug, StructOpt)]
#[derive(Debug, Parser)]
#[clap(author, version, about)]
struct Opt {
/// How many candidates participate in this election
#[structopt(short, long)]
#[clap(short, long)]
candidates: Option<usize>,
/// How many voters participate in this election
#[structopt(short, long)]
#[clap(short, long)]
voters: Option<usize>,
/// Random seed to use in this election
#[structopt(long)]
#[clap(long)]
seed: Option<u64>,
}
#[cfg(not(fuzzing))]
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
// the constant.
iteration(
@@ -79,8 +79,7 @@ fn generate_random_phragmen_assignment(
let mut targets_to_chose_from = all_targets.clone();
let targets_to_chose = if edge_per_voter_var > 0 {
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 {
avg_edge_per_voter
@@ -89,11 +88,11 @@ fn generate_random_phragmen_assignment(
let distribution = (0..targets_to_chose)
.map(|_| {
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) {
winners.push(target.clone());
}
(target, rng.gen_range(1 * KSM, 100 * KSM))
(target, rng.gen_range(1 * KSM..100 * KSM))
})
.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-state-machine = { version = "0.10.0", path = "../../../primitives/state-machine" }
codec = { version = "2.0.0", package = "parity-scale-codec" }
structopt = "0.3.25"
clap = { version = "3.0", features = ["derive"] }
chrono = "0.4"
serde = "1.0.132"
handlebars = "4.1.6"
@@ -28,124 +28,119 @@ fn parse_pallet_name(pallet: &str) -> String {
}
/// The `benchmark` command used to benchmark FRAME Pallets.
#[derive(Debug, structopt::StructOpt)]
#[derive(Debug, clap::Parser)]
pub struct BenchmarkCmd {
/// 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>,
/// 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>,
/// 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,
/// 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>,
/// 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>,
/// 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,
/// 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.
#[structopt(long, default_value = "1")]
#[clap(long, default_value = "1")]
pub external_repeat: u32,
/// Print the raw results.
#[structopt(long = "raw")]
#[clap(long = "raw")]
pub raw_data: bool,
/// Don't print the median-slopes linear regression analysis.
#[structopt(long)]
#[clap(long)]
pub no_median_slopes: bool,
/// Don't print the min-squares linear regression analysis.
#[structopt(long)]
#[clap(long)]
pub no_min_squares: bool,
/// Output the benchmarks to a Rust file at the given path.
#[structopt(long)]
#[clap(long)]
pub output: Option<std::path::PathBuf>,
/// Add a header file to your outputted benchmarks
#[structopt(long)]
#[clap(long)]
pub header: Option<std::path::PathBuf>,
/// Path to Handlebars template file used for outputting benchmark results. (Optional)
#[structopt(long)]
#[clap(long)]
pub template: Option<std::path::PathBuf>,
/// Which analysis function to use when outputting benchmarks:
/// * min-squares (default)
/// * median-slopes
/// * max (max of min squares and median slopes for each value)
#[structopt(long)]
#[clap(long)]
pub output_analysis: Option<String>,
/// Set the heap pages while running benchmarks. If not set, the default value from the client
/// is used.
#[structopt(long)]
#[clap(long)]
pub heap_pages: Option<u64>,
/// Disable verification logic when running benchmarks.
#[structopt(long)]
#[clap(long)]
pub no_verify: bool,
/// Display and run extra benchmarks that would otherwise not be needed for weight
/// construction.
#[structopt(long)]
#[clap(long)]
pub extra: bool,
/// Estimate PoV size.
#[structopt(long)]
#[clap(long)]
pub record_proof: bool,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: sc_cli::SharedParams,
/// The execution strategy that should be used for benchmarks
#[structopt(
long = "execution",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true)]
pub execution: Option<ExecutionStrategy>,
/// Method for executing Wasm runtime code.
#[structopt(
#[clap(
long = "wasm-execution",
value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(),
case_insensitive = true,
possible_values = WasmExecutionMethod::variants(),
ignore_case = true,
default_value = "compiled"
)]
pub wasm_method: WasmExecutionMethod,
/// 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,
/// List the benchmarks that match your query rather than running them.
///
/// When nothing is provided, we list all benchmarks.
#[structopt(long)]
#[clap(long)]
pub list: bool,
/// 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
/// template for that purpose.
#[structopt(long)]
#[clap(long)]
pub no_storage_info: bool,
}
@@ -11,10 +11,11 @@ documentation = "https://docs.rs/substrate-frame-cli"
readme = "README.md"
[dependencies]
clap = { version = "3.0", features = ["derive"] }
sp-core = { version = "4.1.0-dev", path = "../../../primitives/core" }
sc-cli = { version = "0.10.0-dev", path = "../../../client/cli" }
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-support = { version = "4.0.0-dev", path = "../../../frame/support" }
@@ -17,6 +17,7 @@
//! Implementation of the `palletid` subcommand
use clap::Parser;
use frame_support::PalletId;
use sc_cli::{
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_runtime::traits::AccountIdConversion;
use structopt::StructOpt;
/// The `palletid` command
#[derive(Debug, StructOpt)]
#[structopt(name = "palletid", about = "Inspect a module ID address")]
#[derive(Debug, Parser)]
#[clap(name = "palletid", about = "Inspect a module ID address")]
pub struct PalletIdCmd {
/// The module ID used to derive the account
id: String,
/// network address format
#[structopt(
#[clap(
long,
value_name = "NETWORK",
possible_values = &Ss58AddressFormat::all_names()[..],
parse(try_from_str = Ss58AddressFormat::try_from),
case_insensitive = true,
ignore_case = true,
)]
pub network: Option<Ss58AddressFormat>,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub output_scheme: OutputTypeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub crypto_scheme: CryptoSchemeFlag,
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub keystore_params: KeystoreParams,
}
@@ -23,4 +23,3 @@ sp-io = { version = "4.0.0", path = "../../../primitives/io" }
chrono = { version = "0.4.19" }
git2 = { version = "0.13.25", default-features = false }
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 = "../" }
# 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.
use clap::Parser;
use generate_bags::generate_thresholds;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[derive(Debug, Parser)]
// #[clap(author, version, about)]
struct Opt {
/// How many bags to generate.
#[structopt(long, default_value = "200")]
#[clap(long, default_value = "200")]
n_bags: usize,
/// Where to write the output.
output: PathBuf,
/// The total issuance of the currency used to create `VoteWeight`.
#[structopt(short, long)]
#[clap(short, long)]
total_issuance: u128,
/// The minimum account balance (i.e. existential deposit) for the currency used to create
/// `VoteWeight`.
#[structopt(short, long)]
#[clap(short, long)]
minimum_balance: u128,
}
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)
}
@@ -13,10 +13,11 @@ readme = "README.md"
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
clap = { version = "3.0", features = ["derive"] }
log = "0.4.8"
parity-scale-codec = { version = "2.3.1" }
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-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" }
remote-externalities = { version = "0.10.0-dev", path = "../../remote-externalities" }
jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"]}
zstd = "0.9.0"
jsonrpsee = { version = "0.4.1", default-features = false, features = ["ws-client"] }
@@ -26,25 +26,25 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use std::{fmt::Debug, str::FromStr};
/// Configurations of the [`Command::ExecuteBlock`].
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct ExecuteBlockCmd {
/// Overwrite the wasm code in state or not.
#[structopt(long)]
#[clap(long)]
overwrite_wasm_code: bool,
/// If set, then the state root check is disabled by the virtue of calling into
/// `TryRuntime_execute_block_no_check` instead of
/// `Core_execute_block`.
#[structopt(long)]
#[clap(long)]
no_check: bool,
/// 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
/// the `state::at` is. Only use this (with care) when combined with a snapshot.
#[structopt(
#[clap(
long,
multiple = false,
multiple_values = false,
parse(try_from_str = crate::parse::hash)
)]
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
/// the `state::uri` is. Only use this (with care) when combined with a snapshot.
#[structopt(
#[clap(
long,
multiple = false,
multiple_values = false,
parse(try_from_str = crate::parse::url)
)]
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.
///
/// If `block_at` is provided, then the [`State::Live::at`] is being ignored.
#[structopt(subcommand)]
#[clap(subcommand)]
state: State,
}
@@ -35,14 +35,10 @@ const SUB: &'static str = "chain_subscribeFinalizedHeads";
const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads";
/// Configurations of the [`Command::FollowChain`].
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct FollowChainCmd {
/// The url to connect to.
#[structopt(
short,
long,
parse(try_from_str = parse::url),
)]
#[clap(short, long, parse(try_from_str = parse::url))]
uri: String,
}
@@ -28,19 +28,19 @@ use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::{fmt::Debug, str::FromStr};
/// Configurations of the [`Command::OffchainWorker`].
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct OffchainWorkerCmd {
/// Overwrite the wasm code in state or not.
#[structopt(long)]
#[clap(long)]
overwrite_wasm_code: bool,
/// 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
/// the `state::at` is. Only use this (with care) when combined with a snapshot.
#[structopt(
#[clap(
long,
multiple = false,
multiple_values = false,
parse(try_from_str = parse::hash)
)]
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
/// the `state::uri` is. Only use this (with care) when combined with a snapshot.
#[structopt(
#[clap(
long,
multiple = false,
multiple_values = false,
parse(try_from_str = parse::url)
)]
header_ws_uri: Option<String>,
/// The state type to use.
#[structopt(subcommand)]
#[clap(subcommand)]
pub state: State,
}
@@ -28,10 +28,10 @@ use crate::{
};
/// Configurations of the [`Command::OnRuntimeUpgrade`].
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct OnRuntimeUpgradeCmd {
/// The state type to use.
#[structopt(subcommand)]
#[clap(subcommand)]
pub state: State,
}
@@ -293,7 +293,7 @@ pub(crate) mod parse;
pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli";
/// Possible commands of `try-runtime`.
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Subcommand)]
pub enum Command {
/// Execute the migrations of the "local runtime".
///
@@ -373,70 +373,64 @@ pub enum Command {
}
/// Shared parameters of the `try-runtime` commands
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct SharedParams {
/// Shared parameters of substrate cli.
#[allow(missing_docs)]
#[structopt(flatten)]
#[clap(flatten)]
pub shared_params: sc_cli::SharedParams,
/// The execution strategy that should be used.
#[structopt(
long = "execution",
value_name = "STRATEGY",
possible_values = &ExecutionStrategy::variants(),
case_insensitive = true,
default_value = "Wasm",
)]
#[clap(long, value_name = "STRATEGY", arg_enum, ignore_case = true, default_value = "Wasm")]
pub execution: ExecutionStrategy,
/// Type of wasm execution used.
#[structopt(
#[clap(
long = "wasm-execution",
value_name = "METHOD",
possible_values = &WasmExecutionMethod::variants(),
case_insensitive = true,
possible_values = WasmExecutionMethod::variants(),
ignore_case = true,
default_value = "Compiled"
)]
pub wasm_method: WasmExecutionMethod,
/// The number of 64KB pages to allocate for Wasm execution. Defaults to
/// [`sc_service::Configuration.default_heap_pages`].
#[structopt(long)]
#[clap(long)]
pub heap_pages: Option<u64>,
/// 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,
}
/// Our `try-runtime` command.
///
/// See [`Command`] for more info.
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Parser)]
pub struct TryRuntimeCmd {
#[structopt(flatten)]
#[clap(flatten)]
pub shared: SharedParams,
#[structopt(subcommand)]
#[clap(subcommand)]
pub command: Command,
}
/// The source of runtime *state* to use.
#[derive(Debug, Clone, structopt::StructOpt)]
#[derive(Debug, Clone, clap::Subcommand)]
pub enum State {
/// Use a state snapshot as the source of runtime state.
///
/// This can be crated by passing a value to [`State::Live::snapshot_path`].
Snap {
#[structopt(short, long)]
#[clap(short, long)]
snapshot_path: PathBuf,
},
/// Use a live chain as the source of runtime state.
Live {
/// The url to connect to.
#[structopt(
#[clap(
short,
long,
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
/// for [`Command::OnRuntimeUpgrade`].
#[structopt(
#[clap(
short,
long,
multiple = false,
multiple_values = false,
parse(try_from_str = parse::hash),
)]
at: Option<String>,
/// An optional state snapshot file to WRITE to. Not written if set to `None`.
#[structopt(short, long)]
#[clap(short, long)]
snapshot_path: Option<PathBuf>,
/// 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>>,
/// 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
/// 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.
#[structopt(long, require_delimiter = true)]
#[clap(long, require_delimiter = true)]
child_tree: bool,
},
}