From 027f0655afb6602412c729cabdd95d3d5bad53e3 Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Wed, 12 Mar 2025 16:58:42 +0100 Subject: [PATCH 1/6] feat: Can choose between ed25519 ans sr25519 --- src/commands/vault.rs | 122 +++++++++++++++---------- src/commands/vault/display.rs | 105 +++++++++++++++++++-- src/keys.rs | 167 ++++++++++++++++++++++------------ 3 files changed, 278 insertions(+), 116 deletions(-) diff --git a/src/commands/vault.rs b/src/commands/vault.rs index 8d6de10..a4e3594 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -41,14 +41,18 @@ pub enum Subcommand { /// Secret key format (substrate, seed, g1v1) #[clap(short = 'S', long, required = false, default_value = SecretFormat::Substrate)] secret_format: SecretFormat, + + /// Crypto scheme to use (sr25519, ed25519) + #[clap(short = 'c', long, required = false, default_value = CryptoScheme::Ed25519)] + crypto_scheme: CryptoScheme, }, /// Add a derivation to an existing SS58 Address #[clap(long_about = "Add a derivation to an existing SS58 Address.\n\ \n\ - Only \"sr25519\" crypto scheme is supported for derivations.\n\ + Both \"sr25519\" and \"ed25519\" crypto schemes are supported \n\ Use command `vault list base` to see available <Base> account and their crypto scheme\n\ - And then use command 'vault list for' to find all accounts linked to that <Base> account.")] + And then use command 'vault list for' to find all accounts linked to that <Base> account")] #[clap(alias = "deriv")] #[clap(alias = "derivation")] Derive { @@ -87,18 +91,35 @@ pub enum Subcommand { Where, } -#[derive(Clone, Default, Debug, clap::Parser)] +#[derive(Clone, Debug, clap::Parser)] pub enum ListChoice { /// List all <Base> SS58 Addresses and their linked derivations in the vault - #[default] - All, + All { + /// Show G1v1 public keys + #[clap(long, default_value = "false")] + show_g1v1: bool, + }, /// List <Base> and Derivation SS58 Addresses linked to the selected one For { #[clap(flatten)] address_or_vault_name: AddressOrVaultNameGroup, + + /// Show G1v1 public keys + #[clap(long, default_value = "false")] + show_g1v1: bool, }, /// List all <Base> SS58 Addresses in the vault - Base, + Base { + /// Show G1v1 public keys + #[clap(long, default_value = "false")] + show_g1v1: bool, + }, +} + +impl Default for ListChoice { + fn default() -> Self { + ListChoice::All { show_g1v1: false } + } } #[derive(Debug, clap::Args, Clone)] @@ -151,26 +172,27 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE // match subcommand match command { Subcommand::List(choice) => match choice { - ListChoice::All => { + ListChoice::All { show_g1v1 } => { let all_account_tree_node_hierarchies = vault_account::fetch_all_base_account_tree_node_hierarchies(db).await?; - let table = - display::compute_vault_accounts_table(&all_account_tree_node_hierarchies)?; + + let table = display::compute_vault_accounts_table_with_g1v1(&all_account_tree_node_hierarchies, show_g1v1)?; println!("available SS58 Addresses:"); println!("{table}"); } - ListChoice::Base => { + ListChoice::Base { show_g1v1 } => { let base_account_tree_nodes = vault_account::fetch_only_base_account_tree_nodes(db).await?; - let table = display::compute_vault_accounts_table(&base_account_tree_nodes)?; + let table = display::compute_vault_accounts_table_with_g1v1(&base_account_tree_nodes, show_g1v1)?; println!("available <Base> SS58 Addresses:"); println!("{table}"); } ListChoice::For { address_or_vault_name, + show_g1v1, } => { let account_tree_node = retrieve_account_tree_node(db, address_or_vault_name).await?; @@ -178,7 +200,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let base_account_tree_node = vault_account::get_base_account_tree_node(&account_tree_node); - let table = display::compute_vault_accounts_table(&[base_account_tree_node])?; + let table = display::compute_vault_accounts_table_with_g1v1(&[base_account_tree_node], show_g1v1)?; println!( "available SS58 Addresses linked to {}:", @@ -215,9 +237,9 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let mnemonic = bip39::Mnemonic::generate(12).unwrap(); println!("{mnemonic}"); } - Subcommand::Import { secret_format } => { + Subcommand::Import { secret_format, crypto_scheme } => { let vault_data_for_import = - prompt_secret_and_compute_vault_data_to_import(secret_format)?; + prompt_secret_and_compute_vault_data_to_import(secret_format, crypto_scheme)?; //Extra check for SecretFormat::G1v1 (old cesium) - showing the G1v1 cesium public key for confirmation if secret_format == SecretFormat::G1v1 { @@ -235,7 +257,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE println!(); let _account = - create_base_account_for_vault_data_to_import(&txn, &vault_data_for_import, None) + create_base_account_for_vault_data_to_import(&txn, &vault_data_for_import, None, Some(crypto_scheme)) .await?; txn.commit().await?; @@ -255,25 +277,6 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let base_account = &base_account_tree_node.borrow().account.clone(); - if base_account.crypto_scheme.is_none() { - return Err(GcliError::DatabaseError(DbErr::Custom(format!("Crypto scheme is not set for the base account:{base_account} - should never happen")))); - } - - if let Some(crypto_scheme) = base_account.crypto_scheme { - if CryptoScheme::from(crypto_scheme) == CryptoScheme::Ed25519 { - println!( - "Only \"{}\" crypto scheme is supported for derivations.", - Into::<&str>::into(CryptoScheme::Sr25519), - ); - println!(); - println!( - "Use command `vault list base` to see available <Base> account and their crypto scheme\n\ - And then use command 'vault list for' to find all accounts linked to that <Base> account" - ); - return Ok(()); - } - } - println!("Adding derivation to: {account_to_derive}"); let base_parent_hierarchy_account_tree_node_to_derive = @@ -307,8 +310,12 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let derivation_secret_suri = format!("{account_to_derive_secret_suri}{derivation_path}"); + let crypto_scheme = base_account.crypto_scheme + .map(CryptoScheme::from) + .unwrap_or(CryptoScheme::Ed25519); // Fallback to Ed25519 if not defined (should never happen) + let derivation_keypair = - compute_keypair(CryptoScheme::Sr25519, &derivation_secret_suri)?; + compute_keypair(crypto_scheme, &derivation_secret_suri)?; let derivation_address: String = derivation_keypair.address().to_string(); @@ -468,6 +475,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE &txn, &vault_data_to_import, Some(&vault_data_from_file.password), + None, ) .await; @@ -539,12 +547,24 @@ pub fn parse_prefix_and_derivation_path_from_suri( Ok((address_uri.phrase.map(|s| s.to_string()), full_path)) } -fn map_secret_format_to_crypto_scheme(secret_format: SecretFormat) -> CryptoScheme { - match secret_format { - SecretFormat::Seed => CryptoScheme::Sr25519, - SecretFormat::Substrate => CryptoScheme::Sr25519, - SecretFormat::Predefined => CryptoScheme::Sr25519, - SecretFormat::G1v1 => CryptoScheme::Ed25519, +fn map_secret_format_to_crypto_scheme(secret_format: SecretFormat, override_crypto_scheme: Option<CryptoScheme>) -> CryptoScheme { + // If a crypto_scheme is explicitly specified, use it except for G1v1 which must always use Ed25519 + if let Some(scheme) = override_crypto_scheme { + if secret_format == SecretFormat::G1v1 { + // G1v1 must always use Ed25519 + CryptoScheme::Ed25519 + } else { + scheme + } + } else { + // Default behavior if no crypto_scheme is specified + match secret_format { + // All formats use Ed25519 by default + SecretFormat::Seed => CryptoScheme::Ed25519, + SecretFormat::Substrate => CryptoScheme::Ed25519, + SecretFormat::Predefined => CryptoScheme::Ed25519, + SecretFormat::G1v1 => CryptoScheme::Ed25519, + } } } @@ -675,13 +695,14 @@ where fn create_vault_data_to_import<F, P>( secret_format: SecretFormat, + crypto_scheme: CryptoScheme, prompt_fn: F, ) -> Result<VaultDataToImport, GcliError> where - F: Fn() -> (String, P), + F: Fn(CryptoScheme) -> (String, P), P: Into<KeyPair>, { - let (secret, pair) = prompt_fn(); + let (secret, pair) = prompt_fn(crypto_scheme); let key_pair = pair.into(); Ok(VaultDataToImport { secret_format, @@ -692,19 +713,21 @@ where fn prompt_secret_and_compute_vault_data_to_import( secret_format: SecretFormat, + crypto_scheme: CryptoScheme, ) -> Result<VaultDataToImport, GcliError> { match secret_format { SecretFormat::Substrate => { - create_vault_data_to_import(secret_format, prompt_secret_substrate_and_compute_keypair) + create_vault_data_to_import(secret_format, crypto_scheme, prompt_secret_substrate_and_compute_keypair) } SecretFormat::Seed => { - create_vault_data_to_import(secret_format, prompt_seed_and_compute_keypair) + create_vault_data_to_import(secret_format, crypto_scheme, prompt_seed_and_compute_keypair) } SecretFormat::G1v1 => { - create_vault_data_to_import(secret_format, prompt_secret_cesium_and_compute_keypair) + // G1v1 always uses Ed25519, ignore crypto_scheme + create_vault_data_to_import(secret_format, CryptoScheme::Ed25519, prompt_secret_cesium_and_compute_keypair) } SecretFormat::Predefined => { - create_vault_data_to_import(secret_format, prompt_predefined_and_compute_keypair) + create_vault_data_to_import(secret_format, crypto_scheme, prompt_predefined_and_compute_keypair) } } } @@ -720,6 +743,7 @@ pub async fn create_base_account_for_vault_data_to_import<C>( db_tx: &C, vault_data: &VaultDataToImport, password: Option<&String>, + crypto_scheme: Option<CryptoScheme>, ) -> Result<vault_account::Model, GcliError> where C: ConnectionTrait, @@ -793,7 +817,7 @@ where vault_account.path = Set(None); vault_account.parent = Set(None); vault_account.crypto_scheme = Set(Some( - map_secret_format_to_crypto_scheme(vault_data.secret_format).into(), + map_secret_format_to_crypto_scheme(vault_data.secret_format, crypto_scheme).into(), )); vault_account.encrypted_suri = Set(Some(encrypted_suri)); vault_account.name = Set(name.clone()); @@ -816,7 +840,7 @@ where println!("(Optional) Enter a name for the vault entry"); let name = inputs::prompt_vault_name_and_check_availability(db_tx, None).await?; - let crypto_scheme = map_secret_format_to_crypto_scheme(secret_format); + let crypto_scheme = map_secret_format_to_crypto_scheme(secret_format, crypto_scheme); let base_account = vault_account::create_base_account( db_tx, diff --git a/src/commands/vault/display.rs b/src/commands/vault/display.rs index 021a84f..e9a9d2d 100644 --- a/src/commands/vault/display.rs +++ b/src/commands/vault/display.rs @@ -25,18 +25,26 @@ pub fn compute_vault_key_files_table(vault_key_addresses: &[String]) -> Result<T pub fn compute_vault_accounts_table( account_tree_nodes: &[Rc<RefCell<AccountTreeNode>>], +) -> Result<Table, GcliError> { + // Appel to the new function with show_g1v1 = true to maintain compatibility + compute_vault_accounts_table_with_g1v1(account_tree_nodes, true) +} + +pub fn compute_vault_accounts_table_with_g1v1( + account_tree_nodes: &[Rc<RefCell<AccountTreeNode>>], + show_g1v1: bool, ) -> Result<Table, GcliError> { let mut table = Table::new(); table.load_preset(comfy_table::presets::UTF8_BORDERS_ONLY); table.set_header(vec![ - "SS58 Address/G1v1 public key", + if show_g1v1 { "SS58 Address/G1v1 public key" } else { "SS58 Address" }, "Crypto", "Path", "Name", ]); for account_tree_node in account_tree_nodes { - let _ = add_account_tree_node_to_table(&mut table, account_tree_node); + let _ = add_account_tree_node_to_table_with_g1v1(&mut table, account_tree_node, show_g1v1); } Ok(table) @@ -46,13 +54,22 @@ fn add_account_tree_node_to_table( table: &mut Table, account_tree_node: &Rc<RefCell<AccountTreeNode>>, ) -> Result<(), GcliError> { - let rows = compute_vault_accounts_row(account_tree_node)?; + // Appel to the new function with show_g1v1 = true to maintain compatibility + add_account_tree_node_to_table_with_g1v1(table, account_tree_node, true) +} + +fn add_account_tree_node_to_table_with_g1v1( + table: &mut Table, + account_tree_node: &Rc<RefCell<AccountTreeNode>>, + show_g1v1: bool, +) -> Result<(), GcliError> { + let rows = compute_vault_accounts_row_with_g1v1(account_tree_node, show_g1v1)?; rows.iter().for_each(|row| { table.add_row(row.clone()); }); for child in &account_tree_node.borrow().children { - let _ = add_account_tree_node_to_table(table, child); + let _ = add_account_tree_node_to_table_with_g1v1(table, child, show_g1v1); } Ok(()) @@ -63,6 +80,17 @@ fn add_account_tree_node_to_table( /// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key pub fn compute_vault_accounts_row( account_tree_node: &Rc<RefCell<AccountTreeNode>>, +) -> Result<Vec<Vec<Cell>>, GcliError> { + // Appel to the new function with show_g1v1 = true to maintain compatibility + compute_vault_accounts_row_with_g1v1(account_tree_node, true) +} + +/// Computes one or more row of the table for selected account_tree_node +/// +/// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key if show_g1v1 is true +pub fn compute_vault_accounts_row_with_g1v1( + account_tree_node: &Rc<RefCell<AccountTreeNode>>, + show_g1v1: bool, ) -> Result<Vec<Vec<Cell>>, GcliError> { let empty_string = "".to_string(); @@ -93,9 +121,14 @@ pub fn compute_vault_accounts_row( (path, empty_string.clone()) } else { let crypto_scheme = CryptoScheme::from(account_tree_node.account.crypto_scheme.unwrap()); - - // Adding 2nd row for G1v1 public key - if CryptoScheme::Ed25519 == crypto_scheme { + let crypto_scheme_str: &str = crypto_scheme.into(); + + // Check if it's an ed25519 key (for G1v1, we always use Ed25519) + // We don't have access to the secret_format field, so we rely only on the crypto_scheme + let is_ed25519 = crypto_scheme == CryptoScheme::Ed25519; + + // Adding 2nd row for G1v1 public key only if show_g1v1 is true and it's an Ed25519 key + if show_g1v1 && is_ed25519 { rows.push(vec![Cell::new(format!( "â”” G1v1: {}", cesium::compute_g1v1_public_key_from_ed25519_account_id( @@ -104,7 +137,6 @@ pub fn compute_vault_accounts_row( ))]); } - let crypto_scheme_str: &str = crypto_scheme.into(); ( format!("<{}>", account_tree_node.account.account_type()), crypto_scheme_str.to_string(), @@ -128,12 +160,13 @@ pub fn compute_vault_accounts_row( #[cfg(test)] mod tests { mod vault_accounts_table_tests { - use crate::commands::vault::display::compute_vault_accounts_table; + use crate::commands::vault::display::{compute_vault_accounts_table, compute_vault_accounts_table_with_g1v1}; use crate::entities::vault_account::tests::account_tree_node_tests::{ mother_account_tree_node, mother_g1v1_account_tree_node, }; use indoc::indoc; + // Tests for compute_vault_accounts_table (old function) #[test] fn test_compute_vault_accounts_table_empty() { let table = compute_vault_accounts_table(&[]).unwrap(); @@ -191,5 +224,59 @@ mod tests { assert_eq!(table.to_string(), expected_table); } + + // Tests for compute_vault_accounts_table_with_g1v1 + #[test] + fn test_compute_vault_accounts_table_with_g1v1_empty() { + // Test with show_g1v1 = true (default behavior) + let table = compute_vault_accounts_table_with_g1v1(&[], true).unwrap(); + println!("Table with show_g1v1=true:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + + // Test with show_g1v1 = false + let table = compute_vault_accounts_table_with_g1v1(&[], false).unwrap(); + println!("Table with show_g1v1=false:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + } + + #[test] + fn test_compute_vault_accounts_table_with_g1v1() { + let account_tree_node = mother_account_tree_node(); + let g1v1_account_tree_node = mother_g1v1_account_tree_node(); + let account_tree_nodes = vec![account_tree_node, g1v1_account_tree_node]; + + // Test with show_g1v1 = true (default behavior) + let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + println!("Table with show_g1v1=true:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + + // Test with show_g1v1 = false + let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + println!("Table with show_g1v1=false:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + } + + #[test] + fn test_compute_vault_accounts_table_with_g1v1_partial() { + let mother = mother_account_tree_node(); + let child1 = mother.borrow().children[0].clone(); + let account_tree_nodes = vec![child1]; + + // Test with show_g1v1 = true (default behavior) + let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + println!("Table with show_g1v1=true:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + + // Test with show_g1v1 = false + let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + println!("Table with show_g1v1=false:\n{}", table.to_string()); + let expected_table = table.to_string(); + assert_eq!(table.to_string(), expected_table); + } } } diff --git a/src/keys.rs b/src/keys.rs index 7b7babd..a81f2bf 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -139,7 +139,7 @@ pub fn get_keypair( ) -> Result<KeyPair, GcliError> { match (secret_format, secret) { (SecretFormat::Predefined, Some(deriv)) => pair_from_predefined(deriv).map(|v| v.into()), - (secret_format, None) => Ok(prompt_secret(secret_format)), + (secret_format, None) => Ok(prompt_secret(secret_format, None)), (_, Some(secret)) => Ok(pair_from_secret(secret_format, secret)?.into()), } } @@ -214,79 +214,130 @@ pub fn seed_from_cesium(id: &str, pwd: &str) -> [u8; 32] { /// ask user to input a secret pub fn prompt_secret_substrate() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - prompt_secret_substrate_and_compute_keypair().1 -} - -pub fn prompt_secret_substrate_and_compute_keypair() -> (String, sr25519::Pair) { - loop { - println!("Substrate URI can be a mnemonic or a mini-secret ('0x' prefixed seed) together with optional derivation path"); - let substrate_suri = inputs::prompt_password_query("Substrate URI: ").unwrap(); - match pair_from_sr25519_str(&substrate_suri) { - Ok(pair) => return (substrate_suri, pair), - Err(_) => println!("Invalid secret"), - } - } + // Only interested in the keypair which is the second element of the tuple + match prompt_secret_substrate_and_compute_keypair(CryptoScheme::Sr25519).1 { + KeyPair::Sr25519(pair) => pair, + _ => panic!("Expected Sr25519 keypair"), + } +} + +pub fn prompt_secret_substrate_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { + loop { + println!("Substrate URI can be a mnemonic or a mini-secret ('0x' prefixed seed) together with optional derivation path"); + let substrate_suri = inputs::prompt_password_query("Substrate URI: ").unwrap(); + match crypto_scheme { + CryptoScheme::Sr25519 => { + match pair_from_sr25519_str(&substrate_suri) { + Ok(pair) => return (substrate_suri, pair.into()), + Err(_) => println!("Invalid secret"), + } + }, + CryptoScheme::Ed25519 => { + match pair_from_ed25519_str(&substrate_suri) { + Ok(pair) => return (substrate_suri, pair.into()), + Err(_) => println!("Invalid secret"), + } + } + } + } } /// ask user pass (Cesium format) pub fn prompt_secret_cesium() -> ed25519::Pair { - // Only interested in the keypair which is the second element of the tuple - prompt_secret_cesium_and_compute_keypair().1 + // Only interested in the keypair which is the second element of the tuple + match prompt_secret_cesium_and_compute_keypair(CryptoScheme::Ed25519).1 { + KeyPair::Ed25519(pair) => pair, + _ => panic!("Expected Ed25519 keypair"), + } } -pub fn prompt_secret_cesium_and_compute_keypair() -> (String, ed25519::Pair) { - let id = inputs::prompt_password_query("G1v1 id: ").unwrap(); - let pwd = inputs::prompt_password_query("G1v1 password: ").unwrap(); +pub fn prompt_secret_cesium_and_compute_keypair(_crypto_scheme: CryptoScheme) -> (String, KeyPair) { + let id = inputs::prompt_password_query("G1v1 id: ").unwrap(); + let pwd = inputs::prompt_password_query("G1v1 password: ").unwrap(); - let seed = seed_from_cesium(&id, &pwd); - let secret_suri = format!("0x{}", hex::encode(seed)); + let seed = seed_from_cesium(&id, &pwd); + let secret_suri = format!("0x{}", hex::encode(seed)); - match pair_from_ed25519_str(&secret_suri) { - Ok(pair) => (secret_suri, pair), - Err(_) => panic!("Could not compute KeyPair from G1v1 id/pwd"), - } + // G1v1 always uses Ed25519, ignore crypto_scheme + match pair_from_ed25519_str(&secret_suri) { + Ok(pair) => (secret_suri, pair.into()), + Err(_) => panic!("Could not compute KeyPair from G1v1 id/pwd"), + } } /// ask user to input a seed pub fn prompt_seed() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - prompt_seed_and_compute_keypair().1 -} - -pub fn prompt_seed_and_compute_keypair() -> (String, sr25519::Pair) { - loop { - let seed_str = inputs::prompt_seed().unwrap(); - let secret_suri = format!("0x{}", seed_str); - - match pair_from_sr25519_str(&secret_suri) { - Ok(pair) => return (secret_suri, pair), - Err(_) => println!("Invalid seed"), - } - } + // Only interested in the keypair which is the second element of the tuple + match prompt_seed_and_compute_keypair(CryptoScheme::Sr25519).1 { + KeyPair::Sr25519(pair) => pair, + _ => panic!("Expected Sr25519 keypair"), + } +} + +pub fn prompt_seed_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { + loop { + let seed_str = inputs::prompt_seed().unwrap(); + let secret_suri = format!("0x{}", seed_str); + + match crypto_scheme { + CryptoScheme::Sr25519 => { + match pair_from_sr25519_str(&secret_suri) { + Ok(pair) => return (secret_suri, pair.into()), + Err(_) => println!("Invalid seed"), + } + }, + CryptoScheme::Ed25519 => { + match pair_from_ed25519_str(&secret_suri) { + Ok(pair) => return (secret_suri, pair.into()), + Err(_) => println!("Invalid seed"), + } + } + } + } } /// ask user pass (Cesium format) pub fn prompt_predefined() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - prompt_predefined_and_compute_keypair().1 -} - -pub fn prompt_predefined_and_compute_keypair() -> (String, sr25519::Pair) { - let deriv = inputs::prompt_password_query("Enter derivation path: ").unwrap(); - ( - predefined_mnemonic(&deriv), - pair_from_predefined(&deriv).expect("invalid secret"), - ) -} - -/// ask user secret in relevant format -pub fn prompt_secret(secret_format: SecretFormat) -> KeyPair { + // Only interested in the keypair which is the second element of the tuple + match prompt_predefined_and_compute_keypair(CryptoScheme::Sr25519).1 { + KeyPair::Sr25519(pair) => pair, + _ => panic!("Expected Sr25519 keypair"), + } +} + +pub fn prompt_predefined_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { + let deriv = inputs::prompt_password_query("Enter derivation path: ").unwrap(); + let mnemonic = predefined_mnemonic(&deriv); + + match crypto_scheme { + CryptoScheme::Sr25519 => { + match pair_from_sr25519_str(&mnemonic) { + Ok(pair) => (mnemonic, pair.into()), + Err(e) => panic!("Invalid secret: {}", e), + } + }, + CryptoScheme::Ed25519 => { + match pair_from_ed25519_str(&mnemonic) { + Ok(pair) => (mnemonic, pair.into()), + Err(e) => panic!("Invalid secret: {}", e), + } + } + } +} + +pub fn prompt_secret(secret_format: SecretFormat, crypto_scheme: Option<CryptoScheme>) -> KeyPair { + let default_scheme = match secret_format { + SecretFormat::G1v1 => CryptoScheme::Ed25519, // G1v1 always uses Ed25519 + _ => CryptoScheme::Ed25519, // All formats use Ed25519 by default + }; + + let scheme = crypto_scheme.unwrap_or(default_scheme); + match secret_format { - SecretFormat::Substrate => prompt_secret_substrate().into(), - SecretFormat::G1v1 => prompt_secret_cesium().into(), - SecretFormat::Seed => prompt_seed().into(), - SecretFormat::Predefined => prompt_predefined().into(), + SecretFormat::Substrate => prompt_secret_substrate_and_compute_keypair(scheme).1, + SecretFormat::G1v1 => prompt_secret_cesium_and_compute_keypair(CryptoScheme::Ed25519).1, // G1v1 always uses Ed25519 + SecretFormat::Seed => prompt_seed_and_compute_keypair(scheme).1, + SecretFormat::Predefined => prompt_predefined_and_compute_keypair(scheme).1, } } @@ -309,7 +360,7 @@ pub async fn fetch_or_get_keypair( } // at the moment, there is no way to confg gcli to use an other kind of secret // without telling explicitly each time - Ok(prompt_secret(SecretFormat::Substrate)) + Ok(prompt_secret(SecretFormat::Substrate, None)) } // catch known addresses -- GitLab From 28e8ba8d7ee19def1a2c7cfa88ac5d65d561d349 Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Thu, 13 Mar 2025 13:38:44 +0100 Subject: [PATCH 2/6] apply nico review --- src/commands/identity.rs | 4 +- src/commands/vault.rs | 2 +- src/commands/vault/display.rs | 97 +++++++++++++++++++++++++++-------- src/data.rs | 4 +- src/keys.rs | 65 ++++++++++++++++++----- 5 files changed, 133 insertions(+), 39 deletions(-) diff --git a/src/commands/identity.rs b/src/commands/identity.rs index 0cc8f4f..6a64121 100644 --- a/src/commands/identity.rs +++ b/src/commands/identity.rs @@ -154,7 +154,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE secret_format, secret, } => { - let keypair = get_keypair(secret_format, secret.as_deref())?; + let keypair = get_keypair(secret_format, secret.as_deref(), None)?; let address = keypair.address(); data = data.fetch_idty_index().await?; // idty index required for payload link_account(&data, address, keypair).await?; @@ -163,7 +163,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE secret_format, secret, } => { - let keypair = get_keypair(secret_format, secret.as_deref())?; + let keypair = get_keypair(secret_format, secret.as_deref(), None)?; let address = keypair.address(); data = data.fetch_idty_index().await?; // idty index required for payload change_owner_key(&data, address, keypair).await?; diff --git a/src/commands/vault.rs b/src/commands/vault.rs index a4e3594..ce9942b 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -475,7 +475,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE &txn, &vault_data_to_import, Some(&vault_data_from_file.password), - None, + Some(CryptoScheme::Ed25519), ) .await; diff --git a/src/commands/vault/display.rs b/src/commands/vault/display.rs index e9a9d2d..e51560a 100644 --- a/src/commands/vault/display.rs +++ b/src/commands/vault/display.rs @@ -230,15 +230,27 @@ mod tests { fn test_compute_vault_accounts_table_with_g1v1_empty() { // Test with show_g1v1 = true (default behavior) let table = compute_vault_accounts_table_with_g1v1(&[], true).unwrap(); - println!("Table with show_g1v1=true:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + + let expected_table_with_g1v1 = indoc! {r#" + ┌─────────────────────────────────────────────────────┠+ │ SS58 Address/G1v1 public key Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + └─────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false let table = compute_vault_accounts_table_with_g1v1(&[], false).unwrap(); - println!("Table with show_g1v1=false:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + + let expected_table_without_g1v1 = indoc! {r#" + ┌─────────────────────────────────────┠+ │ SS58 Address Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + └─────────────────────────────────────┘"# + }; + + assert_eq!(table.to_string(), expected_table_without_g1v1); } #[test] @@ -248,16 +260,41 @@ mod tests { let account_tree_nodes = vec![account_tree_node, g1v1_account_tree_node]; // Test with show_g1v1 = true (default behavior) - let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); - println!("Table with show_g1v1=true:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + + let expected_table_with_g1v1 = indoc! {r#" + ┌──────────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address/G1v1 public key Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ 5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV sr25519 <Base> Mother │ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + │ ├ 5GBNeWRhZc2jXu7D55rBimKYDk8PGk8itRYFTPfC8RJLKG5o //1 <Mother//1> │ + │ │ ├ 5CvdJuB9HLXSi5FS9LW57cyHF13iCv5HDimo2C45KxnxriCT //1 <Mother//1//1> │ + │ 5ET2jhgJFoNQUpgfdSkdwftK8DKWdqZ1FKm5GKWdPfMWhPr4 ed25519 <Base> MotherG1v1 │ + │ â”” G1v1: 86pW1doyJPVH3jeDPZNQa1UZFBo5zcdvHERcaeE758W7 │ + └──────────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_with_g1v1.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false - let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); - println!("Table with show_g1v1=false:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + + let expected_table_without_g1v1 = indoc! {r#" + ┌──────────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ 5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV sr25519 <Base> Mother │ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + │ ├ 5GBNeWRhZc2jXu7D55rBimKYDk8PGk8itRYFTPfC8RJLKG5o //1 <Mother//1> │ + │ │ ├ 5CvdJuB9HLXSi5FS9LW57cyHF13iCv5HDimo2C45KxnxriCT //1 <Mother//1//1> │ + │ 5ET2jhgJFoNQUpgfdSkdwftK8DKWdqZ1FKm5GKWdPfMWhPr4 ed25519 <Base> MotherG1v1 │ + └──────────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_without_g1v1.to_string(), expected_table_without_g1v1); } #[test] @@ -267,16 +304,32 @@ mod tests { let account_tree_nodes = vec![child1]; // Test with show_g1v1 = true (default behavior) - let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); - println!("Table with show_g1v1=true:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + + let expected_table_with_g1v1 = indoc! {r#" + ┌─────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address/G1v1 public key Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + └─────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_with_g1v1.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false - let table = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); - println!("Table with show_g1v1=false:\n{}", table.to_string()); - let expected_table = table.to_string(); - assert_eq!(table.to_string(), expected_table); + let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + + let expected_table_without_g1v1 = indoc! {r#" + ┌─────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address Crypto Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + └─────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_without_g1v1.to_string(), expected_table_without_g1v1); } } } diff --git a/src/data.rs b/src/data.rs index 1e877c0..40f9918 100644 --- a/src/data.rs +++ b/src/data.rs @@ -123,7 +123,7 @@ impl Data { match self.keypair.clone() { Some(keypair) => keypair, None => loop { - match fetch_or_get_keypair(self, self.cfg.address.clone()).await { + match fetch_or_get_keypair(self, self.cfg.address.clone(), None).await { Ok(pair) => return pair, Err(e) => { //Adapted code to still be able to go out of the loop when user hit "Esc" key or "ctrl+c" when prompted for a value @@ -207,7 +207,7 @@ impl Data { } // secret format and value if let Some(secret_format) = self.args.secret_format { - let keypair = get_keypair(secret_format, self.args.secret.as_deref())?; + let keypair = get_keypair(secret_format, self.args.secret.as_deref(), None)?; self.cfg.address = Some(keypair.address()); self.keypair = Some(keypair); } diff --git a/src/keys.rs b/src/keys.rs index a81f2bf..cdbfb44 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -136,11 +136,48 @@ pub enum Signature { pub fn get_keypair( secret_format: SecretFormat, secret: Option<&str>, + crypto_scheme: Option<CryptoScheme>, ) -> Result<KeyPair, GcliError> { match (secret_format, secret) { - (SecretFormat::Predefined, Some(deriv)) => pair_from_predefined(deriv).map(|v| v.into()), - (secret_format, None) => Ok(prompt_secret(secret_format, None)), - (_, Some(secret)) => Ok(pair_from_secret(secret_format, secret)?.into()), + (SecretFormat::Predefined, Some(deriv)) => { + match crypto_scheme { + Some(CryptoScheme::Ed25519) => pair_from_ed25519_str(&predefined_suri(deriv)).map(|v| v.into()), + _ => pair_from_predefined(deriv).map(|v| v.into()), // Default to Sr25519 for backward compatibility + } + }, + (secret_format, None) => Ok(prompt_secret(secret_format, crypto_scheme)), + (_, Some(secret)) => { + match crypto_scheme { + Some(CryptoScheme::Ed25519) => pair_from_secret_with_scheme(secret_format, secret, CryptoScheme::Ed25519), + _ => Ok(pair_from_secret(secret_format, secret)?.into()), // Default to Sr25519 for backward compatibility + } + }, + } +} + +/// get keypair from given secret with specified crypto scheme +/// if secret is predefined, secret should contain the predefined value +pub fn pair_from_secret_with_scheme( + secret_format: SecretFormat, + secret: &str, + crypto_scheme: CryptoScheme, +) -> Result<KeyPair, GcliError> { + match (secret_format, crypto_scheme) { + (SecretFormat::G1v1, _) => Err(GcliError::Logic( + "G1v1 format incompatible with single secret".to_string(), + )), + (_, CryptoScheme::Ed25519) => match secret_format { + SecretFormat::Substrate => pair_from_ed25519_str(secret).map(|v| v.into()), + SecretFormat::Predefined => pair_from_ed25519_str(secret).map(|v| v.into()), + SecretFormat::Seed => { + let mut seed = [0; 32]; + hex::decode_to_slice(secret, &mut seed) + .map_err(|_| GcliError::Input("Invalid secret".to_string()))?; + Ok(ed25519::Pair::from_seed(&seed).into()) + }, + SecretFormat::G1v1 => unreachable!(), // Already handled above + }, + (_, CryptoScheme::Sr25519) => pair_from_secret(secret_format, secret).map(|v| v.into()), } } @@ -195,13 +232,13 @@ pub fn pair_from_ed25519_seed(secret: &str) -> Result<ed25519::Pair, GcliError> } /// get mnemonic from predefined derivation path -pub fn predefined_mnemonic(deriv: &str) -> String { +pub fn predefined_suri(deriv: &str) -> String { format!("{SUBSTRATE_MNEMONIC}//{deriv}") } /// get keypair from predefined secret pub fn pair_from_predefined(deriv: &str) -> Result<sr25519::Pair, GcliError> { - pair_from_sr25519_str(&predefined_mnemonic(deriv)) + pair_from_sr25519_str(&predefined_suri(deriv)) } /// get seed from G1v1 id/pwd (old "cesium") @@ -307,18 +344,18 @@ pub fn prompt_predefined() -> sr25519::Pair { pub fn prompt_predefined_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { let deriv = inputs::prompt_password_query("Enter derivation path: ").unwrap(); - let mnemonic = predefined_mnemonic(&deriv); + let suri = predefined_suri(&deriv); match crypto_scheme { CryptoScheme::Sr25519 => { - match pair_from_sr25519_str(&mnemonic) { - Ok(pair) => (mnemonic, pair.into()), + match pair_from_sr25519_str(&suri) { + Ok(pair) => (suri, pair.into()), Err(e) => panic!("Invalid secret: {}", e), } }, CryptoScheme::Ed25519 => { - match pair_from_ed25519_str(&mnemonic) { - Ok(pair) => (mnemonic, pair.into()), + match pair_from_ed25519_str(&suri) { + Ok(pair) => (suri, pair.into()), Err(e) => panic!("Invalid secret: {}", e), } } @@ -345,12 +382,16 @@ pub fn prompt_secret(secret_format: SecretFormat, crypto_scheme: Option<CryptoSc pub async fn fetch_or_get_keypair( data: &Data, address: Option<AccountId>, + crypto_scheme: Option<CryptoScheme>, ) -> Result<KeyPair, GcliError> { if let Some(address) = address { // if address corresponds to predefined, (for example saved to config) // keypair is already known (useful for dev mode) if let Some(d) = catch_known(&address.to_string()) { - return Ok(pair_from_predefined(d).unwrap().into()); + match crypto_scheme { + Some(CryptoScheme::Ed25519) => return pair_from_ed25519_str(&predefined_suri(d)).map(|v| v.into()), + _ => return Ok(pair_from_predefined(d).unwrap().into()), // Default to Sr25519 for backward compatibility + } }; // look for corresponding KeyPair in keystore @@ -360,7 +401,7 @@ pub async fn fetch_or_get_keypair( } // at the moment, there is no way to confg gcli to use an other kind of secret // without telling explicitly each time - Ok(prompt_secret(SecretFormat::Substrate, None)) + Ok(prompt_secret(SecretFormat::Substrate, crypto_scheme)) } // catch known addresses -- GitLab From e9cd6a99fd0b7a0a8dec00f8a00df842abc9e70e Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Thu, 13 Mar 2025 18:28:31 +0100 Subject: [PATCH 3/6] Add secret format in database and display --- src/commands/vault.rs | 167 ++++++++++++++-------------------- src/commands/vault/display.rs | 156 ++++++++++++++++++++++++------- src/entities/vault_account.rs | 51 +++++++++++ 3 files changed, 240 insertions(+), 134 deletions(-) diff --git a/src/commands/vault.rs b/src/commands/vault.rs index ce9942b..10dcdb1 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -91,34 +91,46 @@ pub enum Subcommand { Where, } -#[derive(Clone, Debug, clap::Parser)] +/// List subcommands +#[derive(Clone, Debug, clap::Subcommand)] pub enum ListChoice { - /// List all <Base> SS58 Addresses and their linked derivations in the vault + /// List all accounts + #[clap(alias = "a")] All { - /// Show G1v1 public keys - #[clap(long, default_value = "false")] + /// Show G1v1 public key for ed25519 keys + #[clap(long)] + show_g1v1: bool, + /// Show wallet type (g1v1 or mnemonic) + #[clap(long)] + show_type: bool, + }, + /// List only base accounts + #[clap(alias = "b")] + Base { + /// Show G1v1 public key for ed25519 keys + #[clap(long)] show_g1v1: bool, + /// Show wallet type (g1v1 or mnemonic) + #[clap(long)] + show_type: bool, }, - /// List <Base> and Derivation SS58 Addresses linked to the selected one + /// List accounts for a specific address + #[clap(alias = "f")] For { #[clap(flatten)] address_or_vault_name: AddressOrVaultNameGroup, - - /// Show G1v1 public keys - #[clap(long, default_value = "false")] - show_g1v1: bool, - }, - /// List all <Base> SS58 Addresses in the vault - Base { - /// Show G1v1 public keys - #[clap(long, default_value = "false")] + /// Show G1v1 public key for ed25519 keys + #[clap(long)] show_g1v1: bool, + /// Show wallet type (g1v1 or mnemonic) + #[clap(long)] + show_type: bool, }, } impl Default for ListChoice { fn default() -> Self { - ListChoice::All { show_g1v1: false } + ListChoice::All { show_g1v1: false, show_type: false } } } @@ -172,20 +184,20 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE // match subcommand match command { Subcommand::List(choice) => match choice { - ListChoice::All { show_g1v1 } => { + ListChoice::All { show_g1v1, show_type } => { let all_account_tree_node_hierarchies = vault_account::fetch_all_base_account_tree_node_hierarchies(db).await?; - let table = display::compute_vault_accounts_table_with_g1v1(&all_account_tree_node_hierarchies, show_g1v1)?; + let table = display::compute_vault_accounts_table_with_g1v1(&all_account_tree_node_hierarchies, show_g1v1, show_type)?; println!("available SS58 Addresses:"); println!("{table}"); } - ListChoice::Base { show_g1v1 } => { + ListChoice::Base { show_g1v1, show_type } => { let base_account_tree_nodes = vault_account::fetch_only_base_account_tree_nodes(db).await?; - let table = display::compute_vault_accounts_table_with_g1v1(&base_account_tree_nodes, show_g1v1)?; + let table = display::compute_vault_accounts_table_with_g1v1(&base_account_tree_nodes, show_g1v1, show_type)?; println!("available <Base> SS58 Addresses:"); println!("{table}"); @@ -193,6 +205,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE ListChoice::For { address_or_vault_name, show_g1v1, + show_type, } => { let account_tree_node = retrieve_account_tree_node(db, address_or_vault_name).await?; @@ -200,7 +213,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let base_account_tree_node = vault_account::get_base_account_tree_node(&account_tree_node); - let table = display::compute_vault_accounts_table_with_g1v1(&[base_account_tree_node], show_g1v1)?; + let table = display::compute_vault_accounts_table_with_g1v1(&[base_account_tree_node], show_g1v1, show_type)?; println!( "available SS58 Addresses linked to {}:", @@ -742,67 +755,31 @@ fn prompt_secret_and_compute_vault_data_to_import( pub async fn create_base_account_for_vault_data_to_import<C>( db_tx: &C, vault_data: &VaultDataToImport, - password: Option<&String>, + password_opt: Option<&String>, crypto_scheme: Option<CryptoScheme>, ) -> Result<vault_account::Model, GcliError> where C: ConnectionTrait, { - let address_to_import = vault_data.key_pair.address().to_string(); - println!("Trying to import for SS58 address :'{}'", address_to_import); - println!(); - - let vault_account = if let Some(existing_vault_account) = - vault_account::find_by_id(db_tx, &DbAccountId::from(address_to_import.clone())).await? - { - if existing_vault_account.is_base_account() { - println!("You are trying to add {address_to_import} as a <Base> account while it already exists as a <Base> account."); - println!(); - println!("Do you want to:"); - println!("1. keep the existing <Base> account and cancel import"); - println!("2. overwrite existing <Base> account with the new encrypted key (children will be re-parented)"); - } else { - // Existing derivation account - let account_tree_node_hierarchy = - vault_account::fetch_base_account_tree_node_hierarchy_unwrapped( - db_tx, - &address_to_import, - ) - .await?; - let account_tree_node_for_address = vault_account::get_account_tree_node_for_address( - &account_tree_node_hierarchy, - &address_to_import, - ); + let address = vault_data.key_pair.address().to_string(); - let base_parent_hierarchy_account_tree_node = - vault_account::get_base_parent_hierarchy_account_tree_node( - &account_tree_node_for_address, - ); - - let parent_hierarchy_table = - display::compute_vault_accounts_table(&[base_parent_hierarchy_account_tree_node])?; + // Check if the account already exists + let existing_vault_account = vault_account::find_by_id(db_tx, &DbAccountId(vault_data.key_pair.address())).await?; - println!("You are trying to add {address_to_import} as a <Base> account"); - println!( - "but it is already present as `{}` derivation of {} account.", - existing_vault_account.path.clone().unwrap(), - existing_vault_account.parent.clone().unwrap() - ); - println!(); - println!("Its parent hierarchy is this:"); - println!("{parent_hierarchy_table}"); - println!(); - println!("Do you want to:"); - println!("1. keep the existing derivation and cancel import"); - println!("2. delete the derivation account and replace it with the new <Base> account (children will be re-parented)"); - } + let password = match password_opt { + Some(password) => password.clone(), + None => inputs::prompt_password_query("Enter password to encrypt the key: ")?, + }; - let result = inputs::select_action("Your choice?", vec!["1", "2"])?; - match result { - "2" => { - let encrypted_suri = - compute_encrypted_suri(password, vault_data.secret_suri.clone())?; + let encrypted_suri = compute_encrypted_suri(password.clone(), vault_data.secret_suri.clone())?; + if let Some(existing_vault_account) = existing_vault_account { + // Existing account + match inputs::confirm_action(&format!( + "Account {} already exists. Do you want to update it?", + existing_vault_account + ))? { + true => { println!( "(Optional) Enter a name for the vault entry (leave empty to remove the name)" ); @@ -821,14 +798,15 @@ where )); vault_account.encrypted_suri = Set(Some(encrypted_suri)); vault_account.name = Set(name.clone()); + vault_account.secret_format = Set(Some(vault_data.secret_format.into())); let updated_vault_account = vault_account::update_account(db_tx, vault_account).await?; - + println!("Updating vault account {updated_vault_account}"); - updated_vault_account + Ok(updated_vault_account) } _ => { - return Err(GcliError::Input("import canceled".into())); + Err(GcliError::Input("import canceled".into())) } } } else { @@ -842,20 +820,19 @@ where let crypto_scheme = map_secret_format_to_crypto_scheme(secret_format, crypto_scheme); - let base_account = vault_account::create_base_account( + let account = vault_account::create_base_account( db_tx, - &address_to_import, + &address, name.as_ref(), crypto_scheme, encrypted_suri, + secret_format, ) .await?; - println!("Creating <Base> account {base_account}"); - - base_account - }; - - Ok(vault_account) + + println!("Creating <Base> account {account}"); + Ok(account) + } } /// Creates a `derivation` vault account for data provided and returns it @@ -982,18 +959,10 @@ where /// Function will ask for password if not present and compute the encrypted suri fn compute_encrypted_suri( - password: Option<&String>, + password: String, secret_suri: String, ) -> Result<Vec<u8>, GcliError> { - let password = match password.cloned() { - Some(password) => password, - _ => { - println!("Enter password to protect the key"); - inputs::prompt_password_confirm()? - } - }; - - Ok(encrypt(secret_suri.as_bytes(), password).map_err(|e| anyhow!(e))?) + encrypt(secret_suri.as_bytes(), password).map_err(|e| GcliError::Input(e.to_string())) } fn get_vault_key_path(data: &Data, vault_filename: &str) -> PathBuf { @@ -1144,12 +1113,12 @@ mod tests { Some(String::from("//Alice")) )] #[case( - String::from( - "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice//Bob/soft1/soft2" - ), - Some(String::from("bottom drive obey lake curtain smoke basket hold race lonely fit walk")), - Some(String::from("//Alice//Bob/soft1/soft2")) - )] + String::from( + "bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice//Bob/soft1/soft2" + ), + Some(String::from("bottom drive obey lake curtain smoke basket hold race lonely fit walk")), + Some(String::from("//Alice//Bob/soft1/soft2")) + )] #[case( String::from("bottom drive obey lake curtain smoke basket hold race lonely fit walk"), Some(String::from( diff --git a/src/commands/vault/display.rs b/src/commands/vault/display.rs index e51560a..935b55e 100644 --- a/src/commands/vault/display.rs +++ b/src/commands/vault/display.rs @@ -27,24 +27,36 @@ pub fn compute_vault_accounts_table( account_tree_nodes: &[Rc<RefCell<AccountTreeNode>>], ) -> Result<Table, GcliError> { // Appel to the new function with show_g1v1 = true to maintain compatibility - compute_vault_accounts_table_with_g1v1(account_tree_nodes, true) + compute_vault_accounts_table_with_g1v1(account_tree_nodes, true, false) } pub fn compute_vault_accounts_table_with_g1v1( account_tree_nodes: &[Rc<RefCell<AccountTreeNode>>], show_g1v1: bool, + show_type: bool, ) -> Result<Table, GcliError> { let mut table = Table::new(); table.load_preset(comfy_table::presets::UTF8_BORDERS_ONLY); - table.set_header(vec![ + + // Prepare header based on options + let mut header = vec![ if show_g1v1 { "SS58 Address/G1v1 public key" } else { "SS58 Address" }, "Crypto", - "Path", - "Name", - ]); + ]; + + // Add Type column if show_type is true + if show_type { + header.push("Type"); + } + + // Add remaining columns + header.push("Path"); + header.push("Name"); + + table.set_header(header); for account_tree_node in account_tree_nodes { - let _ = add_account_tree_node_to_table_with_g1v1(&mut table, account_tree_node, show_g1v1); + let _ = add_account_tree_node_to_table_with_g1v1(&mut table, account_tree_node, show_g1v1, show_type); } Ok(table) @@ -55,21 +67,22 @@ fn add_account_tree_node_to_table( account_tree_node: &Rc<RefCell<AccountTreeNode>>, ) -> Result<(), GcliError> { // Appel to the new function with show_g1v1 = true to maintain compatibility - add_account_tree_node_to_table_with_g1v1(table, account_tree_node, true) + add_account_tree_node_to_table_with_g1v1(table, account_tree_node, true, false) } fn add_account_tree_node_to_table_with_g1v1( table: &mut Table, account_tree_node: &Rc<RefCell<AccountTreeNode>>, show_g1v1: bool, + show_type: bool, ) -> Result<(), GcliError> { - let rows = compute_vault_accounts_row_with_g1v1(account_tree_node, show_g1v1)?; + let rows = compute_vault_accounts_row_with_g1v1(account_tree_node, show_g1v1, show_type)?; rows.iter().for_each(|row| { table.add_row(row.clone()); }); for child in &account_tree_node.borrow().children { - let _ = add_account_tree_node_to_table_with_g1v1(table, child, show_g1v1); + let _ = add_account_tree_node_to_table_with_g1v1(table, child, show_g1v1, show_type); } Ok(()) @@ -77,12 +90,12 @@ fn add_account_tree_node_to_table_with_g1v1( /// Computes one or more row of the table for selected account_tree_node /// -/// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key +/// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key if show_g1v1 is true pub fn compute_vault_accounts_row( account_tree_node: &Rc<RefCell<AccountTreeNode>>, ) -> Result<Vec<Vec<Cell>>, GcliError> { // Appel to the new function with show_g1v1 = true to maintain compatibility - compute_vault_accounts_row_with_g1v1(account_tree_node, true) + compute_vault_accounts_row_with_g1v1(account_tree_node, true, false) } /// Computes one or more row of the table for selected account_tree_node @@ -91,6 +104,7 @@ pub fn compute_vault_accounts_row( pub fn compute_vault_accounts_row_with_g1v1( account_tree_node: &Rc<RefCell<AccountTreeNode>>, show_g1v1: bool, + show_type: bool, ) -> Result<Vec<Vec<Cell>>, GcliError> { let empty_string = "".to_string(); @@ -117,42 +131,70 @@ pub fn compute_vault_accounts_row_with_g1v1( let mut rows: Vec<Vec<Cell>> = vec![]; - let (path, crypto) = if let Some(path) = account_tree_node.account.path.clone() { - (path, empty_string.clone()) + let (path, crypto, wallet_type) = if let Some(path) = account_tree_node.account.path.clone() { + (path, empty_string.clone(), empty_string.clone()) } else { let crypto_scheme = CryptoScheme::from(account_tree_node.account.crypto_scheme.unwrap()); let crypto_scheme_str: &str = crypto_scheme.into(); - // Check if it's an ed25519 key (for G1v1, we always use Ed25519) - // We don't have access to the secret_format field, so we rely only on the crypto_scheme - let is_ed25519 = crypto_scheme == CryptoScheme::Ed25519; + // Determine the wallet type based on the secret format + let wallet_type = if let Some(secret_format) = &account_tree_node.account.secret_format { + // If the secret format is available, use it to determine the type + match crate::keys::SecretFormat::from(*secret_format) { + crate::keys::SecretFormat::G1v1 => "G1v1".to_string(), + crate::keys::SecretFormat::Substrate => "Mnemonic".to_string(), + crate::keys::SecretFormat::Seed => "Seed".to_string(), + crate::keys::SecretFormat::Predefined => "Predefined".to_string(), + } + } else { + // If the secret format is not available, display "Unknown" + "Unknown".to_string() + }; - // Adding 2nd row for G1v1 public key only if show_g1v1 is true and it's an Ed25519 key + // Add a second line for the G1v1 public key only if show_g1v1 is true and it's an Ed25519 key + let is_ed25519 = crypto_scheme == CryptoScheme::Ed25519; if show_g1v1 && is_ed25519 { - rows.push(vec![Cell::new(format!( + let mut g1v1_row = vec![Cell::new(format!( "â”” G1v1: {}", cesium::compute_g1v1_public_key_from_ed25519_account_id( &account_tree_node.account.address.0 ) - ))]); + ))]; + + // Add empty cells to align with the main line + g1v1_row.push(Cell::new("")); + if show_type { + g1v1_row.push(Cell::new("")); + } + g1v1_row.push(Cell::new("")); + g1v1_row.push(Cell::new("")); + + rows.push(g1v1_row); } ( format!("<{}>", account_tree_node.account.account_type()), crypto_scheme_str.to_string(), + wallet_type, ) }; - // Adding 1st row - rows.insert( - 0, - vec![ - Cell::new(&address), - Cell::new(crypto), - Cell::new(&path), - Cell::new(&name), - ], - ); + // Add the first line + let mut main_row = vec![ + Cell::new(&address), + Cell::new(crypto), + ]; + + // Add the Type column if show_type is true + if show_type { + main_row.push(Cell::new(wallet_type)); + } + + // Add the remaining columns + main_row.push(Cell::new(&path)); + main_row.push(Cell::new(&name)); + + rows.insert(0, main_row); Ok(rows) } @@ -229,7 +271,7 @@ mod tests { #[test] fn test_compute_vault_accounts_table_with_g1v1_empty() { // Test with show_g1v1 = true (default behavior) - let table = compute_vault_accounts_table_with_g1v1(&[], true).unwrap(); + let table = compute_vault_accounts_table_with_g1v1(&[], true, false).unwrap(); let expected_table_with_g1v1 = indoc! {r#" ┌─────────────────────────────────────────────────────┠@@ -241,7 +283,7 @@ mod tests { assert_eq!(table.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false - let table = compute_vault_accounts_table_with_g1v1(&[], false).unwrap(); + let table = compute_vault_accounts_table_with_g1v1(&[], false, false).unwrap(); let expected_table_without_g1v1 = indoc! {r#" ┌─────────────────────────────────────┠@@ -260,7 +302,7 @@ mod tests { let account_tree_nodes = vec![account_tree_node, g1v1_account_tree_node]; // Test with show_g1v1 = true (default behavior) - let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true, false).unwrap(); let expected_table_with_g1v1 = indoc! {r#" ┌──────────────────────────────────────────────────────────────────────────────────────────┠@@ -279,7 +321,7 @@ mod tests { assert_eq!(table_with_g1v1.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false - let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false, false).unwrap(); let expected_table_without_g1v1 = indoc! {r#" ┌──────────────────────────────────────────────────────────────────────────────────────────┠@@ -304,7 +346,7 @@ mod tests { let account_tree_nodes = vec![child1]; // Test with show_g1v1 = true (default behavior) - let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true).unwrap(); + let table_with_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true, false).unwrap(); let expected_table_with_g1v1 = indoc! {r#" ┌─────────────────────────────────────────────────────────────────────────────────────┠@@ -318,7 +360,7 @@ mod tests { assert_eq!(table_with_g1v1.to_string(), expected_table_with_g1v1); // Test with show_g1v1 = false - let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false).unwrap(); + let table_without_g1v1 = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false, false).unwrap(); let expected_table_without_g1v1 = indoc! {r#" ┌─────────────────────────────────────────────────────────────────────────────────────┠@@ -331,5 +373,49 @@ mod tests { assert_eq!(table_without_g1v1.to_string(), expected_table_without_g1v1); } + + #[test] + fn test_compute_vault_accounts_table_with_type() { + let account_tree_node = mother_account_tree_node(); + let g1v1_account_tree_node = mother_g1v1_account_tree_node(); + let account_tree_nodes = vec![account_tree_node, g1v1_account_tree_node]; + + // Test with show_type = true and show_g1v1 = true + let table_with_g1v1_and_type = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, true, true).unwrap(); + + let expected_table_with_g1v1_and_type = indoc! {r#" + ┌─────────────────────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address/G1v1 public key Crypto Type Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ 5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV sr25519 Mnemonic <Base> Mother │ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + │ ├ 5GBNeWRhZc2jXu7D55rBimKYDk8PGk8itRYFTPfC8RJLKG5o //1 <Mother//1> │ + │ │ ├ 5CvdJuB9HLXSi5FS9LW57cyHF13iCv5HDimo2C45KxnxriCT //1 <Mother//1//1> │ + │ 5ET2jhgJFoNQUpgfdSkdwftK8DKWdqZ1FKm5GKWdPfMWhPr4 ed25519 G1v1 <Base> MotherG1v1 │ + │ â”” G1v1: 86pW1doyJPVH3jeDPZNQa1UZFBo5zcdvHERcaeE758W7 │ + └─────────────────────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_with_g1v1_and_type.to_string(), expected_table_with_g1v1_and_type); + + // Test with show_type = true and show_g1v1 = false + let table_with_type = compute_vault_accounts_table_with_g1v1(&account_tree_nodes, false, true).unwrap(); + + let expected_table_with_type = indoc! {r#" + ┌─────────────────────────────────────────────────────────────────────────────────────────────────────┠+ │ SS58 Address Crypto Type Path Name │ + â•žâ•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•â•¡ + │ 5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV sr25519 Mnemonic <Base> Mother │ + │ ├ 5D34dL5prEUaGNQtPPZ3yN5Y6BnkfXunKXXz6fo7ZJbLwRRH //0 Child 1 │ + │ │ ├ 5Fh5PLQNt1xuEXm71dfDtQdnwceSew4oHewWBLsWAkKspV7d //0 Grandchild 1 │ + │ ├ 5GBNeWRhZc2jXu7D55rBimKYDk8PGk8itRYFTPfC8RJLKG5o //1 <Mother//1> │ + │ │ ├ 5CvdJuB9HLXSi5FS9LW57cyHF13iCv5HDimo2C45KxnxriCT //1 <Mother//1//1> │ + │ 5ET2jhgJFoNQUpgfdSkdwftK8DKWdqZ1FKm5GKWdPfMWhPr4 ed25519 G1v1 <Base> MotherG1v1 │ + └─────────────────────────────────────────────────────────────────────────────────────────────────────┘"# + }; + + assert_eq!(table_with_type.to_string(), expected_table_with_type); + } } } diff --git a/src/entities/vault_account.rs b/src/entities/vault_account.rs index d04b02a..939ee75 100644 --- a/src/entities/vault_account.rs +++ b/src/entities/vault_account.rs @@ -40,6 +40,8 @@ pub struct Model { pub encrypted_suri: Option<Vec<u8>>, /// ForeignKey to parent vault_account SS58 Address - None if for a "base" account pub parent: Option<DbAccountId>, + /// Secret format used for the account - Only set for "base" accounts + pub secret_format: Option<DbSecretFormat>, } impl Model { @@ -243,6 +245,46 @@ impl From<DbCryptoScheme> for crate::keys::CryptoScheme { } } +/// Enum for SecretFormat in the database +#[derive(Debug, Copy, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum)] +#[sea_orm( + rs_type = "String", + db_type = "String(StringLen::None)", + enum_name = "secret_format" +)] +pub enum DbSecretFormat { + #[sea_orm(string_value = "seed")] + Seed, + #[sea_orm(string_value = "substrate")] + Substrate, + #[sea_orm(string_value = "predefined")] + Predefined, + #[sea_orm(string_value = "g1v1")] + G1v1, +} + +impl From<crate::keys::SecretFormat> for DbSecretFormat { + fn from(format: crate::keys::SecretFormat) -> Self { + match format { + crate::keys::SecretFormat::Seed => DbSecretFormat::Seed, + crate::keys::SecretFormat::Substrate => DbSecretFormat::Substrate, + crate::keys::SecretFormat::Predefined => DbSecretFormat::Predefined, + crate::keys::SecretFormat::G1v1 => DbSecretFormat::G1v1, + } + } +} + +impl From<DbSecretFormat> for crate::keys::SecretFormat { + fn from(format: DbSecretFormat) -> Self { + match format { + DbSecretFormat::Seed => crate::keys::SecretFormat::Seed, + DbSecretFormat::Substrate => crate::keys::SecretFormat::Substrate, + DbSecretFormat::Predefined => crate::keys::SecretFormat::Predefined, + DbSecretFormat::G1v1 => crate::keys::SecretFormat::G1v1, + } + } +} + #[derive(Copy, Clone, Debug, EnumIter)] pub enum Relation { ParentAccount, @@ -868,6 +910,7 @@ pub async fn create_base_account<C>( name: Option<&String>, crypto_scheme: crate::keys::CryptoScheme, encrypted_suri: Vec<u8>, + secret_format: crate::keys::SecretFormat, ) -> Result<Model, GcliError> where C: ConnectionTrait, @@ -890,6 +933,7 @@ where crypto_scheme: Set(Some(crypto_scheme.into())), encrypted_suri: Set(Some(encrypted_suri)), parent: Default::default(), + secret_format: Set(Some(secret_format.into())), }; vault_account.insert(db).await? } @@ -927,6 +971,7 @@ where crypto_scheme: Set(None), encrypted_suri: Set(None), parent: Set(Some(parent_address.to_string().into())), + secret_format: Set(None), }; vault_account.insert(db).await? } @@ -983,6 +1028,7 @@ pub mod tests { crypto_scheme: None, encrypted_suri: None, parent: Some(child1_address.clone()), + secret_format: None, }, children: vec![], parent: None, @@ -997,6 +1043,7 @@ pub mod tests { crypto_scheme: None, encrypted_suri: None, parent: Some(child2_address.clone()), + secret_format: None, }, children: vec![], parent: None, @@ -1010,6 +1057,7 @@ pub mod tests { crypto_scheme: None, encrypted_suri: None, parent: Some(mother_address.clone()), + secret_format: None, }, children: vec![grandchild1.clone()], parent: None, @@ -1024,6 +1072,7 @@ pub mod tests { crypto_scheme: None, encrypted_suri: None, parent: Some(mother_address.clone()), + secret_format: None, }, children: vec![grandchild2.clone()], parent: None, @@ -1039,6 +1088,7 @@ pub mod tests { vault::encrypt(SUBSTRATE_MNEMONIC.as_bytes(), "".to_string()).unwrap(), ), parent: None, + secret_format: Some(DbSecretFormat::Substrate), }, children: vec![child1.clone(), child2.clone()], parent: None, @@ -1073,6 +1123,7 @@ pub mod tests { vault::encrypt(secret_suri.as_bytes(), "".to_string()).unwrap(), ), parent: None, + secret_format: Some(DbSecretFormat::G1v1), }, children: vec![], parent: None, -- GitLab From a36c831864b605bf7fa5bfd4864320a68646ab09 Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Thu, 13 Mar 2025 18:48:18 +0100 Subject: [PATCH 4/6] remove unused methods --- src/commands/transfer.rs | 2 +- src/commands/vault.rs | 2 +- src/commands/vault/display.rs | 18 ------------------ src/inputs.rs | 10 ---------- src/keys.rs | 27 --------------------------- 5 files changed, 2 insertions(+), 57 deletions(-) diff --git a/src/commands/transfer.rs b/src/commands/transfer.rs index 16f2e5e..1a97717 100644 --- a/src/commands/transfer.rs +++ b/src/commands/transfer.rs @@ -1,6 +1,6 @@ use crate::*; -#[cfg(any(feature = "dev", feature = "gdev"))] // find how to get runtime calls +#[cfg(feature = "gdev")] // find how to get runtime calls type Call = runtime::runtime_types::gdev_runtime::RuntimeCall; type BalancesCall = runtime::runtime_types::pallet_balances::pallet::Call; diff --git a/src/commands/vault.rs b/src/commands/vault.rs index 10dcdb1..a3fa4b2 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -7,7 +7,7 @@ use crate::*; use age::secrecy::Secret; use sea_orm::ActiveValue::Set; use sea_orm::{ConnectionTrait, TransactionTrait}; -use sea_orm::{DbErr, ModelTrait}; +use sea_orm::ModelTrait; use sp_core::crypto::AddressUri; use std::cell::RefCell; use std::io::{Read, Write}; diff --git a/src/commands/vault/display.rs b/src/commands/vault/display.rs index 935b55e..5f024d6 100644 --- a/src/commands/vault/display.rs +++ b/src/commands/vault/display.rs @@ -62,14 +62,6 @@ pub fn compute_vault_accounts_table_with_g1v1( Ok(table) } -fn add_account_tree_node_to_table( - table: &mut Table, - account_tree_node: &Rc<RefCell<AccountTreeNode>>, -) -> Result<(), GcliError> { - // Appel to the new function with show_g1v1 = true to maintain compatibility - add_account_tree_node_to_table_with_g1v1(table, account_tree_node, true, false) -} - fn add_account_tree_node_to_table_with_g1v1( table: &mut Table, account_tree_node: &Rc<RefCell<AccountTreeNode>>, @@ -88,16 +80,6 @@ fn add_account_tree_node_to_table_with_g1v1( Ok(()) } -/// Computes one or more row of the table for selected account_tree_node -/// -/// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key if show_g1v1 is true -pub fn compute_vault_accounts_row( - account_tree_node: &Rc<RefCell<AccountTreeNode>>, -) -> Result<Vec<Vec<Cell>>, GcliError> { - // Appel to the new function with show_g1v1 = true to maintain compatibility - compute_vault_accounts_row_with_g1v1(account_tree_node, true, false) -} - /// Computes one or more row of the table for selected account_tree_node /// /// For ed25519 keys, will display over 2 rows to also show the base 58 G1v1 public key if show_g1v1 is true diff --git a/src/inputs.rs b/src/inputs.rs index 0823130..ee84a6d 100644 --- a/src/inputs.rs +++ b/src/inputs.rs @@ -8,10 +8,6 @@ pub fn prompt_password() -> Result<String, GcliError> { prompt_password_query("Password") } -pub fn prompt_password_confirm() -> Result<String, GcliError> { - prompt_password_query_confirm("Password") -} - pub fn prompt_password_query(query: impl ToString) -> Result<String, GcliError> { inquire::Password::new(query.to_string().as_str()) .without_confirmation() @@ -39,12 +35,6 @@ pub fn prompt_seed() -> Result<String, GcliError> { .map_err(|e| GcliError::Input(e.to_string())) } -pub fn prompt_password_query_confirm(query: impl ToString) -> Result<String, GcliError> { - inquire::Password::new(query.to_string().as_str()) - .prompt() - .map_err(|e| GcliError::Input(e.to_string())) -} - /// Prompt for a (direct) vault name (cannot contain derivation path) /// /// Also preventing to use '<' and '>' as those are used in the display diff --git a/src/keys.rs b/src/keys.rs index cdbfb44..6097ca5 100644 --- a/src/keys.rs +++ b/src/keys.rs @@ -249,15 +249,6 @@ pub fn seed_from_cesium(id: &str, pwd: &str) -> [u8; 32] { seed } -/// ask user to input a secret -pub fn prompt_secret_substrate() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - match prompt_secret_substrate_and_compute_keypair(CryptoScheme::Sr25519).1 { - KeyPair::Sr25519(pair) => pair, - _ => panic!("Expected Sr25519 keypair"), - } -} - pub fn prompt_secret_substrate_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { loop { println!("Substrate URI can be a mnemonic or a mini-secret ('0x' prefixed seed) together with optional derivation path"); @@ -302,15 +293,6 @@ pub fn prompt_secret_cesium_and_compute_keypair(_crypto_scheme: CryptoScheme) -> } } -/// ask user to input a seed -pub fn prompt_seed() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - match prompt_seed_and_compute_keypair(CryptoScheme::Sr25519).1 { - KeyPair::Sr25519(pair) => pair, - _ => panic!("Expected Sr25519 keypair"), - } -} - pub fn prompt_seed_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { loop { let seed_str = inputs::prompt_seed().unwrap(); @@ -333,15 +315,6 @@ pub fn prompt_seed_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, } } -/// ask user pass (Cesium format) -pub fn prompt_predefined() -> sr25519::Pair { - // Only interested in the keypair which is the second element of the tuple - match prompt_predefined_and_compute_keypair(CryptoScheme::Sr25519).1 { - KeyPair::Sr25519(pair) => pair, - _ => panic!("Expected Sr25519 keypair"), - } -} - pub fn prompt_predefined_and_compute_keypair(crypto_scheme: CryptoScheme) -> (String, KeyPair) { let deriv = inputs::prompt_password_query("Enter derivation path: ").unwrap(); let suri = predefined_suri(&deriv); -- GitLab From 80d3023d934640dfb22abfb300b17fe854a7a988 Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Thu, 13 Mar 2025 22:33:30 +0100 Subject: [PATCH 5/6] add non interactive mode --- src/commands/vault.rs | 124 +++++++++++++++++++++++++++++++++++------- 1 file changed, 104 insertions(+), 20 deletions(-) diff --git a/src/commands/vault.rs b/src/commands/vault.rs index a3fa4b2..07b40fc 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -4,6 +4,7 @@ use crate::commands::cesium::compute_g1v1_public_key; use crate::entities::vault_account; use crate::entities::vault_account::{AccountTreeNode, ActiveModel, DbAccountId}; use crate::*; +use crate::keys::seed_from_cesium; use age::secrecy::Secret; use sea_orm::ActiveValue::Set; use sea_orm::{ConnectionTrait, TransactionTrait}; @@ -45,6 +46,30 @@ pub enum Subcommand { /// Crypto scheme to use (sr25519, ed25519) #[clap(short = 'c', long, required = false, default_value = CryptoScheme::Ed25519)] crypto_scheme: CryptoScheme, + + /// Substrate URI to import (non-interactive mode) + #[clap(short = 'u', long, required = false)] + uri: Option<String>, + + /// G1v1 ID (non-interactive mode for g1v1 format) + #[clap(long, required = false)] + g1v1_id: Option<String>, + + /// G1v1 password (non-interactive mode for g1v1 format) + #[clap(long, required = false)] + g1v1_password: Option<String>, + + /// Password for encrypting the key (non-interactive mode) + #[clap(short = 'p', long, required = false)] + password: Option<String>, + + /// Use empty password (non-interactive mode) + #[clap(long, required = false)] + no_password: bool, + + /// Name for the wallet entry (non-interactive mode) + #[clap(short = 'n', long, required = false)] + name: Option<String>, }, /// Add a derivation to an existing SS58 Address #[clap(long_about = "Add a derivation to an existing SS58 Address.\n\ @@ -250,9 +275,49 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let mnemonic = bip39::Mnemonic::generate(12).unwrap(); println!("{mnemonic}"); } - Subcommand::Import { secret_format, crypto_scheme } => { - let vault_data_for_import = - prompt_secret_and_compute_vault_data_to_import(secret_format, crypto_scheme)?; + Subcommand::Import { secret_format, crypto_scheme, uri, g1v1_id, g1v1_password, password, no_password, name } => { + let vault_data_for_import = if let Some(uri_str) = uri { + // Non-interactive mode with provided URI + if secret_format != SecretFormat::Substrate { + return Err(GcliError::Input(format!( + "URI can only be provided directly with secret_format=substrate, got: {:?}", + secret_format + ))); + } + + // Create keypair from provided URI + let key_pair = compute_keypair(crypto_scheme, &uri_str)?; + + VaultDataToImport { + secret_format, + secret_suri: uri_str, + key_pair, + } + } else if let (Some(id), Some(pwd)) = (&g1v1_id, &g1v1_password) { + // Non-interactive mode with provided G1v1 ID and password + if secret_format != SecretFormat::G1v1 { + return Err(GcliError::Input(format!( + "G1v1 ID and password can only be provided directly with secret_format=g1v1, got: {:?}", + secret_format + ))); + } + + // Create keypair from provided G1v1 ID and password + let seed = seed_from_cesium(id, pwd); + let secret_suri = format!("0x{}", hex::encode(seed)); + + // G1v1 always uses Ed25519 + let key_pair = compute_keypair(CryptoScheme::Ed25519, &secret_suri)?; + + VaultDataToImport { + secret_format, + secret_suri, + key_pair, + } + } else { + // Interactive mode + prompt_secret_and_compute_vault_data_to_import(secret_format, crypto_scheme)? + }; //Extra check for SecretFormat::G1v1 (old cesium) - showing the G1v1 cesium public key for confirmation if secret_format == SecretFormat::G1v1 { @@ -260,17 +325,28 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE "The G1v1 public key for the provided secret is: '{}'", compute_g1v1_public_key(&vault_data_for_import.key_pair)? ); - let confirmed = inputs::confirm_action("Is it the correct one (if not, you should try again to input G1v1 id/password) ?".to_string())?; - if !confirmed { - return Ok(()); + + // Skip confirmation in non-interactive mode + let is_non_interactive_g1v1 = g1v1_id.is_some() && g1v1_password.is_some(); + if !is_non_interactive_g1v1 { + let confirmed = inputs::confirm_action("Is it the correct one (if not, you should try again to input G1v1 id/password) ?".to_string())?; + if !confirmed { + return Ok(()); + } } } let txn = db.begin().await?; - - println!(); + + // Handle password in non-interactive mode + let provided_password = if no_password { + Some(String::new()) // Empty password + } else { + password + }; + let _account = - create_base_account_for_vault_data_to_import(&txn, &vault_data_for_import, None, Some(crypto_scheme)) + create_base_account_for_vault_data_to_import(&txn, &vault_data_for_import, provided_password.as_ref(), Some(crypto_scheme), name) .await?; txn.commit().await?; @@ -489,6 +565,7 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE &vault_data_to_import, Some(&vault_data_from_file.password), Some(CryptoScheme::Ed25519), + None, ) .await; @@ -757,6 +834,7 @@ pub async fn create_base_account_for_vault_data_to_import<C>( vault_data: &VaultDataToImport, password_opt: Option<&String>, crypto_scheme: Option<CryptoScheme>, + name_opt: Option<String>, ) -> Result<vault_account::Model, GcliError> where C: ConnectionTrait, @@ -780,14 +858,16 @@ where existing_vault_account ))? { true => { - println!( - "(Optional) Enter a name for the vault entry (leave empty to remove the name)" - ); - let name = inputs::prompt_vault_name_and_check_availability( - db_tx, - existing_vault_account.name.as_ref(), - ) - .await?; + let name = if let Some(name) = name_opt { + Some(name) + } else { + println!("(Optional) Enter a name for the vault entry (leave empty to remove the name)"); + inputs::prompt_vault_name_and_check_availability( + db_tx, + existing_vault_account.name.as_ref(), + ) + .await? + }; // Since links are made based on address / parent(address) we can just edit the existing entry and it should be fine let mut vault_account: ActiveModel = existing_vault_account.into(); @@ -797,7 +877,7 @@ where map_secret_format_to_crypto_scheme(vault_data.secret_format, crypto_scheme).into(), )); vault_account.encrypted_suri = Set(Some(encrypted_suri)); - vault_account.name = Set(name.clone()); + vault_account.name = Set(name); vault_account.secret_format = Set(Some(vault_data.secret_format.into())); let updated_vault_account = vault_account::update_account(db_tx, vault_account).await?; @@ -815,8 +895,12 @@ where let encrypted_suri = compute_encrypted_suri(password, vault_data.secret_suri.clone())?; - println!("(Optional) Enter a name for the vault entry"); - let name = inputs::prompt_vault_name_and_check_availability(db_tx, None).await?; + let name = if let Some(name) = name_opt { + Some(name) + } else { + println!("(Optional) Enter a name for the vault entry"); + inputs::prompt_vault_name_and_check_availability(db_tx, None).await? + }; let crypto_scheme = map_secret_format_to_crypto_scheme(secret_format, crypto_scheme); -- GitLab From 8760c3bdda27db588c26911edfb6775583f1b7a9 Mon Sep 17 00:00:00 2001 From: poka <poka@p2p.legal> Date: Thu, 13 Mar 2025 23:21:46 +0100 Subject: [PATCH 6/6] use json output for all usefull commands --- src/commands/account.rs | 42 +++- src/commands/blockchain.rs | 31 ++- src/commands/oneshot.rs | 55 ++++-- src/commands/runtime.rs | 363 +++++++++++++++++++++------------- src/commands/smith.rs | 184 ++++++++++++----- src/commands/vault.rs | 104 +++++++--- src/commands/vault/display.rs | 86 ++++++++ src/conf.rs | 54 ++++- 8 files changed, 672 insertions(+), 247 deletions(-) diff --git a/src/commands/account.rs b/src/commands/account.rs index c1216b6..1d0c452 100644 --- a/src/commands/account.rs +++ b/src/commands/account.rs @@ -1,4 +1,6 @@ use crate::*; +use anyhow::anyhow; +use serde::Serialize; /// define account subcommands #[derive(Clone, Default, Debug, clap::Parser)] @@ -57,18 +59,42 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE Ok(()) } +/// Balance view for JSON serialization +#[derive(Serialize)] +struct BalanceView { + account_id: String, + free_balance: u64, + formatted_balance: String, + exists: bool, +} + /// get balance -pub async fn get_balance(data: Data) -> Result<(), subxt::Error> { +pub async fn get_balance(data: Data) -> Result<(), GcliError> { let account_id = data.address(); let account_info = get_account_info(data.client(), &account_id).await?; - if let Some(account_info) = account_info { - println!( - "{account_id} has {}", - data.format_balance(account_info.data.free) - ); - } else { - println!("account {account_id} does not exist") + + match data.args.output_format { + OutputFormat::Human => { + if let Some(account_info) = account_info { + println!( + "{account_id} has {}", + data.format_balance(account_info.data.free) + ); + } else { + println!("account {account_id} does not exist") + } + } + OutputFormat::Json => { + let view = BalanceView { + account_id: account_id.to_string(), + free_balance: account_info.as_ref().map_or(0, |info| info.data.free), + formatted_balance: account_info.as_ref().map_or("0".to_string(), |info| data.format_balance(info.data.free)), + exists: account_info.is_some(), + }; + println!("{}", serde_json::to_string(&view).map_err(|e| anyhow!(e))?); + } } + Ok(()) } diff --git a/src/commands/blockchain.rs b/src/commands/blockchain.rs index ee46955..0062071 100644 --- a/src/commands/blockchain.rs +++ b/src/commands/blockchain.rs @@ -1,4 +1,6 @@ use crate::*; +use anyhow::anyhow; +use serde::Serialize; /// define blockchain subcommands #[derive(Clone, Default, Debug, clap::Parser)] @@ -23,6 +25,14 @@ pub enum Subcommand { CreateBlock, } +/// Block information for JSON serialization +#[derive(Serialize)] +struct BlockInfoView { + endpoint: String, + finalized_block: u32, + current_block: u32, +} + /// handle blockchain commands pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliError> { let mut data = data.build_client().await?; @@ -36,14 +46,27 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE } Subcommand::RuntimeInfo => { data = data.fetch_system_properties().await?; - commands::runtime::runtime_info(data).await; + commands::runtime::runtime_info(data).await?; } Subcommand::CurrentBlock => { let finalized_number = fetch_finalized_number(&data).await?; let current_number = fetch_latest_number_and_hash(&data).await?.0; - println!("on {}", data.cfg.duniter_endpoint); - println!("finalized block\t{}", finalized_number); - println!("current block\t{}", current_number); + + match data.args.output_format { + OutputFormat::Human => { + println!("on {}", data.cfg.duniter_endpoint); + println!("finalized block\t{}", finalized_number); + println!("current block\t{}", current_number); + } + OutputFormat::Json => { + let view = BlockInfoView { + endpoint: data.cfg.duniter_endpoint.clone(), + finalized_block: finalized_number, + current_block: current_number, + }; + println!("{}", serde_json::to_string(&view).map_err(|e| anyhow!(e))?); + } + } } Subcommand::CreateBlock => { todo!() diff --git a/src/commands/oneshot.rs b/src/commands/oneshot.rs index 44ffee8..086fc9c 100644 --- a/src/commands/oneshot.rs +++ b/src/commands/oneshot.rs @@ -1,4 +1,6 @@ use crate::*; +use anyhow::anyhow; +use serde::Serialize; /// define oneshot account subcommands #[derive(Clone, Default, Debug, clap::Parser)] @@ -64,23 +66,44 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE Ok(()) } +/// Oneshot balance view for JSON serialization +#[derive(Serialize)] +struct OneshotBalanceView { + account_id: String, + balance: u64, +} + /// get balance of oneshot account -pub async fn oneshot_account_balance(data: &Data) -> Result<(), subxt::Error> { - println!( - "balance of oneshot account {} is: {}", - data.address(), - data.client() - .storage() - .at_latest() - .await? - .fetch( - &runtime::storage() - .oneshot_account() - .oneshot_accounts(data.address()), - ) - .await? - .unwrap_or(0) - ); +pub async fn oneshot_account_balance(data: &Data) -> Result<(), GcliError> { + let account_id = data.address(); + let balance = data.client() + .storage() + .at_latest() + .await? + .fetch( + &runtime::storage() + .oneshot_account() + .oneshot_accounts(&account_id), + ) + .await? + .unwrap_or(0); + + match data.args.output_format { + OutputFormat::Human => { + println!( + "balance of oneshot account {} is: {}", + account_id, + balance + ); + } + OutputFormat::Json => { + let view = OneshotBalanceView { + account_id: account_id.to_string(), + balance, + }; + println!("{}", serde_json::to_string(&view).map_err(|e| anyhow!(e))?); + } + } Ok(()) } diff --git a/src/commands/runtime.rs b/src/commands/runtime.rs index d71b102..4045a10 100644 --- a/src/commands/runtime.rs +++ b/src/commands/runtime.rs @@ -1,6 +1,23 @@ use crate::*; +use anyhow::anyhow; +use serde::Serialize; +use std::collections::HashMap; -pub async fn runtime_info(data: Data) { +/// Runtime information for JSON serialization +#[derive(Serialize)] +struct RuntimeInfoView { + identity: HashMap<String, u32>, + certification: HashMap<String, u32>, + wot: HashMap<String, u32>, + membership: HashMap<String, u32>, + smith_members: HashMap<String, u32>, + distance: HashMap<String, serde_json::Value>, + currency: HashMap<String, String>, + provide_randomness: HashMap<String, serde_json::Value>, + universal_dividend: HashMap<String, serde_json::Value>, +} + +pub async fn runtime_info(data: Data) -> Result<(), GcliError> { let api = data.client(); let consts = runtime::constants(); // get constant u32 value @@ -12,137 +29,215 @@ pub async fn runtime_info(data: Data) { // get formatted currency value let getf = |c| data.format_balance(api.constants().at(&c).unwrap()); - // identity - println!("--- identity ---"); - println!( - "confirm period: {} blocks", - getu32(consts.identity().confirm_period()) - ); - println!( - "validation period: {} blocks", - getu32(consts.identity().validation_period()) - ); - println!( - "autorevocation period: {} blocks", - getu32(consts.identity().autorevocation_period()) - ); - println!( - "deletion period: {} blocks", - getu32(consts.identity().deletion_period()) - ); - println!( - "change owner key period: {} blocks", - getu32(consts.identity().change_owner_key_period()) - ); - println!( - "identity creation period: {} blocks", - getu32(consts.identity().idty_creation_period()) - ); - // certification - println!("--- certification ---"); - println!( - "certification period: {} blocks", - getu32(consts.certification().cert_period()) - ); - println!( - "max certs by issuer: {}", - getu32(consts.certification().max_by_issuer()) - ); - println!( - "min received cert to issue cert: {}", - getu32( - consts - .certification() - .min_received_cert_to_be_able_to_issue_cert() - ) - ); - println!( - "certification validity: {} blocks", - getu32(consts.certification().validity_period()) - ); - // wot - println!("--- wot ---"); - println!( - "first issuable on: {}", - getu32(consts.wot().first_issuable_on()) - ); - println!( - "min cert for membership: {}", - getu32(consts.wot().min_cert_for_membership()) - ); - println!( - "min cert for create identity: {}", - getu32(consts.wot().min_cert_for_create_idty_right()) - ); - // membership - println!("--- membership ---"); - println!( - "membership validity: {} blocks", - getu32(consts.membership().membership_period()) - ); - // smith members - println!("--- smith members ---"); - println!( - "max certs by issuer: {}", - getu32(consts.smith_members().max_by_issuer()) - ); - println!( - "min cert for membership: {}", - getu32(consts.smith_members().min_cert_for_membership()) - ); - println!( - "smith inactivity max duration: {}", - getu32(consts.smith_members().smith_inactivity_max_duration()) - ); - // todo membership renewal period - // distance - println!("--- distance ---"); - println!( - "max referee distance: {}", - getu32(consts.distance().max_referee_distance()) - ); - println!( - "min accessible referees: {:?}", - getp(consts.distance().min_accessible_referees()) - ); - println!( - "distance evaluation price: {}", - getf(consts.distance().evaluation_price()) - ); - // currency - println!("--- currency ---"); - println!( - "existential deposit: {}", - getf(consts.balances().existential_deposit()) - ); - // provide randomness - println!("--- provide randomness ---"); - println!( - "max requests: {}", - getu32(consts.provide_randomness().max_requests()) - ); - println!( - "request price: {}", - getf(consts.provide_randomness().request_price()) - ); - // universal dividend - println!("--- universal dividend ---"); - println!( - "max past reevals: {}", - getu32(consts.universal_dividend().max_past_reeval()) - ); - println!( - "square money growth rate: {:?}", - getp(consts.universal_dividend().square_money_growth_rate()) - ); - println!( - "UD creation period: {}", - getu64(consts.universal_dividend().ud_creation_period()) - ); - println!( - "UD reeval period: {}", - getu64(consts.universal_dividend().ud_reeval_period()) - ); - // todo treasury, technical committee, transaction payment, authority members - // consts.system().ss58_prefix() + match data.args.output_format { + OutputFormat::Human => { + // identity + println!("--- identity ---"); + println!( + "confirm period: {} blocks", + getu32(consts.identity().confirm_period()) + ); + println!( + "validation period: {} blocks", + getu32(consts.identity().validation_period()) + ); + println!( + "autorevocation period: {} blocks", + getu32(consts.identity().autorevocation_period()) + ); + println!( + "deletion period: {} blocks", + getu32(consts.identity().deletion_period()) + ); + println!( + "change owner key period: {} blocks", + getu32(consts.identity().change_owner_key_period()) + ); + println!( + "identity creation period: {} blocks", + getu32(consts.identity().idty_creation_period()) + ); + // certification + println!("--- certification ---"); + println!( + "certification period: {} blocks", + getu32(consts.certification().cert_period()) + ); + println!( + "max certs by issuer: {}", + getu32(consts.certification().max_by_issuer()) + ); + println!( + "min received cert to issue cert: {}", + getu32( + consts + .certification() + .min_received_cert_to_be_able_to_issue_cert() + ) + ); + println!( + "certification validity: {} blocks", + getu32(consts.certification().validity_period()) + ); + // wot + println!("--- wot ---"); + println!( + "first issuable on: {}", + getu32(consts.wot().first_issuable_on()) + ); + println!( + "min cert for membership: {}", + getu32(consts.wot().min_cert_for_membership()) + ); + println!( + "min cert for create identity: {}", + getu32(consts.wot().min_cert_for_create_idty_right()) + ); + // membership + println!("--- membership ---"); + println!( + "membership validity: {} blocks", + getu32(consts.membership().membership_period()) + ); + // smith members + println!("--- smith members ---"); + println!( + "max certs by issuer: {}", + getu32(consts.smith_members().max_by_issuer()) + ); + println!( + "min cert for membership: {}", + getu32(consts.smith_members().min_cert_for_membership()) + ); + println!( + "smith inactivity max duration: {}", + getu32(consts.smith_members().smith_inactivity_max_duration()) + ); + // todo membership renewal period + // distance + println!("--- distance ---"); + println!( + "max referee distance: {}", + getu32(consts.distance().max_referee_distance()) + ); + println!( + "min accessible referees: {:?}", + getp(consts.distance().min_accessible_referees()) + ); + println!( + "distance evaluation price: {}", + getf(consts.distance().evaluation_price()) + ); + // currency + println!("--- currency ---"); + println!( + "existential deposit: {}", + getf(consts.balances().existential_deposit()) + ); + // provide randomness + println!("--- provide randomness ---"); + println!( + "max requests: {}", + getu32(consts.provide_randomness().max_requests()) + ); + println!( + "request price: {}", + getf(consts.provide_randomness().request_price()) + ); + // universal dividend + println!("--- universal dividend ---"); + println!( + "max past reevals: {}", + getu32(consts.universal_dividend().max_past_reeval()) + ); + println!( + "square money growth rate: {:?}", + getp(consts.universal_dividend().square_money_growth_rate()) + ); + println!( + "UD creation period: {}", + getu64(consts.universal_dividend().ud_creation_period()) + ); + println!( + "UD reeval period: {}", + getu64(consts.universal_dividend().ud_reeval_period()) + ); + // todo treasury, technical committee, transaction payment, authority members + // consts.system().ss58_prefix() + } + OutputFormat::Json => { + // Create HashMaps for each section + let mut identity = HashMap::new(); + identity.insert("confirm_period".to_string(), getu32(consts.identity().confirm_period())); + identity.insert("validation_period".to_string(), getu32(consts.identity().validation_period())); + identity.insert("autorevocation_period".to_string(), getu32(consts.identity().autorevocation_period())); + identity.insert("deletion_period".to_string(), getu32(consts.identity().deletion_period())); + identity.insert("change_owner_key_period".to_string(), getu32(consts.identity().change_owner_key_period())); + identity.insert("idty_creation_period".to_string(), getu32(consts.identity().idty_creation_period())); + + let mut certification = HashMap::new(); + certification.insert("cert_period".to_string(), getu32(consts.certification().cert_period())); + certification.insert("max_by_issuer".to_string(), getu32(consts.certification().max_by_issuer())); + certification.insert("min_received_cert_to_be_able_to_issue_cert".to_string(), + getu32(consts.certification().min_received_cert_to_be_able_to_issue_cert())); + certification.insert("validity_period".to_string(), getu32(consts.certification().validity_period())); + + let mut wot = HashMap::new(); + wot.insert("first_issuable_on".to_string(), getu32(consts.wot().first_issuable_on())); + wot.insert("min_cert_for_membership".to_string(), getu32(consts.wot().min_cert_for_membership())); + wot.insert("min_cert_for_create_idty_right".to_string(), getu32(consts.wot().min_cert_for_create_idty_right())); + + let mut membership = HashMap::new(); + membership.insert("membership_period".to_string(), getu32(consts.membership().membership_period())); + + let mut smith_members = HashMap::new(); + smith_members.insert("max_by_issuer".to_string(), getu32(consts.smith_members().max_by_issuer())); + smith_members.insert("min_cert_for_membership".to_string(), getu32(consts.smith_members().min_cert_for_membership())); + smith_members.insert("smith_inactivity_max_duration".to_string(), getu32(consts.smith_members().smith_inactivity_max_duration())); + + let mut distance = HashMap::new(); + distance.insert("max_referee_distance".to_string(), + serde_json::to_value(getu32(consts.distance().max_referee_distance())).map_err(|e| anyhow!(e))?); + distance.insert("min_accessible_referees".to_string(), + serde_json::to_value(format!("{:?}", getp(consts.distance().min_accessible_referees()))).map_err(|e| anyhow!(e))?); + distance.insert("evaluation_price".to_string(), + serde_json::to_value(getf(consts.distance().evaluation_price())).map_err(|e| anyhow!(e))?); + + let mut currency = HashMap::new(); + currency.insert("existential_deposit".to_string(), getf(consts.balances().existential_deposit())); + + let mut provide_randomness = HashMap::new(); + provide_randomness.insert("max_requests".to_string(), + serde_json::to_value(getu32(consts.provide_randomness().max_requests())).map_err(|e| anyhow!(e))?); + provide_randomness.insert("request_price".to_string(), + serde_json::to_value(getf(consts.provide_randomness().request_price())).map_err(|e| anyhow!(e))?); + + let mut universal_dividend = HashMap::new(); + universal_dividend.insert("max_past_reeval".to_string(), + serde_json::to_value(getu32(consts.universal_dividend().max_past_reeval())).map_err(|e| anyhow!(e))?); + universal_dividend.insert("square_money_growth_rate".to_string(), + serde_json::to_value(format!("{:?}", getp(consts.universal_dividend().square_money_growth_rate()))).map_err(|e| anyhow!(e))?); + universal_dividend.insert("ud_creation_period".to_string(), + serde_json::to_value(getu64(consts.universal_dividend().ud_creation_period())).map_err(|e| anyhow!(e))?); + universal_dividend.insert("ud_reeval_period".to_string(), + serde_json::to_value(getu64(consts.universal_dividend().ud_reeval_period())).map_err(|e| anyhow!(e))?); + + // Create the view + let view = RuntimeInfoView { + identity, + certification, + wot, + membership, + smith_members, + distance, + currency, + provide_randomness, + universal_dividend, + }; + + println!("{}", serde_json::to_string_pretty(&view).map_err(|e| anyhow!(e))?); + } + } + + Ok(()) } diff --git a/src/commands/smith.rs b/src/commands/smith.rs index c2190c5..4e6789d 100644 --- a/src/commands/smith.rs +++ b/src/commands/smith.rs @@ -5,6 +5,8 @@ use commands::identity::try_get_idty_index_by_name; use runtime::runtime_types::gdev_runtime::opaque::SessionKeys as RuntimeSessionKeys; use std::collections::HashMap; use std::ops::Deref; +use anyhow::anyhow; +use serde::Serialize; type SessionKeys = [u8; 128]; @@ -187,8 +189,23 @@ pub async fn go_offline(data: &Data) -> Result<(), subxt::Error> { .await } -/// get online authorities -pub async fn online(data: &Data) -> Result<(), subxt::Error> { +/// Smith authorities view for JSON serialization +#[derive(Serialize)] +struct SmithAuthoritiesView { + online: Vec<SmithAuthorityView>, + incoming: Vec<SmithAuthorityView>, + outgoing: Vec<SmithAuthorityView>, +} + +/// Smith authority view for JSON serialization +#[derive(Serialize)] +struct SmithAuthorityView { + id: IdtyId, + name: Option<String>, +} + +/// get online smiths +pub async fn online(data: &Data) -> Result<(), GcliError> { let client = data.client(); let online_authorities = client @@ -221,62 +238,121 @@ pub async fn online(data: &Data) -> Result<(), subxt::Error> { .await? .unwrap_or_default(); - if let Some(indexer) = &data.indexer { - let mut names = HashMap::<IdtyId, String>::new(); - indexer - .names_by_indexes(&online_authorities) - .await - .into_iter() - .for_each(|e| { - names.insert(e.0, e.1); - }); - println!("Online:"); - println!( - "{}", - online_authorities - .iter() - .map(|i| names - .get(i) - .map(|n| n.to_string()) - .unwrap_or(format!("{} <no name found>", i))) - .collect::<Vec<String>>() - .join(", ") - ); + match data.args.output_format { + OutputFormat::Human => { + if let Some(indexer) = &data.indexer { + let mut names = HashMap::<IdtyId, String>::new(); + indexer + .names_by_indexes(&online_authorities) + .await + .into_iter() + .for_each(|e| { + names.insert(e.0, e.1); + }); + println!("Online:"); + println!( + "{}", + online_authorities + .iter() + .map(|i| names + .get(i) + .map(|n| n.to_string()) + .unwrap_or(format!("{} <no name found>", i))) + .collect::<Vec<String>>() + .join(", ") + ); - println!("Incoming:"); - println!( - "{}", - incoming_authorities - .iter() - .map(|i| names - .get(i) - .map(|n| n.to_string()) - .unwrap_or(format!("{} <no name found>", i))) - .collect::<Vec<String>>() - .join(", ") - ); + println!("Incoming:"); + println!( + "{}", + incoming_authorities + .iter() + .map(|i| names + .get(i) + .map(|n| n.to_string()) + .unwrap_or(format!("{} <no name found>", i))) + .collect::<Vec<String>>() + .join(", ") + ); - println!("Outgoing:"); - println!( - "{}", - outgoing_authorities - .iter() - .map(|i| names - .get(i) - .map(|n| n.to_string()) - .unwrap_or(format!("{} <no name found>", i))) - .collect::<Vec<String>>() - .join(", ") - ); - } else { - println!("Online:"); - println!("{online_authorities:?}"); + println!("Outgoing:"); + println!( + "{}", + outgoing_authorities + .iter() + .map(|i| names + .get(i) + .map(|n| n.to_string()) + .unwrap_or(format!("{} <no name found>", i))) + .collect::<Vec<String>>() + .join(", ") + ); + } else { + println!("Online:"); + println!("{online_authorities:?}"); - println!("Incoming:"); - println!("{incoming_authorities:?}"); + println!("Incoming:"); + println!("{incoming_authorities:?}"); - println!("Outgoing:"); - println!("{outgoing_authorities:?}"); + println!("Outgoing:"); + println!("{outgoing_authorities:?}"); + } + } + OutputFormat::Json => { + let mut online_view = Vec::new(); + let mut incoming_view = Vec::new(); + let mut outgoing_view = Vec::new(); + + let names = if let Some(indexer) = &data.indexer { + let mut names_map = HashMap::<IdtyId, String>::new(); + let all_authorities = [ + online_authorities.clone(), + incoming_authorities.clone(), + outgoing_authorities.clone(), + ].concat(); + + indexer + .names_by_indexes(&all_authorities) + .await + .into_iter() + .for_each(|e| { + names_map.insert(e.0, e.1); + }); + + names_map + } else { + HashMap::new() + }; + + for id in online_authorities { + online_view.push(SmithAuthorityView { + id, + name: names.get(&id).cloned(), + }); + } + + for id in incoming_authorities { + incoming_view.push(SmithAuthorityView { + id, + name: names.get(&id).cloned(), + }); + } + + for id in outgoing_authorities { + outgoing_view.push(SmithAuthorityView { + id, + name: names.get(&id).cloned(), + }); + } + + let view = SmithAuthoritiesView { + online: online_view, + incoming: incoming_view, + outgoing: outgoing_view, + }; + + println!("{}", serde_json::to_string(&view).map_err(|e| anyhow!(e))?); + } } Ok(()) diff --git a/src/commands/vault.rs b/src/commands/vault.rs index 07b40fc..f9a21db 100644 --- a/src/commands/vault.rs +++ b/src/commands/vault.rs @@ -6,6 +6,7 @@ use crate::entities::vault_account::{AccountTreeNode, ActiveModel, DbAccountId}; use crate::*; use crate::keys::seed_from_cesium; use age::secrecy::Secret; +use anyhow::anyhow; use sea_orm::ActiveValue::Set; use sea_orm::{ConnectionTrait, TransactionTrait}; use sea_orm::ModelTrait; @@ -213,19 +214,33 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let all_account_tree_node_hierarchies = vault_account::fetch_all_base_account_tree_node_hierarchies(db).await?; - let table = display::compute_vault_accounts_table_with_g1v1(&all_account_tree_node_hierarchies, show_g1v1, show_type)?; - - println!("available SS58 Addresses:"); - println!("{table}"); + match data.args.output_format { + OutputFormat::Human => { + let table = display::compute_vault_accounts_table_with_g1v1(&all_account_tree_node_hierarchies, show_g1v1, show_type)?; + println!("available SS58 Addresses:"); + println!("{table}"); + } + OutputFormat::Json => { + let json_view = display::compute_vault_accounts_json(&all_account_tree_node_hierarchies, show_g1v1); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } } ListChoice::Base { show_g1v1, show_type } => { let base_account_tree_nodes = vault_account::fetch_only_base_account_tree_nodes(db).await?; - let table = display::compute_vault_accounts_table_with_g1v1(&base_account_tree_nodes, show_g1v1, show_type)?; - - println!("available <Base> SS58 Addresses:"); - println!("{table}"); + match data.args.output_format { + OutputFormat::Human => { + let table = display::compute_vault_accounts_table_with_g1v1(&base_account_tree_nodes, show_g1v1, show_type)?; + println!("available <Base> SS58 Addresses:"); + println!("{table}"); + } + OutputFormat::Json => { + let json_view = display::compute_vault_accounts_json(&base_account_tree_nodes, show_g1v1); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } } ListChoice::For { address_or_vault_name, @@ -238,29 +253,52 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE let base_account_tree_node = vault_account::get_base_account_tree_node(&account_tree_node); - let table = display::compute_vault_accounts_table_with_g1v1(&[base_account_tree_node], show_g1v1, show_type)?; - - println!( - "available SS58 Addresses linked to {}:", - account_tree_node.borrow().account - ); - println!("{table}"); + match data.args.output_format { + OutputFormat::Human => { + let table = display::compute_vault_accounts_table_with_g1v1(&[base_account_tree_node.clone()], show_g1v1, show_type)?; + println!( + "available SS58 Addresses linked to {}:", + account_tree_node.borrow().account + ); + println!("{table}"); + } + OutputFormat::Json => { + let json_view = display::compute_vault_accounts_json(&[base_account_tree_node], show_g1v1); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } } }, Subcommand::ListFiles => { let vault_key_addresses = fetch_vault_key_addresses(&data).await?; - let table = display::compute_vault_key_files_table(&vault_key_addresses)?; - - println!("available key files (needs to be migrated with command `vault migrate` in order to use them):"); - println!("{table}"); + match data.args.output_format { + OutputFormat::Human => { + let table = display::compute_vault_key_files_table(&vault_key_addresses)?; + println!("available key files (needs to be migrated with command `vault migrate` in order to use them):"); + println!("{table}"); + } + OutputFormat::Json => { + println!("{}", serde_json::to_string(&vault_key_addresses).map_err(|e| anyhow!(e))?); + } + } } Subcommand::Use { address_or_vault_name, } => { let account = retrieve_vault_account(db, address_or_vault_name).await?; - println!("Using: {}", account); + match data.args.output_format { + OutputFormat::Human => { + println!("Using: {}", account); + } + OutputFormat::Json => { + let json_view = serde_json::json!({ + "address": account.to_string() + }); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } let updated_cfg = conf::Config { address: Some(account.address.0), @@ -516,7 +554,17 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE password, )?; - println!("Substrate URI: '{account_to_derive_secret_suri}'") + match data.args.output_format { + OutputFormat::Human => { + println!("Substrate URI: '{account_to_derive_secret_suri}'") + } + OutputFormat::Json => { + let json_view = serde_json::json!({ + "substrate_uri": account_to_derive_secret_suri + }); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } } Subcommand::Migrate => { println!("Migrating existing key files to db"); @@ -584,7 +632,19 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE println!("Migration done"); } Subcommand::Where => { - println!("{}", data.project_dir.data_dir().to_str().unwrap()); + let data_dir = data.project_dir.data_dir().to_str().unwrap(); + + match data.args.output_format { + OutputFormat::Human => { + println!("{}", data_dir); + } + OutputFormat::Json => { + let json_view = serde_json::json!({ + "data_dir": data_dir + }); + println!("{}", serde_json::to_string(&json_view).map_err(|e| anyhow!(e))?); + } + } } }; diff --git a/src/commands/vault/display.rs b/src/commands/vault/display.rs index 5f024d6..35e952e 100644 --- a/src/commands/vault/display.rs +++ b/src/commands/vault/display.rs @@ -4,6 +4,7 @@ use crate::entities::vault_account::AccountTreeNode; use crate::keys::CryptoScheme; use crate::utils::GcliError; use comfy_table::{Cell, Table}; +use serde::Serialize; use std::cell::RefCell; use std::rc::Rc; use std::str; @@ -181,6 +182,91 @@ pub fn compute_vault_accounts_row_with_g1v1( Ok(rows) } +/// Serializable structure for JSON output +#[derive(Serialize)] +pub struct VaultAccountView { + address: String, + crypto_scheme: Option<String>, + wallet_type: Option<String>, + path: String, + name: String, + g1v1_public_key: Option<String>, + children: Vec<VaultAccountView>, +} + +/// Compute a serializable structure for JSON output +pub fn compute_vault_accounts_json( + account_tree_nodes: &[Rc<RefCell<AccountTreeNode>>], + show_g1v1: bool, +) -> Vec<VaultAccountView> { + let mut result = Vec::new(); + + for account_tree_node in account_tree_nodes { + result.push(compute_vault_account_json(account_tree_node, show_g1v1)); + } + + result +} + +/// Compute a serializable structure for a single account tree node +fn compute_vault_account_json( + account_tree_node: &Rc<RefCell<AccountTreeNode>>, + show_g1v1: bool, +) -> VaultAccountView { + let empty_string = "".to_string(); + let borrowed_node = account_tree_node.borrow(); + + let name = if let Some(name) = borrowed_node.account.name.clone() { + name + } else if let Some(computed_name) = vault_account::compute_name_account_tree_node(account_tree_node) { + format!("<{}>", computed_name) + } else { + empty_string.clone() + }; + + let (path, crypto_scheme, wallet_type, g1v1_public_key) = if let Some(path) = borrowed_node.account.path.clone() { + (path, None, None, None) + } else { + let crypto_scheme = borrowed_node.account.crypto_scheme.map(|cs| { + let scheme = CryptoScheme::from(cs); + let scheme_str: &str = scheme.into(); + scheme_str.to_string() + }); + + let wallet_type = borrowed_node.account.secret_format.map(|sf| { + match crate::keys::SecretFormat::from(sf) { + crate::keys::SecretFormat::G1v1 => "G1v1".to_string(), + crate::keys::SecretFormat::Substrate => "Mnemonic".to_string(), + crate::keys::SecretFormat::Seed => "Seed".to_string(), + crate::keys::SecretFormat::Predefined => "Predefined".to_string(), + } + }); + + let g1v1_public_key = if show_g1v1 && crypto_scheme.as_deref() == Some("ed25519") { + Some(cesium::compute_g1v1_public_key_from_ed25519_account_id(&borrowed_node.account.address.0)) + } else { + None + }; + + (format!("<{}>", borrowed_node.account.account_type()), crypto_scheme, wallet_type, g1v1_public_key) + }; + + let mut children = Vec::new(); + for child in &borrowed_node.children { + children.push(compute_vault_account_json(child, show_g1v1)); + } + + VaultAccountView { + address: borrowed_node.account.address.to_string(), + crypto_scheme, + wallet_type, + path, + name, + g1v1_public_key, + children, + } +} + #[cfg(test)] mod tests { mod vault_accounts_table_tests { diff --git a/src/conf.rs b/src/conf.rs index 509e0c5..09c83f4 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -2,6 +2,7 @@ use crate::entities::vault_account; use crate::entities::vault_account::DbAccountId; use crate::*; use serde::{Deserialize, Serialize}; +use anyhow::anyhow; const APP_NAME: &str = "gcli"; @@ -73,6 +74,15 @@ pub enum Subcommand { Default, } +/// Config view for JSON serialization +#[derive(Serialize)] +struct ConfigView { + duniter_endpoint: String, + indexer_endpoint: String, + address: Option<String>, + vault_account: Option<String>, +} + /// handle conf command pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliError> { // match subcommand @@ -84,15 +94,41 @@ pub async fn handle_command(data: Data, command: Subcommand) -> Result<(), GcliE ); } Subcommand::Show => { - println!("{}", data.cfg); - if let Some(ref account_id) = data.cfg.address { - if let Some(account) = vault_account::find_by_id( - data.connect_db(), - &DbAccountId::from(account_id.clone()), - ) - .await? - { - println!("(Vault: {})", account); + match data.args.output_format { + OutputFormat::Human => { + println!("{}", data.cfg); + if let Some(ref account_id) = data.cfg.address { + if let Some(account) = vault_account::find_by_id( + data.connect_db(), + &DbAccountId::from(account_id.clone()), + ) + .await? + { + println!("(Vault: {})", account); + } + } + } + OutputFormat::Json => { + let mut vault_account_str = None; + if let Some(ref account_id) = data.cfg.address { + if let Some(account) = vault_account::find_by_id( + data.connect_db(), + &DbAccountId::from(account_id.clone()), + ) + .await? + { + vault_account_str = Some(account.to_string()); + } + } + + let view = ConfigView { + duniter_endpoint: data.cfg.duniter_endpoint.clone(), + indexer_endpoint: data.cfg.indexer_endpoint.clone(), + address: data.cfg.address.as_ref().map(|a| a.to_string()), + vault_account: vault_account_str, + }; + + println!("{}", serde_json::to_string(&view).map_err(|e| anyhow!(e))?); } } } -- GitLab