wallet + config + ui: load wallet info, wallet connections and app config refactoring, check external connections availability, config subdir argument format, item button color, radio buttons stroke, chain type selection from connections, update translations

This commit is contained in:
ardocrat
2023-08-09 02:22:16 +03:00
parent 8ed6bc0578
commit 076a692e1b
27 changed files with 647 additions and 856 deletions
+27 -18
View File
@@ -19,33 +19,49 @@ use grin_core::global::ChainTypes;
use serde_derive::{Deserialize, Serialize};
use crate::{AppConfig, Settings};
use crate::wallet::types::ConnectionMethod;
/// Wallet configuration.
#[derive(Serialize, Deserialize, Clone)]
pub struct WalletConfig {
/// Chain type for current wallet.
pub(crate) chain_type: ChainTypes,
pub chain_type: ChainTypes,
/// Identifier for a wallet.
pub(crate) id: i64,
pub id: i64,
/// Human-readable wallet name for ui.
pub(crate) name: String,
/// External node connection URL.
pub(crate) external_node_url: Option<String>,
pub name: String,
/// External connection identifier.
pub ext_conn_id: Option<i64>,
/// Minimal amount of confirmations.
pub min_confirmations: u64
}
/// Wallet configuration file name.
const CONFIG_FILE_NAME: &'static str = "grim-wallet.toml";
/// Base wallets directory name.
pub const BASE_DIR_NAME: &'static str = "wallets";
/// Wallet configuration file name.
const CONFIG_FILE_NAME: &'static str = "grim-wallet.toml";
/// Minimal amount of confirmations default value.
const MIN_CONFIRMATIONS_DEFAULT: u64 = 10;
impl WalletConfig {
/// Create wallet config.
pub fn create(name: String, external_node_url: Option<String>) -> WalletConfig {
pub fn create(name: String, conn_method: &ConnectionMethod) -> WalletConfig {
// Setup configuration path.
let id = chrono::Utc::now().timestamp();
let chain_type = AppConfig::chain_type();
let config_path = Self::get_config_file_path(chain_type, id);
let config = WalletConfig { chain_type, id, name, external_node_url };
// Write configuration to the file.
let config = WalletConfig {
chain_type,
id,
name,
ext_conn_id: match conn_method {
ConnectionMethod::Integrated => None,
ConnectionMethod::External(id) => Some(*id)
},
min_confirmations: MIN_CONFIRMATIONS_DEFAULT,
};
Settings::write_to_file(&config, config_path);
config
}
@@ -62,8 +78,7 @@ impl WalletConfig {
/// Get wallets base directory path for provided [`ChainTypes`].
pub fn get_base_path(chain_type: ChainTypes) -> PathBuf {
let chain_name = chain_type.shortname();
let sub_dir = Some(chain_name.as_str());
let sub_dir = Some(chain_type.shortname());
let mut wallets_path = Settings::get_base_path(sub_dir);
wallets_path.push(BASE_DIR_NAME);
// Create wallets base directory if it doesn't exist.
@@ -98,10 +113,4 @@ impl WalletConfig {
let config_path = Self::get_config_file_path(self.chain_type, self.id);
Settings::write_to_file(self, config_path);
}
/// Set external node connection URL.
pub fn save_external_node_url(&mut self, url: Option<String>) {
self.external_node_url = url;
self.save();
}
}
+62 -61
View File
@@ -12,66 +12,73 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::{Arc, RwLock};
use lazy_static::lazy_static;
use grin_core::global::ChainTypes;
use serde_derive::{Deserialize, Serialize};
use crate::config::AppConfig;
use crate::Settings;
use crate::wallet::ExternalConnection;
lazy_static! {
/// Static connections state to be accessible globally.
static ref CONNECTIONS_STATE: Arc<RwLock<ConnectionsConfig>> = Arc::new(
RwLock::new(
Settings::init_config(Settings::get_config_path(CONFIG_FILE_NAME, None))
)
);
}
/// Wallet connections configuration.
#[derive(Serialize, Deserialize, Clone)]
pub struct ConnectionsConfig {
/// Network type for connections.
chain_type: ChainTypes,
/// URLs of external connections for wallets.
external: Vec<ExternalConnection>
}
impl Default for ConnectionsConfig {
fn default() -> Self {
Self {
external: vec![
ExternalConnection::default()
],
impl ConnectionsConfig {
/// Wallet connections configuration file name.
pub const FILE_NAME: &'static str = "connections.toml";
/// Initialize configuration for provided [`ChainTypes`].
pub fn for_chain_type(chain_type: &ChainTypes) -> Self {
let path = Settings::get_config_path(Self::FILE_NAME, Some(chain_type.shortname()));
let parsed = Settings::read_from_file::<ConnectionsConfig>(path.clone());
if !path.exists() || parsed.is_err() {
let default_config = ConnectionsConfig {
chain_type: *chain_type,
external: if chain_type == &ChainTypes::Mainnet {
vec![
ExternalConnection::default_main()
]
} else {
vec![]
},
};
Settings::write_to_file(&default_config, path);
default_config
} else {
parsed.unwrap()
}
}
}
/// Wallet configuration file name.
const CONFIG_FILE_NAME: &'static str = "connections.toml";
impl ConnectionsConfig {
/// Save connections config to file.
/// Save connections configuration to the file.
pub fn save(&self) {
Settings::write_to_file(self, Settings::get_config_path(CONFIG_FILE_NAME, None));
let chain_type = AppConfig::chain_type();
let sub_dir = Some(chain_type.shortname());
Settings::write_to_file(self, Settings::get_config_path(Self::FILE_NAME, sub_dir));
}
/// Get external connections for the wallet.
pub fn external_connections() -> Vec<ExternalConnection> {
let r_config = CONNECTIONS_STATE.read().unwrap();
/// Get [`ExternalConnection`] list.
pub fn ext_conn_list() -> Vec<ExternalConnection> {
let r_config = Settings::conn_config_to_read();
r_config.external.clone()
}
/// Save external connection for the wallet in app config.
pub fn add_external_connection(conn: ExternalConnection) {
/// Save [`ExternalConnection`] in configuration.
pub fn add_ext_conn(conn: ExternalConnection) {
// Do not update default connection.
if conn.url == ExternalConnection::DEFAULT_EXTERNAL_NODE_URL {
if conn.url == ExternalConnection::DEFAULT_MAIN_URL {
return;
}
let mut w_config = CONNECTIONS_STATE.write().unwrap();
let mut w_config = Settings::conn_config_to_update();
let mut exists = false;
for mut c in w_config.external.iter_mut() {
// Update connection if URL exists.
if c.url == conn.url {
// Update connection if config exists.
if c.id == conn.id {
c.url = conn.url.clone();
c.secret = conn.secret.clone();
exists = true;
break;
@@ -84,39 +91,33 @@ impl ConnectionsConfig {
w_config.save();
}
/// Save external connection for the wallet in app config.
pub fn update_external_connection(conn: ExternalConnection, updated: ExternalConnection) {
// Do not update default connection.
if conn.url == ExternalConnection::DEFAULT_EXTERNAL_NODE_URL {
return;
}
let mut w_config = CONNECTIONS_STATE.write().unwrap();
for mut c in w_config.external.iter_mut() {
// Update connection if URL exists.
if c.url == conn.url {
c.url = updated.url.clone();
c.secret = updated.secret.clone();
break;
}
}
w_config.save();
}
/// Get external node connection secret from provided URL.
pub fn get_external_connection_secret(url: String) -> Option<String> {
let r_config = CONNECTIONS_STATE.read().unwrap();
/// Get [`ExternalConnection`] by provided identifier.
pub fn ext_conn(id: i64) -> Option<ExternalConnection> {
let r_config = Settings::conn_config_to_read();
for c in &r_config.external {
if c.url == url {
return c.secret.clone();
if c.id == id {
return Some(c.clone());
}
}
None
}
/// Remove external node connection.
pub fn remove_external_connection(conn: &ExternalConnection) {
let mut w_config = CONNECTIONS_STATE.write().unwrap();
let index = w_config.external.iter().position(|c| c.url == conn.url);
/// Set [`ExternalConnection`] availability flag.
pub fn update_ext_conn_availability(id: i64, available: bool) {
let mut w_config = Settings::conn_config_to_update();
for mut c in w_config.external.iter_mut() {
if c.id == id {
c.available = Some(available);
w_config.save();
break;
}
}
}
/// Remove external node connection by provided identifier.
pub fn remove_ext_conn(id: i64) {
let mut w_config = Settings::conn_config_to_update();
let index = w_config.external.iter().position(|c| c.id == id);
if let Some(i) = index {
w_config.external.remove(i);
w_config.save();
+67 -10
View File
@@ -12,28 +12,85 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Duration;
use serde_derive::{Deserialize, Serialize};
/// External node connection for the wallet.
use crate::AppConfig;
use crate::wallet::ConnectionsConfig;
/// External connection for the wallet.
#[derive(Serialize, Deserialize, Clone)]
pub struct ExternalConnection {
/// Connection identifier.
pub id: i64,
/// Node URL.
pub url: String,
/// Optional API secret key.
pub secret: Option<String>
pub secret: Option<String>,
/// Flag to check if server is available.
#[serde(skip_serializing)]
pub available: Option<bool>
}
impl ExternalConnection {
/// Default external node URL.
pub const DEFAULT_EXTERNAL_NODE_URL: &'static str = "https://grinnnode.live:3413";
/// Default external node URL for main network.
pub const DEFAULT_MAIN_URL: &'static str = "https://grinnode.live:3413";
pub fn new(url: String, secret: Option<String>) -> Self {
Self { url, secret }
/// External connections availability check delay.
const AVAILABILITY_CHECK_DELAY: Duration = Duration::from_millis(10 * 1000);
/// Create default external connection.
pub fn default_main() -> Self {
Self { id: 1, url: Self::DEFAULT_MAIN_URL.to_string(), secret: None, available: None }
}
}
impl Default for ExternalConnection {
fn default() -> Self {
Self { url: Self::DEFAULT_EXTERNAL_NODE_URL.to_string(), secret: None }
/// Create new external connection.
pub fn new(url: String, secret: Option<String>) -> Self {
let id = chrono::Utc::now().timestamp();
Self { id, url, secret, available: None }
}
/// Check connection availability.
fn check_conn_availability(&self) {
// Check every connection at separate thread.
let conn = self.clone();
std::thread::spawn(move || {
let url = url::Url::parse(conn.url.as_str()).unwrap();
let addr = url.socket_addrs(|| None).unwrap();
match std::net::TcpStream::connect_timeout(&addr[0], Self::AVAILABILITY_CHECK_DELAY) {
Ok(_) => {
ConnectionsConfig::update_ext_conn_availability(conn.id, true);
}
Err(_) => {
ConnectionsConfig::update_ext_conn_availability(conn.id, false);
}
}
});
}
/// Start external connections availability check at another thread.
pub fn start_ext_conn_availability_check() {
std::thread::spawn(move || {
let chain_type = AppConfig::chain_type();
loop {
// Stop checking if connections are not showing or network type was changed.
if !AppConfig::show_connections_network_panel()
|| chain_type != AppConfig::chain_type() {
break;
}
// Check external connections URLs availability.
let conn_list = ConnectionsConfig::ext_conn_list();
for conn in conn_list {
// Check every connection at separate thread.
conn.check_conn_availability();
}
// Pause checking for delay value.
std::thread::sleep(Self::AVAILABILITY_CHECK_DELAY);
}
});
}
}
+10 -1
View File
@@ -76,4 +76,13 @@ pub type WalletInstance = Arc<
>,
>,
>,
>;
>;
/// Wallet node connection method type.
#[derive(PartialEq)]
pub enum ConnectionMethod {
/// Integrated node.
Integrated,
/// External node, contains connection identifier.
External(i64)
}
+106 -480
View File
@@ -12,30 +12,25 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{cmp, thread};
use std::thread;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc, RwLock};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::time::Duration;
use grin_core::global;
use grin_core::global::ChainTypes;
use grin_keychain::{ExtKeychain, Identifier, Keychain};
use grin_keychain::{ExtKeychain, Keychain};
use grin_util::types::ZeroingString;
use grin_wallet_api::{Foreign, ForeignCheckMiddlewareFn, Owner};
use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl, HTTPNodeClient};
use grin_wallet_libwallet::{Error, NodeClient, NodeVersionInfo, OutputStatus, scan, Slate, slate_versions, SlatepackArmor, Slatepacker, SlatepackerArgs, TxLogEntry, wallet_lock, WalletBackend, WalletInfo, WalletInst, WalletLCProvider};
use log::debug;
use grin_wallet_libwallet::{Error, NodeClient, StatusMessage, WalletBackend, WalletInfo, WalletInst, WalletLCProvider};
use grin_wallet_libwallet::api_impl::owner::retrieve_summary_info;
use parking_lot::Mutex;
use uuid::Uuid;
use crate::AppConfig;
use crate::node::NodeConfig;
use crate::wallet::{ConnectionsConfig, WalletConfig};
use crate::wallet::selection::lock_tx_context;
use crate::wallet::tx::{add_inputs_to_slate, new_tx_slate};
use crate::wallet::types::WalletInstance;
use crate::wallet::updater::{cancel_tx, refresh_output_state, retrieve_txs};
use crate::wallet::{ConnectionsConfig, ExternalConnection, WalletConfig};
use crate::wallet::types::{ConnectionMethod, WalletInstance};
/// [`Wallet`] list wrapper.
pub struct Wallets {
@@ -55,12 +50,6 @@ impl Default for Wallets {
}
impl Wallets {
/// Delay in seconds to update outputs after wallet opening.
pub const OUTPUTS_UPDATE_DELAY: Duration = Duration::from_millis(30 * 1000);
/// Delay in seconds to update wallet info.
pub const INFO_UPDATE_DELAY: Duration = Duration::from_millis(10 * 1000);
/// Initialize wallets from base directory for provided [`ChainType`].
fn init(chain_type: ChainTypes) -> Vec<Wallet> {
let mut wallets = Vec::new();
@@ -109,87 +98,15 @@ impl Wallets {
false
}
/// Open selected wallet.
pub fn open_selected(&mut self, password: String) -> Result<(), Error> {
/// Open and load selected wallet.
pub fn launch_selected(&mut self, password: String) -> Result<(), Error> {
for w in self.list.iter_mut() {
if Some(w.config.id) == self.selected_id {
return w.open(password);
return w.open(password.clone());
}
}
Err(Error::GenericError("Wallet is not selected".to_string()))
}
/// Load the wallet by scanning available outputs at separate thread.
pub fn load(w: &mut Wallet) {
if !w.is_open() {
return;
}
let mut wallet = w.clone();
thread::spawn(move || {
// Get pmmr range output indexes.
match wallet.pmmr_range() {
Ok((mut lowest_index, highest_index)) => {
println!("pmmr_range: {} {}", lowest_index, highest_index);
let mut from_index = lowest_index;
loop {
// Stop loop if wallet is not open.
if !wallet.is_open() {
break;
}
// Scan outputs for last retrieved index.
println!("scan_outputs from {} to {}", from_index, highest_index);
match wallet.scan_outputs(from_index, highest_index) {
Ok(last_index) => {
println!("retrieved index: {}", last_index);
if lowest_index == 0 {
lowest_index = last_index;
}
// Finish scanning or start new scan from last retrieved index.
if last_index == highest_index {
println!("scan finished");
wallet.loading_progress = 100;
wallet.is_loaded.store(true, Ordering::Relaxed);
} else {
println!("continue scan");
from_index = last_index;
}
// Update loading progress.
let range = highest_index - lowest_index;
let progress = last_index - lowest_index;
wallet.loading_progress = cmp::min(
(progress / range) as u8 * 100,
99
);
println!("progress: {}", wallet.loading_progress);
}
Err(e) => {
if !wallet.is_loaded() {
wallet.loading_error = Some(e);
break;
}
}
}
// Stop loop if wallet is not open.
if !wallet.is_open() {
break;
}
// Scan outputs at next cycle again.
println!("finished scanning, waiting");
thread::sleep(Self::OUTPUTS_UPDATE_DELAY);
}
}
Err(e) => {
wallet.loading_progress = 0;
wallet.loading_error = Some(e);
}
}
});
}
}
/// Contains wallet instance and config.
@@ -199,29 +116,33 @@ pub struct Wallet {
instance: WalletInstance,
/// Wallet configuration.
pub(crate) config: WalletConfig,
pub config: WalletConfig,
/// Flag to check if wallet is open.
is_open: Arc<AtomicBool>,
/// Flag to check if wallet is loaded and ready to use.
is_loaded: Arc<AtomicBool>,
/// Error on wallet loading.
pub loading_error: Option<Error>,
/// Loading progress in percents
pub loading_progress: u8,
pub loading_progress: Arc<AtomicU8>,
/// Wallet balance information.
info: Arc<RwLock<Option<WalletInfo>>>
}
impl Wallet {
/// Delay in seconds to update wallet info.
pub const INFO_UPDATE_DELAY: Duration = Duration::from_millis(20 * 1000);
/// Create wallet from provided instance and config.
fn new(instance: WalletInstance, config: WalletConfig) -> Self {
Self {
instance,
config,
is_loaded: Arc::new(AtomicBool::new(false)),
is_open: Arc::new(AtomicBool::new(false)),
is_open: Arc::from(AtomicBool::new(false)),
loading_error: None,
loading_progress: 0,
loading_progress: Arc::new(AtomicU8::new(0)),
info: Arc::new(RwLock::new(None)),
}
}
@@ -230,9 +151,9 @@ impl Wallet {
name: String,
password: String,
mnemonic: String,
external_node_url: Option<String>
conn_method: &ConnectionMethod
) -> Result<Wallet, Error> {
let config = WalletConfig::create(name, external_node_url);
let config = WalletConfig::create(name, conn_method);
let instance = Self::create_wallet_instance(config.clone())?;
let w = Wallet::new(instance, config);
{
@@ -278,8 +199,12 @@ impl Wallet {
}
// Setup node client.
let (node_api_url, node_secret) = if let Some(url) = &config.external_node_url {
(url.to_owned(), ConnectionsConfig::get_external_connection_secret(url.to_owned()))
let (node_api_url, node_secret) = if let Some(id) = config.ext_conn_id {
if let Some(conn) = ConnectionsConfig::ext_conn(id) {
(conn.url, conn.secret)
} else {
(ExternalConnection::DEFAULT_MAIN_URL.to_string(), None)
}
} else {
let api_url = format!("http://{}", NodeConfig::get_api_address());
let api_secret = NodeConfig::get_foreign_api_secret();
@@ -314,16 +239,85 @@ impl Wallet {
Ok(Arc::new(Mutex::new(wallet)))
}
/// Open wallet instance.
/// Open wallet and start info updating at separate thread.
pub fn open(&self, password: String) -> Result<(), Error> {
let mut wallet_lock = self.instance.lock();
let lc = wallet_lock.lc_provider()?;
lc.close_wallet(None)?;
lc.open_wallet(None, ZeroingString::from(password), false, false)?;
self.is_open.store(true, Ordering::Relaxed);
let mut wallet = self.clone();
match lc.open_wallet(None, ZeroingString::from(password), false, false) {
Ok(result) => {
self.is_open.store(true, Ordering::Relaxed);
let keychain_mask = result.clone();
// Launch loop at separate thread to update wallet info.
thread::spawn(move || loop {
// Stop updating if wallet was closed.
if !wallet.is_open() {
break;
}
let (tx, rx) = mpsc::channel::<StatusMessage>();
// Update progress at separate thread.
let wallet_scan = wallet.clone();
thread::spawn(move || {
while let Ok(m) = rx.recv() {
println!("m: {}", serde_json::to_string::<StatusMessage>(&m.clone()).unwrap());
match m {
StatusMessage::UpdatingOutputs(_) => {}
StatusMessage::UpdatingTransactions(_) => {}
StatusMessage::FullScanWarn(_) => {}
StatusMessage::Scanning(_, progress) => {
wallet_scan
.loading_progress
.store(progress, Ordering::Relaxed);
}
StatusMessage::ScanningComplete(_) => {
wallet_scan
.loading_progress
.store(100, Ordering::Relaxed);
}
StatusMessage::UpdateWarning(_) => {}
}
}
});
// Retrieve wallet info.
match retrieve_summary_info(
wallet.instance.clone(),
keychain_mask.as_ref(),
&Some(tx),
true,
wallet.config.min_confirmations
) {
Ok(info) => {
let mut w_info = wallet.info.write().unwrap();
*w_info = Some(info.1);
}
Err(e) => {
println!("Error!: {}", e);
wallet.loading_error = Some(e);
}
}
// Repeat after default delay or after 1 second if update was not complete.
let delay = if wallet.loading_progress() == 100 {
Self::INFO_UPDATE_DELAY
} else {
Duration::from_millis(1000)
};
thread::sleep(delay);
});
}
Err(e) => return Err(e)
}
Ok(())
}
pub fn loading_progress(&self) -> u8 {
self.loading_progress.load(Ordering::Relaxed)
}
/// Check if wallet is open.
pub fn is_open(&self) -> bool {
self.is_open.load(Ordering::Relaxed)
@@ -340,377 +334,9 @@ impl Wallet {
Ok(())
}
/// Check if wallet is loaded and ready to use.
pub fn is_loaded(&self) -> bool {
self.is_loaded.load(Ordering::Relaxed)
}
/// Scan wallet outputs to check/repair the wallet.
fn scan_outputs(
&self,
last_retrieved_index: u64,
highest_index: u64
) -> Result<u64, Error> {
let wallet = self.instance.clone();
let info = scan(
wallet.clone(),
None,
false,
last_retrieved_index,
highest_index,
&None,
)?;
let result = info.last_pmmr_index;
let parent_key_id = {
wallet_lock!(wallet.clone(), w);
w.parent_key_id().clone()
};
{
wallet_lock!(wallet, w);
let mut batch = w.batch(None)?;
batch.save_last_confirmed_height(&parent_key_id, info.height)?;
batch.commit()?;
};
Ok(result)
}
/// Get pmmr indices representing the outputs for the wallet.
fn pmmr_range(&self) -> Result<(u64, u64), Error> {
wallet_lock!(self.instance.clone(), w);
let pmmr_range = w.w2n_client().height_range_to_pmmr_indices(0, None)?;
Ok(pmmr_range)
}
/// Create transaction.
pub fn tx_create(
&self,
amount: u64,
minimum_confirmations: u64,
selection_strategy_is_use_all: bool,
) -> Result<(Vec<TxLogEntry>, String), Error> {
let parent_key_id = {
wallet_lock!(self.instance, w);
w.parent_key_id().clone()
};
let slate = {
wallet_lock!(self.instance, w);
let mut slate = new_tx_slate(&mut **w, amount, false, 2, false, None)?;
let height = w.w2n_client().get_chain_tip()?.0;
let context = add_inputs_to_slate(
&mut **w,
None,
&mut slate,
height,
minimum_confirmations,
500,
1,
selection_strategy_is_use_all,
&parent_key_id,
true,
false,
false,
)?;
{
let mut batch = w.batch(None)?;
batch.save_private_context(slate.id.as_bytes(), &context)?;
batch.commit()?;
}
lock_tx_context(&mut **w, None, &slate, height, &context, None)?;
slate.compact()?;
slate
};
let packer = Slatepacker::new(SlatepackerArgs {
sender: None, // sender
recipients: vec![],
dec_key: None,
});
let slatepack = packer.create_slatepack(&slate)?;
let api = Owner::new(self.instance.clone(), None);
let txs = api.retrieve_txs(None, false, None, Some(slate.id), None)?;
let result = (
txs.1,
SlatepackArmor::encode(&slatepack)?,
);
Ok(result)
}
/// Callback to check slate compatibility at current node.
fn check_middleware(
name: ForeignCheckMiddlewareFn,
node_version_info: Option<NodeVersionInfo>,
slate: Option<&Slate>,
) -> Result<(), Error> {
match name {
ForeignCheckMiddlewareFn::BuildCoinbase => Ok(()),
_ => {
let mut bhv = 3;
if let Some(n) = node_version_info {
bhv = n.block_header_version;
}
if let Some(s) = slate {
if bhv > 4
&& s.version_info.block_header_version
< slate_versions::GRIN_BLOCK_HEADER_VERSION
{
Err(Error::Compatibility(
"Incoming Slate is not compatible with this wallet. \
Please upgrade the node or use a different one."
.into(),
))?;
}
}
Ok(())
}
}
}
/// Receive transaction.
pub fn tx_receive(
&self,
account: &str,
slate_armored: &str
) -> Result<(Vec<TxLogEntry>, String), Error> {
let foreign_api =
Foreign::new(self.instance.clone(), None, Some(Self::check_middleware), false);
let owner_api = Owner::new(self.instance.clone(), None);
let mut slate =
owner_api.slate_from_slatepack_message(None, slate_armored.to_owned(), vec![0])?;
let slatepack =
owner_api.decode_slatepack_message(None, slate_armored.to_owned(), vec![0])?;
let _ret_address = slatepack.sender;
slate = foreign_api.receive_tx(&slate, Some(&account), None)?;
let txs = owner_api.retrieve_txs(None, false, None, Some(slate.id), None)?;
let packer = Slatepacker::new(SlatepackerArgs {
sender: None, // sender
recipients: vec![],
dec_key: None,
});
let slatepack = packer.create_slatepack(&slate)?;
let result = (
txs.1,
SlatepackArmor::encode(&slatepack)?,
);
Ok(result)
}
/// Cancel transaction.
pub fn tx_cancel(&self, id: u32) -> Result<String, Error> {
wallet_lock!(self.instance, w);
let parent_key_id = w.parent_key_id();
cancel_tx(&mut **w, None, &parent_key_id, Some(id), None)?;
Ok("".to_owned())
}
/// Get transaction info.
pub fn get_tx(&self, tx_slate_id: &str) -> Result<(bool, Vec<TxLogEntry>), Error> {
let api = Owner::new(self.instance.clone(), None);
let uuid = Uuid::parse_str(tx_slate_id).unwrap();
let txs = api.retrieve_txs(None, true, None, Some(uuid), None)?;
Ok(txs)
}
/// Finalize transaction.
pub fn tx_finalize(&self, slate_armored: &str) -> Result<(bool, Vec<TxLogEntry>), Error> {
let owner_api = Owner::new(self.instance.clone(), None);
let mut slate =
owner_api.slate_from_slatepack_message(None, slate_armored.to_owned(), vec![0])?;
let slatepack =
owner_api.decode_slatepack_message(None, slate_armored.to_owned(), vec![0])?;
let _ret_address = slatepack.sender;
slate = owner_api.finalize_tx(None, &slate)?;
let txs = owner_api.retrieve_txs(None, false, None, Some(slate.id), None)?;
Ok(txs)
}
/// Post transaction to node for broadcasting.
pub fn tx_post(&self, tx_slate_id: &str) -> Result<(), Error> {
let api = Owner::new(self.instance.clone(), None);
let tx_uuid = Uuid::parse_str(tx_slate_id).unwrap();
let (_, txs) = api.retrieve_txs(None, true, None, Some(tx_uuid.clone()), None)?;
if txs[0].confirmed {
return Err(Error::GenericError(format!(
"Transaction with id {} is already confirmed. Not posting.",
tx_slate_id
)));
}
let stored_tx = api.get_stored_tx(None, None, Some(&tx_uuid))?;
match stored_tx {
Some(stored_tx) => {
api.post_tx(None, &stored_tx, true)?;
Ok(())
}
None => Err(Error::GenericError(format!(
"Transaction with id {} does not have transaction data. Not posting.",
tx_slate_id
))),
}
}
/// Get transactions and base wallet info.
pub fn get_txs_info(
&self,
minimum_confirmations: u64
) -> Result<(bool, Vec<TxLogEntry>, WalletInfo), Error> {
let refreshed = Self::update_state(self.instance.clone()).unwrap_or(false);
let wallet_info = {
wallet_lock!(self.instance, w);
let parent_key_id = w.parent_key_id();
Self::get_info(&mut **w, &parent_key_id, minimum_confirmations)?
};
let api = Owner::new(self.instance.clone(), None);
let txs = api.retrieve_txs(None, false, None, None, None)?;
Ok((refreshed, txs.1, wallet_info))
}
/// Update wallet instance state.
fn update_state<'a, L, C, K>(
wallet_inst: Arc<Mutex<Box<dyn WalletInst<'a, L, C, K>>>>,
) -> Result<bool, Error>
where
L: WalletLCProvider<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let parent_key_id = {
wallet_lock!(wallet_inst, w);
w.parent_key_id().clone()
};
let mut client = {
wallet_lock!(wallet_inst, w);
w.w2n_client().clone()
};
let tip = client.get_chain_tip()?;
// Step1: Update outputs and transactions purely based on UTXO state.
{
wallet_lock!(wallet_inst, w);
if !match refresh_output_state(&mut **w, None, tip.0, &parent_key_id, true) {
Ok(_) => true,
Err(_) => false,
} {
// We are unable to contact the node.
return Ok(false);
}
}
let mut txs = {
wallet_lock!(wallet_inst, w);
retrieve_txs(&mut **w, None, None, None, Some(&parent_key_id), true)?
};
for tx in txs.iter_mut() {
// Step 2: Cancel any transactions with an expired TTL.
if let Some(e) = tx.ttl_cutoff_height {
if tip.0 >= e {
wallet_lock!(wallet_inst, w);
let parent_key_id = w.parent_key_id();
cancel_tx(&mut **w, None, &parent_key_id, Some(tx.id), None)?;
continue;
}
}
// Step 3: Update outstanding transactions with no change outputs by kernel.
if tx.confirmed {
continue;
}
if tx.amount_debited != 0 && tx.amount_credited != 0 {
continue;
}
if let Some(e) = tx.kernel_excess {
let res = client.get_kernel(&e, tx.kernel_lookup_min_height, Some(tip.0));
let kernel = match res {
Ok(k) => k,
Err(_) => return Ok(false),
};
if let Some(k) = kernel {
debug!("Kernel Retrieved: {:?}", k);
wallet_lock!(wallet_inst, w);
let mut batch = w.batch(None)?;
tx.confirmed = true;
tx.update_confirmation_ts();
batch.save_tx_log_entry(tx.clone(), &parent_key_id)?;
batch.commit()?;
}
}
}
return Ok(true);
}
/// Get summary info about the wallet.
fn get_info<'a, T: ?Sized, C, K>(
wallet: &mut T,
parent_key_id: &Identifier,
minimum_confirmations: u64,
) -> Result<WalletInfo, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let current_height = wallet.last_confirmed_height()?;
let outputs = wallet
.iter()
.filter(|out| out.root_key_id == *parent_key_id);
let mut unspent_total = 0;
let mut immature_total = 0;
let mut awaiting_finalization_total = 0;
let mut unconfirmed_total = 0;
let mut locked_total = 0;
let mut reverted_total = 0;
for out in outputs {
match out.status {
OutputStatus::Unspent => {
if out.is_coinbase && out.lock_height > current_height {
immature_total += out.value;
} else if out.num_confirmations(current_height) < minimum_confirmations {
// Treat anything less than minimum confirmations as "unconfirmed".
unconfirmed_total += out.value;
} else {
unspent_total += out.value;
}
}
OutputStatus::Unconfirmed => {
// We ignore unconfirmed coinbase outputs completely.
if !out.is_coinbase {
if minimum_confirmations == 0 {
unconfirmed_total += out.value;
} else {
awaiting_finalization_total += out.value;
}
}
}
OutputStatus::Locked => {
locked_total += out.value;
}
OutputStatus::Reverted => reverted_total += out.value,
OutputStatus::Spent => {}
}
}
Ok(WalletInfo {
last_confirmed_height: current_height,
minimum_confirmations,
total: unspent_total + unconfirmed_total + immature_total,
amount_awaiting_finalization: awaiting_finalization_total,
amount_awaiting_confirmation: unconfirmed_total,
amount_immature: immature_total,
amount_locked: locked_total,
amount_currently_spendable: unspent_total,
amount_reverted: reverted_total,
})
/// Get wallet info.
pub fn get_info(&self) -> Option<WalletInfo> {
let r_info = self.info.read().unwrap();
r_info.clone()
}
}