diff --git a/Cargo.lock b/Cargo.lock index 0bb4612..605af04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -786,11 +786,9 @@ dependencies = [ "thiserror", "tokio", "tokio-stream", - "tokio-test", "tokio-util", "tower", "tracing", - "tracing-subscriber", ] [[package]] diff --git a/p2p/p2p-core/Cargo.toml b/p2p/p2p-core/Cargo.toml index 9ef8e24..4175c5f 100644 --- a/p2p/p2p-core/Cargo.toml +++ b/p2p/p2p-core/Cargo.toml @@ -28,9 +28,12 @@ hex-literal = { workspace = true } borsh = { workspace = true, features = ["derive", "std"], optional = true } [dev-dependencies] -cuprate-test-utils = {path = "../../test-utils"} +cuprate-test-utils = { path = "../../test-utils" } hex = { workspace = true, features = ["std"] } tokio = { workspace = true, features = ["net", "rt-multi-thread", "rt", "macros"]} -tokio-test = { workspace = true } -tracing-subscriber = { workspace = true } +# tokio-test = { workspace = true } +# tracing-subscriber = { workspace = true } + +[lints] +workspace = true \ No newline at end of file diff --git a/p2p/p2p-core/src/client.rs b/p2p/p2p-core/src/client.rs index 662a8ee..7deb88a 100644 --- a/p2p/p2p-core/src/client.rs +++ b/p2p/p2p-core/src/client.rs @@ -43,8 +43,8 @@ pub enum InternalPeerID { impl Display for InternalPeerID { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - InternalPeerID::KnownAddr(addr) => addr.fmt(f), - InternalPeerID::Unknown(id) => f.write_str(&format!("Unknown, ID: {id}")), + Self::KnownAddr(addr) => addr.fmt(f), + Self::Unknown(id) => f.write_str(&format!("Unknown, ID: {id}")), } } } @@ -113,7 +113,7 @@ impl Client { fn set_err(&self, err: PeerError) -> tower::BoxError { let err_str = err.to_string(); match self.error.try_insert_err(err) { - Ok(_) => err_str, + Ok(()) => err_str, Err(e) => e.to_string(), } .into() @@ -169,7 +169,7 @@ impl Service for Client { TrySendError::Closed(req) | TrySendError::Full(req) => { self.set_err(PeerError::ClientChannelClosed); - let _ = req + let _unused = req .response_channel .send(Err(PeerError::ClientChannelClosed.into())); } @@ -216,7 +216,7 @@ where tracing::debug!("Sending back response"); - let _ = req.response_channel.send(Ok(res)); + let _unused = req.response_channel.send(Ok(res)); } } .instrument(task_span), diff --git a/p2p/p2p-core/src/client/connection.rs b/p2p/p2p-core/src/client/connection.rs index f3f3f6b..1353c8e 100644 --- a/p2p/p2p-core/src/client/connection.rs +++ b/p2p/p2p-core/src/client/connection.rs @@ -26,7 +26,7 @@ use crate::{ }; /// A request to the connection task from a [`Client`](crate::client::Client). -pub struct ConnectionTaskRequest { +pub(crate) struct ConnectionTaskRequest { /// The request. pub request: PeerRequest, /// The response channel. @@ -36,7 +36,7 @@ pub struct ConnectionTaskRequest { } /// The connection state. -pub enum State { +pub(crate) enum State { /// Waiting for a request from Cuprate or the connected peer. WaitingForRequest, /// Waiting for a response from the peer. @@ -53,7 +53,7 @@ pub enum State { /// Returns if the [`LevinCommand`] is the correct response message for our request. /// /// e.g. that we didn't get a block for a txs request. -fn levin_command_response(message_id: &MessageID, command: LevinCommand) -> bool { +const fn levin_command_response(message_id: MessageID, command: LevinCommand) -> bool { matches!( (message_id, command), (MessageID::Handshake, LevinCommand::Handshake) @@ -71,7 +71,7 @@ fn levin_command_response(message_id: &MessageID, command: LevinCommand) -> bool } /// This represents a connection to a peer. -pub struct Connection { +pub(crate) struct Connection { /// The peer sink - where we send messages to the peer. peer_sink: Z::Sink, @@ -104,15 +104,15 @@ where BrdcstStrm: Stream + Send + 'static, { /// Create a new connection struct. - pub fn new( + pub(crate) fn new( peer_sink: Z::Sink, client_rx: mpsc::Receiver, broadcast_stream: BrdcstStrm, peer_request_handler: PeerRequestHandler, connection_guard: ConnectionGuard, error: SharedError, - ) -> Connection { - Connection { + ) -> Self { + Self { peer_sink, state: State::WaitingForRequest, request_timeout: None, @@ -174,15 +174,15 @@ where if let Err(e) = res { // can't clone the error so turn it to a string first, hacky but oh well. let err_str = e.to_string(); - let _ = req.response_channel.send(Err(err_str.clone().into())); + let _unused = req.response_channel.send(Err(err_str.into())); return Err(e); - } else { - // We still need to respond even if the response is this. - let _ = req - .response_channel - .send(Ok(PeerResponse::Protocol(ProtocolResponse::NA))); } + // We still need to respond even if the response is this. + let _unused = req + .response_channel + .send(Ok(PeerResponse::Protocol(ProtocolResponse::NA))); + Ok(()) } @@ -215,7 +215,7 @@ where }; // Check if the message is a response to our request. - if levin_command_response(request_id, mes.command()) { + if levin_command_response(*request_id, mes.command()) { // TODO: Do more checks before returning response. let State::WaitingForResponse { tx, .. } = @@ -224,7 +224,7 @@ where panic!("Not in correct state, can't receive response!") }; - let _ = tx.send(Ok(mes + let _unused = tx.send(Ok(mes .try_into() .map_err(|_| PeerError::PeerSentInvalidMessage)?)); @@ -282,7 +282,7 @@ where tokio::select! { biased; - _ = self.request_timeout.as_mut().expect("Request timeout was not set!") => { + () = self.request_timeout.as_mut().expect("Request timeout was not set!") => { Err(PeerError::ClientChannelClosed) } broadcast_req = self.broadcast_stream.next() => { @@ -306,8 +306,11 @@ where /// Runs the Connection handler logic, this should be put in a separate task. /// /// `eager_protocol_messages` are protocol messages that we received during a handshake. - pub async fn run(mut self, mut stream: Str, eager_protocol_messages: Vec) - where + pub(crate) async fn run( + mut self, + mut stream: Str, + eager_protocol_messages: Vec, + ) where Str: FusedStream> + Unpin, { tracing::debug!( @@ -348,6 +351,7 @@ where /// Shutdowns the connection, flushing pending requests and setting the error slot, if it hasn't been /// set already. + #[expect(clippy::significant_drop_tightening)] fn shutdown(mut self, err: PeerError) { tracing::debug!("Connection task shutting down: {}", err); @@ -362,11 +366,11 @@ where if let State::WaitingForResponse { tx, .. } = std::mem::replace(&mut self.state, State::WaitingForRequest) { - let _ = tx.send(Err(err_str.clone().into())); + let _unused = tx.send(Err(err_str.clone().into())); } while let Ok(req) = client_rx.try_recv() { - let _ = req.response_channel.send(Err(err_str.clone().into())); + let _unused = req.response_channel.send(Err(err_str.clone().into())); } self.connection_guard.connection_closed(); diff --git a/p2p/p2p-core/src/client/connector.rs b/p2p/p2p-core/src/client/connector.rs index d937165..3c4a52e 100644 --- a/p2p/p2p-core/src/client/connector.rs +++ b/p2p/p2p-core/src/client/connector.rs @@ -40,7 +40,7 @@ impl Connector { /// Create a new connector from a handshaker. - pub fn new(handshaker: HandShaker) -> Self { + pub const fn new(handshaker: HandShaker) -> Self { Self { handshaker } } } diff --git a/p2p/p2p-core/src/client/handshaker.rs b/p2p/p2p-core/src/client/handshaker.rs index 67a58d4..46b63e4 100644 --- a/p2p/p2p-core/src/client/handshaker.rs +++ b/p2p/p2p-core/src/client/handshaker.rs @@ -113,7 +113,7 @@ impl HandShaker { /// Creates a new handshaker. - fn new( + const fn new( address_book: AdrBook, peer_sync_svc: PSync, core_sync_svc: CSync, @@ -226,7 +226,8 @@ pub async fn ping(addr: N::Addr) -> Result Err(BucketError::IO(std::io::Error::new( std::io::ErrorKind::ConnectionAborted, "The peer stream returned None", - )))? + )) + .into()) } /// This function completes a handshake with the requested peer. @@ -403,7 +404,10 @@ where break 'check_out_addr None; }; - // u32 does not make sense as a port so just truncate it. + #[expect( + clippy::cast_possible_truncation, + reason = "u32 does not make sense as a port so just truncate it." + )] outbound_address.set_port(peer_node_data.my_port as u16); let Ok(Ok(ping_peer_id)) = timeout( @@ -508,7 +512,7 @@ where info.id, info.handle.clone(), connection_tx.clone(), - semaphore.clone(), + Arc::clone(&semaphore), address_book, core_sync_svc, peer_sync_svc, @@ -671,7 +675,7 @@ async fn wait_for_message( _ => { return Err(HandshakeError::PeerSentInvalidMessage( "Peer sent an admin request before responding to the handshake", - )) + )); } } } @@ -686,16 +690,17 @@ async fn wait_for_message( )); } - _ => Err(HandshakeError::PeerSentInvalidMessage( + Message::Response(_) => Err(HandshakeError::PeerSentInvalidMessage( "Peer sent an incorrect message", )), - }? + }?; } Err(BucketError::IO(std::io::Error::new( std::io::ErrorKind::ConnectionAborted, "The peer stream returned None", - )))? + )) + .into()) } /// Sends a [`AdminResponseMessage::SupportFlags`] down the peer sink. diff --git a/p2p/p2p-core/src/client/handshaker/builder.rs b/p2p/p2p-core/src/client/handshaker/builder.rs index a40f396..069811d 100644 --- a/p2p/p2p-core/src/client/handshaker/builder.rs +++ b/p2p/p2p-core/src/client/handshaker/builder.rs @@ -87,14 +87,13 @@ impl where NAdrBook: AddressBook + Clone, { - let HandshakerBuilder { + let Self { core_sync_svc, peer_sync_svc, protocol_request_svc, our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, .. } = self; @@ -106,7 +105,7 @@ impl our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, + _zone: PhantomData, } } @@ -130,14 +129,13 @@ impl where NCSync: CoreSyncSvc + Clone, { - let HandshakerBuilder { + let Self { address_book, peer_sync_svc, protocol_request_svc, our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, .. } = self; @@ -149,7 +147,7 @@ impl our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, + _zone: PhantomData, } } @@ -167,14 +165,13 @@ impl where NPSync: PeerSyncSvc + Clone, { - let HandshakerBuilder { + let Self { address_book, core_sync_svc, protocol_request_svc, our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, .. } = self; @@ -186,7 +183,7 @@ impl our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, + _zone: PhantomData, } } @@ -204,14 +201,13 @@ impl where NProtoHdlr: ProtocolRequestHandler + Clone, { - let HandshakerBuilder { + let Self { address_book, core_sync_svc, peer_sync_svc, our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, .. } = self; @@ -223,7 +219,7 @@ impl our_basic_node_data, broadcast_stream_maker, connection_parent_span, - _zone, + _zone: PhantomData, } } @@ -242,14 +238,13 @@ impl BrdcstStrm: Stream + Send + 'static, NBrdcstStrmMkr: Fn(InternalPeerID) -> BrdcstStrm + Clone + Send + 'static, { - let HandshakerBuilder { + let Self { address_book, core_sync_svc, peer_sync_svc, protocol_request_svc, our_basic_node_data, connection_parent_span, - _zone, .. } = self; @@ -261,7 +256,7 @@ impl our_basic_node_data, broadcast_stream_maker: new_broadcast_stream_maker, connection_parent_span, - _zone, + _zone: PhantomData, } } @@ -270,6 +265,7 @@ impl /// ## Default Connection Parent Span /// /// The default connection span will be [`Span::none`]. + #[must_use] pub fn with_connection_parent_span(self, connection_parent_span: Span) -> Self { Self { connection_parent_span: Some(connection_parent_span), diff --git a/p2p/p2p-core/src/client/handshaker/builder/dummy.rs b/p2p/p2p-core/src/client/handshaker/builder/dummy.rs index ae97cdc..e3c4335 100644 --- a/p2p/p2p-core/src/client/handshaker/builder/dummy.rs +++ b/p2p/p2p-core/src/client/handshaker/builder/dummy.rs @@ -42,8 +42,8 @@ pub struct DummyCoreSyncSvc(CoreSyncData); impl DummyCoreSyncSvc { /// Returns a [`DummyCoreSyncSvc`] that will just return the mainnet genesis [`CoreSyncData`]. - pub fn static_mainnet_genesis() -> DummyCoreSyncSvc { - DummyCoreSyncSvc(CoreSyncData { + pub const fn static_mainnet_genesis() -> Self { + Self(CoreSyncData { cumulative_difficulty: 1, cumulative_difficulty_top64: 0, current_height: 1, @@ -56,8 +56,8 @@ impl DummyCoreSyncSvc { } /// Returns a [`DummyCoreSyncSvc`] that will just return the testnet genesis [`CoreSyncData`]. - pub fn static_testnet_genesis() -> DummyCoreSyncSvc { - DummyCoreSyncSvc(CoreSyncData { + pub const fn static_testnet_genesis() -> Self { + Self(CoreSyncData { cumulative_difficulty: 1, cumulative_difficulty_top64: 0, current_height: 1, @@ -70,8 +70,8 @@ impl DummyCoreSyncSvc { } /// Returns a [`DummyCoreSyncSvc`] that will just return the stagenet genesis [`CoreSyncData`]. - pub fn static_stagenet_genesis() -> DummyCoreSyncSvc { - DummyCoreSyncSvc(CoreSyncData { + pub const fn static_stagenet_genesis() -> Self { + Self(CoreSyncData { cumulative_difficulty: 1, cumulative_difficulty_top64: 0, current_height: 1, @@ -84,8 +84,8 @@ impl DummyCoreSyncSvc { } /// Returns a [`DummyCoreSyncSvc`] that will return the provided [`CoreSyncData`]. - pub fn static_custom(data: CoreSyncData) -> DummyCoreSyncSvc { - DummyCoreSyncSvc(data) + pub const fn static_custom(data: CoreSyncData) -> Self { + Self(data) } } diff --git a/p2p/p2p-core/src/client/request_handler.rs b/p2p/p2p-core/src/client/request_handler.rs index 284f954..7059eed 100644 --- a/p2p/p2p-core/src/client/request_handler.rs +++ b/p2p/p2p-core/src/client/request_handler.rs @@ -46,7 +46,7 @@ pub(crate) struct PeerRequestHandler { pub peer_info: PeerInformation, } -impl PeerRequestHandler +impl PeerRequestHandler where Z: NetworkZone, A: AddressBook, @@ -55,7 +55,7 @@ where PR: ProtocolRequestHandler, { /// Handles an incoming [`PeerRequest`] to our node. - pub async fn handle_peer_request( + pub(crate) async fn handle_peer_request( &mut self, req: PeerRequest, ) -> Result { diff --git a/p2p/p2p-core/src/client/timeout_monitor.rs b/p2p/p2p-core/src/client/timeout_monitor.rs index 5228ede..6dbb4a2 100644 --- a/p2p/p2p-core/src/client/timeout_monitor.rs +++ b/p2p/p2p-core/src/client/timeout_monitor.rs @@ -1,6 +1,6 @@ //! Timeout Monitor //! -//! This module holds the task that sends periodic [TimedSync](PeerRequest::TimedSync) requests to a peer to make +//! This module holds the task that sends periodic [`TimedSync`](PeerRequest::TimedSync) requests to a peer to make //! sure the connection is still active. use std::sync::Arc; @@ -64,7 +64,7 @@ where return Ok(()); } - let Ok(permit) = semaphore.clone().try_acquire_owned() else { + let Ok(permit) = Arc::clone(&semaphore).try_acquire_owned() else { // If we can't get a permit the connection is currently waiting for a response, so no need to // do a timed sync. continue; diff --git a/p2p/p2p-core/src/error.rs b/p2p/p2p-core/src/error.rs index 65303ad..d0de923 100644 --- a/p2p/p2p-core/src/error.rs +++ b/p2p/p2p-core/src/error.rs @@ -4,7 +4,7 @@ pub struct SharedError(Arc>); impl Clone for SharedError { fn clone(&self) -> Self { - Self(self.0.clone()) + Self(Arc::clone(&self.0)) } } diff --git a/p2p/p2p-core/src/handles.rs b/p2p/p2p-core/src/handles.rs index da47b65..30123f7 100644 --- a/p2p/p2p-core/src/handles.rs +++ b/p2p/p2p-core/src/handles.rs @@ -18,11 +18,12 @@ pub struct HandleBuilder { impl HandleBuilder { /// Create a new builder. - pub fn new() -> Self { + pub const fn new() -> Self { Self { permit: None } } /// Sets the permit for this connection. + #[must_use] pub fn with_permit(mut self, permit: Option) -> Self { self.permit = permit; self @@ -40,7 +41,7 @@ impl HandleBuilder { _permit: self.permit, }, ConnectionHandle { - token: token.clone(), + token, ban: Arc::new(OnceLock::new()), }, ) @@ -66,13 +67,13 @@ impl ConnectionGuard { /// /// This will be called on [`Drop::drop`]. pub fn connection_closed(&self) { - self.token.cancel() + self.token.cancel(); } } impl Drop for ConnectionGuard { fn drop(&mut self) { - self.token.cancel() + self.token.cancel(); } } @@ -90,6 +91,7 @@ impl ConnectionHandle { } /// Bans the peer for the given `duration`. pub fn ban_peer(&self, duration: Duration) { + #[expect(clippy::let_underscore_must_use, reason = "TODO: handle error")] let _ = self.ban.set(BanPeer(duration)); self.token.cancel(); } @@ -103,6 +105,6 @@ impl ConnectionHandle { } /// Sends the signal to the connection task to disconnect. pub fn send_close_signal(&self) { - self.token.cancel() + self.token.cancel(); } } diff --git a/p2p/p2p-core/src/lib.rs b/p2p/p2p-core/src/lib.rs index 83cc4d2..54b40c6 100644 --- a/p2p/p2p-core/src/lib.rs +++ b/p2p/p2p-core/src/lib.rs @@ -6,7 +6,7 @@ //! //! # Network Zones //! -//! This crate abstracts over network zones, Tor/I2p/clearnet with the [NetworkZone] trait. Currently only clearnet is implemented: [ClearNet]. +//! This crate abstracts over network zones, Tor/I2p/clearnet with the [`NetworkZone`] trait. Currently only clearnet is implemented: [`ClearNet`]. //! //! # Usage //! @@ -65,6 +65,9 @@ use cuprate_wire::{ NetworkAddress, }; +#[cfg(test)] +mod tests; + pub mod client; mod constants; pub mod error; @@ -102,7 +105,7 @@ pub trait NetZoneAddress: + Unpin + 'static { - /// Cuprate needs to be able to ban peers by IP addresses and not just by SocketAddr as + /// Cuprate needs to be able to ban peers by IP addresses and not just by `SocketAddr` as /// that include the port, to be able to facilitate this network addresses must have a ban ID /// which for hidden services could just be the address it self but for clear net addresses will /// be the IP address. diff --git a/p2p/p2p-core/src/network_zones/clear.rs b/p2p/p2p-core/src/network_zones/clear.rs index 192e363..2ca9448 100644 --- a/p2p/p2p-core/src/network_zones/clear.rs +++ b/p2p/p2p-core/src/network_zones/clear.rs @@ -19,7 +19,7 @@ impl NetZoneAddress for SocketAddr { type BanID = IpAddr; fn set_port(&mut self, port: u16) { - SocketAddr::set_port(self, port) + Self::set_port(self, port); } fn ban_id(&self) -> Self::BanID { diff --git a/p2p/p2p-core/src/protocol.rs b/p2p/p2p-core/src/protocol.rs index 5e4f4d7..7d8d431 100644 --- a/p2p/p2p-core/src/protocol.rs +++ b/p2p/p2p-core/src/protocol.rs @@ -8,7 +8,7 @@ //! //! Here is every P2P request/response. //! -//! *note admin messages are already request/response so "Handshake" is actually made of a HandshakeRequest & HandshakeResponse +//! *note admin messages are already request/response so "Handshake" is actually made of a `HandshakeRequest` & `HandshakeResponse` //! //! ```md //! Admin: @@ -78,15 +78,15 @@ pub enum PeerRequest { } impl PeerRequest { - pub fn id(&self) -> MessageID { + pub const fn id(&self) -> MessageID { match self { - PeerRequest::Admin(admin_req) => match admin_req { + Self::Admin(admin_req) => match admin_req { AdminRequestMessage::Handshake(_) => MessageID::Handshake, AdminRequestMessage::TimedSync(_) => MessageID::TimedSync, AdminRequestMessage::Ping => MessageID::Ping, AdminRequestMessage::SupportFlags => MessageID::SupportFlags, }, - PeerRequest::Protocol(protocol_request) => match protocol_request { + Self::Protocol(protocol_request) => match protocol_request { ProtocolRequest::GetObjects(_) => MessageID::GetObjects, ProtocolRequest::GetChain(_) => MessageID::GetChain, ProtocolRequest::FluffyMissingTxs(_) => MessageID::FluffyMissingTxs, @@ -98,10 +98,10 @@ impl PeerRequest { } } - pub fn needs_response(&self) -> bool { + pub const fn needs_response(&self) -> bool { !matches!( self, - PeerRequest::Protocol( + Self::Protocol( ProtocolRequest::NewBlock(_) | ProtocolRequest::NewFluffyBlock(_) | ProtocolRequest::NewTransactions(_) @@ -126,15 +126,15 @@ pub enum PeerResponse { } impl PeerResponse { - pub fn id(&self) -> Option { + pub const fn id(&self) -> Option { Some(match self { - PeerResponse::Admin(admin_res) => match admin_res { + Self::Admin(admin_res) => match admin_res { AdminResponseMessage::Handshake(_) => MessageID::Handshake, AdminResponseMessage::TimedSync(_) => MessageID::TimedSync, AdminResponseMessage::Ping(_) => MessageID::Ping, AdminResponseMessage::SupportFlags(_) => MessageID::SupportFlags, }, - PeerResponse::Protocol(protocol_res) => match protocol_res { + Self::Protocol(protocol_res) => match protocol_res { ProtocolResponse::GetObjects(_) => MessageID::GetObjects, ProtocolResponse::GetChain(_) => MessageID::GetChain, ProtocolResponse::NewFluffyBlock(_) => MessageID::NewBlock, diff --git a/p2p/p2p-core/src/protocol/try_from.rs b/p2p/p2p-core/src/protocol/try_from.rs index 8a0b67d..0c81a52 100644 --- a/p2p/p2p-core/src/protocol/try_from.rs +++ b/p2p/p2p-core/src/protocol/try_from.rs @@ -11,15 +11,15 @@ pub struct MessageConversionError; impl From for ProtocolMessage { fn from(value: ProtocolRequest) -> Self { match value { - ProtocolRequest::GetObjects(val) => ProtocolMessage::GetObjectsRequest(val), - ProtocolRequest::GetChain(val) => ProtocolMessage::ChainRequest(val), + ProtocolRequest::GetObjects(val) => Self::GetObjectsRequest(val), + ProtocolRequest::GetChain(val) => Self::ChainRequest(val), ProtocolRequest::FluffyMissingTxs(val) => { - ProtocolMessage::FluffyMissingTransactionsRequest(val) + Self::FluffyMissingTransactionsRequest(val) } - ProtocolRequest::GetTxPoolCompliment(val) => ProtocolMessage::GetTxPoolCompliment(val), - ProtocolRequest::NewBlock(val) => ProtocolMessage::NewBlock(val), - ProtocolRequest::NewFluffyBlock(val) => ProtocolMessage::NewFluffyBlock(val), - ProtocolRequest::NewTransactions(val) => ProtocolMessage::NewTransactions(val), + ProtocolRequest::GetTxPoolCompliment(val) => Self::GetTxPoolCompliment(val), + ProtocolRequest::NewBlock(val) => Self::NewBlock(val), + ProtocolRequest::NewFluffyBlock(val) => Self::NewFluffyBlock(val), + ProtocolRequest::NewTransactions(val) => Self::NewTransactions(val), } } } @@ -29,15 +29,15 @@ impl TryFrom for ProtocolRequest { fn try_from(value: ProtocolMessage) -> Result { Ok(match value { - ProtocolMessage::GetObjectsRequest(val) => ProtocolRequest::GetObjects(val), - ProtocolMessage::ChainRequest(val) => ProtocolRequest::GetChain(val), + ProtocolMessage::GetObjectsRequest(val) => Self::GetObjects(val), + ProtocolMessage::ChainRequest(val) => Self::GetChain(val), ProtocolMessage::FluffyMissingTransactionsRequest(val) => { - ProtocolRequest::FluffyMissingTxs(val) + Self::FluffyMissingTxs(val) } - ProtocolMessage::GetTxPoolCompliment(val) => ProtocolRequest::GetTxPoolCompliment(val), - ProtocolMessage::NewBlock(val) => ProtocolRequest::NewBlock(val), - ProtocolMessage::NewFluffyBlock(val) => ProtocolRequest::NewFluffyBlock(val), - ProtocolMessage::NewTransactions(val) => ProtocolRequest::NewTransactions(val), + ProtocolMessage::GetTxPoolCompliment(val) => Self::GetTxPoolCompliment(val), + ProtocolMessage::NewBlock(val) => Self::NewBlock(val), + ProtocolMessage::NewFluffyBlock(val) => Self::NewFluffyBlock(val), + ProtocolMessage::NewTransactions(val) => Self::NewTransactions(val), ProtocolMessage::GetObjectsResponse(_) | ProtocolMessage::ChainEntryResponse(_) => { return Err(MessageConversionError) } @@ -48,8 +48,8 @@ impl TryFrom for ProtocolRequest { impl From for Message { fn from(value: PeerRequest) -> Self { match value { - PeerRequest::Admin(val) => Message::Request(val), - PeerRequest::Protocol(val) => Message::Protocol(val.into()), + PeerRequest::Admin(val) => Self::Request(val), + PeerRequest::Protocol(val) => Self::Protocol(val.into()), } } } @@ -59,8 +59,8 @@ impl TryFrom for PeerRequest { fn try_from(value: Message) -> Result { match value { - Message::Request(req) => Ok(PeerRequest::Admin(req)), - Message::Protocol(pro) => Ok(PeerRequest::Protocol(pro.try_into()?)), + Message::Request(req) => Ok(Self::Admin(req)), + Message::Protocol(pro) => Ok(Self::Protocol(pro.try_into()?)), Message::Response(_) => Err(MessageConversionError), } } @@ -71,10 +71,10 @@ impl TryFrom for ProtocolMessage { fn try_from(value: ProtocolResponse) -> Result { Ok(match value { - ProtocolResponse::NewTransactions(val) => ProtocolMessage::NewTransactions(val), - ProtocolResponse::NewFluffyBlock(val) => ProtocolMessage::NewFluffyBlock(val), - ProtocolResponse::GetChain(val) => ProtocolMessage::ChainEntryResponse(val), - ProtocolResponse::GetObjects(val) => ProtocolMessage::GetObjectsResponse(val), + ProtocolResponse::NewTransactions(val) => Self::NewTransactions(val), + ProtocolResponse::NewFluffyBlock(val) => Self::NewFluffyBlock(val), + ProtocolResponse::GetChain(val) => Self::ChainEntryResponse(val), + ProtocolResponse::GetObjects(val) => Self::GetObjectsResponse(val), ProtocolResponse::NA => return Err(MessageConversionError), }) } @@ -85,10 +85,10 @@ impl TryFrom for ProtocolResponse { fn try_from(value: ProtocolMessage) -> Result { Ok(match value { - ProtocolMessage::NewTransactions(val) => ProtocolResponse::NewTransactions(val), - ProtocolMessage::NewFluffyBlock(val) => ProtocolResponse::NewFluffyBlock(val), - ProtocolMessage::ChainEntryResponse(val) => ProtocolResponse::GetChain(val), - ProtocolMessage::GetObjectsResponse(val) => ProtocolResponse::GetObjects(val), + ProtocolMessage::NewTransactions(val) => Self::NewTransactions(val), + ProtocolMessage::NewFluffyBlock(val) => Self::NewFluffyBlock(val), + ProtocolMessage::ChainEntryResponse(val) => Self::GetChain(val), + ProtocolMessage::GetObjectsResponse(val) => Self::GetObjects(val), ProtocolMessage::ChainRequest(_) | ProtocolMessage::FluffyMissingTransactionsRequest(_) | ProtocolMessage::GetObjectsRequest(_) @@ -103,8 +103,8 @@ impl TryFrom for PeerResponse { fn try_from(value: Message) -> Result { match value { - Message::Response(res) => Ok(PeerResponse::Admin(res)), - Message::Protocol(pro) => Ok(PeerResponse::Protocol(pro.try_into()?)), + Message::Response(res) => Ok(Self::Admin(res)), + Message::Protocol(pro) => Ok(Self::Protocol(pro.try_into()?)), Message::Request(_) => Err(MessageConversionError), } } @@ -115,8 +115,8 @@ impl TryFrom for Message { fn try_from(value: PeerResponse) -> Result { Ok(match value { - PeerResponse::Admin(val) => Message::Response(val), - PeerResponse::Protocol(val) => Message::Protocol(val.try_into()?), + PeerResponse::Admin(val) => Self::Response(val), + PeerResponse::Protocol(val) => Self::Protocol(val.try_into()?), }) } } diff --git a/p2p/p2p-core/src/services.rs b/p2p/p2p-core/src/services.rs index 6d66cfa..ba87684 100644 --- a/p2p/p2p-core/src/services.rs +++ b/p2p/p2p-core/src/services.rs @@ -52,7 +52,7 @@ pub struct ZoneSpecificPeerListEntryBase { pub rpc_credits_per_hash: u32, } -impl From> for cuprate_wire::PeerListEntryBase { +impl From> for PeerListEntryBase { fn from(value: ZoneSpecificPeerListEntryBase) -> Self { Self { adr: value.adr.into(), @@ -74,9 +74,7 @@ pub enum PeerListConversionError { PruningSeed(#[from] PruningError), } -impl TryFrom - for ZoneSpecificPeerListEntryBase -{ +impl TryFrom for ZoneSpecificPeerListEntryBase { type Error = PeerListConversionError; fn try_from(value: PeerListEntryBase) -> Result { diff --git a/p2p/p2p-core/src/tests.rs b/p2p/p2p-core/src/tests.rs new file mode 100644 index 0000000..4d96c55 --- /dev/null +++ b/p2p/p2p-core/src/tests.rs @@ -0,0 +1,4 @@ +mod fragmented_handshake; +mod handles; +mod handshake; +mod sending_receiving; diff --git a/p2p/p2p-core/tests/fragmented_handshake.rs b/p2p/p2p-core/src/tests/fragmented_handshake.rs similarity index 99% rename from p2p/p2p-core/tests/fragmented_handshake.rs rename to p2p/p2p-core/src/tests/fragmented_handshake.rs index c19a2a6..6058542 100644 --- a/p2p/p2p-core/tests/fragmented_handshake.rs +++ b/p2p/p2p-core/src/tests/fragmented_handshake.rs @@ -1,4 +1,5 @@ //! This file contains a test for a handshake with monerod but uses fragmented messages. + use std::{ net::SocketAddr, pin::Pin, @@ -21,20 +22,20 @@ use tokio_util::{ use tower::{Service, ServiceExt}; use cuprate_helper::network::Network; -use cuprate_p2p_core::{ - client::{ - handshaker::HandshakerBuilder, ConnectRequest, Connector, DoHandshakeRequest, - InternalPeerID, - }, - ClearNetServerCfg, ConnectionDirection, NetworkZone, -}; +use cuprate_test_utils::monerod::monerod; use cuprate_wire::{ common::PeerSupportFlags, levin::{message::make_fragmented_messages, LevinMessage, Protocol}, BasicNodeData, Message, MoneroWireCodec, }; -use cuprate_test_utils::monerod::monerod; +use crate::{ + client::{ + handshaker::HandshakerBuilder, ConnectRequest, Connector, DoHandshakeRequest, + InternalPeerID, + }, + ClearNetServerCfg, ConnectionDirection, NetworkZone, +}; /// A network zone equal to clear net where every message sent is turned into a fragmented message. /// Does not support sending fragmented or dummy messages manually. @@ -184,7 +185,7 @@ async fn fragmented_handshake_monerod_to_cuprate() { let next_connection_fut = timeout(Duration::from_secs(30), listener.next()); if let Some(Ok((addr, stream, sink))) = next_connection_fut.await.unwrap() { - let _ = handshaker + let _unused = handshaker .ready() .await .unwrap() diff --git a/p2p/p2p-core/tests/handles.rs b/p2p/p2p-core/src/tests/handles.rs similarity index 97% rename from p2p/p2p-core/tests/handles.rs rename to p2p/p2p-core/src/tests/handles.rs index 47d70b0..3f247b1 100644 --- a/p2p/p2p-core/tests/handles.rs +++ b/p2p/p2p-core/src/tests/handles.rs @@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration}; use tokio::sync::Semaphore; -use cuprate_p2p_core::handles::HandleBuilder; +use crate::handles::HandleBuilder; #[test] fn send_ban_signal() { diff --git a/p2p/p2p-core/tests/handshake.rs b/p2p/p2p-core/src/tests/handshake.rs similarity index 98% rename from p2p/p2p-core/tests/handshake.rs rename to p2p/p2p-core/src/tests/handshake.rs index 5ce6153..599f33b 100644 --- a/p2p/p2p-core/tests/handshake.rs +++ b/p2p/p2p-core/src/tests/handshake.rs @@ -9,9 +9,13 @@ use tokio_util::codec::{FramedRead, FramedWrite}; use tower::{Service, ServiceExt}; use cuprate_helper::network::Network; +use cuprate_test_utils::{ + monerod::monerod, + test_netzone::{TestNetZone, TestNetZoneAddr}, +}; use cuprate_wire::{common::PeerSupportFlags, BasicNodeData, MoneroWireCodec}; -use cuprate_p2p_core::{ +use crate::{ client::{ handshaker::HandshakerBuilder, ConnectRequest, Connector, DoHandshakeRequest, InternalPeerID, @@ -19,11 +23,6 @@ use cuprate_p2p_core::{ ClearNet, ClearNetServerCfg, ConnectionDirection, NetworkZone, }; -use cuprate_test_utils::{ - monerod::monerod, - test_netzone::{TestNetZone, TestNetZoneAddr}, -}; - #[tokio::test] async fn handshake_cuprate_to_cuprate() { // Tests a Cuprate <-> Cuprate handshake by making 2 handshake services and making them talk to @@ -147,7 +146,7 @@ async fn handshake_monerod_to_cuprate() { let next_connection_fut = timeout(Duration::from_secs(30), listener.next()); if let Some(Ok((addr, stream, sink))) = next_connection_fut.await.unwrap() { - let _ = handshaker + let _unused = handshaker .ready() .await .unwrap() diff --git a/p2p/p2p-core/tests/sending_receiving.rs b/p2p/p2p-core/src/tests/sending_receiving.rs similarity index 98% rename from p2p/p2p-core/tests/sending_receiving.rs rename to p2p/p2p-core/src/tests/sending_receiving.rs index e035daf..f820d98 100644 --- a/p2p/p2p-core/tests/sending_receiving.rs +++ b/p2p/p2p-core/src/tests/sending_receiving.rs @@ -1,16 +1,15 @@ use tower::{Service, ServiceExt}; use cuprate_helper::network::Network; +use cuprate_test_utils::monerod::monerod; use cuprate_wire::{common::PeerSupportFlags, protocol::GetObjectsRequest, BasicNodeData}; -use cuprate_p2p_core::{ +use crate::{ client::{handshaker::HandshakerBuilder, ConnectRequest, Connector}, protocol::{PeerRequest, PeerResponse}, ClearNet, ProtocolRequest, ProtocolResponse, }; -use cuprate_test_utils::monerod::monerod; - #[tokio::test] async fn get_single_block_from_monerod() { let monerod = monerod(["--out-peers=0"]).await;