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

Store and recall encrypted slate during send operations #56

Merged
merged 1 commit into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
71 changes: 40 additions & 31 deletions crates/core/src/config/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::backup::CompressionFormat;
use crate::error::FilesystemError;
use serde::{Deserialize, Serialize};
use std::f32::consts::E;
use std::fmt::{self, Display, Formatter};
use std::path::PathBuf;

Expand Down Expand Up @@ -70,10 +71,24 @@ pub struct Config {
}

impl Config {
pub fn add_wallet(&mut self, wallet: Wallet) -> usize{
pub fn add_wallet(&mut self, wallet: Wallet) -> usize {
self.wallets.push(wallet);
self.wallets.len() - 1
}

pub fn get_wallet_slatepack_dir(&self) -> Option<String> {
if let Some(i) = self.current_wallet_index.as_ref() {
if let Some(ref tld) = self.wallets[*i].tld {
let slate_dir = format!("{}/{}", tld.as_os_str().to_str().unwrap(), "slatepack");
let _ = std::fs::create_dir_all(slate_dir.clone());
Some(slate_dir)
} else {
None
}
} else {
None
}
}
}

impl PersistentData for Config {
Expand Down Expand Up @@ -167,10 +182,7 @@ impl std::fmt::Display for Language {

impl Language {
// Alphabetically sorted based on their local name (@see `impl Display`).
pub const ALL: [Language; 2] = [
Language::German,
Language::English,
];
pub const ALL: [Language; 2] = [Language::German, Language::English];

pub const fn language_code(self) -> &'static str {
match self {
Expand All @@ -186,10 +198,11 @@ impl Default for Language {
}
}


#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, PartialOrd, Ord)]
#[derive(
Default, Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash, PartialOrd, Ord,
)]
pub enum Currency {
#[default]
#[default]
GRIN,
BTC,
USD,
Expand All @@ -211,35 +224,31 @@ impl std::fmt::Display for Currency {

impl Currency {
// Alphabetically sorted based on their local name (@see `impl Display`).
pub const ALL: [Currency; 3] = [
Currency::BTC,
Currency::GRIN,
Currency::USD,
];
pub const ALL: [Currency; 3] = [Currency::BTC, Currency::GRIN, Currency::USD];

pub fn shortname(&self) -> String {
match *self {
Currency::BTC => "btc".to_owned(),
Currency::GRIN => "grin".to_owned(),
Currency::USD => "usd".to_owned(),
}
}
match *self {
Currency::BTC => "btc".to_owned(),
Currency::GRIN => "grin".to_owned(),
Currency::USD => "usd".to_owned(),
}
}

pub fn symbol(&self) -> String {
match *self {
Currency::BTC => "₿".to_owned(),
Currency::GRIN => "".to_owned(),
Currency::USD => "$".to_owned(),
}
}
match *self {
Currency::BTC => "₿".to_owned(),
Currency::GRIN => "".to_owned(),
Currency::USD => "$".to_owned(),
}
}

pub fn precision(&self) -> usize {
match *self {
Currency::BTC => 8,
Currency::GRIN => 9,
Currency::USD => 4,
}
}
match *self {
Currency::BTC => 8,
Currency::GRIN => 9,
Currency::USD => 4,
}
}
}

/// Returns a Config.
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ pub enum GrinWalletInterfaceError {
ForeignAPINotInstantiated,
#[error("Invalid Slatepack Address")]
InvalidSlatepackAddress,
#[error("Can't load slatepack file at {file}")]
InvalidSlatepackFile{file: String},
}

#[derive(thiserror::Error, Debug)]
Expand Down
12 changes: 6 additions & 6 deletions crates/core/src/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ where
wallet_interface: Arc<RwLock<WalletInterface<L, C>>>,
init_args: InitTxArgs,
dest_slatepack_address: String,
) -> Result<String, GrinWalletInterfaceError> {
) -> Result<(Slate, String), GrinWalletInterfaceError> {
let w = wallet_interface.write().unwrap();
let _address = match SlatepackAddress::try_from(dest_slatepack_address.as_str()) {
Ok(a) => Some(a),
Expand All @@ -450,7 +450,7 @@ where
if let Some(o) = &w.owner_api {
let slate = { o.init_send_tx(None, init_args)? };
o.tx_lock_outputs(None, &slate)?;
return WalletInterface::encrypt_slatepack(o, &dest_slatepack_address, &slate);
return Ok((slate.clone(), WalletInterface::encrypt_slatepack(o, &dest_slatepack_address, &slate)?));
} else {
return Err(GrinWalletInterfaceError::OwnerAPINotInstantiated);
}
Expand All @@ -460,7 +460,7 @@ where
wallet_interface: Arc<RwLock<WalletInterface<L, C>>>,
slate: Slate,
dest_slatepack_address: String,
) -> Result<Option<String>, GrinWalletInterfaceError> {
) -> Result<(Slate, Option<String>), GrinWalletInterfaceError> {
let w = wallet_interface.write().unwrap();
let ret_slate;
if let Some(f) = &w.foreign_api {
Expand All @@ -471,7 +471,7 @@ where
if let Some(o) = &w.owner_api {
let encrypted =
WalletInterface::encrypt_slatepack(o, &dest_slatepack_address, &ret_slate)?;
return Ok(Some(encrypted));
return Ok((ret_slate, Some(encrypted)));
} else {
return Err(GrinWalletInterfaceError::OwnerAPINotInstantiated);
}
Expand All @@ -481,12 +481,12 @@ where
wallet_interface: Arc<RwLock<WalletInterface<L, C>>>,
slate: Slate,
send_to_chain: bool,
) -> Result<Option<String>, GrinWalletInterfaceError> {
) -> Result<(Slate, Option<String>), GrinWalletInterfaceError> {
let w = wallet_interface.write().unwrap();
if let Some(o) = &w.owner_api {
let ret_slate = o.finalize_tx(None, &slate)?;
o.post_tx(None, &ret_slate, true)?;
return Ok(None);
return Ok((ret_slate, None));
} else {
return Err(GrinWalletInterfaceError::ForeignAPINotInstantiated);
}
Expand Down
3 changes: 2 additions & 1 deletion locale/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -245,5 +245,6 @@
"apply-tx-confirm": "Confirm Transaction Details",
"tx-sender-name": "Sender",
"apply-tx-amount": "Incoming amount",
"tx-state": "Transaction Stage (this will be presented better)"
"tx-state": "Transaction Stage (this will be presented better)",
"tx-reload-slate": "Show Slatepack"
}
3 changes: 2 additions & 1 deletion locale/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -254,5 +254,6 @@
"apply-tx-confirm": "Confirm Transaction Details",
"tx-sender-name": "Sender",
"apply-tx-amount": "Incoming amount",
"tx-state": "Transaction Stage (this will be presented better)"
"tx-state": "Transaction Stage (this will be presented better)",
"tx-reload-slate": "Show Slatepack"
}
33 changes: 25 additions & 8 deletions src/gui/element/wallet/operation/apply_tx_confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use grin_gui_core::{
use grin_gui_widgets::widget::header;
use iced_aw::Card;
use iced_native::Widget;
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;

use super::tx_list::{HeaderState, TxList};
Expand Down Expand Up @@ -64,7 +66,7 @@ pub enum Action {}
pub enum LocalViewInteraction {
Back,
Accept,
TxAcceptSuccess(Option<String>),
TxAcceptSuccess(Slate, Option<String>),
TxAcceptFailure(Arc<RwLock<Option<anyhow::Error>>>),
}

Expand Down Expand Up @@ -105,9 +107,9 @@ pub fn handle_message<'a>(

return Ok(Command::perform(fut(), |r| {
match r.context("Failed to Progress Transaction") {
Ok(ret) => Message::Interaction(
Ok((slate, enc_slate)) => Message::Interaction(
Interaction::WalletOperationApplyTxConfirmViewInteraction(
LocalViewInteraction::TxAcceptSuccess(ret),
LocalViewInteraction::TxAcceptSuccess(slate, enc_slate),
),
),
Err(e) => Message::Interaction(
Expand All @@ -125,9 +127,9 @@ pub fn handle_message<'a>(

return Ok(Command::perform(fut(), |r| {
match r.context("Failed to Progress Transaction") {
Ok(ret) => Message::Interaction(
Ok((slate, enc_slate)) => Message::Interaction(
Interaction::WalletOperationApplyTxConfirmViewInteraction(
LocalViewInteraction::TxAcceptSuccess(ret),
LocalViewInteraction::TxAcceptSuccess(slate, enc_slate),
),
),
Err(e) => Message::Interaction(
Expand All @@ -146,13 +148,28 @@ pub fn handle_message<'a>(
}
}
}
LocalViewInteraction::TxAcceptSuccess(slate) => {
log::debug!("{:?}", slate);
LocalViewInteraction::TxAcceptSuccess(slate, encrypted_slate) => {
// Output the latest slatepack, overriding any previous
if let Some(ref s) = encrypted_slate {
if let Some(dir) = grin_gui.config.get_wallet_slatepack_dir() {
let out_file_name = format!("{}/{}.slatepack", dir, slate.id);
let mut output = File::create(out_file_name.clone())?;
output.write_all(&s.as_bytes())?;
output.sync_all()?;
}
} else {
// If no encrypted slate, tx was posted so remove file
if let Some(dir) = grin_gui.config.get_wallet_slatepack_dir() {
let out_file_name = format!("{}/{}.slatepack", dir, slate.id);
let _ = fs::remove_file(out_file_name);
}
}

grin_gui
.wallet_state
.operation_state
.apply_tx_success_state
.encrypted_slate = slate;
.encrypted_slate = encrypted_slate;
grin_gui.wallet_state.operation_state.mode =
crate::gui::element::wallet::operation::Mode::ApplyTxSuccess;
}
Expand Down
23 changes: 17 additions & 6 deletions src/gui/element/wallet/operation/create_tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ use grin_gui_core::{
use grin_gui_widgets::widget::header;
use iced_aw::Card;
use iced_native::Widget;
use std::fs::File;
use std::io::{Read, Write};
use std::path::PathBuf;

use super::tx_list::{HeaderState, TxList};
Expand Down Expand Up @@ -68,7 +70,7 @@ pub enum LocalViewInteraction {
Amount(String),
CreateTransaction(),

TxCreatedOk(String),
TxCreatedOk(Slate, String),
TxCreateError(Arc<RwLock<Option<anyhow::Error>>>),
SlatepackAddressError,
}
Expand Down Expand Up @@ -123,9 +125,9 @@ pub fn handle_message<'a>(
move || WalletInterface::create_tx(w, args, state.recipient_address_value.clone());

return Ok(Command::perform(fut(), |r| match r {
Ok(ret) => {
Ok((enc_slate, unenc_slate)) => {
Message::Interaction(Interaction::WalletOperationCreateTxViewInteraction(
LocalViewInteraction::TxCreatedOk(ret),
LocalViewInteraction::TxCreatedOk(enc_slate, unenc_slate),
))
}
Err(e) => match e {
Expand All @@ -142,13 +144,22 @@ pub fn handle_message<'a>(
},
}));
}
LocalViewInteraction::TxCreatedOk(slate) => {
log::debug!("{:?}", slate);
LocalViewInteraction::TxCreatedOk(unencrypted_slate, encrypted_slate) => {
log::debug!("{:?}", encrypted_slate);
grin_gui
.wallet_state
.operation_state
.create_tx_success_state
.encrypted_slate = slate.to_string();
.encrypted_slate = encrypted_slate.to_string();

// create a directory to which files will be output, if it doesn't exist
if let Some(dir) = grin_gui.config.get_wallet_slatepack_dir() {
let out_file_name = format!("{}/{}.slatepack", dir, unencrypted_slate.id);
let mut output = File::create(out_file_name.clone())?;
output.write_all(&encrypted_slate.as_bytes())?;
output.sync_all()?;
}

grin_gui.wallet_state.operation_state.mode =
crate::gui::element::wallet::operation::Mode::CreateTxSuccess;
}
Expand Down
Loading