Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wallet): add view key commands #6426

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
380 changes: 191 additions & 189 deletions applications/minotari_app_grpc/proto/wallet.proto

Large diffs are not rendered by default.

35 changes: 34 additions & 1 deletion applications/minotari_console_wallet/src/automation/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ use tari_core::{
blocks::pre_mine::{create_pre_mine_genesis_block_file, get_pre_mine_items, PreMineItem},
covenants::Covenant,
transactions::{
key_manager::TransactionKeyManagerInterface,
key_manager::{SecretTransactionKeyManagerInterface, TransactionKeyManagerInterface},
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should not use this trait:
#6447

tari_amount::{uT, MicroMinotari, Minotari},
transaction_components::{
encrypted_data::PaymentId,
Expand Down Expand Up @@ -2163,6 +2163,39 @@ pub async fn command_runner(
Err(e) => eprintln!("GetBalance error! {}", e),
}
},
ExportViewKeyAndSpendKey(args) => {
let view_key = wallet.key_manager_service.get_view_key().await?;
let spend_key = wallet.key_manager_service.get_spend_key().await?;
let view_key_hex = view_key.pub_key.to_hex();
let private_view_key_hex = wallet
.key_manager_service
.get_private_key(&view_key.key_id)
.await?
.to_hex();
let spend_key_hex = spend_key.pub_key.to_hex();
let output_file = args.output_file;
#[derive(Serialize)]
struct ViewKeyFile {
view_key: String,
public_view_key: String,
spend_key: String,
}
let view_key_file = ViewKeyFile {
view_key: private_view_key_hex.clone(),
public_view_key: view_key_hex.clone(),
spend_key: spend_key_hex.clone(),
};
let view_key_file_json =
serde_json::to_string(&view_key_file).map_err(|e| CommandError::JsonFile(e.to_string()))?;
if let Some(file) = output_file {
let file = File::create(file).map_err(|e| CommandError::JsonFile(e.to_string()))?;
let mut file = LineWriter::new(file);
writeln!(file, "{}", view_key_file_json).map_err(|e| CommandError::JsonFile(e.to_string()))?;
} else {
println!("View key: {}", private_view_key_hex);
println!("Spend key: {}", spend_key_hex);
}
},
}
}

Expand Down
12 changes: 12 additions & 0 deletions applications/minotari_console_wallet/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ pub struct Cli {
pub command2: Option<CliCommands>,
#[clap(long, alias = "profile")]
pub profile_with_tokio_console: bool,
// For read only wallets
#[clap(long)]
pub view_private_key: Option<String>,
#[clap(long)]
pub spend_key: Option<String>,
}

impl ConfigOverrideProvider for Cli {
Expand Down Expand Up @@ -145,6 +150,7 @@ pub enum CliCommands {
RegisterValidatorNode(RegisterValidatorNodeArgs),
CreateTlsCerts,
Sync(SyncArgs),
ExportViewKeyAndSpendKey(ExportViewKeyAndSpendKeyArgs),
}

#[derive(Debug, Args, Clone)]
Expand Down Expand Up @@ -335,6 +341,12 @@ pub struct ExportTxArgs {
pub output_file: Option<PathBuf>,
}

#[derive(Debug, Args, Clone)]
pub struct ExportViewKeyAndSpendKeyArgs {
#[clap(short, long)]
pub output_file: Option<PathBuf>,
}

#[derive(Debug, Args, Clone)]
pub struct ImportTxArgs {
#[clap(short, long)]
Expand Down
3 changes: 3 additions & 0 deletions applications/minotari_console_wallet/src/grpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub fn convert_to_transaction_event(event: String, source: TransactionWrapper) -
direction: completed.direction.to_string(),
amount: completed.amount.as_u64(),
message: completed.message.to_string(),
payment_id: completed.payment_id.map(|id| id.to_bytes()).unwrap_or_default(),
},
TransactionWrapper::Outbound(outbound) => TransactionEvent {
event,
Expand All @@ -39,6 +40,7 @@ pub fn convert_to_transaction_event(event: String, source: TransactionWrapper) -
direction: "outbound".to_string(),
amount: outbound.amount.as_u64(),
message: outbound.message,
payment_id: vec![],
},
TransactionWrapper::Inbound(inbound) => TransactionEvent {
event,
Expand All @@ -49,6 +51,7 @@ pub fn convert_to_transaction_event(event: String, source: TransactionWrapper) -
direction: "inbound".to_string(),
amount: inbound.amount.as_u64(),
message: inbound.message.clone(),
payment_id: vec![],
},
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,7 @@ impl wallet_server::Wallet for WalletGrpcServer {
.get_signature()
.to_vec(),
message: txn.message.clone(),
payment_id: txn.payment_id.as_ref().map(|id| id.to_bytes()).unwrap_or_default(),
}),
};
match sender.send(Ok(response)).await {
Expand Down Expand Up @@ -1100,6 +1101,7 @@ fn simple_event(event: &str) -> TransactionEvent {
direction: event.to_string(),
amount: 0,
message: String::default(),
payment_id: vec![],
}
}

