building socks5

This commit is contained in:
Jędrzej Stuczyński
2023-05-25 16:23:35 +01:00
parent 7f5e2f2909
commit 2ab4a445b7
14 changed files with 208 additions and 216 deletions
+1 -1
View File
@@ -107,7 +107,7 @@ impl SocketClient {
}
fn key_store(&self) -> OnDiskKeys {
OnDiskKeys::new(self.config.paths.key_pathfinder.clone())
OnDiskKeys::new(self.config.paths.keys_pathfinder.clone())
}
// TODO: see if this could also be shared with socks5 client / nym-sdk maybe
+2 -2
View File
@@ -154,7 +154,7 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let key_store = OnDiskKeys::new(config.paths.key_pathfinder.clone());
let key_store = OnDiskKeys::new(config.paths.keys_pathfinder.clone());
let gateway = nym_client_core::init::setup_gateway_from_config::<_>(
&key_store,
register_gateway,
@@ -177,7 +177,7 @@ pub(crate) async fn execute(args: &Init) -> Result<(), ClientError> {
);
let address = nym_client_core::init::get_client_address_from_stored_ondisk_keys(
&config.paths.key_pathfinder,
&config.paths.keys_pathfinder,
&config.base.client.gateway_endpoint,
)?;
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::client::config::Config;
+23 -30
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
use crate::commands::try_upgrade_v1_1_13_config;
use crate::config::{default_config_filepath, Config};
use crate::{
commands::{override_config, OverrideConfig},
error::Socks5ClientError,
@@ -9,9 +10,7 @@ use crate::{
use clap::Args;
use nym_bin_common::output_format::OutputFormat;
use nym_client_core::client::key_manager::persistence::OnDiskKeys;
use nym_config::NymConfig;
use nym_crypto::asymmetric::identity;
use nym_socks5_client_core::config::Config;
use nym_sphinx::addressing::clients::Recipient;
use serde::Serialize;
use std::fmt::Display;
@@ -100,15 +99,15 @@ impl From<Init> for OverrideConfig {
pub struct InitResults {
#[serde(flatten)]
client_core: nym_client_core::init::InitResults,
socks5_listening_port: String,
socks5_listening_port: u16,
client_address: String,
}
impl InitResults {
fn new(config: &Config, address: &Recipient) -> Self {
Self {
client_core: nym_client_core::init::InitResults::new(config.get_base(), address),
socks5_listening_port: config.get_socks5().get_listening_port().to_string(),
client_core: nym_client_core::init::InitResults::new(&config.core.base, address),
socks5_listening_port: config.core.socks5.listening_port,
client_address: address.to_string(),
}
}
@@ -128,13 +127,15 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
let id = &args.id;
let provider_address = &args.provider;
let already_init = Config::default_config_file_path(id).exists();
if already_init {
let already_init = if default_config_filepath(&id).exists() {
// in case we're using old config, try to upgrade it
// (if we're using the current version, it's a no-op)
try_upgrade_v1_1_13_config(id)?;
eprintln!("SOCKS5 client \"{id}\" was already initialised before");
}
true
} else {
false
};
// Usually you only register with the gateway on the first init, however you can force
// re-registering if wanted.
@@ -159,44 +160,36 @@ pub(crate) async fn execute(args: &Init) -> Result<(), Socks5ClientError> {
// Setup gateway by either registering a new one, or creating a new config from the selected
// one but with keys kept, or reusing the gateway configuration.
let key_store = OnDiskKeys::from_config(config.get_base());
let gateway = nym_client_core::init::setup_gateway_from_config::<Config, _, _>(
let key_store = OnDiskKeys::new(config.paths.keys_pathfinder.clone());
let gateway = nym_client_core::init::setup_gateway_from_config::<_>(
&key_store,
register_gateway,
user_chosen_gateway_id,
config.get_base(),
&config.core.base,
args.latency_based_selection,
)
.await
.tap_err(|err| eprintln!("Failed to setup gateway\nError: {err}"))?;
config.get_base_mut().set_gateway_endpoint(gateway);
config.core.base.set_gateway_endpoint(gateway);
// TODO: ask the service provider we specified for its interface version and set it in the config
config.save_to_file(None).tap_err(|_| {
let config_save_location = config.default_location();
config.save_to_default_location().tap_err(|_| {
log::error!("Failed to save the config file");
})?;
eprintln!(
"Saved configuration file to {}",
config_save_location.display()
);
print_saved_config(&config);
let address =
nym_client_core::init::get_client_address_from_stored_ondisk_keys(config.get_base())?;
let address = nym_client_core::init::get_client_address_from_stored_ondisk_keys(
&config.paths.keys_pathfinder,
&config.core.base.client.gateway_endpoint,
)?;
let init_results = InitResults::new(&config, &address);
println!("{}", args.output.format(&init_results));
Ok(())
}
fn print_saved_config(config: &Config) {
let config_save_location = config.get_config_file_save_location();
eprintln!("Saved configuration file to {:?}", config_save_location);
eprintln!("Using gateway: {}", config.get_base().get_gateway_id());
log::debug!("Gateway id: {}", config.get_base().get_gateway_id());
log::debug!("Gateway owner: {}", config.get_base().get_gateway_owner());
log::debug!(
"Gateway listener: {}",
config.get_base().get_gateway_listener()
);
eprintln!("Client configuration completed.\n");
}
+17 -15
View File
@@ -1,6 +1,7 @@
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::config::old_config_v1_1_13::OldConfigV1_1_13;
use crate::config::{BaseConfig, Config};
use clap::CommandFactory;
use clap::{Parser, Subcommand};
@@ -8,7 +9,7 @@ use lazy_static::lazy_static;
use log::info;
use nym_bin_common::build_information::BinaryBuildInformation;
use nym_bin_common::completions::{fig_generate, ArgShell};
use nym_config::{NymConfig, OptionalSet};
use nym_config::OptionalSet;
use nym_sphinx::params::PacketType;
use std::error::Error;
@@ -92,36 +93,37 @@ pub(crate) fn override_config(config: Config, args: OverrideConfig) -> Config {
.with_base(BaseConfig::with_packet_type, packet_type)
.with_optional(Config::with_anonymous_replies, args.use_anonymous_replies)
.with_optional(Config::with_port, args.port)
.with_optional_custom_env_ext(
.with_optional_base_custom_env(
BaseConfig::with_custom_nym_apis,
args.nym_apis,
nym_network_defaults::var_names::NYM_API,
nym_config::parse_urls,
)
.with_optional_custom_env_ext(
.with_optional_base_custom_env(
BaseConfig::with_custom_nyxd,
args.nyxd_urls,
nym_network_defaults::var_names::NYXD,
nym_config::parse_urls,
)
.with_optional_ext(
.with_optional_base(
BaseConfig::with_disabled_credentials,
args.enabled_credentials_mode.map(|b| !b),
)
}
fn try_upgrade_v1_1_13_config(id: &str) -> std::io::Result<()> {
// explicitly load it as v1.1.13 (which is incompatible with the current, i.e. 1.1.14+)
let Ok(old_config) = OldConfigV1_1_13::load_from_file(id) else {
// if we failed to load it, there might have been nothing to upgrade
// or maybe it was an even older file. in either way. just ignore it and carry on with our day
return Ok(());
};
info!("It seems the client is using <= v1.1.13 config template.");
info!("It is going to get updated to the current specification.");
let updated: Config = old_config.into();
updated.save_to_file(None)
todo!()
// // explicitly load it as v1.1.13 (which is incompatible with the current, i.e. 1.1.14+)
// let Ok(old_config) = OldConfigV1_1_13::load_from_file(id) else {
// // if we failed to load it, there might have been nothing to upgrade
// // or maybe it was an even older file. in either way. just ignore it and carry on with our day
// return Ok(());
// };
// info!("It seems the client is using <= v1.1.13 config template.");
// info!("It is going to get updated to the current specification.");
//
// let updated: Config = old_config.into();
// updated.save_to_file(None)
}
#[cfg(test)]
+7 -11
View File
@@ -1,7 +1,8 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::commands::try_upgrade_v1_1_13_config;
use crate::config::Config;
use crate::{
commands::{override_config, OverrideConfig},
error::Socks5ClientError,
@@ -10,9 +11,8 @@ use clap::Args;
use log::*;
use nym_bin_common::version_checker::is_minor_version_compatible;
use nym_client_core::client::base_client::storage::OnDiskPersistent;
use nym_config::NymConfig;
use nym_crypto::asymmetric::identity;
use nym_socks5_client_core::{config::Config, NymClient};
use nym_socks5_client_core::NymClient;
use nym_sphinx::addressing::clients::Recipient;
#[derive(Args, Clone)]
@@ -92,7 +92,7 @@ impl From<Run> for OverrideConfig {
// network version. It might do so in the future.
fn version_check(cfg: &Config) -> bool {
let binary_version = env!("CARGO_PKG_VERSION");
let config_version = cfg.get_base().get_version();
let config_version = &cfg.core.base.client.version;
if binary_version == config_version {
true
} else {
@@ -117,7 +117,7 @@ pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error
// (if we're using the current version, it's a no-op)
try_upgrade_v1_1_13_config(id)?;
let mut config = match Config::load_from_file(id) {
let mut config = match Config::read_from_default_path(id) {
Ok(cfg) => cfg,
Err(err) => {
error!("Failed to load config for {}. Are you sure you have run `init` before? (Error was: {err})", id);
@@ -134,15 +134,11 @@ pub(crate) async fn execute(args: &Run) -> Result<(), Box<dyn std::error::Error
let override_config_fields = OverrideConfig::from(args.clone());
config = override_config(config, override_config_fields);
if config.get_base_mut().set_empty_fields_to_defaults() {
warn!("some of the core config options were left unset. the default values are going to get used instead.");
}
if !version_check(&config) {
error!("failed the local version check");
return Err(Box::new(Socks5ClientError::FailedLocalVersionCheck));
}
let storage = OnDiskPersistent::from_config(config.get_base()).await?;
NymClient::new(config, storage).run_forever().await
let storage = OnDiskPersistent::from_paths(config.paths, &config.core.base.debug).await?;
NymClient::new(config.core, storage).run_forever().await
}
+21 -55
View File
@@ -1,11 +1,9 @@
// Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use nym_bin_common::version_checker::Version;
use nym_config::NymConfig;
use nym_socks5_client_core::config::{Config, MISSING_VALUE};
use crate::config::Config;
use clap::Args;
use nym_bin_common::version_checker::Version;
use std::{fmt::Display, process};
#[allow(dead_code)]
@@ -15,36 +13,32 @@ fn fail_upgrade<D1: Display, D2: Display>(from_version: D1, to_version: D2) -> !
}
fn print_start_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
println!(
"\n==================\nTrying to upgrade client from {} to {} ...",
from, to
);
println!("\n==================\nTrying to upgrade client from {from} to {to} ...");
}
fn print_failed_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
eprintln!(
"Upgrade from {} to {} failed!\n==================\n",
from, to
);
eprintln!("Upgrade from {from} to {to} failed!\n==================\n");
}
fn print_successful_upgrade<D1: Display, D2: Display>(from: D1, to: D2) {
println!(
"Upgrade from {} to {} was successful!\n==================\n",
from, to
);
println!("Upgrade from {from} to {to} was successful!\n==================\n");
}
fn outdated_upgrade(config_version: &Version, package_version: &Version) -> ! {
eprintln!(
"Cannot perform upgrade from {} to {}. Your version is too old to perform the upgrade.!",
config_version, package_version
"Cannot perform upgrade from {config_version} to {package_version}. Your version is too old to perform the upgrade.!"
);
process::exit(1)
}
fn unsupported_upgrade(current_version: &Version, config_version: &Version) -> ! {
eprintln!("Cannot perform upgrade from {} to {}. Please let the developers know about this issue if you expected it to work!", config_version, current_version);
eprintln!("Cannot perform upgrade from {config_version} to {current_version}. Please let the developers know about this issue if you expected it to work!");
process::exit(1)
}
fn unimplemented_upgrade(current_version: &Version, config_version: &Version) -> ! {
eprintln!("Cannot perform upgrade from {config_version} to {current_version} as it hasn't been implemented yet");
todo!();
process::exit(1)
}
@@ -56,7 +50,7 @@ pub(crate) struct Upgrade {
}
fn parse_config_version(config: &Config) -> Version {
let version = Version::parse(config.get_base().get_version()).unwrap_or_else(|err| {
let version = Version::parse(&config.core.base.client.version).unwrap_or_else(|err| {
eprintln!("failed to parse client version! - {err}");
process::exit(1)
});
@@ -89,35 +83,6 @@ fn parse_package_version() -> Version {
version
}
fn minor_0_12_upgrade(
mut config: Config,
_args: &Upgrade,
config_version: &Version,
package_version: &Version,
) -> Config {
let to_version = if package_version.major == 0 && package_version.minor == 12 {
package_version.clone()
} else {
Version::new(0, 12, 0)
};
print_start_upgrade(config_version, &to_version);
config
.get_base_mut()
.set_custom_version(to_version.to_string().as_ref());
config.save_to_file(None).unwrap_or_else(|err| {
eprintln!("failed to overwrite config file! - {err}");
print_failed_upgrade(config_version, &to_version);
process::exit(1);
});
print_successful_upgrade(config_version, to_version);
config
}
fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
loop {
let config_version = parse_config_version(&config);
@@ -128,9 +93,10 @@ fn do_upgrade(mut config: Config, args: &Upgrade, package_version: &Version) {
}
config = match config_version.major {
0 => match config_version.minor {
9 | 10 => outdated_upgrade(&config_version, package_version),
11 => minor_0_12_upgrade(config, args, &config_version, package_version),
0 => outdated_upgrade(&config_version, package_version),
1 => match config_version.minor {
n if n <= 13 => outdated_upgrade(&config_version, package_version),
n if n > 13 && n < 19 => unimplemented_upgrade(&config_version, package_version),
_ => unsupported_upgrade(&config_version, package_version),
},
_ => unsupported_upgrade(&config_version, package_version),
@@ -143,12 +109,12 @@ pub(crate) fn execute(args: &Upgrade) {
let id = &args.id;
let existing_config = Config::load_from_file(id).unwrap_or_else(|err| {
let existing_config = Config::read_from_default_path(id).unwrap_or_else(|err| {
eprintln!("failed to load existing config file! - {err}");
process::exit(1)
});
if existing_config.get_base().get_version() == MISSING_VALUE {
if existing_config.core.base.client.version.is_empty() {
eprintln!("the existing configuration file does not seem to contain version number.");
process::exit(1);
}
+58 -28
View File
@@ -1,20 +1,16 @@
// Copyright 2021-2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::config::template::{config_template, CONFIG_TEMPLATE};
use crate::config::template::CONFIG_TEMPLATE;
use nym_bin_common::logging::LoggingSettings;
use nym_client_core::config::disk_persistence::CommonClientPathfinder;
pub use nym_client_core::config::Config as BaseConfig;
use nym_client_core::config::{ClientCoreConfigTrait, DebugConfig};
use nym_config::defaults::DEFAULT_SOCKS5_LISTENING_PORT;
use nym_config::{
must_get_home, read_config_from_toml_file, save_formatted_config_to_file, NymConfig,
NymConfigTemplate, OptionalSet, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME, DEFAULT_DATA_DIR,
NYM_DIR,
must_get_home, read_config_from_toml_file, save_formatted_config_to_file, NymConfigTemplate,
OptionalSet, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME, DEFAULT_DATA_DIR, NYM_DIR,
};
use nym_service_providers_common::interface::ProviderInterfaceVersion;
pub use nym_socks5_client_core::config::Config as CoreConfig;
use nym_socks5_requests::Socks5ProtocolVersion;
use nym_sphinx::addressing::clients::Recipient;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
@@ -48,7 +44,7 @@ pub fn default_data_directory<P: AsRef<Path>>(id: P) -> PathBuf {
.join(DEFAULT_DATA_DIR)
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(flatten)]
@@ -68,7 +64,7 @@ impl NymConfigTemplate for Config {
impl Config {
pub fn new<S: AsRef<str>>(id: S, provider_mix_address: S) -> Self {
Config {
core: CoreConfig::new(id.as_ref(), provider_mix_address),
core: CoreConfig::new(id.as_ref(), provider_mix_address.as_ref()),
paths: CommonClientPathfinder::new_default(default_data_directory(id.as_ref())),
logging: Default::default(),
}
@@ -83,7 +79,7 @@ impl Config {
}
pub fn default_location(&self) -> PathBuf {
default_config_filepath(&self.base.client.id)
default_config_filepath(&self.core.base.client.id)
}
pub fn save_to_default_location(&self) -> io::Result<()> {
@@ -105,23 +101,16 @@ impl Config {
}
pub fn with_port(mut self, port: u16) -> Self {
self.socks5.with_port(port);
self.core.socks5.listening_port = port;
self
}
pub fn with_anonymous_replies(mut self, anonymous_replies: bool) -> Self {
self.socks5.with_anonymous_replies(anonymous_replies);
self.core.socks5.send_anonymously = anonymous_replies;
self
}
// poor man's 'builder' method
pub fn with_core<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(CoreConfig, T) -> CoreConfig,
{
self.base = f(self.base, val);
self
}
pub fn with_base<F, T>(mut self, f: F, val: T) -> Self
where
@@ -131,27 +120,68 @@ impl Config {
self
}
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
pub fn with_optional_base<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(CoreConfig, T) -> CoreConfig,
F: Fn(BaseConfig, T) -> BaseConfig,
{
self.base = self.base.with_optional(f, val);
self.core = self.core.with_optional_base(f, val);
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
pub fn with_optional_base_env<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig, T) -> BaseConfig,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.core = self.core.with_optional_base_env(f, val, env_var);
self
}
pub fn with_optional_base_custom_env<F, T, G>(
mut self,
f: F,
val: Option<T>,
env_var: &str,
parser: G,
) -> Self
where
F: Fn(BaseConfig, T) -> BaseConfig,
G: Fn(&str) -> T,
{
self.core = self
.core
.with_optional_base_custom_env(f, val, env_var, parser);
self
}
pub fn with_core<F, T>(mut self, f: F, val: T) -> Self
where
F: Fn(CoreConfig, T) -> CoreConfig,
{
self.core = f(self.core, val);
self
}
pub fn with_optional_core<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(CoreConfig, T) -> CoreConfig,
{
self.core = self.core.with_optional(f, val);
self
}
pub fn with_optional_core_env<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(CoreConfig, T) -> CoreConfig,
T: FromStr,
<T as FromStr>::Err: Debug,
{
self.base = self.base.with_optional_env(f, val, env_var);
self.core = self.core.with_optional_env(f, val, env_var);
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
pub fn with_optional_core_custom_env<F, T, G>(
mut self,
f: F,
val: Option<T>,
@@ -162,7 +192,7 @@ impl Config {
F: Fn(CoreConfig, T) -> CoreConfig,
G: Fn(&str) -> T,
{
self.base = self.base.with_optional_custom_env(f, val, env_var, parser);
self.core = self.core.with_optional_custom_env(f, val, env_var, parser);
self
}
}
+43 -44
View File
@@ -1,9 +1,8 @@
// Copyright 2023 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::config::{Config, Socks5};
use crate::config::Config;
use nym_client_core::config::old_config_v1_1_13::OldConfigV1_1_13 as OldBaseConfigV1_1_13;
use nym_config::NymConfig;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
@@ -12,51 +11,51 @@ use std::path::PathBuf;
pub struct OldConfigV1_1_13 {
#[serde(flatten)]
base: OldBaseConfigV1_1_13<OldConfigV1_1_13>,
socks5: Socks5,
}
impl NymConfig for OldConfigV1_1_13 {
fn template() -> &'static str {
// not intended to be used
unimplemented!()
}
fn default_root_directory() -> PathBuf {
#[cfg(not(target_os = "android"))]
let base_dir = dirs::home_dir().expect("Failed to evaluate $HOME value");
#[cfg(target_os = "android")]
let base_dir = PathBuf::from("/tmp");
base_dir.join(".nym").join("socks5-clients")
}
fn try_default_root_directory() -> Option<PathBuf> {
dirs::home_dir().map(|path| path.join(".nym").join("socks5-clients"))
}
fn root_directory(&self) -> PathBuf {
self.base.client.nym_root_directory.clone()
}
fn config_directory(&self) -> PathBuf {
self.root_directory()
.join(&self.base.client.id)
.join("config")
}
fn data_directory(&self) -> PathBuf {
self.root_directory()
.join(&self.base.client.id)
.join("data")
}
// socks5: Socks5,
}
// impl NymConfig for OldConfigV1_1_13 {
// fn template() -> &'static str {
// // not intended to be used
// unimplemented!()
// }
//
// fn default_root_directory() -> PathBuf {
// #[cfg(not(target_os = "android"))]
// let base_dir = dirs::home_dir().expect("Failed to evaluate $HOME value");
// #[cfg(target_os = "android")]
// let base_dir = PathBuf::from("/tmp");
//
// base_dir.join(".nym").join("socks5-clients")
// }
//
// fn try_default_root_directory() -> Option<PathBuf> {
// dirs::home_dir().map(|path| path.join(".nym").join("socks5-clients"))
// }
//
// fn root_directory(&self) -> PathBuf {
// self.base.client.nym_root_directory.clone()
// }
//
// fn config_directory(&self) -> PathBuf {
// self.root_directory()
// .join(&self.base.client.id)
// .join("config")
// }
//
// fn data_directory(&self) -> PathBuf {
// self.root_directory()
// .join(&self.base.client.id)
// .join("data")
// }
// }
//
impl From<OldConfigV1_1_13> for Config {
fn from(value: OldConfigV1_1_13) -> Self {
Config {
base: value.base.into(),
socks5: value.socks5,
}
todo!()
// Config {
// base: value.base.into(),
// socks5: value.socks5,
// }
}
}
@@ -17,7 +17,7 @@ use crate::client::base_client::non_wasm_helpers;
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
use crate::client::key_manager::persistence::OnDiskKeys;
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
use crate::config::{persistence::key_pathfinder::ClientKeyPathfinder, Config};
use crate::config::disk_persistence::CommonClientPathfinder;
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
use crate::error::ClientCoreError;
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
@@ -25,6 +25,7 @@ use nym_credential_storage::persistent_storage::PersistentStorage as PersistentC
#[cfg(all(not(target_arch = "wasm32"), feature = "fs-surb-storage"))]
use crate::client::replies::reply_storage::fs_backend;
use crate::config;
pub trait MixnetClientStorage {
type KeyStore: KeyStore;
@@ -95,18 +96,21 @@ impl OnDiskPersistent {
}
}
pub async fn from_config<T>(config: &Config<T>) -> Result<Self, ClientCoreError> {
let pathfinder = ClientKeyPathfinder::new_from_config(config);
let key_store = OnDiskKeys::new(pathfinder);
pub async fn from_paths(
pathfinder: CommonClientPathfinder,
debug_config: &config::DebugConfig,
) -> Result<Self, ClientCoreError> {
let key_store = OnDiskKeys::new(pathfinder.keys_pathfinder);
let reply_store = non_wasm_helpers::setup_fs_reply_surb_backend(
config.get_reply_surb_database_path(),
&config.get_debug_config().reply_surbs,
pathfinder.reply_surb_database_path,
&debug_config.reply_surbs,
)
.await?;
let credential_store =
nym_credential_storage::initialise_persistent_storage(config.get_database_path()).await;
nym_credential_storage::initialise_persistent_storage(pathfinder.credentials_database)
.await;
Ok(OnDiskPersistent {
key_store,
@@ -12,11 +12,10 @@ pub const DEFAULT_CREDENTIALS_DB_FILENAME: &str = "credentials_database.db";
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Serialize)]
pub struct CommonClientPathfinder {
pub key_pathfinder: ClientKeysPathfinder,
pub keys_pathfinder: ClientKeysPathfinder,
// TODO:
// pub gateway_config_pathfinder: (),
/// Path to the database containing bandwidth credentials of this client.
#[serde(alias = "database_path")]
pub credentials_database: PathBuf,
@@ -32,7 +31,7 @@ impl CommonClientPathfinder {
CommonClientPathfinder {
credentials_database: base_dir.join(DEFAULT_CREDENTIALS_DB_FILENAME),
reply_surb_database_path: base_dir.join(DEFAULT_REPLY_SURB_DB_FILENAME),
key_pathfinder: ClientKeysPathfinder::new_default(base_data_directory),
keys_pathfinder: ClientKeysPathfinder::new_default(base_data_directory),
}
}
}
+3 -3
View File
@@ -61,7 +61,7 @@ impl Config {
// helper methods to use `OptionalSet` trait. Those are defined due to very... ehm. 'specific' structure of this config
// (plz, lets refactor it)
pub fn with_optional_ext<F, T>(mut self, f: F, val: Option<T>) -> Self
pub fn with_optional_base<F, T>(mut self, f: F, val: Option<T>) -> Self
where
F: Fn(BaseConfig, T) -> BaseConfig,
{
@@ -69,7 +69,7 @@ impl Config {
self
}
pub fn with_optional_env_ext<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
pub fn with_optional_base_env<F, T>(mut self, f: F, val: Option<T>, env_var: &str) -> Self
where
F: Fn(BaseConfig, T) -> BaseConfig,
T: FromStr,
@@ -79,7 +79,7 @@ impl Config {
self
}
pub fn with_optional_custom_env_ext<F, T, G>(
pub fn with_optional_base_custom_env<F, T, G>(
mut self,
f: F,
val: Option<T>,
+15 -15
View File
@@ -68,8 +68,7 @@ where
#[allow(clippy::too_many_arguments)]
pub fn start_socks5_listener(
socks5_config: &Socks5,
debug_config: DebugConfig,
config: Config,
client_input: ClientInput,
client_output: ClientOutput,
client_status: ClientState,
@@ -95,24 +94,26 @@ where
..
} = client_status;
let packet_size = debug_config
let packet_size = config
.base
.debug
.traffic
.secondary_packet_size
.unwrap_or(debug_config.traffic.primary_packet_size);
.unwrap_or(config.base.debug.traffic.primary_packet_size);
let authenticator = Authenticator::new(auth_methods, allowed_users);
let mut sphinx_socks = NymSocksServer::new(
socks5_config.listening_port,
config.socks5.listening_port,
authenticator,
socks5_config.get_provider_mix_address(),
config.socks5.get_provider_mix_address(),
self_address,
shared_lane_queue_lengths,
socks::client::Config::new(
packet_size,
socks5_config.provider_interface_version,
socks5_config.socks5_protocol_version,
socks5_config.send_anonymously,
socks5_config.socks5_debug,
config.socks5.provider_interface_version,
config.socks5.socks5_protocol_version,
config.socks5.send_anonymously,
config.socks5.socks5_debug,
),
shutdown.clone(),
packet_type,
@@ -191,17 +192,17 @@ where
let (key_store, reply_storage_backend, credential_store) = self.storage.into_split();
// don't create bandwidth controller if credentials are disabled
let bandwidth_controller = if self.config.get_base().get_disabled_credentials_mode() {
let bandwidth_controller = if self.config.base.client.disabled_credentials_mode {
None
} else {
Some(non_wasm_helpers::create_bandwidth_controller(
self.config.get_base(),
&self.config.base,
credential_store,
))
};
let base_builder = BaseClientBuilder::<_, S>::new_from_base_config(
self.config.get_base(),
&self.config.base,
key_store,
bandwidth_controller,
reply_storage_backend,
@@ -217,8 +218,7 @@ where
info!("Running with {packet_type} packets",);
Self::start_socks5_listener(
self.config.get_socks5(),
*self.config.get_debug_settings(),
self.config,
client_input,
client_output,
client_state,
+4 -1
View File
@@ -258,7 +258,10 @@ async fn load_or_generate_base_config(
let expected_store_path =
Socks5Config::default_config_file_path_with_root(&storage_dir, &client_id.to_string());
eprintln!("attempting to load socks5 config from {expected_store_path:?}");
eprintln!(
"attempting to load socks5 config from {}",
expected_store_path.display()
);
// simulator workaround
if let Ok(config) = Socks5Config::load_from_filepath(expected_store_path) {