From f585c70eba95f47942ddb8dbf4931f12d2079775 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 16:36:57 +0200 Subject: [PATCH 01/39] clarify bip32 derivation paths (#800) Co-authored-by: ardocrat --- controller/src/display.rs | 23 ++++++++++++++---- controller/tests/accounts.rs | 2 ++ libwallet/src/address.rs | 41 +++++++++++++++++++++++++-------- libwallet/src/api_impl/owner.rs | 6 ++++- 4 files changed, 57 insertions(+), 15 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index f94a855..559fbcf 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -16,11 +16,12 @@ use crate::core::core::FeeFields; use crate::core::core::{self, amount_to_hr_string}; use crate::core::global; use crate::libwallet::{ - AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, TxLogEntry, - ViewWallet, WalletInfo, + address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, + TxLogEntry, ViewWallet, WalletInfo, }; use crate::util::ToHex; use prettytable; +use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; use term; @@ -537,15 +538,29 @@ pub fn accounts(acct_mappings: Vec) { table.set_titles(row![ mMG->"Name", - bMG->"Parent BIP-32 Derivation Path", + bMG->"Parent Output Key", + bMG->"Slatepack Address (Index 0)", ]); for m in acct_mappings { + let slatepack_path = address::address_derivation_path(&m.path, 0).to_bip_32_string(); table.add_row(row![ bFC->m.label, bGC->m.path.to_bip_32_string(), + bGC->slatepack_path, ]); } - table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); + table.set_format( + FormatBuilder::new() + .column_separator('|') + .separators( + &[LinePosition::Top, LinePosition::Title], + LineSeparator::new('-', '+', '+', '+'), + ) + .padding(1, 1) + .build(), + ); + let width = table.to_string().find('\n').unwrap_or(0); + println!("{:^1$}", "BIP-32 Derivation Path", width); table.printstd(); println!(); } diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 9a47e41..59645f8 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -175,6 +175,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { mask1, PathBuf::from(test_dir), |api, m| { + let labels: Vec<_> = api.accounts(m)?.into_iter().map(|a| a.label).collect(); + assert_eq!(labels, ["account1", "default", "account2", "account3"]); // check last confirmed height on this account is different from above (should be 0) let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; assert_eq!(wallet1_info.last_confirmed_height, 0); diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index 8d55b39..4a6f54b 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -21,6 +21,23 @@ use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; use crate::blake2::blake2b::blake2b; +/// Derive a Slatepack address path from an output parent path and index. +/// +/// Output paths: +/// - account m/0: m/0/0/0, m/0/0/1 +/// - account m/1: m/1/0/0, m/1/0/1 +/// +/// Slatepack address paths: +/// - account m/0: m/0/1/0, m/0/1/1 +/// - account m/1: m/1/1/0, m/1/1/1 +pub fn address_derivation_path(parent_key_id: &Identifier, index: u32) -> Identifier { + let mut key_path = parent_key_id.to_path(); + key_path.path[1] = ChildNumber::from(1); + key_path.depth += 1; + key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); + Identifier::from_path(&key_path) +} + /// Derive a secret key given a derivation path and index pub fn address_from_derivation_path( keychain: &K, @@ -30,16 +47,7 @@ pub fn address_from_derivation_path( where K: Keychain, { - let mut key_path = parent_key_id.to_path(); - // An output derivation for acct m/0 - // is m/0/0/0, m/0/0/1 (for instance), m/1 is m/1/0/0, m/1/0/1 - // Address generation path should be - // for m/0: m/0/1/0, m/0/1/1 - // for m/1: m/1/1/0, m/1/1/1 - key_path.path[1] = ChildNumber::from(1); - key_path.depth += 1; - key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); - let key_id = Identifier::from_path(&key_path); + let key_id = address_derivation_path(parent_key_id, index); let sec_key = keychain.derive_key(0, &key_id, SwitchCommitmentType::None)?; let hashed = blake2b(32, &[], &sec_key.0[..]); Ok(SecretKey::from_slice( @@ -47,3 +55,16 @@ where &hashed.as_bytes()[..], )?) } + +#[cfg(test)] +mod tests { + use super::*; + use grin_keychain::ExtKeychain; + + #[test] + fn slatepack_address_path() { + let parent = ExtKeychain::derive_key_id(2, 2, 0, 0, 0); + let expected = ExtKeychain::derive_key_id(3, 2, 1, 3, 0); + assert_eq!(address_derivation_path(&parent, 3), expected); + } +} diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 10a8d4a..638c608 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -57,7 +57,11 @@ where C: NodeClient, K: Keychain, { - keys::accounts(w) + let mut accounts = keys::accounts(w)?; + accounts.sort_by(|a, b| a.path.cmp(&b.path)); + // Put active account on top. + accounts.sort_by_key(|k| k.path != w.parent_key_id()); + Ok(accounts) } /// new account path From 0f7aa2f7fae2fbef321a73d2e3aab8899e9f4dc6 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 10:02:31 +0200 Subject: [PATCH 02/39] centralize grin workspace dependencies (#787) --- Cargo.toml | 18 +++++++++++++----- api/Cargo.toml | 6 +++--- config/Cargo.toml | 4 ++-- controller/Cargo.toml | 12 ++++++------ impls/Cargo.toml | 12 ++++++------ libwallet/Cargo.toml | 8 ++++---- util/Cargo.toml | 2 +- 7 files changed, 35 insertions(+), 27 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 901278d..ea2bfd4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,14 @@ path = "src/bin/grin-wallet.rs" members = ["api", "config", "controller", "impls", "libwallet", "util"] exclude = ["integration"] +[workspace.dependencies] +grin_api = { path = "grin/api" } +grin_chain = { path = "grin/chain" } +grin_core = { path = "grin/core" } +grin_keychain = { path = "grin/keychain" } +grin_store = { path = "grin/store" } +grin_util = { path = "grin/util" } + [dependencies] clap = { version = "2.33", features = ["yaml"] } rpassword = "7.5.4" @@ -37,10 +45,10 @@ grin_wallet_config = { path = "./config", version = "5.5.0" } ##### Grin Imports -grin_core = { path = "grin/core"} -grin_keychain = { path = "grin/keychain"} -grin_util = { path = "grin/util"} -grin_api = { path = "grin/api"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } ###### @@ -51,4 +59,4 @@ built = { version = "0.8.0", features = ["git2"]} url = "2.1" serde = "1" serde_json = "1" -easy-jsonrpc-mw = "0.5.4" \ No newline at end of file +easy-jsonrpc-mw = "0.5.4" diff --git a/api/Cargo.toml b/api/Cargo.toml index c797161..e7f61e0 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -29,9 +29,9 @@ grin_wallet_util = { path = "../util", version = "5.5.0" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_util = { path = "../grin/util"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } ##### diff --git a/config/Cargo.toml b/config/Cargo.toml index 5d7e339..b059a3f 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -20,8 +20,8 @@ lazy_static = "1" ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_util = { path = "../grin/util"} +grin_core = { workspace = true } +grin_util = { workspace = true } ##### diff --git a/controller/Cargo.toml b/controller/Cargo.toml index 5de94f2..ea8938c 100644 --- a/controller/Cargo.toml +++ b/controller/Cargo.toml @@ -33,13 +33,13 @@ grin_wallet_config = { path = "../config", version = "5.5.0" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_util = { path = "../grin/util"} -grin_api = { path = "../grin/api"} -grin_chain = { path = "../grin/chain"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } +grin_chain = { workspace = true } ##### [dev-dependencies] -ed25519-dalek = "2" \ No newline at end of file +ed25519-dalek = "2" diff --git a/impls/Cargo.toml b/impls/Cargo.toml index bb4add2..35f032f 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -53,10 +53,10 @@ grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_chain = { path = "../grin/chain"} -grin_util = { path = "../grin/util"} -grin_api = { path = "../grin/api"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_chain = { workspace = true } +grin_util = { workspace = true } +grin_api = { workspace = true } -##### \ No newline at end of file +##### diff --git a/libwallet/Cargo.toml b/libwallet/Cargo.toml index c6bfe82..7844c8b 100644 --- a/libwallet/Cargo.toml +++ b/libwallet/Cargo.toml @@ -47,9 +47,9 @@ grin_wallet_config = { path = "../config", version = "5.5.0" } ##### Grin Imports -grin_core = { path = "../grin/core"} -grin_keychain = { path = "../grin/keychain"} -grin_util = { path = "../grin/util"} -grin_store = { path = "../grin/store"} +grin_core = { workspace = true } +grin_keychain = { workspace = true } +grin_util = { workspace = true } +grin_store = { workspace = true } ##### diff --git a/util/Cargo.toml b/util/Cargo.toml index 898522d..b4a30d6 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -19,6 +19,6 @@ thiserror = "1" ##### Grin Imports -grin_util = { path = "../grin/util"} +grin_util = { workspace = true } ###### From 99cca5b8bfdeb1f129d7b467f4241ed043fc47b6 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 14:43:11 +0200 Subject: [PATCH 03/39] handle unavailable terminal colors (#797) Co-authored-by: ardocrat --- controller/src/display.rs | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index 559fbcf..54077fc 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::core::core::amount_to_hr_string; use crate::core::core::FeeFields; -use crate::core::core::{self, amount_to_hr_string}; use crate::core::global; use crate::libwallet::{ address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, @@ -43,9 +43,9 @@ pub fn outputs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -78,7 +78,7 @@ pub fn outputs( }; let num_confirmations = format!("{}", m.output.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.output.value, false)); + let value = format!("{}", amount_to_hr_string(m.output.value, false)); let tx = match m.output.tx_log_entry { None => "".to_owned(), Some(t) => t.to_string(), @@ -118,7 +118,7 @@ pub fn outputs( if !validated { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } @@ -144,9 +144,9 @@ pub fn txs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -193,18 +193,18 @@ pub fn txs( let confirmed = format!("{}", t.confirmed); let num_inputs = format!("{}", t.num_inputs); let num_outputs = format!("{}", t.num_outputs); - let amount_debited_str = core::amount_to_hr_string(t.amount_debited, true); - let amount_credited_str = core::amount_to_hr_string(t.amount_credited, true); + let amount_debited_str = amount_to_hr_string(t.amount_debited, true); + let amount_credited_str = amount_to_hr_string(t.amount_credited, true); let fee = match t.fee { - Some(f) => format!("{}", core::amount_to_hr_string(f.fee(), true)), + Some(f) => format!("{}", amount_to_hr_string(f.fee(), true)), None => "None".to_owned(), }; let net_diff = if t.amount_credited >= t.amount_debited { - core::amount_to_hr_string(t.amount_credited - t.amount_debited, true) + amount_to_hr_string(t.amount_credited - t.amount_debited, true) } else { format!( "-{}", - core::amount_to_hr_string(t.amount_debited - t.amount_credited, true) + amount_to_hr_string(t.amount_debited - t.amount_credited, true) ) }; let tx_data = match t.stored_tx { @@ -290,7 +290,7 @@ pub fn txs( if !validated && include_status { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } @@ -334,9 +334,9 @@ pub fn view_wallet_output( } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -357,7 +357,7 @@ pub fn view_wallet_output( let lock_height = format!("{}", m.lock_height); let is_coinbase = format!("{}", m.is_coinbase); let num_confirmations = format!("{}", m.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.value, false)); + let value = format!("{}", amount_to_hr_string(m.value, false)); if dark_background_color_scheme { table.add_row(row![ @@ -409,11 +409,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -426,7 +426,7 @@ pub fn info( FY->amount_to_hr_string(wallet_info.amount_awaiting_confirmation, false) ]); table.add_row(row![ - bFB->format!("Awaiting Finalization"), + bFB->"Awaiting Finalization", FB->amount_to_hr_string(wallet_info.amount_awaiting_finalization, false) ]); table.add_row(row![ @@ -448,11 +448,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -483,7 +483,7 @@ pub fn info( if !validated { println!( "\nWARNING: Wallet failed to verify data against a live chain. \ - The above is from local cache and only valid up to the given height! \ + The above is from local cache and only valid up to the given height! \ (is your `grin server` offline or broken?)" ); } @@ -533,7 +533,7 @@ pub fn estimate( /// Display list of wallet accounts in a pretty way pub fn accounts(acct_mappings: Vec) { - println!("\n____ Wallet Accounts ____\n",); + println!("\n____ Wallet Accounts ____\n"); let mut table = table!(); table.set_titles(row![ @@ -567,28 +567,28 @@ pub fn accounts(acct_mappings: Vec) { /// Display individual Payment Proof pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { - let title = format!("Payment Proof - Transaction '{}'", tx.id,); + let title = format!("Payment Proof - Transaction '{}'", tx.id); println!(); if term::stdout().is_none() { println!("Could not open terminal"); return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let pp = match &tx.payment_proof { None => { - writeln!(t, "None").unwrap(); - t.reset().unwrap(); + writeln!(t, "None")?; + let _ = t.reset(); return Ok(()); } Some(p) => p.clone(), }; - t.fg(term::color::WHITE).unwrap(); - writeln!(t).unwrap(); + let _ = t.fg(term::color::WHITE); + writeln!(t)?; let receiver_signature = match pp.receiver_signature { Some(s) => { let sig_bytes = s.to_bytes(); @@ -602,11 +602,11 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { None => 0, }; let amount = if tx.amount_credited >= tx.amount_debited { - core::amount_to_hr_string(tx.amount_credited - tx.amount_debited, true) + amount_to_hr_string(tx.amount_credited - tx.amount_debited, true) } else { format!( "{}", - core::amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) + amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) ) }; @@ -630,20 +630,18 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { t, "Receiver Address: {}", SlatepackAddress::new(&pp.receiver_address) - ) - .unwrap(); - writeln!(t, "Receiver Signature: {}", receiver_signature).unwrap(); - writeln!(t, "Amount: {}", amount).unwrap(); - writeln!(t, "Kernel Excess: {}", kernel_excess).unwrap(); + )?; + writeln!(t, "Receiver Signature: {}", receiver_signature)?; + writeln!(t, "Amount: {}", amount)?; + writeln!(t, "Kernel Excess: {}", kernel_excess)?; writeln!( t, "Sender Address: {}", SlatepackAddress::new(&pp.sender_address) - ) - .unwrap(); - writeln!(t, "Sender Signature: {}", sender_signature).unwrap(); + )?; + writeln!(t, "Sender Signature: {}", sender_signature)?; - t.reset().unwrap(); + let _ = t.reset(); println!(); From 645363436d41ba621d8aa9fd536c619ee2110c5d Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 15:00:54 +0200 Subject: [PATCH 04/39] reject invalid invoice locking (#798) --- controller/tests/invoice.rs | 16 ++++++++++++++++ libwallet/src/api_impl/owner.rs | 3 +++ 2 files changed, 19 insertions(+) diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 3713d5e..006d5d4 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -184,6 +184,22 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; assert_eq!(slate.state, SlateState::Invoice2); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + assert_eq!( + api.tx_lock_outputs(m, &slate), + Err(libwallet::Error::SlateState) + ); + let (_, txs) = api.retrieve_txs(m, false, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + Ok(()) + }, + )?; + // wallet 2 finalizes and posts wallet::controller::foreign_single_use( wallet2.clone(), diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 638c608..44aecae 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -830,6 +830,9 @@ where K: Keychain, { let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + if slate.state == SlateState::Invoice2 && context.input_ids.is_empty() { + return Err(Error::SlateState); + } let mut excess_override = None; let mut sl = slate.clone(); From 0d5ea84bfd6bcfffdcc1f2eb5ce313f428d08162 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 14:23:23 +0200 Subject: [PATCH 05/39] fix tx filter (#795) --- controller/tests/tx_list_filter.rs | 19 +++++++++++++++++++ libwallet/src/internal/updater.rs | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index 424db24..c7fa9c8 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -61,6 +61,25 @@ fn test_wallet_tx_filtering( mask, PathBuf::from(test_dir), |api, _m| { + let query = |args| { + api.retrieve_txs(mask, true, None, None, Some(args)) + .map(|(_, txs)| txs) + }; + let txs = query(RetrieveTxQueryArgs::default())?; + assert!(!txs.is_empty()); + let before_first_tx = + txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); + let mut tx_query_args = RetrieveTxQueryArgs::default(); + + // Max creation time before all test transactions + tx_query_args.max_creation_timestamp = Some(before_first_tx); + assert!(query(tx_query_args.clone())?.is_empty()); + + // Min confirmation time should not affect creation time + tx_query_args.max_creation_timestamp = None; + tx_query_args.min_confirmed_timestamp = Some(before_first_tx); + assert_eq!(query(tx_query_args)?.len(), txs.len()); + let mut tx_query_args = RetrieveTxQueryArgs::default(); tx_query_args.min_id = Some(5); diff --git a/libwallet/src/internal/updater.rs b/libwallet/src/internal/updater.rs index 9590f23..47134e5 100644 --- a/libwallet/src/internal/updater.rs +++ b/libwallet/src/internal/updater.rs @@ -247,7 +247,7 @@ where } }) .filter(|tx_entry| { - if let Some(v) = query_args.min_confirmed_timestamp { + if let Some(v) = query_args.max_creation_timestamp { tx_entry.creation_ts <= v } else { true From e0873a1b2ee33492dd08af2566bbd9bd3b8166ea Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 2 Sep 2026 23:32:16 +0300 Subject: [PATCH 06/39] Downgrade arti to 0.43 (#810) --- Cargo.lock | 226 +++++++++++++++++++++++------------------------ impls/Cargo.toml | 16 ++-- 2 files changed, 121 insertions(+), 121 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index debbb82..a300f30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,9 +202,9 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arti-client" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d54b6c87059a9b6562bfe585f3a637b72f90cddaa327ac29b5ddf082a54b4" +checksum = "7ffc89b08e6a475a83d70e52f0ede139a433eb46e986a6cee6eeaa1b73297bf1" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -699,9 +699,9 @@ checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" [[package]] name = "caret" -version = "0.10.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bb840a063107846780a14acc022b55bf6c174997a393ffde8b58ff6630c1b56" +checksum = "beae2cb9f60bc3f21effaaf9c64e51f6627edd54eedc9199ba07f519ef2a2101" [[package]] name = "cc" @@ -1970,9 +1970,9 @@ dependencies = [ [[package]] name = "fs-mistrust" -version = "0.15.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd938e053fbfb6dba36106f4bcf27c53362e6152adc9341700c4bc2264cd4a8f" +checksum = "9cfebc7c6bb65d327ded064db65cd260b6c418c27ae790318650cfa2a81bf33f" dependencies = [ "derive_builder_fork_arti", "dirs 6.0.0", @@ -1984,6 +1984,17 @@ dependencies = [ "walkdir", ] +[[package]] +name = "fslock-guard" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e77b8a36ee17f9079b53db7281de9b16a8fb2bc97a7cd1e41a2998f3a837af7a" +dependencies = [ + "libc", + "thiserror 2.0.18", + "windows-sys 0.61.2", +] + [[package]] name = "fslock-guard" version = "0.8.0" @@ -2040,9 +2051,9 @@ dependencies = [ [[package]] name = "futures-copy" -version = "0.4.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcad91f8ba72542347d5cc8ee43891abe4698429fa7b3de56f17f4bb6fa514c4" +checksum = "24f320278d16b5617859cc2234ca5775a8d9b24faee8c14e54e79540caab053a" dependencies = [ "futures 0.3.32", "libc", @@ -2531,7 +2542,7 @@ dependencies = [ "chrono", "ed25519-dalek", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.8.0", "futures 0.3.32", "grin_api", "grin_chain", @@ -4004,9 +4015,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "oneshot-fused-workaround" -version = "0.7.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60d6f8f565703c8a15f98b7782e39526490f8c291910d80c9be54a753a822f6f" +checksum = "e17b52d0e4a06a4c7eb8d2943c0015fa628cf4ccc409429cebc0f5bed6d33a82" dependencies = [ "futures 0.3.32", ] @@ -5030,9 +5041,9 @@ dependencies = [ [[package]] name = "retry-error" -version = "0.13.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c0e06f9b501df8600ad8bd073f4990f703f36e0f48e574b431f4a15d69b449" +checksum = "cf6aa271ee564cc5d1df57c5cf7c6ac7a21a4f9f40d2bf1d32bf0a1bb3ddaeb0" dependencies = [ "humantime 2.4.0", "web-time", @@ -5343,9 +5354,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "safelog" -version = "0.9.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0812d386a9992c036500b92565c41f84c28fd2e48fe853a395c393261b730b" +checksum = "97a907e0d82c61b1b06a2030c968eb313dcf432686b77801a26bc4b206f96573" dependencies = [ "derive_more", "educe", @@ -5389,9 +5400,9 @@ dependencies = [ [[package]] name = "saturating-time" -version = "0.4.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "802bdbfcca9a239cb46eeaaedea507e37bb13ba1a673762d2e2ef7a9dac63144" +checksum = "b63583a1dd0647d1484228529ab4ecaa874048d2956f117362aa5f5826456230" [[package]] name = "schannel" @@ -5798,9 +5809,9 @@ dependencies = [ [[package]] name = "slotmap-careful" -version = "0.8.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7cd5208f878dce99cfbefa73c692c67edf946ac53e0cc4455e2dabe43d54af7" +checksum = "ed92816c1fbb29891a525b92d5fa95757c9dee47044f76c8e06ceb1e052a8d64" dependencies = [ "paste", "serde", @@ -6464,35 +6475,26 @@ checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tor-async-utils" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58580b41636378f79500bca6a178787e0e434207e0880dd90698ae3f686f24d6" +checksum = "27fc83e7539ac5f717b722456df991ca8819782d04f7ae2ee28eefacca030eef" dependencies = [ - "cfg-if 1.0.4", "derive-deftly", "educe", "futures 0.3.32", "oneshot-fused-workaround", "pin-project", "postage", - "sync_wrapper", "thiserror 2.0.18", - "tokio", - "tokio-util", - "tor-basic-utils", - "tor-rtcompat", - "tracing", "void", - "web-time-compat", ] [[package]] name = "tor-basic-utils" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd3046aa299df67da91b45c02c24d48d40ae1845f9b91e27f9c8adbde78315ba" +checksum = "7bd01b9947f57a99193547f3a40a0bd179e9a332ead855c07e2fb702a1517f74" dependencies = [ - "derive-deftly", "derive_more", "getrandom 0.4.3", "hex", @@ -6505,16 +6507,15 @@ dependencies = [ "slab", "smallvec", "thiserror 2.0.18", - "tracing", "weak-table", "web-time-compat", ] [[package]] name = "tor-bytes" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4833cc8ab3fca79eabc06f3ca97db102a3b7db861d77848d39932a6f0ed598" +checksum = "de6a7af55881d599cd48c841916520318d5711df17514001aafd5f796f61e337" dependencies = [ "bytes 1.12.0", "derive-deftly", @@ -6530,9 +6531,9 @@ dependencies = [ [[package]] name = "tor-cell" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73a01cb2ac6697c12b647729d3d7db404e306d1e08a7a3aacdbee08e35170ebd" +checksum = "dad292658d194b145aaec268ffb91566b7d96c98971eea4980c1bf951d7d082b" dependencies = [ "amplify", "bitflags 2.13.0", @@ -6561,15 +6562,14 @@ dependencies = [ [[package]] name = "tor-cert" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162d44b975e445de099b3a495710689652bbd0a9a3a0e4946341acbb3138b22b" +checksum = "474e732207b1be44f9ae4ddf295fba3644cd3c09494d131846ff9c9a624ab263" dependencies = [ "caret", "derive_builder_fork_arti", "derive_more", "digest 0.10.7", - "saturating-time", "thiserror 2.0.18", "tor-bytes", "tor-checkable", @@ -6580,9 +6580,9 @@ dependencies = [ [[package]] name = "tor-chanmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf15c4cbafa5745def4fced9e8e59148533a2bfc8d938e9fad7a0d6d16757712" +checksum = "b2bb088804f54de320ee97dd2a48ae319f0df9d9d0e37eef050d65488194a768" dependencies = [ "async-trait", "base64ct", @@ -6623,9 +6623,9 @@ dependencies = [ [[package]] name = "tor-checkable" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef81835cb0b2db460c694678eae8c4cbad5f31847e473aac42605f9b945fb31a" +checksum = "9505791bac25b31b8de88c0e2b02e1690e10ff1308583c6f61c320bab2677959" dependencies = [ "humantime 2.4.0", "signature", @@ -6636,9 +6636,9 @@ dependencies = [ [[package]] name = "tor-circmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63cca1f18282f82b905b6a8c20c6f247787bc010d1b317d9eb98503e4352bf" +checksum = "7e986c7c4e1faae8a412b575ce66ff087050525a371db1034f0b24d70b459a2e" dependencies = [ "amplify", "async-trait", @@ -6686,9 +6686,9 @@ dependencies = [ [[package]] name = "tor-config" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a699adfb8bdb34699afcca7cbbd9d26329246940bc9dbc32f380c87578017350" +checksum = "224f85aa02b514c384ea5ec32f1b924233bea6b553195fd83da7f1e50a2e0d1b" dependencies = [ "amplify", "cfg-if 1.0.4", @@ -6720,9 +6720,9 @@ dependencies = [ [[package]] name = "tor-config-path" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38001695121fc778e67ac7a1c733d3158ee8942a55cfa343981b50d90f5daa" +checksum = "4232a56a8ce40a47ad6b42c9c7d9e6f4485e6e6a43b3149304c35bc295034107" dependencies = [ "directories", "serde", @@ -6734,9 +6734,9 @@ dependencies = [ [[package]] name = "tor-consdiff" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e9e3eb11e91ea4c1affe5e1f73628726c283942715739850546acb94bbe028" +checksum = "d5fcd0c631a66b45dca4421b8a06309dd02ae5d6aea5daa55399f68638b2abf3" dependencies = [ "derive_more", "digest 0.10.7", @@ -6751,9 +6751,9 @@ dependencies = [ [[package]] name = "tor-dirclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0027cd2a58abab9ebaf61c3c1da9b0fa9e6cbc914b88fedb7b3102bd4f4dd656" +checksum = "bf637d6a5d8c886f23ca2df50edfaa56443f23294428f037206fb3a0d07ba57e" dependencies = [ "async-compression", "base64ct", @@ -6780,9 +6780,9 @@ dependencies = [ [[package]] name = "tor-dircommon" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d2047b2f1ad3453c1060e5e39203bd87ead266e6873707bd7333b1d6bdac768" +checksum = "35e412167d54c3618c3261dc77f1a31fe20c518f59aca5abfdec5f600b6a9b1f" dependencies = [ "base64ct", "derive-deftly", @@ -6801,9 +6801,9 @@ dependencies = [ [[package]] name = "tor-dirmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57ebc162ccd628ef8e96912a9e42e848cd7305eb2a5a455a6002f54ad6826422" +checksum = "9b984d2b0f0a2764a1b24d7c4c203ef83600b071c0c5af36e20d4f63e80ce562" dependencies = [ "async-trait", "base64ct", @@ -6813,7 +6813,7 @@ dependencies = [ "educe", "event-listener", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "hex", "humantime 2.4.0", @@ -6858,9 +6858,9 @@ dependencies = [ [[package]] name = "tor-error" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6a7ed4aee3e0613a75d420032116dac82d7702594e28566befdfa6707a8fd0e" +checksum = "1409b1a9085502c7797405a01fe3f3292a9827c9ed6a3f7c34fbb222572db5ac" dependencies = [ "derive_more", "futures 0.3.32", @@ -6876,9 +6876,9 @@ dependencies = [ [[package]] name = "tor-general-addr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfee544a33dd3e67e0311cc46ef8f667cbf9c02c7c00ef4f25098a25b2b6e1cf" +checksum = "09f17e219140e587e169f71f53e528ca394c39e83593c9fbe9e9366cce7655e1" dependencies = [ "derive_more", "thiserror 2.0.18", @@ -6887,9 +6887,9 @@ dependencies = [ [[package]] name = "tor-guardmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1e8f52e4b1b08ba58970a9b9879b0b72c35dcba48bad389935f2778ed432d05" +checksum = "d56c43d7afa526449c6e6460d373a02624a24c78637ddd7c68e2ac1879ae587c" dependencies = [ "amplify", "base64ct", @@ -6932,9 +6932,9 @@ dependencies = [ [[package]] name = "tor-hsclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dc813f71e63fd324c4b1b1647ddc2fcc4b6e77c45091e6769ae80e591726ec" +checksum = "1ff8ba0afebc5f76b42240f76b2bfb92aa5862c19ff184492c59c654750ee275" dependencies = [ "async-trait", "derive-deftly", @@ -6977,9 +6977,9 @@ dependencies = [ [[package]] name = "tor-hscrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f82fd6a5a6ede5ece5e7f52708bdf0a007e8f975f9825689b376f038845f1e88" +checksum = "3761c1828e74818cba4eb661d1eb79d4f663b05e8e7d3bc6e35d754968282fc0" dependencies = [ "cipher 0.4.4", "data-encoding", @@ -7010,9 +7010,9 @@ dependencies = [ [[package]] name = "tor-hsrproxy" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4231a55048af49ae2a8fcb2d41ea0df986b68c26bf6128f97f7f1324d47498" +checksum = "cc0d8041225c2721fb68e8406c2121e3168ea3998148df253859fec70ea20741" dependencies = [ "derive-deftly", "futures 0.3.32", @@ -7039,9 +7039,9 @@ dependencies = [ [[package]] name = "tor-hsservice" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170b66c977d3b16a5ff79ec344c06392076f0326d2d65146a58c450c50395dae" +checksum = "5fa87ed8d1ccfe8447b4e65bf0e2dfcab6a8ac9d2eadf7b3f37c102e1c18e9bb" dependencies = [ "amplify", "async-trait", @@ -7098,9 +7098,9 @@ dependencies = [ [[package]] name = "tor-key-forge" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30f83389917e9908c43457c80d0b982ba6dcd3e6ea36a37b29167b7619d9eaa3" +checksum = "86c877b95e0679f151743bc2b706320a29e14bd18d9bcb92918df34948e2e9d2" dependencies = [ "derive-deftly", "derive_more", @@ -7120,9 +7120,9 @@ dependencies = [ [[package]] name = "tor-keymgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7c18fb26d112c6022b7d1de558a4045b574fecfa1c504045145d8e1a9dc01a" +checksum = "5f59fbec28e31d688822b4c00a6f7fd94539886baccd3ce1b35dc26699c37873" dependencies = [ "amplify", "arrayvec 0.7.8", @@ -7161,9 +7161,9 @@ dependencies = [ [[package]] name = "tor-linkspec" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "638a849a5d65d4e37adb6a2fa597a5a5c0decb749c17e76d3c44c4aefd696270" +checksum = "0e1cc8d5469c324d1e0761066d868363d3fdccb723b14cdc983a5aef9b67981b" dependencies = [ "base64ct", "by_address", @@ -7188,9 +7188,9 @@ dependencies = [ [[package]] name = "tor-llcrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef0e63e805e9c1da61511a93eca502dc29bcb0b8635e9668ec750b63a1e53a1" +checksum = "d0015d521f5e30a2f74879fe4c615fc2c3ace822d7cc88c1dfed0ae816b25f15" dependencies = [ "aes", "base64ct", @@ -7231,9 +7231,9 @@ dependencies = [ [[package]] name = "tor-log-ratelim" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d0f759a875b6f9b6f3657a2626a70e2474e698a4404501033babe63ad888a6" +checksum = "7d16152b21f2e7b309dfbdcbe587c5adba9547d3119f2933b453d6edbce7e8e0" dependencies = [ "futures 0.3.32", "humantime 2.4.0", @@ -7247,9 +7247,9 @@ dependencies = [ [[package]] name = "tor-memquota" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c06f2e981120a4c1da1e361573cee4af618d05fa3c7ec37c139d766f1b8d47f" +checksum = "38ad2950d88e968572b0de6bb5702f5ed42f36555f362fb741c572c62441476e" dependencies = [ "cfg-if 1.0.4", "derive-deftly", @@ -7278,9 +7278,9 @@ dependencies = [ [[package]] name = "tor-memquota-cost" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b86eb903fee638e9211daddaddc146f0c5e4f5605d79983548fce6fec596325c" +checksum = "993ad5bfd39fb629990da40c2b2086284b1481b7d4843652a959db1d9e5ac463" dependencies = [ "derive-deftly", "itertools 0.14.0", @@ -7290,9 +7290,9 @@ dependencies = [ [[package]] name = "tor-netdir" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8160580273eec3576158c3e833ff198870665dacebb373585892dde93cf9803" +checksum = "6700c5e590818d9873a13e06b49b95cf3a39fa8fb3968bd67ec3295cd584b97c" dependencies = [ "async-trait", "bitflags 2.13.0", @@ -7323,9 +7323,9 @@ dependencies = [ [[package]] name = "tor-netdoc" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51598bfd24866de2c51e0de7a6e2418f86c6278cfeba2f85295ce45367fd8e06" +checksum = "a497ce4c36f59e4c67c352e3b80cd4642f6c5e660bb003de1922be4c7ed03081" dependencies = [ "amplify", "base64ct", @@ -7339,7 +7339,6 @@ dependencies = [ "hex", "hostname-validator", "humantime 2.4.0", - "ipnet", "itertools 0.14.0", "memchr", "paste", @@ -7373,16 +7372,16 @@ dependencies = [ [[package]] name = "tor-persist" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ff75e20adb6a1a7ad07e16b55e56d5376706cc0090ab8831f008f1a89243f2" +checksum = "b6da1a96a1f6418faac1cd1892e029fd265cf50e67e941a4ba2580d92dd32d47" dependencies = [ "amplify", "derive-deftly", "derive_more", "filetime", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "itertools 0.14.0", "oneshot-fused-workaround", @@ -7402,9 +7401,9 @@ dependencies = [ [[package]] name = "tor-proto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "666b602da8ba5a4189d6ff551f5dd9db949b503780140d175435658970a1ea54" +checksum = "a0a5fa0e1a365fc089a7f140f4142379dd74c91c15103c2f9d11ea711e16029e" dependencies = [ "amplify", "async-trait", @@ -7438,6 +7437,7 @@ dependencies = [ "static_assertions", "strum 0.28.0", "subtle", + "sync_wrapper", "thiserror 2.0.18", "tokio", "tokio-util", @@ -7468,9 +7468,9 @@ dependencies = [ [[package]] name = "tor-protover" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef84569d020c36eb322976f9a5dec1d3fa992db9739237ad1ae923b0ddeb298" +checksum = "c4f7f4ee15c9bfa0b700ae06e85fa52abddf17a35531cd3d3833412900e8da5c" dependencies = [ "caret", "paste", @@ -7482,9 +7482,9 @@ dependencies = [ [[package]] name = "tor-ptmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66db88ee6c5ba60a077b592b7e566d465220de61ccfd473fba6567c577cad475" +checksum = "b4cc37ac22faff9e0233fa287b92819d8819f31cae85a50ff99c51dd549b31c0" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -7512,9 +7512,9 @@ dependencies = [ [[package]] name = "tor-relay-selection" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09778e3a45fdf49ca335fa16a0032abc5d4e1cacff9f46c3ed3e2a416d088aa6" +checksum = "5b565b6dec2e3edb7b033203a3662edb7b586e486d53e02af4295e05e7562870" dependencies = [ "rand 0.10.2", "serde", @@ -7526,9 +7526,9 @@ dependencies = [ [[package]] name = "tor-rtcompat" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "981279291476ad7ec309c874fa99b8d31250432a48ff6eea3f7405edbbd254e1" +checksum = "fcd7a4ff4898044b3ec693c0bf098251accf13c58741c44ed9364ce5faa89287" dependencies = [ "amplify", "async-native-tls", @@ -7561,9 +7561,9 @@ dependencies = [ [[package]] name = "tor-rtmock" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3ee9695304cc44cc0de1dc673c9a71419318e214dc04ed7883a058d050654d" +checksum = "8331e7d57bf7cf157cf3610ff6dbb5a591de5c3b22fa65ea6be18b08ff81477a" dependencies = [ "amplify", "assert_matches", @@ -7591,9 +7591,9 @@ dependencies = [ [[package]] name = "tor-socksproto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbf78ef55dbfccb5a95cd75eb433621947923653cb91c9941d5a0a5116e510ee" +checksum = "55f432eda94343bdadd73995f0b3082d96637dadb0e20c3f9a1bf2349f623d3c" dependencies = [ "amplify", "caret", @@ -7608,9 +7608,9 @@ dependencies = [ [[package]] name = "tor-units" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0325a93f3b35c5a9bda74705ce89b753e1c8e183af6945826188cef16687d80" +checksum = "8cf033ee8b22b11abd8272272e19ccbbf58c7b3152f8d224aa8d21f358c43d0d" dependencies = [ "derive-deftly", "derive_more", @@ -8099,9 +8099,9 @@ dependencies = [ [[package]] name = "web-time-compat" -version = "0.2.0" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af46dad42aa37be3b4a116fe613365f991b8bdae6cd6ce82d84fa9f9e8f70ae4" +checksum = "39819265f219f60a92312f2755262dba9fff180a4ec281556863d69fa36adc59" dependencies = [ "web-time", ] diff --git a/impls/Cargo.toml b/impls/Cargo.toml index 35f032f..22b9f05 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -32,15 +32,15 @@ sysinfo = "0.29" base64 = "0.12.0" url = "2.1" -arti-client = { version = "0.44.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } -tor-rtcompat = { version = "0.44.0", features = ["static"] } -fs-mistrust = "0.15.0" +arti-client = { version = "0.43.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } +tor-rtcompat = { version = "0.43.0", features = ["static"] } +fs-mistrust = "0.14.2" fslock-guard = "0.8" -tor-hsservice = "0.44.0" -tor-hsrproxy = "0.44.0" -tor-keymgr = "0.44.0" -tor-llcrypto = "0.44.0" -tor-hscrypto = "0.44.0" +tor-hsservice = "0.43.0" +tor-hsrproxy = "0.43.0" +tor-keymgr = "0.43.0" +tor-llcrypto = "0.43.0" +tor-hscrypto = "0.43.0" sha2 = "0.10.8" hyper = { version = "1.10.1", features = ["http1", "client"] } hyper-util = { version = "0.1.20", features = ["tokio"] } From f31f3077674059b79911aeb798318a7747101655 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Fri, 18 Sep 2026 21:29:34 +0200 Subject: [PATCH 07/39] unpack plain slatepacks without password (#805) * unpack plain slatepacks without password * cli: better open wallet handling on wallet subcommand --------- Co-authored-by: ardocrat --- controller/src/command.rs | 38 +++++++++--------- src/cmd/wallet_args.rs | 82 ++++++++++++++++++++++++++------------- 2 files changed, 74 insertions(+), 46 deletions(-) diff --git a/controller/src/command.rs b/controller/src/command.rs index b645892..83d0e26 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -24,7 +24,7 @@ use crate::impls::SlateGetter as _; use crate::keychain; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::{ - self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, + self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack, SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider, }; use crate::util::secp::key::SecretKey; @@ -783,32 +783,34 @@ where Ok(()) } +pub fn read_slatepack(args: ReceiveArgs) -> Result { + let packer = Slatepacker::new(SlatepackerArgs { + sender: None, + recipients: vec![], + dec_key: None, + }); + let slatepack = match args.input_file { + Some(f) => PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)?, + None => match args.input_slatepack_message { + Some(message) => packer.deser_slatepack(message.as_bytes(), false)?, + None => { + return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into()); + } + }, + }; + Ok(slatepack) +} + pub fn unpack( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - args: ReceiveArgs, + mut slatepack: Slatepack, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let mut slatepack = match args.input_file { - Some(f) => { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)? - } - None => match args.input_slatepack_message { - Some(mes) => owner_api.decode_slatepack_message(keychain_mask, mes, vec![])?, - None => { - return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into()); - } - }, - }; println!(); println!("SLATEPACK CONTENTS"); println!("------------------"); diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 3446eaf..35cf7b6 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -26,6 +26,7 @@ use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; use grin_wallet_api::Owner; use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; +use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; @@ -1059,37 +1060,36 @@ where wallet_inst_cb(wallet.clone()); // don't open wallet for certain lifecycle commands - let mut open_wallet = true; - match wallet_args.subcommand() { - ("init", Some(_)) => open_wallet = false, - ("recover", _) => open_wallet = false, - ("cli", _) => open_wallet = false, + let keychain_mask = match wallet_args.subcommand() { + ("init", Some(_)) => None, + ("recover", _) => None, + ("cli", _) => None, + ("unpack", Some(args)) => { + let args = arg_parse!(parse_unpack_args(args)); + let slatepack = command::read_slatepack(args)?; + let mask = if slatepack.mode == 1 { + open_wallet(&wallet, &global_wallet_args, wallet_args)? + } else { + None + }; + let mut owner_api = Owner::new(wallet.clone(), None, config.config_file_path.clone()); + command::unpack(&mut owner_api, mask.as_ref(), slatepack)?; + return Ok("unpack".to_string()); + } ("owner_api", _) => { // If wallet exists and password is present then open it. Otherwise, that's fine too. - let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider()?; - open_wallet = wallet_args.is_present("pass") && lc.wallet_exists(None)?; - } - _ => {} - } - - let keychain_mask = match open_wallet { - true => { - let mut wallet_lock = wallet.lock(); - let lc = wallet_lock.lc_provider()?; - let mask = lc.open_wallet( - None, - prompt_password(&global_wallet_args.password)?, - false, - false, - )?; - if let Some(account) = wallet_args.value_of("account") { - let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + let open = { + let mut wallet_lock = wallet.lock(); + let lc = wallet_lock.lc_provider()?; + wallet_args.is_present("pass") && lc.wallet_exists(None)? + }; + if open { + open_wallet(&wallet, &global_wallet_args, wallet_args)? + } else { + None } - mask } - false => None, + _ => open_wallet(&wallet, &global_wallet_args, wallet_args)?, }; let res = match wallet_args.subcommand() { @@ -1123,6 +1123,31 @@ where } } +fn open_wallet( + wallet: &Arc>>>, + global_wallet_args: &GlobalArgs, + wallet_args: &ArgMatches, +) -> Result, Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + let mut wallet_lock = wallet.lock(); + let lc = wallet_lock.lc_provider()?; + let mask = lc.open_wallet( + None, + prompt_password(&global_wallet_args.password)?, + false, + false, + )?; + if let Some(account) = wallet_args.value_of("account") { + let wallet_inst = lc.wallet_inst()?; + wallet_inst.set_parent_key_id_by_name(account)?; + } + Ok(mask) +} + pub fn parse_and_execute( owner_api: &mut Owner, keychain_mask: Option, @@ -1231,7 +1256,8 @@ where } ("unpack", Some(args)) => { let a = arg_parse!(parse_unpack_args(&args)); - command::unpack(owner_api, km, a) + let slatepack = command::read_slatepack(a)?; + command::unpack(owner_api, km, slatepack) } ("finalize", Some(args)) => { let a = arg_parse!(parse_finalize_args(&args)); From 4a487390bdbcb9ba9176c689cef5bdc1e99c1714 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Mon, 21 Sep 2026 20:41:34 +0200 Subject: [PATCH 08/39] reject zero send amounts (#799) --- controller/src/command.rs | 9 ++++-- controller/tests/invoice.rs | 19 ++++++++++++ controller/tests/transaction.rs | 48 ++++++++++++++++++++++++++++- libwallet/src/api_impl/foreign.rs | 4 +++ libwallet/src/api_impl/owner.rs | 12 ++++++++ libwallet/src/error.rs | 4 +++ libwallet/src/internal/selection.rs | 17 +++++----- tests/cmd_line_basic.rs | 5 +++ 8 files changed, 104 insertions(+), 14 deletions(-) diff --git a/controller/src/command.rs b/controller/src/command.rs index 83d0e26..b1543a5 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -372,12 +372,15 @@ where true, args.minimum_confirmations, )?; - if args.use_max_amount { - amount = wallet_info.amount_currently_spendable; - } if !info_updated && !update_skipped { warn!("Wallet info update failed: node connection error"); } + if args.use_max_amount { + amount = wallet_info.amount_currently_spendable; + if amount == 0 { + return Err(Error::GenericError("No spendable funds".to_string())); + } + } if args.estimate_selection_strategies { let strategies = estimate_strategies(args.use_max_amount) .iter() diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 006d5d4..b48f66e 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -113,6 +113,17 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { mask2, PathBuf::from(test_dir), |api, m| { + let error = api + .issue_invoice_tx( + m, + IssueInvoiceTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + // Wallet 2 inititates an invoice transaction, requesting payment let args = IssueInvoiceTxArgs { amount: reward * 2, @@ -177,6 +188,14 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { selection_strategy_is_use_all: true, ..Default::default() }; + let mut zero_amount_slate = slate.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.process_invoice_tx(m, &zero_amount_slate, args.clone()) + .unwrap_err(), + libwallet::Error::InvalidAmount + ); + slate = api.process_invoice_tx(m, &slate, args)?; api.tx_lock_outputs(m, &slate)?; Ok(()) diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 5425ef8..107c17d 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -112,10 +112,41 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> mask1, PathBuf::from(test_dir), |sender_api, m| { + // Do not allow to send 0 + let error = sender_api + .init_send_tx( + m, + InitTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + + // Result amount can not be 0 when amount includes fee + let mut init_args = InitTxArgs { + amount_includes_fee: Some(true), + amount: 23_000_000, + estimate_only: Some(true), + ..Default::default() + }; + let est = sender_api.init_send_tx(m, init_args.clone())?; + assert_eq!(init_args.amount, est.fee_fields.fee()); + + init_args.estimate_only = None; + let error = sender_api.init_send_tx(m, init_args).unwrap_err(); + assert_eq!( + error, + libwallet::Error::GenericError( + "Transaction amount is too small to include fee".to_string() + ) + ); + // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { src_acct_name: None, - amount: amount, + amount, minimum_confirmations: 2, max_outputs: 500, num_change_outputs: 1, @@ -127,6 +158,21 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> assert_eq!(slate_i.state, SlateState::Standard1); assert_eq!(slate_i.version_info.block_header_version, header_version); + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let mut zero_amount_slate = slate_i.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), + libwallet::Error::InvalidAmount + ); + Ok(()) + }, + )?; + // Check we are creating a tx with the expected lock_height of 0. // We will check this produces a Plain kernel later. assert_eq!(0, slate.kernel_features); diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 4547b87..5c63a52 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -65,6 +65,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); if ret_slate.state != SlateState::Standard1 { return Err(Error::SlateState); diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 44aecae..58bfbd2 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -534,6 +534,10 @@ where C: NodeClient, K: Keychain, { + if args.amount == 0 { + return Err(Error::InvalidAmount); + } + let payment_proof_address = if let Some(a) = &args.payment_proof_recipient_address { if a.valid_network() { Some(a) @@ -657,6 +661,10 @@ where C: NodeClient, K: Keychain, { + if args.amount == 0 { + return Err(Error::InvalidAmount); + } + let parent_key_id = match args.dest_acct_name { Some(d) => { let pm = w.get_acct_path(d)?; @@ -710,6 +718,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); check_ttl(w, &ret_slate)?; let parent_key_id = match args.src_acct_name { diff --git a/libwallet/src/error.rs b/libwallet/src/error.rs index 1c772bf..5300dd1 100644 --- a/libwallet/src/error.rs +++ b/libwallet/src/error.rs @@ -24,6 +24,10 @@ use grin_store; /// Wallet errors, mostly wrappers around underlying crypto or I/O errors. #[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)] pub enum Error { + /// Invalid transaction amount + #[error("Invalid amount (must be greater than zero)")] + InvalidAmount, + /// Not enough funds #[error("Not enough funds. Required: {needed_disp:?}, Available: {available_disp:?}")] NotEnoughFunds { diff --git a/libwallet/src/internal/selection.rs b/libwallet/src/internal/selection.rs index ac17dbd..bac6d92 100644 --- a/libwallet/src/internal/selection.rs +++ b/libwallet/src/internal/selection.rs @@ -73,9 +73,12 @@ where false, )?; if amount_includes_fee { - slate.amount = slate.amount.checked_sub(fee).ok_or(Error::GenericError( - "Transaction amount is too small to include fee".to_string(), - ))?; + let small_amount_err = + Error::GenericError("Transaction amount is too small to include fee".to_string()); + if slate.amount == fee { + return Err(small_amount_err); + } + slate.amount = slate.amount.checked_sub(fee).ok_or(small_amount_err)?; }; if fixed_fee.map(|f| fee != f).unwrap_or(false) { @@ -104,15 +107,9 @@ where context.add_input(&input.key_id, &input.mmr_index, input.value); } - let mut commits: HashMap> = HashMap::new(); - - // Store change output(s) and cached commits + // Store change output(s) for (change_amount, id, mmr_index) in &change_amounts_derivations { context.add_output(&id, &mmr_index, *change_amount); - commits.insert( - id.clone(), - wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?, - ); } Ok(context) diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 86f7675..a4d8308 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -147,6 +147,11 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let arg_vec = vec!["grin-wallet", "-p", "password2", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // Return an explained error when trying to send max amount on empty wallet. + let arg_vec = vec!["grin-wallet", "-p", "password2", "send", "max"]; + let err = execute_command(&app, test_dir, "wallet2", &client2, arg_vec).unwrap_err(); + assert!(format!("{}", err).contains("No spendable funds")); + // Mine a bit into wallet 1 so we have something to send // (TODO: Be able to stop listeners so we can test this better) let wallet_config1 = config1.clone().members.wallet; From 51ce8e2f2a2698e988cb84edfdbf8e4da69c9617 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Tue, 22 Sep 2026 14:14:04 +0200 Subject: [PATCH 09/39] avoid empty wallet seeds (#801) * fix empty wallet seeds * mnemonic: return actual error with entropy size on recovering * seed: extend mnemonic error description * seed: clarify mnemonic errors * seed: clarify mnemonic errors, fix missing phrase test * Clean up seed handling add test --------- Co-authored-by: ardocrat --- api/src/owner.rs | 6 +- impls/src/error.rs | 4 +- impls/src/lifecycle/default.rs | 108 +++++++++++++++++++++++++++++++-- impls/src/lifecycle/seed.rs | 36 +++++++---- libwallet/src/types.rs | 2 +- 5 files changed, 134 insertions(+), 22 deletions(-) diff --git a/api/src/owner.rs b/api/src/owner.rs index 7ca6b5d..1296db8 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -1726,8 +1726,10 @@ where /// * `name`: Reserved for future use, use `None` for the time being. /// * `mnemonic`: If present, restore the wallet seed from the given mnemonic instead of creating /// a new random seed. - /// * `mnemonic_length`: Desired length of mnemonic in bytes (16 or 32, either 12 or 24 words). - /// Use 0 if mnemonic isn't being used. + /// * `mnemonic_length`: Entropy length in bytes: 16, 20, 24, 28 or 32 + /// (12, 15, 18, 21 or 24 words). Ignored when `mnemonic` is provided. + /// For a new random seed, 0 is also accepted and defaults to 32 bytes. + /// All other values return an error. /// * `password`: The password used to encrypt/decrypt the `wallet.seed` file /// /// # Returns diff --git a/impls/src/error.rs b/impls/src/error.rs index 4169e68..a22cb2a 100644 --- a/impls/src/error.rs +++ b/impls/src/error.rs @@ -75,8 +75,8 @@ pub enum Error { Encryption, /// BIP 39 word list - #[error("BIP39 Mnemonic (word list) Error")] - Mnemonic, + #[error("BIP39 Mnemonic (word list) Error: {}", _0)] + Mnemonic(String), /// Command line argument error #[error("{}", _0)] diff --git a/impls/src/lifecycle/default.rs b/impls/src/lifecycle/default.rs index 7514a30..ca11687 100644 --- a/impls/src/lifecycle/default.rs +++ b/impls/src/lifecycle/default.rs @@ -182,7 +182,7 @@ where &mut self, _name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error> { @@ -196,16 +196,15 @@ where return Err(Error::WalletSeedExists(msg)); } } + let entropy_size = if entropy_size == 0 { 32 } else { entropy_size }; WalletSeed::init_file( &data_dir_name, - mnemonic_length, + entropy_size, mnemonic.clone(), password, test_mode, ) - .map_err(|_| { - Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned()) - })?; + .map_err(|e| Error::Lifecycle(format!("Error creating wallet seed: {}", e)))?; info!("Wallet seed file created"); let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { @@ -248,6 +247,9 @@ where let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| { Error::Lifecycle("Error opening wallet (is password correct?)".to_owned()) })?; + if wallet_seed.is_empty() { + warn!("This wallet has an empty seed and its funds are unsafe. Move them to a new wallet."); + } let keychain = wallet_seed .derive_keychain(global::is_testnet()) .map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?; @@ -286,7 +288,7 @@ where .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; let res = wallet_seed .to_mnemonic() - .map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?; + .map_err(|e| Error::Lifecycle(format!("Error recovering wallet seed: {}. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.", e)))?; Ok(ZeroingString::from(res)) } @@ -382,3 +384,97 @@ where } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::keychain::ExtKeychain; + use crate::lifecycle::seed::{EncryptedWalletSeed, SEED_FILE}; + use crate::node_clients::HTTPNodeClient; + use std::fs::File; + use std::io::Write; + use std::time::Duration; + + fn provider(test_dir: &str) -> DefaultLCProvider { + let client = + HTTPNodeClient::new("http://127.0.0.1:1", None, Duration::from_secs(1)).unwrap(); + let mut provider = DefaultLCProvider::new(client); + provider.set_top_level_directory(test_dir).unwrap(); + provider + } + + #[test] + fn default_recovery_phrase() { + let test_dir = "test_output/default_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + + provider + .create_wallet(None, None, 0, password.clone(), false) + .unwrap(); + let mnemonic = provider.get_mnemonic(None, password).unwrap(); + + assert_eq!(mnemonic.split_whitespace().count(), 24); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn mnemonic_error_redacted() { + let test_dir = "test_output/mnemonic_error_redacted"; + let _ = fs::remove_dir_all(test_dir); + let mut provider = provider(test_dir); + let input = ZeroingString::from("INVALID_INPUT_MARKER ".repeat(12)); + let error = provider + .create_wallet(None, Some(input), 32, ZeroingString::from("test"), false) + .unwrap_err() + .to_string(); + + assert!(error.contains("invalid bip39 word")); + assert!(!error.contains("INVALID_INPUT_MARKER")); + assert!(!provider.wallet_exists(None).unwrap()); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn missing_recovery_phrase() { + let test_dir = "test_output/missing_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + let data_dir = PathBuf::from(test_dir).join(GRIN_WALLET_DIR); + fs::create_dir_all(data_dir.clone()).unwrap(); + + let seed_file_path = &format!( + "{}{}{}", + fmt_path(data_dir.to_str().unwrap().to_string()), + MAIN_SEPARATOR, + SEED_FILE, + ); + + let enc_seed = EncryptedWalletSeed::from_seed( + &WalletSeed::from_bytes(vec![].as_slice()), + password.clone(), + ) + .unwrap(); + let enc_seed_json = serde_json::to_string_pretty(&enc_seed).unwrap(); + let mut file = File::create(seed_file_path).unwrap(); + file.write_all(&enc_seed_json.as_bytes()).unwrap(); + + let error = match provider.get_mnemonic(None, password.clone()) { + Ok(_) => panic!("expected missing recovery phrase error"), + Err(error) => error, + }; + + assert_eq!( + error, + Error::Lifecycle("Error recovering wallet seed: BIP39 Mnemonic (word list) Error: invalid mnemonic/entropy length 0. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.".into()) + ); + provider.open_wallet(None, password, false, false).unwrap(); + provider.close_wallet(None).unwrap(); + assert_eq!(fs::read_to_string(seed_file_path).unwrap(), enc_seed_json); + fs::remove_dir_all(test_dir).unwrap(); + } +} diff --git a/impls/src/lifecycle/seed.rs b/impls/src/lifecycle/seed.rs index 5dbbd6c..16f924a 100644 --- a/impls/src/lifecycle/seed.rs +++ b/impls/src/lifecycle/seed.rs @@ -39,11 +39,18 @@ impl WalletSeed { WalletSeed(bytes.to_vec()) } + pub(super) fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn from_mnemonic(word_list: util::ZeroingString) -> Result { let res = mnemonic::to_entropy(&word_list); match res { Ok(s) => Ok(WalletSeed::from_bytes(&s)), - Err(_) => Err(Error::Mnemonic.into()), + Err(mnemonic::Error::BadWord(_)) => { + Err(Error::Mnemonic("invalid bip39 word".to_owned())) + } + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } @@ -61,7 +68,7 @@ impl WalletSeed { let result = mnemonic::from_entropy(&self.0); match result { Ok(r) => Ok(r), - Err(_) => Err(Error::Mnemonic.into()), + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } @@ -76,14 +83,14 @@ impl WalletSeed { } pub fn init_new( - seed_length: usize, + entropy_size: usize, test_mode: bool, password: Option, - ) -> WalletSeed { + ) -> Result { let mut seed: Vec = vec![]; let mut rng = thread_rng(); if !test_mode { - for _ in 0..seed_length { + for _ in 0..entropy_size { seed.push(rng.gen()); } } else { @@ -93,7 +100,10 @@ impl WalletSeed { .as_bytes() .to_vec(); } - WalletSeed(seed) + let _ = mnemonic::from_entropy(seed.as_slice()) + .map(util::ZeroingString::from) + .map_err(|e| Error::Mnemonic(format!("{}", e)))?; + Ok(WalletSeed(seed)) } pub fn seed_file_exists(data_file_dir: &str) -> Result { @@ -168,7 +178,7 @@ impl WalletSeed { pub fn init_file( data_file_dir: &str, - seed_length: usize, + entropy_size: usize, recovery_phrase: Option, password: util::ZeroingString, test_mode: bool, @@ -193,7 +203,7 @@ impl WalletSeed { let seed = match recovery_phrase { Some(p) => WalletSeed::from_mnemonic(p)?, - None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())), + None => WalletSeed::init_new(entropy_size, test_mode, Some(password.clone()))?, }; let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; @@ -277,7 +287,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -325,7 +335,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -359,8 +369,12 @@ mod tests { use crate::util::ZeroingString; #[test] fn wallet_seed_encrypt() { + // Wrong entropy size. + let wrong_entropy_size = WalletSeed::init_new(31, false, None).err(); + assert!(wrong_entropy_size.is_some()); + let password = ZeroingString::from("passwoid"); - let wallet_seed = WalletSeed::init_new(32, false, None); + let wallet_seed = WalletSeed::init_new(32, false, None).unwrap(); let mut enc_wallet_seed = EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap(); println!("EWS: {:?}", enc_wallet_seed); diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index ae86f1b..0aec740 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -81,7 +81,7 @@ where &mut self, name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error>; From 452a3ec51b302091e12fc1a7b2eb24c0ac2625b0 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 16 Sep 2026 15:53:57 +0300 Subject: [PATCH 10/39] Lock outputs before sending with Tor (#814) Co-authored-by: wiesche --- api/src/owner.rs | 73 +- controller/src/command.rs | 34 +- controller/src/controller.rs | 17 - controller/tests/accounts.rs | 294 +++---- controller/tests/build_chain.rs | 91 +-- controller/tests/build_output.rs | 35 +- controller/tests/check.rs | 648 +++++---------- controller/tests/common/mod.rs | 35 +- controller/tests/config_api.rs | 18 +- controller/tests/file.rs | 265 ++---- controller/tests/invoice.rs | 397 ++++----- controller/tests/late_lock.rs | 145 ++-- controller/tests/mwixnet.rs | 168 ++-- controller/tests/no_change.rs | 214 ++--- controller/tests/payment_proofs.rs | 136 ++-- controller/tests/repost.rs | 232 ++---- controller/tests/revert.rs | 289 +++---- controller/tests/self_send.rs | 103 +-- controller/tests/slatepack.rs | 512 +++++------- controller/tests/transaction.rs | 1108 ++++++++++++-------------- controller/tests/ttl_cutoff.rs | 155 ++-- controller/tests/tx_list_filter.rs | 434 +++++----- controller/tests/updater_thread.rs | 31 +- grin | 2 +- impls/src/adapters/tor.rs | 2 +- libwallet/src/mwixnet/onion/onion.rs | 2 +- tests/cmd_line_basic.rs | 248 +++--- tests/owner_v3_lifecycle.rs | 41 +- 28 files changed, 2276 insertions(+), 3453 deletions(-) diff --git a/api/src/owner.rs b/api/src/owner.rs index 1296db8..c180934 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -40,6 +40,7 @@ use grin_wallet_util::OnionV3Address; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; +use libwallet::wallet_lock; use std::convert::TryFrom; use std::fs::File; use std::io::Write; @@ -709,9 +710,9 @@ where /// is confirmed. This method also returns a function that will perform that locking, and it is /// up to the caller to decide the best time to call the lock function /// (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) method). - /// If the exchange method is intended to be synchronous (such as via a direct http call,) + /// If the exchange method is intended to be synchronous (such as via a direct http call) /// then the lock call can wait until the response is confirmed. If it is asynchronous, (such - /// as via file transfer,) the lock call should happen immediately (before the file is sent + /// as via file transfer) the lock call should happen immediately (before the file is sent /// to the recipient). /// /// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html), @@ -719,7 +720,7 @@ where /// function will attempt to send the slate back to the sender using the slatepack sync /// send (TOR). If providing this argument, check the `state` field of the slate to see if the /// sync_send was successful (it should be S2 if the sync sent successfully). It will also post - /// the transction if the `post_tx` field is set. + /// the transaction if the `post_tx` field is set. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if @@ -730,11 +731,15 @@ where /// # Returns /// * a result containing: /// * The transaction [Slate](../grin_wallet_libwallet/slate/struct.Slate.html), - /// which can be forwarded to the recieving party by any means. Once the caller is relatively - /// certain that the transaction has been sent to the recipient, the associated wallet - /// transaction outputs should be locked via a call to - /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs). This must be called before calling - /// [`finalize_tx`](struct.Owner.html#method.finalize_tx). + /// which can be forwarded to the receiving party by any means. With normal locking, an + /// attempted Tor send already locks the outputs, even if sending fails. Do not call + /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) again when forwarding manually. + /// If sending was not requested or was skipped, lock the outputs before forwarding the slate. + /// With late locking, outputs are locked during finalization instead. + /// If `skip_tor` is omitted, `skip_send_attempt` in the Tor config decides whether to send. + /// With normal locking, a returned S1 slate alone does not tell you whether outputs are locked. + /// Set `skip_tor` explicitly or check [`retrieve_txs`](struct.Owner.html#method.retrieve_txs) + /// for the slate ID before locking manually. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks @@ -768,7 +773,7 @@ where /// if let Ok(slate) = result { /// // Send slate somehow /// // ... - /// // Lock our outputs if we're happy the slate was (or is being) sent + /// // Lock outputs for manual sending without late locking /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` @@ -785,32 +790,36 @@ where } _ => None, }; - let (slate, tor_config) = { - let mut w_lock = self.wallet_inst.lock(); - let tor_config = send_args - .as_ref() - .map(|_| crate::tor_config::load(&self.config_path())) - .transpose()?; - let w = w_lock.lc_provider()?.wallet_inst()?; - let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; - (slate, tor_config) - }; + + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + // Helper functionality. If send arguments exist, attempt to send sync and // finalize match send_args { Some(sa) => { - let tc = tor_config.ok_or_else(|| { - Error::TorConfig("Tor config was not loaded with send arguments".into()) - })?; - let can_send = tc.send_tor(sa.skip_tor); - if self.doctest_mode || !can_send || dest.is_none() { - return Ok(slate); - } + let slate = { + wallet_lock!(self.wallet_inst, w); + let late_lock = args.late_lock.unwrap_or(false); + let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + let tc = tor_config.as_ref().ok_or_else(|| { + Error::TorConfig("Tor config was not loaded with send arguments".into()) + })?; + let can_send = tc.send_tor(sa.skip_tor); + if self.doctest_mode || !can_send || dest.is_none() { + return Ok(slate); + } + if !late_lock { + owner::tx_lock_outputs(w, keychain_mask, &slate)?; + } + slate + }; let res = - try_slatepack_sync_workflow(&slate, &dest.unwrap(), Some(tc), None, false); + try_slatepack_sync_workflow(&slate, &dest.unwrap(), tor_config, None, false); match res { Ok(s) => { - self.tx_lock_outputs(keychain_mask, &s)?; let ret_slate = self.finalize_tx(keychain_mask, &s)?; if sa.post_tx { let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff); @@ -834,7 +843,11 @@ where } } } - None => Ok(slate), + None => { + wallet_lock!(self.wallet_inst, w); + let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + Ok(slate) + } } } @@ -2353,7 +2366,7 @@ where /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `slatepack` - A string representing an armored slatepack - /// * `secret_indices` - Indices along this wallet's deriviation path with which to attempt + /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt /// decryption. This function will attempt to use secret keys at each index along this path /// to attempt to decrypt the payload, returning an error if none of the keys match. /// diff --git a/controller/src/command.rs b/controller/src/command.rs index b1543a5..93b02fc 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -439,7 +439,6 @@ where target_slate_version: args.target_slate_version, payment_proof_recipient_address, ttl_blocks: args.ttl_blocks, - send_args: None, late_lock: Some(args.late_lock), ..Default::default() }; @@ -494,14 +493,14 @@ where tor_config.bridge.bridge_line = Some(b); } - let output_sp = || -> Result<(), Error> { + let output_sp = |owner_api: &mut Owner, lock_outputs: bool| -> Result<(), Error> { Ok(output_slatepack( owner_api, keychain_mask, &slate, dest.clone(), args.outfile, - true, + lock_outputs, false, args.slatepack_qr, )?) @@ -509,7 +508,11 @@ where let can_send = tor_config.send_tor(args.skip_tor); if test_mode || !can_send || dest.is_none() { - return output_sp(); + return output_sp(owner_api, !args.late_lock); + } + + if !args.late_lock { + owner_api.tx_lock_outputs(keychain_mask, &slate)?; } let dest = dest.as_ref().unwrap(); @@ -517,7 +520,6 @@ where match res { Ok(s) => { - owner_api.tx_lock_outputs(keychain_mask, &s)?; let ret_slate = owner_api.finalize_tx(keychain_mask, &s)?; let result = owner_api.post_tx(keychain_mask, &ret_slate, args.fluff); match result { @@ -532,7 +534,13 @@ where } Err(e) => { error!("Error sending slate sync: {}", e); - output_sp()?; + output_sp(owner_api, false)?; + if !args.late_lock { + println!( + "Outputs are locked. To unlock them, cancel with `cancel -t {}`.", + slate.id + ); + } } } Ok(()) @@ -581,7 +589,18 @@ where println!(); if !finalizing { - println!("Slatepack data follows. Please provide this output to the other party"); + let cancel_hint = if lock { + format!( + " or cancel it manually with `cancel -t {}` command", + slate.id + ) + } else { + "".to_string() + }; + println!( + "Slatepack data follows. Please provide this output to the other party{}.", + cancel_hint + ); } else { println!("Slatepack data follows."); } @@ -1076,7 +1095,6 @@ where selection_strategy_is_use_all: args.selection_strategy == "all", refresh_outputs_from_node: !info_updated, ttl_blocks: args.ttl_blocks, - send_args: None, ..Default::default() }; let result = owner_api.process_invoice_tx(keychain_mask, &slate, init_args); diff --git a/controller/src/controller.rs b/controller/src/controller.rs index ef61152..49fa040 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -136,23 +136,6 @@ fn init_tor_listener( Ok(process) } -/// Instantiate wallet Owner API for a single-use (command line) call -/// Return a function containing a loaded API context to call -pub fn owner_single_use( - wallet: Arc>>>, - keychain_mask: Option<&SecretKey>, - config_path: PathBuf, - f: F, -) -> Result<(), Error> -where - L: WalletLCProvider<'static, C, K> + 'static, - F: FnOnce(&mut Owner, Option<&SecretKey>) -> Result<(), Error>, - C: NodeClient + 'static, - K: Keychain + 'static, -{ - f(&mut Owner::new(wallet, None, config_path), keychain_mask) -} - /// Instantiate wallet Foreign API for a single-use (command line) call /// Return a function containing a loaded API context to call pub fn foreign_single_use<'a, L, F, C, K>( diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 59645f8..fd19c28 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -19,7 +19,6 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_keychain as keychain; -use std::path::PathBuf; use self::core::global; use self::keychain::{ExtKeychain, Keychain}; @@ -49,7 +48,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -62,7 +62,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -79,48 +80,30 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // test default accounts exist - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let accounts = api.accounts(m)?; - assert_eq!(accounts[0].label, "default"); - assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); - Ok(()) - }, - )?; + { + let accounts = api1.accounts(mask1)?; + assert_eq!(accounts[0].label, "default"); + assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); + } // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let new_path = api.create_account_path(m, "account1").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - let new_path = api.create_account_path(m, "account2").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); - let new_path = api.create_account_path(m, "account3").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); - // trying to add same label again should fail - let res = api.create_account_path(m, "account1"); - assert!(res.is_err()); - Ok(()) - }, - )?; + { + let new_path = api1.create_account_path(mask1, "account1").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "account2").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "account3").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); + // trying to add same label again should fail + let res = api1.create_account_path(mask1, "account1"); + assert!(res.is_err()); + } // add account to wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let new_path = api.create_account_path(m, "listener_account").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - Ok(()) - }, - )?; + { + let new_path = api2.create_account_path(mask2, "listener_account").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + } // Default wallet 2 to listen on that account { @@ -144,120 +127,85 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 5 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 5); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 5 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 5); + } // now check second account { - // let mut w_lock = wallet1.lock(); - // let lc = w_lock.lc_provider()?; - // let w = lc.wallet_inst()?; wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let labels: Vec<_> = api.accounts(m)?.into_iter().map(|a| a.label).collect(); - assert_eq!(labels, ["account1", "default", "account2", "account3"]); - // check last confirmed height on this account is different from above (should be 0) - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 7 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 7); - Ok(()) - }, - )?; - + { + let labels: Vec<_> = api1.accounts(mask1)?.into_iter().map(|a| a.label).collect(); + assert_eq!(labels, ["account1", "default", "account2", "account3"]); + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 7 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 7); + } // should be nothing in default account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 0,); - assert_eq!(wallet1_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 0,); + assert_eq!(wallet1_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 0); + } // Send a tx to another wallet { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 9); - Ok(()) - }, - )?; + { + let args = InitTxArgs { + src_acct_name: None, + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; + } + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 9); + } // Use the requested account's stored height { wallet_inst!(wallet1, w); @@ -272,59 +220,41 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 12); - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - println!("{:?}", txs); - assert_eq!(txs.len(), 5); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 12); + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + println!("{:?}", txs); + assert_eq!(txs.len(), 5); + } // wallet 2 should only have this tx on the listener account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - }, - )?; + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + } // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet2_info.last_confirmed_height, 0); - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - assert_eq!(wallet2_info.total, 0,); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - }, - )?; + { + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, false, 1)?; + assert_eq!(wallet2_info.last_confirmed_height, 0); + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + assert_eq!(wallet2_info.total, 0,); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); + } // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/build_chain.rs b/controller/tests/build_chain.rs index 7120e44..12210e8 100644 --- a/controller/tests/build_chain.rs +++ b/controller/tests/build_chain.rs @@ -21,9 +21,8 @@ extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; use grin_core as core; -use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use rand::Rng; use std::sync::atomic::Ordering; @@ -48,7 +47,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); debug!("Mask1: {:?}", mask1); @@ -60,7 +60,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); debug!("Mask2: {:?}", mask2); @@ -74,25 +75,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -105,22 +89,14 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } // let's say 1 in every 3 blocks has a transaction (i.e. random 0 here and wallet1 has funds) let transact = rng.gen_range(0, 2) == 0; @@ -134,30 +110,21 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let num_txs = rng.gen_range(0, 3); for _ in 0..num_txs { let amount: u64 = rng.gen_range(1, 10_000_000_001); - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; } } // let logging finish diff --git a/controller/tests/build_output.rs b/controller/tests/build_output.rs index 491e916..798732d 100644 --- a/controller/tests/build_output.rs +++ b/controller/tests/build_output.rs @@ -25,7 +25,6 @@ use grin_util::{secp, ZeroingString}; use grin_wallet_libwallet as libwallet; use impls::test_framework::LocalWalletClient; use rand::{thread_rng, Rng}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -37,7 +36,7 @@ use common::{clean_output_dir, create_wallet_proxy, setup}; fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Generate seed so we can verify the blinding factor is derived correctly let seed: [u8; 32] = thread_rng().gen(); - let keychain = ExtKeychain::from_seed(&seed, false).unwrap(); + let keychain = ExtKeychain::from_seed(&seed, false)?; let mnemonic = mnemonic::from_entropy(&seed).unwrap(); // Create a new proxy to simulate server and wallet responses @@ -52,7 +51,8 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error "wallet1", Some(ZeroingString::from(mnemonic)), &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -67,28 +67,19 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error let secp = secp::Secp256k1::with_caps(secp::ContextFlag::Commit); let features = OutputFeatures::Plain; let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let built_output = sender_api.build_output(m, features, amount)?; + let built_output = api1.build_output(mask1, features, amount)?; - let key_id = built_output.key_id; - assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); + let key_id = built_output.key_id; + assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); - let blind = built_output.blind; - let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; - assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); + let blind = built_output.blind; + let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; + assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); - let output = built_output.output; - assert_eq!(output.features(), features); - assert_eq!(output.commitment(), secp.commit(amount, key)?); - output.verify_proof()?; - - Ok(()) - }, - )?; + let output = built_output.output; + assert_eq!(output.features(), features); + assert_eq!(output.commitment(), secp.commit(amount, key)?); + output.verify_proof()?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/check.rs b/controller/tests/check.rs index d526335..6d7fbdb 100644 --- a/controller/tests/check.rs +++ b/controller/tests/check.rs @@ -27,7 +27,6 @@ use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlatePutter as _}; use libwallet::{InitTxArgs, NodeClient}; use std::cmp; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -66,7 +65,8 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -77,7 +77,8 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -89,34 +90,22 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // few values to keep things shorter - let reward = core::consensus::REWARD; - let cm = global::coinbase_maturity() as u64; // assume all testing precedes soft fork height + let reward = consensus::REWARD; + let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "named_account_1")?; - api.create_account_path(m, "account_2")?; - api.create_account_path(m, "account_3")?; - api.set_active_account(m, "named_account_1")?; - Ok(()) - }, - )?; + { + api1.create_account_path(mask1, "named_account_1")?; + api1.create_account_path(mask1, "account_2")?; + api1.create_account_path(mask1, "account_3")?; + api1.set_active_account(mask1, "named_account_1")?; + } // add account to wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + { + api2.create_account_path(mask2, "account_1")?; + api2.set_active_account(mask2, "account_1")?; + } // Do some mining let bh = 20u64; @@ -124,36 +113,21 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Sanity check contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(wallet1_info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(wallet1_info.total, c); + assert_eq!(txs.len(), bh as usize); + } // Accidentally delete some outputs - let mut w1_outputs_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - w1_outputs_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let w1_outputs_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; let w1_outputs: Vec = w1_outputs_commits.into_iter().map(|m| m.output).collect(); { @@ -170,108 +144,54 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { } // check we have a problem now - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_ne!(wallet1_info.total, c); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_ne!(wallet1_info.total, c); // this should restore our missing outputs - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check our outputs match again - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.total, bh * reward); - // And check account names haven't been splatted - let accounts = api.accounts(m)?; - assert_eq!(accounts.len(), 4); - assert!(api.set_active_account(m, "account_1").is_err()); - assert!(api.set_active_account(m, "named_account_1").is_ok()); - Ok(()) - }, - )?; - + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.total, bh * reward); + // And check account names haven't been splatted + let accounts = api1.accounts(mask1)?; + assert_eq!(accounts.len(), 4); + assert!(api1.set_active_account(mask1, "account_1").is_err()); + assert!(api1.set_active_account(mask1, "named_account_1").is_ok()); + } // perform a transaction, but don't let it finish - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - let send_file = format!("{}/part_tx_1.tx", test_dir); - PathToSlate(send_file.into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + { + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + } // check we're all locked - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.amount_currently_spendable, 0); - Ok(()) - }, - )?; - + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.amount_currently_spendable, 0); // unlock/restore - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check spendable amount again - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -300,7 +220,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "miner", None, &mut wallet_proxy, - false + false, + _m_api ); let miner_mask = (&miner_mask_i).as_ref(); @@ -313,7 +234,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet1", seed_phrase, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -324,7 +246,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet2", seed_phrase, &mut wallet_proxy, - false + false, + _api2 ); let mask2 = (&mask2_i).as_ref(); // we'll restore into here @@ -336,7 +259,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet3", seed_phrase, &mut wallet_proxy, - false + false, + api3 ); let mask3 = (&mask3_i).as_ref(); // also restore into here @@ -348,7 +272,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet4", seed_phrase, &mut wallet_proxy, - false + false, + api4 ); let mask4 = (&mask4_i).as_ref(); // Simulate a recover from seed without restore into here @@ -360,7 +285,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet5", seed_phrase, &mut wallet_proxy, - false + false, + api5 ); //simulate a recover from seed without restore into here let mask5 = (&mask5_i).as_ref(); @@ -372,7 +298,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet6", seed_phrase, &mut wallet_proxy, - false + false, + api6 ); let mask6 = (&mask6_i).as_ref(); @@ -384,7 +311,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet7", seed_phrase, &mut wallet_proxy, - false + false, + api7 ); let mask7 = (&mask7_i).as_ref(); create_wallet_and_add!( @@ -395,7 +323,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet8", seed_phrase, &mut wallet_proxy, - false + false, + api8 ); let mask8 = (&mask8_i).as_ref(); create_wallet_and_add!( @@ -406,7 +335,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet9", seed_phrase, &mut wallet_proxy, - false + false, + api9 ); let mask9 = (&mask9_i).as_ref(); create_wallet_and_add!( @@ -417,7 +347,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet10", seed_phrase, &mut wallet_proxy, - false + false, + api10 ); let mask10 = (&mask10_i).as_ref(); @@ -468,18 +399,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // 0) Check repair when all is okay should leave wallet contents alone - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - let info = wallet_info!(wallet1.clone(), m)?; - assert_eq!(info.amount_currently_spendable, base_amount * 6); - assert_eq!(info.total, base_amount * 6); - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; + let info = wallet_info!(wallet1.clone(), mask1)?; + assert_eq!(info.amount_currently_spendable, base_amount * 6); + assert_eq!(info.total, base_amount * 6); // send some funds to wallet 2 send_to_dest!( @@ -523,53 +446,21 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er // seed + BIP32 path. // 1) a full restore should recover all of them: - wallet::controller::owner_single_use( - wallet3.clone(), - mask3, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api3.scan(mask3, None, false)?; - wallet::controller::owner_single_use( - wallet3.clone(), - mask3, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet3.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - assert_eq!(info.total, base_amount * 21); - Ok(()) - }, - )?; + let info = wallet_info!(wallet3.clone(), mask3)?; + let outputs = api3.retrieve_outputs(mask3, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + assert_eq!(info.total, base_amount * 21); // 2) scan should recover them into a single wallet - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet1.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - Ok(()) - }, - )?; + let info = wallet_info!(wallet1.clone(), mask1)?; + let outputs = api1.retrieve_outputs(mask1, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); // 3) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -601,41 +492,17 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet4.clone(), - mask4, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet4.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * 45); - Ok(()) - }, - )?; + let info = wallet_info!(wallet4.clone(), mask4)?; + let outputs = api4.retrieve_outputs(mask4, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * 45); - wallet::controller::owner_single_use( - wallet5.clone(), - mask5, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api5.scan(mask5, None, false)?; - wallet::controller::owner_single_use( - wallet5.clone(), - mask5, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet5.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * (45)); - Ok(()) - }, - )?; + let info = wallet_info!(wallet5.clone(), mask5)?; + let outputs = api5.retrieve_outputs(mask5, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * (45)); // 4) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -662,50 +529,20 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er )?; bh += 3; - let _ = test_framework::award_blocks_to_wallet( - &chain, - miner.clone(), - miner_mask, - cm as usize, - false, - ); + let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * 78); - Ok(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * 78); - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api6.scan(mask6, None, true)?; - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * (78)); - Ok(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * (78)); // 5) Start using same seed with a different account, amounts should // be distinct and restore should return funds from other account @@ -734,16 +571,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // mix it up a bit - wallet::controller::owner_single_use( - wallet7.clone(), - mask7, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api7.create_account_path(mask7, "account_1")?; + api7.set_active_account(mask7, "account_1")?; send_to_dest!( miner.clone(), @@ -772,57 +601,33 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet7.clone(), - mask7, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); + api7.set_active_account(mask7, "default")?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); - wallet::controller::owner_single_use( - wallet8.clone(), - mask8, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - Ok(()) - }, - )?; + api8.scan(mask8, None, false)?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + api8.set_active_account(mask8, "account_1")?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); // 6) Start using same seed with a different account, now overwriting // ids on account 2 as well, scan should get all outputs created // to now into 2 accounts - wallet::controller::owner_single_use( - wallet9.clone(), - mask9, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api9.create_account_path(mask9, "account_1")?; + api9.set_active_account(mask9, "account_1")?; send_to_dest!( miner.clone(), @@ -848,53 +653,37 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; let _bh = bh; - wallet::controller::owner_single_use( - wallet9.clone(), - mask9, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.scan(m, None, true)?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + api9.scan(mask9, None, true)?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + api9.set_active_account(mask9, "default")?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); // 7) Ensure scan creates missing accounts - wallet::controller::owner_single_use( - wallet10.clone(), - mask10, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + api10.scan(mask10, None, true)?; + api10.set_active_account(mask10, "account_1")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + api10.set_active_account(mask10, "default")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -918,7 +707,8 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + _api1 ); let mask1 = (&mask1_i).as_ref(); thread::spawn(move || { @@ -952,7 +742,7 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> ); assert_eq!(outputs.2.len(), 14); - // mid range + // mid-range let ranges = client1.height_range_to_pmmr_indices(5, Some(14))?; assert_eq!(ranges, (8, 25)); let outputs = client1.get_outputs_by_pmmr_index(ranges.0, Some(ranges.1), 1000)?; @@ -1002,7 +792,8 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -1017,19 +808,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1076,18 +858,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } assert!(batches > 1); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let (_, info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - Ok(()) - }, - )?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, false, true, None)?; + let (_, info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); @@ -1109,7 +883,8 @@ fn restore_corrupted_outputs_across_batches_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -1124,18 +899,9 @@ fn restore_corrupted_outputs_across_batches_impl( let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1173,30 +939,22 @@ fn restore_corrupted_outputs_across_batches_impl( assert_eq!(last_scanned.hash, ""); } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, outputs_after_first_batch) = api.retrieve_outputs(m, false, false, None)?; - assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); + let (_, outputs_after_first_batch) = api1.retrieve_outputs(mask1, false, false, None)?; + assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let unique_keys = restored_outputs - .iter() - .map(|o| o.output.key_id.clone()) - .collect::>(); + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, false, true, None)?; + let unique_keys = restored_outputs + .iter() + .map(|o| o.output.key_id.clone()) + .collect::>(); - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - assert_eq!(unique_keys.len(), bh as usize); - assert!(restored_outputs - .iter() - .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); - Ok(()) - }, - )?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); + assert_eq!(unique_keys.len(), bh as usize); + assert!(restored_outputs + .iter() + .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); diff --git a/controller/tests/common/mod.rs b/controller/tests/common/mod.rs index 725160e..716b79e 100644 --- a/controller/tests/common/mod.rs +++ b/controller/tests/common/mod.rs @@ -19,11 +19,15 @@ extern crate grin_wallet_libwallet as libwallet; use grin_core as core; use grin_keychain as keychain; use grin_util as util; +use std::env; +use std::path::PathBuf; use self::core::global; use self::core::global::ChainTypes; use self::keychain::ExtKeychain; use self::libwallet::WalletInst; +use grin_wallet_api::Owner; +use grin_wallet_config::{initial_setup_wallet, GRIN_WALLET_DIR}; use impls::test_framework::{LocalWalletClient, WalletProxy}; use impls::{DefaultLCProvider, DefaultWalletImpl}; use std::sync::Arc; @@ -41,9 +45,9 @@ macro_rules! wallet_inst { #[macro_export] macro_rules! create_wallet_and_add { - ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr) => { + ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr, $owner_api: ident) => { let $client = LocalWalletClient::new($name, $proxy.tx.clone()); - let ($wallet, $mask) = common::create_local_wallet( + let ($wallet, $mask, $owner_api) = common::create_local_wallet( $test_dir, $name, $seed_phrase.clone(), @@ -125,7 +129,18 @@ pub fn create_local_wallet( >, >, Option, + Owner, LocalWalletClient, ExtKeychain>, ) { + let mut current_dir; + current_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + current_dir.push(test_dir); + current_dir.push(name); + let config = + initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(current_dir), true).unwrap(); + let mut wallet_config = config.clone().members.wallet; + let mut wallet = Box::new(DefaultWalletImpl::::new(client).unwrap()) as Box< dyn WalletInst< @@ -135,13 +150,25 @@ pub fn create_local_wallet( >, >; let lc = wallet.lc_provider().unwrap(); - let _ = lc.set_top_level_directory(&format!("{}/{}", test_dir, name)); + // legacy hack to avoid the need for changes in existing grin-wallet.toml files + // remove `wallet_data` from end of path as + // new lifecycle provider assumes grin_wallet.toml is in root of data directory + let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir); + if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) { + top_level_wallet_dir.pop(); + wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); + } + let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); lc.create_wallet(None, mnemonic, 32, ZeroingString::from(""), false) .unwrap(); let mask = lc .open_wallet(None, ZeroingString::from(""), create_mask, false) .unwrap(); - (Arc::new(Mutex::new(wallet)), mask) + + let wallet = Arc::new(Mutex::new(wallet)); + let owner_api = Owner::new(wallet.clone(), None, config.config_file_path.clone()); + + (wallet, mask, owner_api) } #[allow(dead_code)] diff --git a/controller/tests/config_api.rs b/controller/tests/config_api.rs index 5936a7f..6d1ac20 100644 --- a/controller/tests/config_api.rs +++ b/controller/tests/config_api.rs @@ -21,9 +21,9 @@ use config::config::{get_global_config, reload_global_config}; use config::GlobalWalletConfig; use impls::test_framework::LocalWalletClient; use libwallet::{InitTxArgs, InitTxSendArgs}; -use std::fs; use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; +use std::{env, fs}; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; @@ -63,7 +63,8 @@ fn tor_disable() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let path = PathBuf::from(test_dir).join("grin-wallet.toml"); let mut config = @@ -94,6 +95,7 @@ fn tor_disable() { ); assert_eq!(cached, stored); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -113,7 +115,8 @@ fn send_preflight() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let owner = api::Owner::new( wallet.clone(), @@ -144,6 +147,7 @@ fn send_preflight() { assert!(after_txs.is_empty()); assert_eq!(snapshot(&wallet_data), before_data); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -163,9 +167,13 @@ fn directory_change() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); - let old_dir = PathBuf::from(test_dir).join("wallet"); + let old_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + let old_dir = old_dir.join(test_dir).join("wallet"); let old_config = old_dir.join("grin-wallet.toml"); let new_dir = PathBuf::from(test_dir).join("other"); let owner = api::Owner::new(wallet.clone(), None, old_config.clone()); diff --git a/controller/tests/file.rs b/controller/tests/file.rs index e313407..a4e1fc4 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -27,7 +27,7 @@ use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; -use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate}; +use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs}; #[macro_use] mod common; @@ -50,7 +50,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -61,7 +62,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -76,28 +78,12 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -122,32 +108,24 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }; // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; // Get some mining done { @@ -169,52 +147,28 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'wallet 2' account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -231,44 +185,27 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), ), }; - let mut slate = Slate::blank(2, true); + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = PathToSlate((&send_file).into()).get_tx()?.0; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = PathToSlate((&send_file).into()).get_tx()?.0; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - }, - )?; wallet::controller::foreign_single_use( wallet2.clone(), PathBuf::from(test_dir), @@ -281,15 +218,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + + api1.post_tx(mask1, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -305,40 +235,22 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), format!("{}/standard_pp_S3.txbin", test_dir), ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; wallet::controller::foreign_single_use( wallet2.clone(), @@ -352,21 +264,12 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index b48f66e..8b76998 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -22,7 +22,7 @@ use grin_wallet_libwallet as libwallet; use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate, SlateState}; +use libwallet::{InitTxArgs, IssueInvoiceTxArgs, SlateState}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -46,7 +46,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - true + true, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -72,16 +74,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -93,46 +87,28 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, _bh as usize, false); // Sanity check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, _bh); - assert_eq!(wallet1_info.total, _bh * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, _bh); + assert_eq!(wallet1_info.total, _bh * reward); - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let error = api - .issue_invoice_tx( - m, - IssueInvoiceTxArgs { - amount: 0, - ..Default::default() - }, - ) - .unwrap_err(); - assert_eq!(error, libwallet::Error::InvalidAmount); - - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, + let error = api2 + .issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { + amount: 0, ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let receive_result = wallet::controller::foreign_single_use( @@ -142,16 +118,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { |api| api.receive_tx(&slate, None, None).map(|_| ()), ); assert_eq!(receive_result, Err(libwallet::Error::SlateState)); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, false, None, Some(slate.id), None)?; - assert!(txs.is_empty()); - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); // receive must reject every slate state except S1 for state in [ @@ -173,51 +141,34 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(res, Err(libwallet::Error::SlateState), "state {}", state); } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut zero_amount_slate = slate.clone(); - zero_amount_slate.amount = 0; - assert_eq!( - api.process_invoice_tx(m, &zero_amount_slate, args.clone()) - .unwrap_err(), - libwallet::Error::InvalidAmount - ); - - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut zero_amount_slate = slate.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api1.process_invoice_tx(mask1, &zero_amount_slate, args.clone()) + .unwrap_err(), + libwallet::Error::InvalidAmount + ); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - assert_eq!( - api.tx_lock_outputs(m, &slate), - Err(libwallet::Error::SlateState) - ); - let (_, txs) = api.retrieve_txs(m, false, None, None, None)?; - assert_eq!(txs.len(), 1); - assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); - Ok(()) - }, - )?; + assert_eq!( + api2.tx_lock_outputs(mask2, &slate), + Err(libwallet::Error::SlateState) + ); + let (_, txs) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); // wallet 2 finalizes and posts wallet::controller::foreign_single_use( @@ -233,86 +184,54 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(slate.state, SlateState::Invoice3); // wallet 1 posts so wallet 2 doesn't get the mined amount - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; _bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert!(txs.len() == 1); - println!( - "last confirmed height: {}, bh: {}", - wallet2_info.last_confirmed_height, _bh - ); - assert!(refreshed); - Ok(()) - }, - )?; + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), 1); + println!( + "last confirmed height: {}, bh: {}", + wallet2_info.last_confirmed_height, _bh + ); + assert!(refreshed); // Check transaction log for wallet 1, ensure only 1 entry // exists - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len() as u64, _bh + 1); - println!( - "Wallet 1: last confirmed height: {}, bh: {}", - wallet1_info.last_confirmed_height, _bh - ); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len() as u64, _bh + 1); + println!( + "Wallet 1: last confirmed height: {}, bh: {}", + wallet1_info.last_confirmed_height, _bh + ); // Test self-sending - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - println!("Self invoice slate init: {}", slate); - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api1.issue_invoice_tx(mask1, args)?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + println!("Self invoice slate init: {}", slate); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; println!("Self invoice slate after process: {}", slate); @@ -329,112 +248,66 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); - //bh += 3; - // As above, but use owner API to finalize - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); - // wallet 2 finalizes via owner API - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 2 receives and finalizes via owner API + slate = api2.finalize_tx(mask2, &slate)?; assert_eq!(slate.state, SlateState::Invoice3); // test that payee can only cancel once let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let orig_slate = slate.clone(); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args.clone())?; - api.tx_lock_outputs(m, &slate)?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args.clone())?; + api1.tx_lock_outputs(mask1, &slate)?; - // Wallet 1 cancels the invoice transaction - api.cancel_tx(m, None, Some(slate.id))?; + // Wallet 1 cancels the invoice transaction + api1.cancel_tx(mask1, None, Some(slate.id))?; - // Wallet 1 attempts to repay again - let res = api.process_invoice_tx(m, &orig_slate, args); - assert!(res.is_err()); - - Ok(()) - }, - )?; + // Wallet 1 attempts to repay again + let res = api1.process_invoice_tx(mask1, &orig_slate, args); + assert!(res.is_err()); assert_eq!(slate.state, SlateState::Invoice2); // let logging finish diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index 2d1ec29..8783610 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -18,9 +18,8 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -28,6 +27,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use libwallet::InitTxSendArgs; /// self send impl fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -46,7 +46,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -69,26 +71,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - Ok(()) - }, - )?; - - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api2.create_account_path(mask2, "account1")?; // Get some mining done { @@ -102,70 +86,75 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; - let mut slate = Slate::blank(2, false); let amount = 100_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - late_lock: Some(true), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - println!("S1 SLATE: {}", slate_i); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - println!("S2 SLATE: {}", slate); + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + late_lock: Some(true), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + println!("S1 SLATE: {}", slate_i); + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + println!("S2 SLATE: {}", slate); - // Note we don't call `tx_lock_outputs` on the sender side here, - // as the outputs will only be locked during finalization + // Note we don't call `tx_lock_outputs` on the sender side here, + // as the outputs will only be locked during finalization - slate = sender_api.finalize_tx(m, &slate)?; - println!("S3 SLATE: {}", slate); + slate = api1.finalize_tx(mask1, &slate)?; + println!("S3 SLATE: {}", slate); - // Now post tx to our node for inclusion in the next block. - sender_api.post_tx(m, &slate, true)?; - - Ok(()) - }, - )?; + // Now post tx to our node for inclusion in the next block. + api1.post_tx(mask1, &slate, true)?; test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false)?; // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - // Reward from mining 11 blocks, minus the amount sent. - // Note: We mined the block containing the tx, so fees are effectively refunded. - assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + // Reward from mining 11 blocks, minus the amount sent. + // Note: We mined the block containing the tx, so fees are effectively refunded. + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(amount, wallet_info.amount_currently_spendable); - Ok(()) - }, - )?; + // Make sure outputs are not locked on failed send with arguments. + // Fail sending without starting Tor + api1.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + late_lock: Some(true), + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); + // Make sure spendable balance not changed. + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); + + let (wallet2_refreshed, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(amount, wallet_info.amount_currently_spendable); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 60e4bd8..5ae886b 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -50,7 +50,8 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -65,16 +66,8 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -86,123 +79,84 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( wallet1.clone(), - mask1, PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use( - wallet1.clone(), - PathBuf::from(test_dir), - mask1_i.clone(), - |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; - Ok(()) - }, - )?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // Recipient wallet creates a mwixnet request from the last output - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let secp_locked = util::static_secp_instance(); - let secp = secp_locked.lock(); - let server_pubkey_str_1 = - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; - let server_pubkey_str_2 = - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; - let server_pubkey_str_3 = - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; - let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) - .unwrap(); - let server_key_2 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) - .unwrap(); - let server_key_3 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) - .unwrap(); - let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, - }; - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); + let secp_locked = util::static_secp_instance(); + let secp = secp_locked.lock(); + let server_pubkey_str_1 = "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; + let server_pubkey_str_2 = "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; + let server_pubkey_str_3 = "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; + let server_key_1 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap())?; + let server_key_2 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap())?; + let server_key_3 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap())?; + let params = MixnetReqCreationParams { + server_keys: vec![server_key_1, server_key_2, server_key_3], + fee_per_hop: 50_000_000, + }; + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; + let mwixnet_req = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; - println!("MWIXNET REQ: {:?}", mwixnet_req); + println!("MWIXNET REQ: {:?}", mwixnet_req); - // check output we created comsig for is indeed locked - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert!(last_output.output.status == libwallet::OutputStatus::Locked); - - Ok(()) - }, - )?; + // check output we created comsig for is indeed locked + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); + assert_eq!(last_output.output.status, libwallet::OutputStatus::Locked); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/no_change.rs b/controller/tests/no_change.rs index aa1a56e..503691e 100644 --- a/controller/tests/no_change.rs +++ b/controller/tests/no_change.rs @@ -22,7 +22,7 @@ use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate}; +use libwallet::{InitTxArgs, IssueInvoiceTxArgs}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -44,7 +44,8 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -57,7 +58,8 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -77,109 +79,67 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let fee = core::libtx::tx_fee(1, 1, 1); // send a single block's worth of transactions with minimal strategy - let mut slate = Slate::blank(2, false); - let mut stored_excess = None; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward - fee, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - println!("Posted Slate: {:?}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: None, + amount: reward - fee, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + println!("Posted Slate: {:?}", slate); + let mut stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api1.post_tx(mask1, &slate, false)?; // ensure stored excess is correct in both wallets // Wallet 1 calculated the excess with the full slate // Wallet 2 only had the excess provided by // wallet 1 // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - SENDING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - }, - )?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - SENDING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); // Refresh and check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - RECEIVING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - RECEIVING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); // ensure invoice TX works as well with no change - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward - fee, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward - fee, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; // wallet 2 finalizes and posts wallet::controller::foreign_single_use( @@ -192,54 +152,30 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - println!("Invoice Posted TX: {}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + println!("Invoice Posted TX: {}", slate); + stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api2.post_tx(mask2, &slate, false)?; // check wallet 2's version - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - stored_excess = tx.kernel_excess; - println!("Wallet 2: {:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - } - Ok(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + stored_excess = tx.kernel_excess; + println!("Wallet 2: {:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); + } // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - println!("Wallet 1: {:?}", tx); - println!(); - assert_eq!(stored_excess, tx.kernel_excess); - assert!(tx.confirmed); - } - Ok(()) - }, - )?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + println!("Wallet 1: {:?}", tx); + println!(); + assert_eq!(stored_excess, tx.kernel_excess); + assert!(tx.confirmed); + } // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index 651e486..5c4eeaf 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -21,7 +21,6 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; use libwallet::{InitTxArgs, Slate}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -45,7 +44,8 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -58,7 +58,8 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -77,99 +78,74 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); println!("Public address is: {:?}", address); let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - assert_eq!( - slate_i.payment_proof.as_ref().unwrap().receiver_address, - address.as_ref().unwrap().pub_key, - ); - println!( - "Sender addr: {:?}", - slate_i.payment_proof.as_ref().unwrap().sender_address - ); + assert_eq!( + slate_i.payment_proof.as_ref().unwrap().receiver_address, + address.as_ref().unwrap().pub_key, + ); + println!( + "Sender addr: {:?}", + slate_i.payment_proof.as_ref().unwrap().sender_address + ); - // Check we are creating a tx with kernel features 0 - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); + // Check we are creating a tx with kernel features 0 + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; - // Ensure what's stored in TX log for payment proof is correct - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(txs[0].payment_proof.is_some()); - let pp = txs[0].clone().payment_proof.unwrap(); - assert_eq!( - pp.receiver_address, - slate_i.payment_proof.as_ref().unwrap().receiver_address - ); - assert!(pp.receiver_signature.is_some()); - assert_eq!(pp.sender_address_path, 0); - assert_eq!(pp.sender_signature, None); + // Ensure what's stored in TX log for payment proof is correct + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(txs[0].payment_proof.is_some()); + let pp = txs[0].clone().payment_proof.unwrap(); + assert_eq!( + pp.receiver_address, + slate_i.payment_proof.as_ref().unwrap().receiver_address + ); + assert!(pp.receiver_signature.is_some()); + assert_eq!(pp.sender_address_path, 0); + assert_eq!(pp.sender_signature, None); - // check we should get an error at this point since proof is not complete - let pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id)); - assert!(pp.is_err()); + // check we should get an error at this point since proof is not complete + let pp = api1.retrieve_payment_proof(mask1, true, None, Some(slate.id)); + assert!(pp.is_err()); - slate = sender_api.finalize_tx(m, &slate)?; - sender_api.post_tx(m, &slate, true)?; - Ok(()) - }, - )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, true)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // Check payment proof here - let mut pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id))?; + // Check payment proof here + let mut pp = api1.retrieve_payment_proof(mask1, true, None, Some(slate.id))?; - println!("Payment proof: {:?}", pp); + println!("Payment proof: {:?}", pp); - // verify, should be good - let res = sender_api.verify_payment_proof(m, &pp)?; - assert_eq!(res, (true, false)); + // verify, should be good + let res = api1.verify_payment_proof(mask1, &pp)?; + assert_eq!(res, (true, false)); - // Modify values, should not be good - pp.amount = 20; - let res = sender_api.verify_payment_proof(m, &pp); - assert!(res.is_err()); - Ok(()) - }, - )?; + // Modify values, should not be good + pp.amount = 20; + let res = api1.verify_payment_proof(mask1, &pp); + assert!(res.is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 0718364..7f3a39b 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -21,7 +21,7 @@ extern crate grin_wallet_libwallet as libwallet; use grin_core as core; use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlateGetter as _, SlatePutter as _}; use std::sync::atomic::Ordering; @@ -49,7 +49,8 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -60,7 +61,8 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -75,28 +77,11 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -110,34 +95,24 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let send_file = format!("{}/part_tx_1.tx", test_dir); let receive_file = format!("{}/part_tx_2.tx", test_dir); - let mut slate = Slate::blank(2, false); - // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; @@ -167,69 +142,37 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } // wallet 1 finalize - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - slate = PathToSlate((&receive_file).into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + slate = PathToSlate((&receive_file).into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; // Now repost from cached - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - println!("TXS[0]: {:?}", txs[0]); - let stored_tx = api.get_stored_tx(m, None, Some(&txs[0].tx_slate_id.unwrap()))?; - println!("Stored tx: {:?}", stored_tx); - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + println!("TXS[0]: {:?}", txs[0]); + let stored_tx = api1.get_stored_tx(mask1, None, Some(&txs[0].tx_slate_id.unwrap()))?; + println!("Stored tx: {:?}", stored_tx); + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); - // as above, but syncronously + // as above, but synchronously { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("mining")?; @@ -239,78 +182,45 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> w.set_parent_key_id_by_name("account1")?; } - let mut slate = Slate::blank(2, false); let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Now repost from cached - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let stored_tx_slate = api.get_stored_tx(m, Some(txs[0].id), None)?.unwrap(); - api.post_tx(m, &stored_tx_slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let stored_tx_slate = api1.get_stored_tx(mask1, Some(txs[0].id), None)?.unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; - // - // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 4); - Ok(()) - }, - )?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * amount); - Ok(()) - }, - )?; + // update/test contents of both accounts + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 4); + + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * amount); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/revert.rs b/controller/tests/revert.rs index ef5a887..6c4c8a6 100644 --- a/controller/tests/revert.rs +++ b/controller/tests/revert.rs @@ -24,14 +24,13 @@ use grin_core::global; use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; use grin_util::Mutex; -use grin_wallet_controller::controller::owner_single_use as owner; +use grin_wallet_api::Owner; use grin_wallet_impls::test_framework::*; use grin_wallet_impls::{DefaultLCProvider, PathToSlate, SlatePutter}; use grin_wallet_libwallet as libwallet; use grin_wallet_libwallet::api_impl::types::InitTxArgs; use grin_wallet_libwallet::WalletInst; use log::error; -use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; @@ -63,6 +62,8 @@ fn revert( Option, Wallet, Option, + Owner, LocalWalletClient, ExtKeychain>, + Owner, LocalWalletClient, ExtKeychain>, ), libwallet::Error, > { @@ -82,7 +83,8 @@ fn revert( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = mask1_i.as_ref(); @@ -94,28 +96,23 @@ fn revert( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running - std::thread::spawn(move || { + thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "a")?; - api.set_active_account(m, "a")?; - Ok(()) - })?; + api1.create_account_path(mask1, "a")?; + api1.set_active_account(mask1, "a")?; - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "b")?; - api.set_active_account(m, "b")?; - Ok(()) - })?; + api2.create_account_path(mask2, "b")?; + api2.set_active_account(mask2, "b")?; let reward = core::consensus::REWARD; let cm = global::coinbase_maturity() as u64; @@ -126,76 +123,60 @@ fn revert( award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false)?; // Sanity check contents - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, bh * reward); - assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - })?; + let (refreshed, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(info.total, c); + assert_eq!(txs.len(), bh as usize); - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); // Send some funds - let mut tx = None; - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: sent, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - let send_file = format!("{}/part_tx_1.tx", test_dir); - PathToSlate(send_file.into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - let slate = client1.send_tx_slate_direct("wallet2", &slate)?; - let slate = api.finalize_tx(m, &slate)?; - tx = slate.tx; - - Ok(()) - })?; - let tx = tx.expect("tx from slate"); + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: sent, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate)?; + let slate = api1.finalize_tx(mask1, &slate)?; + let tx = slate.tx.expect("tx from slate"); // Check funds have been received - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(!tx.confirmed); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(!&txs[0].confirmed); // Update parallel chain assert_eq!(chain2.head_header().unwrap().height, 0); @@ -223,23 +204,19 @@ fn revert( let bh = bh + 1; // Check funds have been confirmed - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.kernel_excess.is_some()); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(&txs[0].confirmed); + assert!(&txs[0].kernel_excess.is_some()); + assert!(&txs[0].reverted_after.is_none()); // Attach more blocks to the parallel chain, making it the longest one award_block_to_wallet(&chain2, &[], wallet1.clone(), mask1)?; @@ -258,32 +235,29 @@ fn revert( let bh = bh + 1; // Check funds have been reverted - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - api.scan(m, None, false)?; - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReverted); - assert!(!tx.confirmed); - assert!(tx.reverted_after.is_some()); - Ok(()) - })?; + api2.scan(mask2, None, false)?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReverted); + assert!(!&txs[0].confirmed); + assert!(&txs[0].reverted_after.is_some()); stopper2.store(false, Ordering::Relaxed); Ok(( - chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, + chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, api1, api2, )) } fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i) = revert(test_dir)?; + let (chain, stopper, sent, bh, tx, wallet1, mask1_i, _wallet2, mask2_i, _api1, api2) = + revert(test_dir)?; let mask1 = mask1_i.as_ref(); let mask2 = mask2_i.as_ref(); @@ -293,22 +267,19 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let bh = bh + 1; // Check funds have been confirmed again - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(tx.confirmed); + assert!(tx.reverted_after.is_none()); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -317,41 +288,37 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } fn revert_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (_, stopper, sent, bh, _, _, _, wallet2, mask2_i) = revert(test_dir)?; + let (_, stopper, sent, bh, _, _, _, _wallet2, mask2_i, _api1, api2) = revert(test_dir)?; let mask2 = mask2_i.as_ref(); - // Cancelling tx - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - // Sanity check - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); + // Sanity check + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; - // Cancel - api.cancel_tx(m, Some(tx.id), None)?; + // Cancel + api2.cancel_tx(mask2, Some(tx.id), None)?; - // Check updated summary info - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); + // Check updated summary info + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); - // Check updated tx log - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); - Ok(()) - })?; + // Check updated tx log + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index 6cf572e..c6ca437 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -48,7 +48,8 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -63,16 +64,8 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -84,78 +77,54 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( wallet1.clone(), - mask1, PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use( - wallet1.clone(), - PathBuf::from(test_dir), - mask1_i.clone(), - |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; - Ok(()) - }, - )?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index 9bdd740..d53f1c4 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -100,7 +100,8 @@ fn slatepack_exchange_test_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -111,7 +112,8 @@ fn slatepack_exchange_test_impl( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -126,28 +128,11 @@ fn slatepack_exchange_test_impl( let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -160,19 +145,9 @@ fn slatepack_exchange_test_impl( let (recipients_1, dec_key_1, sender_1) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - }, - )?; + let sec_key = api1.get_slatepack_secret_key(mask1, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); ( vec![rec_address.clone()], Some(sec_key), @@ -184,19 +159,9 @@ fn slatepack_exchange_test_impl( let (recipients_2, dec_key_2, sender_2) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - }, - )?; + let sec_key = api2.get_slatepack_secret_key(mask2, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); ( vec![rec_address.clone()], Some(sec_key), @@ -219,39 +184,31 @@ fn slatepack_exchange_test_impl( ), }; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1.clone(), - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1.clone(), + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; // Get some mining done { @@ -286,52 +243,27 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, mut slate) = - slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, mut slate) = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'wallet 2' account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -348,61 +280,43 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_2.clone(), - recipients_1.clone(), - )?; - Ok(()) - }, + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_2.clone(), + recipients_1.clone(), )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; - slatepack = res.0; - slate = res.1; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - output_slatepack( - &slate, - &receive_file, - use_armored, - use_bin, - sender_1.clone(), - match slatepack.sender.clone() { - Some(s) => vec![s.clone()], - None => vec![], - }, - )?; - Ok(()) + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; + slatepack = res.0; + slate = res.1; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender.clone() { + Some(s) => vec![s.clone()], + None => vec![], }, )?; wallet::controller::foreign_single_use( @@ -418,15 +332,7 @@ fn slatepack_exchange_test_impl( Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -443,47 +349,29 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1, - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1, + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; wallet::controller::foreign_single_use( wallet2.clone(), @@ -509,22 +397,13 @@ fn slatepack_exchange_test_impl( }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = res.1; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = res.1; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -550,7 +429,8 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -569,32 +449,24 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // create an encrypted slatepack (just encrypted for self) - let enc_addr = api.get_slatepack_address(m, 0)?; - let slatepack = api.create_slatepack_message(m, &slate, Some(0), vec![enc_addr])?; - println!("{}", slatepack); - let slatepack_raw = api.decode_slatepack_message(m, slatepack.clone(), vec![0])?; - println!("{}", slatepack_raw); - let decoded_slate = api.slate_from_slatepack_message(m, slatepack, vec![0])?; - println!("{}", decoded_slate); - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // create an encrypted slatepack (just encrypted for self) + let enc_addr = api1.get_slatepack_address(mask1, 0)?; + let slatepack = api1.create_slatepack_message(mask1, &slate, Some(0), vec![enc_addr])?; + println!("{}", slatepack); + let slatepack_raw = api1.decode_slatepack_message(mask1, slatepack.clone(), vec![0])?; + println!("{}", slatepack_raw); + let decoded_slate = api1.slate_from_slatepack_message(mask1, slatepack, vec![0])?; + println!("{}", decoded_slate); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -609,8 +481,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let stopper = wallet_proxy.running.clone(); let config_path = PathBuf::from(test_dir).join("grin-wallet.toml"); GlobalWalletConfig::for_chain(&core::global::ChainTypes::AutomatedTesting, &config_path) - .write_to_file(config_path.to_str().unwrap(), false, None, None) - .unwrap(); + .write_to_file(config_path.to_str().unwrap(), false, None, None)?; create_wallet_and_add!( client1, @@ -620,7 +491,8 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -632,7 +504,8 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -644,62 +517,57 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let reward = core::consensus::REWARD; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 6, false); - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use(wallet2.clone(), mask2, config_path.clone(), |api, m| { - slate = api.issue_invoice_tx( - m, - IssueInvoiceTxArgs { - amount: reward, - ..Default::default() - }, - )?; - Ok(()) - })?; - - wallet::controller::owner_single_use(wallet1.clone(), mask1, config_path, |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), + let slate = api2.issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, ..Default::default() - }; + }, + )?; - let mut wrong_net_args = args.clone(); - wrong_net_args.send_args = Some(InitTxSendArgs { - dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, wrong_net_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, wrong_net_args).is_err()); + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let mut invalid_args = args.clone(); - invalid_args.send_args = Some(InitTxSendArgs { - dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7" - .to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, invalid_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, invalid_args).is_err()); + let mut wrong_net_args = args.clone(); + wrong_net_args.send_args = Some(InitTxSendArgs { + dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, wrong_net_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, wrong_net_args) + .is_err()); - let mut valid_args = args; - valid_args.send_args = Some(InitTxSendArgs { - dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - api.process_invoice_tx(m, &slate, valid_args.clone())?; - api.init_send_tx(m, valid_args)?; - Ok(()) - })?; + let mut invalid_args = args.clone(); + invalid_args.send_args = Some(InitTxSendArgs { + dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, invalid_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, invalid_args) + .is_err()); + + let mut valid_args = args; + valid_args.send_args = Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + api1.process_invoice_tx(mask1, &slate, valid_args.clone())?; + api1.init_send_tx(mask1, valid_args)?; stopper.store(false, Ordering::Relaxed); proxy_thread.join().expect("wallet proxy thread panicked"); @@ -710,7 +578,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: fn slatepack_exchange_json() { let test_dir = "test_output/slatepack_exchange_json"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, false) { panic!("Libwallet Error: {}", e); } @@ -743,7 +611,7 @@ fn slatepack_exchange_armored() { fn slatepack_exchange_json_enc() { let test_dir = "test_output/slatepack_exchange_json_enc"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, true) { panic!("Libwallet Error: {}", e); } @@ -776,7 +644,7 @@ fn slatepack_exchange_armored_enc() { fn slatepack_api() { let test_dir = "test_output/slatepack_api"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_api_impl(test_dir) { panic!("Libwallet Error: {}", e); } diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 107c17d..6613095 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -33,6 +33,8 @@ use std::time::Duration; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; +use libwallet::InitTxSendArgs; /// Exercises the Transaction API fully with a test NodeClient operating /// directly on a chain instance @@ -51,7 +53,8 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); println!("Mask1: {:?}", mask1); @@ -63,7 +66,8 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); println!("Mask2: {:?}", mask2); @@ -81,459 +85,425 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> // mine a few blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); - // Check wallet 1 contents are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - assert_eq!(wallet1_info.amount_immature, cm * reward); - Ok(()) - }, - )?; + // Check wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + assert_eq!(wallet1_info.amount_immature, cm * reward); + } // assert wallet contents // and a single use api for a send command let amount = 60_000_000_000; let header_version = core::consensus::header_version(chain.head().unwrap().height).0; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // Do not allow to send 0 - let error = sender_api - .init_send_tx( - m, - InitTxArgs { - amount: 0, - ..Default::default() - }, - ) - .unwrap_err(); - assert_eq!(error, libwallet::Error::InvalidAmount); + { + // Do not allow to send 0 + let error = api1 + .init_send_tx( + mask1, + InitTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); - // Result amount can not be 0 when amount includes fee - let mut init_args = InitTxArgs { - amount_includes_fee: Some(true), - amount: 23_000_000, - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args.clone())?; - assert_eq!(init_args.amount, est.fee_fields.fee()); + // Result amount can not be 0 when amount includes fee + let mut init_args = InitTxArgs { + amount_includes_fee: Some(true), + amount: 23_000_000, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args.clone())?; + assert_eq!(init_args.amount, est.fee_fields.fee()); - init_args.estimate_only = None; - let error = sender_api.init_send_tx(m, init_args).unwrap_err(); - assert_eq!( - error, - libwallet::Error::GenericError( - "Transaction amount is too small to include fee".to_string() - ) - ); + init_args.estimate_only = None; + let error = api1.init_send_tx(mask1, init_args).unwrap_err(); + assert_eq!( + error, + libwallet::Error::GenericError( + "Transaction amount is too small to include fee".to_string() + ) + ); - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); - assert_eq!(slate_i.version_info.block_header_version, header_version); + assert_eq!(slate_i.state, SlateState::Standard1); + assert_eq!(slate_i.version_info.block_header_version, header_version); - wallet::controller::foreign_single_use( + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let mut zero_amount_slate = slate_i.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), + libwallet::Error::InvalidAmount + ); + Ok(()) + }, + )?; + + // Check we are creating a tx with the expected lock_height of 0. + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); + + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + assert_eq!(slate.state, SlateState::Standard2); + + // wallet2 already has this slate, so accepted versions fail on the duplicate check + for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { + let mut s = slate_i.clone(); + s.version_info.block_header_version = bhv; + let res = wallet::controller::foreign_single_use( wallet2.clone(), PathBuf::from(test_dir), mask2_i.clone(), - |api| { - let mut zero_amount_slate = slate_i.clone(); - zero_amount_slate.amount = 0; - assert_eq!( - api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), - libwallet::Error::InvalidAmount - ); - Ok(()) - }, - )?; - - // Check we are creating a tx with the expected lock_height of 0. - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); - - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - assert_eq!(slate.state, SlateState::Standard2); - - // wallet2 already has this slate, so accepted versions fail on the duplicate check - for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { - let mut s = slate_i.clone(); - s.version_info.block_header_version = bhv; - let res = wallet::controller::foreign_single_use( - wallet2.clone(), - PathBuf::from(test_dir), - mask2_i.clone(), - |api| api.receive_tx(&s, None, None).map(|_| ()), - ); - if bhv <= GRIN_BLOCK_HEADER_VERSION { - assert!(matches!( - res, - Err(libwallet::Error::TransactionAlreadyReceived(_)) - )); - } else { - assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); - } - } - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - assert_eq!(slate.state, SlateState::Standard3); - - // Check we have a single kernel and that it is a Plain kernel (no lock_height). - // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) - assert_eq!(slate.tx_or_err()?.kernels().len(), 1); - assert_eq!( - slate - .tx_or_err()? - .kernels() - .first() - .map(|k| k.features) - .unwrap(), - transaction::KernelFeatures::Plain { - fee: 26_000_000.into() - } + |api| api.receive_tx(&s, None, None).map(|_| ()), ); + if bhv <= GRIN_BLOCK_HEADER_VERSION { + assert!(matches!( + res, + Err(libwallet::Error::TransactionAlreadyReceived(_)) + )); + } else { + assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); + } + } + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + assert_eq!(slate.state, SlateState::Standard3); - Ok(()) - }, - )?; + // Check we have a single kernel and that it is a Plain kernel (no lock_height). + // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) + assert_eq!(slate.tx_or_err()?.kernels().len(), 1); + assert_eq!( + slate + .tx_or_err()? + .kernels() + .first() + .map(|k| k.features) + .unwrap(), + transaction::KernelFeatures::Plain { + fee: 26_000_000.into() + } + ); + } // Check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - cm as usize, - 2, - 1, - ); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); - println!("tx: {:?}", tx); - assert_eq!(Some(fee.try_into().unwrap()), tx.fee); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - cm as usize, + 2, + 1, + ); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); + println!("tx: {:?}", tx); + assert_eq!(Some(fee.try_into().unwrap()), tx.fee); + } // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(amount, tx.amount_credited); - assert_eq!(0, tx.amount_debited); - assert_eq!(None, tx.fee); - Ok(()) - }, - )?; + { + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(amount, tx.amount_credited); + assert_eq!(0, tx.amount_debited); + assert_eq!(None, tx.fee); + } // post transaction - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; - // Check wallet 1 contents are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Post Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - 1 - cm as usize, - 2, - 1, - ); - assert!(wallet1_refreshed); - // wallet 1 received fees, so amount should be the same - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - amount - fee - ); - assert_eq!(wallet1_info.amount_immature, cm * reward + fee); + // Check wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 Info Post Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - 1 - cm as usize, + 2, + 1, + ); + assert!(wallet1_refreshed); + // wallet 1 received fees, so amount should be the same + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward - amount - fee + ); + assert_eq!(wallet1_info.amount_immature, cm * reward + fee); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // refresh wallets and retrieve info/tests for each wallet after maturity - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!("Wallet 1 Info: {:?}", wallet1_info); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm - 1) * reward - ); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!("Wallet 1 Info: {:?}", wallet1_info); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm - 1) * reward + ); + } - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // Estimate fee and locked amount for a transaction - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 600_000_000_000); - // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) - assert_eq!(est.fee_fields.fee(), 25_000_000); + { + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args)?; + assert_eq!(est.amount, 600_000_000_000); + // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) + assert_eq!(est.fee_fields.fee(), 25_000_000); - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, //select smallest number - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 180_000_000_000); - // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) - assert_eq!(est.fee_fields.fee(), 24_000_000); - - Ok(()) - }, - )?; + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, //select smallest number + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args)?; + assert_eq!(est.amount, 180_000_000_000); + // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) + assert_eq!(est.fee_fields.fee(), 24_000_000); + } // Send another transaction, but don't post to chain immediately and use // the stored transaction instead - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let (refreshed, _wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - let (_, txs) = sender_api.retrieve_txs(m, true, None, None, None)?; - // find the transaction - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - let stored_tx_slate = sender_api - .get_stored_tx(m, None, Some(&tx.tx_slate_id.unwrap()))? - .unwrap(); - sender_api.post_tx(m, &stored_tx_slate, false)?; - let (_, wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - // should be mined now - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount * 3 - ); - Ok(()) - }, - )?; + let (refreshed, _wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + // find the transaction + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + let stored_tx_slate = api1 + .get_stored_tx(mask1, None, Some(&tx.tx_slate_id.unwrap()))? + .unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // should be mined now + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount * 3 + ); + } // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // check wallet2 has stored transaction - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // try to send a transaction with amount inclusive of fees, but amount too // small to cover fees. Should fail. - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: 1, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = sender_api.init_send_tx(m, args); - assert!(res.is_err()); - Ok(()) - }, - )?; + { + let args = InitTxArgs { + src_acct_name: None, + amount: 1, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = api1.init_send_tx(mask1, args); + assert!(res.is_err()); + } + + // Multiple send attempts, make sure same outputs not locked. + // Fail sending without starting Tor + api2.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + let mut handles = vec![]; + + let api2_1 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_1.init_send_tx(None, args) + })); + let api2_2 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_2.init_send_tx(None, args) + })); + let results: Vec<_> = handles + .into_iter() + .map(|handle| handle.join().unwrap()) + .collect(); + assert_eq!(results.iter().filter(|r| { r.is_ok() }).count(), 1); + let err_res = results.iter().find(|r| r.is_err()).unwrap(); + assert!(matches!( + err_res.as_ref().err().unwrap(), + libwallet::Error::NotEnoughFunds { .. } + )); // try to build a transaction with amount inclusive of fees. Confirm that tx // amount + fee is equal to the originally specified amount let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); - let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); - assert_eq!(amount, total_spend); - Ok(()) - }, - )?; + { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + assert_eq!(slate_i.state, SlateState::Standard1); + let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); + assert_eq!(amount, total_spend); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -557,7 +527,8 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -568,7 +539,8 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -586,159 +558,121 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); let amount = 30_000_000_000; - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + let slate_i = api1.init_send_tx(mask1, args)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; // Check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - assert!(refreshed); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let mut locked_count = 0; - let mut unconfirmed_count = 0; - // get the tx entry, check outputs are as expected - let (_, output_mappings) = - api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in output_mappings.clone() { - if m.output.status == OutputStatus::Locked { - locked_count = locked_count + 1; - } - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; - } + { + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let mut locked_count = 0; + let mut unconfirmed_count = 0; + // get the tx entry, check outputs are as expected + let (_, output_mappings) = + api1.retrieve_outputs(mask1, true, false, Some(tx.unwrap().id))?; + for m in output_mappings.clone() { + if m.output.status == OutputStatus::Locked { + locked_count = locked_count + 1; } - assert_eq!(output_mappings.len(), 3); - assert_eq!(locked_count, 2); - assert_eq!(unconfirmed_count, 1); - - Ok(()) - }, - )?; + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; + } + } + assert_eq!(output_mappings.len(), 3); + assert_eq!(locked_count, 2); + assert_eq!(unconfirmed_count, 1); + } // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let mut unconfirmed_count = 0; - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - // get the tx entry, check outputs are as expected - let (_, outputs) = api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in outputs.clone() { - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; - } + { + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let mut unconfirmed_count = 0; + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + // get the tx entry, check outputs are as expected + let (_, outputs) = api2.retrieve_outputs(mask2, true, false, Some(tx.unwrap().id))?; + for m in outputs.clone() { + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; } - assert_eq!(outputs.len(), 1); - assert_eq!(unconfirmed_count, 1); - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.amount_awaiting_finalization, amount); - Ok(()) - }, - )?; + } + assert_eq!(outputs.len(), 1); + assert_eq!(unconfirmed_count, 1); + let (refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.amount_awaiting_finalization, amount); + } // wallet 1 is bold and doesn't ever post the transaction // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Wallet 1 decides to roll back instead - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // can't roll back coinbase - let res = api.cancel_tx(m, Some(1), None); - assert!(res.is_err()); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - // check all eligible inputs should be now be spendable - println!("cm: {}", cm); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); - - Ok(()) - }, - )?; - + { + // can't roll back coinbase + let res = api1.cancel_tx(mask1, Some(1), None); + assert!(res.is_err()); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api1.cancel_tx(mask1, Some(tx.id), None)?; + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + // check all eligible inputs should be now be spendable + println!("cm: {}", cm); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + // can't roll back again + let res = api1.cancel_tx(mask1, Some(tx.id), None); + assert!(res.is_err()); + } // Wallet 2 rolls back - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - // check all eligible inputs should be now be spendable - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.total, 0,); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); - - Ok(()) - }, - )?; + { + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api2.cancel_tx(mask2, Some(tx.id), None)?; + let (refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + // check all eligible inputs should be now be spendable + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.total, 0,); + // can't roll back again + let res = api2.cancel_tx(mask2, Some(tx.id), None); + assert!(res.is_err()); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -760,7 +694,8 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); println!("Mask1: {:?}", mask1); @@ -783,50 +718,35 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { let min_confirmations = 1; // Check wallet 1 content are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = - api.retrieve_summary_info(m, true, min_confirmations)?; - println!( - "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - assert_eq!(wallet1_info.amount_immature, cm * reward); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = + api1.retrieve_summary_info(mask1, true, min_confirmations)?; + println!( + "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + assert_eq!(wallet1_info.amount_immature, cm * reward); + } // test selecting max amount - let result = wallet::controller::owner_single_use( - wallet1.clone(), + let result = api1.init_send_tx( mask1, - PathBuf::from(test_dir), - |api, m| { - api.init_send_tx( - m, - InitTxArgs { - amount: (reward * outputs_num as u64) - (cm * reward), - amount_includes_fee: Some(true), - minimum_confirmations: 0, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - refresh_outputs_from_node: true, - ..InitTxArgs::default() - }, - )?; - Ok(()) + InitTxArgs { + amount: (reward * outputs_num as u64) - (cm * reward), + amount_includes_fee: Some(true), + minimum_confirmations: 0, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + refresh_outputs_from_node: true, + ..InitTxArgs::default() }, ); - println!("{:?}", result); let max_tx_weight = global::max_tx_weight(); @@ -844,19 +764,11 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { Ok(_) => {} Err(e) => match e { libwallet::Error::BigAmountError(a, fee, num_inputs) => { - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, e_a, e_fee, e_num_inputs) = - api.estimate_max_sendable(m, true, min_confirmations)?; - assert_eq!(e_a, a - fee); - assert_eq!(e_fee, fee); - assert_eq!(e_num_inputs, num_inputs); - Ok(()) - }, - )?; + let (_, e_a, e_fee, e_num_inputs) = + api1.estimate_max_sendable(mask1, true, min_confirmations)?; + assert_eq!(e_a, a - fee); + assert_eq!(e_fee, fee); + assert_eq!(e_num_inputs, num_inputs); } _ => {} }, diff --git a/controller/tests/ttl_cutoff.rs b/controller/tests/ttl_cutoff.rs index faa3990..4c9bd12 100644 --- a/controller/tests/ttl_cutoff.rs +++ b/controller/tests/ttl_cutoff.rs @@ -20,8 +20,7 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, Slate, TxLogEntryType}; -use std::path::PathBuf; +use libwallet::{InitTxArgs, TxLogEntryType}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -45,7 +44,8 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -58,7 +58,8 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -78,126 +79,76 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let amount = 60_000_000_000; - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); // Now mine past the block, and check again. Transaction should be gone. let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); // Should also be gone in wallet 2, and output gone - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); - let outputs = sender_api.retrieve_outputs(m, false, true, None)?.1; - assert_eq!(outputs.len(), 0); + let (_, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); + let outputs = api2.retrieve_outputs(mask2, false, true, None)?.1; + assert_eq!(outputs.len(), 0); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); // try again, except try and send off the transaction for completion beyond the expiry - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - sender_api.tx_lock_outputs(m, &slate_i)?; - slate = slate_i; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate_i)?; + slate = slate_i; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(14)); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(14)); // Mine past the ttl block and try to send let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); // Wallet 2 will need to have updated past the TTL - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - Ok(()) - }, - )?; + let (_, _) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; // And when wallet 1 sends, should be rejected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |_sender_api, _m| { - let res = client1.send_tx_slate_direct("wallet2", &slate); - println!("Send after TTL result is: {:?}", res); - assert!(res.is_err()); - Ok(()) - }, - )?; + let res = client1.send_tx_slate_direct("wallet2", &slate); + println!("Send after TTL result is: {:?}", res); + assert!(res.is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index c7fa9c8..cc63c15 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -23,210 +23,183 @@ use grin_core as core; use grin_keychain as keychain; use grin_util as util; use libwallet::{RetrieveTxQueryArgs, RetrieveTxQuerySortField}; -use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::sync::{atomic::Ordering, Arc}; +use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; use util::secp::key::SecretKey; -use util::Mutex; use self::keychain::ExtKeychain; -use self::libwallet::WalletInst; use impls::DefaultLCProvider; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; fn test_wallet_tx_filtering( - wallet: Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, - >, mask: Option<&SecretKey>, - test_dir: &'static str, + api: Owner, LocalWalletClient, ExtKeychain>, ) -> Result<(), libwallet::Error> { - wallet::controller::owner_single_use( - wallet.clone(), - mask, - PathBuf::from(test_dir), - |api, _m| { - let query = |args| { - api.retrieve_txs(mask, true, None, None, Some(args)) - .map(|(_, txs)| txs) - }; - let txs = query(RetrieveTxQueryArgs::default())?; - assert!(!txs.is_empty()); - let before_first_tx = - txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); - let mut tx_query_args = RetrieveTxQueryArgs::default(); + let query = |args| { + api.retrieve_txs(mask, true, None, None, Some(args)) + .map(|(_, txs)| txs) + }; + let txs = query(RetrieveTxQueryArgs::default())?; + assert!(!txs.is_empty()); + let before_first_tx = + txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); + let mut tx_query_args = RetrieveTxQueryArgs::default(); - // Max creation time before all test transactions - tx_query_args.max_creation_timestamp = Some(before_first_tx); - assert!(query(tx_query_args.clone())?.is_empty()); + // Max creation time before all test transactions + tx_query_args.max_creation_timestamp = Some(before_first_tx); + assert!(query(tx_query_args.clone())?.is_empty()); - // Min confirmation time should not affect creation time - tx_query_args.max_creation_timestamp = None; - tx_query_args.min_confirmed_timestamp = Some(before_first_tx); - assert_eq!(query(tx_query_args)?.len(), txs.len()); + // Min confirmation time should not affect creation time + tx_query_args.max_creation_timestamp = None; + tx_query_args.min_confirmed_timestamp = Some(before_first_tx); + assert_eq!(query(tx_query_args)?.len(), txs.len()); - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); - // Min ID - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 33); + // Min ID + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 33); - // Max ID - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(20); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 20); + // Max ID + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(20); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 20); - // Exclude 1 cancelled - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 28); + // Exclude 1 canceled + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 28); - // Exclude 1 cancelled, show confirmed only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 14); + // Exclude 1 canceled, show confirmed only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 14); - // show outstanding only (including cancelled) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // show outstanding only (including canceled) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // outstanding only and confirmed only should give empty set - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // outstanding only and confirmed only should give empty set + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include sent only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_sent_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // include sent only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_sent_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // include received only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_received_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include received only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_received_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include reverted only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_reverted_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include reverted only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_reverted_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include coinbase only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_coinbase_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // include coinbase only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_coinbase_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // Amounts - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 27); + // Amounts + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 27); - // amount, should see as above with coinbases excluded - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - tx_query_args.max_amount = Some(60_000_000_000 - 1); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 8); + // amount, should see as above with coinbases excluded + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + tx_query_args.max_amount = Some(60_000_000_000 - 1); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 8); - // Amount - should only see coinbase (incoming) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // Amount - should only see coinbase (incoming) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // sort order - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; + // sort order + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; - assert_eq!(tx_results[0].id, 33); - assert_eq!(tx_results[tx_results.len() - 1].id, 0); + assert_eq!(tx_results[0].id, 33); + assert_eq!(tx_results[tx_results.len() - 1].id, 0); - // change sort field to amount desc, should have coinbases first - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].amount_credited, 60_000_000_000); - - /*for entry in tx_results.iter() { - println!("{:?}", entry); - }*/ - - Ok(()) - }, - )?; + // change sort field to amount desc, should have coinbases first + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].amount_credited, 60_000_000_000); Ok(()) } @@ -248,7 +221,8 @@ fn build_chain_for_tx_filtering( "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); debug!("Mask1: {:?}", mask1); @@ -260,7 +234,8 @@ fn build_chain_for_tx_filtering( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); debug!("Mask2: {:?}", mask2); @@ -274,25 +249,8 @@ fn build_chain_for_tx_filtering( // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -304,22 +262,14 @@ fn build_chain_for_tx_filtering( let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } if !wallet_1_has_funds { let _ = @@ -331,62 +281,44 @@ fn build_chain_for_tx_filtering( let num_txs = 1; for _ in 0..num_txs { let amount: u64 = i as u64 * 1_000_000; - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; - } - } - - // Cancel a tx for filtering testing - let amount: u64 = 1_000_000; - let mut slate = Slate::blank(1, false); - debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { src_acct_name: None, - amount: amount, + amount, minimum_confirmations: 1, max_outputs: 500, num_change_outputs: 1, selection_strategy_is_use_all: false, ..Default::default() }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - sender_api.cancel_tx(m, Some(33), None)?; - Ok(()) - }, - )?; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; + } + } + + // Cancel a tx for filtering testing + let amount: u64 = 1_000_000; + debug!("Creating TX for {}", amount); + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.cancel_tx(mask1, Some(33), None)?; // Perform actual testing - test_wallet_tx_filtering(wallet1, mask1, test_dir)?; + test_wallet_tx_filtering(mask1, api1)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index 2beebab..8e33355 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -46,7 +46,8 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -69,28 +71,11 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err }); // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { diff --git a/grin b/grin index d5f3235..1425f60 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit d5f32350ab548736c17c1db7ff51457917fe4e96 +Subproject commit 1425f603295ba166eccd9e4e0af0226742f90844 diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index 1394dd7..63f56c0 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -124,7 +124,7 @@ impl TorSlateSender { let res: String = self.post(url, req).map_err(|e| { let mut report = format!("Performing version check (is recipient listening?): {}", e); let err_string = format!("{}", e); - if err_string.contains("404") { + if !self.config.use_integrated.unwrap_or(false) && err_string.contains("404") { // Report that the other version of the wallet is out of date report = "Other wallet is incompatible and requires an upgrade. \ Please urge the other wallet owner to upgrade and try the transaction again." diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index 2540dae..46e6690 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -366,7 +366,7 @@ impl From for OnionError { } #[cfg(test)] -pub mod tests { +mod tests { use super::*; use crate::mwixnet::onion::crypto::secp::random_secret; use crate::mwixnet::onion::{new_hop, Hop}; diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index a4d8308..f54987c 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -21,9 +21,9 @@ extern crate log; extern crate grin_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; -use std::path::PathBuf; use clap::App; +use std::sync::mpsc; use std::thread; use std::time::Duration; @@ -32,9 +32,23 @@ use grin_wallet_impls::DefaultLCProvider; mod common; use common::{clean_output_dir, execute_command, initial_setup_wallet, instantiate_wallet, setup}; +use grin_wallet_api::Owner; +use grin_wallet_libwallet::{OutputStatus, TxLogEntryType}; /// command line tests fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller::Error> { + let (logs_tx, logs_rx) = mpsc::sync_channel(100); + let panic_hook = std::panic::take_hook(); + grin_util::init_logger( + Some(grin_util::logger::LoggingConfig { + log_to_file: false, + stdout_log_level: log::Level::Error, + tui_running: Some(true), + ..Default::default() + }), + Some(logs_tx), + ); + std::panic::set_hook(panic_hook); setup(test_dir); // Create a new proxy to simulate server and wallet responses let mut wallet_proxy: WalletProxy< @@ -158,15 +172,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let (wallet1, mask1_i) = instantiate_wallet(wallet_config1, client1.clone(), "password1", "default")?; let mask1 = (&mask1_i).as_ref(); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - Ok(()) - }, - )?; + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); + + api1.set_active_account(mask1, "mining")?; let mut bh = 10u64; let _ = @@ -236,23 +244,16 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); // Check our transaction log, should have 10 entries - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - for t in txs { - assert!(t.kernel_excess.is_some()); - } - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); + for t in txs { + assert!(t.kernel_excess.is_some()); + } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); bh += 10; @@ -273,33 +274,17 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask2 = (&mask2_i).as_ref(); + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "account_1")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "account_1")?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); // Send to wallet 2 with --amount_includes_fee - let mut old_balance = 0; - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - old_balance = wallet1_info.amount_currently_spendable; - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; let arg_vec = vec![ "grin-wallet", "-p", @@ -349,22 +334,14 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check the new balance of wallet 1 reduced by EXACTLY the tx amount (instead of amount + fee) // This confirms that the TX amount was correctly computed to allow for the fee - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then - let amt_mined = 10 * 60_000_000_000; - assert_eq!( - wallet1_info.amount_currently_spendable + 10_000_000_000, - old_balance + amt_mined - ); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then + let amt_mined = 10 * 60_000_000_000; + assert_eq!( + wallet1_info.amount_currently_spendable + 10_000_000_000, + old_balance + amt_mined + ); // Send encrypted from wallet 1 to wallet 2 // output wallet 2's address for test creation purposes, @@ -435,19 +412,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); // Send to self let arg_vec = vec![ @@ -508,19 +478,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize + 1); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize + 1); // Another file exchange, don't send, but unlock with repair command let arg_vec = vec![ @@ -649,24 +612,15 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; // get tx output via -tx parameter - let mut tx_id = "".to_string(); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "default")?; - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let some_tx_id = txs[0].tx_slate_id.clone(); - assert!(some_tx_id.is_some()); - tx_id = some_tx_id.unwrap().to_string().clone(); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "default")?; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let some_tx_id = txs[0].tx_slate_id.clone(); + assert!(some_tx_id.is_some()); + let tx_id = some_tx_id.unwrap().to_string().clone(); let arg_vec = vec!["grin-wallet", "-p", "password2", "txs", "-t", &tx_id[..]]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; - // bit of mining + // a bit of mining let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); // Test wallet sweep @@ -717,21 +671,77 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check wallet 1 is now empty, except for immature coinbase outputs from recent mining), // and recently matured coinbase outputs, which were not mature at time of spending. // This confirms that the TX amount was correctly computed to allow for the fee - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 10)?; - // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs - // which matured in the last batch of mining. Check that the new spendable balance is - // exactly equal to those matured coins. - let amt_mined = 10 * 60_000_000_000; - assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 10)?; + // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs + // which matured in the last batch of mining. Check that the new spendable balance is + // exactly equal to those matured coins. + let amt_mined = 10 * 60_000_000_000; + assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); + + // Failed send, with --late-lock, make sure outputs not locked (amount not changed). + api2.set_active_account(mask2, "account_1")?; + let (_, txs_before) = api2.retrieve_txs(mask2, false, None, None, None)?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; + let mut arg_vec = vec![ + "grin-wallet", + "-p", + "password2", + "-a", + "account_1", + "send", + "-d", + "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "1", + "--late-lock", + ]; + let args = app.clone().get_matches_from(arg_vec.clone()); + let mut config = initial_setup_wallet(test_dir, "wallet2"); + config.members.tor = Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }); + let send = |args: &clap::ArgMatches| -> Result<(), grin_wallet_controller::Error> { + logs_rx.try_iter().for_each(drop); + grin_wallet::cmd::wallet_args::wallet_command( + args, + config.clone(), + client2.clone(), + false, + |_| {}, + )?; + assert!(logs_rx.try_iter().any(|entry| { + entry.log.contains("Error sending slate sync:") && entry.log.contains("AddrParseError") + })); + Ok(()) + }; + send(&args)?; + api2.set_active_account(mask2, "account_1")?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_before.len(), txs_after.len()); + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(old_balance, wallet1_info.amount_currently_spendable); + + // The same failure without late locking leaves one transaction and locked outputs + arg_vec.pop(); + let args = app.clone().get_matches_from(arg_vec); + send(&args)?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_after.len(), txs_before.len() + 1); + let tx = txs_after + .iter() + .find(|tx| !txs_before.iter().any(|before| before.id == tx.id)) + .unwrap(); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert!(tx.tx_slate_id.is_some()); + let (_, outputs) = api2.retrieve_outputs(mask2, false, false, Some(tx.id))?; + assert!(outputs + .iter() + .any(|output| output.output.status == OutputStatus::Locked)); + let (_, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet_info.amount_currently_spendable < old_balance); // let logging finish thread::sleep(Duration::from_millis(200)); diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index 997bdb3..bf6711e 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -19,7 +19,7 @@ extern crate log; extern crate grin_wallet; -use grin_wallet_api::{ECDHPubkey, JsonId}; +use grin_wallet_api::{ECDHPubkey, JsonId, Owner}; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::App; @@ -64,7 +64,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { >, >, > = Arc::new(Mutex::new(WalletProxy::new(test_dir))); - let (chain, wallet2, mask2_i) = { + let (chain, wallet2, mask2_i, config2) = { let mut wallet_proxy = wallet_proxy_a.lock(); let chain = wallet_proxy.chain.clone(); @@ -118,7 +118,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { ) .unwrap(); }); - (chain, wallet2, mask2_i) + (chain, wallet2, mask2_i, config2) }; // give a bit for wallet to init and populate proxy with wallet via callback in thread above thread::sleep(Duration::from_millis(500)); @@ -402,27 +402,20 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let mut slate: Slate = res.unwrap().into(); // give this slate over to wallet 2 manually - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let res = api.process_invoice_tx(m, &slate, args); - assert!(res.is_ok()); - slate = res.unwrap(); - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let res = api2.process_invoice_tx(mask2, &slate, args); + assert!(res.is_ok()); + slate = res?; + api2.tx_lock_outputs(mask2, &slate)?; //16) Finalize the invoice tx (to foreign api) // (Tests that foreign API on same port also has its stored mask updated) From 2d87b8c894bc65d4a10265b6d3271d42e2194e37 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Thu, 17 Sep 2026 22:31:13 +0300 Subject: [PATCH 11/39] Accounts balances (#815) Co-authored-by: wiesche --- api/src/owner.rs | 66 ++++++++++++--------- api/src/owner_rpc.rs | 69 +++++++++++++++++++++- controller/src/command.rs | 76 ++++++++++++++++-------- controller/src/display.rs | 8 +++ controller/tests/accounts.rs | 84 ++++++++++++++++++++++---- controller/tests/file.rs | 4 +- controller/tests/invoice.rs | 2 +- controller/tests/late_lock.rs | 4 +- controller/tests/mwixnet.rs | 4 +- controller/tests/repost.rs | 12 ++-- controller/tests/self_send.rs | 4 +- controller/tests/slatepack.rs | 4 +- controller/tests/updater_thread.rs | 2 +- libwallet/src/api_impl/owner.rs | 29 ++++++--- libwallet/src/backend.rs | 95 ++++++++++++++++++++++-------- libwallet/src/internal/keys.rs | 6 +- libwallet/src/internal/updater.rs | 63 +++++++++++++++----- libwallet/src/types.rs | 8 ++- src/bin/grin-wallet.yml | 14 ++++- src/cli/cli.rs | 11 ++-- src/cmd/wallet_args.rs | 37 +++++++++--- tests/cmd_line_basic.rs | 66 ++++++++++++++++++++- tests/common/mod.rs | 10 ++-- 23 files changed, 525 insertions(+), 153 deletions(-) diff --git a/api/src/owner.rs b/api/src/owner.rs index c180934..ffcdf0b 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -262,7 +262,7 @@ where } /// Returns a list of accounts stored in the wallet (i.e. mappings between - /// user-specified labels and BIP32 derivation paths. + /// user-specified labels and BIP32 derivation paths). /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// being used. @@ -296,11 +296,22 @@ where &self, keychain_mask: Option<&SecretKey>, ) -> Result, Error> { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + wallet_lock!(self.wallet_inst, w); // Test keychain mask, to keep API consistent let _ = w.keychain(keychain_mask)?; - owner::accounts(w) + owner::accounts(w, None) + } + + /// Returns accounts with balances from local wallet data, without refreshing from the node. + /// `minimum_confirmations` is the minimum confirmations required for spendable outputs. + pub fn accounts_info( + &self, + keychain_mask: Option<&SecretKey>, + minimum_confirmations: u64, + ) -> Result, Error> { + wallet_lock!(self.wallet_inst, w); + let _ = w.keychain(keychain_mask)?; + owner::accounts(w, Some(minimum_confirmations)) } /// Creates a new 'account', which is a mapping of a user-specified @@ -310,7 +321,7 @@ where /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// being used. - /// * `label` - A human readable label to which to map the new BIP32 Path + /// * `label` - A human-readable label to which to map the new BIP32 Path /// /// # Returns /// * Result Containing: @@ -319,10 +330,10 @@ where /// /// # Remarks /// - /// * Wallets should be initialised with the 'default' path mapped to `m/0/0` + /// * Wallets should be initialized with the 'default' path mapped to `m/0/0` /// * Each call to this function will increment the first element of the path /// so the first call will create an account at `m/1/0` and the second at - /// `m/2/0` etc. . . + /// `m/2/0` etc. /// * The account path is used throughout as the parent key for most key-derivation /// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for /// further details. @@ -354,12 +365,13 @@ where } /// Sets the wallet's currently active account. This sets the - /// BIP32 parent path used for most key-derivation operations. + /// BIP32 parent path used for most key-derivation operations + /// persistently between wallet restarts. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// being used. - /// * `label` - The human readable label for the account. Accounts can be retrieved via + /// * `label` - The human-readable label for the account. Accounts can be retrieved via /// the [`account`](struct.Owner.html#method.accounts) method /// /// # Returns @@ -370,7 +382,7 @@ where /// # Remarks /// /// * Wallet parent paths are 2 path elements long, e.g. `m/0/0` is the path - /// labelled 'default'. Keys derived from this parent path are 3 elements long, + /// labeled 'default'. Keys derived from this parent path are 3 elements long, /// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`, /// `m/0/0/1` etc... /// @@ -400,7 +412,7 @@ where let w = w_lock.lc_provider()?.wallet_inst()?; // Test keychain mask, to keep API consistent let _ = w.keychain(keychain_mask)?; - owner::set_active_account(w, label) + owner::set_active_account(w, keychain_mask, label) } /// Returns a list of outputs from the active account in the wallet. @@ -710,9 +722,9 @@ where /// is confirmed. This method also returns a function that will perform that locking, and it is /// up to the caller to decide the best time to call the lock function /// (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) method). - /// If the exchange method is intended to be synchronous (such as via a direct http call) + /// If the exchange method is intended to be synchronous (such as via a direct http call), /// then the lock call can wait until the response is confirmed. If it is asynchronous, (such - /// as via file transfer) the lock call should happen immediately (before the file is sent + /// as via file transfer), the lock call should happen immediately (before the file is sent /// to the recipient). /// /// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html), @@ -1221,10 +1233,10 @@ where /// Cancels a transaction. This entails: /// * Setting the transaction status to either `TxSentCancelled` or `TxReceivedCancelled` /// * Deleting all change outputs or recipient outputs associated with the transaction - /// * Setting the status of all assocatied inputs from `Locked` to `Spent` so they can be + /// * Setting the status of all associated inputs from `Locked` to `Spent` so they can be /// used in new transactions. /// - /// Transactions can be cancelled by transaction log id or slate id (call with either set to + /// Transactions can be canceled by transaction log id or slate id (call with either set to /// Some, not both) /// /// # Arguments @@ -1306,7 +1318,7 @@ where /// /// # Returns /// * Ok(Some([Slate](../grin_wallet_libwallet/slate/struct.Slate.html)) containing the stored - /// transaction, if successful. Note that this Slate will not contain all of the fields used by + /// transaction, if successful. Note that this Slate will not contain all the fields used by /// the original Slate that resulted in the transaction. /// * Ok(None) if the stored Transaction isn't found. /// * [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. @@ -1344,7 +1356,7 @@ where } /// Return the rewind hash of the wallet. - /// The rewind hash when shared, help third-party to retrieve informations (outputs, balance, ...) that belongs to this wallet. + /// The rewind hash when shared, help third-party to retrieve information (outputs, balance, ...) that belongs to this wallet. /// /// # Arguments /// @@ -1379,7 +1391,7 @@ where /// Scans the entire UTXO set from the node, identify which outputs belong to the given rewind hash view wallet. /// - /// This function can be used to retrieve outputs informations (outputs, balance, ...) from a rewind hash view wallet. + /// This function can be used to retrieve outputs information (outputs, balance, ...) from a rewind hash view wallet. /// /// This operation scans the entire chain, and is expected to be time intensive. It is imperative /// that no other processes should be trying to use the wallet at the same time this function is @@ -1429,7 +1441,7 @@ where /// update the wallet state to be consistent with what's currently in the UTXO set. /// /// This function can be used to repair wallet state, particularly by restoring outputs that may - /// be missing if the wallet owner has cancelled transactions locally that were then successfully + /// be missing if the wallet owner has canceled transactions locally that were then successfully /// posted to the chain. /// /// This operation scans the entire chain, and is expected to be time intensive. It is imperative @@ -1571,7 +1583,7 @@ where /// * None /// /// # Returns - /// * Ok with a String value representing the full path to the top level wallet dierctory + /// * Ok with a String value representing the full path to the top level wallet directory /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1605,7 +1617,7 @@ where /// description of the top level directory and default paths. /// /// The wallet must be closed and the updater stopped before changing this directory. - /// Open the wallet again afterwards to load its database from the new location. + /// Open the wallet again afterward to load its database from the new location. /// /// # Arguments /// @@ -1803,7 +1815,7 @@ where /// `Opens` a wallet, populating the internal keychain with the encrypted seed, and optionally /// returning a `keychain_mask` token to the caller to provide in all future calls. /// If using a mask, the seed will be stored in-memory XORed against the `keychain_mask`, and - /// will not be useable if the mask is not provided. + /// will not be usable if the mask is not provided. /// /// # Arguments /// @@ -1840,7 +1852,7 @@ where /// // Create configuration /// let result = api_owner.create_config(&ChainTypes::Mainnet, None, None, None); /// - /// // create new wallet wirh random seed + /// // create new wallet with random seed /// let pw = ZeroingString::from("my_password"); /// let _ = api_owner.create_wallet(None, None, 0, pw.clone()); /// @@ -1916,7 +1928,7 @@ where /// * `password`: The password used to encrypt the seed file. /// /// # Returns - /// * Ok(BIP-39 mneminc) if successful + /// * Ok(BIP-39 mnemonic) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -2409,14 +2421,14 @@ where } /// Decode an armored slatepack, returning a Slatepack object that can be - /// viewed, manipulated, output as json, etc. The resulting slatepack will be + /// viewed, manipulated, output as JSON, etc. The resulting slatepack will be /// decrypted by this wallet if possible /// /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using /// * `slatepack` - A string representing an armored slatepack - /// * `secret_indices` - Indices along this wallet's deriviation path with which to attempt + /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned /// Slatepack will remain encrypted. /// @@ -2601,7 +2613,7 @@ where // MWIXNET - /// Creates an mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html) + /// Creates a mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html) /// from a given output commitment under this wallet's control. /// /// # Arguments diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 92511b0..51d3168 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -48,7 +48,7 @@ use std::time::Duration; #[easy_jsonrpc_mw::rpc] pub trait OwnerRpc { /** - Networked version of [Owner::accounts](struct.Owner.html#method.accounts). + Networked version of [Owner::accounts](struct.Owner.html#method.accounts). Returns account mappings without balances. # Json rpc example @@ -72,7 +72,9 @@ pub trait OwnerRpc { "Ok": [ { "label": "default", - "path": "0200000000000000000000000000000000" + "path": "0200000000000000000000000000000000", + "info": null, + "current": true } ] }, @@ -84,6 +86,60 @@ pub trait OwnerRpc { */ fn accounts(&self, token: Token) -> Result, Error>; + /** + Networked version of [Owner::accounts_info](struct.Owner.html#method.accounts_info). Returns balances from locally stored state without refreshing from the node. + + # Json rpc example + + ``` + # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( + # r#" + { + "jsonrpc": "2.0", + "method": "accounts_info", + "params": { + "token": "d202964900000000d302964900000000d402964900000000d502964900000000", + "minimum_confirmations": 1 + }, + "id": 1 + } + # "# + # , + # r#" + { + "jsonrpc": "2.0", + "result": { + "Ok": [ + { + "label": "default", + "path": "0200000000000000000000000000000000", + "info": { + "amount_awaiting_confirmation": "0", + "amount_awaiting_finalization": "0", + "amount_currently_spendable": "60000000000", + "amount_immature": "180000000000", + "amount_locked": "0", + "amount_reverted": "0", + "last_confirmed_height": "4", + "minimum_confirmations": "1", + "total": "240000000000" + }, + "current": true + } + ] + }, + "id": 1 + } + # "# + # , 4, false, false, false, false); + ``` + */ + fn accounts_info( + &self, + token: Token, + minimum_confirmations: u64, + ) -> Result, Error>; + /** Networked version of [Owner::create_account_path](struct.Owner.html#method.create_account_path). @@ -119,6 +175,7 @@ pub trait OwnerRpc { /** Networked version of [Owner::set_active_account](struct.Owner.html#method.set_active_account). + The account selection is saved across wallet restarts # Json rpc example @@ -2089,6 +2146,14 @@ where Owner::accounts(self, (&token.keychain_mask).as_ref()) } + fn accounts_info( + &self, + token: Token, + minimum_confirmations: u64, + ) -> Result, Error> { + Owner::accounts_info(self, (&token.keychain_mask).as_ref(), minimum_confirmations) + } + fn create_account_path(&self, token: Token, label: &String) -> Result { Owner::create_account_path(self, (&token.keychain_mask).as_ref(), label) } diff --git a/controller/src/command.rs b/controller/src/command.rs index 93b02fc..b3e3146 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -31,6 +31,7 @@ use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; use crate::{controller, display}; +use grin_wallet_libwallet::wallet_lock; use qr_code::QrCode; use serde_json as json; use std::fs::File; @@ -52,7 +53,7 @@ fn show_recovery_phrase(phrase: ZeroingString) { /// Arguments common to all wallet commands #[derive(Clone)] pub struct GlobalArgs { - pub account: String, + pub account: Option, pub api_secret: Option, pub node_api_secret: Option, pub show_spent: bool, @@ -263,6 +264,8 @@ where /// Arguments for account command pub struct AccountArgs { pub create: Option, + pub minimum_confirmations: u64, + pub active: Option, } pub fn account( @@ -275,20 +278,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - if args.create.is_none() { - let res = { - let acct_mappings = owner_api.accounts(keychain_mask)?; - // give logging thread a moment to catch up - thread::sleep(Duration::from_millis(200)); - display::accounts(acct_mappings); - Ok(()) - }; - if let Err(e) = res { - error!("Error listing accounts: {}", e); - return Err(Error::LibWallet(e)); - } - } else { - let label = args.create.unwrap(); + if let Some(label) = args.create { let res = { owner_api.create_account_path(keychain_mask, &label)?; thread::sleep(Duration::from_millis(200)); @@ -300,6 +290,31 @@ where error!("Error creating account '{}': {}", label, e); return Err(Error::LibWallet(e)); } + } else if let Some(label) = args.active { + let res = { + owner_api.set_active_account(keychain_mask, &label)?; + thread::sleep(Duration::from_millis(200)); + info!("Account: '{}' set as active!", label); + Ok(()) + }; + if let Err(e) = res { + thread::sleep(Duration::from_millis(200)); + error!("Error setting account '{}' as active: {}", label, e); + return Err(Error::LibWallet(e)); + } + } else { + let res = { + let acct_mappings = + owner_api.accounts_info(keychain_mask, args.minimum_confirmations)?; + // give logging thread a moment to catch up + thread::sleep(Duration::from_millis(200)); + display::accounts(acct_mappings); + Ok(()) + }; + if let Err(e) = res { + error!("Error listing accounts: {}", e); + return Err(Error::LibWallet(e)); + } } Ok(()) } @@ -702,7 +717,6 @@ pub struct ReceiveArgs { pub fn receive( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: ReceiveArgs, mut tor_config: TorConfig, test_mode: bool, @@ -752,7 +766,7 @@ where owner_api.config_path(), km, |api| { - slate = api.receive_tx(&slate, Some(&g_args.account), None)?; + slate = api.receive_tx(&slate, None, None)?; Ok(()) }, )?; @@ -1174,7 +1188,6 @@ pub struct InfoArgs { pub fn info( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: InfoArgs, dark_scheme: bool, ) -> Result<(), Error> @@ -1186,8 +1199,9 @@ where let updater_running = owner_api.updater_running.load(Ordering::Relaxed); let (validated, wallet_info) = owner_api.retrieve_summary_info(keychain_mask, true, args.minimum_confirmations)?; + let account = account_label(owner_api)?; display::info( - &g_args.account, + &account, &wallet_info, validated || updater_running, dark_scheme, @@ -1210,8 +1224,9 @@ where let res = owner_api.node_height(keychain_mask)?; let (validated, outputs) = owner_api.retrieve_outputs(keychain_mask, g_args.show_spent, true, None)?; + let account = account_label(owner_api)?; display::outputs( - &g_args.account, + &account, res.height, validated || updater_running, outputs, @@ -1230,7 +1245,6 @@ pub struct TxsArgs { pub fn txs( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, - g_args: &GlobalArgs, args: TxsArgs, dark_scheme: bool, ) -> Result<(), Error> @@ -1249,8 +1263,9 @@ where let first_tx = args .count .map_or(0, |c| txs.len().saturating_sub(c as usize)); + let account = account_label(owner_api)?; display::txs( - &g_args.account, + &account, res.height, validated || updater_running, &txs[first_tx..], @@ -1276,7 +1291,7 @@ where if id.is_some() { let (_, outputs) = owner_api.retrieve_outputs(keychain_mask, true, false, id)?; display::outputs( - &g_args.account, + &account, res.height, validated || updater_running, outputs, @@ -1459,7 +1474,6 @@ where /// Payment Proof Address pub fn address( owner_api: &mut Owner, - g_args: &GlobalArgs, keychain_mask: Option<&SecretKey>, ) -> Result<(), Error> where @@ -1469,14 +1483,26 @@ where { // Just address at derivation index 0 for now let address = owner_api.get_slatepack_address(keychain_mask, 0)?; + let account = account_label(owner_api)?; println!(); - println!("Address for account - {}", g_args.account); + println!("Address for account - {}", account); println!("-------------------------------------"); println!("{}", address); println!(); Ok(()) } +/// Get current account label. +fn account_label(owner_api: &mut Owner) -> Result +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + wallet_lock!(owner_api.wallet_inst, w); + Ok(w.active_account().label) +} + /// Proof Export Args pub struct ProofExportArgs { pub output_file: String, diff --git a/controller/src/display.rs b/controller/src/display.rs index 54077fc..9ed991f 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -540,13 +540,20 @@ pub fn accounts(acct_mappings: Vec) { mMG->"Name", bMG->"Parent Output Key", bMG->"Slatepack Address (Index 0)", + bMG->"Spendable balance", ]); for m in acct_mappings { let slatepack_path = address::address_derivation_path(&m.path, 0).to_bip_32_string(); + let spendable = if let Some(info) = m.info { + amount_to_hr_string(info.amount_currently_spendable, true) + } else { + "-".to_string() + }; table.add_row(row![ bFC->m.label, bGC->m.path.to_bip_32_string(), bGC->slatepack_path, + bGC->spendable, ]); } table.set_format( @@ -562,6 +569,7 @@ pub fn accounts(acct_mappings: Vec) { let width = table.to_string().find('\n').unwrap_or(0); println!("{:^1$}", "BIP-32 Derivation Path", width); table.printstd(); + println!("Balances use local data and may be out of date."); println!(); } diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index fd19c28..f1dcbe1 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -81,7 +81,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // test default accounts exist { - let accounts = api1.accounts(mask1)?; + let accounts = api1.accounts_info(mask1, 2)?; assert_eq!(accounts[0].label, "default"); assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); } @@ -97,6 +97,53 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // trying to add same label again should fail let res = api1.create_account_path(mask1, "account1"); assert!(res.is_err()); + // Check missing flags and temporary account changes + for saved in [None, Some(true)] { + { + wallet_inst!(wallet1, w); + let mut account = w.get_acct_path("default".to_owned())?.unwrap(); + account.current = saved; + let mut batch = w.batch(mask1)?; + batch.save_acct_path(account)?; + batch.commit()?; + } + for active in ["default", "account1"] { + { + wallet_inst!(wallet1, w); + w.set_account_by_name(active)?; + } + for accounts in [api1.accounts(mask1)?, api1.accounts_info(mask1, 2)?] { + assert_eq!(accounts.len(), 4); + assert_eq!(accounts[0].label, active); + for account in accounts { + assert_eq!(account.current, Some(account.label == active)); + } + } + // Keep the saved selection unchanged + wallet_inst!(wallet1, w); + for account in w.acct_path_iter()? { + let expected = if account.label == "default" { + saved + } else { + None + }; + assert_eq!(account.current, expected); + } + } + } + // Restore the saved account on reopen + api1.set_active_account(mask1, "account1")?; + { + wallet_inst!(wallet1, w); + w.set_account_by_name("default")?; + assert_eq!(w.active_account().label, "default"); + } + api1.close_wallet(None)?; + api1.open_wallet(None, "".into(), false)?; + { + wallet_inst!(wallet1, w); + assert_eq!(w.active_account().label, "account1"); + } } // add account to wallet 2 @@ -108,20 +155,20 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Default wallet 2 to listen on that account { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("listener_account")?; + w.set_account_by_name("listener_account")?; } // Mine into two different accounts in the same wallet { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 7, false); { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; assert_eq!(w.parent_key_id(), ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); @@ -141,12 +188,28 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // now check second account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } { - let labels: Vec<_> = api1.accounts(mask1)?.into_iter().map(|a| a.label).collect(); + let labels: Vec<_> = api1 + .accounts_info(mask1, 2)? + .into_iter() + .map(|a| a.label) + .collect(); assert_eq!(labels, ["account1", "default", "account2", "account3"]); + assert!(api1.accounts(mask1)?.iter().all(|a| a.info.is_none())); + for confirmations in [0, 1, 2, 10] { + let accounts = api1.accounts_info(mask1, confirmations)?; + assert_eq!(accounts[0].info.as_ref().unwrap().last_confirmed_height, 0); + assert_eq!(accounts[2].info.as_ref().unwrap().last_confirmed_height, 12); + for account in accounts { + api1.set_active_account(mask1, &account.label)?; + let (_, summary) = api1.retrieve_summary_info(mask1, false, confirmations)?; + assert_eq!(account.info.unwrap(), summary); + } + api1.set_active_account(mask1, "account1")?; + } // check last confirmed height on this account is different from above (should be 0) let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; assert_eq!(wallet1_info.last_confirmed_height, 0); @@ -159,10 +222,11 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; assert_eq!(txs.len(), 7); } + // should be nothing in default account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; } { let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; @@ -180,7 +244,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Send a tx to another wallet { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } { let args = InitTxArgs { @@ -218,7 +282,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // other account should be untouched { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("account2")?; + w.set_account_by_name("account2")?; } { let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; @@ -241,7 +305,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("default")?; + w.set_account_by_name("default")?; } { let (_, wallet2_info) = api2.retrieve_summary_info(mask2, false, 1)?; diff --git a/controller/tests/file.rs b/controller/tests/file.rs index a4e1fc4..b768080 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -88,7 +88,7 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -130,7 +130,7 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), // Get some mining done { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let mut slate = PathToSlate((&send_file).into()).get_tx()?.0; diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 8b76998..4671db0 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -80,7 +80,7 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut _bh = 10u64; let _ = diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index 8783610..5624976 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -77,11 +77,11 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 5ae886b..04e920c 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -72,7 +72,7 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -121,7 +121,7 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Check total in 'listener' account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; assert!(wallet1_refreshed); diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 7f3a39b..2eccce9 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -86,7 +86,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -120,7 +120,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // wallet 1 receives file to different account, completes { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } wallet::controller::foreign_single_use( @@ -138,7 +138,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // wallet 1 receives file to different account, completes { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } // wallet 1 finalize @@ -164,7 +164,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; @@ -175,11 +175,11 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> // as above, but synchronously { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let amount = 60_000_000_000; diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index c6ca437..424d31a 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -70,7 +70,7 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -119,7 +119,7 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Check total in 'listener' account { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("listener")?; + w.set_account_by_name("listener")?; } let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; assert!(wallet1_refreshed); diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index d53f1c4..21023f4 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -137,7 +137,7 @@ fn slatepack_exchange_test_impl( // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let mut bh = 10u64; let _ = @@ -213,7 +213,7 @@ fn slatepack_exchange_test_impl( // Get some mining done { wallet_inst!(wallet2, w); - w.set_parent_key_id_by_name("account1")?; + w.set_account_by_name("account1")?; } let (mut slatepack, mut slate) = diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index 8e33355..cb339b0 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -80,7 +80,7 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err // Get some mining done { wallet_inst!(wallet1, w); - w.set_parent_key_id_by_name("mining")?; + w.set_account_by_name("mining")?; } let bh = 10u64; let _ = diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 58bfbd2..e6fb0d0 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -52,19 +52,30 @@ use std::sync::mpsc::Sender; use std::sync::Arc; /// List of accounts -pub fn accounts(w: &mut WalletBackend) -> Result, Error> +pub fn accounts( + w: &mut WalletBackend, + minimum_confirmations: Option, +) -> Result, Error> where C: NodeClient, K: Keychain, { - let mut accounts = keys::accounts(w)?; + let mut accounts: Vec = if let Some(mc) = minimum_confirmations { + updater::retrieve_accounts_info(w, mc)? + } else { + keys::accounts(w)? + }; + let active = w.parent_key_id(); + for account in accounts.iter_mut() { + account.current = Some(account.path == active); + } accounts.sort_by(|a, b| a.path.cmp(&b.path)); // Put active account on top. - accounts.sort_by_key(|k| k.path != w.parent_key_id()); + accounts.sort_by_key(|k| k.path != active); Ok(accounts) } -/// new account path +/// New account path pub fn create_account_path( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -77,13 +88,17 @@ where keys::new_acct_path(w, keychain_mask, label) } -/// set active account -pub fn set_active_account(w: &mut WalletBackend, label: &str) -> Result<(), Error> +/// Set active account +pub fn set_active_account( + w: &mut WalletBackend, + keychain_mask: Option<&SecretKey>, + label: &str, +) -> Result<(), Error> where C: NodeClient, K: Keychain, { - w.set_parent_key_id_by_name(label) + w.set_active_account(keychain_mask, label) } /// Hash of the wallet root public key diff --git a/libwallet/src/backend.rs b/libwallet/src/backend.rs index 1fdd310..97324c0 100644 --- a/libwallet/src/backend.rs +++ b/libwallet/src/backend.rs @@ -108,8 +108,8 @@ where pub keychain: Option, /// Check value for XORed keychain seed pub master_checksum: Box>, - /// Parent path to use by default for output operations - parent_key_id: Identifier, + /// BIP32 account path to use by default for output operations + active_account: AcctPathMapping, /// wallet to node client w2n_client: C, } @@ -138,30 +138,48 @@ where // Make sure default wallet derivation path always exists // as well as path (so it can be retrieved by batches to know where to store - // completed transactions, for reference + // completed transactions, for reference) let default_account = AcctPathMapping { - label: "default".to_owned(), + label: "default".to_string(), path: WalletBackend::::default_path(), + info: None, + current: Some(true), }; - { let mut batch = store.batch()?; - batch.put_ser( + let saved_default = batch.get_ser::( Some(ACCOUNT_PATH_MAPPING_PREFIX), default_account.label.as_bytes(), - &default_account, + None, )?; - batch.commit()?; + if saved_default.is_none() { + batch.put_ser( + Some(ACCOUNT_PATH_MAPPING_PREFIX), + default_account.label.as_bytes(), + &default_account, + )?; + batch.commit()?; + } } - let res = WalletBackend { + let mut res = WalletBackend { db: store, data_file_dir: data_file_dir.to_owned(), keychain: None, master_checksum: Box::new(None), - parent_key_id: WalletBackend::::default_path(), + active_account: default_account, w2n_client: n_client, }; + + // Set current active account + let active = res + .acct_path_iter()? + .filter(|a| a.current.unwrap_or(false)) + .collect::>(); + if let Some(a) = active.get(0) { + res.active_account = a.clone(); + } + Ok(res) } @@ -275,27 +293,55 @@ where /*}*/ } - /// Set parent key id by stored account name. - pub fn set_parent_key_id_by_name(&mut self, label: &str) -> Result<(), Error> { + /// Set current active account by stored account name. + pub fn set_active_account( + &mut self, + keychain_mask: Option<&SecretKey>, + label: &str, + ) -> Result<(), Error> { + let res = self.acct_path_iter()?.find(|l| l.label == label); + match res { + None => Err(Error::UnknownAccountLabel(label.to_string())), + Some(mut a) => { + let mut batch = self.batch(keychain_mask)?; + let current = batch + .acct_path_iter()? + .filter(|a| a.current.unwrap_or(false)) + .collect::>(); + for mut a in current { + a.current = None; + batch.save_acct_path(a.clone())?; + } + a.current = Some(true); + batch.save_acct_path(a.clone())?; + batch.commit()?; + + self.active_account = a; + Ok(()) + } + } + } + + /// Set account by stored account name. + pub fn set_account_by_name(&mut self, label: &str) -> Result<(), Error> { let label = label.to_owned(); let res = self.acct_path_iter()?.find(|l| l.label == label); if let Some(a) = res { - self.set_parent_key_id(a.path); + self.active_account = a; Ok(()) } else { Err(Error::UnknownAccountLabel(label)) } } - /// The BIP32 path of the parent path to use for all output-related - /// functions, essentially 'accounts' within a wallet. - pub fn set_parent_key_id(&mut self, id: Identifier) { - self.parent_key_id = id; + /// Get active account. + pub fn active_account(&self) -> AcctPathMapping { + self.active_account.clone() } /// Get the parent path. pub fn parent_key_id(&mut self) -> Identifier { - self.parent_key_id.clone() + self.active_account.path.clone() } /// Get output data by id. @@ -465,14 +511,14 @@ where /// Next child ID when we want to create a new output, based on current parent. pub fn next_child(&mut self, keychain_mask: Option<&SecretKey>) -> Result { - let parent_key_id = self.parent_key_id.clone(); + let parent_key_id = self.active_account.path.clone(); let mut deriv_idx = { let batch = self.db.batch()?; batch - .get_ser(Some(DERIV_PREFIX), &self.parent_key_id.to_bytes(), None)? + .get_ser(Some(DERIV_PREFIX), &parent_key_id.to_bytes(), None)? .unwrap_or_else(|| 0) }; - let mut return_path = self.parent_key_id.to_path(); + let mut return_path = parent_key_id.to_path(); return_path.depth += 1; return_path.path[return_path.depth as usize - 1] = ChildNumber::from(deriv_idx); deriv_idx += 1; @@ -484,8 +530,8 @@ where /// Last verified height of outputs directly descending from the current parent key. pub fn last_confirmed_height(&mut self) -> Result { - let parent_key_id = self.parent_key_id.clone(); - self.last_confirmed_height_for_parent(&parent_key_id) + let parent_key_id = self.active_account.clone(); + self.last_confirmed_height_for_parent(&parent_key_id.path) } /// Last verified height of outputs directly descending from the given parent key. @@ -693,7 +739,8 @@ where } /// Save an account label -> path mapping. - pub fn save_acct_path(&mut self, mapping: AcctPathMapping) -> Result<(), Error> { + pub fn save_acct_path(&mut self, mut mapping: AcctPathMapping) -> Result<(), Error> { + mapping.info = None; self.db.put_ser( Some(ACCOUNT_PATH_MAPPING_PREFIX), mapping.label.as_bytes(), diff --git a/libwallet/src/internal/keys.rs b/libwallet/src/internal/keys.rs index 21c937a..7b223bd 100644 --- a/libwallet/src/internal/keys.rs +++ b/libwallet/src/internal/keys.rs @@ -68,7 +68,7 @@ where K: Keychain, { let label = label.to_owned(); - if wallet.acct_path_iter()?.any(|l| l.label == label) { + if wallet.acct_path_iter()?.any(|a| a.label == label) { return Err(Error::AccountLabelAlreadyExists(label)); } @@ -93,6 +93,8 @@ where let save_path = AcctPathMapping { label, path: return_id.clone(), + info: None, + current: None, }; let mut batch = wallet.batch(keychain_mask)?; @@ -116,6 +118,8 @@ where let save_path = AcctPathMapping { label, path: path.clone(), + info: None, + current: None, }; let mut batch = wallet.batch(keychain_mask)?; diff --git a/libwallet/src/internal/updater.rs b/libwallet/src/internal/updater.rs index 47134e5..024559c 100644 --- a/libwallet/src/internal/updater.rs +++ b/libwallet/src/internal/updater.rs @@ -25,12 +25,12 @@ use crate::grin_core::global; use crate::grin_core::libtx::proof::ProofBuilder; use crate::grin_core::libtx::reward; use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util as util; use crate::grin_util::secp::key::SecretKey; use crate::grin_util::secp::pedersen; use crate::grin_util::static_secp_instance; use crate::internal::keys; use crate::types::{NodeClient, OutputData, OutputStatus, TxLogEntry, TxLogEntryType, WalletInfo}; +use crate::{grin_util as util, AcctPathMapping}; use crate::{ BlockFees, CbData, OutputCommitMapping, RetrieveTxQueryArgs, RetrieveTxQuerySortField, RetrieveTxQuerySortOrder, WalletBackend, @@ -793,22 +793,12 @@ where Ok(()) } -/// Retrieve summary info about the wallet -/// caller should refresh first if desired -pub fn retrieve_info( - wallet: &mut WalletBackend, - parent_key_id: &Identifier, +/// Return summary info about the wallet account from provided outputs. +fn account_outputs_info>( + outputs: impl IntoIterator, + current_height: u64, minimum_confirmations: u64, -) -> Result -where - C: NodeClient, - K: Keychain, -{ - let current_height = wallet.last_confirmed_height_for_parent(parent_key_id)?; - let outputs = wallet - .iter()? - .filter(|out| out.root_key_id == *parent_key_id); - +) -> Result { let mut unspent_total = 0; let mut immature_total = 0; let mut awaiting_finalization_total = 0; @@ -817,6 +807,7 @@ where let mut reverted_total = 0; for out in outputs { + let out = out.borrow(); match out.status { OutputStatus::Unspent => { if out.is_coinbase && out.lock_height > current_height { @@ -859,6 +850,46 @@ where }) } +/// Retrieve summary info about the wallet accounts +/// caller should refresh first if desired +pub fn retrieve_accounts_info( + wallet: &mut WalletBackend, + minimum_confirmations: u64, +) -> Result, Error> +where + C: NodeClient, + K: Keychain, +{ + let outputs: Vec = wallet.iter()?.collect(); + let mut accounts = keys::accounts(wallet)?; + for a in accounts.iter_mut() { + let os = outputs.iter().filter(|out| out.root_key_id == a.path); + let current_height = wallet.last_confirmed_height_for_parent(&a.path)?; + let info = account_outputs_info(os, current_height, minimum_confirmations)?; + a.info = Some(info); + } + Ok(accounts) +} + +/// Retrieve summary info about the wallet +/// caller should refresh first if desired +pub fn retrieve_info( + wallet: &mut WalletBackend, + parent_key_id: &Identifier, + minimum_confirmations: u64, +) -> Result +where + C: NodeClient, + K: Keychain, +{ + let outputs = wallet + .iter()? + .filter(|out| out.root_key_id == *parent_key_id); + let current_height = wallet.last_confirmed_height_for_parent(&parent_key_id)?; + let info = account_outputs_info(outputs, current_height, minimum_confirmations)?; + Ok(info) +} + /// Build a coinbase output and insert into wallet pub fn build_coinbase( wallet: &mut WalletBackend, diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index 0aec740..76d7189 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -768,10 +768,14 @@ impl ser::Readable for StoredProofInfo { /// Map of named accounts to BIP32 paths #[derive(Clone, Debug, Serialize, Deserialize)] pub struct AcctPathMapping { - /// label used by user + /// Label used by user. pub label: String, - /// Corresponding parent BIP32 derivation path + /// Corresponding parent BIP32 derivation path. pub path: Identifier, + /// Wallet information for this account, can be loaded after deserialization. + pub info: Option, + /// Flag to check if this is current active account. + pub current: Option, } impl ser::Writeable for AcctPathMapping { diff --git a/src/bin/grin-wallet.yml b/src/bin/grin-wallet.yml index 93a4342..2980a87 100644 --- a/src/bin/grin-wallet.yml +++ b/src/bin/grin-wallet.yml @@ -21,7 +21,6 @@ args: short: a long: account takes_value: true - default_value: default - top_level_dir: help: Top directory in which wallet files are stored (location of 'grin-wallet.toml') short: t @@ -41,13 +40,24 @@ subcommands: - cli: about: Start the wallet in interactive CLI mode (EXPERIMENTAL and UNDER DEVELOPMENT) - account: - about: List wallet accounts or create a new account + about: List accounts, create an account or select the active account args: - create: help: Create a new wallet account with provided name short: c long: create takes_value: true + - minimum_confirmations: + help: Minimum number of confirmations required for an output to be spendable + short: m + long: min_conf + default_value: "10" + takes_value: true + - active: + help: Save the active account, used whenever --account is not given + short: a + long: active + takes_value: true - rewind_hash: about: Return the hash of the wallet root public key. - scan_rewind_hash: diff --git a/src/cli/cli.rs b/src/cli/cli.rs index d410785..2df64e3 100644 --- a/src/cli/cli.rs +++ b/src/cli/cli.rs @@ -186,7 +186,7 @@ where keychain_mask = match args.subcommand() { ("open", Some(_)) => { let mut wallet_lock = owner_api.wallet_inst.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; let mask = match lc.open_wallet( None, wallet_args::prompt_password(&global_wallet_args.password)?, @@ -202,17 +202,20 @@ where None } }; - if let Some(account) = args.value_of("account") { + if let Some(account) = args + .value_of("account") + .or(global_wallet_args.account.as_deref()) + { if wallet_opened { let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + wallet_inst.set_account_by_name(account)?; } } mask } ("close", Some(_)) => { let mut wallet_lock = owner_api.wallet_inst.lock(); - let lc = wallet_lock.lc_provider().unwrap(); + let lc = wallet_lock.lc_provider()?; lc.close_wallet(None)?; None } diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 35cf7b6..55297b2 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -308,7 +308,11 @@ pub fn parse_global_args( config: &WalletConfig, args: &ArgMatches, ) -> Result { - let account = parse_required(args, "account")?; + let account = if args.subcommand_matches("account").is_some() { + None + } else { + parse_optional(args, "account")? + }; let mut show_spent = false; if args.is_present("show_spent") { show_spent = true; @@ -335,7 +339,7 @@ pub fn parse_global_args( }; Ok(command::GlobalArgs { - account: account.to_owned(), + account, show_spent, api_secret, node_api_secret, @@ -431,7 +435,26 @@ pub fn parse_account_args(account_args: &ArgMatches) -> Result None, Some(s) => Some(s.to_owned()), }; - Ok(command::AccountArgs { create }) + + let active = match account_args.value_of("active") { + None => None, + Some(s) => Some(s.to_owned()), + }; + + if create.is_some() && active.is_some() { + let msg = "create and active cannot both be present".to_string(); + return Err(ParseError::ArgumentError(msg)); + } + + // minimum_confirmations + let min_c = parse_required(account_args, "minimum_confirmations")?; + let min_c = parse_u64(min_c, "minimum_confirmations")?; + + Ok(command::AccountArgs { + create, + minimum_confirmations: min_c, + active, + }) } pub fn parse_send_args(args: &ArgMatches) -> Result { @@ -1143,7 +1166,7 @@ where )?; if let Some(account) = wallet_args.value_of("account") { let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + wallet_inst.set_account_by_name(account)?; } Ok(mask) } @@ -1252,7 +1275,7 @@ where } ("receive", Some(args)) => { let a = arg_parse!(parse_receive_args(&args)); - command::receive(owner_api, km, &global_wallet_args, a, tor_config, test_mode) + command::receive(owner_api, km, a, tor_config, test_mode) } ("unpack", Some(args)) => { let a = arg_parse!(parse_unpack_args(&args)); @@ -1288,7 +1311,6 @@ where command::info( owner_api, km, - global_wallet_args, a, wallet_config.dark_background_color_scheme.unwrap_or(true), ) @@ -1304,7 +1326,6 @@ where command::txs( owner_api, km, - &global_wallet_args, a, wallet_config.dark_background_color_scheme.unwrap_or(true), ) @@ -1329,7 +1350,7 @@ where let a = arg_parse!(parse_verify_proof_args(&args)); command::proof_verify(owner_api, km, a) } - ("address", Some(_)) => command::address(owner_api, &global_wallet_args, km), + ("address", Some(_)) => command::address(owner_api, km), ("scan", Some(args)) => { let a = arg_parse!(parse_check_args(&args)); command::scan(owner_api, km, a) diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index f54987c..632c362 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -21,6 +21,8 @@ extern crate log; extern crate grin_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; +use std::io::Write; +use std::process::{Command, Stdio}; use clap::App; use std::sync::mpsc; @@ -153,6 +155,36 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: ]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // Check account selection through the CLI loop + let mut cli = Command::new(env!("CARGO_BIN_EXE_grin-wallet")) + .args([ + "-t", + &format!("{}/wallet2", test_dir), + "-p", + "password2", + "-a", + "account_1", + "-r", + "http://127.0.0.1:1", + "cli", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + cli.stdin.take().unwrap().write_all( + b"open\naddress\nclose\n-a default open\naddress\naccount -a account_1\naddress\nexit\n", + ).unwrap(); + let output = cli.wait_with_output().unwrap(); + assert!(output.status.success()); + let output = String::from_utf8(output.stdout).unwrap(); + let accounts: Vec<_> = output + .lines() + .filter_map(|line| line.strip_prefix("Address for account - ")) + .collect(); + assert_eq!(accounts, ["account_1", "default", "account_1"]); + // let's see those accounts let arg_vec = vec!["grin-wallet", "-p", "password1", "account"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; @@ -213,7 +245,35 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "-i", &file_name, ]; - execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; + // Reuse startup args as in interactive mode + { + let start = app + .clone() + .get_matches_from(vec!["grin-wallet", "-a", "default", "cli"]); + let global_args = + grin_wallet::cmd::wallet_args::parse_global_args(&wallet_config2, &start).unwrap(); + let mut api = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); + for command in [ + vec!["grin-wallet", "account", "-a", "account_1"], + vec!["grin-wallet", "address"], + vec!["grin-wallet", "receive", "-i", &file_name], + ] { + let args = app.clone().get_matches_from(command); + grin_wallet::cmd::wallet_args::parse_and_execute( + &mut api, + mask2_i.clone(), + &wallet_config2, + config2.tor_config(), + &global_args, + &args, + true, + true, + )?; + } + let (_, txs) = api.retrieve_txs(mask2_i.as_ref(), false, None, None, None)?; + assert_eq!(txs.len(), 1); + api.set_active_account(mask2_i.as_ref(), "default")?; + } // shouldn't be allowed to receive twice assert!(execute_command(&app, test_dir, "wallet2", &client2, arg_vec).is_err()); @@ -527,6 +587,10 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + // set default account for wallet2 + let arg_vec = vec!["grin-wallet", "-p", "password2", "account", "-a", "default"]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // issue an invoice tx, wallet 2 let arg_vec = vec!["grin-wallet", "-p", "password2", "invoice", "65"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 85cbe74..2f4d5b5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -241,7 +241,7 @@ pub fn instantiate_wallet( grin_wallet_controller::Error, > { wallet_config.chain_type = None; - let mut wallet = Box::new(DefaultWalletImpl::::new(node_client).unwrap()) + let mut wallet = Box::new(DefaultWalletImpl::::new(node_client)?) as Box< dyn WalletInst< DefaultLCProvider, @@ -249,7 +249,7 @@ pub fn instantiate_wallet( ExtKeychain, >, >; - let lc = wallet.lc_provider().unwrap(); + let lc = wallet.lc_provider()?; // legacy hack to avoid the need for changes in existing grin-wallet.toml files // remove `wallet_data` from end of path as // new lifecycle provider assumes grin_wallet.toml is in root of data directory @@ -259,11 +259,9 @@ pub fn instantiate_wallet( wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); } let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); - let keychain_mask = lc - .open_wallet(None, ZeroingString::from(passphrase), true, false) - .unwrap(); + let keychain_mask = lc.open_wallet(None, ZeroingString::from(passphrase), true, false)?; let wallet_inst = lc.wallet_inst()?; - wallet_inst.set_parent_key_id_by_name(account)?; + wallet_inst.set_account_by_name(account)?; Ok((Arc::new(Mutex::new(wallet)), keychain_mask)) } From ec1e9910afe4c5852e0f0e614c88f4a20140f3d8 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:11:32 +0200 Subject: [PATCH 12/39] Show HTTP status when node requests fail (#820) --- impls/src/client_utils/client.rs | 62 +++++++++++++++++++++++++++++--- impls/src/node_clients/http.rs | 19 ++++------ 2 files changed, 64 insertions(+), 17 deletions(-) diff --git a/impls/src/client_utils/client.rs b/impls/src/client_utils/client.rs index 94b7b37..20e787f 100644 --- a/impls/src/client_utils/client.rs +++ b/impls/src/client_utils/client.rs @@ -225,7 +225,7 @@ impl Client { IN: Serialize, { let json = serde_json::to_string(input) - .map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?; + .map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?; self.build_request(url, Method::POST, api_secret, Some(json)) } @@ -235,7 +235,7 @@ impl Client { { let data = self.send_request(req)?; serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned())) + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e))) } async fn handle_request_async(&self, req: RequestBuilder) -> Result @@ -244,7 +244,7 @@ impl Client { { let data = self.send_request_async(req).await?; let ser = serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?; + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?; Ok(ser) } @@ -253,6 +253,10 @@ impl Client { .send() .await .map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?; + let status = resp.status(); + if status.is_client_error() || status.is_server_error() { + return Err(Error::ResponseError(format!("HTTP {}", status))); + } let text = resp .text() .await @@ -261,7 +265,7 @@ impl Client { } pub fn send_request(&self, req: RequestBuilder) -> Result { - // This client is currently used both outside and inside of a tokio runtime + // This client is currently used both outside and inside the tokio runtime // context. In the latter case we are not allowed to do a blocking call to // our global runtime, which unfortunately means we have to spawn a new thread if Handle::try_current().is_ok() { @@ -275,3 +279,53 @@ impl Client { } } } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + use tokio::net::TcpListener; + + #[tokio::test] + async fn http_status() { + let client = Client { + client: ClientBuilder::new() + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(), + }; + for (status, body, expected) in [ + ("200 OK", "{}", Ok(serde_json::json!({}))), + ( + "401 Unauthorized", + "Unauthorized", + Err(Error::ResponseError("HTTP 401 Unauthorized".into())), + ), + ] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut headers = BufReader::new(&mut stream).lines(); + while let Some(line) = headers.next_line().await.unwrap() { + if line.is_empty() { + break; + } + } + let response = format!( + "HTTP/1.1 {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + status, + body.len(), + body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + }); + assert_eq!( + client._get_async::(&url, None).await, + expected + ); + server.await.unwrap(); + } + } +} diff --git a/impls/src/node_clients/http.rs b/impls/src/node_clients/http.rs index 8b7ed0e..b28a30c 100644 --- a/impls/src/node_clients/http.rs +++ b/impls/src/node_clients/http.rs @@ -142,19 +142,12 @@ impl NodeClient for HTTPNodeClient { }, Err(e) => { // If node isn't available, allow offline functions - // unfortunately have to parse string due to error structure - let err_string = format!("{}", e); - return if err_string.contains("404") { - Some(NodeVersionInfo { - node_version: "1.0.0".into(), - block_header_version: 1, - verified: Some(false), - }) - } else { - error!("Unable to contact Node to get version info: {}, check your node is running", e); - warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly"); - None - }; + error!( + "Unable to contact Node to get version info: {}, check your node is running", + e + ); + warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly"); + return None; } }; self.node_version_info = Some(retval.clone()); From fe79256467917f23d982e5c20aec1388aef05b86 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 30 Sep 2026 18:38:16 +0300 Subject: [PATCH 13/39] Add linter to CI (#823) Co-authored-by: wiesche --- .github/workflows/ci.yaml | 13 +- .hooks/pre-commit | 8 + api/src/foreign.rs | 58 ++- api/src/foreign_rpc.rs | 34 +- api/src/owner.rs | 427 ++++++++----------- api/src/owner_rpc.rs | 166 +++---- api/src/types.rs | 24 +- api/tests/slate_versioning.rs | 1 - config/src/config.rs | 29 +- config/src/types.rs | 28 +- controller/src/command.rs | 59 ++- controller/src/controller.rs | 52 +-- controller/src/display.rs | 32 +- controller/tests/accounts.rs | 4 +- controller/tests/build_chain.rs | 4 +- controller/tests/build_output.rs | 2 +- controller/tests/check.rs | 36 +- controller/tests/common/mod.rs | 33 +- controller/tests/file.rs | 4 +- controller/tests/invoice.rs | 4 +- controller/tests/late_lock.rs | 4 +- controller/tests/mwixnet.rs | 8 +- controller/tests/no_change.rs | 4 +- controller/tests/payment_proofs.rs | 4 +- controller/tests/repost.rs | 4 +- controller/tests/revert.rs | 28 +- controller/tests/self_send.rs | 2 +- controller/tests/slatepack.rs | 24 +- controller/tests/transaction.rs | 23 +- controller/tests/ttl_cutoff.rs | 4 +- controller/tests/tx_list_filter.rs | 131 +++--- controller/tests/updater_thread.rs | 4 +- grin | 2 +- impls/src/adapters/slatepack.rs | 2 +- impls/src/adapters/tor.rs | 9 +- impls/src/client_utils/client.rs | 12 +- impls/src/client_utils/json_rpc.rs | 18 +- impls/src/lifecycle/default.rs | 26 +- impls/src/lifecycle/seed.rs | 20 +- impls/src/node_clients/http.rs | 11 +- impls/src/test_framework/mod.rs | 17 +- impls/src/test_framework/testclient.rs | 16 +- impls/src/tor/arti.rs | 18 +- impls/src/tor/bridge.rs | 95 ++--- impls/src/tor/config.rs | 8 +- impls/src/tor/process.rs | 10 +- impls/src/tor/proxy.rs | 29 +- libwallet/src/address.rs | 7 +- libwallet/src/api_impl/foreign.rs | 8 +- libwallet/src/api_impl/owner.rs | 119 +++--- libwallet/src/api_impl/owner_updater.rs | 17 +- libwallet/src/api_impl/types.rs | 20 +- libwallet/src/backend.rs | 33 +- libwallet/src/error.rs | 10 +- libwallet/src/internal/keys.rs | 4 +- libwallet/src/internal/scan.rs | 40 +- libwallet/src/internal/selection.rs | 36 +- libwallet/src/internal/tx.rs | 52 ++- libwallet/src/internal/updater.rs | 61 ++- libwallet/src/lib.rs | 8 +- libwallet/src/mwixnet/onion/crypto/comsig.rs | 29 +- libwallet/src/mwixnet/onion/crypto/dalek.rs | 17 +- libwallet/src/mwixnet/onion/crypto/secp.rs | 10 +- libwallet/src/mwixnet/onion/mod.rs | 21 +- libwallet/src/mwixnet/onion/onion.rs | 28 +- libwallet/src/mwixnet/onion/util.rs | 10 +- libwallet/src/slate.rs | 126 +++--- libwallet/src/slate_versions/ser.rs | 133 +++--- libwallet/src/slate_versions/v4.rs | 18 +- libwallet/src/slate_versions/v4_bin.rs | 46 +- libwallet/src/slatepack/address.rs | 17 +- libwallet/src/slatepack/armor.rs | 8 +- libwallet/src/slatepack/packer.rs | 6 +- libwallet/src/slatepack/types.rs | 53 ++- libwallet/src/types.rs | 50 ++- libwallet/tests/libwallet.rs | 74 ++-- src/bin/grin-wallet.rs | 25 +- src/build/build.rs | 5 +- src/cli/cli.rs | 14 +- src/cli/mod.rs | 1 + src/cmd/wallet.rs | 2 +- src/cmd/wallet_args.rs | 145 +++---- tests/cmd_line_basic.rs | 17 +- tests/common/mod.rs | 37 +- tests/owner_v3_init_secure.rs | 17 +- tests/owner_v3_lifecycle.rs | 46 +- util/src/byte_ser.rs | 18 +- 87 files changed, 1300 insertions(+), 1639 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 989bfb6..0da7c95 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -2,6 +2,17 @@ name: Continuous Integration on: [push, pull_request] jobs: + clippy: + name: Cargo clippy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + - run: rustup toolchain install 1.99.0 --profile minimal --component clippy + - run: cargo +1.99.0 clippy --workspace --all-targets -- -D warnings + + # Run tests alongside Clippy, even if lint fails linux-tests: name: Linux Tests runs-on: ubuntu-latest @@ -36,4 +47,4 @@ jobs: with: submodules: recursive - name: Tests - run: cargo test --release --all \ No newline at end of file + run: cargo test --release --all diff --git a/.hooks/pre-commit b/.hooks/pre-commit index 8056d6c..05bd537 100755 --- a/.hooks/pre-commit +++ b/.hooks/pre-commit @@ -14,6 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +cargo +1.99.0 clippy --workspace --all-targets -- -D warnings +if [ $? != 0 ]; then + printf "clippy check failed; check with:\n" + printf "cargo +1.99.0 clippy --workspace --all-targets -- -D warnings\n" + printf "if clippy is missing: rustup toolchain install 1.99.0 --profile minimal --component clippy\n" + exit 1 +fi + rustfmt --version &>/dev/null if [ $? != 0 ]; then printf "[pre_commit] \033[0;31merror\033[0m: \"rustfmt\" not available. \n" diff --git a/api/src/foreign.rs b/api/src/foreign.rs index 2d03c18..1d1f6f5 100644 --- a/api/src/foreign.rs +++ b/api/src/foreign.rs @@ -18,16 +18,12 @@ use crate::keychain::Keychain; use crate::libwallet::api_impl::foreign; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::{ - BlockFees, CbData, Error, NodeClient, NodeVersionInfo, Slate, VersionInfo, WalletInst, - WalletLCProvider, + BlockFees, CbData, Error, NodeClient, NodeVersionInfo, Slate, VersionInfo, WalletLCProvider, }; use crate::try_slatepack_sync_workflow; use crate::util::secp::key::SecretKey; -use crate::util::Mutex; use libwallet::SlatepackAddress; -use std::sync::Arc; - /// ForeignAPI Middleware Check callback pub type ForeignCheckMiddleware = fn(ForeignCheckMiddlewareFn, Option, Option<&Slate>) -> Result<(), Error>; @@ -51,15 +47,14 @@ pub enum ForeignCheckMiddlewareFn { /// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs /// /// * The 'Foreign' API contains methods that other wallets will -/// use to interact with the owner's wallet. This API can be exposed -/// to the outside world, with the consideration as to how that can -/// be done securely up to the implementor. +/// use to interact with the owner's wallet. This API can be exposed +/// to the outside world, with the consideration as to how that can +/// be done securely up to the implementor. /// /// Methods in both APIs are intended to be 'single use', that is to say each /// method will 'open' the wallet (load the keychain with its master seed), perform /// its operation, then 'close' the wallet (unloading references to the keychain and master /// seed). - pub struct Foreign<'a, L, C, K> where L: WalletLCProvider<'a, C, K>, @@ -67,7 +62,7 @@ where K: Keychain + 'a, { /// Wallet instance - pub wallet_inst: Arc>>>, + pub wallet_inst: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, /// Wallet configuration path config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. @@ -94,13 +89,13 @@ where /// /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the - /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. /// * `config_path` - Path to the wallet configuration file /// * `keychain_mask` - Mask value stored internally to use when calling a wallet - /// whose seed has been XORed with a token value (such as when running the foreign - /// and owner listeners in the same instance) + /// whose seed has been XORed with a token value (such as when running the foreign + /// and owner listeners in the same instance) /// * middleware - Option middleware which containts the NodeVersionInfo and can call - /// a predefined function with the slate to check if the operation should continue + /// a predefined function with the slate to check if the operation should continue /// /// # Returns /// * An instance of the ForeignApi holding a reference to the provided wallet @@ -170,9 +165,8 @@ where /// // .. perform wallet operations /// /// ``` - pub fn new

( - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, config_path: P, keychain_mask: Option, middleware: Option, @@ -205,7 +199,6 @@ where /// let version_info = api_foreign.check_version(); /// // check and proceed accordingly /// ``` - pub fn check_version(&self) -> Result { if let Some(m) = self.middleware.as_ref() { let mut w_lock = self.wallet_inst.lock(); @@ -231,7 +224,7 @@ where /// # Arguments /// /// * `block_fees` - A [`BlockFees`](../grin_wallet_libwallet/api_impl/types/struct.BlockFees.html) - /// struct, set up as follows: + /// struct, set up as follows: /// /// `fees` - should contain the sum of all transaction fees included in the potential /// block @@ -244,7 +237,7 @@ where /// /// # Returns /// * `Ok`([`cb_data`](../grin_wallet_libwallet/api_impl/types/struct.CbData.html)`)` if successful. This - /// will contain the corresponding output, kernel and keyID used to create the coinbase output. + /// will contain the corresponding output, kernel and keyID used to create the coinbase output. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -268,7 +261,6 @@ where /// // ... /// } /// ``` - pub fn build_coinbase(&self, block_fees: &BlockFees) -> Result { let mut w_lock = self.wallet_inst.lock(); let w = w_lock.lc_provider()?.wallet_inst()?; @@ -281,7 +273,7 @@ where } foreign::build_coinbase( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), block_fees, self.doctest_mode, ) @@ -304,18 +296,18 @@ where /// /// # Arguments /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). - /// The slate should contain the results of the sender's round 1 (e.g, public nonce and public - /// excess value). + /// The slate should contain the results of the sender's round 1 (e.g, public nonce and public + /// excess value). /// * `dest_acct_name` - The name of the account into which the slate should be received. If - /// `None`, the default account is used. + /// `None`, the default account is used. /// * `r_addr` - If included, attempt to send the slate back to the sender using the slatepack sync - /// send (TOR). If providing this argument, check the `state` field of the slate to see if the - /// sync_send was successful (it should be S3 if the synced send sent successfully). + /// send (TOR). If providing this argument, check the `state` field of the slate to see if the + /// sync_send was successful (it should be S3 if the synced send sent successfully). /// /// # Returns /// * a result containing: /// * `Ok`([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html)`)` if successful, - /// containing the new slate updated with the recipient's output and public signing information. + /// containing the new slate updated with the recipient's output and public signing information. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks @@ -339,7 +331,6 @@ where /// // ... /// } /// ``` - pub fn receive_tx( &self, slate: &Slate, @@ -361,7 +352,7 @@ where } let ret_slate = foreign::receive_tx( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), slate, dest_acct_name, self.doctest_mode, @@ -381,7 +372,7 @@ where let parent_key_id = w.parent_key_id(); match update_tx_slate_state( w, - (&self.keychain_mask).as_ref(), + self.keychain_mask.as_ref(), &parent_key_id, &s, ) { @@ -416,11 +407,11 @@ where /// # Arguments /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). The /// * `post_automatically` - If true, post the finalized transaction to the configured listening - /// node + /// node /// /// # Returns /// * Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html)) if successful, - /// containing the new finalized slate. + /// containing the new finalized slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -447,7 +438,6 @@ where /// let slate = api_foreign.finalize_tx(&slate, true); /// // if okay, then post via the owner API /// ``` - pub fn finalize_tx(&self, slate: &Slate, post_automatically: bool) -> Result { let mut w_lock = self.wallet_inst.lock(); let w = w_lock.lc_provider()?.wallet_inst()?; @@ -455,7 +445,7 @@ where true => false, false => post_automatically, }; - foreign::finalize_tx(w, (&self.keychain_mask).as_ref(), slate, post_automatically) + foreign::finalize_tx(w, self.keychain_mask.as_ref(), slate, post_automatically) } } diff --git a/api/src/foreign_rpc.rs b/api/src/foreign_rpc.rs index 2c5ffaa..ae4e5a4 100644 --- a/api/src/foreign_rpc.rs +++ b/api/src/foreign_rpc.rs @@ -20,7 +20,6 @@ use crate::libwallet::{ Slate, SlateVersion, VersionInfo, VersionedCoinbase, VersionedSlate, WalletLCProvider, }; use crate::{Foreign, ForeignCheckMiddlewareFn}; -use easy_jsonrpc_mw; use grin_wallet_config::initial_setup_wallet; use libwallet::SlatepackAddress; use std::path::PathBuf; @@ -112,7 +111,6 @@ pub trait ForeignRpc { # ,false, 4, false, false); ``` */ - fn build_coinbase(&self, block_fees: &BlockFees) -> Result; /** @@ -322,19 +320,14 @@ where } }, }; - let out_slate = Foreign::receive_tx( - self, - &slate_from, - dest_acct_name.as_ref().map(String::as_str), - dest, - )?; - Ok(VersionedSlate::into_version(out_slate, version)?) + let out_slate = Foreign::receive_tx(self, &slate_from, dest_acct_name.as_deref(), dest)?; + VersionedSlate::into_version(out_slate, version) } fn finalize_tx(&self, in_slate: VersionedSlate) -> Result { let version = in_slate.version(); let out_slate = Foreign::finalize_tx(self, &Slate::from(in_slate), true)?; - Ok(VersionedSlate::into_version(out_slate, version)?) + VersionedSlate::into_version(out_slate, version) } } @@ -467,19 +460,14 @@ pub fn run_doctest_foreign( let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 1 as usize, + mask1.as_ref(), + 1_usize, false, ); //update local outputs after each block, so transaction IDs stay consistent - let (wallet_refreshed, _) = api_impl::owner::retrieve_summary_info( - wallet1.clone(), - (&mask1).as_ref(), - &None, - true, - 1, - ) - .unwrap(); + let (wallet_refreshed, _) = + api_impl::owner::retrieve_summary_info(wallet1.clone(), mask1.as_ref(), &None, true, 1) + .unwrap(); assert!(wallet_refreshed); } @@ -492,7 +480,7 @@ pub fn run_doctest_foreign( amount, ..Default::default() }; - api_impl::owner::issue_invoice_tx(w, (&mask2).as_ref(), args, true).unwrap() + api_impl::owner::issue_invoice_tx(w, mask2.as_ref(), args, true).unwrap() }; slate = { let mut w_lock = wallet1.lock(); @@ -506,7 +494,7 @@ pub fn run_doctest_foreign( selection_strategy_is_use_all: true, ..Default::default() }; - api_impl::owner::process_invoice_tx(w, (&mask1).as_ref(), &slate, args, true).unwrap() + api_impl::owner::process_invoice_tx(w, mask1.as_ref(), &slate, args, true).unwrap() }; println!("INIT INVOICE SLATE"); // Spit out slate for input to finalize_tx @@ -526,7 +514,7 @@ pub fn run_doctest_foreign( selection_strategy_is_use_all: true, ..Default::default() }; - let slate = api_impl::owner::init_send_tx(w, (&mask1).as_ref(), args, true).unwrap(); + let slate = api_impl::owner::init_send_tx(w, mask1.as_ref(), args, true).unwrap(); println!("INIT SLATE"); // Spit out slate for input to finalize_tx println!("{}", serde_json::to_string_pretty(&slate).unwrap()); diff --git a/api/src/owner.rs b/api/src/owner.rs index ffcdf0b..aecde62 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -26,7 +26,7 @@ use crate::libwallet::api_impl::{owner, owner_updater}; use crate::libwallet::{ AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, - TxLogEntry, ViewWallet, WalletInfo, WalletInst, WalletLCProvider, + TxLogEntry, ViewWallet, WalletInfo, WalletLCProvider, }; use crate::util::logger::LoggingConfig; use crate::util::secp::{key::SecretKey, pedersen::Commitment}; @@ -57,15 +57,14 @@ use uuid::Uuid; /// called the ['Owner'](struct.Owner.html) and ['Foreign'](struct.Foreign.html) APIs /// /// * The 'Owner' API is intended to expose methods that are to be -/// used by the wallet owner only. It is vital that this API is not -/// exposed to anyone other than the owner of the wallet (i.e. the -/// person with access to the seed and password. +/// used by the wallet owner only. It is vital that this API is not +/// exposed to anyone other than the owner of the wallet (i.e. the +/// person with access to the seed and password. /// /// Methods in both APIs are intended to be 'single use', that is to say each /// method will 'open' the wallet (load the keychain with its master seed), perform /// its operation, then 'close' the wallet (unloading references to the keychain and master /// seed). - pub struct Owner where L: WalletLCProvider<'static, C, K> + 'static, @@ -73,7 +72,7 @@ where K: Keychain + 'static, { /// Contains all methods to manage the wallet - pub wallet_inst: Arc>>>, + pub wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Wallet configuration path config_path: crate::ConfigPath, /// Flag to normalize some output during testing. Can mostly be ignored. @@ -109,9 +108,9 @@ where /// /// # Arguments /// * `wallet_in` - A reference-counted mutex containing an implementation of the - /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. + /// [`WalletBackend`](../grin_wallet_libwallet/types/trait.WalletBackend.html) trait. /// * `custom_channel` - A custom MPSC Tx/Rx pair to capture status - /// updates + /// updates /// * `config_path` - Path to the wallet configuration file /// /// # Returns @@ -181,9 +180,8 @@ where /// // .. perform wallet operations /// /// ``` - pub fn new

( - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, custom_channel: Option>, config_path: P, ) -> Self @@ -241,7 +239,6 @@ where /// * `Ok(())` if the config was correctly saved /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// - pub fn set_tor_config(&self, tor_config: Option) -> Result<(), Error> { let _wallet_lock = self.wallet_inst.lock(); update_global_config(&self.config_path(), |config| { @@ -265,7 +262,7 @@ where /// user-specified labels and BIP32 derivation paths). /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * Result Containing: @@ -275,7 +272,7 @@ where /// # Remarks /// /// * A wallet should always have the path with the label 'default' path defined, - /// with path m/0/0 + /// with path m/0/0 /// * This method does not need to use the wallet seed or keychain. /// /// # Example @@ -291,7 +288,6 @@ where /// //... /// } /// ``` - pub fn accounts( &self, keychain_mask: Option<&SecretKey>, @@ -320,7 +316,7 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `label` - A human-readable label to which to map the new BIP32 Path /// /// # Returns @@ -332,11 +328,11 @@ where /// /// * Wallets should be initialized with the 'default' path mapped to `m/0/0` /// * Each call to this function will increment the first element of the path - /// so the first call will create an account at `m/1/0` and the second at - /// `m/2/0` etc. + /// so the first call will create an account at `m/1/0` and the second at + /// `m/2/0` etc. /// * The account path is used throughout as the parent key for most key-derivation - /// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for - /// further details. + /// operations. See [`set_active_account`](struct.Owner.html#method.set_active_account) for + /// further details. /// /// * This function does not need to use the root wallet seed or keychain. /// @@ -353,7 +349,6 @@ where /// //... /// } /// ``` - pub fn create_account_path( &self, keychain_mask: Option<&SecretKey>, @@ -370,9 +365,9 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `label` - The human-readable label for the account. Accounts can be retrieved via - /// the [`account`](struct.Owner.html#method.accounts) method + /// the [`account`](struct.Owner.html#method.accounts) method /// /// # Returns /// * Result Containing: @@ -382,9 +377,9 @@ where /// # Remarks /// /// * Wallet parent paths are 2 path elements long, e.g. `m/0/0` is the path - /// labeled 'default'. Keys derived from this parent path are 3 elements long, - /// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`, - /// `m/0/0/1` etc... + /// labeled 'default'. Keys derived from this parent path are 3 elements long, + /// e.g. the secret keys derived from the `m/0/0` path will be at paths `m/0/0/0`, + /// `m/0/0/1` etc... /// /// * This function does not need to use the root wallet seed or keychain. /// @@ -402,7 +397,6 @@ where /// let result2 = api_owner.set_active_account(None, "account1"); /// } /// ``` - pub fn set_active_account( &self, keychain_mask: Option<&SecretKey>, @@ -419,30 +413,30 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `include_spent` - If `true`, outputs that have been marked as 'spent' - /// in the wallet will be returned. If `false`, spent outputs will omitted - /// from the results. + /// in the wallet will be returned. If `false`, spent outputs will omitted + /// from the results. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain output information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain output information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)`, only return the outputs associated with - /// the transaction log entry of id `i`. + /// the transaction log entry of id `i`. /// /// # Returns /// * `(bool, Vec)` - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`. + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`. /// * The second element contains a vector of - /// [OutputCommitMapping](../grin_wallet_libwallet/types/struct.OutputCommitMapping.html) - /// of which each element is a mapping between the wallet's internal - /// [OutputData](../grin_wallet_libwallet/types/struct.Output.html) - /// and the Output commitment as identified in the chain's UTXO set + /// [OutputCommitMapping](../grin_wallet_libwallet/types/struct.OutputCommitMapping.html) + /// of which each element is a mapping between the wallet's internal + /// [OutputData](../grin_wallet_libwallet/types/struct.Output.html) + /// and the Output commitment as identified in the chain's UTXO set /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -460,7 +454,6 @@ where /// //... /// } /// ``` - pub fn retrieve_outputs( &self, keychain_mask: Option<&SecretKey>, @@ -490,22 +483,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `minimum_confirmations` - The minimum number of confirmations an output - /// should have before it's included in the 'amount_currently_spendable' total + /// should have before it's included in the 'amount_currently_spendable' total /// /// # Returns /// * `(bool, u64, u64, u32)` - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`). + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`). /// * The second `u64` is amount to send. /// * The third element is fee /// * The fourth is maximum input count @@ -524,7 +517,6 @@ where /// //... /// } /// ``` - pub fn estimate_max_sendable( &self, keychain_mask: Option<&SecretKey>, @@ -554,29 +546,29 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)`, only return the transactions associated with - /// the transaction log entry of id `i`. + /// the transaction log entry of id `i`. /// * `tx_slate_id` - If `Some(uuid)`, only return transactions associated with - /// the given [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) uuid. + /// the given [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html) uuid. /// * `tx_query_args` - If provided, use advanced query arguments as documented in - /// (../grin_wallet_libwallet/types.struct.RetrieveTxQueryArgs.html). If either - /// `tx_id` or `tx_slate_id` is provided in the same call, this argument is ignored + /// (../grin_wallet_libwallet/types.struct.RetrieveTxQueryArgs.html). If either + /// `tx_id` or `tx_slate_id` is provided in the same call, this argument is ignored /// /// # Returns /// * `(bool, Vec, @@ -639,22 +630,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `minimum_confirmations` - The minimum number of confirmations an output - /// should have before it's included in the 'amount_currently_spendable' total + /// should have before it's included in the 'amount_currently_spendable' total /// /// # Returns /// * (`bool`, [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html)) - A tuple: /// * The first `bool` element indicates whether the data was successfully - /// refreshed from the node (note this may be false even if the `refresh_from_node` - /// argument was set to `true`. + /// refreshed from the node (note this may be false even if the `refresh_from_node` + /// argument was set to `true`. /// * The second element contains the Summary [`WalletInfo`](../grin_wallet_libwallet/types/struct.WalletInfo.html) /// /// # Example @@ -673,7 +664,6 @@ where /// //... /// } /// ``` - pub fn retrieve_summary_info( &self, keychain_mask: Option<&SecretKey>, @@ -736,30 +726,30 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), - /// transaction initialization arguments. See struct documentation for further detail. + /// transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * a result containing: /// * The transaction [Slate](../grin_wallet_libwallet/slate/struct.Slate.html), - /// which can be forwarded to the receiving party by any means. With normal locking, an - /// attempted Tor send already locks the outputs, even if sending fails. Do not call - /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) again when forwarding manually. - /// If sending was not requested or was skipped, lock the outputs before forwarding the slate. - /// With late locking, outputs are locked during finalization instead. - /// If `skip_tor` is omitted, `skip_send_attempt` in the Tor config decides whether to send. - /// With normal locking, a returned S1 slate alone does not tell you whether outputs are locked. - /// Set `skip_tor` explicitly or check [`retrieve_txs`](struct.Owner.html#method.retrieve_txs) - /// for the slate ID before locking manually. + /// which can be forwarded to the receiving party by any means. With normal locking, an + /// attempted Tor send already locks the outputs, even if sending fails. Do not call + /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) again when forwarding manually. + /// If sending was not requested or was skipped, lock the outputs before forwarding the slate. + /// With late locking, outputs are locked during finalization instead. + /// If `skip_tor` is omitted, `skip_send_attempt` in the Tor config decides whether to send. + /// With normal locking, a returned S1 slate alone does not tell you whether outputs are locked. + /// Set `skip_tor` explicitly or check [`retrieve_txs`](struct.Owner.html#method.retrieve_txs) + /// for the slate ID before locking manually. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks /// /// * This method requires an active connection to a node, and will fail with error if a node - /// cannot be contacted to refresh output statuses. + /// cannot be contacted to refresh output statuses. /// * This method will store a partially completed transaction in the wallet's transaction log, - /// which will be updated on the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx). + /// which will be updated on the corresponding call to [`finalize_tx`](struct.Owner.html#method.finalize_tx). /// /// # Example /// Set up as in [new](struct.Owner.html#method.new) method above. @@ -789,7 +779,6 @@ where /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` - pub fn init_send_tx( &self, keychain_mask: Option<&SecretKey>, @@ -871,13 +860,13 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `args` - [`IssueInvoiceTxArgs`](../grin_wallet_libwallet/types/struct.IssueInvoiceTxArgs.html), - /// invoice transaction initialization arguments. See struct documentation for further detail. + /// invoice transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the updated slate. + /// containing the updated slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -930,15 +919,15 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). The - /// payer should have filled in round 1 and 2. + /// payer should have filled in round 1 and 2. /// * `args` - [`InitTxArgs`](../grin_wallet_libwallet/types/struct.InitTxArgs.html), - /// transaction initialization arguments. See struct documentation for further detail. + /// transaction initialization arguments. See struct documentation for further detail. /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the updated slate. + /// containing the updated slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -968,7 +957,6 @@ where /// // . . . /// } /// ``` - pub fn process_invoice_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1018,7 +1006,7 @@ where } } // Output slatepack message to file. - match output_slatepack_file(&self, keychain_mask, &s, Some(dest)) { + match output_slatepack_file(self, keychain_mask, &s, Some(dest)) { Ok(_) => {} Err(e) => error!("Error on saving output slatepack message: {}", e), } @@ -1049,12 +1037,12 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All /// * `participant_id` - The participant id, generally 0 for the party putting in funds, 1 for the - /// party receiving. - /// elements in the `input` vector of the `tx` field that are found in the wallet's currently - /// active account will be set to status `Locked` + /// party receiving. + /// elements in the `input` vector of the `tx` field that are found in the wallet's currently + /// active account will be set to status `Locked` /// /// # Returns /// * Ok(()) if successful @@ -1087,7 +1075,6 @@ where /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` - pub fn tx_lock_outputs( &self, keychain_mask: Option<&SecretKey>, @@ -1112,14 +1099,14 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `slate` - The transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). All - /// participants must have filled in both rounds, and the sender should have locked their - /// outputs (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) function). + /// participants must have filled in both rounds, and the sender should have locked their + /// outputs (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) function). /// /// # Returns /// * ``Ok([`slate`](../grin_wallet_libwallet/slate/struct.Slate.html))` if successful, - /// containing the new finalized slate. + /// containing the new finalized slate. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1153,7 +1140,6 @@ where /// let res = api_owner.finalize_tx(None, &slate); /// } /// ``` - pub fn finalize_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1169,13 +1155,13 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx` - A completed [`Transaction`](../grin_core/core/transaction/struct.Transaction.html), - /// typically the `tx` field in the transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). + /// typically the `tx` field in the transaction [`Slate`](../grin_wallet_libwallet/slate/struct.Slate.html). /// * `fluff` - Instruct the node whether to use the Dandelion protocol when posting the - /// transaction. If `true`, the node should skip the Dandelion phase and broadcast the - /// transaction to all peers immediately. If `false`, the node will follow dandelion logic and - /// initiate the stem phase. + /// transaction. If `true`, the node should skip the Dandelion phase and broadcast the + /// transaction to all peers immediately. If `false`, the node will follow dandelion logic and + /// initiate the stem phase. /// /// # Returns /// * `Ok(())` if successful @@ -1213,7 +1199,6 @@ where /// let res = api_owner.post_tx(None, &slate, true); /// } /// ``` - pub fn post_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1234,7 +1219,7 @@ where /// * Setting the transaction status to either `TxSentCancelled` or `TxReceivedCancelled` /// * Deleting all change outputs or recipient outputs associated with the transaction /// * Setting the status of all associated inputs from `Locked` to `Spent` so they can be - /// used in new transactions. + /// used in new transactions. /// /// Transactions can be canceled by transaction log id or slate id (call with either set to /// Some, not both) @@ -1242,9 +1227,9 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx_id` - If present, cancel by the [`TxLogEntry`](../grin_wallet_libwallet/types/struct.TxLogEntry.html) id - /// for the transaction. + /// for the transaction. /// /// * `tx_slate_id` - If present, cancel by the Slate id. /// @@ -1283,7 +1268,6 @@ where /// let res = api_owner.cancel_tx(None, None, Some(slate.id.clone())); /// } /// ``` - pub fn cancel_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1310,16 +1294,16 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `tx_id` - The id of the transaction in the wallet's Transaction Log. Either this or - /// `slate_id` must be provided. + /// `slate_id` must be provided. /// * `slate_id` - The UUID of the Transaction Slate to find. Either this or `tx_id` must be - /// provided + /// provided /// /// # Returns /// * Ok(Some([Slate](../grin_wallet_libwallet/slate/struct.Slate.html)) containing the stored - /// transaction, if successful. Note that this Slate will not contain all the fields used by - /// the original Slate that resulted in the transaction. + /// transaction, if successful. Note that this Slate will not contain all the fields used by + /// the original Slate that resulted in the transaction. /// * Ok(None) if the stored Transaction isn't found. /// * [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// @@ -1341,7 +1325,6 @@ where /// //... /// } /// ``` - pub fn get_stored_tx( &self, keychain_mask: Option<&SecretKey>, @@ -1361,12 +1344,11 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * `Ok(String)` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1384,7 +1366,6 @@ where /// // ... /// } /// ``` - pub fn get_rewind_hash(&self, keychain_mask: Option<&SecretKey>) -> Result { owner::get_rewind_hash(self.wallet_inst.clone(), keychain_mask) } @@ -1401,12 +1382,11 @@ where /// /// * `rewind_hash` - Rewind hash of a wallet, used to retrieve the output of a third-party wallet. /// * `start_height` - If provided, the height of the first block from which to start scanning. - /// The scan will start from block 1 if this is not provided. + /// The scan will start from block 1 if this is not provided. /// /// # Returns /// * `Ok(ViewWallet)` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1424,7 +1404,6 @@ where /// // ... /// } /// ``` - pub fn scan_rewind_hash( &self, rewind_hash: String, @@ -1454,23 +1433,22 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `start_height` - If provided, the height of the first block from which to start scanning. - /// The scan will start from block 1 if this is not provided. + /// The scan will start from block 1 if this is not provided. /// * `delete_unconfirmed` - if `false`, the scan process will be non-destructive, and - /// mostly limited to restoring missing outputs. It will leave unconfirmed transaction logs entries - /// and unconfirmed outputs intact. If `true`, the process will unlock all locked outputs, - /// restore all missing outputs, and mark any outputs that have been marked 'Spent' but are still - /// in the UTXO set as 'Unspent' (as can happen during a fork). It will also attempt to cancel any - /// transaction log entries associated with any locked outputs or outputs incorrectly marked 'Spent'. - /// Note this completely removes all outstanding transactions, so users should be very aware what - /// will happen if this flag is set. Note that if transactions/outputs are removed that later - /// confirm on the chain, another call to this function will restore them. + /// mostly limited to restoring missing outputs. It will leave unconfirmed transaction logs entries + /// and unconfirmed outputs intact. If `true`, the process will unlock all locked outputs, + /// restore all missing outputs, and mark any outputs that have been marked 'Spent' but are still + /// in the UTXO set as 'Unspent' (as can happen during a fork). It will also attempt to cancel any + /// transaction log entries associated with any locked outputs or outputs incorrectly marked 'Spent'. + /// Note this completely removes all outstanding transactions, so users should be very aware what + /// will happen if this flag is set. Note that if transactions/outputs are removed that later + /// confirm on the chain, another call to this function will restore them. /// /// # Returns /// * `Ok(())` if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. - /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. /// ``` @@ -1488,7 +1466,6 @@ where /// // ... /// } /// ``` - pub fn scan( &self, keychain_mask: Option<&SecretKey>, @@ -1510,10 +1487,10 @@ where /// Retrieves the last known height known by the wallet. This is determined as follows: /// * If the wallet can successfully contact its configured node, the reported node - /// height is returned, and the `updated_from_node` field in the response is `true` + /// height is returned, and the `updated_from_node` field in the response is `true` /// * If the wallet cannot contact the node, this function returns the maximum height - /// of all outputs contained within the wallet, and the `updated_from_node` fields - /// in the response is set to false. + /// of all outputs contained within the wallet, and the `updated_from_node` fields + /// in the response is set to false. /// /// Clients should generally ensure the `updated_from_node` field is returned as /// `true` before assuming the height for any operation. @@ -1521,12 +1498,12 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// /// # Returns /// * Ok with a [`NodeHeightResult`](../grin_wallet_libwallet/types/struct.NodeHeightResult.html) - /// if successful. If the height result was obtained from the configured node, - /// `updated_from_node` will be set to `true` + /// if successful. If the height result was obtained from the configured node, + /// `updated_from_node` will be set to `true` /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Example @@ -1545,7 +1522,6 @@ where /// //... /// } /// ``` - pub fn node_height( &self, keychain_mask: Option<&SecretKey>, @@ -1575,7 +1551,7 @@ where /// The top level directory defaults to (in order of precedence): /// /// 1) The current directory, from which `grin-wallet` or the main process was run, if it - /// contains a `grin-wallet.toml` file. + /// contains a `grin-wallet.toml` file. /// 2) ~/.grin// otherwise /// /// # Arguments @@ -1599,7 +1575,6 @@ where /// //... /// } /// ``` - pub fn get_top_level_directory(&self) -> Result { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -1622,7 +1597,7 @@ where /// # Arguments /// /// * `dir`: The new top-level directory path (either relative to current directory or - /// absolute. + /// absolute. /// /// # Returns /// * Ok if successful @@ -1649,7 +1624,6 @@ where /// //... /// } /// ``` - pub fn set_top_level_directory(&self, dir: &str) -> Result<(), Error> { if self.updater_running.load(Ordering::Relaxed) { return Err(Error::Lifecycle( @@ -1717,7 +1691,6 @@ where /// //... /// } /// ``` - pub fn create_config( &self, chain_type: &global::ChainTypes, @@ -1750,11 +1723,11 @@ where /// /// * `name`: Reserved for future use, use `None` for the time being. /// * `mnemonic`: If present, restore the wallet seed from the given mnemonic instead of creating - /// a new random seed. + /// a new random seed. /// * `mnemonic_length`: Entropy length in bytes: 16, 20, 24, 28 or 32 - /// (12, 15, 18, 21 or 24 words). Ignored when `mnemonic` is provided. - /// For a new random seed, 0 is also accepted and defaults to 32 bytes. - /// All other values return an error. + /// (12, 15, 18, 21 or 24 words). Ignored when `mnemonic` is provided. + /// For a new random seed, 0 is also accepted and defaults to 32 bytes. + /// All other values return an error. /// * `password`: The password used to encrypt/decrypt the `wallet.seed` file /// /// # Returns @@ -1793,7 +1766,6 @@ where /// //... /// } /// ``` - pub fn create_wallet( &self, name: Option<&str>, @@ -1821,9 +1793,9 @@ where /// /// * `name`: Reserved for future use, use `None` for the time being. /// * `password`: The password to use to open the wallet - /// a new random seed. + /// a new random seed. /// * `use_mask`: Whether to create and return a mask which much be provided in all future - /// API calls. + /// API calls. /// /// # Returns /// * Ok if successful @@ -1863,7 +1835,6 @@ where /// let mask = m; /// } /// ``` - pub fn open_wallet( &self, name: Option<&str>, @@ -1911,7 +1882,6 @@ where /// // ... /// } /// ``` - pub fn close_wallet(&self, name: Option<&str>) -> Result<(), Error> { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -2035,7 +2005,6 @@ where /// // ... /// } /// ``` - pub fn delete_wallet(&self, name: Option<&str>) -> Result<(), Error> { let mut w_lock = self.wallet_inst.lock(); let lc = w_lock.lc_provider()?; @@ -2048,14 +2017,14 @@ where /// The updater process is as follows: /// /// * Reconcile the wallet outputs against the node's current UTXO set, confirming - /// transactions if needs be. + /// transactions if needs be. /// * Look up transactions by kernel in cases where it's necessary (for instance, when - /// there are no change outputs for a transaction and transaction status can't be - /// inferred from the output state. + /// there are no change outputs for a transaction and transaction status can't be + /// inferred from the output state. /// * Incrementally perform a scan of the UTXO set, correcting outputs and transactions - /// where their local state differs from what's on-chain. The wallet stores the last - /// position scanned, and will scan back 100 blocks worth of UTXOs on each update, to - /// correct any differences due to forks or otherwise. + /// where their local state differs from what's on-chain. The wallet stores the last + /// position scanned, and will scan back 100 blocks worth of UTXOs on each update, to + /// correct any differences due to forks or otherwise. /// /// Note that an update process can take a long time, particularly when the entire /// UTXO set is being scanned for correctness. The wallet status can be determined by @@ -2064,10 +2033,10 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `frequency`: The frequency at which to call the update process. Note this is - /// time elapsed since the last successful update process. If calling via the JSON-RPC - /// api, this represents milliseconds. + /// time elapsed since the last successful update process. If calling via the JSON-RPC + /// api, this represents milliseconds. /// /// # Returns /// * Ok if successful @@ -2091,7 +2060,6 @@ where /// // ... /// } /// ``` - pub fn start_updater( &self, keychain_mask: Option<&SecretKey>, @@ -2102,10 +2070,7 @@ where let t = self.status_tx.lock(); t.clone() }; - let keychain_mask = match keychain_mask { - Some(m) => Some(m.clone()), - None => None, - }; + let keychain_mask = keychain_mask.cloned(); let _ = thread::Builder::new() .name("wallet-updater".to_string()) .spawn(move || { @@ -2148,7 +2113,6 @@ where /// /// let res = api_owner.stop_updater(); /// ``` - pub fn stop_updater(&self) -> Result<(), Error> { self.updater_running.store(false, Ordering::Relaxed); Ok(()) @@ -2191,7 +2155,6 @@ where /// } /// /// ``` - pub fn get_updater_messages(&self, count: usize) -> Result, Error> { let mut q = self.updater_messages.lock(); let index = q.len().saturating_sub(count); @@ -2255,7 +2218,6 @@ where /// } /// /// ``` - pub fn get_slatepack_address( &self, keychain_mask: Option<&SecretKey>, @@ -2311,7 +2273,7 @@ where /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `sender_index` - If Some(n), the index along the derivation path to include as the sender /// * `recipients` - Optional recipients for which to encrypt the slatepack's payload (i.e. the - /// slate). If an empty vec, the payload will remain unencrypted + /// slate). If an empty vec, the payload will remain unencrypted /// /// # Returns /// * Ok with a String representing an armored slatepack if successful @@ -2354,7 +2316,6 @@ where /// } /// /// ``` - pub fn create_slatepack_message( &self, keychain_mask: Option<&SecretKey>, @@ -2379,8 +2340,8 @@ where /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `slatepack` - A string representing an armored slatepack /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt - /// decryption. This function will attempt to use secret keys at each index along this path - /// to attempt to decrypt the payload, returning an error if none of the keys match. + /// decryption. This function will attempt to use secret keys at each index along this path + /// to attempt to decrypt the payload, returning an error if none of the keys match. /// /// # Returns /// * Ok with a [Slate](../grin_wallet_libwallet/slate/struct.Slate.html) if successful @@ -2405,7 +2366,6 @@ where /// vec![0, 1, 2], /// ); /// ``` - pub fn slate_from_slatepack_message( &self, keychain_mask: Option<&SecretKey>, @@ -2429,8 +2389,8 @@ where /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using /// * `slatepack` - A string representing an armored slatepack /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt - /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned - /// Slatepack will remain encrypted. + /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned + /// Slatepack will remain encrypted. /// /// # Returns /// * Ok with a [Slatepack](../grin_wallet_libwallet/slatepack/types/struct.Slatepack.html) if successful @@ -2456,7 +2416,6 @@ where /// ); /// /// ``` - pub fn decode_slatepack_message( &self, keychain_mask: Option<&SecretKey>, @@ -2482,22 +2441,22 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `refresh_from_node` - If true, the wallet will attempt to contact - /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) - /// provided during wallet instantiation). If `false`, the results will - /// contain transaction information that may be out-of-date (from the last time - /// the wallet's output set was refreshed against the node). - /// Note this setting is ignored if the updater process is running via a call to - /// [`start_updater`](struct.Owner.html#method.start_updater) + /// a node (via the [`NodeClient`](../grin_wallet_libwallet/types/trait.NodeClient.html) + /// provided during wallet instantiation). If `false`, the results will + /// contain transaction information that may be out-of-date (from the last time + /// the wallet's output set was refreshed against the node). + /// Note this setting is ignored if the updater process is running via a call to + /// [`start_updater`](struct.Owner.html#method.start_updater) /// * `tx_id` - If `Some(i)` return the proof associated with the transaction with id `i` /// * `tx_slate_id` - If `Some(uuid)`, return the proof associated with the transaction with the - /// given `uuid` + /// given `uuid` /// /// # Returns /// * Ok([PaymentProof](../grin_wallet_libwallet/api_impl/types/struct.PaymentProof.html)) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered - /// or the proof is not present or complete + /// or the proof is not present or complete /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -2516,7 +2475,6 @@ where /// //... /// } /// ``` - pub fn retrieve_payment_proof( &self, keychain_mask: Option<&SecretKey>, @@ -2548,9 +2506,9 @@ where /// * Ensuring the kernel identified by the proof's stored excess commitment exists in the kernel set /// * Reproducing the signed message `amount|kernel_commitment|sender_address` /// * Validating the proof's `recipient_sig` against the message using the recipient's - /// address as the public key and + /// address as the public key and /// * Validating the proof's `sender_sig` against the message using the senders's - /// address as the public key + /// address as the public key /// /// This function also checks whether the sender or recipient address belongs to the currently /// open wallet, and returns 2 booleans indicating whether the address belongs to the sender and @@ -2558,15 +2516,15 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `proof` A [PaymentProof](../grin_wallet_libwallet/api_impl/types/struct.PaymentProof.html)) /// /// # Returns /// * Ok((bool, bool)) if the proof is valid. The first boolean indicates whether the sender - /// address belongs to this wallet, the second whether the recipient address belongs to this - /// wallet + /// address belongs to this wallet, the second whether the recipient address belongs to this + /// wallet /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered - /// or the proof is not present or complete + /// or the proof is not present or complete /// /// # Example /// Set up as in [`new`](struct.Owner.html#method.new) method above. @@ -2590,7 +2548,6 @@ where /// } /// } /// ``` - pub fn verify_payment_proof( &self, keychain_mask: Option<&SecretKey>, @@ -2618,11 +2575,11 @@ where /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// being used. + /// being used. /// * `params` - A [MixnetReqCreationParams](../grin_wallet_libwallet/api_impl/types/struct.MixnetReqCreationParams.html) - /// struct containing the parameters for the request, which include: - /// `server_keys` - The public keys of the servers participating in the mixnet (each encoded internally as a `SecretKey`) - /// `fee_per_hop` - The fee to be paid to each server for each hop in the mixnet + /// struct containing the parameters for the request, which include: + /// `server_keys` - The public keys of the servers participating in the mixnet (each encoded internally as a `SecretKey`) + /// `fee_per_hop` - The fee to be paid to each server for each hop in the mixnet /// * `commitment` - The commitment of the output to be mixed /// * `lock_output` - Whether to lock the referenced output after creating the request /// @@ -2656,7 +2613,6 @@ where /// //... /// } /// ``` - pub fn create_mwixnet_req( &self, keychain_mask: Option<&SecretKey>, @@ -2686,28 +2642,23 @@ pub fn try_slatepack_sync_workflow( send_to_finalize: bool, ) -> Result { let mut ret_slate = Slate::blank(2, false); - let mut send_sync = |mut sender: TorSlateSender, method_str: &str| { - return match sender.send_tx(&slate, send_to_finalize) { - Ok(s) => { - ret_slate = s; - Ok(()) - } - Err(e) => { - debug!( - "Send ({}): Could not send Slate via {}: {}", - method_str, method_str, e - ); - Err(e) - } - }; + let mut send_sync = |mut sender: TorSlateSender, method_str: &str| match sender + .send_tx(slate, send_to_finalize) + { + Ok(s) => { + ret_slate = s; + Ok(()) + } + Err(e) => { + debug!( + "Send ({}): Could not send Slate via {}: {}", + method_str, method_str, e + ); + Err(e) + } }; - let tor_addr = OnionV3Address::try_from(dest).map_err(|_| { - Error::SlatepackAddress(format!( - "Destination {} is not a valid Onion address.", - dest - )) - })?; + let tor_addr = OnionV3Address::from(dest); let sender = match tor_sender { None => { if let Some(tc) = tor_config { @@ -2818,7 +2769,7 @@ where Some(a) => vec![a], None => vec![], }; - let message = api.create_slatepack_message(keychain_mask, &slate, Some(0), recipients)?; + let message = api.create_slatepack_message(keychain_mask, slate, Some(0), recipients)?; let tld = api.get_top_level_directory()?; // Create a directory to which files will be output. @@ -2827,7 +2778,7 @@ where let out_file_name = format!("{}/{}.{}.slatepack", slate_dir, slate.id, slate.state); let mut output = File::create(out_file_name.clone())?; - output.write_all(&message.as_bytes())?; + output.write_all(message.as_bytes())?; output.sync_all()?; Ok(()) } diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 51d3168..367f82d 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -32,7 +32,6 @@ use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::secp::pedersen::Commitment; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; use crate::{ECDHPubkey, Ed25519SecretKey, Owner, Token}; -use easy_jsonrpc_mw; use grin_wallet_util::OnionV3Address; use rand::thread_rng; use std::convert::TryFrom; @@ -171,6 +170,7 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ + #[allow(clippy::ptr_arg)] fn create_account_path(&self, token: Token, label: &String) -> Result; /** @@ -205,6 +205,7 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ + #[allow(clippy::ptr_arg)] fn set_active_account(&self, token: Token, label: &String) -> Result<(), Error>; /** @@ -276,7 +277,6 @@ pub trait OwnerRpc { # , 2, false, false, false, false); ``` */ - fn retrieve_outputs( &self, token: Token, @@ -322,7 +322,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn estimate_max_sendable( &self, token: Token, @@ -409,7 +408,6 @@ pub trait OwnerRpc { # , 2, false, false, false, false); ``` */ - fn retrieve_txs( &self, token: Token, @@ -503,7 +501,6 @@ pub trait OwnerRpc { ``` */ - fn query_txs( &self, token: Token, @@ -554,7 +551,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn retrieve_summary_info( &self, token: Token, @@ -619,7 +615,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn init_send_tx(&self, token: Token, args: InitTxArgs) -> Result; /** @@ -666,7 +661,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn issue_invoice_tx( &self, token: Token, @@ -750,7 +744,6 @@ pub trait OwnerRpc { # , 4, false, false, false, false); ``` */ - fn process_invoice_tx( &self, token: Token, @@ -955,7 +948,6 @@ pub trait OwnerRpc { # , 5, true, true, true, false); ``` */ - fn post_tx(&self, token: Token, slate: VersionedSlate, fluff: bool) -> Result<(), Error>; /** @@ -1277,7 +1269,6 @@ pub trait OwnerRpc { ``` */ - fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result; /** @@ -1307,7 +1298,6 @@ pub trait OwnerRpc { # , 5, false, false, false, false); ``` */ - fn get_top_level_directory(&self) -> Result; /** @@ -1340,7 +1330,6 @@ pub trait OwnerRpc { # , 5, false, false, false, false); ``` */ - fn set_top_level_directory(&self, dir: String) -> Result<(), Error>; /** @@ -1443,7 +1432,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn create_wallet( &self, name: Option, @@ -1480,7 +1468,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn open_wallet(&self, name: Option, password: String) -> Result; /** @@ -1510,7 +1497,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn close_wallet(&self, name: Option) -> Result<(), Error>; /** @@ -1541,7 +1527,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_mnemonic(&self, name: Option, password: String) -> Result; /** @@ -1632,7 +1617,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn start_updater(&self, token: Token, frequency: u32) -> Result<(), Error>; /** @@ -1689,7 +1673,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_updater_messages(&self, count: u32) -> Result, Error>; /** @@ -1720,7 +1703,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_slatepack_address( &self, token: Token, @@ -1755,7 +1737,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn get_slatepack_secret_key( &self, token: Token, @@ -1805,7 +1786,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn create_slatepack_message( &self, token: Token, @@ -1860,7 +1840,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn slate_from_slatepack_message( &self, token: Token, @@ -1902,7 +1881,6 @@ pub trait OwnerRpc { # , 0, false, false, false, false); ``` */ - fn decode_slatepack_message( &self, token: Token, @@ -1947,7 +1925,6 @@ pub trait OwnerRpc { # , 5, true, true, true, true); ``` */ - fn retrieve_payment_proof( &self, token: Token, @@ -1994,7 +1971,6 @@ pub trait OwnerRpc { # , 5, true, true, true, true); ``` */ - fn verify_payment_proof( &self, token: Token, @@ -2125,7 +2101,6 @@ pub trait OwnerRpc { ``` * */ - fn create_mwixnet_req( &self, token: Token, @@ -2143,7 +2118,7 @@ where K: Keychain + 'static, { fn accounts(&self, token: Token) -> Result, Error> { - Owner::accounts(self, (&token.keychain_mask).as_ref()) + Owner::accounts(self, token.keychain_mask.as_ref()) } fn accounts_info( @@ -2151,15 +2126,15 @@ where token: Token, minimum_confirmations: u64, ) -> Result, Error> { - Owner::accounts_info(self, (&token.keychain_mask).as_ref(), minimum_confirmations) + Owner::accounts_info(self, token.keychain_mask.as_ref(), minimum_confirmations) } fn create_account_path(&self, token: Token, label: &String) -> Result { - Owner::create_account_path(self, (&token.keychain_mask).as_ref(), label) + Owner::create_account_path(self, token.keychain_mask.as_ref(), label) } fn set_active_account(&self, token: Token, label: &String) -> Result<(), Error> { - Owner::set_active_account(self, (&token.keychain_mask).as_ref(), label) + Owner::set_active_account(self, token.keychain_mask.as_ref(), label) } fn retrieve_outputs( @@ -2171,7 +2146,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_outputs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), include_spent, refresh_from_node, tx_id, @@ -2186,7 +2161,7 @@ where ) -> Result<(bool, u64, u64, u32), Error> { Owner::estimate_max_sendable( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, minimum_confirmations, ) @@ -2201,7 +2176,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_txs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, tx_id, tx_slate_id, @@ -2217,7 +2192,7 @@ where ) -> Result<(bool, Vec), Error> { Owner::retrieve_txs( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, None, None, @@ -2233,14 +2208,14 @@ where ) -> Result<(bool, WalletInfo), Error> { Owner::retrieve_summary_info( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, minimum_confirmations, ) } fn init_send_tx(&self, token: Token, args: InitTxArgs) -> Result { - let slate = Owner::init_send_tx(self, (&token.keychain_mask).as_ref(), args)?; + let slate = Owner::init_send_tx(self, token.keychain_mask.as_ref(), args)?; let version = SlateVersion::V4; VersionedSlate::into_version(slate, version) } @@ -2250,7 +2225,7 @@ where token: Token, args: IssueInvoiceTxArgs, ) -> Result { - let slate = Owner::issue_invoice_tx(self, (&token.keychain_mask).as_ref(), args)?; + let slate = Owner::issue_invoice_tx(self, token.keychain_mask.as_ref(), args)?; let version = SlateVersion::V4; VersionedSlate::into_version(slate, version) } @@ -2263,7 +2238,7 @@ where ) -> Result { let out_slate = Owner::process_invoice_tx( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(in_slate), args, )?; @@ -2272,19 +2247,12 @@ where } fn tx_lock_outputs(&self, token: Token, in_slate: VersionedSlate) -> Result<(), Error> { - Owner::tx_lock_outputs( - self, - (&token.keychain_mask).as_ref(), - &Slate::from(in_slate), - ) + Owner::tx_lock_outputs(self, token.keychain_mask.as_ref(), &Slate::from(in_slate)) } fn finalize_tx(&self, token: Token, in_slate: VersionedSlate) -> Result { - let out_slate = Owner::finalize_tx( - self, - (&token.keychain_mask).as_ref(), - &Slate::from(in_slate), - )?; + let out_slate = + Owner::finalize_tx(self, token.keychain_mask.as_ref(), &Slate::from(in_slate))?; let version = SlateVersion::V4; VersionedSlate::into_version(out_slate, version) } @@ -2292,7 +2260,7 @@ where fn post_tx(&self, token: Token, slate: VersionedSlate, fluff: bool) -> Result<(), Error> { Owner::post_tx( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(slate), fluff, ) @@ -2304,7 +2272,7 @@ where tx_id: Option, tx_slate_id: Option, ) -> Result<(), Error> { - Owner::cancel_tx(self, (&token.keychain_mask).as_ref(), tx_id, tx_slate_id) + Owner::cancel_tx(self, token.keychain_mask.as_ref(), tx_id, tx_slate_id) } fn get_stored_tx( @@ -2313,12 +2281,8 @@ where id: Option, slate_id: Option, ) -> Result, Error> { - let out_slate = Owner::get_stored_tx( - self, - (&token.keychain_mask).as_ref(), - id, - (&slate_id).as_ref(), - )?; + let out_slate = + Owner::get_stored_tx(self, token.keychain_mask.as_ref(), id, slate_id.as_ref())?; match out_slate { Some(s) => { let version = SlateVersion::V4; @@ -2329,7 +2293,7 @@ where } fn get_rewind_hash(&self, token: Token) -> Result { - Owner::get_rewind_hash(self, (&token.keychain_mask).as_ref()) + Owner::get_rewind_hash(self, token.keychain_mask.as_ref()) } fn scan_rewind_hash( @@ -2348,14 +2312,14 @@ where ) -> Result<(), Error> { Owner::scan( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), start_height, delete_unconfirmed, ) } fn node_height(&self, token: Token) -> Result { - Owner::node_height(self, (&token.keychain_mask).as_ref()) + Owner::node_height(self, token.keychain_mask.as_ref()) } fn init_secure_api(&self, ecdh_pubkey: ECDHPubkey) -> Result { @@ -2407,16 +2371,13 @@ where mnemonic_length: u32, password: String, ) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); - let m = match mnemonic { - Some(s) => Some(ZeroingString::from(s)), - None => None, - }; + let n = name.as_deref(); + let m = mnemonic.map(ZeroingString::from); Owner::create_wallet(self, n, m, mnemonic_length, ZeroingString::from(password)) } fn open_wallet(&self, name: Option, password: String) -> Result { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); let sec_key = Owner::open_wallet(self, n, ZeroingString::from(password), true)?; Ok(Token { keychain_mask: sec_key, @@ -2424,30 +2385,30 @@ where } fn close_wallet(&self, name: Option) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::close_wallet(self, n) } fn get_mnemonic(&self, name: Option, password: String) -> Result { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); let res = Owner::get_mnemonic(self, n, ZeroingString::from(password))?; - Ok((&*res).to_string()) + Ok((*res).to_string()) } fn change_password(&self, name: Option, old: String, new: String) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::change_password(self, n, ZeroingString::from(old), ZeroingString::from(new)) } fn delete_wallet(&self, name: Option) -> Result<(), Error> { - let n = name.as_ref().map(|s| s.as_str()); + let n = name.as_deref(); Owner::delete_wallet(self, n) } fn start_updater(&self, token: Token, frequency: u32) -> Result<(), Error> { Owner::start_updater( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), Duration::from_millis(frequency as u64), ) } @@ -2465,7 +2426,7 @@ where token: Token, derivation_index: u32, ) -> Result { - Owner::get_slatepack_address(self, (&token.keychain_mask).as_ref(), derivation_index) + Owner::get_slatepack_address(self, token.keychain_mask.as_ref(), derivation_index) } fn get_slatepack_secret_key( @@ -2473,11 +2434,8 @@ where token: Token, derivation_index: u32, ) -> Result { - let key = Owner::get_slatepack_secret_key( - self, - (&token.keychain_mask).as_ref(), - derivation_index, - )?; + let key = + Owner::get_slatepack_secret_key(self, token.keychain_mask.as_ref(), derivation_index)?; Ok(Ed25519SecretKey { key }) } @@ -2490,7 +2448,7 @@ where ) -> Result { let res = Owner::create_slatepack_message( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &Slate::from(slate), sender_index, recipients, @@ -2506,7 +2464,7 @@ where ) -> Result { let slate = Owner::slate_from_slatepack_message( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), message, secret_indices, )?; @@ -2520,12 +2478,7 @@ where message: String, secret_indices: Vec, ) -> Result { - Owner::decode_slatepack_message( - self, - (&token.keychain_mask).as_ref(), - message, - secret_indices, - ) + Owner::decode_slatepack_message(self, token.keychain_mask.as_ref(), message, secret_indices) } fn retrieve_payment_proof( @@ -2537,7 +2490,7 @@ where ) -> Result { Owner::retrieve_payment_proof( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), refresh_from_node, tx_id, tx_slate_id, @@ -2549,7 +2502,7 @@ where token: Token, proof: PaymentProof, ) -> Result<(bool, bool), Error> { - Owner::verify_payment_proof(self, (&token.keychain_mask).as_ref(), &proof) + Owner::verify_payment_proof(self, token.keychain_mask.as_ref(), &proof) } fn set_tor_config(&self, tor_config: Option) -> Result<(), Error> { @@ -2563,7 +2516,7 @@ where features: OutputFeatures, amount: Amount, ) -> Result { - Owner::build_output(self, (&token.keychain_mask).as_ref(), features, amount.0) + Owner::build_output(self, token.keychain_mask.as_ref(), features, amount.0) } fn create_mwixnet_req( @@ -2574,8 +2527,7 @@ where lock_output: bool, server_keys: Vec, ) -> Result { - let commit = - Commitment::from_vec(from_hex(&commitment).map_err(|e| Error::CommitDeser(e))?); + let commit = Commitment::from_vec(from_hex(&commitment).map_err(Error::CommitDeser)?); let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); @@ -2584,7 +2536,7 @@ where for key in server_keys { keys.push(SecretKey::from_slice( &secp, - &grin_util::from_hex(&key).map_err(|e| Error::ServerKeyDeser(e))?, + &grin_util::from_hex(&key).map_err(Error::ServerKeyDeser)?, )?) } @@ -2597,7 +2549,7 @@ where Owner::create_mwixnet_req( self, - (&token.keychain_mask).as_ref(), + token.keychain_mask.as_ref(), &req_params, &commit, lock_output, @@ -2730,19 +2682,14 @@ pub fn run_doctest_owner( let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 1 as usize, + mask1.as_ref(), + 1_usize, false, ); //update local outputs after each block, so transaction IDs stay consistent - let (wallet_refreshed, _) = api_impl::owner::retrieve_summary_info( - wallet1.clone(), - (&mask1).as_ref(), - &None, - true, - 1, - ) - .unwrap(); + let (wallet_refreshed, _) = + api_impl::owner::retrieve_summary_info(wallet1.clone(), mask1.as_ref(), &None, true, 1) + .unwrap(); assert!(wallet_refreshed); } @@ -2769,25 +2716,24 @@ pub fn run_doctest_owner( payment_proof_recipient_address: proof_address, ..Default::default() }; - let mut slate = api_impl::owner::init_send_tx(w, (&mask1).as_ref(), args, true).unwrap(); + let mut slate = api_impl::owner::init_send_tx(w, mask1.as_ref(), args, true).unwrap(); println!("INITIAL SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); { let mut w_lock = wallet2.lock(); let w2 = w_lock.lc_provider().unwrap().wallet_inst().unwrap(); - slate = - api_impl::foreign::receive_tx(w2, (&mask2).as_ref(), &slate, None, true).unwrap(); + slate = api_impl::foreign::receive_tx(w2, mask2.as_ref(), &slate, None, true).unwrap(); w2.close().unwrap(); } // Spit out slate for input to finalize_tx if lock_tx { println!("LOCKING TX"); - api_impl::owner::tx_lock_outputs(w, (&mask1).as_ref(), &slate).unwrap(); + api_impl::owner::tx_lock_outputs(w, mask1.as_ref(), &slate).unwrap(); } println!("RECEIPIENT SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); if finalize_tx { - slate = api_impl::owner::finalize_tx(w, (&mask1).as_ref(), &slate).unwrap(); + slate = api_impl::owner::finalize_tx(w, mask1.as_ref(), &slate).unwrap(); error!("FINALIZED TX SLATE"); println!("{}", serde_json::to_string_pretty(&slate).unwrap()); } @@ -2803,8 +2749,8 @@ pub fn run_doctest_owner( let _ = test_framework::award_blocks_to_wallet( &chain, wallet1.clone(), - (&mask1).as_ref(), - 3 as usize, + mask1.as_ref(), + 3_usize, false, ); } diff --git a/api/src/types.rs b/api/src/types.rs index 797901a..d2503dc 100644 --- a/api/src/types.rs +++ b/api/src/types.rs @@ -18,7 +18,6 @@ use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::{from_hex, ToHex}; use ed25519_dalek::SigningKey as DalekSecretKey; -use base64; use rand::{thread_rng, Rng}; use ring::aead; use serde_json::{self, Value}; @@ -90,8 +89,10 @@ impl EncryptedBody { aad, &mut to_encrypt, ); - if let Err(_) = res { - return Err(Error::APIEncryption("EncryptedBody: encryption failed".to_owned()).into()); + if res.is_err() { + return Err(Error::APIEncryption( + "EncryptedBody: encryption failed".to_owned(), + )); } Ok(EncryptedBody { @@ -129,8 +130,7 @@ impl EncryptedBody { if nonce.len() < 12 { return Err(Error::APIEncryption( "EncryptedBody Dec: Invalid Nonce length".to_string(), - ) - .into()); + )); } let mut n = [0u8; 12]; n.copy_from_slice(&nonce[0..12]); @@ -139,8 +139,10 @@ impl EncryptedBody { let aad = aead::Aad::from(&[]); let res = opening_key.open_in_place(aead::Nonce::assume_unique_for_key(n), aad, &mut to_decrypt); - if let Err(_) = res { - return Err(Error::APIEncryption("EncryptedBody: decryption failed".to_owned()).into()); + if res.is_err() { + return Err(Error::APIEncryption( + "EncryptedBody: decryption failed".to_owned(), + )); } for _ in 0..aead::AES_256_GCM.tag_len() { to_decrypt.pop(); @@ -148,8 +150,8 @@ impl EncryptedBody { let decrypted = String::from_utf8(to_decrypt) .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid UTF-8".to_string()))?; - Ok(serde_json::from_str(&decrypted) - .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid JSON".to_string()))?) + serde_json::from_str(&decrypted) + .map_err(|_| Error::APIEncryption("EncryptedBody Dec: Invalid JSON".to_string())) } } @@ -275,9 +277,9 @@ impl EncryptionErrorResponse { pub fn new(id: u64, code: i32, message: &str) -> Self { EncryptionErrorResponse { jsonrpc: "2.0".to_owned(), - id: id, + id, error: EncryptionError { - code: code, + code, message: message.to_owned(), }, } diff --git a/api/tests/slate_versioning.rs b/api/tests/slate_versioning.rs index ede8453..83e0d25 100644 --- a/api/tests/slate_versioning.rs +++ b/api/tests/slate_versioning.rs @@ -15,7 +15,6 @@ //use grin_wallet_api::foreign_rpc_client; use grin_wallet_api::run_doctest_foreign; //use grin_wallet_libwallet::VersionedSlate; -use serde_json; use serde_json::Value; use tempfile::tempdir; //use grin_wallet_libwallet::slate_versions::v1::SlateV1; diff --git a/config/src/config.rs b/config/src/config.rs index c32a5bb..1407373 100644 --- a/config/src/config.rs +++ b/config/src/config.rs @@ -170,13 +170,13 @@ pub fn get_wallet_path( // A - Detect grin-wallet.toml in working dir let mut config_path = env::current_dir()?; config_path.push(WALLET_CONFIG_FILE_NAME); - if create_path == false && config_path.exists() { + if !create_path && config_path.exists() { config_path.pop(); println!("Detected 'grin-wallet.toml' in working dir - opening associated wallet"); return Ok(config_path); }; // B - Select home directory - let mut wallet_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut wallet_path = dirs::home_dir().unwrap_or_default(); wallet_path.push(GRIN_HOME); wallet_path.push(chain_type.shortname()); // Create if the default path doesn't exist @@ -199,7 +199,7 @@ pub fn get_node_path( data_path: Option, chain_type: &global::ChainTypes, ) -> Result { - let node_path = match data_path { + match data_path { // 1) A If top dir provided and api_secret exist, return top dir Some(path) => { let mut node_path = path; @@ -211,7 +211,7 @@ pub fn get_node_path( Ok(node_path) // 1) B If top dir exists, but no api_secret, return home dir } else { - let mut node_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut node_path = dirs::home_dir().unwrap_or_default(); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) @@ -219,13 +219,12 @@ pub fn get_node_path( } // 2) If there is no top_dir provided, always return home dir None => { - let mut node_path = dirs::home_dir().unwrap_or_else(|| PathBuf::new()); + let mut node_path = dirs::home_dir().unwrap_or_default(); node_path.push(GRIN_HOME); node_path.push(chain_type.shortname()); Ok(node_path) } - }; - node_path + } } /// Checks if config in current working dir @@ -297,10 +296,10 @@ fn check_api_secret_file( /// Initial wallet setup does the following /// 1) Load wallet config if run without 'init' 2) create wallet if run with 'init' -/// Try in this order: -/// a) current dir as template, -/// b) in top path, or -/// c) .grin home +/// Try in this order: +/// a) current dir as template, +/// b) in top path, or +/// c) .grin home /// - load default config values /// - update the wallet and node dir to the correct paths /// - if grin-wallet.toml exists, but the wallet data dir does not, load config and continue wallet generation @@ -371,7 +370,7 @@ pub fn initial_setup_wallet( // Return config if not run with init true => { // If run with init and seed do not yet exists, continue, else throw error - if data_dir.exists() && create_path == true { + if data_dir.exists() && create_path { let msg = format!( "{} already exists in the target directory ({}). Please remove it first", config_path.to_str().unwrap(), @@ -409,9 +408,9 @@ impl Default for GlobalWalletConfigMembers { impl GlobalWalletConfig { /// Same as GlobalConfig::default() but further tweaks parameters to /// apply defaults for each chain type - pub fn for_chain(chain_type: &global::ChainTypes, file_path: &PathBuf) -> GlobalWalletConfig { + pub fn for_chain(chain_type: &global::ChainTypes, file_path: &Path) -> GlobalWalletConfig { let mut defaults_conf = GlobalWalletConfig { - config_file_path: file_path.clone(), + config_file_path: file_path.to_path_buf(), members: GlobalWalletConfigMembers::default(), }; let defaults = &mut defaults_conf.members.wallet; @@ -484,7 +483,7 @@ impl GlobalWalletConfig { } /// Update paths - pub fn update_paths(&mut self, wallet_home: &PathBuf, node_home: &Path) { + pub fn update_paths(&mut self, wallet_home: &Path, node_home: &Path) { let mut data_file_dir = wallet_home.to_path_buf(); let mut node_secret_path = node_home.to_path_buf(); let mut secret_path = wallet_home.to_path_buf(); diff --git a/config/src/types.rs b/config/src/types.rs index bf33a57..624e45f 100644 --- a/config/src/types.rs +++ b/config/src/types.rs @@ -112,7 +112,7 @@ impl WalletConfig { /// Accept fee base pub fn accept_fee_base(&self) -> u64 { self.accept_fee_base - .unwrap_or_else(|| WalletConfig::default_accept_fee_base()) + .unwrap_or_else(WalletConfig::default_accept_fee_base) } /// Node API requests timeout. @@ -249,7 +249,7 @@ impl TorConfig { } /// Tor Bridge Config -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorBridgeConfig { /// Path to bridge binary to use with integrated Tor library pub bridge_bin_path: Option, @@ -259,16 +259,6 @@ pub struct TorBridgeConfig { pub client_option: Option, } -impl Default for TorBridgeConfig { - fn default() -> TorBridgeConfig { - TorBridgeConfig { - bridge_bin_path: None, - bridge_line: None, - client_option: None, - } - } -} - impl fmt::Display for TorBridgeConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) @@ -276,7 +266,7 @@ impl fmt::Display for TorBridgeConfig { } /// Tor Proxy configuration (useful for protocols such as shadowsocks) -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorProxyConfig { /// socks4 |socks5 | http(s) pub transport: Option, @@ -290,18 +280,6 @@ pub struct TorProxyConfig { pub allowed_port: Option>, } -impl Default for TorProxyConfig { - fn default() -> TorProxyConfig { - TorProxyConfig { - transport: None, - address: None, - username: None, - password: None, - allowed_port: None, - } - } -} - impl fmt::Display for TorProxyConfig { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) diff --git a/controller/src/command.rs b/controller/src/command.rs index b3e3146..54abd74 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -120,7 +120,7 @@ where Ok(()) } -pub fn rewind_hash<'a, L, C, K>( +pub fn rewind_hash( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, ) -> Result<(), Error> @@ -159,7 +159,7 @@ where let tip_height = owner_api.node_height(None)?.height; let start_height = match args.backwards_from_tip { Some(b) => tip_height.saturating_sub(b), - None => args.start_height.unwrap_or_else(|| 1), + None => args.start_height.unwrap_or(1), }; warn!( "Starting view wallet output scan from height {} ...", @@ -184,6 +184,7 @@ where } } +#[allow(clippy::too_many_arguments)] pub fn listen( owner_api: &mut Owner, keychain_mask: Arc>>, @@ -222,7 +223,7 @@ where if let Ok(t) = api_thread { if !cli_mode { let r = t.join(); - if let Err(_) = r { + if r.is_err() { error!("Error starting listener"); return Err(Error::ListenerError); } @@ -424,11 +425,11 @@ where init_args = max_retry_args(init_args, amount, max_inputs); owner_api.init_send_tx(keychain_mask, init_args)? } else { - return Err(grin_wallet_libwallet::Error::from(e)); + return Err(e); } } _ => { - return Err(grin_wallet_libwallet::Error::from(e)); + return Err(e); } }, }; @@ -459,20 +460,15 @@ where }; let init_send_tx = |init_args: InitTxArgs| -> Result { let result = owner_api.init_send_tx(keychain_mask, init_args.clone()); - let slate = match result { - Ok(s) => { - info!( - "Tx created: {} grin to {} (strategy '{}')", - core::amount_to_hr_string(init_args.amount, false), - dest.as_ref() - .map(ToString::to_string) - .unwrap_or_else(|| "no destination".to_string()), - args.selection_strategy, - ); - s - } - Err(e) => return Err(e), - }; + let slate = result?; + info!( + "Tx created: {} grin to {} (strategy '{}')", + core::amount_to_hr_string(init_args.amount, false), + dest.as_ref() + .map(ToString::to_string) + .unwrap_or_else(|| "no destination".to_string()), + args.selection_strategy, + ); Ok(slate) }; slate = match init_send_tx(init_args.clone()) { @@ -561,6 +557,7 @@ where Ok(()) } +#[allow(clippy::too_many_arguments)] pub fn output_slatepack( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, @@ -582,7 +579,7 @@ where Some(a) => vec![a], None => vec![], }; - let message = owner_api.create_slatepack_message(keychain_mask, &slate, Some(0), recipients)?; + let message = owner_api.create_slatepack_message(keychain_mask, slate, Some(0), recipients)?; let tld = owner_api.get_top_level_directory()?; // create a directory to which files will be output @@ -594,12 +591,12 @@ where }; if lock { - owner_api.tx_lock_outputs(keychain_mask, &slate)?; + owner_api.tx_lock_outputs(keychain_mask, slate)?; } println!("{}", out_file_name); let mut output = File::create(out_file_name.clone())?; - output.write_all(&message.as_bytes())?; + output.write_all(message.as_bytes())?; output.sync_all()?; println!(); @@ -695,7 +692,7 @@ where } None => { let msg = "No slate provided via file or direct input"; - return Err(Error::GenericError(msg.into()).into()); + return Err(Error::GenericError(msg.into())); } } } @@ -752,10 +749,7 @@ where _ => {} } - let km = match keychain_mask.as_ref() { - None => None, - Some(&m) => Some(m.to_owned()), - }; + let km = keychain_mask.as_ref().map(|&m| m.to_owned()); if let Some(b) = args.bridge { tor_config.bridge.bridge_line = Some(b); @@ -830,7 +824,7 @@ pub fn read_slatepack(args: ReceiveArgs) -> Result { None => match args.input_slatepack_message { Some(message) => packer.deser_slatepack(message.as_bytes(), false)?, None => { - return Err(Error::ArgumentError("Invalid Slatepack Input".into()).into()); + return Err(Error::ArgumentError("Invalid Slatepack Input".into())); } }, }; @@ -942,10 +936,7 @@ where let is_invoice = slate.state == SlateState::Invoice2; if is_invoice { - let km = match keychain_mask.as_ref() { - None => None, - Some(&m) => Some(m.to_owned()), - }; + let km = keychain_mask.as_ref().map(|&m| m.to_owned()); controller::foreign_single_use( owner_api.wallet_inst.clone(), owner_api.config_path(), @@ -1258,7 +1249,7 @@ where // Note advanced query args not currently supported by command line client let (validated, txs) = owner_api.retrieve_txs(keychain_mask, true, args.id, args.tx_slate_id, None)?; - let include_status = !args.id.is_some() && !args.tx_slate_id.is_some(); + let include_status = args.id.is_none() && args.tx_slate_id.is_none(); // If view count is specified, restrict the TX list to `txs.len() - count` let first_tx = args .count @@ -1455,7 +1446,7 @@ where let tip_height = owner_api.node_height(keychain_mask)?.height; let start_height = match args.backwards_from_tip { Some(b) => tip_height.saturating_sub(b), - None => args.start_height.unwrap_or_else(|| 1), + None => args.start_height.unwrap_or(1), }; warn!("Starting output scan from height {} ...", start_height); let result = owner_api.scan(keychain_mask, Some(start_height), args.delete_unconfirmed); diff --git a/controller/src/controller.rs b/controller/src/controller.rs index 49fa040..6e5ad91 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -21,8 +21,8 @@ use crate::impls::tor::process as tor_process; use crate::impls::tor::{bridge as tor_bridge, proxy as tor_proxy}; use crate::keychain::Keychain; use crate::libwallet::{ - address, Error, NodeClient, NodeVersionInfo, Slate, SlatepackAddress, WalletInst, - WalletLCProvider, GRIN_BLOCK_HEADER_VERSION, + address, Error, NodeClient, NodeVersionInfo, Slate, SlatepackAddress, WalletLCProvider, + GRIN_BLOCK_HEADER_VERSION, }; use crate::util::secp::key::SecretKey; use crate::util::{from_hex, static_secp_instance, to_base64, Mutex}; @@ -102,29 +102,23 @@ fn init_tor_listener( let mut hm_tor_bridge: HashMap = HashMap::new(); if tor_config.bridge.bridge_line.is_some() { let bridge_config = tor_bridge::TorBridge::try_from(tor_config.bridge) - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; hm_tor_bridge = bridge_config .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; } let mut hm_tor_poxy: HashMap = HashMap::new(); if tor_config.proxy.transport.is_some() || tor_config.proxy.allowed_port.is_some() { let proxy_config = tor_proxy::TorProxy::try_from(tor_config.proxy) - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; hm_tor_poxy = proxy_config .to_hashmap() - .map_err(|e| Error::TorConfig(format!("{}", e).into()))?; + .map_err(|e| Error::TorConfig(format!("{}", e)))?; } - tor_config::output_tor_listener_config( - &tor_dir, - addr, - &vec![sec_key], - hm_tor_bridge, - hm_tor_poxy, - ) - .map_err(|e| Error::TorConfig(format!("{:?}", e).into()))?; + tor_config::output_tor_listener_config(&tor_dir, addr, &[sec_key], hm_tor_bridge, hm_tor_poxy) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; // Start TOR process process .torrc_path(&format!("{}/torrc", tor_dir)) @@ -139,7 +133,7 @@ fn init_tor_listener( /// Instantiate wallet Foreign API for a single-use (command line) call /// Return a function containing a loaded API context to call pub fn foreign_single_use<'a, L, F, C, K>( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, config_path: PathBuf, keychain_mask: Option, f: F, @@ -179,9 +173,9 @@ where K: Keychain + 'static, { let mut router = Router::new(); - if api_secret.is_some() { + if let Some(api_secret) = api_secret { let api_basic_auth = - "Basic ".to_string() + &to_base64(&("grin:".to_string() + &api_secret.unwrap())); + "Basic ".to_string() + &to_base64(&("grin:".to_string() + &api_secret)); let basic_auth_middleware = Arc::new(BasicAuthMiddleware::new( api_basic_auth, &GRIN_OWNER_BASIC_REALM, @@ -231,8 +225,9 @@ where /// Listener version, providing same API but listening for requests on a /// port and wrapping the calls +#[allow(clippy::too_many_arguments)] pub fn foreign_listener( - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: PathBuf, bridge: Option, use_tor: Option, @@ -258,7 +253,7 @@ where let mut w_lock = wallet.lock(); let lc = w_lock.lc_provider()?; let w_inst = lc.wallet_inst()?; - let k = w_inst.keychain((&mask).as_ref())?; + let k = w_inst.keychain(mask.as_ref())?; let parent_key_id = w_inst.parent_key_id(); let sec_key = address::address_from_derivation_path(&k, &parent_key_id, 0) .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; @@ -400,7 +395,7 @@ where K: Keychain + 'static, { /// Wallet instance - pub wallet: Arc + 'static>>>, + pub wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Handle to Owner API owner_api: Arc>, @@ -462,7 +457,7 @@ impl OwnerV3Helpers { val: &serde_json::Value, new_key: Option, ) { - if let Some(_) = val["result"]["Ok"].as_str() { + if val["result"]["Ok"].as_str().is_some() { let mut share_key_ref = key.lock(); *share_key_ref = new_key; } @@ -503,7 +498,7 @@ impl OwnerV3Helpers { .as_json_value() })?; let id = enc_req.id.clone(); - let res = enc_req.decrypt(&shared_key).map_err(|e| { + let res = enc_req.decrypt(shared_key).map_err(|e| { EncryptionErrorResponse::new(1, -32002, &format!("Decryption error: {}", e)) .as_json_value() })?; @@ -518,7 +513,7 @@ impl OwnerV3Helpers { ) -> Result { let share_key_ref = key.lock(); let shared_key = share_key_ref.as_ref().unwrap(); - let enc_res = EncryptedResponse::from_json(id, res, &shared_key).map_err(|e| { + let enc_res = EncryptedResponse::from_json(id, res, shared_key).map_err(|e| { EncryptionErrorResponse::new(1, -32003, &format!("EncryptionError: {}", e)) .as_json_value() })?; @@ -576,10 +571,7 @@ impl OwnerV3Helpers { retval } else if val["result"]["Err"].is_string() { let parsed = serde_json::from_value::(val["result"]["Err"].clone()); - match parsed { - Ok(p) => Some(p), - Err(_) => None, - } + parsed.ok() } else { None }; @@ -737,7 +729,7 @@ where K: Keychain + 'static, { /// Wallet instance. - pub wallet: Arc + 'static>>>, + pub wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, /// Wallet configuration path. pub config_path: ConfigPath, /// Keychain mask @@ -754,7 +746,7 @@ where { /// Create a new foreign API handler for GET methods pub fn new( - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: ConfigPath, keychain_mask: Arc>>, test_mode: bool, @@ -785,7 +777,7 @@ where async fn handle_post_request( req: Request, mask: Option, - wallet: Arc + 'static>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config_path: ConfigPath, test_mode: bool, ) -> Result, Error> { diff --git a/controller/src/display.rs b/controller/src/display.rs index 9ed991f..44e598f 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -62,7 +62,7 @@ pub fn outputs( ]); for m in outputs { - let commit = format!("{}", m.commit.as_ref().to_hex()); + let commit = m.commit.as_ref().to_hex(); let index = match m.output.mmr_index { None => "None".to_owned(), Some(t) => t.to_string(), @@ -78,7 +78,7 @@ pub fn outputs( }; let num_confirmations = format!("{}", m.output.num_confirmations(cur_height)); - let value = format!("{}", amount_to_hr_string(m.output.value, false)); + let value = amount_to_hr_string(m.output.value, false); let tx = match m.output.tx_log_entry { None => "".to_owned(), Some(t) => t.to_string(), @@ -196,7 +196,7 @@ pub fn txs( let amount_debited_str = amount_to_hr_string(t.amount_debited, true); let amount_credited_str = amount_to_hr_string(t.amount_credited, true); let fee = match t.fee { - Some(f) => format!("{}", amount_to_hr_string(f.fee(), true)), + Some(f) => amount_to_hr_string(f.fee(), true), None => "None".to_owned(), }; let net_diff = if t.amount_credited >= t.amount_debited { @@ -297,24 +297,17 @@ pub fn txs( Ok(()) } -pub fn view_wallet_balance(w: ViewWallet, cur_height: u64, dark_background_color_scheme: bool) { +pub fn view_wallet_balance(w: ViewWallet, cur_height: u64, _dark_background_color_scheme: bool) { println!( "\n____ View Wallet Summary Info - Block Height: {} ____\n Rewind Hash - {}\n", cur_height, w.rewind_hash ); let mut table = table!(); - if dark_background_color_scheme { - table.add_row(row![ - bFG->"Total Balance", - FG->amount_to_hr_string(w.total_balance, false) - ]); - } else { - table.add_row(row![ - bFG->"Total Balance", - FG->amount_to_hr_string(w.total_balance, false) - ]); - }; + table.add_row(row![ + bFG->"Total Balance", + FG->amount_to_hr_string(w.total_balance, false) + ]); table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.printstd(); println!(); @@ -351,13 +344,13 @@ pub fn view_wallet_output( ]); for m in view_wallet.output_result { - let commit = format!("{}", m.commit); + let commit = m.commit.as_str(); let index = m.mmr_index; let height = format!("{}", m.height); let lock_height = format!("{}", m.lock_height); let is_coinbase = format!("{}", m.is_coinbase); let num_confirmations = format!("{}", m.num_confirmations(cur_height)); - let value = format!("{}", amount_to_hr_string(m.value, false)); + let value = amount_to_hr_string(m.value, false); if dark_background_color_scheme { table.add_row(row![ @@ -612,10 +605,7 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { let amount = if tx.amount_credited >= tx.amount_debited { amount_to_hr_string(tx.amount_credited - tx.amount_debited, true) } else { - format!( - "{}", - amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) - ) + amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) }; let sender_signature = match pp.sender_signature { diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index f1dcbe1..6b1f421 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -52,7 +52,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -66,7 +66,7 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/build_chain.rs b/controller/tests/build_chain.rs index 12210e8..35fa286 100644 --- a/controller/tests/build_chain.rs +++ b/controller/tests/build_chain.rs @@ -50,7 +50,7 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); debug!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -63,7 +63,7 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); debug!("Mask2: {:?}", mask2); // Set the wallet proxy listener running diff --git a/controller/tests/build_output.rs b/controller/tests/build_output.rs index 798732d..eaf6bd6 100644 --- a/controller/tests/build_output.rs +++ b/controller/tests/build_output.rs @@ -55,7 +55,7 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/check.rs b/controller/tests/check.rs index 6d7fbdb..4d172e2 100644 --- a/controller/tests/check.rs +++ b/controller/tests/check.rs @@ -68,7 +68,7 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -80,7 +80,7 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -223,7 +223,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, _m_api ); - let miner_mask = (&miner_mask_i).as_ref(); + let miner_mask = miner_mask_i.as_ref(); // non-mining recipient wallets create_wallet_and_add!( @@ -237,7 +237,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -249,7 +249,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, _api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // we'll restore into here create_wallet_and_add!( client3, @@ -262,7 +262,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api3 ); - let mask3 = (&mask3_i).as_ref(); + let mask3 = mask3_i.as_ref(); // also restore into here create_wallet_and_add!( client4, @@ -275,7 +275,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api4 ); - let mask4 = (&mask4_i).as_ref(); + let mask4 = mask4_i.as_ref(); // Simulate a recover from seed without restore into here create_wallet_and_add!( client5, @@ -289,7 +289,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er api5 ); //simulate a recover from seed without restore into here - let mask5 = (&mask5_i).as_ref(); + let mask5 = mask5_i.as_ref(); create_wallet_and_add!( client6, wallet6, @@ -301,7 +301,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api6 ); - let mask6 = (&mask6_i).as_ref(); + let mask6 = mask6_i.as_ref(); create_wallet_and_add!( client7, @@ -314,7 +314,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api7 ); - let mask7 = (&mask7_i).as_ref(); + let mask7 = mask7_i.as_ref(); create_wallet_and_add!( client8, wallet8, @@ -326,7 +326,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api8 ); - let mask8 = (&mask8_i).as_ref(); + let mask8 = mask8_i.as_ref(); create_wallet_and_add!( client9, wallet9, @@ -338,7 +338,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api9 ); - let mask9 = (&mask9_i).as_ref(); + let mask9 = mask9_i.as_ref(); create_wallet_and_add!( client10, wallet10, @@ -350,7 +350,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er false, api10 ); - let mask10 = (&mask10_i).as_ref(); + let mask10 = mask10_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -380,7 +380,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er miner_mask, m_client.clone(), "wallet1", - base_amount * 1 + base_amount )?; send_to_dest!( miner.clone(), @@ -579,7 +579,7 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er miner_mask, m_client.clone(), "wallet7", - base_amount * 1 + base_amount )?; send_to_dest!( miner.clone(), @@ -710,7 +710,7 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> false, _api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); @@ -795,7 +795,7 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { @@ -886,7 +886,7 @@ fn restore_corrupted_outputs_across_batches_impl( false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); thread::spawn(move || { if let Err(e) = wallet_proxy.run() { diff --git a/controller/tests/common/mod.rs b/controller/tests/common/mod.rs index 716b79e..c11b645 100644 --- a/controller/tests/common/mod.rs +++ b/controller/tests/common/mod.rs @@ -109,6 +109,7 @@ pub fn create_wallet_proxy( WalletProxy::new(test_dir) } +#[allow(clippy::type_complexity)] pub fn create_local_wallet( test_dir: &str, name: &str, @@ -116,17 +117,11 @@ pub fn create_local_wallet( client: LocalWalletClient, create_mask: bool, ) -> ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, Owner, LocalWalletClient, ExtKeychain>, @@ -178,17 +173,11 @@ pub fn open_local_wallet( client: LocalWalletClient, create_mask: bool, ) -> ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, ) { diff --git a/controller/tests/file.rs b/controller/tests/file.rs index b768080..6f6d445 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -53,7 +53,7 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -65,7 +65,7 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 4671db0..426306d 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -49,7 +49,7 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -61,7 +61,7 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { true, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index 5624976..dae59a4 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -49,7 +49,7 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -61,7 +61,7 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 04e920c..5e81a35 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -53,7 +53,7 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -135,11 +135,11 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let server_pubkey_str_2 = "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; let server_pubkey_str_3 = "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap())?; + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_1).unwrap())?; let server_key_2 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap())?; + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_2).unwrap())?; let server_key_3 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap())?; + SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_3).unwrap())?; let params = MixnetReqCreationParams { server_keys: vec![server_key_1, server_key_2, server_key_3], fee_per_hop: 50_000_000, diff --git a/controller/tests/no_change.rs b/controller/tests/no_change.rs index 503691e..70b36f9 100644 --- a/controller/tests/no_change.rs +++ b/controller/tests/no_change.rs @@ -48,7 +48,7 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -62,7 +62,7 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index 5c4eeaf..51bb034 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -48,7 +48,7 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -62,7 +62,7 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 2eccce9..6ad6b3d 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -52,7 +52,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -64,7 +64,7 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/revert.rs b/controller/tests/revert.rs index 6c4c8a6..abd27af 100644 --- a/controller/tests/revert.rs +++ b/controller/tests/revert.rs @@ -23,32 +23,25 @@ use grin_core::core::Transaction; use grin_core::global; use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; -use grin_util::Mutex; use grin_wallet_api::Owner; use grin_wallet_impls::test_framework::*; use grin_wallet_impls::{DefaultLCProvider, PathToSlate, SlatePutter}; use grin_wallet_libwallet as libwallet; use grin_wallet_libwallet::api_impl::types::InitTxArgs; -use grin_wallet_libwallet::WalletInst; use log::error; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; -type Wallet = Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, +type Wallet = grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >; +#[allow(clippy::type_complexity)] fn revert( test_dir: &'static str, ) -> Result< @@ -189,8 +182,13 @@ fn revert( // Build 2 blocks at same height: 1 with the tx, 1 without let head = chain.head_header().unwrap(); - let block_with = - create_block_for_wallet(&chain, head.clone(), &[tx.clone()], wallet1.clone(), mask1)?; + let block_with = create_block_for_wallet( + &chain, + head.clone(), + std::slice::from_ref(&tx), + wallet1.clone(), + mask1, + )?; let block_without = create_block_for_wallet(&chain, head, &[], wallet1.clone(), mask1)?; // Add block with tx to the chain diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index 424d31a..d7ce466 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -51,7 +51,7 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index 21023f4..b7fb10f 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -57,7 +57,7 @@ fn output_slatepack( if armored { file = format!("{}.armored", file); } - PathToSlatepack::new(file.into(), &packer, armored).put_tx(&slate, use_bin) + PathToSlatepack::new(file.into(), &packer, armored).put_tx(slate, use_bin) } fn slate_from_packed( @@ -103,7 +103,7 @@ fn slatepack_exchange_test_impl( false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -115,7 +115,7 @@ fn slatepack_exchange_test_impl( false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -217,7 +217,7 @@ fn slatepack_exchange_test_impl( } let (mut slatepack, mut slate) = - slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; + slate_from_packed(&send_file, use_armored, dec_key_2.as_ref())?; // wallet 2 receives file, completes, sends file back wallet::controller::foreign_single_use( @@ -243,7 +243,7 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - let (_, mut slate) = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + let (_, mut slate) = slate_from_packed(&receive_file, use_armored, dec_key_1.as_ref())?; slate = api1.finalize_tx(mask1, &slate)?; // Output final file for reference output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; @@ -303,7 +303,7 @@ fn slatepack_exchange_test_impl( selection_strategy_is_use_all: true, ..Default::default() }; - let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; + let res = slate_from_packed(&send_file, use_armored, dec_key_1.as_ref())?; slatepack = res.0; slate = res.1; slate = api1.process_invoice_tx(mask1, &slate, args)?; @@ -325,7 +325,7 @@ fn slatepack_exchange_test_impl( mask2_i.clone(), |api| { // Wallet 2 receives the invoice transaction - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_2).as_ref())?; + let res = slate_from_packed(&receive_file, use_armored, dec_key_2.as_ref())?; slate = res.1; slate = api.finalize_tx(&slate, false)?; output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; @@ -378,7 +378,7 @@ fn slatepack_exchange_test_impl( PathBuf::from(test_dir), mask2_i.clone(), |api| { - let res = slate_from_packed(&send_file, use_armored, (&dec_key_2).as_ref())?; + let res = slate_from_packed(&send_file, use_armored, dec_key_2.as_ref())?; let slatepack = res.0; slate = res.1; slate = api.receive_tx(&slate, None, None)?; @@ -398,7 +398,7 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + let res = slate_from_packed(&receive_file, use_armored, dec_key_1.as_ref())?; slate = res.1; slate = api1.finalize_tx(mask1, &slate)?; // Output final file for reference @@ -432,7 +432,7 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -494,7 +494,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -507,7 +507,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); let proxy_thread = thread::spawn(move || { if let Err(e) = wallet_proxy.run() { diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 6613095..7a0e514 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -56,7 +56,7 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); println!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -69,7 +69,7 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); println!("Mask2: {:?}", mask2); // Set the wallet proxy listener running @@ -530,7 +530,7 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -542,7 +542,7 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { @@ -592,10 +592,10 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { api1.retrieve_outputs(mask1, true, false, Some(tx.unwrap().id))?; for m in output_mappings.clone() { if m.output.status == OutputStatus::Locked { - locked_count = locked_count + 1; + locked_count += 1; } if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; + unconfirmed_count += 1; } } assert_eq!(output_mappings.len(), 3); @@ -614,7 +614,7 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { let (_, outputs) = api2.retrieve_outputs(mask2, true, false, Some(tx.unwrap().id))?; for m in outputs.clone() { if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; + unconfirmed_count += 1; } } assert_eq!(outputs.len(), 1); @@ -697,7 +697,7 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); println!("Mask1: {:?}", mask1); // Set the wallet proxy listener running @@ -762,16 +762,15 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { match result { Ok(_) => {} - Err(e) => match e { - libwallet::Error::BigAmountError(a, fee, num_inputs) => { + Err(e) => { + if let libwallet::Error::BigAmountError(a, fee, num_inputs) = e { let (_, e_a, e_fee, e_num_inputs) = api1.estimate_max_sendable(mask1, true, min_confirmations)?; assert_eq!(e_a, a - fee); assert_eq!(e_fee, fee); assert_eq!(e_num_inputs, num_inputs); } - _ => {} - }, + } } // let logging finish diff --git a/controller/tests/ttl_cutoff.rs b/controller/tests/ttl_cutoff.rs index 4c9bd12..d8e70d7 100644 --- a/controller/tests/ttl_cutoff.rs +++ b/controller/tests/ttl_cutoff.rs @@ -48,7 +48,7 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, @@ -62,7 +62,7 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index cc63c15..1536bcc 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -50,10 +50,11 @@ fn test_wallet_tx_filtering( assert!(!txs.is_empty()); let before_first_tx = txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); - let mut tx_query_args = RetrieveTxQueryArgs::default(); - // Max creation time before all test transactions - tx_query_args.max_creation_timestamp = Some(before_first_tx); + let mut tx_query_args = RetrieveTxQueryArgs { + max_creation_timestamp: Some(before_first_tx), + ..Default::default() + }; assert!(query(tx_query_args.clone())?.is_empty()); // Min confirmation time should not affect creation time @@ -61,8 +62,10 @@ fn test_wallet_tx_filtering( tx_query_args.min_confirmed_timestamp = Some(before_first_tx); assert_eq!(query(tx_query_args)?.len(), txs.len()); - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); + let tx_query_args = RetrieveTxQueryArgs { + min_id: Some(5), + ..Default::default() + }; // Min ID let tx_results = api @@ -72,9 +75,11 @@ fn test_wallet_tx_filtering( assert_eq!(tx_results[tx_results.len() - 1].id, 33); // Max ID - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(20); + let tx_query_args = RetrieveTxQueryArgs { + min_id: Some(5), + max_id: Some(20), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; @@ -82,109 +87,133 @@ fn test_wallet_tx_filtering( assert_eq!(tx_results[tx_results.len() - 1].id, 20); // Exclude 1 canceled - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 28); // Exclude 1 canceled, show confirmed only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(true), + include_confirmed_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 14); // show outstanding only (including canceled) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + include_outstanding_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 15); // outstanding only and confirmed only should give empty set - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); + let tx_query_args = RetrieveTxQueryArgs { + exclude_cancelled: Some(false), + include_outstanding_only: Some(true), + include_confirmed_only: Some(true), + min_id: Some(5), + max_id: Some(50), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 0); // include sent only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_sent_only = Some(true); + let tx_query_args = RetrieveTxQueryArgs { + include_sent_only: Some(true), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 15); // include received only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_received_only = Some(true); + let tx_query_args = RetrieveTxQueryArgs { + include_received_only: Some(true), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 0); // include reverted only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_reverted_only = Some(true); + let tx_query_args = RetrieveTxQueryArgs { + include_reverted_only: Some(true), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 0); // include coinbase only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_coinbase_only = Some(true); + let tx_query_args = RetrieveTxQueryArgs { + include_coinbase_only: Some(true), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 19); // Amounts - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000 - 59_963_300_000), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 27); // amount, should see as above with coinbases excluded - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - tx_query_args.max_amount = Some(60_000_000_000 - 1); + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000 - 59_963_300_000), + max_amount: Some(60_000_000_000 - 1), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 8); // Amount - should only see coinbase (incoming) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000); + let tx_query_args = RetrieveTxQueryArgs { + min_amount: Some(60_000_000_000), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; assert_eq!(tx_results.len(), 19); // sort order - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + let tx_query_args = RetrieveTxQueryArgs { + sort_order: Some(libwallet::RetrieveTxQuerySortOrder::Desc), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; @@ -193,9 +222,11 @@ fn test_wallet_tx_filtering( assert_eq!(tx_results[tx_results.len() - 1].id, 0); // change sort field to amount desc, should have coinbases first - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); + let tx_query_args = RetrieveTxQueryArgs { + sort_order: Some(libwallet::RetrieveTxQuerySortOrder::Desc), + sort_field: Some(RetrieveTxQuerySortField::TotalAmount), + ..Default::default() + }; let tx_results = api .retrieve_txs(mask, true, None, None, Some(tx_query_args))? .1; @@ -224,7 +255,7 @@ fn build_chain_for_tx_filtering( true, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); debug!("Mask1: {:?}", mask1); create_wallet_and_add!( client2, @@ -237,7 +268,7 @@ fn build_chain_for_tx_filtering( false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); debug!("Mask2: {:?}", mask2); // Set the wallet proxy listener running diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index cb339b0..52c94db 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -49,7 +49,7 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err false, api1 ); - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); create_wallet_and_add!( client2, wallet2, @@ -61,7 +61,7 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err false, api2 ); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running thread::spawn(move || { diff --git a/grin b/grin index 1425f60..4182d34 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit 1425f603295ba166eccd9e4e0af0226742f90844 +Subproject commit 4182d3422175184d723232d23f85ac4ec6990285 diff --git a/impls/src/adapters/slatepack.rs b/impls/src/adapters/slatepack.rs index 2b04c23..88b6368 100644 --- a/impls/src/adapters/slatepack.rs +++ b/impls/src/adapters/slatepack.rs @@ -111,7 +111,7 @@ mod tests { clean_output_dir(test_dir); } - const SLATEPACK_DIR: &'static str = "target/test_output/slatepack"; + const SLATEPACK_DIR: &str = "target/test_output/slatepack"; #[test] fn pathbuf_get_file_contents() { diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index 63f56c0..b5233fc 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -27,7 +27,7 @@ use serde_json::{json, Value}; use std::collections::HashMap; use std::convert::TryFrom; use std::net::SocketAddr; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; #[derive(Clone)] @@ -65,7 +65,7 @@ impl TorSlateSender { } /// Launch external Tor process. - fn launch_tor_process(config: &TorConfig, tor_dir: &PathBuf) -> Result { + fn launch_tor_process(config: &TorConfig, tor_dir: &Path) -> Result { let mut tor = TorProcess::new(); let socks_proxy_addr = SocketAddr::V4( config @@ -101,7 +101,7 @@ impl TorSlateSender { ) .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; // Start TOR process - let mut path = tor_dir.clone(); + let mut path = tor_dir.to_path_buf(); path.push("torrc"); tor.torrc_path(path.to_str().unwrap()) .working_dir(tor_dir.to_str().unwrap()) @@ -184,8 +184,7 @@ impl TorSlateSender { let client = Client::with_proxy(socks_proxy_addr, "socks5h://", timeout) .map_err(|_| ClientError::Internal("Unable to create http client".into()))?; let req = client.create_post_request(url, None, &input)?; - let res = client.send_request(req)?; - res + client.send_request(req)? } else { tor_post(&self.config, &input, url) .map_err(|e| ClientError::RequestError(format!("{:?}", e)))? diff --git a/impls/src/client_utils/client.rs b/impls/src/client_utils/client.rs index 20e787f..728c3ba 100644 --- a/impls/src/client_utils/client.rs +++ b/impls/src/client_utils/client.rs @@ -19,7 +19,6 @@ use lazy_static::lazy_static; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT}; use reqwest::{ClientBuilder, Method, Proxy, RequestBuilder}; use serde::{Deserialize, Serialize}; -use serde_json; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; @@ -32,6 +31,7 @@ lazy_static! { } #[derive(Clone, Eq, thiserror::Error, PartialEq, Debug)] +#[allow(clippy::enum_variant_names)] pub enum Error { #[error("Internal error: {0}")] Internal(String), @@ -76,7 +76,7 @@ impl Client { if let Some(p) = proxy { let (addr, scheme) = p; - let proxy = Proxy::all(&format!("{}{}:{}", scheme, addr.ip(), addr.port())) + let proxy = Proxy::all(format!("{}{}:{}", scheme, addr.ip(), addr.port())) .map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?; builder = builder.proxy(proxy); } @@ -91,7 +91,7 @@ impl Client { /// Helper function to easily issue a HTTP GET request against a given URL that /// returns a JSON object. Handles request building, JSON deserialization and /// response code checking. - pub fn _get<'a, T>(&self, url: &'a str, api_secret: Option) -> Result + pub fn _get(&self, url: &str, api_secret: Option) -> Result where for<'de> T: Deserialize<'de>, { @@ -101,11 +101,7 @@ impl Client { /// Helper function to easily issue an async HTTP GET request against a given /// URL that returns a future. Handles request building, JSON deserialization /// and response code checking. - pub async fn _get_async<'a, T>( - &self, - url: &'a str, - api_secret: Option, - ) -> Result + pub async fn _get_async(&self, url: &str, api_secret: Option) -> Result where for<'de> T: Deserialize<'de> + Send + 'static, { diff --git a/impls/src/client_utils/json_rpc.rs b/impls/src/client_utils/json_rpc.rs index 06e4465..a125336 100644 --- a/impls/src/client_utils/json_rpc.rs +++ b/impls/src/client_utils/json_rpc.rs @@ -22,7 +22,7 @@ use serde_json; pub fn build_request<'a, 'b>(name: &'a str, params: &'b serde_json::Value) -> Request<'a, 'b> { Request { method: name, - params: params, + params, id: From::from(1), jsonrpc: Some("2.0"), } @@ -133,7 +133,7 @@ impl fmt::Display for Error { write!(f, "duplicate RPC batch response ID: {}", v) } Error::_WrongBatchResponseId(ref v) => write!(f, "wrong RPC batch response ID: {}", v), - ref e => f.write_str(&format!("{}", e)), + ref e => write!(f, "{:?}", e), } } } @@ -217,27 +217,27 @@ pub fn _standard_error(code: StandardError, data: Option) -> StandardError::ParseError => RpcError { code: -32700, message: "Parse error".to_string(), - data: data, + data, }, StandardError::InvalidRequest => RpcError { code: -32600, message: "Invalid Request".to_string(), - data: data, + data, }, StandardError::MethodNotFound => RpcError { code: -32601, message: "Method not found".to_string(), - data: data, + data, }, StandardError::InvalidParams => RpcError { code: -32602, message: "Invalid params".to_string(), - data: data, + data, }, StandardError::InternalError => RpcError { code: -32603, message: "Internal error".to_string(), - data: data, + data, }, } } @@ -251,13 +251,13 @@ pub fn _result_to_response( Ok(data) => Response { result: Some(data), error: None, - id: id, + id, jsonrpc: Some(String::from("2.0")), }, Err(err) => Response { result: None, error: Some(err), - id: id, + id, jsonrpc: Some(String::from("2.0")), }, } diff --git a/impls/src/lifecycle/default.rs b/impls/src/lifecycle/default.rs index ca11687..594f462 100644 --- a/impls/src/lifecycle/default.rs +++ b/impls/src/lifecycle/default.rs @@ -32,9 +32,7 @@ use std::path::MAIN_SEPARATOR; /// Helper function to format paths according to OS, avoids bugs on Linux pub fn fmt_path(path: String) -> String { let sep = &MAIN_SEPARATOR.to_string(); - let path = path.replace("/", &sep); - let path = path.replace("\\", &sep); - path + path.replace("/", sep).replace("\\", sep) } pub struct DefaultLCProvider @@ -77,8 +75,8 @@ where let data_dir = self .data_dir .to_owned() - .replace("/", &sep) - .replace("\\", &sep); + .replace("/", sep) + .replace("\\", sep); Ok(data_dir) } @@ -108,7 +106,7 @@ where return Ok(()); } - let mut default_config = GlobalWalletConfig::for_chain(&chain_type, &config_file_name); + let mut default_config = GlobalWalletConfig::for_chain(chain_type, &config_file_name); let config_file_version = default_config.members.config_file_version; let logging = match logging_config.clone() { Some(l) => Some(l), @@ -140,7 +138,7 @@ where absolute_path_wallet.push(self.data_dir.clone()); // if no config provided, update defaults - if update == true { + if update { // create top level dir if it doesn't exist let dd = PathBuf::from(self.data_dir.clone()); if !dd.exists() { @@ -209,9 +207,9 @@ where let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { Err(e) => { - let msg = format!("Error creating wallet: {}, Data Dir: {}", e, &data_dir_name); + let msg = format!("Error creating wallet: {}, Data Dir: {}", e, data_dir_name); error!("{}", msg); - return Err(Error::Lifecycle(msg).into()); + return Err(Error::Lifecycle(msg)); } Ok(d) => d, }; @@ -239,7 +237,7 @@ where let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { Err(e) => { - let msg = format!("Error opening wallet: {}, Data Dir: {}", e, &data_dir_name); + let msg = format!("Error opening wallet: {}, Data Dir: {}", e, data_dir_name); return Err(Error::Lifecycle(msg)); } Ok(d) => d, @@ -271,7 +269,7 @@ where let mut data_dir_name = PathBuf::from(self.data_dir.clone()); data_dir_name.push(GRIN_WALLET_DIR); let data_dir_name = data_dir_name.to_str().unwrap(); - let res = WalletSeed::seed_file_exists(&data_dir_name) + let res = WalletSeed::seed_file_exists(data_dir_name) .map_err(|_| Error::CallbackImpl("Error checking for wallet existence"))?; Ok(res) } @@ -322,7 +320,7 @@ where data_dir_name.push(GRIN_WALLET_DIR); let data_dir_name = data_dir_name.to_str().unwrap(); // Get seed for later check - let orig_wallet_seed = WalletSeed::from_file(&data_dir_name, old) + let orig_wallet_seed = WalletSeed::from_file(data_dir_name, old) .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; let orig_mnemonic = orig_wallet_seed .to_mnemonic() @@ -348,7 +346,7 @@ where ); info!("Wallet seed file created"); - let new_wallet_seed = WalletSeed::from_file(&data_dir_name, new) + let new_wallet_seed = WalletSeed::from_file(data_dir_name, new) .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; if orig_wallet_seed != new_wallet_seed { @@ -461,7 +459,7 @@ mod tests { .unwrap(); let enc_seed_json = serde_json::to_string_pretty(&enc_seed).unwrap(); let mut file = File::create(seed_file_path).unwrap(); - file.write_all(&enc_seed_json.as_bytes()).unwrap(); + file.write_all(enc_seed_json.as_bytes()).unwrap(); let error = match provider.get_mnemonic(None, password.clone()) { Ok(_) => panic!("expected missing recovery phrase error"), diff --git a/impls/src/lifecycle/seed.rs b/impls/src/lifecycle/seed.rs index 16f924a..09969b3 100644 --- a/impls/src/lifecycle/seed.rs +++ b/impls/src/lifecycle/seed.rs @@ -15,7 +15,6 @@ use crate::blake2; use core::num::NonZeroU32; use rand::{thread_rng, Rng}; -use serde_json; use std::fs::{self, File}; use std::io::{Read, Write}; use std::path::Path; @@ -55,8 +54,8 @@ impl WalletSeed { } pub fn _from_hex(hex: &str) -> Result { - let bytes = util::from_hex(&hex.to_string()) - .map_err(|_| Error::GenericError("Invalid hex".to_owned()))?; + let bytes = + util::from_hex(hex).map_err(|_| Error::GenericError("Invalid hex".to_owned()))?; Ok(WalletSeed::from_bytes(&bytes)) } @@ -136,7 +135,9 @@ impl WalletSeed { } path.push(backup_seed_file_name.clone()); if fs::rename(seed_file_name, backup_seed_file_name.as_str()).is_err() { - return Err(Error::GenericError("Can't rename wallet seed file".to_owned()).into()); + return Err(Error::GenericError( + "Can't rename wallet seed file".to_owned(), + )); } warn!("{} backed up as {}", seed_file_name, backup_seed_file_name); Ok(backup_seed_file_name) @@ -163,14 +164,13 @@ impl WalletSeed { data_file_dir.to_owned(), "To create a new wallet from a recovery phrase, use 'grin-wallet init -r'" .to_owned(), - ) - .into()); + )); } let seed = WalletSeed::from_mnemonic(word_list)?; let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?; let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?; - file.write_all(&enc_seed_json.as_bytes()) + file.write_all(enc_seed_json.as_bytes()) .map_err(|_| Error::IO)?; warn!("Seed created from word list"); Ok(()) @@ -209,7 +209,7 @@ impl WalletSeed { let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; let enc_seed_json = serde_json::to_string_pretty(&enc_seed).map_err(|_| Error::Format)?; let mut file = File::create(seed_file_path).map_err(|_| Error::IO)?; - file.write_all(&enc_seed_json.as_bytes()) + file.write_all(enc_seed_json.as_bytes()) .map_err(|_| Error::IO)?; Ok(seed) } @@ -307,7 +307,7 @@ impl EncryptedWalletSeed { aad, &mut enc_bytes, ); - if let Err(_) = res { + if res.is_err() { return Err(Error::Encryption); } @@ -352,7 +352,7 @@ impl EncryptedWalletSeed { aad, &mut encrypted_seed, ); - if let Err(_) = res { + if res.is_err() { return Err(Error::Encryption); } for _ in 0..aead::AES_256_GCM.tag_len() { diff --git a/impls/src/node_clients/http.rs b/impls/src/node_clients/http.rs index b28a30c..4feba20 100644 --- a/impls/src/node_clients/http.rs +++ b/impls/src/node_clients/http.rs @@ -213,7 +213,7 @@ impl NodeClient for HTTPNodeClient { // build vec of commits for inclusion in query let query_params: Vec = wallet_outputs .iter() - .map(|commit| format!("{}", commit.as_ref().to_hex())) + .map(|commit| commit.as_ref().to_hex()) .collect(); // going to leave this here even though we're moving @@ -276,10 +276,9 @@ impl NodeClient for HTTPNodeClient { }; let rt = RUNTIME.clone(); - let res: Result, _> = - std::thread::spawn(move || rt.block_on(async move { task.await })) - .join() - .unwrap(); + let res: Result, _> = std::thread::spawn(move || rt.block_on(task)) + .join() + .unwrap(); let results: Vec = match res { Ok(resps) => { @@ -338,7 +337,7 @@ impl NodeClient for HTTPNodeClient { let params = json!([start_index, end_index, max_outputs, Some(true)]); let res = self.send_json_request::("get_unspent_outputs", ¶ms)?; // We asked for unspent outputs via the api but defensively filter out spent outputs just in case. - for out in res.outputs.into_iter().filter(|out| out.spent == false) { + for out in res.outputs.into_iter().filter(|out| !out.spent) { let is_coinbase = match out.output_type { api::OutputType::Coinbase => true, api::OutputType::Transaction => false, diff --git a/impls/src/test_framework/mod.rs b/impls/src/test_framework/mod.rs index c90eac5..1191229 100644 --- a/impls/src/test_framework/mod.rs +++ b/impls/src/test_framework/mod.rs @@ -20,12 +20,9 @@ use crate::core::core::{Output, Transaction, TxKernel}; use crate::core::{consensus, global, pow}; use crate::libwallet; use crate::libwallet::api_impl::{foreign, owner}; -use crate::libwallet::{ - BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletInst, WalletLCProvider, -}; +use crate::libwallet::{BlockFees, InitTxArgs, NodeClient, WalletInfo, WalletLCProvider}; use crate::util::secp::key::SecretKey; use crate::util::secp::pedersen; -use crate::util::Mutex; use chrono::Duration; use grin_keychain::Keychain; use std::sync::Arc; @@ -54,7 +51,7 @@ fn get_kernel_local( max_height: Option, ) -> Option { chain - .get_kernel_height(&excess, min_height, max_height) + .get_kernel_height(excess, min_height, max_height) .unwrap() .map(|(tx_kernel, height, mmr_index)| api::LocatedTxKernel { tx_kernel, @@ -147,7 +144,7 @@ pub fn create_block_for_wallet<'a, L, C, K>( chain: &Chain, prev: core::core::BlockHeader, txs: &[Transaction], - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -178,7 +175,7 @@ where pub fn award_block_to_wallet<'a, L, C, K>( chain: &Chain, txs: &[Transaction], - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result<(), libwallet::Error> where @@ -200,7 +197,7 @@ pub fn process_block(chain: &Chain, block: core::core::Block) { /// Award a blocks to a wallet directly pub fn award_blocks_to_wallet<'a, L, C, K>( chain: &Chain, - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, number: usize, pause_between: bool, @@ -221,7 +218,7 @@ where /// send an amount to a destination pub fn send_to_dest<'a, L, C, K>( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, client: LocalWalletClient, dest: &str, @@ -261,7 +258,7 @@ where /// get wallet info totals pub fn wallet_info<'a, L, C, K>( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where diff --git a/impls/src/test_framework/testclient.rs b/impls/src/test_framework/testclient.rs index dcd2ac1..ed99fcc 100644 --- a/impls/src/test_framework/testclient.rs +++ b/impls/src/test_framework/testclient.rs @@ -26,7 +26,7 @@ use crate::keychain::Keychain; use crate::libwallet; use crate::libwallet::api_impl::foreign; use crate::libwallet::slate_versions::v4::SlateV4; -use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletInst, WalletLCProvider}; +use crate::libwallet::{NodeClient, NodeVersionInfo, Slate, WalletLCProvider}; use crate::util; use crate::util::secp::key::SecretKey; use crate::util::secp::pedersen; @@ -66,11 +66,12 @@ where /// handle to chain itself pub chain: Arc, /// list of interested wallets + #[allow(clippy::type_complexity)] pub wallets: HashMap< String, ( Sender, - Arc>>>, + grin_wallet_libwallet::WalletHandle<'a, L, C, K>, Option, ), >, @@ -119,7 +120,7 @@ where &mut self, addr: &str, tx: Sender, - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'a, L, C, K>, keychain_mask: Option, ) { self.wallets @@ -185,12 +186,7 @@ where libwallet::Error::ClientCallback("Error parsing Transaction".to_owned()) })?; - super::award_block_to_wallet( - &self.chain, - &[tx], - dest_wallet, - (&dest_wallet_mask).as_ref(), - )?; + super::award_block_to_wallet(&self.chain, &[tx], dest_wallet, dest_wallet_mask.as_ref())?; Ok(WalletProxyMessage { sender_id: "node".to_owned(), @@ -219,7 +215,7 @@ where let w = w_lock.lc_provider()?.wallet_inst()?; let mask = wallet.2.clone(); // receive tx - match foreign::receive_tx(w, (&mask).as_ref(), &Slate::from(slate), None, false) { + match foreign::receive_tx(w, mask.as_ref(), &Slate::from(slate), None, false) { Err(e) => { return Ok(WalletProxyMessage { sender_id: m.dest, diff --git a/impls/src/tor/arti.rs b/impls/src/tor/arti.rs index 769e2bc..3abeedd 100644 --- a/impls/src/tor/arti.rs +++ b/impls/src/tor/arti.rs @@ -59,12 +59,14 @@ struct TorService { state_lock: PathBuf, } +type ArtiClientConfig = (Arc>, TorClientConfig); + lazy_static! { /// Arti Tokio runtime. static ref ARTI_RUNTIME: LazyLock>> = LazyLock::new(|| Mutex::new(ArtiRuntimeWrapper::create().ok())); /// Arti client and config. - static ref ARTI_CLIENT_CONFIG: LazyLock>, TorClientConfig)>>> = + static ref ARTI_CLIENT_CONFIG: LazyLock>> = LazyLock::new(|| Mutex::new(None)); /// Running services, where key is onion address. static ref ARTI_PROXY_SERVICES: LazyLock>> = @@ -138,7 +140,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu info!("Proxy configuration will be ignored."); } - let (state_path, cache_path) = state_cache_paths(&config); + let (state_path, cache_path) = state_cache_paths(config); let (client, config) = init_client(&state_path, &cache_path, config)?; // Add service key to keystore. @@ -151,7 +153,7 @@ pub fn start_tor_service(key: SecretKey, addr: &str, config: &TorConfig) -> Resu let state_lock = state_path .join("hss") .join(format!("{}.lock", onion_address)); - let _ = add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?; + add_service_key(config.fs_mistrust(), &key, &hs, keystore_path)?; // Launch Onion service. let service_config = OnionServiceConfigBuilder::default() @@ -233,7 +235,7 @@ where } .to_string(); let timeout = tor_config.request_timeout(); - let (state_path, cache_path) = state_cache_paths(&tor_config); + let (state_path, cache_path) = state_cache_paths(tor_config); let (client, _) = init_client(&state_path, &cache_path, tor_config)?; let res: Result = thread::spawn(move || { let c = client.clone(); @@ -286,7 +288,7 @@ where }) }) .join() - .unwrap_or_else(|e| return Err(Error::TorProcess(format!("{:?}", e))))?; + .unwrap_or_else(|e| Err(Error::TorProcess(format!("{:?}", e))))?; res } @@ -296,7 +298,7 @@ fn init_client( cache_path: &PathBuf, tor_config: &TorConfig, ) -> Result<(Arc>, TorClientConfig), Error> { - let mut builder = TorClientConfigBuilder::from_directories(&state_path, cache_path); + let mut builder = TorClientConfigBuilder::from_directories(state_path, cache_path); builder.address_filter().allow_onion_addrs(true); // Configure bridge. @@ -345,7 +347,7 @@ fn init_client( *cached_client_config = None; } } - let res = launch_client(config.clone(), &tor_config); + let res = launch_client(config.clone(), tor_config); match res { Ok(client) => { cached_client_config.replace((client.clone(), config.clone())); @@ -458,7 +460,7 @@ fn add_service_key( Some(expanded_kp) => { key_manager .insert( - HsIdKey::from(expanded_kp.public().clone()), + HsIdKey::from(*expanded_kp.public()), &HsIdPublicKeySpecifier::new(hs_nickname.clone()), KeystoreSelector::Primary, true, diff --git a/impls/src/tor/bridge.rs b/impls/src/tor/bridge.rs index 834e0b9..764658c 100644 --- a/impls/src/tor/bridge.rs +++ b/impls/src/tor/bridge.rs @@ -87,8 +87,8 @@ impl<'a> FlagParser<'a> { fn end(&mut self, is_bool_flag: bool, right: &str) -> usize { if is_bool_flag { 0 - } else if right.starts_with('"') { - right[1..].find('"').unwrap_or(0) + 2 + } else if let Some(stripped) = right.strip_prefix('"') { + stripped.find('"').unwrap_or(0) + 2 } else { right.find(' ').unwrap_or(right.len()) } @@ -113,7 +113,7 @@ impl<'a> Iterator for FlagParser<'a> { let end = self.end(self.is_bool_flag, right); let key = left.split_whitespace().last()?; let val = &right[..end]; - self.line = &right[end..].trim(); + self.line = right[end..].trim(); Some((key, val)) } } @@ -121,7 +121,7 @@ impl<'a> Iterator for FlagParser<'a> { /// Every args field that could be in the bridge line /// obfs4 args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/obfs4/obfs4.go#L86-L91 /// meek_lite args : https://github.com/Yawning/obfs4/blob/40245c4a1cf221395c59d1f4bf274127045352f9/transports/meeklite/meek.go#L93-L127 -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct Transport { /// transport type: obfs4, meek_lite, meek, snowflake pub transport: Option, @@ -143,22 +143,6 @@ pub struct Transport { pub disablehpkp: Option, } -impl Default for Transport { - fn default() -> Transport { - Transport { - transport: None, - server: None, - fingerprint: None, - cert: None, - iatmode: None, - url: None, - front: None, - utls: None, - disablehpkp: None, - } - } -} - impl Transport { /// Parse the server address of the bridge line fn parse_socketaddr_arg(arg: Option<&&str>) -> Result { @@ -170,7 +154,7 @@ impl Transport { Ok(address.to_string()) } None => { - let msg = format!("Missing bridge server address"); + let msg = "Missing bridge server address".to_string(); Err(Error::TorBridge(msg)) } } @@ -202,7 +186,7 @@ impl Transport { })?; if cert_vec.len() != 52 { let msg = format!("Invalid certificate: {}", arg); - return Err(Error::TorBridge(msg).into()); + return Err(Error::TorBridge(msg)); } Ok(arg.to_string()) } @@ -219,16 +203,17 @@ impl Transport { /// Parse the max value for the arg -max in the client line option (snowflake) fn parse_hpkp_arg(arg: &str) -> Result { let max = arg.parse::().map_err(|_e| { - Error::TorBridge( - format!("Invalid -max value: {}, must be \"true\" or \"false\"", arg).into(), - ) + Error::TorBridge(format!( + "Invalid -max value: {}, must be \"true\" or \"false\"", + arg + )) })?; Ok(max.to_string()) } } // Client Plugin such as snowflake or obfs4proxy -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct PluginClient { // Path plugin client pub path: Option, @@ -236,15 +221,6 @@ pub struct PluginClient { pub option: Option, } -impl Default for PluginClient { - fn default() -> PluginClient { - PluginClient { - path: None, - option: None, - } - } -} - impl PluginClient { /// Get the hashmap key(argument) and attached value of the client option line. pub fn get_flags(s: &str) -> HashMap<&str, &str> { @@ -333,7 +309,7 @@ impl PluginClient { "Invalid ICE address: {}. Must be a stun or turn address", addr ); - return Err(Error::TorBridge(msg).into()); + return Err(Error::TorBridge(msg)); } } Ok(ice_addr.to_string()) @@ -372,9 +348,9 @@ impl PluginClient { let (ck_url, ck_ice) = (hm_flags.contains_key("-url"), hm_flags.contains_key("-ice")); if !(ck_url || ck_ice) { let msg = if !ck_url { - format!("Missing URL argurment for snowflake transport, specify \"-url\"") + "Missing URL argurment for snowflake transport, specify \"-url\"".to_string() } else { - format!("Missing ICE argurment for snowflake transport, specify \"-ice\"") + "Missing ICE argurment for snowflake transport, specify \"-ice\"".to_string() }; return Err(Error::TorBridge(msg)); } @@ -410,7 +386,7 @@ impl PluginClient { } /// Tor Bridge Field -#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default)] pub struct TorBridge { /// tor bridge (transport field) pub bridge: Transport, @@ -418,15 +394,6 @@ pub struct TorBridge { pub client: PluginClient, } -impl Default for TorBridge { - fn default() -> TorBridge { - TorBridge { - bridge: Transport::default(), - client: PluginClient::default(), - } - } -} - impl TorBridge { /// Get the hashmap key(argument) and attached value of the bridge line. r pub fn get_flags(s: &str) -> HashMap<&str, &str> { @@ -541,8 +508,8 @@ impl TryFrom for TorBridge { let cert = match flags.get_key_value("cert=") { Some(hm) => Transport::parse_cert_arg(hm.1)?, None => { - let msg = - format!("Missing cert argurment in obfs4 transport, specify \"cert=\""); + let msg = "Missing cert argurment in obfs4 transport, specify \"cert=\"" + .to_string(); return Err(Error::TorBridge(msg)); } }; @@ -559,14 +526,14 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("obfs4".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, - cert: Some(cert.into()), + fingerprint, + cert: Some(cert), iatmode: Some(iatmode), ..Transport::default() }, client: PluginClient { path: Some(path), - option: option, + option, }, }; Ok(tbpc) @@ -578,9 +545,8 @@ impl TryFrom for TorBridge { let url = match flags.get_key_value("url=") { Some(hm) => PluginClient::parse_url_arg(hm.1)?, None => { - let msg = format!( - "Missing url argurment in meek_lite transport, specify \"url=\"" - ); + let msg = "Missing url argurment in meek_lite transport, specify \"url=\"" + .to_string(); return Err(Error::TorBridge(msg)); } }; @@ -588,10 +554,7 @@ impl TryFrom for TorBridge { Some(hm) => Some(PluginClient::parse_front_arg(hm.1)?), None => None, }; - let utls = match flags.get_key_value("utls=") { - Some(hm) => Some(hm.1.to_string()), - None => None, - }; + let utls = flags.get_key_value("utls=").map(|hm| hm.1.to_string()); let disablehpkp = match flags.get_key_value("disablehpkp=") { Some(hm) => Some(Transport::parse_hpkp_arg(hm.1)?), None => None, @@ -605,16 +568,16 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("meek_lite".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, + fingerprint, url: Some(url), - front: front, - utls: utls, - disablehpkp: disablehpkp, + front, + utls, + disablehpkp, ..Transport::default() }, client: PluginClient { path: Some(path), - option: option, + option, }, }; Ok(tbpc) @@ -638,7 +601,7 @@ impl TryFrom for TorBridge { bridge: Transport { transport: Some("snowflake".into()), server: Some(socketaddr.to_string()), - fingerprint: fingerprint, + fingerprint, ..Transport::default() }, client: PluginClient { diff --git a/impls/src/tor/config.rs b/impls/src/tor/config.rs index 422fae1..3375dd4 100644 --- a/impls/src/tor/config.rs +++ b/impls/src/tor/config.rs @@ -131,7 +131,7 @@ pub fn create_onion_service_pub_key_file( pub fn create_onion_service_hostname_file(os_directory: &str, hostname: &str) -> Result<(), Error> { let file_path = &format!("{}{}{}", os_directory, MAIN_SEPARATOR, HOSTNAME_FILE); let mut file = File::create(file_path).map_err(|_| Error::IO)?; - file.write_all(&format!("{}.onion\n", hostname).as_bytes()) + file.write_all(format!("{}.onion\n", hostname).as_bytes()) .map_err(|_| Error::IO)?; Ok(()) } @@ -228,7 +228,7 @@ pub fn output_tor_listener_config( let mut service_dirs = vec![]; for k in listener_keys { - let service_dir = output_onion_service_config(tor_config_directory, &k)?; + let service_dir = output_onion_service_config(tor_config_directory, k)?; service_dirs.push(service_dir.to_string()); } @@ -253,7 +253,7 @@ pub fn output_tor_sender_config( hm_tor_proxy: HashMap, ) -> Result<(), Error> { // create data directory if it doesn't exist - fs::create_dir_all(&tor_config_dir).map_err(|_| Error::IO)?; + fs::create_dir_all(tor_config_dir).map_err(|_| Error::IO)?; output_torrc( tor_config_dir, @@ -272,7 +272,7 @@ pub fn is_tor_address(input: &str) -> Result<(), Error> { Ok(_) => Ok(()), Err(e) => { let msg = format!("{:?}", e); - Err(Error::NotOnion(msg).into()) + Err(Error::NotOnion(msg)) } } } diff --git a/impls/src/tor/process.rs b/impls/src/tor/process.rs index 4e53f8e..9bf8b7f 100644 --- a/impls/src/tor/process.rs +++ b/impls/src/tor/process.rs @@ -90,6 +90,12 @@ pub struct TorProcess { sys: System, } +impl Default for TorProcess { + fn default() -> Self { + Self::new() + } +} + impl TorProcess { pub fn new() -> Self { TorProcess { @@ -153,7 +159,7 @@ impl TorProcess { let mut tor = Command::new(&self.tor_cmd); if let Some(ref d) = self.working_dir { - tor.current_dir(&d); + tor.current_dir(d); let pid_file_name = format!("{}{}pid", d, MAIN_SEPARATOR); // kill off PID if its already running if Path::new(&pid_file_name).exists() { @@ -167,7 +173,7 @@ impl TorProcess { } } if let Some(ref torrc_path) = self.torrc_path { - tor.args(&vec!["-f", torrc_path]); + tor.args(vec!["-f", torrc_path]); } let mut tor_process = tor .args(&self.args) diff --git a/impls/src/tor/proxy.rs b/impls/src/tor/proxy.rs index 9e0deb2..a54e9ca 100644 --- a/impls/src/tor/proxy.rs +++ b/impls/src/tor/proxy.rs @@ -20,7 +20,7 @@ use std::str; use url::Host; /// Tor Proxy -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)] pub struct TorProxy { /// proxy type used for the proxy, eg "socks4", "socks5", "http", "https" pub transport: Option, @@ -34,18 +34,6 @@ pub struct TorProxy { pub allowed_port: Option>, } -impl Default for TorProxy { - fn default() -> TorProxy { - TorProxy { - transport: None, - address: None, - username: None, - password: None, - allowed_port: None, - } - } -} - impl TorProxy { fn parse_host_port(addr: &str) -> Result<(String, Option), Error> { let host: String; @@ -70,7 +58,7 @@ impl TorProxy { } pub fn parse_address(addr: &str) -> Result<(String, Option), Error> { - let (host, str_port) = TorProxy::parse_host_port(&addr)?; + let (host, str_port) = TorProxy::parse_host_port(addr)?; let host = Host::parse(&host) .map_err(|_e| Error::TorProxy(format!("Invalid host address: {}", host)))?; let port = if let Some(p) = str_port { @@ -92,13 +80,10 @@ impl TorProxy { for port in ports.clone() { allowed_ports.push_str(format!("*:{}", port).as_str()); if port != last_port { - allowed_ports.push_str(","); + allowed_ports.push(','); } } - hm.insert( - "ReachableAddresses".to_string(), - format!("{}", allowed_ports.clone()), - ); + hm.insert("ReachableAddresses".to_string(), allowed_ports); } let transport = match self.transport { @@ -156,7 +141,7 @@ impl TryFrom for TorProxy { address_addr = host } Ok(TorProxy { - transport: Some(transport.into()), + transport: Some(transport), address: Some(address_addr), username: tb.username, password: tb.password, @@ -167,7 +152,7 @@ impl TryFrom for TorProxy { "Missing proxy address: {} - must be or ", transport ); - return Err(Error::TorProxy(msg).into()); + Err(Error::TorProxy(msg)) } } // Missing transport type @@ -176,7 +161,7 @@ impl TryFrom for TorProxy { "Invalid proxy transport: {} - must be socks4/socks5/http(s)", transport ); - Err(Error::TorProxy(msg).into()) + Err(Error::TorProxy(msg)) } } } else { diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index 4a6f54b..d4f9dfe 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -15,9 +15,9 @@ //! Functions defining wallet 'addresses', i.e. ed2559 keys based on //! a derivation path -use crate::grin_util::secp::key::SecretKey; use crate::Error; use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::SecretKey; use crate::blake2::blake2b::blake2b; @@ -50,10 +50,7 @@ where let key_id = address_derivation_path(parent_key_id, index); let sec_key = keychain.derive_key(0, &key_id, SwitchCommitmentType::None)?; let hashed = blake2b(32, &[], &sec_key.0[..]); - Ok(SecretKey::from_slice( - &keychain.secp(), - &hashed.as_bytes()[..], - )?) + Ok(SecretKey::from_slice(keychain.secp(), hashed.as_bytes())?) } #[cfg(test)] diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 5c63a52..84aa16e 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -20,14 +20,14 @@ use super::owner::tx_lock_outputs; use crate::api_impl::owner::{check_ttl, post_tx}; use crate::api_impl::types::update_tx_slate_state; use crate::backend::WalletBackend; -use crate::grin_core::core::FeeFields; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; use crate::internal::{selection, tx, updater}; use crate::slate_versions::SlateVersion; use crate::{ address, BlockFees, CbData, Error, NodeClient, Slate, SlateState, TxLogEntryType, VersionInfo, }; +use grin_core::core::FeeFields; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; const FOREIGN_API_VERSION: u16 = 2; @@ -164,7 +164,7 @@ where selection::repopulate_tx(w, keychain_mask, &mut sl, &temp_ctx, false)?; tx::complete_tx(w, keychain_mask, &mut sl, &context)?; - tx::update_stored_tx(w, keychain_mask, &context, &mut sl, true)?; + tx::update_stored_tx(w, keychain_mask, &context, &sl, true)?; { let mut batch = w.batch(keychain_mask)?; batch.delete_private_context(sl.id.as_bytes())?; diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index e6fb0d0..9c34925 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -18,18 +18,16 @@ use std::cmp; use uuid::Uuid; use crate::api_impl::foreign::finalize_tx as foreign_finalize; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::core::hash::Hashed; -use crate::grin_core::core::{FeeFields, Output, OutputFeatures, Transaction}; -use crate::grin_core::libtx::proof; -use crate::grin_keychain::ViewKey; -use crate::grin_util::secp::{key::SecretKey, pedersen::Commitment}; -use crate::grin_util::Mutex; -use crate::grin_util::ToHex; use crate::util::OnionV3Address; +use grin_core::core::amount_to_hr_string; +use grin_core::core::hash::Hashed; +use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction}; +use grin_core::libtx::proof; +use grin_keychain::ViewKey; +use grin_util::secp::{key::SecretKey, pedersen::Commitment}; +use grin_util::ToHex; use crate::api_impl::owner_updater::StatusMessage; -use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; use crate::internal::{keys, scan, selection, tx, updater}; use crate::slate::{PaymentInfo, Slate, SlateState}; use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletInfo}; @@ -39,8 +37,9 @@ use crate::{ wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack, SlatepackAddress, Slatepacker, SlatepackerArgs, TxLogEntryType, ViewWallet, WalletBackend, - WalletInitStatus, WalletInst, WalletLCProvider, + WalletInitStatus, WalletLCProvider, }; +use grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::Verifier; @@ -49,7 +48,6 @@ use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; use std::convert::{TryFrom, TryInto}; use std::sync::mpsc::Sender; -use std::sync::Arc; /// List of accounts pub fn accounts( @@ -103,7 +101,7 @@ where /// Hash of the wallet root public key pub fn get_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -121,7 +119,7 @@ where /// Retrieve the slatepack address for the current parent key at /// the given index pub fn get_slatepack_address<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, index: u32, ) -> Result @@ -140,7 +138,7 @@ where /// Retrieve the decryption key for the current parent key /// the given index pub fn get_slatepack_secret_key<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, index: u32, ) -> Result @@ -159,7 +157,7 @@ where /// Create a slatepack message from the given slate pub fn create_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slate: &Slate, sender_index: Option, @@ -186,7 +184,7 @@ where /// Unpack a slate from the given slatepack message, /// optionally decrypting pub fn slate_from_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, secret_indices: Vec, @@ -214,7 +212,7 @@ where let packer = Slatepacker::new(SlatepackerArgs { sender: None, recipients: vec![], - dec_key: (&dec_key).as_ref(), + dec_key: dec_key.as_ref(), }); let res = packer.deser_slatepack(slatepack.as_bytes(), true); let slatepack = match res { @@ -228,8 +226,7 @@ where Err(Error::SlatepackDecryption( "Could not decrypt slatepack with any provided index on the address derivation path" .to_owned(), - ) - .into()) + )) } } @@ -237,7 +234,7 @@ where /// Will decrypt if possible, otherwise will return /// undecrypted slatepack pub fn decode_slatepack_message<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, secret_indices: Vec, @@ -264,7 +261,7 @@ where let packer = Slatepacker::new(SlatepackerArgs { sender: None, recipients: vec![], - dec_key: (&dec_key).as_ref(), + dec_key: dec_key.as_ref(), }); let res = packer.deser_slatepack(slatepack.as_bytes(), true); let slatepack = match res { @@ -281,7 +278,7 @@ where /// retrieve outputs pub fn retrieve_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, include_spent: bool, @@ -315,7 +312,7 @@ where /// Calculate max amount to send. pub fn estimate_max_sendable<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -374,7 +371,7 @@ where /// Retrieve txs pub fn retrieve_txs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -414,7 +411,7 @@ where /// Retrieve summary info pub fn retrieve_summary_info<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -444,7 +441,7 @@ where /// Retrieve payment proof pub fn retrieve_payment_proof<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, refresh_from_node: bool, @@ -864,7 +861,7 @@ where let mut sl = slate.clone(); - if sl.tx == None { + if sl.tx.is_none() { sl.tx = Some(Slate::empty_transaction()); selection::repopulate_tx(w, keychain_mask, &mut sl, &context, true)?; } @@ -893,7 +890,7 @@ where /// cancel tx pub fn cancel_tx<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, tx_id: Option, @@ -932,11 +929,7 @@ where { let mut uuid = None; if let Some(i) = tx_id { - let tx = w - .tx_log_iter()? - .filter(|tx| tx.is_ok()) - .map(|tx| tx.unwrap()) - .find(|t| t.id == i); + let tx = w.tx_log_iter()?.flatten().find(|t| t.id == i); if let Some(t) = tx { uuid = t.tx_slate_id; } @@ -992,7 +985,7 @@ where /// Scan outputs with the rewind hash of a third-party wallet. /// Help to retrieve outputs information that belongs it pub fn scan_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, rewind_hash: String, start_height: Option, status_send_channel: &Option>, @@ -1013,7 +1006,7 @@ where w.w2n_client().get_chain_tip()? }; - let start_height = start_height.unwrap_or_else(|| 1); + let start_height = start_height.unwrap_or(1); let info = scan::scan_rewind_hash( wallet_inst, @@ -1029,7 +1022,7 @@ where /// Accepts a wallet inst instead of a raw wallet so it can /// lock as little as possible pub fn scan<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, start_height: Option, delete_unconfirmed: bool, @@ -1046,7 +1039,7 @@ where w.w2n_client().get_chain_tip()? }; - let start_height = start_height.unwrap_or_else(|| 1); + let start_height = start_height.unwrap_or(1); // Scan every 10k heights to save data between batches in case of interruption. let mut total_pmmr_range = None; @@ -1081,7 +1074,7 @@ where /// node height pub fn node_height<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, ) -> Result where @@ -1101,12 +1094,7 @@ where }), Err(_) => { let outputs = retrieve_outputs(wallet_inst, keychain_mask, &None, true, false, None)?; - let height = outputs - .1 - .iter() - .map(|m| m.output.height) - .max() - .unwrap_or_else(|| 0); + let height = outputs.1.iter().map(|m| m.output.height).max().unwrap_or(0); Ok(NodeHeightResult { height, header_hash: "".to_owned(), @@ -1121,7 +1109,7 @@ pub const REORG_RESCAN_WINDOW: u64 = 24 * 60 * 2; /// Experimental, wrap the entire definition of how a wallet's state is updated pub fn update_wallet_state<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, status_send_channel: &Option>, update_all: bool, @@ -1275,10 +1263,8 @@ where { // Refuse if TTL is expired let last_confirmed_height = w.last_confirmed_height()?; - if slate.ttl_cutoff_height != 0 { - if last_confirmed_height >= slate.ttl_cutoff_height { - return Err(Error::TransactionExpired); - } + if slate.ttl_cutoff_height != 0 && last_confirmed_height >= slate.ttl_cutoff_height { + return Err(Error::TransactionExpired); } Ok(()) } @@ -1286,7 +1272,7 @@ where /// Verify/validate arbitrary payment proof /// Returns (whether this wallet is the sender, whether this wallet is the recipient) pub fn verify_payment_proof<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, proof: &PaymentProof, ) -> Result<(bool, bool), Error> @@ -1350,7 +1336,7 @@ where /// Attempt to update outputs in wallet, return whether it was successful fn update_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, update_all: bool, ) -> Result @@ -1374,9 +1360,9 @@ where /// Update transactions that need to be validated via kernel lookup fn update_txs_via_kernel<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - txs: &mut Vec, + txs: &mut [TxLogEntry], ) -> Result where L: WalletLCProvider<'a, C, K>, @@ -1515,30 +1501,29 @@ where let mut blind_sum = new_output .blind - .split(&BlindingFactor::from_secret_key(input_blind.clone()), &secp)?; + .split(&BlindingFactor::from_secret_key(input_blind.clone()), secp)?; - let hops = server_pubkeys + let hops: Vec = server_pubkeys .iter() .enumerate() .map(|(i, &p)| { if (i + 1) == server_pubkeys.len() { Hop { - server_pubkey: p.clone(), - excess: blind_sum.secret_key(&secp).unwrap(), + server_pubkey: p, + excess: blind_sum.secret_key(secp).unwrap(), fee: FeeFields::from(fee as u32), - rangeproof: Some(new_output.output.proof.clone()), + rangeproof: Some(new_output.output.proof), } } else { - let hop_excess; - if use_test_rng { - hop_excess = BlindingFactor::zero(); + let hop_excess = if use_test_rng { + BlindingFactor::zero() } else { - hop_excess = BlindingFactor::rand(&secp); - } - blind_sum = blind_sum.split(&hop_excess, &secp).unwrap(); + BlindingFactor::rand(secp) + }; + blind_sum = blind_sum.split(&hop_excess, secp).unwrap(); Hop { - server_pubkey: p.clone(), - excess: hop_excess.secret_key(&secp).unwrap(), + server_pubkey: p, + excess: hop_excess.secret_key(secp).unwrap(), fee: FeeFields::from(fee as u32), rangeproof: None, } @@ -1546,7 +1531,7 @@ where }) .collect(); - let onion = create_onion(&commitment, &hops, use_test_rng).unwrap(); + let onion = create_onion(commitment, &hops, use_test_rng).unwrap(); let comsig = ComSignature::sign( amount, &input_blind, diff --git a/libwallet/src/api_impl/owner_updater.rs b/libwallet/src/api_impl/owner_updater.rs index 9201c6e..f513a82 100644 --- a/libwallet/src/api_impl/owner_updater.rs +++ b/libwallet/src/api_impl/owner_updater.rs @@ -19,14 +19,14 @@ use std::sync::Arc; use std::thread; use std::time::Duration; -use crate::grin_keychain::Keychain; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::Mutex; +use grin_keychain::Keychain; +use grin_util::secp::key::SecretKey; +use grin_util::Mutex; use crate::api_impl::owner; use crate::types::NodeClient; use crate::Error; -use crate::{WalletInst, WalletLCProvider}; +use crate::WalletLCProvider; const MESSAGE_QUEUE_MAX_LEN: usize = 10_000; @@ -101,7 +101,7 @@ where C: NodeClient + 'a, K: Keychain + 'a, { - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, is_running: Arc, } @@ -112,10 +112,7 @@ where K: Keychain + 'a, { /// create a new updater - pub fn new( - wallet_inst: Arc>>>, - is_running: Arc, - ) -> Self { + pub fn new(wallet_inst: crate::WalletHandle<'a, L, C, K>, is_running: Arc) -> Self { is_running.store(false, Ordering::Relaxed); Updater { wallet_inst, @@ -141,7 +138,7 @@ where if wallet_opened { owner::update_wallet_state( self.wallet_inst.clone(), - (&keychain_mask).as_ref(), + keychain_mask.as_ref(), status_send_channel, false, )?; diff --git a/libwallet/src/api_impl/types.rs b/libwallet/src/api_impl/types.rs index 3d0973a..06ccf26 100644 --- a/libwallet/src/api_impl/types.rs +++ b/libwallet/src/api_impl/types.rs @@ -14,14 +14,14 @@ //! Types specific to the wallet api, mostly argument serialization -use crate::grin_core::core::Output; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::{BlindingFactor, Identifier}; -use crate::grin_util::secp::pedersen; use crate::slate_versions::ser as dalek_ser; use crate::slate_versions::SlateVersion; use crate::types::OutputData; use crate::{Error, NodeClient, Slate, SlatepackAddress, WalletBackend}; +use grin_core::core::Output; +use grin_core::libtx::secp_ser; +use grin_keychain::{BlindingFactor, Identifier}; +use grin_util::secp::pedersen; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; @@ -132,7 +132,7 @@ impl Default for InitTxArgs { } /// V2 Issue Invoice Tx Args -#[derive(Clone, Serialize, Deserialize)] +#[derive(Clone, Serialize, Deserialize, Default)] pub struct IssueInvoiceTxArgs { /// The human readable account name to which the received funds should be added /// overriding whatever the active account is as set via the @@ -147,16 +147,6 @@ pub struct IssueInvoiceTxArgs { pub target_slate_version: Option, } -impl Default for IssueInvoiceTxArgs { - fn default() -> IssueInvoiceTxArgs { - IssueInvoiceTxArgs { - dest_acct_name: None, - amount: 0, - target_slate_version: None, - } - } -} - /// Sort tx retrieval order #[derive(Clone, Serialize, Deserialize)] pub enum RetrieveTxQuerySortOrder { diff --git a/libwallet/src/backend.rs b/libwallet/src/backend.rs index 97324c0..90c4b6b 100644 --- a/libwallet/src/backend.rs +++ b/libwallet/src/backend.rs @@ -77,7 +77,7 @@ where // h(root_key|slate_id|"blind") let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - hasher.update(&slate_id[..]); + hasher.update(slate_id); hasher.update(&b"blind"[..]); let blind_xor_key = hasher.finalize(); let mut ret_blind = [0; SECRET_KEY_SIZE]; @@ -86,7 +86,7 @@ where // h(root_key|slate_id|"nonce") let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - hasher.update(&slate_id[..]); + hasher.update(slate_id); hasher.update(&b"nonce"[..]); let nonce_xor_key = hasher.finalize(); let mut ret_nonce = [0; SECRET_KEY_SIZE]; @@ -172,12 +172,9 @@ where }; // Set current active account - let active = res - .acct_path_iter()? - .filter(|a| a.current.unwrap_or(false)) - .collect::>(); - if let Some(a) = active.get(0) { - res.active_account = a.clone(); + let active = res.acct_path_iter()?.find(|a| a.current.unwrap_or(false)); + if let Some(a) = active { + res.active_account = a; } Ok(res) @@ -210,7 +207,7 @@ where let root_key = k.derive_key(0, &K::root_key_id(), SwitchCommitmentType::Regular)?; let mut hasher = Blake2b::new(SECRET_KEY_SIZE); hasher.update(&root_key.0[..]); - self.master_checksum = Box::new(Some(hasher.finalize())); + *self.master_checksum = Some(hasher.finalize()); let mask_value = { match mask { @@ -220,9 +217,9 @@ where let mask_value = match use_test_rng { true => { let mut test_rng = StepRng::new(1_234_567_890_u64, 1); - SecretKey::new(&k.secp(), &mut test_rng) + SecretKey::new(k.secp(), &mut test_rng) } - false => SecretKey::new(&k.secp(), &mut thread_rng()), + false => SecretKey::new(k.secp(), &mut thread_rng()), }; k.mask_master_key(&mask_value)?; Some(mask_value) @@ -285,7 +282,7 @@ where } else {*/ Ok(Some( self.keychain(keychain_mask)? - .commit(amount, &id, SwitchCommitmentType::Regular)? + .commit(amount, id, SwitchCommitmentType::Regular)? .0 .to_vec() .to_hex(), // TODO: proper support for different switch commitment schemes @@ -452,7 +449,7 @@ where let path_buf = Path::new(&path).to_path_buf(); let mut stored_tx = File::create(path_buf)?; let tx_hex = ser::ser_vec(tx, ser::ProtocolVersion(1)).unwrap().to_hex(); - stored_tx.write_all(&tx_hex.as_bytes())?; + stored_tx.write_all(tx_hex.as_bytes())?; stored_tx.sync_all()?; Ok(()) } @@ -504,7 +501,7 @@ where let batch = self.db.batch()?; batch .get_ser(Some(DERIV_PREFIX), &parent_key_id.to_bytes(), None)? - .unwrap_or_else(|| 0) + .unwrap_or(0) }; Ok(index) } @@ -516,7 +513,7 @@ where let batch = self.db.batch()?; batch .get_ser(Some(DERIV_PREFIX), &parent_key_id.to_bytes(), None)? - .unwrap_or_else(|| 0) + .unwrap_or(0) }; let mut return_path = parent_key_id.to_path(); return_path.depth += 1; @@ -546,7 +543,7 @@ where &parent_key_id.to_bytes(), None, )? - .unwrap_or_else(|| 0); + .unwrap_or(0); Ok(last_confirmed_height) } @@ -573,7 +570,7 @@ where WALLET_INIT_STATUS_KEY.as_bytes(), None, )? - .unwrap_or_else(|| WalletInitStatus::InitComplete); + .unwrap_or(WalletInitStatus::InitComplete); Ok(status) } } @@ -693,7 +690,7 @@ where let last_tx_log_id = self .db .get_ser(Some(TX_LOG_ID_PREFIX), &parent_key_id.to_bytes(), None)? - .unwrap_or_else(|| 0); + .unwrap_or(0); self.db.put_ser( Some(TX_LOG_ID_PREFIX), &parent_key_id.to_bytes(), diff --git a/libwallet/src/error.rs b/libwallet/src/error.rs index 5300dd1..020d80f 100644 --- a/libwallet/src/error.rs +++ b/libwallet/src/error.rs @@ -14,12 +14,10 @@ //! Error types for libwallet -use crate::grin_core::core::{amount_to_hr_string, committed, transaction}; -use crate::grin_core::libtx; -use crate::grin_keychain; -use crate::grin_util::secp; use crate::util; -use grin_store; +use grin_core::core::{amount_to_hr_string, committed, transaction}; +use grin_core::libtx; +use grin_util::secp; /// Wallet errors, mostly wrappers around underlying crypto or I/O errors. #[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)] @@ -95,7 +93,7 @@ pub enum Error { /// Other serialization errors #[error("Ser/Deserialization error")] - Deser(crate::grin_core::ser::Error), + Deser(grin_core::ser::Error), /// IO Error #[error("I/O error {0}")] diff --git a/libwallet/src/internal/keys.rs b/libwallet/src/internal/keys.rs index 7b223bd..313f8a5 100644 --- a/libwallet/src/internal/keys.rs +++ b/libwallet/src/internal/keys.rs @@ -14,10 +14,10 @@ //! Wallet key management functions use crate::error::Error; -use crate::grin_keychain::{ChildNumber, ExtKeychain, Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; use crate::types::{AcctPathMapping, NodeClient}; use crate::WalletBackend; +use grin_keychain::{ChildNumber, ExtKeychain, Identifier, Keychain}; +use grin_util::secp::key::SecretKey; /// Get next available key in the wallet for a given parent pub fn next_available_key( diff --git a/libwallet/src/internal/scan.rs b/libwallet/src/internal/scan.rs index fb5ec73..5371a36 100644 --- a/libwallet/src/internal/scan.rs +++ b/libwallet/src/internal/scan.rs @@ -14,44 +14,34 @@ //! Functions to restore a wallet's outputs from just the master seed use crate::api_impl::owner_updater::StatusMessage; -use crate::grin_core::consensus::{valid_header_version, WEEK_HEIGHT}; -use crate::grin_core::core::HeaderVersion; -use crate::grin_core::global; -use crate::grin_core::libtx::proof; -use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::secp::{ContextFlag, Secp256k1}; -use crate::grin_util::Mutex; -use crate::grin_util::{from_hex, ToHex}; use crate::internal::{keys, updater}; use crate::types::*; use crate::{wallet_lock, Error, OutputCommitMapping}; use blake2_rfc::blake2b::blake2b; +use grin_core::consensus::{valid_header_version, WEEK_HEIGHT}; +use grin_core::core::HeaderVersion; +use grin_core::global; +use grin_core::libtx::proof; +use grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::secp::{ContextFlag, Secp256k1}; +use grin_util::{from_hex, ToHex}; use rayon::prelude::*; use std::cmp; use std::collections::HashMap; use std::sync::mpsc::Sender; -use std::sync::Arc; /// Utility struct for return values from below #[derive(Debug, Clone)] struct OutputResult { - /// pub commit: pedersen::Commitment, - /// pub key_id: Identifier, - /// pub n_child: u32, - /// pub mmr_index: u64, - /// pub value: u64, - /// pub height: u64, - /// pub lock_height: u64, - /// pub is_coinbase: bool, } @@ -293,7 +283,7 @@ where const MISSING_OUTPUTS_BATCH_SIZE: usize = 1000; fn restore_missing_outputs<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, outputs: Vec, found_parents: &mut HashMap, @@ -359,9 +349,8 @@ where Ok(()) } -/// fn cancel_tx_log_entry<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, output: &OutputData, ) -> Result<(), Error> @@ -406,7 +395,7 @@ where /// Scan outputs with a given rewind hash view wallet. /// Retrieve all outputs information that belongs to it. pub fn scan_rewind_hash<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, rewind_hash: String, start_height: u64, end_height: u64, @@ -463,8 +452,9 @@ where /// The returned `ScannedBlockInfo` is the progress marker to persist after the /// batch. The returned PMMR range can be passed into the next batch to avoid /// looking up the full range again. +#[allow(clippy::too_many_arguments)] pub fn scan<'a, L, C, K>( - wallet_inst: Arc>>>, + wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, delete_unconfirmed: bool, batch_start_height: u64, @@ -642,7 +632,7 @@ where keys::set_acct_path(w, keychain_mask, &label, path)?; acct_index += 1; } - let current_child_index = w.current_child_index(&path)?; + let current_child_index = w.current_child_index(path)?; if *max_child_index >= current_child_index { let mut batch = w.batch(keychain_mask)?; debug!("Next child for account {} is {}", path, max_child_index + 1); diff --git a/libwallet/src/internal/selection.rs b/libwallet/src/internal/selection.rs index bac6d92..fc1b9a5 100644 --- a/libwallet/src/internal/selection.rs +++ b/libwallet/src/internal/selection.rs @@ -15,22 +15,22 @@ //! Selection of inputs for building transactions use crate::error::Error; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::libtx::{ - build, - proof::{ProofBuild, ProofBuilder}, - tx_fee, -}; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; use crate::internal::keys; use crate::slate::Slate; use crate::types::*; use crate::util::OnionV3Address; use crate::{address, WalletBackend}; +use grin_core::core::amount_to_hr_string; use grin_core::core::Transaction; use grin_core::global; +use grin_core::libtx::{ + build, + proof::{ProofBuild, ProofBuilder}, + tx_fee, +}; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; use std::collections::HashMap; use std::convert::TryInto; @@ -38,7 +38,7 @@ use std::convert::TryInto; /// libwallet transaction slate with the appropriate inputs selected, /// and saves the private wallet identifiers of our selected outputs /// into our transaction context - +#[allow(clippy::too_many_arguments)] pub fn build_send_tx( wallet: &mut WalletBackend, keychain: &K, @@ -109,7 +109,7 @@ where // Store change output(s) for (change_amount, id, mmr_index) in &change_amounts_derivations { - context.add_output(&id, &mmr_index, *change_amount); + context.add_output(id, mmr_index, *change_amount); } Ok(context) @@ -136,7 +136,7 @@ where output_commits.insert( id.clone(), ( - wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?, + wallet.calc_commit_for_cache(keychain_mask, *change_amount, id)?, *change_amount, ), ); @@ -191,8 +191,7 @@ where None => { return Err(Error::PaymentProof( "Payment proof derivation index required".to_owned(), - ) - .into()); + )); } }; let sender_key = address::address_from_derivation_path( @@ -213,7 +212,7 @@ where // write the output representing our change for (id, _, _) in &context.get_outputs() { t.num_outputs += 1; - let (commit, change_amount) = output_commits.get(&id).unwrap().clone(); + let (commit, change_amount) = output_commits.get(id).unwrap().clone(); t.amount_credited += change_amount; batch.save(OutputData { root_key_id: parent_key_id.clone(), @@ -315,6 +314,7 @@ where /// Builds a transaction to send to someone from the HD seed associated with the /// wallet and the amount to send. Handles reading through the wallet data file, /// selecting outputs to spend and building the change. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] pub fn select_send_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -350,7 +350,7 @@ where max_outputs, change_outputs, selection_strategy_is_use_all, - &parent_key_id, + parent_key_id, )?; // build transaction skeleton with inputs and change @@ -368,6 +368,7 @@ where } /// Select outputs and calculating fee. +#[allow(clippy::too_many_arguments)] pub fn select_coins_and_fee( wallet: &mut WalletBackend, amount: u64, @@ -569,6 +570,7 @@ where } /// Selects inputs and change for a transaction +#[allow(clippy::type_complexity)] pub fn inputs_and_change( coins: &[OutputData], wallet: &mut WalletBackend, @@ -758,7 +760,7 @@ where let keychain = wallet.keychain(keychain_mask)?; // restore my signature data - slate.add_participant_info(&keychain, &context, None)?; + slate.add_participant_info(&keychain, context, None)?; let mut parts = vec![]; for (id, mmr_index, value) in &context.get_inputs() { diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 6b655e3..5635235 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -18,11 +18,6 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::Cursor; use uuid::Uuid; -use crate::grin_core::consensus::header_version; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::Mutex; use crate::internal::{selection, updater}; use crate::slate::Slate; use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType}; @@ -33,7 +28,12 @@ use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::VerifyingKey as DalekPublicKey; use ed25519_dalek::{Signer, Verifier}; +use grin_core::consensus::header_version; use grin_core::core::FeeFields; +use grin_keychain::{Identifier, Keychain}; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::Mutex; // static for incrementing test UUIDs lazy_static! { @@ -79,6 +79,7 @@ where } /// Estimates locked amount and fee for the transaction without creating one +#[allow(clippy::too_many_arguments)] pub fn estimate_send_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -130,6 +131,7 @@ where } /// Add inputs to the slate (effectively becoming the sender) +#[allow(clippy::too_many_arguments)] pub fn add_inputs_to_slate( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -234,7 +236,7 @@ where // update excess in stored transaction let mut batch = wallet.batch(keychain_mask)?; tx.kernel_excess = Some(slate.calc_excess(keychain.secp())?); - batch.save_tx_log_entry(tx.clone(), &parent_key_id)?; + batch.save_tx_log_entry(tx, parent_key_id)?; batch.commit()?; } @@ -271,14 +273,14 @@ where init_tx_args.max_outputs as usize, init_tx_args.num_change_outputs as usize, init_tx_args.selection_strategy_is_use_all, - &parent_key_id, + parent_key_id, )?; slate.fee_fields = FeeFields::new(0, fee)?; let keychain = wallet.keychain(keychain_mask)?; // Create our own private context - let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, true); + let mut context = Context::new(keychain.secp(), parent_key_id, use_test_rng, true); context.fee = Some(slate.fee_fields); context.amount = slate.amount; context.late_lock_args = Some(init_tx_args.clone()); @@ -340,14 +342,8 @@ where } else if let Some(tx_slate_id) = tx_slate_id { tx_id_string = tx_slate_id.to_string(); } - let tx_vec = updater::retrieve_txs( - wallet, - tx_id, - tx_slate_id, - None, - Some(&parent_key_id), - false, - )?; + let tx_vec = + updater::retrieve_txs(wallet, tx_id, tx_slate_id, None, Some(parent_key_id), false)?; if tx_vec.len() != 1 { return Err(Error::TransactionDoesntExist(tx_id_string)); } @@ -365,7 +361,7 @@ where keychain_mask, false, Some(tx.id), - Some(&parent_key_id), + Some(parent_key_id), )?; let outputs = res.iter().map(|m| m.output.clone()).collect(); updater::cancel_tx_and_outputs(wallet, keychain_mask, tx, outputs, parent_key_id)?; @@ -409,7 +405,7 @@ where } if let Some(ref p) = slate.clone().payment_proof { - let derivation_index = context.payment_proof_derivation_index.unwrap_or_else(|| 0); + let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); let keychain = wallet.keychain(keychain_mask)?; let parent_key_id = wallet.parent_key_id(); let excess = slate.calc_excess(keychain.secp())?; @@ -453,12 +449,12 @@ pub fn _decode_payment_proof_message( let mut rdr = Cursor::new(msg); let amount = rdr.read_u64::()?; let mut commit_bytes = [0u8; 33]; - for i in 0..33 { - commit_bytes[i] = rdr.read_u8()?; + for byte in &mut commit_bytes { + *byte = rdr.read_u8()?; } let mut sender_address_bytes = [0u8; 32]; - for i in 0..32 { - sender_address_bytes[i] = rdr.read_u8()?; + for byte in &mut sender_address_bytes { + *byte = rdr.read_u8()?; } Ok(( @@ -548,7 +544,7 @@ where } let msg = payment_proof_message( slate.amount, - &slate.calc_excess(&keychain.secp())?, + &slate.calc_excess(keychain.secp())?, orig_sender_address.to_ed25519()?, )?; let sig = match p.receiver_signature { @@ -572,12 +568,12 @@ mod test { use super::*; use rand::rngs::mock::StepRng; - use crate::grin_core::core::{FeeFields, KernelFeatures}; - use crate::grin_core::libtx::{build, ProofBuilder}; - use crate::grin_keychain::{ + use grin_core::core::{FeeFields, KernelFeatures}; + use grin_core::libtx::{build, ProofBuilder}; + use grin_keychain::{ BlindSum, BlindingFactor, ExtKeychain, ExtKeychainPath, Keychain, SwitchCommitmentType, }; - use crate::grin_util::{secp, static_secp_instance}; + use grin_util::{secp, static_secp_instance}; #[test] // demonstrate that input.commitment == referenced output.commitment @@ -637,7 +633,7 @@ mod test { .unwrap(); keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; diff --git a/libwallet/src/internal/updater.rs b/libwallet/src/internal/updater.rs index 024559c..686b8c8 100644 --- a/libwallet/src/internal/updater.rs +++ b/libwallet/src/internal/updater.rs @@ -19,22 +19,23 @@ use std::collections::{HashMap, HashSet}; use uuid::Uuid; use crate::error::Error; -use crate::grin_core::consensus::reward; -use crate::grin_core::core::{Output, TxKernel}; -use crate::grin_core::global; -use crate::grin_core::libtx::proof::ProofBuilder; -use crate::grin_core::libtx::reward; -use crate::grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; -use crate::grin_util::secp::key::SecretKey; -use crate::grin_util::secp::pedersen; -use crate::grin_util::static_secp_instance; use crate::internal::keys; use crate::types::{NodeClient, OutputData, OutputStatus, TxLogEntry, TxLogEntryType, WalletInfo}; -use crate::{grin_util as util, AcctPathMapping}; +use crate::AcctPathMapping; use crate::{ BlockFees, CbData, OutputCommitMapping, RetrieveTxQueryArgs, RetrieveTxQuerySortField, RetrieveTxQuerySortOrder, WalletBackend, }; +use grin_core::consensus::reward; +use grin_core::core::{Output, TxKernel}; +use grin_core::global; +use grin_core::libtx::proof::ProofBuilder; +use grin_core::libtx::reward; +use grin_keychain::{Identifier, Keychain, SwitchCommitmentType}; +use grin_util as util; +use grin_util::secp::key::SecretKey; +use grin_util::secp::pedersen; +use grin_util::static_secp_instance; use num_bigint::BigInt; @@ -319,11 +320,8 @@ where return_txs.sort_by_key(|tx| tx.id); } - if let Some(ref s) = query_args.sort_order { - match s { - RetrieveTxQuerySortOrder::Desc => return_txs.reverse(), - _ => {} - } + if let Some(RetrieveTxQuerySortOrder::Desc) = query_args.sort_order { + return_txs.reverse(); } // Apply limit if requested @@ -351,8 +349,8 @@ where let mut txs; // Adding in new transaction list query logic. If `tx_id` or `tx_slate_id` // is provided, then `query_args` is ignored and old logic is followed. - if query_args.is_some() && tx_id.is_none() && tx_slate_id.is_none() { - txs = apply_advanced_tx_list_filtering(wallet, parent_key_id, &query_args.unwrap())? + if let Some(query_args) = query_args.filter(|_| tx_id.is_none() && tx_slate_id.is_none()) { + txs = apply_advanced_tx_list_filtering(wallet, parent_key_id, &query_args)? } else { let mut bad_records = 0; txs = wallet @@ -424,6 +422,7 @@ where /// transactions for the account and outputs without a transaction log entry. /// Returns mapping of output commit to tuple of derived key for output, /// PMMR index, tx entry log identifier and check if output is unspent +#[allow(clippy::type_complexity)] pub fn map_wallet_outputs( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -441,7 +440,7 @@ where .filter(|x| x.root_key_id == *parent_key_id && x.status != OutputStatus::Spent) .collect(); - let tx_entries = retrieve_txs(wallet, None, None, None, Some(&parent_key_id), true)?; + let tx_entries = retrieve_txs(wallet, None, None, None, Some(parent_key_id), true)?; // Only select outputs that are actually involved in an outstanding transaction let unspents = match update_all { @@ -510,6 +509,7 @@ where } /// Apply refreshed API output data to the wallet +#[allow(clippy::type_complexity)] fn apply_api_outputs( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -541,7 +541,7 @@ where let mut batch = wallet.batch(keychain_mask)?; for (commit, (id, mmr_index, _, _)) in wallet_outputs.iter() { if let Ok(mut output) = batch.get(id, mmr_index) { - match api_outputs.get(&commit) { + match api_outputs.get(commit) { Some(o) => { // if this is a coinbase tx being confirmed, it's recordable in tx log if output.is_coinbase && output.status == OutputStatus::Unconfirmed { @@ -566,7 +566,7 @@ where } t.update_confirmation_ts(); output.tx_log_entry = Some(log_id); - batch.save_tx_log_entry(t, &parent_key_id)?; + batch.save_tx_log_entry(t, parent_key_id)?; } // also mark the transaction in which this output is involved as confirmed // note that one involved input/output confirmation SHOULD be enough @@ -575,14 +575,10 @@ where && (output.status == OutputStatus::Unconfirmed || output.status == OutputStatus::Reverted) { - let tx = batch - .tx_log_iter()? - .filter(|t| t.is_ok()) - .map(|t| t.unwrap()) - .find(|t| { - Some(t.id) == output.tx_log_entry - && t.parent_key_id == *parent_key_id - }); + let tx = batch.tx_log_iter()?.flatten().find(|t| { + Some(t.id) == output.tx_log_entry + && t.parent_key_id == *parent_key_id + }); if let Some(mut t) = tx { if t.tx_type == TxLogEntryType::TxReverted { t.tx_type = TxLogEntryType::TxReceived; @@ -590,7 +586,7 @@ where } t.update_confirmation_ts(); t.confirmed = true; - batch.save_tx_log_entry(t, &parent_key_id)?; + batch.save_tx_log_entry(t, parent_key_id)?; } else { if let Some(tx_id) = output.tx_log_entry { error!("apply_api_outputs: tx with id {:?} not found", tx_id); @@ -631,7 +627,7 @@ where { if reverted_kernels.contains(&tx.id) && tx.parent_key_id == *parent_key_id { tx.tx_type = TxLogEntryType::TxReverted; - tx.reverted_after = tx.confirmation_ts.clone().and_then(|t| { + tx.reverted_after = tx.confirmation_ts.and_then(|t| { let now = chrono::Utc::now(); (now - t).to_std().ok() }); @@ -648,7 +644,7 @@ where } for tx in txs_to_save { - batch.save_tx_log_entry(tx, &parent_key_id)?; + batch.save_tx_log_entry(tx, parent_key_id)?; } { @@ -702,6 +698,7 @@ where Ok(()) } +#[allow(clippy::type_complexity)] fn find_reverted_kernels( wallet: &mut WalletBackend, wallet_outputs: &HashMap, Option, bool)>, @@ -885,7 +882,7 @@ where let outputs = wallet .iter()? .filter(|out| out.root_key_id == *parent_key_id); - let current_height = wallet.last_confirmed_height_for_parent(&parent_key_id)?; + let current_height = wallet.last_confirmed_height_for_parent(parent_key_id)?; let info = account_outputs_info(outputs, current_height, minimum_confirmations)?; Ok(info) } diff --git a/libwallet/src/lib.rs b/libwallet/src/lib.rs index a212836..cc1d417 100644 --- a/libwallet/src/lib.rs +++ b/libwallet/src/lib.rs @@ -24,10 +24,6 @@ use grin_wallet_config as config; -use grin_core; -use grin_keychain; -use grin_util; - use grin_wallet_util as util; use blake2_rfc as blake2; @@ -82,6 +78,10 @@ pub use types::{ ViewWallet, WalletInfo, WalletInitStatus, WalletInst, WalletLCProvider, }; +/// Shared wallet handle for APIs and workers +pub type WalletHandle<'a, L, C, K> = + std::sync::Arc>>>; + /// Helper for taking a lock on the wallet instance #[macro_export] macro_rules! wallet_lock { diff --git a/libwallet/src/mwixnet/onion/crypto/comsig.rs b/libwallet/src/mwixnet/onion/crypto/comsig.rs index 89eb8f8..0df427e 100644 --- a/libwallet/src/mwixnet/onion/crypto/comsig.rs +++ b/libwallet/src/mwixnet/onion/crypto/comsig.rs @@ -63,7 +63,7 @@ impl ComSignature { pub fn sign( amount: u64, blind: &SecretKey, - msg: &Vec, + msg: &[u8], use_test_rng: bool, ) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Commit); @@ -87,13 +87,8 @@ impl ComSignature { let commitment = secp.commit(amount, blind.clone())?; let nonce_commitment = secp.commit_blind(k_1.clone(), k_2.clone())?; - let e = ComSignature::calc_challenge( - &secp, - &commitment, - &nonce_commitment, - &msg, - use_test_rng, - )?; + let e = + ComSignature::calc_challenge(&secp, &commitment, &nonce_commitment, msg, use_test_rng)?; // s = k_1 + (e * amount) let mut s = k_amt.clone(); @@ -109,16 +104,16 @@ impl ComSignature { } /// Verify the commitment signature - pub fn verify(&self, commit: &Commitment, msg: &Vec) -> Result<(), ComSigError> { + pub fn verify(&self, commit: &Commitment, msg: &[u8]) -> Result<(), ComSigError> { let secp = Secp256k1::with_caps(ContextFlag::Commit); let s1 = secp.commit_blind(self.s.clone(), self.t.clone())?; let mut ce = commit.to_pubkey(&secp)?; - let e = ComSignature::calc_challenge(&secp, &commit, &self.pub_nonce, &msg, false)?; + let e = ComSignature::calc_challenge(&secp, commit, &self.pub_nonce, msg, false)?; ce.mul_assign(&secp, &e)?; - let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce.clone()]; + let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce]; let s2 = secp.commit_sum(commits, Vec::new())?; if s1 != s2 { @@ -132,7 +127,7 @@ impl ComSignature { secp: &Secp256k1, commit: &Commitment, nonce_commit: &Commitment, - msg: &Vec, + msg: &[u8], use_test_rng: bool, ) -> Result { let mut challenge_hasher = Blake2b::new(32); @@ -146,7 +141,7 @@ impl ComSignature { let mut challenge = [0; 32]; challenge.copy_from_slice(challenge_hasher.finalize().as_bytes()); - Ok(SecretKey::from_slice(&secp, &challenge)?) + Ok(SecretKey::from_slice(secp, &challenge)?) } } @@ -213,16 +208,16 @@ mod tests { let amount = thread_rng().next_u64(); let blind = SecretKey::new(&secp, &mut thread_rng()); let msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; - let comsig = ComSignature::sign(amount, &blind, &msg.to_vec(), false)?; + let comsig = ComSignature::sign(amount, &blind, msg.as_ref(), false)?; let commit = secp.commit(amount, blind.clone())?; - assert!(comsig.verify(&commit, &msg.to_vec()).is_ok()); + assert!(comsig.verify(&commit, msg.as_ref()).is_ok()); let wrong_msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17]; - assert!(comsig.verify(&commit, &wrong_msg.to_vec()).is_err()); + assert!(comsig.verify(&commit, wrong_msg.as_ref()).is_err()); let wrong_commit = secp.commit(amount, SecretKey::new(&secp, &mut thread_rng()))?; - assert!(comsig.verify(&wrong_commit, &msg.to_vec()).is_err()); + assert!(comsig.verify(&wrong_commit, msg.as_ref()).is_err()); Ok(()) } diff --git a/libwallet/src/mwixnet/onion/crypto/dalek.rs b/libwallet/src/mwixnet/onion/crypto/dalek.rs index adbebd7..1d02d7f 100644 --- a/libwallet/src/mwixnet/onion/crypto/dalek.rs +++ b/libwallet/src/mwixnet/onion/crypto/dalek.rs @@ -76,7 +76,7 @@ pub mod option_dalek_pubkey_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as hex, or null pub fn serialize(pk: &Option, serializer: S) -> Result where S: Serializer, @@ -87,7 +87,7 @@ pub mod option_dalek_pubkey_serde { } } - /// + /// Read an optional Ed25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -95,7 +95,7 @@ pub mod option_dalek_pubkey_serde { Option::::deserialize(deserializer).and_then(|res| match res { Some(string) => DalekPublicKey::from_hex(&string) .map_err(|e| Error::custom(e.to_string())) - .and_then(|pk: DalekPublicKey| Ok(Some(pk))), + .map(|pk: DalekPublicKey| Some(pk)), None => Ok(None), }) } @@ -130,8 +130,7 @@ impl DalekSignature { .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; let b = <[u8; 64]>::try_from(bytes.as_slice()) .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; - let sig = ed25519_dalek::Signature::try_from(b) - .map_err(|_| DalekError::HexError(format!("failed to decode {}", hex)))?; + let sig = ed25519_dalek::Signature::from(b); Ok(DalekSignature(sig)) } @@ -139,7 +138,7 @@ impl DalekSignature { #[allow(dead_code)] pub fn verify(&self, pk: &DalekPublicKey, msg: &[u8]) -> Result<(), DalekError> { pk.as_ref() - .verify(&msg, &self.0) + .verify(msg, &self.0) .map_err(|_| DalekError::SigVerifyFailed) } } @@ -157,7 +156,7 @@ pub mod dalek_sig_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 signature as hex pub fn serialize(sig: &DalekSignature, serializer: S) -> Result where S: Serializer, @@ -165,7 +164,7 @@ pub mod dalek_sig_serde { serializer.serialize_str(&sig.0.to_bytes().to_hex()) } - /// + /// Read an Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -180,7 +179,7 @@ pub mod dalek_sig_serde { pub fn sign(sk: &SecretKey, message: &[u8]) -> Result { use ed25519_dalek::{Signer, SigningKey}; let secret = SigningKey::from_bytes(&sk.0); - let sig = secret.sign(&message); + let sig = secret.sign(message); Ok(DalekSignature(sig)) } diff --git a/libwallet/src/mwixnet/onion/crypto/secp.rs b/libwallet/src/mwixnet/onion/crypto/secp.rs index 200c24f..19548d8 100644 --- a/libwallet/src/mwixnet/onion/crypto/secp.rs +++ b/libwallet/src/mwixnet/onion/crypto/secp.rs @@ -61,7 +61,7 @@ pub fn add_excess( let secp = Secp256k1::with_caps(ContextFlag::Commit); let excess_commit: Commitment = secp.commit(0, excess.clone())?; - let commits = vec![commitment.clone(), excess_commit.clone()]; + let commits = vec![*commitment, excess_commit]; let sum = secp.commit_sum(commits, Vec::new())?; Ok(sum) } @@ -70,7 +70,7 @@ pub fn add_excess( pub fn sub_value(commitment: &Commitment, value: u64) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Commit); let neg_commit: Commitment = secp.commit(value, ZERO_KEY)?; - let sum = secp.commit_sum(vec![commitment.clone()], vec![neg_commit.clone()])?; + let sum = secp.commit_sum(vec![*commitment], vec![neg_commit])?; Ok(sum) } @@ -81,11 +81,11 @@ pub fn sign( msg: &grin_util::secp::Message, ) -> Result { let secp = Secp256k1::with_caps(ContextFlag::Full); - let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, &sk)?; + let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, sk)?; let sig = grin_util::secp::aggsig::sign_single( &secp, - &msg, - &sk, + msg, + sk, None, None, None, diff --git a/libwallet/src/mwixnet/onion/mod.rs b/libwallet/src/mwixnet/onion/mod.rs index e1eb424..aa3d7c3 100644 --- a/libwallet/src/mwixnet/onion/mod.rs +++ b/libwallet/src/mwixnet/onion/mod.rs @@ -15,6 +15,7 @@ //! Onion module definition pub mod crypto; +#[allow(clippy::module_inception)] pub mod onion; pub mod util; @@ -56,9 +57,9 @@ pub fn new_hop( proof: Option, ) -> Hop { Hop { - server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0.clone())), + server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0)), excess: hop_excess.clone(), - fee: FeeFields::from(fee as u32), + fee: FeeFields::from(fee), rangeproof: proof, } } @@ -66,13 +67,13 @@ pub fn new_hop( /// Create an Onion for the Commitment, encrypting the payload for each hop pub fn create_onion( commitment: &Commitment, - hops: &Vec, + hops: &[Hop], use_test_rng: bool, ) -> Result { if hops.is_empty() { return Ok(Onion { ephemeral_pubkey: xPublicKey::from([0u8; 32]), - commit: commitment.clone(), + commit: *commitment, enc_payloads: vec![], }); } @@ -96,22 +97,22 @@ pub fn create_onion( let payload = Payload { next_ephemeral_pk, excess: hop.excess.clone(), - fee: hop.fee.clone(), - rangeproof: hop.rangeproof.clone(), + fee: hop.fee, + rangeproof: hop.rangeproof, }; enc_payloads.push(payload.serialize()?); } for i in (0..shared_secrets.len()).rev() { let mut cipher = new_stream_cipher(&shared_secrets[i])?; - for j in i..shared_secrets.len() { - cipher.apply_keystream(&mut enc_payloads[j]); + for payload in enc_payloads.iter_mut().skip(i) { + cipher.apply_keystream(payload); } } let onion = Onion { ephemeral_pubkey: onion_ephemeral_pk, - commit: commitment.clone(), + commit: *commitment, enc_payloads, }; Ok(onion) @@ -182,7 +183,7 @@ pub mod test_util { let mut blind = input_blind.clone(); for hop_excess in hop_excesses { - blind.add_assign(&secp, &hop_excess).unwrap(); + blind.add_assign(&secp, hop_excess).unwrap(); } let out_value = value - (fee as u64); diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index 46e6690..e135a52 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -94,7 +94,7 @@ pub struct Payload { impl Payload { /// Deserialize - pub fn deserialize(bytes: &Vec) -> Result { + pub fn deserialize(bytes: &[u8]) -> Result { let payload: Payload = ser::deserialize_default(&mut &bytes[..])?; Ok(payload) } @@ -131,7 +131,7 @@ impl Readable for Payload { impl Writeable for Payload { fn write(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_u8(CURRENT_ONION_VERSION)?; - writer.write_fixed_bytes(&self.next_ephemeral_pk.as_bytes())?; + writer.write_fixed_bytes(self.next_ephemeral_pk.as_bytes())?; writer.write_fixed_bytes(&self.excess)?; writer.write_u64(self.fee.into())?; write_optional(writer, &self.rangeproof)?; @@ -163,8 +163,8 @@ impl Onion { let mut decrypted_bytes = self.enc_payloads[0].clone(); cipher.apply_keystream(&mut decrypted_bytes); - let decrypted_payload = Payload::deserialize(&decrypted_bytes) - .map_err(|e| OnionError::DeserializationError(e))?; + let decrypted_payload = + Payload::deserialize(&decrypted_bytes).map_err(OnionError::DeserializationError)?; let enc_payloads: Vec = self .enc_payloads @@ -178,15 +178,15 @@ impl Onion { }) .collect(); - let mut commitment = self.commit.clone(); + let mut commitment = self.commit; commitment = secp::add_excess(&commitment, &decrypted_payload.excess) - .map_err(|e| OnionError::CalcCommitError(e))?; + .map_err(OnionError::CalcCommitError)?; commitment = secp::sub_value(&commitment, decrypted_payload.fee.into()) - .map_err(|e| OnionError::CalcCommitError(e))?; + .map_err(OnionError::CalcCommitError)?; let peeled_onion = Onion { ephemeral_pubkey: decrypted_payload.next_ephemeral_pk, - commit: commitment.clone(), + commit: commitment, enc_payloads, }; Ok(PeeledOnion { @@ -205,13 +205,13 @@ pub fn new_stream_cipher(shared_secret: &SharedSecret) -> Result(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_fixed_bytes(self.ephemeral_pubkey.as_bytes())?; - writer.write_fixed_bytes(&self.commit)?; + writer.write_fixed_bytes(self.commit)?; writer.write_u64(self.enc_payloads.len() as u64)?; for p in &self.enc_payloads { writer.write_u64(p.len() as u64)?; @@ -326,7 +326,7 @@ impl<'de> serde::de::Deserialize<'de> for Onion { } const FIELDS: &[&str] = &["pubkey", "commit", "data"]; - deserializer.deserialize_struct("Onion", &FIELDS, OnionVisitor) + deserializer.deserialize_struct("Onion", FIELDS, OnionVisitor) } } @@ -419,13 +419,13 @@ mod tests { crate::mwixnet::onion::create_onion(&commitment, &hops, false).unwrap(); let mut payload = Payload { - next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(), + next_ephemeral_pk: onion_packet.ephemeral_pubkey, excess: random_secret(false), fee: FeeFields::from(fee_per_hop), rangeproof: None, }; - for i in 0..5 { - let peeled = onion_packet.peel_layer(&keys[i]).unwrap(); + for key in &keys { + let peeled = onion_packet.peel_layer(key).unwrap(); payload = peeled.payload; onion_packet = peeled.onion; } diff --git a/libwallet/src/mwixnet/onion/util.rs b/libwallet/src/mwixnet/onion/util.rs index 6661177..a5df490 100644 --- a/libwallet/src/mwixnet/onion/util.rs +++ b/libwallet/src/mwixnet/onion/util.rs @@ -37,7 +37,7 @@ use std::convert::TryInto; /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional; +/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional; /// let mut writer:Vec = vec![]; /// let optional_value: Option = Some(10); /// //write_optional(&mut writer, &optional_value); @@ -75,7 +75,7 @@ pub fn write_optional( /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional; +/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional; /// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode}; /// let mut buf: &[u8] = &[1, 0, 0, 0, 10]; /// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default()); @@ -100,18 +100,18 @@ pub fn read_optional(reader: &mut R) -> Result /// # Returns /// /// * If successful, returns an `Ok` wrapping an array of size `S` containing -/// the first `S` bytes of `vec`. +/// the first `S` bytes of `vec`. /// * If `vec` is smaller than `S`, returns an `Err` indicating a count error. /// /// # Example /// /// ``` -/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array; +/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array; /// let v = vec![0, 1, 2, 3, 4, 5]; /// let a = vec_to_array::<4>(&v).unwrap(); /// assert_eq!(a, [0, 1, 2, 3]); /// ``` -pub fn vec_to_array(vec: &Vec) -> Result<[u8; S], ser::Error> { +pub fn vec_to_array(vec: &[u8]) -> Result<[u8; S], ser::Error> { if vec.len() < S { return Err(ser::Error::CountError); } diff --git a/libwallet/src/slate.rs b/libwallet/src/slate.rs index 9095d60..4ec38ef 100644 --- a/libwallet/src/slate.rs +++ b/libwallet/src/slate.rs @@ -16,22 +16,21 @@ //! around during an interactive wallet exchange use crate::error::Error; -use crate::grin_core::core::amount_to_hr_string; -use crate::grin_core::core::transaction::{ +use ed25519_dalek::Signature as DalekSignature; +use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::amount_to_hr_string; +use grin_core::core::transaction::{ FeeFields, Input, Inputs, KernelFeatures, NRDRelativeHeight, Output, OutputFeatures, Transaction, TxKernel, Weighting, }; -use crate::grin_core::libtx::{aggsig, build, proof::ProofBuild, tx_fee}; -use crate::grin_core::map_vec; -use crate::grin_keychain::{BlindSum, BlindingFactor, Keychain, SwitchCommitmentType}; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::pedersen::Commitment; -use crate::grin_util::secp::Signature; -use crate::grin_util::{secp, static_secp_instance}; -use ed25519_dalek::Signature as DalekSignature; -use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::libtx::{aggsig, build, proof::ProofBuild, tx_fee}; +use grin_core::map_vec; +use grin_keychain::{BlindSum, BlindingFactor, Keychain, SwitchCommitmentType}; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::pedersen::Commitment; +use grin_util::secp::Signature; +use grin_util::{secp, static_secp_instance}; use serde::ser::{Serialize, Serializer}; -use serde_json; use std::fmt; use uuid::Uuid; @@ -110,10 +109,10 @@ pub struct Slate { /// associated outputs pub ttl_cutoff_height: u64, /// Kernel Features flag - - /// 0: plain - /// 1: coinbase (invalid) - /// 2: height_locked - /// 3: NRD + /// 0: plain + /// 1: coinbase (invalid) + /// 2: height_locked + /// 3: NRD pub kernel_features: u8, /// Offset, needed when posting of transaction is deferred pub offset: BlindingFactor, @@ -167,19 +166,13 @@ impl fmt::Display for SlateState { } } -#[derive(Debug, Clone, PartialEq, Eq)] /// Kernel features arguments definition +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct KernelFeaturesArgs { /// Lock height, for HeightLocked (also NRD relative lock height) pub lock_height: u64, } -impl Default for KernelFeaturesArgs { - fn default() -> KernelFeaturesArgs { - KernelFeaturesArgs { lock_height: 0 } - } -} - /// Versioning and compatibility info about this slate #[derive(Debug, Clone)] pub struct VersionCompatInfo { @@ -226,9 +219,7 @@ impl Slate { /// Upgrade a versioned slate pub fn upgrade(v_slate: VersionedSlate) -> Result { - let v4: SlateV4 = match v_slate { - VersionedSlate::V4(s) => s, - }; + let VersionedSlate::V4(v4) = v_slate; Ok(v4.into()) } /// Compact the slate for initial sending, storing the excess + offset explicit @@ -287,8 +278,8 @@ impl Slate { where K: Keychain, { - let pub_nonce = PublicKey::from_secret_key(keychain.secp(), &sec_nonce)?; - let pub_key = PublicKey::from_secret_key(keychain.secp(), &sec_key)?; + let pub_nonce = PublicKey::from_secret_key(keychain.secp(), sec_nonce)?; + let pub_key = PublicKey::from_secret_key(keychain.secp(), sec_key)?; self.participant_data = self .participant_data .clone() @@ -357,14 +348,14 @@ impl Slate { fee: self.fee_fields, lock_height: match &self.kernel_features_args { Some(a) => a.lock_height, - None => return Err(Error::KernelFeaturesMissing(format!("lock_height"))), + None => return Err(Error::KernelFeaturesMissing("lock_height".to_string())), }, }), 3 => Ok(KernelFeatures::NoRecentDuplicate { fee: self.fee_fields, relative_height: match &self.kernel_features_args { Some(a) => NRDRelativeHeight::new(a.lock_height)?, - None => return Err(Error::KernelFeaturesMissing(format!("lock_height"))), + None => return Err(Error::KernelFeaturesMissing("lock_height".to_string())), }, }), n => Err(Error::UnknownKernelFeatures(n)), @@ -400,8 +391,8 @@ impl Slate { Some(&self.pub_blind_sum(keychain.secp())?), &self.msg_to_sign()?, )?; - let pub_excess = PublicKey::from_secret_key(keychain.secp(), &sec_key)?; - let pub_nonce = PublicKey::from_secret_key(keychain.secp(), &sec_nonce)?; + let pub_excess = PublicKey::from_secret_key(keychain.secp(), sec_key)?; + let pub_nonce = PublicKey::from_secret_key(keychain.secp(), sec_nonce)?; for i in 0..self.num_participants() as usize { // find my entry if self.participant_data[i].public_blind_excess == pub_excess @@ -431,8 +422,10 @@ impl Slate { .iter() .map(|p| &p.public_nonce) .collect(); - if pub_nonces.len() == 0 { - return Err(Error::Commit(format!("Participant nonces cannot be empty"))); + if pub_nonces.is_empty() { + return Err(Error::Commit( + "Participant nonces cannot be empty".to_string(), + )); } match PublicKey::from_combination(secp, pub_nonces) { Ok(k) => Ok(k), @@ -447,10 +440,10 @@ impl Slate { .iter() .map(|p| &p.public_blind_excess) .collect(); - if pub_blinds.len() == 0 { - return Err(Error::Commit(format!( - "Participant Blind sums cannot be empty" - ))); + if pub_blinds.is_empty() { + return Err(Error::Commit( + "Participant Blind sums cannot be empty".to_string(), + )); } match PublicKey::from_combination(secp, pub_blinds) { Ok(k) => Ok(k), @@ -462,8 +455,7 @@ impl Slate { fn part_sigs(&self) -> Vec<&Signature> { self.participant_data .iter() - .filter(|p| p.part_sig.is_some()) - .map(|p| p.part_sig.as_ref().unwrap()) + .filter_map(|p| p.part_sig.as_ref()) .collect() } @@ -493,7 +485,7 @@ impl Slate { .filter(|v| { if v.public_nonce == pub_nonce && v.public_blind_excess == pub_key - && part_sig == None + && part_sig.is_none() { part_sig = v.part_sig } @@ -504,7 +496,7 @@ impl Slate { self.participant_data.push(ParticipantData { public_blind_excess: pub_key, public_nonce: pub_nonce, - part_sig: part_sig, + part_sig, }); Ok(()) } @@ -603,7 +595,6 @@ impl Slate { /// fee (= M) /// /// Returns completed transaction ready for posting to the chain - fn finalize_signature(&mut self, secp: &secp::Secp256k1) -> Result { self.verify_part_sigs(secp)?; @@ -655,7 +646,7 @@ impl Slate { let mut kernel = final_tx.kernels()[0]; kernel.excess = final_excess; - kernel.excess_sig = final_sig.clone(); + kernel.excess_sig = *final_sig; let final_tx = final_tx.clone().replace_kernel(kernel); @@ -710,16 +701,10 @@ impl From for SlateV4 { payment_proof, kernel_features_args, } = slate.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantDataV4::from(data)); + let participant_data = map_vec!(participant_data, ParticipantDataV4::from); let ver = VersionCompatInfoV4::from(&version_info); - let payment_proof = match payment_proof { - Some(p) => Some(PaymentInfoV4::from(&p)), - None => None, - }; - let feat_args = match kernel_features_args { - Some(a) => Some(KernelFeaturesArgsV4::from(&a)), - None => None, - }; + let payment_proof = payment_proof.map(|p| PaymentInfoV4::from(&p)); + let feat_args = kernel_features_args.map(|a| KernelFeaturesArgsV4::from(&a)); let sta = SlateStateV4::from(&state); SlateV4 { num_parts, @@ -763,17 +748,13 @@ impl From<&Slate> for SlateV4 { let feat = *kernel_features; let ttl = *ttl; let off = offset.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantDataV4::from(data)); + let participant_data = map_vec!(participant_data, ParticipantDataV4::from); let ver = VersionCompatInfoV4::from(version_info); - let payment_proof = match payment_proof { - Some(p) => Some(PaymentInfoV4::from(p)), - None => None, - }; + let payment_proof = payment_proof.as_ref().map(PaymentInfoV4::from); let sta = SlateStateV4::from(state); - let feat_args = match kernel_features_args { - Some(a) => Some(KernelFeaturesArgsV4::from(a)), - None => None, - }; + let feat_args = kernel_features_args + .as_ref() + .map(KernelFeaturesArgsV4::from); SlateV4 { num_parts, id, @@ -916,16 +897,10 @@ impl From for Slate { proof: payment_proof, feat_args, } = slate.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantData::from(data)); + let participant_data = map_vec!(participant_data, ParticipantData::from); let version_info = VersionCompatInfo::from(&ver); - let payment_proof = match &payment_proof { - Some(p) => Some(PaymentInfo::from(p)), - None => None, - }; - let kernel_features_args = match &feat_args { - Some(a) => Some(KernelFeaturesArgs::from(a)), - None => None, - }; + let payment_proof = payment_proof.as_ref().map(PaymentInfo::from); + let kernel_features_args = feat_args.as_ref().map(KernelFeaturesArgs::from); let state = SlateState::from(&sta); Slate { num_participants, @@ -946,10 +921,7 @@ impl From for Slate { } pub fn tx_from_slate_v4(slate: &SlateV4) -> Option { - let coms = match slate.coms.as_ref() { - Some(c) => c, - None => return None, - }; + let coms = slate.coms.as_ref()?; let secp = static_secp_instance(); let secp = secp.lock(); let mut calc_slate = Slate::blank(2, false); @@ -992,7 +964,7 @@ pub fn tx_from_slate_v4(slate: &SlateV4) -> Option { for c in coms.iter() { match &c.p { Some(p) => { - outputs.push(Output::new(c.f.into(), c.c, p.clone())); + outputs.push(Output::new(c.f.into(), c.c, *p)); } None => { inputs.push(Input { @@ -1095,7 +1067,7 @@ impl From for OutputFeatures { fn from(of: OutputFeaturesV4) -> OutputFeatures { match of.0 { 1 => OutputFeatures::Coinbase, - 0 | _ => OutputFeatures::Plain, + _ => OutputFeatures::Plain, } } } diff --git a/libwallet/src/slate_versions/ser.rs b/libwallet/src/slate_versions/ser.rs index b9395c4..30e0b47 100644 --- a/libwallet/src/slate_versions/ser.rs +++ b/libwallet/src/slate_versions/ser.rs @@ -34,14 +34,14 @@ where .and_then(|string| base64::decode(&string).map_err(|err| Error::custom(err.to_string()))) } -/// Serializes an Option to and from hex +/// Optional range proof as hex pub mod option_rangeproof_hex { - use crate::grin_util::secp::pedersen::RangeProof; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::secp::pedersen::RangeProof; + use grin_util::{from_hex, ToHex}; use serde::de::{Error, IntoDeserializer}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the range proof as hex, or null pub fn serialize(proof: &Option, serializer: S) -> Result where S: Serializer, @@ -52,7 +52,7 @@ pub mod option_rangeproof_hex { } } - /// + /// Read an optional range proof from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -66,7 +66,7 @@ pub mod option_rangeproof_hex { } } -/// Serializes an OnionV3Address to and from hex +/// Optional onion address as text pub mod option_ov3_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -74,7 +74,7 @@ pub mod option_ov3_serde { use crate::util::{OnionV3Address, OnionV3AddressError}; - /// + /// Write the onion address as text, or null pub fn serialize(addr: &Option, serializer: S) -> Result where S: Serializer, @@ -85,7 +85,7 @@ pub mod option_ov3_serde { } } - /// + /// Read an optional onion address pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -93,13 +93,13 @@ pub mod option_ov3_serde { Option::::deserialize(deserializer).and_then(|res| match res { Some(s) => OnionV3Address::try_from(s.as_str()) .map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err))) - .and_then(|a| Ok(Some(a))), + .map(Some), None => Ok(None), }) } } -/// Serializes an OnionV3Address to and from hex +/// Onion address as text pub mod ov3_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; @@ -107,7 +107,7 @@ pub mod ov3_serde { use crate::util::{OnionV3Address, OnionV3AddressError}; - /// + /// Write the onion address as text pub fn serialize(addr: &OnionV3Address, serializer: S) -> Result where S: Serializer, @@ -115,7 +115,7 @@ pub mod ov3_serde { serializer.serialize_str(&addr.to_string()) } - /// + /// Read an onion address pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -123,18 +123,17 @@ pub mod ov3_serde { String::deserialize(deserializer).and_then(|s| { OnionV3Address::try_from(s.as_str()) .map_err(|err: OnionV3AddressError| Error::custom(format!("{:?}", err))) - .and_then(Ok) }) } } -/// Serializes an ed25519 PublicKey to and from hex +/// Ed25519 signing key as hex pub mod dalek_seckey_serde { - use crate::grin_util::{from_hex, ToHex}; use ed25519_dalek::SigningKey as DalekSecretKey; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 signing key as hex pub fn serialize(key: &DalekSecretKey, serializer: S) -> Result where S: Serializer, @@ -142,7 +141,7 @@ pub mod dalek_seckey_serde { serializer.serialize_str(&key.to_bytes().to_hex()) } - /// + /// Read an Ed25519 signing key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -160,11 +159,11 @@ pub mod dalek_seckey_serde { /// Serializes an ed25519 PublicKey to and from hex pub mod dalek_pubkey_serde { - use crate::grin_util::{from_hex, ToHex}; use ed25519_dalek::VerifyingKey as DalekPublicKey; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as hex pub fn serialize(key: &DalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -172,7 +171,7 @@ pub mod dalek_pubkey_serde { serializer.serialize_str(&key.to_bytes().to_hex()) } - /// + /// Read an Ed25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -193,11 +192,11 @@ pub mod dalek_pubkey_serde { /// Serializes a x25519 PublicKey to and from hex pub mod dalek_xpubkey_serde { - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; use serde::{Deserialize, Deserializer, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; - /// + /// Write the X25519 public key as hex pub fn serialize(key: &xDalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -205,7 +204,7 @@ pub mod dalek_xpubkey_serde { serializer.serialize_str(&key.as_bytes().to_hex()) } - /// + /// Read an X25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -213,10 +212,10 @@ pub mod dalek_xpubkey_serde { use serde::de::Error; String::deserialize(deserializer) .and_then(|string| from_hex(&string).map_err(|err| Error::custom(err.to_string()))) - .and_then(|bytes: Vec| { + .map(|bytes: Vec| { let mut b = [0u8; 32]; b.copy_from_slice(&bytes[0..32]); - Ok(xDalekPublicKey::from(b)) + xDalekPublicKey::from(b) }) } } @@ -227,7 +226,7 @@ pub mod dalek_pubkey_base64 { use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as base64 pub fn serialize(key: &DalekPublicKey, serializer: S) -> Result where S: Serializer, @@ -235,7 +234,7 @@ pub mod dalek_pubkey_base64 { serializer.serialize_str(&base64::encode(&key.to_bytes())) } - /// + /// Read an Ed25519 public key from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -256,14 +255,14 @@ pub mod dalek_pubkey_base64 { } } -/// Serializes an Option to and from hex +/// Optional Ed25519 public key as base64 pub mod option_dalek_pubkey_base64 { use base64; use ed25519_dalek::VerifyingKey as DalekPublicKey; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Write the Ed25519 public key as base64, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -274,7 +273,7 @@ pub mod option_dalek_pubkey_base64 { } } - /// + /// Read an optional Ed25519 public key from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -303,9 +302,9 @@ pub mod option_dalek_pubkey_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 public key as hex, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -316,7 +315,7 @@ pub mod option_dalek_pubkey_serde { } } - /// + /// Read an optional Ed25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -342,9 +341,9 @@ pub mod option_xdalek_pubkey_serde { use serde::{Deserialize, Deserializer, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the X25519 public key as hex, or null pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -355,7 +354,7 @@ pub mod option_xdalek_pubkey_serde { } } - /// + /// Read an optional X25519 public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -363,10 +362,10 @@ pub mod option_xdalek_pubkey_serde { Option::::deserialize(deserializer).and_then(|res| match res { Some(string) => from_hex(&string) .map_err(|err| Error::custom(err.to_string())) - .and_then(|bytes: Vec| { + .map(|bytes: Vec| { let mut b = [0u8; 32]; b.copy_from_slice(&bytes[0..32]); - Ok(Some(xDalekPublicKey::from(b))) + Some(xDalekPublicKey::from(b)) }), None => Ok(None), }) @@ -380,9 +379,9 @@ pub mod dalek_sig_serde { use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 signature as hex pub fn serialize(sig: &DalekSignature, serializer: S) -> Result where S: Serializer, @@ -390,7 +389,7 @@ pub mod dalek_sig_serde { serializer.serialize_str(&sig.to_bytes().as_ref().to_hex()) } - /// + /// Read an Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -400,21 +399,21 @@ pub mod dalek_sig_serde { .and_then(|bytes: Vec| { let b = <[u8; 64]>::try_from(bytes.as_slice()) .map_err(|_| Error::custom("invalid signature length"))?; - DalekSignature::try_from(b).map_err(|err| Error::custom(err.to_string())) + Ok(DalekSignature::from(b)) }) } } -/// Serializes an Option to and from hex +/// Optional Ed25519 signature as hex pub mod option_dalek_sig_serde { use ed25519_dalek::Signature as DalekSignature; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - use crate::grin_util::{from_hex, ToHex}; + use grin_util::{from_hex, ToHex}; - /// + /// Write the Ed25519 signature as hex, or null pub fn serialize(sig: &Option, serializer: S) -> Result where S: Serializer, @@ -425,7 +424,7 @@ pub mod option_dalek_sig_serde { } } - /// + /// Read an optional Ed25519 signature from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -436,16 +435,14 @@ pub mod option_dalek_sig_serde { .and_then(|bytes: Vec| { let b = <[u8; 64]>::try_from(bytes.as_slice()) .map_err(|_| Error::custom("invalid signature length"))?; - DalekSignature::try_from(b) - .map(Some) - .map_err(|err| Error::custom(err.to_string())) + Ok(Some(DalekSignature::from(b))) }), None => Ok(None), }) } } -/// Serializes an Option to and from base64 +/// Optional Ed25519 signature as base64 pub mod option_dalek_sig_base64 { use base64; use ed25519_dalek::Signature as DalekSignature; @@ -453,7 +450,7 @@ pub mod option_dalek_sig_base64 { use serde::{Deserialize, Deserializer, Serializer}; use std::convert::TryFrom; - /// + /// Write the Ed25519 signature as base64, or null pub fn serialize(sig: &Option, serializer: S) -> Result where S: Serializer, @@ -464,7 +461,7 @@ pub mod option_dalek_sig_base64 { } } - /// + /// Read an optional Ed25519 signature from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -475,9 +472,7 @@ pub mod option_dalek_sig_base64 { .and_then(|bytes: Vec| { let b = <[u8; 64]>::try_from(bytes.as_slice()) .map_err(|_| Error::custom("invalid signature length"))?; - DalekSignature::try_from(b) - .map(Some) - .map_err(|err| Error::custom(err.to_string())) + Ok(Some(DalekSignature::from(b))) }), None => Ok(None), }) @@ -491,7 +486,7 @@ pub mod version_info_v4 { use crate::slate_versions::v4::VersionCompatInfoV4; - /// + /// Write the version as `slate_version:block_header_version` pub fn serialize(v: &VersionCompatInfoV4, serializer: S) -> Result where S: Serializer, @@ -499,7 +494,7 @@ pub mod version_info_v4 { serializer.serialize_str(&format!("{}:{}", v.version, v.block_header_version)) } - /// + /// Read `slate_version:block_header_version` pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -513,11 +508,11 @@ pub mod version_info_v4 { if v.len() != 2 { return Err(Error::custom("Cannot parse version")); } - match u16::from_str_radix(v[0], 10) { + match v[0].parse::() { Ok(u) => retval.version = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } - match u16::from_str_radix(v[1], 10) { + match v[1].parse::() { Ok(u) => retval.block_header_version = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } @@ -533,7 +528,7 @@ pub mod slate_state_v4 { use crate::slate_versions::v4::SlateStateV4; - /// + /// Write the state as `NA`, `S1`–`S3` or `I1`–`I3` pub fn serialize(st: &SlateStateV4, serializer: S) -> Result where S: Serializer, @@ -550,7 +545,7 @@ pub mod slate_state_v4 { serializer.serialize_str(label) } - /// + /// Read a slate state label pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -571,13 +566,13 @@ pub mod slate_state_v4 { } } -/// Serializes an secp256k1 pubkey to base64 +/// UUID as base64 pub mod uuid_base64 { use base64; use serde::{Deserialize, Deserializer, Serializer}; use uuid::Uuid; - /// + /// Write the UUID bytes as base64 pub fn serialize(id: &Uuid, serializer: S) -> Result where S: Serializer, @@ -585,7 +580,7 @@ pub mod uuid_base64 { serializer.serialize_str(&base64::encode(&id.as_bytes())) } - /// + /// Read a UUID from base64 pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -595,10 +590,10 @@ pub mod uuid_base64 { .and_then(|string| { base64::decode(&string).map_err(|err| Error::custom(err.to_string())) }) - .and_then(|bytes: Vec| { + .map(|bytes: Vec| { let mut b = [0u8; 16]; b.copy_from_slice(&bytes[0..16]); - Ok(Uuid::from_bytes(b)) + Uuid::from_bytes(b) }) } } @@ -608,11 +603,11 @@ mod test { use super::*; use rand::rngs::mock::StepRng; - use crate::grin_util::{secp, static_secp_instance}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::Signer; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::VerifyingKey as DalekPublicKey; + use grin_util::{secp, static_secp_instance}; use serde::Deserialize; use serde_json; @@ -642,9 +637,9 @@ mod test { println!("D sig: {:?}", d_sig); SerTest { - pub_key: d_pub_key.clone(), + pub_key: d_pub_key, pub_key_opt: Some(d_pub_key), - sig: d_sig.clone(), + sig: d_sig, sig_opt: Some(d_sig), } } diff --git a/libwallet/src/slate_versions/v4.rs b/libwallet/src/slate_versions/v4.rs index a3ba1b1..a2348b2 100644 --- a/libwallet/src/slate_versions/v4.rs +++ b/libwallet/src/slate_versions/v4.rs @@ -34,7 +34,7 @@ //! * The feat_args struct is added, which may be populated for non-Plain kernels //! * `proof` may be omitted from the slate if it is None (null), //! * `off` (offset) is added, and will be modified by every participant in the transaction with a random -//! value - the value of their inputs' blinding factors +//! value - the value of their inputs' blinding factors //! //! #### Participant Data (`sigs`) //! @@ -53,17 +53,17 @@ //! * The `receiver_signature` field is renamed to `rsig` //! * `rsig` may be omitted if it has not yet been filled out -use crate::grin_core::core::FeeFields; -use crate::grin_core::core::{Input, Output, TxKernel}; -use crate::grin_core::libtx::secp_ser; -use crate::grin_keychain::{BlindingFactor, Identifier}; -use crate::grin_util::secp; -use crate::grin_util::secp::key::PublicKey; -use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; -use crate::grin_util::secp::Signature; use crate::{slate_versions::ser, CbData}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::FeeFields; +use grin_core::core::{Input, Output, TxKernel}; +use grin_core::libtx::secp_ser; +use grin_keychain::{BlindingFactor, Identifier}; +use grin_util::secp; +use grin_util::secp::key::PublicKey; +use grin_util::secp::pedersen::{Commitment, RangeProof}; +use grin_util::secp::Signature; use uuid::Uuid; #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/libwallet/src/slate_versions/v4_bin.rs b/libwallet/src/slate_versions/v4_bin.rs index 5a4ad38..2c45331 100644 --- a/libwallet/src/slate_versions/v4_bin.rs +++ b/libwallet/src/slate_versions/v4_bin.rs @@ -14,15 +14,15 @@ //! Wraps a V4 Slate into a V4 Binary slate -use crate::grin_core::core::transaction::{FeeFields, OutputFeatures}; -use crate::grin_core::ser as grin_ser; -use crate::grin_core::ser::{Readable, Reader, Writeable, Writer}; -use crate::grin_keychain::BlindingFactor; -use crate::grin_util::secp::key::PublicKey; -use crate::grin_util::secp::pedersen::{Commitment, RangeProof}; -use crate::grin_util::secp::Signature; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::transaction::{FeeFields, OutputFeatures}; +use grin_core::ser as grin_ser; +use grin_core::ser::{Readable, Reader, Writeable, Writer}; +use grin_keychain::BlindingFactor; +use grin_util::secp::key::PublicKey; +use grin_util::secp::pedersen::{Commitment, RangeProof}; +use grin_util::secp::Signature; use std::convert::TryFrom; use uuid::Uuid; @@ -68,7 +68,7 @@ struct UuidWrap(Uuid); impl Writeable for UuidWrap { fn write(&self, writer: &mut W) -> Result<(), grin_ser::Error> { - writer.write_fixed_bytes(&self.0.as_bytes()) + writer.write_fixed_bytes(self.0.as_bytes()) } } @@ -211,7 +211,7 @@ impl Readable for SigsWrap { nonce: PublicKey::read(reader)?, part: match has_partial { 1 => Some(Signature::read(reader)?), - 0 | _ => None, + _ => None, }, }; ret.push(c); @@ -252,10 +252,10 @@ impl<'a> Writeable for SlateOptStructsRef<'a> { }; writer.write_u8(status)?; if let Some(c) = self.coms { - ComsWrapRef(&c).write(writer)?; + ComsWrapRef(c).write(writer)?; } if let Some(p) = self.proof { - ProofWrapRef(&p).write(writer)?; + ProofWrapRef(p).write(writer)?; } Ok(()) } @@ -314,7 +314,7 @@ impl Readable for ComsWrap { c: Commitment::read(reader)?, p: match is_output { 1 => Some(RangeProof::read(reader)?), - 0 | _ => None, + _ => None, }, }; ret.push(c); @@ -335,7 +335,7 @@ impl<'a> Writeable for ProofWrapRef<'a> { match self.0.rsig { Some(s) => { writer.write_u8(1)?; - writer.write_fixed_bytes(&s.to_bytes().to_vec())?; + writer.write_fixed_bytes(s.to_bytes())?; } None => writer.write_u8(0)?, } @@ -359,7 +359,7 @@ impl Readable for ProofWrap { let rsig = match reader.read_u8()? { 0 => None, - 1 | _ => Some( + _ => Some( DalekSignature::try_from(&reader.read_fixed_bytes(64)?[..]) .map_err(|_| grin_ser::Error::CorruptedData)?, ), @@ -503,11 +503,11 @@ impl Readable for SlateV4Bin { #[test] fn slate_v4_serialize_deserialize() { - use crate::grin_util::from_hex; - use crate::grin_util::secp::key::PublicKey; use crate::Slate; use grin_core::global::{set_local_chain_type, ChainTypes}; use grin_keychain::{ExtKeychain, Keychain, SwitchCommitmentType}; + use grin_util::from_hex; + use grin_util::secp::key::PublicKey; set_local_chain_type(ChainTypes::Mainnet); let slate = Slate::blank(1, false); @@ -547,11 +547,7 @@ fn slate_v4_serialize_deserialize() { c: Commitment::from_vec([4u8; 1].to_vec()), p: Some(RangeProof::zero()), }; - let mut coms = vec![]; - coms.push(com1.clone()); - coms.push(com1.clone()); - coms.push(com1.clone()); - coms.push(com2); + let coms = vec![com1, com1, com1, com2]; v4.coms = Some(coms); v4.amt = 234324899824; @@ -563,7 +559,7 @@ fn slate_v4_serialize_deserialize() { let v4_bin = SlateV4Bin(v4); let mut vec = Vec::new(); - let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); + grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap(); let v4_2 = b4_bin_2.0.clone(); assert_eq!(v4_1.ver, v4_2.ver); @@ -586,15 +582,15 @@ fn slate_v4_serialize_deserialize() { let b = <&[u8; 32]>::try_from(bytes.as_slice()).unwrap(); let d_pkey = DalekPublicKey::from_bytes(b.as_array().unwrap()).unwrap(); v4.proof = Some(PaymentInfoV4 { - raddr: d_pkey.clone(), - saddr: d_pkey.clone(), + raddr: d_pkey, + saddr: d_pkey, rsig: None, }); v4.coms = None; let v4_1 = v4.clone(); let v4_bin = SlateV4Bin(v4); let mut vec = Vec::new(); - let _ = grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); + grin_ser::serialize_default(&mut vec, &v4_bin).expect("serialization failed"); let b4_bin_2: SlateV4Bin = grin_ser::deserialize_default(&mut &vec[..]).unwrap(); let v4_2 = b4_bin_2.0.clone(); assert_eq!(v4_1.ver, v4_2.ver); diff --git a/libwallet/src/slatepack/address.rs b/libwallet/src/slatepack/address.rs index 9368e38..4add579 100644 --- a/libwallet/src/slatepack/address.rs +++ b/libwallet/src/slatepack/address.rs @@ -20,11 +20,11 @@ use rand::{thread_rng, Rng}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use x25519_dalek::PublicKey as xDalekPublicKey; -use crate::grin_core::global; -use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer}; -use crate::grin_util::secp::key::SecretKey; use crate::util::OnionV3Address; use crate::Error; +use grin_core::global; +use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; +use grin_util::secp::key::SecretKey; use std::convert::TryFrom; use std::fmt::{self, Display}; @@ -53,7 +53,7 @@ impl SlatepackAddress { pub fn new(pub_key: &edDalekPublicKey) -> Self { Self { hrp: String::from(slatepack_hrp()), - pub_key: pub_key.clone(), + pub_key: *pub_key, } } @@ -68,7 +68,7 @@ impl SlatepackAddress { pub fn encoded_len(&self) -> Result { let encoded = String::try_from(self)?; // add length byte - Ok(encoded.as_bytes().len() + 1) + Ok(encoded.len() + 1) } /// utility to construct a public key that can be read by age 0.5+, @@ -97,7 +97,7 @@ impl Display for SlatepackAddress { impl TryFrom<&str> for SlatepackAddress { type Error = Error; fn try_from(encoded: &str) -> Result { - let (hrp, data) = bech32::decode(&encoded)?; + let (hrp, data) = bech32::decode(encoded)?; if !valid_network(&hrp) { return Err(Error::SlatepackAddress(format!( "wrong address prefix for chain {:?}", @@ -107,7 +107,7 @@ impl TryFrom<&str> for SlatepackAddress { let bytes = Vec::::from_base32(&data)?; let b = <&[u8; 32]>::try_from(bytes.as_slice()) .map_err(|_| Error::SlatepackAddress("Wrong encoded data".to_string()))?; - let pub_key = match edDalekPublicKey::from_bytes(&b) { + let pub_key = match edDalekPublicKey::from_bytes(b) { Ok(k) => k, Err(e) => { return Err(Error::ED25519Key(format!("{}", e))); @@ -170,7 +170,6 @@ impl TryFrom<&SecretKey> for SlatepackAddress { /// Serializes a SlatepackAddress to a bech32 string impl Serialize for SlatepackAddress { - /// fn serialize(&self, serializer: S) -> Result where S: Serializer, @@ -232,7 +231,7 @@ impl Writeable for SlatepackAddress { return Err(ser::Error::CorruptedData); } writer.write_u8(bytes.len() as u8)?; - writer.write_fixed_bytes(&bytes) + writer.write_fixed_bytes(bytes) } } diff --git a/libwallet/src/slatepack/armor.rs b/libwallet/src/slatepack/armor.rs index c8be299..9178284 100644 --- a/libwallet/src/slatepack/armor.rs +++ b/libwallet/src/slatepack/armor.rs @@ -50,11 +50,9 @@ pub fn min_size() -> u64 { } lazy_static! { - static ref HEADER_REGEX: Regex = - Regex::new(concat!(r"^[>\n\r\t ]*BEGINSLATEPACK[>\n\r\t ]*$")).unwrap(); - static ref FOOTER_REGEX: Regex = - Regex::new(concat!(r"^[>\n\r\t ]*ENDSLATEPACK[>\n\r\t ]*$")).unwrap(); - static ref WHITESPACE_LIST: [u8; 5] = [b'>', b'\n', b'\r', b'\t', b' ']; + static ref HEADER_REGEX: Regex = Regex::new(r"^[>\n\r\t ]*BEGINSLATEPACK[>\n\r\t ]*$").unwrap(); + static ref FOOTER_REGEX: Regex = Regex::new(r"^[>\n\r\t ]*ENDSLATEPACK[>\n\r\t ]*$").unwrap(); + static ref WHITESPACE_LIST: [u8; 5] = *b">\n\r\t "; } /// Wrapper for associated functions diff --git a/libwallet/src/slatepack/packer.rs b/libwallet/src/slatepack/packer.rs index d2eda6d..d0575fc 100644 --- a/libwallet/src/slatepack/packer.rs +++ b/libwallet/src/slatepack/packer.rs @@ -52,7 +52,7 @@ impl<'a> Slatepacker<'a> { // check if data is armored, if so, remove and continue let data_len = data.len() as u64; if data_len < slatepack::min_size() || data_len > slatepack::max_size() { - let msg = format!("Data invalid length"); + let msg = "Data invalid length".to_string(); return Err(Error::SlatepackDeser(msg)); } @@ -105,7 +105,7 @@ impl<'a> Slatepacker<'a> { /// Armor a slatepack pub fn armor_slatepack(&self, slatepack: &Slatepack) -> Result { - SlatepackArmor::encode(&slatepack) + SlatepackArmor::encode(slatepack) } /// Return/upgrade slate from slatepack @@ -116,6 +116,6 @@ impl<'a> Slatepacker<'a> { let msg = format!("{}", e); Error::SlatepackDeser(msg) })?; - Ok(Slate::upgrade(slate_bin.into())?) + Slate::upgrade(slate_bin.into()) } } diff --git a/libwallet/src/slatepack/types.rs b/libwallet/src/slatepack/types.rs index 72867a9..aef6a02 100644 --- a/libwallet/src/slatepack/types.rs +++ b/libwallet/src/slatepack/types.rs @@ -20,8 +20,8 @@ use sha2::{Digest, Sha512}; use x25519_dalek::StaticSecret; use crate::dalek_ser; -use crate::grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use crate::Error; +use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use grin_wallet_util::byte_ser; use super::SlatepackAddress; @@ -155,7 +155,7 @@ impl Slatepack { to_encrypt.append(&mut self.payload); - let rec_keys: Result, _> = recipients + let rec_keys: Result, Error> = recipients .into_iter() .map(|addr| { let recp_key: age::x25519::Recipient = addr.to_age_pubkey_str()?.parse()?; @@ -163,10 +163,7 @@ impl Slatepack { }) .collect(); - let keys = match rec_keys { - Ok(k) => k, - Err(e) => return Err(e), - }; + let keys = rec_keys?; let encryptor = age::Encryptor::with_recipients(keys); let mut encrypted = vec![]; @@ -196,7 +193,7 @@ impl Slatepack { let x_dec_secret = StaticSecret::from(b); let x_dec_secret_bech32 = - bech32::encode("age-secret-key-", (&x_dec_secret).to_bytes().to_base32())?; + bech32::encode("age-secret-key-", x_dec_secret.to_bytes().to_base32())?; let key: age::x25519::Identity = x_dec_secret_bech32.parse()?; let decryptor = match age::Decryptor::new(&self.payload[..])? { @@ -427,7 +424,7 @@ pub mod slatepack_version { use super::SlatepackVersion; - /// + /// Write the Slatepack version as `major.minor` pub fn serialize(v: &SlatepackVersion, serializer: S) -> Result where S: Serializer, @@ -435,7 +432,7 @@ pub mod slatepack_version { serializer.serialize_str(&format!("{}.{}", v.major, v.minor)) } - /// + /// Read a `major.minor` Slatepack version pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -446,11 +443,11 @@ pub mod slatepack_version { if v.len() != 2 { return Err(Error::custom("Cannot parse version")); } - match u8::from_str_radix(v[0], 10) { + match v[0].parse::() { Ok(u) => retval.major = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } - match u8::from_str_radix(v[1], 10) { + match v[1].parse::() { Ok(u) => retval.minor = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } @@ -573,7 +570,7 @@ impl Writeable for SlatepackEncMetadataBin { if !inner.recipients.is_empty() { let len = inner.recipients.len(); // write number of recipients - if len as u16 > std::u16::MAX { + if len > u16::MAX as usize { error!("Too many recipients: {}", len); return Err(ser::Error::CorruptedData); } @@ -663,7 +660,7 @@ fn slatepack_bin_basic_ser() -> Result<(), grin_wallet_util::byte_ser::Error> { #[test] fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Error> { - use crate::grin_core::global; + use grin_core::global; use grin_wallet_util::byte_ser; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let mut payload: Vec = Vec::with_capacity(243); @@ -688,8 +685,8 @@ fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Erro // ensure that a slatepack with unknown data in the optional fields can be read #[test] fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { - use crate::grin_core::global; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + use grin_core::global; use grin_wallet_util::byte_ser; use rand::{thread_rng, Rng}; use std::io::Cursor; @@ -733,9 +730,7 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { let end_head_pos = opt_fields_len as usize + 8 + 1; - for i in 0..end_head_pos { - new_bytes.push(ser[i]); - } + new_bytes.extend_from_slice(&ser[..end_head_pos]); for _ in 0..num_extra_bytes { new_bytes.push(thread_rng().gen()); } @@ -753,9 +748,7 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { let mut wtr = vec![]; wtr.write_u32::(opt_fields_len + num_extra_bytes as u32) .unwrap(); - for i in 0..wtr.len() { - new_bytes[5 + i] = wtr[i]; - } + new_bytes[5..(wtr.len() + 5)].copy_from_slice(&wtr[..]); let deser = byte_ser::from_bytes::(&new_bytes)?.0; assert_eq!(sp, deser); @@ -766,10 +759,10 @@ fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { // if mode == 1 #[test] fn slatepack_encrypted_meta() -> Result<(), Error> { - use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; + use grin_core::global; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); @@ -784,8 +777,10 @@ fn slatepack_encrypted_meta() -> Result<(), Error> { let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap(); assert_eq!(addr, parsed_addr); - let mut slatepack = super::Slatepack::default(); - slatepack.sender = Some(SlatepackAddress::random()); + let mut slatepack = Slatepack { + sender: Some(SlatepackAddress::random()), + ..Default::default() + }; slatepack.add_recipient(SlatepackAddress::random()); slatepack.add_recipient(SlatepackAddress::random()); @@ -815,10 +810,10 @@ fn slatepack_encrypted_meta() -> Result<(), Error> { // metadata won't break parsing #[test] fn slatepack_encrypted_meta_future() -> Result<(), Error> { - use crate::grin_core::global; use crate::{Slate, SlateVersion, VersionedBinSlate, VersionedSlate}; use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; + use grin_core::global; use rand::{thread_rng, Rng}; use std::convert::TryFrom; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); @@ -833,8 +828,10 @@ fn slatepack_encrypted_meta_future() -> Result<(), Error> { let parsed_addr = SlatepackAddress::try_from(encoded.as_str()).unwrap(); assert_eq!(addr, parsed_addr); - let mut slatepack = Slatepack::default(); - slatepack.sender = Some(SlatepackAddress::random()); + let mut slatepack = Slatepack { + sender: Some(SlatepackAddress::random()), + ..Default::default() + }; slatepack.add_recipient(SlatepackAddress::random()); slatepack.add_recipient(SlatepackAddress::random()); @@ -892,12 +889,12 @@ fn encrypt_plaintext_to_slatepack_recipient( #[test] fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> { - use crate::grin_core::global; + use grin_core::global; global::set_local_chain_type(global::ChainTypes::AutomatedTesting); let (ed_sec_key, addr) = slatepack_test_decryption_key(); - for plaintext in vec![vec![], vec![0], vec![0, 0, 0], vec![0xff; 4]] { + for plaintext in [vec![], vec![0], vec![0, 0, 0], vec![0xff; 4]] { let mut slatepack = Slatepack { mode: 1, payload: encrypt_plaintext_to_slatepack_recipient(&addr, &plaintext)?, diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index 76d7189..e7e3f69 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -17,25 +17,23 @@ use crate::config::{TorConfig, WalletConfig}; use crate::error::Error; -use crate::grin_core::core::hash::Hash; -use crate::grin_core::core::FeeFields; -use crate::grin_core::core::{Output, Transaction, TxKernel}; -use crate::grin_core::libtx::{aggsig, secp_ser}; -use crate::grin_core::{global, ser}; -use crate::grin_keychain::{Identifier, Keychain}; -use crate::grin_util::logger::LoggingConfig; -use crate::grin_util::secp::key::{PublicKey, SecretKey}; -use crate::grin_util::secp::{pedersen, Secp256k1}; -use crate::grin_util::{ToHex, ZeroingString}; use crate::slate_versions::ser as dalek_ser; use crate::{InitTxArgs, SlateState, WalletBackend}; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; +use grin_core::core::hash::Hash; +use grin_core::core::FeeFields; +use grin_core::core::{Output, Transaction, TxKernel}; +use grin_core::libtx::{aggsig, secp_ser}; +use grin_core::{global, ser}; +use grin_keychain::{Identifier, Keychain}; +use grin_util::logger::LoggingConfig; +use grin_util::secp::key::{PublicKey, SecretKey}; +use grin_util::secp::{pedersen, Secp256k1}; +use grin_util::{ToHex, ZeroingString}; use rand::rngs::mock::StepRng; use rand::thread_rng; -use serde; -use serde_json; use std::collections::HashMap; use std::time::Duration; use std::{cmp, fmt}; @@ -76,7 +74,7 @@ where tor_config: Option, ) -> Result<(), Error>; - /// + /// Create the seed file and wallet database from a mnemonic or fresh entropy fn create_wallet( &mut self, name: Option<&str>, @@ -86,7 +84,7 @@ where test_mode: bool, ) -> Result<(), Error>; - /// + /// Unlock the wallet and optionally mask its keychain fn open_wallet( &mut self, name: Option<&str>, @@ -95,7 +93,7 @@ where use_test_rng: bool, ) -> Result, Error>; - /// + /// Close the wallet and drop its stored keychain fn close_wallet(&mut self, name: Option<&str>) -> Result<(), Error>; /// whether a wallet exists at the given directory @@ -180,6 +178,7 @@ pub trait NodeClient: Send + Sync + Clone { /// Returns /// (last available output index, last insertion index retrieved, /// outputs(commit, proof, is_coinbase, height, mmr_index)) + #[allow(clippy::type_complexity)] fn get_outputs_by_pmmr_index( &self, start_height: u64, @@ -322,9 +321,8 @@ impl OutputData { /// Mark an output as reverted pub fn mark_reverted(&mut self) { - match self.status { - OutputStatus::Unspent => self.status = OutputStatus::Reverted, - _ => (), + if self.status == OutputStatus::Unspent { + self.status = OutputStatus::Reverted } } } @@ -876,17 +874,17 @@ pub struct ViewWallet { /// Utility struct for return values from below #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ViewWalletOutputResult { - /// + /// Output commitment as hex pub commit: String, - /// + /// Value in nanogrins pub value: u64, - /// + /// Block height of the output pub height: u64, - /// + /// Output position in the PMMR pub mmr_index: u64, - /// + /// Whether this is a mining reward pub is_coinbase: bool, - /// + /// Earliest spendable height pub lock_height: u64, } @@ -933,7 +931,7 @@ pub mod option_duration_as_secs { use serde::{Deserialize, Deserializer, Serializer}; use std::time::Duration; - /// + /// Write whole seconds as a string, or null pub fn serialize(dur: &Option, serializer: S) -> Result where S: Serializer, @@ -944,7 +942,7 @@ pub mod option_duration_as_secs { } } - /// + /// Read an optional duration from a seconds string pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, diff --git a/libwallet/tests/libwallet.rs b/libwallet/tests/libwallet.rs index 6d392a9..8c41703 100644 --- a/libwallet/tests/libwallet.rs +++ b/libwallet/tests/libwallet.rs @@ -56,7 +56,7 @@ fn aggsig_sender_receiver_interaction() { keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; @@ -75,10 +75,10 @@ fn aggsig_sender_receiver_interaction() { .blind_sum(&bs.sub_blinding_factor(BlindingFactor::from_secret_key(skey))) .unwrap(); - let blind = blinding_factor.secret_key(&keychain.secp()).unwrap(); + let blind = blinding_factor.secret_key(keychain.secp()).unwrap(); - s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - s_cx.get_public_keys(&keychain.secp()) + s_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + s_cx.get_public_keys(keychain.secp()) }; let pub_nonce_sum; @@ -91,8 +91,8 @@ fn aggsig_sender_receiver_interaction() { // let blind = blind_sum.secret_key(&keychain.secp())?; let blind = keychain.derive_key(0, &key_id, switch).unwrap(); - rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp()); + rx_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + let (pub_excess, pub_nonce) = rx_cx.get_public_keys(keychain.secp()); rx_cx.add_output(&key_id, &None, 0); pub_nonce_sum = PublicKey::from_combination( @@ -115,7 +115,7 @@ fn aggsig_sender_receiver_interaction() { let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -132,14 +132,14 @@ fn aggsig_sender_receiver_interaction() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_sig_part, &pub_nonce_sum, &receiver_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // now sender signs with their key @@ -147,7 +147,7 @@ fn aggsig_sender_receiver_interaction() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &s_cx.sec_key, &s_cx.sec_nonce, &pub_nonce_sum, @@ -164,14 +164,14 @@ fn aggsig_sender_receiver_interaction() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sender_sig_part, &pub_nonce_sum, &sender_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Receiver now builds final signature from sender and receiver parts @@ -180,7 +180,7 @@ fn aggsig_sender_receiver_interaction() { let msg = kernel_sig_msg(); let our_sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -191,7 +191,7 @@ fn aggsig_sender_receiver_interaction() { // Receiver now generates final signature from the two parts let final_sig = aggsig::add_signatures( - &keychain.secp(), + keychain.secp(), vec![&sender_sig_part, &our_sig_part], &pub_nonce_sum, ) @@ -217,13 +217,13 @@ fn aggsig_sender_receiver_interaction() { // Receiver check the final signature verifies let sig_verifies = aggsig::verify_completed_sig( - &keychain.secp(), + keychain.secp(), &final_sig, &final_pubkey, Some(&final_pubkey), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Check we can verify the sig using the kernel excess @@ -231,9 +231,9 @@ fn aggsig_sender_receiver_interaction() { let keychain = ExtKeychain::from_random_seed(true).unwrap(); let msg = kernel_sig_msg(); let sig_verifies = - aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess); + aggsig::verify_single_from_commit(keychain.secp(), &final_sig, &msg, &kernel_excess); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } } @@ -247,7 +247,7 @@ fn aggsig_sender_receiver_interaction_offset() { // This is the kernel offset that we use to split the key // Summing these at the block level prevents the // kernels from being used to reconstruct (or identify) individual transactions - let kernel_offset = SecretKey::new(&sender_keychain.secp(), &mut thread_rng()); + let kernel_offset = SecretKey::new(sender_keychain.secp(), &mut thread_rng()); // Calculate the kernel excess here for convenience. // Normally this would happen during transaction building. @@ -270,7 +270,7 @@ fn aggsig_sender_receiver_interaction_offset() { keychain .secp() - .commit(0, blinding_factor.secret_key(&keychain.secp()).unwrap()) + .commit(0, blinding_factor.secret_key(keychain.secp()).unwrap()) .unwrap() }; @@ -294,10 +294,10 @@ fn aggsig_sender_receiver_interaction_offset() { ) .unwrap(); - let blind = blinding_factor.secret_key(&keychain.secp()).unwrap(); + let blind = blinding_factor.secret_key(keychain.secp()).unwrap(); - s_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - s_cx.get_public_keys(&keychain.secp()) + s_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + s_cx.get_public_keys(keychain.secp()) }; // receiver receives partial tx @@ -309,8 +309,8 @@ fn aggsig_sender_receiver_interaction_offset() { let blind = keychain.derive_key(0, &key_id, switch).unwrap(); - rx_cx = Context::with_excess(&keychain.secp(), blind, &parent, false); - let (pub_excess, pub_nonce) = rx_cx.get_public_keys(&keychain.secp()); + rx_cx = Context::with_excess(keychain.secp(), blind, &parent, false); + let (pub_excess, pub_nonce) = rx_cx.get_public_keys(keychain.secp()); rx_cx.add_output(&key_id, &None, 0); pub_nonce_sum = PublicKey::from_combination( @@ -333,7 +333,7 @@ fn aggsig_sender_receiver_interaction_offset() { let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -350,14 +350,14 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sig_part, &pub_nonce_sum, &receiver_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // now sender signs with their key @@ -365,7 +365,7 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = sender_keychain.clone(); let msg = kernel_sig_msg(); let sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &s_cx.sec_key, &s_cx.sec_nonce, &pub_nonce_sum, @@ -382,14 +382,14 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let sig_verifies = aggsig::verify_partial_sig( - &keychain.secp(), + keychain.secp(), &sender_sig_part, &pub_nonce_sum, &sender_pub_excess, Some(&pub_key_sum), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Receiver now builds final signature from sender and receiver parts @@ -397,7 +397,7 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = receiver_keychain.clone(); let msg = kernel_sig_msg(); let our_sig_part = aggsig::calculate_partial_sig( - &keychain.secp(), + keychain.secp(), &rx_cx.sec_key, &rx_cx.sec_nonce, &pub_nonce_sum, @@ -408,7 +408,7 @@ fn aggsig_sender_receiver_interaction_offset() { // Receiver now generates final signature from the two parts let final_sig = aggsig::add_signatures( - &keychain.secp(), + keychain.secp(), vec![&sender_sig_part, &our_sig_part], &pub_nonce_sum, ) @@ -434,13 +434,13 @@ fn aggsig_sender_receiver_interaction_offset() { // Receiver check the final signature verifies let sig_verifies = aggsig::verify_completed_sig( - &keychain.secp(), + keychain.secp(), &final_sig, &final_pubkey, Some(&final_pubkey), &msg, ); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } // Check we can verify the sig using the kernel excess @@ -448,9 +448,9 @@ fn aggsig_sender_receiver_interaction_offset() { let keychain = ExtKeychain::from_random_seed(true).unwrap(); let msg = kernel_sig_msg(); let sig_verifies = - aggsig::verify_single_from_commit(&keychain.secp(), &final_sig, &msg, &kernel_excess); + aggsig::verify_single_from_commit(keychain.secp(), &final_sig, &msg, &kernel_excess); - assert!(!sig_verifies.is_err()); + assert!(sig_verifies.is_ok()); } } diff --git a/src/bin/grin-wallet.rs b/src/bin/grin-wallet.rs index 6e90995..6efca45 100644 --- a/src/bin/grin-wallet.rs +++ b/src/bin/grin-wallet.rs @@ -58,8 +58,7 @@ pub fn info_strings() -> (String, String) { /// Helper function to format paths according to OS, avoids bugs on Linux pub fn fmt_path(path: String) -> String { let sep = &MAIN_SEPARATOR.to_string(); - let path = path.replace("/", &sep).replace("\\", &sep); - path + path.replace("/", sep).replace("\\", sep) } fn log_build_info() { @@ -103,16 +102,13 @@ fn real_main() -> i32 { } // special cases for certain lifecycle commands - match args.subcommand() { - ("init", Some(init_args)) => { - if init_args.is_present("here") { - current_dir = Some(env::current_dir().unwrap_or_else(|e| { - panic!("Error creating config file: {}", e); - })); - } - create_path = true; + if let ("init", Some(init_args)) = args.subcommand() { + if init_args.is_present("here") { + current_dir = Some(env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + })); } - _ => {} + create_path = true; } // Load relevant config, try and load a wallet config file @@ -136,9 +132,8 @@ fn real_main() -> i32 { // Load logging config let mut l = config.members.logging.clone().unwrap(); // no logging to stdout if we're running cli - match args.subcommand() { - ("cli", _) => l.log_to_stdout = true, - _ => {} + if let ("cli", _) = args.subcommand() { + l.log_to_stdout = true }; init_logger(Some(l), None); info!( @@ -147,7 +142,7 @@ fn real_main() -> i32 { ); log_build_info(); - global::init_global_chain_type(config.members.wallet.chain_type.as_ref().unwrap().clone()); + global::init_global_chain_type(*config.members.wallet.chain_type.as_ref().unwrap()); global::init_global_accept_fee_base(config.members.wallet.accept_fee_base()); let wallet_config = config.clone().members.wallet; diff --git a/src/build/build.rs b/src/build/build.rs index 1d3d9bb..52307cc 100644 --- a/src/build/build.rs +++ b/src/build/build.rs @@ -14,7 +14,6 @@ //! Build hooks to spit out version+build time info -use built; use std::env; use std::path::{Path, PathBuf}; use std::process::Command; @@ -28,12 +27,12 @@ fn main() { if cfg!(target_os = "windows") { Command::new("cmd") - .args(&["/C", &git_hooks]) + .args(["/C", &git_hooks]) .output() .expect("failed to execute git config for hooks"); } else { Command::new("sh") - .args(&["-c", &git_hooks]) + .args(["-c", &git_hooks]) .output() .expect("failed to execute git config for hooks"); } diff --git a/src/cli/cli.rs b/src/cli/cli.rs index 2df64e3..612518b 100644 --- a/src/cli/cli.rs +++ b/src/cli/cli.rs @@ -33,12 +33,11 @@ use rustyline::validate::Validator; use rustyline::{CompletionType, Config, Context, EditMode, Editor, Helper, OutputStreamType}; use std::borrow::Cow::{self, Borrowed, Owned}; use std::sync::mpsc::{channel, Receiver}; -use std::sync::Arc; use std::thread; use std::time::Duration; -const COLORED_PROMPT: &'static str = "\x1b[36mgrin-wallet>\x1b[0m "; -const PROMPT: &'static str = "grin-wallet> "; +const COLORED_PROMPT: &str = "\x1b[36mgrin-wallet>\x1b[0m "; +const PROMPT: &str = "grin-wallet> "; //const HISTORY_PATH: &str = ".history"; // static for keeping track of current stdin buffer contents @@ -109,7 +108,7 @@ pub fn start_updater_thread(rx: Receiver) -> Result<(), Error> { pub fn command_loop( config: GlobalWalletConfig, - wallet_inst: Arc>>>, + wallet_inst: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, keychain_mask: Option, global_wallet_args: &GlobalArgs, test_mode: bool, @@ -155,7 +154,7 @@ where start_updater_thread(rx)?; // start the automatic updater - owner_api.start_updater((&keychain_mask).as_ref(), Duration::from_secs(30))?; + owner_api.start_updater(keychain_mask.as_ref(), Duration::from_secs(30))?; let mut wallet_opened = false; loop { match reader.readline(PROMPT) { @@ -178,8 +177,7 @@ where // Just add 'grin-wallet' to each command behind the scenes // so we don't need to maintain a separate definition file let augmented_command = format!("grin-wallet {}", command); - let args = - app.get_matches_from_safe_borrow(augmented_command.trim().split_whitespace()); + let args = app.get_matches_from_safe_borrow(augmented_command.split_whitespace()); let done = match args { Ok(args) => { // handle opening /closing separately @@ -230,7 +228,7 @@ where keychain_mask.clone(), &wallet_config, tor_config, - &global_wallet_args, + global_wallet_args, &args, test_mode, true, diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 7d24895..8ce0617 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[allow(clippy::module_inception)] mod cli; pub use cli::command_loop; diff --git a/src/cmd/wallet.rs b/src/cmd/wallet.rs index 9e6c2cb..2838fc6 100644 --- a/src/cmd/wallet.rs +++ b/src/cmd/wallet.rs @@ -31,7 +31,7 @@ where C: NodeClient + 'static, { // Check the node version info, and exit with report if we're not compatible - let global_wallet_args = wallet_args::parse_global_args(&config.members.wallet, &wallet_args) + let global_wallet_args = wallet_args::parse_global_args(&config.members.wallet, wallet_args) .expect("Can't read configuration file"); node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone()); diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 55297b2..32be712 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -106,7 +106,7 @@ fn prompt_password_confirm() -> Result { } fn prompt_recovery_phrase( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, ) -> Result where DefaultWalletImpl: WalletInst<'static, L, C, K>, @@ -198,7 +198,7 @@ fn prompt_pay_invoice(slate: &Slate, dest: &str) -> Result { "* {} of your wallet funds will be added to the transaction to pay this invoice.", amount ); - if dest.len() > 0 { + if !dest.is_empty() { println!("* The wallet will IMMEDIATELY attempt to send the resulting transaction to the wallet listening at: '{}'.", dest); println!("* If other wallet is not listening, the resulting transaction will output as a slatepack which you can manually send back to the invoice creator."); } else { @@ -239,7 +239,7 @@ fn prompt_pay_invoice(slate: &Slate, dest: &str) -> Result { pub fn inst_wallet( config: WalletConfig, node_client: C, -) -> Result>>>, ParseError> +) -> Result, ParseError> where DefaultWalletImpl: WalletInst<'static, L, C, K>, L: WalletLCProvider<'static, C, K>, @@ -294,14 +294,7 @@ fn parse_u64(arg: &str, name: &str) -> Result { // As above, but optional fn parse_u64_or_none(arg: Option<&str>) -> Option { - let val = match arg { - Some(a) => a.parse::(), - None => return None, - }; - match val { - Ok(v) => Some(v), - Err(_) => None, - } + arg?.parse().ok() } pub fn parse_global_args( @@ -319,10 +312,7 @@ pub fn parse_global_args( } let api_secret = get_first_line(config.api_secret_path.clone()); let node_api_secret = get_first_line(config.node_api_secret_path.clone()); - let password = match args.value_of("pass") { - None => None, - Some(p) => Some(ZeroingString::from(p)), - }; + let password = args.value_of("pass").map(ZeroingString::from); let tls_conf = match config.tls_certificate_file.clone() { None => None, @@ -349,7 +339,7 @@ pub fn parse_global_args( } pub fn parse_init_args( - wallet: Arc>>>, + wallet: grin_wallet_libwallet::WalletHandle<'static, L, C, K>, config: &WalletConfig, g_args: &command::GlobalArgs, args: &ArgMatches, @@ -431,15 +421,9 @@ pub fn parse_scan_rewind_hash_args( } pub fn parse_account_args(account_args: &ArgMatches) -> Result { - let create = match account_args.value_of("create") { - None => None, - Some(s) => Some(s.to_owned()), - }; + let create = account_args.value_of("create").map(|s| s.to_owned()); - let active = match account_args.value_of("active") { - None => None, - Some(s) => Some(s.to_owned()), - }; + let active = account_args.value_of("active").map(|s| s.to_owned()); if create.is_some() && active.is_some() { let msg = "create and active cannot both be present".to_string(); @@ -490,11 +474,7 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Result Some(b.to_string()), - None => None, - }; + let bridge = args.value_of("bridge").map(|b| b.to_string()); let slatepack_qr = args.is_present("slatepack_qr"); @@ -578,7 +555,7 @@ pub fn parse_receive_args(args: &ArgMatches) -> Result Result Result Result Result None, - Some(d) => Some(d.to_owned()), - }; + let dump_file = args.value_of("dumpfile").map(|d| d.to_owned()); Ok(command::RepostArgs { id: tx_id.unwrap(), @@ -1024,17 +990,11 @@ pub fn wallet_command( where C: NodeClient + 'static + Clone, F: FnOnce( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - C, - keychain::ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + C, + keychain::ExtKeychain, >, ), { @@ -1047,7 +1007,7 @@ where wallet_config.check_node_api_http_addr = sa.to_string().clone(); } - let global_wallet_args = arg_parse!(parse_global_args(&wallet_config, &wallet_args)); + let global_wallet_args = arg_parse!(parse_global_args(&wallet_config, wallet_args)); node_client.set_node_url(&wallet_config.check_node_api_http_addr); node_client.set_node_api_secret(global_wallet_args.node_api_secret.clone()); @@ -1132,7 +1092,7 @@ where &wallet_config, tor_config, &global_wallet_args, - &wallet_args, + wallet_args, test_mode, false, ) @@ -1147,7 +1107,7 @@ where } fn open_wallet( - wallet: &Arc>>>, + wallet: &grin_wallet_libwallet::WalletHandle<'static, L, C, K>, global_wallet_args: &GlobalArgs, wallet_args: &ArgMatches, ) -> Result, Error> @@ -1171,6 +1131,7 @@ where Ok(mask) } +#[allow(clippy::too_many_arguments)] pub fn parse_and_execute( owner_api: &mut Owner, keychain_mask: Option, @@ -1187,7 +1148,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let km = (&keychain_mask).as_ref(); + let km = keychain_mask.as_ref(); if test_mode { owner_api.doctest_mode = true; @@ -1200,13 +1161,13 @@ where owner_api.wallet_inst.clone(), wallet_config, global_wallet_args, - &args, + args, test_mode, )); - command::init(owner_api, &global_wallet_args, a, test_mode) + command::init(owner_api, global_wallet_args, a, test_mode) } ("recover", Some(_)) => { - let a = arg_parse!(parse_recover_args(&global_wallet_args,)); + let a = arg_parse!(parse_recover_args(global_wallet_args,)); command::recover(owner_api, a) } ("listen", Some(args)) => { @@ -1214,11 +1175,7 @@ where if let Some(port) = args.value_of("port") { c.api_listen_port = port.parse().unwrap(); } - let bridge = if let Some(bridge) = args.value_of("bridge") { - Some(bridge.into()) - } else { - None - }; + let bridge = args.value_of("bridge").map(|bridge| bridge.into()); let use_tor = if args.is_present("no_tor") { Some(false) } else { @@ -1239,7 +1196,7 @@ where let mut c = wallet_config.clone(); let mut g = global_wallet_args.clone(); g.tls_conf = None; - arg_parse!(parse_owner_api_args(&mut c, &args)); + arg_parse!(parse_owner_api_args(&mut c, args)); command::owner_api(owner_api, keychain_mask, &c, &g, test_mode) } ("web", Some(_)) => command::owner_api( @@ -1251,7 +1208,7 @@ where ), ("rewind_hash", Some(_)) => command::rewind_hash(owner_api, km), ("scan_rewind_hash", Some(args)) => { - let a = arg_parse!(parse_scan_rewind_hash_args(&args)); + let a = arg_parse!(parse_scan_rewind_hash_args(args)); command::scan_rewind_hash( owner_api, a, @@ -1259,11 +1216,11 @@ where ) } ("account", Some(args)) => { - let a = arg_parse!(parse_account_args(&args)); + let a = arg_parse!(parse_account_args(args)); command::account(owner_api, km, a) } ("send", Some(args)) => { - let a = arg_parse!(parse_send_args(&args)); + let a = arg_parse!(parse_send_args(args)); command::send( owner_api, km, @@ -1274,29 +1231,27 @@ where ) } ("receive", Some(args)) => { - let a = arg_parse!(parse_receive_args(&args)); + let a = arg_parse!(parse_receive_args(args)); command::receive(owner_api, km, a, tor_config, test_mode) } ("unpack", Some(args)) => { - let a = arg_parse!(parse_unpack_args(&args)); + let a = arg_parse!(parse_unpack_args(args)); let slatepack = command::read_slatepack(a)?; command::unpack(owner_api, km, slatepack) } ("finalize", Some(args)) => { - let a = arg_parse!(parse_finalize_args(&args)); + let a = arg_parse!(parse_finalize_args(args)); command::finalize(owner_api, km, a) } ("invoice", Some(args)) => { - let a = arg_parse!(parse_issue_invoice_args(&args)); + let a = arg_parse!(parse_issue_invoice_args(args)); command::issue_invoice_tx(owner_api, km, a) } ("pay", Some(args)) => { // get slate first let (slate, address) = get_slate(owner_api, km, args)?; - let a = arg_parse!(parse_process_invoice_args( - &args, !test_mode, slate, address - )); + let a = arg_parse!(parse_process_invoice_args(args, !test_mode, slate, address)); command::process_invoice( owner_api, km, @@ -1307,7 +1262,7 @@ where ) } ("info", Some(args)) => { - let a = arg_parse!(parse_info_args(&args)); + let a = arg_parse!(parse_info_args(args)); command::info( owner_api, km, @@ -1318,11 +1273,11 @@ where ("outputs", Some(_)) => command::outputs( owner_api, km, - &global_wallet_args, + global_wallet_args, wallet_config.dark_background_color_scheme.unwrap_or(true), ), ("txs", Some(args)) => { - let a = arg_parse!(parse_txs_args(&args)); + let a = arg_parse!(parse_txs_args(args)); command::txs( owner_api, km, @@ -1331,28 +1286,28 @@ where ) } ("post", Some(args)) => { - let a = arg_parse!(parse_post_args(&args)); + let a = arg_parse!(parse_post_args(args)); command::post(owner_api, km, a) } ("repost", Some(args)) => { - let a = arg_parse!(parse_repost_args(&args)); + let a = arg_parse!(parse_repost_args(args)); command::repost(owner_api, km, a) } ("cancel", Some(args)) => { - let a = arg_parse!(parse_cancel_args(&args)); + let a = arg_parse!(parse_cancel_args(args)); command::cancel(owner_api, km, a) } ("export_proof", Some(args)) => { - let a = arg_parse!(parse_export_proof_args(&args)); + let a = arg_parse!(parse_export_proof_args(args)); command::proof_export(owner_api, km, a) } ("verify_proof", Some(args)) => { - let a = arg_parse!(parse_verify_proof_args(&args)); + let a = arg_parse!(parse_verify_proof_args(args)); command::proof_verify(owner_api, km, a) } ("address", Some(_)) => command::address(owner_api, km), ("scan", Some(args)) => { - let a = arg_parse!(parse_check_args(&args)); + let a = arg_parse!(parse_check_args(args)); command::scan(owner_api, km, a) } ("open", Some(_)) => { diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 632c362..55ce29a 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -181,7 +181,10 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let output = String::from_utf8(output.stdout).unwrap(); let accounts: Vec<_> = output .lines() - .filter_map(|line| line.strip_prefix("Address for account - ")) + .filter_map(|line| { + line.split_once("Address for account - ") + .map(|(_, name)| name) + }) .collect(); assert_eq!(accounts, ["account_1", "default", "account_1"]); @@ -203,7 +206,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let wallet_config1 = config1.clone().members.wallet; let (wallet1, mask1_i) = instantiate_wallet(wallet_config1, client1.clone(), "password1", "default")?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); api1.set_active_account(mask1, "mining")?; @@ -303,7 +306,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); // Check our transaction log, should have 10 entries @@ -333,7 +336,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password2", "default", )?; - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); api2.set_active_account(mask2, "account_1")?; @@ -471,7 +474,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); api1.set_active_account(mask1, "mining")?; @@ -537,7 +540,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "password1", "default", )?; - let mask1 = (&mask1_i).as_ref(); + let mask1 = mask1_i.as_ref(); let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); api1.set_active_account(mask1, "mining")?; @@ -678,7 +681,7 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // get tx output via -tx parameter api2.set_active_account(mask2, "default")?; let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; - let some_tx_id = txs[0].tx_slate_id.clone(); + let some_tx_id = txs[0].tx_slate_id; assert!(some_tx_id.is_some()); let tx_id = some_tx_id.unwrap().to_string().clone(); let arg_vec = vec!["grin-wallet", "-p", "password2", "txs", "-t", &tx_id[..]]; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 2f4d5b5..b5a4264 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -160,7 +160,7 @@ pub fn config_command_wallet( let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); if config_file_name.exists() { - return Err(grin_wallet_controller::Error::ArgumentError( + Err(grin_wallet_controller::Error::ArgumentError( "grin-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; @@ -217,6 +217,7 @@ fn get_wallet_subcommand<'a>( /// Helper to create an instance of the LMDB wallet #[allow(dead_code)] +#[allow(clippy::type_complexity)] pub fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, @@ -224,17 +225,11 @@ pub fn instantiate_wallet( account: &str, ) -> Result< ( - Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, >, Option, ), @@ -292,13 +287,21 @@ pub fn execute_command_no_setup( where C: NodeClient + 'static + Clone, F: FnOnce( - Arc, C, ExtKeychain>>>>, + grin_wallet_libwallet::WalletHandle< + 'static, + DefaultLCProvider, + C, + ExtKeychain, + >, ), { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); + // Avoid conflicts with local wallets + let wallet_dir = PathBuf::from(test_dir).join(format!("{}_bootstrap", wallet_name)); let mut config = - config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, true).unwrap(); + config::initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(wallet_dir), true) + .unwrap(); let mut wallet_config = config.clone().members.wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; @@ -372,7 +375,7 @@ where { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); - let req = EncryptedRequest::from_json(sec_req_id, &req_val, &shared_key).unwrap(); + let req = EncryptedRequest::from_json(sec_req_id, &req_val, shared_key).unwrap(); let res = post(&url, None, &req).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); @@ -444,7 +447,7 @@ pub fn derive_ecdh_key(sec_key_str: &str, other_pubkey: &PublicKey) -> SecretKey let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); - let mut shared_pubkey = other_pubkey.clone(); + let mut shared_pubkey = *other_pubkey; shared_pubkey.mul_assign(&secp, &sec_key).unwrap(); let x_coord = shared_pubkey.serialize_vec(&secp, true); @@ -460,7 +463,7 @@ pub struct WalletAPIReturnError { impl std::fmt::Display for WalletAPIReturnError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{} - {}", self.code, &self.message) + write!(f, "{} - {}", self.code, self.message) } } diff --git a/tests/owner_v3_init_secure.rs b/tests/owner_v3_init_secure.rs index a03be00..59f1bfc 100644 --- a/tests/owner_v3_init_secure.rs +++ b/tests/owner_v3_init_secure.rs @@ -30,7 +30,6 @@ use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; use grin_util::{from_hex, static_secp_instance}; use grin_wallet_impls::DefaultLCProvider; -use serde_json; #[macro_use] mod common; @@ -80,7 +79,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::IntId(1), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &sec_key, )?; println!("RES 1: {:?}", res); @@ -88,7 +87,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { assert_eq!(res.unwrap_err().code, -32001); // 2) Call any function on the V3 api without calling 'init_secure_api` first - let res = send_request::(1, "http://127.0.0.1:33420/v3/owner", &req)?; + let res = send_request::(1, "http://127.0.0.1:33420/v3/owner", req)?; println!("RES 2: {:?}", res); assert!(res.is_err()); assert_eq!(res.unwrap_err().code, -32001); @@ -108,7 +107,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 4: {:?}", res); @@ -122,7 +121,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &bad_key, )?; println!("RES 5: {:?}", res); @@ -164,7 +163,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req.to_string(), + req, &shared_key, )?; println!("RES 8: {:?}", res); @@ -178,7 +177,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 9: {:?}", res); @@ -199,7 +198,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 11: {:?}", res); @@ -232,7 +231,7 @@ fn owner_v3_init_secure() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("13")), 1, "http://127.0.0.1:33420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 13: {:?}", res); diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index bf6711e..3369dd1 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -30,7 +30,6 @@ use grin_keychain::ExtKeychain; use grin_wallet_config::GlobalWalletConfig; use grin_wallet_impls::DefaultLCProvider; use grin_wallet_libwallet::{InitTxArgs, Slate, SlateVersion, VersionedSlate}; -use serde_json; use grin_util::Mutex; use std::path::PathBuf; @@ -55,6 +54,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let app = App::from_yaml(yml); // Create a new proxy to simulate server and wallet responses + #[allow(clippy::type_complexity)] let wallet_proxy_a: Arc< Mutex< WalletProxy< @@ -122,7 +122,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { }; // give a bit for wallet to init and populate proxy with wallet via callback in thread above thread::sleep(Duration::from_millis(500)); - let mask2 = (&mask2_i).as_ref(); + let mask2 = mask2_i.as_ref(); let wallet_proxy = wallet_proxy_a.clone(); // Set the wallet proxy listener running @@ -148,18 +148,24 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let value: ECDHPubkey = res.unwrap(); let shared_key = derive_ecdh_key(sec_key_str, &value.ecdh_pubkey); - // 2) get the top level directory, should default to ~/.grin/auto + // 2) get the top level directory let req = include_str!("data/v3_reqs/get_top_level.req.json"); let res = send_request_enc::( &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 2: {:?}", res); assert!(res.is_ok()); - assert!(res.unwrap().contains("auto")); + assert_eq!( + PathBuf::from(res.unwrap()).canonicalize().unwrap(), + PathBuf::from(test_dir) + .join("wallet1_bootstrap") + .canonicalize() + .unwrap() + ); // 3) now set the top level directory to our test wallet dir let req = serde_json::json!({ @@ -186,7 +192,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 4: {:?}", res); @@ -220,7 +226,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 5: {:?}", res); @@ -232,7 +238,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 6: {:?}", res); @@ -244,7 +250,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 7: {:?}", res); @@ -256,7 +262,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 8: {:?}", res); @@ -313,7 +319,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 11: {:?}", res); @@ -347,7 +353,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 13: {:?}", res); @@ -438,7 +444,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 17: {:?}", res); @@ -449,7 +455,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 17a: {:?}", res); @@ -461,7 +467,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 18: {:?}", res); @@ -579,7 +585,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; assert!(res.is_ok()); @@ -589,7 +595,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 24: {:?}", res); @@ -601,7 +607,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 25: {:?}", res); @@ -613,7 +619,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 26: {:?}", res); @@ -625,7 +631,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { &JsonId::StrId(String::from("1")), 1, "http://127.0.0.1:43420/v3/owner", - &req, + req, &shared_key, )?; println!("RES 27: {:?}", res); diff --git a/util/src/byte_ser.rs b/util/src/byte_ser.rs index 8e5a936..7b9a7f7 100644 --- a/util/src/byte_ser.rs +++ b/util/src/byte_ser.rs @@ -63,7 +63,7 @@ where Ok(serializer.output) } -impl<'a> ser::Serializer for &'a mut ByteSerializer { +impl ser::Serializer for &mut ByteSerializer { type Ok = (); type Error = Error; type SerializeSeq = Self; @@ -226,7 +226,7 @@ impl<'a> ser::Serializer for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeSeq for &'a mut ByteSerializer { +impl ser::SerializeSeq for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -242,7 +242,7 @@ impl<'a> ser::SerializeSeq for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTuple for &'a mut ByteSerializer { +impl ser::SerializeTuple for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -258,7 +258,7 @@ impl<'a> ser::SerializeTuple for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTupleStruct for &'a mut ByteSerializer { +impl ser::SerializeTupleStruct for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -274,7 +274,7 @@ impl<'a> ser::SerializeTupleStruct for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeTupleVariant for &'a mut ByteSerializer { +impl ser::SerializeTupleVariant for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -290,7 +290,7 @@ impl<'a> ser::SerializeTupleVariant for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeMap for &'a mut ByteSerializer { +impl ser::SerializeMap for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -313,7 +313,7 @@ impl<'a> ser::SerializeMap for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeStruct for &'a mut ByteSerializer { +impl ser::SerializeStruct for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -329,7 +329,7 @@ impl<'a> ser::SerializeStruct for &'a mut ByteSerializer { } } -impl<'a> ser::SerializeStructVariant for &'a mut ByteSerializer { +impl ser::SerializeStructVariant for &mut ByteSerializer { type Ok = (); type Error = Error; @@ -366,7 +366,7 @@ where Ok(t) } -impl<'de, 'a> de::Deserializer<'de> for &'a mut ByteDeserializer<'de> { +impl<'de> de::Deserializer<'de> for &mut ByteDeserializer<'de> { type Error = Error; fn deserialize_any(self, visitor: V) -> Result From 965e8f1667cf976df61fa846005f9aeddbb14967 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Tue, 29 Sep 2026 23:22:45 +0300 Subject: [PATCH 14/39] Compact transaction table at CLI view (#822) --- controller/src/display.rs | 163 ++++++++++++++++++++------------------ libwallet/src/types.rs | 8 +- 2 files changed, 88 insertions(+), 83 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index 44e598f..99af9ea 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -17,9 +17,10 @@ use crate::core::core::FeeFields; use crate::core::global; use crate::libwallet::{ address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, - TxLogEntry, ViewWallet, WalletInfo, + TxLogEntry, TxLogEntryType, ViewWallet, WalletInfo, }; use crate::util::ToHex; + use prettytable; use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; @@ -150,47 +151,68 @@ pub fn txs( let mut table = table!(); - table.set_titles(row![ - bMG->"Id", - bMG->"Type", - bMG->"State", - bMG->"Shared Transaction Id", - bMG->"Creation Time", - bMG->"TTL Cutoff Height", - bMG->"Confirmed?", - bMG->"Confirmation Time", - bMG->"Num. \nInputs", - bMG->"Num. \nOutputs", - bMG->"Amount \nCredited", - bMG->"Amount \nDebited", - bMG->"Fee", - bMG->"Net \nDifference", - bMG->"Payment \nProof", - bMG->"Kernel", - bMG->"Tx \nData", - ]); + table.set_titles(if dark_background_color_scheme { + row![ + bMG->"Id", + bMG->"Type (State)", + bMG->"Shared Transaction Id \nKernel", + bMG->"Creation Time \nConfirmation Time", + bMG->"Payment Proof \nTTL Cutoff Height", + bMG->"Inputs \nOutputs", + bMG->"Credited \nDebited", + bMG->"Fee \nDifference", + ] + } else { + row![ + bFD ->"Id", + bFD->"Type (State)", + bFD->"Shared Transaction Id \nKernel", + bFD->"Creation Time \nConfirmation Time", + bFD->"Payment Proof \nTTL Cutoff Height", + bFD->"Inputs \nOutputs", + bFD->"Credited \nDebited", + bFD->"Fee \nDifference", + ] + }); - for t in txs { + for (i, t) in txs.iter().enumerate() { let id = format!("{}", t.id); let slate_id = match t.tx_slate_id { Some(m) => format!("{}", m), None => "None".to_owned(), }; - let slate_state = match t.tx_slate_state.as_ref() { - Some(m) => format!("{}", m), - None => "None".to_owned(), + + let entry_type = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Coinbase", + TxLogEntryType::TxReceived => "Received Tx", + TxLogEntryType::TxSent => "Sent Tx", + TxLogEntryType::TxReceivedCancelled => "Received Tx", + TxLogEntryType::TxSentCancelled => "Sent Tx", + TxLogEntryType::TxReverted => "Received Tx", + }) + .to_string(); + let entry_type_state = match t.tx_slate_state.as_ref() { + None => entry_type.to_string(), + Some(s) => format!("{} ({})", entry_type, s), }; - let entry_type = format!("{}", t.tx_type); + let entry_type_desc = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Confirmed", + TxLogEntryType::TxReceived => "", + TxLogEntryType::TxSent => "", + TxLogEntryType::TxReceivedCancelled => "Cancelled", + TxLogEntryType::TxSentCancelled => "Cancelled", + TxLogEntryType::TxReverted => "Reverted", + }) + .to_string(); let creation_ts = format!("{}", t.creation_ts.format("%Y-%m-%d %H:%M:%S")); let ttl_cutoff_height = match t.ttl_cutoff_height { - Some(b) => format!("{}", b), + Some(b) => b.to_string(), None => "None".to_owned(), }; let confirmation_ts = match t.confirmation_ts { Some(m) => format!("{}", m.format("%Y-%m-%d %H:%M:%S")), None => "None".to_owned(), }; - let confirmed = format!("{}", t.confirmed); let num_inputs = format!("{}", t.num_inputs); let num_outputs = format!("{}", t.num_outputs); let amount_debited_str = amount_to_hr_string(t.amount_debited, true); @@ -207,10 +229,6 @@ pub fn txs( amount_to_hr_string(t.amount_debited - t.amount_credited, true) ) }; - let tx_data = match t.stored_tx { - Some(_) => "Yes".to_owned(), - None => "None".to_owned(), - }; let kernel_excess = match t.kernel_excess { Some(e) => { let excess: &[u8] = e.0.as_ref(); @@ -225,65 +243,52 @@ pub fn txs( if dark_background_color_scheme { table.add_row(row![ bFC->id, - bFC->entry_type, - bFC->slate_state, + bFC->entry_type_state, bFC->slate_id, bFB->creation_ts, - bFB->ttl_cutoff_height, - bFC->confirmed, - bFB->confirmation_ts, + bFC->payment_proof, bFC->num_inputs, - bFC->num_outputs, bFG->amount_credited_str, - bFR->amount_debited_str, bFR->fee, - bFY->net_diff, - bfG->payment_proof, + ]); + table.add_row(row![ + bFD->"", + bFC->entry_type_desc, bFB->kernel_excess, - bFb->tx_data, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFC->num_outputs, + bFR->amount_debited_str, + bFY->net_diff, ]); } else { - if t.confirmed { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFg->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } else { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFR->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } + table.add_row(row![ + bFD->id, + bFb->entry_type_state, + bFD->slate_id, + bFB->creation_ts, + bFD->payment_proof, + bFD->num_inputs, + bFG->amount_credited_str, + bFR->fee, + ]); + table.add_row(row![ + bFD->"", + bFb->entry_type_desc, + bFB->kernel_excess, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFD->num_outputs, + bFR->amount_debited_str, + bFG->net_diff, + ]); + } + if i != txs.len() - 1 { + table.add_empty_row(); } } - table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP); + table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.printstd(); println!(); diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index e7e3f69..ae96d6b 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -608,12 +608,12 @@ pub enum TxLogEntryType { impl fmt::Display for TxLogEntryType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed \nCoinbase"), + TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed Coinbase"), TxLogEntryType::TxReceived => write!(f, "Received Tx"), TxLogEntryType::TxSent => write!(f, "Sent Tx"), - TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx\n- Cancelled"), - TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx\n- Cancelled"), - TxLogEntryType::TxReverted => write!(f, "Received Tx\n- Reverted"), + TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx - Cancelled"), + TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx - Cancelled"), + TxLogEntryType::TxReverted => write!(f, "Received Tx - Reverted"), } } } From d2d893da72fa7be935a0167dd0710713a83380fd Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:58:07 +0200 Subject: [PATCH 15/39] fix late lock self send proof (#829) --- controller/tests/self_send.rs | 58 +++++++++++++++++++++++++++++++++++ libwallet/src/internal/tx.rs | 16 +++++----- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index d7ce466..c7ab5af 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -141,3 +141,61 @@ fn wallet_self_send() { } clean_output_dir(test_dir); } + +#[test] +fn late_lock_self_send_proof() -> Result<(), libwallet::Error> { + let test_dir = "test_output/late_lock_self_send_proof"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + let chain = wallet_proxy.chain.clone(); + let stopper = wallet_proxy.running.clone(); + create_wallet_and_add!( + client1, + wallet1, + mask1_i, + test_dir, + "wallet1", + None, + &mut wallet_proxy, + false, + api1 + ); + let mask1 = mask1_i.as_ref(); + let worker = thread::spawn(move || wallet_proxy.run()); + + let result = (|| { + test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; + let mut slate = api1.init_send_tx( + mask1, + InitTxArgs { + amount: core::consensus::REWARD, + minimum_confirmations: 2, + late_lock: Some(true), + payment_proof_recipient_address: Some(api1.get_slatepack_address(mask1, 0)?), + ..Default::default() + }, + )?; + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + Ok(()) + }, + )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + + api1.finalize_tx(mask1, &slate).map(|_| ()) + })(); + + stopper.store(false, Ordering::Relaxed); + worker.join().unwrap()?; + drop(api1); + drop(wallet1); + drop(chain); + clean_output_dir(test_dir); + result +} diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 5635235..1400490 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -496,13 +496,15 @@ where Some(parent_key_id), false, )?; - if tx_vec.is_empty() { - return Err(Error::PaymentProof( - "TxLogEntry with original proof info not found (is account correct?)".to_owned(), - )); - } - - let orig_proof_info = tx_vec[0].clone().payment_proof; + let orig_proof_info = tx_vec + .into_iter() + .find(|tx| tx.tx_type == TxLogEntryType::TxSent) + .ok_or_else(|| { + Error::PaymentProof( + "TxLogEntry with original proof info not found (is account correct?)".to_owned(), + ) + })? + .payment_proof; if orig_proof_info.is_some() && slate.payment_proof.is_none() { return Err(Error::PaymentProof( From dce4e5eecc656d3f7f0a02600348d7eea5fc639b Mon Sep 17 00:00:00 2001 From: ardocrat Date: Sat, 10 Oct 2026 14:18:40 +0300 Subject: [PATCH 16/39] fix: do not scan outputs twice on payment proof retrieval (#830) --- libwallet/src/api_impl/owner.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 9c34925..0794bcd 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -458,8 +458,8 @@ where "Transaction ID or Slate UUID must be specified".to_owned(), )); } - if refresh_from_node { - update_wallet_state( + let refresh_txs_from_node = if refresh_from_node { + !update_wallet_state( wallet_inst.clone(), keychain_mask, status_send_channel, @@ -472,7 +472,7 @@ where wallet_inst.clone(), keychain_mask, status_send_channel, - refresh_from_node, + refresh_txs_from_node, tx_id, tx_slate_id, None, From 390ed15f4cc762f912e77550875ad15454f1debf Mon Sep 17 00:00:00 2001 From: wiesche Date: Thu, 8 Oct 2026 22:22:15 +0200 Subject: [PATCH 17/39] update secp256k1 to 0.8.0 --- Cargo.lock | 20 ++++++++++---------- grin | 2 +- libwallet/src/mwixnet/onion/mod.rs | 19 +++++++++++-------- libwallet/src/mwixnet/onion/onion.rs | 18 ++++++++++-------- 4 files changed, 32 insertions(+), 27 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index debbb82..2067978 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2222,7 +2222,7 @@ checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" [[package]] name = "grin_api" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bytes 1.12.0", "easy-jsonrpc-mw", @@ -2254,7 +2254,7 @@ dependencies = [ [[package]] name = "grin_chain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bit-vec", "bitflags 1.3.2", @@ -2278,7 +2278,7 @@ dependencies = [ [[package]] name = "grin_core" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2304,7 +2304,7 @@ dependencies = [ [[package]] name = "grin_keychain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2325,7 +2325,7 @@ dependencies = [ [[package]] name = "grin_p2p" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bitflags 1.3.2", "built", @@ -2348,7 +2348,7 @@ dependencies = [ [[package]] name = "grin_pool" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "chrono", @@ -2365,9 +2365,9 @@ dependencies = [ [[package]] name = "grin_secp256k1zkp" -version = "0.7.15" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7bb95f155b1eede2648a1b9afbba82bc3d9f2af0518b478767559a572bd973" +checksum = "57e0a5f761e8c56db5be865f79832677d3badb3be91d7172d468e448f3d69f82" dependencies = [ "arrayvec 0.7.8", "cc", @@ -2380,7 +2380,7 @@ dependencies = [ [[package]] name = "grin_store" -version = "5.5.1" +version = "5.5.2" dependencies = [ "byteorder", "chrono", @@ -2402,7 +2402,7 @@ dependencies = [ [[package]] name = "grin_util" -version = "5.5.1" +version = "5.5.2" dependencies = [ "anyhow", "backtrace", diff --git a/grin b/grin index d5f3235..dbaff34 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit d5f32350ab548736c17c1db7ff51457917fe4e96 +Subproject commit dbaff34f7751ee23316fbbfe5806b47c546776ca diff --git a/libwallet/src/mwixnet/onion/mod.rs b/libwallet/src/mwixnet/onion/mod.rs index e1eb424..c23ada3 100644 --- a/libwallet/src/mwixnet/onion/mod.rs +++ b/libwallet/src/mwixnet/onion/mod.rs @@ -170,6 +170,7 @@ pub mod test_util { None, None, ) + .expect("failed to generate test bulletproof") } pub fn proof( @@ -187,14 +188,16 @@ pub mod test_util { let out_value = value - (fee as u64); - let rp = secp.bullet_proof( - out_value, - blind.clone(), - secp::random_secret(false), - secp::random_secret(false), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + blind.clone(), + secp::random_secret(false), + secp::random_secret(false), + None, + None, + ) + .expect("failed to generate test bulletproof"); (secp::commit(out_value, &blind).unwrap(), rp) } diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index 2540dae..8159232 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -397,14 +397,16 @@ pub mod tests { final_commit = secp::add_excess(&final_commit, &excess).unwrap(); let proof = if i == 4 { let n1 = random_secret(false); - let rp = secp.bullet_proof( - out_value, - final_blind.clone(), - n1.clone(), - n1.clone(), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + final_blind.clone(), + n1.clone(), + n1.clone(), + None, + None, + ) + .expect("failed to generate test bulletproof"); assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok()); Some(rp) } else { From ac4d18d6bd0759be23a8485a2054416187848946 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Mon, 14 Sep 2026 21:08:36 +0200 Subject: [PATCH 18/39] reject wrong slate states in receive and finalize (#807) (cherry picked from commit e5e319b47efb754ca02000b03f4ba65e608937c7) --- controller/src/command.rs | 38 +++++++++++++++++++++++++++++++ controller/tests/invoice.rs | 38 +++++++++++++++++++++++++++++++ libwallet/src/api_impl/foreign.rs | 3 +++ tests/cmd_line_basic.rs | 16 +++++++++++++ 4 files changed, 95 insertions(+) diff --git a/controller/src/command.rs b/controller/src/command.rs index e8970bd..b645892 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -696,6 +696,25 @@ where args.input_file, args.input_slatepack_message, )?; + match slate.state { + SlateState::Invoice1 => { + return Err(Error::GenericError( + "Use the 'pay' command to process this invoice transaction".to_string(), + )) + } + SlateState::Standard2 | SlateState::Invoice2 => { + return Err(Error::GenericError( + "Use the 'finalize' command to complete this transaction".to_string(), + )) + } + SlateState::Standard3 | SlateState::Invoice3 => { + return Err(Error::GenericError( + "Use the 'post' command to post this finalized transaction to the chain" + .to_string(), + )) + } + _ => {} + } let km = match keychain_mask.as_ref() { None => None, @@ -859,6 +878,25 @@ where args.input_file.clone(), args.input_slatepack_message.clone(), )?; + match slate.state { + SlateState::Standard1 => { + return Err(Error::GenericError( + "Use the 'receive' command on the recipient's wallet first".to_string(), + )) + } + SlateState::Invoice1 => { + return Err(Error::GenericError( + "Use the 'pay' command on the payer's wallet first".to_string(), + )) + } + SlateState::Standard3 | SlateState::Invoice3 => { + return Err(Error::GenericError( + "Use the 'post' command to post this finalized transaction to the chain" + .to_string(), + )) + } + _ => {} + } // Rather than duplicating the entire command, we'll just // try to determine what kind of finalization this is diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 7acd8bf..3713d5e 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -124,6 +124,44 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; assert_eq!(slate.state, SlateState::Invoice1); + let receive_result = wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| api.receive_tx(&slate, None, None).map(|_| ()), + ); + assert_eq!(receive_result, Err(libwallet::Error::SlateState)); + wallet::controller::owner_single_use( + wallet1.clone(), + mask1, + PathBuf::from(test_dir), + |api, m| { + let (_, txs) = api.retrieve_txs(m, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); + Ok(()) + }, + )?; + + // receive must reject every slate state except S1 + for state in [ + SlateState::Unknown, + SlateState::Standard2, + SlateState::Standard3, + SlateState::Invoice1, + SlateState::Invoice2, + SlateState::Invoice3, + ] { + let mut bad_slate = slate.clone(); + bad_slate.state = state.clone(); + let res = wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| api.receive_tx(&bad_slate, None, None).map(|_| ()), + ); + assert_eq!(res, Err(libwallet::Error::SlateState), "state {}", state); + } + wallet::controller::owner_single_use( wallet1.clone(), mask1, diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 76b6014..4547b87 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -66,6 +66,9 @@ where K: Keychain, { let mut ret_slate = slate.clone(); + if ret_slate.state != SlateState::Standard1 { + return Err(Error::SlateState); + } check_ttl(w, &ret_slate)?; let parent_key_id = match dest_acct_name { Some(d) => { diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 019e6cf..86f7675 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -567,6 +567,22 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: test_dir ); + // receive and finalize should point to pay + for cmd in ["receive", "finalize"] { + let arg_vec = vec![ + "grin-wallet", + "-a", + "mining", + "-p", + "password1", + cmd, + "-i", + &file_name, + ]; + let e = execute_command(&app, test_dir, "wallet1", &client1, arg_vec).unwrap_err(); + assert!(e.to_string().contains("'pay'"), "{}", e); + } + // now pay the invoice tx, wallet 1 let arg_vec = vec![ "grin-wallet", From bded95e28233f9eaec71c36c27ee12b39afa9c13 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Tue, 15 Sep 2026 19:42:56 +0200 Subject: [PATCH 19/39] use current header version in new slates (#804) * use current header version * flip header version check and bump min node version (cherry picked from commit 991ba1a1f7d4e0e4d0e233ca475cfd77b498a6c3) --- api/src/owner_rpc.rs | 2 +- controller/src/controller.rs | 10 +++------- controller/tests/transaction.rs | 24 +++++++++++++++++++++++- libwallet/src/internal/tx.rs | 15 ++------------- libwallet/src/slate_versions/mod.rs | 4 ++-- src/cmd/wallet.rs | 2 +- 6 files changed, 32 insertions(+), 25 deletions(-) diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 628d8ef..92511b0 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -973,7 +973,7 @@ pub trait OwnerRpc { "id": "0436430c-2b02-624c-2032-570501212b00", "sigs": [], "sta": "S3", - "ver": "4:3" + "ver": "4:5" } } } diff --git a/controller/src/controller.rs b/controller/src/controller.rs index c2f2c4e..ef61152 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -66,22 +66,18 @@ lazy_static! { fn check_middleware( name: ForeignCheckMiddlewareFn, - node_version_info: Option, + _node_version_info: Option, slate: Option<&Slate>, ) -> Result<(), Error> { match name { // allow coinbases to be built regardless ForeignCheckMiddlewareFn::BuildCoinbase => Ok(()), _ => { - let mut bhv = 3; - if let Some(n) = node_version_info { - bhv = n.block_header_version; - } if let Some(s) = slate { - if bhv > 4 && s.version_info.block_header_version < GRIN_BLOCK_HEADER_VERSION { + if s.version_info.block_header_version > GRIN_BLOCK_HEADER_VERSION { Err(Error::Compatibility( "Incoming Slate is not compatible with this wallet. \ - Please upgrade the node or use a different one." + Please upgrade the wallet." .into(), ))?; } diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 6c3d8e5..5425ef8 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -23,7 +23,7 @@ use grin_core as core; use self::core::core::transaction; use self::core::core::Transaction; use self::core::global; -use self::libwallet::{InitTxArgs, OutputStatus, Slate, SlateState}; +use self::libwallet::{InitTxArgs, OutputStatus, Slate, SlateState, GRIN_BLOCK_HEADER_VERSION}; use impls::test_framework::{self, LocalWalletClient}; use std::convert::TryInto; use std::path::PathBuf; @@ -105,6 +105,7 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> // assert wallet contents // and a single use api for a send command let amount = 60_000_000_000; + let header_version = core::consensus::header_version(chain.head().unwrap().height).0; let mut slate = Slate::blank(1, false); wallet::controller::owner_single_use( wallet1.clone(), @@ -124,6 +125,7 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> let slate_i = sender_api.init_send_tx(m, args)?; assert_eq!(slate_i.state, SlateState::Standard1); + assert_eq!(slate_i.version_info.block_header_version, header_version); // Check we are creating a tx with the expected lock_height of 0. // We will check this produces a Plain kernel later. @@ -131,6 +133,26 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; assert_eq!(slate.state, SlateState::Standard2); + + // wallet2 already has this slate, so accepted versions fail on the duplicate check + for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { + let mut s = slate_i.clone(); + s.version_info.block_header_version = bhv; + let res = wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| api.receive_tx(&s, None, None).map(|_| ()), + ); + if bhv <= GRIN_BLOCK_HEADER_VERSION { + assert!(matches!( + res, + Err(libwallet::Error::TransactionAlreadyReceived(_)) + )); + } else { + assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); + } + } sender_api.tx_lock_outputs(m, &slate)?; slate = sender_api.finalize_tx(m, &slate)?; assert_eq!(slate.state, SlateState::Standard3); diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 449f98f..6b655e3 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -18,8 +18,7 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use std::io::Cursor; use uuid::Uuid; -use crate::grin_core::consensus::valid_header_version; -use crate::grin_core::core::HeaderVersion; +use crate::grin_core::consensus::header_version; use crate::grin_keychain::{Identifier, Keychain}; use crate::grin_util::secp::key::SecretKey; use crate::grin_util::secp::pedersen; @@ -70,17 +69,7 @@ where } slate.amount = amount; - if valid_header_version(current_height, HeaderVersion(1)) { - slate.version_info.block_header_version = 1; - } - - if valid_header_version(current_height, HeaderVersion(2)) { - slate.version_info.block_header_version = 2; - } - - if valid_header_version(current_height, HeaderVersion(3)) { - slate.version_info.block_header_version = 3; - } + slate.version_info.block_header_version = header_version(current_height).0; // Set the features explicitly to 0 here. // This will generate a Plain kernel (rather than a HeightLocked kernel). diff --git a/libwallet/src/slate_versions/mod.rs b/libwallet/src/slate_versions/mod.rs index ca2e749..05416d9 100644 --- a/libwallet/src/slate_versions/mod.rs +++ b/libwallet/src/slate_versions/mod.rs @@ -34,8 +34,8 @@ pub mod v4_bin; /// The most recent version of the slate pub const CURRENT_SLATE_VERSION: u16 = 4; -/// The grin block header this slate is intended to be compatible with -pub const GRIN_BLOCK_HEADER_VERSION: u16 = 3; +/// The latest grin block header version this wallet supports +pub const GRIN_BLOCK_HEADER_VERSION: u16 = 5; /// Existing versions of the slate #[derive(EnumIter, Serialize, Deserialize, Clone, Debug, PartialEq, PartialOrd, Eq, Ord)] diff --git a/src/cmd/wallet.rs b/src/cmd/wallet.rs index e538ef6..9e6c2cb 100644 --- a/src/cmd/wallet.rs +++ b/src/cmd/wallet.rs @@ -20,7 +20,7 @@ use semver::Version; use std::thread; use std::time::Duration; -const MIN_COMPAT_NODE_VERSION: &str = "4.0.0-alpha.1"; +const MIN_COMPAT_NODE_VERSION: &str = "5.0.0-beta.1"; pub fn wallet_command( wallet_args: &ArgMatches<'_>, From 31635576d7273511a1250b230cea92dcbd5a93b9 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Tue, 15 Sep 2026 20:34:26 +0200 Subject: [PATCH 20/39] display slatepack addresses (#808) (cherry picked from commit 18da793ace9b8fe83407aa7cd55fd85375f0ea37) --- controller/src/display.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index e5f2f88..f94a855 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -16,10 +16,10 @@ use crate::core::core::FeeFields; use crate::core::core::{self, amount_to_hr_string}; use crate::core::global; use crate::libwallet::{ - AcctPathMapping, Error, OutputCommitMapping, OutputStatus, TxLogEntry, ViewWallet, WalletInfo, + AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, TxLogEntry, + ViewWallet, WalletInfo, }; use crate::util::ToHex; -use grin_wallet_util::OnionV3Address; use prettytable; use std::io::prelude::Write; use term; @@ -614,7 +614,7 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { writeln!( t, "Receiver Address: {}", - OnionV3Address::from_bytes(pp.receiver_address.to_bytes()) + SlatepackAddress::new(&pp.receiver_address) ) .unwrap(); writeln!(t, "Receiver Signature: {}", receiver_signature).unwrap(); @@ -623,7 +623,7 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { writeln!( t, "Sender Address: {}", - OnionV3Address::from_bytes(pp.sender_address.to_bytes()) + SlatepackAddress::new(&pp.sender_address) ) .unwrap(); writeln!(t, "Sender Signature: {}", sender_signature).unwrap(); From 4cb67d9e54398b20732d872db25696f8672032bc Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 16:36:57 +0200 Subject: [PATCH 21/39] clarify bip32 derivation paths (#800) Co-authored-by: ardocrat (cherry picked from commit f585c70eba95f47942ddb8dbf4931f12d2079775) --- controller/src/display.rs | 23 ++++++++++++++---- controller/tests/accounts.rs | 2 ++ libwallet/src/address.rs | 41 +++++++++++++++++++++++++-------- libwallet/src/api_impl/owner.rs | 6 ++++- 4 files changed, 57 insertions(+), 15 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index f94a855..559fbcf 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -16,11 +16,12 @@ use crate::core::core::FeeFields; use crate::core::core::{self, amount_to_hr_string}; use crate::core::global; use crate::libwallet::{ - AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, TxLogEntry, - ViewWallet, WalletInfo, + address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, + TxLogEntry, ViewWallet, WalletInfo, }; use crate::util::ToHex; use prettytable; +use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; use term; @@ -537,15 +538,29 @@ pub fn accounts(acct_mappings: Vec) { table.set_titles(row![ mMG->"Name", - bMG->"Parent BIP-32 Derivation Path", + bMG->"Parent Output Key", + bMG->"Slatepack Address (Index 0)", ]); for m in acct_mappings { + let slatepack_path = address::address_derivation_path(&m.path, 0).to_bip_32_string(); table.add_row(row![ bFC->m.label, bGC->m.path.to_bip_32_string(), + bGC->slatepack_path, ]); } - table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); + table.set_format( + FormatBuilder::new() + .column_separator('|') + .separators( + &[LinePosition::Top, LinePosition::Title], + LineSeparator::new('-', '+', '+', '+'), + ) + .padding(1, 1) + .build(), + ); + let width = table.to_string().find('\n').unwrap_or(0); + println!("{:^1$}", "BIP-32 Derivation Path", width); table.printstd(); println!(); } diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 9a47e41..59645f8 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -175,6 +175,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { mask1, PathBuf::from(test_dir), |api, m| { + let labels: Vec<_> = api.accounts(m)?.into_iter().map(|a| a.label).collect(); + assert_eq!(labels, ["account1", "default", "account2", "account3"]); // check last confirmed height on this account is different from above (should be 0) let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; assert_eq!(wallet1_info.last_confirmed_height, 0); diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index 8d55b39..4a6f54b 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -21,6 +21,23 @@ use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; use crate::blake2::blake2b::blake2b; +/// Derive a Slatepack address path from an output parent path and index. +/// +/// Output paths: +/// - account m/0: m/0/0/0, m/0/0/1 +/// - account m/1: m/1/0/0, m/1/0/1 +/// +/// Slatepack address paths: +/// - account m/0: m/0/1/0, m/0/1/1 +/// - account m/1: m/1/1/0, m/1/1/1 +pub fn address_derivation_path(parent_key_id: &Identifier, index: u32) -> Identifier { + let mut key_path = parent_key_id.to_path(); + key_path.path[1] = ChildNumber::from(1); + key_path.depth += 1; + key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); + Identifier::from_path(&key_path) +} + /// Derive a secret key given a derivation path and index pub fn address_from_derivation_path( keychain: &K, @@ -30,16 +47,7 @@ pub fn address_from_derivation_path( where K: Keychain, { - let mut key_path = parent_key_id.to_path(); - // An output derivation for acct m/0 - // is m/0/0/0, m/0/0/1 (for instance), m/1 is m/1/0/0, m/1/0/1 - // Address generation path should be - // for m/0: m/0/1/0, m/0/1/1 - // for m/1: m/1/1/0, m/1/1/1 - key_path.path[1] = ChildNumber::from(1); - key_path.depth += 1; - key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); - let key_id = Identifier::from_path(&key_path); + let key_id = address_derivation_path(parent_key_id, index); let sec_key = keychain.derive_key(0, &key_id, SwitchCommitmentType::None)?; let hashed = blake2b(32, &[], &sec_key.0[..]); Ok(SecretKey::from_slice( @@ -47,3 +55,16 @@ where &hashed.as_bytes()[..], )?) } + +#[cfg(test)] +mod tests { + use super::*; + use grin_keychain::ExtKeychain; + + #[test] + fn slatepack_address_path() { + let parent = ExtKeychain::derive_key_id(2, 2, 0, 0, 0); + let expected = ExtKeychain::derive_key_id(3, 2, 1, 3, 0); + assert_eq!(address_derivation_path(&parent, 3), expected); + } +} diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 10a8d4a..638c608 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -57,7 +57,11 @@ where C: NodeClient, K: Keychain, { - keys::accounts(w) + let mut accounts = keys::accounts(w)?; + accounts.sort_by(|a, b| a.path.cmp(&b.path)); + // Put active account on top. + accounts.sort_by_key(|k| k.path != w.parent_key_id()); + Ok(accounts) } /// new account path From 2daa36f7485a935903e2650e8325a823e1b7c671 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 14:43:11 +0200 Subject: [PATCH 22/39] handle unavailable terminal colors (#797) Co-authored-by: ardocrat (cherry picked from commit 99cca5b8bfdeb1f129d7b467f4241ed043fc47b6) --- controller/src/display.rs | 88 +++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index 559fbcf..54077fc 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use crate::core::core::amount_to_hr_string; use crate::core::core::FeeFields; -use crate::core::core::{self, amount_to_hr_string}; use crate::core::global; use crate::libwallet::{ address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, @@ -43,9 +43,9 @@ pub fn outputs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -78,7 +78,7 @@ pub fn outputs( }; let num_confirmations = format!("{}", m.output.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.output.value, false)); + let value = format!("{}", amount_to_hr_string(m.output.value, false)); let tx = match m.output.tx_log_entry { None => "".to_owned(), Some(t) => t.to_string(), @@ -118,7 +118,7 @@ pub fn outputs( if !validated { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } @@ -144,9 +144,9 @@ pub fn txs( return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -193,18 +193,18 @@ pub fn txs( let confirmed = format!("{}", t.confirmed); let num_inputs = format!("{}", t.num_inputs); let num_outputs = format!("{}", t.num_outputs); - let amount_debited_str = core::amount_to_hr_string(t.amount_debited, true); - let amount_credited_str = core::amount_to_hr_string(t.amount_credited, true); + let amount_debited_str = amount_to_hr_string(t.amount_debited, true); + let amount_credited_str = amount_to_hr_string(t.amount_credited, true); let fee = match t.fee { - Some(f) => format!("{}", core::amount_to_hr_string(f.fee(), true)), + Some(f) => format!("{}", amount_to_hr_string(f.fee(), true)), None => "None".to_owned(), }; let net_diff = if t.amount_credited >= t.amount_debited { - core::amount_to_hr_string(t.amount_credited - t.amount_debited, true) + amount_to_hr_string(t.amount_credited - t.amount_debited, true) } else { format!( "-{}", - core::amount_to_hr_string(t.amount_debited - t.amount_credited, true) + amount_to_hr_string(t.amount_debited - t.amount_credited, true) ) }; let tx_data = match t.stored_tx { @@ -290,7 +290,7 @@ pub fn txs( if !validated && include_status { println!( "\nWARNING: Wallet failed to verify data. \ - The above is from local cache and possibly invalid! \ + The above is from local cache and possibly invalid! \ (is your `grin server` offline or broken?)" ); } @@ -334,9 +334,9 @@ pub fn view_wallet_output( } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let mut table = table!(); @@ -357,7 +357,7 @@ pub fn view_wallet_output( let lock_height = format!("{}", m.lock_height); let is_coinbase = format!("{}", m.is_coinbase); let num_confirmations = format!("{}", m.num_confirmations(cur_height)); - let value = format!("{}", core::amount_to_hr_string(m.value, false)); + let value = format!("{}", amount_to_hr_string(m.value, false)); if dark_background_color_scheme { table.add_row(row![ @@ -409,11 +409,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -426,7 +426,7 @@ pub fn info( FY->amount_to_hr_string(wallet_info.amount_awaiting_confirmation, false) ]); table.add_row(row![ - bFB->format!("Awaiting Finalization"), + bFB->"Awaiting Finalization", FB->amount_to_hr_string(wallet_info.amount_awaiting_finalization, false) ]); table.add_row(row![ @@ -448,11 +448,11 @@ pub fn info( ]); if wallet_info.amount_reverted > 0 { table.add_row(row![ - Fr->format!("Reverted"), + Fr->"Reverted", Fr->amount_to_hr_string(wallet_info.amount_reverted, false) ]); } - // Only dispay "Immature Coinbase" if we have related outputs in the wallet. + // Only display "Immature Coinbase" if we have related outputs in the wallet. // This row just introduces confusion if the wallet does not receive coinbase rewards. if wallet_info.amount_immature > 0 { table.add_row(row![ @@ -483,7 +483,7 @@ pub fn info( if !validated { println!( "\nWARNING: Wallet failed to verify data against a live chain. \ - The above is from local cache and only valid up to the given height! \ + The above is from local cache and only valid up to the given height! \ (is your `grin server` offline or broken?)" ); } @@ -533,7 +533,7 @@ pub fn estimate( /// Display list of wallet accounts in a pretty way pub fn accounts(acct_mappings: Vec) { - println!("\n____ Wallet Accounts ____\n",); + println!("\n____ Wallet Accounts ____\n"); let mut table = table!(); table.set_titles(row![ @@ -567,28 +567,28 @@ pub fn accounts(acct_mappings: Vec) { /// Display individual Payment Proof pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { - let title = format!("Payment Proof - Transaction '{}'", tx.id,); + let title = format!("Payment Proof - Transaction '{}'", tx.id); println!(); if term::stdout().is_none() { println!("Could not open terminal"); return Ok(()); } let mut t = term::stdout().unwrap(); - t.fg(term::color::MAGENTA).unwrap(); - writeln!(t, "{}", title).unwrap(); - t.reset().unwrap(); + let _ = t.fg(term::color::MAGENTA); + writeln!(t, "{}", title)?; + let _ = t.reset(); let pp = match &tx.payment_proof { None => { - writeln!(t, "None").unwrap(); - t.reset().unwrap(); + writeln!(t, "None")?; + let _ = t.reset(); return Ok(()); } Some(p) => p.clone(), }; - t.fg(term::color::WHITE).unwrap(); - writeln!(t).unwrap(); + let _ = t.fg(term::color::WHITE); + writeln!(t)?; let receiver_signature = match pp.receiver_signature { Some(s) => { let sig_bytes = s.to_bytes(); @@ -602,11 +602,11 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { None => 0, }; let amount = if tx.amount_credited >= tx.amount_debited { - core::amount_to_hr_string(tx.amount_credited - tx.amount_debited, true) + amount_to_hr_string(tx.amount_credited - tx.amount_debited, true) } else { format!( "{}", - core::amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) + amount_to_hr_string(tx.amount_debited - tx.amount_credited - fee, true) ) }; @@ -630,20 +630,18 @@ pub fn payment_proof(tx: &TxLogEntry) -> Result<(), Error> { t, "Receiver Address: {}", SlatepackAddress::new(&pp.receiver_address) - ) - .unwrap(); - writeln!(t, "Receiver Signature: {}", receiver_signature).unwrap(); - writeln!(t, "Amount: {}", amount).unwrap(); - writeln!(t, "Kernel Excess: {}", kernel_excess).unwrap(); + )?; + writeln!(t, "Receiver Signature: {}", receiver_signature)?; + writeln!(t, "Amount: {}", amount)?; + writeln!(t, "Kernel Excess: {}", kernel_excess)?; writeln!( t, "Sender Address: {}", SlatepackAddress::new(&pp.sender_address) - ) - .unwrap(); - writeln!(t, "Sender Signature: {}", sender_signature).unwrap(); + )?; + writeln!(t, "Sender Signature: {}", sender_signature)?; - t.reset().unwrap(); + let _ = t.reset(); println!(); From 78ae279bdf3a63bb70cb7afdf71f1c59f4b37a9e Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 15:00:54 +0200 Subject: [PATCH 23/39] reject invalid invoice locking (#798) (cherry picked from commit 645363436d41ba621d8aa9fd536c619ee2110c5d) --- controller/tests/invoice.rs | 16 ++++++++++++++++ libwallet/src/api_impl/owner.rs | 3 +++ 2 files changed, 19 insertions(+) diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 3713d5e..006d5d4 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -184,6 +184,22 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; assert_eq!(slate.state, SlateState::Invoice2); + wallet::controller::owner_single_use( + wallet2.clone(), + mask2, + PathBuf::from(test_dir), + |api, m| { + assert_eq!( + api.tx_lock_outputs(m, &slate), + Err(libwallet::Error::SlateState) + ); + let (_, txs) = api.retrieve_txs(m, false, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + Ok(()) + }, + )?; + // wallet 2 finalizes and posts wallet::controller::foreign_single_use( wallet2.clone(), diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 638c608..44aecae 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -830,6 +830,9 @@ where K: Keychain, { let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + if slate.state == SlateState::Invoice2 && context.input_ids.is_empty() { + return Err(Error::SlateState); + } let mut excess_override = None; let mut sl = slate.clone(); From 5adceaae786eee4a4e2593f0c3941896e5d7b196 Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 17 Aug 2026 14:23:23 +0200 Subject: [PATCH 24/39] fix tx filter (#795) (cherry picked from commit 0d5ea84bfd6bcfffdcc1f2eb5ce313f428d08162) --- controller/tests/tx_list_filter.rs | 19 +++++++++++++++++++ libwallet/src/internal/updater.rs | 2 +- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index 424db24..c7fa9c8 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -61,6 +61,25 @@ fn test_wallet_tx_filtering( mask, PathBuf::from(test_dir), |api, _m| { + let query = |args| { + api.retrieve_txs(mask, true, None, None, Some(args)) + .map(|(_, txs)| txs) + }; + let txs = query(RetrieveTxQueryArgs::default())?; + assert!(!txs.is_empty()); + let before_first_tx = + txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); + let mut tx_query_args = RetrieveTxQueryArgs::default(); + + // Max creation time before all test transactions + tx_query_args.max_creation_timestamp = Some(before_first_tx); + assert!(query(tx_query_args.clone())?.is_empty()); + + // Min confirmation time should not affect creation time + tx_query_args.max_creation_timestamp = None; + tx_query_args.min_confirmed_timestamp = Some(before_first_tx); + assert_eq!(query(tx_query_args)?.len(), txs.len()); + let mut tx_query_args = RetrieveTxQueryArgs::default(); tx_query_args.min_id = Some(5); diff --git a/libwallet/src/internal/updater.rs b/libwallet/src/internal/updater.rs index 9590f23..47134e5 100644 --- a/libwallet/src/internal/updater.rs +++ b/libwallet/src/internal/updater.rs @@ -247,7 +247,7 @@ where } }) .filter(|tx_entry| { - if let Some(v) = query_args.min_confirmed_timestamp { + if let Some(v) = query_args.max_creation_timestamp { tx_entry.creation_ts <= v } else { true From 697cee89b74a8807cd87b437295ecdc089031ecb Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 2 Sep 2026 23:32:16 +0300 Subject: [PATCH 25/39] Downgrade arti to 0.43 (#810) (cherry picked from commit e0873a1b2ee33492dd08af2566bbd9bd3b8166ea) --- Cargo.lock | 226 +++++++++++++++++++++++------------------------ impls/Cargo.toml | 16 ++-- 2 files changed, 121 insertions(+), 121 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2067978..b1948dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -202,9 +202,9 @@ checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" [[package]] name = "arti-client" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d54b6c87059a9b6562bfe585f3a637b72f90cddaa327ac29b5ddf082a54b4" +checksum = "7ffc89b08e6a475a83d70e52f0ede139a433eb46e986a6cee6eeaa1b73297bf1" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -699,9 +699,9 @@ checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" [[package]] name = "caret" -version = "0.10.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bb840a063107846780a14acc022b55bf6c174997a393ffde8b58ff6630c1b56" +checksum = "beae2cb9f60bc3f21effaaf9c64e51f6627edd54eedc9199ba07f519ef2a2101" [[package]] name = "cc" @@ -1970,9 +1970,9 @@ dependencies = [ [[package]] name = "fs-mistrust" -version = "0.15.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd938e053fbfb6dba36106f4bcf27c53362e6152adc9341700c4bc2264cd4a8f" +checksum = "9cfebc7c6bb65d327ded064db65cd260b6c418c27ae790318650cfa2a81bf33f" dependencies = [ "derive_builder_fork_arti", "dirs 6.0.0", @@ -1984,6 +1984,17 @@ dependencies = [ "walkdir", ] +[[package]] +name = "fslock-guard" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e77b8a36ee17f9079b53db7281de9b16a8fb2bc97a7cd1e41a2998f3a837af7a" +dependencies = [ + "libc", + "thiserror 2.0.18", + "windows-sys 0.61.2", +] + [[package]] name = "fslock-guard" version = "0.8.0" @@ -2040,9 +2051,9 @@ dependencies = [ [[package]] name = "futures-copy" -version = "0.4.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcad91f8ba72542347d5cc8ee43891abe4698429fa7b3de56f17f4bb6fa514c4" +checksum = "24f320278d16b5617859cc2234ca5775a8d9b24faee8c14e54e79540caab053a" dependencies = [ "futures 0.3.32", "libc", @@ -2531,7 +2542,7 @@ dependencies = [ "chrono", "ed25519-dalek", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.8.0", "futures 0.3.32", "grin_api", "grin_chain", @@ -4004,9 +4015,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "oneshot-fused-workaround" -version = "0.7.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60d6f8f565703c8a15f98b7782e39526490f8c291910d80c9be54a753a822f6f" +checksum = "e17b52d0e4a06a4c7eb8d2943c0015fa628cf4ccc409429cebc0f5bed6d33a82" dependencies = [ "futures 0.3.32", ] @@ -5030,9 +5041,9 @@ dependencies = [ [[package]] name = "retry-error" -version = "0.13.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c0e06f9b501df8600ad8bd073f4990f703f36e0f48e574b431f4a15d69b449" +checksum = "cf6aa271ee564cc5d1df57c5cf7c6ac7a21a4f9f40d2bf1d32bf0a1bb3ddaeb0" dependencies = [ "humantime 2.4.0", "web-time", @@ -5343,9 +5354,9 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "safelog" -version = "0.9.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c0812d386a9992c036500b92565c41f84c28fd2e48fe853a395c393261b730b" +checksum = "97a907e0d82c61b1b06a2030c968eb313dcf432686b77801a26bc4b206f96573" dependencies = [ "derive_more", "educe", @@ -5389,9 +5400,9 @@ dependencies = [ [[package]] name = "saturating-time" -version = "0.4.0" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "802bdbfcca9a239cb46eeaaedea507e37bb13ba1a673762d2e2ef7a9dac63144" +checksum = "b63583a1dd0647d1484228529ab4ecaa874048d2956f117362aa5f5826456230" [[package]] name = "schannel" @@ -5798,9 +5809,9 @@ dependencies = [ [[package]] name = "slotmap-careful" -version = "0.8.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7cd5208f878dce99cfbefa73c692c67edf946ac53e0cc4455e2dabe43d54af7" +checksum = "ed92816c1fbb29891a525b92d5fa95757c9dee47044f76c8e06ceb1e052a8d64" dependencies = [ "paste", "serde", @@ -6464,35 +6475,26 @@ checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tor-async-utils" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58580b41636378f79500bca6a178787e0e434207e0880dd90698ae3f686f24d6" +checksum = "27fc83e7539ac5f717b722456df991ca8819782d04f7ae2ee28eefacca030eef" dependencies = [ - "cfg-if 1.0.4", "derive-deftly", "educe", "futures 0.3.32", "oneshot-fused-workaround", "pin-project", "postage", - "sync_wrapper", "thiserror 2.0.18", - "tokio", - "tokio-util", - "tor-basic-utils", - "tor-rtcompat", - "tracing", "void", - "web-time-compat", ] [[package]] name = "tor-basic-utils" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd3046aa299df67da91b45c02c24d48d40ae1845f9b91e27f9c8adbde78315ba" +checksum = "7bd01b9947f57a99193547f3a40a0bd179e9a332ead855c07e2fb702a1517f74" dependencies = [ - "derive-deftly", "derive_more", "getrandom 0.4.3", "hex", @@ -6505,16 +6507,15 @@ dependencies = [ "slab", "smallvec", "thiserror 2.0.18", - "tracing", "weak-table", "web-time-compat", ] [[package]] name = "tor-bytes" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b4833cc8ab3fca79eabc06f3ca97db102a3b7db861d77848d39932a6f0ed598" +checksum = "de6a7af55881d599cd48c841916520318d5711df17514001aafd5f796f61e337" dependencies = [ "bytes 1.12.0", "derive-deftly", @@ -6530,9 +6531,9 @@ dependencies = [ [[package]] name = "tor-cell" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73a01cb2ac6697c12b647729d3d7db404e306d1e08a7a3aacdbee08e35170ebd" +checksum = "dad292658d194b145aaec268ffb91566b7d96c98971eea4980c1bf951d7d082b" dependencies = [ "amplify", "bitflags 2.13.0", @@ -6561,15 +6562,14 @@ dependencies = [ [[package]] name = "tor-cert" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162d44b975e445de099b3a495710689652bbd0a9a3a0e4946341acbb3138b22b" +checksum = "474e732207b1be44f9ae4ddf295fba3644cd3c09494d131846ff9c9a624ab263" dependencies = [ "caret", "derive_builder_fork_arti", "derive_more", "digest 0.10.7", - "saturating-time", "thiserror 2.0.18", "tor-bytes", "tor-checkable", @@ -6580,9 +6580,9 @@ dependencies = [ [[package]] name = "tor-chanmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf15c4cbafa5745def4fced9e8e59148533a2bfc8d938e9fad7a0d6d16757712" +checksum = "b2bb088804f54de320ee97dd2a48ae319f0df9d9d0e37eef050d65488194a768" dependencies = [ "async-trait", "base64ct", @@ -6623,9 +6623,9 @@ dependencies = [ [[package]] name = "tor-checkable" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef81835cb0b2db460c694678eae8c4cbad5f31847e473aac42605f9b945fb31a" +checksum = "9505791bac25b31b8de88c0e2b02e1690e10ff1308583c6f61c320bab2677959" dependencies = [ "humantime 2.4.0", "signature", @@ -6636,9 +6636,9 @@ dependencies = [ [[package]] name = "tor-circmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b63cca1f18282f82b905b6a8c20c6f247787bc010d1b317d9eb98503e4352bf" +checksum = "7e986c7c4e1faae8a412b575ce66ff087050525a371db1034f0b24d70b459a2e" dependencies = [ "amplify", "async-trait", @@ -6686,9 +6686,9 @@ dependencies = [ [[package]] name = "tor-config" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a699adfb8bdb34699afcca7cbbd9d26329246940bc9dbc32f380c87578017350" +checksum = "224f85aa02b514c384ea5ec32f1b924233bea6b553195fd83da7f1e50a2e0d1b" dependencies = [ "amplify", "cfg-if 1.0.4", @@ -6720,9 +6720,9 @@ dependencies = [ [[package]] name = "tor-config-path" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38001695121fc778e67ac7a1c733d3158ee8942a55cfa343981b50d90f5daa" +checksum = "4232a56a8ce40a47ad6b42c9c7d9e6f4485e6e6a43b3149304c35bc295034107" dependencies = [ "directories", "serde", @@ -6734,9 +6734,9 @@ dependencies = [ [[package]] name = "tor-consdiff" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e9e3eb11e91ea4c1affe5e1f73628726c283942715739850546acb94bbe028" +checksum = "d5fcd0c631a66b45dca4421b8a06309dd02ae5d6aea5daa55399f68638b2abf3" dependencies = [ "derive_more", "digest 0.10.7", @@ -6751,9 +6751,9 @@ dependencies = [ [[package]] name = "tor-dirclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0027cd2a58abab9ebaf61c3c1da9b0fa9e6cbc914b88fedb7b3102bd4f4dd656" +checksum = "bf637d6a5d8c886f23ca2df50edfaa56443f23294428f037206fb3a0d07ba57e" dependencies = [ "async-compression", "base64ct", @@ -6780,9 +6780,9 @@ dependencies = [ [[package]] name = "tor-dircommon" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d2047b2f1ad3453c1060e5e39203bd87ead266e6873707bd7333b1d6bdac768" +checksum = "35e412167d54c3618c3261dc77f1a31fe20c518f59aca5abfdec5f600b6a9b1f" dependencies = [ "base64ct", "derive-deftly", @@ -6801,9 +6801,9 @@ dependencies = [ [[package]] name = "tor-dirmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57ebc162ccd628ef8e96912a9e42e848cd7305eb2a5a455a6002f54ad6826422" +checksum = "9b984d2b0f0a2764a1b24d7c4c203ef83600b071c0c5af36e20d4f63e80ce562" dependencies = [ "async-trait", "base64ct", @@ -6813,7 +6813,7 @@ dependencies = [ "educe", "event-listener", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "hex", "humantime 2.4.0", @@ -6858,9 +6858,9 @@ dependencies = [ [[package]] name = "tor-error" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6a7ed4aee3e0613a75d420032116dac82d7702594e28566befdfa6707a8fd0e" +checksum = "1409b1a9085502c7797405a01fe3f3292a9827c9ed6a3f7c34fbb222572db5ac" dependencies = [ "derive_more", "futures 0.3.32", @@ -6876,9 +6876,9 @@ dependencies = [ [[package]] name = "tor-general-addr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfee544a33dd3e67e0311cc46ef8f667cbf9c02c7c00ef4f25098a25b2b6e1cf" +checksum = "09f17e219140e587e169f71f53e528ca394c39e83593c9fbe9e9366cce7655e1" dependencies = [ "derive_more", "thiserror 2.0.18", @@ -6887,9 +6887,9 @@ dependencies = [ [[package]] name = "tor-guardmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1e8f52e4b1b08ba58970a9b9879b0b72c35dcba48bad389935f2778ed432d05" +checksum = "d56c43d7afa526449c6e6460d373a02624a24c78637ddd7c68e2ac1879ae587c" dependencies = [ "amplify", "base64ct", @@ -6932,9 +6932,9 @@ dependencies = [ [[package]] name = "tor-hsclient" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dc813f71e63fd324c4b1b1647ddc2fcc4b6e77c45091e6769ae80e591726ec" +checksum = "1ff8ba0afebc5f76b42240f76b2bfb92aa5862c19ff184492c59c654750ee275" dependencies = [ "async-trait", "derive-deftly", @@ -6977,9 +6977,9 @@ dependencies = [ [[package]] name = "tor-hscrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f82fd6a5a6ede5ece5e7f52708bdf0a007e8f975f9825689b376f038845f1e88" +checksum = "3761c1828e74818cba4eb661d1eb79d4f663b05e8e7d3bc6e35d754968282fc0" dependencies = [ "cipher 0.4.4", "data-encoding", @@ -7010,9 +7010,9 @@ dependencies = [ [[package]] name = "tor-hsrproxy" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4231a55048af49ae2a8fcb2d41ea0df986b68c26bf6128f97f7f1324d47498" +checksum = "cc0d8041225c2721fb68e8406c2121e3168ea3998148df253859fec70ea20741" dependencies = [ "derive-deftly", "futures 0.3.32", @@ -7039,9 +7039,9 @@ dependencies = [ [[package]] name = "tor-hsservice" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170b66c977d3b16a5ff79ec344c06392076f0326d2d65146a58c450c50395dae" +checksum = "5fa87ed8d1ccfe8447b4e65bf0e2dfcab6a8ac9d2eadf7b3f37c102e1c18e9bb" dependencies = [ "amplify", "async-trait", @@ -7098,9 +7098,9 @@ dependencies = [ [[package]] name = "tor-key-forge" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30f83389917e9908c43457c80d0b982ba6dcd3e6ea36a37b29167b7619d9eaa3" +checksum = "86c877b95e0679f151743bc2b706320a29e14bd18d9bcb92918df34948e2e9d2" dependencies = [ "derive-deftly", "derive_more", @@ -7120,9 +7120,9 @@ dependencies = [ [[package]] name = "tor-keymgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7c18fb26d112c6022b7d1de558a4045b574fecfa1c504045145d8e1a9dc01a" +checksum = "5f59fbec28e31d688822b4c00a6f7fd94539886baccd3ce1b35dc26699c37873" dependencies = [ "amplify", "arrayvec 0.7.8", @@ -7161,9 +7161,9 @@ dependencies = [ [[package]] name = "tor-linkspec" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "638a849a5d65d4e37adb6a2fa597a5a5c0decb749c17e76d3c44c4aefd696270" +checksum = "0e1cc8d5469c324d1e0761066d868363d3fdccb723b14cdc983a5aef9b67981b" dependencies = [ "base64ct", "by_address", @@ -7188,9 +7188,9 @@ dependencies = [ [[package]] name = "tor-llcrypto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ef0e63e805e9c1da61511a93eca502dc29bcb0b8635e9668ec750b63a1e53a1" +checksum = "d0015d521f5e30a2f74879fe4c615fc2c3ace822d7cc88c1dfed0ae816b25f15" dependencies = [ "aes", "base64ct", @@ -7231,9 +7231,9 @@ dependencies = [ [[package]] name = "tor-log-ratelim" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37d0f759a875b6f9b6f3657a2626a70e2474e698a4404501033babe63ad888a6" +checksum = "7d16152b21f2e7b309dfbdcbe587c5adba9547d3119f2933b453d6edbce7e8e0" dependencies = [ "futures 0.3.32", "humantime 2.4.0", @@ -7247,9 +7247,9 @@ dependencies = [ [[package]] name = "tor-memquota" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c06f2e981120a4c1da1e361573cee4af618d05fa3c7ec37c139d766f1b8d47f" +checksum = "38ad2950d88e968572b0de6bb5702f5ed42f36555f362fb741c572c62441476e" dependencies = [ "cfg-if 1.0.4", "derive-deftly", @@ -7278,9 +7278,9 @@ dependencies = [ [[package]] name = "tor-memquota-cost" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b86eb903fee638e9211daddaddc146f0c5e4f5605d79983548fce6fec596325c" +checksum = "993ad5bfd39fb629990da40c2b2086284b1481b7d4843652a959db1d9e5ac463" dependencies = [ "derive-deftly", "itertools 0.14.0", @@ -7290,9 +7290,9 @@ dependencies = [ [[package]] name = "tor-netdir" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8160580273eec3576158c3e833ff198870665dacebb373585892dde93cf9803" +checksum = "6700c5e590818d9873a13e06b49b95cf3a39fa8fb3968bd67ec3295cd584b97c" dependencies = [ "async-trait", "bitflags 2.13.0", @@ -7323,9 +7323,9 @@ dependencies = [ [[package]] name = "tor-netdoc" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51598bfd24866de2c51e0de7a6e2418f86c6278cfeba2f85295ce45367fd8e06" +checksum = "a497ce4c36f59e4c67c352e3b80cd4642f6c5e660bb003de1922be4c7ed03081" dependencies = [ "amplify", "base64ct", @@ -7339,7 +7339,6 @@ dependencies = [ "hex", "hostname-validator", "humantime 2.4.0", - "ipnet", "itertools 0.14.0", "memchr", "paste", @@ -7373,16 +7372,16 @@ dependencies = [ [[package]] name = "tor-persist" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ff75e20adb6a1a7ad07e16b55e56d5376706cc0090ab8831f008f1a89243f2" +checksum = "b6da1a96a1f6418faac1cd1892e029fd265cf50e67e941a4ba2580d92dd32d47" dependencies = [ "amplify", "derive-deftly", "derive_more", "filetime", "fs-mistrust", - "fslock-guard", + "fslock-guard 0.7.0", "futures 0.3.32", "itertools 0.14.0", "oneshot-fused-workaround", @@ -7402,9 +7401,9 @@ dependencies = [ [[package]] name = "tor-proto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "666b602da8ba5a4189d6ff551f5dd9db949b503780140d175435658970a1ea54" +checksum = "a0a5fa0e1a365fc089a7f140f4142379dd74c91c15103c2f9d11ea711e16029e" dependencies = [ "amplify", "async-trait", @@ -7438,6 +7437,7 @@ dependencies = [ "static_assertions", "strum 0.28.0", "subtle", + "sync_wrapper", "thiserror 2.0.18", "tokio", "tokio-util", @@ -7468,9 +7468,9 @@ dependencies = [ [[package]] name = "tor-protover" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef84569d020c36eb322976f9a5dec1d3fa992db9739237ad1ae923b0ddeb298" +checksum = "c4f7f4ee15c9bfa0b700ae06e85fa52abddf17a35531cd3d3833412900e8da5c" dependencies = [ "caret", "paste", @@ -7482,9 +7482,9 @@ dependencies = [ [[package]] name = "tor-ptmgr" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66db88ee6c5ba60a077b592b7e566d465220de61ccfd473fba6567c577cad475" +checksum = "b4cc37ac22faff9e0233fa287b92819d8819f31cae85a50ff99c51dd549b31c0" dependencies = [ "async-trait", "cfg-if 1.0.4", @@ -7512,9 +7512,9 @@ dependencies = [ [[package]] name = "tor-relay-selection" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09778e3a45fdf49ca335fa16a0032abc5d4e1cacff9f46c3ed3e2a416d088aa6" +checksum = "5b565b6dec2e3edb7b033203a3662edb7b586e486d53e02af4295e05e7562870" dependencies = [ "rand 0.10.2", "serde", @@ -7526,9 +7526,9 @@ dependencies = [ [[package]] name = "tor-rtcompat" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "981279291476ad7ec309c874fa99b8d31250432a48ff6eea3f7405edbbd254e1" +checksum = "fcd7a4ff4898044b3ec693c0bf098251accf13c58741c44ed9364ce5faa89287" dependencies = [ "amplify", "async-native-tls", @@ -7561,9 +7561,9 @@ dependencies = [ [[package]] name = "tor-rtmock" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3ee9695304cc44cc0de1dc673c9a71419318e214dc04ed7883a058d050654d" +checksum = "8331e7d57bf7cf157cf3610ff6dbb5a591de5c3b22fa65ea6be18b08ff81477a" dependencies = [ "amplify", "assert_matches", @@ -7591,9 +7591,9 @@ dependencies = [ [[package]] name = "tor-socksproto" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbf78ef55dbfccb5a95cd75eb433621947923653cb91c9941d5a0a5116e510ee" +checksum = "55f432eda94343bdadd73995f0b3082d96637dadb0e20c3f9a1bf2349f623d3c" dependencies = [ "amplify", "caret", @@ -7608,9 +7608,9 @@ dependencies = [ [[package]] name = "tor-units" -version = "0.44.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0325a93f3b35c5a9bda74705ce89b753e1c8e183af6945826188cef16687d80" +checksum = "8cf033ee8b22b11abd8272272e19ccbbf58c7b3152f8d224aa8d21f358c43d0d" dependencies = [ "derive-deftly", "derive_more", @@ -8099,9 +8099,9 @@ dependencies = [ [[package]] name = "web-time-compat" -version = "0.2.0" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af46dad42aa37be3b4a116fe613365f991b8bdae6cd6ce82d84fa9f9e8f70ae4" +checksum = "39819265f219f60a92312f2755262dba9fff180a4ec281556863d69fa36adc59" dependencies = [ "web-time", ] diff --git a/impls/Cargo.toml b/impls/Cargo.toml index bb4add2..b93b32f 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -32,15 +32,15 @@ sysinfo = "0.29" base64 = "0.12.0" url = "2.1" -arti-client = { version = "0.44.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } -tor-rtcompat = { version = "0.44.0", features = ["static"] } -fs-mistrust = "0.15.0" +arti-client = { version = "0.43.0", features = ["static", "pt-client", "onion-service-service", "onion-service-client"] } +tor-rtcompat = { version = "0.43.0", features = ["static"] } +fs-mistrust = "0.14.2" fslock-guard = "0.8" -tor-hsservice = "0.44.0" -tor-hsrproxy = "0.44.0" -tor-keymgr = "0.44.0" -tor-llcrypto = "0.44.0" -tor-hscrypto = "0.44.0" +tor-hsservice = "0.43.0" +tor-hsrproxy = "0.43.0" +tor-keymgr = "0.43.0" +tor-llcrypto = "0.43.0" +tor-hscrypto = "0.43.0" sha2 = "0.10.8" hyper = { version = "1.10.1", features = ["http1", "client"] } hyper-util = { version = "0.1.20", features = ["tokio"] } From 90d81a856a31c1b30f71c23889867f878e7b941f Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Mon, 21 Sep 2026 20:41:34 +0200 Subject: [PATCH 26/39] reject zero send amounts (#799) (cherry picked from commit 4a487390bdbcb9ba9176c689cef5bdc1e99c1714) --- controller/src/command.rs | 9 ++++-- controller/tests/invoice.rs | 19 ++++++++++++ controller/tests/transaction.rs | 48 ++++++++++++++++++++++++++++- libwallet/src/api_impl/foreign.rs | 4 +++ libwallet/src/api_impl/owner.rs | 12 ++++++++ libwallet/src/error.rs | 4 +++ libwallet/src/internal/selection.rs | 17 +++++----- tests/cmd_line_basic.rs | 5 +++ 8 files changed, 104 insertions(+), 14 deletions(-) diff --git a/controller/src/command.rs b/controller/src/command.rs index b645892..daeb256 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -372,12 +372,15 @@ where true, args.minimum_confirmations, )?; - if args.use_max_amount { - amount = wallet_info.amount_currently_spendable; - } if !info_updated && !update_skipped { warn!("Wallet info update failed: node connection error"); } + if args.use_max_amount { + amount = wallet_info.amount_currently_spendable; + if amount == 0 { + return Err(Error::GenericError("No spendable funds".to_string())); + } + } if args.estimate_selection_strategies { let strategies = estimate_strategies(args.use_max_amount) .iter() diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index 006d5d4..b48f66e 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -113,6 +113,17 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { mask2, PathBuf::from(test_dir), |api, m| { + let error = api + .issue_invoice_tx( + m, + IssueInvoiceTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + // Wallet 2 inititates an invoice transaction, requesting payment let args = IssueInvoiceTxArgs { amount: reward * 2, @@ -177,6 +188,14 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { selection_strategy_is_use_all: true, ..Default::default() }; + let mut zero_amount_slate = slate.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.process_invoice_tx(m, &zero_amount_slate, args.clone()) + .unwrap_err(), + libwallet::Error::InvalidAmount + ); + slate = api.process_invoice_tx(m, &slate, args)?; api.tx_lock_outputs(m, &slate)?; Ok(()) diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 5425ef8..107c17d 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -112,10 +112,41 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> mask1, PathBuf::from(test_dir), |sender_api, m| { + // Do not allow to send 0 + let error = sender_api + .init_send_tx( + m, + InitTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + + // Result amount can not be 0 when amount includes fee + let mut init_args = InitTxArgs { + amount_includes_fee: Some(true), + amount: 23_000_000, + estimate_only: Some(true), + ..Default::default() + }; + let est = sender_api.init_send_tx(m, init_args.clone())?; + assert_eq!(init_args.amount, est.fee_fields.fee()); + + init_args.estimate_only = None; + let error = sender_api.init_send_tx(m, init_args).unwrap_err(); + assert_eq!( + error, + libwallet::Error::GenericError( + "Transaction amount is too small to include fee".to_string() + ) + ); + // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { src_acct_name: None, - amount: amount, + amount, minimum_confirmations: 2, max_outputs: 500, num_change_outputs: 1, @@ -127,6 +158,21 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> assert_eq!(slate_i.state, SlateState::Standard1); assert_eq!(slate_i.version_info.block_header_version, header_version); + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let mut zero_amount_slate = slate_i.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), + libwallet::Error::InvalidAmount + ); + Ok(()) + }, + )?; + // Check we are creating a tx with the expected lock_height of 0. // We will check this produces a Plain kernel later. assert_eq!(0, slate.kernel_features); diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 4547b87..5c63a52 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -65,6 +65,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); if ret_slate.state != SlateState::Standard1 { return Err(Error::SlateState); diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 44aecae..58bfbd2 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -534,6 +534,10 @@ where C: NodeClient, K: Keychain, { + if args.amount == 0 { + return Err(Error::InvalidAmount); + } + let payment_proof_address = if let Some(a) = &args.payment_proof_recipient_address { if a.valid_network() { Some(a) @@ -657,6 +661,10 @@ where C: NodeClient, K: Keychain, { + if args.amount == 0 { + return Err(Error::InvalidAmount); + } + let parent_key_id = match args.dest_acct_name { Some(d) => { let pm = w.get_acct_path(d)?; @@ -710,6 +718,10 @@ where C: NodeClient, K: Keychain, { + if slate.amount == 0 { + return Err(Error::InvalidAmount); + } + let mut ret_slate = slate.clone(); check_ttl(w, &ret_slate)?; let parent_key_id = match args.src_acct_name { diff --git a/libwallet/src/error.rs b/libwallet/src/error.rs index 1c772bf..5300dd1 100644 --- a/libwallet/src/error.rs +++ b/libwallet/src/error.rs @@ -24,6 +24,10 @@ use grin_store; /// Wallet errors, mostly wrappers around underlying crypto or I/O errors. #[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)] pub enum Error { + /// Invalid transaction amount + #[error("Invalid amount (must be greater than zero)")] + InvalidAmount, + /// Not enough funds #[error("Not enough funds. Required: {needed_disp:?}, Available: {available_disp:?}")] NotEnoughFunds { diff --git a/libwallet/src/internal/selection.rs b/libwallet/src/internal/selection.rs index ac17dbd..bac6d92 100644 --- a/libwallet/src/internal/selection.rs +++ b/libwallet/src/internal/selection.rs @@ -73,9 +73,12 @@ where false, )?; if amount_includes_fee { - slate.amount = slate.amount.checked_sub(fee).ok_or(Error::GenericError( - "Transaction amount is too small to include fee".to_string(), - ))?; + let small_amount_err = + Error::GenericError("Transaction amount is too small to include fee".to_string()); + if slate.amount == fee { + return Err(small_amount_err); + } + slate.amount = slate.amount.checked_sub(fee).ok_or(small_amount_err)?; }; if fixed_fee.map(|f| fee != f).unwrap_or(false) { @@ -104,15 +107,9 @@ where context.add_input(&input.key_id, &input.mmr_index, input.value); } - let mut commits: HashMap> = HashMap::new(); - - // Store change output(s) and cached commits + // Store change output(s) for (change_amount, id, mmr_index) in &change_amounts_derivations { context.add_output(&id, &mmr_index, *change_amount); - commits.insert( - id.clone(), - wallet.calc_commit_for_cache(keychain_mask, *change_amount, &id)?, - ); } Ok(context) diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 86f7675..a4d8308 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -147,6 +147,11 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let arg_vec = vec!["grin-wallet", "-p", "password2", "account"]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + // Return an explained error when trying to send max amount on empty wallet. + let arg_vec = vec!["grin-wallet", "-p", "password2", "send", "max"]; + let err = execute_command(&app, test_dir, "wallet2", &client2, arg_vec).unwrap_err(); + assert!(format!("{}", err).contains("No spendable funds")); + // Mine a bit into wallet 1 so we have something to send // (TODO: Be able to stop listeners so we can test this better) let wallet_config1 = config1.clone().members.wallet; From 50caa5ecc4c09b4caed3148cce9dbfcfdb0a8bdd Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Tue, 22 Sep 2026 14:14:04 +0200 Subject: [PATCH 27/39] avoid empty wallet seeds (#801) * fix empty wallet seeds * mnemonic: return actual error with entropy size on recovering * seed: extend mnemonic error description * seed: clarify mnemonic errors * seed: clarify mnemonic errors, fix missing phrase test * Clean up seed handling add test --------- Co-authored-by: ardocrat (cherry picked from commit 51ce8e2f2a2698e988cb84edfdbf8e4da69c9617) --- api/src/owner.rs | 6 +- impls/src/error.rs | 4 +- impls/src/lifecycle/default.rs | 108 +++++++++++++++++++++++++++++++-- impls/src/lifecycle/seed.rs | 36 +++++++---- libwallet/src/types.rs | 2 +- 5 files changed, 134 insertions(+), 22 deletions(-) diff --git a/api/src/owner.rs b/api/src/owner.rs index 7ca6b5d..1296db8 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -1726,8 +1726,10 @@ where /// * `name`: Reserved for future use, use `None` for the time being. /// * `mnemonic`: If present, restore the wallet seed from the given mnemonic instead of creating /// a new random seed. - /// * `mnemonic_length`: Desired length of mnemonic in bytes (16 or 32, either 12 or 24 words). - /// Use 0 if mnemonic isn't being used. + /// * `mnemonic_length`: Entropy length in bytes: 16, 20, 24, 28 or 32 + /// (12, 15, 18, 21 or 24 words). Ignored when `mnemonic` is provided. + /// For a new random seed, 0 is also accepted and defaults to 32 bytes. + /// All other values return an error. /// * `password`: The password used to encrypt/decrypt the `wallet.seed` file /// /// # Returns diff --git a/impls/src/error.rs b/impls/src/error.rs index 4169e68..a22cb2a 100644 --- a/impls/src/error.rs +++ b/impls/src/error.rs @@ -75,8 +75,8 @@ pub enum Error { Encryption, /// BIP 39 word list - #[error("BIP39 Mnemonic (word list) Error")] - Mnemonic, + #[error("BIP39 Mnemonic (word list) Error: {}", _0)] + Mnemonic(String), /// Command line argument error #[error("{}", _0)] diff --git a/impls/src/lifecycle/default.rs b/impls/src/lifecycle/default.rs index 7514a30..ca11687 100644 --- a/impls/src/lifecycle/default.rs +++ b/impls/src/lifecycle/default.rs @@ -182,7 +182,7 @@ where &mut self, _name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error> { @@ -196,16 +196,15 @@ where return Err(Error::WalletSeedExists(msg)); } } + let entropy_size = if entropy_size == 0 { 32 } else { entropy_size }; WalletSeed::init_file( &data_dir_name, - mnemonic_length, + entropy_size, mnemonic.clone(), password, test_mode, ) - .map_err(|_| { - Error::Lifecycle("Error creating wallet seed (is mnemonic valid?)".to_owned()) - })?; + .map_err(|e| Error::Lifecycle(format!("Error creating wallet seed: {}", e)))?; info!("Wallet seed file created"); let mut wallet: WalletBackend = match WalletBackend::new(&data_dir_name, self.node_client.clone()) { @@ -248,6 +247,9 @@ where let wallet_seed = WalletSeed::from_file(&data_dir_name, password).map_err(|_| { Error::Lifecycle("Error opening wallet (is password correct?)".to_owned()) })?; + if wallet_seed.is_empty() { + warn!("This wallet has an empty seed and its funds are unsafe. Move them to a new wallet."); + } let keychain = wallet_seed .derive_keychain(global::is_testnet()) .map_err(|_| Error::Lifecycle("Error deriving keychain".to_owned()))?; @@ -286,7 +288,7 @@ where .map_err(|_| Error::Lifecycle("Error opening wallet seed file".into()))?; let res = wallet_seed .to_mnemonic() - .map_err(|_| Error::Lifecycle("Error recovering wallet seed".into()))?; + .map_err(|e| Error::Lifecycle(format!("Error recovering wallet seed: {}. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.", e)))?; Ok(ZeroingString::from(res)) } @@ -382,3 +384,97 @@ where } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::keychain::ExtKeychain; + use crate::lifecycle::seed::{EncryptedWalletSeed, SEED_FILE}; + use crate::node_clients::HTTPNodeClient; + use std::fs::File; + use std::io::Write; + use std::time::Duration; + + fn provider(test_dir: &str) -> DefaultLCProvider { + let client = + HTTPNodeClient::new("http://127.0.0.1:1", None, Duration::from_secs(1)).unwrap(); + let mut provider = DefaultLCProvider::new(client); + provider.set_top_level_directory(test_dir).unwrap(); + provider + } + + #[test] + fn default_recovery_phrase() { + let test_dir = "test_output/default_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + + provider + .create_wallet(None, None, 0, password.clone(), false) + .unwrap(); + let mnemonic = provider.get_mnemonic(None, password).unwrap(); + + assert_eq!(mnemonic.split_whitespace().count(), 24); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn mnemonic_error_redacted() { + let test_dir = "test_output/mnemonic_error_redacted"; + let _ = fs::remove_dir_all(test_dir); + let mut provider = provider(test_dir); + let input = ZeroingString::from("INVALID_INPUT_MARKER ".repeat(12)); + let error = provider + .create_wallet(None, Some(input), 32, ZeroingString::from("test"), false) + .unwrap_err() + .to_string(); + + assert!(error.contains("invalid bip39 word")); + assert!(!error.contains("INVALID_INPUT_MARKER")); + assert!(!provider.wallet_exists(None).unwrap()); + fs::remove_dir_all(test_dir).unwrap(); + } + + #[test] + fn missing_recovery_phrase() { + let test_dir = "test_output/missing_recovery_phrase"; + let _ = fs::remove_dir_all(test_dir); + global::set_local_chain_type(global::ChainTypes::AutomatedTesting); + let mut provider = provider(test_dir); + let password = ZeroingString::from("test"); + let data_dir = PathBuf::from(test_dir).join(GRIN_WALLET_DIR); + fs::create_dir_all(data_dir.clone()).unwrap(); + + let seed_file_path = &format!( + "{}{}{}", + fmt_path(data_dir.to_str().unwrap().to_string()), + MAIN_SEPARATOR, + SEED_FILE, + ); + + let enc_seed = EncryptedWalletSeed::from_seed( + &WalletSeed::from_bytes(vec![].as_slice()), + password.clone(), + ) + .unwrap(); + let enc_seed_json = serde_json::to_string_pretty(&enc_seed).unwrap(); + let mut file = File::create(seed_file_path).unwrap(); + file.write_all(&enc_seed_json.as_bytes()).unwrap(); + + let error = match provider.get_mnemonic(None, password.clone()) { + Ok(_) => panic!("expected missing recovery phrase error"), + Err(error) => error, + }; + + assert_eq!( + error, + Error::Lifecycle("Error recovering wallet seed: BIP39 Mnemonic (word list) Error: invalid mnemonic/entropy length 0. This wallet has no valid recovery phrase and its funds may be unsafe. Move them to a new wallet.".into()) + ); + provider.open_wallet(None, password, false, false).unwrap(); + provider.close_wallet(None).unwrap(); + assert_eq!(fs::read_to_string(seed_file_path).unwrap(), enc_seed_json); + fs::remove_dir_all(test_dir).unwrap(); + } +} diff --git a/impls/src/lifecycle/seed.rs b/impls/src/lifecycle/seed.rs index 5dbbd6c..16f924a 100644 --- a/impls/src/lifecycle/seed.rs +++ b/impls/src/lifecycle/seed.rs @@ -39,11 +39,18 @@ impl WalletSeed { WalletSeed(bytes.to_vec()) } + pub(super) fn is_empty(&self) -> bool { + self.0.is_empty() + } + pub fn from_mnemonic(word_list: util::ZeroingString) -> Result { let res = mnemonic::to_entropy(&word_list); match res { Ok(s) => Ok(WalletSeed::from_bytes(&s)), - Err(_) => Err(Error::Mnemonic.into()), + Err(mnemonic::Error::BadWord(_)) => { + Err(Error::Mnemonic("invalid bip39 word".to_owned())) + } + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } @@ -61,7 +68,7 @@ impl WalletSeed { let result = mnemonic::from_entropy(&self.0); match result { Ok(r) => Ok(r), - Err(_) => Err(Error::Mnemonic.into()), + Err(e) => Err(Error::Mnemonic(format!("{}", e))), } } @@ -76,14 +83,14 @@ impl WalletSeed { } pub fn init_new( - seed_length: usize, + entropy_size: usize, test_mode: bool, password: Option, - ) -> WalletSeed { + ) -> Result { let mut seed: Vec = vec![]; let mut rng = thread_rng(); if !test_mode { - for _ in 0..seed_length { + for _ in 0..entropy_size { seed.push(rng.gen()); } } else { @@ -93,7 +100,10 @@ impl WalletSeed { .as_bytes() .to_vec(); } - WalletSeed(seed) + let _ = mnemonic::from_entropy(seed.as_slice()) + .map(util::ZeroingString::from) + .map_err(|e| Error::Mnemonic(format!("{}", e)))?; + Ok(WalletSeed(seed)) } pub fn seed_file_exists(data_file_dir: &str) -> Result { @@ -168,7 +178,7 @@ impl WalletSeed { pub fn init_file( data_file_dir: &str, - seed_length: usize, + entropy_size: usize, recovery_phrase: Option, password: util::ZeroingString, test_mode: bool, @@ -193,7 +203,7 @@ impl WalletSeed { let seed = match recovery_phrase { Some(p) => WalletSeed::from_mnemonic(p)?, - None => WalletSeed::init_new(seed_length, test_mode, Some(password.clone())), + None => WalletSeed::init_new(entropy_size, test_mode, Some(password.clone()))?, }; let enc_seed = EncryptedWalletSeed::from_seed(&seed, password)?; @@ -277,7 +287,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -325,7 +335,7 @@ impl EncryptedWalletSeed { let password = password.as_bytes(); let mut key = [0; 32]; pbkdf2::derive( - ring::pbkdf2::PBKDF2_HMAC_SHA512, + pbkdf2::PBKDF2_HMAC_SHA512, NonZeroU32::new(100).unwrap(), &salt, password, @@ -359,8 +369,12 @@ mod tests { use crate::util::ZeroingString; #[test] fn wallet_seed_encrypt() { + // Wrong entropy size. + let wrong_entropy_size = WalletSeed::init_new(31, false, None).err(); + assert!(wrong_entropy_size.is_some()); + let password = ZeroingString::from("passwoid"); - let wallet_seed = WalletSeed::init_new(32, false, None); + let wallet_seed = WalletSeed::init_new(32, false, None).unwrap(); let mut enc_wallet_seed = EncryptedWalletSeed::from_seed(&wallet_seed, password.clone()).unwrap(); println!("EWS: {:?}", enc_wallet_seed); diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index ae86f1b..0aec740 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -81,7 +81,7 @@ where &mut self, name: Option<&str>, mnemonic: Option, - mnemonic_length: usize, + entropy_size: usize, password: ZeroingString, test_mode: bool, ) -> Result<(), Error>; From cec94917de9b3c10ac2f0bcf58be149c65455d71 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:11:32 +0200 Subject: [PATCH 28/39] Show HTTP status when node requests fail (#820) (cherry picked from commit ec1e9910afe4c5852e0f0e614c88f4a20140f3d8) --- impls/src/client_utils/client.rs | 62 +++++++++++++++++++++++++++++--- impls/src/node_clients/http.rs | 19 ++++------ 2 files changed, 64 insertions(+), 17 deletions(-) diff --git a/impls/src/client_utils/client.rs b/impls/src/client_utils/client.rs index 94b7b37..20e787f 100644 --- a/impls/src/client_utils/client.rs +++ b/impls/src/client_utils/client.rs @@ -225,7 +225,7 @@ impl Client { IN: Serialize, { let json = serde_json::to_string(input) - .map_err(|_| Error::Internal("Could not serialize data to JSON".to_owned()))?; + .map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?; self.build_request(url, Method::POST, api_secret, Some(json)) } @@ -235,7 +235,7 @@ impl Client { { let data = self.send_request(req)?; serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned())) + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e))) } async fn handle_request_async(&self, req: RequestBuilder) -> Result @@ -244,7 +244,7 @@ impl Client { { let data = self.send_request_async(req).await?; let ser = serde_json::from_str(&data) - .map_err(|_| Error::ResponseError("Cannot parse response".to_owned()))?; + .map_err(|e| Error::ResponseError(format!("Cannot parse response: {}", e)))?; Ok(ser) } @@ -253,6 +253,10 @@ impl Client { .send() .await .map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?; + let status = resp.status(); + if status.is_client_error() || status.is_server_error() { + return Err(Error::ResponseError(format!("HTTP {}", status))); + } let text = resp .text() .await @@ -261,7 +265,7 @@ impl Client { } pub fn send_request(&self, req: RequestBuilder) -> Result { - // This client is currently used both outside and inside of a tokio runtime + // This client is currently used both outside and inside the tokio runtime // context. In the latter case we are not allowed to do a blocking call to // our global runtime, which unfortunately means we have to spawn a new thread if Handle::try_current().is_ok() { @@ -275,3 +279,53 @@ impl Client { } } } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + use tokio::net::TcpListener; + + #[tokio::test] + async fn http_status() { + let client = Client { + client: ClientBuilder::new() + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap(), + }; + for (status, body, expected) in [ + ("200 OK", "{}", Ok(serde_json::json!({}))), + ( + "401 Unauthorized", + "Unauthorized", + Err(Error::ResponseError("HTTP 401 Unauthorized".into())), + ), + ] { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut headers = BufReader::new(&mut stream).lines(); + while let Some(line) = headers.next_line().await.unwrap() { + if line.is_empty() { + break; + } + } + let response = format!( + "HTTP/1.1 {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + status, + body.len(), + body + ); + stream.write_all(response.as_bytes()).await.unwrap(); + }); + assert_eq!( + client._get_async::(&url, None).await, + expected + ); + server.await.unwrap(); + } + } +} diff --git a/impls/src/node_clients/http.rs b/impls/src/node_clients/http.rs index 8b7ed0e..b28a30c 100644 --- a/impls/src/node_clients/http.rs +++ b/impls/src/node_clients/http.rs @@ -142,19 +142,12 @@ impl NodeClient for HTTPNodeClient { }, Err(e) => { // If node isn't available, allow offline functions - // unfortunately have to parse string due to error structure - let err_string = format!("{}", e); - return if err_string.contains("404") { - Some(NodeVersionInfo { - node_version: "1.0.0".into(), - block_header_version: 1, - verified: Some(false), - }) - } else { - error!("Unable to contact Node to get version info: {}, check your node is running", e); - warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly"); - None - }; + error!( + "Unable to contact Node to get version info: {}, check your node is running", + e + ); + warn!("Warning: a) Node is offline, or b) 'node_api_secret_path' in 'grin-wallet.toml' is set incorrectly"); + return None; } }; self.node_version_info = Some(retval.clone()); From 2302135709df5f8f9a0d5aeeee7b7807258275e3 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 16 Sep 2026 15:53:57 +0300 Subject: [PATCH 29/39] Lock outputs before sending with Tor (#814) Co-authored-by: wiesche (cherry picked from commit 452a3ec51b302091e12fc1a7b2eb24c0ac2625b0) --- api/src/owner.rs | 73 +- controller/src/command.rs | 34 +- controller/src/controller.rs | 17 - controller/tests/accounts.rs | 294 +++---- controller/tests/build_chain.rs | 91 +-- controller/tests/build_output.rs | 35 +- controller/tests/check.rs | 648 +++++---------- controller/tests/common/mod.rs | 35 +- controller/tests/config_api.rs | 18 +- controller/tests/file.rs | 265 ++---- controller/tests/invoice.rs | 397 ++++----- controller/tests/late_lock.rs | 145 ++-- controller/tests/mwixnet.rs | 168 ++-- controller/tests/no_change.rs | 214 ++--- controller/tests/payment_proofs.rs | 136 ++-- controller/tests/repost.rs | 232 ++---- controller/tests/revert.rs | 289 +++---- controller/tests/self_send.rs | 103 +-- controller/tests/slatepack.rs | 512 +++++------- controller/tests/transaction.rs | 1108 ++++++++++++-------------- controller/tests/ttl_cutoff.rs | 155 ++-- controller/tests/tx_list_filter.rs | 434 +++++----- controller/tests/updater_thread.rs | 31 +- impls/src/adapters/tor.rs | 2 +- libwallet/src/mwixnet/onion/onion.rs | 2 +- tests/cmd_line_basic.rs | 248 +++--- tests/owner_v3_lifecycle.rs | 41 +- 27 files changed, 2275 insertions(+), 3452 deletions(-) diff --git a/api/src/owner.rs b/api/src/owner.rs index 1296db8..c180934 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -40,6 +40,7 @@ use grin_wallet_util::OnionV3Address; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; +use libwallet::wallet_lock; use std::convert::TryFrom; use std::fs::File; use std::io::Write; @@ -709,9 +710,9 @@ where /// is confirmed. This method also returns a function that will perform that locking, and it is /// up to the caller to decide the best time to call the lock function /// (via the [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) method). - /// If the exchange method is intended to be synchronous (such as via a direct http call,) + /// If the exchange method is intended to be synchronous (such as via a direct http call) /// then the lock call can wait until the response is confirmed. If it is asynchronous, (such - /// as via file transfer,) the lock call should happen immediately (before the file is sent + /// as via file transfer) the lock call should happen immediately (before the file is sent /// to the recipient). /// /// If the `send_args` [`InitTxSendArgs`](../grin_wallet_libwallet/types/struct.InitTxSendArgs.html), @@ -719,7 +720,7 @@ where /// function will attempt to send the slate back to the sender using the slatepack sync /// send (TOR). If providing this argument, check the `state` field of the slate to see if the /// sync_send was successful (it should be S2 if the sync sent successfully). It will also post - /// the transction if the `post_tx` field is set. + /// the transaction if the `post_tx` field is set. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if @@ -730,11 +731,15 @@ where /// # Returns /// * a result containing: /// * The transaction [Slate](../grin_wallet_libwallet/slate/struct.Slate.html), - /// which can be forwarded to the recieving party by any means. Once the caller is relatively - /// certain that the transaction has been sent to the recipient, the associated wallet - /// transaction outputs should be locked via a call to - /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs). This must be called before calling - /// [`finalize_tx`](struct.Owner.html#method.finalize_tx). + /// which can be forwarded to the receiving party by any means. With normal locking, an + /// attempted Tor send already locks the outputs, even if sending fails. Do not call + /// [`tx_lock_outputs`](struct.Owner.html#method.tx_lock_outputs) again when forwarding manually. + /// If sending was not requested or was skipped, lock the outputs before forwarding the slate. + /// With late locking, outputs are locked during finalization instead. + /// If `skip_tor` is omitted, `skip_send_attempt` in the Tor config decides whether to send. + /// With normal locking, a returned S1 slate alone does not tell you whether outputs are locked. + /// Set `skip_tor` explicitly or check [`retrieve_txs`](struct.Owner.html#method.retrieve_txs) + /// for the slate ID before locking manually. /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. /// /// # Remarks @@ -768,7 +773,7 @@ where /// if let Ok(slate) = result { /// // Send slate somehow /// // ... - /// // Lock our outputs if we're happy the slate was (or is being) sent + /// // Lock outputs for manual sending without late locking /// api_owner.tx_lock_outputs(None, &slate); /// } /// ``` @@ -785,32 +790,36 @@ where } _ => None, }; - let (slate, tor_config) = { - let mut w_lock = self.wallet_inst.lock(); - let tor_config = send_args - .as_ref() - .map(|_| crate::tor_config::load(&self.config_path())) - .transpose()?; - let w = w_lock.lc_provider()?.wallet_inst()?; - let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; - (slate, tor_config) - }; + + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + // Helper functionality. If send arguments exist, attempt to send sync and // finalize match send_args { Some(sa) => { - let tc = tor_config.ok_or_else(|| { - Error::TorConfig("Tor config was not loaded with send arguments".into()) - })?; - let can_send = tc.send_tor(sa.skip_tor); - if self.doctest_mode || !can_send || dest.is_none() { - return Ok(slate); - } + let slate = { + wallet_lock!(self.wallet_inst, w); + let late_lock = args.late_lock.unwrap_or(false); + let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + let tc = tor_config.as_ref().ok_or_else(|| { + Error::TorConfig("Tor config was not loaded with send arguments".into()) + })?; + let can_send = tc.send_tor(sa.skip_tor); + if self.doctest_mode || !can_send || dest.is_none() { + return Ok(slate); + } + if !late_lock { + owner::tx_lock_outputs(w, keychain_mask, &slate)?; + } + slate + }; let res = - try_slatepack_sync_workflow(&slate, &dest.unwrap(), Some(tc), None, false); + try_slatepack_sync_workflow(&slate, &dest.unwrap(), tor_config, None, false); match res { Ok(s) => { - self.tx_lock_outputs(keychain_mask, &s)?; let ret_slate = self.finalize_tx(keychain_mask, &s)?; if sa.post_tx { let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff); @@ -834,7 +843,11 @@ where } } } - None => Ok(slate), + None => { + wallet_lock!(self.wallet_inst, w); + let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + Ok(slate) + } } } @@ -2353,7 +2366,7 @@ where /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `slatepack` - A string representing an armored slatepack - /// * `secret_indices` - Indices along this wallet's deriviation path with which to attempt + /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt /// decryption. This function will attempt to use secret keys at each index along this path /// to attempt to decrypt the payload, returning an error if none of the keys match. /// diff --git a/controller/src/command.rs b/controller/src/command.rs index daeb256..97b59d5 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -439,7 +439,6 @@ where target_slate_version: args.target_slate_version, payment_proof_recipient_address, ttl_blocks: args.ttl_blocks, - send_args: None, late_lock: Some(args.late_lock), ..Default::default() }; @@ -494,14 +493,14 @@ where tor_config.bridge.bridge_line = Some(b); } - let output_sp = || -> Result<(), Error> { + let output_sp = |owner_api: &mut Owner, lock_outputs: bool| -> Result<(), Error> { Ok(output_slatepack( owner_api, keychain_mask, &slate, dest.clone(), args.outfile, - true, + lock_outputs, false, args.slatepack_qr, )?) @@ -509,7 +508,11 @@ where let can_send = tor_config.send_tor(args.skip_tor); if test_mode || !can_send || dest.is_none() { - return output_sp(); + return output_sp(owner_api, !args.late_lock); + } + + if !args.late_lock { + owner_api.tx_lock_outputs(keychain_mask, &slate)?; } let dest = dest.as_ref().unwrap(); @@ -517,7 +520,6 @@ where match res { Ok(s) => { - owner_api.tx_lock_outputs(keychain_mask, &s)?; let ret_slate = owner_api.finalize_tx(keychain_mask, &s)?; let result = owner_api.post_tx(keychain_mask, &ret_slate, args.fluff); match result { @@ -532,7 +534,13 @@ where } Err(e) => { error!("Error sending slate sync: {}", e); - output_sp()?; + output_sp(owner_api, false)?; + if !args.late_lock { + println!( + "Outputs are locked. To unlock them, cancel with `cancel -t {}`.", + slate.id + ); + } } } Ok(()) @@ -581,7 +589,18 @@ where println!(); if !finalizing { - println!("Slatepack data follows. Please provide this output to the other party"); + let cancel_hint = if lock { + format!( + " or cancel it manually with `cancel -t {}` command", + slate.id + ) + } else { + "".to_string() + }; + println!( + "Slatepack data follows. Please provide this output to the other party{}.", + cancel_hint + ); } else { println!("Slatepack data follows."); } @@ -1074,7 +1093,6 @@ where selection_strategy_is_use_all: args.selection_strategy == "all", refresh_outputs_from_node: !info_updated, ttl_blocks: args.ttl_blocks, - send_args: None, ..Default::default() }; let result = owner_api.process_invoice_tx(keychain_mask, &slate, init_args); diff --git a/controller/src/controller.rs b/controller/src/controller.rs index ef61152..49fa040 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -136,23 +136,6 @@ fn init_tor_listener( Ok(process) } -/// Instantiate wallet Owner API for a single-use (command line) call -/// Return a function containing a loaded API context to call -pub fn owner_single_use( - wallet: Arc>>>, - keychain_mask: Option<&SecretKey>, - config_path: PathBuf, - f: F, -) -> Result<(), Error> -where - L: WalletLCProvider<'static, C, K> + 'static, - F: FnOnce(&mut Owner, Option<&SecretKey>) -> Result<(), Error>, - C: NodeClient + 'static, - K: Keychain + 'static, -{ - f(&mut Owner::new(wallet, None, config_path), keychain_mask) -} - /// Instantiate wallet Foreign API for a single-use (command line) call /// Return a function containing a loaded API context to call pub fn foreign_single_use<'a, L, F, C, K>( diff --git a/controller/tests/accounts.rs b/controller/tests/accounts.rs index 59645f8..fd19c28 100644 --- a/controller/tests/accounts.rs +++ b/controller/tests/accounts.rs @@ -19,7 +19,6 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_keychain as keychain; -use std::path::PathBuf; use self::core::global; use self::keychain::{ExtKeychain, Keychain}; @@ -49,7 +48,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -62,7 +62,8 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -79,48 +80,30 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // test default accounts exist - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let accounts = api.accounts(m)?; - assert_eq!(accounts[0].label, "default"); - assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); - Ok(()) - }, - )?; + { + let accounts = api1.accounts(mask1)?; + assert_eq!(accounts[0].label, "default"); + assert_eq!(accounts[0].path, ExtKeychain::derive_key_id(2, 0, 0, 0, 0)); + } // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let new_path = api.create_account_path(m, "account1").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - let new_path = api.create_account_path(m, "account2").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); - let new_path = api.create_account_path(m, "account3").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); - // trying to add same label again should fail - let res = api.create_account_path(m, "account1"); - assert!(res.is_err()); - Ok(()) - }, - )?; + { + let new_path = api1.create_account_path(mask1, "account1").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "account2").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 2, 0, 0, 0)); + let new_path = api1.create_account_path(mask1, "account3").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 3, 0, 0, 0)); + // trying to add same label again should fail + let res = api1.create_account_path(mask1, "account1"); + assert!(res.is_err()); + } // add account to wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let new_path = api.create_account_path(m, "listener_account").unwrap(); - assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); - Ok(()) - }, - )?; + { + let new_path = api2.create_account_path(mask2, "listener_account").unwrap(); + assert_eq!(new_path, ExtKeychain::derive_key_id(2, 1, 0, 0, 0)); + } // Default wallet 2 to listen on that account { @@ -144,120 +127,85 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 5 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 5); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 5 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (5 - cm) * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 5); + } // now check second account { - // let mut w_lock = wallet1.lock(); - // let lc = w_lock.lc_provider()?; - // let w = lc.wallet_inst()?; wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let labels: Vec<_> = api.accounts(m)?.into_iter().map(|a| a.label).collect(); - assert_eq!(labels, ["account1", "default", "account2", "account3"]); - // check last confirmed height on this account is different from above (should be 0) - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 7 * reward); - assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 7); - Ok(()) - }, - )?; - + { + let labels: Vec<_> = api1.accounts(mask1)?.into_iter().map(|a| a.label).collect(); + assert_eq!(labels, ["account1", "default", "account2", "account3"]); + // check last confirmed height on this account is different from above (should be 0) + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 7 * reward); + assert_eq!(wallet1_info.amount_currently_spendable, 7 * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 7); + } // should be nothing in default account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 0); - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 12); - assert_eq!(wallet1_info.total, 0,); - assert_eq!(wallet1_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 0); + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 12); + assert_eq!(wallet1_info.total, 0,); + assert_eq!(wallet1_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 0); + } // Send a tx to another wallet { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account1")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 9); - Ok(()) - }, - )?; + { + let args = InitTxArgs { + src_acct_name: None, + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; + } + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert_eq!(txs.len(), 9); + } // Use the requested account's stored height { wallet_inst!(wallet1, w); @@ -272,59 +220,41 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("account2")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 12); - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - println!("{:?}", txs); - assert_eq!(txs.len(), 5); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 12); + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, 13); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + println!("{:?}", txs); + assert_eq!(txs.len(), 5); + } // wallet 2 should only have this tx on the listener account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - Ok(()) - }, - )?; + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + } // Default account on wallet 2 should be untouched { wallet_inst!(wallet2, w); w.set_parent_key_id_by_name("default")?; } - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(wallet2_info.last_confirmed_height, 0); - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, 13); - assert_eq!(wallet2_info.total, 0,); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - }, - )?; + { + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, false, 1)?; + assert_eq!(wallet2_info.last_confirmed_height, 0); + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, 13); + assert_eq!(wallet2_info.total, 0,); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); + } // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/build_chain.rs b/controller/tests/build_chain.rs index 7120e44..12210e8 100644 --- a/controller/tests/build_chain.rs +++ b/controller/tests/build_chain.rs @@ -21,9 +21,8 @@ extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; use grin_core as core; -use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use rand::Rng; use std::sync::atomic::Ordering; @@ -48,7 +47,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); debug!("Mask1: {:?}", mask1); @@ -60,7 +60,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); debug!("Mask2: {:?}", mask2); @@ -74,25 +75,8 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -105,22 +89,14 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } // let's say 1 in every 3 blocks has a transaction (i.e. random 0 here and wallet1 has funds) let transact = rng.gen_range(0, 2) == 0; @@ -134,30 +110,21 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal let num_txs = rng.gen_range(0, 3); for _ in 0..num_txs { let amount: u64 = rng.gen_range(1, 10_000_000_001); - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; } } // let logging finish diff --git a/controller/tests/build_output.rs b/controller/tests/build_output.rs index 491e916..798732d 100644 --- a/controller/tests/build_output.rs +++ b/controller/tests/build_output.rs @@ -25,7 +25,6 @@ use grin_util::{secp, ZeroingString}; use grin_wallet_libwallet as libwallet; use impls::test_framework::LocalWalletClient; use rand::{thread_rng, Rng}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -37,7 +36,7 @@ use common::{clean_output_dir, create_wallet_proxy, setup}; fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { // Generate seed so we can verify the blinding factor is derived correctly let seed: [u8; 32] = thread_rng().gen(); - let keychain = ExtKeychain::from_seed(&seed, false).unwrap(); + let keychain = ExtKeychain::from_seed(&seed, false)?; let mnemonic = mnemonic::from_entropy(&seed).unwrap(); // Create a new proxy to simulate server and wallet responses @@ -52,7 +51,8 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error "wallet1", Some(ZeroingString::from(mnemonic)), &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -67,28 +67,19 @@ fn build_output_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error let secp = secp::Secp256k1::with_caps(secp::ContextFlag::Commit); let features = OutputFeatures::Plain; let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let built_output = sender_api.build_output(m, features, amount)?; + let built_output = api1.build_output(mask1, features, amount)?; - let key_id = built_output.key_id; - assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); + let key_id = built_output.key_id; + assert_eq!(key_id.to_path(), ExtKeychainPath::new(3, 0, 0, 0, 0)); - let blind = built_output.blind; - let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; - assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); + let blind = built_output.blind; + let key = keychain.derive_key(amount, &key_id, SwitchCommitmentType::Regular)?; + assert_eq!(blind, BlindingFactor::from_secret_key(key.clone())); - let output = built_output.output; - assert_eq!(output.features(), features); - assert_eq!(output.commitment(), secp.commit(amount, key)?); - output.verify_proof()?; - - Ok(()) - }, - )?; + let output = built_output.output; + assert_eq!(output.features(), features); + assert_eq!(output.commitment(), secp.commit(amount, key)?); + output.verify_proof()?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/check.rs b/controller/tests/check.rs index d526335..6d7fbdb 100644 --- a/controller/tests/check.rs +++ b/controller/tests/check.rs @@ -27,7 +27,6 @@ use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlatePutter as _}; use libwallet::{InitTxArgs, NodeClient}; use std::cmp; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -66,7 +65,8 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -77,7 +77,8 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -89,34 +90,22 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // few values to keep things shorter - let reward = core::consensus::REWARD; - let cm = global::coinbase_maturity() as u64; // assume all testing precedes soft fork height + let reward = consensus::REWARD; + let cm = global::coinbase_maturity(); // assume all testing precedes soft fork height // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "named_account_1")?; - api.create_account_path(m, "account_2")?; - api.create_account_path(m, "account_3")?; - api.set_active_account(m, "named_account_1")?; - Ok(()) - }, - )?; + { + api1.create_account_path(mask1, "named_account_1")?; + api1.create_account_path(mask1, "account_2")?; + api1.create_account_path(mask1, "account_3")?; + api1.set_active_account(mask1, "named_account_1")?; + } // add account to wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + { + api2.create_account_path(mask2, "account_1")?; + api2.set_active_account(mask2, "account_1")?; + } // Do some mining let bh = 20u64; @@ -124,36 +113,21 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Sanity check contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(wallet1_info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(wallet1_info.total, c); + assert_eq!(txs.len(), bh as usize); + } // Accidentally delete some outputs - let mut w1_outputs_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - w1_outputs_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let w1_outputs_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; let w1_outputs: Vec = w1_outputs_commits.into_iter().map(|m| m.output).collect(); { @@ -170,108 +144,54 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { } // check we have a problem now - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_ne!(wallet1_info.total, c); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_ne!(wallet1_info.total, c); // this should restore our missing outputs - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check our outputs match again - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.total, bh * reward); - // And check account names haven't been splatted - let accounts = api.accounts(m)?; - assert_eq!(accounts.len(), 4); - assert!(api.set_active_account(m, "account_1").is_err()); - assert!(api.set_active_account(m, "named_account_1").is_ok()); - Ok(()) - }, - )?; - + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.total, bh * reward); + // And check account names haven't been splatted + let accounts = api1.accounts(mask1)?; + assert_eq!(accounts.len(), 4); + assert!(api1.set_active_account(mask1, "account_1").is_err()); + assert!(api1.set_active_account(mask1, "named_account_1").is_ok()); + } // perform a transaction, but don't let it finish - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - let send_file = format!("{}/part_tx_1.tx", test_dir); - PathToSlate(send_file.into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + { + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + } // check we're all locked - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.amount_currently_spendable, 0); - Ok(()) - }, - )?; - + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.amount_currently_spendable, 0); // unlock/restore - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; // check spendable amount again - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -300,7 +220,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "miner", None, &mut wallet_proxy, - false + false, + _m_api ); let miner_mask = (&miner_mask_i).as_ref(); @@ -313,7 +234,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet1", seed_phrase, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -324,7 +246,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet2", seed_phrase, &mut wallet_proxy, - false + false, + _api2 ); let mask2 = (&mask2_i).as_ref(); // we'll restore into here @@ -336,7 +259,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet3", seed_phrase, &mut wallet_proxy, - false + false, + api3 ); let mask3 = (&mask3_i).as_ref(); // also restore into here @@ -348,7 +272,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet4", seed_phrase, &mut wallet_proxy, - false + false, + api4 ); let mask4 = (&mask4_i).as_ref(); // Simulate a recover from seed without restore into here @@ -360,7 +285,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet5", seed_phrase, &mut wallet_proxy, - false + false, + api5 ); //simulate a recover from seed without restore into here let mask5 = (&mask5_i).as_ref(); @@ -372,7 +298,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet6", seed_phrase, &mut wallet_proxy, - false + false, + api6 ); let mask6 = (&mask6_i).as_ref(); @@ -384,7 +311,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet7", seed_phrase, &mut wallet_proxy, - false + false, + api7 ); let mask7 = (&mask7_i).as_ref(); create_wallet_and_add!( @@ -395,7 +323,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet8", seed_phrase, &mut wallet_proxy, - false + false, + api8 ); let mask8 = (&mask8_i).as_ref(); create_wallet_and_add!( @@ -406,7 +335,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet9", seed_phrase, &mut wallet_proxy, - false + false, + api9 ); let mask9 = (&mask9_i).as_ref(); create_wallet_and_add!( @@ -417,7 +347,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er "wallet10", seed_phrase, &mut wallet_proxy, - false + false, + api10 ); let mask10 = (&mask10_i).as_ref(); @@ -468,18 +399,10 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // 0) Check repair when all is okay should leave wallet contents alone - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - let info = wallet_info!(wallet1.clone(), m)?; - assert_eq!(info.amount_currently_spendable, base_amount * 6); - assert_eq!(info.total, base_amount * 6); - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; + let info = wallet_info!(wallet1.clone(), mask1)?; + assert_eq!(info.amount_currently_spendable, base_amount * 6); + assert_eq!(info.total, base_amount * 6); // send some funds to wallet 2 send_to_dest!( @@ -523,53 +446,21 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er // seed + BIP32 path. // 1) a full restore should recover all of them: - wallet::controller::owner_single_use( - wallet3.clone(), - mask3, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api3.scan(mask3, None, false)?; - wallet::controller::owner_single_use( - wallet3.clone(), - mask3, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet3.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - assert_eq!(info.total, base_amount * 21); - Ok(()) - }, - )?; + let info = wallet_info!(wallet3.clone(), mask3)?; + let outputs = api3.retrieve_outputs(mask3, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + assert_eq!(info.total, base_amount * 21); // 2) scan should recover them into a single wallet - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api1.scan(mask1, None, true)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet1.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - Ok(()) - }, - )?; + let info = wallet_info!(wallet1.clone(), mask1)?; + let outputs = api1.retrieve_outputs(mask1, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); // 3) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -601,41 +492,17 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet4.clone(), - mask4, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet4.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * 45); - Ok(()) - }, - )?; + let info = wallet_info!(wallet4.clone(), mask4)?; + let outputs = api4.retrieve_outputs(mask4, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * 45); - wallet::controller::owner_single_use( - wallet5.clone(), - mask5, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - Ok(()) - }, - )?; + api5.scan(mask5, None, false)?; - wallet::controller::owner_single_use( - wallet5.clone(), - mask5, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet5.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 9); - assert_eq!(info.amount_currently_spendable, base_amount * (45)); - Ok(()) - }, - )?; + let info = wallet_info!(wallet5.clone(), mask5)?; + let outputs = api5.retrieve_outputs(mask5, true, false, None)?.1; + assert_eq!(outputs.len(), 9); + assert_eq!(info.amount_currently_spendable, base_amount * (45)); // 4) If I recover from seed and start using the wallet without restoring, // scan should restore the older outputs @@ -662,50 +529,20 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er )?; bh += 3; - let _ = test_framework::award_blocks_to_wallet( - &chain, - miner.clone(), - miner_mask, - cm as usize, - false, - ); + let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * 78); - Ok(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * 78); - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - Ok(()) - }, - )?; + api6.scan(mask6, None, true)?; - wallet::controller::owner_single_use( - wallet6.clone(), - mask6, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet6.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 12); - assert_eq!(info.amount_currently_spendable, base_amount * (78)); - Ok(()) - }, - )?; + let info = wallet_info!(wallet6.clone(), mask6)?; + let outputs = api6.retrieve_outputs(mask6, true, false, None)?.1; + assert_eq!(outputs.len(), 12); + assert_eq!(info.amount_currently_spendable, base_amount * (78)); // 5) Start using same seed with a different account, amounts should // be distinct and restore should return funds from other account @@ -734,16 +571,8 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; // mix it up a bit - wallet::controller::owner_single_use( - wallet7.clone(), - mask7, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api7.create_account_path(mask7, "account_1")?; + api7.set_active_account(mask7, "account_1")?; send_to_dest!( miner.clone(), @@ -772,57 +601,33 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); bh += cm as u64; - wallet::controller::owner_single_use( - wallet7.clone(), - mask7, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet7.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); + api7.set_active_account(mask7, "default")?; + let info = wallet_info!(wallet7.clone(), mask7)?; + let outputs = api7.retrieve_outputs(mask7, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); - wallet::controller::owner_single_use( - wallet8.clone(), - mask8, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, false)?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet8.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 3); - assert_eq!(info.amount_currently_spendable, base_amount * 6); - Ok(()) - }, - )?; + api8.scan(mask8, None, false)?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); + api8.set_active_account(mask8, "account_1")?; + let info = wallet_info!(wallet8.clone(), mask8)?; + let outputs = api8.retrieve_outputs(mask8, true, false, None)?.1; + assert_eq!(outputs.len(), 3); + assert_eq!(info.amount_currently_spendable, base_amount * 6); // 6) Start using same seed with a different account, now overwriting // ids on account 2 as well, scan should get all outputs created // to now into 2 accounts - wallet::controller::owner_single_use( - wallet9.clone(), - mask9, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account_1")?; - api.set_active_account(m, "account_1")?; - Ok(()) - }, - )?; + api9.create_account_path(mask9, "account_1")?; + api9.set_active_account(mask9, "account_1")?; send_to_dest!( miner.clone(), @@ -848,53 +653,37 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er bh += 3; let _bh = bh; - wallet::controller::owner_single_use( - wallet9.clone(), - mask9, - PathBuf::from(test_dir), - |api, m| { - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.scan(m, None, true)?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); + api9.scan(mask9, None, true)?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet9.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + api9.set_active_account(mask9, "default")?; + let info = wallet_info!(wallet9.clone(), mask9)?; + let outputs = api9.retrieve_outputs(mask9, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); let _ = test_framework::award_blocks_to_wallet(&chain, miner.clone(), miner_mask, cm, false); // 7) Ensure scan creates missing accounts - wallet::controller::owner_single_use( - wallet10.clone(), - mask10, - PathBuf::from(test_dir), - |api, m| { - api.scan(m, None, true)?; - api.set_active_account(m, "account_1")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 6); - assert_eq!(info.amount_currently_spendable, base_amount * 21); + api10.scan(mask10, None, true)?; + api10.set_active_account(mask10, "account_1")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, true, false, None)?.1; + assert_eq!(outputs.len(), 6); + assert_eq!(info.amount_currently_spendable, base_amount * 21); - api.set_active_account(m, "default")?; - let info = wallet_info!(wallet10.clone(), m)?; - let outputs = api.retrieve_outputs(m, true, false, None)?.1; - assert_eq!(outputs.len(), 15); - assert_eq!(info.amount_currently_spendable, base_amount * 120); - Ok(()) - }, - )?; + api10.set_active_account(mask10, "default")?; + let info = wallet_info!(wallet10.clone(), mask10)?; + let outputs = api10.retrieve_outputs(mask10, true, false, None)?.1; + assert_eq!(outputs.len(), 15); + assert_eq!(info.amount_currently_spendable, base_amount * 120); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -918,7 +707,8 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + _api1 ); let mask1 = (&mask1_i).as_ref(); thread::spawn(move || { @@ -952,7 +742,7 @@ fn output_scanning_impl(test_dir: &'static str) -> Result<(), libwallet::Error> ); assert_eq!(outputs.2.len(), 14); - // mid range + // mid-range let ranges = client1.height_range_to_pmmr_indices(5, Some(14))?; assert_eq!(ranges, (8, 25)); let outputs = client1.get_outputs_by_pmmr_index(ranges.0, Some(ranges.1), 1000)?; @@ -1002,7 +792,8 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -1017,19 +808,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1076,18 +858,10 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } assert!(batches > 1); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let (_, info) = api.retrieve_summary_info(m, false, 1)?; - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - Ok(()) - }, - )?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, false, true, None)?; + let (_, info) = api1.retrieve_summary_info(mask1, false, 1)?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); @@ -1109,7 +883,8 @@ fn restore_corrupted_outputs_across_batches_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -1124,18 +899,9 @@ fn restore_corrupted_outputs_across_batches_impl( let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut output_commits = vec![]; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(info.total, bh * reward); - output_commits = api.retrieve_outputs(m, false, true, None)?.1; - Ok(()) - }, - )?; + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert_eq!(info.total, bh * reward); + let output_commits = api1.retrieve_outputs(mask1, false, true, None)?.1; { wallet_inst!(wallet1, w); @@ -1173,30 +939,22 @@ fn restore_corrupted_outputs_across_batches_impl( assert_eq!(last_scanned.hash, ""); } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, outputs_after_first_batch) = api.retrieve_outputs(m, false, false, None)?; - assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); + let (_, outputs_after_first_batch) = api1.retrieve_outputs(mask1, false, false, None)?; + assert_eq!(outputs_after_first_batch.len(), (bh - 1) as usize); - let (_, info) = api.retrieve_summary_info(m, true, 1)?; - let (_, restored_outputs) = api.retrieve_outputs(m, false, true, None)?; - let unique_keys = restored_outputs - .iter() - .map(|o| o.output.key_id.clone()) - .collect::>(); + let (_, info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (_, restored_outputs) = api1.retrieve_outputs(mask1, false, true, None)?; + let unique_keys = restored_outputs + .iter() + .map(|o| o.output.key_id.clone()) + .collect::>(); - assert_eq!(info.total, bh * reward); - assert_eq!(restored_outputs.len(), bh as usize); - assert_eq!(unique_keys.len(), bh as usize); - assert!(restored_outputs - .iter() - .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); - Ok(()) - }, - )?; + assert_eq!(info.total, bh * reward); + assert_eq!(restored_outputs.len(), bh as usize); + assert_eq!(unique_keys.len(), bh as usize); + assert!(restored_outputs + .iter() + .all(|o| o.output.status == libwallet::OutputStatus::Unspent)); stopper.store(false, Ordering::Relaxed); thread::sleep(Duration::from_millis(200)); diff --git a/controller/tests/common/mod.rs b/controller/tests/common/mod.rs index 725160e..716b79e 100644 --- a/controller/tests/common/mod.rs +++ b/controller/tests/common/mod.rs @@ -19,11 +19,15 @@ extern crate grin_wallet_libwallet as libwallet; use grin_core as core; use grin_keychain as keychain; use grin_util as util; +use std::env; +use std::path::PathBuf; use self::core::global; use self::core::global::ChainTypes; use self::keychain::ExtKeychain; use self::libwallet::WalletInst; +use grin_wallet_api::Owner; +use grin_wallet_config::{initial_setup_wallet, GRIN_WALLET_DIR}; use impls::test_framework::{LocalWalletClient, WalletProxy}; use impls::{DefaultLCProvider, DefaultWalletImpl}; use std::sync::Arc; @@ -41,9 +45,9 @@ macro_rules! wallet_inst { #[macro_export] macro_rules! create_wallet_and_add { - ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr) => { + ($client:ident, $wallet: ident, $mask: ident, $test_dir: expr, $name: expr, $seed_phrase: expr, $proxy: expr, $create_mask: expr, $owner_api: ident) => { let $client = LocalWalletClient::new($name, $proxy.tx.clone()); - let ($wallet, $mask) = common::create_local_wallet( + let ($wallet, $mask, $owner_api) = common::create_local_wallet( $test_dir, $name, $seed_phrase.clone(), @@ -125,7 +129,18 @@ pub fn create_local_wallet( >, >, Option, + Owner, LocalWalletClient, ExtKeychain>, ) { + let mut current_dir; + current_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + current_dir.push(test_dir); + current_dir.push(name); + let config = + initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(current_dir), true).unwrap(); + let mut wallet_config = config.clone().members.wallet; + let mut wallet = Box::new(DefaultWalletImpl::::new(client).unwrap()) as Box< dyn WalletInst< @@ -135,13 +150,25 @@ pub fn create_local_wallet( >, >; let lc = wallet.lc_provider().unwrap(); - let _ = lc.set_top_level_directory(&format!("{}/{}", test_dir, name)); + // legacy hack to avoid the need for changes in existing grin-wallet.toml files + // remove `wallet_data` from end of path as + // new lifecycle provider assumes grin_wallet.toml is in root of data directory + let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir); + if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) { + top_level_wallet_dir.pop(); + wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); + } + let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); lc.create_wallet(None, mnemonic, 32, ZeroingString::from(""), false) .unwrap(); let mask = lc .open_wallet(None, ZeroingString::from(""), create_mask, false) .unwrap(); - (Arc::new(Mutex::new(wallet)), mask) + + let wallet = Arc::new(Mutex::new(wallet)); + let owner_api = Owner::new(wallet.clone(), None, config.config_file_path.clone()); + + (wallet, mask, owner_api) } #[allow(dead_code)] diff --git a/controller/tests/config_api.rs b/controller/tests/config_api.rs index 5936a7f..6d1ac20 100644 --- a/controller/tests/config_api.rs +++ b/controller/tests/config_api.rs @@ -21,9 +21,9 @@ use config::config::{get_global_config, reload_global_config}; use config::GlobalWalletConfig; use impls::test_framework::LocalWalletClient; use libwallet::{InitTxArgs, InitTxSendArgs}; -use std::fs; use std::path::{Path, PathBuf}; use std::sync::atomic::Ordering; +use std::{env, fs}; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; @@ -63,7 +63,8 @@ fn tor_disable() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let path = PathBuf::from(test_dir).join("grin-wallet.toml"); let mut config = @@ -94,6 +95,7 @@ fn tor_disable() { ); assert_eq!(cached, stored); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -113,7 +115,8 @@ fn send_preflight() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); let owner = api::Owner::new( wallet.clone(), @@ -144,6 +147,7 @@ fn send_preflight() { assert!(after_txs.is_empty()); assert_eq!(snapshot(&wallet_data), before_data); + drop(_api); drop(owner); drop(wallet); drop(wallet_proxy); @@ -163,9 +167,13 @@ fn directory_change() { "wallet", None, &mut wallet_proxy, - false + false, + _api ); - let old_dir = PathBuf::from(test_dir).join("wallet"); + let old_dir = env::current_dir().unwrap_or_else(|e| { + panic!("Error creating config file: {}", e); + }); + let old_dir = old_dir.join(test_dir).join("wallet"); let old_config = old_dir.join("grin-wallet.toml"); let new_dir = PathBuf::from(test_dir).join("other"); let owner = api::Owner::new(wallet.clone(), None, old_config.clone()); diff --git a/controller/tests/file.rs b/controller/tests/file.rs index e313407..a4e1fc4 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -27,7 +27,7 @@ use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; -use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate}; +use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs}; #[macro_use] mod common; @@ -50,7 +50,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -61,7 +62,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -76,28 +78,12 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -122,32 +108,24 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }; // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; // Get some mining done { @@ -169,52 +147,28 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + let mut slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'wallet 2' account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -231,44 +185,27 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), ), }; - let mut slate = Slate::blank(2, true); + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = PathToSlate((&send_file).into()).get_tx()?.0; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = PathToSlate((&send_file).into()).get_tx()?.0; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?; - Ok(()) - }, - )?; wallet::controller::foreign_single_use( wallet2.clone(), PathBuf::from(test_dir), @@ -281,15 +218,8 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + + api1.post_tx(mask1, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -305,40 +235,22 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), format!("{}/standard_pp_S3.txbin", test_dir), ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, use_bin)?; + api1.tx_lock_outputs(mask1, &slate)?; wallet::controller::foreign_single_use( wallet2.clone(), @@ -352,21 +264,12 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - slate = PathToSlate(receive_file.into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + slate = PathToSlate(receive_file.into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/invoice.rs b/controller/tests/invoice.rs index b48f66e..8b76998 100644 --- a/controller/tests/invoice.rs +++ b/controller/tests/invoice.rs @@ -22,7 +22,7 @@ use grin_wallet_libwallet as libwallet; use std::path::PathBuf; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate, SlateState}; +use libwallet::{InitTxArgs, IssueInvoiceTxArgs, SlateState}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -46,7 +46,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - true + true, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -72,16 +74,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -93,46 +87,28 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, _bh as usize, false); // Sanity check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, _bh); - assert_eq!(wallet1_info.total, _bh * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, _bh); + assert_eq!(wallet1_info.total, _bh * reward); - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let error = api - .issue_invoice_tx( - m, - IssueInvoiceTxArgs { - amount: 0, - ..Default::default() - }, - ) - .unwrap_err(); - assert_eq!(error, libwallet::Error::InvalidAmount); - - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, + let error = api2 + .issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { + amount: 0, ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); + + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let receive_result = wallet::controller::foreign_single_use( @@ -142,16 +118,8 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { |api| api.receive_tx(&slate, None, None).map(|_| ()), ); assert_eq!(receive_result, Err(libwallet::Error::SlateState)); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, false, None, Some(slate.id), None)?; - assert!(txs.is_empty()); - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); // receive must reject every slate state except S1 for state in [ @@ -173,51 +141,34 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(res, Err(libwallet::Error::SlateState), "state {}", state); } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut zero_amount_slate = slate.clone(); - zero_amount_slate.amount = 0; - assert_eq!( - api.process_invoice_tx(m, &zero_amount_slate, args.clone()) - .unwrap_err(), - libwallet::Error::InvalidAmount - ); - - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut zero_amount_slate = slate.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api1.process_invoice_tx(mask1, &zero_amount_slate, args.clone()) + .unwrap_err(), + libwallet::Error::InvalidAmount + ); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - assert_eq!( - api.tx_lock_outputs(m, &slate), - Err(libwallet::Error::SlateState) - ); - let (_, txs) = api.retrieve_txs(m, false, None, None, None)?; - assert_eq!(txs.len(), 1); - assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); - Ok(()) - }, - )?; + assert_eq!( + api2.tx_lock_outputs(mask2, &slate), + Err(libwallet::Error::SlateState) + ); + let (_, txs) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); // wallet 2 finalizes and posts wallet::controller::foreign_single_use( @@ -233,86 +184,54 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { assert_eq!(slate.state, SlateState::Invoice3); // wallet 1 posts so wallet 2 doesn't get the mined amount - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; _bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert!(txs.len() == 1); - println!( - "last confirmed height: {}, bh: {}", - wallet2_info.last_confirmed_height, _bh - ); - assert!(refreshed); - Ok(()) - }, - )?; + let (_, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), 1); + println!( + "last confirmed height: {}, bh: {}", + wallet2_info.last_confirmed_height, _bh + ); + assert!(refreshed); // Check transaction log for wallet 1, ensure only 1 entry // exists - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len() as u64, _bh + 1); - println!( - "Wallet 1: last confirmed height: {}, bh: {}", - wallet1_info.last_confirmed_height, _bh - ); - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len() as u64, _bh + 1); + println!( + "Wallet 1: last confirmed height: {}, bh: {}", + wallet1_info.last_confirmed_height, _bh + ); // Test self-sending - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - println!("Self invoice slate init: {}", slate); - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api1.issue_invoice_tx(mask1, args)?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + println!("Self invoice slate init: {}", slate); + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; println!("Self invoice slate after process: {}", slate); @@ -329,112 +248,66 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { )?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); - //bh += 3; - // As above, but use owner API to finalize - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; assert_eq!(slate.state, SlateState::Invoice2); - // wallet 2 finalizes via owner API - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 receives the invoice transaction - slate = api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 2 receives and finalizes via owner API + slate = api2.finalize_tx(mask2, &slate)?; assert_eq!(slate.state, SlateState::Invoice3); // test that payee can only cancel once let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); _bh += 3; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward * 2, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward * 2, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; assert_eq!(slate.state, SlateState::Invoice1); let orig_slate = slate.clone(); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args.clone())?; - api.tx_lock_outputs(m, &slate)?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args.clone())?; + api1.tx_lock_outputs(mask1, &slate)?; - // Wallet 1 cancels the invoice transaction - api.cancel_tx(m, None, Some(slate.id))?; + // Wallet 1 cancels the invoice transaction + api1.cancel_tx(mask1, None, Some(slate.id))?; - // Wallet 1 attempts to repay again - let res = api.process_invoice_tx(m, &orig_slate, args); - assert!(res.is_err()); - - Ok(()) - }, - )?; + // Wallet 1 attempts to repay again + let res = api1.process_invoice_tx(mask1, &orig_slate, args); + assert!(res.is_err()); assert_eq!(slate.state, SlateState::Invoice2); // let logging finish diff --git a/controller/tests/late_lock.rs b/controller/tests/late_lock.rs index 2d1ec29..8783610 100644 --- a/controller/tests/late_lock.rs +++ b/controller/tests/late_lock.rs @@ -18,9 +18,8 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; extern crate grin_wallet_libwallet as libwallet; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -28,6 +27,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use libwallet::InitTxSendArgs; /// self send impl fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -46,7 +46,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -69,26 +71,8 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { }); // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - Ok(()) - }, - )?; - - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api2.create_account_path(mask2, "account1")?; // Get some mining done { @@ -102,70 +86,75 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; - let mut slate = Slate::blank(2, false); let amount = 100_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - late_lock: Some(true), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - println!("S1 SLATE: {}", slate_i); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - println!("S2 SLATE: {}", slate); + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + late_lock: Some(true), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + println!("S1 SLATE: {}", slate_i); + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + println!("S2 SLATE: {}", slate); - // Note we don't call `tx_lock_outputs` on the sender side here, - // as the outputs will only be locked during finalization + // Note we don't call `tx_lock_outputs` on the sender side here, + // as the outputs will only be locked during finalization - slate = sender_api.finalize_tx(m, &slate)?; - println!("S3 SLATE: {}", slate); + slate = api1.finalize_tx(mask1, &slate)?; + println!("S3 SLATE: {}", slate); - // Now post tx to our node for inclusion in the next block. - sender_api.post_tx(m, &slate, true)?; - - Ok(()) - }, - )?; + // Now post tx to our node for inclusion in the next block. + api1.post_tx(mask1, &slate, true)?; test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false)?; // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - // Reward from mining 11 blocks, minus the amount sent. - // Note: We mined the block containing the tx, so fees are effectively refunded. - assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + // Reward from mining 11 blocks, minus the amount sent. + // Note: We mined the block containing the tx, so fees are effectively refunded. + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(amount, wallet_info.amount_currently_spendable); - Ok(()) - }, - )?; + // Make sure outputs are not locked on failed send with arguments. + // Fail sending without starting Tor + api1.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + late_lock: Some(true), + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert!(txs.is_empty()); + // Make sure spendable balance not changed. + let (wallet1_refreshed, wallet_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(560_000_000_000, wallet_info.amount_currently_spendable); + + let (wallet2_refreshed, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(amount, wallet_info.amount_currently_spendable); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 60e4bd8..5ae886b 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -50,7 +50,8 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -65,16 +66,8 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -86,123 +79,84 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( wallet1.clone(), - mask1, PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use( - wallet1.clone(), - PathBuf::from(test_dir), - mask1_i.clone(), - |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; - Ok(()) - }, - )?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // Recipient wallet creates a mwixnet request from the last output - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let secp_locked = util::static_secp_instance(); - let secp = secp_locked.lock(); - let server_pubkey_str_1 = - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; - let server_pubkey_str_2 = - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; - let server_pubkey_str_3 = - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; - let server_key_1 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap()) - .unwrap(); - let server_key_2 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap()) - .unwrap(); - let server_key_3 = - SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap()) - .unwrap(); - let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, - }; - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); + let secp_locked = util::static_secp_instance(); + let secp = secp_locked.lock(); + let server_pubkey_str_1 = "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332"; + let server_pubkey_str_2 = "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e"; + let server_pubkey_str_3 = "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"; + let server_key_1 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap())?; + let server_key_2 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap())?; + let server_key_3 = + SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap())?; + let params = MixnetReqCreationParams { + server_keys: vec![server_key_1, server_key_2, server_key_3], + fee_per_hop: 50_000_000, + }; + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api.create_mwixnet_req(m, ¶ms, &last_output.commit, true)?; + let mwixnet_req = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; - println!("MWIXNET REQ: {:?}", mwixnet_req); + println!("MWIXNET REQ: {:?}", mwixnet_req); - // check output we created comsig for is indeed locked - let outputs = api.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert!(last_output.output.status == libwallet::OutputStatus::Locked); - - Ok(()) - }, - )?; + // check output we created comsig for is indeed locked + let outputs = api1.retrieve_outputs(mask1, false, false, None)?; + // get last output + let last_output = outputs.1[outputs.1.len() - 1].clone(); + assert_eq!(last_output.output.status, libwallet::OutputStatus::Locked); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/no_change.rs b/controller/tests/no_change.rs index aa1a56e..503691e 100644 --- a/controller/tests/no_change.rs +++ b/controller/tests/no_change.rs @@ -22,7 +22,7 @@ use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate}; +use libwallet::{InitTxArgs, IssueInvoiceTxArgs}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -44,7 +44,8 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -57,7 +58,8 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -77,109 +79,67 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let fee = core::libtx::tx_fee(1, 1, 1); // send a single block's worth of transactions with minimal strategy - let mut slate = Slate::blank(2, false); - let mut stored_excess = None; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: reward - fee, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate)?; - api.tx_lock_outputs(m, &slate)?; - slate = api.finalize_tx(m, &slate)?; - println!("Posted Slate: {:?}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: None, + amount: reward - fee, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + println!("Posted Slate: {:?}", slate); + let mut stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api1.post_tx(mask1, &slate, false)?; // ensure stored excess is correct in both wallets // Wallet 1 calculated the excess with the full slate // Wallet 2 only had the excess provided by // wallet 1 // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - SENDING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - }, - )?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - SENDING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); // Refresh and check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - let tx = txs[0].clone(); - println!("SIMPLE SEND - RECEIVING WALLET"); - println!("{:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - Ok(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + assert!(refreshed); + let tx = txs[0].clone(); + println!("SIMPLE SEND - RECEIVING WALLET"); + println!("{:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); // ensure invoice TX works as well with no change - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - // Wallet 2 inititates an invoice transaction, requesting payment - let args = IssueInvoiceTxArgs { - amount: reward - fee, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - Ok(()) - }, - )?; + // Wallet 2 initiates an invoice transaction, requesting payment + let args = IssueInvoiceTxArgs { + amount: reward - fee, + ..Default::default() + }; + slate = api2.issue_invoice_tx(mask2, args)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // Wallet 1 receives the invoice transaction - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + // Wallet 1 receives the invoice transaction + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; // wallet 2 finalizes and posts wallet::controller::foreign_single_use( @@ -192,54 +152,30 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - println!("Invoice Posted TX: {}", slate); - stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + println!("Invoice Posted TX: {}", slate); + stored_excess = Some(slate.tx.as_ref().unwrap().body.kernels[0].excess); + api2.post_tx(mask2, &slate, false)?; // check wallet 2's version - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - stored_excess = tx.kernel_excess; - println!("Wallet 2: {:?}", tx); - println!(); - assert!(tx.confirmed); - assert_eq!(stored_excess, tx.kernel_excess); - } - Ok(()) - }, - )?; + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + stored_excess = tx.kernel_excess; + println!("Wallet 2: {:?}", tx); + println!(); + assert!(tx.confirmed); + assert_eq!(stored_excess, tx.kernel_excess); + } // Refresh and check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(refreshed); - for tx in txs { - println!("Wallet 1: {:?}", tx); - println!(); - assert_eq!(stored_excess, tx.kernel_excess); - assert!(tx.confirmed); - } - Ok(()) - }, - )?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(refreshed); + for tx in txs { + println!("Wallet 1: {:?}", tx); + println!(); + assert_eq!(stored_excess, tx.kernel_excess); + assert!(tx.confirmed); + } // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index 651e486..5c4eeaf 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -21,7 +21,6 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; use libwallet::{InitTxArgs, Slate}; -use std::path::PathBuf; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -45,7 +44,8 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -58,7 +58,8 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -77,99 +78,74 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); println!("Public address is: {:?}", address); let amount = 60_000_000_000; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - assert_eq!( - slate_i.payment_proof.as_ref().unwrap().receiver_address, - address.as_ref().unwrap().pub_key, - ); - println!( - "Sender addr: {:?}", - slate_i.payment_proof.as_ref().unwrap().sender_address - ); + assert_eq!( + slate_i.payment_proof.as_ref().unwrap().receiver_address, + address.as_ref().unwrap().pub_key, + ); + println!( + "Sender addr: {:?}", + slate_i.payment_proof.as_ref().unwrap().sender_address + ); - // Check we are creating a tx with kernel features 0 - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); + // Check we are creating a tx with kernel features 0 + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; - // Ensure what's stored in TX log for payment proof is correct - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - assert!(txs[0].payment_proof.is_some()); - let pp = txs[0].clone().payment_proof.unwrap(); - assert_eq!( - pp.receiver_address, - slate_i.payment_proof.as_ref().unwrap().receiver_address - ); - assert!(pp.receiver_signature.is_some()); - assert_eq!(pp.sender_address_path, 0); - assert_eq!(pp.sender_signature, None); + // Ensure what's stored in TX log for payment proof is correct + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + assert!(txs[0].payment_proof.is_some()); + let pp = txs[0].clone().payment_proof.unwrap(); + assert_eq!( + pp.receiver_address, + slate_i.payment_proof.as_ref().unwrap().receiver_address + ); + assert!(pp.receiver_signature.is_some()); + assert_eq!(pp.sender_address_path, 0); + assert_eq!(pp.sender_signature, None); - // check we should get an error at this point since proof is not complete - let pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id)); - assert!(pp.is_err()); + // check we should get an error at this point since proof is not complete + let pp = api1.retrieve_payment_proof(mask1, true, None, Some(slate.id)); + assert!(pp.is_err()); - slate = sender_api.finalize_tx(m, &slate)?; - sender_api.post_tx(m, &slate, true)?; - Ok(()) - }, - )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, true)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // Check payment proof here - let mut pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id))?; + // Check payment proof here + let mut pp = api1.retrieve_payment_proof(mask1, true, None, Some(slate.id))?; - println!("Payment proof: {:?}", pp); + println!("Payment proof: {:?}", pp); - // verify, should be good - let res = sender_api.verify_payment_proof(m, &pp)?; - assert_eq!(res, (true, false)); + // verify, should be good + let res = api1.verify_payment_proof(mask1, &pp)?; + assert_eq!(res, (true, false)); - // Modify values, should not be good - pp.amount = 20; - let res = sender_api.verify_payment_proof(m, &pp); - assert!(res.is_err()); - Ok(()) - }, - )?; + // Modify values, should not be good + pp.amount = 20; + let res = api1.verify_payment_proof(mask1, &pp); + assert!(res.is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/repost.rs b/controller/tests/repost.rs index 0718364..7f3a39b 100644 --- a/controller/tests/repost.rs +++ b/controller/tests/repost.rs @@ -21,7 +21,7 @@ extern crate grin_wallet_libwallet as libwallet; use grin_core as core; use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; use impls::{PathToSlate, SlateGetter as _, SlatePutter as _}; use std::sync::atomic::Ordering; @@ -49,7 +49,8 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -60,7 +61,8 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -75,28 +77,11 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -110,34 +95,24 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let send_file = format!("{}/part_tx_1.tx", test_dir); let receive_file = format!("{}/part_tx_2.tx", test_dir); - let mut slate = Slate::blank(2, false); - // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - PathToSlate((&send_file).into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + PathToSlate((&send_file).into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; @@ -167,69 +142,37 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } // wallet 1 finalize - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - slate = PathToSlate((&receive_file).into()).get_tx()?.0; - slate = api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + slate = PathToSlate((&receive_file).into()).get_tx()?.0; + slate = api1.finalize_tx(mask1, &slate)?; // Now repost from cached - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - println!("TXS[0]: {:?}", txs[0]); - let stored_tx = api.get_stored_tx(m, None, Some(&txs[0].tx_slate_id.unwrap()))?; - println!("Stored tx: {:?}", stored_tx); - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + println!("TXS[0]: {:?}", txs[0]); + let stored_tx = api1.get_stored_tx(mask1, None, Some(&txs[0].tx_slate_id.unwrap()))?; + println!("Stored tx: {:?}", stored_tx); + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); - // as above, but syncronously + // as above, but synchronously { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("mining")?; @@ -239,78 +182,45 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> w.set_parent_key_id_by_name("account1")?; } - let mut slate = Slate::blank(2, false); let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Now repost from cached - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let stored_tx_slate = api.get_stored_tx(m, Some(txs[0].id), None)?.unwrap(); - api.post_tx(m, &stored_tx_slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let stored_tx_slate = api1.get_stored_tx(mask1, Some(txs[0].id), None)?.unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; - // - // update/test contents of both accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 4); - Ok(()) - }, - )?; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * amount); - Ok(()) - }, - )?; + // update/test contents of both accounts + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 4); + + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * amount); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/revert.rs b/controller/tests/revert.rs index ef5a887..6c4c8a6 100644 --- a/controller/tests/revert.rs +++ b/controller/tests/revert.rs @@ -24,14 +24,13 @@ use grin_core::global; use grin_keychain::ExtKeychain; use grin_util::secp::key::SecretKey; use grin_util::Mutex; -use grin_wallet_controller::controller::owner_single_use as owner; +use grin_wallet_api::Owner; use grin_wallet_impls::test_framework::*; use grin_wallet_impls::{DefaultLCProvider, PathToSlate, SlatePutter}; use grin_wallet_libwallet as libwallet; use grin_wallet_libwallet::api_impl::types::InitTxArgs; use grin_wallet_libwallet::WalletInst; use log::error; -use std::path::PathBuf; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; @@ -63,6 +62,8 @@ fn revert( Option, Wallet, Option, + Owner, LocalWalletClient, ExtKeychain>, + Owner, LocalWalletClient, ExtKeychain>, ), libwallet::Error, > { @@ -82,7 +83,8 @@ fn revert( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = mask1_i.as_ref(); @@ -94,28 +96,23 @@ fn revert( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = mask2_i.as_ref(); // Set the wallet proxy listener running - std::thread::spawn(move || { + thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "a")?; - api.set_active_account(m, "a")?; - Ok(()) - })?; + api1.create_account_path(mask1, "a")?; + api1.set_active_account(mask1, "a")?; - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - api.create_account_path(m, "b")?; - api.set_active_account(m, "b")?; - Ok(()) - })?; + api2.create_account_path(mask2, "b")?; + api2.set_active_account(mask2, "b")?; let reward = core::consensus::REWARD; let cm = global::coinbase_maturity() as u64; @@ -126,76 +123,60 @@ fn revert( award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false)?; // Sanity check contents - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, bh * reward); - assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); - assert_eq!(info.total, c); - assert_eq!(txs.len(), bh as usize); - Ok(()) - })?; + let (refreshed, info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, bh * reward); + assert_eq!(info.amount_currently_spendable, (bh - cm) * reward); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let (c, _) = libwallet::TxLogEntry::sum_confirmed(&txs); + assert_eq!(info.total, c); + assert_eq!(txs.len(), bh as usize); - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 0); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 0); // Send some funds - let mut tx = None; - owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: None, - amount: sent, - minimum_confirmations: cm, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - let send_file = format!("{}/part_tx_1.tx", test_dir); - PathToSlate(send_file.into()).put_tx(&slate, false)?; - api.tx_lock_outputs(m, &slate)?; - let slate = client1.send_tx_slate_direct("wallet2", &slate)?; - let slate = api.finalize_tx(m, &slate)?; - tx = slate.tx; - - Ok(()) - })?; - let tx = tx.expect("tx from slate"); + // send to send + let args = InitTxArgs { + src_acct_name: None, + amount: sent, + minimum_confirmations: cm, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + let send_file = format!("{}/part_tx_1.tx", test_dir); + PathToSlate(send_file.into()).put_tx(&slate, false)?; + api1.tx_lock_outputs(mask1, &slate)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate)?; + let slate = api1.finalize_tx(mask1, &slate)?; + let tx = slate.tx.expect("tx from slate"); // Check funds have been received - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(!tx.confirmed); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(!&txs[0].confirmed); // Update parallel chain assert_eq!(chain2.head_header().unwrap().height, 0); @@ -223,23 +204,19 @@ fn revert( let bh = bh + 1; // Check funds have been confirmed - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.kernel_excess.is_some()); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(&txs[0].confirmed); + assert!(&txs[0].kernel_excess.is_some()); + assert!(&txs[0].reverted_after.is_none()); // Attach more blocks to the parallel chain, making it the longest one award_block_to_wallet(&chain2, &[], wallet1.clone(), mask1)?; @@ -258,32 +235,29 @@ fn revert( let bh = bh + 1; // Check funds have been reverted - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - api.scan(m, None, false)?; - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReverted); - assert!(!tx.confirmed); - assert!(tx.reverted_after.is_some()); - Ok(()) - })?; + api2.scan(mask2, None, false)?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReverted); + assert!(!&txs[0].confirmed); + assert!(&txs[0].reverted_after.is_some()); stopper2.store(false, Ordering::Relaxed); Ok(( - chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, + chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i, api1, api2, )) } fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (chain, stopper, sent, bh, tx, wallet1, mask1_i, wallet2, mask2_i) = revert(test_dir)?; + let (chain, stopper, sent, bh, tx, wallet1, mask1_i, _wallet2, mask2_i, _api1, api2) = + revert(test_dir)?; let mask1 = mask1_i.as_ref(); let mask2 = mask2_i.as_ref(); @@ -293,22 +267,19 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> let bh = bh + 1; // Check funds have been confirmed again - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, sent); - assert_eq!(info.amount_currently_spendable, sent); - assert_eq!(info.amount_reverted, 0); - // check tx log as well - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); - assert!(tx.confirmed); - assert!(tx.reverted_after.is_none()); - Ok(()) - })?; + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, sent); + assert_eq!(info.amount_currently_spendable, sent); + assert_eq!(info.amount_reverted, 0); + // check tx log as well + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceived); + assert!(tx.confirmed); + assert!(tx.reverted_after.is_none()); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -317,41 +288,37 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error> } fn revert_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { - let (_, stopper, sent, bh, _, _, _, wallet2, mask2_i) = revert(test_dir)?; + let (_, stopper, sent, bh, _, _, _, _wallet2, mask2_i, _api1, api2) = revert(test_dir)?; let mask2 = mask2_i.as_ref(); - // Cancelling tx - owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| { - // Sanity check - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, sent); + // Sanity check + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, sent); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; - // Cancel - api.cancel_tx(m, Some(tx.id), None)?; + // Cancel + api2.cancel_tx(mask2, Some(tx.id), None)?; - // Check updated summary info - let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(info.last_confirmed_height, bh); - assert_eq!(info.total, 0); - assert_eq!(info.amount_currently_spendable, 0); - assert_eq!(info.amount_reverted, 0); + // Check updated summary info + let (refreshed, info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(info.last_confirmed_height, bh); + assert_eq!(info.total, 0); + assert_eq!(info.amount_currently_spendable, 0); + assert_eq!(info.amount_reverted, 0); - // Check updated tx log - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert_eq!(txs.len(), 1); - let tx = &txs[0]; - assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); - Ok(()) - })?; + // Check updated tx log + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert_eq!(txs.len(), 1); + let tx = &txs[0]; + assert_eq!(tx.tx_type, libwallet::TxLogEntryType::TxReceivedCancelled); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index 6cf572e..c6ca437 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -48,7 +48,8 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -63,16 +64,8 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; // Get some mining done { @@ -84,78 +77,54 @@ fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); // Should have 5 in account1 (5 spendable), 5 in account (2 spendable) - wallet::controller::owner_single_use( + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + // Send directly to self + wallet::controller::foreign_single_use( wallet1.clone(), - mask1, PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let mut slate = api.init_send_tx(m, args)?; - api.tx_lock_outputs(m, &slate)?; - // Send directly to self - wallet::controller::foreign_single_use( - wallet1.clone(), - PathBuf::from(test_dir), - mask1_i.clone(), - |api| { - slate = api.receive_tx(&slate, Some("listener"), None)?; - Ok(()) - }, - )?; - slate = api.finalize_tx(m, &slate)?; - api.post_tx(m, &slate, false)?; // mines a block - bh += 1; + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, Some("listener"), None)?; Ok(()) }, )?; + slate = api1.finalize_tx(mask1, &slate)?; + api1.post_tx(mask1, &slate, false)?; // mines a block + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'listener' account { wallet_inst!(wallet1, w); w.set_parent_key_id_by_name("listener")?; } - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, 2 * reward); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index 9bdd740..d53f1c4 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -100,7 +100,8 @@ fn slatepack_exchange_test_impl( "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -111,7 +112,8 @@ fn slatepack_exchange_test_impl( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -126,28 +128,11 @@ fn slatepack_exchange_test_impl( let reward = core::consensus::REWARD; // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { @@ -160,19 +145,9 @@ fn slatepack_exchange_test_impl( let (recipients_1, dec_key_1, sender_1) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - }, - )?; + let sec_key = api1.get_slatepack_secret_key(mask1, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); ( vec![rec_address.clone()], Some(sec_key), @@ -184,19 +159,9 @@ fn slatepack_exchange_test_impl( let (recipients_2, dec_key_2, sender_2) = match use_encryption { true => { - let mut rec_address = SlatepackAddress::random(); - let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]); - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - sec_key = api.get_slatepack_secret_key(m, 0)?; - let pub_key = edDalekPublicKey::from(&sec_key); - rec_address = SlatepackAddress::new(&pub_key); - Ok(()) - }, - )?; + let sec_key = api2.get_slatepack_secret_key(mask2, 0)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let rec_address = SlatepackAddress::new(&pub_key); ( vec![rec_address.clone()], Some(sec_key), @@ -219,39 +184,31 @@ fn slatepack_exchange_test_impl( ), }; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward); - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // output tx file - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1.clone(), - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward); + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // output tx file + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1.clone(), + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; // Get some mining done { @@ -286,52 +243,27 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, mut slate) = - slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + let (_, mut slate) = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api1.post_tx(mask1, &slate, false)?; + bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; // Check total in mining account - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet1_refreshed); - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.total, bh * reward - reward * 2); - Ok(()) - }, - )?; + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(wallet1_refreshed); + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.total, bh * reward - reward * 2); // Check total in 'wallet 2' account - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.last_confirmed_height, bh); - assert_eq!(wallet2_info.total, 2 * reward); - Ok(()) - }, - )?; + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.last_confirmed_height, bh); + assert_eq!(wallet2_info.total, 2 * reward); // Now other types of exchange, for reference // Invoice transaction @@ -348,61 +280,43 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = IssueInvoiceTxArgs { - amount: 1000000000, - ..Default::default() - }; - slate = api.issue_invoice_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_2.clone(), - recipients_1.clone(), - )?; - Ok(()) - }, + let args = IssueInvoiceTxArgs { + amount: 1000000000, + ..Default::default() + }; + let mut slate = api2.issue_invoice_tx(mask2, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_2.clone(), + recipients_1.clone(), )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; - slatepack = res.0; - slate = res.1; - slate = api.process_invoice_tx(m, &slate, args)?; - api.tx_lock_outputs(m, &slate)?; - output_slatepack( - &slate, - &receive_file, - use_armored, - use_bin, - sender_1.clone(), - match slatepack.sender.clone() { - Some(s) => vec![s.clone()], - None => vec![], - }, - )?; - Ok(()) + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = slate_from_packed(&send_file, use_armored, (&dec_key_1).as_ref())?; + slatepack = res.0; + slate = res.1; + slate = api1.process_invoice_tx(mask1, &slate, args)?; + api1.tx_lock_outputs(mask1, &slate)?; + output_slatepack( + &slate, + &receive_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender.clone() { + Some(s) => vec![s.clone()], + None => vec![], }, )?; wallet::controller::foreign_single_use( @@ -418,15 +332,7 @@ fn slatepack_exchange_test_impl( Ok(()) }, )?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -443,47 +349,29 @@ fn slatepack_exchange_test_impl( ), }; - let mut slate = Slate::blank(2, true); - let mut address = None; - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - address = Some(api.get_slatepack_address(m, 0)?); - Ok(()) - }, - )?; + let address = Some(api2.get_slatepack_address(mask2, 0)?); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // send to send - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - output_slatepack( - &slate, - &send_file, - use_armored, - use_bin, - sender_1, - recipients_2.clone(), - )?; - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, + // send to send + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + payment_proof_recipient_address: address.clone(), + ..Default::default() + }; + let mut slate = api1.init_send_tx(mask1, args)?; + output_slatepack( + &slate, + &send_file, + use_armored, + use_bin, + sender_1, + recipients_2.clone(), )?; + api1.tx_lock_outputs(mask1, &slate)?; wallet::controller::foreign_single_use( wallet2.clone(), @@ -509,22 +397,13 @@ fn slatepack_exchange_test_impl( }, )?; - // wallet 1 finalises and posts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; - slate = res.1; - slate = api.finalize_tx(m, &slate)?; - // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - api.post_tx(m, &slate, false)?; - bh += 1; - Ok(()) - }, - )?; + // wallet 1 finalizes and posts + let res = slate_from_packed(&receive_file, use_armored, (&dec_key_1).as_ref())?; + slate = res.1; + slate = api1.finalize_tx(mask1, &slate)?; + // Output final file for reference + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api1.post_tx(mask1, &slate, false)?; // let logging finish stopper.store(false, Ordering::Relaxed); @@ -550,7 +429,8 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -569,32 +449,24 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), - amount: reward * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate = api.init_send_tx(m, args)?; - // create an encrypted slatepack (just encrypted for self) - let enc_addr = api.get_slatepack_address(m, 0)?; - let slatepack = api.create_slatepack_message(m, &slate, Some(0), vec![enc_addr])?; - println!("{}", slatepack); - let slatepack_raw = api.decode_slatepack_message(m, slatepack.clone(), vec![0])?; - println!("{}", slatepack_raw); - let decoded_slate = api.slate_from_slatepack_message(m, slatepack, vec![0])?; - println!("{}", decoded_slate); - Ok(()) - }, - )?; + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate = api1.init_send_tx(mask1, args)?; + // create an encrypted slatepack (just encrypted for self) + let enc_addr = api1.get_slatepack_address(mask1, 0)?; + let slatepack = api1.create_slatepack_message(mask1, &slate, Some(0), vec![enc_addr])?; + println!("{}", slatepack); + let slatepack_raw = api1.decode_slatepack_message(mask1, slatepack.clone(), vec![0])?; + println!("{}", slatepack_raw); + let decoded_slate = api1.slate_from_slatepack_message(mask1, slatepack, vec![0])?; + println!("{}", decoded_slate); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -609,8 +481,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let stopper = wallet_proxy.running.clone(); let config_path = PathBuf::from(test_dir).join("grin-wallet.toml"); GlobalWalletConfig::for_chain(&core::global::ChainTypes::AutomatedTesting, &config_path) - .write_to_file(config_path.to_str().unwrap(), false, None, None) - .unwrap(); + .write_to_file(config_path.to_str().unwrap(), false, None, None)?; create_wallet_and_add!( client1, @@ -620,7 +491,8 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -632,7 +504,8 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -644,62 +517,57 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: let reward = core::consensus::REWARD; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 6, false); - let mut slate = Slate::blank(2, true); - - wallet::controller::owner_single_use(wallet2.clone(), mask2, config_path.clone(), |api, m| { - slate = api.issue_invoice_tx( - m, - IssueInvoiceTxArgs { - amount: reward, - ..Default::default() - }, - )?; - Ok(()) - })?; - - wallet::controller::owner_single_use(wallet1.clone(), mask1, config_path, |api, m| { - let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), + let slate = api2.issue_invoice_tx( + mask2, + IssueInvoiceTxArgs { amount: reward, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, ..Default::default() - }; + }, + )?; - let mut wrong_net_args = args.clone(); - wrong_net_args.send_args = Some(InitTxSendArgs { - dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, wrong_net_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, wrong_net_args).is_err()); + let args = InitTxArgs { + src_acct_name: Some("mining".to_owned()), + amount: reward, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let mut invalid_args = args.clone(); - invalid_args.send_args = Some(InitTxSendArgs { - dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7" - .to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - assert!(api.init_send_tx(m, invalid_args.clone()).is_err()); - assert!(api.process_invoice_tx(m, &slate, invalid_args).is_err()); + let mut wrong_net_args = args.clone(); + wrong_net_args.send_args = Some(InitTxSendArgs { + dest: "grin1dvge9z4uqgqlpspmljrd7smh3grrw9xu2r9lkz3u67s3emj3ud2sd5gk9p".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, wrong_net_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, wrong_net_args) + .is_err()); - let mut valid_args = args; - valid_args.send_args = Some(InitTxSendArgs { - dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), - post_tx: false, - fluff: false, - skip_tor: Some(true), - }); - api.process_invoice_tx(m, &slate, valid_args.clone())?; - api.init_send_tx(m, valid_args)?; - Ok(()) - })?; + let mut invalid_args = args.clone(); + invalid_args.send_args = Some(InitTxSendArgs { + dest: "tgrinaddr10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqnlumr7".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + assert!(api1.init_send_tx(mask1, invalid_args.clone()).is_err()); + assert!(api1 + .process_invoice_tx(mask1, &slate, invalid_args) + .is_err()); + + let mut valid_args = args; + valid_args.send_args = Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".to_string(), + post_tx: false, + fluff: false, + skip_tor: Some(true), + }); + api1.process_invoice_tx(mask1, &slate, valid_args.clone())?; + api1.init_send_tx(mask1, valid_args)?; stopper.store(false, Ordering::Relaxed); proxy_thread.join().expect("wallet proxy thread panicked"); @@ -710,7 +578,7 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: fn slatepack_exchange_json() { let test_dir = "test_output/slatepack_exchange_json"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, false) { panic!("Libwallet Error: {}", e); } @@ -743,7 +611,7 @@ fn slatepack_exchange_armored() { fn slatepack_exchange_json_enc() { let test_dir = "test_output/slatepack_exchange_json_enc"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_exchange_test_impl(test_dir, false, false, true) { panic!("Libwallet Error: {}", e); } @@ -776,7 +644,7 @@ fn slatepack_exchange_armored_enc() { fn slatepack_api() { let test_dir = "test_output/slatepack_api"; setup(test_dir); - // Json output + // JSON output if let Err(e) = slatepack_api_impl(test_dir) { panic!("Libwallet Error: {}", e); } diff --git a/controller/tests/transaction.rs b/controller/tests/transaction.rs index 107c17d..6613095 100644 --- a/controller/tests/transaction.rs +++ b/controller/tests/transaction.rs @@ -33,6 +33,8 @@ use std::time::Duration; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; +use libwallet::InitTxSendArgs; /// Exercises the Transaction API fully with a test NodeClient operating /// directly on a chain instance @@ -51,7 +53,8 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); println!("Mask1: {:?}", mask1); @@ -63,7 +66,8 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); println!("Mask2: {:?}", mask2); @@ -81,459 +85,425 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error> // mine a few blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); - // Check wallet 1 contents are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - assert_eq!(wallet1_info.amount_immature, cm * reward); - Ok(()) - }, - )?; + // Check wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + assert_eq!(wallet1_info.amount_immature, cm * reward); + } // assert wallet contents // and a single use api for a send command let amount = 60_000_000_000; let header_version = core::consensus::header_version(chain.head().unwrap().height).0; let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // Do not allow to send 0 - let error = sender_api - .init_send_tx( - m, - InitTxArgs { - amount: 0, - ..Default::default() - }, - ) - .unwrap_err(); - assert_eq!(error, libwallet::Error::InvalidAmount); + { + // Do not allow to send 0 + let error = api1 + .init_send_tx( + mask1, + InitTxArgs { + amount: 0, + ..Default::default() + }, + ) + .unwrap_err(); + assert_eq!(error, libwallet::Error::InvalidAmount); - // Result amount can not be 0 when amount includes fee - let mut init_args = InitTxArgs { - amount_includes_fee: Some(true), - amount: 23_000_000, - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args.clone())?; - assert_eq!(init_args.amount, est.fee_fields.fee()); + // Result amount can not be 0 when amount includes fee + let mut init_args = InitTxArgs { + amount_includes_fee: Some(true), + amount: 23_000_000, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args.clone())?; + assert_eq!(init_args.amount, est.fee_fields.fee()); - init_args.estimate_only = None; - let error = sender_api.init_send_tx(m, init_args).unwrap_err(); - assert_eq!( - error, - libwallet::Error::GenericError( - "Transaction amount is too small to include fee".to_string() - ) - ); + init_args.estimate_only = None; + let error = api1.init_send_tx(mask1, init_args).unwrap_err(); + assert_eq!( + error, + libwallet::Error::GenericError( + "Transaction amount is too small to include fee".to_string() + ) + ); - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); - assert_eq!(slate_i.version_info.block_header_version, header_version); + assert_eq!(slate_i.state, SlateState::Standard1); + assert_eq!(slate_i.version_info.block_header_version, header_version); - wallet::controller::foreign_single_use( + wallet::controller::foreign_single_use( + wallet2.clone(), + PathBuf::from(test_dir), + mask2_i.clone(), + |api| { + let mut zero_amount_slate = slate_i.clone(); + zero_amount_slate.amount = 0; + assert_eq!( + api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), + libwallet::Error::InvalidAmount + ); + Ok(()) + }, + )?; + + // Check we are creating a tx with the expected lock_height of 0. + // We will check this produces a Plain kernel later. + assert_eq!(0, slate.kernel_features); + + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + assert_eq!(slate.state, SlateState::Standard2); + + // wallet2 already has this slate, so accepted versions fail on the duplicate check + for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { + let mut s = slate_i.clone(); + s.version_info.block_header_version = bhv; + let res = wallet::controller::foreign_single_use( wallet2.clone(), PathBuf::from(test_dir), mask2_i.clone(), - |api| { - let mut zero_amount_slate = slate_i.clone(); - zero_amount_slate.amount = 0; - assert_eq!( - api.receive_tx(&zero_amount_slate, None, None).unwrap_err(), - libwallet::Error::InvalidAmount - ); - Ok(()) - }, - )?; - - // Check we are creating a tx with the expected lock_height of 0. - // We will check this produces a Plain kernel later. - assert_eq!(0, slate.kernel_features); - - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - assert_eq!(slate.state, SlateState::Standard2); - - // wallet2 already has this slate, so accepted versions fail on the duplicate check - for bhv in 1..=GRIN_BLOCK_HEADER_VERSION + 1 { - let mut s = slate_i.clone(); - s.version_info.block_header_version = bhv; - let res = wallet::controller::foreign_single_use( - wallet2.clone(), - PathBuf::from(test_dir), - mask2_i.clone(), - |api| api.receive_tx(&s, None, None).map(|_| ()), - ); - if bhv <= GRIN_BLOCK_HEADER_VERSION { - assert!(matches!( - res, - Err(libwallet::Error::TransactionAlreadyReceived(_)) - )); - } else { - assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); - } - } - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - assert_eq!(slate.state, SlateState::Standard3); - - // Check we have a single kernel and that it is a Plain kernel (no lock_height). - // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) - assert_eq!(slate.tx_or_err()?.kernels().len(), 1); - assert_eq!( - slate - .tx_or_err()? - .kernels() - .first() - .map(|k| k.features) - .unwrap(), - transaction::KernelFeatures::Plain { - fee: 26_000_000.into() - } + |api| api.receive_tx(&s, None, None).map(|_| ()), ); + if bhv <= GRIN_BLOCK_HEADER_VERSION { + assert!(matches!( + res, + Err(libwallet::Error::TransactionAlreadyReceived(_)) + )); + } else { + assert!(matches!(res, Err(libwallet::Error::Compatibility(_)))); + } + } + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; + assert_eq!(slate.state, SlateState::Standard3); - Ok(()) - }, - )?; + // Check we have a single kernel and that it is a Plain kernel (no lock_height). + // fees for 7 inputs, 2 outputs, 1 kernel (weight 52) + assert_eq!(slate.tx_or_err()?.kernels().len(), 1); + assert_eq!( + slate + .tx_or_err()? + .kernels() + .first() + .map(|k| k.features) + .unwrap(), + transaction::KernelFeatures::Plain { + fee: 26_000_000.into() + } + ); + } // Check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - cm as usize, - 2, - 1, - ); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); - println!("tx: {:?}", tx); - assert_eq!(Some(fee.try_into().unwrap()), tx.fee); - Ok(()) - }, - )?; + { + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - cm as usize, + 2, + 1, + ); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(tx.amount_debited - tx.amount_credited, fee + amount); + println!("tx: {:?}", tx); + assert_eq!(Some(fee.try_into().unwrap()), tx.fee); + } // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(!tx.confirmed); - assert!(tx.confirmation_ts.is_none()); - assert_eq!(amount, tx.amount_credited); - assert_eq!(0, tx.amount_debited); - assert_eq!(None, tx.fee); - Ok(()) - }, - )?; + { + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(!tx.confirmed); + assert!(tx.confirmation_ts.is_none()); + assert_eq!(amount, tx.amount_credited); + assert_eq!(0, tx.amount_debited); + assert_eq!(None, tx.fee); + } // post transaction - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.post_tx(m, &slate, false)?; - Ok(()) - }, - )?; + api1.post_tx(mask1, &slate, false)?; - // Check wallet 1 contents are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 Info Post Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - let fee = core::libtx::tx_fee( - wallet1_info.last_confirmed_height as usize - 1 - cm as usize, - 2, - 1, - ); - assert!(wallet1_refreshed); - // wallet 1 received fees, so amount should be the same - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - amount - fee - ); - assert_eq!(wallet1_info.amount_immature, cm * reward + fee); + // Check wallet1 contents are as expected + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 Info Post Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + let fee = core::libtx::tx_fee( + wallet1_info.last_confirmed_height as usize - 1 - cm as usize, + 2, + 1, + ); + assert!(wallet1_refreshed); + // wallet 1 received fees, so amount should be the same + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward - amount - fee + ); + assert_eq!(wallet1_info.amount_immature, cm * reward + fee); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // refresh wallets and retrieve info/tests for each wallet after maturity - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!("Wallet 1 Info: {:?}", wallet1_info); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount - ); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm - 1) * reward - ); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!("Wallet 1 Info: {:?}", wallet1_info); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount + ); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm - 1) * reward + ); + } - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // Estimate fee and locked amount for a transaction - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 600_000_000_000); - // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) - assert_eq!(est.fee_fields.fee(), 25_000_000); + { + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args)?; + assert_eq!(est.amount, 600_000_000_000); + // fees for 5 inputs, 2 outputs, 1 kernel (weight 50) + assert_eq!(est.fee_fields.fee(), 25_000_000); - let init_args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, //select smallest number - estimate_only: Some(true), - ..Default::default() - }; - let est = sender_api.init_send_tx(m, init_args)?; - assert_eq!(est.amount, 180_000_000_000); - // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) - assert_eq!(est.fee_fields.fee(), 24_000_000); - - Ok(()) - }, - )?; + let init_args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, //select smallest number + estimate_only: Some(true), + ..Default::default() + }; + let est = api1.init_send_tx(mask1, init_args)?; + assert_eq!(est.amount, 180_000_000_000); + // fees for 3 inputs, 2 outputs, 1 kernel (weight 48) + assert_eq!(est.fee_fields.fee(), 24_000_000); + } // Send another transaction, but don't post to chain immediately and use // the stored transaction instead - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount * 2, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount: amount * 2, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let (refreshed, _wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - let (_, txs) = sender_api.retrieve_txs(m, true, None, None, None)?; - // find the transaction - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - let stored_tx_slate = sender_api - .get_stored_tx(m, None, Some(&tx.tx_slate_id.unwrap()))? - .unwrap(); - sender_api.post_tx(m, &stored_tx_slate, false)?; - let (_, wallet1_info) = sender_api.retrieve_summary_info(m, true, 1)?; - // should be mined now - assert_eq!( - wallet1_info.total, - amount * wallet1_info.last_confirmed_height - amount * 3 - ); - Ok(()) - }, - )?; + let (refreshed, _wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + // find the transaction + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + let stored_tx_slate = api1 + .get_stored_tx(mask1, None, Some(&tx.tx_slate_id.unwrap()))? + .unwrap(); + api1.post_tx(mask1, &stored_tx_slate, false)?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // should be mined now + assert_eq!( + wallet1_info.total, + amount * wallet1_info.last_confirmed_height - amount * 3 + ); + } // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); // check wallet2 has stored transaction - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (wallet2_refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(wallet2_refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); + { + let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet2_refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, amount * 3); - // check tx log entry is confirmed - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let tx = tx.unwrap(); - assert!(tx.confirmed); - assert!(tx.confirmation_ts.is_some()); - Ok(()) - }, - )?; + // check tx log entry is confirmed + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let tx = tx.unwrap(); + assert!(tx.confirmed); + assert!(tx.confirmation_ts.is_some()); + } // try to send a transaction with amount inclusive of fees, but amount too // small to cover fees. Should fail. - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: 1, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let res = sender_api.init_send_tx(m, args); - assert!(res.is_err()); - Ok(()) - }, - )?; + { + let args = InitTxArgs { + src_acct_name: None, + amount: 1, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let res = api1.init_send_tx(mask1, args); + assert!(res.is_err()); + } + + // Multiple send attempts, make sure same outputs not locked. + // Fail sending without starting Tor + api2.set_tor_config(Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }))?; + let mut handles = vec![]; + + let api2_1 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_1.init_send_tx(None, args) + })); + let api2_2 = Owner::new(api2.wallet_inst.clone(), None, api2.config_path()); + handles.push(thread::spawn(move || { + let args = InitTxArgs { + src_acct_name: None, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + amount: 1, + send_args: Some(InitTxSendArgs { + dest: "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp".into(), + post_tx: false, + fluff: false, + skip_tor: Some(false), + }), + ..Default::default() + }; + api2_2.init_send_tx(None, args) + })); + let results: Vec<_> = handles + .into_iter() + .map(|handle| handle.join().unwrap()) + .collect(); + assert_eq!(results.iter().filter(|r| { r.is_ok() }).count(), 1); + let err_res = results.iter().find(|r| r.is_err()).unwrap(); + assert!(matches!( + err_res.as_ref().err().unwrap(), + libwallet::Error::NotEnoughFunds { .. } + )); // try to build a transaction with amount inclusive of fees. Confirm that tx // amount + fee is equal to the originally specified amount let amount = 60_000_000_000; - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - amount_includes_fee: Some(true), - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - assert_eq!(slate_i.state, SlateState::Standard1); - let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); - assert_eq!(amount, total_spend); - Ok(()) - }, - )?; + { + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + amount_includes_fee: Some(true), + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + assert_eq!(slate_i.state, SlateState::Standard1); + let total_spend: u64 = slate_i.amount + slate_i.fee_fields.fee(); + assert_eq!(amount, total_spend); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -557,7 +527,8 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -568,7 +539,8 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -586,159 +558,121 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> { let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); let amount = 30_000_000_000; - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ..Default::default() - }; + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ..Default::default() + }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; + let slate_i = api1.init_send_tx(mask1, args)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + slate = api1.finalize_tx(mask1, &slate)?; // Check transaction log for wallet 1 - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - assert!(refreshed); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - // we should have a transaction entry for this slate - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - let mut locked_count = 0; - let mut unconfirmed_count = 0; - // get the tx entry, check outputs are as expected - let (_, output_mappings) = - api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in output_mappings.clone() { - if m.output.status == OutputStatus::Locked { - locked_count = locked_count + 1; - } - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; - } + { + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + assert!(refreshed); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + // we should have a transaction entry for this slate + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + let mut locked_count = 0; + let mut unconfirmed_count = 0; + // get the tx entry, check outputs are as expected + let (_, output_mappings) = + api1.retrieve_outputs(mask1, true, false, Some(tx.unwrap().id))?; + for m in output_mappings.clone() { + if m.output.status == OutputStatus::Locked { + locked_count = locked_count + 1; } - assert_eq!(output_mappings.len(), 3); - assert_eq!(locked_count, 2); - assert_eq!(unconfirmed_count, 1); - - Ok(()) - }, - )?; + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; + } + } + assert_eq!(output_mappings.len(), 3); + assert_eq!(locked_count, 2); + assert_eq!(unconfirmed_count, 1); + } // Check transaction log for wallet 2 - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - let mut unconfirmed_count = 0; - let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); - assert!(tx.is_some()); - // get the tx entry, check outputs are as expected - let (_, outputs) = api.retrieve_outputs(m, true, false, Some(tx.unwrap().id))?; - for m in outputs.clone() { - if m.output.status == OutputStatus::Unconfirmed { - unconfirmed_count = unconfirmed_count + 1; - } + { + let (refreshed, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + assert!(refreshed); + let mut unconfirmed_count = 0; + let tx = txs.iter().find(|t| t.tx_slate_id == Some(slate.id)); + assert!(tx.is_some()); + // get the tx entry, check outputs are as expected + let (_, outputs) = api2.retrieve_outputs(mask2, true, false, Some(tx.unwrap().id))?; + for m in outputs.clone() { + if m.output.status == OutputStatus::Unconfirmed { + unconfirmed_count = unconfirmed_count + 1; } - assert_eq!(outputs.len(), 1); - assert_eq!(unconfirmed_count, 1); - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.amount_awaiting_finalization, amount); - Ok(()) - }, - )?; + } + assert_eq!(outputs.len(), 1); + assert_eq!(unconfirmed_count, 1); + let (refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.amount_awaiting_finalization, amount); + } // wallet 1 is bold and doesn't ever post the transaction // mine a few more blocks let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 5, false); // Wallet 1 decides to roll back instead - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - // can't roll back coinbase - let res = api.cancel_tx(m, Some(1), None); - assert!(res.is_err()); - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - println!( - "last confirmed height: {}", - wallet1_info.last_confirmed_height - ); - // check all eligible inputs should be now be spendable - println!("cm: {}", cm); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); - - Ok(()) - }, - )?; - + { + // can't roll back coinbase + let res = api1.cancel_tx(mask1, Some(1), None); + assert!(res.is_err()); + let (_, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api1.cancel_tx(mask1, Some(tx.id), None)?; + let (refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + assert!(refreshed); + println!( + "last confirmed height: {}", + wallet1_info.last_confirmed_height + ); + // check all eligible inputs should be now be spendable + println!("cm: {}", cm); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + // can't roll back again + let res = api1.cancel_tx(mask1, Some(tx.id), None); + assert!(res.is_err()); + } // Wallet 2 rolls back - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let tx = txs - .iter() - .find(|t| t.tx_slate_id == Some(slate.id)) - .unwrap(); - api.cancel_tx(m, Some(tx.id), None)?; - let (refreshed, wallet2_info) = api.retrieve_summary_info(m, true, 1)?; - assert!(refreshed); - // check all eligible inputs should be now be spendable - assert_eq!(wallet2_info.amount_currently_spendable, 0,); - assert_eq!(wallet2_info.total, 0,); - // can't roll back again - let res = api.cancel_tx(m, Some(tx.id), None); - assert!(res.is_err()); - - Ok(()) - }, - )?; + { + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let tx = txs + .iter() + .find(|t| t.tx_slate_id == Some(slate.id)) + .unwrap(); + api2.cancel_tx(mask2, Some(tx.id), None)?; + let (refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(refreshed); + // check all eligible inputs should be now be spendable + assert_eq!(wallet2_info.amount_currently_spendable, 0,); + assert_eq!(wallet2_info.total, 0,); + // can't roll back again + let res = api2.cancel_tx(mask2, Some(tx.id), None); + assert!(res.is_err()); + } // let logging finish stopper.store(false, Ordering::Relaxed); @@ -760,7 +694,8 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); println!("Mask1: {:?}", mask1); @@ -783,50 +718,35 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { let min_confirmations = 1; // Check wallet 1 content are as expected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (wallet1_refreshed, wallet1_info) = - api.retrieve_summary_info(m, true, min_confirmations)?; - println!( - "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", - wallet1_info.last_confirmed_height, wallet1_info - ); - assert!(wallet1_refreshed); - assert_eq!( - wallet1_info.amount_currently_spendable, - (wallet1_info.last_confirmed_height - cm) * reward - ); - assert_eq!(wallet1_info.amount_immature, cm * reward); - Ok(()) - }, - )?; + { + let (wallet1_refreshed, wallet1_info) = + api1.retrieve_summary_info(mask1, true, min_confirmations)?; + println!( + "Wallet 1 Info Pre-Transaction, after {} blocks: {:?}", + wallet1_info.last_confirmed_height, wallet1_info + ); + assert!(wallet1_refreshed); + assert_eq!( + wallet1_info.amount_currently_spendable, + (wallet1_info.last_confirmed_height - cm) * reward + ); + assert_eq!(wallet1_info.amount_immature, cm * reward); + } // test selecting max amount - let result = wallet::controller::owner_single_use( - wallet1.clone(), + let result = api1.init_send_tx( mask1, - PathBuf::from(test_dir), - |api, m| { - api.init_send_tx( - m, - InitTxArgs { - amount: (reward * outputs_num as u64) - (cm * reward), - amount_includes_fee: Some(true), - minimum_confirmations: 0, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - refresh_outputs_from_node: true, - ..InitTxArgs::default() - }, - )?; - Ok(()) + InitTxArgs { + amount: (reward * outputs_num as u64) - (cm * reward), + amount_includes_fee: Some(true), + minimum_confirmations: 0, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + refresh_outputs_from_node: true, + ..InitTxArgs::default() }, ); - println!("{:?}", result); let max_tx_weight = global::max_tx_weight(); @@ -844,19 +764,11 @@ fn big_amount_error(test_dir: &'static str) -> Result<(), libwallet::Error> { Ok(_) => {} Err(e) => match e { libwallet::Error::BigAmountError(a, fee, num_inputs) => { - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, e_a, e_fee, e_num_inputs) = - api.estimate_max_sendable(m, true, min_confirmations)?; - assert_eq!(e_a, a - fee); - assert_eq!(e_fee, fee); - assert_eq!(e_num_inputs, num_inputs); - Ok(()) - }, - )?; + let (_, e_a, e_fee, e_num_inputs) = + api1.estimate_max_sendable(mask1, true, min_confirmations)?; + assert_eq!(e_a, a - fee); + assert_eq!(e_fee, fee); + assert_eq!(e_num_inputs, num_inputs); } _ => {} }, diff --git a/controller/tests/ttl_cutoff.rs b/controller/tests/ttl_cutoff.rs index faa3990..4c9bd12 100644 --- a/controller/tests/ttl_cutoff.rs +++ b/controller/tests/ttl_cutoff.rs @@ -20,8 +20,7 @@ extern crate grin_wallet_util; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{InitTxArgs, Slate, TxLogEntryType}; -use std::path::PathBuf; +use libwallet::{InitTxArgs, TxLogEntryType}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -45,7 +44,8 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); @@ -58,7 +58,8 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -78,126 +79,76 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let amount = 60_000_000_000; - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; + let mut slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); // Now mine past the block, and check again. Transaction should be gone. let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled); // Should also be gone in wallet 2, and output gone - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); - let outputs = sender_api.retrieve_outputs(m, false, true, None)?.1; - assert_eq!(outputs.len(), 0); + let (_, txs) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); + let outputs = api2.retrieve_outputs(mask2, false, true, None)?.1; + assert_eq!(outputs.len(), 0); - assert_eq!(tx.ttl_cutoff_height, Some(12)); - assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(12)); + assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled); // try again, except try and send off the transaction for completion beyond the expiry - let mut slate = Slate::blank(1, false); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount, - minimum_confirmations: 2, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: true, - ttl_blocks: Some(2), - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - sender_api.tx_lock_outputs(m, &slate_i)?; - slate = slate_i; + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 2, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: true, + ttl_blocks: Some(2), + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + api1.tx_lock_outputs(mask1, &slate_i)?; + slate = slate_i; - let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - let tx = txs[0].clone(); + let (_, txs) = api1.retrieve_txs(mask1, true, None, Some(slate.id), None)?; + let tx = txs[0].clone(); - assert_eq!(tx.ttl_cutoff_height, Some(14)); - Ok(()) - }, - )?; + assert_eq!(tx.ttl_cutoff_height, Some(14)); // Mine past the ttl block and try to send let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false); // Wallet 2 will need to have updated past the TTL - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |sender_api, m| { - let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?; - Ok(()) - }, - )?; + let (_, _) = api2.retrieve_txs(mask2, true, None, Some(slate.id), None)?; // And when wallet 1 sends, should be rejected - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |_sender_api, _m| { - let res = client1.send_tx_slate_direct("wallet2", &slate); - println!("Send after TTL result is: {:?}", res); - assert!(res.is_err()); - Ok(()) - }, - )?; + let res = client1.send_tx_slate_direct("wallet2", &slate); + println!("Send after TTL result is: {:?}", res); + assert!(res.is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/tx_list_filter.rs b/controller/tests/tx_list_filter.rs index c7fa9c8..cc63c15 100644 --- a/controller/tests/tx_list_filter.rs +++ b/controller/tests/tx_list_filter.rs @@ -23,210 +23,183 @@ use grin_core as core; use grin_keychain as keychain; use grin_util as util; use libwallet::{RetrieveTxQueryArgs, RetrieveTxQuerySortField}; -use std::path::PathBuf; -use self::libwallet::{InitTxArgs, Slate}; +use self::libwallet::InitTxArgs; use impls::test_framework::{self, LocalWalletClient}; -use std::sync::{atomic::Ordering, Arc}; +use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; use util::secp::key::SecretKey; -use util::Mutex; use self::keychain::ExtKeychain; -use self::libwallet::WalletInst; use impls::DefaultLCProvider; mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_api::Owner; fn test_wallet_tx_filtering( - wallet: Arc< - Mutex< - Box< - dyn WalletInst< - 'static, - DefaultLCProvider, - LocalWalletClient, - ExtKeychain, - >, - >, - >, - >, mask: Option<&SecretKey>, - test_dir: &'static str, + api: Owner, LocalWalletClient, ExtKeychain>, ) -> Result<(), libwallet::Error> { - wallet::controller::owner_single_use( - wallet.clone(), - mask, - PathBuf::from(test_dir), - |api, _m| { - let query = |args| { - api.retrieve_txs(mask, true, None, None, Some(args)) - .map(|(_, txs)| txs) - }; - let txs = query(RetrieveTxQueryArgs::default())?; - assert!(!txs.is_empty()); - let before_first_tx = - txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); - let mut tx_query_args = RetrieveTxQueryArgs::default(); + let query = |args| { + api.retrieve_txs(mask, true, None, None, Some(args)) + .map(|(_, txs)| txs) + }; + let txs = query(RetrieveTxQueryArgs::default())?; + assert!(!txs.is_empty()); + let before_first_tx = + txs.iter().map(|tx| tx.creation_ts).min().unwrap() - Duration::from_secs(1); + let mut tx_query_args = RetrieveTxQueryArgs::default(); - // Max creation time before all test transactions - tx_query_args.max_creation_timestamp = Some(before_first_tx); - assert!(query(tx_query_args.clone())?.is_empty()); + // Max creation time before all test transactions + tx_query_args.max_creation_timestamp = Some(before_first_tx); + assert!(query(tx_query_args.clone())?.is_empty()); - // Min confirmation time should not affect creation time - tx_query_args.max_creation_timestamp = None; - tx_query_args.min_confirmed_timestamp = Some(before_first_tx); - assert_eq!(query(tx_query_args)?.len(), txs.len()); + // Min confirmation time should not affect creation time + tx_query_args.max_creation_timestamp = None; + tx_query_args.min_confirmed_timestamp = Some(before_first_tx); + assert_eq!(query(tx_query_args)?.len(), txs.len()); - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); - // Min ID - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 33); + // Min ID + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 33); - // Max ID - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(20); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].id, 5); - assert_eq!(tx_results[tx_results.len() - 1].id, 20); + // Max ID + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(20); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].id, 5); + assert_eq!(tx_results[tx_results.len() - 1].id, 20); - // Exclude 1 cancelled - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 28); + // Exclude 1 canceled + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 28); - // Exclude 1 cancelled, show confirmed only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 14); + // Exclude 1 canceled, show confirmed only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 14); - // show outstanding only (including cancelled) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // show outstanding only (including canceled) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // outstanding only and confirmed only should give empty set - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.exclude_cancelled = Some(false); - tx_query_args.include_outstanding_only = Some(true); - tx_query_args.include_confirmed_only = Some(true); - tx_query_args.min_id = Some(5); - tx_query_args.max_id = Some(50); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // outstanding only and confirmed only should give empty set + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.exclude_cancelled = Some(false); + tx_query_args.include_outstanding_only = Some(true); + tx_query_args.include_confirmed_only = Some(true); + tx_query_args.min_id = Some(5); + tx_query_args.max_id = Some(50); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include sent only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_sent_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 15); + // include sent only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_sent_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 15); - // include received only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_received_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include received only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_received_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include reverted only (none in this set) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_reverted_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 0); + // include reverted only (none in this set) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_reverted_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 0); - // include coinbase only - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.include_coinbase_only = Some(true); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // include coinbase only + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.include_coinbase_only = Some(true); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // Amounts - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 27); + // Amounts + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 27); - // amount, should see as above with coinbases excluded - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); - tx_query_args.max_amount = Some(60_000_000_000 - 1); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 8); + // amount, should see as above with coinbases excluded + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000 - 59_963_300_000); + tx_query_args.max_amount = Some(60_000_000_000 - 1); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 8); - // Amount - should only see coinbase (incoming) - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.min_amount = Some(60_000_000_000); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results.len(), 19); + // Amount - should only see coinbase (incoming) + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.min_amount = Some(60_000_000_000); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results.len(), 19); - // sort order - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; + // sort order + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; - assert_eq!(tx_results[0].id, 33); - assert_eq!(tx_results[tx_results.len() - 1].id, 0); + assert_eq!(tx_results[0].id, 33); + assert_eq!(tx_results[tx_results.len() - 1].id, 0); - // change sort field to amount desc, should have coinbases first - let mut tx_query_args = RetrieveTxQueryArgs::default(); - tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); - tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); - let tx_results = api - .retrieve_txs(mask, true, None, None, Some(tx_query_args))? - .1; - assert_eq!(tx_results[0].amount_credited, 60_000_000_000); - - /*for entry in tx_results.iter() { - println!("{:?}", entry); - }*/ - - Ok(()) - }, - )?; + // change sort field to amount desc, should have coinbases first + let mut tx_query_args = RetrieveTxQueryArgs::default(); + tx_query_args.sort_order = Some(libwallet::RetrieveTxQuerySortOrder::Desc); + tx_query_args.sort_field = Some(RetrieveTxQuerySortField::TotalAmount); + let tx_results = api + .retrieve_txs(mask, true, None, None, Some(tx_query_args))? + .1; + assert_eq!(tx_results[0].amount_credited, 60_000_000_000); Ok(()) } @@ -248,7 +221,8 @@ fn build_chain_for_tx_filtering( "wallet1", None, &mut wallet_proxy, - true + true, + api1 ); let mask1 = (&mask1_i).as_ref(); debug!("Mask1: {:?}", mask1); @@ -260,7 +234,8 @@ fn build_chain_for_tx_filtering( "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); debug!("Mask2: {:?}", mask2); @@ -274,25 +249,8 @@ fn build_chain_for_tx_filtering( // Stop the scanning updater threads because it extends the time needed to build the chain // exponentially - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; - - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, _m| { - api.stop_updater()?; - Ok(()) - }, - )?; + api1.stop_updater()?; + api2.stop_updater()?; // few values to keep things shorter let reward = core::consensus::REWARD; @@ -304,22 +262,14 @@ fn build_chain_for_tx_filtering( let mut wallet_1_has_funds = false; // Check wallet 1 contents - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - debug!( - "Wallet 1 spendable - {}", - wallet1_info.amount_currently_spendable - ); - if wallet1_info.amount_currently_spendable > reward { - wallet_1_has_funds = true; - } - Ok(()) - }, - )?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + debug!( + "Wallet 1 spendable - {}", + wallet1_info.amount_currently_spendable + ); + if wallet1_info.amount_currently_spendable > reward { + wallet_1_has_funds = true; + } if !wallet_1_has_funds { let _ = @@ -331,62 +281,44 @@ fn build_chain_for_tx_filtering( let num_txs = 1; for _ in 0..num_txs { let amount: u64 = i as u64 * 1_000_000; - let mut slate = Slate::blank(1, false); debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { - // note this will increment the block count as part of the transaction "Posting" - let args = InitTxArgs { - src_acct_name: None, - amount: amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - slate = sender_api.finalize_tx(m, &slate)?; - Ok(()) - }, - )?; - } - } - - // Cancel a tx for filtering testing - let amount: u64 = 1_000_000; - let mut slate = Slate::blank(1, false); - debug!("Creating TX for {}", amount); - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |sender_api, m| { // note this will increment the block count as part of the transaction "Posting" let args = InitTxArgs { src_acct_name: None, - amount: amount, + amount, minimum_confirmations: 1, max_outputs: 500, num_change_outputs: 1, selection_strategy_is_use_all: false, ..Default::default() }; - let slate_i = sender_api.init_send_tx(m, args)?; - slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; - sender_api.tx_lock_outputs(m, &slate)?; - sender_api.cancel_tx(m, Some(33), None)?; - Ok(()) - }, - )?; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.finalize_tx(mask1, &slate)?; + } + } + + // Cancel a tx for filtering testing + let amount: u64 = 1_000_000; + debug!("Creating TX for {}", amount); + // note this will increment the block count as part of the transaction "Posting" + let args = InitTxArgs { + src_acct_name: None, + amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let slate_i = api1.init_send_tx(mask1, args)?; + let slate = client1.send_tx_slate_direct("wallet2", &slate_i)?; + api1.tx_lock_outputs(mask1, &slate)?; + api1.cancel_tx(mask1, Some(33), None)?; // Perform actual testing - test_wallet_tx_filtering(wallet1, mask1, test_dir)?; + test_wallet_tx_filtering(mask1, api1)?; // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/controller/tests/updater_thread.rs b/controller/tests/updater_thread.rs index 2beebab..8e33355 100644 --- a/controller/tests/updater_thread.rs +++ b/controller/tests/updater_thread.rs @@ -46,7 +46,8 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet1", None, &mut wallet_proxy, - false + false, + api1 ); let mask1 = (&mask1_i).as_ref(); create_wallet_and_add!( @@ -57,7 +58,8 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err "wallet2", None, &mut wallet_proxy, - false + false, + api2 ); let mask2 = (&mask2_i).as_ref(); @@ -69,28 +71,11 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err }); // add some accounts - wallet::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "mining")?; - api.create_account_path(m, "listener")?; - Ok(()) - }, - )?; + api1.create_account_path(mask1, "mining")?; + api1.create_account_path(mask1, "listener")?; - // add some accounts - wallet::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.create_account_path(m, "account1")?; - api.create_account_path(m, "account2")?; - Ok(()) - }, - )?; + api2.create_account_path(mask2, "account1")?; + api2.create_account_path(mask2, "account2")?; // Get some mining done { diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index 1394dd7..63f56c0 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -124,7 +124,7 @@ impl TorSlateSender { let res: String = self.post(url, req).map_err(|e| { let mut report = format!("Performing version check (is recipient listening?): {}", e); let err_string = format!("{}", e); - if err_string.contains("404") { + if !self.config.use_integrated.unwrap_or(false) && err_string.contains("404") { // Report that the other version of the wallet is out of date report = "Other wallet is incompatible and requires an upgrade. \ Please urge the other wallet owner to upgrade and try the transaction again." diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index 8159232..1958e42 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -366,7 +366,7 @@ impl From for OnionError { } #[cfg(test)] -pub mod tests { +mod tests { use super::*; use crate::mwixnet::onion::crypto::secp::random_secret; use crate::mwixnet::onion::{new_hop, Hop}; diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index a4d8308..f54987c 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -21,9 +21,9 @@ extern crate log; extern crate grin_wallet; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; -use std::path::PathBuf; use clap::App; +use std::sync::mpsc; use std::thread; use std::time::Duration; @@ -32,9 +32,23 @@ use grin_wallet_impls::DefaultLCProvider; mod common; use common::{clean_output_dir, execute_command, initial_setup_wallet, instantiate_wallet, setup}; +use grin_wallet_api::Owner; +use grin_wallet_libwallet::{OutputStatus, TxLogEntryType}; /// command line tests fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller::Error> { + let (logs_tx, logs_rx) = mpsc::sync_channel(100); + let panic_hook = std::panic::take_hook(); + grin_util::init_logger( + Some(grin_util::logger::LoggingConfig { + log_to_file: false, + stdout_log_level: log::Level::Error, + tui_running: Some(true), + ..Default::default() + }), + Some(logs_tx), + ); + std::panic::set_hook(panic_hook); setup(test_dir); // Create a new proxy to simulate server and wallet responses let mut wallet_proxy: WalletProxy< @@ -158,15 +172,9 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let (wallet1, mask1_i) = instantiate_wallet(wallet_config1, client1.clone(), "password1", "default")?; let mask1 = (&mask1_i).as_ref(); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - Ok(()) - }, - )?; + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); + + api1.set_active_account(mask1, "mining")?; let mut bh = 10u64; let _ = @@ -236,23 +244,16 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); // Check our transaction log, should have 10 entries - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - for t in txs { - assert!(t.kernel_excess.is_some()); - } - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); + for t in txs { + assert!(t.kernel_excess.is_some()); + } let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); bh += 10; @@ -273,33 +274,17 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask2 = (&mask2_i).as_ref(); + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "account_1")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - assert_eq!(wallet1_info.last_confirmed_height, bh); - assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "account_1")?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(wallet1_info.last_confirmed_height, bh); + assert_eq!(wallet1_info.amount_currently_spendable, 10_000_000_000); // Send to wallet 2 with --amount_includes_fee - let mut old_balance = 0; - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - old_balance = wallet1_info.amount_currently_spendable; - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; let arg_vec = vec![ "grin-wallet", "-p", @@ -349,22 +334,14 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check the new balance of wallet 1 reduced by EXACTLY the tx amount (instead of amount + fee) // This confirms that the TX amount was correctly computed to allow for the fee - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?; - // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then - let amt_mined = 10 * 60_000_000_000; - assert_eq!( - wallet1_info.amount_currently_spendable + 10_000_000_000, - old_balance + amt_mined - ); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; + // make sure the new balance is exactly equal to the old balance - the tx amount + the amount mined since then + let amt_mined = 10 * 60_000_000_000; + assert_eq!( + wallet1_info.amount_currently_spendable + 10_000_000_000, + old_balance + amt_mined + ); // Send encrypted from wallet 1 to wallet 2 // output wallet 2's address for test creation purposes, @@ -435,19 +412,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize); // Send to self let arg_vec = vec![ @@ -508,19 +478,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "default", )?; let mask1 = (&mask1_i).as_ref(); + let api1 = Owner::new(wallet1.clone(), None, config1.config_file_path.clone()); - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?; - assert!(refreshed); - assert_eq!(txs.len(), bh as usize + 1); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (refreshed, txs) = api1.retrieve_txs(mask1, true, None, None, None)?; + assert!(refreshed); + assert_eq!(txs.len(), bh as usize + 1); // Another file exchange, don't send, but unlock with repair command let arg_vec = vec![ @@ -649,24 +612,15 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; // get tx output via -tx parameter - let mut tx_id = "".to_string(); - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "default")?; - let (_, txs) = api.retrieve_txs(m, true, None, None, None)?; - let some_tx_id = txs[0].tx_slate_id.clone(); - assert!(some_tx_id.is_some()); - tx_id = some_tx_id.unwrap().to_string().clone(); - Ok(()) - }, - )?; + api2.set_active_account(mask2, "default")?; + let (_, txs) = api2.retrieve_txs(mask2, true, None, None, None)?; + let some_tx_id = txs[0].tx_slate_id.clone(); + assert!(some_tx_id.is_some()); + let tx_id = some_tx_id.unwrap().to_string().clone(); let arg_vec = vec!["grin-wallet", "-p", "password2", "txs", "-t", &tx_id[..]]; execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; - // bit of mining + // a bit of mining let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false); // Test wallet sweep @@ -717,21 +671,77 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: // Check wallet 1 is now empty, except for immature coinbase outputs from recent mining), // and recently matured coinbase outputs, which were not mature at time of spending. // This confirms that the TX amount was correctly computed to allow for the fee - grin_wallet_controller::controller::owner_single_use( - wallet1.clone(), - mask1, - PathBuf::from(test_dir), - |api, m| { - api.set_active_account(m, "mining")?; - let (_, wallet1_info) = api.retrieve_summary_info(m, true, 10)?; - // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs - // which matured in the last batch of mining. Check that the new spendable balance is - // exactly equal to those matured coins. - let amt_mined = 10 * 60_000_000_000; - assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); - Ok(()) - }, - )?; + api1.set_active_account(mask1, "mining")?; + let (_, wallet1_info) = api1.retrieve_summary_info(mask1, true, 10)?; + // Entire 'spendable' wallet balance should have been swept, except the coinbase outputs + // which matured in the last batch of mining. Check that the new spendable balance is + // exactly equal to those matured coins. + let amt_mined = 10 * 60_000_000_000; + assert_eq!(wallet1_info.amount_currently_spendable, amt_mined); + + // Failed send, with --late-lock, make sure outputs not locked (amount not changed). + api2.set_active_account(mask2, "account_1")?; + let (_, txs_before) = api2.retrieve_txs(mask2, false, None, None, None)?; + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + let old_balance = wallet1_info.amount_currently_spendable; + let mut arg_vec = vec![ + "grin-wallet", + "-p", + "password2", + "-a", + "account_1", + "send", + "-d", + "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "1", + "--late-lock", + ]; + let args = app.clone().get_matches_from(arg_vec.clone()); + let mut config = initial_setup_wallet(test_dir, "wallet2"); + config.members.tor = Some(grin_wallet_config::TorConfig { + use_integrated: Some(false), + socks_proxy_addr: "invalid".into(), + ..Default::default() + }); + let send = |args: &clap::ArgMatches| -> Result<(), grin_wallet_controller::Error> { + logs_rx.try_iter().for_each(drop); + grin_wallet::cmd::wallet_args::wallet_command( + args, + config.clone(), + client2.clone(), + false, + |_| {}, + )?; + assert!(logs_rx.try_iter().any(|entry| { + entry.log.contains("Error sending slate sync:") && entry.log.contains("AddrParseError") + })); + Ok(()) + }; + send(&args)?; + api2.set_active_account(mask2, "account_1")?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_before.len(), txs_after.len()); + let (_, wallet1_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert_eq!(old_balance, wallet1_info.amount_currently_spendable); + + // The same failure without late locking leaves one transaction and locked outputs + arg_vec.pop(); + let args = app.clone().get_matches_from(arg_vec); + send(&args)?; + let (_, txs_after) = api2.retrieve_txs(mask2, false, None, None, None)?; + assert_eq!(txs_after.len(), txs_before.len() + 1); + let tx = txs_after + .iter() + .find(|tx| !txs_before.iter().any(|before| before.id == tx.id)) + .unwrap(); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert!(tx.tx_slate_id.is_some()); + let (_, outputs) = api2.retrieve_outputs(mask2, false, false, Some(tx.id))?; + assert!(outputs + .iter() + .any(|output| output.output.status == OutputStatus::Locked)); + let (_, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; + assert!(wallet_info.amount_currently_spendable < old_balance); // let logging finish thread::sleep(Duration::from_millis(200)); diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index 997bdb3..bf6711e 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -19,7 +19,7 @@ extern crate log; extern crate grin_wallet; -use grin_wallet_api::{ECDHPubkey, JsonId}; +use grin_wallet_api::{ECDHPubkey, JsonId, Owner}; use grin_wallet_impls::test_framework::{self, LocalWalletClient, WalletProxy}; use clap::App; @@ -64,7 +64,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { >, >, > = Arc::new(Mutex::new(WalletProxy::new(test_dir))); - let (chain, wallet2, mask2_i) = { + let (chain, wallet2, mask2_i, config2) = { let mut wallet_proxy = wallet_proxy_a.lock(); let chain = wallet_proxy.chain.clone(); @@ -118,7 +118,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { ) .unwrap(); }); - (chain, wallet2, mask2_i) + (chain, wallet2, mask2_i, config2) }; // give a bit for wallet to init and populate proxy with wallet via callback in thread above thread::sleep(Duration::from_millis(500)); @@ -402,27 +402,20 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let mut slate: Slate = res.unwrap().into(); // give this slate over to wallet 2 manually - grin_wallet_controller::controller::owner_single_use( - wallet2.clone(), - mask2, - PathBuf::from(test_dir), - |api, m| { - let args = InitTxArgs { - src_acct_name: None, - amount: slate.amount, - minimum_confirmations: 1, - max_outputs: 500, - num_change_outputs: 1, - selection_strategy_is_use_all: false, - ..Default::default() - }; - let res = api.process_invoice_tx(m, &slate, args); - assert!(res.is_ok()); - slate = res.unwrap(); - api.tx_lock_outputs(m, &slate)?; - Ok(()) - }, - )?; + let api2 = Owner::new(wallet2.clone(), None, config2.config_file_path.clone()); + let args = InitTxArgs { + src_acct_name: None, + amount: slate.amount, + minimum_confirmations: 1, + max_outputs: 500, + num_change_outputs: 1, + selection_strategy_is_use_all: false, + ..Default::default() + }; + let res = api2.process_invoice_tx(mask2, &slate, args); + assert!(res.is_ok()); + slate = res?; + api2.tx_lock_outputs(mask2, &slate)?; //16) Finalize the invoice tx (to foreign api) // (Tests that foreign API on same port also has its stored mask updated) From 57a01674ffa780608fe6aa1c81d3111f080b0dcb Mon Sep 17 00:00:00 2001 From: wiesche Date: Fri, 2 Oct 2026 22:15:25 +0200 Subject: [PATCH 30/39] isolate tests (cherry picked from commit 3a2ad4edbfbca29bd4191fd30cab23e15fa47cde) --- tests/common/mod.rs | 5 ++++- tests/owner_v3_lifecycle.rs | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 85cbe74..313a795 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -299,8 +299,11 @@ where { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); + // Avoid conflicts with local wallets + let wallet_dir = PathBuf::from(test_dir).join(format!("{}_bootstrap", wallet_name)); let mut config = - config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None, true).unwrap(); + config::initial_setup_wallet(&ChainTypes::AutomatedTesting, Some(wallet_dir), true) + .unwrap(); let mut wallet_config = config.clone().members.wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; diff --git a/tests/owner_v3_lifecycle.rs b/tests/owner_v3_lifecycle.rs index bf6711e..363c6ed 100644 --- a/tests/owner_v3_lifecycle.rs +++ b/tests/owner_v3_lifecycle.rs @@ -148,7 +148,7 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { let value: ECDHPubkey = res.unwrap(); let shared_key = derive_ecdh_key(sec_key_str, &value.ecdh_pubkey); - // 2) get the top level directory, should default to ~/.grin/auto + // 2) get the top level directory let req = include_str!("data/v3_reqs/get_top_level.req.json"); let res = send_request_enc::( &JsonId::StrId(String::from("1")), @@ -159,7 +159,13 @@ fn owner_v3_lifecycle() -> Result<(), grin_wallet_controller::Error> { )?; println!("RES 2: {:?}", res); assert!(res.is_ok()); - assert!(res.unwrap().contains("auto")); + assert_eq!( + PathBuf::from(res.unwrap()).canonicalize().unwrap(), + PathBuf::from(test_dir) + .join("wallet1_bootstrap") + .canonicalize() + .unwrap() + ); // 3) now set the top level directory to our test wallet dir let req = serde_json::json!({ From fcb1d37876d7bf2b4a4718bc54404af7cda3cd0d Mon Sep 17 00:00:00 2001 From: ardocrat Date: Tue, 29 Sep 2026 23:22:45 +0300 Subject: [PATCH 31/39] Compact transaction table at CLI view (#822) (cherry picked from commit 965e8f1667cf976df61fa846005f9aeddbb14967) --- controller/src/display.rs | 163 ++++++++++++++++++++------------------ libwallet/src/types.rs | 8 +- 2 files changed, 88 insertions(+), 83 deletions(-) diff --git a/controller/src/display.rs b/controller/src/display.rs index 54077fc..8251d35 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -17,9 +17,10 @@ use crate::core::core::FeeFields; use crate::core::global; use crate::libwallet::{ address, AcctPathMapping, Error, OutputCommitMapping, OutputStatus, SlatepackAddress, - TxLogEntry, ViewWallet, WalletInfo, + TxLogEntry, TxLogEntryType, ViewWallet, WalletInfo, }; use crate::util::ToHex; + use prettytable; use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; @@ -150,47 +151,68 @@ pub fn txs( let mut table = table!(); - table.set_titles(row![ - bMG->"Id", - bMG->"Type", - bMG->"State", - bMG->"Shared Transaction Id", - bMG->"Creation Time", - bMG->"TTL Cutoff Height", - bMG->"Confirmed?", - bMG->"Confirmation Time", - bMG->"Num. \nInputs", - bMG->"Num. \nOutputs", - bMG->"Amount \nCredited", - bMG->"Amount \nDebited", - bMG->"Fee", - bMG->"Net \nDifference", - bMG->"Payment \nProof", - bMG->"Kernel", - bMG->"Tx \nData", - ]); + table.set_titles(if dark_background_color_scheme { + row![ + bMG->"Id", + bMG->"Type (State)", + bMG->"Shared Transaction Id \nKernel", + bMG->"Creation Time \nConfirmation Time", + bMG->"Payment Proof \nTTL Cutoff Height", + bMG->"Inputs \nOutputs", + bMG->"Credited \nDebited", + bMG->"Fee \nDifference", + ] + } else { + row![ + bFD ->"Id", + bFD->"Type (State)", + bFD->"Shared Transaction Id \nKernel", + bFD->"Creation Time \nConfirmation Time", + bFD->"Payment Proof \nTTL Cutoff Height", + bFD->"Inputs \nOutputs", + bFD->"Credited \nDebited", + bFD->"Fee \nDifference", + ] + }); - for t in txs { + for (i, t) in txs.iter().enumerate() { let id = format!("{}", t.id); let slate_id = match t.tx_slate_id { Some(m) => format!("{}", m), None => "None".to_owned(), }; - let slate_state = match t.tx_slate_state.as_ref() { - Some(m) => format!("{}", m), - None => "None".to_owned(), + + let entry_type = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Coinbase", + TxLogEntryType::TxReceived => "Received Tx", + TxLogEntryType::TxSent => "Sent Tx", + TxLogEntryType::TxReceivedCancelled => "Received Tx", + TxLogEntryType::TxSentCancelled => "Sent Tx", + TxLogEntryType::TxReverted => "Received Tx", + }) + .to_string(); + let entry_type_state = match t.tx_slate_state.as_ref() { + None => entry_type.to_string(), + Some(s) => format!("{} ({})", entry_type, s), }; - let entry_type = format!("{}", t.tx_type); + let entry_type_desc = (match t.tx_type { + TxLogEntryType::ConfirmedCoinbase => "Confirmed", + TxLogEntryType::TxReceived => "", + TxLogEntryType::TxSent => "", + TxLogEntryType::TxReceivedCancelled => "Cancelled", + TxLogEntryType::TxSentCancelled => "Cancelled", + TxLogEntryType::TxReverted => "Reverted", + }) + .to_string(); let creation_ts = format!("{}", t.creation_ts.format("%Y-%m-%d %H:%M:%S")); let ttl_cutoff_height = match t.ttl_cutoff_height { - Some(b) => format!("{}", b), + Some(b) => b.to_string(), None => "None".to_owned(), }; let confirmation_ts = match t.confirmation_ts { Some(m) => format!("{}", m.format("%Y-%m-%d %H:%M:%S")), None => "None".to_owned(), }; - let confirmed = format!("{}", t.confirmed); let num_inputs = format!("{}", t.num_inputs); let num_outputs = format!("{}", t.num_outputs); let amount_debited_str = amount_to_hr_string(t.amount_debited, true); @@ -207,10 +229,6 @@ pub fn txs( amount_to_hr_string(t.amount_debited - t.amount_credited, true) ) }; - let tx_data = match t.stored_tx { - Some(_) => "Yes".to_owned(), - None => "None".to_owned(), - }; let kernel_excess = match t.kernel_excess { Some(e) => { let excess: &[u8] = e.0.as_ref(); @@ -225,65 +243,52 @@ pub fn txs( if dark_background_color_scheme { table.add_row(row![ bFC->id, - bFC->entry_type, - bFC->slate_state, + bFC->entry_type_state, bFC->slate_id, bFB->creation_ts, - bFB->ttl_cutoff_height, - bFC->confirmed, - bFB->confirmation_ts, + bFC->payment_proof, bFC->num_inputs, - bFC->num_outputs, bFG->amount_credited_str, - bFR->amount_debited_str, bFR->fee, - bFY->net_diff, - bfG->payment_proof, + ]); + table.add_row(row![ + bFD->"", + bFC->entry_type_desc, bFB->kernel_excess, - bFb->tx_data, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFC->num_outputs, + bFR->amount_debited_str, + bFY->net_diff, ]); } else { - if t.confirmed { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFg->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } else { - table.add_row(row![ - bFD->id, - bFb->entry_type, - bFD->slate_id, - bFB->creation_ts, - bFR->confirmed, - bFB->confirmation_ts, - bFD->num_inputs, - bFD->num_outputs, - bFG->amount_credited_str, - bFD->amount_debited_str, - bFD->fee, - bFG->net_diff, - bfG->payment_proof, - bFB->kernel_excess, - bFB->tx_data, - ]); - } + table.add_row(row![ + bFD->id, + bFb->entry_type_state, + bFD->slate_id, + bFB->creation_ts, + bFD->payment_proof, + bFD->num_inputs, + bFG->amount_credited_str, + bFR->fee, + ]); + table.add_row(row![ + bFD->"", + bFb->entry_type_desc, + bFB->kernel_excess, + bFB->confirmation_ts, + bFB->ttl_cutoff_height, + bFD->num_outputs, + bFR->amount_debited_str, + bFG->net_diff, + ]); + } + if i != txs.len() - 1 { + table.add_empty_row(); } } - table.set_format(*prettytable::format::consts::FORMAT_NO_COLSEP); + table.set_format(*prettytable::format::consts::FORMAT_NO_LINESEP_WITH_TITLE); table.printstd(); println!(); diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index 0aec740..b4e2e5e 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -610,12 +610,12 @@ pub enum TxLogEntryType { impl fmt::Display for TxLogEntryType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed \nCoinbase"), + TxLogEntryType::ConfirmedCoinbase => write!(f, "Confirmed Coinbase"), TxLogEntryType::TxReceived => write!(f, "Received Tx"), TxLogEntryType::TxSent => write!(f, "Sent Tx"), - TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx\n- Cancelled"), - TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx\n- Cancelled"), - TxLogEntryType::TxReverted => write!(f, "Received Tx\n- Reverted"), + TxLogEntryType::TxReceivedCancelled => write!(f, "Received Tx - Cancelled"), + TxLogEntryType::TxSentCancelled => write!(f, "Sent Tx - Cancelled"), + TxLogEntryType::TxReverted => write!(f, "Received Tx - Reverted"), } } } From 6c9c5e6b36d736dbaaeedd9cede49595c6673a09 Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:58:07 +0200 Subject: [PATCH 32/39] fix late lock self send proof (#829) --- controller/tests/self_send.rs | 58 +++++++++++++++++++++++++++++++++++ libwallet/src/internal/tx.rs | 16 +++++----- 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index c6ca437..6d1a9a1 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -141,3 +141,61 @@ fn wallet_self_send() { } clean_output_dir(test_dir); } + +#[test] +fn late_lock_self_send_proof() -> Result<(), libwallet::Error> { + let test_dir = "test_output/late_lock_self_send_proof"; + setup(test_dir); + let mut wallet_proxy = create_wallet_proxy(test_dir); + let chain = wallet_proxy.chain.clone(); + let stopper = wallet_proxy.running.clone(); + create_wallet_and_add!( + client1, + wallet1, + mask1_i, + test_dir, + "wallet1", + None, + &mut wallet_proxy, + false, + api1 + ); + let mask1 = mask1_i.as_ref(); + let worker = thread::spawn(move || wallet_proxy.run()); + + let result = (|| { + test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 10, false)?; + let mut slate = api1.init_send_tx( + mask1, + InitTxArgs { + amount: core::consensus::REWARD, + minimum_confirmations: 2, + late_lock: Some(true), + payment_proof_recipient_address: Some(api1.get_slatepack_address(mask1, 0)?), + ..Default::default() + }, + )?; + wallet::controller::foreign_single_use( + wallet1.clone(), + PathBuf::from(test_dir), + mask1_i.clone(), + |api| { + slate = api.receive_tx(&slate, None, None)?; + Ok(()) + }, + )?; + let (_, txs) = api1.retrieve_txs(mask1, false, None, Some(slate.id), None)?; + assert_eq!(txs.len(), 1); + assert_eq!(txs[0].tx_type, libwallet::TxLogEntryType::TxReceived); + + api1.finalize_tx(mask1, &slate).map(|_| ()) + })(); + + stopper.store(false, Ordering::Relaxed); + worker.join().unwrap()?; + drop(api1); + drop(wallet1); + drop(chain); + clean_output_dir(test_dir); + result +} diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 6b655e3..379e572 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -500,13 +500,15 @@ where Some(parent_key_id), false, )?; - if tx_vec.is_empty() { - return Err(Error::PaymentProof( - "TxLogEntry with original proof info not found (is account correct?)".to_owned(), - )); - } - - let orig_proof_info = tx_vec[0].clone().payment_proof; + let orig_proof_info = tx_vec + .into_iter() + .find(|tx| tx.tx_type == TxLogEntryType::TxSent) + .ok_or_else(|| { + Error::PaymentProof( + "TxLogEntry with original proof info not found (is account correct?)".to_owned(), + ) + })? + .payment_proof; if orig_proof_info.is_some() && slate.payment_proof.is_none() { return Err(Error::PaymentProof( From 6517e3d4ed1a96d73a768654f6623800377c7832 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Sat, 10 Oct 2026 14:18:40 +0300 Subject: [PATCH 33/39] fix: do not scan outputs twice on payment proof retrieval (#830) --- libwallet/src/api_impl/owner.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 58bfbd2..0f2f46b 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -446,8 +446,8 @@ where "Transaction ID or Slate UUID must be specified".to_owned(), )); } - if refresh_from_node { - update_wallet_state( + let refresh_txs_from_node = if refresh_from_node { + !update_wallet_state( wallet_inst.clone(), keychain_mask, status_send_channel, @@ -460,7 +460,7 @@ where wallet_inst.clone(), keychain_mask, status_send_channel, - refresh_from_node, + refresh_txs_from_node, tx_id, tx_slate_id, None, From f097811ee953fc81be4e70435d6ef845b6b2e8c9 Mon Sep 17 00:00:00 2001 From: wiesche Date: Thu, 8 Oct 2026 22:30:11 +0200 Subject: [PATCH 34/39] bump to version 5.5.1 --- Cargo.lock | 14 +++++++------- Cargo.toml | 12 ++++++------ api/Cargo.toml | 10 +++++----- config/Cargo.toml | 2 +- controller/Cargo.toml | 12 ++++++------ impls/Cargo.toml | 8 ++++---- libwallet/Cargo.toml | 6 +++--- util/Cargo.toml | 2 +- 8 files changed, 33 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b1948dc..950840e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2433,7 +2433,7 @@ dependencies = [ [[package]] name = "grin_wallet" -version = "5.5.0" +version = "5.5.1" dependencies = [ "built", "clap", @@ -2461,7 +2461,7 @@ dependencies = [ [[package]] name = "grin_wallet_api" -version = "5.5.0" +version = "5.5.1" dependencies = [ "base64 0.12.3", "chrono", @@ -2486,7 +2486,7 @@ dependencies = [ [[package]] name = "grin_wallet_config" -version = "5.5.0" +version = "5.5.1" dependencies = [ "dirs 2.0.2", "grin_core", @@ -2502,7 +2502,7 @@ dependencies = [ [[package]] name = "grin_wallet_controller" -version = "5.5.0" +version = "5.5.1" dependencies = [ "easy-jsonrpc-mw", "ed25519-dalek", @@ -2533,7 +2533,7 @@ dependencies = [ [[package]] name = "grin_wallet_impls" -version = "5.5.0" +version = "5.5.1" dependencies = [ "arti-client", "base64 0.12.3", @@ -2580,7 +2580,7 @@ dependencies = [ [[package]] name = "grin_wallet_libwallet" -version = "5.5.0" +version = "5.5.1" dependencies = [ "age", "base64 0.9.3", @@ -2618,7 +2618,7 @@ dependencies = [ [[package]] name = "grin_wallet_util" -version = "5.5.0" +version = "5.5.1" dependencies = [ "data-encoding", "ed25519-dalek", diff --git a/Cargo.toml b/Cargo.toml index 901278d..8dbc578 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -29,11 +29,11 @@ semver = "1.0.28" rustyline = "9" lazy_static = "1" -grin_wallet_api = { path = "./api", version = "5.5.0" } -grin_wallet_impls = { path = "./impls", version = "5.5.0" } -grin_wallet_libwallet = { path = "./libwallet", version = "5.5.0" } -grin_wallet_controller = { path = "./controller", version = "5.5.0" } -grin_wallet_config = { path = "./config", version = "5.5.0" } +grin_wallet_api = { path = "./api", version = "5.5.1" } +grin_wallet_impls = { path = "./impls", version = "5.5.1" } +grin_wallet_libwallet = { path = "./libwallet", version = "5.5.1" } +grin_wallet_controller = { path = "./controller", version = "5.5.1" } +grin_wallet_config = { path = "./config", version = "5.5.1" } ##### Grin Imports diff --git a/api/Cargo.toml b/api/Cargo.toml index c797161..f364849 100644 --- a/api/Cargo.toml +++ b/api/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_api" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Grin Wallet API" license = "Apache-2.0" @@ -22,10 +22,10 @@ ring = "0.17.14" base64 = "0.12" ed25519-dalek = "2" -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } -grin_wallet_impls = { path = "../impls", version = "5.5.0" } -grin_wallet_util = { path = "../util", version = "5.5.0" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } +grin_wallet_impls = { path = "../impls", version = "5.5.1" } +grin_wallet_util = { path = "../util", version = "5.5.1" } ##### Grin Imports diff --git a/config/Cargo.toml b/config/Cargo.toml index 5d7e339..6600bc0 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_config" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Configuration for grin wallet , a simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" diff --git a/controller/Cargo.toml b/controller/Cargo.toml index 5de94f2..4019663 100644 --- a/controller/Cargo.toml +++ b/controller/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_controller" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Controllers for grin wallet instantiation" license = "Apache-2.0" @@ -25,11 +25,11 @@ lazy_static = "1" thiserror = "1" qr_code = "1.1.0" -grin_wallet_util = { path = "../util", version = "5.5.0" } -grin_wallet_api = { path = "../api", version = "5.5.0" } -grin_wallet_impls = { path = "../impls", version = "5.5.0" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_api = { path = "../api", version = "5.5.1" } +grin_wallet_impls = { path = "../impls", version = "5.5.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } ##### Grin Imports diff --git a/impls/Cargo.toml b/impls/Cargo.toml index b93b32f..314510a 100644 --- a/impls/Cargo.toml +++ b/impls/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_impls" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Concrete types derived from libwallet traits" license = "Apache-2.0" @@ -47,9 +47,9 @@ hyper-util = { version = "0.1.20", features = ["tokio"] } http-body-util = "0.1.3" bytes = "1.11.1" -grin_wallet_util = { path = "../util", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } -grin_wallet_libwallet = { path = "../libwallet", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } +grin_wallet_libwallet = { path = "../libwallet", version = "5.5.1" } ##### Grin Imports diff --git a/libwallet/Cargo.toml b/libwallet/Cargo.toml index c6bfe82..824af61 100644 --- a/libwallet/Cargo.toml +++ b/libwallet/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_libwallet" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format." license = "Apache-2.0" @@ -42,8 +42,8 @@ num-bigint = "0.2" chacha20 = "0.8.1" hmac = { version = "0.12.0", features = ["std"]} -grin_wallet_util = { path = "../util", version = "5.5.0" } -grin_wallet_config = { path = "../config", version = "5.5.0" } +grin_wallet_util = { path = "../util", version = "5.5.1" } +grin_wallet_config = { path = "../config", version = "5.5.1" } ##### Grin Imports diff --git a/util/Cargo.toml b/util/Cargo.toml index 898522d..2bf7192 100644 --- a/util/Cargo.toml +++ b/util/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "grin_wallet_util" -version = "5.5.0" +version = "5.5.1" authors = ["Grin Developers "] description = "Util, for generic utilities and to re-export grin crates" license = "Apache-2.0" From 6f24b5dff002d12302fd5091ed1445c14ddda71e Mon Sep 17 00:00:00 2001 From: ardocrat Date: Mon, 12 Oct 2026 14:01:47 +0300 Subject: [PATCH 35/39] build: remove conflict test, update grin submodule --- libwallet/src/address.rs | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index 013fd5d..d4f9dfe 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -65,16 +65,3 @@ mod tests { assert_eq!(address_derivation_path(&parent, 3), expected); } } - -#[cfg(test)] -mod tests { - use super::*; - use grin_keychain::ExtKeychain; - - #[test] - fn slatepack_address_path() { - let parent = ExtKeychain::derive_key_id(2, 2, 0, 0, 0); - let expected = ExtKeychain::derive_key_id(3, 2, 1, 3, 0); - assert_eq!(address_derivation_path(&parent, 3), expected); - } -} From b8ddf130016a95dec4b975da23d437a3d745cbb6 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Tue, 13 Oct 2026 16:41:29 +0300 Subject: [PATCH 36/39] Slatepack address index on send (#821) * Store address_index into tx log entry to get address and decrypt slatepack message, increment over all values * Provide address index on send and issue_invoice command * Keep 0 index for receive * Use sender address index at payment proof Rust API users need to update to SlatepackAddressIndex and the Slatepack methods Keep a wallet database backup for pending transactions and saved address indices. Seed recovery alone does not restore these, and the address counter restarts at 1. --- Cargo.lock | 1 + Cargo.toml | 1 + api/src/owner.rs | 113 +++++--- api/src/owner_rpc.rs | 29 ++- controller/src/command.rs | 138 +++++----- controller/src/controller.rs | 6 +- controller/src/display.rs | 5 +- controller/tests/file.rs | 3 +- controller/tests/payment_proofs.rs | 5 +- controller/tests/self_send.rs | 5 +- controller/tests/slatepack.rs | 391 +++++++++++++++++++++------- impls/src/adapters/mod.rs | 2 - impls/src/adapters/slatepack.rs | 179 ------------- impls/src/lib.rs | 3 +- libwallet/src/address.rs | 19 +- libwallet/src/api_impl/foreign.rs | 7 +- libwallet/src/api_impl/owner.rs | 351 ++++++++++++++++++------- libwallet/src/api_impl/types.rs | 20 +- libwallet/src/backend.rs | 67 ++++- libwallet/src/internal/selection.rs | 1 + libwallet/src/internal/tx.rs | 11 +- libwallet/src/lib.rs | 4 +- libwallet/src/slate.rs | 31 ++- libwallet/src/slatepack/armor.rs | 6 +- libwallet/src/slatepack/mod.rs | 29 ++- libwallet/src/slatepack/packer.rs | 121 --------- libwallet/src/slatepack/types.rs | 80 +++++- libwallet/src/types.rs | 9 +- src/bin/grin-wallet.yml | 10 + src/cmd/wallet_args.rs | 132 +++++----- tests/cmd_line_basic.rs | 127 +++++++++ 31 files changed, 1171 insertions(+), 735 deletions(-) delete mode 100644 impls/src/adapters/slatepack.rs delete mode 100644 libwallet/src/slatepack/packer.rs diff --git a/Cargo.lock b/Cargo.lock index a300f30..d6452a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2457,6 +2457,7 @@ dependencies = [ "serde_json", "thiserror 1.0.69", "url", + "uuid", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index ea2bfd4..11b3e21 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ linefeed = "0.6" semver = "1.0.28" rustyline = "9" lazy_static = "1" +uuid = { version = "1.23.4", features = ["v4"] } grin_wallet_api = { path = "./api", version = "5.5.0" } grin_wallet_impls = { path = "./impls", version = "5.5.0" } diff --git a/api/src/owner.rs b/api/src/owner.rs index aecde62..368b999 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -23,10 +23,11 @@ use crate::keychain::{Identifier, Keychain}; use crate::libwallet::api_impl::owner_updater::{start_updater_log_thread, StatusMessage}; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::api_impl::{owner, owner_updater}; +use crate::libwallet::wallet_lock; use crate::libwallet::{ AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, - TxLogEntry, ViewWallet, WalletInfo, WalletLCProvider, + TxLogEntry, ViewWallet, WalletBackend, WalletInfo, WalletLCProvider, }; use crate::util::logger::LoggingConfig; use crate::util::secp::{key::SecretKey, pedersen::Commitment}; @@ -35,12 +36,12 @@ use grin_wallet_config::config::{ reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME, }; use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use grin_wallet_libwallet::RetrieveTxQueryArgs; use grin_wallet_util::OnionV3Address; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; -use libwallet::wallet_lock; use std::convert::TryFrom; use std::fs::File; use std::io::Write; @@ -782,7 +783,7 @@ where pub fn init_send_tx( &self, keychain_mask: Option<&SecretKey>, - args: InitTxArgs, + mut args: InitTxArgs, ) -> Result { let send_args = args.send_args.clone(); let dest = match send_args.as_ref() { @@ -797,6 +798,18 @@ where .map(|_| crate::tor_config::load(&self.config_path())) .transpose()?; + let init_send_tx = |w: &mut WalletBackend, args: &mut InitTxArgs| { + if args.address_index.is_none() && args.estimate_only != Some(true) { + let parent_key_id = match &args.src_acct_name { + Some(name) => w.get_acct_path(name.clone())?.map(|account| account.path), + None => None, + } + .unwrap_or_else(|| w.parent_key_id()); + args.address_index = Some(w.next_tx_slatepack_address_index(&parent_key_id)?); + } + owner::init_send_tx(w, keychain_mask, args.clone(), self.doctest_mode) + }; + // Helper functionality. If send arguments exist, attempt to send sync and // finalize match send_args { @@ -804,7 +817,7 @@ where let slate = { wallet_lock!(self.wallet_inst, w); let late_lock = args.late_lock.unwrap_or(false); - let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + let slate = init_send_tx(w, &mut args)?; let tc = tor_config.as_ref().ok_or_else(|| { Error::TorConfig("Tor config was not loaded with send arguments".into()) })?; @@ -815,12 +828,29 @@ where if !late_lock { owner::tx_lock_outputs(w, keychain_mask, &slate)?; } + slate }; - let res = - try_slatepack_sync_workflow(&slate, &dest.unwrap(), tor_config, None, false); + let res = try_slatepack_sync_workflow( + &slate, + dest.as_ref().unwrap(), + tor_config, + None, + false, + ); match res { Ok(s) => { + // Output slatepack message to file. + match output_slatepack_file( + self, + keychain_mask, + &s, + dest, + args.address_index, + ) { + Ok(_) => {} + Err(e) => error!("Error on saving output slatepack message: {}", e), + } let ret_slate = self.finalize_tx(keychain_mask, &s)?; if sa.post_tx { let result = self.post_tx(keychain_mask, &ret_slate, sa.fluff); @@ -846,7 +876,7 @@ where } None => { wallet_lock!(self.wallet_inst, w); - let slate = owner::init_send_tx(w, keychain_mask, args, self.doctest_mode)?; + let slate = init_send_tx(w, &mut args)?; Ok(slate) } } @@ -938,7 +968,7 @@ where /// let mut api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// /// // . . . - /// // The slate has been recieved from the invoicer, somehow + /// // The slate has been received from the invoicer, somehow /// # let slate = Slate::blank(2, true); /// let args = InitTxArgs { /// src_acct_name: None, @@ -970,19 +1000,17 @@ where } _ => None, }; - let (slate, tor_config) = { + let tor_config = send_args + .as_ref() + .map(|_| crate::tor_config::load(&self.config_path())) + .transpose()?; + let slate = { let mut w_lock = self.wallet_inst.lock(); - let tor_config = send_args - .as_ref() - .map(|_| crate::tor_config::load(&self.config_path())) - .transpose()?; let w = w_lock.lc_provider()?.wallet_inst()?; - let slate = - owner::process_invoice_tx(w, keychain_mask, slate, args, self.doctest_mode)?; - (slate, tor_config) + owner::process_invoice_tx(w, keychain_mask, slate, args.clone(), self.doctest_mode)? }; // Helper functionality. If send arguments exist, attempt to send - match send_args { + match send_args.as_ref() { Some(sa) => { let tc = tor_config.ok_or_else(|| { Error::TorConfig("Tor config was not loaded with send arguments".into()) @@ -1006,7 +1034,13 @@ where } } // Output slatepack message to file. - match output_slatepack_file(self, keychain_mask, &s, Some(dest)) { + match output_slatepack_file( + self, + keychain_mask, + &s, + Some(dest), + args.address_index, + ) { Ok(_) => {} Err(e) => error!("Error on saving output slatepack message: {}", e), } @@ -2193,7 +2227,7 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `derivation_index` - The index along the derivation path to retrieve an address for + /// * `derivation_index` - The index along the derivation path to retrieve an address for, should be not higher than 2^31 - 1 /// /// # Returns /// * Ok with a SlatepackAddress representing the address @@ -2205,13 +2239,14 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// /// // Set up as above /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// - /// let res = api_owner.get_slatepack_address(None, 0); + /// let res = api_owner.get_slatepack_address(None, SlatepackAddressIndex(0)); /// /// if let Ok(_) = res { /// // ... @@ -2221,7 +2256,7 @@ where pub fn get_slatepack_address( &self, keychain_mask: Option<&SecretKey>, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { owner::get_slatepack_address(self.wallet_inst.clone(), keychain_mask, derivation_index) } @@ -2231,9 +2266,8 @@ where /// /// # Arguments /// - /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `derivation_index` - The index along the derivation path to for which to retrieve the secret key - /// + /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using + /// * `derivation_index` - The index along the derivation path to for which to retrieve the secret key, should be not higher than 2^31 - 1 /// # Returns /// * Ok with an ed25519_dalek::SecretKey if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered. @@ -2244,13 +2278,14 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// /// // Set up as above /// # let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// - /// let res = api_owner.get_slatepack_secret_key(None, 0); + /// let res = api_owner.get_slatepack_secret_key(None, SlatepackAddressIndex(0)); /// /// if let Ok(_) = res { /// // ... @@ -2260,7 +2295,7 @@ where pub fn get_slatepack_secret_key( &self, keychain_mask: Option<&SecretKey>, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { owner::get_slatepack_secret_key(self.wallet_inst.clone(), keychain_mask, derivation_index) } @@ -2271,7 +2306,7 @@ where /// # Arguments /// /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if - /// * `sender_index` - If Some(n), the index along the derivation path to include as the sender + /// * `sender_index` - If Some(n), the index along the derivation path to include as the sender, should be not higher than 2^31 - 1 /// * `recipients` - Optional recipients for which to encrypt the slatepack's payload (i.e. the /// slate). If an empty vec, the payload will remain unencrypted /// @@ -2285,6 +2320,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2310,7 +2346,7 @@ where /// let slatepack = api_owner.create_slatepack_message( /// None, /// &slate, - /// Some(0), + /// Some(SlatepackAddressIndex(0)), /// vec![], /// ); /// } @@ -2320,7 +2356,7 @@ where &self, keychain_mask: Option<&SecretKey>, slate: &Slate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result { owner::create_slatepack_message( @@ -2340,8 +2376,7 @@ where /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// * `slatepack` - A string representing an armored slatepack /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt - /// decryption. This function will attempt to use secret keys at each index along this path - /// to attempt to decrypt the payload, returning an error if none of the keys match. + /// decryption. This function will attempt to use secret keys at each index along this path to attempt to decrypt the payload, returning an error if none of the keys match. Should be not higher than 2^31 - 1 each. /// /// # Returns /// * Ok with a [Slate](../grin_wallet_libwallet/slate/struct.Slate.html) if successful @@ -2353,6 +2388,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2363,14 +2399,14 @@ where /// let res = api_owner.slate_from_slatepack_message( /// None, /// slatepack_string, - /// vec![0, 1, 2], + /// vec![SlatepackAddressIndex(0), SlatepackAddressIndex(1), SlatepackAddressIndex(2)], /// ); /// ``` pub fn slate_from_slatepack_message( &self, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { owner::slate_from_slatepack_message( self.wallet_inst.clone(), @@ -2389,8 +2425,7 @@ where /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using /// * `slatepack` - A string representing an armored slatepack /// * `secret_indices` - Indices along this wallet's derivation path with which to attempt - /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned - /// Slatepack will remain encrypted. + /// decryption. If this wallet can't decrypt this slatepack, the payload of the returned Slatepack will remain encrypted. Should be not higher than 2^31 - 1 each. /// /// # Returns /// * Ok with a [Slatepack](../grin_wallet_libwallet/slatepack/types/struct.Slatepack.html) if successful @@ -2402,6 +2437,7 @@ where /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); /// /// use grin_core::global::ChainTypes; + /// use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// /// use std::time::Duration; /// @@ -2412,7 +2448,7 @@ where /// let res = api_owner.decode_slatepack_message( /// None, /// slatepack_string, - /// vec![0, 1, 2], + /// vec![SlatepackAddressIndex(0), SlatepackAddressIndex(1), SlatepackAddressIndex(2)], /// ); /// /// ``` @@ -2420,7 +2456,7 @@ where &self, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { owner::decode_slatepack_message( self.wallet_inst.clone(), @@ -2758,6 +2794,7 @@ fn output_slatepack_file( keychain_mask: Option<&SecretKey>, slate: &Slate, dest: Option, + sender_index: Option, ) -> Result<(), Error> where L: WalletLCProvider<'static, C, K> + 'static, @@ -2769,7 +2806,7 @@ where Some(a) => vec![a], None => vec![], }; - let message = api.create_slatepack_message(keychain_mask, slate, Some(0), recipients)?; + let message = api.create_slatepack_message(keychain_mask, slate, sender_index, recipients)?; let tld = api.get_top_level_directory()?; // Create a directory to which files will be output. diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 367f82d..6532e24 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -33,6 +33,7 @@ use crate::util::secp::pedersen::Commitment; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; use crate::{ECDHPubkey, Ed25519SecretKey, Owner, Token}; use grin_wallet_util::OnionV3Address; +use libwallet::slatepack::SlatepackAddressIndex; use rand::thread_rng; use std::convert::TryFrom; use std::path::PathBuf; @@ -359,6 +360,7 @@ pub trait OwnerRpc { true, [ { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -380,6 +382,7 @@ pub trait OwnerRpc { "tx_type": "ConfirmedCoinbase" }, { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -451,6 +454,7 @@ pub trait OwnerRpc { true, [ { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -472,6 +476,7 @@ pub trait OwnerRpc { "tx_type": "ConfirmedCoinbase" }, { + "address_index": null, "amount_credited": "60000000000", "amount_debited": "0", "confirmation_ts": "2019-01-15T16:01:26Z", @@ -598,7 +603,7 @@ pub trait OwnerRpc { "id": "0436430c-2b02-624c-2032-570501212b00", "proof": { "raddr": "32cdd63928854f8b2628b1dce4626ddcdf35d56cb7cfdf7d64cca5822b78d4d3", - "saddr": "32cdd63928854f8b2628b1dce4626ddcdf35d56cb7cfdf7d64cca5822b78d4d3" + "saddr": "4b2adcc4efc1d547c08ed7c9f7d987ff085f1788d62805e73c8f632e4b065039" }, "sigs": [ { @@ -1706,7 +1711,7 @@ pub trait OwnerRpc { fn get_slatepack_address( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result; /** @@ -1740,7 +1745,7 @@ pub trait OwnerRpc { fn get_slatepack_secret_key( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result; /** @@ -1790,7 +1795,7 @@ pub trait OwnerRpc { &self, token: Token, slate: VersionedSlate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result; @@ -1844,7 +1849,7 @@ pub trait OwnerRpc { &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result; /** @@ -1885,7 +1890,7 @@ pub trait OwnerRpc { &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result; /** @@ -1917,6 +1922,7 @@ pub trait OwnerRpc { "recipient_address": "tgrin10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqq6t83r", "recipient_sig": "02868f2d2b983981f8f98043701687a8531ed2de564ea3df48e9e7e0229ccbe8359efe506896df2efbe3528e977252c50e4a41ca3cc9896e7c5a30bbb1d33604", "sender_address": "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "sender_address_path": 0, "sender_sig": "c511764f3f61ed3d1cbca9514df8bc6811fad5662b1cb0e0587b9c9e49db9f33183cce71af6cb24b507fabf525a2bc405c6e84e63a60334edff0b451ae5e6102" } } @@ -1949,6 +1955,7 @@ pub trait OwnerRpc { "recipient_address": "tgrin10qlk22rxjap2ny8qltc2tl996kenxr3hhwuu6hrzs6tdq08yaqgqq6t83r", "recipient_sig": "02868f2d2b983981f8f98043701687a8531ed2de564ea3df48e9e7e0229ccbe8359efe506896df2efbe3528e977252c50e4a41ca3cc9896e7c5a30bbb1d33604", "sender_address": "tgrin1xtxavwfgs48ckf3gk8wwgcndmn0nt4tvkl8a7ltyejjcy2mc6nfs9gm2lp", + "sender_address_path": 0, "sender_sig": "c511764f3f61ed3d1cbca9514df8bc6811fad5662b1cb0e0587b9c9e49db9f33183cce71af6cb24b507fabf525a2bc405c6e84e63a60334edff0b451ae5e6102" } }, @@ -2424,7 +2431,7 @@ where fn get_slatepack_address( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { Owner::get_slatepack_address(self, token.keychain_mask.as_ref(), derivation_index) } @@ -2432,7 +2439,7 @@ where fn get_slatepack_secret_key( &self, token: Token, - derivation_index: u32, + derivation_index: SlatepackAddressIndex, ) -> Result { let key = Owner::get_slatepack_secret_key(self, token.keychain_mask.as_ref(), derivation_index)?; @@ -2443,7 +2450,7 @@ where &self, token: Token, slate: VersionedSlate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result { let res = Owner::create_slatepack_message( @@ -2460,7 +2467,7 @@ where &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { let slate = Owner::slate_from_slatepack_message( self, @@ -2476,7 +2483,7 @@ where &self, token: Token, message: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result { Owner::decode_slatepack_message(self, token.keychain_mask.as_ref(), message, secret_indices) } diff --git a/controller/src/command.rs b/controller/src/command.rs index 54abd74..3962cdb 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -19,19 +19,20 @@ use crate::apiwallet::{try_slatepack_sync_workflow, Owner}; use crate::config::{TorConfig, WalletConfig, WALLET_CONFIG_FILE_NAME}; use crate::core::{core, global}; use crate::error::Error; -use crate::impls::PathToSlatepack; -use crate::impls::SlateGetter as _; use crate::keychain; +use crate::libwallet::api_impl::owner::{self, decrypt_slatepack, deserialize_slatepack}; use crate::libwallet::api_impl::types::update_tx_slate_state; +use crate::libwallet::slatepack::get_slatepack_file_contents; +use crate::libwallet::slatepack::SlatepackAddressIndex; use crate::libwallet::{ self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack, - SlatepackAddress, Slatepacker, SlatepackerArgs, WalletLCProvider, + SlatepackAddress, WalletLCProvider, }; +use crate::libwallet::{wallet_lock, WalletHandle}; use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; use crate::{controller, display}; -use grin_wallet_libwallet::wallet_lock; use qr_code::QrCode; use serde_json as json; use std::fs::File; @@ -341,6 +342,7 @@ pub struct SendArgs { pub outfile: Option, pub bridge: Option, pub slatepack_qr: bool, + pub address_index: Option, } fn max_retry_args(mut init_args: InitTxArgs, amount: u64, max_inputs: u32) -> InitTxArgs { @@ -412,6 +414,7 @@ where selection_strategy_is_use_all: strategy == "all", refresh_outputs_from_node: !info_updated, estimate_only: Some(true), + address_index: args.address_index, ..Default::default() }; let result = owner_api.init_send_tx(keychain_mask, init_args.clone()); @@ -456,6 +459,7 @@ where payment_proof_recipient_address, ttl_blocks: args.ttl_blocks, late_lock: Some(args.late_lock), + address_index: args.address_index, ..Default::default() }; let init_send_tx = |init_args: InitTxArgs| -> Result { @@ -505,6 +509,11 @@ where } let output_sp = |owner_api: &mut Owner, lock_outputs: bool| -> Result<(), Error> { + let sender_index = { + wallet_lock!(owner_api.wallet_inst, w); + let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + context.payment_proof_derivation_index + }; Ok(output_slatepack( owner_api, keychain_mask, @@ -514,6 +523,7 @@ where lock_outputs, false, args.slatepack_qr, + sender_index, )?) }; @@ -567,6 +577,7 @@ pub fn output_slatepack( lock: bool, finalizing: bool, show_qr: bool, + sender_index: Option, ) -> Result<(), libwallet::Error> where L: WalletLCProvider<'static, C, K> + 'static, @@ -579,7 +590,8 @@ where Some(a) => vec![a], None => vec![], }; - let message = owner_api.create_slatepack_message(keychain_mask, slate, Some(0), recipients)?; + let message = + owner_api.create_slatepack_message(keychain_mask, slate, sender_index, recipients)?; let tld = owner_api.get_top_level_directory()?; // create a directory to which files will be output @@ -653,42 +665,30 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let mut ret_address = None; - let slate = match filename { + let (slate, sender_address) = match filename { Some(f) => { // otherwise, get slate from slatepack - let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: Some(&dec_key), - }); - let pts = PathToSlatepack::new(f.into(), &packer, true); - let sl = Some(pts.get_tx()?.0); - ret_address = pts.get_slatepack(true)?.sender; - sl + let data = get_slatepack_file_contents(&f.into())?; + let sp = deserialize_slatepack( + &data, + owner_api.wallet_inst.clone(), + keychain_mask, + vec![SlatepackAddressIndex(0)], + )?; + let sl = sp.get_slate()?; + (sl, sp.sender) } - None => None, - }; - - let slate = match slate { - Some(s) => s, None => { // try and parse directly from input_slatepack_message match message { Some(message) => { - let slate = owner_api.slate_from_slatepack_message( + let sp = owner_api.decode_slatepack_message( keychain_mask, message.clone(), - vec![0], + vec![SlatepackAddressIndex(0)], )?; - let slatepack = owner_api.decode_slatepack_message( - keychain_mask, - message.clone(), - vec![0], - )?; - ret_address = slatepack.sender; - slate + let sl = sp.get_slate()?; + (sl, sp.sender) } None => { let msg = "No slate provided via file or direct input"; @@ -697,7 +697,7 @@ where } } }; - Ok((slate, ret_address)) + Ok((slate, sender_address)) } /// Receive command argument @@ -775,6 +775,7 @@ where false, false, args.slatepack_qr, + None, )?) }; @@ -790,8 +791,7 @@ where Ok(s) => { // Update slate state. { - let mut w_lock = owner_api.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + wallet_lock!(owner_api.wallet_inst, w); let parent_key_id = w.parent_key_id(); match update_tx_slate_state(w, keychain_mask, &parent_key_id, &s) { Ok(_) => {} @@ -814,25 +814,18 @@ where } pub fn read_slatepack(args: ReceiveArgs) -> Result { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let slatepack = match args.input_file { - Some(f) => PathToSlatepack::new(f.into(), &packer, true).get_slatepack(false)?, + let data = match args.input_file { + Some(f) => get_slatepack_file_contents(&f.into())?, None => match args.input_slatepack_message { - Some(message) => packer.deser_slatepack(message.as_bytes(), false)?, - None => { - return Err(Error::ArgumentError("Invalid Slatepack Input".into())); - } + Some(message) => message.into_bytes(), + None => return Err(Error::ArgumentError("Invalid Slatepack Input".into())), }, }; - Ok(slatepack) + Ok(owner::parse_slatepack(&data)?) } pub fn unpack( - owner_api: &mut Owner, + wallet_inst: WalletHandle<'static, L, C, K>, keychain_mask: Option<&SecretKey>, mut slatepack: Slatepack, ) -> Result<(), Error> @@ -847,33 +840,32 @@ where println!("{}", slatepack); println!("------------------"); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - if slatepack.mode == 1 { - let dec_key = owner_api.get_slatepack_secret_key(keychain_mask, 0)?; - match slatepack.try_decrypt_payload(Some(&dec_key)) { - Ok(_) => { + match decrypt_slatepack( + &mut slatepack, + wallet_inst, + keychain_mask, + vec![SlatepackAddressIndex(0)], + ) + .and_then(|_| slatepack.get_slate()) + { + Ok(s) => { println!("Slatepack is encrypted for this wallet"); println!(); println!("DECRYPTED SLATEPACK"); println!("-------------------"); println!("{}", slatepack); - let slate = packer.get_slate(&slatepack)?; println!(); println!("DECRYPTED SLATE"); println!("---------------"); - println!("{}", slate); + println!("{}", s); } Err(_) => { println!("Slatepack payload cannot be decrypted by this wallet"); } } } else { - let slate = packer.get_slate(&slatepack)?; + let slate = slatepack.get_slate()?; println!("Slatepack is not encrypted"); println!(); println!("SLATE"); @@ -904,7 +896,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let (mut slate, _ret_address) = parse_slatepack( + let (mut slate, _) = parse_slatepack( owner_api, keychain_mask, args.input_file.clone(), @@ -975,6 +967,7 @@ where false, true, args.slatepack_qr, + None, )?; Ok(()) @@ -984,11 +977,11 @@ where pub struct IssueInvoiceArgs { /// Slatepack address pub dest: Option, - /// issue invoice tx args + /// Issue invoice tx args pub issue_args: IssueInvoiceTxArgs, - /// output file override + /// Output file override pub outfile: Option, - /// show slatepack as QR code + /// Show slatepack as QR code pub slatepack_qr: bool, } @@ -1009,8 +1002,13 @@ where .transpose()?; let issue_args = args.issue_args.clone(); - let slate = owner_api.issue_invoice_tx(keychain_mask, issue_args)?; + let slate = owner_api.issue_invoice_tx(keychain_mask, issue_args.clone())?; + let sender_index = { + wallet_lock!(owner_api.wallet_inst, w); + let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?; + context.payment_proof_derivation_index + }; output_slatepack( owner_api, keychain_mask, @@ -1020,6 +1018,7 @@ where false, false, args.slatepack_qr, + sender_index, )?; Ok(()) } @@ -1133,6 +1132,7 @@ where true, false, args.slatepack_qr, + None, )?) }; @@ -1314,7 +1314,7 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - let (slate, _ret_address) = parse_slatepack( + let (slate, _) = parse_slatepack( owner_api, keychain_mask, args.input_file, @@ -1462,7 +1462,7 @@ where } } -/// Payment Proof Address +/// Show wallet's slatepack address. pub fn address( owner_api: &mut Owner, keychain_mask: Option<&SecretKey>, @@ -1472,8 +1472,10 @@ where C: NodeClient + 'static, K: keychain::Keychain + 'static, { - // Just address at derivation index 0 for now - let address = owner_api.get_slatepack_address(keychain_mask, 0)?; + // Just address at derivation index 0 for now, + // cause sender encrypts message for address, + // and we don't know its derivation path index. + let address = owner_api.get_slatepack_address(keychain_mask, SlatepackAddressIndex(0))?; let account = account_label(owner_api)?; println!(); println!("Address for account - {}", account); diff --git a/controller/src/controller.rs b/controller/src/controller.rs index 6e5ad91..bfb4970 100644 --- a/controller/src/controller.rs +++ b/controller/src/controller.rs @@ -55,6 +55,7 @@ use grin_wallet_config::config::{ }; use grin_wallet_impls::tor::arti::{start_tor_service, stop_tor_service}; use grin_wallet_impls::tor::process::TorProcess; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use http_body_util::{BodyExt, Full}; use hyper::body::Incoming; use tokio::sync::mpsc; @@ -255,8 +256,9 @@ where let w_inst = lc.wallet_inst()?; let k = w_inst.keychain(mask.as_ref())?; let parent_key_id = w_inst.parent_key_id(); - let sec_key = address::address_from_derivation_path(&k, &parent_key_id, 0) - .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; + let sec_key = + address::address_from_derivation_path(&k, &parent_key_id, SlatepackAddressIndex(0)) + .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; let tor_dir = format!("{}/tor/listener", lc.get_top_level_directory()?); let onion_address = OnionV3Address::from_private(&sec_key.0) .map_err(|e| Error::TorConfig(format!("{:?}", e)))?; diff --git a/controller/src/display.rs b/controller/src/display.rs index 99af9ea..d5cf1f8 100644 --- a/controller/src/display.rs +++ b/controller/src/display.rs @@ -20,7 +20,7 @@ use crate::libwallet::{ TxLogEntry, TxLogEntryType, ViewWallet, WalletInfo, }; use crate::util::ToHex; - +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use prettytable; use prettytable::format::{FormatBuilder, LinePosition, LineSeparator}; use std::io::prelude::Write; @@ -541,7 +541,8 @@ pub fn accounts(acct_mappings: Vec) { bMG->"Spendable balance", ]); for m in acct_mappings { - let slatepack_path = address::address_derivation_path(&m.path, 0).to_bip_32_string(); + let slatepack_path = + address::address_derivation_path(&m.path, SlatepackAddressIndex(0)).to_bip_32_string(); let spendable = if let Some(info) = m.info { amount_to_hr_string(info.amount_currently_spendable, true) } else { diff --git a/controller/tests/file.rs b/controller/tests/file.rs index 6f6d445..71509df 100644 --- a/controller/tests/file.rs +++ b/controller/tests/file.rs @@ -32,6 +32,7 @@ use grin_wallet_libwallet::{InitTxArgs, IssueInvoiceTxArgs}; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// self send impl fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), libwallet::Error> { @@ -235,7 +236,7 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(), format!("{}/standard_pp_S3.txbin", test_dir), ), }; - let address = Some(api2.get_slatepack_address(mask2, 0)?); + let address = Some(api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?); // send to send let args = InitTxArgs { diff --git a/controller/tests/payment_proofs.rs b/controller/tests/payment_proofs.rs index 51bb034..b72b98e 100644 --- a/controller/tests/payment_proofs.rs +++ b/controller/tests/payment_proofs.rs @@ -28,6 +28,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// Various tests on accounts within the same wallet fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -78,7 +79,7 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let address = Some(api2.get_slatepack_address(mask2, 0)?); + let address = Some(api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?); println!("Public address is: {:?}", address); let amount = 60_000_000_000; @@ -121,7 +122,7 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err slate_i.payment_proof.as_ref().unwrap().receiver_address ); assert!(pp.receiver_signature.is_some()); - assert_eq!(pp.sender_address_path, 0); + assert_eq!(pp.sender_address_path, SlatepackAddressIndex(1)); assert_eq!(pp.sender_signature, None); // check we should get an error at this point since proof is not complete diff --git a/controller/tests/self_send.rs b/controller/tests/self_send.rs index c7ab5af..0c18640 100644 --- a/controller/tests/self_send.rs +++ b/controller/tests/self_send.rs @@ -30,6 +30,7 @@ use std::time::Duration; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; /// self send impl fn self_send_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { @@ -171,7 +172,9 @@ fn late_lock_self_send_proof() -> Result<(), libwallet::Error> { amount: core::consensus::REWARD, minimum_confirmations: 2, late_lock: Some(true), - payment_proof_recipient_address: Some(api1.get_slatepack_address(mask1, 0)?), + payment_proof_recipient_address: Some( + api1.get_slatepack_address(mask1, SlatepackAddressIndex(0))?, + ), ..Default::default() }, )?; diff --git a/controller/tests/slatepack.rs b/controller/tests/slatepack.rs index b7fb10f..2aeb115 100644 --- a/controller/tests/slatepack.rs +++ b/controller/tests/slatepack.rs @@ -20,25 +20,30 @@ extern crate grin_wallet_impls as impls; use grin_core as core; use grin_wallet_config::GlobalWalletConfig; use grin_wallet_libwallet as libwallet; -use std::path::PathBuf; - use impls::test_framework::{self, LocalWalletClient}; -use impls::{PathToSlatepack, SlatePutter as _}; +use impls::DefaultLCProvider; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; use std::sync::atomic::Ordering; -use std::thread; use std::time::Duration; +use std::{fs, thread}; use grin_wallet_libwallet::{ - InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs, Slate, Slatepack, SlatepackAddress, - Slatepacker, SlatepackerArgs, + slatepack, Error, InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs, Slate, Slatepack, + SlatepackAddress, SlatepackBin, WalletHandle, }; -use ed25519_dalek::SigningKey as edDalekSecretKey; use ed25519_dalek::VerifyingKey as edDalekPublicKey; #[macro_use] mod common; use common::{clean_output_dir, create_wallet_proxy, setup}; +use grin_keychain::ExtKeychain; +use grin_util::secp::SecretKey; +use grin_wallet_libwallet::api_impl::owner::{decrypt_slatepack, deserialize_slatepack}; +use grin_wallet_libwallet::slatepack::{get_slatepack_file_contents, SlatepackAddressIndex}; +use grin_wallet_util::byte_ser; fn output_slatepack( slate: &Slate, @@ -47,35 +52,55 @@ fn output_slatepack( use_bin: bool, sender: Option, recipients: Vec, -) -> Result<(), libwallet::Error> { - let packer = Slatepacker::new(SlatepackerArgs { - sender, - recipients, - dec_key: None, - }); +) -> Result<(), Error> { let mut file = file.into(); if armored { file = format!("{}.armored", file); } - PathToSlatepack::new(file.into(), &packer, armored).put_tx(slate, use_bin) + let slatepack = slate.create_slatepack(sender, recipients)?; + let mut pub_tx = File::create(&file)?; + if use_bin { + if armored { + let armored = slatepack.armor()?; + pub_tx.write_all(armored.as_bytes())?; + } else { + pub_tx.write_all( + &byte_ser::to_bytes(&SlatepackBin(slatepack)).map_err(|_| Error::SlatepackSer)?, + )?; + } + } else { + pub_tx.write_all( + serde_json::to_string_pretty(&slatepack) + .map_err(|_| Error::SlateSer)? + .as_bytes(), + )?; + } + pub_tx.sync_all()?; + Ok(()) } fn slate_from_packed( + wallet_inst: WalletHandle< + DefaultLCProvider, + LocalWalletClient, + ExtKeychain, + >, + keychain_mask: Option<&SecretKey>, file: &str, armored: bool, - dec_key: Option<&edDalekSecretKey>, -) -> Result<(Slatepack, Slate), libwallet::Error> { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key, - }); +) -> Result<(Slatepack, Slate), Error> { let mut file = file.into(); if armored { file = format!("{}.armored", file); } - let slatepack = PathToSlatepack::new(file.into(), &packer, armored).get_slatepack(true)?; - Ok((slatepack.clone(), packer.get_slate(&slatepack)?)) + let data = get_slatepack_file_contents(&file.into())?; + let slatepack = deserialize_slatepack( + &data, + wallet_inst, + keychain_mask, + vec![SlatepackAddressIndex(0)], + )?; + Ok((slatepack.clone(), slatepack.get_slate()?)) } /// self send impl @@ -84,7 +109,7 @@ fn slatepack_exchange_test_impl( use_bin: bool, use_armored: bool, use_encryption: bool, -) -> Result<(), libwallet::Error> { +) -> Result<(), Error> { // Create a new proxy to simulate server and wallet responses let mut wallet_proxy = create_wallet_proxy(test_dir); let chain = wallet_proxy.chain.clone(); @@ -134,41 +159,49 @@ fn slatepack_exchange_test_impl( api2.create_account_path(mask2, "account1")?; api2.create_account_path(mask2, "account2")?; - // Get some mining done { wallet_inst!(wallet1, w); w.set_account_by_name("mining")?; } + + { + wallet_inst!(wallet2, w); + w.set_account_by_name("account1")?; + } + + // Get some mining done let mut bh = 10u64; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); - let (recipients_1, dec_key_1, sender_1) = match use_encryption { + let (recipients_1, sender_1) = match use_encryption { true => { - let sec_key = api1.get_slatepack_secret_key(mask1, 0)?; + let sec_key = api1.get_slatepack_secret_key(mask1, SlatepackAddressIndex(0))?; let pub_key = edDalekPublicKey::from(&sec_key); let rec_address = SlatepackAddress::new(&pub_key); - ( - vec![rec_address.clone()], - Some(sec_key), - Some(rec_address.clone()), - ) + + let sen_index = SlatepackAddressIndex(7); + let sec_key = api1.get_slatepack_secret_key(mask1, sen_index)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let sen_address = SlatepackAddress::new(&pub_key); + (vec![rec_address.clone()], Some(sen_address.clone())) } - false => (vec![], None, None), + false => (vec![], None), }; - let (recipients_2, dec_key_2, sender_2) = match use_encryption { + let (recipients_2, sender_2) = match use_encryption { true => { - let sec_key = api2.get_slatepack_secret_key(mask2, 0)?; + let sec_key = api2.get_slatepack_secret_key(mask2, SlatepackAddressIndex(0))?; let pub_key = edDalekPublicKey::from(&sec_key); let rec_address = SlatepackAddress::new(&pub_key); - ( - vec![rec_address.clone()], - Some(sec_key), - Some(rec_address.clone()), - ) + + let sen_index = SlatepackAddressIndex(11); + let sec_key = api2.get_slatepack_secret_key(mask2, sen_index)?; + let pub_key = edDalekPublicKey::from(&sec_key); + let sen_address = SlatepackAddress::new(&pub_key); + (vec![rec_address.clone()], Some(sen_address.clone())) } - false => (vec![], None, None), + false => (vec![], None), }; let (send_file, receive_file, final_file) = match use_bin { @@ -190,7 +223,7 @@ fn slatepack_exchange_test_impl( assert_eq!(wallet1_info.total, bh * reward); // send to send let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), + address_index: Some(SlatepackAddressIndex(7)), amount: reward * 2, minimum_confirmations: 2, max_outputs: 500, @@ -210,14 +243,8 @@ fn slatepack_exchange_test_impl( )?; api1.tx_lock_outputs(mask1, &slate)?; - // Get some mining done - { - wallet_inst!(wallet2, w); - w.set_account_by_name("account1")?; - } - - let (mut slatepack, mut slate) = - slate_from_packed(&send_file, use_armored, dec_key_2.as_ref())?; + let (slatepack, mut slate) = + slate_from_packed(wallet2.clone(), mask2, &send_file, use_armored)?; // wallet 2 receives file, completes, sends file back wallet::controller::foreign_single_use( @@ -231,8 +258,8 @@ fn slatepack_exchange_test_impl( &receive_file, use_armored, use_bin, - // re-encrypt for sender! sender_2.clone(), + // re-encrypt for sender! match slatepack.sender.clone() { Some(s) => vec![s.clone()], None => vec![], @@ -243,23 +270,34 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - let (_, mut slate) = slate_from_packed(&receive_file, use_armored, dec_key_1.as_ref())?; + let (slatepack, mut slate) = + slate_from_packed(wallet1.clone(), mask1, &receive_file, use_armored)?; slate = api1.finalize_tx(mask1, &slate)?; // Output final file for reference - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + output_slatepack( + &slate, + &final_file, + use_armored, + use_bin, + sender_1.clone(), + match slatepack.sender { + Some(s) => vec![s.clone()], + None => vec![], + }, + )?; api1.post_tx(mask1, &slate, false)?; bh += 1; let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); bh += 3; - // Check total in mining account + // Check total in wallet 1 account let (wallet1_refreshed, wallet1_info) = api1.retrieve_summary_info(mask1, true, 1)?; assert!(wallet1_refreshed); assert_eq!(wallet1_info.last_confirmed_height, bh); assert_eq!(wallet1_info.total, bh * reward - reward * 2); - // Check total in 'wallet 2' account + // Check total in wallet 2 account let (wallet2_refreshed, wallet2_info) = api2.retrieve_summary_info(mask2, true, 1)?; assert!(wallet2_refreshed); assert_eq!(wallet2_info.last_confirmed_height, bh); @@ -281,10 +319,11 @@ fn slatepack_exchange_test_impl( }; let args = IssueInvoiceTxArgs { + address_index: Some(SlatepackAddressIndex(11)), amount: 1000000000, ..Default::default() }; - let mut slate = api2.issue_invoice_tx(mask2, args)?; + let slate = api2.issue_invoice_tx(mask2, args)?; output_slatepack( &slate, &send_file, @@ -303,9 +342,8 @@ fn slatepack_exchange_test_impl( selection_strategy_is_use_all: true, ..Default::default() }; - let res = slate_from_packed(&send_file, use_armored, dec_key_1.as_ref())?; - slatepack = res.0; - slate = res.1; + let (slatepack, mut slate) = + slate_from_packed(wallet1.clone(), mask1, &send_file, use_armored)?; slate = api1.process_invoice_tx(mask1, &slate, args)?; api1.tx_lock_outputs(mask1, &slate)?; output_slatepack( @@ -314,25 +352,16 @@ fn slatepack_exchange_test_impl( use_armored, use_bin, sender_1.clone(), - match slatepack.sender.clone() { + match slatepack.sender { Some(s) => vec![s.clone()], None => vec![], }, )?; - wallet::controller::foreign_single_use( - wallet2.clone(), - PathBuf::from(test_dir), - mask2_i.clone(), - |api| { - // Wallet 2 receives the invoice transaction - let res = slate_from_packed(&receive_file, use_armored, dec_key_2.as_ref())?; - slate = res.1; - slate = api.finalize_tx(&slate, false)?; - output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; - Ok(()) - }, - )?; - api1.post_tx(mask1, &slate, false)?; + // Wallet 2 receives the invoice transaction + let (_, mut slate) = slate_from_packed(wallet2.clone(), mask2, &receive_file, use_armored)?; + slate = api2.finalize_tx(mask2, &slate)?; + output_slatepack(&slate, &final_file, use_armored, use_bin, None, vec![])?; + api2.post_tx(mask2, &slate, false)?; // Standard, with payment proof let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false); @@ -349,17 +378,17 @@ fn slatepack_exchange_test_impl( ), }; - let address = Some(api2.get_slatepack_address(mask2, 0)?); - - // send to send + // send from 1st wallet let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), + address_index: Some(SlatepackAddressIndex(7)), amount: reward, minimum_confirmations: 2, max_outputs: 500, num_change_outputs: 1, selection_strategy_is_use_all: true, - payment_proof_recipient_address: address.clone(), + payment_proof_recipient_address: Some( + api2.get_slatepack_address(mask2, SlatepackAddressIndex(0))?, + ), ..Default::default() }; let mut slate = api1.init_send_tx(mask1, args)?; @@ -373,21 +402,21 @@ fn slatepack_exchange_test_impl( )?; api1.tx_lock_outputs(mask1, &slate)?; + // receive at 2nd wallet wallet::controller::foreign_single_use( wallet2.clone(), PathBuf::from(test_dir), mask2_i.clone(), |api| { - let res = slate_from_packed(&send_file, use_armored, dec_key_2.as_ref())?; - let slatepack = res.0; - slate = res.1; + let (slatepack, mut slate) = + slate_from_packed(wallet2.clone(), mask2, &send_file, use_armored)?; slate = api.receive_tx(&slate, None, None)?; output_slatepack( &slate, &receive_file, use_armored, use_bin, - sender_2, + sender_2.clone(), match slatepack.sender { Some(s) => vec![s.clone()], None => vec![], @@ -398,7 +427,7 @@ fn slatepack_exchange_test_impl( )?; // wallet 1 finalizes and posts - let res = slate_from_packed(&receive_file, use_armored, dec_key_1.as_ref())?; + let res = slate_from_packed(wallet1.clone(), mask1, &receive_file, use_armored)?; slate = res.1; slate = api1.finalize_tx(mask1, &slate)?; // Output final file for reference @@ -450,7 +479,6 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false); let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), amount: reward * 2, minimum_confirmations: 2, max_outputs: 500, @@ -458,15 +486,141 @@ fn slatepack_api_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { selection_strategy_is_use_all: true, ..Default::default() }; + for index in [SlatepackAddressIndex::MAX + 1, u32::MAX] { + assert!(matches!( + api1.init_send_tx( + mask1, + InitTxArgs { + address_index: Some(SlatepackAddressIndex(index)), + ..args.clone() + } + ), + Err(Error::SlatepackAddress(_)) + )); + assert!(matches!( + api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + address_index: Some(SlatepackAddressIndex(index)), + ..Default::default() + } + ), + Err(Error::SlatepackAddress(_)) + )); + } + api1.init_send_tx( + mask1, + InitTxArgs { + estimate_only: Some(true), + ..args.clone() + }, + )?; let slate = api1.init_send_tx(mask1, args)?; // create an encrypted slatepack (just encrypted for self) - let enc_addr = api1.get_slatepack_address(mask1, 0)?; - let slatepack = api1.create_slatepack_message(mask1, &slate, Some(0), vec![enc_addr])?; - println!("{}", slatepack); - let slatepack_raw = api1.decode_slatepack_message(mask1, slatepack.clone(), vec![0])?; - println!("{}", slatepack_raw); - let decoded_slate = api1.slate_from_slatepack_message(mask1, slatepack, vec![0])?; - println!("{}", decoded_slate); + let address_index = SlatepackAddressIndex(0); + let enc_addr = api1.get_slatepack_address(mask1, address_index)?; + let slatepack = + api1.create_slatepack_message(mask1, &slate, Some(address_index), vec![enc_addr])?; + let mut encrypted = api1.decode_slatepack_message(mask1, slatepack.clone(), vec![])?; + assert_eq!(encrypted.mode, 1); + decrypt_slatepack(&mut encrypted, wallet1.clone(), mask1, vec![address_index])?; + assert_eq!(encrypted.get_slate()?.id, slate.id); + let slatepack_raw = + api1.decode_slatepack_message(mask1, slatepack.clone(), vec![address_index])?; + assert_eq!(slatepack_raw.mode, 0); + assert_eq!(slatepack_raw.get_slate()?.id, slate.id); + let decoded_slate = api1.slate_from_slatepack_message(mask1, slatepack, vec![address_index])?; + assert_eq!(decoded_slate.id, slate.id); + + let unknown_index = SlatepackAddressIndex(77); + let unknown_address = api1.get_slatepack_address(mask1, unknown_index)?; + let message = api1.create_slatepack_message(mask1, &slate, None, vec![unknown_address])?; + let encrypted = api1.decode_slatepack_message(mask1, message.clone(), vec![])?; + let decoded = api1.decode_slatepack_message(mask1, message.clone(), vec![address_index])?; + assert_eq!(decoded.mode, 1); + assert_eq!(decoded.payload, encrypted.payload); + assert!(matches!( + api1.slate_from_slatepack_message(mask1, message.clone(), vec![address_index]), + Err(Error::SlatepackDecryption(_)) + )); + let mut api1 = api1; + assert!(matches!( + wallet::command::parse_slatepack(&mut api1, mask1, None, Some(message)), + Err(wallet::Error::LibWallet(Error::SlatepackDecryption(_))) + )); + + let index = { + wallet_inst!(wallet1, w); + w.get_private_context(mask1, slate.id.as_bytes())? + .payment_proof_derivation_index + .unwrap() + }; + assert_eq!(index, SlatepackAddressIndex(1)); + let address = api1.get_slatepack_address(mask1, index)?; + let message = api1.create_slatepack_message(mask1, &slate, None, vec![address])?; + let decoded = api1.decode_slatepack_message(mask1, message.clone(), vec![address_index])?; + assert_eq!(decoded.mode, 0); + assert_eq!(decoded.get_slate()?.id, slate.id); + + api1.create_account_path(mask1, "other")?; + api1.set_active_account(mask1, "other")?; + test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 6, false)?; + api1.set_active_account(mask1, "default")?; + let invoice = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + dest_acct_name: Some("other".into()), + ..Default::default() + }, + )?; + let send = api1.init_send_tx( + mask1, + InitTxArgs { + amount: reward, + src_acct_name: Some("other".into()), + minimum_confirmations: 2, + ..Default::default() + }, + )?; + api1.set_active_account(mask1, "other")?; + let next = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + ..Default::default() + }, + )?; + for (slate, expected) in [(&invoice, 1), (&send, 2), (&next, 3)] { + wallet_inst!(wallet1, w); + let context = w.get_private_context(mask1, slate.id.as_bytes())?; + assert_eq!(context.parent_key_id, w.parent_key_id()); + assert_eq!( + context.payment_proof_derivation_index, + Some(SlatepackAddressIndex(expected)) + ); + } + api1.set_active_account(mask1, "default")?; + let invoice = api1.issue_invoice_tx( + mask1, + IssueInvoiceTxArgs { + amount: reward, + ..Default::default() + }, + )?; + { + wallet_inst!(wallet1, w); + assert_eq!( + w.get_private_context(mask1, invoice.id.as_bytes())? + .payment_proof_derivation_index, + Some(SlatepackAddressIndex(2)) + ); + } + + api1.close_wallet(None)?; + let encrypted = api1.decode_slatepack_message(None, message, vec![])?; + assert_eq!(encrypted.mode, 1); // let logging finish stopper.store(false, Ordering::Relaxed); @@ -526,7 +680,6 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: )?; let args = InitTxArgs { - src_acct_name: Some("mining".to_owned()), amount: reward, minimum_confirmations: 2, max_outputs: 500, @@ -566,6 +719,15 @@ fn slatepack_address_validation(test_dir: &'static str) -> Result<(), libwallet: fluff: false, skip_tor: Some(true), }); + let missing_config = PathBuf::from(test_dir).join("missing.toml"); + let api = grin_wallet_api::Owner::new(wallet1.clone(), None, missing_config); + assert!(api + .process_invoice_tx(mask1, &slate, valid_args.clone()) + .is_err()); + { + wallet_inst!(wallet1, w); + assert!(w.get_private_context(mask1, slate.id.as_bytes()).is_err()); + } api1.process_invoice_tx(mask1, &slate, valid_args.clone())?; api1.init_send_tx(mask1, valid_args)?; @@ -660,3 +822,46 @@ fn slatepack_address() { } clean_output_dir(test_dir); } + +#[test] +fn slatepack_file_contents() { + let test_dir = "test_output/slatepack_file_contents"; + setup(test_dir); + + fs::create_dir_all(test_dir).unwrap(); + let sp_path = PathBuf::from(test_dir).join("pack_file"); + + // set Slatepack file to minimum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::min_size()).unwrap(); + } + + let mut pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_ok()); + + // set Slatepack file to maximum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::max_size()).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_ok()); + + // set Slatepack file below minimum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::min_size() - 1).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_err()); + + // set Slatepack file above maximum allowable size + { + let f = File::create(sp_path.clone()).unwrap(); + f.set_len(slatepack::max_size() + 1).unwrap(); + } + pack_path = get_slatepack_file_contents(&sp_path); + assert!(pack_path.is_err()); + clean_output_dir(test_dir); +} diff --git a/impls/src/adapters/mod.rs b/impls/src/adapters/mod.rs index 361009e..c59e122 100644 --- a/impls/src/adapters/mod.rs +++ b/impls/src/adapters/mod.rs @@ -13,11 +13,9 @@ // limitations under the License. mod file; -mod slatepack; pub mod tor; pub use self::file::PathToSlate; -pub use self::slatepack::PathToSlatepack; pub use self::tor::TorSlateSender; use crate::config::WalletConfig; diff --git a/impls/src/adapters/slatepack.rs b/impls/src/adapters/slatepack.rs deleted file mode 100644 index 88b6368..0000000 --- a/impls/src/adapters/slatepack.rs +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2021 The Grin Developers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/// Slatepack Output 'plugin' implementation -use std::fs::{metadata, File}; -use std::io::{Read, Write}; -use std::path::PathBuf; - -use crate::libwallet::{slatepack, Error, Slate, Slatepack, SlatepackBin, Slatepacker}; -use crate::{SlateGetter, SlatePutter}; -use grin_wallet_util::byte_ser; - -// And Slate putter impls to output to files -pub struct PathToSlatepack<'a> { - pub pathbuf: PathBuf, - pub packer: &'a Slatepacker<'a>, - pub armor_output: bool, -} - -impl<'a> PathToSlatepack<'a> { - /// Create with pathbuf and recipients - pub fn new(pathbuf: PathBuf, packer: &'a Slatepacker<'a>, armor_output: bool) -> Self { - Self { - pathbuf, - packer, - armor_output, - } - } - - pub fn get_slatepack_file_contents(&self) -> Result, Error> { - let metadata = metadata(&self.pathbuf)?; - let len = metadata.len(); - let min_len = slatepack::min_size(); - let max_len = slatepack::max_size(); - if len < min_len || len > max_len { - let msg = format!( - "Data is invalid length: {} | min: {}, max: {} |", - len, min_len, max_len - ); - return Err(Error::SlatepackDeser(msg)); - } - let mut pub_tx_f = File::open(&self.pathbuf)?; - let mut data = Vec::new(); - pub_tx_f.read_to_end(&mut data)?; - Ok(data) - } - - pub fn get_slatepack(&self, decrypt: bool) -> Result { - let data = self.get_slatepack_file_contents()?; - self.packer.deser_slatepack(&data, decrypt) - } -} - -impl<'a> SlatePutter for PathToSlatepack<'a> { - fn put_tx(&self, slate: &Slate, as_bin: bool) -> Result<(), Error> { - let slatepack = self.packer.create_slatepack(slate)?; - let mut pub_tx = File::create(&self.pathbuf)?; - if as_bin { - if self.armor_output { - let armored = self.packer.armor_slatepack(&slatepack)?; - pub_tx.write_all(armored.as_bytes())?; - } else { - pub_tx.write_all( - &byte_ser::to_bytes(&SlatepackBin(slatepack)) - .map_err(|_| Error::SlatepackSer)?, - )?; - } - } else { - pub_tx.write_all( - serde_json::to_string_pretty(&slatepack) - .map_err(|_| Error::SlateSer)? - .as_bytes(), - )?; - } - pub_tx.sync_all()?; - Ok(()) - } -} - -impl<'a> SlateGetter for PathToSlatepack<'a> { - fn get_tx(&self) -> Result<(Slate, bool), Error> { - let data = self.get_slatepack_file_contents()?; - let slatepack = self.packer.deser_slatepack(&data, true)?; - Ok((self.packer.get_slate(&slatepack)?, true)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::fs; - - use grin_core::global; - - fn clean_output_dir(test_dir: &str) { - let _ = fs::remove_dir_all(test_dir); - } - - fn setup(test_dir: &str) { - clean_output_dir(test_dir); - } - - const SLATEPACK_DIR: &str = "target/test_output/slatepack"; - - #[test] - fn pathbuf_get_file_contents() { - global::set_local_chain_type(global::ChainTypes::AutomatedTesting); - setup(SLATEPACK_DIR); - - fs::create_dir_all(SLATEPACK_DIR).unwrap(); - let sp_path = PathBuf::from(SLATEPACK_DIR).join("pack_file"); - - // set Slatepack file to minimum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::min_size()).unwrap(); - } - - let args = slatepack::SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }; - let packer = Slatepacker::new(args); - - let mut pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - // set Slatepack file to maximum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::max_size()).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_ok()); - - // set Slatepack file below minimum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::min_size() - 1).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - // set Slatepack file above maximum allowable size - { - let f = File::create(sp_path.clone()).unwrap(); - f.set_len(slatepack::max_size() + 1).unwrap(); - } - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, true); - assert!(pack_path.get_slatepack_file_contents().is_err()); - - pack_path = PathToSlatepack::new(sp_path.clone(), &packer, false); - assert!(pack_path.get_slatepack_file_contents().is_err()); - } -} diff --git a/impls/src/lib.rs b/impls/src/lib.rs index 9bbedfa..4ff0c1b 100644 --- a/impls/src/lib.rs +++ b/impls/src/lib.rs @@ -42,8 +42,7 @@ pub mod test_framework; pub mod tor; pub use crate::adapters::{ - PathToSlate, PathToSlatepack, SlateGetter, SlatePutter, SlateReceiver, SlateSender, - TorSlateSender, + PathToSlate, SlateGetter, SlatePutter, SlateReceiver, SlateSender, TorSlateSender, }; pub use crate::error::Error; pub use crate::lifecycle::DefaultLCProvider; diff --git a/libwallet/src/address.rs b/libwallet/src/address.rs index d4f9dfe..01bed27 100644 --- a/libwallet/src/address.rs +++ b/libwallet/src/address.rs @@ -15,12 +15,13 @@ //! Functions defining wallet 'addresses', i.e. ed2559 keys based on //! a derivation path +use crate::blake2::blake2b::blake2b; +use crate::slatepack::SlatepackAddressIndex; use crate::Error; + use grin_keychain::{ChildNumber, Identifier, Keychain, SwitchCommitmentType}; use grin_util::secp::key::SecretKey; -use crate::blake2::blake2b::blake2b; - /// Derive a Slatepack address path from an output parent path and index. /// /// Output paths: @@ -30,11 +31,14 @@ use crate::blake2::blake2b::blake2b; /// Slatepack address paths: /// - account m/0: m/0/1/0, m/0/1/1 /// - account m/1: m/1/1/0, m/1/1/1 -pub fn address_derivation_path(parent_key_id: &Identifier, index: u32) -> Identifier { +pub fn address_derivation_path( + parent_key_id: &Identifier, + index: SlatepackAddressIndex, +) -> Identifier { let mut key_path = parent_key_id.to_path(); key_path.path[1] = ChildNumber::from(1); key_path.depth += 1; - key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index); + key_path.path[key_path.depth as usize - 1] = ChildNumber::from(index.value()); Identifier::from_path(&key_path) } @@ -42,7 +46,7 @@ pub fn address_derivation_path(parent_key_id: &Identifier, index: u32) -> Identi pub fn address_from_derivation_path( keychain: &K, parent_key_id: &Identifier, - index: u32, + index: SlatepackAddressIndex, ) -> Result where K: Keychain, @@ -62,6 +66,9 @@ mod tests { fn slatepack_address_path() { let parent = ExtKeychain::derive_key_id(2, 2, 0, 0, 0); let expected = ExtKeychain::derive_key_id(3, 2, 1, 3, 0); - assert_eq!(address_derivation_path(&parent, 3), expected); + assert_eq!( + address_derivation_path(&parent, SlatepackAddressIndex(3)), + expected + ); } } diff --git a/libwallet/src/api_impl/foreign.rs b/libwallet/src/api_impl/foreign.rs index 84aa16e..49313a3 100644 --- a/libwallet/src/api_impl/foreign.rs +++ b/libwallet/src/api_impl/foreign.rs @@ -22,6 +22,7 @@ use crate::api_impl::types::update_tx_slate_state; use crate::backend::WalletBackend; use crate::internal::{selection, tx, updater}; use crate::slate_versions::SlateVersion; +use crate::slatepack::SlatepackAddressIndex; use crate::{ address, BlockFees, CbData, Error, NodeClient, Slate, SlateState, TxLogEntryType, VersionInfo, }; @@ -124,7 +125,11 @@ where ret_slate.amount, &excess, p.sender_address, - address::address_from_derivation_path(&keychain, &parent_key_id, 0)?, + address::address_from_derivation_path( + &keychain, + &parent_key_id, + SlatepackAddressIndex(0), + )?, )?; p.receiver_signature = Some(sig); diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 0794bcd..7017ef7 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -34,9 +34,9 @@ use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletInfo}; use crate::{ address, mwixnet::{create_onion, ComSignature, Hop, MixnetReqCreationParams, SwapReq}, - wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, + slatepack, wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack, - SlatepackAddress, Slatepacker, SlatepackerArgs, TxLogEntryType, ViewWallet, WalletBackend, + SlatepackAddress, SlatepackArmor, SlatepackBin, TxLogEntryType, ViewWallet, WalletBackend, WalletInitStatus, WalletLCProvider, }; use grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; @@ -46,6 +46,8 @@ use ed25519_dalek::Verifier; use ed25519_dalek::VerifyingKey as DalekPublicKey; use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; +use crate::slatepack::SlatepackAddressIndex; +use grin_wallet_util::byte_ser; use std::convert::{TryFrom, TryInto}; use std::sync::mpsc::Sender; @@ -121,13 +123,14 @@ where pub fn get_slatepack_address<'a, L, C, K>( wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - index: u32, + index: SlatepackAddressIndex, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { + index.check()?; wallet_lock!(wallet_inst, w); let parent_key_id = w.parent_key_id(); let k = w.keychain(keychain_mask)?; @@ -140,13 +143,14 @@ where pub fn get_slatepack_secret_key<'a, L, C, K>( wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, - index: u32, + index: SlatepackAddressIndex, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { + index.check()?; wallet_lock!(wallet_inst, w); let parent_key_id = w.parent_key_id(); let k = w.keychain(keychain_mask)?; @@ -160,7 +164,7 @@ pub fn create_slatepack_message<'a, L, C, K>( wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slate: &Slate, - sender_index: Option, + sender_index: Option, recipients: Vec, ) -> Result where @@ -168,17 +172,16 @@ where C: NodeClient + 'a, K: Keychain + 'a, { - let sender = match sender_index { - Some(i) => Some(get_slatepack_address(wallet_inst, keychain_mask, i)?), + let sender = match sender_index.as_ref() { + Some(i) => Some(get_slatepack_address( + wallet_inst.clone(), + keychain_mask, + *i, + )?), None => None, }; - let packer = Slatepacker::new(SlatepackerArgs { - sender, - recipients, - dec_key: None, - }); - let slatepack = packer.create_slatepack(slate)?; - packer.armor_slatepack(&slatepack) + let slatepack = slate.create_slatepack(sender, recipients)?; + slatepack.armor() } /// Unpack a slate from the given slatepack message, @@ -187,47 +190,16 @@ pub fn slate_from_slatepack_message<'a, L, C, K>( wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - if secret_indices.is_empty() { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - let slatepack = packer.deser_slatepack(slatepack.as_bytes(), true)?; - packer.get_slate(&slatepack) - } else { - for index in secret_indices { - let dec_key = Some(get_slatepack_secret_key( - wallet_inst.clone(), - keychain_mask, - index, - )?); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: dec_key.as_ref(), - }); - let res = packer.deser_slatepack(slatepack.as_bytes(), true); - let slatepack = match res { - Ok(sp) => sp, - Err(_) => { - continue; - } - }; - return packer.get_slate(&slatepack); - } - Err(Error::SlatepackDecryption( - "Could not decrypt slatepack with any provided index on the address derivation path" - .to_owned(), - )) - } + let sp = decode_slatepack_message(wallet_inst, keychain_mask, slatepack, secret_indices) + .map_err(|e| Error::SlatepackDecryption(format!("Could not decrypt slatepack: {}", e)))?; + sp.get_slate() } /// Decode a slatepack message, to allow viewing @@ -237,43 +209,199 @@ pub fn decode_slatepack_message<'a, L, C, K>( wallet_inst: crate::WalletHandle<'a, L, C, K>, keychain_mask: Option<&SecretKey>, slatepack: String, - secret_indices: Vec, + secret_indices: Vec, ) -> Result where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: None, - }); - if secret_indices.is_empty() { - packer.deser_slatepack(slatepack.as_bytes(), false) - } else { - for index in secret_indices { - let dec_key = Some(get_slatepack_secret_key( - wallet_inst.clone(), - keychain_mask, - index, - )?); - let packer = Slatepacker::new(SlatepackerArgs { - sender: None, - recipients: vec![], - dec_key: dec_key.as_ref(), - }); - let res = packer.deser_slatepack(slatepack.as_bytes(), true); - let slatepack = match res { - Ok(sp) => sp, - Err(_) => { - continue; - } - }; - return Ok(slatepack); - } - packer.deser_slatepack(slatepack.as_bytes(), false) + for i in &secret_indices { + i.check()?; } + let slatepack = parse_slatepack(slatepack.as_bytes())?; + if slatepack.mode == 1 && !secret_indices.is_empty() { + let mut decrypted = slatepack.clone(); + if decrypt_slatepack(&mut decrypted, wallet_inst, keychain_mask, secret_indices).is_ok() { + return Ok(decrypted); + } + } + Ok(slatepack) +} + +/// Deserialize provided data to slatepack +pub fn deserialize_slatepack<'a, L, C, K>( + data: &[u8], + wallet_inst: crate::WalletHandle<'a, L, C, K>, + keychain_mask: Option<&SecretKey>, + secret_indices: Vec, +) -> Result +where + L: WalletLCProvider<'a, C, K>, + C: NodeClient + 'a, + K: Keychain + 'a, +{ + let mut slatepack = parse_slatepack(data)?; + decrypt_slatepack(&mut slatepack, wallet_inst, keychain_mask, secret_indices)?; + Ok(slatepack) +} + +/// Parse a slatepack without accessing wallet keys +pub fn parse_slatepack(data: &[u8]) -> Result { + // check if data is armored, if so, remove and continue + let data_len = data.len() as u64; + if data_len < slatepack::min_size() || data_len > slatepack::max_size() { + return Err(Error::SlatepackDeser("Data invalid length".to_string())); + } + + let test_header = &data[..slatepack::HEADER.len()]; + + let data = match str::from_utf8(test_header) { + Ok(s) => { + if s == slatepack::HEADER { + SlatepackArmor::decode(data)? + } else { + data.to_vec() + } + } + Err(_) => data.to_vec(), + }; + + // try as bin first, then as json + let slatepack = match byte_ser::from_bytes::(&data) { + Ok(s) => s.0, + Err(e) => { + debug!("Not a valid binary slatepack: {} - Will try JSON", e); + let content = String::from_utf8(data).map_err(|e| { + let msg = format!("{}", e); + Error::SlatepackDeser(msg) + })?; + serde_json::from_str(&content).map_err(|e| { + let msg = format!("Error reading JSON slatepack: {}", e); + Error::SlatepackDeser(msg) + })? + } + }; + + slatepack.ver_check_warn(); + Ok(slatepack) +} + +/// Decrypt a parsed slatepack using wallet indices +pub fn decrypt_slatepack<'a, L, C, K>( + slatepack: &mut Slatepack, + wallet_inst: crate::WalletHandle<'a, L, C, K>, + keychain_mask: Option<&SecretKey>, + mut secret_indices: Vec, +) -> Result<(), Error> +where + L: WalletLCProvider<'a, C, K>, + C: NodeClient + 'a, + K: Keychain + 'a, +{ + secret_indices.sort_unstable(); + secret_indices.dedup(); + if slatepack.mode == 1 { + // Try decrypt with selected indices. + let mut try_decrypt_with = |indices: &Vec| -> Result<(), Error> { + for i in indices { + let dec_key = get_slatepack_secret_key(wallet_inst.clone(), keychain_mask, *i)?; + match slatepack.try_decrypt_payload(Some(&dec_key)) { + Ok(_) => return Ok(()), + Err(e) => { + if matches!(e, Error::Age(_)) { + continue; + } else { + return Err(e); + } + } + } + } + Err(Error::SlatepackDecryption( + "Can not decrypt slatepack with provided indexes".to_string(), + )) + }; + + // Try decrypt with initial indices. + return match try_decrypt_with(&secret_indices) { + Ok(_) => Ok(()), + Err(_) => { + // Collect indexes for transactions. + let collect_indexes = |outstanding: bool, + secret_indices: &Vec| + -> Result, Error> { + wallet_lock!(wallet_inst, w); + let mut indices: Vec = w + .tx_log_iter()? + .flatten() + .filter(|tx| { + let tx_type = if outstanding { + !tx.confirmed + && (tx.tx_type == TxLogEntryType::TxReceived + || tx.tx_type == TxLogEntryType::TxSent + || tx.tx_type == TxLogEntryType::TxReverted) + } else { + tx.confirmed + && tx.tx_type != TxLogEntryType::TxReceivedCancelled + && tx.tx_type != TxLogEntryType::TxSentCancelled + }; + tx_type && tx.parent_key_id == w.parent_key_id() + }) + .filter_map(|t| t.address_index) + .filter(|i| !secret_indices.contains(i)) + .collect(); + indices.sort_unstable(); + indices.dedup(); + Ok(indices) + }; + let mut indexes = collect_indexes(true, &secret_indices)?; + match try_decrypt_with(&mut indexes) { + Ok(_) => Ok(()), + Err(_) => { + for i in indexes { + if !secret_indices.contains(&i) { + secret_indices.push(i); + } + } + let indexes = collect_indexes(false, &secret_indices)?; + match try_decrypt_with(&indexes) { + Ok(()) => Ok(()), + Err(_) => { + for i in indexes { + if !secret_indices.contains(&i) { + secret_indices.push(i); + } + } + let mut indexes: Vec = { + wallet_lock!(wallet_inst, w); + w.private_context_iter()? + .flatten() + .filter(|c| { + let index = + if let Some(i) = c.payment_proof_derivation_index { + !secret_indices.contains(&i) + } else { + false + }; + c.parent_key_id == w.parent_key_id() && index + }) + .map(|c| c.payment_proof_derivation_index.unwrap()) + .collect() + }; + indexes.sort_unstable(); + indexes.dedup(); + match try_decrypt_with(&indexes) { + Ok(_) => Ok(()), + Err(e) => Err(e), + } + } + } + } + } + } + }; + } + Ok(()) } /// retrieve outputs @@ -532,6 +660,7 @@ where recipient_sig: r_sig, sender_address: SlatepackAddress::new(&proof.sender_address), sender_sig: s_sig, + sender_address_path: Some(proof.sender_address_path), }) } @@ -546,6 +675,10 @@ where C: NodeClient, K: Keychain, { + if let Some(index) = args.address_index { + index.check()?; + } + if args.amount == 0 { return Err(Error::InvalidAmount); } @@ -629,15 +762,12 @@ where )? }; - // Payment Proof, add addresses to slate and save address - // TODO: Note we only use single derivation path for now, - // probably want to allow sender to specify which one - let deriv_path = 0u32; - + let address_index = args.address_index.unwrap_or(SlatepackAddressIndex(0)); if let Some(a) = payment_proof_address { let k = w.keychain(keychain_mask)?; - let sec_addr_key = address::address_from_derivation_path(&k, &parent_key_id, deriv_path)?; + let sec_addr_key = + address::address_from_derivation_path(&k, &parent_key_id, address_index)?; let sender_address = OnionV3Address::from_private(&sec_addr_key.0)?; slate.payment_proof = Some(PaymentInfo { @@ -645,14 +775,13 @@ where receiver_address: a.pub_key, receiver_signature: None, }); - - context.payment_proof_derivation_index = Some(deriv_path); } // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; + context.payment_proof_derivation_index = Some(address_index); batch.save_private_context(slate.id.as_bytes(), &context)?; batch.commit()?; } @@ -666,13 +795,17 @@ where pub fn issue_invoice_tx( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, - args: IssueInvoiceTxArgs, + mut args: IssueInvoiceTxArgs, use_test_rng: bool, ) -> Result where C: NodeClient, K: Keychain, { + if let Some(index) = args.address_index { + index.check()?; + } + if args.amount == 0 { return Err(Error::InvalidAmount); } @@ -688,9 +821,13 @@ where None => w.parent_key_id(), }; + if args.address_index.is_none() { + args.address_index = Some(w.next_tx_slatepack_address_index(&parent_key_id)?); + } + let mut slate = tx::new_tx_slate(w, args.amount, true, 2, use_test_rng, None)?; let height = w.w2n_client().get_chain_tip()?.0; - let context = tx::add_output_to_slate( + let mut context = tx::add_output_to_slate( w, keychain_mask, &mut slate, @@ -704,10 +841,20 @@ where slate.version_info.version = v; }; + // Update transaction log address index + let mut tx = w.get_tx_log_entry(&slate.id, &parent_key_id)?; + if let Some(tx) = tx.as_mut() { + tx.address_index = args.address_index; + let mut batch = w.batch(keychain_mask)?; + batch.save_tx_log_entry(tx.clone(), &parent_key_id)?; + batch.commit()?; + } + // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; + context.payment_proof_derivation_index = args.address_index; batch.save_private_context(slate.id.as_bytes(), &context)?; batch.commit()?; } @@ -813,6 +960,7 @@ where // if self-sending, merge contexts if let Ok(c) = context_res { + context.payment_proof_derivation_index = c.payment_proof_derivation_index; context.initial_sec_key = c.initial_sec_key; context.initial_sec_nonce = c.initial_sec_nonce; context.fee = c.fee; @@ -828,7 +976,7 @@ where selection::repopulate_tx(w, keychain_mask, &mut ret_slate, &context, false)?; // Save the aggsig context in our DB for when we - // recieve the transaction back + // receive the transaction back { let mut batch = w.batch(keychain_mask)?; batch.save_private_context(slate.id.as_bytes(), &context)?; @@ -1324,12 +1472,23 @@ where }; // for now, simple test whether one of the addresses belongs to this wallet - let sec_key = address::address_from_derivation_path(&keychain, &parent_key_id, 0)?; + let sec_key = + address::address_from_derivation_path(&keychain, &parent_key_id, SlatepackAddressIndex(0))?; let d_skey = DalekSecretKey::from_bytes(&sec_key.0); - let my_address_pubkey: DalekPublicKey = (&d_skey).into(); + let possible_receiver_key: DalekPublicKey = (&d_skey).into(); - let sender_mine = my_address_pubkey == sender_pubkey; - let recipient_mine = my_address_pubkey == recipient_pubkey; + let sec_key = address::address_from_derivation_path( + &keychain, + &parent_key_id, + proof + .sender_address_path + .unwrap_or(SlatepackAddressIndex(0)), + )?; + let d_skey = DalekSecretKey::from_bytes(&sec_key.0); + let possible_sender_key: DalekPublicKey = (&d_skey).into(); + + let sender_mine = possible_sender_key == sender_pubkey; + let recipient_mine = possible_receiver_key == recipient_pubkey; Ok((sender_mine, recipient_mine)) } diff --git a/libwallet/src/api_impl/types.rs b/libwallet/src/api_impl/types.rs index 06ccf26..4538be9 100644 --- a/libwallet/src/api_impl/types.rs +++ b/libwallet/src/api_impl/types.rs @@ -29,6 +29,7 @@ use grin_keychain::Keychain; use grin_util::secp::SecretKey; pub use crate::mwixnet::{Hop, MixnetReqCreationParams, SwapReq}; +use crate::slatepack::SlatepackAddressIndex; /// Type for storing amounts (in nanogrins). /// Serializes as a string but can deserialize from a string or u64. @@ -38,7 +39,7 @@ pub struct Amount(#[serde(with = "secp_ser::string_or_u64")] pub u64); /// V2 Init / Send TX API Args #[derive(Clone, Debug, Serialize, Deserialize)] pub struct InitTxArgs { - /// The human readable account name from which to draw outputs + /// The human-readable account name from which to draw outputs /// for the transaction, overriding whatever the active account is as set via the /// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method. pub src_acct_name: Option, @@ -91,6 +92,9 @@ pub struct InitTxArgs { /// inputs until just before finalization #[serde(default)] pub late_lock: Option, + /// Slatepack address index + #[serde(default)] + pub address_index: Option, /// Sender arguments. If present, the underlying function will also attempt to send the /// transaction to a destination and optionally finalize the result pub send_args: Option, @@ -126,6 +130,7 @@ impl Default for InitTxArgs { estimate_only: Some(false), payment_proof_recipient_address: None, late_lock: Some(false), + address_index: None, send_args: None, } } @@ -134,7 +139,7 @@ impl Default for InitTxArgs { /// V2 Issue Invoice Tx Args #[derive(Clone, Serialize, Deserialize, Default)] pub struct IssueInvoiceTxArgs { - /// The human readable account name to which the received funds should be added + /// The human-readable account name to which the received funds should be added /// overriding whatever the active account is as set via the /// [`set_active_account`](../grin_wallet_api/owner/struct.Owner.html#method.set_active_account) method. pub dest_acct_name: Option, @@ -145,6 +150,8 @@ pub struct IssueInvoiceTxArgs { /// down to the minimum slate version compatible with the current. If `None` the slate /// is generated with the latest version. pub target_slate_version: Option, + /// Issuer slatepack address derivation path index. + pub address_index: Option, } /// Sort tx retrieval order @@ -179,7 +186,7 @@ pub struct RetrieveTxQueryArgs { /// Retrieve transactions with an id higher than or equal to the given /// If None, consider items from the first transaction and later pub min_id: Option, - /// Retrieve tranactions with an id less than or equal to the given + /// Retrieve transactions with an id less than or equal to the given /// If None, consider items from the last transaction and earlier pub max_id: Option, /// The maximum number of transactions to return @@ -216,7 +223,7 @@ pub struct RetrieveTxQueryArgs { pub min_confirmed_timestamp: Option>, /// higher bound on the confirmation timestamp, inclusive pub max_confirmed_timestamp: Option>, - /// Field within the tranasction list on which to sort + /// Field within the transaction list on which to sort /// defaults to ID if not present pub sort_field: Option, /// Sort order, defaults to ASC if not present (earliest is first) @@ -268,7 +275,7 @@ impl BlockFees { } } -/// Map Outputdata to commits +/// Map [OutputData] to commits #[derive(Serialize, Deserialize, Debug, Clone)] pub struct OutputCommitMapping { /// Output Data @@ -324,6 +331,9 @@ pub struct PaymentProof { /// Sender Signature #[serde(with = "dalek_ser::dalek_sig_serde")] pub sender_sig: DalekSignature, + /// Sender Slatepack address derivation path index + #[serde(default)] + pub sender_address_path: Option, } /// Build output result diff --git a/libwallet/src/backend.rs b/libwallet/src/backend.rs index 90c4b6b..50b4481 100644 --- a/libwallet/src/backend.rs +++ b/libwallet/src/backend.rs @@ -21,6 +21,7 @@ use uuid::Uuid; use crate::blake2::blake2b::{Blake2b, Blake2bResult}; +use crate::slatepack::SlatepackAddressIndex; use crate::{ AcctPathMapping, Context, Error, NodeClient, OutputData, ScannedBlockInfo, TxLogEntry, WalletInitStatus, @@ -44,19 +45,21 @@ const CONFIRMED_HEIGHT_PREFIX: u8 = b'c'; const PRIVATE_TX_CONTEXT_PREFIX: u8 = b'p'; const TX_LOG_ENTRY_PREFIX: u8 = b't'; const TX_LOG_ID_PREFIX: u8 = b'i'; +const TX_ADDRESS_INDEX_PREFIX: u8 = b's'; const ACCOUNT_PATH_MAPPING_PREFIX: u8 = b'a'; const LAST_SCANNED_BLOCK: u8 = b'l'; const LAST_SCANNED_KEY: &str = "LAST_SCANNED_KEY"; const WALLET_INIT_STATUS: u8 = b'w'; const WALLET_INIT_STATUS_KEY: &str = "WALLET_INIT_STATUS"; -const DB_PREFIXES: [u8; 9] = [ +const DB_PREFIXES: [u8; 10] = [ OUTPUT_PREFIX, DERIV_PREFIX, CONFIRMED_HEIGHT_PREFIX, PRIVATE_TX_CONTEXT_PREFIX, TX_LOG_ENTRY_PREFIX, TX_LOG_ID_PREFIX, + TX_ADDRESS_INDEX_PREFIX, ACCOUNT_PATH_MAPPING_PREFIX, LAST_SCANNED_BLOCK, WALLET_INIT_STATUS, @@ -369,10 +372,16 @@ where } /// Get an (Optional) tx log entry by uuid. - pub fn get_tx_log_entry(&self, u: &Uuid) -> Result, Error> { - self.db - .get_ser(Some(TX_LOG_ENTRY_PREFIX), u.as_bytes(), None) - .map_err(|e| e.into()) + pub fn get_tx_log_entry( + &self, + id: &Uuid, + parent_id: &Identifier, + ) -> Result, Error> { + let tx = self + .tx_log_iter()? + .flatten() + .find(|tx| tx.parent_key_id == *parent_id && tx.tx_slate_id == Some(*id)); + Ok(tx) } /// Iterate over all tx log data stored by the backend. @@ -392,6 +401,54 @@ where .map_err(From::from) } + /// Next transaction slatepack address derivation path index. + pub fn next_tx_slatepack_address_index( + &mut self, + parent_key_id: &Identifier, + ) -> Result { + let mut index = { + let batch = self.db.batch()?; + batch + .get_ser( + Some(TX_ADDRESS_INDEX_PREFIX), + &parent_key_id.to_bytes(), + None, + )? + .unwrap_or(0) + }; + if index >= SlatepackAddressIndex::MAX { + return Err(Error::SlatepackAddress( + "Slatepack address indices exhausted".into(), + )); + } + index += 1; + let mut batch = self.db.batch()?; + batch.put_ser( + Some(TX_ADDRESS_INDEX_PREFIX), + &parent_key_id.to_bytes(), + &index, + )?; + batch.commit()?; + Ok(SlatepackAddressIndex(index)) + } + + /// Iterator over private tx contexts. + pub fn private_context_iter( + &self, + ) -> Result>, Error> { + let protocol_version = self.db.protocol_version(); + self.db + .iter(Some(PRIVATE_TX_CONTEXT_PREFIX), move |_, mut v| { + ser::deserialize( + &mut v, + protocol_version, + ser::DeserializationMode::default(), + ) + .map_err(From::from) + }) + .map_err(From::from) + } + /// Retrieve the private context associated with a given slate id. pub fn get_private_context( &mut self, diff --git a/libwallet/src/internal/selection.rs b/libwallet/src/internal/selection.rs index fc1b9a5..440a95e 100644 --- a/libwallet/src/internal/selection.rs +++ b/libwallet/src/internal/selection.rs @@ -208,6 +208,7 @@ where sender_signature: None, }); }; + t.address_index = context.payment_proof_derivation_index; // write the output representing our change for (id, _, _) in &context.get_outputs() { diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index 1400490..f3d746e 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -20,6 +20,7 @@ use uuid::Uuid; use crate::internal::{selection, updater}; use crate::slate::Slate; +use crate::slatepack::SlatepackAddressIndex; use crate::types::{Context, NodeClient, StoredProofInfo, TxLogEntryType}; use crate::util::OnionV3Address; use crate::{address, Error}; @@ -368,7 +369,7 @@ where Ok(()) } -/// Update the stored transaction (this update needs to happen when the TX is finalised) +/// Update the stored transaction (this update needs to happen when the TX is finalized) pub fn update_stored_tx( wallet: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -405,19 +406,21 @@ where } if let Some(ref p) = slate.clone().payment_proof { - let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); + let sender_address_path = context + .payment_proof_derivation_index + .unwrap_or(SlatepackAddressIndex(0)); let keychain = wallet.keychain(keychain_mask)?; let parent_key_id = wallet.parent_key_id(); let excess = slate.calc_excess(keychain.secp())?; let sender_key = - address::address_from_derivation_path(&keychain, &parent_key_id, derivation_index)?; + address::address_from_derivation_path(&keychain, &parent_key_id, sender_address_path)?; let sender_address = OnionV3Address::from_private(&sender_key.0)?; let sig = create_payment_proof_signature(slate.amount, &excess, p.sender_address, sender_key)?; tx.payment_proof = Some(StoredProofInfo { receiver_address: p.receiver_address, receiver_signature: p.receiver_signature, - sender_address_path: derivation_index, + sender_address_path, sender_address: sender_address.to_ed25519()?, sender_signature: Some(sig), }) diff --git a/libwallet/src/lib.rs b/libwallet/src/lib.rs index cc1d417..a8e3c87 100644 --- a/libwallet/src/lib.rs +++ b/libwallet/src/lib.rs @@ -57,9 +57,7 @@ pub use crate::slate_versions::{ SlateVersion, VersionedBinSlate, VersionedCoinbase, VersionedSlate, CURRENT_SLATE_VERSION, GRIN_BLOCK_HEADER_VERSION, }; -pub use crate::slatepack::{ - Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, Slatepacker, SlatepackerArgs, -}; +pub use crate::slatepack::{Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin}; pub use api_impl::owner_updater::StatusMessage; pub use api_impl::types::{ Amount, BlockFees, BuiltOutput, InitTxArgs, InitTxSendArgs, IssueInvoiceTxArgs, diff --git a/libwallet/src/slate.rs b/libwallet/src/slate.rs index 4ec38ef..c2b7604 100644 --- a/libwallet/src/slate.rs +++ b/libwallet/src/slate.rs @@ -16,6 +16,13 @@ //! around during an interactive wallet exchange use crate::error::Error; +use crate::slate_versions::v4::{ + CommitsV4, KernelFeaturesArgsV4, OutputFeaturesV4, ParticipantDataV4, PaymentInfoV4, + SlateStateV4, SlateV4, VersionCompatInfoV4, +}; +use crate::slate_versions::VersionedSlate; +use crate::slate_versions::{CURRENT_SLATE_VERSION, GRIN_BLOCK_HEADER_VERSION}; +use crate::{Context, SlateVersion, Slatepack, SlatepackAddress, VersionedBinSlate}; use ed25519_dalek::Signature as DalekSignature; use ed25519_dalek::VerifyingKey as DalekPublicKey; use grin_core::core::amount_to_hr_string; @@ -30,18 +37,11 @@ use grin_util::secp::key::{PublicKey, SecretKey}; use grin_util::secp::pedersen::Commitment; use grin_util::secp::Signature; use grin_util::{secp, static_secp_instance}; +use grin_wallet_util::byte_ser; use serde::ser::{Serialize, Serializer}; use std::fmt; use uuid::Uuid; -use crate::slate_versions::v4::{ - CommitsV4, KernelFeaturesArgsV4, OutputFeaturesV4, ParticipantDataV4, PaymentInfoV4, - SlateStateV4, SlateV4, VersionCompatInfoV4, -}; -use crate::slate_versions::VersionedSlate; -use crate::slate_versions::{CURRENT_SLATE_VERSION, GRIN_BLOCK_HEADER_VERSION}; -use crate::Context; - #[derive(Debug, Clone)] pub struct PaymentInfo { /// Sender address @@ -670,6 +670,21 @@ impl Slate { Ok(()) } } + + /// Create slatepack from this slate. + pub fn create_slatepack( + &self, + sender: Option, + recipients: Vec, + ) -> Result { + let out_slate = VersionedSlate::into_version(self.clone(), SlateVersion::V4)?; + let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlatepackSer)?; + let mut slatepack = Slatepack::default(); + slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?; + slatepack.sender = sender; + slatepack.try_encrypt_payload(recipients)?; + Ok(slatepack) + } } impl Serialize for Slate { diff --git a/libwallet/src/slatepack/armor.rs b/libwallet/src/slatepack/armor.rs index 9178284..9f4b31f 100644 --- a/libwallet/src/slatepack/armor.rs +++ b/libwallet/src/slatepack/armor.rs @@ -29,9 +29,11 @@ use std::str; use super::types::{Slatepack, SlatepackBin}; -// Framing and formatting for slate armor +/// Slatepack file header. pub static HEADER: &str = "BEGINSLATEPACK."; -static FOOTER: &str = ". ENDSLATEPACK."; +/// Slatepack file footer. +pub static FOOTER: &str = ". ENDSLATEPACK."; + const WORD_LENGTH: usize = 15; const WORDS_PER_LINE: usize = 200; const WEIGHT_RATIO: u64 = 32; diff --git a/libwallet/src/slatepack/mod.rs b/libwallet/src/slatepack/mod.rs index 157b5cf..410fa58 100644 --- a/libwallet/src/slatepack/mod.rs +++ b/libwallet/src/slatepack/mod.rs @@ -16,10 +16,31 @@ mod address; mod armor; -mod packer; mod types; pub use self::address::SlatepackAddress; -pub use self::armor::{max_size, min_size, SlatepackArmor}; -pub use self::packer::{Slatepacker, SlatepackerArgs}; -pub use self::types::{Slatepack, SlatepackBin}; +pub use self::armor::{max_size, min_size, SlatepackArmor, FOOTER, HEADER}; +pub use self::types::{Slatepack, SlatepackAddressIndex, SlatepackBin}; + +use std::fs::{metadata, File}; +use std::io::Read; +use std::path::PathBuf; + +/// Get slatepack file contents. +pub fn get_slatepack_file_contents(path: &PathBuf) -> Result, crate::Error> { + let metadata = metadata(path)?; + let len = metadata.len(); + let min_len = min_size(); + let max_len = max_size(); + if len < min_len || len > max_len { + let msg = format!( + "Data is invalid length: {} | min: {}, max: {} |", + len, min_len, max_len + ); + return Err(crate::Error::SlatepackDeser(msg)); + } + let mut pub_tx_f = File::open(path)?; + let mut data = Vec::new(); + pub_tx_f.read_to_end(&mut data)?; + Ok(data) +} diff --git a/libwallet/src/slatepack/packer.rs b/libwallet/src/slatepack/packer.rs deleted file mode 100644 index d0575fc..0000000 --- a/libwallet/src/slatepack/packer.rs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2021 The Grin Developers -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use std::convert::TryFrom; -use std::str; - -use super::armor::HEADER; -use crate::Error; -use crate::{ - slatepack, Slate, SlateVersion, Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, - VersionedBinSlate, VersionedSlate, -}; - -use grin_wallet_util::byte_ser; - -use ed25519_dalek::SigningKey as edSecretKey; - -#[derive(Clone)] -/// Arguments, mostly for encrypting decrypting a slatepack -pub struct SlatepackerArgs<'a> { - /// Optional sender to include in slatepack - pub sender: Option, - /// Optional list of recipients, for encryption - pub recipients: Vec, - /// Optional decryption key - pub dec_key: Option<&'a edSecretKey>, -} - -/// Helper struct to pack and unpack slatepacks -#[derive(Clone)] -pub struct Slatepacker<'a>(SlatepackerArgs<'a>); - -impl<'a> Slatepacker<'a> { - /// Create with pathbuf and recipients - pub fn new(args: SlatepackerArgs<'a>) -> Self { - Self(args) - } - - /// return slatepack - pub fn deser_slatepack(&self, data: &[u8], decrypt: bool) -> Result { - // check if data is armored, if so, remove and continue - let data_len = data.len() as u64; - if data_len < slatepack::min_size() || data_len > slatepack::max_size() { - let msg = "Data invalid length".to_string(); - return Err(Error::SlatepackDeser(msg)); - } - - let test_header = &data[..HEADER.len()]; - - let data = match str::from_utf8(test_header) { - Ok(s) => { - if s == HEADER { - SlatepackArmor::decode(data)? - } else { - data.to_vec() - } - } - Err(_) => data.to_vec(), - }; - - // try as bin first, then as json - let mut slatepack = match byte_ser::from_bytes::(&data) { - Ok(s) => s.0, - Err(e) => { - debug!("Not a valid binary slatepack: {} - Will try JSON", e); - let content = String::from_utf8(data).map_err(|e| { - let msg = format!("{}", e); - Error::SlatepackDeser(msg) - })?; - serde_json::from_str(&content).map_err(|e| { - let msg = format!("Error reading JSON slatepack: {}", e); - Error::SlatepackDeser(msg) - })? - } - }; - - slatepack.ver_check_warn(); - if decrypt { - slatepack.try_decrypt_payload(self.0.dec_key)?; - } - Ok(slatepack) - } - - /// Create slatepack from slate and args - pub fn create_slatepack(&self, slate: &Slate) -> Result { - let out_slate = VersionedSlate::into_version(slate.clone(), SlateVersion::V4)?; - let bin_slate = VersionedBinSlate::try_from(out_slate).map_err(|_| Error::SlatepackSer)?; - let mut slatepack = Slatepack::default(); - slatepack.payload = byte_ser::to_bytes(&bin_slate).map_err(|_| Error::SlatepackSer)?; - slatepack.sender = self.0.sender.clone(); - slatepack.try_encrypt_payload(self.0.recipients.clone())?; - Ok(slatepack) - } - - /// Armor a slatepack - pub fn armor_slatepack(&self, slatepack: &Slatepack) -> Result { - SlatepackArmor::encode(slatepack) - } - - /// Return/upgrade slate from slatepack - pub fn get_slate(&self, slatepack: &Slatepack) -> Result { - let slate_bin = - byte_ser::from_bytes::(&slatepack.payload).map_err(|e| { - error!("Error reading slate from armored slatepack: {}", e); - let msg = format!("{}", e); - Error::SlatepackDeser(msg) - })?; - Slate::upgrade(slate_bin.into()) - } -} diff --git a/libwallet/src/slatepack/types.rs b/libwallet/src/slatepack/types.rs index aef6a02..ba30c55 100644 --- a/libwallet/src/slatepack/types.rs +++ b/libwallet/src/slatepack/types.rs @@ -12,22 +12,19 @@ // See the License for the specific language governing permissions and // limitations under the License. -use bech32::{self, ToBase32}; -use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; -/// Slatepack Types + Serialization implementation -use ed25519_dalek::SigningKey as edSecretKey; -use sha2::{Digest, Sha512}; -use x25519_dalek::StaticSecret; - -use crate::dalek_ser; +use super::SlatepackAddress; use crate::Error; +use crate::{dalek_ser, Slate, SlatepackArmor, VersionedBinSlate}; use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use grin_wallet_util::byte_ser; -use super::SlatepackAddress; - +use bech32::{self, ToBase32}; +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use ed25519_dalek::SigningKey as edSecretKey; +use sha2::{Digest, Sha512}; use std::fmt; use std::io::{Cursor, Read, Write}; +use x25519_dalek::StaticSecret; pub const SLATEPACK_MAJOR_VERSION: u8 = 1; pub const SLATEPACK_MINOR_VERSION: u8 = 0; @@ -260,6 +257,52 @@ impl Slatepack { ); } } + + /// Return/upgrade slate from slatepack. + pub fn get_slate(&self) -> Result { + if self.mode == 1 { + return Err(Error::SlatepackDecryption( + "Slatepack payload is encrypted".into(), + )); + } + let slate_bin = byte_ser::from_bytes::(&self.payload).map_err(|e| { + error!("Error reading slate from armored slatepack: {}", e); + let msg = format!("{}", e); + Error::SlatepackDeser(msg) + })?; + Slate::upgrade(slate_bin.into()) + } + + /// Armor this slatepack. + pub fn armor(&self) -> Result { + SlatepackArmor::encode(self) + } +} + +/// Slatepack address derivation path index +#[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub struct SlatepackAddressIndex(pub u32); + +impl SlatepackAddressIndex { + /// The max BIP32 index. + pub const MAX: u32 = 2_147_483_647; + + /// Check the index range + pub fn check(self) -> Result { + if self.0 > Self::MAX { + return Err(Error::SlatepackAddress(format!( + "Slatepack index {} is out of bound, maximum value is {}", + self.0, + Self::MAX + ))); + } + Ok(self) + } + + /// Index value. + pub fn value(self) -> u32 { + self.0 + } } /// Wrapper for outputting slate as binary @@ -335,7 +378,7 @@ impl Writeable for SlatepackBin { }; // encrypted metadata is only included in the payload - // on encryption, and is not serialised here + // on encryption, and is not serialized here // Now write payload (length prefixed) writer.write_bytes(sp.payload.clone()) @@ -684,7 +727,7 @@ fn slatepack_bin_opt_fields_ser() -> Result<(), grin_wallet_util::byte_ser::Erro // ensure that a slatepack with unknown data in the optional fields can be read #[test] -fn slatepack_bin_future() -> Result<(), grin_wallet_util::byte_ser::Error> { +fn slatepack_bin_future() -> Result<(), byte_ser::Error> { use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use grin_core::global; use grin_wallet_util::byte_ser; @@ -908,3 +951,16 @@ fn slatepack_decrypt_rejects_malformed_plaintexts() -> Result<(), Error> { Ok(()) } + +#[test] +fn index_bounds() { + for index in [0, SlatepackAddressIndex::MAX] { + assert_eq!(SlatepackAddressIndex(index).check().unwrap().value(), index); + } + for index in [SlatepackAddressIndex::MAX + 1, u32::MAX] { + assert!(matches!( + SlatepackAddressIndex(index).check(), + Err(Error::SlatepackAddress(_)) + )); + } +} diff --git a/libwallet/src/types.rs b/libwallet/src/types.rs index ae96d6b..6b34c30 100644 --- a/libwallet/src/types.rs +++ b/libwallet/src/types.rs @@ -18,6 +18,7 @@ use crate::config::{TorConfig, WalletConfig}; use crate::error::Error; use crate::slate_versions::ser as dalek_ser; +use crate::slatepack::SlatepackAddressIndex; use crate::{InitTxArgs, SlateState, WalletBackend}; use chrono::prelude::*; use ed25519_dalek::Signature as DalekSignature; @@ -386,7 +387,7 @@ pub struct Context { /// store the calculated fee pub fee: Option, /// Payment proof sender address derivation path, if needed - pub payment_proof_derivation_index: Option, + pub payment_proof_derivation_index: Option, /// If late-locking, store my tranasction creation prefs /// for later pub late_lock_args: Option, @@ -675,6 +676,9 @@ pub struct TxLogEntry { /// Track the time it took for a transaction to get reverted #[serde(with = "option_duration_as_secs", default)] pub reverted_after: Option, + /// Slatepack address derivation path index + #[serde(default)] + pub address_index: Option, } impl ser::Writeable for TxLogEntry { @@ -713,6 +717,7 @@ impl TxLogEntry { kernel_lookup_min_height: None, payment_proof: None, reverted_after: None, + address_index: None, } } @@ -741,7 +746,7 @@ pub struct StoredProofInfo { /// receiver signature pub receiver_signature: Option, /// sender address derivation path index - pub sender_address_path: u32, + pub sender_address_path: SlatepackAddressIndex, /// sender address #[serde(with = "dalek_ser::dalek_pubkey_serde")] pub sender_address: DalekPublicKey, diff --git a/src/bin/grin-wallet.yml b/src/bin/grin-wallet.yml index 2980a87..8abdbea 100644 --- a/src/bin/grin-wallet.yml +++ b/src/bin/grin-wallet.yml @@ -185,6 +185,11 @@ subcommands: - amount_includes_fee: help: Transaction amount includes transaction fee. Recipient will receive (amount - fee). long: amount_includes_fee + - address_index: + help: Slatepack address derivation path index + short: a + long: address_index + takes_value: true - unpack: about: Unpack and display an armored Slatepack Message, decrypting if possible args: @@ -264,6 +269,11 @@ subcommands: help: Show slatepack data as QR code short: q long: slatepack_qr + - address_index: + help: Slatepack address derivation path index + short: a + long: address_index + takes_value: true - pay: about: Spend coins to pay the provided invoice transaction args: diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 32be712..fdee2b4 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -20,7 +20,6 @@ use crate::util::file::get_first_line; use crate::util::secp::key::SecretKey; use crate::util::{Mutex, ZeroingString}; -use clap::ArgMatches; use grin_core as core; use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; @@ -29,8 +28,11 @@ use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; +use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider}; + +use clap::ArgMatches; use linefeed::terminal::Signal; use linefeed::{Interface, ReadResult}; use rpassword; @@ -38,6 +40,7 @@ use std::convert::TryFrom; use std::io::{IsTerminal, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; +use uuid::Uuid; // define what to do on argument error macro_rules! arg_parse { @@ -526,6 +529,8 @@ pub fn parse_send_args(args: &ArgMatches) -> Result Result Result { - // input file - let input_file = match args.is_present("input") { - true => { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", file); +fn parse_address_index_arg(args: &ArgMatches) -> Result, ParseError> { + let address = if let Some(i) = parse_optional(args, "address_index")? { + let val = i.parse::(); + match val { + Ok(v) => Some( + SlatepackAddressIndex(v) + .check() + .map_err(|e| ParseError::ArgumentError(e.to_string()))?, + ), + Err(e) => { + let msg = format!("Could not parse address_index as a whole number. e={}", e); return Err(ParseError::ArgumentError(msg)); } - Some(file) } - false => None, + } else { + None }; + Ok(address) +} + +pub fn parse_receive_args(args: &ArgMatches) -> Result { + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -590,8 +604,7 @@ pub fn parse_receive_args(args: &ArgMatches) -> Result Result { - // input file +fn parse_input_file_arg(args: &ArgMatches) -> Result, ParseError> { let input_file = match args.is_present("input") { true => { let file = args.value_of("input").unwrap().to_owned(); @@ -604,6 +617,11 @@ pub fn parse_unpack_args(args: &ArgMatches) -> Result None, }; + Ok(input_file) +} + +pub fn parse_unpack_args(args: &ArgMatches) -> Result { + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -636,18 +654,7 @@ pub fn parse_finalize_args(args: &ArgMatches) -> Result { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", file); - return Err(ParseError::ArgumentError(msg)); - } - Some(file) - } - false => None, - }; + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -702,12 +709,15 @@ pub fn parse_issue_invoice_args( let slatepack_qr = args.is_present("slatepack_qr"); + let address_index = parse_address_index_arg(args)?; + Ok(command::IssueInvoiceArgs { dest, issue_args: IssueInvoiceTxArgs { dest_acct_name: None, amount, target_slate_version, + address_index, }, outfile, slatepack_qr, @@ -757,7 +767,7 @@ pub fn parse_process_invoice_args( args: &ArgMatches, prompt: bool, slate: Slate, - ret_address: Option, + mut ret_address: Option, ) -> Result { // minimum_confirmations let min_c = parse_required(args, "minimum_confirmations")?; @@ -776,9 +786,18 @@ pub fn parse_process_invoice_args( let max_outputs = 500; if prompt { - let dest = match ret_address.clone() { - Some(a) => String::try_from(&a).unwrap(), - None => String::from(""), + let dest = parse_optional(args, "dest")?; + let dest = match dest { + Some(dest) => { + ret_address = Some(SlatepackAddress::try_from(dest.as_str()).map_err(|e| { + ParseError::ArgumentError(format!("Can not parse destination address {}", e)) + })?); + dest + } + None => match ret_address.clone() { + Some(a) => String::try_from(&a).unwrap(), + None => String::from(""), + }, }; // Now we need to prompt the user whether they want to do this, prompt_pay_invoice(&slate, &dest)?; @@ -842,16 +861,7 @@ pub fn parse_txs_args(args: &ArgMatches) -> Result None => None, Some(tx) => Some(parse_u64(tx, "id")? as u32), }; - let tx_slate_id = match args.value_of("txid") { - None => None, - Some(tx) => match tx.parse() { - Ok(t) => Some(t), - Err(e) => { - let msg = format!("Could not parse txid parameter. e={}", e); - return Err(ParseError::ArgumentError(msg)); - } - }, - }; + let tx_slate_id = parse_tx_slate_id_arg(args)?; if tx_id.is_some() && tx_slate_id.is_some() { let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string(); return Err(ParseError::ArgumentError(msg)); @@ -867,22 +877,24 @@ pub fn parse_txs_args(args: &ArgMatches) -> Result }) } +fn parse_tx_slate_id_arg(args: &ArgMatches) -> Result, ParseError> { + let tx_slate_id = match args.value_of("txid") { + None => None, + Some(tx) => match tx.parse() { + Ok(t) => Some(t), + Err(e) => { + let msg = format!("Could not parse txid parameter. e={}", e); + return Err(ParseError::ArgumentError(msg)); + } + }, + }; + Ok(tx_slate_id) +} + pub fn parse_post_args(args: &ArgMatches) -> Result { let fluff = args.is_present("fluff"); - // input file - let input_file = match args.is_present("input") { - true => { - let file = args.value_of("input").unwrap().to_owned(); - // validate input - if !Path::new(&file).is_file() { - let msg = format!("File {} not found.", file); - return Err(ParseError::ArgumentError(msg)); - } - Some(file) - } - false => None, - }; + let input_file = parse_input_file_arg(args)?; let mut input_slatepack_message = None; if input_file.is_none() { @@ -948,16 +960,7 @@ pub fn parse_export_proof_args(args: &ArgMatches) -> Result None, Some(tx) => Some(parse_u64(tx, "id")? as u32), }; - let tx_slate_id = match args.value_of("txid") { - None => None, - Some(tx) => match tx.parse() { - Ok(t) => Some(t), - Err(e) => { - let msg = format!("Could not parse txid parameter. e={}", e); - return Err(ParseError::ArgumentError(msg)); - } - }, - }; + let tx_slate_id = parse_tx_slate_id_arg(args)?; if tx_id.is_some() && tx_slate_id.is_some() { let msg = "At most one of 'id' (-i) or 'txid' (-t) may be provided.".to_string(); return Err(ParseError::ArgumentError(msg)); @@ -1055,8 +1058,7 @@ where } else { None }; - let mut owner_api = Owner::new(wallet.clone(), None, config.config_file_path.clone()); - command::unpack(&mut owner_api, mask.as_ref(), slatepack)?; + command::unpack(wallet.clone(), mask.as_ref(), slatepack)?; return Ok("unpack".to_string()); } ("owner_api", _) => { @@ -1237,7 +1239,7 @@ where ("unpack", Some(args)) => { let a = arg_parse!(parse_unpack_args(args)); let slatepack = command::read_slatepack(a)?; - command::unpack(owner_api, km, slatepack) + command::unpack(owner_api.wallet_inst.clone(), km, slatepack) } ("finalize", Some(args)) => { let a = arg_parse!(parse_finalize_args(args)); diff --git a/tests/cmd_line_basic.rs b/tests/cmd_line_basic.rs index 55ce29a..92afa59 100644 --- a/tests/cmd_line_basic.rs +++ b/tests/cmd_line_basic.rs @@ -235,6 +235,12 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: "10", ]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + let args = vec!["grin-wallet", "-p", "unused", "unpack", "-i", &file_name]; + assert_eq!( + execute_command(&app, test_dir, "wallet1", &client1, args)?, + "unpack" + ); + let arg_vec = vec!["grin-wallet", "-a", "mining", "-p", "password1", "txs"]; execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; @@ -810,6 +816,127 @@ fn command_line_test_impl(test_dir: &str) -> Result<(), grin_wallet_controller:: let (_, wallet_info) = api2.retrieve_summary_info(mask2, true, 1)?; assert!(wallet_info.amount_currently_spendable < old_balance); + // Issue encrypted invoice using custom address index, wallet2. + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password2", + "invoice", + "--address_index", + "3", + "-d", + "tgrin1fu5z9y4p8atxr83l6nfj0j2m067r9gjfkd6mzeuuz0v6sqftua2quv0ll3", + "1", + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + let file_name = format!( + "{}/wallet2/slatepack/0436430c-2b02-624c-2032-570501212b08.I1.slatepack", + test_dir + ); + + // Pay the invoice tx, wallet 1 + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password1", + "pay", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + + let file_name = format!( + "{}/wallet1/slatepack/0436430c-2b02-624c-2032-570501212b08.I2.slatepack", + test_dir + ); + + // Finalize the invoice, wallet 2 + let arg_vec = vec![ + "grin-wallet", + "-a", + "default", + "-p", + "password2", + "finalize", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec)?; + + // Send encrypted to wallet 2 using custom address index + let arg_vec = vec![ + "grin-wallet", + "-p", + "password1", + "-a", + "mining", + "send", + "-d", + "tgrin1ak8aaxpjg6ct5uje4lgzvjp65l0nrmgxndp5xjy74sumzp7wasysje3kmf", + "--address_index", + "5", + "1", + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + + // Receive, wallet 2 + let file_name = format!( + "{}/wallet1/slatepack/0436430c-2b02-624c-2032-570501212b09.S1.slatepack", + test_dir + ); + for (wallet, password, account, client) in [ + ("wallet1", "password1", "mining", &client1), + ("wallet2", "password2", "account_1", &client2), + ] { + let args = vec![ + "grin-wallet", + "-p", + password, + "-a", + account, + "unpack", + "-i", + &file_name, + ]; + assert_eq!( + execute_command(&app, test_dir, wallet, client, args)?, + "unpack" + ); + } + let arg_vec = vec![ + "grin-wallet", + "-p", + "password2", + "-a", + "account_1", + "receive", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet2", &client2, arg_vec.clone())?; + + let file_name = format!( + "{}/wallet2/slatepack/0436430c-2b02-624c-2032-570501212b09.S2.slatepack", + test_dir + ); + + // Finalize the send, wallet 1 + let arg_vec = vec![ + "grin-wallet", + "-a", + "mining", + "-p", + "password1", + "finalize", + "-i", + &file_name, + ]; + execute_command(&app, test_dir, "wallet1", &client1, arg_vec)?; + // let logging finish thread::sleep(Duration::from_millis(200)); clean_output_dir(test_dir); From b5c38187135616cb2c1f44853525d925fe6a3bd1 Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 14 Oct 2026 16:29:15 +0300 Subject: [PATCH 37/39] Update jayson to 5 (#834) * build: update jayson to 5 * docs: update readme for node and remove unused override --- doc/samples/v3_api_node/package-lock.json | 49 +++-------------------- doc/samples/v3_api_node/package.json | 5 +-- doc/samples/v3_api_node/readme.md | 2 +- 3 files changed, 7 insertions(+), 49 deletions(-) diff --git a/doc/samples/v3_api_node/package-lock.json b/doc/samples/v3_api_node/package-lock.json index 0649ef6..6cc6f67 100644 --- a/doc/samples/v3_api_node/package-lock.json +++ b/doc/samples/v3_api_node/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.1", "license": "ISC", "dependencies": { - "jayson": "^4.3.0" + "jayson": "^5.0.0" } }, "node_modules/@types/connect": { @@ -65,14 +65,6 @@ "es6-promise": "^4.0.3" } }, - "node_modules/eyes": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", - "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", - "engines": { - "node": "> 0.1.90" - } - }, "node_modules/isomorphic-ws": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz", @@ -83,9 +75,9 @@ } }, "node_modules/jayson": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/jayson/-/jayson-4.3.0.tgz", - "integrity": "sha512-AauzHcUcqs8OBnCHOkJY280VaTiCm57AbuO7lqzcw7JapGj50BisE3xhksye4zlTSR1+1tAz67wLTl8tEH1obQ==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/jayson/-/jayson-5.0.0.tgz", + "integrity": "sha512-FghxOWlJB5ZPsRsuMF1U4GFHjkJfOEYSlIHpI6Wt6MXIzvqWVo0Kpl7/SMfY36vWggA+b+L09zRGP6m4ROVnKg==", "license": "MIT", "dependencies": { "@types/connect": "^3.4.33", @@ -94,18 +86,15 @@ "commander": "^2.20.3", "delay": "^5.0.0", "es6-promisify": "^5.0.0", - "eyes": "^0.1.8", "isomorphic-ws": "^4.0.1", "json-stringify-safe": "^5.0.1", - "stream-json": "^1.9.1", - "uuid": "^8.3.2", "ws": "^7.5.10" }, "bin": { "jayson": "bin/jayson.js" }, "engines": { - "node": ">=8" + "node": ">=20" } }, "node_modules/json-stringify-safe": { @@ -113,34 +102,6 @@ "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=" }, - "node_modules/stream-chain": { - "version": "2.2.5", - "resolved": "https://registry.npmjs.org/stream-chain/-/stream-chain-2.2.5.tgz", - "integrity": "sha512-1TJmBx6aSWqZ4tx7aTpBDXK0/e2hhcNSTV8+CbFJtDjbb+I1mZ8lHit0Grw9GRT+6JbIrrDd8esncgBi8aBXGA==", - "license": "BSD-3-Clause" - }, - "node_modules/stream-json": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/stream-json/-/stream-json-1.9.1.tgz", - "integrity": "sha512-uWkjJ+2Nt/LO9Z/JyKZbMusL8Dkh97uUBTv3AJQ74y07lVahLY4eEFsPsE97pxYBwr8nnjMAIch5eqI0gPShyw==", - "license": "BSD-3-Clause", - "dependencies": { - "stream-chain": "^2.2.5" - } - }, - "node_modules/uuid": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.1.tgz", - "integrity": "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "license": "MIT", - "bin": { - "uuid": "dist/esm/bin/uuid" - } - }, "node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", diff --git a/doc/samples/v3_api_node/package.json b/doc/samples/v3_api_node/package.json index fb89fc9..71bdfff 100644 --- a/doc/samples/v3_api_node/package.json +++ b/doc/samples/v3_api_node/package.json @@ -9,9 +9,6 @@ "author": "", "license": "ISC", "dependencies": { - "jayson": "^4.3.0" - }, - "overrides": { - "uuid": "^11.1.1" + "jayson": "^5.0.0" } } diff --git a/doc/samples/v3_api_node/readme.md b/doc/samples/v3_api_node/readme.md index ed8e907..1a490ca 100644 --- a/doc/samples/v3_api_node/readme.md +++ b/doc/samples/v3_api_node/readme.md @@ -20,7 +20,7 @@ The sample sends it as the password for the `grin` user. If `api_secret_path` is Ensure the client connection settings in `src/index.js` match the Owner API address. -Then (assuming node.js and npm are installed on the system): +Then (assuming Node.js >=20 and npm are installed on the system): ```.sh npm install From 6429e38cafb265e19a4b04263dca08aae168ad2a Mon Sep 17 00:00:00 2001 From: ardocrat Date: Wed, 14 Oct 2026 16:37:53 +0300 Subject: [PATCH 38/39] build: update grin submodule --- grin | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/grin b/grin index 7f100ed..da95576 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit 7f100ed59a71fff377b40106140b5235ad56b051 +Subproject commit da955767a35a59cf1d8790a4a4dd70a49372710b From 90846a4212329d861a73ed47959ed3ef85f8a68b Mon Sep 17 00:00:00 2001 From: wiesche <120273695+wiesche89@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:15:56 +0200 Subject: [PATCH 39/39] Mwixnet wallet support (#783) * Update rust edition to 2021 (#749) * build: update rust edition 2021 * cargo: format all * build: fix tests and warnings * Save last scanned block info for wallet scanning (#748) * scan: save last scanned block info for initial wallet scanning * scan: save start height at scanned block info on outputs collecting * scan: 10k blocks batches * fix: include last height into batch on scan * scan: save hash of last block * scan: add larger window (2880 blocks) to scan outputs when updating wallet state * add test batched scan and resume, add scan doc * rename corrupted restore test --------- Co-authored-by: Joerg * Bump openssl from 0.10.68 to 0.10.80 (#752) * Update lmdb (#755) * wallet: update lmdb from store crate, migrate single backend from trait to struct, update tests cargo deps and design doc * backend: do not panic on iter and directory creation * return iterator errors * build: update to last node revision * fix: height selection for scan, remove unused mutability for wallet * wallet: remove unused mutability conversion * tx: store slate state at database * build: cargo fmt * fix: do not return error when slate not found on tx slate state update * lmdb: do not collect all tx log records at iterator, show read errors at log * fix: save slate state, return error if slate not found * tx: specify amount of bad txs on slate state update error --------- Co-authored-by: Joerg * Node submodules (#758) * build: use node submodule as dependency * ci: checkout submodules * docs: add contributing and build instruction * ci: update release build * git: remove old submodule * git: grin staging submodule * git: add submodule dir * Integrated Tor arti Client (#750) * tor: integrated client for listener, update tokio to last version * tor: send transaction with integrated client * build: code format * tor: optimize bootstrap percent check * tor: handle config build error * tor: do not show slatepack address if tor not launched * tor: handle keystore errors * tor: keep service launched * tor: bootstrap timeout, clean cache before client launch * tor: post request timeout * fix: post timeout * build: update deps after merge * tor: store arti runtime * tor: do not send over tor if `manual` arg presents or `skip_send_attempt` set at config * fix: arg name * tor: handle arti runtime creation error * tor: handle connection error * tor: handle bootstrap error * tor: handle start service name error * tor: handle service config creation error * tor: service proxy errors * tor: handle service key creation emptiness * build: format code * build: update arti to 0.43, hyper to 0.10.1 * api: start foreign listener before tor connection * tor: handle json parse errors * tor: prevent to create several client runtimes, ability to recreate * tor: return bootstrap error * tor: handle host parse error * tor: restart proxy on error * tor: do not use integrated client when config value use_integrated is missing, add logging * build: update lock file * Global Tor client state (#762) * tor: global client state * tor: optimize init client thread-safety * tor: handle config change on client init * tor: add logging for client reuse or reinit * tor: do not reuse arti client for requests * Optimize tor sync flow (#763) * Connection timeout (#765) * Update deps (#768) * build: update grin submodule to last staging * build: update grin submodule * build: remove remove_dir_all dependency * build: update rpassword * build: update semver * build: remove unused deps * build: update ring * build: update lock file deps * build: update rustyline * build: update ed25519-dalek * build: update curve25519-dalek * build: update age * build: update uuid * fix: uuid test * build: update x25519-dalek * fix: x25519-dalek build * build: update arti * build: update grin submodule * build: update hyper * fix: initialize rustls provider for tests * build: update grin submodule * fix: rustls install provider * tor: share getting private key * fix: show an error on node version parse * cli: renamed prompt password method * fix: replace into_boxed_slice with try_from * fix: dalek tests for onion * config: comment expanded secret key * fix: import api body for controller * password: handle prompt error * wallet: parse node error message * tests: do not use random values for sign messages * build: make hook executable * build: cargo format all * rustls: do not install provider at tests and globally * build: update grin submodule * build: fix api channel from grin submodule * args: use read_password for piped prompt * build: remove unused dep * test: fixed signature * preserve piped pw input --------- Co-authored-by: wiesche * Bump lodash from 4.17.21 to 4.18.1 (#774) * build: update lodash to 4.18.1 * fix: readme * docs: add owner api authentication setup * build: update package-lock.json to version 3 * fix: token result, inline some vars --------- Co-authored-by: ardocrat * Global config instance (#769) * config: global instance * fix: cli tests * fix: owner api tests * config: save tor config * fix: owner rpc tests * fix: set config file path on init and owner api call * tor: store launched services, get global config at command loop, remove unused listen args, check for empty global config to set default, do not save empty tor config at owner * api: update config in memory after successful file write * arti: restart proxy in loop * fix: comment for tor config save * config: set or init, update without error * config: scoped tor config * build: update lock file * config: ability to store multiple configurations at memory from config path * tor: restart service on config change * fix: owner api test * foreign: pass tor config from args, stop service, error handling * arti: move runtime wrapper to single file * config: read existing config from file at create_config * config: handle error on read * arti: single dir for cache * foreign: register config listener before launch * config: save temp * config: remove unused error type * config: make path and members not optional, return an error on config creation if it exists, pass default tor config to send if not set * arti: non public runtime wrapper * config: migrate comments * fix: rpc tests * config: return from cache if exists * config: save disabled tor config when null provided at owner and tor section was not set * config: update tor with args at listener * config: pass pathbuf directly on creation * config: unique tmp file name, setting permissions and providing config version * fix global config handling * fix config persistence * fix tor service restart * fix config synchronization * require wallet close before changing data directory * unify global config updates --------- Co-authored-by: wiesche * Wrong Slatepack address fix (#773) * Use native tls for client (#779) * client: use native tls and disable default features for reqwest * build: bring back reqwest default features except tls * client: remove tls selection * expose mwixnet onion apis (#781) * Update jayson and uuid (#777) * build: update jayson and uuid * npm: update lock file to v3 * npm: update lock file --------- Co-authored-by: ardocrat * Optimize outputs scan and selection (#780) * Make updater APIs public (#782) * Add mwixnet wallet request support * mwixnet key conversion tests * validate and track mwixnet requests * fix Arti HTTP POST request formatting * add mwixnet wallet CLI submission * unlock mwixnet outputs when requests are not sent * support automatic mwixnet output selection * move mwixnet response parsing to libwallet * limit mwixnet hops * centralize grin workspace dependencies * fix tx filter * handle unavailable terminal colors * reject invalid invoice locking * clarify bip32 derivation paths * restore derivation path comments * tor: downgrade arti to 0.43 * owner: put active account on top of list * account table layout * fix: some typos, imports, unwraps and formatting * tx: lock outputs before sending with tor * accounts: display balances at CLI and from owner API when min confirmations are set * unpack plain slatepacks without password (#805) * unpack plain slatepacks without password * cli: better open wallet handling on wallet subcommand --------- Co-authored-by: ardocrat * account: do not skip info from serialization, fix owner rpc test * reject zero send amounts (#799) * cli: fix short for min confirmations at accounts subcommand * accounts: optimize accounts selection * owner: document minimum_confirmations for accounts * accounts: optimize selection * preserve accounts api compatibi and clean up balances * avoid empty wallet seeds (#801) * fix empty wallet seeds * mnemonic: return actual error with entropy size on recovering * seed: extend mnemonic error description * seed: clarify mnemonic errors * seed: clarify mnemonic errors, fix missing phrase test * Clean up seed handling add test --------- Co-authored-by: ardocrat * owner: use same wallet lock for selecting and locking outputs on send * fix: do not lock for late lock * cli: explain how to cancel * fix: error message for offline address and integrated tor * test: late lock for cli and owner api * wallet: persistence for active account * fix: owner_rpc test * fix: lock wallet till lock outputs on send * fix: update docs when to call tx_lock_outputs * build: update grin submodule * tests: get rid of owner_single_use to use correct config path * test: parallel send attempts * fix: cancel hint * fix: late lock test refresh balance * fix: set active account at single batch * owner: document persistence of set_active_account * cli: error when create and active args are present at account * fix: keep display account type as str * restore windows test fixes * fix locking docs cancel hint and tests * test cli send failure * fix current account flag * fix active account use * test account persistence * fix cli account selection * fix: cmd tests * fix: cmd test * fix account test * Show HTTP status when node requests fail (#820) * ci: cargo clippy * fix submodule checkout * update grin for clippy fixes * isolate tests * fix cli test * fix clippy warnings * fix mwixnet output lookup * build: update grin submodule * git: add clippy to hook * fix review nits * fix checks * mwixnet: use MwixnetServerPublicKey wrapper for hop * build: update grin submodule * build: clippy fixes * mwixnet: rename dalek public key * simplify mwixnet keys * clarify mwixnet docs * clarify arti usage * simplify mwixnet tests * tidy mwixnet code and docs * skip spent outputs * simplify mwixnet send * drop host clone * fix mwixnet selection and arti errors * make mwixnet fee optional * mwixnet: use fee at amount format, show min on error * fix: fee per hop test * fix: fee error text check * tor: increase circuit timeout to 60 * fix mwixnet refresh and help * build: update grin submodule and mwixnet tests * cli: do not update wallet state on cancellation of tx after failed mwixnet request * mwixnet: create separate owner api method to send request, do not cancel tx on failed mwixnet request * fix mwixnet cli args and error messages --------- Co-authored-by: ardocrat Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 20 +- api/src/owner.rs | 113 +++++++++-- api/src/owner_rpc.rs | 50 ++--- controller/src/command.rs | 123 +++++++++++- controller/tests/mwixnet.rs | 167 +++++++++++++++- grin | 2 +- impls/src/adapters/tor.rs | 2 +- impls/src/lib.rs | 1 + impls/src/tor/arti.rs | 145 ++++++++++---- libwallet/src/api_impl/owner.rs | 202 ++++++++++++-------- libwallet/src/mwixnet/mod.rs | 9 +- libwallet/src/mwixnet/onion/crypto/dalek.rs | 54 +++--- libwallet/src/mwixnet/onion/mod.rs | 142 +++++++++++--- libwallet/src/mwixnet/onion/onion.rs | 27 ++- libwallet/src/mwixnet/response.rs | 105 ++++++++++ libwallet/src/mwixnet/types.rs | 76 +++++++- src/bin/grin-wallet.yml | 30 +++ src/cmd/wallet_args.rs | 137 +++++++++++++ 18 files changed, 1161 insertions(+), 244 deletions(-) create mode 100644 libwallet/src/mwixnet/response.rs diff --git a/Cargo.lock b/Cargo.lock index d6452a1..2354a45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2233,7 +2233,7 @@ checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" [[package]] name = "grin_api" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bytes 1.12.0", "easy-jsonrpc-mw", @@ -2265,7 +2265,7 @@ dependencies = [ [[package]] name = "grin_chain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bit-vec", "bitflags 1.3.2", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "grin_core" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2315,7 +2315,7 @@ dependencies = [ [[package]] name = "grin_keychain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2336,7 +2336,7 @@ dependencies = [ [[package]] name = "grin_p2p" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bitflags 1.3.2", "built", @@ -2359,7 +2359,7 @@ dependencies = [ [[package]] name = "grin_pool" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "chrono", @@ -2376,9 +2376,9 @@ dependencies = [ [[package]] name = "grin_secp256k1zkp" -version = "0.7.15" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7bb95f155b1eede2648a1b9afbba82bc3d9f2af0518b478767559a572bd973" +checksum = "57e0a5f761e8c56db5be865f79832677d3badb3be91d7172d468e448f3d69f82" dependencies = [ "arrayvec 0.7.8", "cc", @@ -2391,7 +2391,7 @@ dependencies = [ [[package]] name = "grin_store" -version = "5.5.1" +version = "5.5.2" dependencies = [ "byteorder", "chrono", @@ -2413,7 +2413,7 @@ dependencies = [ [[package]] name = "grin_util" -version = "5.5.1" +version = "5.5.2" dependencies = [ "anyhow", "backtrace", diff --git a/api/src/owner.rs b/api/src/owner.rs index 368b999..d124b64 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -14,6 +14,7 @@ //! Owner API External Definition +use crate::config::config::{reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME}; use crate::config::{TorConfig, WalletConfig}; use crate::core::core::OutputFeatures; use crate::core::global; @@ -23,7 +24,11 @@ use crate::keychain::{Identifier, Keychain}; use crate::libwallet::api_impl::owner_updater::{start_updater_log_thread, StatusMessage}; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::api_impl::{owner, owner_updater}; +use crate::libwallet::mwixnet::{parse_mwixnet_response, MwixnetResponse, SwapReq}; +use crate::libwallet::mwixnet::{MixnetReqCreationParams, MwixnetReqCreationResult}; +use crate::libwallet::slatepack::SlatepackAddressIndex; use crate::libwallet::wallet_lock; +use crate::libwallet::RetrieveTxQueryArgs; use crate::libwallet::{ AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, @@ -32,13 +37,9 @@ use crate::libwallet::{ use crate::util::logger::LoggingConfig; use crate::util::secp::{key::SecretKey, pedersen::Commitment}; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; -use grin_wallet_config::config::{ - reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME, -}; -use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq}; -use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; -use grin_wallet_libwallet::RetrieveTxQueryArgs; use grin_wallet_util::OnionV3Address; +use impls::json_rpc; +use impls::tor::arti::tor_post; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; @@ -1318,6 +1319,7 @@ where &tx, tx_id, tx_slate_id, + true, ) } @@ -2606,21 +2608,22 @@ where // MWIXNET - /// Creates a mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html) + /// Creates a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) /// from a given output commitment under this wallet's control. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// being used. - /// * `params` - A [MixnetReqCreationParams](../grin_wallet_libwallet/api_impl/types/struct.MixnetReqCreationParams.html) + /// * `params` - A [MixnetReqCreationParams] /// struct containing the parameters for the request, which include: - /// `server_keys` - The public keys of the servers participating in the mixnet (each encoded internally as a `SecretKey`) - /// `fee_per_hop` - The fee to be paid to each server for each hop in the mixnet + /// `server_keys` - Published X25519 onion keys in route order, not Ed25519 identity keys + /// or private keys + /// `fee_per_hop` - Optional fee per hop with the swap minimum as default /// * `commitment` - The commitment of the output to be mixed /// * `lock_output` - Whether to lock the referenced output after creating the request /// /// # Returns - /// * Ok([SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html)) if successful + /// * Ok([MwixnetReqCreationResult](../grin_wallet_libwallet/mwixnet/struct.MwixnetReqCreationResult.html)) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered /// /// # Example @@ -2631,8 +2634,10 @@ where /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let keychain_mask = None; /// let params = MixnetReqCreationParams { - /// server_keys: vec![], // Public keys here in secret key representation - /// fee_per_hop: 100, + /// server_keys: vec![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, /// }; /// /// let commitment = Commitment::from_vec(vec![0; 32]); @@ -2645,7 +2650,7 @@ where /// lock_output, /// ); /// - /// if let Ok(req) = result { + /// if let Ok(result) = result { /// //... /// } /// ``` @@ -2655,9 +2660,8 @@ where params: &MixnetReqCreationParams, commitment: &Commitment, lock_output: bool, // use_test_rng: bool, - ) -> Result { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + ) -> Result { + wallet_lock!(self.wallet_inst, w); owner::create_mwixnet_req( w, keychain_mask, @@ -2667,6 +2671,81 @@ where self.doctest_mode, ) } + + /// Sends a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) + /// to provided onion server. + /// + /// # Arguments + /// * `req` - A [SwapReq] + /// struct containing the parameters for the request, which include: + /// `comsig` - [ComSignature](grin_wallet_libwallet::mwixnet::ComSignature) signature with a pedersen commitment value & blinding factors as the keys + /// `onion` - [Onion](grin_wallet_libwallet::mwixnet::Onion) encrypted route payload + /// * `server` - Onion server address + /// + /// # Returns + /// * `Ok(None)` if the server accepted the request + /// * `Ok(Some(message))` if the server rejected the request + /// * `Err` for configuration, transport, or invalid-response failures + /// + /// Leaves output locks unchanged + /// + /// # Example + /// Set up as in [`new`](struct.Owner.html#method.new) method above. + /// ``` + /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); + /// + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); + /// let keychain_mask = None; + /// let params = MixnetReqCreationParams { + /// server_keys: vec![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, + /// }; + /// + /// let commitment = Commitment::from_vec(vec![0; 32]); + /// let lock_output = true; + /// + /// let result = api_owner.create_mwixnet_req( + /// keychain_mask, + /// ¶ms, + /// &commitment, + /// lock_output, + /// ); + /// + /// if let Ok(result) = result { + /// let server = "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into().unwrap(); + /// let result = api_owner.send_mwixnet_req(&result.request, server); + /// if let Ok(result) = result { + /// //.. + /// } + /// } + /// ``` + pub fn send_mwixnet_req( + &self, + req: &SwapReq, + server: OnionV3Address, + ) -> Result, Error> { + let url = format!("{}/v1", server.to_http_str()); + let rpc_params = serde_json::json!([req]); + let rpc_request = json_rpc::build_request("swap", &rpc_params); + let tor_config = crate::tor_config::load(&self.config_path())?; + let response = match tor_post(&tor_config, &rpc_request, &url) { + Ok(response) => response, + Err(e) => { + return Err(Error::GenericError(format!( + "Could not determine whether mwixnet accepted the request: {}", + e, + ))); + } + }; + match parse_mwixnet_response(&response).map_err(|e| { + Error::GenericError(format!("Could not confirm the mwixnet response: {}", e)) + })? { + MwixnetResponse::Accepted => Ok(None), + MwixnetResponse::Rejected(message) => Ok(Some(message)), + } + } } /// attempt to send slate synchronously with TOR diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 6532e24..7c5eba4 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -14,7 +14,7 @@ //! JSON-RPC Stub generation for the Owner API use grin_wallet_libwallet::RetrieveTxQueryArgs; -use libwallet::mwixnet::SwapReq; +use libwallet::mwixnet::MwixnetReqCreationResult; use uuid::Uuid; use crate::config::{TorConfig, WalletConfig}; @@ -22,10 +22,11 @@ use crate::core::core::OutputFeatures; use crate::core::global; use crate::keychain::{Identifier, Keychain}; use crate::libwallet::{ - mwixnet::MixnetReqCreationParams, AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, - IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, - SlateVersion, Slatepack, SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, - ViewWallet, WalletInfo, WalletLCProvider, + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}, + AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, + NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, SlateVersion, Slatepack, + SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, ViewWallet, WalletInfo, + WalletLCProvider, }; use crate::util::logger::LoggingConfig; use crate::util::secp::key::{PublicKey, SecretKey}; @@ -2062,7 +2063,11 @@ pub trait OwnerRpc { ) -> Result; /** - Networked version of [Owner::build_output](struct.Owner.html#method.create_mwixnet_req). + Networked version of [Owner::create_mwixnet_req](struct.Owner.html#method.create_mwixnet_req). + + server_keys accepts public X25519 onion keys as hex, in route order, replacing secret keys + fee_per_hop accepts a nanogrin string or null for the swap minimum + ``` # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( # r#" @@ -2072,12 +2077,12 @@ pub trait OwnerRpc { "params": { "token": "d202964900000000d302964900000000d402964900000000d502964900000000", "commitment": "08e1da9e6dc4d6e808a718b2f110a991dd775d65ce5ae408a4e1f002a4961aa9e7", - "fee_per_hop": "5000000", + "fee_per_hop": null, "lock_output": true, "server_keys": [ - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332", - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e", - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5" + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + "3ab3b7d1fb643393897a0b942934d34be9cb823621cd49c09b12fdfa69598d71", + "80f2ceadcc5a767961772f4ae04826c70b0ae497f4f50d782241ff056b71df45" ] }, "id": 1 @@ -2099,12 +2104,13 @@ pub trait OwnerRpc { "62ea6b8369686a0415e1e752b9b4d6e66cf5b6066a2d3c60d8818890a55f3adff4601466f4c6e6b646568b99ae93549a3595b7a7b4be815ced87d9297cabbd69518d7b2ed6edd14007528fd346aaea765a1165fe886666627ebcab9588b8ee1c9e98395ae67913c48eb6e924581b40182fce807f97312fb07fd5e216d99941f2b488babce4078a50cd66b28b30a66c4f54fcc127437408a99b30ffd6c3d0d8c7d39e864fc04e321b8c10138c8852d4cad0a4f2780412b9dadcc6e0f2657b7803a81bccb809ca392464be2e01755be7377d0e815698ad6ea51d4617cc92c3ccf852f038e33cc9c90992438ba5c49cca7cc188b682da684e2f4c9733a84a7b64ac5c2216ebf5926f0ee67b664fb5bab799109cbee755ce1aebc8cd352fea51cd84c333cb958093c53544c3f3ab05dba64d8f041c3b179796b476ec04b11044e39db6994ab767315e52cc0ef023432ec88ade2911612db7e74e0923889f765b58b00e3869c5072a4e882c1b721913f63bda986b8c97b7ae575f0d4be596a1ac3cd0db96ce6074ee000b32018b3bda16d7dba34a13ba9c3ce983946414c16e278351a3411cb8ef2cb8ef5b6e1667c4c58bc797c0324ae4fec8960d684e561c0e833ee4c3331c6c439b59042a62993535e23cc8a8a4cf705c0f9b1d62db4e3d76c22c01138800414b143ddff471e4df4413e842a1b41f43cc9647e47145fd6c86d4d1a34fb2f62f5a55b31c9353ee34743c548eff955f2d2143c1a86cbcb452104f96d0142db31153021bbeed995c71a92de8fb1f97269533a508085c543fcb3ee57000bb265e74187b858403aa97b6c7b085e5d5b6025cbfe5f6926d33c835f90e60fc62013e80bbe0a855da5938b4b8f83ac29c5e8251827795356222079a6d1612e2fdf93bd7836d1613c7a353ada48ce256f880bbbb3108e037e3b5647101bd4d549101b0ee73d2248a932a802a3b1beb0b69d777c4285d57e91d83e96fe2f8a1a2f182fe2c6ca37b18460cf8d7f56c201147b9be19f1d01f8ad305c1e9c4dd79b5d8719d6550432352cf737082b1e9de7a083ffbe1" ], "pubkey": "e7ee7d51b11d09f268ade98bc9d7ae9be3c4ac124ce1c3a40e50d34460fa5f08" - } + }, + "tx_id": 5 } } } # "# - # , 5, true, true, false, false); + # , 5, true, false, false, false); ``` * */ @@ -2112,10 +2118,10 @@ pub trait OwnerRpc { &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result; + ) -> Result; } impl OwnerRpc for Owner @@ -2530,28 +2536,22 @@ where &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result { + ) -> Result { let commit = Commitment::from_vec(from_hex(&commitment).map_err(Error::CommitDeser)?); - let secp_inst = static_secp_instance(); - let secp = secp_inst.lock(); - let mut keys = vec![]; for key in server_keys { - keys.push(SecretKey::from_slice( - &secp, - &grin_util::from_hex(&key).map_err(Error::ServerKeyDeser)?, - )?) + keys.push(MwixnetServerPublicKey::from_hex(&key).map_err(Error::ServerKeyDeser)?) } let req_params = MixnetReqCreationParams { server_keys: keys, fee_per_hop: fee_per_hop - .parse::() - .map_err(|_| Error::U64Deser(fee_per_hop))?, + .map(|fee| fee.parse::().map_err(|_| Error::U64Deser(fee))) + .transpose()?, }; Owner::create_mwixnet_req( diff --git a/controller/src/command.rs b/controller/src/command.rs index 3962cdb..ae2720a 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -22,16 +22,20 @@ use crate::error::Error; use crate::keychain; use crate::libwallet::api_impl::owner::{self, decrypt_slatepack, deserialize_slatepack}; use crate::libwallet::api_impl::types::update_tx_slate_state; +use crate::libwallet::mwixnet::MixnetReqCreationParams; use crate::libwallet::slatepack::get_slatepack_file_contents; use crate::libwallet::slatepack::SlatepackAddressIndex; +use crate::libwallet::OutputCommitMapping; use crate::libwallet::{ self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack, SlatepackAddress, WalletLCProvider, }; use crate::libwallet::{wallet_lock, WalletHandle}; use crate::util::secp::key::SecretKey; -use crate::util::{Mutex, ZeroingString}; +use crate::util::secp::pedersen::Commitment; +use crate::util::{Mutex, ToHex, ZeroingString}; use crate::{controller, display}; +use grin_wallet_util::OnionV3Address; use qr_code::QrCode; use serde_json as json; @@ -1598,6 +1602,123 @@ where } } +pub struct MwixnetArgs { + pub server: OnionV3Address, + pub output: MwixnetOutput, + pub minimum_confirmations: u64, + pub params: MixnetReqCreationParams, +} + +pub enum MwixnetOutput { + Commitment(Commitment), + MinimumAmount(u64), + Max, +} + +fn confirm_mwixnet_response( + response: Result, libwallet::Error>, + tx_id: u32, +) -> Result<(), Error> { + let message = match response { + Ok(None) => { + println!("MWixnet request accepted (transaction {})", tx_id); + return Ok(()); + } + Ok(Some(message)) => format!("MWixnet rejected the request: {}", message), + Err(error) => error.to_string(), + }; + // The server may already have accepted the request + Err(Error::GenericError(format!( + "{}. Output remains locked as transaction {}. The server may already have accepted \ + the request. To cancel manually, use `cancel -i {}`.", + message, tx_id, tx_id + ))) +} + +pub fn mwixnet( + owner_api: &mut Owner, + keychain_mask: Option<&SecretKey>, + args: MwixnetArgs, +) -> Result<(), Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + let height = owner_api.node_height(keychain_mask)?.height; + let (refreshed, outputs) = owner_api.retrieve_outputs(keychain_mask, false, true, None)?; + if !refreshed { + return Err(Error::GenericError( + "Could not refresh wallet outputs. MWixnet request was not created".to_string(), + )); + } + let eligible = |output: &&OutputCommitMapping| { + output + .output + .eligible_to_spend(height, args.minimum_confirmations.max(1)) + }; + let output = match &args.output { + MwixnetOutput::Commitment(commitment) => outputs + .iter() + .find(|output| output.commit == *commitment && eligible(output)), + MwixnetOutput::MinimumAmount(amount) => outputs + .iter() + .filter(eligible) + .filter(|output| output.output.value >= *amount) + .min_by_key(|output| output.output.value), + MwixnetOutput::Max => outputs + .iter() + .filter(eligible) + .max_by_key(|output| output.output.value), + } + .ok_or_else(|| Error::GenericError("No eligible MWixnet output was found".to_string()))?; + let commitment = output.commit; + println!( + "Selected MWixnet output {} with value {}", + commitment.to_hex(), + core::amount_to_hr_string(output.output.value, false) + ); + + let creation = owner_api.create_mwixnet_req(keychain_mask, &args.params, &commitment, true)?; + match creation.tx_id { + None => Err(Error::GenericError( + "MWixnet request was created without locking its output".to_string(), + )), + Some(tx_id) => { + let res = owner_api.send_mwixnet_req(&creation.request, args.server); + confirm_mwixnet_response(res, tx_id) + } + } +} + +#[cfg(test)] +mod tests { + use super::confirm_mwixnet_response; + + #[test] + fn mwixnet_response_reports_uncertain_transactions_as_locked() { + assert!(confirm_mwixnet_response(Ok(None), 3).is_ok()); + let error = + confirm_mwixnet_response(Ok(Some("invalid response".to_string())), 3).unwrap_err(); + assert!(error + .to_string() + .contains("remains locked as transaction 3")); + assert!(error.to_string().contains("cancel -i 3")); + let error = confirm_mwixnet_response( + Err(super::libwallet::Error::GenericError( + "transport failed".into(), + )), + 4, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("transport failed")); + assert!(error.contains("remains locked as transaction 4")); + assert!(error.contains("cancel -i 4")); + assert!(error.contains("may already have accepted")); + } +} + #[cfg(test)] mod send_tests { use super::*; diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 5e81a35..16b348d 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -18,13 +18,17 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; use grin_core as core; +use grin_core::core::FeeFields; use grin_util as util; use grin_util::secp::key::SecretKey; use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{mwixnet::MixnetReqCreationParams, InitTxArgs}; +use libwallet::{ + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey, MAX_MWIXNET_HOPS}, + InitTxArgs, OutputStatus, TxLogEntryType, +}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -141,22 +145,167 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let server_key_3 = SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_3).unwrap())?; let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, + server_keys: vec![ + MwixnetServerPublicKey::from_secret(&server_key_1), + MwixnetServerPublicKey::from_secret(&server_key_2), + MwixnetServerPublicKey::from_secret(&server_key_3), + ], + fee_per_hop: None, }; let outputs = api1.retrieve_outputs(mask1, false, false, None)?; // get last output let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; + // Store the output with an MMR index, like a restored output + let mmr_index = Some(chain.get_output_pos(&last_output.commit).unwrap()); + { + wallet_inst!(wallet1, w); + let mut batch = w.batch(mask1)?; + let mut output = last_output.output.clone(); + batch.delete(&output.key_id, &output.mmr_index)?; + output.mmr_index = mmr_index; + batch.save(output)?; + batch.commit()?; + } - println!("MWIXNET REQ: {:?}", mwixnet_req); + let empty_params = MixnetReqCreationParams { + server_keys: vec![], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &empty_params, &last_output.commit, true) + .is_err()); - // check output we created comsig for is indeed locked + let too_many_params = MixnetReqCreationParams { + server_keys: vec![params.server_keys[0]; MAX_MWIXNET_HOPS + 1], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &too_many_params, &last_output.commit, true) + .is_err()); + + let oversized_fee_params = MixnetReqCreationParams { + server_keys: params.server_keys[..2].to_vec(), + fee_per_hop: Some(1 << 39), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &oversized_fee_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()) + ); + + for fee in [0, 12_499_999] { + let invalid_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(fee), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &invalid_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet fee is below the swap minimum 0.0125".to_string()) + ); + } + let custom_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(25_000_000), + }; + let custom = api1.create_mwixnet_req(mask1, &custom_params, &last_output.commit, false)?; + let mut onion = custom.request.onion; + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion.peel_layer(server_key).unwrap(); + assert_eq!(peeled.payload.fee, FeeFields::try_from(25_000_000u64)?); + onion = peeled.onion; + } + + drop(secp); + + // Failed refresh must not create or lock a swap + let tx_count = api1.retrieve_txs(mask1, false, None, None, None)?.1.len(); + let (disconnected, receiver) = std::sync::mpsc::channel(); + drop(receiver); + let original_proxy = std::mem::replace(&mut *client1.proxy_tx.lock(), disconnected); + let mut api1 = api1; + let result = wallet::command::mwixnet( + &mut api1, + mask1, + wallet::command::MwixnetArgs { + server: "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into()?, + output: wallet::command::MwixnetOutput::Commitment(last_output.commit), + minimum_confirmations: 1, + params: MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: None, + }, + }, + ); + *client1.proxy_tx.lock() = original_proxy; + assert!(result + .unwrap_err() + .to_string() + .contains("Could not refresh wallet outputs")); + assert_eq!( + api1.retrieve_txs(mask1, false, None, None, None)?.1.len(), + tx_count + ); + let outputs = api1.retrieve_outputs(mask1, false, false, None)?.1; + assert_eq!( + outputs + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap() + .output + .status, + OutputStatus::Unspent + ); + + let creation = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; + let creation_tx_id = creation.tx_id.unwrap(); + let fee_per_hop = 12_500_000; + let mut onion = creation.request.onion.clone(); + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion + .peel_layer(server_key) + .map_err(|e| libwallet::Error::GenericError(e.to_string()))?; + assert_eq!(peeled.payload.fee, FeeFields::try_from(fee_per_hop)?); + onion = peeled.onion; + } + + println!("MWIXNET REQ: {:?}", creation.request); + + // Check the input lock and expected output are tracked together. let outputs = api1.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert_eq!(last_output.output.status, libwallet::OutputStatus::Locked); + let input = outputs + .1 + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap(); + assert_eq!(input.output.status, OutputStatus::Locked); + assert_eq!(input.output.mmr_index, mmr_index); + let total_fee = fee_per_hop * params.server_keys.len() as u64; + let expected_amount = last_output.output.value - total_fee; + let expected_output = outputs + .1 + .iter() + .find(|o| o.output.status == OutputStatus::Unconfirmed && o.output.value == expected_amount) + .unwrap(); + assert_eq!( + input.output.tx_log_entry, + expected_output.output.tx_log_entry + ); + + let txs = api1.retrieve_txs(mask1, false, None, None, None)?.1; + let tx = txs.last().unwrap(); + assert_eq!(creation_tx_id, tx.id); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx.amount_debited, last_output.output.value); + assert_eq!(tx.amount_credited, expected_amount); + assert_eq!(tx.num_inputs, 1); + assert_eq!(tx.num_outputs, 1); + assert_eq!(tx.fee, Some(FeeFields::try_from(total_fee)?)); + + assert!(api1 + .create_mwixnet_req(mask1, ¶ms, &last_output.commit, false) + .is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/grin b/grin index 4182d34..da95576 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit 4182d3422175184d723232d23f85ac4ec6990285 +Subproject commit da955767a35a59cf1d8790a4a4dd70a49372710b diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index b5233fc..1684e12 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -187,7 +187,7 @@ impl TorSlateSender { client.send_request(req)? } else { tor_post(&self.config, &input, url) - .map_err(|e| ClientError::RequestError(format!("{:?}", e)))? + .map_err(|e| ClientError::RequestError(e.to_string()))? }; Ok(res) } diff --git a/impls/src/lib.rs b/impls/src/lib.rs index 4ff0c1b..f5c9b5b 100644 --- a/impls/src/lib.rs +++ b/impls/src/lib.rs @@ -44,6 +44,7 @@ pub mod tor; pub use crate::adapters::{ PathToSlate, SlateGetter, SlatePutter, SlateReceiver, SlateSender, TorSlateSender, }; +pub use crate::client_utils::json_rpc; pub use crate::error::Error; pub use crate::lifecycle::DefaultLCProvider; pub use crate::node_clients::HTTPNodeClient; diff --git a/impls/src/tor/arti.rs b/impls/src/tor/arti.rs index 3abeedd..d0a0c89 100644 --- a/impls/src/tor/arti.rs +++ b/impls/src/tor/arti.rs @@ -34,6 +34,7 @@ use sha2::Sha512; use std::collections::HashMap; use std::net::SocketAddr; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; @@ -59,6 +60,18 @@ struct TorService { state_lock: PathBuf, } +/// Failure from an HTTP request over Tor, classified by whether delivery may +/// have started. +#[derive(Debug, thiserror::Error)] +pub enum TorPostError { + /// The failure happened before handing the request to Hyper. + #[error("{0}")] + NotSent(Error), + /// Hyper started sending the request, so delivery cannot be ruled out. + #[error("{0}")] + PossiblySent(Error), +} + type ArtiClientConfig = (Arc>, TorClientConfig); lazy_static! { @@ -218,39 +231,73 @@ pub fn start_tor_client(config: TorConfig) -> Result<(), Error> { Ok(()) } +/// Build an origin-form JSON POST request +fn build_post_request(json: String, url: &Uri) -> Result>, Error> { + let authority = url + .authority() + .ok_or_else(|| Error::GenericError(format!("URL {} has bad authority", url)))?; + let request_target = url + .path_and_query() + .map(|path| path.as_str()) + .unwrap_or("/"); + + Request::builder() + .uri(request_target) + .method("POST") + .header("host", authority.as_str()) + .header("accept", "application/json") + .header("content-type", "application/json") + .body(Full::from(json)) + .map_err(|e| Error::TorProcess(format!("{:?}", e))) +} + /// Make POST request. -pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result +pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result where IN: Serialize, { - let json = serde_json::to_string(input) - .map_err(|_| Error::GenericError("Could not serialize data to JSON".to_owned()))?; + let json = serde_json::to_string(input).map_err(|_| { + TorPostError::NotSent(Error::GenericError( + "Could not serialize data to JSON".to_owned(), + )) + })?; let url = url.to_string(); let url: Uri = url .parse() - .map_err(|_| Error::GenericError(format!("Bad URL: {}", url)))?; + .map_err(|_| TorPostError::NotSent(Error::GenericError(format!("Bad URL: {}", url))))?; let host = match url.host() { - None => return Err(Error::GenericError(format!("URL {} has bad host", url))), + None => { + return Err(TorPostError::NotSent(Error::GenericError(format!( + "URL {} has bad host", + url + )))) + } Some(h) => h, } .to_string(); + let port = url.port_u16().unwrap_or(80); + let request = build_post_request(json, &url).map_err(TorPostError::NotSent)?; let timeout = tor_config.request_timeout(); let (state_path, cache_path) = state_cache_paths(tor_config); - let (client, _) = init_client(&state_path, &cache_path, tor_config)?; - let res: Result = thread::spawn(move || { + let (client, _) = + init_client(&state_path, &cache_path, tor_config).map_err(TorPostError::NotSent)?; + let res: Result = thread::spawn(move || { let c = client.clone(); client.runtime().block_on(async move { - let res = c - .runtime() - .timeout(timeout, async { - let stream = c - .connect((host, url.port_u16().unwrap_or(80))) - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let send_started = Arc::new(AtomicBool::new(false)); + let send_started_in_request = send_started.clone(); + let runtime = c.runtime().clone(); + let res = runtime + .timeout(timeout, async move { + let stream = c.connect((host, port)).await.map_err(|e| { + TorPostError::NotSent(Error::TorProcess(format!("{:?}", e))) + })?; let (mut request_sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + .map_err(|e| { + TorPostError::NotSent(Error::TorProcess(format!("{:?}", e))) + })?; // Spawn a task to poll the connection and drive the HTTP state. tokio::spawn(async move { @@ -259,36 +306,44 @@ where } }); - let resp = request_sender - .send_request( - Request::builder() - .uri(url) - .method("POST") - .body::>(Full::from(json)) - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?, - ) - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + send_started_in_request.store(true, Ordering::Release); + let resp = request_sender.send_request(request).await.map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; - let body_resp = resp - .into_body() - .collect() - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let status = resp.status(); + let body_resp = resp.into_body().collect().await.map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; let body = body_resp.to_bytes().into(); - let body_text = String::from_utf8(body) - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let body_text = String::from_utf8(body).map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; + if !status.is_success() { + return Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "HTTP request failed with status {}: {}", + status, body_text + )))); + } Ok(body_text) }) .await; match res { - Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + Err(e) if send_started.load(Ordering::Acquire) => Err(TorPostError::PossiblySent( + Error::TorProcess(format!("{:?}", e)), + )), + Err(e) => Err(TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))), Ok(body) => Ok(body), } }) }) .join() - .unwrap_or_else(|e| Err(Error::TorProcess(format!("{:?}", e))))?; + .unwrap_or_else(|e| { + Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "{:?}", + e + )))) + })?; res } @@ -300,6 +355,10 @@ fn init_client( ) -> Result<(Arc>, TorClientConfig), Error> { let mut builder = TorClientConfigBuilder::from_directories(state_path, cache_path); builder.address_filter().allow_onion_addrs(true); + // Circuit timeout minimum applies to listeners and sends too + builder + .override_net_params() + .insert("cbtmintimeout".into(), 60_000); // Configure bridge. if let Some(bridge_line) = tor_config.bridge.bridge_line.as_ref() { @@ -478,3 +537,21 @@ fn add_service_key( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::build_post_request; + use hyper::{Method, Uri}; + + #[test] + fn builds_origin_form_json_request() { + let url: Uri = "http://example.onion:8080/v1?test=1".parse().unwrap(); + let request = build_post_request("{}".to_string(), &url).unwrap(); + + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri(), "/v1?test=1"); + assert_eq!(request.headers()["host"], "example.onion:8080"); + assert_eq!(request.headers()["accept"], "application/json"); + assert_eq!(request.headers()["content-type"], "application/json"); + } +} diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 7017ef7..e19587f 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -14,42 +14,42 @@ //! Generic implementation of owner API functions -use std::cmp; -use uuid::Uuid; - use crate::api_impl::foreign::finalize_tx as foreign_finalize; -use crate::util::OnionV3Address; -use grin_core::core::amount_to_hr_string; -use grin_core::core::hash::Hashed; -use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction}; -use grin_core::libtx::proof; -use grin_keychain::ViewKey; -use grin_util::secp::{key::SecretKey, pedersen::Commitment}; -use grin_util::ToHex; - use crate::api_impl::owner_updater::StatusMessage; use crate::internal::{keys, scan, selection, tx, updater}; use crate::slate::{PaymentInfo, Slate, SlateState}; -use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletInfo}; +use crate::slatepack::SlatepackAddressIndex; +use crate::types::{AcctPathMapping, NodeClient, OutputData, OutputStatus, TxLogEntry, WalletInfo}; +use crate::util::OnionV3Address; use crate::{ address, - mwixnet::{create_onion, ComSignature, Hop, MixnetReqCreationParams, SwapReq}, + mwixnet::{ + create_onion, ComSignature, Hop, MixnetReqCreationParams, MwixnetReqCreationResult, + SwapReq, MAX_MWIXNET_HOPS, + }, slatepack, wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, TxLogEntryType, ViewWallet, WalletBackend, WalletInitStatus, WalletLCProvider, }; +use grin_core::core::amount_to_hr_string; +use grin_core::core::hash::Hashed; +use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction, TransactionBody}; +use grin_core::global::DEFAULT_ACCEPT_FEE_BASE; +use grin_core::libtx::proof; +use grin_keychain::ViewKey; use grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::{key::SecretKey, pedersen::Commitment}; +use grin_util::ToHex; +use grin_wallet_util::byte_ser; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::Verifier; use ed25519_dalek::VerifyingKey as DalekPublicKey; -use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; - -use crate::slatepack::SlatepackAddressIndex; -use grin_wallet_util::byte_ser; +use std::cmp; use std::convert::{TryFrom, TryInto}; use std::sync::mpsc::Sender; +use uuid::Uuid; /// List of accounts pub fn accounts( @@ -1043,18 +1043,20 @@ pub fn cancel_tx<'a, L, C, K>( status_send_channel: &Option>, tx_id: Option, tx_slate_id: Option, + refresh_from_node: bool, ) -> Result<(), Error> where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - if !update_wallet_state( - wallet_inst.clone(), - keychain_mask, - status_send_channel, - false, - )? { + if refresh_from_node + && !update_wallet_state( + wallet_inst.clone(), + keychain_mask, + status_send_channel, + false, + )? { return Err(Error::TransactionCancellationError( "Can't contact running Grin node. Not Cancelling.", )); @@ -1610,7 +1612,7 @@ where }) } -/// Create MXMixnet request +/// Create mwixnet request pub fn create_mwixnet_req( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -1618,43 +1620,57 @@ pub fn create_mwixnet_req( commitment: &Commitment, lock_output: bool, use_test_rng: bool, -) -> Result +) -> Result where C: NodeClient, K: Keychain, { - let parent_key_id = w.parent_key_id(); - let keychain = w.keychain(keychain_mask)?; - let outputs = updater::retrieve_outputs(w, keychain_mask, false, None, Some(&parent_key_id))?; - - let mut output = None; - for o in &outputs { - if o.commit == *commitment { - output = Some(o.output.clone()); - break; - } + if params.server_keys.is_empty() { + return Err(Error::GenericError( + "mwixnet requires at least one server key".to_string(), + )); } - - if output.is_none() { - return Err(Error::GenericError(String::from("output not found"))); - } - - let amount = output.clone().unwrap().value; - let input_blind = keychain.derive_key( - amount, - &output.clone().unwrap().key_id, - SwitchCommitmentType::Regular, - )?; - - let mut server_pubkeys = vec![]; - for i in 0..params.server_keys.len() { - server_pubkeys.push(xPublicKey::from(&StaticSecret::from( - params.server_keys[i].0, + if params.server_keys.len() > MAX_MWIXNET_HOPS { + return Err(Error::GenericError(format!( + "mwixnet supports at most {} server keys", + MAX_MWIXNET_HOPS ))); } - let fee = grin_core::libtx::tx_fee(1, 1, 1); - let new_amount = amount - (fee * server_pubkeys.len() as u64); + let parent_key_id = w.parent_key_id(); + let keychain = w.keychain(keychain_mask)?; + let outputs = updater::retrieve_outputs(w, keychain_mask, true, None, Some(&parent_key_id))?; + let output = outputs + .into_iter() + .find(|o| o.commit == *commitment) + .map(|o| o.output) + .ok_or_else(|| Error::GenericError("output not found".to_string()))?; + let current_height = w.w2n_client().get_chain_tip()?.0; + if !output.eligible_to_spend(current_height, 1) { + return Err(Error::GenericError("output is not spendable".to_string())); + } + + let amount = output.value; + let input_blind = keychain.derive_key(amount, &output.key_id, SwitchCommitmentType::Regular)?; + + let server_pubkeys = ¶ms.server_keys; + let minimum_fee = TransactionBody::weight_by_iok(1, 1, 1) * DEFAULT_ACCEPT_FEE_BASE; + let fee_per_hop = params.fee_per_hop.unwrap_or(minimum_fee); + if fee_per_hop < minimum_fee { + return Err(Error::Fee(format!( + "mwixnet fee is below the swap minimum {}", + amount_to_hr_string(minimum_fee, true) + ))); + } + let fee = FeeFields::try_from(fee_per_hop).map_err(|e| Error::Fee(e.to_string()))?; + let total_fee = fee_per_hop + .checked_mul(server_pubkeys.len() as u64) + .ok_or_else(|| Error::Fee("mwixnet fee overflow".to_string()))?; + let total_fee_fields = FeeFields::try_from(total_fee) + .map_err(|_| Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()))?; + let new_amount = amount + .checked_sub(total_fee) + .ok_or_else(|| Error::Fee("mwixnet fees exceed output value".to_string()))?; let new_output = build_output(w, keychain_mask, OutputFeatures::Plain, new_amount)?; let secp = keychain.secp(); @@ -1665,48 +1681,74 @@ where let hops: Vec = server_pubkeys .iter() .enumerate() - .map(|(i, &p)| { + .map(|(i, &p)| -> Result { if (i + 1) == server_pubkeys.len() { - Hop { + Ok(Hop { server_pubkey: p, - excess: blind_sum.secret_key(secp).unwrap(), - fee: FeeFields::from(fee as u32), + excess: blind_sum.secret_key(secp)?, + fee, rangeproof: Some(new_output.output.proof), - } + }) } else { let hop_excess = if use_test_rng { BlindingFactor::zero() } else { BlindingFactor::rand(secp) }; - blind_sum = blind_sum.split(&hop_excess, secp).unwrap(); - Hop { + blind_sum = blind_sum.split(&hop_excess, secp)?; + Ok(Hop { server_pubkey: p, - excess: hop_excess.secret_key(secp).unwrap(), - fee: FeeFields::from(fee as u32), + excess: hop_excess.secret_key(secp)?, + fee, rangeproof: None, - } + }) } }) - .collect(); + .collect::, _>>()?; - let onion = create_onion(commitment, &hops, use_test_rng).unwrap(); - let comsig = ComSignature::sign( - amount, - &input_blind, - &onion.serialize().unwrap(), - use_test_rng, - ) - .unwrap(); + let onion = create_onion(commitment, &hops, use_test_rng) + .map_err(|e| Error::GenericError(e.to_string()))?; + let onion_bytes = onion.serialize().map_err(Error::Deser)?; + let comsig = ComSignature::sign(amount, &input_blind, &onion_bytes, use_test_rng) + .map_err(|e| Error::Signature(e.to_string()))?; // Lock output if requested - if lock_output { + let tx_id = if lock_output { let mut batch = w.batch(keychain_mask)?; - let mut update_output = batch.get(&output.as_ref().unwrap().key_id, &None)?; - update_output.lock(); - batch.lock_output(&mut update_output)?; - batch.commit()?; - } + let log_id = batch.next_tx_log_id(&parent_key_id)?; + let mut tx = TxLogEntry::new(parent_key_id.clone(), TxLogEntryType::TxSent, log_id); + tx.amount_debited = amount; + tx.amount_credited = new_amount; + tx.num_inputs = 1; + tx.num_outputs = 1; + tx.fee = Some(total_fee_fields); + tx.kernel_lookup_min_height = Some(current_height); - Ok(SwapReq { comsig, onion }) + let mut update_output = batch.get(&output.key_id, &output.mmr_index)?; + update_output.tx_log_entry = Some(log_id); + batch.lock_output(&mut update_output)?; + batch.save(OutputData { + root_key_id: parent_key_id.clone(), + key_id: new_output.key_id.clone(), + n_child: new_output.key_id.to_path().last_path_index(), + commit: Some(new_output.output.commitment().to_hex()), + mmr_index: None, + value: new_amount, + status: OutputStatus::Unconfirmed, + height: current_height, + lock_height: 0, + is_coinbase: false, + tx_log_entry: Some(log_id), + })?; + batch.save_tx_log_entry(tx, &parent_key_id)?; + batch.commit()?; + Some(log_id) + } else { + None + }; + + Ok(MwixnetReqCreationResult { + request: SwapReq { comsig, onion }, + tx_id, + }) } diff --git a/libwallet/src/mwixnet/mod.rs b/libwallet/src/mwixnet/mod.rs index ebc5a9c..bb97287 100644 --- a/libwallet/src/mwixnet/mod.rs +++ b/libwallet/src/mwixnet/mod.rs @@ -14,11 +14,16 @@ //! Onion modules for mxmixnet pub mod onion; +mod response; mod types; pub use onion::{ create_onion, onion::Onion, onion::OnionError, util as onion_util, ComSigError, ComSignature, - MwixnetPublicKey, + MAX_MWIXNET_HOPS, }; -pub use types::{Hop, MixnetReqCreationParams, SwapReq}; +pub use response::{parse_mwixnet_response, MwixnetResponse, MwixnetResponseError}; + +pub use types::{ + Hop, MixnetReqCreationParams, MwixnetReqCreationResult, MwixnetServerPublicKey, SwapReq, +}; diff --git a/libwallet/src/mwixnet/onion/crypto/dalek.rs b/libwallet/src/mwixnet/onion/crypto/dalek.rs index 1d02d7f..66c5f69 100644 --- a/libwallet/src/mwixnet/onion/crypto/dalek.rs +++ b/libwallet/src/mwixnet/onion/crypto/dalek.rs @@ -36,48 +36,51 @@ pub enum DalekError { SigVerifyFailed, } -/// Encapsulates an ed25519_dalek::PublicKey and provides (de-)serialization +/// Ed25519 server identity key #[derive(Clone, Debug, PartialEq)] -pub struct DalekPublicKey(VerifyingKey); +pub struct MwixnetServerIdentityKey(VerifyingKey); -impl DalekPublicKey { - /// Convert DalekPublicKey to hex string +impl MwixnetServerIdentityKey { + /// Convert the identity key to hex pub fn to_hex(&self) -> String { self.0.to_hex() } - /// Convert hex string to DalekPublicKey. + /// Parse an identity key from hex pub fn from_hex(hex: &str) -> Result { let err = DalekError::HexError(format!("failed to decode {}", hex)); let bytes = grin_util::from_hex(hex).map_err(|_| err.clone())?; let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| err.clone())?; let pk = VerifyingKey::from_bytes(b).map_err(|_| err)?; - Ok(DalekPublicKey(pk)) + Ok(MwixnetServerIdentityKey(pk)) } - /// Compute DalekPublicKey from a SecretKey + /// Derive the identity key from a secret key pub fn from_secret(key: &SecretKey) -> Self { let secret = ed25519_dalek::SigningKey::from_bytes(&key.0); let pk: VerifyingKey = (&secret).into(); - DalekPublicKey(pk) + MwixnetServerIdentityKey(pk) } } -impl AsRef for DalekPublicKey { +impl AsRef for MwixnetServerIdentityKey { fn as_ref(&self) -> &VerifyingKey { &self.0 } } -/// Serializes an Option to and from hex +/// Serialize an optional identity key as hex pub mod option_dalek_pubkey_serde { - use super::DalekPublicKey; + use super::MwixnetServerIdentityKey; use grin_util::ToHex; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; /// Write the Ed25519 public key as hex, or null - pub fn serialize(pk: &Option, serializer: S) -> Result + pub fn serialize( + pk: &Option, + serializer: S, + ) -> Result where S: Serializer, { @@ -88,29 +91,31 @@ pub mod option_dalek_pubkey_serde { } /// Read an optional Ed25519 public key from hex - pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + pub fn deserialize<'de, D>( + deserializer: D, + ) -> Result, D::Error> where D: Deserializer<'de>, { Option::::deserialize(deserializer).and_then(|res| match res { - Some(string) => DalekPublicKey::from_hex(&string) + Some(string) => MwixnetServerIdentityKey::from_hex(&string) .map_err(|e| Error::custom(e.to_string())) - .map(|pk: DalekPublicKey| Some(pk)), + .map(|pk: MwixnetServerIdentityKey| Some(pk)), None => Ok(None), }) } } -impl Readable for DalekPublicKey { +impl Readable for MwixnetServerIdentityKey { fn read(reader: &mut R) -> Result { let bytes = reader.read_fixed_bytes(32)?; let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| ser::Error::CorruptedData)?; let pk = VerifyingKey::from_bytes(b).map_err(|_| ser::Error::CorruptedData)?; - Ok(DalekPublicKey(pk)) + Ok(MwixnetServerIdentityKey(pk)) } } -impl Writeable for DalekPublicKey { +impl Writeable for MwixnetServerIdentityKey { fn write(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_fixed_bytes(self.0.to_bytes())?; Ok(()) @@ -136,7 +141,7 @@ impl DalekSignature { /// Verifies DalekSignature #[allow(dead_code)] - pub fn verify(&self, pk: &DalekPublicKey, msg: &[u8]) -> Result<(), DalekError> { + pub fn verify(&self, pk: &MwixnetServerIdentityKey, msg: &[u8]) -> Result<(), DalekError> { pk.as_ref() .verify(msg, &self.0) .map_err(|_| DalekError::SigVerifyFailed) @@ -196,20 +201,21 @@ mod tests { #[derive(Serialize, Deserialize, PartialEq, Clone, Debug)] struct TestPubKeySerde { #[serde(with = "option_dalek_pubkey_serde", default)] - pk: Option, + pk: Option, } #[test] fn pubkey_test() -> Result<(), Box> { // Test from_hex let rand_pk = rand_keypair().1; - let pk_from_hex = DalekPublicKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); + let pk_from_hex = MwixnetServerIdentityKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); assert_eq!(rand_pk.0, pk_from_hex.0); // Test ser (de-)serialization let bytes = ser::ser_vec(&rand_pk, ProtocolVersion::local()).unwrap(); assert_eq!(bytes.len(), 32); - let pk_from_deser: DalekPublicKey = ser::deserialize_default(&mut &bytes[..]).unwrap(); + let pk_from_deser: MwixnetServerIdentityKey = + ser::deserialize_default(&mut &bytes[..]).unwrap(); assert_eq!(rand_pk.0, pk_from_deser.0); // Test serde with Some(rand_pk) @@ -260,7 +266,7 @@ mod tests { // Sign a message let s = Secp256k1::new(); let sk = SecretKey::from_slice(&s, &[1; 32]).unwrap(); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::from_secret(&sk); let msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let sig = sign(&sk, &msg).unwrap(); @@ -274,7 +280,7 @@ mod tests { // Wrong pubkey let wrong_sk = SecretKey::from_slice(&s, &[2; 32]).unwrap(); - let wrong_pk = DalekPublicKey::from_secret(&wrong_sk); + let wrong_pk = MwixnetServerIdentityKey::from_secret(&wrong_sk); assert!(sig.verify(&wrong_pk, &msg).is_err()); // Test from_hex diff --git a/libwallet/src/mwixnet/onion/mod.rs b/libwallet/src/mwixnet/onion/mod.rs index aa3d7c3..c56e69e 100644 --- a/libwallet/src/mwixnet/onion/mod.rs +++ b/libwallet/src/mwixnet/onion/mod.rs @@ -19,9 +19,7 @@ pub mod crypto; pub mod onion; pub mod util; -pub use crypto::{ - comsig_serde, dalek::DalekPublicKey as MwixnetPublicKey, ComSigError, ComSignature, -}; +pub use crypto::{comsig_serde, ComSigError, ComSignature}; use chacha20::cipher::StreamCipher; use grin_core::core::FeeFields; @@ -32,14 +30,18 @@ use grin_util::secp::{ use x25519_dalek::PublicKey as xPublicKey; use x25519_dalek::{SharedSecret, StaticSecret}; +use crate::mwixnet::MwixnetServerPublicKey; use crypto::secp::random_secret; use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes}; +/// Maximum route length, including the swap server. +pub const MAX_MWIXNET_HOPS: usize = 8; + /// Onion hop struct #[derive(Clone)] pub struct Hop { /// Comsig server public key - pub server_pubkey: xPublicKey, + pub server_pubkey: MwixnetServerPublicKey, /// Kernel excess pub excess: SecretKey, /// Fee @@ -57,7 +59,7 @@ pub fn new_hop( proof: Option, ) -> Hop { Hop { - server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0)), + server_pubkey: MwixnetServerPublicKey::from_secret(server_key), excess: hop_excess.clone(), fee: FeeFields::from(fee), rangeproof: proof, @@ -70,6 +72,11 @@ pub fn create_onion( hops: &[Hop], use_test_rng: bool, ) -> Result { + if hops.len() > MAX_MWIXNET_HOPS { + return Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS, + }); + } if hops.is_empty() { return Ok(Onion { ephemeral_pubkey: xPublicKey::from([0u8; 32]), @@ -84,7 +91,10 @@ pub fn create_onion( let onion_ephemeral_pk = xPublicKey::from(&ephemeral_sk); for i in 0..hops.len() { let hop = &hops[i]; - let shared_secret = ephemeral_sk.diffie_hellman(&hop.server_pubkey); + let shared_secret = ephemeral_sk.diffie_hellman(&xPublicKey::from(hop.server_pubkey.0)); + if !shared_secret.was_contributory() { + return Err(OnionError::NonContributorySharedSecret); + } shared_secrets.push(shared_secret); ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0); @@ -123,7 +133,7 @@ pub fn create_onion( #[cfg(any(test, feature = "mwixnet-test"))] pub mod test_util { use super::*; - use crypto::dalek::DalekPublicKey; + use crypto::dalek::MwixnetServerIdentityKey; use crypto::secp; use grin_core::core::hash::Hash; @@ -154,23 +164,24 @@ pub mod test_util { } pub fn rand_commit() -> Commitment { - secp::commit(rand::thread_rng().next_u64(), &secp::random_secret(false)).unwrap() + secp::commit(thread_rng().next_u64(), &random_secret(false)).unwrap() } pub fn rand_hash() -> Hash { - Hash::from_hex(secp::random_secret(false).to_hex().as_str()).unwrap() + Hash::from_hex(random_secret(false).to_hex().as_str()).unwrap() } pub fn rand_proof() -> RangeProof { let secp = Secp256k1::new(); secp.bullet_proof( - rand::thread_rng().next_u64(), - secp::random_secret(false), - secp::random_secret(false), - secp::random_secret(false), + thread_rng().next_u64(), + random_secret(false), + random_secret(false), + random_secret(false), None, None, ) + .expect("failed to generate test bulletproof") } pub fn proof( @@ -188,21 +199,106 @@ pub mod test_util { let out_value = value - (fee as u64); - let rp = secp.bullet_proof( - out_value, - blind.clone(), - secp::random_secret(false), - secp::random_secret(false), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + blind.clone(), + random_secret(false), + random_secret(false), + None, + None, + ) + .expect("failed to generate test bulletproof"); (secp::commit(out_value, &blind).unwrap(), rp) } - pub fn rand_keypair() -> (SecretKey, DalekPublicKey) { + pub fn rand_keypair() -> (SecretKey, MwixnetServerIdentityKey) { let sk = random_secret(false); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::from_secret(&sk); (sk, pk) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::mwixnet::MwixnetServerPublicKey; + + #[test] + fn rejects_zero_key() { + let commitment = test_util::rand_commit(); + let hop = Hop { + server_pubkey: MwixnetServerPublicKey([0u8; 32]), + excess: random_secret(false), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + + assert_eq!( + create_onion(&commitment, &[hop], false), + Err(OnionError::NonContributorySharedSecret) + ); + } + + #[test] + fn rejects_too_many_hops() { + let commitment = test_util::rand_commit(); + let hops: Vec = (0..=MAX_MWIXNET_HOPS) + .map(|_| new_hop(&random_secret(false), &random_secret(false), 1, None)) + .collect(); + + assert!(create_onion(&commitment, &hops[..MAX_MWIXNET_HOPS], false).is_ok()); + + assert_eq!( + create_onion(&commitment, &hops, false), + Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS + }) + ); + } + + #[test] + fn x25519_key_roundtrip() { + let server_key = SecretKey::from_slice( + &grin_util::secp::Secp256k1::new(), + &grin_util::from_hex( + "a129111d283b13bf93957c06bf6605c3417b4b89db4b5cb2e7dab2c15e36e0a4", + ) + .unwrap(), + ) + .unwrap(); + let public_key = MwixnetServerPublicKey::from_secret(&server_key); + assert_eq!( + public_key.to_hex(), + "96ced236bdf1aca722ef68b818445755e6ed4bacf23e19d7b71c43efc5f0077b" + ); + let identity_key = + crypto::dalek::MwixnetServerIdentityKey::from_secret(&server_key).to_hex(); + assert_ne!(identity_key, public_key.to_hex()); + + let commitment = crypto::secp::commit(1_000, &server_key).unwrap(); + let excess = server_key.clone(); + let hop = Hop { + server_pubkey: public_key, + excess: excess.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let onion = create_onion(&commitment, &[hop], true).unwrap(); + let peeled = onion.peel_layer(&server_key).unwrap(); + + assert_eq!(peeled.payload.excess, excess); + assert_eq!(peeled.payload.fee, FeeFields::from(1u32)); + + let identity_key = MwixnetServerPublicKey::from_hex(&identity_key).unwrap(); + let wrong_hop = Hop { + server_pubkey: identity_key, + excess: server_key.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let wrong_onion = create_onion(&commitment, &[wrong_hop], true).unwrap(); + assert!(wrong_onion.peel_layer(&server_key).is_err()); + } +} diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index e135a52..e105f4c 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -336,6 +336,15 @@ pub enum OnionError { /// Invalid Key Length #[error("Invalid key length for MAC initialization")] InvalidKeyLength, + /// Non-contributory X25519 shared secret + #[error("Non-contributory X25519 shared secret")] + NonContributorySharedSecret, + /// Too many hops + #[error("Mwixnet routes support at most {max} hops")] + TooManyHops { + /// Maximum supported number of hops + max: usize, + }, /// Serialization Error #[error("Serialization error occurred: {0:?}")] SerializationError(ser::Error), @@ -397,14 +406,16 @@ mod tests { final_commit = secp::add_excess(&final_commit, &excess).unwrap(); let proof = if i == 4 { let n1 = random_secret(false); - let rp = secp.bullet_proof( - out_value, - final_blind.clone(), - n1.clone(), - n1.clone(), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + final_blind.clone(), + n1.clone(), + n1.clone(), + None, + None, + ) + .expect("failed to generate test bulletproof"); assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok()); Some(rp) } else { diff --git a/libwallet/src/mwixnet/response.rs b/libwallet/src/mwixnet/response.rs new file mode 100644 index 0000000..a2e0c8c --- /dev/null +++ b/libwallet/src/mwixnet/response.rs @@ -0,0 +1,105 @@ +// Copyright 2026 The Grin Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mwixnet response parsing. + +use serde::Deserialize; +use serde_json::{self, Value}; + +/// Result returned by a mwixnet server after submitting a swap request. +#[derive(Debug, Eq, PartialEq)] +pub enum MwixnetResponse { + /// The swap request was accepted. + Accepted, + /// The swap request was rejected with a message. + //TODO: extend it with actual errors from mwixnet + Rejected(String), +} + +/// Error parsing or validating a mwixnet response. +#[derive(Debug, Eq, PartialEq, thiserror::Error)] +#[error("{0}")] +pub struct MwixnetResponseError(String); + +#[derive(Deserialize)] +struct JsonRpcResponse { + result: Option, + error: Option, + id: Value, + jsonrpc: Option, +} + +#[derive(Deserialize)] +struct JsonRpcError { + #[serde(rename = "code")] + _code: i32, + message: String, +} + +/// Parse and validate the JSON-RPC response returned by a mwixnet server. +pub fn parse_mwixnet_response(response: &str) -> Result { + let response: JsonRpcResponse = serde_json::from_str(response) + .map_err(|e| MwixnetResponseError(format!("Invalid mwixnet response: {}", e)))?; + + if response.jsonrpc.as_deref() != Some("2.0") { + return Err(MwixnetResponseError( + "Invalid mwixnet response version".to_string(), + )); + } + if response.id != serde_json::json!(1) { + return Err(MwixnetResponseError( + "Invalid mwixnet response ID".to_string(), + )); + } + if response.result.is_some() && response.error.is_some() { + return Err(MwixnetResponseError( + "Mwixnet response contains both result and error".to_string(), + )); + } + if let Some(error) = response.error { + return Ok(MwixnetResponse::Rejected(error.message)); + } + if response.result == Some(serde_json::json!("success")) { + return Ok(MwixnetResponse::Accepted); + } + + Err(MwixnetResponseError(format!( + "Unexpected mwixnet response result: {:?}", + response.result + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_mwixnet_response() { + assert_eq!( + parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":1}"#).unwrap(), + MwixnetResponse::Accepted + ); + + assert_eq!( + parse_mwixnet_response( + r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid swap"},"id":1}"#, + ) + .unwrap(), + MwixnetResponse::Rejected("invalid swap".to_string()) + ); + + assert!(parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":2}"#).is_err()); + assert!(parse_mwixnet_response(r#"{"jsonrpc":"1.0","result":"success","id":1}"#).is_err()); + } +} diff --git a/libwallet/src/mwixnet/types.rs b/libwallet/src/mwixnet/types.rs index 1213f3a..04c253d 100644 --- a/libwallet/src/mwixnet/types.rs +++ b/libwallet/src/mwixnet/types.rs @@ -13,12 +13,15 @@ // limitations under the License. //! Types related to mwixnet requests required by rest of lib crate apis -//! Should rexport all needed types here +//! Should export all needed types here use super::onion::comsig_serde; -use grin_core::libtx::secp_ser::string_or_u64; +use grin_core::libtx::secp_ser::opt_string_or_u64; use grin_util::secp::key::SecretKey; -use serde::{Deserialize, Serialize}; +use grin_util::ToHex; +use serde::de::Error as SerdeError; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use x25519_dalek::{PublicKey, StaticSecret}; pub use super::onion::{onion::Onion, ComSignature, Hop}; @@ -32,12 +35,67 @@ pub struct SwapReq { pub onion: Onion, } -/// mwixnetRequest Creation Params +/// Result of creating a mwixnet request. +#[derive(Serialize, Deserialize, Debug)] +pub struct MwixnetReqCreationResult { + /// Request to submit to the first mwixnet server. + #[serde(flatten)] + pub request: SwapReq, + /// Transaction log ID when the wallet output was locked. + pub tx_id: Option, +} + +/// Public X25519 key of an mwixnet server. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MwixnetServerPublicKey(pub(crate) [u8; 32]); + +impl MwixnetServerPublicKey { + /// Derive the public key published by a mwixnet server. + pub fn from_secret(key: &SecretKey) -> Self { + let key = PublicKey::from(&StaticSecret::from(key.0)); + Self(key.to_bytes()) + } + + /// Parse a public key from hexadecimal representation. + pub fn from_hex(value: &str) -> Result { + let bytes = grin_util::from_hex(value).map_err(|e| e.to_string())?; + let bytes: [u8; 32] = bytes + .try_into() + .map_err(|_| "mwixnet server public key must be 32 bytes".to_string())?; + Ok(Self(bytes)) + } + + /// Return the hexadecimal representation. + pub fn to_hex(self) -> String { + self.0.to_hex() + } +} + +impl Serialize for MwixnetServerPublicKey { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for MwixnetServerPublicKey { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Self::from_hex(&value).map_err(D::Error::custom) + } +} + +/// Mwixnet request creation params #[derive(Serialize, Deserialize, Debug)] pub struct MixnetReqCreationParams { - /// List of all the server keys - pub server_keys: Vec, - /// Fees per hop - #[serde(with = "string_or_u64")] - pub fee_per_hop: u64, + /// Ordered public keys of 1 to [`super::MAX_MWIXNET_HOPS`] participating servers + pub server_keys: Vec, + /// Optional fee per hop with the swap minimum as default + #[serde(default, with = "opt_string_or_u64")] + pub fee_per_hop: Option, } diff --git a/src/bin/grin-wallet.yml b/src/bin/grin-wallet.yml index 8abdbea..ea77e92 100644 --- a/src/bin/grin-wallet.yml +++ b/src/bin/grin-wallet.yml @@ -190,6 +190,36 @@ subcommands: short: a long: address_index takes_value: true + - mwixnet: + about: EXPERIMENTAL - Swap a wallet output through an mwixnet route using Arti only + args: + - output: + help: Commitment or minimum amount of the wallet output to swap, or 'max' for the largest eligible output + index: 1 + required: true + - server: + help: Ed25519 identity key or .onion address of the first mwixnet server + long: server + takes_value: true + required: true + - key: + help: X25519 onion key of an mwixnet server, repeated in route order + long: key + takes_value: true + multiple: true + number_of_values: 1 + required: true + - fee_per_hop: + help: Fee per mwixnet server in Grin, e.g. 0.0125, with the swap minimum as default + long: fee_per_hop + takes_value: true + required: false + - minimum_confirmations: + help: Minimum confirmations required for the selected output + short: c + long: min_conf + default_value: "10" + takes_value: true - unpack: about: Unpack and display an armored Slatepack Message, decrypting if possible args: diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index fdee2b4..7fef1b7 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -23,11 +23,14 @@ use crate::util::{Mutex, ZeroingString}; use grin_core as core; use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; +use grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE; +use grin_util::secp::pedersen::Commitment; use grin_wallet_api::Owner; use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; +use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}; use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider}; @@ -574,6 +577,64 @@ fn parse_address_index_arg(args: &ArgMatches) -> Result Result { + if output.eq_ignore_ascii_case("max") { + Ok(command::MwixnetOutput::Max) + } else if output.len() == PEDERSEN_COMMITMENT_SIZE * 2 { + let commitment = grin_util::from_hex(output) + .map_err(|e| ParseError::ArgumentError(format!("Invalid output commitment: {}", e)))?; + Ok(command::MwixnetOutput::Commitment(Commitment::from_vec( + commitment, + ))) + } else { + let amount = core::core::amount_from_hr_string(output).map_err(|e| { + ParseError::ArgumentError(format!( + "Output must be a commitment, an amount, or 'max': {}", + e + )) + })?; + Ok(command::MwixnetOutput::MinimumAmount(amount)) + } +} + +pub fn parse_mwixnet_args(args: &ArgMatches) -> Result { + let output = parse_mwixnet_output(parse_required(args, "output")?)?; + + let server = parse_required(args, "server")? + .try_into() + .map_err(|e| ParseError::ArgumentError(format!("Invalid mwixnet server: {}", e)))?; + let server_keys = args + .values_of("key") + .ok_or_else(|| { + ParseError::ArgumentError("At least one server key is required".to_string()) + })? + .map(|key| { + MwixnetServerPublicKey::from_hex(key).map_err(|e| { + ParseError::ArgumentError(format!("Invalid mwixnet server key: {}", e)) + }) + }) + .collect::, _>>()?; + let fee_per_hop = args + .value_of("fee_per_hop") + .map(core::core::amount_from_hr_string) + .transpose() + .map_err(|e| ParseError::ArgumentError(format!("Invalid fee_per_hop: {}", e)))?; + let minimum_confirmations = parse_u64( + parse_required(args, "minimum_confirmations")?, + "minimum_confirmations", + )?; + + Ok(command::MwixnetArgs { + server, + output, + minimum_confirmations, + params: MixnetReqCreationParams { + server_keys, + fee_per_hop, + }, + }) +} + pub fn parse_receive_args(args: &ArgMatches) -> Result { let input_file = parse_input_file_arg(args)?; @@ -1232,6 +1293,10 @@ where test_mode, ) } + ("mwixnet", Some(args)) => { + let a = arg_parse!(parse_mwixnet_args(args)); + command::mwixnet(owner_api, km, a) + } ("receive", Some(args)) => { let a = arg_parse!(parse_receive_args(args)); command::receive(owner_api, km, a, tor_config, test_mode) @@ -1326,3 +1391,75 @@ where } } } + +#[cfg(test)] +mod mwixnet_tests { + use super::*; + + #[test] + fn parses_mwixnet_optional_fee() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let args = vec![ + "grin-wallet", + "mwixnet", + "max", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + "--key", + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + ]; + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args.clone()) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, None); + + let mut custom_args = args; + custom_args.extend(["--fee_per_hop", "0.0125"]); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(custom_args) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, Some(12_500_000)); + } + + #[test] + fn mwixnet_args() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let key = "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a"; + for keys in [vec!["--key", key], vec!["--key", key, "--key", key]] { + let key_count = keys.len() / 2; + let mut args = vec![ + "grin-wallet", + "mwixnet", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + ]; + args.extend(keys); + args.push("max"); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args) + .unwrap(); + let parsed = + parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert!(matches!(parsed.output, command::MwixnetOutput::Max)); + assert_eq!(parsed.params.server_keys.len(), key_count); + } + } + + #[test] + fn parses_mwixnet_output_selection() { + assert!(matches!( + parse_mwixnet_output("max").unwrap(), + command::MwixnetOutput::Max + )); + assert!(matches!( + parse_mwixnet_output("10").unwrap(), + command::MwixnetOutput::MinimumAmount(10_000_000_000) + )); + assert!(matches!( + parse_mwixnet_output(&format!("08{}", "00".repeat(32))).unwrap(), + command::MwixnetOutput::Commitment(_) + )); + } +}