Run cargo fmt on the whole code base (#9394)

* Run cargo fmt on the whole code base

* Second run

* Add CI check

* Fix compilation

* More unnecessary braces

* Handle weights

* Use --all

* Use correct attributes...

* Fix UI tests

* AHHHHHHHHH

* 🤦

* Docs

* Fix compilation

* 🤷

* Please stop

* 🤦 x 2

* More

* make rustfmt.toml consistent with polkadot

Co-authored-by: André Silva <andrerfosilva@gmail.com>
This commit is contained in:
Bastian Köcher
2021-07-21 16:32:32 +02:00
committed by GitHub
parent d451c38c1c
commit 7b56ab15b4
1010 changed files with 53339 additions and 51208 deletions
+6 -11
View File
@@ -74,9 +74,8 @@ impl WasmExecutionMethod {
impl Into<sc_service::config::WasmExecutionMethod> for WasmExecutionMethod {
fn into(self) -> sc_service::config::WasmExecutionMethod {
match self {
WasmExecutionMethod::Interpreted => {
sc_service::config::WasmExecutionMethod::Interpreted
}
WasmExecutionMethod::Interpreted =>
sc_service::config::WasmExecutionMethod::Interpreted,
#[cfg(feature = "wasmtime")]
WasmExecutionMethod::Compiled => sc_service::config::WasmExecutionMethod::Compiled,
#[cfg(not(feature = "wasmtime"))]
@@ -250,14 +249,10 @@ impl Into<sc_network::config::SyncMode> for SyncMode {
fn into(self) -> sc_network::config::SyncMode {
match self {
SyncMode::Full => sc_network::config::SyncMode::Full,
SyncMode::Fast => sc_network::config::SyncMode::Fast {
skip_proofs: false,
storage_chain_mode: false,
},
SyncMode::FastUnsafe => sc_network::config::SyncMode::Fast {
skip_proofs: true,
storage_chain_mode: false,
},
SyncMode::Fast =>
sc_network::config::SyncMode::Fast { skip_proofs: false, storage_chain_mode: false },
SyncMode::FastUnsafe =>
sc_network::config::SyncMode::Fast { skip_proofs: true, storage_chain_mode: false },
}
}
}
@@ -16,15 +16,19 @@
// 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 crate::error;
use crate::params::NodeKeyParams;
use crate::params::SharedParams;
use crate::CliConfiguration;
use crate::{
error,
params::{NodeKeyParams, SharedParams},
CliConfiguration,
};
use log::info;
use sc_network::config::build_multiaddr;
use sc_service::{config::{MultiaddrWithPeerId, NetworkConfiguration}, ChainSpec};
use structopt::StructOpt;
use sc_service::{
config::{MultiaddrWithPeerId, NetworkConfiguration},
ChainSpec,
};
use std::io::Write;
use structopt::StructOpt;
/// The `build-spec` command used to build a specification.
#[derive(Debug, StructOpt, Clone)]
@@ -17,7 +17,9 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
CliConfiguration, error, params::{ImportParams, SharedParams, BlockNumberOrHash},
error,
params::{BlockNumberOrHash, ImportParams, SharedParams},
CliConfiguration,
};
use sc_client_api::{BlockBackend, UsageProvider};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
@@ -48,11 +50,7 @@ pub struct CheckBlockCmd {
impl CheckBlockCmd {
/// Run the check-block command
pub async fn run<B, C, IQ>(
&self,
client: Arc<C>,
import_queue: IQ,
) -> error::Result<()>
pub async fn run<B, C, IQ>(&self, client: Arc<C>, import_queue: IQ) -> error::Result<()>
where
B: BlockT + for<'de> serde::Deserialize<'de>,
C: BlockBackend<B> + UsageProvider<B> + Send + Sync + 'static,
@@ -16,21 +16,16 @@
// 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 crate::error;
use crate::params::{GenericNumber, DatabaseParams, PruningParams, SharedParams};
use crate::CliConfiguration;
use log::info;
use sc_service::{
config::DatabaseConfig, chain_ops::export_blocks,
use crate::{
error,
params::{DatabaseParams, GenericNumber, PruningParams, SharedParams},
CliConfiguration,
};
use log::info;
use sc_client_api::{BlockBackend, UsageProvider};
use sc_service::{chain_ops::export_blocks, config::DatabaseConfig};
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::fmt::Debug;
use std::fs;
use std::io;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use std::{fmt::Debug, fs, io, path::PathBuf, str::FromStr, sync::Arc};
use structopt::StructOpt;
/// The `export-blocks` command used to export blocks.
@@ -95,9 +90,7 @@ impl ExportBlocksCmd {
None => Box::new(io::stdout()),
};
export_blocks(client, file, from.into(), to, binary)
.await
.map_err(Into::into)
export_blocks(client, file, from.into(), to, binary).await.map_err(Into::into)
}
}
@@ -17,13 +17,15 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::{
CliConfiguration, error, params::{PruningParams, SharedParams, BlockNumberOrHash},
error,
params::{BlockNumberOrHash, PruningParams, SharedParams},
CliConfiguration,
};
use log::info;
use sp_runtime::traits::{Block as BlockT, Header as HeaderT};
use std::{fmt::Debug, str::FromStr, io::Write, sync::Arc};
use structopt::StructOpt;
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.
+9 -10
View File
@@ -16,12 +16,12 @@
// limitations under the License.
//! Implementation of the `generate` subcommand
use bip39::{MnemonicType, Mnemonic, Language};
use structopt::StructOpt;
use crate::{
utils::print_from_uri, KeystoreParams, Error,
with_crypto_scheme, NetworkSchemeFlag, OutputTypeFlag, CryptoSchemeFlag,
utils::print_from_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams,
NetworkSchemeFlag, OutputTypeFlag,
};
use bip39::{Language, Mnemonic, MnemonicType};
use structopt::StructOpt;
/// The `generate` command
#[derive(Debug, StructOpt, Clone)]
@@ -52,12 +52,11 @@ impl GenerateCmd {
/// Run the command
pub fn run(&self) -> Result<(), Error> {
let words = match self.words {
Some(words) => {
MnemonicType::for_word_count(words)
.map_err(|_| {
Error::Input("Invalid number of words given for phrase: must be 12/15/18/21/24".into())
})?
},
Some(words) => MnemonicType::for_word_count(words).map_err(|_| {
Error::Input(
"Invalid number of words given for phrase: must be 12/15/18/21/24".into(),
)
})?,
None => MnemonicType::Words12,
};
let mnemonic = Mnemonic::new(words, Language::English);
@@ -18,9 +18,9 @@
//! Implementation of the `generate-node-key` subcommand
use crate::Error;
use structopt::StructOpt;
use std::{path::PathBuf, fs};
use libp2p::identity::{ed25519 as libp2p_ed25519, PublicKey};
use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `generate-node-key` command
#[derive(Debug, StructOpt)]
@@ -59,15 +59,14 @@ impl GenerateNodeKeyCmd {
#[cfg(test)]
mod tests {
use super::*;
use tempfile::Builder;
use std::io::Read;
use tempfile::Builder;
#[test]
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::from_iter(&["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());
@@ -16,19 +16,22 @@
// 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 crate::error;
use crate::params::ImportParams;
use crate::params::SharedParams;
use crate::CliConfiguration;
use crate::{
error,
params::{ImportParams, SharedParams},
CliConfiguration,
};
use sc_client_api::UsageProvider;
use sc_service::chain_ops::import_blocks;
use sp_runtime::traits::Block as BlockT;
use std::fmt::Debug;
use std::fs;
use std::io::{self, Read, Seek};
use std::path::PathBuf;
use std::sync::Arc;
use std::{
fmt::Debug,
fs,
io::{self, Read, Seek},
path::PathBuf,
sync::Arc,
};
use structopt::StructOpt;
use sc_client_api::UsageProvider;
/// The `import-blocks` command used to import blocks.
#[derive(Debug, StructOpt)]
@@ -63,11 +66,7 @@ impl<T: Read + Seek> ReadPlusSeek for T {}
impl ImportBlocksCmd {
/// Run the import-blocks command
pub async fn run<B, C, IQ>(
&self,
client: Arc<C>,
import_queue: IQ,
) -> error::Result<()>
pub async fn run<B, C, IQ>(&self, client: Arc<C>, import_queue: IQ) -> error::Result<()>
where
C: UsageProvider<B> + Send + Sync + 'static,
B: BlockT + for<'de> serde::Deserialize<'de>,
@@ -79,7 +78,7 @@ impl ImportBlocksCmd {
let mut buffer = Vec::new();
io::stdin().read_to_end(&mut buffer)?;
Box::new(io::Cursor::new(buffer))
}
},
};
import_blocks(client, import_queue, file, false, self.binary)
+37 -38
View File
@@ -18,22 +18,18 @@
//! Implementation of the `insert` subcommand
use crate::{
Error, KeystoreParams, CryptoSchemeFlag, SharedParams, utils, with_crypto_scheme,
SubstrateCli,
utils, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, SharedParams, SubstrateCli,
};
use std::{sync::Arc, convert::TryFrom};
use structopt::StructOpt;
use sp_core::{crypto::KeyTypeId, crypto::SecretString};
use sp_keystore::{SyncCryptoStorePtr, SyncCryptoStore};
use sc_keystore::LocalKeystore;
use sc_service::config::{KeystoreConfig, BasePath};
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."
)]
#[structopt(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.
@@ -62,7 +58,8 @@ impl InsertKeyCmd {
/// Run the command
pub fn run<C: SubstrateCli>(&self, cli: &C) -> Result<(), Error> {
let suri = utils::read_uri(self.suri.as_ref())?;
let base_path = self.shared_params
let base_path = self
.shared_params
.base_path()
.unwrap_or_else(|| BasePath::from_project("", "", &C::executable_name()));
let chain_id = self.shared_params.chain_id(self.shared_params.is_dev());
@@ -78,10 +75,11 @@ impl InsertKeyCmd {
let keystore: SyncCryptoStorePtr = Arc::new(LocalKeystore::open(path, password)?);
(keystore, public)
},
_ => unreachable!("keystore_config always returns path and password; qed")
_ => unreachable!("keystore_config always returns path and password; qed"),
};
let key_type = KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?;
let key_type =
KeyTypeId::try_from(self.key_type.as_str()).map_err(|_| Error::KeyTypeInvalid)?;
SyncCryptoStore::insert_unknown(&*keystore, key_type, &suri, &public[..])
.map_err(|_| Error::KeyStoreOperation)?;
@@ -98,10 +96,10 @@ fn to_vec<P: sp_core::Pair>(uri: &str, pass: Option<SecretString>) -> Result<Vec
#[cfg(test)]
mod tests {
use super::*;
use sc_service::{ChainSpec, ChainType, GenericChainSpec, NoExtension};
use sp_core::{sr25519::Pair, Pair as _, Public};
use structopt::StructOpt;
use tempfile::TempDir;
use sp_core::{sr25519::Pair, Pair as _, Public};
use sc_service::{ChainSpec, GenericChainSpec, ChainType, NoExtension};
struct Cli;
@@ -135,21 +133,17 @@ mod tests {
}
fn load_spec(&self, _: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
Ok(
Box::new(
GenericChainSpec::from_genesis(
"test",
"test_id",
ChainType::Development,
|| unimplemented!("Not required in tests"),
Vec::new(),
None,
None,
None,
NoExtension::None,
),
),
)
Ok(Box::new(GenericChainSpec::from_genesis(
"test",
"test_id",
ChainType::Development,
|| unimplemented!("Not required in tests"),
Vec::new(),
None,
None,
None,
NoExtension::None,
)))
}
}
@@ -159,15 +153,20 @@ mod tests {
let path_str = format!("{}", path.path().display());
let (key, uri, _) = Pair::generate_with_phrase(None);
let inspect = InsertKeyCmd::from_iter(
&["insert-key", "-d", &path_str, "--key-type", "test", "--suri", &uri],
);
let inspect = InsertKeyCmd::from_iter(&[
"insert-key",
"-d",
&path_str,
"--key-type",
"test",
"--suri",
&uri,
]);
assert!(inspect.run(&Cli).is_ok());
let keystore = LocalKeystore::open(
path.path().join("chains").join("test_id").join("keystore"),
None,
).unwrap();
let keystore =
LocalKeystore::open(path.path().join("chains").join("test_id").join("keystore"), None)
.unwrap();
assert!(keystore.has_keys(&[(key.public().to_raw_vec(), KeyTypeId(*b"test"))]));
}
}
@@ -18,8 +18,8 @@
//! Implementation of the `inspect` subcommand
use crate::{
utils::{self, print_from_uri, print_from_public}, KeystoreParams,
with_crypto_scheme, NetworkSchemeFlag, OutputTypeFlag, CryptoSchemeFlag, Error,
utils::{self, print_from_public, print_from_uri},
with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, NetworkSchemeFlag, OutputTypeFlag,
};
use structopt::StructOpt;
/// The `inspect` command
@@ -103,8 +103,7 @@ 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::from_iter(&["inspect-key", words, "--password", "12345"]);
assert!(inspect.run().is_ok());
let inspect = InspectKeyCmd::from_iter(&["inspect-key", seed]);
@@ -18,9 +18,8 @@
//! Implementation of the `inspect-node-key` subcommand
use crate::{Error, NetworkSchemeFlag};
use std::fs;
use libp2p::identity::{PublicKey, ed25519};
use std::path::PathBuf;
use libp2p::identity::{ed25519, PublicKey};
use std::{fs, path::PathBuf};
use structopt::StructOpt;
/// The `inspect-node-key` command
@@ -42,10 +41,10 @@ pub struct InspectNodeKeyCmd {
impl InspectNodeKeyCmd {
/// runs the command
pub fn run(&self) -> Result<(), Error> {
let mut file_content = hex::decode(fs::read(&self.file)?)
.map_err(|_| "failed to decode secret as hex")?;
let secret = ed25519::SecretKey::from_bytes(&mut file_content)
.map_err(|_| "Bad node key file")?;
let mut file_content =
hex::decode(fs::read(&self.file)?).map_err(|_| "failed to decode secret as hex")?;
let secret =
ed25519::SecretKey::from_bytes(&mut file_content).map_err(|_| "Bad node key file")?;
let keypair = ed25519::Keypair::from(secret);
let peer_id = PublicKey::Ed25519(keypair.public()).into_peer_id();
@@ -58,8 +57,7 @@ impl InspectNodeKeyCmd {
#[cfg(test)]
mod tests {
use super::*;
use super::super::GenerateNodeKeyCmd;
use super::{super::GenerateNodeKeyCmd, *};
#[test]
fn inspect_node_key() {
+2 -5
View File
@@ -21,11 +21,8 @@ use crate::{Error, SubstrateCli};
use structopt::StructOpt;
use super::{
insert_key::InsertKeyCmd,
inspect_key::InspectKeyCmd,
generate::GenerateCmd,
inspect_node_key::InspectNodeKeyCmd,
generate_node_key::GenerateNodeKeyCmd,
generate::GenerateCmd, generate_node_key::GenerateNodeKeyCmd, insert_key::InsertKeyCmd,
inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd,
};
/// Key utilities for the cli.
+15 -26
View File
@@ -19,37 +19,26 @@ mod build_spec_cmd;
mod check_block_cmd;
mod export_blocks_cmd;
mod export_state_cmd;
mod generate;
mod generate_node_key;
mod import_blocks_cmd;
mod insert_key;
mod inspect_key;
mod inspect_node_key;
mod key;
mod purge_chain_cmd;
mod sign;
mod verify;
mod vanity;
mod revert_cmd;
mod run_cmd;
mod generate_node_key;
mod generate;
mod insert_key;
mod inspect_node_key;
mod inspect_key;
mod key;
mod sign;
pub mod utils;
mod vanity;
mod verify;
pub use self::{
build_spec_cmd::BuildSpecCmd,
check_block_cmd::CheckBlockCmd,
export_blocks_cmd::ExportBlocksCmd,
export_state_cmd::ExportStateCmd,
import_blocks_cmd::ImportBlocksCmd,
purge_chain_cmd::PurgeChainCmd,
sign::SignCmd,
generate::GenerateCmd,
insert_key::InsertKeyCmd,
inspect_key::InspectKeyCmd,
generate_node_key::GenerateNodeKeyCmd,
inspect_node_key::InspectNodeKeyCmd,
key::KeySubcommand,
vanity::VanityCmd,
verify::VerifyCmd,
revert_cmd::RevertCmd,
run_cmd::RunCmd,
build_spec_cmd::BuildSpecCmd, check_block_cmd::CheckBlockCmd,
export_blocks_cmd::ExportBlocksCmd, export_state_cmd::ExportStateCmd, generate::GenerateCmd,
generate_node_key::GenerateNodeKeyCmd, import_blocks_cmd::ImportBlocksCmd,
insert_key::InsertKeyCmd, inspect_key::InspectKeyCmd, inspect_node_key::InspectNodeKeyCmd,
key::KeySubcommand, purge_chain_cmd::PurgeChainCmd, revert_cmd::RevertCmd, run_cmd::RunCmd,
sign::SignCmd, vanity::VanityCmd, verify::VerifyCmd,
};
@@ -16,13 +16,17 @@
// 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 crate::error;
use crate::params::{DatabaseParams, SharedParams};
use crate::CliConfiguration;
use crate::{
error,
params::{DatabaseParams, SharedParams},
CliConfiguration,
};
use sc_service::DatabaseConfig;
use std::fmt::Debug;
use std::fs;
use std::io::{self, Write};
use std::{
fmt::Debug,
fs,
io::{self, Write},
};
use structopt::StructOpt;
/// The `purge-chain` command used to remove the whole chain.
@@ -44,10 +48,9 @@ pub struct PurgeChainCmd {
impl PurgeChainCmd {
/// Run the purge command
pub fn run(&self, database_config: DatabaseConfig) -> error::Result<()> {
let db_path = database_config.path()
.ok_or_else(||
error::Error::Input("Cannot purge custom database implementation".into())
)?;
let db_path = database_config.path().ok_or_else(|| {
error::Error::Input("Cannot purge custom database implementation".into())
})?;
if !self.yes {
print!("Are you sure to remove {:?}? [y/N]: ", &db_path);
@@ -61,7 +64,7 @@ impl PurgeChainCmd {
Some('y') | Some('Y') => {},
_ => {
println!("Aborted");
return Ok(());
return Ok(())
},
}
}
@@ -16,16 +16,16 @@
// 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 crate::error;
use crate::params::{GenericNumber, PruningParams, SharedParams};
use crate::CliConfiguration;
use crate::{
error,
params::{GenericNumber, PruningParams, SharedParams},
CliConfiguration,
};
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;
use std::str::FromStr;
use std::sync::Arc;
use std::{fmt::Debug, str::FromStr, sync::Arc};
use structopt::StructOpt;
use sc_client_api::{Backend, UsageProvider};
/// The `revert` command used revert the chain to a previous state.
#[derive(Debug, StructOpt)]
@@ -45,11 +45,7 @@ pub struct RevertCmd {
impl RevertCmd {
/// Run the revert command
pub async fn run<B, BA, C>(
&self,
client: Arc<C>,
backend: Arc<BA>,
) -> error::Result<()>
pub async fn run<B, BA, C>(&self, client: Arc<C>, backend: Arc<BA>) -> error::Result<()>
where
B: BlockT,
BA: Backend<B>,
+29 -38
View File
@@ -16,15 +16,15 @@
// 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 crate::arg_enums::RpcMethods;
use crate::error::{Error, Result};
use crate::params::ImportParams;
use crate::params::KeystoreParams;
use crate::params::NetworkParams;
use crate::params::OffchainWorkerParams;
use crate::params::SharedParams;
use crate::params::TransactionPoolParams;
use crate::CliConfiguration;
use crate::{
arg_enums::RpcMethods,
error::{Error, Result},
params::{
ImportParams, KeystoreParams, NetworkParams, OffchainWorkerParams, SharedParams,
TransactionPoolParams,
},
CliConfiguration,
};
use regex::Regex;
use sc_service::{
config::{BasePath, PrometheusConfig, TransactionPoolOptions},
@@ -308,7 +308,7 @@ impl CliConfiguration for RunCmd {
Error::Input(format!(
"Invalid node name '{}'. Reason: {}. If unsure, use none.",
name, msg
))
))
})?;
Ok(name)
@@ -363,18 +363,13 @@ impl CliConfiguration for RunCmd {
Ok(if self.no_prometheus {
None
} else {
let interface = if self.prometheus_external {
Ipv4Addr::UNSPECIFIED
} else {
Ipv4Addr::LOCALHOST
};
let interface =
if self.prometheus_external { Ipv4Addr::UNSPECIFIED } else { Ipv4Addr::LOCALHOST };
Some(PrometheusConfig::new_with_default_registry(
SocketAddr::new(
interface.into(),
self.prometheus_port.unwrap_or(default_listen_port),
)
))
Some(PrometheusConfig::new_with_default_registry(SocketAddr::new(
interface.into(),
self.prometheus_port.unwrap_or(default_listen_port),
)))
})
}
@@ -416,7 +411,7 @@ impl CliConfiguration for RunCmd {
self.rpc_external,
self.unsafe_rpc_external,
self.rpc_methods,
self.validator
self.validator,
)?;
Ok(Some(SocketAddr::new(interface, self.rpc_port.unwrap_or(default_listen_port))))
@@ -466,19 +461,19 @@ impl CliConfiguration for RunCmd {
pub fn is_node_name_valid(_name: &str) -> std::result::Result<(), &str> {
let name = _name.to_string();
if name.chars().count() >= crate::NODE_NAME_MAX_LENGTH {
return Err("Node name too long");
return Err("Node name too long")
}
let invalid_chars = r"[\\.@]";
let re = Regex::new(invalid_chars).unwrap();
if re.is_match(&name) {
return Err("Node name should not contain invalid chars such as '.' and '@'");
return Err("Node name should not contain invalid chars such as '.' and '@'")
}
let invalid_patterns = r"(https?:\\/+)?(www)+";
let re = Regex::new(invalid_patterns).unwrap();
if re.is_match(&name) {
return Err("Node name should not contain urls");
return Err("Node name should not contain urls")
}
Ok(())
@@ -497,7 +492,7 @@ fn rpc_interface(
or `--rpc-methods=unsafe` if you understand the risks. See the options \
description for more information."
.to_owned(),
));
))
}
if is_external || is_unsafe_external {
@@ -537,11 +532,10 @@ fn parse_telemetry_endpoints(s: &str) -> std::result::Result<(String, u8), Telem
None => Err(TelemetryParsingError::MissingVerbosity),
Some(pos_) => {
let url = s[..pos_].to_string();
let verbosity = s[pos_ + 1..]
.parse()
.map_err(TelemetryParsingError::VerbosityParsingError)?;
let verbosity =
s[pos_ + 1..].parse().map_err(TelemetryParsingError::VerbosityParsingError)?;
Ok((url, verbosity))
}
},
}
}
@@ -574,17 +568,13 @@ fn parse_cors(s: &str) -> std::result::Result<Cors, Box<dyn std::error::Error>>
match part {
"all" | "*" => {
is_all = true;
break;
}
break
},
other => origins.push(other.to_owned()),
}
}
Ok(if is_all {
Cors::All
} else {
Cors::List(origins)
})
Ok(if is_all { Cors::All } else { Cors::List(origins) })
}
#[cfg(test)]
@@ -600,7 +590,8 @@ mod tests {
fn tests_node_name_bad() {
assert!(is_node_name_valid(
"very very long names are really not very cool for the ui at all, really they're not"
).is_err());
)
.is_err());
assert!(is_node_name_valid("Dots.not.Ok").is_err());
assert!(is_node_name_valid("http://visit.me").is_err());
assert!(is_node_name_valid("https://visit.me").is_err());
+11 -13
View File
@@ -5,7 +5,7 @@
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
@@ -18,15 +18,12 @@
//! Implementation of the `sign` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag, KeystoreParams};
use structopt::StructOpt;
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"
)]
#[structopt(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.
@@ -52,7 +49,6 @@ pub struct SignCmd {
pub crypto_scheme: CryptoSchemeFlag,
}
impl SignCmd {
/// Run the command
pub fn run(&self) -> error::Result<()> {
@@ -60,17 +56,19 @@ impl SignCmd {
let suri = utils::read_uri(self.suri.as_ref())?;
let password = self.keystore_params.read_password()?;
let signature = with_crypto_scheme!(
self.crypto_scheme.scheme,
sign(&suri, password, message)
)?;
let signature =
with_crypto_scheme!(self.crypto_scheme.scheme, sign(&suri, password, message))?;
println!("{}", signature);
Ok(())
}
}
fn sign<P: sp_core::Pair>(suri: &str, password: Option<SecretString>, message: Vec<u8>) -> error::Result<String> {
fn sign<P: sp_core::Pair>(
suri: &str,
password: Option<SecretString>,
message: Vec<u8>,
) -> error::Result<String> {
let pair = utils::pair_from_suri::<P>(suri, password)?;
Ok(format!("{}", hex::encode(pair.sign(&message))))
}
@@ -91,7 +89,7 @@ mod test {
"--message",
&seed[2..],
"--password",
"12345"
"12345",
]);
assert!(sign.run().is_ok());
}
+16 -33
View File
@@ -22,9 +22,8 @@ use crate::{
OutputType,
};
use serde_json::json;
use sp_core::crypto::{ExposeSecret, SecretString, Zeroize};
use sp_core::{
crypto::{Ss58AddressFormat, Ss58Codec},
crypto::{ExposeSecret, SecretString, Ss58AddressFormat, Ss58Codec, Zeroize},
hexdisplay::HexDisplay,
Pair,
};
@@ -88,7 +87,7 @@ pub fn print_from_uri<Pair>(
"{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed")
);
}
},
OutputType::Text => {
println!(
"Secret phrase `{}` is account:\n \
@@ -102,12 +101,9 @@ pub fn print_from_uri<Pair>(
format_public_key::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override),
format_account_id::<Pair>(public_key),
pair.public()
.into()
.into_account()
.to_ss58check_with_version(network_override),
pair.public().into().into_account().to_ss58check_with_version(network_override),
);
}
},
}
} else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password.clone()) {
let public_key = pair.public();
@@ -127,7 +123,7 @@ pub fn print_from_uri<Pair>(
"{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed")
);
}
},
OutputType::Text => {
println!(
"Secret Key URI `{}` is account:\n \
@@ -137,20 +133,13 @@ pub fn print_from_uri<Pair>(
Account ID: {}\n \
SS58 Address: {}",
uri,
if let Some(seed) = seed {
format_seed::<Pair>(seed)
} else {
"n/a".into()
},
if let Some(seed) = seed { format_seed::<Pair>(seed) } else { "n/a".into() },
format_public_key::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override),
format_account_id::<Pair>(public_key),
pair.public()
.into()
.into_account()
.to_ss58check_with_version(network_override),
pair.public().into().into_account().to_ss58check_with_version(network_override),
);
}
},
}
} else if let Ok((public_key, network)) = Pair::Public::from_string_with_version(uri) {
let network_override = network_override.unwrap_or(network);
@@ -170,7 +159,7 @@ pub fn print_from_uri<Pair>(
"{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed")
);
}
},
OutputType::Text => {
println!(
"Public Key URI `{}` is account:\n \
@@ -186,7 +175,7 @@ pub fn print_from_uri<Pair>(
format_account_id::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override),
);
}
},
}
} else {
println!("Invalid phrase/URI given");
@@ -220,11 +209,8 @@ where
"ss58Address": public_key.to_ss58check_with_version(network_override),
});
println!(
"{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed")
);
}
println!("{}", serde_json::to_string_pretty(&json).expect("Json pretty print failed"));
},
OutputType::Text => {
println!(
"Network ID/version: {}\n \
@@ -238,7 +224,7 @@ where
format_account_id::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override),
);
}
},
}
Ok(())
@@ -273,10 +259,7 @@ fn format_account_id<P: sp_core::Pair>(public_key: PublicFor<P>) -> String
where
PublicFor<P>: Into<MultiSigner>,
{
format!(
"0x{}",
HexDisplay::from(&public_key.into().into_account().as_ref())
)
format!("0x{}", HexDisplay::from(&public_key.into().into_account().as_ref()))
}
/// helper method for decoding hex
@@ -294,13 +277,13 @@ pub fn read_message(msg: Option<&String>, should_decode: bool) -> Result<Vec<u8>
match msg {
Some(m) => {
message = decode_hex(m)?;
}
},
None => {
std::io::stdin().lock().read_to_end(&mut message)?;
if should_decode {
message = decode_hex(&message)?;
}
}
},
}
Ok(message)
}
+29 -48
View File
@@ -5,7 +5,7 @@
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
@@ -19,21 +19,17 @@
//! implementation of the `vanity` subcommand
use crate::{
error, utils, with_crypto_scheme,
CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag,
error, utils, with_crypto_scheme, CryptoSchemeFlag, NetworkSchemeFlag, OutputTypeFlag,
};
use sp_core::crypto::{Ss58Codec, Ss58AddressFormat};
use structopt::StructOpt;
use rand::{rngs::OsRng, RngCore};
use sp_core::crypto::{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"
)]
#[structopt(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))]
@@ -78,10 +74,10 @@ fn generate_key<Pair>(
desired: &str,
network_override: Ss58AddressFormat,
) -> Result<String, &'static str>
where
Pair: sp_core::Pair,
Pair::Public: IdentifyAccount,
<Pair::Public as IdentifyAccount>::AccountId: Ss58Codec,
where
Pair: sp_core::Pair,
Pair::Public: IdentifyAccount,
<Pair::Public as IdentifyAccount>::AccountId: Ss58Codec,
{
println!("Generating key containing pattern '{}'", desired);
@@ -104,7 +100,7 @@ fn generate_key<Pair>(
best = score;
if best >= top {
println!("best: {} == top: {}", best, top);
return Ok(utils::format_seed::<Pair>(seed.clone()));
return Ok(utils::format_seed::<Pair>(seed.clone()))
}
}
done += 1;
@@ -129,11 +125,11 @@ fn next_seed(seed: &mut [u8]) {
match seed[i] {
255 => {
seed[i] = 0;
}
},
_ => {
seed[i] += 1;
break;
}
break
},
}
}
}
@@ -145,7 +141,7 @@ fn calculate_score(_desired: &str, key: &str) -> usize {
let snip_size = _desired.len() - truncate;
let truncated = &_desired[0..snip_size];
if let Some(pos) = key.find(truncated) {
return (47 - pos) + (snip_size * 48);
return (47 - pos) + (snip_size * 48)
}
}
0
@@ -160,15 +156,13 @@ fn assert_non_empty_string(pattern: &str) -> Result<String, &'static str> {
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::{crypto::Ss58Codec, Pair};
use sp_core::sr25519;
use sp_core::{crypto::Ss58Codec, sr25519, Pair};
use structopt::StructOpt;
#[cfg(feature = "bench")]
use test::Bencher;
use structopt::StructOpt;
#[test]
fn vanity() {
@@ -179,25 +173,21 @@ mod tests {
#[test]
fn test_generation_with_single_char() {
let seed = generate_key::<sr25519::Pair>("ab", Default::default()).unwrap();
assert!(
sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check()
.contains("ab")
);
assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check()
.contains("ab"));
}
#[test]
fn generate_key_respects_network_override() {
let seed = generate_key::<sr25519::Pair>("ab", Ss58AddressFormat::PolkadotAccount).unwrap();
assert!(
sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check_with_version(Ss58AddressFormat::PolkadotAccount)
.contains("ab")
);
assert!(sr25519::Pair::from_seed_slice(&hex::decode(&seed[2..]).unwrap())
.unwrap()
.public()
.to_ss58check_with_version(Ss58AddressFormat::PolkadotAccount)
.contains("ab"));
}
#[test]
@@ -208,10 +198,7 @@ mod tests {
#[test]
fn test_score_100() {
let score = calculate_score(
"Polkadot",
"5PolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim",
);
let score = calculate_score("Polkadot", "5PolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim");
assert_eq!(score, 430);
}
@@ -219,10 +206,7 @@ mod tests {
fn test_score_50_2() {
// 50% for the position + 50% for the size
assert_eq!(
calculate_score(
"Polkadot",
"5PolkXXXXwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"
),
calculate_score("Polkadot", "5PolkXXXXwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"),
238
);
}
@@ -230,10 +214,7 @@ mod tests {
#[test]
fn test_score_0() {
assert_eq!(
calculate_score(
"Polkadot",
"5GUWv4bLCchGUHJrzULXnh4JgXsMpTKRnjuXTY7Qo1Kh9uYK"
),
calculate_score("Polkadot", "5GUWv4bLCchGUHJrzULXnh4JgXsMpTKRnjuXTY7Qo1Kh9uYK"),
0
);
}
+11 -20
View File
@@ -5,7 +5,7 @@
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
@@ -19,7 +19,7 @@
//! implementation of the `verify` subcommand
use crate::{error, utils, with_crypto_scheme, CryptoSchemeFlag};
use sp_core::{Public, crypto::Ss58Codec};
use sp_core::{crypto::Ss58Codec, Public};
use structopt::StructOpt;
/// The `verify` command
@@ -57,32 +57,23 @@ impl VerifyCmd {
let message = utils::read_message(self.message.as_ref(), self.hex)?;
let sig_data = utils::decode_hex(&self.sig)?;
let uri = utils::read_uri(self.uri.as_ref())?;
let uri = if uri.starts_with("0x") {
&uri[2..]
} else {
&uri
};
let uri = if uri.starts_with("0x") { &uri[2..] } else { &uri };
with_crypto_scheme!(
self.crypto_scheme.scheme,
verify(sig_data, message, uri)
)
with_crypto_scheme!(self.crypto_scheme.scheme, verify(sig_data, message, uri))
}
}
fn verify<Pair>(sig_data: Vec<u8>, message: Vec<u8>, uri: &str) -> error::Result<()>
where
Pair: sp_core::Pair,
Pair::Signature: Default + AsMut<[u8]>,
where
Pair: sp_core::Pair,
Pair::Signature: Default + AsMut<[u8]>,
{
let mut signature = Pair::Signature::default();
if sig_data.len() != signature.as_ref().len() {
return Err(
error::Error::SignatureInvalidLength {
read: sig_data.len(),
expected: signature.as_ref().len(),
}
);
return Err(error::Error::SignatureInvalidLength {
read: sig_data.len(),
expected: signature.as_ref().len(),
})
}
signature.as_mut().copy_from_slice(&sig_data);
+22 -42
View File
@@ -18,24 +18,24 @@
//! Configuration trait for a CLI based on substrate
use crate::arg_enums::Database;
use crate::error::Result;
use crate::{
DatabaseParams, ImportParams, KeystoreParams, NetworkParams, NodeKeyParams,
OffchainWorkerParams, PruningParams, SharedParams, SubstrateCli,
arg_enums::Database, error::Result, DatabaseParams, ImportParams, KeystoreParams,
NetworkParams, NodeKeyParams, OffchainWorkerParams, PruningParams, SharedParams, SubstrateCli,
};
use log::warn;
use names::{Generator, Name};
use sc_client_api::execution_extensions::ExecutionStrategies;
use sc_service::config::{
BasePath, Configuration, DatabaseConfig, ExtTransport, KeystoreConfig, NetworkConfiguration,
NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode, Role, RpcMethods,
TaskExecutor, TelemetryEndpoints, TransactionPoolOptions, WasmExecutionMethod,
use sc_service::{
config::{
BasePath, Configuration, DatabaseConfig, ExtTransport, KeystoreConfig,
NetworkConfiguration, NodeKeyConfig, OffchainWorkerConfig, PrometheusConfig, PruningMode,
Role, RpcMethods, TaskExecutor, TelemetryEndpoints, TransactionPoolOptions,
WasmExecutionMethod,
},
ChainSpec, KeepBlocks, TracingReceiver, TransactionStorageMode,
};
use sc_service::{ChainSpec, TracingReceiver, KeepBlocks, TransactionStorageMode};
use sc_tracing::logging::LoggerBuilder;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::{net::SocketAddr, path::PathBuf};
/// The maximum number of characters for a node name.
pub(crate) const NODE_NAME_MAX_LENGTH: usize = 64;
@@ -178,12 +178,7 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
default_listen_port,
)
} else {
NetworkConfiguration::new(
node_name,
client_id,
node_key,
Some(net_config_dir),
)
NetworkConfiguration::new(node_name, client_id, node_key, Some(net_config_dir))
})
}
@@ -201,14 +196,13 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
///
/// By default this is retrieved from `DatabaseParams` if it is available. Otherwise its `None`.
fn database_cache_size(&self) -> Result<Option<usize>> {
Ok(self.database_params()
.map(|x| x.database_cache_size())
.unwrap_or_default())
Ok(self.database_params().map(|x| x.database_cache_size()).unwrap_or_default())
}
/// Get the database transaction storage scheme.
fn database_transaction_storage(&self) -> Result<TransactionStorageMode> {
Ok(self.database_params()
Ok(self
.database_params()
.map(|x| x.transaction_storage())
.unwrap_or(TransactionStorageMode::BlockBody))
}
@@ -228,13 +222,8 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
database: Database,
) -> Result<DatabaseConfig> {
Ok(match database {
Database::RocksDb => DatabaseConfig::RocksDb {
path: base_path.join("db"),
cache_size,
},
Database::ParityDb => DatabaseConfig::ParityDb {
path: base_path.join("paritydb"),
},
Database::RocksDb => DatabaseConfig::RocksDb { path: base_path.join("db"), cache_size },
Database::ParityDb => DatabaseConfig::ParityDb { path: base_path.join("paritydb") },
})
}
@@ -242,9 +231,7 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
///
/// By default this is retrieved from `ImportParams` if it is available. Otherwise its `0`.
fn state_cache_size(&self) -> Result<usize> {
Ok(self.import_params()
.map(|x| x.state_cache_size())
.unwrap_or_default())
Ok(self.import_params().map(|x| x.state_cache_size()).unwrap_or_default())
}
/// Get the state cache child ratio (if any).
@@ -293,18 +280,14 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
/// By default this is retrieved from `ImportParams` if it is available. Otherwise its
/// `WasmExecutionMethod::default()`.
fn wasm_method(&self) -> Result<WasmExecutionMethod> {
Ok(self.import_params()
.map(|x| x.wasm_method())
.unwrap_or_default())
Ok(self.import_params().map(|x| x.wasm_method()).unwrap_or_default())
}
/// Get the path where WASM overrides live.
///
/// By default this is `None`.
fn wasm_runtime_overrides(&self) -> Option<PathBuf> {
self.import_params()
.map(|x| x.wasm_runtime_overrides())
.unwrap_or_default()
self.import_params().map(|x| x.wasm_runtime_overrides()).unwrap_or_default()
}
/// Get the execution strategies.
@@ -502,10 +485,7 @@ pub trait CliConfiguration<DCV: DefaultConfigurationValues = ()>: Sized {
let (keystore_remote, keystore) = self.keystore_config(&config_dir)?;
let telemetry_endpoints = self.telemetry_endpoints(&chain_spec)?;
let unsafe_pruning = self
.import_params()
.map(|p| p.unsafe_pruning)
.unwrap_or(false);
let unsafe_pruning = self.import_params().map(|p| p.unsafe_pruning).unwrap_or(false);
Ok(Configuration {
impl_name: C::impl_name(),
@@ -628,7 +608,7 @@ pub fn generate_node_name() -> String {
let count = node_name.chars().count();
if count < NODE_NAME_MAX_LENGTH {
return node_name;
return node_name
}
}
}
+1 -1
View File
@@ -159,7 +159,7 @@ pub trait SubstrateCli: Sized {
let _ = std::io::stdout().write_all(e.message.as_bytes());
std::process::exit(0);
}
}
},
};
<Self as StructOpt>::from_clap(&matches)
@@ -17,8 +17,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::arg_enums::Database;
use structopt::StructOpt;
use sc_service::TransactionStorageMode;
use structopt::StructOpt;
/// Parameters for block import.
#[derive(Debug, StructOpt, Clone)]
@@ -16,16 +16,17 @@
// 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 crate::arg_enums::{
ExecutionStrategy, WasmExecutionMethod, DEFAULT_EXECUTION_BLOCK_CONSTRUCTION,
DEFAULT_EXECUTION_IMPORT_BLOCK, DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR,
DEFAULT_EXECUTION_OFFCHAIN_WORKER, DEFAULT_EXECUTION_OTHER, DEFAULT_EXECUTION_SYNCING,
use crate::{
arg_enums::{
ExecutionStrategy, WasmExecutionMethod, DEFAULT_EXECUTION_BLOCK_CONSTRUCTION,
DEFAULT_EXECUTION_IMPORT_BLOCK, DEFAULT_EXECUTION_IMPORT_BLOCK_VALIDATOR,
DEFAULT_EXECUTION_OFFCHAIN_WORKER, DEFAULT_EXECUTION_OTHER, DEFAULT_EXECUTION_SYNCING,
},
params::{DatabaseParams, PruningParams},
};
use crate::params::DatabaseParams;
use crate::params::PruningParams;
use sc_client_api::execution_extensions::ExecutionStrategies;
use structopt::StructOpt;
use std::path::PathBuf;
use structopt::StructOpt;
#[cfg(feature = "wasmtime")]
const WASM_METHOD_DEFAULT: &str = "Compiled";
@@ -73,11 +74,7 @@ pub struct ImportParams {
pub execution_strategies: ExecutionStrategiesParams,
/// Specify the state cache size.
#[structopt(
long = "state-cache-size",
value_name = "Bytes",
default_value = "67108864"
)]
#[structopt(long = "state-cache-size", value_name = "Bytes", default_value = "67108864")]
pub state_cache_size: usize,
}
@@ -102,11 +99,7 @@ impl ImportParams {
pub fn execution_strategies(&self, is_dev: bool, is_validator: bool) -> ExecutionStrategies {
let exec = &self.execution_strategies;
let exec_all_or = |strat: Option<ExecutionStrategy>, default: ExecutionStrategy| {
let default = if is_dev {
ExecutionStrategy::Native
} else {
default
};
let default = if is_dev { ExecutionStrategy::Native } else { default };
exec.execution.unwrap_or_else(|| strat.unwrap_or(default)).into()
};
@@ -120,10 +113,14 @@ impl ImportParams {
ExecutionStrategies {
syncing: exec_all_or(exec.execution_syncing, DEFAULT_EXECUTION_SYNCING),
importing: exec_all_or(exec.execution_import_block, default_execution_import_block),
block_construction:
exec_all_or(exec.execution_block_construction, DEFAULT_EXECUTION_BLOCK_CONSTRUCTION),
offchain_worker:
exec_all_or(exec.execution_offchain_worker, DEFAULT_EXECUTION_OFFCHAIN_WORKER),
block_construction: exec_all_or(
exec.execution_block_construction,
DEFAULT_EXECUTION_BLOCK_CONSTRUCTION,
),
offchain_worker: exec_all_or(
exec.execution_offchain_worker,
DEFAULT_EXECUTION_OFFCHAIN_WORKER,
),
other: exec_all_or(exec.execution_other, DEFAULT_EXECUTION_OTHER),
}
}
@@ -16,12 +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 crate::error::Result;
use crate::{error, error::Result};
use sc_service::config::KeystoreConfig;
use std::{fs, path::{PathBuf, Path}};
use structopt::StructOpt;
use crate::error;
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";
@@ -81,8 +83,7 @@ impl KeystoreParams {
#[cfg(target_os = "unknown")]
None
} else if let Some(ref file) = self.password_filename {
let password = fs::read_to_string(file)
.map_err(|e| format!("{}", e))?;
let password = fs::read_to_string(file).map_err(|e| format!("{}", e))?;
Some(SecretString::new(password))
} else {
self.password.clone()
+16 -21
View File
@@ -25,21 +25,20 @@ mod pruning_params;
mod shared_params;
mod transaction_pool_params;
use std::{fmt::Debug, str::FromStr, convert::TryFrom};
use sp_runtime::{generic::BlockId, traits::{Block as BlockT, NumberFor}};
use crate::arg_enums::{CryptoScheme, OutputType};
use sp_core::crypto::Ss58AddressFormat;
use crate::arg_enums::{OutputType, CryptoScheme};
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::*;
pub use crate::params::import_params::*;
pub use crate::params::keystore_params::*;
pub use crate::params::network_params::*;
pub use crate::params::node_key_params::*;
pub use crate::params::offchain_worker_params::*;
pub use crate::params::pruning_params::*;
pub use crate::params::shared_params::*;
pub use crate::params::transaction_pool_params::*;
pub use crate::params::{
database_params::*, import_params::*, keystore_params::*, network_params::*,
node_key_params::*, offchain_worker_params::*, pruning_params::*, shared_params::*,
transaction_pool_params::*,
};
/// Wrapper type of `String` that holds an unsigned integer of arbitrary size, formatted as a decimal.
#[derive(Debug, Clone)]
@@ -50,10 +49,7 @@ impl FromStr for GenericNumber {
fn from_str(block_number: &str) -> Result<Self, Self::Err> {
if let Some(pos) = block_number.chars().position(|d| !d.is_digit(10)) {
Err(format!(
"Expected block number, found illegal digit at position: {}",
pos,
))
Err(format!("Expected block number, found illegal digit at position: {}", pos,))
} else {
Ok(Self(block_number.to_owned()))
}
@@ -66,9 +62,9 @@ impl GenericNumber {
/// See `https://doc.rust-lang.org/std/primitive.str.html#method.parse` for more elaborate
/// documentation.
pub fn parse<N>(&self) -> Result<N, String>
where
N: FromStr,
N::Err: std::fmt::Debug,
where
N: FromStr,
N::Err: std::fmt::Debug,
{
FromStr::from_str(&self.0).map_err(|e| format!("Failed to parse block number: {:?}", e))
}
@@ -109,7 +105,7 @@ impl BlockNumberOrHash {
if self.0.starts_with("0x") {
Ok(BlockId::Hash(
FromStr::from_str(&self.0[2..])
.map_err(|e| format!("Failed to parse block hash: {:?}", e))?
.map_err(|e| format!("Failed to parse block hash: {:?}", e))?,
))
} else {
GenericNumber(self.0.clone()).parse().map(BlockId::Number)
@@ -117,7 +113,6 @@ impl BlockNumberOrHash {
}
}
/// Optional flag for specifying crypto algorithm
#[derive(Debug, StructOpt, Clone)]
pub struct CryptoSchemeFlag {
@@ -16,13 +16,17 @@
// 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 crate::params::node_key_params::NodeKeyParams;
use crate::arg_enums::SyncMode;
use crate::{arg_enums::SyncMode, params::node_key_params::NodeKeyParams};
use sc_network::{
config::{NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig},
config::{
NetworkConfiguration, NodeKeyConfig, NonReservedPeerMode, SetConfig, TransportConfig,
},
multiaddr::Protocol,
};
use sc_service::{ChainSpec, ChainType, config::{Multiaddr, MultiaddrWithPeerId}};
use sc_service::{
config::{Multiaddr, MultiaddrWithPeerId},
ChainSpec, ChainType,
};
use std::{borrow::Cow, path::PathBuf};
use structopt::StructOpt;
@@ -97,11 +101,7 @@ pub struct NetworkParams {
///
/// 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"
)]
#[structopt(long = "max-parallel-downloads", value_name = "COUNT", default_value = "5")]
pub max_parallel_downloads: u32,
#[allow(missing_docs)]
@@ -184,15 +184,16 @@ impl NetworkParams {
let chain_type = chain_spec.chain_type();
// Activate if the user explicitly requested local discovery, `--dev` is given or the
// chain type is `Local`/`Development`
let allow_non_globals_in_dht = self.discover_local
|| is_dev
|| matches!(chain_type, ChainType::Local | ChainType::Development);
let allow_non_globals_in_dht =
self.discover_local ||
is_dev || matches!(chain_type, ChainType::Local | ChainType::Development);
let allow_private_ipv4 = match (self.allow_private_ipv4, self.no_private_ipv4) {
(true, true) => unreachable!("`*_private_ipv4` flags are mutually exclusive; qed"),
(true, false) => true,
(false, true) => false,
(false, false) => is_dev || matches!(chain_type, ChainType::Local | ChainType::Development),
(false, false) =>
is_dev || matches!(chain_type, ChainType::Local | ChainType::Development),
};
NetworkConfiguration {
@@ -16,13 +16,12 @@
// 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_network::{config::identity::ed25519, config::NodeKeyConfig};
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;
use crate::error;
use crate::{arg_enums::NodeKeyType, error};
/// The file name of the node's Ed25519 secret key inside the chain-specific
/// network config directory, if neither `--node-key` nor `--node-key-file`
@@ -103,12 +102,12 @@ impl NodeKeyParams {
sc_network::config::Secret::File(
self.node_key_file
.clone()
.unwrap_or_else(|| net_config_dir.join(NODE_KEY_ED25519_FILE))
.unwrap_or_else(|| net_config_dir.join(NODE_KEY_ED25519_FILE)),
)
};
NodeKeyConfig::Ed25519(secret)
}
},
})
}
}
@@ -120,13 +119,11 @@ fn invalid_node_key(e: impl std::fmt::Display) -> error::Error {
/// Parse a Ed25519 secret key from a hex string into a `sc_network::Secret`.
fn parse_ed25519_secret(hex: &str) -> error::Result<sc_network::config::Ed25519Secret> {
H256::from_str(&hex)
.map_err(invalid_node_key)
.and_then(|bytes| {
ed25519::SecretKey::from_bytes(bytes)
.map(sc_network::config::Secret::Input)
.map_err(invalid_node_key)
})
H256::from_str(&hex).map_err(invalid_node_key).and_then(|bytes| {
ed25519::SecretKey::from_bytes(bytes)
.map(sc_network::config::Secret::Input)
.map_err(invalid_node_key)
})
}
#[cfg(test)]
@@ -151,9 +148,7 @@ mod tests {
params.node_key(net_config_dir).and_then(|c| match c {
NodeKeyConfig::Ed25519(sc_network::config::Secret::Input(ref ski))
if node_key_type == NodeKeyType::Ed25519 && &sk[..] == ski.as_ref() =>
{
Ok(())
}
Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into())),
})
})
@@ -171,14 +166,14 @@ mod tests {
node_key_file: Some(file),
};
let node_key = params.node_key(&PathBuf::from("not-used"))
let node_key = params
.node_key(&PathBuf::from("not-used"))
.expect("Creates node key config")
.into_keypair()
.expect("Creates node key pair");
match node_key {
Keypair::Ed25519(ref pair)
if pair.secret().as_ref() == key.as_ref() => {}
Keypair::Ed25519(ref pair) if pair.secret().as_ref() == key.as_ref() => {},
_ => panic!("Invalid key"),
}
}
@@ -202,11 +197,7 @@ mod tests {
{
NodeKeyType::variants().iter().try_for_each(|t| {
let node_key_type = NodeKeyType::from_str(t).unwrap();
f(NodeKeyParams {
node_key_type,
node_key: None,
node_key_file: None,
})
f(NodeKeyParams { node_key_type, node_key: None, node_key_file: None })
})
}
@@ -214,17 +205,12 @@ mod tests {
with_def_params(|params| {
let dir = PathBuf::from(net_config_dir.clone());
let typ = params.node_key_type;
params
.node_key(net_config_dir)
.and_then(move |c| match c {
NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f))
if typ == NodeKeyType::Ed25519
&& f == &dir.join(NODE_KEY_ED25519_FILE) =>
{
Ok(())
}
_ => Err(error::Error::Input("Unexpected node key config".into())),
})
params.node_key(net_config_dir).and_then(move |c| match c {
NodeKeyConfig::Ed25519(sc_network::config::Secret::File(ref f))
if typ == NodeKeyType::Ed25519 && f == &dir.join(NODE_KEY_ED25519_FILE) =>
Ok(()),
_ => Err(error::Error::Input("Unexpected node key config".into())),
})
})
}
@@ -27,8 +27,7 @@ use sc_network::config::Role;
use sc_service::config::OffchainWorkerConfig;
use structopt::StructOpt;
use crate::error;
use crate::OffchainWorkerEnabled;
use crate::{error, OffchainWorkerEnabled};
/// Offchain worker related parameters.
#[derive(Debug, StructOpt, Clone)]
@@ -49,10 +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"
)]
#[structopt(long = "enable-offchain-indexing", value_name = "ENABLE_OFFCHAIN_INDEXING")]
pub indexing_enabled: bool,
}
@@ -67,9 +63,6 @@ impl OffchainWorkerParams {
};
let indexing_enabled = self.indexing_enabled;
Ok(OffchainWorkerConfig {
enabled,
indexing_enabled,
})
Ok(OffchainWorkerConfig { enabled, indexing_enabled })
}
}
@@ -17,7 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use crate::error;
use sc_service::{PruningMode, Role, KeepBlocks};
use sc_service::{KeepBlocks, PruningMode, Role};
use structopt::StructOpt;
/// Parameters to define the pruning mode
@@ -54,13 +54,13 @@ impl PruningParams {
"Validators should run with state pruning disabled (i.e. archive). \
You can ignore this check with `--unsafe-pruning`."
.to_string(),
));
))
}
PruningMode::keep_blocks(s.parse().map_err(|_| {
error::Error::Input("Invalid pruning mode specified".to_string())
})?)
}
},
})
}
@@ -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 crate::arg_enums::TracingReceiver;
use sc_service::config::BasePath;
use std::path::PathBuf;
use structopt::StructOpt;
use crate::arg_enums::TracingReceiver;
/// Shared parameters used by all `CoreParams`.
#[derive(Debug, StructOpt, Clone)]
@@ -88,13 +88,12 @@ impl SharedParams {
pub fn chain_id(&self, is_dev: bool) -> String {
match self.chain {
Some(ref chain) => chain.clone(),
None => {
None =>
if is_dev {
"dev".into()
} else {
"".into()
}
}
},
}
}
+21 -36
View File
@@ -16,19 +16,13 @@
// 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 crate::CliConfiguration;
use crate::Result;
use crate::SubstrateCli;
use crate::{error::Error as CliError, CliConfiguration, Result, SubstrateCli};
use chrono::prelude::*;
use futures::pin_mut;
use futures::select;
use futures::{future, future::FutureExt, Future};
use futures::{future, future::FutureExt, pin_mut, select, Future};
use log::info;
use sc_service::{Configuration, TaskType, TaskManager};
use sc_service::{Configuration, Error as ServiceError, TaskManager, TaskType};
use sp_utils::metrics::{TOKIO_THREADS_ALIVE, TOKIO_THREADS_TOTAL};
use std::marker::PhantomData;
use sc_service::Error as ServiceError;
use crate::error::Error as CliError;
#[cfg(target_family = "unix")]
async fn main<F, E>(func: F) -> std::result::Result<(), E>
@@ -119,27 +113,19 @@ pub struct Runner<C: SubstrateCli> {
impl<C: SubstrateCli> Runner<C> {
/// Create a new runtime with the command provided in argument
pub fn new<T: CliConfiguration>(
cli: &C,
command: &T,
) -> Result<Runner<C>> {
pub fn new<T: CliConfiguration>(cli: &C, command: &T) -> Result<Runner<C>> {
let tokio_runtime = build_runtime()?;
let runtime_handle = tokio_runtime.handle().clone();
let task_executor = move |fut, task_type| {
match task_type {
TaskType::Async => runtime_handle.spawn(fut).map(drop),
TaskType::Blocking =>
runtime_handle.spawn_blocking(move || futures::executor::block_on(fut))
.map(drop),
}
let task_executor = move |fut, task_type| match task_type {
TaskType::Async => runtime_handle.spawn(fut).map(drop),
TaskType::Blocking => runtime_handle
.spawn_blocking(move || futures::executor::block_on(fut))
.map(drop),
};
Ok(Runner {
config: command.create_configuration(
cli,
task_executor.into(),
)?,
config: command.create_configuration(cli, task_executor.into())?,
tokio_runtime,
phantom: PhantomData,
})
@@ -183,7 +169,7 @@ impl<C: SubstrateCli> Runner<C> {
/// A helper function that runs a command with the configuration of this node.
pub fn sync_run<E>(
self,
runner: impl FnOnce(Configuration) -> std::result::Result<(), E>
runner: impl FnOnce(Configuration) -> std::result::Result<(), E>,
) -> std::result::Result<(), E>
where
E: std::error::Error + Send + Sync + 'static + From<ServiceError>,
@@ -194,7 +180,8 @@ impl<C: SubstrateCli> Runner<C> {
/// A helper function that runs a future with tokio and stops if the process receives
/// the signal `SIGTERM` or `SIGINT`.
pub fn async_run<F, E>(
self, runner: impl FnOnce(Configuration) -> std::result::Result<(F, TaskManager), E>,
self,
runner: impl FnOnce(Configuration) -> std::result::Result<(F, TaskManager), E>,
) -> std::result::Result<(), E>
where
F: Future<Output = std::result::Result<(), E>>,
@@ -219,19 +206,17 @@ impl<C: SubstrateCli> Runner<C> {
pub fn print_node_infos<C: SubstrateCli>(config: &Configuration) {
info!("{}", C::impl_name());
info!("✌️ version {}", C::impl_version());
info!(
"❤️ by {}, {}-{}",
C::author(),
C::copyright_start_year(),
Local::today().year(),
);
info!("❤️ by {}, {}-{}", C::author(), C::copyright_start_year(), Local::today().year(),);
info!("📋 Chain specification: {}", config.chain_spec.name());
info!("🏷 Node name: {}", config.network.node_name);
info!("👤 Role: {}", config.display_role());
info!("💾 Database: {} at {}",
config.database,
config.database.path().map_or_else(|| "<unknown>".to_owned(), |p| p.display().to_string())
info!(
"💾 Database: {} at {}",
config.database,
config
.database
.path()
.map_or_else(|| "<unknown>".to_owned(), |p| p.display().to_string())
);
info!("⛓ Native runtime: {}", C::native_runtime_version(&config.chain_spec));
}