diff --git a/applications/tari_base_node/src/config.rs b/applications/tari_base_node/src/config.rs index 21fd61dfe2..184ff83e9a 100644 --- a/applications/tari_base_node/src/config.rs +++ b/applications/tari_base_node/src/config.rs @@ -83,6 +83,8 @@ pub struct BaseNodeConfig { override_from: Option, /// Selected network pub network: Network, + /// Enable the base node GRPC server + pub grpc_enabled: bool, /// GRPC address of base node pub grpc_address: Option, /// A path to the file that stores the base node identity and secret key @@ -144,7 +146,8 @@ impl Default for BaseNodeConfig { Self { override_from: None, network: Network::default(), - grpc_address: Some("/ip4/127.0.0.1/tcp/18142".parse().unwrap()), + grpc_enabled: true, + grpc_address: None, identity_file: PathBuf::from("config/base_node_id.json"), use_libtor: false, tor_identity_file: PathBuf::from("config/base_node_tor_id.json"), diff --git a/applications/tari_base_node/src/main.rs b/applications/tari_base_node/src/main.rs index 9a63982e7e..a9b0e399e3 100644 --- a/applications/tari_base_node/src/main.rs +++ b/applications/tari_base_node/src/main.rs @@ -94,7 +94,10 @@ use log::*; use opentelemetry::{self, global, KeyValue}; use tari_app_utilities::{consts, identity_management::setup_node_identity, utilities::setup_runtime}; use tari_common::{ - configuration::{bootstrap::ApplicationType, Network}, + configuration::{ + bootstrap::{grpc_default_port, ApplicationType}, + Network, + }, exit_codes::{ExitCode, ExitError}, initialize_logging, load_configuration, @@ -145,7 +148,6 @@ fn main_inner() -> Result<(), ExitError> { include_str!("../log4rs_sample.yml"), )?; - #[cfg_attr(not(all(unix, feature = "libtor")), allow(unused_mut))] let mut config = ApplicationConfig::load_from(&cfg)?; if let Some(network) = &cli.network { config.base_node.network = Network::from_str(network)?; @@ -229,10 +231,14 @@ async fn run_node( // Build, node, build! let ctx = builder::configure_and_initialize_node(config.clone(), node_identity, shutdown.to_signal()).await?; - if let Some(address) = config.base_node.grpc_address.clone() { + if config.base_node.grpc_enabled { + let grpc_address = config.base_node.grpc_address.clone().unwrap_or_else(|| { + let port = grpc_default_port(ApplicationType::BaseNode, config.base_node.network); + format!("/ip4/127.0.0.1/tcp/{}", port).parse().unwrap() + }); // Go, GRPC, go go - let grpc = crate::grpc::base_node_grpc_server::BaseNodeGrpcServer::from_base_node_context(&ctx); - task::spawn(run_grpc(grpc, address, shutdown.to_signal())); + let grpc = grpc::base_node_grpc_server::BaseNodeGrpcServer::from_base_node_context(&ctx); + task::spawn(run_grpc(grpc, grpc_address, shutdown.to_signal())); } // Run, node, run! @@ -288,7 +294,7 @@ fn enable_tracing() { /// Runs the gRPC server async fn run_grpc( - grpc: crate::grpc::base_node_grpc_server::BaseNodeGrpcServer, + grpc: grpc::base_node_grpc_server::BaseNodeGrpcServer, grpc_address: Multiaddr, interrupt_signal: ShutdownSignal, ) -> Result<(), anyhow::Error> { diff --git a/applications/tari_console_wallet/src/init/mod.rs b/applications/tari_console_wallet/src/init/mod.rs index 97ce4105f4..f00b788e31 100644 --- a/applications/tari_console_wallet/src/init/mod.rs +++ b/applications/tari_console_wallet/src/init/mod.rs @@ -27,7 +27,10 @@ use rpassword::prompt_password_stdout; use rustyline::Editor; use tari_app_utilities::identity_management::setup_node_identity; use tari_common::{ - configuration::bootstrap::prompt, + configuration::{ + bootstrap::{grpc_default_port, prompt, ApplicationType}, + Network, + }, exit_codes::{ExitCode, ExitError}, }; use tari_comms::{ @@ -41,7 +44,7 @@ use tari_crypto::keys::PublicKey; use tari_key_manager::{cipher_seed::CipherSeed, mnemonic::MnemonicLanguage}; use tari_p2p::{peer_seeds::SeedPeer, TransportType}; use tari_shutdown::ShutdownSignal; -use tari_utilities::{ByteArray, SafePassword}; +use tari_utilities::{hex::Hex, ByteArray, SafePassword}; use tari_wallet::{ error::{WalletError, WalletStorageError}, output_manager_service::storage::database::OutputManagerDatabase, @@ -164,7 +167,7 @@ pub async fn get_base_node_peer_config( // If the user has not explicitly set a base node in the config, we try detect one if !non_interactive_mode && config.wallet.custom_base_node.is_none() { - if let Some(detected_node) = detect_local_base_node().await { + if let Some(detected_node) = detect_local_base_node(config.wallet.network).await { match selected_base_node { Some(ref base_node) if base_node.public_key == detected_node.public_key => { // Skip asking because it's already set @@ -407,15 +410,31 @@ pub async fn init_wallet( Ok(wallet) } -async fn detect_local_base_node() -> Option { +async fn detect_local_base_node(network: Network) -> Option { use tari_app_grpc::tari_rpc::{base_node_client::BaseNodeClient, Empty}; - const COMMON_BASE_NODE_GRPC_ADDRESS: &str = "http://127.0.0.1:18142"; + let addr = format!( + "http://127.0.0.1:{}", + grpc_default_port(ApplicationType::BaseNode, network) + ); + debug!(target: LOG_TARGET, "Checking for local base node at {}", addr); - let mut node_conn = BaseNodeClient::connect(COMMON_BASE_NODE_GRPC_ADDRESS).await.ok()?; + let mut node_conn = match BaseNodeClient::connect(addr).await.ok() { + Some(conn) => conn, + None => { + debug!(target: LOG_TARGET, "No local base node detected"); + return None; + }, + }; let resp = node_conn.identify(Empty {}).await.ok()?; let identity = resp.get_ref(); let public_key = CommsPublicKey::from_bytes(&identity.public_key).ok()?; let address = Multiaddr::from_str(&identity.public_address).ok()?; + debug!( + target: LOG_TARGET, + "Local base node found with pk={} and addr={}", + public_key.to_hex(), + address + ); Some(SeedPeer::new(public_key, vec![address])) } diff --git a/applications/tari_console_wallet/src/main.rs b/applications/tari_console_wallet/src/main.rs index e8f0b4060c..cbeebbcf4c 100644 --- a/applications/tari_console_wallet/src/main.rs +++ b/applications/tari_console_wallet/src/main.rs @@ -38,7 +38,7 @@ use opentelemetry::{self, global, KeyValue}; use recovery::prompt_private_key_from_seed_words; use tari_app_utilities::consts; use tari_common::{ - configuration::bootstrap::ApplicationType, + configuration::bootstrap::{grpc_default_port, ApplicationType}, exit_codes::{ExitCode, ExitError}, initialize_logging, load_configuration, @@ -99,9 +99,10 @@ fn main_inner() -> Result<(), ExitError> { include_str!("../log4rs_sample.yml"), )?; - #[cfg_attr(not(all(unix, feature = "libtor")), allow(unused_mut))] let mut config = ApplicationConfig::load_from(&cfg)?; + setup_grpc_config(&mut config); + let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() @@ -270,3 +271,16 @@ fn enable_tracing() { tracing::subscriber::set_global_default(subscriber) .expect("Tracing could not be set. Try running without `--tracing-enabled`"); } + +fn setup_grpc_config(config: &mut ApplicationConfig) { + if config.wallet.grpc_address.is_none() { + config.wallet.grpc_address = Some( + format!( + "/ip4/127.0.0.1/tcp/{}", + grpc_default_port(ApplicationType::ConsoleWallet, config.wallet.network) + ) + .parse() + .unwrap(), + ); + } +} diff --git a/applications/tari_console_wallet/src/wallet_modes.rs b/applications/tari_console_wallet/src/wallet_modes.rs index 9bf3e65b38..e92437138b 100644 --- a/applications/tari_console_wallet/src/wallet_modes.rs +++ b/applications/tari_console_wallet/src/wallet_modes.rs @@ -267,12 +267,10 @@ pub fn tui_mode( ) -> Result<(), ExitError> { let (events_broadcaster, _events_listener) = broadcast::channel(100); if config.grpc_enabled { - let grpc = WalletGrpcServer::new(wallet.clone()); - handle.spawn(run_grpc( - grpc, - config.grpc_address.clone(), - config.grpc_authentication.clone(), - )); + if let Some(address) = config.grpc_address.clone() { + let grpc = WalletGrpcServer::new(wallet.clone()); + handle.spawn(run_grpc(grpc, address, config.grpc_authentication.clone())); + } } let notifier = Notifier::new( @@ -369,11 +367,11 @@ pub fn recovery_mode( pub fn grpc_mode(handle: Handle, config: &WalletConfig, wallet: WalletSqlite) -> Result<(), ExitError> { info!(target: LOG_TARGET, "Starting grpc server"); - if config.grpc_enabled { + if let Some(address) = config.grpc_address.as_ref().filter(|_| config.grpc_enabled).cloned() { let grpc = WalletGrpcServer::new(wallet); let auth = config.grpc_authentication.clone(); handle - .block_on(run_grpc(grpc, config.grpc_address.clone(), auth)) + .block_on(run_grpc(grpc, address, auth)) .map_err(|e| ExitError::new(ExitCode::GrpcError, e))?; } else { println!("GRPC server is disabled"); diff --git a/base_layer/wallet/src/config.rs b/base_layer/wallet/src/config.rs index 6d0997fa6e..ca5a472efe 100644 --- a/base_layer/wallet/src/config.rs +++ b/base_layer/wallet/src/config.rs @@ -99,7 +99,7 @@ pub struct WalletConfig { /// If true, a GRPC server will bind to the configured address and listen for incoming GRPC requests. pub grpc_enabled: bool, /// GRPC bind address of the wallet - pub grpc_address: Multiaddr, + pub grpc_address: Option, /// GRPC authentication mode pub grpc_authentication: GrpcAuthentication, /// A custom base node peer that will be used to obtain metadata from @@ -144,7 +144,7 @@ impl Default for WalletConfig { command_send_wait_timeout: Duration::from_secs(300), notify_file: None, grpc_enabled: false, - grpc_address: "/ip4/127.0.0.1/tcp/18143".parse().unwrap(), + grpc_address: None, grpc_authentication: GrpcAuthentication::default(), custom_base_node: None, base_node_service_peers: StringList::default(), diff --git a/common/config/presets/c_base_node.toml b/common/config/presets/c_base_node.toml index fc98a0d3c3..26a5ae09c1 100644 --- a/common/config/presets/c_base_node.toml +++ b/common/config/presets/c_base_node.toml @@ -17,15 +17,22 @@ identity_file = "config/base_node_id_dibbler.json" # A path to the file that stores your node identity and secret key (default = "config/base_node_id.json") identity_file = "config/base_node_id_igor.json" +# The socket to expose for the gRPC base node server (default = "/ip4/127.0.0.1/tcp/18152") +#grpc_address = "/ip4/127.0.0.1/tcp/18152" + [esmeralda.base_node] # A path to the file that stores your node identity and secret key (default = "config/base_node_id.json") identity_file = "config/base_node_id_esmeralda.json" +# The socket to expose for the gRPC base node server (default = "/ip4/127.0.0.1/tcp/18142") +#grpc_address = "/ip4/127.0.0.1/tcp/18142" + [base_node] # Selected network (Note: Not implemented properly, please specify on the command line) (default = "emseralda") #network = "emseralda" -# The socket to expose for the gRPC base node server (default = "/ip4/127.0.0.1/tcp/18142") -#grpc_address = "/ip4/127.0.0.1/tcp/18142" + +# Set to false to disable the base node GRPC server (default = true) +#grpc_enabled = true # A path to the file that stores your node identity and secret key (default = "config/base_node_id.json") #identity_file = "config/base_node_id.json" diff --git a/common/src/configuration/bootstrap.rs b/common/src/configuration/bootstrap.rs index 26dcf14edc..75d65cc0f0 100644 --- a/common/src/configuration/bootstrap.rs +++ b/common/src/configuration/bootstrap.rs @@ -10,6 +10,7 @@ use std::{ }; use super::error::ConfigError; +use crate::configuration::Network; pub fn prompt(question: &str) -> bool { println!("{}", question); @@ -97,6 +98,29 @@ impl Display for ApplicationType { } } +/// Gets the default grpc port for the given application and network +pub fn grpc_default_port(app_type: ApplicationType, network: Network) -> u16 { + match app_type { + ApplicationType::BaseNode => match network { + Network::MainNet => 18102u16, + Network::Weatherwax => 18112, + Network::Dibbler => 18122, + Network::Esmeralda => 18142, + Network::Igor => 18152, + _ => unreachable!("Network {} not supported", network), + }, + ApplicationType::ConsoleWallet => match network { + Network::MainNet => 18103u16, + Network::Weatherwax => 18113, + Network::Dibbler => 18123, + Network::Esmeralda => 18143, + Network::Igor => 18153, + _ => unreachable!("Network {} not supported", network), + }, + _ => unreachable!("Application {} not supported", app_type), + } +} + #[cfg(test)] mod test { use super::*;