mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-27 04:37:57 +00:00
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:
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user