Skip to content

Commit

Permalink
Cleaning up lint errors (#1269)
Browse files Browse the repository at this point in the history
  • Loading branch information
iduartgomez authored Oct 19, 2024
1 parent cdd1dfa commit a78ed3d
Show file tree
Hide file tree
Showing 13 changed files with 23 additions and 178 deletions.
4 changes: 0 additions & 4 deletions crates/core/src/node/network_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ mod handshake;
pub(crate) mod in_memory;
pub(crate) mod p2p_protoc;

// TODO: use this constants when we do real net i/o
// const PING_EVERY: Duration = Duration::from_secs(30);
// const DROP_CONN_AFTER: Duration = Duration::from_secs(30 * 10);

pub(crate) type ConnResult<T> = std::result::Result<T, ConnectionError>;

/// Allows handling of connections to the network as well as sending messages
Expand Down
29 changes: 1 addition & 28 deletions crates/core/src/operations/update.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use freenet_stdlib::client_api::{ErrorKind, HostResponse};
// TODO: complete update logic in the network
use freenet_stdlib::client_api::{ErrorKind, HostResponse};
use freenet_stdlib::prelude::*;

use super::{OpEnum, OpError, OpInitialization, OpOutcome, Operation, OperationResult};
Expand Down Expand Up @@ -28,24 +28,6 @@ impl UpdateOp {
matches!(self.state, None | Some(UpdateState::Finished { .. }))
}

// pub(super) fn record_transfer(&mut self) {
// if let Some(stats) = self.stats.as_mut() {
// match stats.step {
// RecordingStats::Uninitialized => {
// stats.transfer_time = Some((Instant::now(), None));
// stats.step = RecordingStats::InitUpdate;
// }
// RecordingStats::InitUpdate => {
// if let Some((_, e)) = stats.transfer_time.as_mut() {
// *e = Some(Instant::now());
// }
// stats.step = RecordingStats::Completed;
// }
// RecordingStats::Completed => {}
// }
// }
// }

pub(super) fn to_host_result(&self) -> HostResult {
if let Some(UpdateState::Finished { key, summary }) = &self.state {
Ok(HostResponse::ContractResponse(
Expand All @@ -65,17 +47,8 @@ impl UpdateOp {

struct UpdateStats {
target: Option<PeerKeyLocation>,
// step: RecordingStats,
}

// /// While timing, at what particular step we are now.
// #[derive(Clone, Copy, Default)]
// enum RecordingStats {
// #[default]
// Uninitialized,
// Completed,
// }

pub(crate) struct UpdateResult {}

impl TryFrom<UpdateOp> for UpdateResult {
Expand Down
21 changes: 4 additions & 17 deletions crates/core/src/topology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,10 @@ impl TopologyManager {
let decrease_usage_if_above: RateProportion =
RateProportion::new(MAXIMUM_DESIRED_RESOURCE_USAGE_PROPORTION);

let usage_rates = self.calculate_usage_proportion(at_time);

let (resource_type, usage_proportion) = usage_rates.max_usage_rate;
let (resource_type, usage_proportion) = self.calculate_usage_proportion(at_time);

// Detailed resource usage information
debug!("Usage proportions: {:?}", usage_rates);
debug!(?usage_proportion, "Resource usage information");

let adjustment: anyhow::Result<TopologyAdjustment> =
if neighbor_locations.len() > self.limits.max_connections {
Expand Down Expand Up @@ -405,7 +403,7 @@ impl TopologyManager {
adjustment.unwrap_or(TopologyAdjustment::NoChange)
}

fn calculate_usage_proportion(&mut self, at_time: Instant) -> UsageRates {
fn calculate_usage_proportion(&mut self, at_time: Instant) -> (ResourceType, RateProportion) {
let mut usage_rate_per_type = HashMap::new();
for resource_type in ResourceType::all() {
let usage = self.extrapolated_usage(&resource_type, at_time);
Expand All @@ -418,11 +416,7 @@ impl TopologyManager {
.max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(Ordering::Equal))
.unwrap();

UsageRates {
// TODO: Is there a way to avoid this clone()?
usage_rate_per_type: usage_rate_per_type.clone(),
max_usage_rate: (*max_usage_rate.0, *max_usage_rate.1),
}
(*max_usage_rate.0, *max_usage_rate.1)
}

/// modify the current connection acquisition strategy
Expand Down Expand Up @@ -970,10 +964,3 @@ impl Limits {
}
}
}

#[derive(Debug, Clone)]
struct UsageRates {
#[allow(unused)]
usage_rate_per_type: HashMap<ResourceType, RateProportion>,
max_usage_rate: (ResourceType, RateProportion),
}
9 changes: 0 additions & 9 deletions crates/core/src/transport.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#![allow(dead_code)] // TODO: Remove before integration
//! Freenet Transport protocol implementation.
//!
//! Please see `docs/architecture/transport.md` for more information.
Expand All @@ -22,8 +21,6 @@ type MessagePayload = Vec<u8>;

type PacketId = u32;

use self::peer_connection::StreamId;

pub use self::crypto::{TransportKeypair, TransportPublicKey};
#[cfg(test)]
pub(crate) use self::{
Expand All @@ -47,20 +44,14 @@ pub(crate) enum TransportError {
ConnectionClosed(SocketAddr),
#[error("failed while establishing connection, reason: {cause}")]
ConnectionEstablishmentFailure { cause: Cow<'static, str> },
#[error("incomplete inbound stream: {0}")]
IncompleteInboundStream(StreamId),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
Other(#[from] anyhow::Error),
#[error("{0}")]
PrivateKeyDecryptionError(aes_gcm::aead::Error),
#[error(transparent)]
PubKeyDecryptionError(#[from] rsa::errors::Error),
#[error(transparent)]
Serialization(#[from] bincode::Error),
#[error("received unexpected message from remote: {0}")]
UnexpectedMessage(Cow<'static, str>),
}

/// Make connection handler more testable
Expand Down
59 changes: 2 additions & 57 deletions crates/core/src/transport/connection_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,24 +38,7 @@ const MAX_INTERVAL: Duration = Duration::from_millis(5000); // Maximum interval
const DEFAULT_BW_TRACKER_WINDOW_SIZE: Duration = Duration::from_secs(10);
const BANDWITH_LIMIT: usize = 1024 * 1024 * 10; // 10 MB/s

type ConnectionHandlerMessage = (SocketAddr, Vec<u8>);
pub type SerializedMessage = Vec<u8>;
type PeerChannel = (
mpsc::Sender<SerializedMessage>,
mpsc::Receiver<SymmetricMessagePayload>,
);

struct OutboundMessage {
remote_addr: SocketAddr,
msg: SerializedMessage,
recv: mpsc::Receiver<SerializedMessage>,
}

struct GatewayMessage {
remote_addr: SocketAddr,
packet: PacketData<UnknownEncryption>,
resp_tx: oneshot::Sender<bool>,
}

pub(crate) async fn create_connection_handler<S: Socket>(
keypair: TransportKeypair,
Expand Down Expand Up @@ -191,16 +174,6 @@ impl OutboundConnectionHandler {
}
}

pub enum Message {
Short(Vec<u8>),
Streamed(Vec<u8>, mpsc::Receiver<StreamFragment>),
}

pub struct StreamFragment {
pub fragment_number: u32,
pub fragment: Vec<u8>,
}

/// Handles UDP transport internally.
struct UdpPacketsListener<S = UdpSocket> {
socket_listener: Arc<S>,
Expand Down Expand Up @@ -505,8 +478,6 @@ impl<S: Socket> UdpPacketsListener<S> {

let inbound_conn = InboundRemoteConnection {
inbound_packet_sender: inbound_packet_tx,
inbound_intro_packet: None,
inbound_checked_times: 0,
};

tracing::debug!("returning connection at gw");
Expand Down Expand Up @@ -701,8 +672,6 @@ impl<S: Socket> UdpPacketsListener<S> {
},
InboundRemoteConnection {
inbound_packet_sender: inbound_sender,
inbound_intro_packet: None,
inbound_checked_times: 0,
},
));
}
Expand Down Expand Up @@ -771,8 +740,6 @@ impl<S: Socket> UdpPacketsListener<S> {
},
InboundRemoteConnection {
inbound_packet_sender: inbound_sender,
inbound_intro_packet: Some(intro_packet.clone()),
inbound_checked_times: 0,
},
));
}
Expand Down Expand Up @@ -832,28 +799,6 @@ pub(crate) enum ConnectionEvent {

struct InboundRemoteConnection {
inbound_packet_sender: mpsc::Sender<PacketData<UnknownEncryption>>,
inbound_intro_packet: Option<PacketData<AssymetricRSA>>,
inbound_checked_times: usize,
}

impl InboundRemoteConnection {
fn check_inbound_packet(&mut self, packet: &PacketData<UnknownEncryption>) -> bool {
let mut inbound = false;
if let Some(inbound_intro_packet) = self.inbound_intro_packet.as_ref() {
if packet.is_intro_packet(inbound_intro_packet) {
inbound = true;
}
}
if self.inbound_checked_times >= UdpPacketsListener::<UdpSocket>::NAT_TRAVERSAL_MAX_ATTEMPTS
{
// no point in checking more than the max attemps since they won't be sending
// the intro packet more than this amount of times
self.inbound_intro_packet = None;
} else {
self.inbound_checked_times += 1;
}
inbound
}
}

#[cfg(test)]
Expand Down Expand Up @@ -1455,7 +1400,7 @@ mod test {
async fn simulate_send_short_message() -> anyhow::Result<()> {
// crate::config::set_logger(Some(tracing::level_filters::LevelFilter::TRACE), None);
#[derive(Clone, Copy)]
struct TestData(&'static str, usize);
struct TestData(&'static str);

impl TestFixture for TestData {
type Message = String;
Expand All @@ -1477,7 +1422,7 @@ mod test {
peers: 10,
..Default::default()
},
Vec::from_iter((0..10).map(|i| TestData("foo", i))),
Vec::from_iter((0..10).map(|_| TestData("foo"))),
)
.await
}
Expand Down
2 changes: 2 additions & 0 deletions crates/core/src/transport/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ impl TransportKeypair {
&self.public
}

#[cfg(test)]
pub(crate) fn secret(&self) -> &TransportSecretKey {
&self.secret
}
Expand Down Expand Up @@ -93,6 +94,7 @@ impl TransportSecretKey {
self.0.decrypt(Pkcs1v15Encrypt, data)
}

#[cfg(test)]
pub fn to_pkcs8_pem(&self) -> Result<Vec<u8>, pkcs8::Error> {
use pkcs8::EncodePrivateKey;

Expand Down
8 changes: 0 additions & 8 deletions crates/core/src/transport/packet_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,6 @@ impl Encryption for SymmetricAES {}
impl Encryption for AssymetricRSA {}
impl Encryption for UnknownEncryption {}

pub(super) const fn packet_size<const DATA_SIZE: usize>() -> usize {
DATA_SIZE + NONCE_SIZE + TAG_SIZE
}

fn internal_sym_decryption<const N: usize>(
data: &[u8],
size: usize,
Expand Down Expand Up @@ -136,10 +132,6 @@ impl<const N: usize> PacketData<AssymetricRSA, N> {
data_type: PhantomData,
}
}

pub fn preparef_send(self) -> Arc<[u8]> {
self.data[..self.size].into()
}
}

impl<const N: usize> PacketData<Plaintext, N> {
Expand Down
6 changes: 2 additions & 4 deletions crates/core/src/transport/peer_connection.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::atomic::AtomicU32;
use std::sync::Arc;
use std::time::Duration;

use crate::transport::packet_data::UnknownEncryption;
use aes_gcm::Aes128Gcm;
use futures::stream::FuturesUnordered;
use futures::{Future, StreamExt};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
Expand Down Expand Up @@ -67,7 +66,6 @@ impl std::fmt::Display for StreamId {
}

type InboundStreamResult = Result<(StreamId, SerializedMessage), StreamId>;
type InboundStreamFut = Pin<Box<dyn Future<Output = InboundStreamResult> + Send>>;

/// The `PeerConnection` struct is responsible for managing the connection with a remote peer.
/// It provides methods for sending and receiving messages to and from the remote peer.
Expand Down Expand Up @@ -593,7 +591,7 @@ mod tests {
while let Some((_, network_packet)) = receiver.recv().await {
let decrypted = PacketData::<_, MAX_PACKET_SIZE>::from_buf(&network_packet)
.try_decrypt_sym(&cipher)
.map_err(TransportError::PrivateKeyDecryptionError)?;
.map_err(|e| e.to_string())?;
let SymmetricMessage {
payload:
SymmetricMessagePayload::StreamFragment {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ mod tests {
while let Some((_, packet)) = outbound_receiver.recv().await {
let decrypted_packet = PacketData::<_, MAX_PACKET_SIZE>::from_buf(packet.as_ref())
.try_decrypt_sym(&cipher)
.map_err(TransportError::PrivateKeyDecryptionError)?;
.map_err(|e| e.to_string())?;
let deserialized = SymmetricMessage::deser(decrypted_packet.data())?;
let SymmetricMessagePayload::StreamFragment { payload, .. } = deserialized.payload
else {
Expand Down
9 changes: 0 additions & 9 deletions crates/core/src/transport/sent_packet_tracker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,6 @@ impl SentPacketTracker<InstantTimeSrc> {
}

impl<T: TimeSource> SentPacketTracker<T> {
/// Get an estimate of the proportion of outbound packets that were lost This is a value
/// between 0.0 and 1.0, where 0.0 means no packets are lost and 1.0 means all packets are
/// lost. This estimate will be biased towards 0.0 initially, and will converge to the
/// true value over time. It's accuracy will be approximately
/// `PACKET_LOSS_DECAY_FACTOR` (0.001).
pub(super) fn get_recent_packet_loss(&self) -> f64 {
self.packet_loss_proportion
}

pub(super) fn report_sent_packet(&mut self, packet_id: PacketId, payload: Arc<[u8]>) {
self.pending_receipts.insert(packet_id, payload);
self.resend_queue.push_back(ResendQueueEntry {
Expand Down
2 changes: 1 addition & 1 deletion crates/fdev/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "fdev"
version = "0.0.7"
edition = "2021"
rust-version = "1.71.1"
rust-version = "1.80"
publish = true
description = "Freenet development tool"
license = "MIT OR Apache-2.0"
Expand Down
3 changes: 1 addition & 2 deletions crates/fdev/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,8 @@ fn get_out_lib(work_dir: &Path, cli_config: &BuildToolConfig) -> anyhow::Result<
"debug"
};
let output_lib = env::var("CARGO_TARGET_DIR")
.map_err(|e| {
.inspect_err(|_| {
println!("Missing environment variable `CARGO_TARGET_DIR");
e
})?
.parse::<PathBuf>()?
.join(target)
Expand Down
Loading

0 comments on commit a78ed3d

Please sign in to comment.