rustfmt ghost client cli and fix typos

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch 2025-07-29 15:02:07 +03:00
parent a74e42369b
commit 767161ac9c
Signed by: str3tch
GPG Key ID: 84F3190747EE79AA
9 changed files with 598 additions and 569 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "ghost-client-cli" name = "ghost-client-cli"
version = "0.1.3" version = "0.1.4"
description = "Ghost CLI interface" description = "Ghost CLI interface"
license.workspace = true license.workspace = true
authors.workspace = true authors.workspace = true

View File

@ -3,13 +3,10 @@
use bip39::Mnemonic; use bip39::Mnemonic;
use clap::Parser; use clap::Parser;
use itertools::Itertools; use itertools::Itertools;
use sc_cli::{ use sc_cli::{with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, OutputTypeFlag};
with_crypto_scheme, KeystoreParams, OutputTypeFlag,
CryptoSchemeFlag, Error,
};
use crate::params::NetworkSchemeFlag;
use crate::commands::utils::print_from_uri; use crate::commands::utils::print_from_uri;
use crate::params::NetworkSchemeFlag;
/// The `generate` command /// The `generate` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]

View File

@ -1,14 +1,13 @@
//! Implementation of the `inspect` subcommand //! Implementation of the `inspect` subcommand
use crate::commands::utils::{print_from_public, print_from_uri};
use crate::params::NetworkSchemeFlag;
use clap::Parser; use clap::Parser;
use sc_cli::{
utils::read_uri, with_crypto_scheme, CryptoSchemeFlag, Error, KeystoreParams, OutputTypeFlag,
};
use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec}; use sp_core::crypto::{ExposeSecret, SecretString, SecretUri, Ss58Codec};
use std::str::FromStr; use std::str::FromStr;
use sc_cli::{
with_crypto_scheme, KeystoreParams, OutputTypeFlag, CryptoSchemeFlag, Error,
utils::read_uri,
};
use crate::params::NetworkSchemeFlag;
use crate::commands::utils::{print_from_public, print_from_uri};
/// The `inspect` command /// The `inspect` command
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
@ -236,8 +235,16 @@ mod tests {
array_bytes::bytes2hex("0x", valid_public_with_password_and_derivation.as_slice()); array_bytes::bytes2hex("0x", valid_public_with_password_and_derivation.as_slice());
// They should still be valid, because we check the base secret key. // They should still be valid, because we check the base secret key.
check_cmd(&seed_with_password_and_derivation, &valid_public_hex_with_password, true); check_cmd(
check_cmd(&seed_with_password_and_derivation, &valid_accountid_with_password, true); &seed_with_password_and_derivation,
&valid_public_hex_with_password,
true,
);
check_cmd(
&seed_with_password_and_derivation,
&valid_accountid_with_password,
true,
);
// And these should be invalid. // And these should be invalid.
check_cmd(&seed_with_password_and_derivation, &valid_public_hex, false); check_cmd(&seed_with_password_and_derivation, &valid_public_hex, false);

View File

@ -1,10 +1,7 @@
//! Key related CLI utilities //! Key related CLI utilities
use super::{generate::GenerateCmd, inspect_key::InspectKeyCmd}; use super::{generate::GenerateCmd, inspect_key::InspectKeyCmd};
use sc_cli::{ use sc_cli::{Error, GenerateKeyCmdCommon, InsertKeyCmd, InspectNodeKeyCmd, SubstrateCli};
GenerateKeyCmdCommon, InsertKeyCmd, InspectNodeKeyCmd, Error,
SubstrateCli,
};
/// Key utilities for the cli. /// Key utilities for the cli.
#[derive(Debug, clap::Subcommand)] #[derive(Debug, clap::Subcommand)]

View File

@ -1,11 +1,13 @@
mod key;
mod generate; mod generate;
mod vanity;
mod inspect_key; mod inspect_key;
mod key;
mod utils; mod utils;
mod vanity;
pub use self::{ pub use self::{
key::KeySubcommand, vanity::VanityCmd, inspect_key::InspectKeyCmd,
generate::GenerateCmd, generate::GenerateCmd,
utils::{unwrap_or_default_ss58_name, print_from_uri, print_from_public}, inspect_key::InspectKeyCmd,
key::KeySubcommand,
utils::{print_from_public, print_from_uri, unwrap_or_default_ss58_name},
vanity::VanityCmd,
}; };

View File

@ -1,16 +1,15 @@
use serde_json::json;
use sc_cli::{ use sc_cli::{
OutputType,
utils::{PublicFor, SeedFor}, utils::{PublicFor, SeedFor},
OutputType,
}; };
use sp_runtime::{traits::IdentifyAccount, MultiSigner}; use serde_json::json;
use sp_core::{ use sp_core::{
crypto::{ crypto::{
unwrap_or_default_ss58_version, unwrap_or_default_ss58_version, ExposeSecret, SecretString, Ss58AddressFormat, Ss58Codec,
Ss58Codec, ExposeSecret, Ss58AddressFormat, SecretString,
}, },
hexdisplay::HexDisplay, hexdisplay::HexDisplay,
}; };
use sp_runtime::{traits::IdentifyAccount, MultiSigner};
pub fn print_from_uri<Pair>( pub fn print_from_uri<Pair>(
uri: &str, uri: &str,
@ -43,7 +42,7 @@ pub fn print_from_uri<Pair>(
"{}", "{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed") serde_json::to_string_pretty(&json).expect("Json pretty print failed")
); );
}, }
OutputType::Text => { OutputType::Text => {
println!( println!(
"Secret phrase: {}\n \ "Secret phrase: {}\n \
@ -59,9 +58,12 @@ pub fn print_from_uri<Pair>(
format_public_key::<Pair>(public_key.clone()), format_public_key::<Pair>(public_key.clone()),
format_account_id::<Pair>(public_key.clone()), format_account_id::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
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) { } else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password) {
let public_key = pair.public(); let public_key = pair.public();
@ -82,7 +84,7 @@ pub fn print_from_uri<Pair>(
"{}", "{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed") serde_json::to_string_pretty(&json).expect("Json pretty print failed")
); );
}, }
OutputType::Text => { OutputType::Text => {
println!( println!(
"Secret Key URI `{}` is account:\n \ "Secret Key URI `{}` is account:\n \
@ -94,13 +96,20 @@ pub fn print_from_uri<Pair>(
SS58 Address: {}", SS58 Address: {}",
uri, uri,
network_id, network_id,
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()), format_public_key::<Pair>(public_key.clone()),
format_account_id::<Pair>(public_key.clone()), format_account_id::<Pair>(public_key.clone()),
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
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) { } else if let Ok((public_key, network)) = Pair::Public::from_string_with_version(uri) {
let network_override = network_override.unwrap_or(network); let network_override = network_override.unwrap_or(network);
@ -120,7 +129,7 @@ pub fn print_from_uri<Pair>(
"{}", "{}",
serde_json::to_string_pretty(&json).expect("Json pretty print failed") serde_json::to_string_pretty(&json).expect("Json pretty print failed")
); );
}, }
OutputType::Text => { OutputType::Text => {
println!( println!(
"Public Key URI `{}` is account:\n \ "Public Key URI `{}` is account:\n \
@ -136,7 +145,7 @@ pub fn print_from_uri<Pair>(
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
); );
}, }
} }
} else { } else {
println!("Invalid phrase/URI given"); println!("Invalid phrase/URI given");
@ -170,8 +179,11 @@ where
"ss58Address": public_key.to_ss58check_with_version(network_override), "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 => { OutputType::Text => {
println!( println!(
"Network ID/Version: {}\n \ "Network ID/Version: {}\n \
@ -185,7 +197,7 @@ where
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
public_key.to_ss58check_with_version(network_override), public_key.to_ss58check_with_version(network_override),
); );
}, }
} }
Ok(()) Ok(())
@ -216,5 +228,8 @@ fn format_account_id<P: sp_core::Pair>(public_key: PublicFor<P>) -> String
where where
PublicFor<P>: Into<MultiSigner>, 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())
)
} }

