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

feat: different default grpc ports for different networks #4755

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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_base_node/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl Default for BaseNodeConfig {
Self {
override_from: None,
network: Network::default(),
grpc_address: Some("/ip4/127.0.0.1/tcp/18142".parse().unwrap()),
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"),
Expand Down
19 changes: 12 additions & 7 deletions applications/tari_base_node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -229,11 +232,13 @@ 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() {
// 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_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 = grpc::base_node_grpc_server::BaseNodeGrpcServer::from_base_node_context(&ctx);
task::spawn(run_grpc(grpc, grpc_address, shutdown.to_signal()));

// Run, node, run!
let context = CommandContext::new(&ctx, shutdown);
Expand Down Expand Up @@ -288,7 +293,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> {
Expand Down
31 changes: 25 additions & 6 deletions applications/tari_console_wallet/src/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -407,15 +410,31 @@ pub async fn init_wallet(
Ok(wallet)
}

async fn detect_local_base_node() -> Option<SeedPeer> {
async fn detect_local_base_node(network: Network) -> Option<SeedPeer> {
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]))
}

Expand Down
18 changes: 16 additions & 2 deletions applications/tari_console_wallet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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(),
);
}
}
14 changes: 6 additions & 8 deletions applications/tari_console_wallet/src/wallet_modes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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");
Expand Down
4 changes: 2 additions & 2 deletions base_layer/wallet/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Multiaddr>,
/// GRPC authentication mode
pub grpc_authentication: GrpcAuthentication,
/// A custom base node peer that will be used to obtain metadata from
Expand Down Expand Up @@ -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(),
Expand Down
8 changes: 6 additions & 2 deletions common/config/presets/c_base_node.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,19 @@ 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"

# 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"
Expand Down
24 changes: 24 additions & 0 deletions common/src/configuration/bootstrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{
};

use super::error::ConfigError;
use crate::configuration::Network;

pub fn prompt(question: &str) -> bool {
println!("{}", question);
Expand Down Expand Up @@ -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::*;
Expand Down