Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[console wallet] show base node chain tip and sync status #2420

Merged
merged 1 commit into from
Nov 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion applications/tari_app_utilities/src/utilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ pub fn setup_runtime(config: &GlobalConfig) -> Result<Runtime, String> {
/// ## Returns
/// A list of peers, peers which do not have a valid public key are excluded
pub fn parse_peer_seeds(seeds: &[String]) -> Vec<Peer> {
info!("Adding {} peers to the peer database", seeds.len());
info!("Parsing {} peers", seeds.len());
let mut result = Vec::with_capacity(seeds.len());
for s in seeds {
let parts: Vec<&str> = s.split("::").map(|s| s.trim()).collect();
Expand Down
2 changes: 1 addition & 1 deletion applications/tari_console_wallet/src/dummy_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ lazy_static! {
static ref BN_SYNC_CALLS: AtomicU64 = AtomicU64::new(0);
}

pub fn get_dummy_base_node_status() -> Option<u64> {
pub fn _get_dummy_base_node_status() -> Option<u64> {
let seconds = BN_SYNC_CALLS.fetch_add(1, Ordering::SeqCst) / 4;

if seconds / 6 % 2 == 0 {
Expand Down
83 changes: 61 additions & 22 deletions applications/tari_console_wallet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,24 @@
#![deny(unknown_lints)]
#![recursion_limit = "512"]
use log::*;
use rand::{rngs::OsRng, RngCore};
use rand::{rngs::OsRng, seq::SliceRandom};
use std::{fs, sync::Arc};
use structopt::StructOpt;
use tari_app_utilities::{
identity_management::setup_node_identity,
utilities::{parse_peer_seeds, setup_wallet_transport_type, ExitCodes},
};
use tari_common::{configuration::bootstrap::ApplicationType, ConfigBootstrap, GlobalConfig, Network};
use tari_comms::{peer_manager::PeerFeatures, NodeIdentity};
use tari_comms::{
peer_manager::{Peer, PeerFeatures},
NodeIdentity,
};
use tari_comms_dht::{DbConnectionUrl, DhtConfig};
use tari_core::{consensus::Network as NetworkType, transactions::types::CryptoFactories};
use tari_p2p::initialization::CommsConfig;
use tari_shutdown::{Shutdown, ShutdownSignal};
use tari_wallet::{
base_node_service::config::BaseNodeServiceConfig,
error::WalletError,
storage::sqlite_utilities::initialize_sqlite_database_backends,
transaction_service::config::TransactionServiceConfig,
Expand Down Expand Up @@ -109,15 +113,22 @@ fn main_inner() -> Result<(), ExitCodes> {
return Ok(());
}

let wallet = runtime.block_on(setup_wallet(&config, node_identity, shutdown.to_signal()))?;
let base_node = get_base_node_peer(&config)?;

let wallet = runtime.block_on(setup_wallet(
&config,
node_identity,
base_node.clone(),
shutdown.to_signal(),
))?;

debug!(target: LOG_TARGET, "Starting app");

let node_identity = wallet.comms.node_identity().as_ref().clone();

let handle = runtime.handle().clone();
let result = match wallet_mode(bootstrap) {
WalletMode::Tui => tui_mode(handle, config, node_identity, wallet.clone()),
WalletMode::Tui => tui_mode(handle, config, node_identity, wallet.clone(), base_node),
WalletMode::Grpc => grpc_mode(handle, wallet.clone(), config),
WalletMode::Script(path) => script_mode(handle, path, wallet.clone(), config),
WalletMode::Command(command) => command_mode(handle, command, wallet.clone(), config),
Expand All @@ -137,6 +148,32 @@ fn main_inner() -> Result<(), ExitCodes> {
result
}

fn get_base_node_peer(config: &GlobalConfig) -> Result<Peer, ExitCodes> {
// pick a random peer from peer seeds config
// todo: strategy for picking peer seed: random or lowest latency
let peer_seeds = parse_peer_seeds(&config.peer_seeds);
let peer_seed = peer_seeds.choose(&mut OsRng);

// get the configured base node service peer
let base_node_peers = parse_peer_seeds(&[config.wallet_base_node_service_peer.clone()]);
let base_node = base_node_peers.first();

let peer = match (peer_seed, base_node) {
// base node service peer is defined, so use that
(_, Some(node)) => node.clone(),
// only peer seeds were provided in config
(Some(seed), None) => seed.clone(),
// invalid configuration
_ => {
return Err(ExitCodes::ConfigError(
"No peer seeds or base node peer defined in config!".to_string(),
))
},
};

Ok(peer)
}

fn wallet_mode(bootstrap: ConfigBootstrap) -> WalletMode {
match (bootstrap.daemon_mode, bootstrap.input_file, bootstrap.command) {
// TUI mode
Expand All @@ -156,6 +193,7 @@ fn wallet_mode(bootstrap: ConfigBootstrap) -> WalletMode {
async fn setup_wallet(
config: &GlobalConfig,
node_identity: Arc<NodeIdentity>,
base_node: Peer,
shutdown_signal: ShutdownSignal,
) -> Result<WalletSqlite, ExitCodes>
{
Expand Down Expand Up @@ -205,6 +243,11 @@ async fn setup_wallet(
Network::LocalNet => NetworkType::LocalNet,
};

let base_node_service_config = BaseNodeServiceConfig::new(
config.wallet_base_node_service_refresh_interval,
config.wallet_base_node_service_request_max_age,
);

let factories = CryptoFactories::default();
let mut wallet_config = WalletConfig::new(
comms_config.clone(),
Expand All @@ -214,6 +257,7 @@ async fn setup_wallet(
..Default::default()
}),
network,
Some(base_node_service_config),
);
wallet_config.buffer_size = std::cmp::max(BASE_NODE_BUFFER_MIN_SIZE, config.buffer_size_base_node);

Expand All @@ -234,24 +278,19 @@ async fn setup_wallet(
}
})?;

debug!(target: LOG_TARGET, "Setting peer seeds");

// TODO update this to come from an explicit config field. This will be replaced by gRPC interface.
if !config.peer_seeds.is_empty() {
let seed_peers = parse_peer_seeds(&config.peer_seeds);
let random_seed_peer = OsRng.next_u32() as usize % seed_peers.len();
wallet
.set_base_node_peer(
seed_peers[random_seed_peer].public_key.clone(),
seed_peers[random_seed_peer]
.addresses
.first()
.expect("The seed peers should have an address")
.to_string(),
)
.await
.map_err(|e| ExitCodes::WalletError(format!("Error setting wallet base node peer. {}", e)))?;
}
// TODO gRPC interfaces for setting base node
debug!(target: LOG_TARGET, "Setting base node peer");
delta1 marked this conversation as resolved.
Show resolved Hide resolved
wallet
.set_base_node_peer(
base_node.public_key.clone(),
base_node
.addresses
.first()
.expect("The base node peer should have an address!")
.to_string(),
)
.await
.map_err(|e| ExitCodes::WalletError(format!("Error setting wallet base node peer. {}", e)))?;

// Restart transaction protocols
if let Err(e) = wallet.transaction_service.restart_transaction_protocols().await {
Expand Down
62 changes: 25 additions & 37 deletions applications/tari_console_wallet/src/ui/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,25 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::{
dummy_data::get_dummy_base_node_status,
ui::{
components::{
network_tab::NetworkTab,
send_receive_tab::SendReceiveTab,
tabs_container::TabsContainer,
transactions_tab::TransactionsTab,
Component,
},
state::AppState,
MAX_WIDTH,
use crate::ui::{
components::{
base_node::BaseNode,
network_tab::NetworkTab,
send_receive_tab::SendReceiveTab,
tabs_container::TabsContainer,
transactions_tab::TransactionsTab,
Component,
},
state::AppState,
MAX_WIDTH,
};
use tari_common::Network;
use tari_comms::NodeIdentity;
use tari_comms::{peer_manager::Peer, NodeIdentity};
use tari_wallet::WalletSqlite;
use tokio::runtime::Handle;
use tui::{
backend::Backend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::{Block, Borders, Paragraph},
Frame,
};

Expand All @@ -56,26 +51,37 @@ pub struct App<B: Backend> {
pub app_state: AppState,
// Ui working state
pub tabs: TabsContainer<B>,
pub base_node_status: BaseNode,
}

impl<B: Backend> App<B> {
pub fn new(title: String, node_identity: &NodeIdentity, wallet: WalletSqlite, network: Network) -> Self {
pub fn new(
title: String,
node_identity: &NodeIdentity,
wallet: WalletSqlite,
network: Network,
base_node: Peer,
) -> Self
{
// TODO: It's probably better to read the node_identity from the wallet, but that requires
// taking a read lock and making this method async, which adds some read/write cycles,
// so it's easier to just ask for it right now
let app_state = AppState::new(&node_identity, network, wallet);
let app_state = AppState::new(&node_identity, network, wallet, base_node);

let tabs = TabsContainer::<B>::new(title.clone())
.add("Transactions".into(), Box::new(TransactionsTab::new()))
.add("Send/Receive".into(), Box::new(SendReceiveTab::new()))
.add("Network".into(), Box::new(NetworkTab::new()));

let base_node_status = BaseNode::new();

Self {
title,

should_quit: false,
app_state,
tabs,
base_node_status,
}
}

Expand Down Expand Up @@ -145,25 +151,7 @@ impl<B: Backend> App<B> {

self.tabs.draw_titles(f, title_halves[0]);

let chain_meta_data = match get_dummy_base_node_status() {
None => Spans::from(vec![
Span::styled("Base Node Chain Tip:", Style::default().fg(Color::Magenta)),
Span::raw(" "),
Span::styled(" *Not Connected*", Style::default().fg(Color::Red)),
]),
Some(tip) => Spans::from(vec![
Span::styled("Base Node Chain Tip:", Style::default().fg(Color::Magenta)),
Span::raw(" "),
Span::styled(format!("{}", tip), Style::default().fg(Color::Green)),
]),
};
let chain_meta_data_paragraph =
Paragraph::new(chain_meta_data).block(Block::default().borders(Borders::ALL).title(Span::styled(
"Base Node Status:",
Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
)));
f.render_widget(chain_meta_data_paragraph, title_halves[1]);

self.base_node_status.draw(f, title_halves[1], &self.app_state);
self.tabs.draw_content(f, title_chunks[1], &mut self.app_state);
}
}
81 changes: 81 additions & 0 deletions applications/tari_console_wallet/src/ui/components/base_node.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use crate::ui::{components::Component, state::AppState};
use tui::{
backend::Backend,
layout::Rect,
style::{Color, Modifier, Style},
text::{Span, Spans},
widgets::{Block, Borders, Paragraph},
Frame,
};

pub struct BaseNode {}

impl BaseNode {
pub fn new() -> Self {
Self {}
}
}

impl<B: Backend> Component<B> for BaseNode {
fn draw(&mut self, f: &mut Frame<B>, area: Rect, app_state: &AppState)
where B: Backend {
let base_node_state = app_state.get_base_node_state();

let chain_info = match base_node_state.chain_metadata.clone() {
None => Spans::from(vec![
Span::styled("Chain Tip:", Style::default().fg(Color::Magenta)),
Span::raw(" "),
Span::styled("Connecting...", Style::default().fg(Color::Reset)),
]),
Some(metadata) => {
let tip = metadata.height_of_longest_chain();

let synced = base_node_state.is_synced.unwrap_or_default();
let (tip_color, sync_text) = if synced {
(Color::Green, "Synced ✅")
} else {
(Color::Yellow, "Syncing ⏱")
};

let tip_info = vec![
Span::styled("Chain Tip:", Style::default().fg(Color::Magenta)),
Span::raw(" "),
Span::styled(format!("#{}", tip), Style::default().fg(tip_color)),
Span::raw(" "),
Span::styled(sync_text.to_string(), Style::default().fg(Color::DarkGray)),
];

Spans::from(tip_info)
},
};

let chain_metadata_paragraph =
Paragraph::new(chain_info).block(Block::default().borders(Borders::ALL).title(Span::styled(
"Base Node Status:",
Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
)));
f.render_widget(chain_metadata_paragraph, area);
}
}
23 changes: 23 additions & 0 deletions applications/tari_console_wallet/src/ui/components/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
// Copyright 2020. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

pub mod balance;
pub mod base_node;
mod component;
pub mod network_tab;
pub mod send_receive_tab;
Expand Down
Loading