View File

@ -2,21 +2,19 @@
use clap::Parser; use clap::Parser;
use rand::{rngs::OsRng, RngCore}; use rand::{rngs::OsRng, RngCore};
use sp_core::crypto::{ use sc_cli::{utils::format_seed, with_crypto_scheme, CryptoSchemeFlag, Error, OutputTypeFlag};
unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec, use sp_core::crypto::{unwrap_or_default_ss58_version, Ss58AddressFormat, Ss58Codec};
};
use sp_runtime::traits::IdentifyAccount; use sp_runtime::traits::IdentifyAccount;
use sc_cli::{
with_crypto_scheme, Error, OutputTypeFlag, CryptoSchemeFlag,
utils::format_seed,
};
use crate::commands::utils::print_from_uri; use crate::commands::utils::print_from_uri;
use crate::params::NetworkSchemeFlag; use crate::params::NetworkSchemeFlag;
/// The `vanity` command /// The `vanity` command
#[derive(Debug, Clone, Parser)] #[derive(Debug, Clone, Parser)]
#[command(name = "vanity", about = "Generate a seed that provides a vanity address")] #[command(
name = "vanity",
about = "Generate a seed that provides a vanity address"
)]
pub struct VanityCmd { pub struct VanityCmd {
/// Desired pattern /// Desired pattern
#[arg(long, value_parser = assert_non_empty_string)] #[arg(long, value_parser = assert_non_empty_string)]
@ -84,14 +82,17 @@ where
} }
let p = Pair::from_seed(&seed); let p = Pair::from_seed(&seed);
let ss58 = p.public().into_account().to_ss58check_with_version(network_override); let ss58 = p
.public()
.into_account()
.to_ss58check_with_version(network_override);
println!("{:?}", ss58); println!("{:?}", ss58);
let score = calculate_score(desired, &ss58); let score = calculate_score(desired, &ss58);
if score > best || desired.len() < 2 { if score > best || desired.len() < 2 {
best = score; best = score;
if best >= top { if best >= top {
println!("best: {} == top: {}", best, top); println!("best: {} == top: {}", best, top);
return Ok(format_seed::<Pair>(seed.clone())) return Ok(format_seed::<Pair>(seed.clone()));
} }
} }
done += 1; done += 1;
@ -116,11 +117,11 @@ fn next_seed(seed: &mut [u8]) {
match s { match s {
255 => { 255 => {
*s = 0; *s = 0;
}, }
_ => { _ => {
*s += 1; *s += 1;
break break;
}, }
} }
} }
} }
@ -132,7 +133,7 @@ fn calculate_score(_desired: &str, key: &str) -> usize {
let snip_size = _desired.len() - truncate; let snip_size = _desired.len() - truncate;
let truncated = &_desired[0..snip_size]; let truncated = &_desired[0..snip_size];
if let Some(pos) = key.find(truncated) { if let Some(pos) = key.find(truncated) {
return (47 - pos) + (snip_size * 48) return (47 - pos) + (snip_size * 48);
} }
} }
0 0
@ -164,11 +165,13 @@ mod tests {
#[test] #[test]
fn test_generation_with_single_char() { fn test_generation_with_single_char() {
let seed = generate_key::<sr25519::Pair>("ab", default_ss58_version()).unwrap(); let seed = generate_key::<sr25519::Pair>("ab", default_ss58_version()).unwrap();
assert!(sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed)) assert!(
sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed))
.unwrap() .unwrap()
.public() .public()
.to_ss58check() .to_ss58check()
.contains("ab")); .contains("ab")
);
} }
#[test] #[test]
@ -176,11 +179,13 @@ mod tests {
let seed = let seed =
generate_key::<sr25519::Pair>("ab", Ss58AddressFormatRegistry::PolkadotAccount.into()) generate_key::<sr25519::Pair>("ab", Ss58AddressFormatRegistry::PolkadotAccount.into())
.unwrap(); .unwrap();
assert!(sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed)) assert!(
sr25519::Pair::from_seed_slice(&array_bytes::hex2bytes_unchecked(&seed))
.unwrap() .unwrap()
.public() .public()
.to_ss58check_with_version(Ss58AddressFormatRegistry::PolkadotAccount.into()) .to_ss58check_with_version(Ss58AddressFormatRegistry::PolkadotAccount.into())
.contains("ab")); .contains("ab")
);
} }
#[test] #[test]

