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 <wiesche89@googlemail.com>
This commit is contained in:
ardocrat
2026-07-24 22:15:19 +02:00
committed by GitHub
co-authored by wiesche
parent 7fb47646e9
commit d2fe2b90f6
46 changed files with 4880 additions and 3311 deletions
+457 -563
View File
File diff suppressed because it is too large Load Diff
+227 -132
View File
@@ -12,10 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! Controller for wallet.. instantiates and handles listeners (or single-run
//! Controller for wallet, instantiates and handles listeners (or single-run
//! invocations) as needed.
use crate::api::{self, ApiServer, BasicAuthMiddleware, ResponseFuture, Router, TLSConfig};
use crate::config::TorConfig;
use crate::impls::tor::config as tor_config;
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,
@@ -25,6 +28,7 @@ use crate::util::secp::key::SecretKey;
use crate::util::{from_hex, static_secp_instance, to_base64, Mutex};
use grin_wallet_api::JsonId;
use grin_wallet_util::OnionV3Address;
use hyper::header::HeaderValue;
use hyper::{Request, Response, StatusCode};
use qr_code::QrCode;
@@ -34,21 +38,23 @@ use std::collections::HashMap;
use std::convert::TryFrom;
use std::io::Cursor;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use crate::impls::tor::config as tor_config;
use crate::impls::tor::process as tor_process;
use crate::impls::tor::{bridge as tor_bridge, proxy as tor_proxy};
use std::thread;
use crate::apiwallet::{
EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Foreign,
ConfigPath, EncryptedRequest, EncryptedResponse, EncryptionErrorResponse, Foreign,
ForeignCheckMiddlewareFn, ForeignRpc, Owner, OwnerRpc,
};
use easy_jsonrpc_mw;
use easy_jsonrpc_mw::{Handler, MaybeReply};
use grin_api::ApiBody;
use grin_wallet_impls::tor::arti::start_tor_service;
use grin_wallet_impls::tor::Tor;
use grin_wallet_config::config::{
add_global_config_listener, get_global_config, remove_global_config_listener,
};
use grin_wallet_impls::tor::arti::{start_tor_service, stop_tor_service};
use grin_wallet_impls::tor::process::TorProcess;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use tokio::sync::mpsc;
@@ -91,7 +97,7 @@ fn init_tor_listener(
tor_dir: String,
addr: &str,
tor_config: TorConfig,
) -> Result<Tor, Error> {
) -> Result<tor_process::TorProcess, Error> {
info!("Starting external Tor Process listener.");
let mut process = tor_process::TorProcess::new();
@@ -131,19 +137,15 @@ fn init_tor_listener(
.completion_percent(100)
.launch()
.map_err(|e| Error::TorProcess(format!("{:?}", e)))?;
Ok(Tor {
process: Some(process),
service: None,
client: None,
})
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<L, F, C, K>(
wallet: Option<Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>>,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K>>>>,
keychain_mask: Option<&SecretKey>,
api_context: Option<&mut Owner<L, C, K>>,
config_path: PathBuf,
f: F,
) -> Result<(), Error>
where
@@ -152,27 +154,14 @@ where
C: NodeClient + 'static,
K: Keychain + 'static,
{
match api_context {
Some(c) => f(c, keychain_mask)?,
None => {
let wallet = match wallet {
Some(w) => w,
None => {
return Err(Error::GenericError(
"Instantiated wallet or Owner API context must be provided".to_string(),
))
}
};
f(&mut Owner::new(wallet, None), keychain_mask)?
}
}
Ok(())
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>(
wallet: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
config_path: PathBuf,
keychain_mask: Option<SecretKey>,
f: F,
) -> Result<(), Error>
@@ -184,6 +173,7 @@ where
{
f(&mut Foreign::new(
wallet,
config_path,
keychain_mask,
Some(check_middleware),
false,
@@ -196,13 +186,12 @@ where
/// Note keychain mask is only provided here in case the foreign listener is also being used
/// in the same wallet instance
pub fn owner_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
owner_api: &mut Owner<L, C, K>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
addr: &str,
api_secret: Option<String>,
tls_config: Option<TLSConfig>,
owner_api_include_foreign: Option<bool>,
tor_config: Option<TorConfig>,
test_mode: bool,
) -> Result<(), Error>
where
@@ -226,12 +215,8 @@ where
running_foreign = true;
}
let api_handler_v3 = OwnerAPIHandlerV3::new(
wallet.clone(),
keychain_mask.clone(),
tor_config.clone(),
running_foreign,
);
let wallet = owner_api.wallet_inst.clone();
let api_handler_v3 = OwnerAPIHandlerV3::new(owner_api, keychain_mask.clone(), running_foreign);
router
.add_route("/v3/owner", Arc::new(api_handler_v3))
@@ -240,8 +225,12 @@ where
// If so configured, add the foreign API to the same port
if running_foreign {
warn!("Starting HTTP Foreign API on Owner server at {}.", addr);
let foreign_api_handler_v2 =
ForeignAPIHandlerV2::new(wallet, keychain_mask, test_mode, Mutex::new(tor_config));
let foreign_api_handler_v2 = ForeignAPIHandlerV2::new(
wallet,
owner_api.shared_config_path(),
keychain_mask,
test_mode,
);
router
.add_route("/v2/foreign", Arc::new(foreign_api_handler_v2))
.map_err(|_| Error::GenericError("Router failed to add route".to_string()))?;
@@ -265,99 +254,162 @@ where
/// port and wrapping the calls
pub fn foreign_listener<L, C, K>(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
config_path: PathBuf,
bridge: Option<String>,
use_tor: Option<bool>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
addr: &str,
tls_config: Option<TLSConfig>,
use_tor: bool,
test_mode: bool,
tor_config: TorConfig,
) -> Result<(), Error>
where
L: WalletLCProvider<'static, C, K> + 'static,
C: NodeClient + 'static,
K: Keychain + 'static,
{
// Check if wallet has been opened first
let (sec_key, tor_dir, onion_address) = {
let mask = keychain_mask.lock();
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 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 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)))?;
(sec_key, tor_dir, onion_address)
};
loop {
let (restart_tx, restart_rx) = std::sync::mpsc::channel::<()>();
register_config_listener(&config_path, "foreign_listener", restart_tx)?;
let api_handler_v2 = ForeignAPIHandlerV2::new(
wallet,
keychain_mask,
test_mode,
Mutex::new(Some(tor_config.clone())),
);
let mut router = Router::new();
let tor_config = listener_tor_config(&config_path, bridge.clone(), use_tor)?;
router
.add_route("/v2/foreign", Arc::new(api_handler_v2))
.map_err(|_| Error::GenericError("Router failed to add route".to_string()))?;
let api_chan: (mpsc::Sender<()>, mpsc::Receiver<()>) = mpsc::channel::<()>(1);
let mut apis = ApiServer::new();
warn!("Starting HTTP Foreign listener API server at {}.", addr);
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
let api_thread = apis
.start(socket_addr, router, tls_config, api_chan)
.map_err(|_| Error::GenericError("API thread failed to start".to_string()))?;
warn!("HTTP Foreign listener started.");
// Need to keep external process in scope while the listener is running.
let tor_service = if use_tor {
let use_integrated = tor_config.use_integrated.unwrap_or(false);
let res = if use_integrated {
start_tor_service(sec_key, &tor_dir, addr, tor_config.clone())
} else {
init_tor_listener(sec_key, tor_dir, addr, tor_config)
// Check if wallet has been opened first
let (sec_key, tor_dir, onion_address) = {
let mask = keychain_mask.lock();
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 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 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)))?;
(sec_key, tor_dir, onion_address)
};
match res {
Ok(service) => {
warn!(
"Starting Tor Hidden Service for API listener at address {}, binding to {}",
onion_address, addr
);
Ok(Some(service))
}
Err(e) => {
warn!("Unable to start TOR listener");
error!("Tor Error: {}", e);
warn!("Listener is available on {}", addr);
Err(e)
}
}
} else {
Ok(None)
};
if tor_service.is_ok() {
if let Some(_) = tor_service.as_ref().unwrap() {
let sp_address = SlatepackAddress::try_from(onion_address.clone())?;
let qr_string = match QrCode::new(sp_address.to_string()) {
Ok(qr) => qr.to_string(false, 3),
Err(_) => "Failed to generate QR code!".to_string(),
let api_handler_v2 = ForeignAPIHandlerV2::new(
wallet.clone(),
config_path.clone().into(),
keychain_mask.clone(),
test_mode,
);
let mut router = Router::new();
router
.add_route("/v2/foreign", Arc::new(api_handler_v2))
.map_err(|_| Error::GenericError("Router failed to add route".to_string()))?;
let api_chan: (mpsc::Sender<()>, mpsc::Receiver<()>) = mpsc::channel::<()>(1);
let stop_tx = api_chan.0.clone();
let mut apis = ApiServer::new();
warn!("Starting HTTP Foreign listener API server at {}.", addr);
let socket_addr: SocketAddr = addr.parse().expect("unable to parse socket address");
let api_thread = apis
.start(socket_addr, router, tls_config.clone(), api_chan)
.map_err(|_| Error::GenericError("API thread failed to start".to_string()))?;
warn!("HTTP Foreign listener started.");
// Need to keep external process in scope while the listener is running.
let _tor_service = if tor_config.use_tor_listener {
let use_integrated = tor_config.use_integrated.unwrap_or(false);
let res: Result<Option<TorProcess>, Error> = if use_integrated {
match start_tor_service(sec_key, addr, &tor_config.clone()) {
Ok(_) => Ok(None),
Err(e) => {
error!("Error starting integrated Tor service: {}", e);
Err(e)
}
}
} else {
match init_tor_listener(sec_key, tor_dir, addr, tor_config.clone()) {
Ok(p) => Ok(Some(p)),
Err(e) => {
error!("Error starting external Tor listener: {}", e);
Err(e)
}
}
};
warn!("Slatepack Address is: {}\n{}", sp_address, qr_string);
match res {
Ok(service) => {
warn!(
"Starting Tor Hidden Service for API listener at address {}, binding to {}",
onion_address, addr
);
let sp_address = SlatepackAddress::try_from(onion_address.clone())?;
let qr_string = match QrCode::new(sp_address.to_string()) {
Ok(qr) => qr.to_string(false, 3),
Err(_) => "Failed to generate QR code!".to_string(),
};
warn!("Slatepack Address is: {}\n{}", sp_address, qr_string);
Ok(service)
}
Err(e) => {
warn!("Unable to start TOR listener");
error!("Tor Error: {}", e);
warn!("Listener is available on {}", addr);
Err(e)
}
}
} else {
warn!("Listener is available on {}", addr);
}
}
Ok(None)
};
api_thread
.join()
.map_err(|e| Error::GenericError(format!("API thread panicked :{:?}", e)))
// Start thread to check if restart is needed.
let restart_needed = Arc::new(AtomicBool::new(false));
let t_restart_needed = restart_needed.clone();
thread::spawn(move || {
if restart_rx.recv().is_ok() {
t_restart_needed.store(true, Ordering::SeqCst);
let _ = stop_tx.try_send(());
}
});
let res = api_thread
.join()
.map_err(|e| Error::GenericError(format!("API thread panicked :{:?}", e)));
if tor_config.use_tor_listener && tor_config.use_integrated.unwrap_or(false) {
stop_tor_service(onion_address.to_string())?;
}
if restart_needed.load(Ordering::Relaxed) {
continue;
}
remove_global_config_listener(&config_path, "foreign_listener");
return res;
}
}
fn register_config_listener(
config_path: &PathBuf,
listener_id: &str,
tx: std::sync::mpsc::Sender<()>,
) -> Result<(), Error> {
get_global_config(config_path)?;
add_global_config_listener(config_path, listener_id, tx);
Ok(())
}
fn listener_tor_config(
config_path: &Path,
bridge: Option<String>,
use_tor: Option<bool>,
) -> Result<TorConfig, Error> {
let mut tor_config = get_global_config(config_path)?.tor_config();
if let Some(bridge) = bridge {
tor_config.bridge.bridge_line = Some(bridge);
}
if let Some(use_tor) = use_tor {
tor_config.use_tor_listener = use_tor;
}
Ok(tor_config)
}
/// V3 API Handler/Wrapper for owner functions, which include a secure
@@ -577,17 +629,16 @@ where
{
/// Create a new owner API handler for GET methods
pub fn new(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
owner_api: &Owner<L, C, K>,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
tor_config: Option<TorConfig>,
running_foreign: bool,
) -> OwnerAPIHandlerV3<L, C, K> {
let owner_api = Owner::new(wallet.clone(), None);
owner_api.set_tor_config(tor_config);
let owner_api = Arc::new(owner_api);
let wallet = owner_api.wallet_inst.clone();
let config_path = owner_api.shared_config_path();
let owner_api = Owner::new(wallet.clone(), None, config_path);
OwnerAPIHandlerV3 {
wallet,
owner_api,
owner_api: Arc::new(owner_api),
shared_key: Arc::new(Mutex::new(None)),
keychain_mask,
running_foreign,
@@ -706,14 +757,14 @@ where
C: NodeClient + 'static,
K: Keychain + 'static,
{
/// Wallet instance
/// Wallet instance.
pub wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
/// Wallet configuration path.
pub config_path: ConfigPath,
/// Keychain mask
pub keychain_mask: Arc<Mutex<Option<SecretKey>>>,
/// run in doctest mode
pub test_mode: bool,
/// tor config
pub tor_config: Mutex<Option<TorConfig>>,
}
impl<L, C, K> ForeignAPIHandlerV2<L, C, K>
@@ -725,15 +776,15 @@ where
/// Create a new foreign API handler for GET methods
pub fn new(
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
config_path: ConfigPath,
keychain_mask: Arc<Mutex<Option<SecretKey>>>,
test_mode: bool,
tor_config: Mutex<Option<TorConfig>>,
) -> ForeignAPIHandlerV2<L, C, K> {
ForeignAPIHandlerV2 {
wallet,
config_path,
keychain_mask,
test_mode,
tor_config,
}
}
@@ -756,11 +807,10 @@ where
req: Request<Incoming>,
mask: Option<SecretKey>,
wallet: Arc<Mutex<Box<dyn WalletInst<'static, L, C, K> + 'static>>>,
config_path: ConfigPath,
test_mode: bool,
tor_config: Option<TorConfig>,
) -> Result<Response<ApiBody>, Error> {
let api = Foreign::new(wallet, mask, Some(check_middleware), test_mode);
api.set_tor_config(tor_config);
let api = Foreign::new(wallet, config_path, mask, Some(check_middleware), test_mode);
let res = Self::call_api(req, api).await?;
Ok(json_response_pretty(&res))
}
@@ -776,10 +826,10 @@ where
let mask = self.keychain_mask.lock().clone();
let wallet = self.wallet.clone();
let test_mode = self.test_mode;
let tor_config = self.tor_config.lock().clone();
let config_path = self.config_path.clone();
Box::pin(async move {
match Self::handle_post_request(req, mask, wallet, test_mode, tor_config).await {
match Self::handle_post_request(req, mask, wallet, config_path, test_mode).await {
Ok(v) => Ok(v),
Err(e) => {
error!("Request Error: {:?}", e);
@@ -866,3 +916,48 @@ where
serde_json::from_reader(cursor)
.map_err(|e| Error::GenericError(format!("Invalid request body: {}", e)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::global::ChainTypes;
use grin_wallet_config::config::update_global_config;
use grin_wallet_config::GlobalWalletConfig;
use std::fs;
use std::sync::mpsc::channel;
use std::time::Duration;
use uuid::Uuid;
#[test]
fn listener_reload() {
let dir = std::env::temp_dir().join(format!("grin-wallet-listener-{}", Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join("grin-wallet.toml");
let mut config = GlobalWalletConfig::for_chain(&ChainTypes::AutomatedTesting, &path);
config
.write_to_file(path.to_str().unwrap(), false, None, None)
.unwrap();
let (restart_tx, restart_rx) = channel();
register_config_listener(&path, "test_listener", restart_tx).unwrap();
update_global_config(&path, |config| {
config.members.tor.as_mut().unwrap().socks_proxy_addr = "127.0.0.1:59051".into();
Ok(())
})
.unwrap();
restart_rx.recv_timeout(Duration::from_secs(1)).unwrap();
let tor_config =
listener_tor_config(&path, Some("obfs4 test-bridge".into()), Some(false)).unwrap();
assert_eq!(tor_config.socks_proxy_addr, "127.0.0.1:59051");
assert_eq!(
tor_config.bridge.bridge_line.as_deref(),
Some("obfs4 test-bridge")
);
assert!(!tor_config.use_tor_listener);
remove_global_config_listener(&path, "test_listener");
fs::remove_dir_all(dir).unwrap();
}
}
+173 -117
View File
@@ -19,6 +19,7 @@ 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};
@@ -78,33 +79,48 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// add account to wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// Default wallet 2 to listen on that account
{
@@ -128,17 +144,22 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// now check second account
{
@@ -149,115 +170,150 @@ fn accounts_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
w.set_parent_key_id_by_name("account1")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
// 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(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
// 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(())
},
)?;
// should be nothing in default account
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("default")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Send a tx to another wallet
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("account1")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// other account should be untouched
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("account2")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// wallet 2 should only have this tx on the listener account
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// 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(Some(wallet2.clone()), mask2, None, |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(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
+38 -22
View File
@@ -21,6 +21,7 @@ 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 impls::test_framework::{self, LocalWalletClient};
@@ -73,15 +74,25 @@ 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(Some(wallet1.clone()), mask1, None, |api, _m| {
api.stop_updater()?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, _m| {
api.stop_updater()?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, _m| {
api.stop_updater()?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, _m| {
api.stop_updater()?;
Ok(())
},
)?;
// few values to keep things shorter
let reward = core::consensus::REWARD;
@@ -94,17 +105,22 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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'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;
@@ -121,14 +137,14 @@ fn build_chain(test_dir: &'static str, block_height: usize) -> Result<(), libwal
let mut slate = Slate::blank(1, false);
debug!("Creating TX for {}", amount);
wallet::controller::owner_single_use(
Some(wallet1.clone()),
wallet1.clone(),
mask1,
None,
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,
+19 -13
View File
@@ -25,6 +25,7 @@ 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;
@@ -66,23 +67,28 @@ 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(Some(wallet1.clone()), mask1, None, |sender_api, m| {
let built_output = sender_api.build_output(m, features, amount)?;
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 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()?;
let output = built_output.output;
assert_eq!(output.features(), features);
assert_eq!(output.commitment(), secp.commit(amount, key)?);
output.verify_proof()?;
Ok(())
})?;
Ok(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+414 -253
View File
@@ -27,6 +27,7 @@ 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;
@@ -92,20 +93,30 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let cm = global::coinbase_maturity() as u64; // assume all testing precedes soft fork height
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// add account to wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account_1")?;
api.set_active_account(m, "account_1")?;
Ok(())
})?;
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(())
},
)?;
// Do some mining
let bh = 20u64;
@@ -113,26 +124,36 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Accidentally delete some outputs
let mut w1_outputs_commits = vec![];
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
w1_outputs_commits = api.retrieve_outputs(m, false, true, None)?.1;
Ok(())
})?;
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: Vec<libwallet::OutputData> =
w1_outputs_commits.into_iter().map(|m| m.output).collect();
{
@@ -149,73 +170,108 @@ fn scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
}
// check we have a problem now
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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!(wallet1_info.total != c);
Ok(())
})?;
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(())
},
)?;
// this should restore our missing outputs
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.scan(m, None, true)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, true)?;
Ok(())
},
)?;
// check our outputs match again
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// perform a transaction, but don't let it finish
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// check we're all locked
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert!(wallet1_refreshed);
assert!(wallet1_info.amount_currently_spendable == 0);
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.amount_currently_spendable, 0);
Ok(())
},
)?;
// unlock/restore
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.scan(m, None, true)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, true)?;
Ok(())
},
)?;
// check spendable amount again
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert_eq!(wallet1_info.amount_currently_spendable, (bh - cm) * reward);
Ok(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
@@ -412,13 +468,18 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// send some funds to wallet 2
send_to_dest!(
@@ -462,33 +523,53 @@ 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(Some(wallet3.clone()), mask3, None, |api, m| {
api.scan(m, None, false)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet3.clone(),
mask3,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, false)?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet3.clone()), mask3, None, |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(())
})?;
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(())
},
)?;
// 2) scan should recover them into a single wallet
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.scan(m, None, true)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, true)?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// 3) If I recover from seed and start using the wallet without restoring,
// scan should restore the older outputs
@@ -520,26 +601,41 @@ 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(Some(wallet4.clone()), mask4, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet5.clone()), mask5, None, |api, m| {
api.scan(m, None, false)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet5.clone(),
mask5,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, false)?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet5.clone()), mask5, None, |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(())
})?;
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(())
},
)?;
// 4) If I recover from seed and start using the wallet without restoring,
// scan should restore the older outputs
@@ -575,26 +671,41 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er
);
bh += cm as u64;
wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |api, m| {
api.scan(m, None, true)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet6.clone(),
mask6,
PathBuf::from(test_dir),
|api, m| {
api.scan(m, None, true)?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet6.clone()), mask6, None, |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(())
})?;
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(())
},
)?;
// 5) Start using same seed with a different account, amounts should
// be distinct and restore should return funds from other account
@@ -623,11 +734,16 @@ 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(Some(wallet7.clone()), mask7, None, |api, m| {
api.create_account_path(m, "account_1")?;
api.set_active_account(m, "account_1")?;
Ok(())
})?;
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(())
},
)?;
send_to_dest!(
miner.clone(),
@@ -656,42 +772,57 @@ 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(Some(wallet7.clone()), mask7, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet8.clone()), mask8, None, |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(())
})?;
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(())
},
)?;
// 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(Some(wallet9.clone()), mask9, None, |api, m| {
api.create_account_path(m, "account_1")?;
api.set_active_account(m, "account_1")?;
Ok(())
})?;
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(())
},
)?;
send_to_dest!(
miner.clone(),
@@ -717,43 +848,53 @@ fn two_wallets_one_seed_impl(test_dir: &'static str) -> Result<(), libwallet::Er
bh += 3;
let _bh = bh;
wallet::controller::owner_single_use(Some(wallet9.clone()), mask9, None, |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);
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);
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(())
})?;
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(())
},
)?;
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(Some(wallet10.clone()), mask10, None, |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);
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);
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(())
})?;
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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
@@ -877,13 +1018,18 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false);
let mut output_commits = vec![];
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
{
wallet_inst!(wallet1, w);
@@ -930,13 +1076,18 @@ fn multi_batch_scan_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
}
assert!(batches > 1);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
stopper.store(false, Ordering::Relaxed);
thread::sleep(Duration::from_millis(200));
@@ -974,12 +1125,17 @@ fn restore_corrupted_outputs_across_batches_impl(
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false);
let mut output_commits = vec![];
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
{
wallet_inst!(wallet1, w);
@@ -1017,25 +1173,30 @@ fn restore_corrupted_outputs_across_batches_impl(
assert_eq!(last_scanned.hash, "");
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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);
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 (_, 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::<std::collections::HashSet<_>>();
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::<std::collections::HashSet<_>>();
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));
Ok(())
},
)?;
stopper.store(false, Ordering::Relaxed);
thread::sleep(Duration::from_millis(200));
+228
View File
@@ -0,0 +1,228 @@
// 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.
extern crate grin_wallet_api as api;
extern crate grin_wallet_config as config;
extern crate grin_wallet_impls as impls;
extern crate grin_wallet_libwallet as libwallet;
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;
mod common;
use common::{clean_output_dir, create_wallet_proxy, setup};
fn snapshot(path: &Path) -> Vec<(PathBuf, Vec<u8>)> {
fn collect(root: &Path, path: &Path, files: &mut Vec<(PathBuf, Vec<u8>)>) {
for entry in fs::read_dir(path).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if path.is_dir() {
collect(root, &path, files);
} else if path.file_name().and_then(|name| name.to_str()) != Some("lock.mdb") {
files.push((
path.strip_prefix(root).unwrap().into(),
fs::read(path).unwrap(),
));
}
}
}
let mut files = vec![];
collect(path, path, &mut files);
files.sort_by(|left, right| left.0.cmp(&right.0));
files
}
#[test]
fn tor_disable() {
let test_dir = "test_output/config_api_tor";
setup(test_dir);
let mut wallet_proxy = create_wallet_proxy(test_dir);
create_wallet_and_add!(
client,
wallet,
mask,
test_dir,
"wallet",
None,
&mut wallet_proxy,
false
);
let path = PathBuf::from(test_dir).join("grin-wallet.toml");
let mut config =
GlobalWalletConfig::for_chain(&grin_core::global::ChainTypes::AutomatedTesting, &path);
config
.write_to_file(path.to_str().unwrap(), false, None, None)
.unwrap();
reload_global_config(&path).unwrap();
let mut contents = fs::read_to_string(&path).unwrap();
let tor = contents.find("[tor]").unwrap();
let logging = contents.find("[logging]").unwrap();
contents.replace_range(tor..logging, "");
let contents = contents.replace("api_listen_port = 3415", "api_listen_port = 3416");
fs::write(&path, contents).unwrap();
let owner = api::Owner::new(wallet.clone(), None, path.clone());
owner.set_tor_config(None).unwrap();
let stored_config = GlobalWalletConfig::new(path.clone()).unwrap();
assert_eq!(stored_config.members.wallet.api_listen_port, 3416);
let stored = stored_config.tor_config();
let cached = get_global_config(&path).unwrap().tor_config();
assert!(!stored.use_tor_listener);
assert_eq!(stored.skip_send_attempt, Some(true));
assert_eq!(
stored.send_config_dir,
stored_config.members.wallet.data_file_dir
);
assert_eq!(cached, stored);
drop(owner);
drop(wallet);
drop(wallet_proxy);
clean_output_dir(test_dir);
}
#[test]
fn send_preflight() {
let test_dir = "test_output/config_api_send";
setup(test_dir);
let mut wallet_proxy = create_wallet_proxy(test_dir);
create_wallet_and_add!(
client,
wallet,
mask,
test_dir,
"wallet",
None,
&mut wallet_proxy,
false
);
let owner = api::Owner::new(
wallet.clone(),
None,
PathBuf::from(test_dir).join("missing.toml"),
);
let mask = mask.as_ref();
let (_, before_txs) = owner.retrieve_txs(mask, false, None, None, None).unwrap();
assert!(before_txs.is_empty());
let wallet_data = PathBuf::from(test_dir).join("wallet/wallet_data");
let before_data = snapshot(&wallet_data);
assert!(before_data.iter().any(|(path, _)| path.starts_with("db")));
let args = InitTxArgs {
amount: 1,
send_args: Some(InitTxSendArgs {
dest: "unused".into(),
post_tx: false,
fluff: false,
skip_tor: Some(true),
}),
..Default::default()
};
let error = owner.init_send_tx(mask, args).unwrap_err();
assert!(error.to_string().contains("Configuration file not found"));
let (_, after_txs) = owner.retrieve_txs(mask, false, None, None, None).unwrap();
assert!(after_txs.is_empty());
assert_eq!(snapshot(&wallet_data), before_data);
drop(owner);
drop(wallet);
drop(wallet_proxy);
clean_output_dir(test_dir);
}
#[test]
fn directory_change() {
let test_dir = "test_output/config_api_directory";
setup(test_dir);
let mut wallet_proxy = create_wallet_proxy(test_dir);
create_wallet_and_add!(
client,
wallet,
mask,
test_dir,
"wallet",
None,
&mut wallet_proxy,
false
);
let old_dir = PathBuf::from(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());
let error = owner
.set_top_level_directory(new_dir.to_str().unwrap())
.unwrap_err();
assert!(error.to_string().contains("Close the wallet"));
assert_eq!(owner.config_path(), old_config);
assert_eq!(
PathBuf::from(owner.get_top_level_directory().unwrap()),
old_dir
);
owner.close_wallet(None).unwrap();
owner.updater_running.store(true, Ordering::Relaxed);
let error = owner
.set_top_level_directory(new_dir.to_str().unwrap())
.unwrap_err();
assert!(error.to_string().contains("Stop the updater"));
owner.updater_running.store(false, Ordering::Relaxed);
fs::create_dir_all(&new_dir).unwrap();
let new_config = new_dir.join("grin-wallet.toml");
let mut config = GlobalWalletConfig::for_chain(
&grin_core::global::ChainTypes::AutomatedTesting,
&new_config,
);
config
.write_to_file(new_config.to_str().unwrap(), false, None, None)
.unwrap();
reload_global_config(&new_config).unwrap();
let expected_port = config.members.wallet.api_listen_port + 1;
config.members.wallet.api_listen_port = expected_port;
config
.write_to_file(new_config.to_str().unwrap(), false, None, None)
.unwrap();
owner
.set_top_level_directory(new_dir.to_str().unwrap())
.unwrap();
assert_eq!(owner.config_path(), new_config);
assert_eq!(
get_global_config(&owner.config_path())
.unwrap()
.members
.wallet
.api_listen_port,
expected_port
);
assert_eq!(
PathBuf::from(owner.get_top_level_directory().unwrap()),
new_dir
);
drop(owner);
drop(wallet);
drop(wallet_proxy);
clean_output_dir(test_dir);
}
+207 -131
View File
@@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls;
use grin_core as core;
use grin_wallet_libwallet as libwallet;
use std::path::PathBuf;
use impls::test_framework::{self, LocalWalletClient};
use impls::{PathToSlate, SlateGetter as _, SlatePutter as _};
@@ -75,18 +76,28 @@ 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(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// add some accounts
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account1")?;
api.create_account_path(m, "account2")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -111,27 +122,32 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -142,43 +158,63 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(),
let mut slate = PathToSlate((&send_file).into()).get_tx()?.0;
// wallet 2 receives file, completes, sends file back
wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| {
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet2.clone(),
PathBuf::from(test_dir),
mask2_i.clone(),
|api| {
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?;
Ok(())
},
)?;
// wallet 1 finalises and posts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Check total in 'wallet 2' account
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// Now other types of exchange, for reference
// Invoice transaction
@@ -197,43 +233,63 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(),
let mut slate = Slate::blank(2, true);
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(), mask2_i.clone(), |api| {
// Wallet 2 receives the invoice transaction
slate = PathToSlate((&receive_file).into()).get_tx()?.0;
slate = api.finalize_tx(&slate, false)?;
PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?;
Ok(())
})?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
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),
mask2_i.clone(),
|api| {
// Wallet 2 receives the invoice transaction
slate = PathToSlate((&receive_file).into()).get_tx()?.0;
slate = api.finalize_tx(&slate, false)?;
PathToSlate((&final_file).into()).put_tx(&slate, use_bin)?;
Ok(())
},
)?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
},
)?;
// Standard, with payment proof
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
@@ -251,46 +307,66 @@ fn file_exchange_test_impl(test_dir: &'static str, use_bin: bool) -> Result<(),
};
let mut slate = Slate::blank(2, true);
let mut address = None;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| {
slate = PathToSlate((&send_file).into()).get_tx()?.0;
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet2.clone(),
PathBuf::from(test_dir),
mask2_i.clone(),
|api| {
slate = PathToSlate((&send_file).into()).get_tx()?.0;
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, use_bin)?;
Ok(())
},
)?;
// wallet 1 finalises and posts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+229 -153
View File
@@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls;
use grin_core as core;
use grin_wallet_libwallet as libwallet;
use std::path::PathBuf;
use impls::test_framework::{self, LocalWalletClient};
use libwallet::{InitTxArgs, IssueInvoiceTxArgs, Slate, SlateState};
@@ -71,11 +72,16 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let reward = core::consensus::REWARD;
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -87,122 +93,167 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 mut slate = Slate::blank(2, true);
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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::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(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice1);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice2);
// wallet 2 finalizes and posts
wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet2.clone(),
PathBuf::from(test_dir),
mask2_i.clone(),
|api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
Ok(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice3);
// wallet 1 posts so wallet 2 doesn't get the mined amount
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
},
)?;
_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(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// Check transaction log for wallet 1, ensure only 1 entry
// exists
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Test self-sending
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
println!("Self invoice slate after process: {}", slate);
// wallet 1 finalizes and posts
wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet1.clone(),
PathBuf::from(test_dir),
mask1_i.clone(),
|api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
Ok(())
},
)?;
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
//bh += 3;
@@ -210,82 +261,107 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
// As above, but use owner API to finalize
let mut slate = Slate::blank(2, true);
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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::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(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice1);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice2);
// wallet 2 finalizes via owner API
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(m, &slate)?;
Ok(())
})?;
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(())
},
)?;
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(Some(wallet2.clone()), mask2, None, |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::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(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice1);
let orig_slate = slate.clone();
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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 cancels the invoice transaction
api.cancel_tx(m, None, Some(slate.id))?;
// Wallet 1 cancels the invoice transaction
api.cancel_tx(m, None, Some(slate.id))?;
// Wallet 1 attempts to repay again
let res = api.process_invoice_tx(m, &orig_slate, args);
assert!(res.is_err());
// Wallet 1 attempts to repay again
let res = api.process_invoice_tx(m, &orig_slate, args);
assert!(res.is_err());
Ok(())
})?;
Ok(())
},
)?;
assert_eq!(slate.state, SlateState::Invoice2);
// let logging finish
+71 -45
View File
@@ -20,6 +20,7 @@ extern crate grin_wallet_libwallet as libwallet;
use self::libwallet::{InitTxArgs, Slate};
use impls::test_framework::{self, LocalWalletClient};
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
@@ -68,16 +69,26 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
});
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
Ok(())
})?;
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(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account1")?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, m| {
api.create_account_path(m, "account1")?;
Ok(())
},
)?;
// Get some mining done
{
@@ -94,52 +105,67 @@ fn late_lock_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let mut slate = Slate::blank(2, false);
let amount = 100_000_000_000;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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);
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);
// 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 = sender_api.finalize_tx(m, &slate)?;
println!("S3 SLATE: {}", slate);
// Now post tx to our node for inclusion in the next block.
sender_api.post_tx(m, &slate, true)?;
// Now post tx to our node for inclusion in the next block.
sender_api.post_tx(m, &slate, true)?;
Ok(())
})?;
Ok(())
},
)?;
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false)?;
// update/test contents of both accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+110 -79
View File
@@ -20,6 +20,7 @@ extern crate grin_wallet_impls as impls;
use grin_core as core;
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};
@@ -64,11 +65,16 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let reward = core::consensus::REWARD;
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -80,98 +86,123 @@ 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(Some(wallet1.clone()), mask1, None, |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(), mask1_i.clone(), |api| {
slate = api.receive_tx(&slate, Some("listener"), None)?;
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 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;
Ok(())
})?;
slate = api.finalize_tx(m, &slate)?;
api.post_tx(m, &slate, false)?; // mines a block
bh += 1;
Ok(())
})?;
},
)?;
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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Check total in 'listener' account
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("listener")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Recipient wallet creates a mwixnet request from the last output
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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();
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 mwixnet_req = api.create_mwixnet_req(m, &params, &last_output.commit, true)?;
let mwixnet_req = api.create_mwixnet_req(m, &params, &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);
// 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(())
})?;
Ok(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+145 -99
View File
@@ -18,6 +18,7 @@ extern crate grin_wallet_controller as wallet;
extern crate grin_wallet_impls as impls;
use grin_core as core;
use std::path::PathBuf;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient};
@@ -78,122 +79,167 @@ fn no_change_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
// 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Refresh and check transaction log for wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// ensure invoice TX works as well with no change
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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::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::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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 2 finalizes and posts
wallet::controller::foreign_single_use(wallet2.clone(), mask2_i.clone(), |api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
Ok(())
})?;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask1, None, |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(())
})?;
wallet::controller::foreign_single_use(
wallet2.clone(),
PathBuf::from(test_dir),
mask2_i.clone(),
|api| {
// Wallet 2 receives the invoice transaction
slate = api.finalize_tx(&slate, false)?;
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(())
},
)?;
// check wallet 2's version
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// Refresh and check transaction log for wallet 1
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
+77 -61
View File
@@ -21,6 +21,7 @@ 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;
@@ -77,83 +78,98 @@ fn payment_proofs_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false);
let mut address = None;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
},
)?;
println!("Public address is: {:?}", address);
let amount = 60_000_000_000;
let mut slate = Slate::blank(1, false);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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)?;
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)?;
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)?;
sender_api.tx_lock_outputs(m, &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) = 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);
// 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 = sender_api.retrieve_payment_proof(m, 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 = sender_api.finalize_tx(m, &slate)?;
sender_api.post_tx(m, &slate, true)?;
Ok(())
},
)?;
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 2, false);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |sender_api, m| {
// Check payment proof here
let mut pp = sender_api.retrieve_payment_proof(m, true, None, Some(slate.id))?;
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))?;
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 = sender_api.verify_payment_proof(m, &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 = sender_api.verify_payment_proof(m, &pp);
assert!(res.is_err());
Ok(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+163 -102
View File
@@ -19,6 +19,7 @@ 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 impls::test_framework::{self, LocalWalletClient};
@@ -74,18 +75,28 @@ 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(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// add some accounts
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account1")?;
api.create_account_path(m, "account2")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -102,26 +113,31 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
let mut slate = Slate::blank(2, false);
// Should have 5 in account1 (5 spendable), 5 in account (2 spendable)
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
@@ -132,12 +148,17 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
w.set_parent_key_id_by_name("listener")?;
}
wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| {
slate = PathToSlate((&send_file).into()).get_tx()?.0;
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, false)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet1.clone(),
PathBuf::from(test_dir),
mask1_i.clone(),
|api| {
slate = PathToSlate((&send_file).into()).get_tx()?.0;
slate = api.receive_tx(&slate, None, None)?;
PathToSlate((&receive_file).into()).put_tx(&slate, false)?;
Ok(())
},
)?;
// wallet 1 receives file to different account, completes
{
@@ -146,47 +167,67 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
}
// wallet 1 finalize
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
slate = PathToSlate((&receive_file).into()).get_tx()?.0;
slate = api.finalize_tx(m, &slate)?;
Ok(())
})?;
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(())
},
)?;
// Now repost from cached
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 _ = 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("listener")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// as above, but syncronously
{
@@ -201,55 +242,75 @@ fn file_repost_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
let mut slate = Slate::blank(2, false);
let amount = 60_000_000_000;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
// Now repost from cached
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 _ = 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(Some(wallet1.clone()), mask1, None, |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(
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(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+11 -10
View File
@@ -31,6 +31,7 @@ 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;
@@ -104,13 +105,13 @@ fn revert(
}
});
owner(Some(wallet1.clone()), mask1, None, |api, m| {
owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| {
api.create_account_path(m, "a")?;
api.set_active_account(m, "a")?;
Ok(())
})?;
owner(Some(wallet2.clone()), mask2, None, |api, m| {
owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| {
api.create_account_path(m, "b")?;
api.set_active_account(m, "b")?;
Ok(())
@@ -125,7 +126,7 @@ fn revert(
award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false)?;
// Sanity check contents
owner(Some(wallet1.clone()), mask1, None, |api, m| {
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);
@@ -140,7 +141,7 @@ fn revert(
Ok(())
})?;
owner(Some(wallet2.clone()), mask2, None, |api, m| {
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);
@@ -155,7 +156,7 @@ fn revert(
// Send some funds
let mut tx = None;
owner(Some(wallet1.clone()), mask1, None, |api, m| {
owner(wallet1.clone(), mask1, PathBuf::from(test_dir), |api, m| {
// send to send
let args = InitTxArgs {
src_acct_name: None,
@@ -180,7 +181,7 @@ fn revert(
let tx = tx.expect("tx from slate");
// Check funds have been received
owner(Some(wallet2.clone()), mask2, None, |api, m| {
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);
@@ -222,7 +223,7 @@ fn revert(
let bh = bh + 1;
// Check funds have been confirmed
owner(Some(wallet2.clone()), mask2, None, |api, m| {
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);
@@ -257,7 +258,7 @@ fn revert(
let bh = bh + 1;
// Check funds have been reverted
owner(Some(wallet2.clone()), mask2, None, |api, m| {
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);
@@ -292,7 +293,7 @@ fn revert_reconfirm_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
let bh = bh + 1;
// Check funds have been confirmed again
owner(Some(wallet2.clone()), mask2, None, |api, m| {
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);
@@ -320,7 +321,7 @@ fn revert_cancel_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let mask2 = mask2_i.as_ref();
// Cancelling tx
owner(Some(wallet2.clone()), mask2, None, |api, m| {
owner(wallet2.clone(), mask2, PathBuf::from(test_dir), |api, m| {
// Sanity check
let (refreshed, info) = api.retrieve_summary_info(m, true, 1)?;
assert!(refreshed);
+71 -45
View File
@@ -18,6 +18,7 @@ extern crate grin_wallet_controller as wallet;
extern crate grin_wallet_impls as impls;
use grin_core as core;
use std::path::PathBuf;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient};
@@ -62,11 +63,16 @@ 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(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -78,58 +84,78 @@ 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(Some(wallet1.clone()), mask1, None, |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(), mask1_i.clone(), |api| {
slate = api.receive_tx(&slate, Some("listener"), None)?;
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 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;
Ok(())
})?;
slate = api.finalize_tx(m, &slate)?;
api.post_tx(m, &slate, false)?; // mines a block
bh += 1;
Ok(())
})?;
},
)?;
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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Check total in 'listener' account
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("listener")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
+315 -223
View File
@@ -19,6 +19,7 @@ extern crate grin_wallet_impls as impls;
use grin_core as core;
use grin_wallet_libwallet as libwallet;
use std::path::PathBuf;
use impls::test_framework::{self, LocalWalletClient};
use impls::{PathToSlatepack, SlatePutter as _};
@@ -124,18 +125,28 @@ fn slatepack_exchange_test_impl(
let reward = core::consensus::REWARD;
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// add some accounts
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account1")?;
api.create_account_path(m, "account2")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -150,12 +161,17 @@ fn slatepack_exchange_test_impl(
true => {
let mut rec_address = SlatepackAddress::random();
let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
(
vec![rec_address.clone()],
Some(sec_key),
@@ -169,12 +185,17 @@ fn slatepack_exchange_test_impl(
true => {
let mut rec_address = SlatepackAddress::random();
let mut sec_key = edDalekSecretKey::from_bytes(&[0u8; 32]);
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
(
vec![rec_address.clone()],
Some(sec_key),
@@ -197,34 +218,39 @@ fn slatepack_exchange_test_impl(
),
};
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -236,54 +262,75 @@ fn slatepack_exchange_test_impl(
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(wallet2.clone(), mask2_i.clone(), |api| {
slate = api.receive_tx(&slate, None, None)?;
output_slatepack(
&slate,
&receive_file,
use_armored,
use_bin,
// re-encrypt for sender!
sender_2.clone(),
match slatepack.sender.clone() {
Some(s) => vec![s.clone()],
None => vec![],
},
)?;
Ok(())
})?;
wallet::controller::foreign_single_use(
wallet2.clone(),
PathBuf::from(test_dir),
mask2_i.clone(),
|api| {
slate = api.receive_tx(&slate, None, None)?;
output_slatepack(
&slate,
&receive_file,
use_armored,
use_bin,
// re-encrypt for sender!
sender_2.clone(),
match slatepack.sender.clone() {
Some(s) => vec![s.clone()],
None => vec![],
},
)?;
Ok(())
},
)?;
// wallet 1 finalises and posts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
// 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 _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
// Check total in mining account
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Check total in 'wallet 2' account
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// Now other types of exchange, for reference
// Invoice transaction
@@ -302,63 +349,83 @@ fn slatepack_exchange_test_impl(
let mut slate = Slate::blank(2, true);
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
wallet::controller::foreign_single_use(wallet2.clone(), 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(())
})?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
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(())
},
)?;
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(())
},
)?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
},
)?;
// Standard, with payment proof
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
@@ -377,66 +444,86 @@ fn slatepack_exchange_test_impl(
let mut slate = Slate::blank(2, true);
let mut address = None;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, m| {
address = Some(api.get_slatepack_address(m, 0)?);
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
wallet::controller::foreign_single_use(wallet2.clone(), 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;
slate = api.receive_tx(&slate, None, None)?;
output_slatepack(
&slate,
&receive_file,
use_armored,
use_bin,
sender_2,
match slatepack.sender {
Some(s) => vec![s.clone()],
None => vec![],
},
)?;
Ok(())
})?;
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;
slate = api.receive_tx(&slate, None, None)?;
output_slatepack(
&slate,
&receive_file,
use_armored,
use_bin,
sender_2,
match slatepack.sender {
Some(s) => vec![s.clone()],
None => vec![],
},
)?;
Ok(())
},
)?;
// wallet 1 finalises and posts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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::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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
@@ -481,27 +568,32 @@ 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
+471 -374
View File
@@ -25,6 +25,7 @@ use self::core::global;
use self::libwallet::{InitTxArgs, OutputStatus, Slate, SlateState};
use impls::test_framework::{self, LocalWalletClient};
use std::convert::TryInto;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
@@ -80,320 +81,390 @@ fn basic_transaction_api(test_dir: &'static str) -> Result<(), libwallet::Error>
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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// assert wallet contents
// and a single use api for a send command
let amount = 60_000_000_000;
let mut slate = Slate::blank(1, false);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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 slate_i = sender_api.init_send_tx(m, args)?;
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 slate_i = sender_api.init_send_tx(m, args)?;
assert_eq!(slate_i.state, SlateState::Standard1);
assert_eq!(slate_i.state, SlateState::Standard1);
// 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);
// 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);
sender_api.tx_lock_outputs(m, &slate)?;
slate = sender_api.finalize_tx(m, &slate)?;
assert_eq!(slate.state, SlateState::Standard3);
slate = client1.send_tx_slate_direct("wallet2", &slate_i)?;
assert_eq!(slate.state, SlateState::Standard2);
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()
}
);
// 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()
}
);
Ok(())
})?;
Ok(())
},
)?;
// Check transaction log for wallet 1
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// Check transaction log for wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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(())
})?;
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(())
},
)?;
// post transaction
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
},
)?;
// Check wallet 1 contents are as expected
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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);
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 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());
// 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(())
})?;
Ok(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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);
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);
// 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) = 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(())
},
)?;
// Estimate fee and locked amount for a transaction
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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);
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: 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);
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(())
})?;
Ok(())
},
)?;
// Send another transaction, but don't post to chain immediately and use
// the stored transaction instead
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// 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(Some(wallet2.clone()), mask2, None, |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);
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);
// 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) = 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(())
},
)?;
// try to send a transaction with amount inclusive of fees, but amount too
// small to cover fees. Should fail.
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
@@ -447,132 +518,158 @@ fn tx_rollback(test_dir: &'static str) -> Result<(), libwallet::Error> {
let amount = 30_000_000_000;
let mut slate = Slate::blank(1, false);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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()
};
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 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 = 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(())
},
)?;
// Check transaction log for wallet 1
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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;
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;
}
}
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);
assert_eq!(output_mappings.len(), 3);
assert_eq!(locked_count, 2);
assert_eq!(unconfirmed_count, 1);
Ok(())
})?;
Ok(())
},
)?;
// Check transaction log for wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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;
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;
}
}
}
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) = 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(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |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());
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(())
})?;
Ok(())
},
)?;
// Wallet 2 rolls back
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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());
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(())
})?;
Ok(())
},
)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+97 -66
View File
@@ -21,6 +21,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 std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
@@ -78,95 +79,125 @@ fn ttl_cutoff_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error>
let amount = 60_000_000_000;
let mut slate = Slate::blank(1, false);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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)?;
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)?;
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)?;
sender_api.tx_lock_outputs(m, &slate)?;
let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?;
let tx = txs[0].clone();
let (_, txs) = sender_api.retrieve_txs(m, 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));
Ok(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |sender_api, m| {
let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?;
let tx = txs[0].clone();
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();
assert_eq!(tx.ttl_cutoff_height, Some(12));
assert!(tx.tx_type == TxLogEntryType::TxSentCancelled);
Ok(())
})?;
assert_eq!(tx.ttl_cutoff_height, Some(12));
assert_eq!(tx.tx_type, TxLogEntryType::TxSentCancelled);
Ok(())
},
)?;
// Should also be gone in wallet 2, and output gone
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |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);
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);
assert_eq!(tx.ttl_cutoff_height, Some(12));
assert!(tx.tx_type == TxLogEntryType::TxReceivedCancelled);
Ok(())
})?;
assert_eq!(tx.ttl_cutoff_height, Some(12));
assert_eq!(tx.tx_type, TxLogEntryType::TxReceivedCancelled);
Ok(())
},
)?;
// 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(Some(wallet1.clone()), mask1, None, |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)?;
sender_api.tx_lock_outputs(m, &slate_i)?;
slate = slate_i;
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;
let (_, txs) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?;
let tx = txs[0].clone();
let (_, txs) = sender_api.retrieve_txs(m, 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));
Ok(())
},
)?;
// 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(Some(wallet2.clone()), mask2, None, |sender_api, m| {
let (_, _) = sender_api.retrieve_txs(m, true, None, Some(slate.id), None)?;
Ok(())
})?;
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(())
},
)?;
// And when wallet 1 sends, should be rejected
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |_sender_api, _m| {
let res = client1.send_tx_slate_direct("wallet2", &slate);
println!("Send after TTL result is: {:?}", res);
assert!(res.is_err());
Ok(())
})?;
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 logging finish
stopper.store(false, Ordering::Relaxed);
+195 -168
View File
@@ -23,6 +23,7 @@ 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 impls::test_framework::{self, LocalWalletClient};
@@ -53,154 +54,160 @@ fn test_wallet_tx_filtering(
>,
>,
mask: Option<&SecretKey>,
test_dir: &'static str,
) -> Result<(), libwallet::Error> {
wallet::controller::owner_single_use(Some(wallet.clone()), mask, None, |api, _m| {
let mut tx_query_args = RetrieveTxQueryArgs::default();
tx_query_args.min_id = Some(5);
wallet::controller::owner_single_use(
wallet.clone(),
mask,
PathBuf::from(test_dir),
|api, _m| {
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 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 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 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);
// 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 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);
// 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);
// 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);
}*/
/*for entry in tx_results.iter() {
println!("{:?}", entry);
}*/
Ok(())
})?;
Ok(())
},
)?;
Ok(())
}
@@ -248,15 +255,25 @@ 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(Some(wallet1.clone()), mask1, None, |api, _m| {
api.stop_updater()?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet1.clone(),
mask1,
PathBuf::from(test_dir),
|api, _m| {
api.stop_updater()?;
Ok(())
},
)?;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, _m| {
api.stop_updater()?;
Ok(())
})?;
wallet::controller::owner_single_use(
wallet2.clone(),
mask2,
PathBuf::from(test_dir),
|api, _m| {
api.stop_updater()?;
Ok(())
},
)?;
// few values to keep things shorter
let reward = core::consensus::REWARD;
@@ -268,17 +285,22 @@ fn build_chain_for_tx_filtering(
let mut wallet_1_has_funds = false;
// Check wallet 1 contents
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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(())
})?;
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(())
},
)?;
if !wallet_1_has_funds {
let _ =
@@ -293,9 +315,9 @@ fn build_chain_for_tx_filtering(
let mut slate = Slate::blank(1, false);
debug!("Creating TX for {}", amount);
wallet::controller::owner_single_use(
Some(wallet1.clone()),
wallet1.clone(),
mask1,
None,
PathBuf::from(test_dir),
|sender_api, m| {
// note this will increment the block count as part of the transaction "Posting"
let args = InitTxArgs {
@@ -321,26 +343,31 @@ fn build_chain_for_tx_filtering(
let amount: u64 = 1_000_000;
let mut slate = Slate::blank(1, false);
debug!("Creating TX for {}", amount);
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |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)?;
sender_api.cancel_tx(m, Some(33), None)?;
Ok(())
})?;
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)?;
sender_api.cancel_tx(m, Some(33), None)?;
Ok(())
},
)?;
// Perform actual testing
test_wallet_tx_filtering(wallet1, mask1)?;
test_wallet_tx_filtering(wallet1, mask1, test_dir)?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
+22 -11
View File
@@ -23,6 +23,7 @@ extern crate grin_wallet_libwallet as libwallet;
// use grin_wallet_util::grin_core as core;
use impls::test_framework::{self, LocalWalletClient};
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
@@ -71,18 +72,28 @@ fn updater_thread_test_impl(test_dir: &'static str) -> Result<(), libwallet::Err
});
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
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(())
},
)?;
// add some accounts
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
api.create_account_path(m, "account1")?;
api.create_account_path(m, "account2")?;
Ok(())
})?;
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(())
},
)?;
// Get some mining done
{
@@ -93,7 +104,7 @@ fn updater_thread_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 owner_api = api::Owner::new(wallet1, None);
let owner_api = api::Owner::new(wallet1, None, PathBuf::from(test_dir));
owner_api.start_updater(mask1, Duration::from_secs(5))?;
// let updater thread run a bit