diff --git a/.cargo/config.toml b/.cargo/config.toml index b98b715c9ab..e55adcc9ed1 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,3 +1,3 @@ [alias] # Temporary solution to have clippy config in a single place until https://github.com/rust-lang/rust-clippy/blob/master/doc/roadmap-2021.md#lintstoml-configuration is shipped. -custom-clippy = "clippy --workspace --all-features --all-targets -- -A clippy::type_complexity -A clippy::pedantic -W clippy::used_underscore_binding -D warnings" +custom-clippy = "clippy --workspace --all-features --all-targets -- -A clippy::type_complexity -A clippy::pedantic -W clippy::used_underscore_binding -W unreachable_pub -D warnings" diff --git a/core/src/lib.rs b/core/src/lib.rs index 84e39fdafb1..ba531c919f2 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -38,6 +38,7 @@ #![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))] mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); pub use self::{ envelope_proto::*, peer_record_proto::mod_PeerRecord::*, peer_record_proto::PeerRecord, diff --git a/core/src/signed_envelope.rs b/core/src/signed_envelope.rs index a9d7ecd5208..a50146f87d1 100644 --- a/core/src/signed_envelope.rs +++ b/core/src/signed_envelope.rs @@ -182,7 +182,7 @@ mod tests { use super::*; #[test] - pub fn test_roundtrip() { + fn test_roundtrip() { let kp = Keypair::generate_ed25519(); let payload = "some payload".as_bytes(); let domain_separation = "domain separation".to_string(); diff --git a/core/src/transport/boxed.rs b/core/src/transport/boxed.rs index b2560c4a662..a55e4db8466 100644 --- a/core/src/transport/boxed.rs +++ b/core/src/transport/boxed.rs @@ -29,7 +29,7 @@ use std::{ }; /// Creates a new [`Boxed`] transport from the given transport. -pub fn boxed(transport: T) -> Boxed +pub(crate) fn boxed(transport: T) -> Boxed where T: Transport + Send + Unpin + 'static, T::Error: Send + Sync, diff --git a/core/src/upgrade/apply.rs b/core/src/upgrade/apply.rs index 76a48baed04..0b4b4d6b992 100644 --- a/core/src/upgrade/apply.rs +++ b/core/src/upgrade/apply.rs @@ -25,7 +25,7 @@ use log::debug; use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture}; use std::{iter, mem, pin::Pin, task::Context, task::Poll}; -pub use multistream_select::Version; +pub(crate) use multistream_select::Version; use smallvec::SmallVec; use std::fmt; @@ -275,7 +275,7 @@ impl AsRef<[u8]> for NameWrap { } /// Wrapper for printing a [`ProtocolName`] that is expected to be mostly ASCII -pub(crate) struct DisplayProtocolName(pub N); +pub(crate) struct DisplayProtocolName(pub(crate) N); impl fmt::Display for DisplayProtocolName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/examples/file-sharing/src/network.rs b/examples/file-sharing/src/network.rs index 0f9ff32863e..62496172e4a 100644 --- a/examples/file-sharing/src/network.rs +++ b/examples/file-sharing/src/network.rs @@ -33,7 +33,7 @@ use std::iter; /// - The network event stream, e.g. for incoming requests. /// /// - The network task driving the network itself. -pub async fn new( +pub(crate) async fn new( secret_key_seed: Option, ) -> Result<(Client, impl Stream, EventLoop), Box> { // Create a public/private key pair, either random or based on a seed. @@ -82,13 +82,16 @@ pub async fn new( } #[derive(Clone)] -pub struct Client { +pub(crate) struct Client { sender: mpsc::Sender, } impl Client { /// Listen for incoming connections on the given address. - pub async fn start_listening(&mut self, addr: Multiaddr) -> Result<(), Box> { + pub(crate) async fn start_listening( + &mut self, + addr: Multiaddr, + ) -> Result<(), Box> { let (sender, receiver) = oneshot::channel(); self.sender .send(Command::StartListening { addr, sender }) @@ -98,7 +101,7 @@ impl Client { } /// Dial the given peer at the given address. - pub async fn dial( + pub(crate) async fn dial( &mut self, peer_id: PeerId, peer_addr: Multiaddr, @@ -116,7 +119,7 @@ impl Client { } /// Advertise the local node as the provider of the given file on the DHT. - pub async fn start_providing(&mut self, file_name: String) { + pub(crate) async fn start_providing(&mut self, file_name: String) { let (sender, receiver) = oneshot::channel(); self.sender .send(Command::StartProviding { file_name, sender }) @@ -126,7 +129,7 @@ impl Client { } /// Find the providers for the given file on the DHT. - pub async fn get_providers(&mut self, file_name: String) -> HashSet { + pub(crate) async fn get_providers(&mut self, file_name: String) -> HashSet { let (sender, receiver) = oneshot::channel(); self.sender .send(Command::GetProviders { file_name, sender }) @@ -136,7 +139,7 @@ impl Client { } /// Request the content of the given file from the given peer. - pub async fn request_file( + pub(crate) async fn request_file( &mut self, peer: PeerId, file_name: String, @@ -154,7 +157,11 @@ impl Client { } /// Respond with the provided file content to the given request. - pub async fn respond_file(&mut self, file: Vec, channel: ResponseChannel) { + pub(crate) async fn respond_file( + &mut self, + file: Vec, + channel: ResponseChannel, + ) { self.sender .send(Command::RespondFile { file, channel }) .await @@ -162,7 +169,7 @@ impl Client { } } -pub struct EventLoop { +pub(crate) struct EventLoop { swarm: Swarm, command_receiver: mpsc::Receiver, event_sender: mpsc::Sender, @@ -190,7 +197,7 @@ impl EventLoop { } } - pub async fn run(mut self) { + pub(crate) async fn run(mut self) { loop { futures::select! { event = self.swarm.next() => self.handle_event(event.expect("Swarm stream to be infinite.")).await , @@ -452,7 +459,7 @@ enum Command { } #[derive(Debug)] -pub enum Event { +pub(crate) enum Event { InboundRequest { request: String, channel: ResponseChannel, @@ -468,8 +475,7 @@ struct FileExchangeCodec(); #[derive(Debug, Clone, PartialEq, Eq)] struct FileRequest(String); #[derive(Debug, Clone, PartialEq, Eq)] -pub struct FileResponse(Vec); - +pub(crate) struct FileResponse(Vec); impl ProtocolName for FileExchangeProtocol { fn protocol_name(&self) -> &[u8] { "/file-exchange/1".as_bytes() diff --git a/examples/metrics/src/http_service.rs b/examples/metrics/src/http_service.rs index d1baf946d77..84102c2b558 100644 --- a/examples/metrics/src/http_service.rs +++ b/examples/metrics/src/http_service.rs @@ -31,7 +31,7 @@ use std::task::{Context, Poll}; const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text;charset=utf-8;version=1.0.0"; -pub async fn metrics_server(registry: Registry) -> Result<(), std::io::Error> { +pub(crate) async fn metrics_server(registry: Registry) -> Result<(), std::io::Error> { // Serve on localhost. let addr = ([127, 0, 0, 1], 0).into(); @@ -47,7 +47,7 @@ pub async fn metrics_server(registry: Registry) -> Result<(), std::io::Error> { }) } -pub struct MetricService { +pub(crate) struct MetricService { reg: Arc>, } @@ -102,12 +102,12 @@ impl Service> for MetricService { } } -pub struct MakeMetricService { +pub(crate) struct MakeMetricService { reg: SharedRegistry, } impl MakeMetricService { - pub fn new(registry: Registry) -> MakeMetricService { + pub(crate) fn new(registry: Registry) -> MakeMetricService { MakeMetricService { reg: Arc::new(Mutex::new(registry)), } diff --git a/identity/src/lib.rs b/identity/src/lib.rs index 332b3b08763..ea9ced51622 100644 --- a/identity/src/lib.rs +++ b/identity/src/lib.rs @@ -42,8 +42,9 @@ feature = "rsa" ))] mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::keys_proto::*; + pub(crate) use self::keys_proto::*; } #[cfg(feature = "ecdsa")] diff --git a/identity/src/rsa.rs b/identity/src/rsa.rs index b598b093b7e..e4e16af206c 100644 --- a/identity/src/rsa.rs +++ b/identity/src/rsa.rs @@ -159,12 +159,12 @@ struct Asn1RawOid<'a> { impl<'a> Asn1RawOid<'a> { /// The underlying OID as byte literal. - pub fn oid(&self) -> &[u8] { + pub(crate) fn oid(&self) -> &[u8] { self.object.value() } /// Writes an OID raw `value` as DER-object to `sink`. - pub fn write(value: &[u8], sink: &mut S) -> Result<(), Asn1DerError> { + pub(crate) fn write(value: &[u8], sink: &mut S) -> Result<(), Asn1DerError> { DerObject::write(Self::TAG, value.len(), &mut value.iter(), sink) } } diff --git a/misc/keygen/src/config.rs b/misc/keygen/src/config.rs index 30ec8f8324e..e6c563b3c32 100644 --- a/misc/keygen/src/config.rs +++ b/misc/keygen/src/config.rs @@ -8,16 +8,19 @@ use libp2p_identity::PeerId; #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] -pub struct Config { - pub identity: Identity, +pub(crate) struct Config { + pub(crate) identity: Identity, } impl Config { - pub fn from_file(path: &Path) -> Result> { + pub(crate) fn from_file(path: &Path) -> Result> { Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) } - pub fn from_key_material(peer_id: PeerId, keypair: &Keypair) -> Result> { + pub(crate) fn from_key_material( + peer_id: PeerId, + keypair: &Keypair, + ) -> Result> { let priv_key = BASE64_STANDARD.encode(keypair.to_protobuf_encoding()?); let peer_id = peer_id.to_base58(); Ok(Self { @@ -28,10 +31,10 @@ impl Config { #[derive(Clone, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] -pub struct Identity { +pub(crate) struct Identity { #[serde(rename = "PeerID")] - pub peer_id: String, - pub priv_key: String, + pub(crate) peer_id: String, + pub(crate) priv_key: String, } impl zeroize::Zeroize for Config { diff --git a/misc/metrics/src/dcutr.rs b/misc/metrics/src/dcutr.rs index d2f0c63961c..18ee8a14d1e 100644 --- a/misc/metrics/src/dcutr.rs +++ b/misc/metrics/src/dcutr.rs @@ -23,12 +23,12 @@ use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::family::Family; use prometheus_client::registry::Registry; -pub struct Metrics { +pub(crate) struct Metrics { events: Family, } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("dcutr"); let events = Family::default(); diff --git a/misc/metrics/src/gossipsub.rs b/misc/metrics/src/gossipsub.rs index b00671ac636..2d90b92fbc6 100644 --- a/misc/metrics/src/gossipsub.rs +++ b/misc/metrics/src/gossipsub.rs @@ -21,12 +21,12 @@ use prometheus_client::metrics::counter::Counter; use prometheus_client::registry::Registry; -pub struct Metrics { +pub(crate) struct Metrics { messages: Counter, } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("gossipsub"); let messages = Counter::default(); diff --git a/misc/metrics/src/identify.rs b/misc/metrics/src/identify.rs index e93620b4fef..91f7d78722d 100644 --- a/misc/metrics/src/identify.rs +++ b/misc/metrics/src/identify.rs @@ -30,7 +30,7 @@ use std::collections::HashMap; use std::iter; use std::sync::{Arc, Mutex}; -pub struct Metrics { +pub(crate) struct Metrics { protocols: Protocols, error: Counter, pushed: Counter, @@ -42,7 +42,7 @@ pub struct Metrics { } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("identify"); let protocols = Protocols::default(); diff --git a/misc/metrics/src/kad.rs b/misc/metrics/src/kad.rs index af56eb08491..bc83146f937 100644 --- a/misc/metrics/src/kad.rs +++ b/misc/metrics/src/kad.rs @@ -24,7 +24,7 @@ use prometheus_client::metrics::family::Family; use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; use prometheus_client::registry::{Registry, Unit}; -pub struct Metrics { +pub(crate) struct Metrics { query_result_get_record_ok: Counter, query_result_get_record_error: Family, @@ -45,7 +45,7 @@ pub struct Metrics { } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("kad"); let query_result_get_record_ok = Counter::default(); diff --git a/misc/metrics/src/ping.rs b/misc/metrics/src/ping.rs index 0e7a7f26320..195cb302675 100644 --- a/misc/metrics/src/ping.rs +++ b/misc/metrics/src/ping.rs @@ -52,14 +52,14 @@ enum Failure { Other, } -pub struct Metrics { +pub(crate) struct Metrics { rtt: Histogram, failure: Family, pong_received: Counter, } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("ping"); let rtt = Histogram::new(exponential_buckets(0.001, 2.0, 12)); diff --git a/misc/metrics/src/protocol_stack.rs b/misc/metrics/src/protocol_stack.rs index 1715b51f034..59e8c0bfa6a 100644 --- a/misc/metrics/src/protocol_stack.rs +++ b/misc/metrics/src/protocol_stack.rs @@ -1,6 +1,6 @@ use libp2p_core::multiaddr::Multiaddr; -pub fn as_string(ma: &Multiaddr) -> String { +pub(crate) fn as_string(ma: &Multiaddr) -> String { let len = ma .protocol_stack() .fold(0, |acc, proto| acc + proto.len() + 1); diff --git a/misc/metrics/src/relay.rs b/misc/metrics/src/relay.rs index 479a518eeaf..4b8f63588fe 100644 --- a/misc/metrics/src/relay.rs +++ b/misc/metrics/src/relay.rs @@ -23,12 +23,12 @@ use prometheus_client::metrics::counter::Counter; use prometheus_client::metrics::family::Family; use prometheus_client::registry::Registry; -pub struct Metrics { +pub(crate) struct Metrics { events: Family, } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("relay"); let events = Family::default(); diff --git a/misc/metrics/src/swarm.rs b/misc/metrics/src/swarm.rs index c913710cbce..d04fd028a00 100644 --- a/misc/metrics/src/swarm.rs +++ b/misc/metrics/src/swarm.rs @@ -25,7 +25,7 @@ use prometheus_client::metrics::family::Family; use prometheus_client::metrics::histogram::{exponential_buckets, Histogram}; use prometheus_client::registry::Registry; -pub struct Metrics { +pub(crate) struct Metrics { connections_incoming: Family, connections_incoming_error: Family, @@ -45,7 +45,7 @@ pub struct Metrics { } impl Metrics { - pub fn new(registry: &mut Registry) -> Self { + pub(crate) fn new(registry: &mut Registry) -> Self { let sub_registry = registry.sub_registry_with_prefix("swarm"); let connections_incoming = Family::default(); diff --git a/misc/multistream-select/src/length_delimited.rs b/misc/multistream-select/src/length_delimited.rs index 981dfff82f8..d1de7cd292e 100644 --- a/misc/multistream-select/src/length_delimited.rs +++ b/misc/multistream-select/src/length_delimited.rs @@ -40,7 +40,7 @@ const DEFAULT_BUFFER_SIZE: usize = 64; /// unlikely to be more than 16KiB long. #[pin_project::pin_project] #[derive(Debug)] -pub struct LengthDelimited { +pub(crate) struct LengthDelimited { /// The inner I/O resource. #[pin] inner: R, @@ -76,7 +76,7 @@ impl Default for ReadState { impl LengthDelimited { /// Creates a new I/O resource for reading and writing unsigned-varint /// length delimited frames. - pub fn new(inner: R) -> LengthDelimited { + pub(crate) fn new(inner: R) -> LengthDelimited { LengthDelimited { inner, read_state: ReadState::default(), @@ -93,7 +93,7 @@ impl LengthDelimited { /// The read buffer is guaranteed to be empty whenever `Stream::poll` yields /// a new `Bytes` frame. The write buffer is guaranteed to be empty after /// flushing. - pub fn into_inner(self) -> R { + pub(crate) fn into_inner(self) -> R { assert!(self.read_buffer.is_empty()); assert!(self.write_buffer.is_empty()); self.inner @@ -106,7 +106,7 @@ impl LengthDelimited { /// This is typically done if further uvi-framed messages are expected to be /// received but no more such messages are written, allowing the writing of /// follow-up protocol data to commence. - pub fn into_reader(self) -> LengthDelimitedReader { + pub(crate) fn into_reader(self) -> LengthDelimitedReader { LengthDelimitedReader { inner: self } } @@ -115,10 +115,7 @@ impl LengthDelimited { /// /// After this method returns `Poll::Ready`, the write buffer of frames /// submitted to the `Sink` is guaranteed to be empty. - pub fn poll_write_buffer( - self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll> + fn poll_write_buffer(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> where R: AsyncWrite, { @@ -300,7 +297,7 @@ where /// frames on an underlying I/O resource combined with direct `AsyncWrite` access. #[pin_project::pin_project] #[derive(Debug)] -pub struct LengthDelimitedReader { +pub(crate) struct LengthDelimitedReader { #[pin] inner: LengthDelimited, } @@ -318,7 +315,7 @@ impl LengthDelimitedReader { /// yield a new `Message`. The write buffer is guaranteed to be empty whenever /// [`LengthDelimited::poll_write_buffer`] yields [`Poll::Ready`] or after /// the [`Sink`] has been completely flushed via [`Sink::poll_flush`]. - pub fn into_inner(self) -> R { + pub(crate) fn into_inner(self) -> R { self.inner.into_inner() } } diff --git a/misc/multistream-select/src/protocol.rs b/misc/multistream-select/src/protocol.rs index 65cdb40fedd..a560d116e53 100644 --- a/misc/multistream-select/src/protocol.rs +++ b/misc/multistream-select/src/protocol.rs @@ -53,7 +53,7 @@ const MSG_LS: &[u8] = b"ls\n"; /// /// Every [`Version`] has a corresponding header line. #[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum HeaderLine { +pub(crate) enum HeaderLine { /// The `/multistream/1.0.0` header line. V1, } @@ -68,8 +68,7 @@ impl From for HeaderLine { /// A protocol (name) exchanged during protocol negotiation. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Protocol(Bytes); - +pub(crate) struct Protocol(Bytes); impl AsRef<[u8]> for Protocol { fn as_ref(&self) -> &[u8] { self.0.as_ref() @@ -106,7 +105,7 @@ impl fmt::Display for Protocol { /// Multistream-select protocol messages are exchanged with the goal /// of agreeing on a application-layer protocol to use on an I/O stream. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Message { +pub(crate) enum Message { /// A header message identifies the multistream-select protocol /// that the sender wishes to speak. Header(HeaderLine), @@ -123,7 +122,7 @@ pub enum Message { impl Message { /// Encodes a `Message` into its byte representation. - pub fn encode(&self, dest: &mut BytesMut) -> Result<(), ProtocolError> { + fn encode(&self, dest: &mut BytesMut) -> Result<(), ProtocolError> { match self { Message::Header(HeaderLine::V1) => { dest.reserve(MSG_MULTISTREAM_1_0.len()); @@ -164,7 +163,7 @@ impl Message { } /// Decodes a `Message` from its byte representation. - pub fn decode(mut msg: Bytes) -> Result { + fn decode(mut msg: Bytes) -> Result { if msg == MSG_MULTISTREAM_1_0 { return Ok(Message::Header(HeaderLine::V1)); } @@ -220,14 +219,14 @@ impl Message { /// A `MessageIO` implements a [`Stream`] and [`Sink`] of [`Message`]s. #[pin_project::pin_project] -pub struct MessageIO { +pub(crate) struct MessageIO { #[pin] inner: LengthDelimited, } impl MessageIO { /// Constructs a new `MessageIO` resource wrapping the given I/O stream. - pub fn new(inner: R) -> MessageIO + pub(crate) fn new(inner: R) -> MessageIO where R: AsyncRead + AsyncWrite, { @@ -243,7 +242,7 @@ impl MessageIO { /// This is typically done if further negotiation messages are expected to be /// received but no more messages are written, allowing the writing of /// follow-up protocol data to commence. - pub fn into_reader(self) -> MessageReader { + pub(crate) fn into_reader(self) -> MessageReader { MessageReader { inner: self.inner.into_reader(), } @@ -258,7 +257,7 @@ impl MessageIO { /// has not yet been flushed. The read buffer is guaranteed to be empty whenever /// `MessageIO::poll` returned a message. The write buffer is guaranteed to be empty /// when the sink has been flushed. - pub fn into_inner(self) -> R { + pub(crate) fn into_inner(self) -> R { self.inner.into_inner() } } @@ -311,7 +310,7 @@ where /// I/O resource combined with direct `AsyncWrite` access. #[pin_project::pin_project] #[derive(Debug)] -pub struct MessageReader { +pub(crate) struct MessageReader { #[pin] inner: LengthDelimitedReader, } @@ -328,7 +327,7 @@ impl MessageReader { /// outgoing frame has not yet been flushed. The read buffer is guaranteed to /// be empty whenever `MessageReader::poll` returned a message. The write /// buffer is guaranteed to be empty whenever the sink has been flushed. - pub fn into_inner(self) -> R { + pub(crate) fn into_inner(self) -> R { self.inner.into_inner() } } diff --git a/muxers/mplex/src/codec.rs b/muxers/mplex/src/codec.rs index 48dbd243a09..ec605edc6a7 100644 --- a/muxers/mplex/src/codec.rs +++ b/muxers/mplex/src/codec.rs @@ -50,7 +50,7 @@ pub(crate) const MAX_FRAME_SIZE: usize = 1024 * 1024; /// > Conversely, when receiving a frame with a flag identifying the remote as a "sender", /// > the corresponding local ID has the role `Endpoint::Listener`. #[derive(Copy, Clone, Eq, Debug)] -pub struct LocalStreamId { +pub(crate) struct LocalStreamId { num: u64, role: Endpoint, } @@ -91,13 +91,13 @@ impl nohash_hasher::IsEnabled for LocalStreamId {} /// and mapped by the receiver to `LocalStreamId`s via /// [`RemoteStreamId::into_local()`]. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct RemoteStreamId { +pub(crate) struct RemoteStreamId { num: u64, role: Endpoint, } impl LocalStreamId { - pub fn dialer(num: u64) -> Self { + pub(crate) fn dialer(num: u64) -> Self { Self { num, role: Endpoint::Dialer, @@ -105,14 +105,14 @@ impl LocalStreamId { } #[cfg(test)] - pub fn listener(num: u64) -> Self { + pub(crate) fn listener(num: u64) -> Self { Self { num, role: Endpoint::Listener, } } - pub fn next(self) -> Self { + pub(crate) fn next(self) -> Self { Self { num: self .num @@ -123,7 +123,7 @@ impl LocalStreamId { } #[cfg(test)] - pub fn into_remote(self) -> RemoteStreamId { + pub(crate) fn into_remote(self) -> RemoteStreamId { RemoteStreamId { num: self.num, role: !self.role, @@ -148,7 +148,7 @@ impl RemoteStreamId { /// Converts this `RemoteStreamId` into the corresponding `LocalStreamId` /// that identifies the same substream. - pub fn into_local(self) -> LocalStreamId { + pub(crate) fn into_local(self) -> LocalStreamId { LocalStreamId { num: self.num, role: !self.role, @@ -158,7 +158,7 @@ impl RemoteStreamId { /// An Mplex protocol frame. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Frame { +pub(crate) enum Frame { Open { stream_id: T }, Data { stream_id: T, data: Bytes }, Close { stream_id: T }, @@ -166,7 +166,7 @@ pub enum Frame { } impl Frame { - pub fn remote_id(&self) -> RemoteStreamId { + pub(crate) fn remote_id(&self) -> RemoteStreamId { match *self { Frame::Open { stream_id } => stream_id, Frame::Data { stream_id, .. } => stream_id, @@ -176,7 +176,7 @@ impl Frame { } } -pub struct Codec { +pub(crate) struct Codec { varint_decoder: codec::Uvi, decoder_state: CodecDecodeState, } @@ -190,7 +190,7 @@ enum CodecDecodeState { } impl Codec { - pub fn new() -> Codec { + pub(crate) fn new() -> Codec { Codec { varint_decoder: codec::Uvi::default(), decoder_state: CodecDecodeState::Begin, diff --git a/muxers/mplex/src/io.rs b/muxers/mplex/src/io.rs index f1d6fa9bd1b..85b58820823 100644 --- a/muxers/mplex/src/io.rs +++ b/muxers/mplex/src/io.rs @@ -35,8 +35,7 @@ use std::{ task::{Context, Poll, Waker}, }; -pub use std::io::{Error, ErrorKind, Result}; - +pub(crate) use std::io::{Error, Result}; /// A connection identifier. /// /// Randomly generated and mainly intended to improve log output @@ -56,7 +55,7 @@ impl fmt::Display for ConnectionId { } } /// A multiplexed I/O stream. -pub struct Multiplexed { +pub(crate) struct Multiplexed { /// A unique ID for the multiplexed stream (i.e. connection). id: ConnectionId, /// The current operating status of the multiplex stream. @@ -116,7 +115,7 @@ where C: AsyncRead + AsyncWrite + Unpin, { /// Creates a new multiplexed I/O stream. - pub fn new(io: C, config: MplexConfig) -> Self { + pub(crate) fn new(io: C, config: MplexConfig) -> Self { let id = ConnectionId(rand::random()); debug!("New multiplexed connection: {}", id); Multiplexed { @@ -144,7 +143,7 @@ where } /// Flushes the underlying I/O stream. - pub fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll> { + pub(crate) fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll> { match &self.status { Status::Closed => return Poll::Ready(Ok(())), Status::Err(e) => return Poll::Ready(Err(io::Error::new(e.kind(), e.to_string()))), @@ -170,7 +169,7 @@ where /// > **Note**: No `Close` or `Reset` frames are sent on open substreams /// > before closing the underlying connection. However, the connection /// > close implies a flush of any frames already sent. - pub fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll> { + pub(crate) fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll> { match &self.status { Status::Closed => return Poll::Ready(Ok(())), Status::Err(e) => return Poll::Ready(Err(io::Error::new(e.kind(), e.to_string()))), @@ -209,7 +208,10 @@ where /// [`MaxBufferBehaviour::Block`] is used, this method is blocked /// (i.e. `Pending`) on some task reading from the substream whose /// buffer is full. - pub fn poll_next_stream(&mut self, cx: &mut Context<'_>) -> Poll> { + pub(crate) fn poll_next_stream( + &mut self, + cx: &mut Context<'_>, + ) -> Poll> { self.guard_open()?; // Try to read from the buffer first. @@ -250,7 +252,10 @@ where } /// Creates a new (outbound) substream, returning the allocated stream ID. - pub fn poll_open_stream(&mut self, cx: &mut Context<'_>) -> Poll> { + pub(crate) fn poll_open_stream( + &mut self, + cx: &mut Context<'_>, + ) -> Poll> { self.guard_open()?; // Check the stream limits. @@ -317,7 +322,7 @@ where /// > **Note**: All substreams obtained via `poll_next_stream` /// > or `poll_open_stream` must eventually be "dropped" by /// > calling this method when they are no longer used. - pub fn drop_stream(&mut self, id: LocalStreamId) { + pub(crate) fn drop_stream(&mut self, id: LocalStreamId) { // Check if the underlying stream is ok. match self.status { Status::Closed | Status::Err(_) => return, @@ -367,7 +372,7 @@ where } /// Writes data to a substream. - pub fn poll_write_stream( + pub(crate) fn poll_write_stream( &mut self, cx: &mut Context<'_>, id: LocalStreamId, @@ -417,7 +422,7 @@ where /// and under consideration of the number of already used substreams, /// thereby waking the task that last called `poll_next_stream`, if any. /// Inbound substreams received in excess of that limit are immediately reset. - pub fn poll_read_stream( + pub(crate) fn poll_read_stream( &mut self, cx: &mut Context<'_>, id: LocalStreamId, @@ -509,7 +514,7 @@ where /// > **Note**: This is equivalent to `poll_flush()`, i.e. to flushing /// > all substreams, except that this operation returns an error if /// > the underlying I/O stream is already closed. - pub fn poll_flush_stream( + pub(crate) fn poll_flush_stream( &mut self, cx: &mut Context<'_>, id: LocalStreamId, @@ -525,7 +530,7 @@ where /// Closes a stream for writing. /// /// > **Note**: As opposed to `poll_close()`, a flush it not implied. - pub fn poll_close_stream( + pub(crate) fn poll_close_stream( &mut self, cx: &mut Context<'_>, id: LocalStreamId, diff --git a/protocols/autonat/src/behaviour/as_client.rs b/protocols/autonat/src/behaviour/as_client.rs index 1c1eea9b723..e0c0b2e9e0a 100644 --- a/protocols/autonat/src/behaviour/as_client.rs +++ b/protocols/autonat/src/behaviour/as_client.rs @@ -83,26 +83,21 @@ pub enum OutboundProbeEvent { } /// View over [`super::Behaviour`] in a client role. -pub struct AsClient<'a> { - pub inner: &'a mut request_response::Behaviour, - pub local_peer_id: PeerId, - pub config: &'a Config, - pub connected: &'a HashMap>>, - pub probe_id: &'a mut ProbeId, - - pub servers: &'a HashSet, - pub throttled_servers: &'a mut Vec<(PeerId, Instant)>, - - pub nat_status: &'a mut NatStatus, - pub confidence: &'a mut usize, - - pub ongoing_outbound: &'a mut HashMap, - - pub last_probe: &'a mut Option, - pub schedule_probe: &'a mut Delay, - - pub listen_addresses: &'a ListenAddresses, - pub external_addresses: &'a ExternalAddresses, +pub(crate) struct AsClient<'a> { + pub(crate) inner: &'a mut request_response::Behaviour, + pub(crate) local_peer_id: PeerId, + pub(crate) config: &'a Config, + pub(crate) connected: &'a HashMap>>, + pub(crate) probe_id: &'a mut ProbeId, + pub(crate) servers: &'a HashSet, + pub(crate) throttled_servers: &'a mut Vec<(PeerId, Instant)>, + pub(crate) nat_status: &'a mut NatStatus, + pub(crate) confidence: &'a mut usize, + pub(crate) ongoing_outbound: &'a mut HashMap, + pub(crate) last_probe: &'a mut Option, + pub(crate) schedule_probe: &'a mut Delay, + pub(crate) listen_addresses: &'a ListenAddresses, + pub(crate) external_addresses: &'a ExternalAddresses, } impl<'a> HandleInnerEvent for AsClient<'a> { @@ -200,7 +195,7 @@ impl<'a> HandleInnerEvent for AsClient<'a> { } impl<'a> AsClient<'a> { - pub fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll { + pub(crate) fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll { match self.schedule_probe.poll_unpin(cx) { Poll::Ready(()) => { self.schedule_probe.reset(self.config.retry_interval); @@ -231,7 +226,7 @@ impl<'a> AsClient<'a> { } // An inbound connection can indicate that we are public; adjust the delay to the next probe. - pub fn on_inbound_connection(&mut self) { + pub(crate) fn on_inbound_connection(&mut self) { if *self.confidence == self.config.confidence_max { if self.nat_status.is_public() { self.schedule_next_probe(self.config.refresh_interval * 2); @@ -241,7 +236,7 @@ impl<'a> AsClient<'a> { } } - pub fn on_new_address(&mut self) { + pub(crate) fn on_new_address(&mut self) { if !self.nat_status.is_public() { // New address could be publicly reachable, trigger retry. if *self.confidence > 0 { @@ -251,7 +246,7 @@ impl<'a> AsClient<'a> { } } - pub fn on_expired_address(&mut self, addr: &Multiaddr) { + pub(crate) fn on_expired_address(&mut self, addr: &Multiaddr) { if let NatStatus::Public(public_address) = self.nat_status { if public_address == addr { *self.confidence = 0; diff --git a/protocols/autonat/src/behaviour/as_server.rs b/protocols/autonat/src/behaviour/as_server.rs index 822b0552e7f..063943392f3 100644 --- a/protocols/autonat/src/behaviour/as_server.rs +++ b/protocols/autonat/src/behaviour/as_server.rs @@ -74,16 +74,14 @@ pub enum InboundProbeEvent { } /// View over [`super::Behaviour`] in a server role. -pub struct AsServer<'a> { - pub inner: &'a mut request_response::Behaviour, - pub config: &'a Config, - pub connected: &'a HashMap>>, - pub probe_id: &'a mut ProbeId, - - pub throttled_clients: &'a mut Vec<(PeerId, Instant)>, - +pub(crate) struct AsServer<'a> { + pub(crate) inner: &'a mut request_response::Behaviour, + pub(crate) config: &'a Config, + pub(crate) connected: &'a HashMap>>, + pub(crate) probe_id: &'a mut ProbeId, + pub(crate) throttled_clients: &'a mut Vec<(PeerId, Instant)>, #[allow(clippy::type_complexity)] - pub ongoing_inbound: &'a mut HashMap< + pub(crate) ongoing_inbound: &'a mut HashMap< PeerId, ( ProbeId, @@ -197,7 +195,7 @@ impl<'a> HandleInnerEvent for AsServer<'a> { } impl<'a> AsServer<'a> { - pub fn on_outbound_connection( + pub(crate) fn on_outbound_connection( &mut self, peer: &PeerId, address: &Multiaddr, @@ -229,7 +227,7 @@ impl<'a> AsServer<'a> { }) } - pub fn on_outbound_dial_error( + pub(crate) fn on_outbound_dial_error( &mut self, peer: Option, error: &DialError, diff --git a/protocols/autonat/src/lib.rs b/protocols/autonat/src/lib.rs index e0fc3e9bc81..10c87b1e984 100644 --- a/protocols/autonat/src/lib.rs +++ b/protocols/autonat/src/lib.rs @@ -35,6 +35,7 @@ pub use self::{ pub use libp2p_request_response::{InboundFailure, OutboundFailure}; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::structs::{mod_Message::*, Message}; + pub(crate) use self::structs::{mod_Message::*, Message}; } diff --git a/protocols/dcutr/src/handler.rs b/protocols/dcutr/src/handler.rs index cc59e3ab4ce..0339b9654d3 100644 --- a/protocols/dcutr/src/handler.rs +++ b/protocols/dcutr/src/handler.rs @@ -18,5 +18,5 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -pub mod direct; -pub mod relayed; +pub(crate) mod direct; +pub(crate) mod relayed; diff --git a/protocols/dcutr/src/lib.rs b/protocols/dcutr/src/lib.rs index 8d5db45000c..b35849319d2 100644 --- a/protocols/dcutr/src/lib.rs +++ b/protocols/dcutr/src/lib.rs @@ -28,8 +28,9 @@ mod handler; mod protocol; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::holepunch::pb::{mod_HolePunch::*, HolePunch}; + pub(crate) use self::holepunch::pb::{mod_HolePunch::*, HolePunch}; } pub use behaviour_impl::Behaviour; diff --git a/protocols/dcutr/src/protocol.rs b/protocols/dcutr/src/protocol.rs index 67f9af69f70..4da255fc1d9 100644 --- a/protocols/dcutr/src/protocol.rs +++ b/protocols/dcutr/src/protocol.rs @@ -18,9 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -pub mod inbound; -pub mod outbound; - +pub(crate) mod inbound; +pub(crate) mod outbound; pub const PROTOCOL_NAME: &[u8; 13] = b"/libp2p/dcutr"; const MAX_MESSAGE_SIZE_BYTES: usize = 4096; diff --git a/protocols/floodsub/src/lib.rs b/protocols/floodsub/src/lib.rs index 6bd4dfac9bf..94766d5fdca 100644 --- a/protocols/floodsub/src/lib.rs +++ b/protocols/floodsub/src/lib.rs @@ -30,8 +30,9 @@ mod layer; mod topic; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::floodsub::pb::{mod_RPC::SubOpts, Message, RPC}; + pub(crate) use self::floodsub::pb::{mod_RPC::SubOpts, Message, RPC}; } pub use self::layer::{Floodsub, FloodsubEvent}; diff --git a/protocols/gossipsub/src/backoff.rs b/protocols/gossipsub/src/backoff.rs index b05d338deff..e6f05047a3e 100644 --- a/protocols/gossipsub/src/backoff.rs +++ b/protocols/gossipsub/src/backoff.rs @@ -32,7 +32,7 @@ use wasm_timer::Instant; struct HeartbeatIndex(usize); /// Stores backoffs in an efficient manner. -pub struct BackoffStorage { +pub(crate) struct BackoffStorage { /// Stores backoffs and the index in backoffs_by_heartbeat per peer per topic. backoffs: HashMap>, /// Stores peer topic pairs per heartbeat (this is cyclic the current index is @@ -52,7 +52,7 @@ impl BackoffStorage { as usize } - pub fn new( + pub(crate) fn new( prune_backoff: &Duration, heartbeat_interval: Duration, backoff_slack: u32, @@ -71,7 +71,7 @@ impl BackoffStorage { /// Updates the backoff for a peer (if there is already a more restrictive backoff then this call /// doesn't change anything). - pub fn update_backoff(&mut self, topic: &TopicHash, peer: &PeerId, time: Duration) { + pub(crate) fn update_backoff(&mut self, topic: &TopicHash, peer: &PeerId, time: Duration) { let instant = Instant::now() + time; let insert_into_backoffs_by_heartbeat = |heartbeat_index: HeartbeatIndex, @@ -127,13 +127,13 @@ impl BackoffStorage { /// /// This method should be used for deciding if we can already send a GRAFT to a previously /// backoffed peer. - pub fn is_backoff_with_slack(&self, topic: &TopicHash, peer: &PeerId) -> bool { + pub(crate) fn is_backoff_with_slack(&self, topic: &TopicHash, peer: &PeerId) -> bool { self.backoffs .get(topic) .map_or(false, |m| m.contains_key(peer)) } - pub fn get_backoff_time(&self, topic: &TopicHash, peer: &PeerId) -> Option { + pub(crate) fn get_backoff_time(&self, topic: &TopicHash, peer: &PeerId) -> Option { Self::get_backoff_time_from_backoffs(&self.backoffs, topic, peer) } @@ -149,7 +149,7 @@ impl BackoffStorage { /// Applies a heartbeat. That should be called regularly in intervals of length /// `heartbeat_interval`. - pub fn heartbeat(&mut self) { + pub(crate) fn heartbeat(&mut self) { // Clean up backoffs_by_heartbeat if let Some(s) = self.backoffs_by_heartbeat.get_mut(self.heartbeat_index.0) { let backoffs = &mut self.backoffs; diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 9e06f448afa..13ce3fcee35 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -189,7 +189,7 @@ impl SequenceNumber { } impl PublishConfig { - pub fn get_own_id(&self) -> Option<&PeerId> { + pub(crate) fn get_own_id(&self) -> Option<&PeerId> { match self { Self::Signing { author, .. } => Some(author), Self::Author(author) => Some(author), diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index ca94e4ac15f..9b662f765d5 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -61,7 +61,7 @@ where D: DataTransform + Default + Clone + Send + 'static, F: TopicSubscriptionFilter + Clone + Default + Send + 'static, { - pub fn create_network(self) -> (Behaviour, Vec, Vec) { + pub(crate) fn create_network(self) -> (Behaviour, Vec, Vec) { let keypair = libp2p_identity::Keypair::generate_ed25519(); // create a gossipsub struct let mut gs: Behaviour = Behaviour::new_with_subscription_filter_and_transform( diff --git a/protocols/gossipsub/src/gossip_promises.rs b/protocols/gossipsub/src/gossip_promises.rs index a5804c82c01..cae3b169033 100644 --- a/protocols/gossipsub/src/gossip_promises.rs +++ b/protocols/gossipsub/src/gossip_promises.rs @@ -38,12 +38,12 @@ pub(crate) struct GossipPromises { impl GossipPromises { /// Returns true if the message id exists in the promises. - pub fn contains(&self, message: &MessageId) -> bool { + pub(crate) fn contains(&self, message: &MessageId) -> bool { self.promises.contains_key(message) } /// Track a promise to deliver a message from a list of [`MessageId`]s we are requesting. - pub fn add_promise(&mut self, peer: PeerId, messages: &[MessageId], expires: Instant) { + pub(crate) fn add_promise(&mut self, peer: PeerId, messages: &[MessageId], expires: Instant) { for message_id in messages { // If a promise for this message id and peer already exists we don't update the expiry! self.promises @@ -54,12 +54,12 @@ impl GossipPromises { } } - pub fn message_delivered(&mut self, message_id: &MessageId) { + pub(crate) fn message_delivered(&mut self, message_id: &MessageId) { // Someone delivered a message, we can stop tracking all promises for it. self.promises.remove(message_id); } - pub fn reject_message(&mut self, message_id: &MessageId, reason: &RejectReason) { + pub(crate) fn reject_message(&mut self, message_id: &MessageId, reason: &RejectReason) { // A message got rejected, so we can stop tracking promises and let the score penalty apply // from invalid message delivery. // We do take exception and apply promise penalty regardless in the following cases, where @@ -77,7 +77,7 @@ impl GossipPromises { /// request. /// This should be called not too often relative to the expire times, since it iterates over /// the whole stored data. - pub fn get_broken_promises(&mut self) -> HashMap { + pub(crate) fn get_broken_promises(&mut self) -> HashMap { let now = Instant::now(); let mut result = HashMap::new(); self.promises.retain(|msg, peers| { diff --git a/protocols/gossipsub/src/mcache.rs b/protocols/gossipsub/src/mcache.rs index 7fa08a6ac6a..e85a5bf9c6a 100644 --- a/protocols/gossipsub/src/mcache.rs +++ b/protocols/gossipsub/src/mcache.rs @@ -31,14 +31,14 @@ use std::{ /// CacheEntry stored in the history. #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct CacheEntry { +pub(crate) struct CacheEntry { mid: MessageId, topic: TopicHash, } /// MessageCache struct holding history of messages. #[derive(Clone)] -pub struct MessageCache { +pub(crate) struct MessageCache { msgs: HashMap)>, /// For every message and peer the number of times this peer asked for the message iwant_counts: HashMap>, @@ -61,7 +61,7 @@ impl fmt::Debug for MessageCache { /// Implementation of the MessageCache. impl MessageCache { - pub fn new(gossip: usize, history_capacity: usize) -> Self { + pub(crate) fn new(gossip: usize, history_capacity: usize) -> Self { MessageCache { gossip, msgs: HashMap::default(), @@ -73,7 +73,7 @@ impl MessageCache { /// Put a message into the memory cache. /// /// Returns true if the message didn't already exist in the cache. - pub fn put(&mut self, message_id: &MessageId, msg: RawMessage) -> bool { + pub(crate) fn put(&mut self, message_id: &MessageId, msg: RawMessage) -> bool { match self.msgs.entry(message_id.clone()) { Entry::Occupied(_) => { // Don't add duplicate entries to the cache. @@ -94,7 +94,7 @@ impl MessageCache { } /// Keeps track of peers we know have received the message to prevent forwarding to said peers. - pub fn observe_duplicate(&mut self, message_id: &MessageId, source: &PeerId) { + pub(crate) fn observe_duplicate(&mut self, message_id: &MessageId, source: &PeerId) { if let Some((message, originating_peers)) = self.msgs.get_mut(message_id) { // if the message is already validated, we don't need to store extra peers sending us // duplicates as the message has already been forwarded @@ -108,13 +108,13 @@ impl MessageCache { /// Get a message with `message_id` #[cfg(test)] - pub fn get(&self, message_id: &MessageId) -> Option<&RawMessage> { + pub(crate) fn get(&self, message_id: &MessageId) -> Option<&RawMessage> { self.msgs.get(message_id).map(|(message, _)| message) } /// Increases the iwant count for the given message by one and returns the message together /// with the iwant if the message exists. - pub fn get_with_iwant_counts( + pub(crate) fn get_with_iwant_counts( &mut self, message_id: &MessageId, peer: &PeerId, @@ -140,7 +140,10 @@ impl MessageCache { /// Gets a message with [`MessageId`] and tags it as validated. /// This function also returns the known peers that have sent us this message. This is used to /// prevent us sending redundant messages to peers who have already propagated it. - pub fn validate(&mut self, message_id: &MessageId) -> Option<(&RawMessage, HashSet)> { + pub(crate) fn validate( + &mut self, + message_id: &MessageId, + ) -> Option<(&RawMessage, HashSet)> { self.msgs.get_mut(message_id).map(|(message, known_peers)| { message.validated = true; // Clear the known peers list (after a message is validated, it is forwarded and we no @@ -151,7 +154,7 @@ impl MessageCache { } /// Get a list of [`MessageId`]s for a given topic. - pub fn get_gossip_message_ids(&self, topic: &TopicHash) -> Vec { + pub(crate) fn get_gossip_message_ids(&self, topic: &TopicHash) -> Vec { self.history[..self.gossip] .iter() .fold(vec![], |mut current_entries, entries| { @@ -181,7 +184,7 @@ impl MessageCache { /// Shift the history array down one and delete messages associated with the /// last entry. - pub fn shift(&mut self) { + pub(crate) fn shift(&mut self) { for entry in self.history.pop().expect("history is always > 1") { if let Some((msg, _)) = self.msgs.remove(&entry.mid) { if !msg.validated { @@ -204,7 +207,10 @@ impl MessageCache { } /// Removes a message from the cache and returns it if existent - pub fn remove(&mut self, message_id: &MessageId) -> Option<(RawMessage, HashSet)> { + pub(crate) fn remove( + &mut self, + message_id: &MessageId, + ) -> Option<(RawMessage, HashSet)> { //We only remove the message from msgs and iwant_count and keep the message_id in the // history vector. Zhe id in the history vector will simply be ignored on popping. diff --git a/protocols/gossipsub/src/peer_score.rs b/protocols/gossipsub/src/peer_score.rs index 1270ad1274b..2f17b14b7a6 100644 --- a/protocols/gossipsub/src/peer_score.rs +++ b/protocols/gossipsub/src/peer_score.rs @@ -95,7 +95,7 @@ impl Default for PeerStats { impl PeerStats { /// Returns a mutable reference to topic stats if they exist, otherwise if the supplied parameters score the /// topic, inserts the default stats and returns a reference to those. If neither apply, returns None. - pub fn stats_or_default_mut( + pub(crate) fn stats_or_default_mut( &mut self, topic_hash: TopicHash, params: &PeerScoreParams, @@ -125,7 +125,7 @@ struct TopicStats { impl TopicStats { /// Returns true if the peer is in the `mesh`. - pub fn in_mesh(&self) -> bool { + pub(crate) fn in_mesh(&self) -> bool { matches!(self.mesh_status, MeshStatus::Active { .. }) } } @@ -143,7 +143,7 @@ enum MeshStatus { impl MeshStatus { /// Initialises a new [`MeshStatus::Active`] mesh status. - pub fn new_active() -> Self { + pub(crate) fn new_active() -> Self { MeshStatus::Active { graft_time: Instant::now(), mesh_time: Duration::from_secs(0), @@ -196,11 +196,11 @@ impl Default for DeliveryRecord { impl PeerScore { /// Creates a new [`PeerScore`] using a given set of peer scoring parameters. #[allow(dead_code)] - pub fn new(params: PeerScoreParams) -> Self { + pub(crate) fn new(params: PeerScoreParams) -> Self { Self::new_with_message_delivery_time_callback(params, None) } - pub fn new_with_message_delivery_time_callback( + pub(crate) fn new_with_message_delivery_time_callback( params: PeerScoreParams, callback: Option, ) -> Self { @@ -214,13 +214,13 @@ impl PeerScore { } /// Returns the score for a peer - pub fn score(&self, peer_id: &PeerId) -> f64 { + pub(crate) fn score(&self, peer_id: &PeerId) -> f64 { self.metric_score(peer_id, None) } /// Returns the score for a peer, logging metrics. This is called from the heartbeat and /// increments the metric counts for penalties. - pub fn metric_score(&self, peer_id: &PeerId, mut metrics: Option<&mut Metrics>) -> f64 { + pub(crate) fn metric_score(&self, peer_id: &PeerId, mut metrics: Option<&mut Metrics>) -> f64 { let peer_stats = match self.peer_stats.get(peer_id) { Some(v) => v, None => return 0.0, @@ -345,7 +345,7 @@ impl PeerScore { score } - pub fn add_penalty(&mut self, peer_id: &PeerId, count: usize) { + pub(crate) fn add_penalty(&mut self, peer_id: &PeerId, count: usize) { if let Some(peer_stats) = self.peer_stats.get_mut(peer_id) { debug!( "[Penalty] Behavioral penalty for peer {}, count = {}.", @@ -367,7 +367,7 @@ impl PeerScore { } } - pub fn refresh_scores(&mut self) { + pub(crate) fn refresh_scores(&mut self) { let now = Instant::now(); let params_ref = &self.params; let peer_ips_ref = &mut self.peer_ips; @@ -436,7 +436,7 @@ impl PeerScore { /// Adds a connected peer to [`PeerScore`], initialising with empty ips (ips get added later /// through add_ip. - pub fn add_peer(&mut self, peer_id: PeerId) { + pub(crate) fn add_peer(&mut self, peer_id: PeerId) { let peer_stats = self.peer_stats.entry(peer_id).or_default(); // mark the peer as connected @@ -444,7 +444,7 @@ impl PeerScore { } /// Adds a new ip to a peer, if the peer is not yet known creates a new peer_stats entry for it - pub fn add_ip(&mut self, peer_id: &PeerId, ip: IpAddr) { + pub(crate) fn add_ip(&mut self, peer_id: &PeerId, ip: IpAddr) { trace!("Add ip for peer {}, ip: {}", peer_id, ip); let peer_stats = self.peer_stats.entry(*peer_id).or_default(); @@ -461,7 +461,7 @@ impl PeerScore { } /// Removes an ip from a peer - pub fn remove_ip(&mut self, peer_id: &PeerId, ip: &IpAddr) { + pub(crate) fn remove_ip(&mut self, peer_id: &PeerId, ip: &IpAddr) { if let Some(peer_stats) = self.peer_stats.get_mut(peer_id) { peer_stats.known_ips.remove(ip); if let Some(peer_ids) = self.peer_ips.get_mut(ip) { @@ -485,7 +485,7 @@ impl PeerScore { /// Removes a peer from the score table. This retains peer statistics if their score is /// non-positive. - pub fn remove_peer(&mut self, peer_id: &PeerId) { + pub(crate) fn remove_peer(&mut self, peer_id: &PeerId) { // we only retain non-positive scores of peers if self.score(peer_id) > 0f64 { if let hash_map::Entry::Occupied(entry) = self.peer_stats.entry(*peer_id) { @@ -527,7 +527,7 @@ impl PeerScore { } /// Handles scoring functionality as a peer GRAFTs to a topic. - pub fn graft(&mut self, peer_id: &PeerId, topic: impl Into) { + pub(crate) fn graft(&mut self, peer_id: &PeerId, topic: impl Into) { let topic = topic.into(); if let Some(peer_stats) = self.peer_stats.get_mut(peer_id) { // if we are scoring the topic, update the mesh status. @@ -539,7 +539,7 @@ impl PeerScore { } /// Handles scoring functionality as a peer PRUNEs from a topic. - pub fn prune(&mut self, peer_id: &PeerId, topic: TopicHash) { + pub(crate) fn prune(&mut self, peer_id: &PeerId, topic: TopicHash) { if let Some(peer_stats) = self.peer_stats.get_mut(peer_id) { // if we are scoring the topic, update the mesh status. if let Some(topic_stats) = peer_stats.stats_or_default_mut(topic.clone(), &self.params) @@ -563,7 +563,12 @@ impl PeerScore { } } - pub fn validate_message(&mut self, from: &PeerId, msg_id: &MessageId, topic_hash: &TopicHash) { + pub(crate) fn validate_message( + &mut self, + from: &PeerId, + msg_id: &MessageId, + topic_hash: &TopicHash, + ) { // adds an empty record with the message id self.deliveries .entry(msg_id.clone()) @@ -582,7 +587,12 @@ impl PeerScore { } } - pub fn deliver_message(&mut self, from: &PeerId, msg_id: &MessageId, topic_hash: &TopicHash) { + pub(crate) fn deliver_message( + &mut self, + from: &PeerId, + msg_id: &MessageId, + topic_hash: &TopicHash, + ) { self.mark_first_message_delivery(from, topic_hash); let record = self @@ -608,7 +618,7 @@ impl PeerScore { } /// Similar to `reject_message` except does not require the message id or reason for an invalid message. - pub fn reject_invalid_message(&mut self, from: &PeerId, topic_hash: &TopicHash) { + pub(crate) fn reject_invalid_message(&mut self, from: &PeerId, topic_hash: &TopicHash) { debug!( "[Penalty] Message from {} rejected because of ValidationError or SelfOrigin", from @@ -618,7 +628,7 @@ impl PeerScore { } // Reject a message. - pub fn reject_message( + pub(crate) fn reject_message( &mut self, from: &PeerId, msg_id: &MessageId, @@ -670,7 +680,7 @@ impl PeerScore { } } - pub fn duplicated_message( + pub(crate) fn duplicated_message( &mut self, from: &PeerId, msg_id: &MessageId, @@ -726,7 +736,7 @@ impl PeerScore { /// Sets the application specific score for a peer. Returns true if the peer is the peer is /// connected or if the score of the peer is not yet expired and false otherwise. - pub fn set_application_score(&mut self, peer_id: &PeerId, new_score: f64) -> bool { + pub(crate) fn set_application_score(&mut self, peer_id: &PeerId, new_score: f64) -> bool { if let Some(peer_stats) = self.peer_stats.get_mut(peer_id) { peer_stats.application_score = new_score; true @@ -736,7 +746,7 @@ impl PeerScore { } /// Sets scoring parameters for a topic. - pub fn set_topic_params(&mut self, topic_hash: TopicHash, params: TopicScoreParams) { + pub(crate) fn set_topic_params(&mut self, topic_hash: TopicHash, params: TopicScoreParams) { use hash_map::Entry::*; match self.params.topics.entry(topic_hash.clone()) { Occupied(mut entry) => { diff --git a/protocols/gossipsub/src/rpc_proto.rs b/protocols/gossipsub/src/rpc_proto.rs index 470475070b9..94c7aafbc3e 100644 --- a/protocols/gossipsub/src/rpc_proto.rs +++ b/protocols/gossipsub/src/rpc_proto.rs @@ -18,7 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -pub mod proto { +pub(crate) mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); pub use self::gossipsub::pb::{mod_RPC::SubOpts, *}; } diff --git a/protocols/gossipsub/src/types.rs b/protocols/gossipsub/src/types.rs index ae9b5a09f35..9c9cd3f97f1 100644 --- a/protocols/gossipsub/src/types.rs +++ b/protocols/gossipsub/src/types.rs @@ -88,11 +88,11 @@ declare_message_id_type!(MessageId, "MessageId"); declare_message_id_type!(FastMessageId, "FastMessageId"); #[derive(Debug, Clone, PartialEq, Eq)] -pub struct PeerConnections { +pub(crate) struct PeerConnections { /// The kind of protocol the peer supports. - pub kind: PeerKind, + pub(crate) kind: PeerKind, /// Its current connections. - pub connections: Vec, + pub(crate) connections: Vec, } /// Describes the types of peers that can exist in the gossipsub context. diff --git a/protocols/identify/src/lib.rs b/protocols/identify/src/lib.rs index 7fb8df253ff..f7a4a1ecbd8 100644 --- a/protocols/identify/src/lib.rs +++ b/protocols/identify/src/lib.rs @@ -70,6 +70,7 @@ mod handler; mod protocol; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::structs::Identify; + pub(crate) use self::structs::Identify; } diff --git a/protocols/kad/src/jobs.rs b/protocols/kad/src/jobs.rs index 22e3dfc6797..cfc4f92941b 100644 --- a/protocols/kad/src/jobs.rs +++ b/protocols/kad/src/jobs.rs @@ -75,12 +75,10 @@ use std::vec; /// The maximum number of queries towards which background jobs /// are allowed to start new queries on an invocation of /// `Kademlia::poll`. -pub const JOBS_MAX_QUERIES: usize = 100; - +pub(crate) const JOBS_MAX_QUERIES: usize = 100; /// The maximum number of new queries started by a background job /// per invocation of `Kademlia::poll`. -pub const JOBS_MAX_NEW_QUERIES: usize = 10; - +pub(crate) const JOBS_MAX_NEW_QUERIES: usize = 10; /// A background job run periodically. #[derive(Debug)] struct PeriodicJob { @@ -129,7 +127,7 @@ enum PeriodicJobState { // PutRecordJob /// Periodic job for replicating / publishing records. -pub struct PutRecordJob { +pub(crate) struct PutRecordJob { local_id: PeerId, next_publish: Option, publish_interval: Option, @@ -141,7 +139,7 @@ pub struct PutRecordJob { impl PutRecordJob { /// Creates a new periodic job for replicating and re-publishing /// locally stored records. - pub fn new( + pub(crate) fn new( local_id: PeerId, replicate_interval: Duration, publish_interval: Option, @@ -166,12 +164,12 @@ impl PutRecordJob { /// Adds the key of a record that is ignored on the current or /// next run of the job. - pub fn skip(&mut self, key: record_priv::Key) { + pub(crate) fn skip(&mut self, key: record_priv::Key) { self.skipped.insert(key); } /// Checks whether the job is currently running. - pub fn is_running(&self) -> bool { + pub(crate) fn is_running(&self) -> bool { self.inner.is_running() } @@ -179,7 +177,7 @@ impl PutRecordJob { /// for the delay to expire. /// /// The job is guaranteed to run on the next invocation of `poll`. - pub fn asap(&mut self, publish: bool) { + pub(crate) fn asap(&mut self, publish: bool) { if publish { self.next_publish = Some(Instant::now().checked_sub(Duration::from_secs(1)).unwrap()) } @@ -191,7 +189,12 @@ impl PutRecordJob { /// Must be called in the context of a task. When `NotReady` is returned, /// the current task is registered to be notified when the job is ready /// to be run. - pub fn poll(&mut self, cx: &mut Context<'_>, store: &mut T, now: Instant) -> Poll + pub(crate) fn poll( + &mut self, + cx: &mut Context<'_>, + store: &mut T, + now: Instant, + ) -> Poll where T: RecordStore, { @@ -250,13 +253,13 @@ impl PutRecordJob { // AddProviderJob /// Periodic job for replicating provider records. -pub struct AddProviderJob { +pub(crate) struct AddProviderJob { inner: PeriodicJob>, } impl AddProviderJob { /// Creates a new periodic job for provider announcements. - pub fn new(interval: Duration) -> Self { + pub(crate) fn new(interval: Duration) -> Self { let now = Instant::now(); Self { inner: PeriodicJob { @@ -270,7 +273,7 @@ impl AddProviderJob { } /// Checks whether the job is currently running. - pub fn is_running(&self) -> bool { + pub(crate) fn is_running(&self) -> bool { self.inner.is_running() } @@ -278,7 +281,7 @@ impl AddProviderJob { /// for the delay to expire. /// /// The job is guaranteed to run on the next invocation of `poll`. - pub fn asap(&mut self) { + pub(crate) fn asap(&mut self) { self.inner.asap() } @@ -287,7 +290,7 @@ impl AddProviderJob { /// Must be called in the context of a task. When `NotReady` is returned, /// the current task is registered to be notified when the job is ready /// to be run. - pub fn poll( + pub(crate) fn poll( &mut self, cx: &mut Context<'_>, store: &mut T, diff --git a/protocols/kad/src/kbucket_priv/bucket.rs b/protocols/kad/src/kbucket_priv/bucket.rs index 1f560676608..78bcd95261b 100644 --- a/protocols/kad/src/kbucket_priv/bucket.rs +++ b/protocols/kad/src/kbucket_priv/bucket.rs @@ -30,7 +30,7 @@ pub use crate::K_VALUE; /// A `PendingNode` is a `Node` that is pending insertion into a `KBucket`. #[derive(Debug, Clone)] -pub struct PendingNode { +pub(crate) struct PendingNode { /// The pending node to insert. node: Node, @@ -55,27 +55,27 @@ pub enum NodeStatus { } impl PendingNode { - pub fn key(&self) -> &TKey { + pub(crate) fn key(&self) -> &TKey { &self.node.key } - pub fn status(&self) -> NodeStatus { + pub(crate) fn status(&self) -> NodeStatus { self.status } - pub fn value_mut(&mut self) -> &mut TVal { + pub(crate) fn value_mut(&mut self) -> &mut TVal { &mut self.node.value } - pub fn is_ready(&self) -> bool { + pub(crate) fn is_ready(&self) -> bool { Instant::now() >= self.replace } - pub fn set_ready_at(&mut self, t: Instant) { + pub(crate) fn set_ready_at(&mut self, t: Instant) { self.replace = t; } - pub fn into_node(self) -> Node { + pub(crate) fn into_node(self) -> Node { self.node } } @@ -94,12 +94,11 @@ pub struct Node { /// The position of a node in a `KBucket`, i.e. a non-negative integer /// in the range `[0, K_VALUE)`. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct Position(usize); - +pub(crate) struct Position(usize); /// A `KBucket` is a list of up to `K_VALUE` keys and associated values, /// ordered from least-recently connected to most-recently connected. #[derive(Debug, Clone)] -pub struct KBucket { +pub(crate) struct KBucket { /// The nodes contained in the bucket. nodes: ArrayVec, { K_VALUE.get() }>, @@ -167,7 +166,7 @@ where TVal: Clone, { /// Creates a new `KBucket` with the given timeout for pending entries. - pub fn new(pending_timeout: Duration) -> Self { + pub(crate) fn new(pending_timeout: Duration) -> Self { KBucket { nodes: ArrayVec::new(), first_connected_pos: None, @@ -177,29 +176,29 @@ where } /// Returns a reference to the pending node of the bucket, if there is any. - pub fn pending(&self) -> Option<&PendingNode> { + pub(crate) fn pending(&self) -> Option<&PendingNode> { self.pending.as_ref() } /// Returns a mutable reference to the pending node of the bucket, if there is any. - pub fn pending_mut(&mut self) -> Option<&mut PendingNode> { + pub(crate) fn pending_mut(&mut self) -> Option<&mut PendingNode> { self.pending.as_mut() } /// Returns a reference to the pending node of the bucket, if there is any /// with a matching key. - pub fn as_pending(&self, key: &TKey) -> Option<&PendingNode> { + pub(crate) fn as_pending(&self, key: &TKey) -> Option<&PendingNode> { self.pending() .filter(|p| p.node.key.as_ref() == key.as_ref()) } /// Returns a reference to a node in the bucket. - pub fn get(&self, key: &TKey) -> Option<&Node> { + pub(crate) fn get(&self, key: &TKey) -> Option<&Node> { self.position(key).map(|p| &self.nodes[p.0]) } /// Returns an iterator over the nodes in the bucket, together with their status. - pub fn iter(&self) -> impl Iterator, NodeStatus)> { + pub(crate) fn iter(&self) -> impl Iterator, NodeStatus)> { self.nodes .iter() .enumerate() @@ -212,7 +211,7 @@ where /// If a pending node has been inserted, its key is returned together with /// the node that was replaced. `None` indicates that the nodes in the /// bucket remained unchanged. - pub fn apply_pending(&mut self) -> Option> { + pub(crate) fn apply_pending(&mut self) -> Option> { if let Some(pending) = self.pending.take() { if pending.replace <= Instant::now() { if self.nodes.is_full() { @@ -269,20 +268,20 @@ where } /// Updates the status of the pending node, if any. - pub fn update_pending(&mut self, status: NodeStatus) { + pub(crate) fn update_pending(&mut self, status: NodeStatus) { if let Some(pending) = &mut self.pending { pending.status = status } } /// Removes the pending node from the bucket, if any. - pub fn remove_pending(&mut self) -> Option> { + pub(crate) fn remove_pending(&mut self) -> Option> { self.pending.take() } /// Updates the status of the node referred to by the given key, if it is /// in the bucket. - pub fn update(&mut self, key: &TKey, status: NodeStatus) { + pub(crate) fn update(&mut self, key: &TKey, status: NodeStatus) { // Remove the node from its current position and then reinsert it // with the desired status, which puts it at the end of either the // prefix list of disconnected nodes or the suffix list of connected @@ -319,7 +318,11 @@ where /// i.e. as the most-recently disconnected node. If there are no connected nodes, /// the new node is added as the last element of the bucket. /// - pub fn insert(&mut self, node: Node, status: NodeStatus) -> InsertResult { + pub(crate) fn insert( + &mut self, + node: Node, + status: NodeStatus, + ) -> InsertResult { match status { NodeStatus::Connected => { if self.nodes.is_full() { @@ -357,7 +360,10 @@ where } /// Removes the node with the given key from the bucket, if it exists. - pub fn remove(&mut self, key: &TKey) -> Option<(Node, NodeStatus, Position)> { + pub(crate) fn remove( + &mut self, + key: &TKey, + ) -> Option<(Node, NodeStatus, Position)> { if let Some(pos) = self.position(key) { // Remove the node from its current position. let status = self.status(pos); @@ -385,7 +391,7 @@ where } /// Returns the status of the node at the given position. - pub fn status(&self, pos: Position) -> NodeStatus { + pub(crate) fn status(&self, pos: Position) -> NodeStatus { if self.first_connected_pos.map_or(false, |i| pos.0 >= i) { NodeStatus::Connected } else { @@ -394,27 +400,27 @@ where } /// Checks whether the given position refers to a connected node. - pub fn is_connected(&self, pos: Position) -> bool { + pub(crate) fn is_connected(&self, pos: Position) -> bool { self.status(pos) == NodeStatus::Connected } /// Gets the number of entries currently in the bucket. - pub fn num_entries(&self) -> usize { + pub(crate) fn num_entries(&self) -> usize { self.nodes.len() } /// Gets the number of entries in the bucket that are considered connected. - pub fn num_connected(&self) -> usize { + pub(crate) fn num_connected(&self) -> usize { self.first_connected_pos.map_or(0, |i| self.nodes.len() - i) } /// Gets the number of entries in the bucket that are considered disconnected. - pub fn num_disconnected(&self) -> usize { + pub(crate) fn num_disconnected(&self) -> usize { self.nodes.len() - self.num_connected() } /// Gets the position of an node in the bucket. - pub fn position(&self, key: &TKey) -> Option { + pub(crate) fn position(&self, key: &TKey) -> Option { self.nodes .iter() .position(|p| p.key.as_ref() == key.as_ref()) @@ -425,7 +431,7 @@ where /// /// Returns `None` if the given key does not refer to a node in the /// bucket. - pub fn get_mut(&mut self, key: &TKey) -> Option<&mut Node> { + pub(crate) fn get_mut(&mut self, key: &TKey) -> Option<&mut Node> { self.nodes .iter_mut() .find(move |p| p.key.as_ref() == key.as_ref()) diff --git a/protocols/kad/src/lib.rs b/protocols/kad/src/lib.rs index 36f2c74bb41..c3a705900d8 100644 --- a/protocols/kad/src/lib.rs +++ b/protocols/kad/src/lib.rs @@ -76,6 +76,7 @@ mod jobs; mod query; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); pub use self::dht::pb::{ mod_Message::{ConnectionType, MessageType, Peer}, diff --git a/protocols/kad/src/query.rs b/protocols/kad/src/query.rs index ab29c812b01..d06b4920404 100644 --- a/protocols/kad/src/query.rs +++ b/protocols/kad/src/query.rs @@ -39,14 +39,14 @@ use std::{num::NonZeroUsize, time::Duration}; /// Internally, a `Query` is in turn driven by an underlying `QueryPeerIter` /// that determines the peer selection strategy, i.e. the order in which the /// peers involved in the query should be contacted. -pub struct QueryPool { +pub(crate) struct QueryPool { next_id: usize, config: QueryConfig, queries: FnvHashMap>, } /// The observable states emitted by [`QueryPool::poll`]. -pub enum QueryPoolState<'a, TInner> { +pub(crate) enum QueryPoolState<'a, TInner> { /// The pool is idle, i.e. there are no queries to process. Idle, /// At least one query is waiting for results. `Some(request)` indicates @@ -60,7 +60,7 @@ pub enum QueryPoolState<'a, TInner> { impl QueryPool { /// Creates a new `QueryPool` with the given configuration. - pub fn new(config: QueryConfig) -> Self { + pub(crate) fn new(config: QueryConfig) -> Self { QueryPool { next_id: 0, config, @@ -69,27 +69,27 @@ impl QueryPool { } /// Gets a reference to the `QueryConfig` used by the pool. - pub fn config(&self) -> &QueryConfig { + pub(crate) fn config(&self) -> &QueryConfig { &self.config } /// Returns an iterator over the queries in the pool. - pub fn iter(&self) -> impl Iterator> { + pub(crate) fn iter(&self) -> impl Iterator> { self.queries.values() } /// Gets the current size of the pool, i.e. the number of running queries. - pub fn size(&self) -> usize { + pub(crate) fn size(&self) -> usize { self.queries.len() } /// Returns an iterator that allows modifying each query in the pool. - pub fn iter_mut(&mut self) -> impl Iterator> { + pub(crate) fn iter_mut(&mut self) -> impl Iterator> { self.queries.values_mut() } /// Adds a query to the pool that contacts a fixed set of peers. - pub fn add_fixed(&mut self, peers: I, inner: TInner) -> QueryId + pub(crate) fn add_fixed(&mut self, peers: I, inner: TInner) -> QueryId where I: IntoIterator, { @@ -101,7 +101,7 @@ impl QueryPool { /// Continues an earlier query with a fixed set of peers, reusing /// the given query ID, which must be from a query that finished /// earlier. - pub fn continue_fixed(&mut self, id: QueryId, peers: I, inner: TInner) + pub(crate) fn continue_fixed(&mut self, id: QueryId, peers: I, inner: TInner) where I: IntoIterator, { @@ -113,7 +113,7 @@ impl QueryPool { } /// Adds a query to the pool that iterates towards the closest peers to the target. - pub fn add_iter_closest(&mut self, target: T, peers: I, inner: TInner) -> QueryId + pub(crate) fn add_iter_closest(&mut self, target: T, peers: I, inner: TInner) -> QueryId where T: Into + Clone, I: IntoIterator>, @@ -124,8 +124,13 @@ impl QueryPool { } /// Adds a query to the pool that iterates towards the closest peers to the target. - pub fn continue_iter_closest(&mut self, id: QueryId, target: T, peers: I, inner: TInner) - where + pub(crate) fn continue_iter_closest( + &mut self, + id: QueryId, + target: T, + peers: I, + inner: TInner, + ) where T: Into + Clone, I: IntoIterator>, { @@ -154,17 +159,17 @@ impl QueryPool { } /// Returns a reference to a query with the given ID, if it is in the pool. - pub fn get(&self, id: &QueryId) -> Option<&Query> { + pub(crate) fn get(&self, id: &QueryId) -> Option<&Query> { self.queries.get(id) } /// Returns a mutablereference to a query with the given ID, if it is in the pool. - pub fn get_mut(&mut self, id: &QueryId) -> Option<&mut Query> { + pub(crate) fn get_mut(&mut self, id: &QueryId) -> Option<&mut Query> { self.queries.get_mut(id) } /// Polls the pool to advance the queries. - pub fn poll(&mut self, now: Instant) -> QueryPoolState<'_, TInner> { + pub(crate) fn poll(&mut self, now: Instant) -> QueryPoolState<'_, TInner> { let mut finished = None; let mut timeout = None; let mut waiting = None; @@ -222,26 +227,23 @@ pub struct QueryId(usize); /// The configuration for queries in a `QueryPool`. #[derive(Debug, Clone)] -pub struct QueryConfig { +pub(crate) struct QueryConfig { /// Timeout of a single query. /// /// See [`crate::behaviour::KademliaConfig::set_query_timeout`] for details. - pub timeout: Duration, - + pub(crate) timeout: Duration, /// The replication factor to use. /// /// See [`crate::behaviour::KademliaConfig::set_replication_factor`] for details. - pub replication_factor: NonZeroUsize, - + pub(crate) replication_factor: NonZeroUsize, /// Allowed level of parallelism for iterative queries. /// /// See [`crate::behaviour::KademliaConfig::set_parallelism`] for details. - pub parallelism: NonZeroUsize, - + pub(crate) parallelism: NonZeroUsize, /// Whether to use disjoint paths on iterative lookups. /// /// See [`crate::behaviour::KademliaConfig::disjoint_query_paths`] for details. - pub disjoint_query_paths: bool, + pub(crate) disjoint_query_paths: bool, } impl Default for QueryConfig { @@ -256,7 +258,7 @@ impl Default for QueryConfig { } /// A query in a `QueryPool`. -pub struct Query { +pub(crate) struct Query { /// The unique ID of the query. id: QueryId, /// The peer iterator that drives the query state. @@ -264,7 +266,7 @@ pub struct Query { /// Execution statistics of the query. stats: QueryStats, /// The opaque inner query state. - pub inner: TInner, + pub(crate) inner: TInner, } /// The peer selection strategies that can be used by queries. @@ -286,17 +288,17 @@ impl Query { } /// Gets the unique ID of the query. - pub fn id(&self) -> QueryId { + pub(crate) fn id(&self) -> QueryId { self.id } /// Gets the current execution statistics of the query. - pub fn stats(&self) -> &QueryStats { + pub(crate) fn stats(&self) -> &QueryStats { &self.stats } /// Informs the query that the attempt to contact `peer` failed. - pub fn on_failure(&mut self, peer: &PeerId) { + pub(crate) fn on_failure(&mut self, peer: &PeerId) { let updated = match &mut self.peer_iter { QueryPeerIter::Closest(iter) => iter.on_failure(peer), QueryPeerIter::ClosestDisjoint(iter) => iter.on_failure(peer), @@ -310,7 +312,7 @@ impl Query { /// Informs the query that the attempt to contact `peer` succeeded, /// possibly resulting in new peers that should be incorporated into /// the query, if applicable. - pub fn on_success(&mut self, peer: &PeerId, new_peers: I) + pub(crate) fn on_success(&mut self, peer: &PeerId, new_peers: I) where I: IntoIterator, { @@ -325,7 +327,7 @@ impl Query { } /// Checks whether the query is currently waiting for a result from `peer`. - pub fn is_waiting(&self, peer: &PeerId) -> bool { + pub(crate) fn is_waiting(&self, peer: &PeerId) -> bool { match &self.peer_iter { QueryPeerIter::Closest(iter) => iter.is_waiting(peer), QueryPeerIter::ClosestDisjoint(iter) => iter.is_waiting(peer), @@ -365,7 +367,7 @@ impl Query { /// A finished query immediately stops yielding new peers to contact and /// will be reported by [`QueryPool::poll`] via /// [`QueryPoolState::Finished`]. - pub fn try_finish<'a, I>(&mut self, peers: I) -> bool + pub(crate) fn try_finish<'a, I>(&mut self, peers: I) -> bool where I: IntoIterator, { @@ -386,7 +388,7 @@ impl Query { /// /// A finished query immediately stops yielding new peers to contact and will be /// reported by [`QueryPool::poll`] via [`QueryPoolState::Finished`]. - pub fn finish(&mut self) { + pub(crate) fn finish(&mut self) { match &mut self.peer_iter { QueryPeerIter::Closest(iter) => iter.finish(), QueryPeerIter::ClosestDisjoint(iter) => iter.finish(), @@ -398,7 +400,7 @@ impl Query { /// /// A finished query is eventually reported by `QueryPool::next()` and /// removed from the pool. - pub fn is_finished(&self) -> bool { + pub(crate) fn is_finished(&self) -> bool { match &self.peer_iter { QueryPeerIter::Closest(iter) => iter.is_finished(), QueryPeerIter::ClosestDisjoint(iter) => iter.is_finished(), @@ -407,7 +409,7 @@ impl Query { } /// Consumes the query, producing the final `QueryResult`. - pub fn into_result(self) -> QueryResult> { + pub(crate) fn into_result(self) -> QueryResult> { let peers = match self.peer_iter { QueryPeerIter::Closest(iter) => Either::Left(Either::Left(iter.into_result())), QueryPeerIter::ClosestDisjoint(iter) => Either::Left(Either::Right(iter.into_result())), @@ -422,13 +424,13 @@ impl Query { } /// The result of a `Query`. -pub struct QueryResult { +pub(crate) struct QueryResult { /// The opaque inner query state. - pub inner: TInner, + pub(crate) inner: TInner, /// The successfully contacted peers. - pub peers: TPeers, + pub(crate) peers: TPeers, /// The collected query statistics. - pub stats: QueryStats, + pub(crate) stats: QueryStats, } /// Execution statistics of a query. diff --git a/protocols/kad/src/query/peers.rs b/protocols/kad/src/query/peers.rs index 824fb658e7c..11b8f974de9 100644 --- a/protocols/kad/src/query/peers.rs +++ b/protocols/kad/src/query/peers.rs @@ -38,9 +38,8 @@ //! //! [`Finished`]: PeersIterState::Finished -pub mod closest; -pub mod fixed; - +pub(crate) mod closest; +pub(crate) mod fixed; use libp2p_identity::PeerId; use std::borrow::Cow; diff --git a/protocols/kad/src/query/peers/closest.rs b/protocols/kad/src/query/peers/closest.rs index 11486796c29..66ea9d9ce52 100644 --- a/protocols/kad/src/query/peers/closest.rs +++ b/protocols/kad/src/query/peers/closest.rs @@ -27,8 +27,7 @@ use libp2p_identity::PeerId; use std::collections::btree_map::{BTreeMap, Entry}; use std::{iter::FromIterator, num::NonZeroUsize, time::Duration}; -pub mod disjoint; - +pub(crate) mod disjoint; /// A peer iterator for a dynamically changing list of peers, sorted by increasing /// distance to a chosen target. #[derive(Debug, Clone)] diff --git a/protocols/kad/src/query/peers/closest/disjoint.rs b/protocols/kad/src/query/peers/closest/disjoint.rs index 22a6051f3de..2ea484ed43c 100644 --- a/protocols/kad/src/query/peers/closest/disjoint.rs +++ b/protocols/kad/src/query/peers/closest/disjoint.rs @@ -30,7 +30,7 @@ use std::{ /// Wraps around a set of [`ClosestPeersIter`], enforcing a disjoint discovery /// path per configured parallelism according to the S/Kademlia paper. -pub struct ClosestDisjointPeersIter { +pub(crate) struct ClosestDisjointPeersIter { config: ClosestPeersIterConfig, target: KeyBytes, @@ -51,7 +51,7 @@ pub struct ClosestDisjointPeersIter { impl ClosestDisjointPeersIter { /// Creates a new iterator with a default configuration. - pub fn new(target: KeyBytes, known_closest_peers: I) -> Self + pub(crate) fn new(target: KeyBytes, known_closest_peers: I) -> Self where I: IntoIterator>, { @@ -63,7 +63,7 @@ impl ClosestDisjointPeersIter { } /// Creates a new iterator with the given configuration. - pub fn with_config( + pub(crate) fn with_config( config: ClosestPeersIterConfig, target: T, known_closest_peers: I, @@ -108,7 +108,7 @@ impl ClosestDisjointPeersIter { /// If the iterator is finished, it is not currently waiting for a /// result from `peer`, or a result for `peer` has already been reported, /// calling this function has no effect and `false` is returned. - pub fn on_failure(&mut self, peer: &PeerId) -> bool { + pub(crate) fn on_failure(&mut self, peer: &PeerId) -> bool { let mut updated = false; if let Some(PeerState { @@ -151,7 +151,7 @@ impl ClosestDisjointPeersIter { /// If the iterator is finished, it is not currently waiting for a /// result from `peer`, or a result for `peer` has already been reported, /// calling this function has no effect and `false` is returned. - pub fn on_success(&mut self, peer: &PeerId, closer_peers: I) -> bool + pub(crate) fn on_success(&mut self, peer: &PeerId, closer_peers: I) -> bool where I: IntoIterator, { @@ -190,11 +190,11 @@ impl ClosestDisjointPeersIter { updated } - pub fn is_waiting(&self, peer: &PeerId) -> bool { + pub(crate) fn is_waiting(&self, peer: &PeerId) -> bool { self.iters.iter().any(|i| i.is_waiting(peer)) } - pub fn next(&mut self, now: Instant) -> PeersIterState<'_> { + pub(crate) fn next(&mut self, now: Instant) -> PeersIterState<'_> { let mut state = None; // Ensure querying each iterator at most once. @@ -290,7 +290,7 @@ impl ClosestDisjointPeersIter { /// Finishes all paths containing one of the given peers. /// /// See [`crate::query::Query::try_finish`] for details. - pub fn finish_paths<'a, I>(&mut self, peers: I) -> bool + pub(crate) fn finish_paths<'a, I>(&mut self, peers: I) -> bool where I: IntoIterator, { @@ -304,14 +304,14 @@ impl ClosestDisjointPeersIter { } /// Immediately transitions the iterator to [`PeersIterState::Finished`]. - pub fn finish(&mut self) { + pub(crate) fn finish(&mut self) { for iter in &mut self.iters { iter.finish(); } } /// Checks whether the iterator has finished. - pub fn is_finished(&self) -> bool { + pub(crate) fn is_finished(&self) -> bool { self.iters.iter().all(|i| i.is_finished()) } @@ -323,7 +323,7 @@ impl ClosestDisjointPeersIter { /// `num_results` closest benign peers, but as it can not /// differentiate benign from faulty paths it as well returns faulty /// peers and thus overall returns more than `num_results` peers. - pub fn into_result(self) -> impl Iterator { + pub(crate) fn into_result(self) -> impl Iterator { let result_per_path = self .iters .into_iter() @@ -609,7 +609,7 @@ mod tests { } #[derive(Debug, Clone)] - struct PeerVec(pub Vec>); + struct PeerVec(Vec>); impl Arbitrary for PeerVec { fn arbitrary(g: &mut Gen) -> Self { diff --git a/protocols/kad/src/query/peers/fixed.rs b/protocols/kad/src/query/peers/fixed.rs index 07ec6cf9f4e..1169feee87f 100644 --- a/protocols/kad/src/query/peers/fixed.rs +++ b/protocols/kad/src/query/peers/fixed.rs @@ -25,7 +25,7 @@ use libp2p_identity::PeerId; use std::{collections::hash_map::Entry, num::NonZeroUsize, vec}; /// A peer iterator for a fixed set of peers. -pub struct FixedPeersIter { +pub(crate) struct FixedPeersIter { /// Ther permitted parallelism, i.e. number of pending results. parallelism: NonZeroUsize, @@ -59,7 +59,7 @@ enum PeerState { impl FixedPeersIter { #[allow(clippy::needless_collect)] - pub fn new(peers: I, parallelism: NonZeroUsize) -> Self + pub(crate) fn new(peers: I, parallelism: NonZeroUsize) -> Self where I: IntoIterator, { @@ -83,7 +83,7 @@ impl FixedPeersIter { /// If the iterator is finished, it is not currently waiting for a /// result from `peer`, or a result for `peer` has already been reported, /// calling this function has no effect and `false` is returned. - pub fn on_success(&mut self, peer: &PeerId) -> bool { + pub(crate) fn on_success(&mut self, peer: &PeerId) -> bool { if let State::Waiting { num_waiting } = &mut self.state { if let Some(state @ PeerState::Waiting) = self.peers.get_mut(peer) { *state = PeerState::Succeeded; @@ -104,7 +104,7 @@ impl FixedPeersIter { /// If the iterator is finished, it is not currently waiting for a /// result from `peer`, or a result for `peer` has already been reported, /// calling this function has no effect and `false` is returned. - pub fn on_failure(&mut self, peer: &PeerId) -> bool { + pub(crate) fn on_failure(&mut self, peer: &PeerId) -> bool { if let State::Waiting { num_waiting } = &mut self.state { if let Some(state @ PeerState::Waiting) = self.peers.get_mut(peer) { *state = PeerState::Failed; @@ -115,22 +115,22 @@ impl FixedPeersIter { false } - pub fn is_waiting(&self, peer: &PeerId) -> bool { + pub(crate) fn is_waiting(&self, peer: &PeerId) -> bool { self.peers.get(peer) == Some(&PeerState::Waiting) } - pub fn finish(&mut self) { + pub(crate) fn finish(&mut self) { if let State::Waiting { .. } = self.state { self.state = State::Finished } } /// Checks whether the iterator has finished. - pub fn is_finished(&self) -> bool { + pub(crate) fn is_finished(&self) -> bool { self.state == State::Finished } - pub fn next(&mut self) -> PeersIterState<'_> { + pub(crate) fn next(&mut self) -> PeersIterState<'_> { match &mut self.state { State::Finished => PeersIterState::Finished, State::Waiting { num_waiting } => { @@ -161,7 +161,7 @@ impl FixedPeersIter { } } - pub fn into_result(self) -> impl Iterator { + pub(crate) fn into_result(self) -> impl Iterator { self.peers.into_iter().filter_map(|(p, s)| { if let PeerState::Succeeded = s { Some(p) diff --git a/protocols/mdns/src/behaviour/iface.rs b/protocols/mdns/src/behaviour/iface.rs index 4b5580e0869..0f556e1b237 100644 --- a/protocols/mdns/src/behaviour/iface.rs +++ b/protocols/mdns/src/behaviour/iface.rs @@ -41,7 +41,7 @@ use std::{ /// An mDNS instance for a networking interface. To discover all peers when having multiple /// interfaces an [`InterfaceState`] is required for each interface. #[derive(Debug)] -pub struct InterfaceState { +pub(crate) struct InterfaceState { /// Address this instance is bound to. addr: IpAddr, /// Receive socket. @@ -77,7 +77,7 @@ where T: Builder + futures::Stream, { /// Builds a new [`InterfaceState`]. - pub fn new(addr: IpAddr, config: Config, local_peer_id: PeerId) -> io::Result { + pub(crate) fn new(addr: IpAddr, config: Config, local_peer_id: PeerId) -> io::Result { log::info!("creating instance on iface {}", addr); let recv_socket = match addr { IpAddr::V4(addr) => { @@ -141,15 +141,15 @@ where }) } - pub fn reset_timer(&mut self) { + pub(crate) fn reset_timer(&mut self) { self.timeout = T::interval(self.query_interval); } - pub fn fire_timer(&mut self) { + pub(crate) fn fire_timer(&mut self) { self.timeout = T::interval_at(Instant::now(), self.query_interval); } - pub fn poll( + pub(crate) fn poll( &mut self, cx: &mut Context, listen_addresses: &ListenAddresses, diff --git a/protocols/mdns/src/behaviour/iface/dns.rs b/protocols/mdns/src/behaviour/iface/dns.rs index 0e277d65cbe..6a10497e69f 100644 --- a/protocols/mdns/src/behaviour/iface/dns.rs +++ b/protocols/mdns/src/behaviour/iface/dns.rs @@ -47,11 +47,10 @@ const MAX_PACKET_SIZE: usize = 9000 - 68; const MAX_RECORDS_PER_PACKET: usize = (MAX_PACKET_SIZE - 100) / MAX_TXT_RECORD_SIZE; /// An encoded MDNS packet. -pub type MdnsPacket = Vec; - +pub(crate) type MdnsPacket = Vec; /// Decodes a `` (as defined by RFC1035) into a `Vec` of ASCII characters. // TODO: better error type? -pub fn decode_character_string(mut from: &[u8]) -> Result, ()> { +pub(crate) fn decode_character_string(mut from: &[u8]) -> Result, ()> { if from.is_empty() { return Ok(Cow::Owned(Vec::new())); } @@ -70,7 +69,7 @@ pub fn decode_character_string(mut from: &[u8]) -> Result, ()> { } /// Builds the binary representation of a DNS query to send on the network. -pub fn build_query() -> MdnsPacket { +pub(crate) fn build_query() -> MdnsPacket { let mut out = Vec::with_capacity(33); // Program-generated transaction ID; unused by our implementation. @@ -104,7 +103,7 @@ pub fn build_query() -> MdnsPacket { /// Builds the response to an address discovery DNS query. /// /// If there are more than 2^16-1 addresses, ignores the rest. -pub fn build_query_response<'a>( +pub(crate) fn build_query_response<'a>( id: u16, peer_id: PeerId, addresses: impl ExactSizeIterator, @@ -166,7 +165,7 @@ pub fn build_query_response<'a>( } /// Builds the response to a service discovery DNS query. -pub fn build_service_discovery_response(id: u16, ttl: Duration) -> MdnsPacket { +pub(crate) fn build_service_discovery_response(id: u16, ttl: Duration) -> MdnsPacket { // Convert the TTL into seconds. let ttl = duration_to_secs(ttl); diff --git a/protocols/mdns/src/behaviour/iface/query.rs b/protocols/mdns/src/behaviour/iface/query.rs index 5eb491dbbf6..745926cf658 100644 --- a/protocols/mdns/src/behaviour/iface/query.rs +++ b/protocols/mdns/src/behaviour/iface/query.rs @@ -34,7 +34,7 @@ use trust_dns_proto::{ /// A valid mDNS packet received by the service. #[derive(Debug)] -pub enum MdnsPacket { +pub(crate) enum MdnsPacket { /// A query made by a remote. Query(MdnsQuery), /// A response sent by a remote in response to one of our queries. @@ -44,7 +44,7 @@ pub enum MdnsPacket { } impl MdnsPacket { - pub fn new_from_bytes( + pub(crate) fn new_from_bytes( buf: &[u8], from: SocketAddr, ) -> Result, trust_dns_proto::error::ProtoError> { @@ -82,7 +82,7 @@ impl MdnsPacket { } /// A received mDNS query. -pub struct MdnsQuery { +pub(crate) struct MdnsQuery { /// Sender of the address. from: SocketAddr, /// Id of the received DNS query. We need to pass this ID back in the results. @@ -91,12 +91,12 @@ pub struct MdnsQuery { impl MdnsQuery { /// Source address of the packet. - pub fn remote_addr(&self) -> &SocketAddr { + pub(crate) fn remote_addr(&self) -> &SocketAddr { &self.from } /// Query id of the packet. - pub fn query_id(&self) -> u16 { + pub(crate) fn query_id(&self) -> u16 { self.query_id } } @@ -111,7 +111,7 @@ impl fmt::Debug for MdnsQuery { } /// A received mDNS service discovery query. -pub struct MdnsServiceDiscovery { +pub(crate) struct MdnsServiceDiscovery { /// Sender of the address. from: SocketAddr, /// Id of the received DNS query. We need to pass this ID back in the results. @@ -120,12 +120,12 @@ pub struct MdnsServiceDiscovery { impl MdnsServiceDiscovery { /// Source address of the packet. - pub fn remote_addr(&self) -> &SocketAddr { + pub(crate) fn remote_addr(&self) -> &SocketAddr { &self.from } /// Query id of the packet. - pub fn query_id(&self) -> u16 { + pub(crate) fn query_id(&self) -> u16 { self.query_id } } @@ -140,14 +140,14 @@ impl fmt::Debug for MdnsServiceDiscovery { } /// A received mDNS response. -pub struct MdnsResponse { +pub(crate) struct MdnsResponse { peers: Vec, from: SocketAddr, } impl MdnsResponse { /// Creates a new `MdnsResponse` based on the provided `Packet`. - pub fn new(packet: &Message, from: SocketAddr) -> MdnsResponse { + pub(crate) fn new(packet: &Message, from: SocketAddr) -> MdnsResponse { let peers = packet .answers() .iter() @@ -168,7 +168,7 @@ impl MdnsResponse { MdnsResponse { peers, from } } - pub fn extract_discovered( + pub(crate) fn extract_discovered( &self, now: Instant, local_peer_id: PeerId, @@ -188,7 +188,7 @@ impl MdnsResponse { } /// Source address of the packet. - pub fn remote_addr(&self) -> &SocketAddr { + pub(crate) fn remote_addr(&self) -> &SocketAddr { &self.from } @@ -218,7 +218,7 @@ impl fmt::Debug for MdnsResponse { } /// A peer discovered by the service. -pub struct MdnsPeer { +pub(crate) struct MdnsPeer { addrs: Vec, /// Id of the peer. peer_id: PeerId, @@ -228,7 +228,7 @@ pub struct MdnsPeer { impl MdnsPeer { /// Creates a new `MdnsPeer` based on the provided `Packet`. - pub fn new(packet: &Message, record_value: &Name, ttl: u32) -> Option { + pub(crate) fn new(packet: &Message, record_value: &Name, ttl: u32) -> Option { let mut my_peer_id: Option = None; let addrs = packet .additionals() @@ -291,20 +291,20 @@ impl MdnsPeer { /// Returns the id of the peer. #[inline] - pub fn id(&self) -> &PeerId { + pub(crate) fn id(&self) -> &PeerId { &self.peer_id } /// Returns the requested time-to-live for the record. #[inline] - pub fn ttl(&self) -> Duration { + pub(crate) fn ttl(&self) -> Duration { Duration::from_secs(u64::from(self.ttl)) } /// Returns the list of addresses the peer says it is listening on. /// /// Filters out invalid addresses. - pub fn addresses(&self) -> &Vec { + pub(crate) fn addresses(&self) -> &Vec { &self.addrs } } diff --git a/protocols/mdns/src/behaviour/socket.rs b/protocols/mdns/src/behaviour/socket.rs index 4406ed33fde..fa9e0fbaf1e 100644 --- a/protocols/mdns/src/behaviour/socket.rs +++ b/protocols/mdns/src/behaviour/socket.rs @@ -26,6 +26,7 @@ use std::{ }; /// Interface that must be implemented by the different runtimes to use the [`UdpSocket`] in async mode +#[allow(unreachable_pub)] // Users should not depend on this. pub trait AsyncSocket: Unpin + Send + 'static { /// Create the async socket from the [`std::net::UdpSocket`] fn from_std(socket: UdpSocket) -> std::io::Result @@ -49,14 +50,13 @@ pub trait AsyncSocket: Unpin + Send + 'static { } #[cfg(feature = "async-io")] -pub mod asio { +pub(crate) mod asio { use super::*; use async_io::Async; use futures::FutureExt; /// AsyncIo UdpSocket - pub type AsyncUdpSocket = Async; - + pub(crate) type AsyncUdpSocket = Async; impl AsyncSocket for AsyncUdpSocket { fn from_std(socket: UdpSocket) -> std::io::Result { Async::new(socket) @@ -92,13 +92,12 @@ pub mod asio { } #[cfg(feature = "tokio")] -pub mod tokio { +pub(crate) mod tokio { use super::*; use ::tokio::{io::ReadBuf, net::UdpSocket as TkUdpSocket}; /// Tokio ASync Socket` - pub type TokioUdpSocket = TkUdpSocket; - + pub(crate) type TokioUdpSocket = TkUdpSocket; impl AsyncSocket for TokioUdpSocket { fn from_std(socket: UdpSocket) -> std::io::Result { socket.set_nonblocking(true)?; diff --git a/protocols/mdns/src/behaviour/timer.rs b/protocols/mdns/src/behaviour/timer.rs index b503459258c..29622be9a38 100644 --- a/protocols/mdns/src/behaviour/timer.rs +++ b/protocols/mdns/src/behaviour/timer.rs @@ -31,6 +31,7 @@ pub struct Timer { } /// Builder interface to homogenize the different implementations +#[allow(unreachable_pub)] // Users should not depend on this. pub trait Builder: Send + Unpin + 'static { /// Creates a timer that emits an event once at the given time instant. fn at(instant: Instant) -> Self; @@ -43,7 +44,7 @@ pub trait Builder: Send + Unpin + 'static { } #[cfg(feature = "async-io")] -pub mod asio { +pub(crate) mod asio { use super::*; use async_io::Timer as AsioTimer; use futures::Stream; @@ -53,8 +54,7 @@ pub mod asio { }; /// Async Timer - pub type AsyncTimer = Timer; - + pub(crate) type AsyncTimer = Timer; impl Builder for AsyncTimer { fn at(instant: Instant) -> Self { Self { @@ -85,7 +85,7 @@ pub mod asio { } #[cfg(feature = "tokio")] -pub mod tokio { +pub(crate) mod tokio { use super::*; use ::tokio::time::{self, Instant as TokioInstant, Interval, MissedTickBehavior}; use futures::Stream; @@ -95,8 +95,7 @@ pub mod tokio { }; /// Tokio wrapper - pub type TokioTimer = Timer; - + pub(crate) type TokioTimer = Timer; impl Builder for TokioTimer { fn at(instant: Instant) -> Self { // Taken from: https://docs.rs/async-io/1.7.0/src/async_io/lib.rs.html#91 diff --git a/protocols/perf/src/protocol.rs b/protocols/perf/src/protocol.rs index 808ea45752b..7f9c5137c9a 100644 --- a/protocols/perf/src/protocol.rs +++ b/protocols/perf/src/protocol.rs @@ -26,7 +26,7 @@ use crate::{client, server}; const BUF: [u8; 1024] = [0; 1024]; -pub async fn send_receive( +pub(crate) async fn send_receive( params: client::RunParams, mut stream: S, ) -> Result { @@ -67,7 +67,7 @@ pub async fn send_receive( }) } -pub async fn receive_send( +pub(crate) async fn receive_send( mut stream: S, ) -> Result { let to_send = { diff --git a/protocols/ping/src/protocol.rs b/protocols/ping/src/protocol.rs index 3c44adcd0b4..032b4aa0a0a 100644 --- a/protocols/ping/src/protocol.rs +++ b/protocols/ping/src/protocol.rs @@ -45,12 +45,11 @@ pub const PROTOCOL_NAME: &[u8] = b"/ipfs/ping/1.0.0"; /// > which can affect latencies especially on otherwise low-volume /// > connections. #[derive(Default, Debug, Copy, Clone)] -pub struct Ping; - +pub(crate) struct Ping; const PING_SIZE: usize = 32; /// Sends a ping and waits for the pong. -pub async fn send_ping(mut stream: S) -> io::Result<(S, Duration)> +pub(crate) async fn send_ping(mut stream: S) -> io::Result<(S, Duration)> where S: AsyncRead + AsyncWrite + Unpin, { @@ -71,7 +70,7 @@ where } /// Waits for a ping and sends a pong. -pub async fn recv_ping(mut stream: S) -> io::Result +pub(crate) async fn recv_ping(mut stream: S) -> io::Result where S: AsyncRead + AsyncWrite + Unpin, { diff --git a/protocols/relay/src/behaviour.rs b/protocols/relay/src/behaviour.rs index f21b699114b..9f2852dd19e 100644 --- a/protocols/relay/src/behaviour.rs +++ b/protocols/relay/src/behaviour.rs @@ -21,8 +21,7 @@ //! [`NetworkBehaviour`] to act as a circuit relay v2 **relay**. mod handler; -pub mod rate_limiter; - +pub(crate) mod rate_limiter; use crate::behaviour::handler::Handler; use crate::multiaddr_ext::MultiaddrExt; use crate::proto; diff --git a/protocols/relay/src/behaviour/handler.rs b/protocols/relay/src/behaviour/handler.rs index 88147a307e7..29b5c4b9dbd 100644 --- a/protocols/relay/src/behaviour/handler.rs +++ b/protocols/relay/src/behaviour/handler.rs @@ -962,7 +962,7 @@ pub struct OutboundOpenInfo { src_connection_id: ConnectionId, } -pub struct CircuitParts { +pub(crate) struct CircuitParts { circuit_id: CircuitId, src_stream: NegotiatedSubstream, src_pending_data: Bytes, diff --git a/protocols/relay/src/behaviour/rate_limiter.rs b/protocols/relay/src/behaviour/rate_limiter.rs index 542b23e5c43..31223c309f2 100644 --- a/protocols/relay/src/behaviour/rate_limiter.rs +++ b/protocols/relay/src/behaviour/rate_limiter.rs @@ -18,13 +18,15 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -pub use generic::{ - RateLimiter as GenericRateLimiter, RateLimiterConfig as GenericRateLimiterConfig, -}; use instant::Instant; use libp2p_core::multiaddr::{Multiaddr, Protocol}; use libp2p_identity::PeerId; +use std::collections::{HashMap, VecDeque}; +use std::convert::TryInto; +use std::hash::Hash; use std::net::IpAddr; +use std::num::NonZeroU32; +use std::time::Duration; /// Allows rate limiting access to some resource based on the [`PeerId`] and /// [`Multiaddr`] of a remote peer. @@ -36,12 +38,12 @@ pub trait RateLimiter: Send { fn try_next(&mut self, peer: PeerId, addr: &Multiaddr, now: Instant) -> bool; } -pub fn new_per_peer(config: GenericRateLimiterConfig) -> Box { +pub(crate) fn new_per_peer(config: GenericRateLimiterConfig) -> Box { let mut limiter = GenericRateLimiter::new(config); Box::new(move |peer_id, _addr: &Multiaddr, now| limiter.try_next(peer_id, now)) } -pub fn new_per_ip(config: GenericRateLimiterConfig) -> Box { +pub(crate) fn new_per_ip(config: GenericRateLimiterConfig) -> Box { let mut limiter = GenericRateLimiter::new(config); Box::new(move |_peer_id, addr: &Multiaddr, now| { multiaddr_to_ip(addr) @@ -64,249 +66,235 @@ fn multiaddr_to_ip(addr: &Multiaddr) -> Option { }) } -mod generic { - use instant::Instant; - use std::collections::{HashMap, VecDeque}; - use std::convert::TryInto; - use std::hash::Hash; - use std::num::NonZeroU32; - use std::time::Duration; - - /// Rate limiter using the [Token Bucket] algorithm. - /// - /// [Token Bucket]: https://en.wikipedia.org/wiki/Token_bucket - pub struct RateLimiter { - limit: u32, - interval: Duration, +/// Rate limiter using the [Token Bucket] algorithm. +/// +/// [Token Bucket]: https://en.wikipedia.org/wiki/Token_bucket +pub(crate) struct GenericRateLimiter { + limit: u32, + interval: Duration, - refill_schedule: VecDeque<(Instant, Id)>, - buckets: HashMap, - } + refill_schedule: VecDeque<(Instant, Id)>, + buckets: HashMap, +} - /// Configuration for a [`RateLimiter`]. - #[derive(Debug, Clone, Copy)] - pub struct RateLimiterConfig { - /// The maximum number of tokens in the bucket at any point in time. - pub limit: NonZeroU32, - /// The interval at which a single token is added to the bucket. - pub interval: Duration, - } +/// Configuration for a [`GenericRateLimiter`]. +#[derive(Debug, Clone, Copy)] +pub(crate) struct GenericRateLimiterConfig { + /// The maximum number of tokens in the bucket at any point in time. + pub(crate) limit: NonZeroU32, + /// The interval at which a single token is added to the bucket. + pub(crate) interval: Duration, +} - impl RateLimiter { - pub(crate) fn new(config: RateLimiterConfig) -> Self { - assert!(!config.interval.is_zero()); +impl GenericRateLimiter { + pub(crate) fn new(config: GenericRateLimiterConfig) -> Self { + assert!(!config.interval.is_zero()); - Self { - limit: config.limit.into(), - interval: config.interval, - refill_schedule: Default::default(), - buckets: Default::default(), - } + Self { + limit: config.limit.into(), + interval: config.interval, + refill_schedule: Default::default(), + buckets: Default::default(), } + } - pub(crate) fn try_next(&mut self, id: Id, now: Instant) -> bool { - self.refill(now); - - match self.buckets.get_mut(&id) { - // If the bucket exists, try to take a token. - Some(balance) => match balance.checked_sub(1) { - Some(a) => { - *balance = a; - true - } - None => false, - }, - // If the bucket is missing, act like the bucket has `limit` number of tokens. Take one - // token and track the new bucket balance. - None => { - self.buckets.insert(id.clone(), self.limit - 1); - self.refill_schedule.push_back((now, id)); + pub(crate) fn try_next(&mut self, id: Id, now: Instant) -> bool { + self.refill(now); + + match self.buckets.get_mut(&id) { + // If the bucket exists, try to take a token. + Some(balance) => match balance.checked_sub(1) { + Some(a) => { + *balance = a; true } + None => false, + }, + // If the bucket is missing, act like the bucket has `limit` number of tokens. Take one + // token and track the new bucket balance. + None => { + self.buckets.insert(id.clone(), self.limit - 1); + self.refill_schedule.push_back((now, id)); + true } } + } - fn refill(&mut self, now: Instant) { - // Note when used with a high number of buckets: This loop refills all the to-be-refilled - // buckets at once, thus potentially delaying the parent call to `try_next`. - loop { - match self.refill_schedule.get(0) { - // Only continue if (a) there is a bucket and (b) the bucket has not already been - // refilled recently. - Some((last_refill, _)) if now.duration_since(*last_refill) >= self.interval => { - } - // Otherwise stop refilling. Items in `refill_schedule` are sorted, thus, if the - // first ain't ready, none of them are. - _ => return, - }; - - let (last_refill, id) = self - .refill_schedule - .pop_front() - .expect("Queue not to be empty."); - - // Get the current balance of the bucket. - let balance = self - .buckets - .get(&id) - .expect("Entry can only be removed via refill."); - - // Calculate the new balance. - let duration_since = now.duration_since(last_refill); - let new_tokens = duration_since - .as_micros() - // Note that the use of `as_micros` limits the number of tokens to 10^6 per second. - .checked_div(self.interval.as_micros()) - .and_then(|i| i.try_into().ok()) - .unwrap_or(u32::MAX); - let new_balance = balance.checked_add(new_tokens).unwrap_or(u32::MAX); - - // If the new balance is below the limit, update the bucket. - if new_balance < self.limit { - self.buckets - .insert(id.clone(), new_balance) - .expect("To override value."); - self.refill_schedule.push_back((now, id)); - } else { - // If the balance is above the limit, the bucket can be removed, given that a - // non-existing bucket is equivalent to a bucket with `limit` tokens. - self.buckets.remove(&id); - } + fn refill(&mut self, now: Instant) { + // Note when used with a high number of buckets: This loop refills all the to-be-refilled + // buckets at once, thus potentially delaying the parent call to `try_next`. + loop { + match self.refill_schedule.get(0) { + // Only continue if (a) there is a bucket and (b) the bucket has not already been + // refilled recently. + Some((last_refill, _)) if now.duration_since(*last_refill) >= self.interval => {} + // Otherwise stop refilling. Items in `refill_schedule` are sorted, thus, if the + // first ain't ready, none of them are. + _ => return, + }; + + let (last_refill, id) = self + .refill_schedule + .pop_front() + .expect("Queue not to be empty."); + + // Get the current balance of the bucket. + let balance = self + .buckets + .get(&id) + .expect("Entry can only be removed via refill."); + + // Calculate the new balance. + let duration_since = now.duration_since(last_refill); + let new_tokens = duration_since + .as_micros() + // Note that the use of `as_micros` limits the number of tokens to 10^6 per second. + .checked_div(self.interval.as_micros()) + .and_then(|i| i.try_into().ok()) + .unwrap_or(u32::MAX); + let new_balance = balance.checked_add(new_tokens).unwrap_or(u32::MAX); + + // If the new balance is below the limit, update the bucket. + if new_balance < self.limit { + self.buckets + .insert(id.clone(), new_balance) + .expect("To override value."); + self.refill_schedule.push_back((now, id)); + } else { + // If the balance is above the limit, the bucket can be removed, given that a + // non-existing bucket is equivalent to a bucket with `limit` tokens. + self.buckets.remove(&id); } } } +} - #[cfg(test)] - mod tests { - use super::*; - use quickcheck::{QuickCheck, TestResult}; - use std::num::NonZeroU32; - - #[test] - fn first() { - let id = 1; - let mut l = RateLimiter::new(RateLimiterConfig { - limit: NonZeroU32::new(10).unwrap(), - interval: Duration::from_secs(1), - }); - assert!(l.try_next(id, Instant::now())); - } +#[cfg(test)] +mod tests { + use super::*; + use quickcheck::{QuickCheck, TestResult}; + use std::num::NonZeroU32; - #[test] - fn limits() { - let id = 1; - let now = Instant::now(); - let mut l = RateLimiter::new(RateLimiterConfig { - limit: NonZeroU32::new(10).unwrap(), - interval: Duration::from_secs(1), - }); - for _ in 0..10 { - assert!(l.try_next(id, now)); - } + #[test] + fn first() { + let id = 1; + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { + limit: NonZeroU32::new(10).unwrap(), + interval: Duration::from_secs(1), + }); + assert!(l.try_next(id, Instant::now())); + } - assert!(!l.try_next(id, now)); + #[test] + fn limits() { + let id = 1; + let now = Instant::now(); + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { + limit: NonZeroU32::new(10).unwrap(), + interval: Duration::from_secs(1), + }); + for _ in 0..10 { + assert!(l.try_next(id, now)); } - #[test] - fn refills() { - let id = 1; - let now = Instant::now(); - let mut l = RateLimiter::new(RateLimiterConfig { - limit: NonZeroU32::new(10).unwrap(), - interval: Duration::from_secs(1), - }); - - for _ in 0..10 { - assert!(l.try_next(id, now)); - } - assert!(!l.try_next(id, now)); + assert!(!l.try_next(id, now)); + } - let now = now + Duration::from_secs(1); - assert!(l.try_next(id, now)); - assert!(!l.try_next(id, now)); + #[test] + fn refills() { + let id = 1; + let now = Instant::now(); + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { + limit: NonZeroU32::new(10).unwrap(), + interval: Duration::from_secs(1), + }); - let now = now + Duration::from_secs(10); - for _ in 0..10 { - assert!(l.try_next(id, now)); - } + for _ in 0..10 { + assert!(l.try_next(id, now)); } + assert!(!l.try_next(id, now)); - #[test] - fn move_at_half_interval_steps() { - let id = 1; - let now = Instant::now(); - let mut l = RateLimiter::new(RateLimiterConfig { - limit: NonZeroU32::new(1).unwrap(), - interval: Duration::from_secs(2), - }); + let now = now + Duration::from_secs(1); + assert!(l.try_next(id, now)); + assert!(!l.try_next(id, now)); + let now = now + Duration::from_secs(10); + for _ in 0..10 { assert!(l.try_next(id, now)); - assert!(!l.try_next(id, now)); + } + } - let now = now + Duration::from_secs(1); - assert!(!l.try_next(id, now)); + #[test] + fn move_at_half_interval_steps() { + let id = 1; + let now = Instant::now(); + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { + limit: NonZeroU32::new(1).unwrap(), + interval: Duration::from_secs(2), + }); - let now = now + Duration::from_secs(1); - assert!(l.try_next(id, now)); - } + assert!(l.try_next(id, now)); + assert!(!l.try_next(id, now)); - #[test] - fn garbage_collects() { - let now = Instant::now(); - let mut l = RateLimiter::new(RateLimiterConfig { - limit: NonZeroU32::new(1).unwrap(), - interval: Duration::from_secs(1), - }); + let now = now + Duration::from_secs(1); + assert!(!l.try_next(id, now)); - assert!(l.try_next(1, now)); + let now = now + Duration::from_secs(1); + assert!(l.try_next(id, now)); + } - let now = now + Duration::from_secs(1); - assert!(l.try_next(2, now)); + #[test] + fn garbage_collects() { + let now = Instant::now(); + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { + limit: NonZeroU32::new(1).unwrap(), + interval: Duration::from_secs(1), + }); - assert_eq!(l.buckets.len(), 1); - assert_eq!(l.refill_schedule.len(), 1); - } + assert!(l.try_next(1, now)); - #[test] - fn quick_check() { - fn prop( - limit: NonZeroU32, - interval: Duration, - events: Vec<(u32, Duration)>, - ) -> TestResult { - if interval.is_zero() { - return TestResult::discard(); - } + let now = now + Duration::from_secs(1); + assert!(l.try_next(2, now)); - let mut now = Instant::now(); - let mut l = RateLimiter::new(RateLimiterConfig { limit, interval }); + assert_eq!(l.buckets.len(), 1); + assert_eq!(l.refill_schedule.len(), 1); + } - for (id, d) in events { - now = if let Some(now) = now.checked_add(d) { - now - } else { - return TestResult::discard(); - }; - l.try_next(id, now); - } + #[test] + fn quick_check() { + fn prop(limit: NonZeroU32, interval: Duration, events: Vec<(u32, Duration)>) -> TestResult { + if interval.is_zero() { + return TestResult::discard(); + } + + let mut now = Instant::now(); + let mut l = GenericRateLimiter::new(GenericRateLimiterConfig { limit, interval }); - now = if let Some(now) = interval - .checked_mul(limit.into()) - .and_then(|full_interval| now.checked_add(full_interval)) - { + for (id, d) in events { + now = if let Some(now) = now.checked_add(d) { now } else { return TestResult::discard(); }; - assert!(l.try_next(1, now)); + l.try_next(id, now); + } - assert_eq!(l.buckets.len(), 1); - assert_eq!(l.refill_schedule.len(), 1); + now = if let Some(now) = interval + .checked_mul(limit.into()) + .and_then(|full_interval| now.checked_add(full_interval)) + { + now + } else { + return TestResult::discard(); + }; + assert!(l.try_next(1, now)); - TestResult::passed() - } + assert_eq!(l.buckets.len(), 1); + assert_eq!(l.refill_schedule.len(), 1); - QuickCheck::new().quickcheck(prop as fn(_, _, _) -> _) + TestResult::passed() } + + QuickCheck::new().quickcheck(prop as fn(_, _, _) -> _) } } diff --git a/protocols/relay/src/copy_future.rs b/protocols/relay/src/copy_future.rs index 2f9eabed349..755344cd698 100644 --- a/protocols/relay/src/copy_future.rs +++ b/protocols/relay/src/copy_future.rs @@ -36,7 +36,7 @@ use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; -pub struct CopyFuture { +pub(crate) struct CopyFuture { src: BufReader, dst: BufReader, @@ -46,7 +46,12 @@ pub struct CopyFuture { } impl CopyFuture { - pub fn new(src: S, dst: D, max_circuit_duration: Duration, max_circuit_bytes: u64) -> Self { + pub(crate) fn new( + src: S, + dst: D, + max_circuit_duration: Duration, + max_circuit_bytes: u64, + ) -> Self { CopyFuture { src: BufReader::new(src), dst: BufReader::new(dst), diff --git a/protocols/relay/src/lib.rs b/protocols/relay/src/lib.rs index 05b6292c9e2..8421026d984 100644 --- a/protocols/relay/src/lib.rs +++ b/protocols/relay/src/lib.rs @@ -31,10 +31,13 @@ mod protocol; pub mod v2; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::message_v2::pb::mod_HopMessage::Type as HopMessageType; + pub(crate) use self::message_v2::pb::mod_HopMessage::Type as HopMessageType; pub use self::message_v2::pb::mod_StopMessage::Type as StopMessageType; - pub use self::message_v2::pb::{HopMessage, Limit, Peer, Reservation, Status, StopMessage}; + pub(crate) use self::message_v2::pb::{ + HopMessage, Limit, Peer, Reservation, Status, StopMessage, + }; } pub use behaviour::{Behaviour, CircuitId, Config, Event}; diff --git a/protocols/relay/src/protocol.rs b/protocols/relay/src/protocol.rs index 4933eb6a523..2c471d36dd9 100644 --- a/protocols/relay/src/protocol.rs +++ b/protocols/relay/src/protocol.rs @@ -21,11 +21,10 @@ use crate::proto; use std::time::Duration; -pub mod inbound_hop; -pub mod inbound_stop; -pub mod outbound_hop; -pub mod outbound_stop; - +pub(crate) mod inbound_hop; +pub(crate) mod inbound_stop; +pub(crate) mod outbound_hop; +pub(crate) mod outbound_stop; pub const HOP_PROTOCOL_NAME: &[u8; 31] = b"/libp2p/circuit/relay/0.2.0/hop"; pub const STOP_PROTOCOL_NAME: &[u8; 32] = b"/libp2p/circuit/relay/0.2.0/stop"; diff --git a/protocols/rendezvous/src/codec.rs b/protocols/rendezvous/src/codec.rs index 39447a56bdb..716ad79893f 100644 --- a/protocols/rendezvous/src/codec.rs +++ b/protocols/rendezvous/src/codec.rs @@ -559,8 +559,9 @@ impl From for ConversionError { pub struct UnmappableStatusCode(proto::ResponseStatus); mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::rendezvous::pb::{mod_Message::*, Message}; + pub(crate) use self::rendezvous::pb::{mod_Message::*, Message}; } #[cfg(test)] diff --git a/protocols/rendezvous/src/handler.rs b/protocols/rendezvous/src/handler.rs index d07bf4d248f..f69748a400b 100644 --- a/protocols/rendezvous/src/handler.rs +++ b/protocols/rendezvous/src/handler.rs @@ -24,9 +24,8 @@ use void::Void; const PROTOCOL_IDENT: &[u8] = b"/rendezvous/1.0.0"; -pub mod inbound; -pub mod outbound; - +pub(crate) mod inbound; +pub(crate) mod outbound; /// Errors that can occur while interacting with a substream. #[allow(clippy::large_enum_variant)] #[derive(Debug, thiserror::Error)] @@ -41,9 +40,10 @@ pub enum Error { UnexpectedEndOfStream, } -pub type OutboundInEvent = crate::substream_handler::InEvent; -pub type OutboundOutEvent = +pub(crate) type OutboundInEvent = crate::substream_handler::InEvent; +pub(crate) type OutboundOutEvent = crate::substream_handler::OutEvent; -pub type InboundInEvent = crate::substream_handler::InEvent<(), inbound::InEvent, Void>; -pub type InboundOutEvent = crate::substream_handler::OutEvent; +pub(crate) type InboundInEvent = crate::substream_handler::InEvent<(), inbound::InEvent, Void>; +pub(crate) type InboundOutEvent = + crate::substream_handler::OutEvent; diff --git a/protocols/rendezvous/src/substream_handler.rs b/protocols/rendezvous/src/substream_handler.rs index 16a493ccc3a..f5f79451b09 100644 --- a/protocols/rendezvous/src/substream_handler.rs +++ b/protocols/rendezvous/src/substream_handler.rs @@ -503,18 +503,20 @@ where /// A helper struct for substream handlers that can be implemented as async functions. /// /// This only works for substreams without an `InEvent` because - once constructed - the state of an inner future is opaque. -pub struct FutureSubstream { +pub(crate) struct FutureSubstream { future: Fuse>>, } impl FutureSubstream { - pub fn new(future: impl Future> + Send + 'static) -> Self { + pub(crate) fn new( + future: impl Future> + Send + 'static, + ) -> Self { Self { future: future.boxed().fuse(), } } - pub fn advance(mut self, cx: &mut Context<'_>) -> Result, TError> { + pub(crate) fn advance(mut self, cx: &mut Context<'_>) -> Result, TError> { if self.future.is_terminated() { return Ok(Next::Done); } diff --git a/scripts/fix-unreachable-pub.py b/scripts/fix-unreachable-pub.py new file mode 100644 index 00000000000..2e3eb5d9037 --- /dev/null +++ b/scripts/fix-unreachable-pub.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 + +import json +import re +import sys +from pathlib import Path + + +# Use this script by piping the output of clippy into it: +# > cargo clippy --workspace --all-features --all-targets --message-format=json -- -W unreachable_pub | python scripts/fix-unreachable-pub.py +# +# You might have to run this in a loop as restricting the visibility of one item can trigger the warning for another item. + +def fix_unreachable_pub_warning(warning): + file_path = Path(warning["spans"][0]["file_name"]) + + try: + line = warning["spans"][0]["line_start"] + + # Don't modify generated code + if "generated" in str(file_path): + return + + with file_path.open() as f: + lines = f.readlines() + + pub_pattern = re.compile(r"(\s*)pub(\s)(.*)") + match = pub_pattern.match(lines[line - 1]) + + if match: + indentation = match.group(1) + space = match.group(2) + rest_of_line = match.group(3) + lines[line - 1] = f"{indentation}pub(crate){space}{rest_of_line}" + + with file_path.open("w") as f: + f.writelines(lines) + except Exception as e: + print(f"Failed to apply suggestion in {file_path}: {e}") + + +def main(): + for line in sys.stdin: + # Ignore other compiler messages + if "unreachable_pub" not in line: + continue + + warning = json.loads(line.strip()) + + # Don't modify code that is not in the current workspace + if str(Path.cwd()) not in str(warning['target']['src_path']): + return + + m = warning["message"] + + if m is None: + continue + + code = m['code'] + + if code is None: + continue + + fix_unreachable_pub_warning(m) + + +if __name__ == "__main__": + main() diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index e7e71fdfebc..e813ad0c66d 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -22,9 +22,9 @@ mod error; pub(crate) mod pool; -pub use error::{ - ConnectionError, PendingConnectionError, PendingInboundConnectionError, - PendingOutboundConnectionError, +pub use error::ConnectionError; +pub(crate) use error::{ + PendingConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError, }; use crate::handler::{ @@ -85,16 +85,16 @@ impl ConnectionId { /// Information about a successfully established connection. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct Connected { +pub(crate) struct Connected { /// The connected endpoint, including network address information. - pub endpoint: ConnectedPoint, + pub(crate) endpoint: ConnectedPoint, /// Information obtained from the transport. - pub peer_id: PeerId, + pub(crate) peer_id: PeerId, } /// Event generated by a [`Connection`]. #[derive(Debug, Clone)] -pub enum Event { +pub(crate) enum Event { /// Event generated by the [`ConnectionHandler`]. Handler(T), /// Address of the remote has changed. @@ -102,7 +102,7 @@ pub enum Event { } /// A multiplexed connection to a peer with an associated [`ConnectionHandler`]. -pub struct Connection +pub(crate) struct Connection where THandler: ConnectionHandler, { @@ -167,7 +167,7 @@ where { /// Builds a new `Connection` from the given substream multiplexer /// and connection handler. - pub fn new( + pub(crate) fn new( muxer: StreamMuxerBox, handler: THandler, substream_upgrade_protocol_override: Option, @@ -186,19 +186,19 @@ where } /// Notifies the connection handler of an event. - pub fn on_behaviour_event(&mut self, event: THandler::InEvent) { + pub(crate) fn on_behaviour_event(&mut self, event: THandler::InEvent) { self.handler.on_behaviour_event(event); } /// Begins an orderly shutdown of the connection, returning the connection /// handler and a `Future` that resolves when connection shutdown is complete. - pub fn close(self) -> (THandler, impl Future>) { + pub(crate) fn close(self) -> (THandler, impl Future>) { (self.handler, self.muxing.close()) } /// Polls the handler and the substream, forwarding events from the former to the latter and /// vice versa. - pub fn poll( + pub(crate) fn poll( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll, ConnectionError>> { @@ -369,16 +369,16 @@ where /// Borrowed information about an incoming connection currently being negotiated. #[derive(Debug, Copy, Clone)] -pub struct IncomingInfo<'a> { +pub(crate) struct IncomingInfo<'a> { /// Local connection address. - pub local_addr: &'a Multiaddr, + pub(crate) local_addr: &'a Multiaddr, /// Address used to send back data to the remote. - pub send_back_addr: &'a Multiaddr, + pub(crate) send_back_addr: &'a Multiaddr, } impl<'a> IncomingInfo<'a> { /// Builds the [`ConnectedPoint`] corresponding to the incoming connection. - pub fn create_connected_point(&self) -> ConnectedPoint { + pub(crate) fn create_connected_point(&self) -> ConnectedPoint { ConnectedPoint::Listener { local_addr: self.local_addr.clone(), send_back_addr: self.send_back_addr.clone(), diff --git a/swarm/src/connection/error.rs b/swarm/src/connection/error.rs index 49a3ee65f12..9e0c58a4e7d 100644 --- a/swarm/src/connection/error.rs +++ b/swarm/src/connection/error.rs @@ -78,11 +78,11 @@ impl From for ConnectionError { /// Note: Addresses for an outbound connection are dialed in parallel. Thus, compared to /// [`PendingInboundConnectionError`], one or more [`TransportError`]s can occur for a single /// connection. -pub type PendingOutboundConnectionError = +pub(crate) type PendingOutboundConnectionError = PendingConnectionError)>>; /// Errors that can occur in the context of a pending incoming `Connection`. -pub type PendingInboundConnectionError = PendingConnectionError>; +pub(crate) type PendingInboundConnectionError = PendingConnectionError>; /// Errors that can occur in the context of a pending `Connection`. #[derive(Debug)] diff --git a/swarm/src/connection/pool.rs b/swarm/src/connection/pool.rs index 5cb70173a92..68ad16ad36a 100644 --- a/swarm/src/connection/pool.rs +++ b/swarm/src/connection/pool.rs @@ -84,7 +84,7 @@ impl ExecSwitch { } /// A connection `Pool` manages a set of connections for each peer. -pub struct Pool +pub(crate) struct Pool where THandler: ConnectionHandler, { @@ -140,7 +140,7 @@ where } #[derive(Debug)] -pub struct EstablishedConnection { +pub(crate) struct EstablishedConnection { endpoint: ConnectedPoint, /// Channel endpoint to send commands to the task. sender: mpsc::Sender>, @@ -157,7 +157,7 @@ impl EstablishedConnection { /// `poll_ready_notify_handler` without another intervening execution /// of `notify_handler`, it only fails if the connection is now about /// to close. - pub fn notify_handler(&mut self, event: TInEvent) -> Result<(), TInEvent> { + pub(crate) fn notify_handler(&mut self, event: TInEvent) -> Result<(), TInEvent> { let cmd = task::Command::NotifyHandler(event); self.sender.try_send(cmd).map_err(|e| match e.into_inner() { task::Command::NotifyHandler(event) => event, @@ -171,14 +171,17 @@ impl EstablishedConnection { /// /// Returns `Err(())` if the background task associated with the connection /// is terminating and the connection is about to close. - pub fn poll_ready_notify_handler(&mut self, cx: &mut Context<'_>) -> Poll> { + pub(crate) fn poll_ready_notify_handler( + &mut self, + cx: &mut Context<'_>, + ) -> Poll> { self.sender.poll_ready(cx).map_err(|_| ()) } /// Initiates a graceful close of the connection. /// /// Has no effect if the connection is already closing. - pub fn start_close(&mut self) { + pub(crate) fn start_close(&mut self) { // Clone the sender so that we are guaranteed to have // capacity for the close command (every sender gets a slot). match self.sender.clone().try_send(task::Command::Close) { @@ -221,7 +224,7 @@ impl fmt::Debug for Pool { /// Event that can happen on the `Pool`. #[derive(Debug)] -pub enum PoolEvent { +pub(crate) enum PoolEvent { /// A new connection has been established. ConnectionEstablished { id: ConnectionId, @@ -306,7 +309,7 @@ where { /// Creates a new empty `Pool`. #[allow(deprecated)] - pub fn new(local_id: PeerId, config: PoolConfig, limits: ConnectionLimits) -> Self { + pub(crate) fn new(local_id: PeerId, config: PoolConfig, limits: ConnectionLimits) -> Self { let (pending_connection_events_tx, pending_connection_events_rx) = mpsc::channel(0); let executor = match config.executor { Some(exec) => ExecSwitch::Executor(exec), @@ -332,12 +335,12 @@ where } /// Gets the dedicated connection counters. - pub fn counters(&self) -> &ConnectionCounters { + pub(crate) fn counters(&self) -> &ConnectionCounters { &self.counters } /// Gets an established connection from the pool by ID. - pub fn get_established( + pub(crate) fn get_established( &mut self, id: ConnectionId, ) -> Option<&mut EstablishedConnection> { @@ -349,13 +352,13 @@ where /// Returns true if we are connected to the given peer. /// /// This will return true only after a `NodeReached` event has been produced by `poll()`. - pub fn is_connected(&self, id: PeerId) -> bool { + pub(crate) fn is_connected(&self, id: PeerId) -> bool { self.established.contains_key(&id) } /// Returns the number of connected peers, i.e. those with at least one /// established connection in the pool. - pub fn num_peers(&self) -> usize { + pub(crate) fn num_peers(&self) -> usize { self.established.len() } @@ -364,7 +367,7 @@ where /// All connections to the peer, whether pending or established are /// closed asap and no more events from these connections are emitted /// by the pool effective immediately. - pub fn disconnect(&mut self, peer: PeerId) { + pub(crate) fn disconnect(&mut self, peer: PeerId) { if let Some(conns) = self.established.get_mut(&peer) { for (_, conn) in conns.iter_mut() { conn.start_close(); @@ -381,7 +384,7 @@ where } /// Returns an iterator over all established connections of `peer`. - pub fn iter_established_connections_of_peer( + pub(crate) fn iter_established_connections_of_peer( &mut self, peer: &PeerId, ) -> impl Iterator + '_ { @@ -392,7 +395,7 @@ where } /// Checks whether we are currently dialing the given peer. - pub fn is_dialing(&self, peer: PeerId) -> bool { + pub(crate) fn is_dialing(&self, peer: PeerId) -> bool { self.pending.iter().any(|(_, info)| { matches!(info.endpoint, PendingPoint::Dialer { .. }) && info.is_for_same_remote_as(peer) }) @@ -400,7 +403,7 @@ where /// Returns an iterator over all connected peers, i.e. those that have /// at least one established connection in the pool. - pub fn iter_connected(&self) -> impl Iterator { + pub(crate) fn iter_connected(&self) -> impl Iterator { self.established.keys() } @@ -410,7 +413,7 @@ where /// Returns an error if the limit of pending outgoing connections /// has been reached. #[allow(deprecated)] - pub fn add_outgoing( + pub(crate) fn add_outgoing( &mut self, dials: Vec< BoxFuture< @@ -465,7 +468,7 @@ where /// Returns an error if the limit of pending incoming connections /// has been reached. #[allow(deprecated)] - pub fn add_incoming( + pub(crate) fn add_incoming( &mut self, future: TFut, info: IncomingInfo<'_>, @@ -503,7 +506,7 @@ where } #[allow(deprecated)] - pub fn spawn_connection( + pub(crate) fn spawn_connection( &mut self, id: ConnectionId, obtained_peer_id: PeerId, @@ -548,7 +551,7 @@ where } /// Polls the connection pool for events. - pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll> + pub(crate) fn poll(&mut self, cx: &mut Context<'_>) -> Poll> where THandler: ConnectionHandler + 'static, ::OutboundOpenInfo: Send, @@ -832,7 +835,7 @@ where /// /// On drop, this type send the connection back to the [`Pool`] where it will be gracefully closed. #[derive(Debug)] -pub struct NewConnection { +pub(crate) struct NewConnection { connection: Option, drop_sender: Option>, } @@ -1101,20 +1104,16 @@ impl ConnectionLimits { /// /// The default configuration specifies no dedicated task executor, a /// task event buffer size of 32, and a task command buffer size of 7. -pub struct PoolConfig { +pub(crate) struct PoolConfig { /// Executor to use to spawn tasks. - pub executor: Option>, - + pub(crate) executor: Option>, /// Size of the task command buffer (per task). - pub task_command_buffer_size: usize, - + pub(crate) task_command_buffer_size: usize, /// Size of the pending connection task event buffer and the established connection task event /// buffer. - pub per_connection_event_buffer_size: usize, - + pub(crate) per_connection_event_buffer_size: usize, /// Number of addresses concurrently dialed for a single outbound connection attempt. - pub dial_concurrency_factor: NonZeroU8, - + pub(crate) dial_concurrency_factor: NonZeroU8, /// The configured override for substream protocol upgrades, if any. substream_upgrade_protocol_override: Option, @@ -1125,7 +1124,7 @@ pub struct PoolConfig { } impl PoolConfig { - pub fn new(executor: Option>) -> Self { + pub(crate) fn new(executor: Option>) -> Self { Self { executor, task_command_buffer_size: 32, @@ -1143,7 +1142,7 @@ impl PoolConfig { /// When the buffer for a particular connection is full, `notify_handler` will no /// longer be able to deliver events to the associated [`Connection`](super::Connection), /// thus exerting back-pressure on the connection and peer API. - pub fn with_notify_handler_buffer_size(mut self, n: NonZeroUsize) -> Self { + pub(crate) fn with_notify_handler_buffer_size(mut self, n: NonZeroUsize) -> Self { self.task_command_buffer_size = n.get() - 1; self } @@ -1154,19 +1153,19 @@ impl PoolConfig { /// When the buffer is full, the background tasks of all connections will stall. /// In this way, the consumers of network events exert back-pressure on /// the network connection I/O. - pub fn with_per_connection_event_buffer_size(mut self, n: usize) -> Self { + pub(crate) fn with_per_connection_event_buffer_size(mut self, n: usize) -> Self { self.per_connection_event_buffer_size = n; self } /// Number of addresses concurrently dialed for a single outbound connection attempt. - pub fn with_dial_concurrency_factor(mut self, factor: NonZeroU8) -> Self { + pub(crate) fn with_dial_concurrency_factor(mut self, factor: NonZeroU8) -> Self { self.dial_concurrency_factor = factor; self } /// Configures an override for the substream upgrade protocol to use. - pub fn with_substream_upgrade_protocol_override( + pub(crate) fn with_substream_upgrade_protocol_override( mut self, v: libp2p_core::upgrade::Version, ) -> Self { @@ -1177,7 +1176,7 @@ impl PoolConfig { /// The maximum number of inbound streams concurrently negotiating on a connection. /// /// See [`Connection::max_negotiating_inbound_streams`]. - pub fn with_max_negotiating_inbound_streams(mut self, v: usize) -> Self { + pub(crate) fn with_max_negotiating_inbound_streams(mut self, v: usize) -> Self { self.max_negotiating_inbound_streams = v; self } diff --git a/swarm/src/connection/pool/concurrent_dial.rs b/swarm/src/connection/pool/concurrent_dial.rs index 024c21a568d..57e4b078098 100644 --- a/swarm/src/connection/pool/concurrent_dial.rs +++ b/swarm/src/connection/pool/concurrent_dial.rs @@ -40,7 +40,7 @@ type Dial = BoxFuture< ), >; -pub struct ConcurrentDial { +pub(crate) struct ConcurrentDial { dials: FuturesUnordered, pending_dials: Box + Send>, errors: Vec<(Multiaddr, TransportError)>, diff --git a/swarm/src/connection/pool/task.rs b/swarm/src/connection/pool/task.rs index 27a2a4780a3..dd318f77d30 100644 --- a/swarm/src/connection/pool/task.rs +++ b/swarm/src/connection/pool/task.rs @@ -41,7 +41,7 @@ use void::Void; /// Commands that can be sent to a task driving an established connection. #[derive(Debug)] -pub enum Command { +pub(crate) enum Command { /// Notify the connection handler of an event. NotifyHandler(T), /// Gracefully close the connection (active close) before @@ -49,7 +49,7 @@ pub enum Command { Close, } -pub enum PendingConnectionEvent { +pub(crate) enum PendingConnectionEvent { ConnectionEstablished { id: ConnectionId, output: (PeerId, StreamMuxerBox), @@ -66,7 +66,7 @@ pub enum PendingConnectionEvent { } #[derive(Debug)] -pub enum EstablishedConnectionEvent { +pub(crate) enum EstablishedConnectionEvent { /// A node we are connected to has changed its address. AddressChange { id: ConnectionId, @@ -91,7 +91,7 @@ pub enum EstablishedConnectionEvent { }, } -pub async fn new_for_pending_outgoing_connection( +pub(crate) async fn new_for_pending_outgoing_connection( connection_id: ConnectionId, dial: ConcurrentDial, abort_receiver: oneshot::Receiver, @@ -127,7 +127,7 @@ pub async fn new_for_pending_outgoing_connection( } } -pub async fn new_for_pending_incoming_connection( +pub(crate) async fn new_for_pending_incoming_connection( connection_id: ConnectionId, future: TFut, abort_receiver: oneshot::Receiver, @@ -167,7 +167,7 @@ pub async fn new_for_pending_incoming_connection( } } -pub async fn new_for_established_connection( +pub(crate) async fn new_for_established_connection( connection_id: ConnectionId, peer_id: PeerId, mut connection: crate::connection::Connection, diff --git a/swarm/src/executor.rs b/swarm/src/executor.rs index d4b97a1d8b8..e949bf3cbde 100644 --- a/swarm/src/executor.rs +++ b/swarm/src/executor.rs @@ -31,8 +31,7 @@ impl Executor for ThreadPool { not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")) ))] #[derive(Default, Debug, Clone, Copy)] -pub struct TokioExecutor; - +pub(crate) struct TokioExecutor; #[cfg(all( feature = "tokio", not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")) @@ -48,8 +47,7 @@ impl Executor for TokioExecutor { not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")) ))] #[derive(Default, Debug, Clone, Copy)] -pub struct AsyncStdExecutor; - +pub(crate) struct AsyncStdExecutor; #[cfg(all( feature = "async-std", not(any(target_os = "emscripten", target_os = "wasi", target_os = "unknown")) @@ -62,8 +60,7 @@ impl Executor for AsyncStdExecutor { #[cfg(feature = "wasm-bindgen")] #[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] -pub struct WasmBindgenExecutor; - +pub(crate) struct WasmBindgenExecutor; #[cfg(feature = "wasm-bindgen")] impl Executor for WasmBindgenExecutor { fn exec(&self, future: Pin + Send>>) { diff --git a/swarm/src/registry.rs b/swarm/src/registry.rs index 04204930580..7f8225a6a25 100644 --- a/swarm/src/registry.rs +++ b/swarm/src/registry.rs @@ -42,7 +42,7 @@ use std::{cmp::Ordering, collections::VecDeque, num::NonZeroUsize}; /// it is removed from the collection. /// #[derive(Debug, Clone)] -pub struct Addresses { +pub(crate) struct Addresses { /// The ranked sequence of addresses, from highest to lowest score. /// /// By design, the number of finitely scored addresses stored here is @@ -171,7 +171,7 @@ pub enum AddAddressResult { impl Addresses { /// Create a new ranked address collection with the given size limit /// for [finitely scored](AddressScore::Finite) addresses. - pub fn new(limit: NonZeroUsize) -> Self { + pub(crate) fn new(limit: NonZeroUsize) -> Self { Addresses { registry: SmallVec::new(), limit, @@ -189,7 +189,7 @@ impl Addresses { /// as per this limited history has its score reduced by the amount /// used in this prior report, with removal from the collection /// occurring when the score drops to 0. - pub fn add(&mut self, addr: Multiaddr, score: AddressScore) -> AddAddressResult { + pub(crate) fn add(&mut self, addr: Multiaddr, score: AddressScore) -> AddAddressResult { // If enough reports (i.e. address additions) occurred, reduce // the score of the least-recently added address. if self.reports.len() == self.limit.get() { @@ -240,7 +240,7 @@ impl Addresses { /// /// Returns `true` if the address existed in the collection /// and was thus removed, false otherwise. - pub fn remove(&mut self, addr: &Multiaddr) -> bool { + pub(crate) fn remove(&mut self, addr: &Multiaddr) -> bool { if let Some(pos) = self.registry.iter().position(|r| &r.addr == addr) { self.registry.remove(pos); true @@ -252,7 +252,7 @@ impl Addresses { /// Return an iterator over all [`Multiaddr`] values. /// /// The iteration is ordered by descending score. - pub fn iter(&self) -> AddressIter<'_> { + pub(crate) fn iter(&self) -> AddressIter<'_> { AddressIter { items: &self.registry, offset: 0, @@ -262,7 +262,7 @@ impl Addresses { /// Return an iterator over all [`Multiaddr`] values. /// /// The iteration is ordered by descending score. - pub fn into_iter(self) -> AddressIntoIter { + pub(crate) fn into_iter(self) -> AddressIntoIter { AddressIntoIter { items: self.registry, } @@ -271,7 +271,7 @@ impl Addresses { /// An iterator over [`Multiaddr`] values. #[derive(Clone)] -pub struct AddressIter<'a> { +pub(crate) struct AddressIter<'a> { items: &'a [AddressRecord], offset: usize, } diff --git a/swarm/src/test.rs b/swarm/src/test.rs index ab5262ade6e..90738b6a6cf 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -34,7 +34,7 @@ use std::task::{Context, Poll}; /// A `MockBehaviour` is a `NetworkBehaviour` that allows for /// the instrumentation of return values, without keeping /// any further state. -pub struct MockBehaviour +pub(crate) struct MockBehaviour where THandler: ConnectionHandler + Clone, THandler::OutEvent: Clone, @@ -42,13 +42,13 @@ where { /// The prototype protocols handler that is cloned for every /// invocation of `new_handler`. - pub handler_proto: THandler, + pub(crate) handler_proto: THandler, /// The addresses to return from `addresses_of_peer`. - pub addresses: HashMap>, + pub(crate) addresses: HashMap>, /// The next action to return from `poll`. /// /// An action is only returned once. - pub next_action: Option>, + pub(crate) next_action: Option>, } impl MockBehaviour @@ -57,7 +57,7 @@ where THandler::OutEvent: Clone, TOutEvent: Send + 'static, { - pub fn new(handler_proto: THandler) -> Self { + pub(crate) fn new(handler_proto: THandler) -> Self { MockBehaviour { handler_proto, addresses: HashMap::new(), @@ -147,29 +147,31 @@ where /// A `CallTraceBehaviour` is a `NetworkBehaviour` that tracks /// invocations of callback methods and their arguments, wrapping /// around an inner behaviour. It ensures certain invariants are met. -pub struct CallTraceBehaviour +pub(crate) struct CallTraceBehaviour where TInner: NetworkBehaviour, { inner: TInner, - pub handle_pending_inbound_connection: Vec<(ConnectionId, Multiaddr, Multiaddr)>, - pub handle_pending_outbound_connection: + pub(crate) handle_pending_inbound_connection: Vec<(ConnectionId, Multiaddr, Multiaddr)>, + pub(crate) handle_pending_outbound_connection: Vec<(Option, Vec, Endpoint, ConnectionId)>, - pub handle_established_inbound_connection: Vec<(PeerId, ConnectionId, Multiaddr, Multiaddr)>, - pub handle_established_outbound_connection: Vec<(PeerId, Multiaddr, Endpoint, ConnectionId)>, - pub on_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, - pub on_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, - pub on_connection_handler_event: Vec<(PeerId, ConnectionId, THandlerOutEvent)>, - pub on_dial_failure: Vec>, - pub on_new_listener: Vec, - pub on_new_listen_addr: Vec<(ListenerId, Multiaddr)>, - pub on_new_external_addr: Vec, - pub on_expired_listen_addr: Vec<(ListenerId, Multiaddr)>, - pub on_expired_external_addr: Vec, - pub on_listener_error: Vec, - pub on_listener_closed: Vec<(ListenerId, bool)>, - pub poll: usize, + pub(crate) handle_established_inbound_connection: + Vec<(PeerId, ConnectionId, Multiaddr, Multiaddr)>, + pub(crate) handle_established_outbound_connection: + Vec<(PeerId, Multiaddr, Endpoint, ConnectionId)>, + pub(crate) on_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, + pub(crate) on_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, + pub(crate) on_connection_handler_event: Vec<(PeerId, ConnectionId, THandlerOutEvent)>, + pub(crate) on_dial_failure: Vec>, + pub(crate) on_new_listener: Vec, + pub(crate) on_new_listen_addr: Vec<(ListenerId, Multiaddr)>, + pub(crate) on_new_external_addr: Vec, + pub(crate) on_expired_listen_addr: Vec<(ListenerId, Multiaddr)>, + pub(crate) on_expired_external_addr: Vec, + pub(crate) on_listener_error: Vec, + pub(crate) on_listener_closed: Vec<(ListenerId, bool)>, + pub(crate) poll: usize, } impl CallTraceBehaviour @@ -177,7 +179,7 @@ where TInner: NetworkBehaviour, THandlerOutEvent: Clone, { - pub fn new(inner: TInner) -> Self { + pub(crate) fn new(inner: TInner) -> Self { Self { inner, handle_pending_inbound_connection: Vec::new(), @@ -200,7 +202,7 @@ where } #[allow(dead_code)] - pub fn reset(&mut self) { + pub(crate) fn reset(&mut self) { self.handle_pending_inbound_connection = Vec::new(); self.handle_pending_outbound_connection = Vec::new(); self.handle_established_inbound_connection = Vec::new(); @@ -217,11 +219,11 @@ where self.poll = 0; } - pub fn inner(&mut self) -> &mut TInner { + pub(crate) fn inner(&mut self) -> &mut TInner { &mut self.inner } - pub fn num_connections_to_peer(&self, peer: PeerId) -> usize { + pub(crate) fn num_connections_to_peer(&self, peer: PeerId) -> usize { self.on_connection_established .iter() .filter(|(peer_id, _, _, _)| *peer_id == peer) @@ -237,7 +239,7 @@ where /// given number of expected disconnections have been received as well. /// /// Returns if the first condition is met. - pub fn assert_disconnected( + pub(crate) fn assert_disconnected( &self, expected_closed_connections: usize, expected_disconnections: usize, @@ -260,7 +262,7 @@ where /// a given number of expected connections have been received as well. /// /// Returns if the first condition is met. - pub fn assert_connected( + pub(crate) fn assert_connected( &self, expected_established_connections: usize, expected_connections: usize, diff --git a/swarm/tests/swarm_derive.rs b/swarm/tests/swarm_derive.rs index 485e8b46139..87f99e35736 100644 --- a/swarm/tests/swarm_derive.rs +++ b/swarm/tests/swarm_derive.rs @@ -461,7 +461,7 @@ fn custom_out_event_no_type_parameters() { use std::task::Context; use std::task::Poll; - pub struct TemplatedBehaviour { + pub(crate) struct TemplatedBehaviour { _data: T, } diff --git a/transports/noise/src/io.rs b/transports/noise/src/io.rs index afeee65363a..314a3b87033 100644 --- a/transports/noise/src/io.rs +++ b/transports/noise/src/io.rs @@ -21,8 +21,7 @@ //! Noise protocol I/O. mod framed; -pub mod handshake; - +pub(crate) mod handshake; use bytes::Bytes; use framed::{NoiseFramed, MAX_FRAME_LEN}; use futures::prelude::*; diff --git a/transports/noise/src/io/framed.rs b/transports/noise/src/io/framed.rs index b04860375f9..1e74e46ac9b 100644 --- a/transports/noise/src/io/framed.rs +++ b/transports/noise/src/io/framed.rs @@ -38,8 +38,7 @@ const MAX_NOISE_MSG_LEN: usize = 65535; /// Space given to the encryption buffer to hold key material. const EXTRA_ENCRYPT_SPACE: usize = 1024; /// Max. length for Noise protocol message payloads. -pub const MAX_FRAME_LEN: usize = MAX_NOISE_MSG_LEN - EXTRA_ENCRYPT_SPACE; - +pub(crate) const MAX_FRAME_LEN: usize = MAX_NOISE_MSG_LEN - EXTRA_ENCRYPT_SPACE; static_assertions::const_assert! { MAX_FRAME_LEN + EXTRA_ENCRYPT_SPACE <= MAX_NOISE_MSG_LEN } @@ -49,7 +48,7 @@ static_assertions::const_assert! { /// /// `T` is the type of the underlying I/O resource and `S` the /// type of the Noise session state. -pub struct NoiseFramed { +pub(crate) struct NoiseFramed { io: T, session: S, read_state: ReadState, @@ -70,7 +69,7 @@ impl fmt::Debug for NoiseFramed { impl NoiseFramed { /// Creates a nwe `NoiseFramed` for beginning a Noise protocol handshake. - pub fn new(io: T, state: snow::HandshakeState) -> Self { + pub(crate) fn new(io: T, state: snow::HandshakeState) -> Self { NoiseFramed { io, session: state, @@ -90,7 +89,9 @@ impl NoiseFramed { /// transitioning to transport mode because the handshake is incomplete, /// an error is returned. Similarly if the remote's static DH key, if /// present, cannot be parsed. - pub fn into_transport(self) -> Result<(Option>, NoiseOutput), NoiseError> + pub(crate) fn into_transport( + self, + ) -> Result<(Option>, NoiseOutput), NoiseError> where C: Protocol + AsRef<[u8]>, { @@ -361,7 +362,7 @@ where } /// A stateful context in which Noise protocol messages can be read and written. -pub trait SessionState { +pub(crate) trait SessionState { fn read_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result; fn write_message(&mut self, msg: &[u8], buf: &mut [u8]) -> Result; } diff --git a/transports/noise/src/io/handshake.rs b/transports/noise/src/io/handshake.rs index e9428f8441c..d968c481ddd 100644 --- a/transports/noise/src/io/handshake.rs +++ b/transports/noise/src/io/handshake.rs @@ -21,6 +21,7 @@ //! Noise protocol handshake I/O. mod proto { + #![allow(unreachable_pub)] include!("../generated/mod.rs"); pub use self::payload::proto::NoiseHandshakePayload; } @@ -67,7 +68,7 @@ pub enum RemoteIdentity { // Internal /// Handshake state. -pub struct State { +pub(crate) struct State { /// The underlying I/O resource. io: NoiseFramed, /// The associated public identity of the local node's static DH keypair, @@ -89,7 +90,7 @@ impl State { /// provided session for cryptographic operations according to the chosen /// Noise handshake pattern. #[allow(deprecated)] - pub fn new( + pub(crate) fn new( io: T, session: snow::HandshakeState, identity: KeypairIdentity, @@ -109,7 +110,7 @@ impl State { impl State { /// Finish a handshake, yielding the established remote identity and the /// [`NoiseOutput`] for communicating on the encrypted channel. - pub fn finish(self) -> Result<(RemoteIdentity, NoiseOutput), NoiseError> + pub(crate) fn finish(self) -> Result<(RemoteIdentity, NoiseOutput), NoiseError> where C: Protocol + AsRef<[u8]>, { @@ -145,7 +146,7 @@ where } /// A future for receiving a Noise handshake message with an empty payload. -pub async fn recv_empty(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn recv_empty(state: &mut State) -> Result<(), NoiseError> where T: AsyncRead + Unpin, { @@ -159,7 +160,7 @@ where } /// A future for sending a Noise handshake message with an empty payload. -pub async fn send_empty(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_empty(state: &mut State) -> Result<(), NoiseError> where T: AsyncWrite + Unpin, { @@ -172,7 +173,7 @@ where /// /// In case `expected_key` is passed, this function will fail if the received key does not match the expected key. /// In case the remote does not send us a key, the expected key is assumed to be the remote's key. -pub async fn recv_identity(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn recv_identity(state: &mut State) -> Result<(), NoiseError> where T: AsyncRead + Unpin, { @@ -231,7 +232,7 @@ where } /// Send a Noise handshake message with a payload identifying the local node to the remote. -pub async fn send_identity(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_identity(state: &mut State) -> Result<(), NoiseError> where T: AsyncWrite + Unpin, { @@ -261,7 +262,7 @@ where } /// Send a Noise handshake message with a payload identifying the local node to the remote. -pub async fn send_signature_only(state: &mut State) -> Result<(), NoiseError> +pub(crate) async fn send_signature_only(state: &mut State) -> Result<(), NoiseError> where T: AsyncWrite + Unpin, { diff --git a/transports/noise/src/protocol.rs b/transports/noise/src/protocol.rs index e61bbd1f0ed..db42b5888b3 100644 --- a/transports/noise/src/protocol.rs +++ b/transports/noise/src/protocol.rs @@ -20,9 +20,8 @@ //! Components of a Noise protocol. -pub mod x25519; -pub mod x25519_spec; - +pub(crate) mod x25519; +pub(crate) mod x25519_spec; use crate::NoiseError; use libp2p_identity as identity; use rand::SeedableRng; diff --git a/transports/plaintext/src/handshake.rs b/transports/plaintext/src/handshake.rs index fb156190c57..b1e322459af 100644 --- a/transports/plaintext/src/handshake.rs +++ b/transports/plaintext/src/handshake.rs @@ -43,11 +43,10 @@ struct Local { } // HandshakeContext --with_remote-> HandshakeContext -pub struct Remote { +pub(crate) struct Remote { // The remote's peer ID: - pub peer_id: PeerId, - // The remote's public key: - pub public_key: PublicKey, + pub(crate) peer_id: PeerId, // The remote's public key: + pub(crate) public_key: PublicKey, } impl HandshakeContext { @@ -95,7 +94,7 @@ impl HandshakeContext { } } -pub async fn handshake( +pub(crate) async fn handshake( socket: S, config: PlainText2Config, ) -> Result<(S, Remote, Bytes), PlainTextError> diff --git a/transports/plaintext/src/lib.rs b/transports/plaintext/src/lib.rs index aeea2763d4d..fe4aba91a88 100644 --- a/transports/plaintext/src/lib.rs +++ b/transports/plaintext/src/lib.rs @@ -43,8 +43,9 @@ use void::Void; mod error; mod handshake; mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::structs::Exchange; + pub(crate) use self::structs::Exchange; } /// `PlainText1Config` is an insecure connection handshake for testing purposes only. diff --git a/transports/pnet/src/crypt_writer.rs b/transports/pnet/src/crypt_writer.rs index e921e278875..c5993548239 100644 --- a/transports/pnet/src/crypt_writer.rs +++ b/transports/pnet/src/crypt_writer.rs @@ -30,7 +30,7 @@ use std::{fmt, pin::Pin}; /// A writer that encrypts and forwards to an inner writer #[pin_project] -pub struct CryptWriter { +pub(crate) struct CryptWriter { #[pin] inner: W, buf: Vec, @@ -39,7 +39,7 @@ pub struct CryptWriter { impl CryptWriter { /// Creates a new `CryptWriter` with the specified buffer capacity. - pub fn with_capacity(capacity: usize, inner: W, cipher: XSalsa20) -> CryptWriter { + pub(crate) fn with_capacity(capacity: usize, inner: W, cipher: XSalsa20) -> CryptWriter { CryptWriter { inner, buf: Vec::with_capacity(capacity), @@ -50,7 +50,7 @@ impl CryptWriter { /// Gets a pinned mutable reference to the inner writer. /// /// It is inadvisable to directly write to the inner writer. - pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> { + pub(crate) fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> { self.project().inner } } diff --git a/transports/quic/src/endpoint.rs b/transports/quic/src/endpoint.rs index cf7b0fbafef..10e650ba41a 100644 --- a/transports/quic/src/endpoint.rs +++ b/transports/quic/src/endpoint.rs @@ -112,7 +112,7 @@ impl Config { /// Represents the inner configuration for [`quinn_proto`]. #[derive(Debug, Clone)] -pub struct QuinnConfig { +pub(crate) struct QuinnConfig { client_config: quinn_proto::ClientConfig, server_config: Arc, endpoint_config: Arc, @@ -169,7 +169,7 @@ impl From for QuinnConfig { /// Channel used to send commands to the [`Driver`]. #[derive(Debug, Clone)] -pub struct Channel { +pub(crate) struct Channel { /// Channel to the background of the endpoint. to_endpoint: mpsc::Sender, /// Address that the socket is bound to. @@ -179,7 +179,7 @@ pub struct Channel { impl Channel { /// Builds a new endpoint that is listening on the [`SocketAddr`]. - pub fn new_bidirectional( + pub(crate) fn new_bidirectional( quinn_config: QuinnConfig, socket_addr: SocketAddr, ) -> Result<(Self, mpsc::Receiver), Error> { @@ -190,7 +190,7 @@ impl Channel { } /// Builds a new endpoint that only supports outbound connections. - pub fn new_dialer( + pub(crate) fn new_dialer( quinn_config: QuinnConfig, socket_family: SocketFamily, ) -> Result { @@ -241,7 +241,7 @@ impl Channel { Ok(channel) } - pub fn socket_addr(&self) -> &SocketAddr { + pub(crate) fn socket_addr(&self) -> &SocketAddr { &self.socket_addr } @@ -252,7 +252,7 @@ impl Channel { /// and the context's waker is registered for wake-up. /// /// If the background task crashed `Err` is returned. - pub fn try_send( + pub(crate) fn try_send( &mut self, to_endpoint: ToEndpoint, cx: &mut Context<'_>, @@ -283,18 +283,17 @@ impl Channel { /// event caused by the owner of this [`Channel`] dropping. /// This clones the sender to the endpoint to guarantee delivery. /// This should *not* be called for regular messages. - pub fn send_on_drop(&mut self, to_endpoint: ToEndpoint) { + pub(crate) fn send_on_drop(&mut self, to_endpoint: ToEndpoint) { let _ = self.to_endpoint.clone().try_send(to_endpoint); } } #[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)] #[error("Background task disconnected")] -pub struct Disconnected {} - +pub(crate) struct Disconnected {} /// Message sent to the endpoint background task. #[derive(Debug)] -pub enum ToEndpoint { +pub(crate) enum ToEndpoint { /// Instruct the [`quinn_proto::Endpoint`] to start connecting to the given address. Dial { /// UDP address to connect to. @@ -369,7 +368,7 @@ pub enum ToEndpoint { /// The background task shuts down if an [`ToEndpoint::Decoupled`] event was received and the /// last active connection has drained. #[derive(Debug)] -pub struct Driver { +pub(crate) struct Driver { // The actual QUIC state machine. endpoint: quinn_proto::Endpoint, // QuinnConfig for client connections. diff --git a/transports/quic/src/transport.rs b/transports/quic/src/transport.rs index 9aadbeb93f4..d68eb7f1928 100644 --- a/transports/quic/src/transport.rs +++ b/transports/quic/src/transport.rs @@ -536,13 +536,13 @@ impl Drop for Listener

{ } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ProtocolVersion { +pub(crate) enum ProtocolVersion { V1, // i.e. RFC9000 Draft29, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum SocketFamily { +pub(crate) enum SocketFamily { Ipv4, Ipv6, } diff --git a/transports/tls/src/verifier.rs b/transports/tls/src/verifier.rs index 29e4ab989e5..a9d9aecaa65 100644 --- a/transports/tls/src/verifier.rs +++ b/transports/tls/src/verifier.rs @@ -42,12 +42,11 @@ use rustls::{ /// /// > The libp2p handshake uses TLS 1.3 (and higher). /// > Endpoints MUST NOT negotiate lower TLS versions. -pub static PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13]; - +pub(crate) static PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13]; /// A list of the TLS 1.3 cipher suites supported by rustls. // By default rustls creates client/server configs with both // TLS 1.3 __and__ 1.2 cipher suites. But we don't need 1.2. -pub static CIPHERSUITES: &[SupportedCipherSuite] = &[ +pub(crate) static CIPHERSUITES: &[SupportedCipherSuite] = &[ // TLS1.3 suites TLS13_CHACHA20_POLY1305_SHA256, TLS13_AES_256_GCM_SHA384, @@ -57,7 +56,7 @@ pub static CIPHERSUITES: &[SupportedCipherSuite] = &[ /// Implementation of the `rustls` certificate verification traits for libp2p. /// /// Only TLS 1.3 is supported. TLS 1.2 should be disabled in the configuration of `rustls`. -pub struct Libp2pCertificateVerifier { +pub(crate) struct Libp2pCertificateVerifier { /// The peer ID we intend to connect to remote_peer_id: Option, } @@ -69,12 +68,12 @@ pub struct Libp2pCertificateVerifier { /// - The certificate must have a valid libp2p extension that includes a /// signature of its public key. impl Libp2pCertificateVerifier { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { remote_peer_id: None, } } - pub fn with_remote_peer_id(remote_peer_id: Option) -> Self { + pub(crate) fn with_remote_peer_id(remote_peer_id: Option) -> Self { Self { remote_peer_id } } diff --git a/transports/webrtc/src/lib.rs b/transports/webrtc/src/lib.rs index 95bd0ac6d7e..012796a6b69 100644 --- a/transports/webrtc/src/lib.rs +++ b/transports/webrtc/src/lib.rs @@ -81,8 +81,9 @@ //! certificate verification off. mod proto { + #![allow(unreachable_pub)] include!("generated/mod.rs"); - pub use self::webrtc::pb::{mod_Message::Flag, Message}; + pub(crate) use self::webrtc::pb::{mod_Message::Flag, Message}; } #[cfg(feature = "tokio")] diff --git a/transports/webrtc/src/tokio/req_res_chan.rs b/transports/webrtc/src/tokio/req_res_chan.rs index a102aa0357a..fb29e16db27 100644 --- a/transports/webrtc/src/tokio/req_res_chan.rs +++ b/transports/webrtc/src/tokio/req_res_chan.rs @@ -28,7 +28,7 @@ use std::{ task::{Context, Poll}, }; -pub fn new(capacity: usize) -> (Sender, Receiver) { +pub(crate) fn new(capacity: usize) -> (Sender, Receiver) { let (sender, receiver) = mpsc::channel(capacity); ( @@ -39,12 +39,12 @@ pub fn new(capacity: usize) -> (Sender, Receiver) ) } -pub struct Sender { +pub(crate) struct Sender { inner: futures::lock::Mutex)>>, } impl Sender { - pub async fn send(&self, req: Req) -> io::Result { + pub(crate) async fn send(&self, req: Req) -> io::Result { let (sender, receiver) = oneshot::channel(); self.inner @@ -61,12 +61,12 @@ impl Sender { } } -pub struct Receiver { +pub(crate) struct Receiver { inner: mpsc::Receiver<(Req, oneshot::Sender)>, } impl Receiver { - pub fn poll_next_unpin( + pub(crate) fn poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll)>> { diff --git a/transports/webrtc/src/tokio/sdp.rs b/transports/webrtc/src/tokio/sdp.rs index 659057788ff..d2f424e5d4e 100644 --- a/transports/webrtc/src/tokio/sdp.rs +++ b/transports/webrtc/src/tokio/sdp.rs @@ -27,7 +27,7 @@ use std::net::{IpAddr, SocketAddr}; use crate::tokio::fingerprint::Fingerprint; /// Creates the SDP answer used by the client. -pub fn answer( +pub(crate) fn answer( addr: SocketAddr, server_fingerprint: &Fingerprint, client_ufrag: &str, @@ -44,7 +44,7 @@ pub fn answer( /// Creates the SDP offer used by the server. /// /// Certificate verification is disabled which is why we hardcode a dummy fingerprint here. -pub fn offer(addr: SocketAddr, client_ufrag: &str) -> RTCSessionDescription { +pub(crate) fn offer(addr: SocketAddr, client_ufrag: &str) -> RTCSessionDescription { RTCSessionDescription::offer(render_description( CLIENT_SESSION_DESCRIPTION, addr, @@ -213,13 +213,13 @@ enum IpVersion { /// `{IP_VERSION}`) with real values. #[derive(Serialize)] struct DescriptionContext { - pub ip_version: IpVersion, - pub target_ip: IpAddr, - pub target_port: u16, - pub fingerprint_algorithm: String, - pub fingerprint_value: String, - pub ufrag: String, - pub pwd: String, + pub(crate) ip_version: IpVersion, + pub(crate) target_ip: IpAddr, + pub(crate) target_port: u16, + pub(crate) fingerprint_algorithm: String, + pub(crate) fingerprint_value: String, + pub(crate) ufrag: String, + pub(crate) pwd: String, } /// Renders a [`TinyTemplate`] description using the provided arguments. diff --git a/transports/webrtc/src/tokio/substream.rs b/transports/webrtc/src/tokio/substream.rs index e3f9ef9e074..89e52376a48 100644 --- a/transports/webrtc/src/tokio/substream.rs +++ b/transports/webrtc/src/tokio/substream.rs @@ -55,8 +55,7 @@ const PROTO_OVERHEAD: usize = 5; /// Maximum length of data, in bytes. const MAX_DATA_LEN: usize = MAX_MSG_LEN - VARINT_LEN - PROTO_OVERHEAD; -pub use drop_listener::DropListener; - +pub(crate) use drop_listener::DropListener; /// A substream on top of a WebRTC data channel. /// /// To be a proper libp2p substream, we need to implement [`AsyncRead`] and [`AsyncWrite`] as well diff --git a/transports/webrtc/src/tokio/substream/drop_listener.rs b/transports/webrtc/src/tokio/substream/drop_listener.rs index 3e3dc18a1d6..735240456fe 100644 --- a/transports/webrtc/src/tokio/substream/drop_listener.rs +++ b/transports/webrtc/src/tokio/substream/drop_listener.rs @@ -31,12 +31,12 @@ use crate::proto::{Flag, Message}; use crate::tokio::substream::framed_dc::FramedDc; #[must_use] -pub struct DropListener { +pub(crate) struct DropListener { state: State, } impl DropListener { - pub fn new(stream: FramedDc, receiver: oneshot::Receiver) -> Self { + pub(crate) fn new(stream: FramedDc, receiver: oneshot::Receiver) -> Self { let substream_id = stream.get_ref().stream_identifier(); Self { @@ -127,4 +127,4 @@ impl Future for DropListener { } /// Indicates that our substream got gracefully closed. -pub struct GracefullyClosed {} +pub(crate) struct GracefullyClosed {} diff --git a/transports/webrtc/src/tokio/substream/framed_dc.rs b/transports/webrtc/src/tokio/substream/framed_dc.rs index 1bf2b3cf769..1b3860b662b 100644 --- a/transports/webrtc/src/tokio/substream/framed_dc.rs +++ b/transports/webrtc/src/tokio/substream/framed_dc.rs @@ -28,9 +28,8 @@ use std::sync::Arc; use super::{MAX_DATA_LEN, MAX_MSG_LEN, VARINT_LEN}; use crate::proto::Message; -pub type FramedDc = Framed, quick_protobuf_codec::Codec>; - -pub fn new(data_channel: Arc) -> FramedDc { +pub(crate) type FramedDc = Framed, quick_protobuf_codec::Codec>; +pub(crate) fn new(data_channel: Arc) -> FramedDc { let mut inner = PollDataChannel::new(data_channel); inner.set_read_buf_capacity(MAX_MSG_LEN); diff --git a/transports/webrtc/src/tokio/substream/state.rs b/transports/webrtc/src/tokio/substream/state.rs index 5e843519ed6..b1768aa2165 100644 --- a/transports/webrtc/src/tokio/substream/state.rs +++ b/transports/webrtc/src/tokio/substream/state.rs @@ -25,7 +25,7 @@ use std::io; use crate::proto::Flag; #[derive(Debug, Copy, Clone)] -pub enum State { +pub(crate) enum State { Open, ReadClosed, WriteClosed, @@ -49,7 +49,7 @@ pub enum State { /// Gracefully closing the read or write requires sending the `STOP_SENDING` or `FIN` flag respectively /// and flushing the underlying connection. #[derive(Debug, Copy, Clone)] -pub enum Closing { +pub(crate) enum Closing { Requested, MessageSent, } @@ -278,7 +278,7 @@ impl State { } /// Acts as a "barrier" for [`Substream::poll_close_read`](super::Substream::poll_close_read). - pub fn close_read_barrier(&mut self) -> io::Result> { + pub(crate) fn close_read_barrier(&mut self) -> io::Result> { loop { match self { State::ReadClosed => return Ok(None), diff --git a/transports/webrtc/src/tokio/udp_mux.rs b/transports/webrtc/src/tokio/udp_mux.rs index 4e432c2e51f..f978121d01c 100644 --- a/transports/webrtc/src/tokio/udp_mux.rs +++ b/transports/webrtc/src/tokio/udp_mux.rs @@ -49,14 +49,14 @@ const RECEIVE_MTU: usize = 8192; /// A previously unseen address of a remote which has sent us an ICE binding request. #[derive(Debug)] -pub struct NewAddr { - pub addr: SocketAddr, - pub ufrag: String, +pub(crate) struct NewAddr { + pub(crate) addr: SocketAddr, + pub(crate) ufrag: String, } /// An event emitted by [`UDPMuxNewAddr`] when it's polled. #[derive(Debug)] -pub enum UDPMuxEvent { +pub(crate) enum UDPMuxEvent { /// Connection error. UDP mux should be stopped. Error(std::io::Error), /// Got a [`NewAddr`] from the socket. @@ -67,7 +67,7 @@ pub enum UDPMuxEvent { /// /// - It has been rewritten to work without locks and channels instead. /// - It reports previously unseen addresses instead of ignoring them. -pub struct UDPMuxNewAddr { +pub(crate) struct UDPMuxNewAddr { udp_sock: UdpSocket, listen_addr: SocketAddr, @@ -100,7 +100,7 @@ pub struct UDPMuxNewAddr { } impl UDPMuxNewAddr { - pub fn listen_on(addr: SocketAddr) -> Result { + pub(crate) fn listen_on(addr: SocketAddr) -> Result { let std_sock = std::net::UdpSocket::bind(addr)?; std_sock.set_nonblocking(true)?; @@ -131,11 +131,11 @@ impl UDPMuxNewAddr { }) } - pub fn listen_addr(&self) -> SocketAddr { + pub(crate) fn listen_addr(&self) -> SocketAddr { self.listen_addr } - pub fn udp_mux_handle(&self) -> Arc { + pub(crate) fn udp_mux_handle(&self) -> Arc { self.udp_mux_handle.clone() } @@ -183,7 +183,7 @@ impl UDPMuxNewAddr { /// Reads from the underlying UDP socket and either reports a new address or proxies data to the /// muxed connection. - pub fn poll(&mut self, cx: &mut Context) -> Poll { + pub(crate) fn poll(&mut self, cx: &mut Context) -> Poll { let mut recv_buf = [0u8; RECEIVE_MTU]; loop { @@ -419,7 +419,7 @@ impl UDPMuxNewAddr { /// Handle which utilizes [`req_res_chan`] to transmit commands (e.g. remove connection) from the /// WebRTC ICE agent to [`UDPMuxNewAddr::poll`]. -pub struct UdpMuxHandle { +pub(crate) struct UdpMuxHandle { close_sender: req_res_chan::Sender<(), Result<(), Error>>, get_conn_sender: req_res_chan::Sender, Error>>, remove_sender: req_res_chan::Sender, @@ -427,7 +427,7 @@ pub struct UdpMuxHandle { impl UdpMuxHandle { /// Returns a new `UdpMuxHandle` and `close`, `get_conn` and `remove` receivers. - pub fn new() -> ( + pub(crate) fn new() -> ( Self, req_res_chan::Receiver<(), Result<(), Error>>, req_res_chan::Receiver, Error>>, @@ -477,7 +477,7 @@ impl UDPMux for UdpMuxHandle { /// Handle which utilizes [`req_res_chan`] to transmit commands from [`UDPMuxConn`] connections to /// [`UDPMuxNewAddr::poll`]. -pub struct UdpMuxWriterHandle { +pub(crate) struct UdpMuxWriterHandle { registration_channel: req_res_chan::Sender<(UDPMuxConn, SocketAddr), ()>, send_channel: req_res_chan::Sender<(Vec, SocketAddr), Result>, } diff --git a/transports/webrtc/src/tokio/upgrade.rs b/transports/webrtc/src/tokio/upgrade.rs index 23dd978ae92..2d5e3fe2c10 100644 --- a/transports/webrtc/src/tokio/upgrade.rs +++ b/transports/webrtc/src/tokio/upgrade.rs @@ -43,7 +43,7 @@ use std::{net::SocketAddr, sync::Arc, time::Duration}; use crate::tokio::{error::Error, fingerprint::Fingerprint, sdp, substream::Substream, Connection}; /// Creates a new outbound WebRTC connection. -pub async fn outbound( +pub(crate) async fn outbound( addr: SocketAddr, config: RTCConfiguration, udp_mux: Arc, @@ -79,7 +79,7 @@ pub async fn outbound( } /// Creates a new inbound WebRTC connection. -pub async fn inbound( +pub(crate) async fn inbound( addr: SocketAddr, config: RTCConfiguration, udp_mux: Arc, diff --git a/transports/webrtc/src/tokio/upgrade/noise.rs b/transports/webrtc/src/tokio/upgrade/noise.rs index ad387510fc4..fb95a0f4b46 100644 --- a/transports/webrtc/src/tokio/upgrade/noise.rs +++ b/transports/webrtc/src/tokio/upgrade/noise.rs @@ -27,7 +27,7 @@ use libp2p_noise::{Keypair, NoiseConfig, X25519Spec}; use crate::tokio::fingerprint::Fingerprint; use crate::tokio::Error; -pub async fn inbound( +pub(crate) async fn inbound( id_keys: identity::Keypair, stream: T, client_fingerprint: Fingerprint, @@ -54,7 +54,7 @@ where Ok(peer_id) } -pub async fn outbound( +pub(crate) async fn outbound( id_keys: identity::Keypair, stream: T, server_fingerprint: Fingerprint, @@ -81,7 +81,10 @@ where Ok(peer_id) } -pub fn noise_prologue(client_fingerprint: Fingerprint, server_fingerprint: Fingerprint) -> Vec { +pub(crate) fn noise_prologue( + client_fingerprint: Fingerprint, + server_fingerprint: Fingerprint, +) -> Vec { let client = client_fingerprint.to_multihash().to_bytes(); let server = server_fingerprint.to_multihash().to_bytes(); const PREFIX: &[u8] = b"libp2p-webrtc-noise:"; diff --git a/transports/webrtc/tests/smoke.rs b/transports/webrtc/tests/smoke.rs index 16f64d058a4..bca159d785b 100644 --- a/transports/webrtc/tests/smoke.rs +++ b/transports/webrtc/tests/smoke.rs @@ -297,7 +297,7 @@ struct ListenUpgrade<'a> { } impl<'a> ListenUpgrade<'a> { - pub fn new(listener: &'a mut Boxed<(PeerId, StreamMuxerBox)>) -> Self { + pub(crate) fn new(listener: &'a mut Boxed<(PeerId, StreamMuxerBox)>) -> Self { Self { listener, listener_upgrade_task: None,