Expand All @@ -1121,6 +1123,7 @@ fn convert_wallet_transaction_into_transaction_info(
excess_sig: Default::default(),
timestamp: tx.timestamp.timestamp() as u64,
message: tx.message,
payment_id: vec![],
},
PendingOutbound(tx) => TransactionInfo {
tx_id: tx.tx_id.into(),
Expand All @@ -1134,6 +1137,7 @@ fn convert_wallet_transaction_into_transaction_info(
excess_sig: Default::default(),
timestamp: tx.timestamp.timestamp() as u64,
message: tx.message,
payment_id: vec![],
},
Completed(tx) => TransactionInfo {
tx_id: tx.tx_id.into(),
Expand All @@ -1151,6 +1155,7 @@ fn convert_wallet_transaction_into_transaction_info(
.map(|s| s.get_signature().to_vec())
.unwrap_or_default(),
message: tx.message,
payment_id: tx.payment_id.map(|id| id.to_bytes()).unwrap_or_default(),
},
}
}
97 changes: 93 additions & 4 deletions applications/minotari_console_wallet/src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

use std::{fs, io, path::PathBuf, str::FromStr, sync::Arc, time::Instant};

use crossterm::terminal::{disable_raw_mode, enable_raw_mode, is_raw_mode_enabled};
use log::*;
use minotari_app_utilities::{consts, identity_management::setup_node_identity};
#[cfg(feature = "ledger")]
Expand Down Expand Up @@ -53,7 +54,7 @@ use tari_common::{
use tari_common_types::{
key_branches::TransactionKeyManagerBranch,
types::{PrivateKey, PublicKey},
wallet_types::{LedgerWallet, WalletType},
wallet_types::{LedgerWallet, ProvidedKeysWallet, WalletType},
};
use tari_comms::{
multiaddr::Multiaddr,
Expand All @@ -77,7 +78,7 @@ use tari_key_manager::{
};
use tari_p2p::{peer_seeds::SeedPeer, TransportType};
use tari_shutdown::ShutdownSignal;
use tari_utilities::{hex::Hex, ByteArray, SafePassword};
use tari_utilities::{encoding::Base58, hex::Hex, ByteArray, SafePassword};
use zxcvbn::zxcvbn;

use crate::{
Expand All @@ -98,6 +99,7 @@ pub enum WalletBoot {
New,
Existing,
Recovery,
ViewAndSpendKey,
}

/// Get and confirm a passphrase from the user, with feedback
Expand Down Expand Up @@ -758,6 +760,10 @@ fn boot(cli: &Cli, wallet_config: &WalletConfig) -> Result<WalletBoot, ExitError
return Ok(WalletBoot::Recovery);
}

if !wallet_exists && cli.view_private_key.is_some() && cli.spend_key.is_some() {
return Ok(WalletBoot::ViewAndSpendKey);
}

if wallet_exists {
// normal startup of existing wallet
Ok(WalletBoot::Existing)
Expand All @@ -780,7 +786,8 @@ fn boot(cli: &Cli, wallet_config: &WalletConfig) -> Result<WalletBoot, ExitError

loop {
println!("1. Create a new wallet.");
println!("2. Recover wallet from seed words.");
println!("2. Recover wallet from seed words or hardware device.");
println!("3. Create a read-only wallet using a view key.");
let readline = rl.readline(">> ");
match readline {
Ok(line) => {
Expand All @@ -793,6 +800,9 @@ fn boot(cli: &Cli, wallet_config: &WalletConfig) -> Result<WalletBoot, ExitError
// recover wallet
return Ok(WalletBoot::Recovery);
},
"3" => {
return Ok(WalletBoot::ViewAndSpendKey);
},
_ => continue,
}
},
Expand Down Expand Up @@ -833,6 +843,10 @@ pub(crate) fn boot_with_password(
debug!(target: LOG_TARGET, "Prompting for passphrase for existing wallet.");
prompt_password("Enter wallet passphrase: ")?
},
WalletBoot::ViewAndSpendKey => {
debug!(target: LOG_TARGET, "Prompting for passphrase for view key wallet.");
get_new_passphrase("Create wallet passphrase: ", "Confirm wallet passphrase: ")?
},
};

Ok((boot_mode, password))
Expand All @@ -842,12 +856,47 @@ pub fn prompt_wallet_type(
boot_mode: WalletBoot,
wallet_config: &WalletConfig,
non_interactive: bool,
view_private_key: Option<String>,
spend_key: Option<String>,
) -> Option<WalletType> {
if non_interactive {
if non_interactive && !matches!(boot_mode, WalletBoot::ViewAndSpendKey) {
return Some(WalletType::default());
}

match boot_mode {
WalletBoot::ViewAndSpendKey => {
let view_key = if let Some(vk) = view_private_key {
match PrivateKey::from_base58(&vk) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in the command window you use hex, here its base58?

Ok(pk) => pk,
Err(_) => {
println!("Invalid view key provided");
panic!("Invalid view key provided");
},
}
} else {
prompt_private_key("Enter view key: ").expect("View key provided was invalid")
};
let spend_key = if
let Some(sk) = spend_key {
let spend_key = match PublicKey::from_base58(&sk) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same as other command hex vs base58

Ok(pk) => pk,
Err(_) => {
println!("Invalid spend key provided");
panic!("Invalid spend key provided");
},
};
spend_key
} else {
let spend_key = prompt_public_key("Enter spend key: ").expect("Spend key provided was invalid");
spend_key
};

Some(WalletType::ProvidedKeys(ProvidedKeysWallet {
view_key,
public_spend_key: spend_key,
private_spend_key: None,
}))
},
WalletBoot::New | WalletBoot::Recovery => {
#[cfg(not(feature = "ledger"))]
return Some(WalletType::default());
Expand Down Expand Up @@ -905,6 +954,46 @@ pub fn prompt_ledger_account(boot_mode: WalletBoot) -> Option<u64> {
}
}

pub fn prompt_private_key(prompt: &str) -> Option<PrivateKey> {
// see what we type, as we type it
let must_re_enable_raw_mode = is_raw_mode_enabled().expect("Could not determine raw mode status");
disable_raw_mode().expect("Could not disable raw mode");

println!("{} (hex)", prompt);
let mut input = "".to_string();
io::stdin().read_line(&mut input).unwrap();
let input = input.trim();
if must_re_enable_raw_mode {
enable_raw_mode().expect("Could not enable raw mode");
}
match PrivateKey::from_canonical_bytes(&Vec::<u8>::from_hex(input).expect("Bad hex data")) {
Ok(pk) => Some(pk),
Err(e) => {
panic!("Bad private key: {}", e)
},
}
}

pub fn prompt_public_key(prompt: &str) -> Option<PublicKey> {
// see what we type, as we type it
let must_re_enable_raw_mode = is_raw_mode_enabled().expect("Could not determine raw mode status");
disable_raw_mode().expect("Could not disable raw mode");
println!("{} (hex or base58)", prompt);
let mut input = "".to_string();
io::stdin().read_line(&mut input).unwrap();
if must_re_enable_raw_mode {
enable_raw_mode().expect("Could not enable raw mode");
}
let input = input.trim();
match PublicKey::from_hex(input) {
Ok(pk) => Some(pk),
Err(_) => match PublicKey::from_base58(input) {
Ok(pk) => Some(pk),
Err(_) => None,
},
}
}

#[cfg(test)]
mod test {
use tari_utilities::SafePassword;
Expand Down
4 changes: 3 additions & 1 deletion applications/minotari_console_wallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ pub fn run_wallet(shutdown: &mut Shutdown, runtime: Runtime, config: &mut Applic
grpc_address: None,
command2: None,
profile_with_tokio_console: false,
view_private_key: None,
spend_key: None
};

run_wallet_with_cli(shutdown, runtime, config, cli)
Expand Down Expand Up @@ -128,7 +130,7 @@ pub fn run_wallet_with_cli(

let recovery_seed = get_recovery_seed(boot_mode, &cli)?;

let wallet_type = prompt_wallet_type(boot_mode, &config.wallet, cli.non_interactive_mode);
let wallet_type = prompt_wallet_type(boot_mode, &config.wallet, cli.non_interactive_mode, cli.view_private_key.clone(), cli.spend_key.clone());

// get command line password if provided
let seed_words_file_name = cli.seed_words_file_name.clone();
Expand Down
5 changes: 1 addition & 4 deletions base_layer/core/src/transactions/key_manager/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,10 +353,7 @@ where TBackend: KeyManagerBackend<PublicKey> + 'static

// If we're trying to access any of the private keys, just say no bueno
if &TransactionKeyManagerBranch::Spend.get_branch_key() == branch {
return wallet
.private_spend_key
.clone()
.ok_or(KeyManagerServiceError::ImportedPrivateKeyInaccessible);
return Ok(PrivateKey::default());
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this will have a conflict anyway, make sure to choose the current code in origin. This error here is fixed.

}
},
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl PaymentId {
}
}

pub fn as_bytes(&self) -> Vec<u8> {
pub fn to_bytes(&self) -> Vec<u8> {
match self {
PaymentId::Empty => Vec::new(),
PaymentId::U64(v) => (*v).to_le_bytes().to_vec(),
Expand Down Expand Up @@ -166,7 +166,7 @@ impl EncryptedData {
let mut bytes = Zeroizing::new(vec![0; SIZE_VALUE + SIZE_MASK + payment_id.get_size()]);
bytes[..SIZE_VALUE].clone_from_slice(value.as_u64().to_le_bytes().as_ref());
bytes[SIZE_VALUE..SIZE_VALUE + SIZE_MASK].clone_from_slice(mask.as_bytes());
bytes[SIZE_VALUE + SIZE_MASK..].clone_from_slice(&payment_id.as_bytes());
bytes[SIZE_VALUE + SIZE_MASK..].clone_from_slice(&payment_id.to_bytes());

// Produce a secure random nonce
let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1965,7 +1965,7 @@ impl CompletedTransactionSql {
let transaction_bytes =
bincode::serialize(&c.transaction).map_err(|e| TransactionStorageError::BincodeSerialize(e.to_string()))?;
let payment_id = match c.payment_id {
Some(id) => Some(id.as_bytes()),
Some(id) => Some(id.to_bytes()),
None => Some(Vec::new()),
};
let output = Self {
Expand Down
2 changes: 1 addition & 1 deletion base_layer/wallet_ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ impl From<DbWalletOutput> for TariUtxo {
.expect("failed to obtain hex from a commitment")
.into_raw(),
payment_id: CString::new(
String::from_utf8(x.payment_id.as_bytes()).unwrap_or_else(|_| "Invalid".to_string()),
String::from_utf8(x.payment_id.to_bytes()).unwrap_or_else(|_| "Invalid".to_string()),
)
.expect("failed to obtain string from a payment id")
.into_raw(),
Expand Down
Loading