Skip to content

Commit

Permalink
rusk-wallet: Gracefully exit on interrupt
Browse files Browse the repository at this point in the history
Ask confimration before deleting cache
  • Loading branch information
Daksh14 committed Oct 23, 2024
1 parent 0dd0973 commit be20743
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 20 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,9 @@ dusk-merkle = "=0.5.3"
dusk-plonk = { version = "=0.20.2", default-features = false }
dusk-poseidon = "=0.40.0"
jubjub-schnorr = { version = "=0.5.0", default-features = false }
kadcast = "=0.7.0"

# we leave kadcast open until a stable release is out
kadcast = "0.7.0-rc.10"
phoenix-circuits = { version = "=0.4.0", default-features = false }
phoenix-core = { version = "=0.32.0", default-features = false }
# we leave piecrust open until a stable release is out
Expand Down
2 changes: 2 additions & 0 deletions rusk-wallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ tracing-subscriber = { workspace = true, features = [
"json",
] }

fastwebsockets = "0.8.0"

rkyv = { workspace = true }

konst = { workspace = true }
Expand Down
7 changes: 7 additions & 0 deletions rusk-wallet/src/bin/io/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,13 @@ pub(crate) fn ask_confirm() -> anyhow::Result<bool> {
Ok(a.as_bool().expect("answer to be a bool"))
}

/// Asks the user for confirmation before deleting cache
pub(crate) fn ask_confirm_erase_cache(msg: &str) -> anyhow::Result<bool> {
let q = requestty::Question::confirm("confirm").message(msg).build();
let a = requestty::prompt_one(q)?;
Ok(a.as_bool().expect("answer to be a bool"))
}

/// Request a receiver address
pub(crate) fn request_rcvr_addr(addr_for: &str) -> anyhow::Result<Address> {
// let the user input the receiver address
Expand Down
50 changes: 44 additions & 6 deletions rusk-wallet/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ mod settings;
pub(crate) use command::{Command, RunResult};
pub(crate) use menu::Menu;

use clap::Parser;
use rocksdb::ErrorKind;
use std::fs::{self, File};
use std::io::Write;
use tracing::{error, info, warn, Level};

use bip39::{Language, Mnemonic, MnemonicType};
use clap::Parser;
Expand Down Expand Up @@ -71,7 +74,7 @@ async fn connect<F>(
mut wallet: Wallet<F>,
settings: &Settings,
status: fn(&str),
) -> Wallet<F>
) -> anyhow::Result<Wallet<F>>
where
F: SecureWalletFile + std::fmt::Debug,
{
Expand All @@ -85,12 +88,44 @@ where

// check for connection errors
match con {
Err(Error::RocksDB(e)) => panic!{"Please reset the cache! {e}"},
Err(e) => warn!("[OFFLINE MODE]: Unable to connect to Rusk, limited functionality available: {e}"),
Err(Error::RocksDB(e)) => {
wallet.close();

let msg = match e.kind() {
ErrorKind::InvalidArgument => {
format!("You've used the wrong key to open the cache database \n\r\n\r{0: <1} delete the cache? (Alternatively specify -p (--profile) flag to open with a different cache db)", "[ALERT]")
},
ErrorKind::Corruption => {
format!("The database appears to be corrupted \n\r\n\r{0: <1} delete the cache?", "[ALERT]")
},
_ => {
format!("Unknown database error {:?} \n\r\n\r{1: <1} delete the cache?", e, "[ALERT]")
}
};

match prompt::ask_confirm_erase_cache(&msg)? {
true => {
if let Some(io_err) = wallet.delete_cache().err() {
error!("Error while deleting the cache: {io_err}");
}

info!("Restart the wallet to create new cache and sync with network");
},
false => {
info!("Wallet will now exit, reset the cache manually");
},

}

// Exit because we cannot proceed because of db error
// wallet is already closed
std::process::exit(1);
},
Err(ref e) => warn!("[OFFLINE MODE]: Unable to connect to Rusk, limited functionality available: {e}"),
_ => {}
}
};

wallet
Ok(wallet)
}

async fn exec() -> anyhow::Result<()> {
Expand Down Expand Up @@ -284,7 +319,7 @@ async fn exec() -> anyhow::Result<()> {
false => status::interactive,
};

wallet = connect(wallet, &settings, status_cb).await;
wallet = connect(wallet, &settings, status_cb).await?;

// run command
match cmd {
Expand Down Expand Up @@ -383,5 +418,8 @@ async fn exec() -> anyhow::Result<()> {
}
}

// Gracefully close the wallet
wallet.close();

Ok(())
}
3 changes: 1 addition & 2 deletions rusk-wallet/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,8 +233,7 @@ impl Cache {
Ok(notes)
}

pub fn close(&self) -> Result<(), Error> {
pub fn close(&self) {
self.db.cancel_all_background_work(false);
Ok(())
}
}
4 changes: 1 addition & 3 deletions rusk-wallet/src/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,9 +400,7 @@ impl State {
}

pub fn close(&mut self) {
// UNWRAP: its okay to panic here because we're closing the database
// if there's an error we want an exception to happen
self.cache().close().unwrap();
self.cache().close();
let store = &mut self.store;

// if there's sync handle we abort it
Expand Down
30 changes: 22 additions & 8 deletions rusk-wallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,13 +244,7 @@ impl<F: SecureWalletFile + Debug> Wallet<F> {
_=> {},
}

let cache_dir = {
if let Some(file) = &self.file {
file.path().cache_dir()
} else {
return Err(Error::WalletFileMissing);
}
};
let cache_dir = self.cache_path()?;

// create a state client
self.state = Some(State::new(
Expand Down Expand Up @@ -398,7 +392,20 @@ impl<F: SecureWalletFile + Debug> Wallet<F> {
derive_phoenix_vk(seed, index)
}

/// Returns the shielded key for a given index.
/// get cache database path
pub(crate) fn cache_path(&self) -> Result<PathBuf, Error> {
let cache_dir = {
if let Some(file) = &self.file {
file.path().cache_dir()
} else {
return Err(Error::WalletFileMissing);
}
};

Ok(cache_dir)
}

/// Returns the Phoenix public-key for a given index.
///
/// # Errors
/// This will error if the wallet doesn't have a profile stored for the
Expand Down Expand Up @@ -579,6 +586,13 @@ impl<F: SecureWalletFile + Debug> Wallet<F> {
Ok(network_last_pos == db_pos)
}

/// Erase the cache directory
pub fn delete_cache(&mut self) -> Result<(), Error> {
let path = self.cache_path()?;

std::fs::remove_dir_all(path).map_err(Error::IO)
}

/// Close the wallet and zeroize the seed
pub fn close(&mut self) {
self.store.inner_mut().zeroize();
Expand Down

0 comments on commit be20743

Please sign in to comment.