View File

@ -1,5 +1,5 @@
pub mod params;
pub mod commands; pub mod commands;
pub mod params;
pub use commands::KeySubcommand; pub use commands::KeySubcommand;
pub use commands::VanityCmd; pub use commands::VanityCmd;

View File

@ -21,15 +21,21 @@ pub struct InnerSs58AddressFormat(Ss58AddressFormat);
impl InnerSs58AddressFormat { impl InnerSs58AddressFormat {
#[inline] #[inline]
pub fn custom(prefix: u16) -> Self { pub fn custom(prefix: u16) -> Self {
Self { 0: Ss58AddressFormat::custom(prefix) } Self {
0: Ss58AddressFormat::custom(prefix),
}
} }
} }
impl std::fmt::Display for InnerSs58AddressFormat { impl std::fmt::Display for InnerSs58AddressFormat {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{} network", ALL_POSSIBLE_IDS write!(
f,
"{} network",
ALL_POSSIBLE_IDS
.binary_search(&u16::from(self.0)) .binary_search(&u16::from(self.0))
.expect("always be found")) .expect("always be found")
)
} }
} }
@ -44,13 +50,13 @@ impl<'a>TryFrom<&'a str> for InnerSs58AddressFormat {
} }
} }
pub fn parse_s58_prefix_address_format(x: &str,) -> Result<Ss58AddressFormat, String> { pub fn parse_s58_prefix_address_format(x: &str) -> Result<Ss58AddressFormat, String> {
match InnerSs58AddressFormat::try_from(x) { match InnerSs58AddressFormat::try_from(x) {
Ok(format_registry) => Ok(format_registry.0.into()), Ok(format_registry) => Ok(format_registry.0.into()),
Err(_) => Err(format!( Err(_) => Err(format!(
"Unable to parse variant. Known variants: {:?}", "Unable to parse variant. Known variants: {:?}",
&ALL_POSSIBLE_NAMES &ALL_POSSIBLE_NAMES
)) )),
} }
} }