From 15b626bb6f3849b06ff7f34de49bd051b4493512 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 11:24:36 +0000 Subject: [PATCH 1/8] Removed comments regarding keypair for mixnode init --- mixnode/src/commands/init.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/mixnode/src/commands/init.rs b/mixnode/src/commands/init.rs index fdbba7dd2d..b7a6c521c7 100644 --- a/mixnode/src/commands/init.rs +++ b/mixnode/src/commands/init.rs @@ -64,10 +64,7 @@ pub fn execute(matches: &ArgMatches) { config = override_config(config, matches); - // TODO: which one should be used? let sphinx_keys = encryption::KeyPair::new(); - // let alternative_keypair = MixIdentityKeyPair::new(); - let pathfinder = MixNodePathfinder::new_from_config(&config); let pem_store = PemStore::new(pathfinder); pem_store From 16c92bebdf2a45072fd4929cacd6d17665bf0eb6 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 11:37:47 +0000 Subject: [PATCH 2/8] Removed the fake-news comments --- nym-client/src/config/mod.rs | 5 ----- nym-client/src/config/template.rs | 5 ----- 2 files changed, 10 deletions(-) diff --git a/nym-client/src/config/mod.rs b/nym-client/src/config/mod.rs index 507e9e7dc5..b1d6a8b7b2 100644 --- a/nym-client/src/config/mod.rs +++ b/nym-client/src/config/mod.rs @@ -318,12 +318,10 @@ pub struct Debug { /// The parameter of Poisson distribution determining how long, on average, /// it is going to take for another loop cover traffic message to be sent. - /// If set to a negative value, the loop cover traffic stream will be disabled. /// The provided value is interpreted as milliseconds. loop_cover_traffic_average_delay: u64, /// The uniform delay every which clients are querying the providers for received packets. - /// If set to a negative value, client will never try to fetch their messages. /// The provided value is interpreted as milliseconds. fetch_message_delay: u64, @@ -331,7 +329,6 @@ pub struct Debug { /// it is going to take another 'real traffic stream' message to be sent. /// If no real packets are available and cover traffic is enabled, /// a loop cover message is sent instead in order to preserve the rate. - /// If set to a negative value, client will never try to send real traffic data. /// The provided value is interpreted as milliseconds. message_sending_average_delay: u64, @@ -343,8 +340,6 @@ pub struct Debug { /// The uniform delay every which clients are querying the directory server /// to try to obtain a compatible network topology to send sphinx packets through. - /// If set to a negative value, client will never try to refresh its topology, - /// meaning it will always try to use whatever it obtained on startup. /// The provided value is interpreted as milliseconds. topology_refresh_rate: u64, diff --git a/nym-client/src/config/template.rs b/nym-client/src/config/template.rs index 78635045c1..561ae802ad 100644 --- a/nym-client/src/config/template.rs +++ b/nym-client/src/config/template.rs @@ -71,12 +71,10 @@ average_packet_delay = {{ debug.average_packet_delay }} # The parameter of Poisson distribution determining how long, on average, # it is going to take for another loop cover traffic message to be sent. -# If set to a negative value, the loop cover traffic stream will be disabled. # The provided value is interpreted as milliseconds. loop_cover_traffic_average_delay = {{ debug.loop_cover_traffic_average_delay }} # The uniform delay every which clients are querying the providers for received packets. -# If set to a negative value, client will never try to fetch their messages. # The provided value is interpreted as milliseconds. fetch_message_delay = {{ debug.fetch_message_delay }} @@ -84,7 +82,6 @@ fetch_message_delay = {{ debug.fetch_message_delay }} # it is going to take another 'real traffic stream' message to be sent. # If no real packets are available and cover traffic is enabled, # a loop cover message is sent instead in order to preserve the rate. -# If set to a negative value, client will never try to send real traffic data. # The provided value is interpreted as milliseconds. message_sending_average_delay = {{ debug.message_sending_average_delay }} @@ -96,8 +93,6 @@ rate_compliant_cover_messages_disabled = {{ debug.rate_compliant_cover_messages_ # The uniform delay every which clients are querying the directory server # to try to obtain a compatible network topology to send sphinx packets through. -# If set to a negative value, client will never try to refresh its topology, -# meaning it will always try to use whatever it obtained on startup. # The provided value is interpreted as milliseconds. topology_refresh_rate = {{ debug.topology_refresh_rate }} From 6515666b843b4710998e8a307e5e0804202fed39 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 11:41:27 +0000 Subject: [PATCH 3/8] Removed comments regarding keypair for sfw-provider init --- sfw-provider/src/commands/init.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/sfw-provider/src/commands/init.rs b/sfw-provider/src/commands/init.rs index f3ec9624f2..a488cd691f 100644 --- a/sfw-provider/src/commands/init.rs +++ b/sfw-provider/src/commands/init.rs @@ -93,10 +93,7 @@ pub fn execute(matches: &ArgMatches) { config = override_config(config, matches); - // TODO: which one should be used? let sphinx_keys = encryption::KeyPair::new(); - // let alternative_keypair = MixIdentityKeyPair::new(); - let pathfinder = ProviderPathfinder::new_from_config(&config); let pem_store = PemStore::new(pathfinder); pem_store From f72b456cddfa8b3008c07dc012862e3b97c4181b Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 15:18:00 +0000 Subject: [PATCH 4/8] Renamed `poisson::sample_from_duration` to `poisson::sample` --- common/clients/mix-client/src/poisson.rs | 2 +- nym-client/src/client/cover_traffic_stream.rs | 3 +-- nym-client/src/client/real_traffic_stream.rs | 5 ++--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/common/clients/mix-client/src/poisson.rs b/common/clients/mix-client/src/poisson.rs index e4bc83de7a..14aaf7a9d4 100644 --- a/common/clients/mix-client/src/poisson.rs +++ b/common/clients/mix-client/src/poisson.rs @@ -1,7 +1,7 @@ use rand_distr::{Distribution, Exp}; use std::time; -pub fn sample_from_duration(average_duration: time::Duration) -> time::Duration { +pub fn sample(average_duration: time::Duration) -> time::Duration { // this is our internal code used by our traffic streams // the error is only thrown if average delay is less than 0, which will never happen // so call to unwrap is perfectly safe here diff --git a/nym-client/src/client/cover_traffic_stream.rs b/nym-client/src/client/cover_traffic_stream.rs index 45fa0aced6..ac012a9a07 100644 --- a/nym-client/src/client/cover_traffic_stream.rs +++ b/nym-client/src/client/cover_traffic_stream.rs @@ -16,8 +16,7 @@ pub(crate) async fn start_loop_cover_traffic_stream( info!("Starting loop cover traffic stream"); loop { trace!("next cover message!"); - let delay_duration = - mix_client::poisson::sample_from_duration(average_cover_message_delay_duration); + let delay_duration = mix_client::poisson::sample(average_cover_message_delay_duration); tokio::time::delay_for(delay_duration).await; let read_lock = topology_ctrl_ref.read().await; diff --git a/nym-client/src/client/real_traffic_stream.rs b/nym-client/src/client/real_traffic_stream.rs index f11af86f04..5da904a7fe 100644 --- a/nym-client/src/client/real_traffic_stream.rs +++ b/nym-client/src/client/real_traffic_stream.rs @@ -38,8 +38,7 @@ impl Stream for OutQueueControl { // we know it's time to send a message, so let's prepare delay for the next one // Get the `now` by looking at the current `delay` deadline let now = self.next_delay.deadline(); - let next_poisson_delay = - mix_client::poisson::sample_from_duration(self.average_message_sending_delay); + let next_poisson_delay = mix_client::poisson::sample(self.average_message_sending_delay); // The next interval value is `next_poisson_delay` after the one that just // yielded. @@ -83,7 +82,7 @@ impl OutQueueControl { pub(crate) async fn run_out_queue_control(mut self) { // we should set initial delay only when we actually start the stream - self.next_delay = time::delay_for(mix_client::poisson::sample_from_duration( + self.next_delay = time::delay_for(mix_client::poisson::sample( self.average_message_sending_delay, )); From a6c389b5a6f346014c2137d4644d9d64f60a8144 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 15:19:13 +0000 Subject: [PATCH 5/8] Renamed 'average_delay_duration' to just 'average_delay' --- common/clients/mix-client/src/packet.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/common/clients/mix-client/src/packet.rs b/common/clients/mix-client/src/packet.rs index d7fb8b242a..8fab9589c3 100644 --- a/common/clients/mix-client/src/packet.rs +++ b/common/clients/mix-client/src/packet.rs @@ -43,7 +43,7 @@ pub fn loop_cover_message( our_address: DestinationAddressBytes, surb_id: SURBIdentifier, topology: &T, - average_delay_duration: time::Duration, + average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let destination = Destination::new(our_address, surb_id); @@ -51,7 +51,7 @@ pub fn loop_cover_message( destination, LOOP_COVER_MESSAGE_PAYLOAD.to_vec(), topology, - average_delay_duration, + average_delay, ) } @@ -59,7 +59,7 @@ pub fn encapsulate_message( recipient: Destination, message: Vec, topology: &T, - average_delay_duration: time::Duration, + average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let mut providers = topology.providers(); if providers.len() == 0 { @@ -70,8 +70,7 @@ pub fn encapsulate_message( let route = topology.route_to(provider)?; - let delays = - sphinx::header::delays::generate_from_average_duration(route.len(), average_delay_duration); + let delays = sphinx::header::delays::generate_from_average_duration(route.len(), average_delay); // build the packet let packet = sphinx::SphinxPacket::new(message, &route[..], &recipient, &delays)?; From a62744a1773d2cd9dd0e2adb8323e8e759b7e285 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 15:33:37 +0000 Subject: [PATCH 6/8] Fixed clippy warnings --- common/clients/mix-client/src/packet.rs | 2 +- common/healthcheck/src/path_check.rs | 8 ++++---- common/healthcheck/src/result.rs | 10 +++------- common/healthcheck/src/score.rs | 2 +- nym-client/src/sockets/tcp.rs | 4 ++-- nym-client/src/sockets/ws.rs | 7 ++----- sfw-provider/sfw-provider-requests/src/responses.rs | 2 +- sfw-provider/src/provider/mod.rs | 3 +-- 8 files changed, 15 insertions(+), 23 deletions(-) diff --git a/common/clients/mix-client/src/packet.rs b/common/clients/mix-client/src/packet.rs index 8fab9589c3..5132d4cb92 100644 --- a/common/clients/mix-client/src/packet.rs +++ b/common/clients/mix-client/src/packet.rs @@ -62,7 +62,7 @@ pub fn encapsulate_message( average_delay: time::Duration, ) -> Result<(SocketAddr, SphinxPacket), SphinxPacketEncapsulationError> { let mut providers = topology.providers(); - if providers.len() == 0 { + if providers.is_empty() { return Err(SphinxPacketEncapsulationError::NoValidProvidersError); } // unwrap is fine here as we asserted there is at least single provider diff --git a/common/healthcheck/src/path_check.rs b/common/healthcheck/src/path_check.rs index 43f4ef329f..79f2f80537 100644 --- a/common/healthcheck/src/path_check.rs +++ b/common/healthcheck/src/path_check.rs @@ -73,7 +73,7 @@ impl PathChecker { // iteration is used to distinguish packets sent through the same path (as the healthcheck // may try to send say 10 packets through given path) - fn unique_path_key(path: &Vec, check_id: [u8; 16], iteration: u8) -> Vec { + fn unique_path_key(path: &[SphinxNode], check_id: [u8; 16], iteration: u8) -> Vec { check_id .iter() .cloned() @@ -173,8 +173,8 @@ impl PathChecker { self.update_path_statuses(provider_messages); } - pub(crate) async fn send_test_packet(&mut self, path: &Vec, iteration: u8) { - if path.len() == 0 { + pub(crate) async fn send_test_packet(&mut self, path: &[SphinxNode], iteration: u8) { + if path.is_empty() { warn!("trying to send test packet through an empty path!"); return; } @@ -221,7 +221,7 @@ impl PathChecker { let first_node_client = self .layer_one_clients .entry(first_node_key) - .or_insert(Some(mix_client::MixClient::new())); + .or_insert_with(|| Some(mix_client::MixClient::new())); if first_node_client.is_none() { debug!("we can ignore this path as layer one mix is inaccessible"); diff --git a/common/healthcheck/src/result.rs b/common/healthcheck/src/result.rs index e1f8ad969c..2db51ddc3a 100644 --- a/common/healthcheck/src/result.rs +++ b/common/healthcheck/src/result.rs @@ -16,7 +16,7 @@ impl std::fmt::Display for HealthCheckResult { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { write!(f, "NETWORK HEALTH\n==============\n")?; for score in self.0.iter() { - write!(f, "{}\n", score)? + writeln!(f, "{}", score)? } Ok(()) } @@ -34,12 +34,8 @@ impl HealthCheckResult { let health = mixes .into_iter() - .map(|node| NodeScore::from_mixnode(node)) - .chain( - providers - .into_iter() - .map(|node| NodeScore::from_provider(node)), - ) + .map(NodeScore::from_mixnode) + .chain(providers.into_iter().map(NodeScore::from_provider)) .collect(); HealthCheckResult(health) diff --git a/common/healthcheck/src/score.rs b/common/healthcheck/src/score.rs index 7262d4ee0d..5cfa6cd811 100644 --- a/common/healthcheck/src/score.rs +++ b/common/healthcheck/src/score.rs @@ -110,7 +110,7 @@ impl NodeScore { pub_key: NodeAddressBytes::from_base58_string(node.pub_key), addresses: vec![node.mixnet_listener, node.client_listener], version: node.version, - layer: format!("provider"), + layer: "provider".to_string(), packets_sent: 0, packets_received: 0, } diff --git a/nym-client/src/sockets/tcp.rs b/nym-client/src/sockets/tcp.rs index 9d9f6d3bd1..28987ad90b 100644 --- a/nym-client/src/sockets/tcp.rs +++ b/nym-client/src/sockets/tcp.rs @@ -125,7 +125,7 @@ impl ClientRequest { Err(e) => { warn!("Failed to fetch client messages - {:?}", e); return ServerResponse::Error { - message: format!("Server failed to receive messages").to_string(), + message: "Server failed to receive messages".to_string(), }; } }; @@ -275,7 +275,7 @@ async fn accept_connection( topology: topology.clone(), msg_input: msg_input.clone(), msg_query: msg_query.clone(), - self_address: self_address.clone(), + self_address, }; match handle_connection(&buf[..n], request_handling_data).await { Ok(res) => res, diff --git a/nym-client/src/sockets/ws.rs b/nym-client/src/sockets/ws.rs index 73d8df3898..9315ac80a1 100644 --- a/nym-client/src/sockets/ws.rs +++ b/nym-client/src/sockets/ws.rs @@ -239,7 +239,7 @@ impl ClientRequest { Err(e) => { warn!("Failed to fetch client messages - {:?}", e); return ServerResponse::Error { - message: format!("Server failed to receive messages").to_string(), + message: "Server failed to receive messages".to_string(), }; } }; @@ -353,10 +353,7 @@ async fn accept_connection( } }; - let mut should_close = false; - if message.is_close() { - should_close = true; - } + let should_close = message.is_close(); if let Err(err) = msg_tx.unbounded_send(message) { error!( diff --git a/sfw-provider/sfw-provider-requests/src/responses.rs b/sfw-provider/sfw-provider-requests/src/responses.rs index 6a181ffedc..4135ed06e4 100644 --- a/sfw-provider/sfw-provider-requests/src/responses.rs +++ b/sfw-provider/sfw-provider-requests/src/responses.rs @@ -72,7 +72,7 @@ impl ProviderResponse for PullResponse { return Err(ProviderResponseError::UnmarshalErrorInvalidLength); } - let mut bytes_copy = bytes.clone(); + let mut bytes_copy = bytes; let num_msgs = read_be_u16(&mut bytes_copy); // can we read all lengths of messages? diff --git a/sfw-provider/src/provider/mod.rs b/sfw-provider/src/provider/mod.rs index 01489211b1..12673ab126 100644 --- a/sfw-provider/src/provider/mod.rs +++ b/sfw-provider/src/provider/mod.rs @@ -63,7 +63,7 @@ impl ClientLedger { } fn has_token(&self, auth_token: &AuthToken) -> bool { - return self.0.contains_key(auth_token); + self.0.contains_key(auth_token) } fn insert_token( @@ -155,7 +155,6 @@ impl ServiceProvider { ) .unwrap_or_else(|e| { error!("failed to store processed sphinx message; err = {:?}", e); - return; }); } Err(e) => { From 1a8573632f2fca5f1749cac07ef69043b8293ce4 Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 15:38:46 +0000 Subject: [PATCH 7/8] 'new_without_default' clippy warnings --- common/crypto/src/encryption/mod.rs | 6 ++++++ common/crypto/src/identity/mod.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/common/crypto/src/encryption/mod.rs b/common/crypto/src/encryption/mod.rs index 4d9d7f6db0..78edbd5c47 100644 --- a/common/crypto/src/encryption/mod.rs +++ b/common/crypto/src/encryption/mod.rs @@ -39,6 +39,12 @@ impl KeyPair { } } +impl Default for KeyPair { + fn default() -> Self { + KeyPair::new() + } +} + impl PemStorableKeyPair for KeyPair { type PrivatePemKey = PrivateKey; type PublicPemKey = PublicKey; diff --git a/common/crypto/src/identity/mod.rs b/common/crypto/src/identity/mod.rs index 4c1ea3cf75..941f786f67 100644 --- a/common/crypto/src/identity/mod.rs +++ b/common/crypto/src/identity/mod.rs @@ -36,6 +36,12 @@ impl MixIdentityKeyPair { } } +impl Default for MixIdentityKeyPair { + fn default() -> Self { + MixIdentityKeyPair::new() + } +} + impl PemStorableKeyPair for MixIdentityKeyPair { type PrivatePemKey = MixIdentityPrivateKey; type PublicPemKey = MixIdentityPublicKey; From bdf1e5bef91f605a711b12da8b8f68d29bb9880d Mon Sep 17 00:00:00 2001 From: Jedrzej Stuczynski Date: Wed, 19 Feb 2020 15:47:38 +0000 Subject: [PATCH 8/8] Fixed further linter warnings --- common/clients/directory-client/src/presence/mod.rs | 5 ++--- common/config/src/lib.rs | 12 ++++++------ common/topology/src/lib.rs | 11 ++++------- mixnode/src/mix_peer.rs | 5 ++--- mixnode/src/node/mod.rs | 2 +- 5 files changed, 15 insertions(+), 20 deletions(-) diff --git a/common/clients/directory-client/src/presence/mod.rs b/common/clients/directory-client/src/presence/mod.rs index b595953758..99d23ca130 100644 --- a/common/clients/directory-client/src/presence/mod.rs +++ b/common/clients/directory-client/src/presence/mod.rs @@ -29,11 +29,10 @@ impl NymTopology for Topology { }; let directory = Client::new(directory_config); - let topology = directory + directory .presence_topology .get() - .expect("Failed to retrieve network topology."); - topology + .expect("Failed to retrieve network topology.") } fn new_from_nodes( diff --git a/common/config/src/lib.rs b/common/config/src/lib.rs index 4cf0cadc37..f5c8c0c032 100644 --- a/common/config/src/lib.rs +++ b/common/config/src/lib.rs @@ -46,19 +46,19 @@ pub trait NymConfig: Default + Serialize + DeserializeOwned { }?; fs::write( - custom_location.unwrap_or(self.config_directory().join(Self::config_file_name())), + custom_location + .unwrap_or_else(|| self.config_directory().join(Self::config_file_name())), templated_config, ) } fn load_from_file(custom_location: Option, id: Option<&str>) -> io::Result { let config_contents = fs::read_to_string( - custom_location.unwrap_or(Self::default_config_directory(id).join("config.toml")), + custom_location + .unwrap_or_else(|| Self::default_config_directory(id).join("config.toml")), )?; - let parsing_result = toml::from_str(&config_contents) - .map_err(|toml_err| io::Error::new(io::ErrorKind::Other, toml_err)); - - parsing_result + toml::from_str(&config_contents) + .map_err(|toml_err| io::Error::new(io::ErrorKind::Other, toml_err)) } } diff --git a/common/topology/src/lib.rs b/common/topology/src/lib.rs index 3067b30b47..5edba93d7d 100644 --- a/common/topology/src/lib.rs +++ b/common/topology/src/lib.rs @@ -30,7 +30,7 @@ pub trait NymTopology: Sized + std::fmt::Debug + Send + Sync { } highest_layer = max(highest_layer, mix.layer); - let layer_nodes = layered_topology.entry(mix.layer).or_insert(Vec::new()); + let layer_nodes = layered_topology.entry(mix.layer).or_insert_with(Vec::new); layer_nodes.push(mix); } @@ -40,12 +40,12 @@ pub trait NymTopology: Sized + std::fmt::Debug + Send + Sync { if !layered_topology.contains_key(&layer) { missing_layers.push(layer); } - if layered_topology[&layer].len() == 0 { + if layered_topology[&layer].is_empty() { missing_layers.push(layer); } } - if missing_layers.len() > 0 { + if !missing_layers.is_empty() { return Err(NymTopologyError::MissingLayerError(missing_layers)); } @@ -112,10 +112,7 @@ pub trait NymTopology: Sized + std::fmt::Debug + Send + Sync { } fn can_construct_path_through(&self) -> bool { - match self.make_layered_topology() { - Ok(_) => true, - Err(_) => false, - } + self.make_layered_topology().is_ok() } } diff --git a/mixnode/src/mix_peer.rs b/mixnode/src/mix_peer.rs index 8a8579a780..82be36c475 100644 --- a/mixnode/src/mix_peer.rs +++ b/mixnode/src/mix_peer.rs @@ -34,13 +34,12 @@ impl MixPeer { } pub async fn send(&self, bytes: Vec) -> Result<(), Box> { - let next_hop_address = self.connection.clone(); - let mut stream = tokio::net::TcpStream::connect(next_hop_address).await?; + let mut stream = tokio::net::TcpStream::connect(self.connection).await?; stream.write_all(&bytes).await?; Ok(()) } - pub fn to_string(&self) -> String { + pub fn stringify(&self) -> String { self.connection.to_string() } } diff --git a/mixnode/src/node/mod.rs b/mixnode/src/node/mod.rs index 2f6f9dccac..9244022302 100644 --- a/mixnode/src/node/mod.rs +++ b/mixnode/src/node/mod.rs @@ -135,7 +135,7 @@ impl PacketProcessor { if forwarding_data .sent_metrics_tx - .send(forwarding_data.recipient.to_string()) + .send(forwarding_data.recipient.stringify()) .await .is_err() {