Skip to content

Commit

Permalink
feat(wallet): add view key commands (#6426)
Browse files Browse the repository at this point in the history
Description
---
Adds commands for exporting a view key and spend key for an existing
wallet, and also commands for creating a read-only wallet that only has
access to the view key.

Note this is only possible to the great work by @SWvheerden who enabled
this functionality in the wallet.

Motivation and Context
---
This allows you to keep an offline cold wallet that has spend access,
and at the same time listen for received funds and act on them. This
enables ecommerce and exchange support without the danger of running a
hot spending wallet.

How Has This Been Tested?
---
Tested locally

What process can a PR reviewer use to test or verify this change?
---
You can follow the steps in the [exchange
guide](tari-project/tari-dot-com#231) to use all
of the additions in this PR

<!-- Checklist -->
<!-- 1. Is the title of your PR in the form that would make nice release
notes? The title, excluding the conventional commit
tag, will be included exactly as is in the CHANGELOG, so please think
about it carefully. -->


Breaking Changes
---

- [x] None
- [ ] Requires data directory on base node to be deleted
- [ ] Requires hard fork
- [ ] Other - Please specify

<!-- Does this include a breaking change? If so, include this line as a
footer -->
<!-- BREAKING CHANGE: Description what the user should do, e.g. delete a
database, resync the chain -->
  • Loading branch information
stringhandler authored Aug 5, 2024
1 parent caa7097 commit 77e5ca9
Show file tree
Hide file tree
Showing 12 changed files with 346 additions and 198 deletions.
380 changes: 191 additions & 189 deletions applications/minotari_app_grpc/proto/wallet.proto

Large diffs are not rendered by default.

29 changes: 29 additions & 0 deletions applications/minotari_console_wallet/src/automation/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2163,6 +2163,35 @@ 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_view_key().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(),
},
}
}
94 changes: 90 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,44 @@ 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_hex(&vk) {
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 {
match PublicKey::from_hex(&sk) {
Ok(pk) => pk,
Err(_) => {
println!("Invalid spend key provided");
panic!("Invalid spend key provided");
},
}
} else {
prompt_public_key("Enter spend key: ").expect("Spend key provided was invalid")
};

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 +951,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
10 changes: 9 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,13 @@ 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
1 change: 1 addition & 0 deletions applications/minotari_console_wallet/src/wallet_modes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,7 @@ mod test {
CliCommands::CreateTlsCerts => {},
CliCommands::PreMineSpendBackupUtxo(_) => {},
CliCommands::Sync(_) => {},
CliCommands::ExportViewKeyAndSpendKey(_) => {},
}
}
assert!(
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
2 changes: 2 additions & 0 deletions integration_tests/src/wallet_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,8 @@ pub fn get_default_cli() -> Cli {
grpc_address: None,
command2: None,
profile_with_tokio_console: false,
view_private_key: None,
spend_key: None,
}
}

Expand Down

0 comments on commit 77e5ca9

Please sign in to comment.