InboundUpgrade for PendingUpgrade
where
P: AsRef + Clone,
{
- type Output = Void;
- type Error = Void;
+ type Output = Infallible;
+ type Error = Infallible;
type Future = future::Pending>;
fn upgrade_inbound(self, _: C, _: Self::Info) -> Self::Future {
@@ -66,8 +67,8 @@ impl OutboundUpgrade for PendingUpgrade
where
P: AsRef + Clone,
{
- type Output = Void;
- type Error = Void;
+ type Output = Infallible;
+ type Error = Infallible;
type Future = future::Pending>;
fn upgrade_outbound(self, _: C, _: Self::Info) -> Self::Future {
diff --git a/core/src/upgrade/ready.rs b/core/src/upgrade/ready.rs
index 7e235902651..22708d726e7 100644
--- a/core/src/upgrade/ready.rs
+++ b/core/src/upgrade/ready.rs
@@ -19,12 +19,14 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
+use std::{convert::Infallible, iter};
+
use futures::future;
-use std::iter;
-use void::Void;
-/// Implementation of [`UpgradeInfo`], [`InboundUpgrade`] and [`OutboundUpgrade`] that directly yields the substream.
+use crate::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
+
+/// Implementation of [`UpgradeInfo`], [`InboundUpgrade`] and [`OutboundUpgrade`]
+/// that directly yields the substream.
#[derive(Debug, Copy, Clone)]
pub struct ReadyUpgrade {
protocol_name: P,
@@ -53,7 +55,7 @@ where
P: AsRef + Clone,
{
type Output = C;
- type Error = Void;
+ type Error = Infallible;
type Future = future::Ready>;
fn upgrade_inbound(self, stream: C, _: Self::Info) -> Self::Future {
@@ -66,7 +68,7 @@ where
P: AsRef + Clone,
{
type Output = C;
- type Error = Void;
+ type Error = Infallible;
type Future = future::Ready>;
fn upgrade_outbound(self, stream: C, _: Self::Info) -> Self::Future {
diff --git a/core/src/upgrade/select.rs b/core/src/upgrade/select.rs
index 037045a2f29..b7fe4a53a7f 100644
--- a/core/src/upgrade/select.rs
+++ b/core/src/upgrade/select.rs
@@ -18,14 +18,18 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::either::EitherFuture;
-use crate::upgrade::{
- InboundConnectionUpgrade, InboundUpgrade, OutboundConnectionUpgrade, OutboundUpgrade,
- UpgradeInfo,
-};
+use std::iter::{Chain, Map};
+
use either::Either;
use futures::future;
-use std::iter::{Chain, Map};
+
+use crate::{
+ either::EitherFuture,
+ upgrade::{
+ InboundConnectionUpgrade, InboundUpgrade, OutboundConnectionUpgrade, OutboundUpgrade,
+ UpgradeInfo,
+ },
+};
/// Upgrade that combines two upgrades into one. Supports all the protocols supported by either
/// sub-upgrade.
diff --git a/core/tests/transport_upgrade.rs b/core/tests/transport_upgrade.rs
index d8bec6f2b59..b9733e38322 100644
--- a/core/tests/transport_upgrade.rs
+++ b/core/tests/transport_upgrade.rs
@@ -18,18 +18,19 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{io, pin::Pin};
+
use futures::prelude::*;
-use libp2p_core::transport::{DialOpts, ListenerId, MemoryTransport, PortUse, Transport};
-use libp2p_core::upgrade::{
- self, InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo,
+use libp2p_core::{
+ transport::{DialOpts, ListenerId, MemoryTransport, PortUse, Transport},
+ upgrade::{self, InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo},
+ Endpoint,
};
-use libp2p_core::Endpoint;
use libp2p_identity as identity;
use libp2p_mplex::MplexConfig;
use libp2p_noise as noise;
use multiaddr::{Multiaddr, Protocol};
use rand::random;
-use std::{io, pin::Pin};
#[derive(Clone)]
struct HelloUpgrade {}
diff --git a/deny.toml b/deny.toml
index 5be86107edf..47487553028 100644
--- a/deny.toml
+++ b/deny.toml
@@ -43,6 +43,8 @@ allow = [
"MIT",
"MPL-2.0",
"Unlicense",
+ "Unicode-3.0",
+ "Zlib",
]
# The confidence threshold for detecting a license from license text.
# The higher the value, the more closely the license text must be to the
diff --git a/docs/coding-guidelines.md b/docs/coding-guidelines.md
index bacbfe9509e..473d7020fcf 100644
--- a/docs/coding-guidelines.md
+++ b/docs/coding-guidelines.md
@@ -236,7 +236,7 @@ Concurrency adds complexity. Concurrency adds overhead due to synchronization.
Thus unless proven to be a bottleneck, don't make things concurrent. As an example
the hierarchical `NetworkBehaviour` state machine runs sequentially. It is easy
to debug as it runs sequentially. Thus far there has been no proof that
-shows a speed up when running it concurrently.
+shows a speed-up when running it concurrently.
## Use `async/await` for sequential execution only
diff --git a/examples/autonat/Cargo.toml b/examples/autonat/Cargo.toml
index 010b76623e0..7c06b48a105 100644
--- a/examples/autonat/Cargo.toml
+++ b/examples/autonat/Cargo.toml
@@ -13,7 +13,6 @@ tokio = { workspace = true, features = ["full"] }
clap = { version = "4.5.6", features = ["derive"] }
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = ["tokio", "tcp", "noise", "yamux", "autonat", "identify", "macros"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/autonat/src/bin/autonat_client.rs b/examples/autonat/src/bin/autonat_client.rs
index def66c4823b..768a2052c80 100644
--- a/examples/autonat/src/bin/autonat_client.rs
+++ b/examples/autonat/src/bin/autonat_client.rs
@@ -20,15 +20,17 @@
#![doc = include_str!("../../README.md")]
+use std::{error::Error, net::Ipv4Addr, time::Duration};
+
use clap::Parser;
use futures::StreamExt;
-use libp2p::core::multiaddr::Protocol;
-use libp2p::core::Multiaddr;
-use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
-use libp2p::{autonat, identify, identity, noise, tcp, yamux, PeerId};
-use std::error::Error;
-use std::net::Ipv4Addr;
-use std::time::Duration;
+use libp2p::{
+ autonat,
+ core::{multiaddr::Protocol, Multiaddr},
+ identify, identity, noise,
+ swarm::{NetworkBehaviour, SwarmEvent},
+ tcp, yamux, PeerId,
+};
use tracing_subscriber::EnvFilter;
#[derive(Debug, Parser)]
@@ -60,7 +62,6 @@ async fn main() -> Result<(), Box> {
yamux::Config::default,
)?
.with_behaviour(|key| Behaviour::new(key.public()))?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
swarm.listen_on(
diff --git a/examples/autonat/src/bin/autonat_server.rs b/examples/autonat/src/bin/autonat_server.rs
index 389cc0fa26f..f3bb6b6a439 100644
--- a/examples/autonat/src/bin/autonat_server.rs
+++ b/examples/autonat/src/bin/autonat_server.rs
@@ -20,14 +20,17 @@
#![doc = include_str!("../../README.md")]
+use std::{error::Error, net::Ipv4Addr};
+
use clap::Parser;
use futures::StreamExt;
-use libp2p::core::{multiaddr::Protocol, Multiaddr};
-use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
-use libp2p::{autonat, identify, identity, noise, tcp, yamux};
-use std::error::Error;
-use std::net::Ipv4Addr;
-use std::time::Duration;
+use libp2p::{
+ autonat,
+ core::{multiaddr::Protocol, Multiaddr},
+ identify, identity, noise,
+ swarm::{NetworkBehaviour, SwarmEvent},
+ tcp, yamux,
+};
use tracing_subscriber::EnvFilter;
#[derive(Debug, Parser)]
@@ -53,7 +56,6 @@ async fn main() -> Result<(), Box> {
yamux::Config::default,
)?
.with_behaviour(|key| Behaviour::new(key.public()))?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
swarm.listen_on(
diff --git a/examples/autonatv2/Cargo.toml b/examples/autonatv2/Cargo.toml
index 6c862ee22e4..d400c53e7fd 100644
--- a/examples/autonatv2/Cargo.toml
+++ b/examples/autonatv2/Cargo.toml
@@ -19,17 +19,15 @@ libp2p = { workspace = true, features = ["macros", "tokio", "tcp", "noise", "yam
clap = { version = "4.4.18", features = ["derive"] }
tokio = { version = "1.35.1", features = ["macros", "rt-multi-thread"] }
tracing = "0.1.40"
-tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
+tracing-subscriber = { workspace = true, features = ["env-filter"] }
rand = "0.8.5"
-opentelemetry = { version = "0.21.0", optional = true }
opentelemetry_sdk = { version = "0.21.1", optional = true, features = ["rt-tokio"] }
tracing-opentelemetry = { version = "0.22.0", optional = true }
opentelemetry-jaeger = { version = "0.20.0", optional = true, features = ["rt-tokio"] }
cfg-if = "1.0.0"
[features]
-jaeger = ["opentelemetry", "opentelemetry_sdk", "tracing-opentelemetry", "opentelemetry-jaeger"]
-opentelemetry = ["dep:opentelemetry"]
+jaeger = ["opentelemetry_sdk", "tracing-opentelemetry", "opentelemetry-jaeger"]
opentelemetry_sdk = ["dep:opentelemetry_sdk"]
tracing-opentelemetry = ["dep:tracing-opentelemetry"]
opentelemetry-jaeger = ["dep:opentelemetry-jaeger"]
diff --git a/examples/autonatv2/Dockerfile b/examples/autonatv2/Dockerfile
index 5a523649d80..083f9f5c113 100644
--- a/examples/autonatv2/Dockerfile
+++ b/examples/autonatv2/Dockerfile
@@ -1,4 +1,4 @@
-FROM rust:1.75-alpine as builder
+FROM rust:1.83-alpine as builder
RUN apk add musl-dev
diff --git a/examples/browser-webrtc/src/lib.rs b/examples/browser-webrtc/src/lib.rs
index 9499ccbd158..e2d884cb445 100644
--- a/examples/browser-webrtc/src/lib.rs
+++ b/examples/browser-webrtc/src/lib.rs
@@ -1,13 +1,11 @@
#![cfg(target_arch = "wasm32")]
+use std::{io, time::Duration};
+
use futures::StreamExt;
use js_sys::Date;
-use libp2p::core::Multiaddr;
-use libp2p::ping;
-use libp2p::swarm::SwarmEvent;
+use libp2p::{core::Multiaddr, ping, swarm::SwarmEvent};
use libp2p_webrtc_websys as webrtc_websys;
-use std::io;
-use std::time::Duration;
use wasm_bindgen::prelude::*;
use web_sys::{Document, HtmlElement};
diff --git a/examples/browser-webrtc/src/main.rs b/examples/browser-webrtc/src/main.rs
index 7f06b0d0d99..52222dc882b 100644
--- a/examples/browser-webrtc/src/main.rs
+++ b/examples/browser-webrtc/src/main.rs
@@ -1,23 +1,24 @@
#![allow(non_upper_case_globals)]
+use std::net::{Ipv4Addr, SocketAddr};
+
use anyhow::Result;
-use axum::extract::{Path, State};
-use axum::http::header::CONTENT_TYPE;
-use axum::http::StatusCode;
-use axum::response::{Html, IntoResponse};
-use axum::{http::Method, routing::get, Router};
+use axum::{
+ extract::{Path, State},
+ http::{header::CONTENT_TYPE, Method, StatusCode},
+ response::{Html, IntoResponse},
+ routing::get,
+ Router,
+};
use futures::StreamExt;
use libp2p::{
- core::muxing::StreamMuxerBox,
- core::Transport,
+ core::{muxing::StreamMuxerBox, Transport},
multiaddr::{Multiaddr, Protocol},
ping,
swarm::SwarmEvent,
};
use libp2p_webrtc as webrtc;
use rand::thread_rng;
-use std::net::{Ipv4Addr, SocketAddr};
-use std::time::Duration;
use tokio::net::TcpListener;
use tower_http::cors::{Any, CorsLayer};
@@ -37,11 +38,6 @@ async fn main() -> anyhow::Result<()> {
.map(|(peer_id, conn), _| (peer_id, StreamMuxerBox::new(conn))))
})?
.with_behaviour(|_| ping::Behaviour::default())?
- .with_swarm_config(|cfg| {
- cfg.with_idle_connection_timeout(
- Duration::from_secs(u64::MAX), // Allows us to observe the pings.
- )
- })
.build();
let address_webrtc = Multiaddr::from(Ipv4Addr::UNSPECIFIED)
@@ -127,7 +123,8 @@ struct Libp2pEndpoint(Multiaddr);
/// Serves the index.html file for our client.
///
/// Our server listens on a random UDP port for the WebRTC transport.
-/// To allow the client to connect, we replace the `__LIBP2P_ENDPOINT__` placeholder with the actual address.
+/// To allow the client to connect, we replace the `__LIBP2P_ENDPOINT__`
+/// placeholder with the actual address.
async fn get_index(
State(Libp2pEndpoint(libp2p_endpoint)): State,
) -> Result, StatusCode> {
diff --git a/examples/chat/Cargo.toml b/examples/chat/Cargo.toml
index a1d32956825..031f84b6f95 100644
--- a/examples/chat/Cargo.toml
+++ b/examples/chat/Cargo.toml
@@ -10,10 +10,8 @@ release = false
[dependencies]
tokio = { workspace = true, features = ["full"] }
-async-trait = "0.1"
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = [ "tokio", "gossipsub", "mdns", "noise", "macros", "tcp", "yamux", "quic"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/chat/src/main.rs b/examples/chat/src/main.rs
index c785d301c2f..b0dcc767b6f 100644
--- a/examples/chat/src/main.rs
+++ b/examples/chat/src/main.rs
@@ -20,12 +20,19 @@
#![doc = include_str!("../README.md")]
+use std::{
+ collections::hash_map::DefaultHasher,
+ error::Error,
+ hash::{Hash, Hasher},
+ time::Duration,
+};
+
use futures::stream::StreamExt;
-use libp2p::{gossipsub, mdns, noise, swarm::NetworkBehaviour, swarm::SwarmEvent, tcp, yamux};
-use std::collections::hash_map::DefaultHasher;
-use std::error::Error;
-use std::hash::{Hash, Hasher};
-use std::time::Duration;
+use libp2p::{
+ gossipsub, mdns, noise,
+ swarm::{NetworkBehaviour, SwarmEvent},
+ tcp, yamux,
+};
use tokio::{io, io::AsyncBufReadExt, select};
use tracing_subscriber::EnvFilter;
@@ -61,7 +68,8 @@ async fn main() -> Result<(), Box> {
// Set a custom gossipsub configuration
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space
- .validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
+ .validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message
+ // signing)
.message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.
.build()
.map_err(|msg| io::Error::new(io::ErrorKind::Other, msg))?; // Temporary hack because `build` does not return a proper `std::error::Error`.
@@ -76,7 +84,6 @@ async fn main() -> Result<(), Box> {
mdns::tokio::Behaviour::new(mdns::Config::default(), key.public().to_peer_id())?;
Ok(MyBehaviour { gossipsub, mdns })
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
// Create a Gossipsub topic
diff --git a/examples/dcutr/Cargo.toml b/examples/dcutr/Cargo.toml
index c1b4bbc6e7e..67edf04e2b0 100644
--- a/examples/dcutr/Cargo.toml
+++ b/examples/dcutr/Cargo.toml
@@ -13,7 +13,6 @@ clap = { version = "4.5.6", features = ["derive"] }
futures = { workspace = true }
futures-timer = "3.0"
libp2p = { path = "../../libp2p", features = [ "dns", "dcutr", "identify", "macros", "noise", "ping", "quic", "relay", "rendezvous", "tcp", "tokio", "yamux"] }
-log = "0.4"
tokio = { workspace = true, features = ["macros", "net", "rt", "signal"] }
tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
diff --git a/examples/dcutr/src/main.rs b/examples/dcutr/src/main.rs
index 630d4b2b1f3..3f403d534e7 100644
--- a/examples/dcutr/src/main.rs
+++ b/examples/dcutr/src/main.rs
@@ -20,6 +20,8 @@
#![doc = include_str!("../README.md")]
+use std::{error::Error, str::FromStr};
+
use clap::Parser;
use futures::{executor::block_on, future::FutureExt, stream::StreamExt};
use libp2p::{
@@ -28,8 +30,6 @@ use libp2p::{
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, PeerId,
};
-use std::str::FromStr;
-use std::{error::Error, time::Duration};
use tracing_subscriber::EnvFilter;
#[derive(Debug, Parser)]
@@ -105,7 +105,6 @@ async fn main() -> Result<(), Box> {
)),
dcutr: dcutr::Behaviour::new(keypair.public().to_peer_id()),
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
swarm
diff --git a/examples/distributed-key-value-store/Cargo.toml b/examples/distributed-key-value-store/Cargo.toml
index 9c2e2bce5c9..8e30dd2c75d 100644
--- a/examples/distributed-key-value-store/Cargo.toml
+++ b/examples/distributed-key-value-store/Cargo.toml
@@ -9,11 +9,9 @@ license = "MIT"
release = false
[dependencies]
-async-std = { version = "1.12", features = ["attributes"] }
-async-trait = "0.1"
+tokio = { workspace = true, features = ["full"] }
futures = { workspace = true }
-libp2p = { path = "../../libp2p", features = [ "async-std", "dns", "kad", "mdns", "noise", "macros", "tcp", "yamux"] }
-tracing = { workspace = true }
+libp2p = { path = "../../libp2p", features = [ "tokio", "dns", "kad", "mdns", "noise", "macros", "tcp", "yamux"] }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/distributed-key-value-store/src/main.rs b/examples/distributed-key-value-store/src/main.rs
index 404333f3d20..3522c84c720 100644
--- a/examples/distributed-key-value-store/src/main.rs
+++ b/examples/distributed-key-value-store/src/main.rs
@@ -20,21 +20,23 @@
#![doc = include_str!("../README.md")]
-use async_std::io;
-use futures::{prelude::*, select};
-use libp2p::kad;
-use libp2p::kad::store::MemoryStore;
-use libp2p::kad::Mode;
+use std::error::Error;
+
+use futures::stream::StreamExt;
use libp2p::{
+ kad,
+ kad::{store::MemoryStore, Mode},
mdns, noise,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux,
};
-use std::error::Error;
-use std::time::Duration;
+use tokio::{
+ io::{self, AsyncBufReadExt},
+ select,
+};
use tracing_subscriber::EnvFilter;
-#[async_std::main]
+#[tokio::main]
async fn main() -> Result<(), Box> {
let _ = tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
@@ -44,11 +46,11 @@ async fn main() -> Result<(), Box> {
#[derive(NetworkBehaviour)]
struct Behaviour {
kademlia: kad::Behaviour,
- mdns: mdns::async_io::Behaviour,
+ mdns: mdns::tokio::Behaviour,
}
let mut swarm = libp2p::SwarmBuilder::with_new_identity()
- .with_async_std()
+ .with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
@@ -60,19 +62,18 @@ async fn main() -> Result<(), Box> {
key.public().to_peer_id(),
MemoryStore::new(key.public().to_peer_id()),
),
- mdns: mdns::async_io::Behaviour::new(
+ mdns: mdns::tokio::Behaviour::new(
mdns::Config::default(),
key.public().to_peer_id(),
)?,
})
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
swarm.behaviour_mut().kademlia.set_mode(Some(Mode::Server));
// Read full lines from stdin
- let mut stdin = io::BufReader::new(io::stdin()).lines().fuse();
+ let mut stdin = io::BufReader::new(io::stdin()).lines();
// Listen on all interfaces and whatever port the OS assigns.
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
@@ -80,7 +81,9 @@ async fn main() -> Result<(), Box> {
// Kick it off.
loop {
select! {
- line = stdin.select_next_some() => handle_input_line(&mut swarm.behaviour_mut().kademlia, line.expect("Stdin not to close")),
+ Ok(Some(line)) = stdin.next_line() => {
+ handle_input_line(&mut swarm.behaviour_mut().kademlia, line);
+ }
event = swarm.select_next_some() => match event {
SwarmEvent::NewListenAddr { address, .. } => {
println!("Listening in {address:?}");
diff --git a/examples/file-sharing/Cargo.toml b/examples/file-sharing/Cargo.toml
index 7cbb96cc7ed..021215c003b 100644
--- a/examples/file-sharing/Cargo.toml
+++ b/examples/file-sharing/Cargo.toml
@@ -14,9 +14,7 @@ tokio = { workspace = true, features = ["full"] }
clap = { version = "4.5.6", features = ["derive"] }
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = [ "tokio", "cbor", "dns", "kad", "noise", "macros", "request-response", "tcp", "websocket", "yamux"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
-void = "1.0.2"
[lints]
workspace = true
diff --git a/examples/file-sharing/src/main.rs b/examples/file-sharing/src/main.rs
index 5f6be83dc11..1e3b80a330c 100644
--- a/examples/file-sharing/src/main.rs
+++ b/examples/file-sharing/src/main.rs
@@ -22,15 +22,12 @@
mod network;
-use clap::Parser;
-use tokio::task::spawn;
+use std::{error::Error, io::Write, path::PathBuf};
-use futures::prelude::*;
-use futures::StreamExt;
+use clap::Parser;
+use futures::{prelude::*, StreamExt};
use libp2p::{core::Multiaddr, multiaddr::Protocol};
-use std::error::Error;
-use std::io::Write;
-use std::path::PathBuf;
+use tokio::task::spawn;
use tracing_subscriber::EnvFilter;
#[tokio::main]
diff --git a/examples/file-sharing/src/network.rs b/examples/file-sharing/src/network.rs
index a74afd1c0da..409255ee9ec 100644
--- a/examples/file-sharing/src/network.rs
+++ b/examples/file-sharing/src/network.rs
@@ -1,7 +1,14 @@
-use futures::channel::{mpsc, oneshot};
-use futures::prelude::*;
-use futures::StreamExt;
+use std::{
+ collections::{hash_map, HashMap, HashSet},
+ error::Error,
+ time::Duration,
+};
+use futures::{
+ channel::{mpsc, oneshot},
+ prelude::*,
+ StreamExt,
+};
use libp2p::{
core::Multiaddr,
identity, kad,
@@ -9,19 +16,13 @@ use libp2p::{
noise,
request_response::{self, OutboundRequestId, ProtocolSupport, ResponseChannel},
swarm::{NetworkBehaviour, Swarm, SwarmEvent},
- tcp, yamux, PeerId,
+ tcp, yamux, PeerId, StreamProtocol,
};
-
-use libp2p::StreamProtocol;
use serde::{Deserialize, Serialize};
-use std::collections::{hash_map, HashMap, HashSet};
-use std::error::Error;
-use std::time::Duration;
/// Creates the network components, namely:
///
-/// - The network client to interact with the network layer from anywhere
-/// within your application.
+/// - The network client to interact with the network layer from anywhere within your application.
///
/// - The network event stream, e.g. for incoming requests.
///
diff --git a/examples/identify/Cargo.toml b/examples/identify/Cargo.toml
index 8d12699afa7..c18f71a0386 100644
--- a/examples/identify/Cargo.toml
+++ b/examples/identify/Cargo.toml
@@ -12,7 +12,6 @@ release = false
tokio = { version = "1.37.0", features = ["full"] }
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = ["identify", "noise", "tcp", "tokio", "yamux"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/identify/src/main.rs b/examples/identify/src/main.rs
index 22474061da6..3f08ac01e23 100644
--- a/examples/identify/src/main.rs
+++ b/examples/identify/src/main.rs
@@ -20,9 +20,10 @@
#![doc = include_str!("../README.md")]
+use std::error::Error;
+
use futures::StreamExt;
use libp2p::{core::multiaddr::Multiaddr, identify, noise, swarm::SwarmEvent, tcp, yamux};
-use std::{error::Error, time::Duration};
use tracing_subscriber::EnvFilter;
#[tokio::main]
@@ -44,7 +45,6 @@ async fn main() -> Result<(), Box> {
key.public(),
))
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
// Tell the swarm to listen on all interfaces and a random, OS-assigned
diff --git a/examples/ipfs-kad/Cargo.toml b/examples/ipfs-kad/Cargo.toml
index 115c604269f..fa04da4edcf 100644
--- a/examples/ipfs-kad/Cargo.toml
+++ b/examples/ipfs-kad/Cargo.toml
@@ -10,13 +10,10 @@ release = false
[dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
-async-trait = "0.1"
clap = { version = "4.5.6", features = ["derive"] }
-env_logger = "0.10"
futures = { workspace = true }
anyhow = "1.0.86"
libp2p = { path = "../../libp2p", features = [ "tokio", "dns", "kad", "noise", "tcp", "yamux", "rsa"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/ipfs-kad/src/main.rs b/examples/ipfs-kad/src/main.rs
index 95921d6fa35..8d9a289bdd1 100644
--- a/examples/ipfs-kad/src/main.rs
+++ b/examples/ipfs-kad/src/main.rs
@@ -20,15 +20,21 @@
#![doc = include_str!("../README.md")]
-use std::num::NonZeroUsize;
-use std::ops::Add;
-use std::time::{Duration, Instant};
+use std::{
+ num::NonZeroUsize,
+ ops::Add,
+ time::{Duration, Instant},
+};
use anyhow::{bail, Result};
use clap::Parser;
use futures::StreamExt;
-use libp2p::swarm::{StreamProtocol, SwarmEvent};
-use libp2p::{bytes::BufMut, identity, kad, noise, tcp, yamux, PeerId};
+use libp2p::{
+ bytes::BufMut,
+ identity, kad, noise,
+ swarm::{StreamProtocol, SwarmEvent},
+ tcp, yamux, PeerId,
+};
use tracing_subscriber::EnvFilter;
const BOOTNODES: [&str; 4] = [
@@ -64,7 +70,6 @@ async fn main() -> Result<()> {
let store = kad::store::MemoryStore::new(key.public().to_peer_id());
kad::Behaviour::with_config(key.public().to_peer_id(), store, cfg)
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build();
// Add the bootnodes to the local routing table. `libp2p-dns` built
diff --git a/examples/ipfs-private/Cargo.toml b/examples/ipfs-private/Cargo.toml
index 0813dba56e0..4dfe596d609 100644
--- a/examples/ipfs-private/Cargo.toml
+++ b/examples/ipfs-private/Cargo.toml
@@ -10,11 +10,9 @@ release = false
[dependencies]
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-std"] }
-async-trait = "0.1"
either = "1.12"
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = [ "tokio", "gossipsub", "dns", "identify", "kad", "macros", "noise", "ping", "pnet", "tcp", "websocket", "yamux"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/ipfs-private/src/main.rs b/examples/ipfs-private/src/main.rs
index a57bfd465e0..6d8f9beb75d 100644
--- a/examples/ipfs-private/src/main.rs
+++ b/examples/ipfs-private/src/main.rs
@@ -20,6 +20,8 @@
#![doc = include_str!("../README.md")]
+use std::{env, error::Error, fs, path::Path, str::FromStr};
+
use either::Either;
use futures::prelude::*;
use libp2p::{
@@ -31,7 +33,6 @@ use libp2p::{
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, Multiaddr, Transport,
};
-use std::{env, error::Error, fs, path::Path, str::FromStr, time::Duration};
use tokio::{io, io::AsyncBufReadExt, select};
use tracing_subscriber::EnvFilter;
@@ -151,7 +152,6 @@ async fn main() -> Result<(), Box> {
ping: ping::Behaviour::new(ping::Config::new()),
})
})?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
println!("Subscribing to {gossipsub_topic:?}");
diff --git a/examples/metrics/Cargo.toml b/examples/metrics/Cargo.toml
index 2b82668f52a..ad2941e3761 100644
--- a/examples/metrics/Cargo.toml
+++ b/examples/metrics/Cargo.toml
@@ -12,13 +12,13 @@ release = false
futures = { workspace = true }
axum = "0.7"
libp2p = { path = "../../libp2p", features = ["tokio", "metrics", "ping", "noise", "identify", "tcp", "yamux", "macros"] }
-opentelemetry = { version = "0.23.0", features = ["metrics"] }
-opentelemetry-otlp = { version = "0.16.0", features = ["metrics"] }
-opentelemetry_sdk = { version = "0.23.0", features = ["rt-tokio", "metrics"] }
+opentelemetry = { version = "0.27.0", features = ["metrics"] }
+opentelemetry-otlp = { version = "0.27.0", features = ["metrics"] }
+opentelemetry_sdk = { version = "0.27.0", features = ["rt-tokio", "metrics"] }
prometheus-client = { workspace = true }
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true }
-tracing-opentelemetry = "0.24.0"
+tracing-opentelemetry = "0.28.0"
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/metrics/src/http_service.rs b/examples/metrics/src/http_service.rs
index 4a9c9785bb3..f1485832d86 100644
--- a/examples/metrics/src/http_service.rs
+++ b/examples/metrics/src/http_service.rs
@@ -18,15 +18,13 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use axum::extract::State;
-use axum::http::StatusCode;
-use axum::response::IntoResponse;
-use axum::routing::get;
-use axum::Router;
-use prometheus_client::encoding::text::encode;
-use prometheus_client::registry::Registry;
-use std::net::SocketAddr;
-use std::sync::{Arc, Mutex};
+use std::{
+ net::SocketAddr,
+ sync::{Arc, Mutex},
+};
+
+use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Router};
+use prometheus_client::{encoding::text::encode, registry::Registry};
use tokio::net::TcpListener;
const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text;charset=utf-8;version=1.0.0";
diff --git a/examples/metrics/src/main.rs b/examples/metrics/src/main.rs
index 99a9ca66aaf..6f6e9d08e31 100644
--- a/examples/metrics/src/main.rs
+++ b/examples/metrics/src/main.rs
@@ -20,18 +20,22 @@
#![doc = include_str!("../README.md")]
+use std::error::Error;
+
use futures::StreamExt;
-use libp2p::core::Multiaddr;
-use libp2p::metrics::{Metrics, Recorder};
-use libp2p::swarm::{NetworkBehaviour, SwarmEvent};
-use libp2p::{identify, identity, noise, ping, tcp, yamux};
-use opentelemetry::KeyValue;
+use libp2p::{
+ core::Multiaddr,
+ identify, identity,
+ metrics::{Metrics, Recorder},
+ noise, ping,
+ swarm::{NetworkBehaviour, SwarmEvent},
+ tcp, yamux,
+};
+use opentelemetry::{trace::TracerProvider as _, KeyValue};
+use opentelemetry_otlp::SpanExporter;
+use opentelemetry_sdk::{runtime, trace::TracerProvider};
use prometheus_client::registry::Registry;
-use std::error::Error;
-use std::time::Duration;
-use tracing_subscriber::layer::SubscriberExt;
-use tracing_subscriber::util::SubscriberInitExt;
-use tracing_subscriber::{EnvFilter, Layer};
+use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
mod http_service;
@@ -50,7 +54,6 @@ async fn main() -> Result<(), Box> {
)?
.with_bandwidth_metrics(&mut metric_registry)
.with_behaviour(|key| Behaviour::new(key.public()))?
- .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
.build();
swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse()?)?;
@@ -90,22 +93,24 @@ async fn main() -> Result<(), Box> {
}
fn setup_tracing() -> Result<(), Box> {
- let tracer = opentelemetry_otlp::new_pipeline()
- .tracing()
- .with_exporter(opentelemetry_otlp::new_exporter().tonic())
- .with_trace_config(opentelemetry_sdk::trace::Config::default().with_resource(
- opentelemetry_sdk::Resource::new(vec![KeyValue::new("service.name", "libp2p")]),
- ))
- .install_batch(opentelemetry_sdk::runtime::Tokio)?;
-
+ let provider = TracerProvider::builder()
+ .with_batch_exporter(
+ SpanExporter::builder().with_tonic().build()?,
+ runtime::Tokio,
+ )
+ .with_resource(opentelemetry_sdk::Resource::new(vec![KeyValue::new(
+ "service.name",
+ "libp2p",
+ )]))
+ .build();
tracing_subscriber::registry()
.with(tracing_subscriber::fmt::layer().with_filter(EnvFilter::from_default_env()))
.with(
tracing_opentelemetry::layer()
- .with_tracer(tracer)
+ .with_tracer(provider.tracer("libp2p-subscriber"))
.with_filter(EnvFilter::from_default_env()),
)
- .try_init()?;
+ .init();
Ok(())
}
diff --git a/examples/ping/Cargo.toml b/examples/ping/Cargo.toml
index 633f043de56..acc3b2affed 100644
--- a/examples/ping/Cargo.toml
+++ b/examples/ping/Cargo.toml
@@ -12,7 +12,6 @@ release = false
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = ["noise", "ping", "tcp", "tokio", "yamux"] }
tokio = { workspace = true, features = ["full"] }
-tracing = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/ping/src/main.rs b/examples/ping/src/main.rs
index 911b0384f89..565ef057c0d 100644
--- a/examples/ping/src/main.rs
+++ b/examples/ping/src/main.rs
@@ -20,9 +20,10 @@
#![doc = include_str!("../README.md")]
+use std::{error::Error, time::Duration};
+
use futures::prelude::*;
use libp2p::{noise, ping, swarm::SwarmEvent, tcp, yamux, Multiaddr};
-use std::{error::Error, time::Duration};
use tracing_subscriber::EnvFilter;
#[tokio::main]
diff --git a/examples/relay-server/Cargo.toml b/examples/relay-server/Cargo.toml
index 12d3e2467ce..3bdaf89b04f 100644
--- a/examples/relay-server/Cargo.toml
+++ b/examples/relay-server/Cargo.toml
@@ -10,11 +10,9 @@ release = false
[dependencies]
clap = { version = "4.5.6", features = ["derive"] }
-async-std = { version = "1.12", features = ["attributes"] }
-async-trait = "0.1"
+tokio = { version = "1.37.0", features = ["full"] }
futures = { workspace = true }
-libp2p = { path = "../../libp2p", features = [ "async-std", "noise", "macros", "ping", "tcp", "identify", "yamux", "relay", "quic"] }
-tracing = { workspace = true }
+libp2p = { path = "../../libp2p", features = ["tokio", "noise", "macros", "ping", "tcp", "identify", "yamux", "relay", "quic"] }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
[lints]
diff --git a/examples/relay-server/src/main.rs b/examples/relay-server/src/main.rs
index bf5817454f8..b7868418fb0 100644
--- a/examples/relay-server/src/main.rs
+++ b/examples/relay-server/src/main.rs
@@ -21,21 +21,23 @@
#![doc = include_str!("../README.md")]
+use std::{
+ error::Error,
+ net::{Ipv4Addr, Ipv6Addr},
+};
+
use clap::Parser;
-use futures::executor::block_on;
-use futures::stream::StreamExt;
+use futures::StreamExt;
use libp2p::{
- core::multiaddr::Protocol,
- core::Multiaddr,
+ core::{multiaddr::Protocol, Multiaddr},
identify, identity, noise, ping, relay,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux,
};
-use std::error::Error;
-use std::net::{Ipv4Addr, Ipv6Addr};
use tracing_subscriber::EnvFilter;
-fn main() -> Result<(), Box> {
+#[tokio::main]
+async fn main() -> Result<(), Box> {
let _ = tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.try_init();
@@ -46,7 +48,7 @@ fn main() -> Result<(), Box> {
let local_key: identity::Keypair = generate_ed25519(opt.secret_key_seed);
let mut swarm = libp2p::SwarmBuilder::with_existing_identity(local_key)
- .with_async_std()
+ .with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
@@ -81,27 +83,25 @@ fn main() -> Result<(), Box> {
.with(Protocol::QuicV1);
swarm.listen_on(listen_addr_quic)?;
- block_on(async {
- loop {
- match swarm.next().await.expect("Infinite Stream.") {
- SwarmEvent::Behaviour(event) => {
- if let BehaviourEvent::Identify(identify::Event::Received {
- info: identify::Info { observed_addr, .. },
- ..
- }) = &event
- {
- swarm.add_external_address(observed_addr.clone());
- }
-
- println!("{event:?}")
- }
- SwarmEvent::NewListenAddr { address, .. } => {
- println!("Listening on {address:?}");
+ loop {
+ match swarm.next().await.expect("Infinite Stream.") {
+ SwarmEvent::Behaviour(event) => {
+ if let BehaviourEvent::Identify(identify::Event::Received {
+ info: identify::Info { observed_addr, .. },
+ ..
+ }) = &event
+ {
+ swarm.add_external_address(observed_addr.clone());
}
- _ => {}
+
+ println!("{event:?}")
+ }
+ SwarmEvent::NewListenAddr { address, .. } => {
+ println!("Listening on {address:?}");
}
+ _ => {}
}
- })
+ }
}
#[derive(NetworkBehaviour)]
diff --git a/examples/rendezvous/src/bin/rzv-discover.rs b/examples/rendezvous/src/bin/rzv-discover.rs
index edd3d10a0ce..bdf9aeafdab 100644
--- a/examples/rendezvous/src/bin/rzv-discover.rs
+++ b/examples/rendezvous/src/bin/rzv-discover.rs
@@ -18,6 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{error::Error, time::Duration};
+
use futures::StreamExt;
use libp2p::{
multiaddr::Protocol,
@@ -25,8 +27,6 @@ use libp2p::{
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, Multiaddr,
};
-use std::error::Error;
-use std::time::Duration;
use tracing_subscriber::EnvFilter;
const NAMESPACE: &str = "rendezvous";
@@ -53,7 +53,6 @@ async fn main() -> Result<(), Box> {
rendezvous: rendezvous::client::Behaviour::new(key.clone()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
})?
- .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(5)))
.build();
swarm.dial(rendezvous_point_address.clone()).unwrap();
diff --git a/examples/rendezvous/src/bin/rzv-identify.rs b/examples/rendezvous/src/bin/rzv-identify.rs
index ff637aa6f49..00e94627292 100644
--- a/examples/rendezvous/src/bin/rzv-identify.rs
+++ b/examples/rendezvous/src/bin/rzv-identify.rs
@@ -18,13 +18,14 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::time::Duration;
+
use futures::StreamExt;
use libp2p::{
identify, noise, ping, rendezvous,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, Multiaddr,
};
-use std::time::Duration;
use tracing_subscriber::EnvFilter;
#[tokio::main]
@@ -55,7 +56,6 @@ async fn main() {
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
})
.unwrap()
- .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(5)))
.build();
let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap());
diff --git a/examples/rendezvous/src/bin/rzv-register.rs b/examples/rendezvous/src/bin/rzv-register.rs
index bd848238d4a..f70eda5d55e 100644
--- a/examples/rendezvous/src/bin/rzv-register.rs
+++ b/examples/rendezvous/src/bin/rzv-register.rs
@@ -18,13 +18,14 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::time::Duration;
+
use futures::StreamExt;
use libp2p::{
noise, ping, rendezvous,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, Multiaddr,
};
-use std::time::Duration;
use tracing_subscriber::EnvFilter;
#[tokio::main]
@@ -51,11 +52,10 @@ async fn main() {
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
})
.unwrap()
- .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(5)))
.build();
- // In production the external address should be the publicly facing IP address of the rendezvous point.
- // This address is recorded in the registration entry by the rendezvous point.
+ // In production the external address should be the publicly facing IP address of the rendezvous
+ // point. This address is recorded in the registration entry by the rendezvous point.
let external_address = "/ip4/127.0.0.1/tcp/0".parse::().unwrap();
swarm.add_external_address(external_address);
diff --git a/examples/rendezvous/src/main.rs b/examples/rendezvous/src/main.rs
index a15bc1ca2d3..a345d0faed9 100644
--- a/examples/rendezvous/src/main.rs
+++ b/examples/rendezvous/src/main.rs
@@ -20,14 +20,14 @@
#![doc = include_str!("../README.md")]
+use std::{error::Error, time::Duration};
+
use futures::StreamExt;
use libp2p::{
identify, noise, ping, rendezvous,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux,
};
-use std::error::Error;
-use std::time::Duration;
use tracing_subscriber::EnvFilter;
#[tokio::main]
@@ -55,7 +55,6 @@ async fn main() -> Result<(), Box> {
rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
})?
- .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(5)))
.build();
let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/62649".parse().unwrap());
diff --git a/examples/stream/Cargo.toml b/examples/stream/Cargo.toml
index ba31d4d9e13..03d7ea425e5 100644
--- a/examples/stream/Cargo.toml
+++ b/examples/stream/Cargo.toml
@@ -12,7 +12,7 @@ release = false
anyhow = "1"
futures = { workspace = true }
libp2p = { path = "../../libp2p", features = [ "tokio", "quic"] }
-libp2p-stream = { path = "../../protocols/stream", version = "0.2.0-alpha" }
+libp2p-stream = { path = "../../protocols/stream", version = "0.3.0-alpha" }
rand = "0.8"
tokio = { workspace = true, features = ["full"] }
tracing = { workspace = true }
diff --git a/examples/stream/src/main.rs b/examples/stream/src/main.rs
index 872ab8c3b98..71d2d2fcc76 100644
--- a/examples/stream/src/main.rs
+++ b/examples/stream/src/main.rs
@@ -44,12 +44,14 @@ async fn main() -> Result<()> {
// Deal with incoming streams.
// Spawning a dedicated task is just one way of doing this.
// libp2p doesn't care how you handle incoming streams but you _must_ handle them somehow.
- // To mitigate DoS attacks, libp2p will internally drop incoming streams if your application cannot keep up processing them.
+ // To mitigate DoS attacks, libp2p will internally drop incoming streams if your application
+ // cannot keep up processing them.
tokio::spawn(async move {
// This loop handles incoming streams _sequentially_ but that doesn't have to be the case.
// You can also spawn a dedicated task per stream if you want to.
- // Be aware that this breaks backpressure though as spawning new tasks is equivalent to an unbounded buffer.
- // Each task needs memory meaning an aggressive remote peer may force you OOM this way.
+ // Be aware that this breaks backpressure though as spawning new tasks is equivalent to an
+ // unbounded buffer. Each task needs memory meaning an aggressive remote peer may
+ // force you OOM this way.
while let Some((peer, stream)) = incoming_streams.next().await {
match echo(stream).await {
@@ -102,7 +104,8 @@ async fn connection_handler(peer: PeerId, mut control: stream::Control) {
}
Err(error) => {
// Other errors may be temporary.
- // In production, something like an exponential backoff / circuit-breaker may be more appropriate.
+ // In production, something like an exponential backoff / circuit-breaker may be
+ // more appropriate.
tracing::debug!(%peer, %error);
continue;
}
diff --git a/examples/upnp/src/main.rs b/examples/upnp/src/main.rs
index fd0764990d1..19de8d773ae 100644
--- a/examples/upnp/src/main.rs
+++ b/examples/upnp/src/main.rs
@@ -20,9 +20,10 @@
#![doc = include_str!("../README.md")]
+use std::error::Error;
+
use futures::prelude::*;
use libp2p::{noise, swarm::SwarmEvent, upnp, yamux, Multiaddr};
-use std::error::Error;
use tracing_subscriber::EnvFilter;
#[tokio::main]
diff --git a/hole-punching-tests/Cargo.toml b/hole-punching-tests/Cargo.toml
index 79728f9535c..c4f36d2a990 100644
--- a/hole-punching-tests/Cargo.toml
+++ b/hole-punching-tests/Cargo.toml
@@ -7,7 +7,7 @@ license = "MIT"
[dependencies]
anyhow = "1"
-env_logger = "0.10.2"
+env_logger = { workspace = true }
futures = { workspace = true }
libp2p = { path = "../libp2p", features = ["tokio", "dcutr", "identify", "macros", "noise", "ping", "relay", "tcp", "yamux", "quic"] }
tracing = { workspace = true }
diff --git a/hole-punching-tests/Dockerfile b/hole-punching-tests/Dockerfile
index af00ef2272f..30c8e0a6414 100644
--- a/hole-punching-tests/Dockerfile
+++ b/hole-punching-tests/Dockerfile
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1.5-labs
-FROM rust:1.75.0 as builder
+FROM rust:1.83.0 as builder
# Run with access to the target cache to speed up builds
WORKDIR /workspace
diff --git a/hole-punching-tests/src/main.rs b/hole-punching-tests/src/main.rs
index 02229e16262..bc5a1bae4f5 100644
--- a/hole-punching-tests/src/main.rs
+++ b/hole-punching-tests/src/main.rs
@@ -18,24 +18,27 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{
+ collections::HashMap,
+ fmt, io,
+ net::{IpAddr, Ipv4Addr},
+ str::FromStr,
+ time::Duration,
+};
+
use anyhow::{Context, Result};
use either::Either;
use futures::stream::StreamExt;
-use libp2p::core::transport::ListenerId;
-use libp2p::swarm::dial_opts::DialOpts;
-use libp2p::swarm::ConnectionId;
use libp2p::{
- core::multiaddr::{Multiaddr, Protocol},
+ core::{
+ multiaddr::{Multiaddr, Protocol},
+ transport::ListenerId,
+ },
dcutr, identify, noise, ping, relay,
- swarm::{NetworkBehaviour, SwarmEvent},
+ swarm::{dial_opts::DialOpts, ConnectionId, NetworkBehaviour, SwarmEvent},
tcp, yamux, Swarm,
};
use redis::AsyncCommands;
-use std::collections::HashMap;
-use std::net::{IpAddr, Ipv4Addr};
-use std::str::FromStr;
-use std::time::Duration;
-use std::{fmt, io};
/// The redis key we push the relay's TCP listen address to.
const RELAY_TCP_ADDRESS: &str = "RELAY_TCP_ADDRESS";
diff --git a/identity/CHANGELOG.md b/identity/CHANGELOG.md
index 9670a843130..98f3e5c5636 100644
--- a/identity/CHANGELOG.md
+++ b/identity/CHANGELOG.md
@@ -1,3 +1,8 @@
+## 0.2.10
+
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
## 0.2.9
- Add `rand` feature gate to ecdsa methods requiring a random number generator.
@@ -5,7 +10,7 @@
## 0.2.8
-- Bump `ring` to `0.17.5.
+- Bump `ring` to `0.17.5`.
See [PR 4779](https://github.com/libp2p/rust-libp2p/pull/4779).
## 0.2.7
diff --git a/identity/Cargo.toml b/identity/Cargo.toml
index cb0b8cb000e..b13229c5826 100644
--- a/identity/Cargo.toml
+++ b/identity/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "libp2p-identity"
-version = "0.2.9"
+version = "0.2.10"
edition = "2021"
description = "Data structures and algorithms for identifying peers in libp2p."
rust-version = "1.73.0" # MUST NOT inherit from workspace because we don't want to publish breaking changes to `libp2p-identity`.
@@ -25,8 +25,7 @@ rand = { version = "0.8", optional = true }
sec1 = { version = "0.7", default-features = false, optional = true }
serde = { version = "1", optional = true, features = ["derive"] }
sha2 = { version = "0.10.8", optional = true }
-thiserror = { version = "1.0", optional = true }
-void = { version = "1.0", optional = true }
+thiserror = { workspace = true, optional = true }
zeroize = { version = "1.8", optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
@@ -34,7 +33,7 @@ ring = { workspace = true, features = ["alloc", "std"], optional = true }
[features]
secp256k1 = ["dep:libsecp256k1", "dep:asn1_der", "dep:sha2", "dep:hkdf", "dep:zeroize"]
-ecdsa = ["dep:p256", "dep:void", "dep:zeroize", "dep:sec1", "dep:sha2", "dep:hkdf"]
+ecdsa = ["dep:p256", "dep:zeroize", "dep:sec1", "dep:sha2", "dep:hkdf"]
rsa = ["dep:ring", "dep:asn1_der", "dep:rand", "dep:zeroize"]
ed25519 = ["dep:ed25519-dalek", "dep:zeroize", "dep:sha2", "dep:hkdf"]
peerid = ["dep:multihash", "dep:bs58", "dep:thiserror", "dep:sha2", "dep:hkdf"]
@@ -42,7 +41,6 @@ rand = ["dep:rand", "ed25519-dalek?/rand_core"]
[dev-dependencies]
quickcheck = { workspace = true }
-base64 = "0.22.1"
serde_json = "1.0"
rmp-serde = "1.3"
criterion = "0.5"
diff --git a/identity/src/ecdsa.rs b/identity/src/ecdsa.rs
index 65cbe885b86..11cdaced795 100644
--- a/identity/src/ecdsa.rs
+++ b/identity/src/ecdsa.rs
@@ -20,10 +20,9 @@
//! ECDSA keys with secp256r1 curve support.
-use super::error::DecodingError;
-use core::cmp;
-use core::fmt;
-use core::hash;
+use core::{cmp, fmt, hash};
+use std::convert::Infallible;
+
use p256::{
ecdsa::{
signature::{Signer, Verifier},
@@ -32,9 +31,10 @@ use p256::{
EncodedPoint,
};
use sec1::{DecodeEcPrivateKey, EncodeEcPrivateKey};
-use void::Void;
use zeroize::Zeroize;
+use super::error::DecodingError;
+
/// An ECDSA keypair generated using `secp256r1` curve.
#[derive(Clone)]
pub struct Keypair {
@@ -158,7 +158,8 @@ impl PublicKey {
self.0.verify(msg, &sig).is_ok()
}
- /// Try to parse a public key from a byte buffer containing raw components of a key with or without compression.
+ /// Try to parse a public key from a byte buffer containing raw
+ /// components of a key with or without compression.
pub fn try_from_bytes(k: &[u8]) -> Result {
let enc_pt = EncodedPoint::from_bytes(k)
.map_err(|e| DecodingError::failed_to_parse("ecdsa p256 encoded point", e))?;
@@ -168,7 +169,8 @@ impl PublicKey {
.map(PublicKey)
}
- /// Convert a public key into a byte buffer containing raw components of the key without compression.
+ /// Convert a public key into a byte buffer containing
+ /// raw components of the key without compression.
pub fn to_bytes(&self) -> Vec {
self.0.to_encoded_point(false).as_bytes().to_owned()
}
@@ -182,7 +184,10 @@ impl PublicKey {
/// Try to decode a public key from a DER encoded byte buffer as defined by SEC1 standard.
pub fn try_decode_der(k: &[u8]) -> Result {
let buf = Self::del_asn1_header(k).ok_or_else(|| {
- DecodingError::failed_to_parse::("ASN.1-encoded ecdsa p256 public key", None)
+ DecodingError::failed_to_parse::(
+ "ASN.1-encoded ecdsa p256 public key",
+ None,
+ )
})?;
Self::try_from_bytes(buf)
}
diff --git a/identity/src/ed25519.rs b/identity/src/ed25519.rs
index d77c44547d6..5a1a53dd4af 100644
--- a/identity/src/ed25519.rs
+++ b/identity/src/ed25519.rs
@@ -20,13 +20,13 @@
//! Ed25519 keys.
-use super::error::DecodingError;
-use core::cmp;
-use core::fmt;
-use core::hash;
+use core::{cmp, fmt, hash};
+
use ed25519_dalek::{self as ed25519, Signer as _, Verifier as _};
use zeroize::Zeroize;
+use super::error::DecodingError;
+
/// An Ed25519 keypair.
#[derive(Clone)]
pub struct Keypair(ed25519::SigningKey);
@@ -152,7 +152,8 @@ impl PublicKey {
self.0.to_bytes()
}
- /// Try to parse a public key from a byte array containing the actual key as produced by `to_bytes`.
+ /// Try to parse a public key from a byte array containing
+ /// the actual key as produced by `to_bytes`.
pub fn try_from_bytes(k: &[u8]) -> Result {
let k = <[u8; 32]>::try_from(k)
.map_err(|e| DecodingError::failed_to_parse("Ed25519 public key", e))?;
@@ -206,9 +207,10 @@ impl SecretKey {
#[cfg(test)]
mod tests {
- use super::*;
use quickcheck::*;
+ use super::*;
+
fn eq_keypairs(kp1: &Keypair, kp2: &Keypair) -> bool {
kp1.public() == kp2.public() && kp1.0.to_bytes() == kp2.0.to_bytes()
}
diff --git a/identity/src/error.rs b/identity/src/error.rs
index 71cd78fe1ea..6e8c4d02caa 100644
--- a/identity/src/error.rs
+++ b/identity/src/error.rs
@@ -20,8 +20,7 @@
//! Errors during identity key operations.
-use std::error::Error;
-use std::fmt;
+use std::{error::Error, fmt};
use crate::KeyType;
diff --git a/identity/src/keypair.rs b/identity/src/keypair.rs
index f1e8a7c2142..a1bbba00fa9 100644
--- a/identity/src/keypair.rs
+++ b/identity/src/keypair.rs
@@ -24,40 +24,40 @@
feature = "ed25519",
feature = "rsa"
))]
-#[cfg(feature = "ed25519")]
-use crate::ed25519;
+use quick_protobuf::{BytesReader, Writer};
+
+#[cfg(feature = "ecdsa")]
+use crate::ecdsa;
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
))]
-use crate::error::OtherVariantError;
-use crate::error::{DecodingError, SigningError};
+#[cfg(feature = "ed25519")]
+use crate::ed25519;
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
))]
-use crate::proto;
+use crate::error::OtherVariantError;
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
feature = "ed25519",
feature = "rsa"
))]
-use quick_protobuf::{BytesReader, Writer};
-
+use crate::proto;
#[cfg(all(feature = "rsa", not(target_arch = "wasm32")))]
use crate::rsa;
-
#[cfg(feature = "secp256k1")]
use crate::secp256k1;
-
-#[cfg(feature = "ecdsa")]
-use crate::ecdsa;
-use crate::KeyType;
+use crate::{
+ error::{DecodingError, SigningError},
+ KeyType,
+};
/// Identity keypair of a node.
///
@@ -75,7 +75,6 @@ use crate::KeyType;
/// let mut bytes = std::fs::read("private.pk8").unwrap();
/// let keypair = Keypair::rsa_from_pkcs8(&mut bytes);
/// ```
-///
#[derive(Debug, Clone)]
pub struct Keypair {
keypair: KeyPairInner,
@@ -341,7 +340,8 @@ impl Keypair {
}
}
- /// Deterministically derive a new secret from this [`Keypair`], taking into account the provided domain.
+ /// Deterministically derive a new secret from this [`Keypair`],
+ /// taking into account the provided domain.
///
/// This works for all key types except RSA where it returns `None`.
///
@@ -352,10 +352,11 @@ impl Keypair {
/// # use libp2p_identity as identity;
/// let key = identity::Keypair::generate_ed25519();
///
- /// let new_key = key.derive_secret(b"my encryption key").expect("can derive secret for ed25519");
+ /// let new_key = key
+ /// .derive_secret(b"my encryption key")
+ /// .expect("can derive secret for ed25519");
/// # }
/// ```
- ///
#[cfg(any(
feature = "ecdsa",
feature = "secp256k1",
@@ -904,9 +905,10 @@ mod tests {
#[test]
fn public_key_implements_hash() {
- use crate::PublicKey;
use std::hash::Hash;
+ use crate::PublicKey;
+
fn assert_implements_hash() {}
assert_implements_hash::();
@@ -914,9 +916,10 @@ mod tests {
#[test]
fn public_key_implements_ord() {
- use crate::PublicKey;
use std::cmp::Ord;
+ use crate::PublicKey;
+
fn assert_implements_ord() {}
assert_implements_ord::();
diff --git a/identity/src/peer_id.rs b/identity/src/peer_id.rs
index 7b3f799f612..7f6d1f44eab 100644
--- a/identity/src/peer_id.rs
+++ b/identity/src/peer_id.rs
@@ -18,17 +18,19 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{fmt, str::FromStr};
+
#[cfg(feature = "rand")]
use rand::Rng;
use sha2::Digest as _;
-use std::{fmt, str::FromStr};
use thiserror::Error;
/// Local type-alias for multihash.
///
/// Must be big enough to accommodate for `MAX_INLINE_KEY_LENGTH`.
/// 64 satisfies that and can hold 512 bit hashes which is what the ecosystem typically uses.
-/// Given that this appears in our type-signature, using a "common" number here makes us more compatible.
+/// Given that this appears in our type-signature,
+/// using a "common" number here makes us more compatible.
type Multihash = multihash::Multihash<64>;
#[cfg(feature = "serde")]
@@ -191,7 +193,7 @@ impl<'de> Deserialize<'de> for PeerId {
struct PeerIdVisitor;
- impl<'de> Visitor<'de> for PeerIdVisitor {
+ impl Visitor<'_> for PeerIdVisitor {
type Value = PeerId;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
diff --git a/identity/src/rsa.rs b/identity/src/rsa.rs
index cbfe3c1b919..b14d8c66d86 100644
--- a/identity/src/rsa.rs
+++ b/identity/src/rsa.rs
@@ -20,15 +20,20 @@
//! RSA keys.
-use super::error::*;
-use asn1_der::typed::{DerDecodable, DerEncodable, DerTypeView, Sequence};
-use asn1_der::{Asn1DerError, Asn1DerErrorVariant, DerObject, Sink, VecBacking};
-use ring::rand::SystemRandom;
-use ring::signature::KeyPair;
-use ring::signature::{self, RsaKeyPair, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_SHA256};
use std::{fmt, sync::Arc};
+
+use asn1_der::{
+ typed::{DerDecodable, DerEncodable, DerTypeView, Sequence},
+ Asn1DerError, Asn1DerErrorVariant, DerObject, Sink, VecBacking,
+};
+use ring::{
+ rand::SystemRandom,
+ signature::{self, KeyPair, RsaKeyPair, RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_SHA256},
+};
use zeroize::Zeroize;
+use super::error::*;
+
/// An RSA keypair.
#[derive(Clone)]
pub struct Keypair(Arc);
@@ -149,7 +154,7 @@ struct Asn1RawOid<'a> {
object: DerObject<'a>,
}
-impl<'a> Asn1RawOid<'a> {
+impl Asn1RawOid<'_> {
/// The underlying OID as byte literal.
pub(crate) fn oid(&self) -> &[u8] {
self.object.value()
@@ -169,7 +174,7 @@ impl<'a> DerTypeView<'a> for Asn1RawOid<'a> {
}
}
-impl<'a> DerEncodable for Asn1RawOid<'a> {
+impl DerEncodable for Asn1RawOid<'_> {
fn encode(&self, sink: &mut S) -> Result<(), Asn1DerError> {
self.object.encode(sink)
}
@@ -315,9 +320,10 @@ impl DerDecodable<'_> for Asn1SubjectPublicKeyInfo {
#[cfg(test)]
mod tests {
- use super::*;
use quickcheck::*;
+ use super::*;
+
const KEY1: &[u8] = include_bytes!("test/rsa-2048.pk8");
const KEY2: &[u8] = include_bytes!("test/rsa-3072.pk8");
const KEY3: &[u8] = include_bytes!("test/rsa-4096.pk8");
diff --git a/identity/src/secp256k1.rs b/identity/src/secp256k1.rs
index a6e9e923268..e884cf1385d 100644
--- a/identity/src/secp256k1.rs
+++ b/identity/src/secp256k1.rs
@@ -20,15 +20,15 @@
//! Secp256k1 keys.
-use super::error::DecodingError;
+use core::{cmp, fmt, hash};
+
use asn1_der::typed::{DerDecodable, Sequence};
-use core::cmp;
-use core::fmt;
-use core::hash;
use libsecp256k1::{Message, Signature};
use sha2::{Digest as ShaDigestTrait, Sha256};
use zeroize::Zeroize;
+use super::error::DecodingError;
+
/// A Secp256k1 keypair.
#[derive(Clone)]
pub struct Keypair {
diff --git a/interop-tests/Cargo.toml b/interop-tests/Cargo.toml
index 0eb32bb4975..8f12275668d 100644
--- a/interop-tests/Cargo.toml
+++ b/interop-tests/Cargo.toml
@@ -13,7 +13,6 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
anyhow = "1"
-either = "1.11.0"
futures = { workspace = true }
rand = "0.8.5"
serde = { version = "1", features = ["derive"] }
diff --git a/interop-tests/Dockerfile.chromium b/interop-tests/Dockerfile.chromium
index a6b0fc89e82..73a9ab82ee7 100644
--- a/interop-tests/Dockerfile.chromium
+++ b/interop-tests/Dockerfile.chromium
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1.5-labs
-FROM rust:1.75.0 as chef
+FROM rust:1.83 as chef
RUN rustup target add wasm32-unknown-unknown
RUN wget -q -O- https://github.com/rustwasm/wasm-pack/releases/download/v0.12.1/wasm-pack-v0.12.1-x86_64-unknown-linux-musl.tar.gz | tar -zx -C /usr/local/bin --strip-components 1 --wildcards "wasm-pack-*/wasm-pack"
RUN wget -q -O- https://github.com/WebAssembly/binaryen/releases/download/version_115/binaryen-version_115-x86_64-linux.tar.gz | tar -zx -C /usr/local/bin --strip-components 2 --wildcards "binaryen-version_*/bin/wasm-opt"
@@ -14,7 +14,7 @@ FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Build dependencies - this is the caching Docker layer!
RUN cargo chef cook --release --package interop-tests --target wasm32-unknown-unknown --recipe-path recipe.json
-RUN RUSTFLAGS='-C target-feature=+crt-static' cargo chef cook --release --package interop-tests --target x86_64-unknown-linux-gnu --bin wasm_ping --recipe-path recipe.json
+RUN cargo chef cook --release --package interop-tests --bin wasm_ping --recipe-path recipe.json
# Build application
COPY . .
RUN wasm-pack build --target web interop-tests
diff --git a/interop-tests/Dockerfile.native b/interop-tests/Dockerfile.native
index b122ac72991..fab50dc50ad 100644
--- a/interop-tests/Dockerfile.native
+++ b/interop-tests/Dockerfile.native
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1.5-labs
-FROM lukemathwalker/cargo-chef:0.1.62-rust-1.75.0 as chef
+FROM lukemathwalker/cargo-chef:0.1.68-rust-bullseye as chef
WORKDIR /app
FROM chef AS planner
@@ -9,13 +9,13 @@ RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
COPY --from=planner /app/recipe.json recipe.json
# Build dependencies - this is the caching Docker layer!
-RUN RUSTFLAGS='-C target-feature=+crt-static' cargo chef cook --release --package interop-tests --target $(rustc -vV | grep host | awk '{print $2}') --bin native_ping --recipe-path recipe.json
+RUN cargo chef cook --release --package interop-tests --bin native_ping --recipe-path recipe.json
# Build application
COPY . .
RUN RUSTFLAGS='-C target-feature=+crt-static' cargo build --release --package interop-tests --target $(rustc -vV | grep host | awk '{print $2}') --bin native_ping
RUN cp /app/target/$(rustc -vV | grep host | awk '{print $2}')/release/native_ping /usr/local/bin/testplan
-FROM scratch
+FROM debian:bullseye
COPY --from=builder /usr/local/bin/testplan /usr/local/bin/testplan
ENV RUST_BACKTRACE=1
ENTRYPOINT ["testplan"]
diff --git a/interop-tests/src/arch.rs b/interop-tests/src/arch.rs
index df36f8e5baf..91fc69dc215 100644
--- a/interop-tests/src/arch.rs
+++ b/interop-tests/src/arch.rs
@@ -1,7 +1,6 @@
// Native re-exports
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use native::{build_swarm, init_logger, sleep, Instant, RedisClient};
-
// Wasm re-exports
#[cfg(target_arch = "wasm32")]
pub(crate) use wasm::{build_swarm, init_logger, sleep, Instant, RedisClient};
@@ -11,11 +10,13 @@ pub(crate) mod native {
use std::time::Duration;
use anyhow::{bail, Context, Result};
- use futures::future::BoxFuture;
- use futures::FutureExt;
- use libp2p::identity::Keypair;
- use libp2p::swarm::{NetworkBehaviour, Swarm};
- use libp2p::{noise, tcp, tls, yamux};
+ use futures::{future::BoxFuture, FutureExt};
+ use libp2p::{
+ identity::Keypair,
+ noise,
+ swarm::{NetworkBehaviour, Swarm},
+ tcp, tls, yamux,
+ };
use libp2p_mplex as mplex;
use libp2p_webrtc as webrtc;
use redis::AsyncCommands;
@@ -48,7 +49,6 @@ pub(crate) mod native {
.with_tokio()
.with_quic()
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/udp/0/quic-v1"),
),
@@ -61,7 +61,6 @@ pub(crate) mod native {
mplex::MplexConfig::default,
)?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0"),
),
@@ -74,7 +73,6 @@ pub(crate) mod native {
yamux::Config::default,
)?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0"),
),
@@ -87,7 +85,6 @@ pub(crate) mod native {
mplex::MplexConfig::default,
)?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0"),
),
@@ -100,7 +97,6 @@ pub(crate) mod native {
yamux::Config::default,
)?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0"),
),
@@ -110,7 +106,6 @@ pub(crate) mod native {
.with_websocket(tls::Config::new, mplex::MplexConfig::default)
.await?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0/ws"),
),
@@ -120,7 +115,6 @@ pub(crate) mod native {
.with_websocket(tls::Config::new, yamux::Config::default)
.await?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0/ws"),
),
@@ -130,7 +124,6 @@ pub(crate) mod native {
.with_websocket(noise::Config::new, mplex::MplexConfig::default)
.await?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0/ws"),
),
@@ -140,7 +133,6 @@ pub(crate) mod native {
.with_websocket(noise::Config::new, yamux::Config::default)
.await?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/tcp/0/ws"),
),
@@ -154,7 +146,6 @@ pub(crate) mod native {
))
})?
.with_behaviour(behaviour_constructor)?
- .with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(5)))
.build(),
format!("/ip4/{ip}/udp/0/webrtc-direct"),
),
@@ -186,15 +177,19 @@ pub(crate) mod native {
#[cfg(target_arch = "wasm32")]
pub(crate) mod wasm {
+ use std::time::Duration;
+
use anyhow::{bail, Context, Result};
use futures::future::{BoxFuture, FutureExt};
- use libp2p::core::upgrade::Version;
- use libp2p::identity::Keypair;
- use libp2p::swarm::{NetworkBehaviour, Swarm};
- use libp2p::{noise, websocket_websys, webtransport_websys, yamux, Transport as _};
+ use libp2p::{
+ core::upgrade::Version,
+ identity::Keypair,
+ noise,
+ swarm::{NetworkBehaviour, Swarm},
+ websocket_websys, webtransport_websys, yamux, Transport as _,
+ };
use libp2p_mplex as mplex;
use libp2p_webrtc_websys as webrtc_websys;
- use std::time::Duration;
use crate::{BlpopRequest, Muxer, SecProtocol, Transport};
diff --git a/interop-tests/src/bin/wasm_ping.rs b/interop-tests/src/bin/wasm_ping.rs
index 0d697a0e2a3..7730b869456 100644
--- a/interop-tests/src/bin/wasm_ping.rs
+++ b/interop-tests/src/bin/wasm_ping.rs
@@ -1,26 +1,27 @@
#![allow(non_upper_case_globals)]
-use std::future::IntoFuture;
-use std::process::Stdio;
-use std::time::Duration;
+use std::{future::IntoFuture, process::Stdio, time::Duration};
use anyhow::{bail, Context, Result};
-use axum::http::{header, Uri};
-use axum::response::{Html, IntoResponse, Response};
-use axum::routing::get;
-use axum::{extract::State, http::StatusCode, routing::post, Json, Router};
+use axum::{
+ extract::State,
+ http::{header, StatusCode, Uri},
+ response::{Html, IntoResponse, Response},
+ routing::{get, post},
+ Json, Router,
+};
+use interop_tests::{BlpopRequest, Report};
use redis::{AsyncCommands, Client};
use thirtyfour::prelude::*;
-use tokio::io::{AsyncBufReadExt, BufReader};
-use tokio::net::TcpListener;
-use tokio::process::Child;
-use tokio::sync::mpsc;
-use tower_http::cors::CorsLayer;
-use tower_http::trace::TraceLayer;
+use tokio::{
+ io::{AsyncBufReadExt, BufReader},
+ net::TcpListener,
+ process::Child,
+ sync::mpsc,
+};
+use tower_http::{cors::CorsLayer, trace::TraceLayer};
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
-use interop_tests::{BlpopRequest, Report};
-
mod config;
const BIND_ADDR: &str = "127.0.0.1:8080";
diff --git a/interop-tests/src/lib.rs b/interop-tests/src/lib.rs
index 0154bec51a4..a16dc4b8228 100644
--- a/interop-tests/src/lib.rs
+++ b/interop-tests/src/lib.rs
@@ -1,11 +1,14 @@
-use std::str::FromStr;
-use std::time::Duration;
+use std::{str::FromStr, time::Duration};
use anyhow::{bail, Context, Result};
use futures::{FutureExt, StreamExt};
-use libp2p::identity::Keypair;
-use libp2p::swarm::SwarmEvent;
-use libp2p::{identify, ping, swarm::NetworkBehaviour, Multiaddr};
+use libp2p::{
+ identify,
+ identity::Keypair,
+ ping,
+ swarm::{NetworkBehaviour, SwarmEvent},
+ Multiaddr,
+};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
diff --git a/libp2p/CHANGELOG.md b/libp2p/CHANGELOG.md
index 72a624786d4..91f1b5628f8 100644
--- a/libp2p/CHANGELOG.md
+++ b/libp2p/CHANGELOG.md
@@ -1,3 +1,29 @@
+## 0.55.0
+
+- Raise MSRV to 1.83.0.
+ See [PR 5650](https://github.com/libp2p/rust-libp2p/pull/5650).
+
+- Add `with_connection_timeout` on `SwarmBuilder` to allow configuration of the connection_timeout parameter.
+ See [PR 5575](https://github.com/libp2p/rust-libp2p/pull/5575).
+
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
+- Update default for idle-connection-timeout to 10s.
+ See [PR 4967](https://github.com/libp2p/rust-libp2p/pull/4967).
+
+- Expose swarm builder phase errors.
+ See [PR 5726](https://github.com/libp2p/rust-libp2p/pull/5726).
+
+- Deprecate `ConnectionHandler::{InboundOpenInfo, OutboundOpenInfo}` associated type.
+ Previously, users could tag pending sub streams with custom data and retrieve the data
+ after the substream has been negotiated.
+ But substreams themselves are completely interchangeable, users should instead track
+ additional data inside `ConnectionHandler` after negotiation.
+ See [PR 5242](https://github.com/libp2p/rust-libp2p/pull/5242).
+
+
+
## 0.54.1
- Update individual crates.
diff --git a/libp2p/Cargo.toml b/libp2p/Cargo.toml
index b1017f5958c..39d01a5c5c7 100644
--- a/libp2p/Cargo.toml
+++ b/libp2p/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p"
edition = "2021"
rust-version = { workspace = true }
description = "Peer-to-peer networking library"
-version = "0.54.1"
+version = "0.55.0"
authors = ["Parity Technologies "]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
@@ -94,7 +94,7 @@ bytes = "1"
either = "1.9.0"
futures = { workspace = true }
futures-timer = "3.0.2" # Explicit dependency to be used in `wasm-bindgen` feature
-getrandom = "0.2.3" # Explicit dependency to be used in `wasm-bindgen` feature
+getrandom = { workspace = true } # Explicit dependency to be used in `wasm-bindgen` feature
# TODO feature flag?
rw-stream-sink = { workspace = true }
@@ -122,7 +122,7 @@ libp2p-webtransport-websys = { workspace = true, optional = true }
libp2p-yamux = { workspace = true, optional = true }
multiaddr = { workspace = true }
pin-project = "1.0.0"
-thiserror = "1.0"
+thiserror = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
libp2p-dns = { workspace = true, optional = true }
@@ -137,12 +137,9 @@ libp2p-websocket = { workspace = true, optional = true }
[dev-dependencies]
async-std = { version = "1.6.2", features = ["attributes"] }
-async-trait = "0.1"
-clap = { version = "4.1.6", features = ["derive"] }
tokio = { workspace = true, features = [ "io-util", "io-std", "macros", "rt", "rt-multi-thread"] }
libp2p-mplex = { workspace = true }
-libp2p-noise = { workspace = true }
libp2p-tcp = { workspace = true, features = ["tokio"] }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
diff --git a/libp2p/src/bandwidth.rs b/libp2p/src/bandwidth.rs
index 8931c5c4166..ac668e26b3f 100644
--- a/libp2p/src/bandwidth.rs
+++ b/libp2p/src/bandwidth.rs
@@ -20,13 +20,6 @@
#![allow(deprecated)]
-use crate::core::muxing::{StreamMuxer, StreamMuxerEvent};
-
-use futures::{
- io::{IoSlice, IoSliceMut},
- prelude::*,
- ready,
-};
use std::{
convert::TryFrom as _,
io,
@@ -38,6 +31,14 @@ use std::{
task::{Context, Poll},
};
+use futures::{
+ io::{IoSlice, IoSliceMut},
+ prelude::*,
+ ready,
+};
+
+use crate::core::muxing::{StreamMuxer, StreamMuxerEvent};
+
/// Wraps around a [`StreamMuxer`] and counts the number of bytes that go through all the opened
/// streams.
#[derive(Clone)]
@@ -123,7 +124,7 @@ impl BandwidthSinks {
/// Returns the total number of bytes that have been downloaded on all the streams.
///
/// > **Note**: This method is by design subject to race conditions. The returned value should
- /// > only ever be used for statistics purposes.
+ /// > only ever be used for statistics purposes.
pub fn total_inbound(&self) -> u64 {
self.inbound.load(Ordering::Relaxed)
}
@@ -131,7 +132,7 @@ impl BandwidthSinks {
/// Returns the total number of bytes that have been uploaded on all the streams.
///
/// > **Note**: This method is by design subject to race conditions. The returned value should
- /// > only ever be used for statistics purposes.
+ /// > only ever be used for statistics purposes.
pub fn total_outbound(&self) -> u64 {
self.outbound.load(Ordering::Relaxed)
}
diff --git a/libp2p/src/builder.rs b/libp2p/src/builder.rs
index de003314cca..ae4d0b0d4e4 100644
--- a/libp2p/src/builder.rs
+++ b/libp2p/src/builder.rs
@@ -4,6 +4,10 @@ mod phase;
mod select_muxer;
mod select_security;
+#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
+pub use phase::WebsocketError;
+pub use phase::{BehaviourError, TransportError};
+
/// Build a [`Swarm`](libp2p_swarm::Swarm) by combining an identity, a set of
/// [`Transport`](libp2p_core::Transport)s and a
/// [`NetworkBehaviour`](libp2p_swarm::NetworkBehaviour).
@@ -33,31 +37,31 @@ mod select_security;
/// # relay: libp2p_relay::client::Behaviour,
/// # }
///
-/// let swarm = SwarmBuilder::with_new_identity()
-/// .with_tokio()
-/// .with_tcp(
-/// Default::default(),
-/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
-/// libp2p_yamux::Config::default,
-/// )?
-/// .with_quic()
-/// .with_other_transport(|_key| DummyTransport::<(PeerId, StreamMuxerBox)>::new())?
-/// .with_dns()?
-/// .with_websocket(
-/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
-/// libp2p_yamux::Config::default,
-/// )
-/// .await?
-/// .with_relay_client(
-/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
-/// libp2p_yamux::Config::default,
-/// )?
-/// .with_behaviour(|_key, relay| MyBehaviour { relay })?
-/// .with_swarm_config(|cfg| {
-/// // Edit cfg here.
-/// cfg
-/// })
-/// .build();
+/// let swarm = SwarmBuilder::with_new_identity()
+/// .with_tokio()
+/// .with_tcp(
+/// Default::default(),
+/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
+/// libp2p_yamux::Config::default,
+/// )?
+/// .with_quic()
+/// .with_other_transport(|_key| DummyTransport::<(PeerId, StreamMuxerBox)>::new())?
+/// .with_dns()?
+/// .with_websocket(
+/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
+/// libp2p_yamux::Config::default,
+/// )
+/// .await?
+/// .with_relay_client(
+/// (libp2p_tls::Config::new, libp2p_noise::Config::new),
+/// libp2p_yamux::Config::default,
+/// )?
+/// .with_behaviour(|_key, relay| MyBehaviour { relay })?
+/// .with_swarm_config(|cfg| {
+/// // Edit cfg here.
+/// cfg
+/// })
+/// .build();
/// #
/// # Ok(())
/// # }
@@ -70,11 +74,12 @@ pub struct SwarmBuilder {
#[cfg(test)]
mod tests {
- use crate::SwarmBuilder;
use libp2p_core::{muxing::StreamMuxerBox, transport::dummy::DummyTransport};
use libp2p_identity::PeerId;
use libp2p_swarm::NetworkBehaviour;
+ use crate::SwarmBuilder;
+
#[test]
#[cfg(all(
feature = "tokio",
diff --git a/libp2p/src/builder/phase.rs b/libp2p/src/builder/phase.rs
index c9679a46767..f8f1672f952 100644
--- a/libp2p/src/builder/phase.rs
+++ b/libp2p/src/builder/phase.rs
@@ -16,23 +16,26 @@ mod websocket;
use bandwidth_logging::*;
use bandwidth_metrics::*;
+pub use behaviour::BehaviourError;
use behaviour::*;
use build::*;
use dns::*;
+use libp2p_core::{muxing::StreamMuxerBox, Transport};
+use libp2p_identity::Keypair;
+pub use other_transport::TransportError;
use other_transport::*;
use provider::*;
use quic::*;
use relay::*;
use swarm::*;
use tcp::*;
+#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
+pub use websocket::WebsocketError;
use websocket::*;
-use super::select_muxer::SelectMuxerUpgrade;
-use super::select_security::SelectSecurityUpgrade;
-use super::SwarmBuilder;
-
-use libp2p_core::{muxing::StreamMuxerBox, Transport};
-use libp2p_identity::Keypair;
+use super::{
+ select_muxer::SelectMuxerUpgrade, select_security::SelectSecurityUpgrade, SwarmBuilder,
+};
#[allow(unreachable_pub)]
pub trait IntoSecurityUpgrade {
diff --git a/libp2p/src/builder/phase/bandwidth_logging.rs b/libp2p/src/builder/phase/bandwidth_logging.rs
index cee9498fcaa..f24df5f3df5 100644
--- a/libp2p/src/builder/phase/bandwidth_logging.rs
+++ b/libp2p/src/builder/phase/bandwidth_logging.rs
@@ -1,10 +1,9 @@
+use std::{marker::PhantomData, sync::Arc};
+
use super::*;
#[allow(deprecated)]
use crate::bandwidth::BandwidthSinks;
-use crate::transport_ext::TransportExt;
-use crate::SwarmBuilder;
-use std::marker::PhantomData;
-use std::sync::Arc;
+use crate::{transport_ext::TransportExt, SwarmBuilder};
pub struct BandwidthLoggingPhase {
pub(crate) relay_behaviour: R,
diff --git a/libp2p/src/builder/phase/bandwidth_metrics.rs b/libp2p/src/builder/phase/bandwidth_metrics.rs
index 52daa731ddd..ddd292c140e 100644
--- a/libp2p/src/builder/phase/bandwidth_metrics.rs
+++ b/libp2p/src/builder/phase/bandwidth_metrics.rs
@@ -1,10 +1,9 @@
+use std::{marker::PhantomData, sync::Arc};
+
use super::*;
#[allow(deprecated)]
use crate::bandwidth::BandwidthSinks;
-use crate::transport_ext::TransportExt;
-use crate::SwarmBuilder;
-use std::marker::PhantomData;
-use std::sync::Arc;
+use crate::{transport_ext::TransportExt, SwarmBuilder};
pub struct BandwidthMetricsPhase {
pub(crate) relay_behaviour: R,
diff --git a/libp2p/src/builder/phase/behaviour.rs b/libp2p/src/builder/phase/behaviour.rs
index 939db935c80..22f8c617051 100644
--- a/libp2p/src/builder/phase/behaviour.rs
+++ b/libp2p/src/builder/phase/behaviour.rs
@@ -1,8 +1,9 @@
+use std::{convert::Infallible, marker::PhantomData};
+
+use libp2p_swarm::NetworkBehaviour;
+
use super::*;
use crate::SwarmBuilder;
-use libp2p_swarm::NetworkBehaviour;
-use std::convert::Infallible;
-use std::marker::PhantomData;
pub struct BehaviourPhase {
pub(crate) relay_behaviour: R,
diff --git a/libp2p/src/builder/phase/build.rs b/libp2p/src/builder/phase/build.rs
index 80a83994eeb..d3138cb8b8d 100644
--- a/libp2p/src/builder/phase/build.rs
+++ b/libp2p/src/builder/phase/build.rs
@@ -1,28 +1,31 @@
+use std::time::Duration;
+
+use libp2p_core::{transport::timeout::TransportTimeout, Transport};
+use libp2p_swarm::Swarm;
+
#[allow(unused_imports)]
use super::*;
-
use crate::SwarmBuilder;
-use libp2p_core::Transport;
-use libp2p_swarm::Swarm;
pub struct BuildPhase {
pub(crate) behaviour: B,
pub(crate) transport: T,
pub(crate) swarm_config: libp2p_swarm::Config,
+ pub(crate) connection_timeout: Duration,
}
-const CONNECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
-
impl
SwarmBuilder>
{
+ /// Timeout of the [`TransportTimeout`] wrapping the transport.
+ pub fn with_connection_timeout(mut self, connection_timeout: Duration) -> Self {
+ self.phase.connection_timeout = connection_timeout;
+ self
+ }
+
pub fn build(self) -> Swarm {
Swarm::new(
- libp2p_core::transport::timeout::TransportTimeout::new(
- self.phase.transport,
- CONNECTION_TIMEOUT,
- )
- .boxed(),
+ TransportTimeout::new(self.phase.transport, self.phase.connection_timeout).boxed(),
self.phase.behaviour,
self.keypair.public().to_peer_id(),
self.phase.swarm_config,
diff --git a/libp2p/src/builder/phase/dns.rs b/libp2p/src/builder/phase/dns.rs
index 638064d58bb..83653836a34 100644
--- a/libp2p/src/builder/phase/dns.rs
+++ b/libp2p/src/builder/phase/dns.rs
@@ -1,6 +1,7 @@
+use std::marker::PhantomData;
+
use super::*;
use crate::SwarmBuilder;
-use std::marker::PhantomData;
pub struct DnsPhase {
pub(crate) transport: T,
diff --git a/libp2p/src/builder/phase/identity.rs b/libp2p/src/builder/phase/identity.rs
index ceb86819dc7..e2511267cd3 100644
--- a/libp2p/src/builder/phase/identity.rs
+++ b/libp2p/src/builder/phase/identity.rs
@@ -1,6 +1,7 @@
+use std::marker::PhantomData;
+
use super::*;
use crate::SwarmBuilder;
-use std::marker::PhantomData;
pub struct IdentityPhase {}
diff --git a/libp2p/src/builder/phase/other_transport.rs b/libp2p/src/builder/phase/other_transport.rs
index e04621b2e3f..c3b951c8c75 100644
--- a/libp2p/src/builder/phase/other_transport.rs
+++ b/libp2p/src/builder/phase/other_transport.rs
@@ -1,20 +1,19 @@
-use std::convert::Infallible;
-use std::marker::PhantomData;
-use std::sync::Arc;
+use std::{convert::Infallible, marker::PhantomData, sync::Arc};
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
-use libp2p_core::Transport;
+use libp2p_core::{
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade},
+ Transport,
+};
#[cfg(feature = "relay")]
use libp2p_core::{Negotiated, UpgradeInfo};
#[cfg(feature = "relay")]
use libp2p_identity::PeerId;
+use super::*;
#[allow(deprecated)]
use crate::bandwidth::BandwidthSinks;
use crate::SwarmBuilder;
-use super::*;
-
pub struct OtherTransportPhase {
pub(crate) transport: T,
}
diff --git a/libp2p/src/builder/phase/provider.rs b/libp2p/src/builder/phase/provider.rs
index 2a9154cda74..00a79e14a30 100644
--- a/libp2p/src/builder/phase/provider.rs
+++ b/libp2p/src/builder/phase/provider.rs
@@ -1,13 +1,15 @@
+use std::marker::PhantomData;
+
#[allow(unused_imports)]
use super::*;
use crate::SwarmBuilder;
-use std::marker::PhantomData;
/// Represents the phase where a provider is not yet specified.
-/// This is a marker type used in the type-state pattern to ensure compile-time checks of the builder's state.
+/// This is a marker type used in the type-state pattern to ensure compile-time checks of the
+/// builder's state.
pub enum NoProviderSpecified {}
-// Define enums for each of the possible runtime environments. These are used as markers in the type-state pattern,
-// allowing compile-time checks for the appropriate environment configuration.
+// Define enums for each of the possible runtime environments. These are used as markers in the
+// type-state pattern, allowing compile-time checks for the appropriate environment configuration.
#[cfg(all(not(target_arch = "wasm32"), feature = "async-std"))]
/// Represents the AsyncStd runtime environment.
@@ -26,7 +28,8 @@ pub struct ProviderPhase {}
impl SwarmBuilder {
/// Configures the SwarmBuilder to use the AsyncStd runtime.
- /// This method is only available when compiling for non-Wasm targets with the `async-std` feature enabled.
+ /// This method is only available when compiling for non-Wasm
+ /// targets with the `async-std` feature enabled.
#[cfg(all(not(target_arch = "wasm32"), feature = "async-std"))]
pub fn with_async_std(self) -> SwarmBuilder {
SwarmBuilder {
@@ -37,7 +40,8 @@ impl SwarmBuilder {
}
/// Configures the SwarmBuilder to use the Tokio runtime.
- /// This method is only available when compiling for non-Wasm targets with the `tokio` feature enabled
+ /// This method is only available when compiling for non-Wasm
+ /// targets with the `tokio` feature enabled
#[cfg(all(not(target_arch = "wasm32"), feature = "tokio"))]
pub fn with_tokio(self) -> SwarmBuilder {
SwarmBuilder {
diff --git a/libp2p/src/builder/phase/quic.rs b/libp2p/src/builder/phase/quic.rs
index e030e9493bb..1b6329c1095 100644
--- a/libp2p/src/builder/phase/quic.rs
+++ b/libp2p/src/builder/phase/quic.rs
@@ -1,5 +1,5 @@
-use super::*;
-use crate::SwarmBuilder;
+use std::{marker::PhantomData, sync::Arc};
+
#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
use libp2p_core::muxing::StreamMuxer;
use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
@@ -8,7 +8,9 @@ use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
all(not(target_arch = "wasm32"), feature = "websocket")
))]
use libp2p_core::{InboundUpgrade, Negotiated, OutboundUpgrade, UpgradeInfo};
-use std::{marker::PhantomData, sync::Arc};
+
+use super::*;
+use crate::SwarmBuilder;
pub struct QuicPhase {
pub(crate) transport: T,
diff --git a/libp2p/src/builder/phase/relay.rs b/libp2p/src/builder/phase/relay.rs
index f8305f9d246..33dbf1fb54c 100644
--- a/libp2p/src/builder/phase/relay.rs
+++ b/libp2p/src/builder/phase/relay.rs
@@ -10,9 +10,8 @@ use libp2p_core::{InboundUpgrade, Negotiated, OutboundUpgrade, StreamMuxer, Upgr
#[cfg(feature = "relay")]
use libp2p_identity::PeerId;
-use crate::SwarmBuilder;
-
use super::*;
+use crate::SwarmBuilder;
pub struct RelayPhase {
pub(crate) transport: T,
diff --git a/libp2p/src/builder/phase/swarm.rs b/libp2p/src/builder/phase/swarm.rs
index ee456ced927..e751ad672e4 100644
--- a/libp2p/src/builder/phase/swarm.rs
+++ b/libp2p/src/builder/phase/swarm.rs
@@ -1,6 +1,9 @@
#[allow(unused_imports)]
use super::*;
+#[allow(unused)] // used below but due to feature flag combinations, clippy gives an unnecessary warning.
+const DEFAULT_CONNECTION_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
+
#[allow(dead_code)]
pub struct SwarmPhase {
pub(crate) behaviour: B,
@@ -20,6 +23,7 @@ macro_rules! impl_with_swarm_config {
behaviour: self.phase.behaviour,
transport: self.phase.transport,
swarm_config: constructor($config),
+ connection_timeout: DEFAULT_CONNECTION_TIMEOUT,
},
keypair: self.keypair,
phantom: std::marker::PhantomData,
diff --git a/libp2p/src/builder/phase/tcp.rs b/libp2p/src/builder/phase/tcp.rs
index 4b7cf29b3d2..f38f52441e5 100644
--- a/libp2p/src/builder/phase/tcp.rs
+++ b/libp2p/src/builder/phase/tcp.rs
@@ -1,5 +1,5 @@
-use super::*;
-use crate::SwarmBuilder;
+use std::marker::PhantomData;
+
#[cfg(all(
not(target_arch = "wasm32"),
any(feature = "tcp", feature = "websocket")
@@ -14,7 +14,9 @@ use libp2p_core::Transport;
use libp2p_core::{
upgrade::InboundConnectionUpgrade, upgrade::OutboundConnectionUpgrade, Negotiated, UpgradeInfo,
};
-use std::marker::PhantomData;
+
+use super::*;
+use crate::SwarmBuilder;
pub struct TcpPhase {}
diff --git a/libp2p/src/builder/phase/websocket.rs b/libp2p/src/builder/phase/websocket.rs
index 68a85bb77b7..a23c6eca854 100644
--- a/libp2p/src/builder/phase/websocket.rs
+++ b/libp2p/src/builder/phase/websocket.rs
@@ -1,5 +1,5 @@
-use super::*;
-use crate::SwarmBuilder;
+use std::marker::PhantomData;
+
#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
use libp2p_core::muxing::{StreamMuxer, StreamMuxerBox};
use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
@@ -15,7 +15,9 @@ use libp2p_core::{InboundUpgrade, Negotiated, OutboundUpgrade, UpgradeInfo};
feature = "relay"
))]
use libp2p_identity::PeerId;
-use std::marker::PhantomData;
+
+use super::*;
+use crate::SwarmBuilder;
pub struct WebsocketPhase {
pub(crate) transport: T,
@@ -126,8 +128,8 @@ impl_websocket_builder!(
impl_websocket_builder!(
"tokio",
super::provider::Tokio,
- // Note this is an unnecessary await for Tokio Websocket (i.e. tokio dns) in order to be consistent
- // with above AsyncStd construction.
+ // Note this is an unnecessary await for Tokio Websocket (i.e. tokio dns) in order to be
+ // consistent with above AsyncStd construction.
futures::future::ready(libp2p_dns::tokio::Transport::system(
libp2p_tcp::tokio::Transport::new(libp2p_tcp::Config::default())
)),
diff --git a/libp2p/src/builder/select_muxer.rs b/libp2p/src/builder/select_muxer.rs
index c93ba9d9991..93ae0547269 100644
--- a/libp2p/src/builder/select_muxer.rs
+++ b/libp2p/src/builder/select_muxer.rs
@@ -20,12 +20,15 @@
#![allow(unreachable_pub)]
+use std::iter::{Chain, Map};
+
use either::Either;
use futures::future;
-use libp2p_core::either::EitherFuture;
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
-use libp2p_core::UpgradeInfo;
-use std::iter::{Chain, Map};
+use libp2p_core::{
+ either::EitherFuture,
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade},
+ UpgradeInfo,
+};
#[derive(Debug, Clone)]
pub struct SelectMuxerUpgrade(A, B);
diff --git a/libp2p/src/builder/select_security.rs b/libp2p/src/builder/select_security.rs
index d6c7f8c172f..1ed760feb1b 100644
--- a/libp2p/src/builder/select_security.rs
+++ b/libp2p/src/builder/select_security.rs
@@ -21,13 +21,15 @@
#![allow(unreachable_pub)]
+use std::iter::{Chain, Map};
+
use either::Either;
-use futures::future::MapOk;
-use futures::{future, TryFutureExt};
-use libp2p_core::either::EitherFuture;
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo};
+use futures::{future, future::MapOk, TryFutureExt};
+use libp2p_core::{
+ either::EitherFuture,
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo},
+};
use libp2p_identity::PeerId;
-use std::iter::{Chain, Map};
/// Upgrade that combines two upgrades into one. Supports all the protocols supported by either
/// sub-upgrade.
diff --git a/libp2p/src/lib.rs b/libp2p/src/lib.rs
index 58f911e9445..47e1142d0e9 100644
--- a/libp2p/src/lib.rs
+++ b/libp2p/src/lib.rs
@@ -34,11 +34,6 @@
pub use bytes;
pub use futures;
-#[doc(inline)]
-pub use libp2p_core::multihash;
-#[doc(inline)]
-pub use multiaddr;
-
#[doc(inline)]
pub use libp2p_allow_block_list as allow_block_list;
#[cfg(feature = "autonat")]
@@ -48,6 +43,8 @@ pub use libp2p_autonat as autonat;
pub use libp2p_connection_limits as connection_limits;
#[doc(inline)]
pub use libp2p_core as core;
+#[doc(inline)]
+pub use libp2p_core::multihash;
#[cfg(feature = "dcutr")]
#[doc(inline)]
pub use libp2p_dcutr as dcutr;
@@ -140,6 +137,8 @@ pub use libp2p_webtransport_websys as webtransport_websys;
#[cfg(feature = "yamux")]
#[doc(inline)]
pub use libp2p_yamux as yamux;
+#[doc(inline)]
+pub use multiaddr;
mod builder;
mod transport_ext;
@@ -149,15 +148,23 @@ pub mod bandwidth;
#[cfg(doc)]
pub mod tutorials;
-pub use self::builder::SwarmBuilder;
-pub use self::core::{
- transport::TransportError,
- upgrade::{InboundUpgrade, OutboundUpgrade},
- Transport,
-};
-pub use self::multiaddr::{multiaddr as build_multiaddr, Multiaddr};
-pub use self::swarm::Swarm;
-pub use self::transport_ext::TransportExt;
+#[cfg(all(not(target_arch = "wasm32"), feature = "websocket"))]
+pub use builder::WebsocketError as WebsocketBuilderError;
pub use libp2p_identity as identity;
pub use libp2p_identity::PeerId;
pub use libp2p_swarm::{Stream, StreamProtocol};
+
+pub use self::{
+ builder::{
+ BehaviourError as BehaviourBuilderError, SwarmBuilder,
+ TransportError as TransportBuilderError,
+ },
+ core::{
+ transport::TransportError,
+ upgrade::{InboundUpgrade, OutboundUpgrade},
+ Transport,
+ },
+ multiaddr::{multiaddr as build_multiaddr, Multiaddr},
+ swarm::Swarm,
+ transport_ext::TransportExt,
+};
diff --git a/libp2p/src/transport_ext.rs b/libp2p/src/transport_ext.rs
index 4f07484fc1f..0ed5b816903 100644
--- a/libp2p/src/transport_ext.rs
+++ b/libp2p/src/transport_ext.rs
@@ -20,15 +20,19 @@
//! Provides the `TransportExt` trait.
+use std::sync::Arc;
+
+use libp2p_identity::PeerId;
+
#[allow(deprecated)]
use crate::bandwidth::{BandwidthLogging, BandwidthSinks};
-use crate::core::{
- muxing::{StreamMuxer, StreamMuxerBox},
- transport::Boxed,
+use crate::{
+ core::{
+ muxing::{StreamMuxer, StreamMuxerBox},
+ transport::Boxed,
+ },
+ Transport,
};
-use crate::Transport;
-use libp2p_identity::PeerId;
-use std::sync::Arc;
/// Trait automatically implemented on all objects that implement `Transport`. Provides some
/// additional utilities.
@@ -42,23 +46,17 @@ pub trait TransportExt: Transport {
/// # Example
///
/// ```
- /// use libp2p_yamux as yamux;
+ /// use libp2p::{core::upgrade, identity, Transport, TransportExt};
/// use libp2p_noise as noise;
/// use libp2p_tcp as tcp;
- /// use libp2p::{
- /// core::upgrade,
- /// identity,
- /// TransportExt,
- /// Transport,
- /// };
+ /// use libp2p_yamux as yamux;
///
/// let id_keys = identity::Keypair::generate_ed25519();
///
/// let transport = tcp::tokio::Transport::new(tcp::Config::default().nodelay(true))
/// .upgrade(upgrade::Version::V1)
/// .authenticate(
- /// noise::Config::new(&id_keys)
- /// .expect("Signing libp2p-noise static DH keypair failed."),
+ /// noise::Config::new(&id_keys).expect("Signing libp2p-noise static DH keypair failed."),
/// )
/// .multiplex(yamux::Config::default())
/// .boxed();
diff --git a/libp2p/src/tutorials/hole_punching.rs b/libp2p/src/tutorials/hole_punching.rs
index 0963c0ca59e..06a4dad4037 100644
--- a/libp2p/src/tutorials/hole_punching.rs
+++ b/libp2p/src/tutorials/hole_punching.rs
@@ -57,8 +57,8 @@
//! cargo build --bin relay-server-example
//! ```
//!
-//! You can find the binary at `target/debug/relay-server-example`. In case you built it locally, copy
-//! it to your server.
+//! You can find the binary at `target/debug/relay-server-example`. In case you built it locally,
+//! copy it to your server.
//!
//! On your server, start the relay server binary:
//!
@@ -98,7 +98,8 @@
//!
//! ``` bash
//! $ libp2p-lookup direct --address /ip4/111.11.111.111/tcp/4001
-//! Lookup for peer with id PeerId("12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN") succeeded.
+//! Lookup for peer with id PeerId("12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN")
+//! succeeded.
//!
//! Protocol version: "/TODO/0.0.1"
//! Agent version: "rust-libp2p/0.36.0"
@@ -163,12 +164,18 @@
//! [`Multiaddr`](crate::Multiaddr).
//!
//! ``` ignore
-//! [2022-01-30T12:54:10Z INFO client] Established connection to PeerId("12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X") via Dialer { address: "/ip4/$RELAY_PEER_ID/tcp/4001/p2p/12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN/p2p-circuit/p2p/12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X", role_override: Dialer }
+//! [2022-01-30T12:54:10Z INFO client] Established connection to
+//! PeerId("12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X") via Dialer { address:
+//! "/ip4/$RELAY_PEER_ID/tcp/4001/p2p/12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN/
+//! p2p-circuit/p2p/12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X",
+//! role_override: Dialer }
//! ```
//!
-//! 2. The direct connection upgrade, also known as hole punch, succeeding.
-//! Reported by [`dcutr`](crate::dcutr) through [`Event`](crate::dcutr::Event) containing [`Result::Ok`] with the [`ConnectionId`](libp2p_swarm::ConnectionId) of the new direct connection.
+//! 2. The direct connection upgrade, also known as hole punch, succeeding. Reported by
+//! [`dcutr`](crate::dcutr) through [`Event`](crate::dcutr::Event) containing [`Result::Ok`] with
+//! the [`ConnectionId`](libp2p_swarm::ConnectionId) of the new direct connection.
//!
//! ``` ignore
-//! [2022-01-30T12:54:11Z INFO client] Event { remote_peer_id: PeerId("12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X"), result: Ok(2) }
+//! [2022-01-30T12:54:11Z INFO client] Event { remote_peer_id:
+//! PeerId("12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X"), result: Ok(2) }
//! ```
diff --git a/libp2p/src/tutorials/ping.rs b/libp2p/src/tutorials/ping.rs
index 31bf5ba3a14..ebaea29f33a 100644
--- a/libp2p/src/tutorials/ping.rs
+++ b/libp2p/src/tutorials/ping.rs
@@ -72,6 +72,7 @@
//!
//! ```rust
//! use std::error::Error;
+//!
//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
@@ -98,8 +99,9 @@
//!
//! ```rust
//! use std::error::Error;
-//! use tracing_subscriber::EnvFilter;
+//!
//! use libp2p::{noise, tcp, yamux};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -139,12 +141,14 @@
//! The two traits [`Transport`] and [`NetworkBehaviour`] allow us to cleanly
//! separate _how_ to send bytes from _what_ bytes and to _whom_ to send.
//!
-//! With the above in mind, let's extend our example, creating a [`ping::Behaviour`](crate::ping::Behaviour) at the end:
+//! With the above in mind, let's extend our example, creating a
+//! [`ping::Behaviour`](crate::ping::Behaviour) at the end:
//!
//! ```rust
//! use std::error::Error;
-//! use tracing_subscriber::EnvFilter;
+//!
//! use libp2p::{noise, ping, tcp, yamux};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -174,8 +178,9 @@
//!
//! ```rust
//! use std::error::Error;
-//! use tracing_subscriber::EnvFilter;
+//!
//! use libp2p::{noise, ping, tcp, yamux};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -209,8 +214,9 @@
//!
//! ```rust
//! use std::{error::Error, time::Duration};
-//! use tracing_subscriber::EnvFilter;
+//!
//! use libp2p::{noise, ping, tcp, yamux};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -226,7 +232,6 @@
//! yamux::Config::default,
//! )?
//! .with_behaviour(|_| ping::Behaviour::default())?
-//! .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
//! .build();
//!
//! Ok(())
@@ -261,8 +266,9 @@
//!
//! ```rust
//! use std::{error::Error, time::Duration};
-//! use tracing_subscriber::EnvFilter;
+//!
//! use libp2p::{noise, ping, tcp, yamux, Multiaddr};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -278,7 +284,6 @@
//! yamux::Config::default,
//! )?
//! .with_behaviour(|_| ping::Behaviour::default())?
-//! .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
//! .build();
//!
//! // Tell the swarm to listen on all interfaces and a random, OS-assigned
@@ -305,9 +310,10 @@
//!
//! ```no_run
//! use std::{error::Error, time::Duration};
-//! use tracing_subscriber::EnvFilter;
-//! use libp2p::{noise, ping, tcp, yamux, Multiaddr, swarm::SwarmEvent};
+//!
//! use futures::prelude::*;
+//! use libp2p::{noise, ping, swarm::SwarmEvent, tcp, yamux, Multiaddr};
+//! use tracing_subscriber::EnvFilter;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box> {
@@ -323,7 +329,6 @@
//! yamux::Config::default,
//! )?
//! .with_behaviour(|_| ping::Behaviour::default())?
-//! .with_swarm_config(|cfg| cfg.with_idle_connection_timeout(Duration::from_secs(u64::MAX)))
//! .build();
//!
//! // Tell the swarm to listen on all interfaces and a random, OS-assigned
diff --git a/misc/allow-block-list/CHANGELOG.md b/misc/allow-block-list/CHANGELOG.md
index 3cda0603ee4..be7619269d0 100644
--- a/misc/allow-block-list/CHANGELOG.md
+++ b/misc/allow-block-list/CHANGELOG.md
@@ -1,8 +1,12 @@
-## 0.4.1
+## 0.5.0
- Add getters & setters for the allowed/blocked peers.
Return a `bool` for every "insert/remove" function, informing if a change was performed.
See [PR 5572](https://github.com/libp2p/rust-libp2p/pull/5572).
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
+
## 0.4.0
diff --git a/misc/allow-block-list/Cargo.toml b/misc/allow-block-list/Cargo.toml
index 1ff0ccff906..859380a68a5 100644
--- a/misc/allow-block-list/Cargo.toml
+++ b/misc/allow-block-list/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-allow-block-list"
edition = "2021"
rust-version = { workspace = true }
description = "Allow/block list connection management for libp2p."
-version = "0.4.1"
+version = "0.5.0"
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
@@ -13,7 +13,6 @@ categories = ["network-programming", "asynchronous"]
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }
libp2p-identity = { workspace = true, features = ["peerid"] }
-void = "1"
[dev-dependencies]
async-std = { version = "1.12.0", features = ["attributes"] }
diff --git a/misc/allow-block-list/src/lib.rs b/misc/allow-block-list/src/lib.rs
index 7646638a651..ea0d56b5a67 100644
--- a/misc/allow-block-list/src/lib.rs
+++ b/misc/allow-block-list/src/lib.rs
@@ -31,12 +31,12 @@
//! #[derive(NetworkBehaviour)]
//! # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
//! struct MyBehaviour {
-//! allowed_peers: allow_block_list::Behaviour,
+//! allowed_peers: allow_block_list::Behaviour,
//! }
//!
//! # fn main() {
//! let behaviour = MyBehaviour {
-//! allowed_peers: allow_block_list::Behaviour::default()
+//! allowed_peers: allow_block_list::Behaviour::default(),
//! };
//! # }
//! ```
@@ -51,27 +51,29 @@
//! #[derive(NetworkBehaviour)]
//! # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
//! struct MyBehaviour {
-//! blocked_peers: allow_block_list::Behaviour,
+//! blocked_peers: allow_block_list::Behaviour,
//! }
//!
//! # fn main() {
//! let behaviour = MyBehaviour {
-//! blocked_peers: allow_block_list::Behaviour::default()
+//! blocked_peers: allow_block_list::Behaviour::default(),
//! };
//! # }
//! ```
-use libp2p_core::transport::PortUse;
-use libp2p_core::{Endpoint, Multiaddr};
+use std::{
+ collections::{HashSet, VecDeque},
+ convert::Infallible,
+ fmt,
+ task::{Context, Poll, Waker},
+};
+
+use libp2p_core::{transport::PortUse, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_swarm::{
dummy, CloseConnection, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler,
THandlerInEvent, THandlerOutEvent, ToSwarm,
};
-use std::collections::{HashSet, VecDeque};
-use std::fmt;
-use std::task::{Context, Poll, Waker};
-use void::Void;
/// A [`NetworkBehaviour`] that can act as an allow or block list.
#[derive(Default, Debug)]
@@ -101,7 +103,8 @@ impl Behaviour {
/// Allow connections to the given peer.
///
- /// Returns whether the peer was newly inserted. Does nothing if the peer was already present in the set.
+ /// Returns whether the peer was newly inserted. Does nothing if the peer
+ /// was already present in the set.
pub fn allow_peer(&mut self, peer: PeerId) -> bool {
let inserted = self.state.peers.insert(peer);
if inserted {
@@ -116,7 +119,8 @@ impl Behaviour {
///
/// All active connections to this peer will be closed immediately.
///
- /// Returns whether the peer was present in the set. Does nothing if the peer was not present in the set.
+ /// Returns whether the peer was present in the set. Does nothing if the peer
+ /// was not present in the set.
pub fn disallow_peer(&mut self, peer: PeerId) -> bool {
let removed = self.state.peers.remove(&peer);
if removed {
@@ -139,7 +143,8 @@ impl Behaviour {
///
/// All active connections to this peer will be closed immediately.
///
- /// Returns whether the peer was newly inserted. Does nothing if the peer was already present in the set.
+ /// Returns whether the peer was newly inserted. Does nothing if the peer was already present in
+ /// the set.
pub fn block_peer(&mut self, peer: PeerId) -> bool {
let inserted = self.state.peers.insert(peer);
if inserted {
@@ -153,7 +158,8 @@ impl Behaviour {
/// Unblock connections to a given peer.
///
- /// Returns whether the peer was present in the set. Does nothing if the peer was not present in the set.
+ /// Returns whether the peer was present in the set. Does nothing if the peer
+ /// was not present in the set.
pub fn unblock_peer(&mut self, peer: PeerId) -> bool {
let removed = self.state.peers.remove(&peer);
if removed {
@@ -222,7 +228,7 @@ where
S: Enforce,
{
type ConnectionHandler = dummy::ConnectionHandler;
- type ToSwarm = Void;
+ type ToSwarm = Infallible;
fn handle_established_inbound_connection(
&mut self,
@@ -271,7 +277,9 @@ where
_: ConnectionId,
event: THandlerOutEvent,
) {
- void::unreachable(event)
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ libp2p_core::util::unreachable(event)
}
fn poll(
@@ -292,10 +300,11 @@ where
#[cfg(test)]
mod tests {
- use super::*;
use libp2p_swarm::{dial_opts::DialOpts, DialError, ListenError, Swarm, SwarmEvent};
use libp2p_swarm_test::SwarmExt;
+ use super::*;
+
#[async_std::test]
async fn cannot_dial_blocked_peer() {
let mut dialer = Swarm::new_ephemeral(|_| Behaviour::::default());
diff --git a/misc/connection-limits/CHANGELOG.md b/misc/connection-limits/CHANGELOG.md
index db88e99ffa7..a84ff4deb32 100644
--- a/misc/connection-limits/CHANGELOG.md
+++ b/misc/connection-limits/CHANGELOG.md
@@ -1,3 +1,10 @@
+## 0.5.0
+
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
+
+
## 0.4.0
diff --git a/misc/connection-limits/Cargo.toml b/misc/connection-limits/Cargo.toml
index 56fe97f984b..21e53ff385c 100644
--- a/misc/connection-limits/Cargo.toml
+++ b/misc/connection-limits/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-connection-limits"
edition = "2021"
rust-version = { workspace = true }
description = "Connection limits for libp2p."
-version = "0.4.0"
+version = "0.5.0"
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
@@ -13,7 +13,6 @@ categories = ["network-programming", "asynchronous"]
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }
libp2p-identity = { workspace = true, features = ["peerid"] }
-void = "1"
[dev-dependencies]
async-std = { version = "1.12.0", features = ["attributes"] }
diff --git a/misc/connection-limits/src/lib.rs b/misc/connection-limits/src/lib.rs
index b02e52f25a1..c8df5be5653 100644
--- a/misc/connection-limits/src/lib.rs
+++ b/misc/connection-limits/src/lib.rs
@@ -18,6 +18,13 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{
+ collections::{HashMap, HashSet},
+ convert::Infallible,
+ fmt,
+ task::{Context, Poll},
+};
+
use libp2p_core::{transport::PortUse, ConnectedPoint, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_swarm::{
@@ -25,22 +32,22 @@ use libp2p_swarm::{
dummy, ConnectionClosed, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler,
THandlerInEvent, THandlerOutEvent, ToSwarm,
};
-use std::collections::{HashMap, HashSet};
-use std::fmt;
-use std::task::{Context, Poll};
-use void::Void;
/// A [`NetworkBehaviour`] that enforces a set of [`ConnectionLimits`].
///
-/// For these limits to take effect, this needs to be composed into the behaviour tree of your application.
+/// For these limits to take effect, this needs to be composed
+/// into the behaviour tree of your application.
///
-/// If a connection is denied due to a limit, either a [`SwarmEvent::IncomingConnectionError`](libp2p_swarm::SwarmEvent::IncomingConnectionError)
-/// or [`SwarmEvent::OutgoingConnectionError`](libp2p_swarm::SwarmEvent::OutgoingConnectionError) will be emitted.
-/// The [`ListenError::Denied`](libp2p_swarm::ListenError::Denied) and respectively the [`DialError::Denied`](libp2p_swarm::DialError::Denied) variant
-/// contain a [`ConnectionDenied`] type that can be downcast to [`Exceeded`] error if (and only if) **this**
-/// behaviour denied the connection.
+/// If a connection is denied due to a limit, either a
+/// [`SwarmEvent::IncomingConnectionError`](libp2p_swarm::SwarmEvent::IncomingConnectionError)
+/// or [`SwarmEvent::OutgoingConnectionError`](libp2p_swarm::SwarmEvent::OutgoingConnectionError)
+/// will be emitted. The [`ListenError::Denied`](libp2p_swarm::ListenError::Denied) and respectively
+/// the [`DialError::Denied`](libp2p_swarm::DialError::Denied) variant
+/// contain a [`ConnectionDenied`] type that can be downcast to [`Exceeded`] error if (and only if)
+/// **this** behaviour denied the connection.
///
-/// If you employ multiple [`NetworkBehaviour`]s that manage connections, it may also be a different error.
+/// If you employ multiple [`NetworkBehaviour`]s that manage connections,
+/// it may also be a different error.
///
/// # Example
///
@@ -53,9 +60,9 @@ use void::Void;
/// #[derive(NetworkBehaviour)]
/// # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
/// struct MyBehaviour {
-/// identify: identify::Behaviour,
-/// ping: ping::Behaviour,
-/// limits: connection_limits::Behaviour
+/// identify: identify::Behaviour,
+/// ping: ping::Behaviour,
+/// limits: connection_limits::Behaviour,
/// }
/// ```
pub struct Behaviour {
@@ -203,7 +210,7 @@ impl ConnectionLimits {
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = dummy::ConnectionHandler;
- type ToSwarm = Void;
+ type ToSwarm = Infallible;
fn handle_pending_inbound_connection(
&mut self,
@@ -355,7 +362,9 @@ impl NetworkBehaviour for Behaviour {
_: ConnectionId,
event: THandlerOutEvent,
) {
- void::unreachable(event)
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ libp2p_core::util::unreachable(event)
}
fn poll(&mut self, _: &mut Context<'_>) -> Poll>> {
@@ -365,14 +374,16 @@ impl NetworkBehaviour for Behaviour {
#[cfg(test)]
mod tests {
- use super::*;
use libp2p_swarm::{
- behaviour::toggle::Toggle, dial_opts::DialOpts, dial_opts::PeerCondition, DialError,
- ListenError, Swarm, SwarmEvent,
+ behaviour::toggle::Toggle,
+ dial_opts::{DialOpts, PeerCondition},
+ DialError, ListenError, Swarm, SwarmEvent,
};
use libp2p_swarm_test::SwarmExt;
use quickcheck::*;
+ use super::*;
+
#[test]
fn max_outgoing() {
use rand::Rng;
@@ -549,7 +560,7 @@ mod tests {
impl NetworkBehaviour for ConnectionDenier {
type ConnectionHandler = dummy::ConnectionHandler;
- type ToSwarm = Void;
+ type ToSwarm = Infallible;
fn handle_established_inbound_connection(
&mut self,
@@ -586,7 +597,9 @@ mod tests {
_connection_id: ConnectionId,
event: THandlerOutEvent,
) {
- void::unreachable(event)
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ libp2p_core::util::unreachable(event)
}
fn poll(
diff --git a/misc/keygen/Cargo.toml b/misc/keygen/Cargo.toml
index 003993a512c..c5e96553a5c 100644
--- a/misc/keygen/Cargo.toml
+++ b/misc/keygen/Cargo.toml
@@ -17,7 +17,6 @@ clap = { version = "4.5.6", features = ["derive"] }
zeroize = "1"
serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"
-libp2p-core = { workspace = true }
base64 = "0.22.1"
libp2p-identity = { workspace = true }
diff --git a/misc/keygen/src/config.rs b/misc/keygen/src/config.rs
index e6c563b3c32..7d46b1849bd 100644
--- a/misc/keygen/src/config.rs
+++ b/misc/keygen/src/config.rs
@@ -1,10 +1,8 @@
+use std::{error::Error, path::Path};
+
use base64::prelude::*;
+use libp2p_identity::{Keypair, PeerId};
use serde::{Deserialize, Serialize};
-use std::error::Error;
-use std::path::Path;
-
-use libp2p_identity::Keypair;
-use libp2p_identity::PeerId;
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
diff --git a/misc/keygen/src/main.rs b/misc/keygen/src/main.rs
index 64d98005369..4c4d3bfbf66 100644
--- a/misc/keygen/src/main.rs
+++ b/misc/keygen/src/main.rs
@@ -1,9 +1,12 @@
+use std::{
+ error::Error,
+ path::PathBuf,
+ str::{self, FromStr},
+ sync::mpsc,
+ thread,
+};
+
use base64::prelude::*;
-use std::error::Error;
-use std::path::PathBuf;
-use std::str::{self, FromStr};
-use std::sync::mpsc;
-use std::thread;
mod config;
diff --git a/misc/memory-connection-limits/CHANGELOG.md b/misc/memory-connection-limits/CHANGELOG.md
index 9e580c5a1d2..ed16fa37eb3 100644
--- a/misc/memory-connection-limits/CHANGELOG.md
+++ b/misc/memory-connection-limits/CHANGELOG.md
@@ -1,3 +1,10 @@
+## 0.4.0
+
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
+
+
## 0.3.0
diff --git a/misc/memory-connection-limits/Cargo.toml b/misc/memory-connection-limits/Cargo.toml
index f56ed33d5ad..3a4dd469ddf 100644
--- a/misc/memory-connection-limits/Cargo.toml
+++ b/misc/memory-connection-limits/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-memory-connection-limits"
edition = "2021"
rust-version = { workspace = true }
description = "Memory usage based connection limits for libp2p."
-version = "0.3.0"
+version = "0.4.0"
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
@@ -14,16 +14,13 @@ memory-stats = { version = "1", features = ["always_use_statm"] }
libp2p-core = { workspace = true }
libp2p-swarm = { workspace = true }
libp2p-identity = { workspace = true, features = ["peerid"] }
-sysinfo = "0.30"
+sysinfo = "0.33"
tracing = { workspace = true }
-void = "1"
[dev-dependencies]
-async-std = { version = "1.12.0", features = ["attributes"] }
libp2p-identify = { workspace = true }
libp2p-swarm-derive = { path = "../../swarm-derive" }
libp2p-swarm-test = { path = "../../swarm-test" }
-rand = "0.8.5"
[lints]
workspace = true
diff --git a/misc/memory-connection-limits/src/lib.rs b/misc/memory-connection-limits/src/lib.rs
index 7b5803a61aa..28fa5598481 100644
--- a/misc/memory-connection-limits/src/lib.rs
+++ b/misc/memory-connection-limits/src/lib.rs
@@ -18,35 +18,40 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{
+ convert::Infallible,
+ fmt,
+ task::{Context, Poll},
+ time::{Duration, Instant},
+};
+
use libp2p_core::{transport::PortUse, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_swarm::{
dummy, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent,
THandlerOutEvent, ToSwarm,
};
-use void::Void;
-
-use std::{
- fmt,
- task::{Context, Poll},
- time::{Duration, Instant},
-};
use sysinfo::MemoryRefreshKind;
/// A [`NetworkBehaviour`] that enforces a set of memory usage based limits.
///
-/// For these limits to take effect, this needs to be composed into the behaviour tree of your application.
+/// For these limits to take effect, this needs to be composed
+/// into the behaviour tree of your application.
///
-/// If a connection is denied due to a limit, either a [`SwarmEvent::IncomingConnectionError`](libp2p_swarm::SwarmEvent::IncomingConnectionError)
-/// or [`SwarmEvent::OutgoingConnectionError`](libp2p_swarm::SwarmEvent::OutgoingConnectionError) will be emitted.
-/// The [`ListenError::Denied`](libp2p_swarm::ListenError::Denied) and respectively the [`DialError::Denied`](libp2p_swarm::DialError::Denied) variant
-/// contain a [`ConnectionDenied`] type that can be downcast to [`MemoryUsageLimitExceeded`] error if (and only if) **this**
-/// behaviour denied the connection.
+/// If a connection is denied due to a limit, either a
+/// [`SwarmEvent::IncomingConnectionError`](libp2p_swarm::SwarmEvent::IncomingConnectionError)
+/// or [`SwarmEvent::OutgoingConnectionError`](libp2p_swarm::SwarmEvent::OutgoingConnectionError)
+/// will be emitted. The [`ListenError::Denied`](libp2p_swarm::ListenError::Denied) and respectively
+/// the [`DialError::Denied`](libp2p_swarm::DialError::Denied) variant
+/// contain a [`ConnectionDenied`] type that can be downcast to [`MemoryUsageLimitExceeded`] error
+/// if (and only if) **this** behaviour denied the connection.
///
-/// If you employ multiple [`NetworkBehaviour`]s that manage connections, it may also be a different error.
+/// If you employ multiple [`NetworkBehaviour`]s that manage connections,
+/// it may also be a different error.
///
/// [Behaviour::with_max_bytes] and [Behaviour::with_max_percentage] are mutually exclusive.
-/// If you need to employ both of them, compose two instances of [Behaviour] into your custom behaviour.
+/// If you need to employ both of them,
+/// compose two instances of [Behaviour] into your custom behaviour.
///
/// # Example
///
@@ -58,8 +63,8 @@ use sysinfo::MemoryRefreshKind;
/// #[derive(NetworkBehaviour)]
/// # #[behaviour(prelude = "libp2p_swarm::derive_prelude")]
/// struct MyBehaviour {
-/// identify: identify::Behaviour,
-/// limits: memory_connection_limits::Behaviour
+/// identify: identify::Behaviour,
+/// limits: memory_connection_limits::Behaviour,
/// }
/// ```
pub struct Behaviour {
@@ -68,7 +73,8 @@ pub struct Behaviour {
last_refreshed: Instant,
}
-/// The maximum duration for which the retrieved memory-stats of the process are allowed to be stale.
+/// The maximum duration for which the retrieved memory-stats
+/// of the process are allowed to be stale.
///
/// Once exceeded, we will retrieve new stats.
const MAX_STALE_DURATION: Duration = Duration::from_millis(100);
@@ -94,7 +100,7 @@ impl Behaviour {
use sysinfo::{RefreshKind, System};
let system_memory_bytes = System::new_with_specifics(
- RefreshKind::new().with_memory(MemoryRefreshKind::new().with_ram()),
+ RefreshKind::default().with_memory(MemoryRefreshKind::default().with_ram()),
)
.total_memory();
@@ -139,7 +145,7 @@ impl Behaviour {
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = dummy::ConnectionHandler;
- type ToSwarm = Void;
+ type ToSwarm = Infallible;
fn handle_pending_inbound_connection(
&mut self,
@@ -190,7 +196,9 @@ impl NetworkBehaviour for Behaviour {
_: ConnectionId,
event: THandlerOutEvent,
) {
- void::unreachable(event)
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ libp2p_core::util::unreachable(event)
}
fn poll(&mut self, _: &mut Context<'_>) -> Poll>> {
diff --git a/misc/memory-connection-limits/tests/max_bytes.rs b/misc/memory-connection-limits/tests/max_bytes.rs
index 7f89e2c7a9a..e82ad67d076 100644
--- a/misc/memory-connection-limits/tests/max_bytes.rs
+++ b/misc/memory-connection-limits/tests/max_bytes.rs
@@ -20,14 +20,14 @@
mod util;
+use std::time::Duration;
+
use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use libp2p_memory_connection_limits::*;
-use std::time::Duration;
-use util::*;
-
use libp2p_swarm::{dial_opts::DialOpts, DialError, Swarm};
use libp2p_swarm_test::SwarmExt;
+use util::*;
#[test]
fn max_bytes() {
@@ -69,7 +69,8 @@ fn max_bytes() {
.expect("Unexpected connection limit.");
}
- std::thread::sleep(Duration::from_millis(100)); // Memory stats are only updated every 100ms internally, ensure they are up-to-date when we try to exceed it.
+ std::thread::sleep(Duration::from_millis(100)); // Memory stats are only updated every 100ms internally, ensure they are up-to-date when we try
+ // to exceed it.
match network
.dial(
diff --git a/misc/memory-connection-limits/tests/max_percentage.rs b/misc/memory-connection-limits/tests/max_percentage.rs
index bfb1b504af5..bdadad437b8 100644
--- a/misc/memory-connection-limits/tests/max_percentage.rs
+++ b/misc/memory-connection-limits/tests/max_percentage.rs
@@ -20,24 +20,24 @@
mod util;
+use std::time::Duration;
+
use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use libp2p_memory_connection_limits::*;
-use std::time::Duration;
-use sysinfo::{MemoryRefreshKind, RefreshKind};
-use util::*;
-
use libp2p_swarm::{
dial_opts::{DialOpts, PeerCondition},
DialError, Swarm,
};
use libp2p_swarm_test::SwarmExt;
+use sysinfo::{MemoryRefreshKind, RefreshKind};
+use util::*;
#[test]
fn max_percentage() {
const CONNECTION_LIMIT: usize = 20;
let system_info = sysinfo::System::new_with_specifics(
- RefreshKind::new().with_memory(MemoryRefreshKind::new().with_ram()),
+ RefreshKind::default().with_memory(MemoryRefreshKind::default().with_ram()),
);
let mut network = Swarm::new_ephemeral(|_| TestBehaviour {
@@ -76,7 +76,9 @@ fn max_percentage() {
.expect("Unexpected connection limit.");
}
- std::thread::sleep(Duration::from_millis(100)); // Memory stats are only updated every 100ms internally, ensure they are up-to-date when we try to exceed it.
+ // Memory stats are only updated every 100ms internally,
+ // ensure they are up-to-date when we try to exceed it.
+ std::thread::sleep(Duration::from_millis(100));
match network
.dial(
diff --git a/misc/memory-connection-limits/tests/util/mod.rs b/misc/memory-connection-limits/tests/util/mod.rs
index d18aa78fd22..205f4d13bc4 100644
--- a/misc/memory-connection-limits/tests/util/mod.rs
+++ b/misc/memory-connection-limits/tests/util/mod.rs
@@ -18,7 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use std::task::{Context, Poll};
+use std::{
+ convert::Infallible,
+ task::{Context, Poll},
+};
use libp2p_core::{transport::PortUse, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
@@ -26,7 +29,6 @@ use libp2p_swarm::{
dummy, ConnectionDenied, ConnectionId, FromSwarm, NetworkBehaviour, THandler, THandlerInEvent,
THandlerOutEvent, ToSwarm,
};
-use void::Void;
#[derive(libp2p_swarm_derive::NetworkBehaviour)]
#[behaviour(prelude = "libp2p_swarm::derive_prelude")]
@@ -62,7 +64,7 @@ impl NetworkBehaviour
for ConsumeMemoryBehaviour
{
type ConnectionHandler = dummy::ConnectionHandler;
- type ToSwarm = Void;
+ type ToSwarm = Infallible;
fn handle_pending_inbound_connection(
&mut self,
@@ -116,7 +118,9 @@ impl NetworkBehaviour
_: ConnectionId,
event: THandlerOutEvent,
) {
- void::unreachable(event)
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ libp2p_core::util::unreachable(event)
}
fn poll(&mut self, _: &mut Context<'_>) -> Poll>> {
diff --git a/misc/metrics/CHANGELOG.md b/misc/metrics/CHANGELOG.md
index bd109c42811..fa57d50fa7a 100644
--- a/misc/metrics/CHANGELOG.md
+++ b/misc/metrics/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 0.16.0
+
+
+
## 0.15.0
- Use `web-time` instead of `instant`.
See [PR 5347](https://github.com/libp2p/rust-libp2p/pull/5347).
diff --git a/misc/metrics/Cargo.toml b/misc/metrics/Cargo.toml
index 0b7a3c93b2f..97cc581c671 100644
--- a/misc/metrics/Cargo.toml
+++ b/misc/metrics/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-metrics"
edition = "2021"
rust-version = { workspace = true }
description = "Metrics for libp2p"
-version = "0.15.0"
+version = "0.16.0"
authors = ["Max Inden "]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
diff --git a/misc/metrics/src/bandwidth.rs b/misc/metrics/src/bandwidth.rs
index 8a0f54e5b65..b6308ed1b51 100644
--- a/misc/metrics/src/bandwidth.rs
+++ b/misc/metrics/src/bandwidth.rs
@@ -1,4 +1,10 @@
-use crate::protocol_stack;
+use std::{
+ convert::TryFrom as _,
+ io,
+ pin::Pin,
+ task::{Context, Poll},
+};
+
use futures::{
future::{MapOk, TryFutureExt},
io::{IoSlice, IoSliceMut},
@@ -16,12 +22,8 @@ use prometheus_client::{
metrics::{counter::Counter, family::Family},
registry::{Registry, Unit},
};
-use std::{
- convert::TryFrom as _,
- io,
- pin::Pin,
- task::{Context, Poll},
-};
+
+use crate::protocol_stack;
#[derive(Debug, Clone)]
#[pin_project::pin_project]
diff --git a/misc/metrics/src/dcutr.rs b/misc/metrics/src/dcutr.rs
index 3e60dca2cab..6a0f27394e9 100644
--- a/misc/metrics/src/dcutr.rs
+++ b/misc/metrics/src/dcutr.rs
@@ -18,10 +18,11 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::family::Family;
-use prometheus_client::registry::Registry;
+use prometheus_client::{
+ encoding::{EncodeLabelSet, EncodeLabelValue},
+ metrics::{counter::Counter, family::Family},
+ registry::Registry,
+};
pub(crate) struct Metrics {
events: Family,
diff --git a/misc/metrics/src/gossipsub.rs b/misc/metrics/src/gossipsub.rs
index 2d90b92fbc6..b3e2e11f0b0 100644
--- a/misc/metrics/src/gossipsub.rs
+++ b/misc/metrics/src/gossipsub.rs
@@ -18,8 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::registry::Registry;
+use prometheus_client::{metrics::counter::Counter, registry::Registry};
pub(crate) struct Metrics {
messages: Counter,
diff --git a/misc/metrics/src/identify.rs b/misc/metrics/src/identify.rs
index 03ac3f9634e..b16c6a56ccf 100644
--- a/misc/metrics/src/identify.rs
+++ b/misc/metrics/src/identify.rs
@@ -18,17 +18,21 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::protocol_stack;
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
+
use libp2p_identity::PeerId;
use libp2p_swarm::StreamProtocol;
-use prometheus_client::collector::Collector;
-use prometheus_client::encoding::{DescriptorEncoder, EncodeMetric};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::gauge::ConstGauge;
-use prometheus_client::metrics::MetricType;
-use prometheus_client::registry::Registry;
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
+use prometheus_client::{
+ collector::Collector,
+ encoding::{DescriptorEncoder, EncodeMetric},
+ metrics::{counter::Counter, gauge::ConstGauge, MetricType},
+ registry::Registry,
+};
+
+use crate::protocol_stack;
const ALLOWED_PROTOCOLS: &[StreamProtocol] = &[
#[cfg(feature = "dcutr")]
diff --git a/misc/metrics/src/kad.rs b/misc/metrics/src/kad.rs
index bd5a6526737..0a2a8038511 100644
--- a/misc/metrics/src/kad.rs
+++ b/misc/metrics/src/kad.rs
@@ -18,11 +18,15 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::family::Family;
-use prometheus_client::metrics::histogram::{exponential_buckets, Histogram};
-use prometheus_client::registry::{Registry, Unit};
+use prometheus_client::{
+ encoding::{EncodeLabelSet, EncodeLabelValue},
+ metrics::{
+ counter::Counter,
+ family::Family,
+ histogram::{exponential_buckets, Histogram},
+ },
+ registry::{Registry, Unit},
+};
pub(crate) struct Metrics {
query_result_get_record_ok: Counter,
diff --git a/misc/metrics/src/lib.rs b/misc/metrics/src/lib.rs
index 74fd15e2181..1fd79e7846f 100644
--- a/misc/metrics/src/lib.rs
+++ b/misc/metrics/src/lib.rs
@@ -67,8 +67,8 @@ impl Metrics {
/// Create a new set of Swarm and protocol [`Metrics`].
///
/// ```
- /// use prometheus_client::registry::Registry;
/// use libp2p_metrics::Metrics;
+ /// use prometheus_client::registry::Registry;
/// let mut registry = Registry::default();
/// let metrics = Metrics::new(&mut registry);
/// ```
diff --git a/misc/metrics/src/ping.rs b/misc/metrics/src/ping.rs
index afdd05134a6..ce653c72ea1 100644
--- a/misc/metrics/src/ping.rs
+++ b/misc/metrics/src/ping.rs
@@ -18,11 +18,15 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::family::Family;
-use prometheus_client::metrics::histogram::{exponential_buckets, Histogram};
-use prometheus_client::registry::{Registry, Unit};
+use prometheus_client::{
+ encoding::{EncodeLabelSet, EncodeLabelValue},
+ metrics::{
+ counter::Counter,
+ family::Family,
+ histogram::{exponential_buckets, Histogram},
+ },
+ registry::{Registry, Unit},
+};
#[derive(Clone, Hash, PartialEq, Eq, EncodeLabelSet, Debug)]
struct FailureLabels {
diff --git a/misc/metrics/src/relay.rs b/misc/metrics/src/relay.rs
index 607daf3f1e1..d4c25b6eb3e 100644
--- a/misc/metrics/src/relay.rs
+++ b/misc/metrics/src/relay.rs
@@ -18,10 +18,11 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::family::Family;
-use prometheus_client::registry::Registry;
+use prometheus_client::{
+ encoding::{EncodeLabelSet, EncodeLabelValue},
+ metrics::{counter::Counter, family::Family},
+ registry::Registry,
+};
pub(crate) struct Metrics {
events: Family,
diff --git a/misc/metrics/src/swarm.rs b/misc/metrics/src/swarm.rs
index 51c0a0af253..6e95d082de6 100644
--- a/misc/metrics/src/swarm.rs
+++ b/misc/metrics/src/swarm.rs
@@ -18,18 +18,25 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use std::collections::HashMap;
-use std::sync::{Arc, Mutex};
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
-use crate::protocol_stack;
use libp2p_swarm::{ConnectionId, DialError, SwarmEvent};
-use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue};
-use prometheus_client::metrics::counter::Counter;
-use prometheus_client::metrics::family::Family;
-use prometheus_client::metrics::histogram::{exponential_buckets, Histogram};
-use prometheus_client::registry::{Registry, Unit};
+use prometheus_client::{
+ encoding::{EncodeLabelSet, EncodeLabelValue},
+ metrics::{
+ counter::Counter,
+ family::Family,
+ histogram::{exponential_buckets, Histogram},
+ },
+ registry::{Registry, Unit},
+};
use web_time::Instant;
+use crate::protocol_stack;
+
pub(crate) struct Metrics {
connections_incoming: Family,
connections_incoming_error: Family,
diff --git a/misc/multistream-select/Cargo.toml b/misc/multistream-select/Cargo.toml
index 1bbe3642477..d11ad4e2709 100644
--- a/misc/multistream-select/Cargo.toml
+++ b/misc/multistream-select/Cargo.toml
@@ -22,7 +22,6 @@ unsigned-varint = { workspace = true }
async-std = { version = "1.6.2", features = ["attributes"] }
futures_ringbuf = "0.4.0"
quickcheck = { workspace = true }
-rand = "0.8"
rw-stream-sink = { workspace = true }
tracing-subscriber = { workspace = true, features = ["env-filter"] }
diff --git a/misc/multistream-select/src/dialer_select.rs b/misc/multistream-select/src/dialer_select.rs
index 83bb4909041..1d13e94910d 100644
--- a/misc/multistream-select/src/dialer_select.rs
+++ b/misc/multistream-select/src/dialer_select.rs
@@ -20,10 +20,6 @@
//! Protocol negotiation strategies for the peer acting as the dialer.
-use crate::protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError};
-use crate::{Negotiated, NegotiationError, Version};
-
-use futures::prelude::*;
use std::{
convert::TryFrom as _,
iter, mem,
@@ -31,6 +27,13 @@ use std::{
task::{Context, Poll},
};
+use futures::prelude::*;
+
+use crate::{
+ protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError},
+ Negotiated, NegotiationError, Version,
+};
+
/// Returns a `Future` that negotiates a protocol on the given I/O stream
/// for a peer acting as the _dialer_ (or _initiator_).
///
@@ -84,8 +87,9 @@ enum State {
impl Future for DialerSelectFuture
where
- // The Unpin bound here is required because we produce a `Negotiated` as the output.
- // It also makes the implementation considerably easier to write.
+ // The Unpin bound here is required because we produce
+ // a `Negotiated` as the output. It also makes
+ // the implementation considerably easier to write.
R: AsyncRead + AsyncWrite + Unpin,
I: Iterator,
I::Item: AsRef,
@@ -204,15 +208,19 @@ where
#[cfg(test)]
mod tests {
- use super::*;
- use crate::listener_select_proto;
- use async_std::future::timeout;
- use async_std::net::{TcpListener, TcpStream};
- use quickcheck::{Arbitrary, Gen, GenRange};
use std::time::Duration;
+
+ use async_std::{
+ future::timeout,
+ net::{TcpListener, TcpStream},
+ };
+ use quickcheck::{Arbitrary, Gen, GenRange};
use tracing::metadata::LevelFilter;
use tracing_subscriber::EnvFilter;
+ use super::*;
+ use crate::listener_select_proto;
+
#[test]
fn select_proto_basic() {
async fn run(version: Version) {
@@ -353,8 +361,8 @@ mod tests {
.unwrap();
assert_eq!(proto, "/proto1");
- // client can close the connection even though protocol negotiation is not yet done, i.e.
- // `_server_connection` had been untouched.
+ // client can close the connection even though protocol negotiation is not yet done,
+ // i.e. `_server_connection` had been untouched.
io.close().await.unwrap();
});
diff --git a/misc/multistream-select/src/length_delimited.rs b/misc/multistream-select/src/length_delimited.rs
index 3a7988d0548..8062455de46 100644
--- a/misc/multistream-select/src/length_delimited.rs
+++ b/misc/multistream-select/src/length_delimited.rs
@@ -18,8 +18,6 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use bytes::{Buf as _, BufMut as _, Bytes, BytesMut};
-use futures::{io::IoSlice, prelude::*};
use std::{
convert::TryFrom as _,
io,
@@ -27,6 +25,9 @@ use std::{
task::{Context, Poll},
};
+use bytes::{Buf as _, BufMut as _, Bytes, BytesMut};
+use futures::{io::IoSlice, prelude::*};
+
const MAX_LEN_BYTES: u16 = 2;
const MAX_FRAME_SIZE: u16 = (1 << (MAX_LEN_BYTES * 8 - MAX_LEN_BYTES)) - 1;
const DEFAULT_BUFFER_SIZE: usize = 64;
@@ -383,10 +384,12 @@ where
#[cfg(test)]
mod tests {
- use crate::length_delimited::LengthDelimited;
+ use std::io::ErrorKind;
+
use futures::{io::Cursor, prelude::*};
use quickcheck::*;
- use std::io::ErrorKind;
+
+ use crate::length_delimited::LengthDelimited;
#[test]
fn basic_read() {
diff --git a/misc/multistream-select/src/lib.rs b/misc/multistream-select/src/lib.rs
index 5565623f25e..96432de6cb0 100644
--- a/misc/multistream-select/src/lib.rs
+++ b/misc/multistream-select/src/lib.rs
@@ -70,20 +70,21 @@
//!
//! ```no_run
//! use async_std::net::TcpStream;
-//! use multistream_select::{dialer_select_proto, Version};
//! use futures::prelude::*;
+//! use multistream_select::{dialer_select_proto, Version};
//!
//! async_std::task::block_on(async move {
//! let socket = TcpStream::connect("127.0.0.1:10333").await.unwrap();
//!
//! let protos = vec!["/echo/1.0.0", "/echo/2.5.0"];
-//! let (protocol, _io) = dialer_select_proto(socket, protos, Version::V1).await.unwrap();
+//! let (protocol, _io) = dialer_select_proto(socket, protos, Version::V1)
+//! .await
+//! .unwrap();
//!
//! println!("Negotiated protocol: {:?}", protocol);
//! // You can now use `_io` to communicate with the remote.
//! });
//! ```
-//!
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
@@ -93,10 +94,12 @@ mod listener_select;
mod negotiated;
mod protocol;
-pub use self::dialer_select::{dialer_select_proto, DialerSelectFuture};
-pub use self::listener_select::{listener_select_proto, ListenerSelectFuture};
-pub use self::negotiated::{Negotiated, NegotiatedComplete, NegotiationError};
-pub use self::protocol::ProtocolError;
+pub use self::{
+ dialer_select::{dialer_select_proto, DialerSelectFuture},
+ listener_select::{listener_select_proto, ListenerSelectFuture},
+ negotiated::{Negotiated, NegotiatedComplete, NegotiationError},
+ protocol::ProtocolError,
+};
/// Supported multistream-select versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
diff --git a/misc/multistream-select/src/listener_select.rs b/misc/multistream-select/src/listener_select.rs
index b4236310a1d..cd5af72a9d0 100644
--- a/misc/multistream-select/src/listener_select.rs
+++ b/misc/multistream-select/src/listener_select.rs
@@ -21,11 +21,6 @@
//! Protocol negotiation strategies for the peer acting as the listener
//! in a multistream-select protocol negotiation.
-use crate::protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError};
-use crate::{Negotiated, NegotiationError};
-
-use futures::prelude::*;
-use smallvec::SmallVec;
use std::{
convert::TryFrom as _,
mem,
@@ -33,6 +28,14 @@ use std::{
task::{Context, Poll},
};
+use futures::prelude::*;
+use smallvec::SmallVec;
+
+use crate::{
+ protocol::{HeaderLine, Message, MessageIO, Protocol, ProtocolError},
+ Negotiated, NegotiationError,
+};
+
/// Returns a `Future` that negotiates a protocol on the given I/O stream
/// for a peer acting as the _listener_ (or _responder_).
///
@@ -109,8 +112,10 @@ enum State {
impl Future for ListenerSelectFuture
where
- // The Unpin bound here is required because we produce a `Negotiated` as the output.
- // It also makes the implementation considerably easier to write.
+ // The Unpin bound here is required because
+ // we produce a `Negotiated` as the output.
+ // It also makes the implementation considerably
+ // easier to write.
R: AsyncRead + AsyncWrite + Unpin,
N: AsRef + Clone,
{
diff --git a/misc/multistream-select/src/negotiated.rs b/misc/multistream-select/src/negotiated.rs
index a24014a4f5f..6693b3b5636 100644
--- a/misc/multistream-select/src/negotiated.rs
+++ b/misc/multistream-select/src/negotiated.rs
@@ -18,7 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::protocol::{HeaderLine, Message, MessageReader, Protocol, ProtocolError};
+use std::{
+ error::Error,
+ fmt, io, mem,
+ pin::Pin,
+ task::{Context, Poll},
+};
use futures::{
io::{IoSlice, IoSliceMut},
@@ -26,12 +31,8 @@ use futures::{
ready,
};
use pin_project::pin_project;
-use std::{
- error::Error,
- fmt, io, mem,
- pin::Pin,
- task::{Context, Poll},
-};
+
+use crate::protocol::{HeaderLine, Message, MessageReader, Protocol, ProtocolError};
/// An I/O stream that has settled on an (application-layer) protocol to use.
///
@@ -59,8 +60,10 @@ pub struct NegotiatedComplete {
impl Future for NegotiatedComplete
where
- // `Unpin` is required not because of implementation details but because we produce the
- // `Negotiated` as the output of the future.
+ // `Unpin` is required not because of
+ // implementation details but because we produce
+ // the `Negotiated` as the output of the
+ // future.
TInner: AsyncRead + AsyncWrite + Unpin,
{
type Output = Result, NegotiationError>;
@@ -250,13 +253,13 @@ where
}
// TODO: implement once method is stabilized in the futures crate
- /*unsafe fn initializer(&self) -> Initializer {
- match &self.state {
- State::Completed { io, .. } => io.initializer(),
- State::Expecting { io, .. } => io.inner_ref().initializer(),
- State::Invalid => panic!("Negotiated: Invalid state"),
- }
- }*/
+ // unsafe fn initializer(&self) -> Initializer {
+ // match &self.state {
+ // State::Completed { io, .. } => io.initializer(),
+ // State::Expecting { io, .. } => io.inner_ref().initializer(),
+ // State::Invalid => panic!("Negotiated: Invalid state"),
+ // }
+ // }
fn poll_read_vectored(
mut self: Pin<&mut Self>,
diff --git a/misc/multistream-select/src/protocol.rs b/misc/multistream-select/src/protocol.rs
index 92b6acedaeb..93cd4ac02b5 100644
--- a/misc/multistream-select/src/protocol.rs
+++ b/misc/multistream-select/src/protocol.rs
@@ -25,19 +25,22 @@
//! `Stream` and `Sink` implementations of `MessageIO` and
//! `MessageReader`.
-use crate::length_delimited::{LengthDelimited, LengthDelimitedReader};
-use crate::Version;
-
-use bytes::{BufMut, Bytes, BytesMut};
-use futures::{io::IoSlice, prelude::*, ready};
use std::{
error::Error,
fmt, io,
pin::Pin,
task::{Context, Poll},
};
+
+use bytes::{BufMut, Bytes, BytesMut};
+use futures::{io::IoSlice, prelude::*, ready};
use unsigned_varint as uvi;
+use crate::{
+ length_delimited::{LengthDelimited, LengthDelimitedReader},
+ Version,
+};
+
/// The maximum number of supported protocols that can be processed.
const MAX_PROTOCOLS: usize = 1000;
@@ -461,10 +464,12 @@ impl fmt::Display for ProtocolError {
#[cfg(test)]
mod tests {
- use super::*;
- use quickcheck::*;
use std::iter;
+ use quickcheck::*;
+
+ use super::*;
+
impl Arbitrary for Protocol {
fn arbitrary(g: &mut Gen) -> Protocol {
let n = g.gen_range(1..g.size());
diff --git a/misc/quick-protobuf-codec/Cargo.toml b/misc/quick-protobuf-codec/Cargo.toml
index 985479059a2..2501e94ca19 100644
--- a/misc/quick-protobuf-codec/Cargo.toml
+++ b/misc/quick-protobuf-codec/Cargo.toml
@@ -13,7 +13,7 @@ categories = ["asynchronous"]
[dependencies]
asynchronous-codec = { workspace = true }
bytes = { version = "1" }
-thiserror = "1.0"
+thiserror = { workspace = true }
unsigned-varint = { workspace = true, features = ["std"] }
quick-protobuf = "0.8"
diff --git a/misc/quick-protobuf-codec/src/lib.rs b/misc/quick-protobuf-codec/src/lib.rs
index 166ee82ff08..d49315a54c3 100644
--- a/misc/quick-protobuf-codec/src/lib.rs
+++ b/misc/quick-protobuf-codec/src/lib.rs
@@ -1,10 +1,10 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
+use std::{io, marker::PhantomData};
+
use asynchronous_codec::{Decoder, Encoder};
use bytes::{Buf, BufMut, BytesMut};
use quick_protobuf::{BytesReader, MessageRead, MessageWrite, Writer, WriterBackend};
-use std::io;
-use std::marker::PhantomData;
mod generated;
@@ -12,6 +12,7 @@ mod generated;
pub use generated::test as proto;
/// [`Codec`] implements [`Encoder`] and [`Decoder`], uses [`unsigned_varint`]
+///
/// to prefix messages with their length and uses [`quick_protobuf`] and a provided
/// `struct` implementing [`MessageRead`] and [`MessageWrite`] to do the encoding.
pub struct Codec {
@@ -119,7 +120,7 @@ impl<'a> BytesMutWriterBackend<'a> {
}
}
-impl<'a> WriterBackend for BytesMutWriterBackend<'a> {
+impl WriterBackend for BytesMutWriterBackend<'_> {
fn pb_write_u8(&mut self, x: u8) -> quick_protobuf::Result<()> {
self.dst.put_u8(x);
@@ -181,12 +182,13 @@ impl From for io::Error {
#[cfg(test)]
mod tests {
- use super::*;
+ use std::error::Error;
+
use asynchronous_codec::FramedRead;
- use futures::io::Cursor;
- use futures::{FutureExt, StreamExt};
+ use futures::{io::Cursor, FutureExt, StreamExt};
use quickcheck::{Arbitrary, Gen, QuickCheck};
- use std::error::Error;
+
+ use super::*;
#[test]
fn honors_max_message_length() {
diff --git a/misc/quick-protobuf-codec/tests/large_message.rs b/misc/quick-protobuf-codec/tests/large_message.rs
index 65dafe065d1..a434d3ce17f 100644
--- a/misc/quick-protobuf-codec/tests/large_message.rs
+++ b/misc/quick-protobuf-codec/tests/large_message.rs
@@ -1,7 +1,6 @@
use asynchronous_codec::Encoder;
use bytes::BytesMut;
-use quick_protobuf_codec::proto;
-use quick_protobuf_codec::Codec;
+use quick_protobuf_codec::{proto, Codec};
#[test]
fn encode_large_message() {
diff --git a/misc/quickcheck-ext/src/lib.rs b/misc/quickcheck-ext/src/lib.rs
index 4ada7e73ba1..9c2deec8743 100644
--- a/misc/quickcheck-ext/src/lib.rs
+++ b/misc/quickcheck-ext/src/lib.rs
@@ -1,9 +1,9 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
-pub use quickcheck::*;
-
use core::ops::Range;
+
use num_traits::sign::Unsigned;
+pub use quickcheck::*;
pub trait GenRange {
fn gen_range(&mut self, _range: Range) -> T;
diff --git a/misc/rw-stream-sink/src/lib.rs b/misc/rw-stream-sink/src/lib.rs
index f10e683ad33..5fdf1987252 100644
--- a/misc/rw-stream-sink/src/lib.rs
+++ b/misc/rw-stream-sink/src/lib.rs
@@ -27,7 +27,6 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
-use futures::{prelude::*, ready};
use std::{
io::{self, Read},
mem,
@@ -35,6 +34,8 @@ use std::{
task::{Context, Poll},
};
+use futures::{prelude::*, ready};
+
static_assertions::const_assert!(mem::size_of::() <= mem::size_of::());
/// Wraps a [`Stream`] and [`Sink`] whose items are buffers.
@@ -115,14 +116,16 @@ where
#[cfg(test)]
mod tests {
- use super::RwStreamSink;
- use async_std::task;
- use futures::{channel::mpsc, prelude::*};
use std::{
pin::Pin,
task::{Context, Poll},
};
+ use async_std::task;
+ use futures::{channel::mpsc, prelude::*};
+
+ use super::RwStreamSink;
+
// This struct merges a stream and a sink and is quite useful for tests.
struct Wrapper(St, Si);
diff --git a/misc/server/CHANGELOG.md b/misc/server/CHANGELOG.md
index 5369163460c..53341baa9ab 100644
--- a/misc/server/CHANGELOG.md
+++ b/misc/server/CHANGELOG.md
@@ -1,18 +1,15 @@
-## 0.12.7
+## 0.12.6
### Changed
+- Stop using kad default protocol.
+ See [PR 5122](https://github.com/libp2p/rust-libp2p/pull/5122)
- Use periodic and automatic bootstrap of Kademlia.
See [PR 4838](https://github.com/libp2p/rust-libp2p/pull/4838).
- Update to [`libp2p-identify` `v0.45.0`](protocols/identify/CHANGELOG.md#0450).
See [PR 4981](https://github.com/libp2p/rust-libp2p/pull/4981).
-
-## 0.12.6
-
-### Changed
-
-- Stop using kad default protocol.
- See [PR 5122](https://github.com/libp2p/rust-libp2p/pull/5122)
+- Remove deprecated [`libp2p-lookup`](https://github.com/mxinden/libp2p-lookup) from Dockerfile.
+ See [PR 5610](https://github.com/libp2p/rust-libp2p/pull/5610).
## 0.12.5
@@ -31,6 +28,7 @@
## 0.12.3
### Changed
+
- Add libp2p-lookup to Dockerfile to enable healthchecks.
### Fixed
@@ -42,14 +40,18 @@
[PR 4467]: https://github.com/libp2p/rust-libp2p/pull/4467
## 0.12.2
+
### Fixed
+
- Adhere to `--metrics-path` flag and listen on `0.0.0.0:8888` (default IPFS metrics port).
[PR 4392]
[PR 4392]: https://github.com/libp2p/rust-libp2p/pull/4392
## 0.12.1
+
### Changed
+
- Move to tokio and hyper.
See [PR 4311].
- Move to distroless Docker base image.
@@ -58,39 +60,57 @@
[PR 4311]: https://github.com/libp2p/rust-libp2p/pull/4311
## 0.8.0
+
### Changed
+
- Remove mplex support.
## 0.7.0
+
### Changed
+
- Update to libp2p v0.47.0.
## 0.6.0 - 2022-05-05
+
### Changed
+
- Update to libp2p v0.44.0.
## 0.5.4 - 2022-01-11
+
### Changed
+
- Pull latest autonat changes.
## 0.5.3 - 2021-12-25
+
### Changed
+
- Update dependencies.
- Pull in autonat fixes.
## 0.5.2 - 2021-12-20
+
### Added
+
- Add support for libp2p autonat protocol via `--enable-autonat`.
## 0.5.1 - 2021-12-20
+
### Fixed
+
- Update dependencies.
- Fix typo in command line flag `--enable-kademlia`.
## 0.5.0 - 2021-11-18
+
### Changed
+
- Disable Kademlia protocol by default.
## 0.4.0 - 2021-11-18
+
### Fixed
+
- Update dependencies.
diff --git a/misc/server/Cargo.toml b/misc/server/Cargo.toml
index 798ecfa07a9..b2b3d33ca1e 100644
--- a/misc/server/Cargo.toml
+++ b/misc/server/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "libp2p-server"
-version = "0.12.7"
+version = "0.12.6"
authors = ["Max Inden "]
edition = "2021"
repository = "https://github.com/libp2p/rust-libp2p"
@@ -14,12 +14,26 @@ license = "MIT"
base64 = "0.22"
clap = { version = "4.5.6", features = ["derive"] }
futures = { workspace = true }
-futures-timer = "3"
axum = "0.7"
-libp2p = { workspace = true, features = ["autonat", "dns", "tokio", "noise", "tcp", "yamux", "identify", "kad", "ping", "relay", "metrics", "rsa", "macros", "quic", "websocket"] }
+libp2p = { workspace = true, features = [
+ "autonat",
+ "dns",
+ "tokio",
+ "noise",
+ "tcp",
+ "yamux",
+ "identify",
+ "kad",
+ "ping",
+ "relay",
+ "metrics",
+ "rsa",
+ "macros",
+ "quic",
+ "websocket",
+] }
prometheus-client = { workspace = true }
-serde = "1.0.203"
-serde_derive = "1.0.125"
+serde = { version = "1", features = ["derive"] }
serde_json = "1.0"
tokio = { workspace = true, features = ["rt-multi-thread", "macros"] }
tracing = { workspace = true }
diff --git a/misc/server/Dockerfile b/misc/server/Dockerfile
index 1583fba6bef..8b5aac2ae82 100644
--- a/misc/server/Dockerfile
+++ b/misc/server/Dockerfile
@@ -1,7 +1,6 @@
# syntax=docker/dockerfile:1.5-labs
-FROM rust:1.75.0 as chef
+FROM rust:1.83.0 as chef
RUN wget -q -O- https://github.com/LukeMathWalker/cargo-chef/releases/download/v0.1.62/cargo-chef-x86_64-unknown-linux-gnu.tar.gz | tar -zx -C /usr/local/bin
-RUN cargo install --locked --root /usr/local libp2p-lookup --version 0.6.4
WORKDIR /app
FROM chef AS planner
@@ -17,5 +16,4 @@ COPY . .
RUN cargo build --release --package libp2p-server
FROM gcr.io/distroless/cc
-COPY --from=builder /usr/local/bin/libp2p-server /usr/local/bin/libp2p-lookup /usr/local/bin/
CMD ["libp2p-server"]
diff --git a/misc/server/README.md b/misc/server/README.md
index 0da1bd8abd9..f9a5d65124a 100644
--- a/misc/server/README.md
+++ b/misc/server/README.md
@@ -25,7 +25,6 @@ Options:
-h, --help Print help
```
-
```
cargo run -- --config ~/.ipfs/config
@@ -33,9 +32,3 @@ Local peer id: PeerId("12D3KooWSa1YEeQVSwvoqAMhwjKQ6kqZQckhWPb3RWEGV3sZGU6Z")
Listening on "/ip4/127.0.0.1/udp/4001/quic"
[...]
```
-
-The Docker container includes [libp2-lookup](https://github.com/mxinden/libp2p-lookup/) to enable adding a proper healthcheck for container startup, e.g.
-
-``` shell
-docker run --health-cmd 'libp2p-lookup direct --address /ip4/127.0.0.1/tcp/4001/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa' /home/ipfs/.ipfs:/ipfs ghcr.io/libp2p/rust-libp2p-server --config /ipfs/config
-```
diff --git a/misc/server/src/behaviour.rs b/misc/server/src/behaviour.rs
index 36b18c9798d..230d62a2ef3 100644
--- a/misc/server/src/behaviour.rs
+++ b/misc/server/src/behaviour.rs
@@ -1,13 +1,10 @@
-use libp2p::autonat;
-use libp2p::identify;
-use libp2p::kad;
-use libp2p::ping;
-use libp2p::relay;
-use libp2p::swarm::behaviour::toggle::Toggle;
-use libp2p::swarm::{NetworkBehaviour, StreamProtocol};
-use libp2p::{identity, Multiaddr, PeerId};
-use std::str::FromStr;
-use std::time::Duration;
+use std::{str::FromStr, time::Duration};
+
+use libp2p::{
+ autonat, identify, identity, kad, ping, relay,
+ swarm::{behaviour::toggle::Toggle, NetworkBehaviour, StreamProtocol},
+ Multiaddr, PeerId,
+};
const BOOTNODES: [&str; 4] = [
"QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
diff --git a/misc/server/src/config.rs b/misc/server/src/config.rs
index c3e3ec529c1..8f8c71369b2 100644
--- a/misc/server/src/config.rs
+++ b/misc/server/src/config.rs
@@ -1,7 +1,7 @@
+use std::{error::Error, path::Path};
+
use libp2p::Multiaddr;
-use serde_derive::Deserialize;
-use std::error::Error;
-use std::path::Path;
+use serde::Deserialize;
#[derive(Clone, Deserialize)]
#[serde(rename_all = "PascalCase")]
diff --git a/misc/server/src/http_service.rs b/misc/server/src/http_service.rs
index cee1aa96e28..87a8adb94e0 100644
--- a/misc/server/src/http_service.rs
+++ b/misc/server/src/http_service.rs
@@ -18,15 +18,13 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use axum::extract::State;
-use axum::http::StatusCode;
-use axum::response::IntoResponse;
-use axum::routing::get;
-use axum::Router;
-use prometheus_client::encoding::text::encode;
-use prometheus_client::registry::Registry;
-use std::net::SocketAddr;
-use std::sync::{Arc, Mutex};
+use std::{
+ net::SocketAddr,
+ sync::{Arc, Mutex},
+};
+
+use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Router};
+use prometheus_client::{encoding::text::encode, registry::Registry};
use tokio::net::TcpListener;
const METRICS_CONTENT_TYPE: &str = "application/openmetrics-text;charset=utf-8;version=1.0.0";
diff --git a/misc/server/src/main.rs b/misc/server/src/main.rs
index 820921beaed..a633a80207e 100644
--- a/misc/server/src/main.rs
+++ b/misc/server/src/main.rs
@@ -1,18 +1,18 @@
+use std::{error::Error, path::PathBuf, str::FromStr};
+
use base64::Engine;
use clap::Parser;
use futures::stream::StreamExt;
-use libp2p::identity;
-use libp2p::identity::PeerId;
-use libp2p::kad;
-use libp2p::metrics::{Metrics, Recorder};
-use libp2p::swarm::SwarmEvent;
-use libp2p::tcp;
-use libp2p::{identify, noise, yamux};
-use prometheus_client::metrics::info::Info;
-use prometheus_client::registry::Registry;
-use std::error::Error;
-use std::path::PathBuf;
-use std::str::FromStr;
+use libp2p::{
+ identify, identity,
+ identity::PeerId,
+ kad,
+ metrics::{Metrics, Recorder},
+ noise,
+ swarm::SwarmEvent,
+ tcp, yamux,
+};
+use prometheus_client::{metrics::info::Info, registry::Registry};
use tracing_subscriber::EnvFilter;
use zeroize::Zeroizing;
diff --git a/misc/webrtc-utils/CHANGELOG.md b/misc/webrtc-utils/CHANGELOG.md
index 3bb31610fa1..992f8354bba 100644
--- a/misc/webrtc-utils/CHANGELOG.md
+++ b/misc/webrtc-utils/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 0.4.0
+
+
+
## 0.3.0
diff --git a/misc/webrtc-utils/Cargo.toml b/misc/webrtc-utils/Cargo.toml
index 88f576f12d9..bfcad64d08f 100644
--- a/misc/webrtc-utils/Cargo.toml
+++ b/misc/webrtc-utils/Cargo.toml
@@ -7,7 +7,7 @@ license = "MIT"
name = "libp2p-webrtc-utils"
repository = "https://github.com/libp2p/rust-libp2p"
rust-version = { workspace = true }
-version = "0.3.0"
+version = "0.4.0"
publish = true
[dependencies]
@@ -23,7 +23,6 @@ quick-protobuf-codec = { workspace = true }
rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
sha2 = "0.10.8"
-thiserror = "1"
tinytemplate = "1.2"
tracing = { workspace = true }
diff --git a/misc/webrtc-utils/src/fingerprint.rs b/misc/webrtc-utils/src/fingerprint.rs
index a02c4d1116d..c32d33d5bab 100644
--- a/misc/webrtc-utils/src/fingerprint.rs
+++ b/misc/webrtc-utils/src/fingerprint.rs
@@ -19,9 +19,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::fmt;
+
use libp2p_core::multihash;
use sha2::Digest as _;
-use std::fmt;
pub const SHA256: &str = "sha-256";
const MULTIHASH_SHA256_CODE: u64 = 0x12;
diff --git a/misc/webrtc-utils/src/noise.rs b/misc/webrtc-utils/src/noise.rs
index 9180acfc1ca..705db7f4697 100644
--- a/misc/webrtc-utils/src/noise.rs
+++ b/misc/webrtc-utils/src/noise.rs
@@ -19,16 +19,17 @@
// DEALINGS IN THE SOFTWARE.
use futures::{AsyncRead, AsyncWrite, AsyncWriteExt};
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
-use libp2p_core::UpgradeInfo;
+use libp2p_core::{
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade},
+ UpgradeInfo,
+};
use libp2p_identity as identity;
use libp2p_identity::PeerId;
use libp2p_noise as noise;
+pub use noise::Error;
use crate::fingerprint::Fingerprint;
-pub use noise::Error;
-
pub async fn inbound(
id_keys: identity::Keypair,
stream: T,
@@ -89,9 +90,10 @@ pub(crate) fn noise_prologue(
#[cfg(test)]
mod tests {
- use super::*;
use hex_literal::hex;
+ use super::*;
+
#[test]
fn noise_prologue_tests() {
let a = Fingerprint::raw(hex!(
diff --git a/misc/webrtc-utils/src/sdp.rs b/misc/webrtc-utils/src/sdp.rs
index 0796548f449..96a07f5db95 100644
--- a/misc/webrtc-utils/src/sdp.rs
+++ b/misc/webrtc-utils/src/sdp.rs
@@ -18,13 +18,13 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::fingerprint::Fingerprint;
-use serde::Serialize;
use std::net::{IpAddr, SocketAddr};
+
+use rand::{distributions::Alphanumeric, thread_rng, Rng};
+use serde::Serialize;
use tinytemplate::TinyTemplate;
-use rand::distributions::Alphanumeric;
-use rand::{thread_rng, Rng};
+use crate::fingerprint::Fingerprint;
pub fn answer(addr: SocketAddr, server_fingerprint: Fingerprint, client_ufrag: &str) -> String {
let answer = render_description(
@@ -71,7 +71,8 @@ pub fn answer(addr: SocketAddr, server_fingerprint: Fingerprint, client_ufrag: &
// the answerer is received, which adds additional latency. setup:active allows the answer and
// the DTLS handshake to occur in parallel. Thus, setup:active is RECOMMENDED.
//
-// a=candidate:
+// a=candidate:
+//
//
// A transport address for a candidate that can be used for connectivity checks (RFC8839).
//
diff --git a/misc/webrtc-utils/src/stream.rs b/misc/webrtc-utils/src/stream.rs
index 17f746a92a1..0ec420a103a 100644
--- a/misc/webrtc-utils/src/stream.rs
+++ b/misc/webrtc-utils/src/stream.rs
@@ -19,20 +19,22 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use bytes::Bytes;
-use futures::{channel::oneshot, prelude::*, ready};
-
use std::{
io,
pin::Pin,
task::{Context, Poll},
};
-use crate::proto::{Flag, Message};
+use bytes::Bytes;
+use futures::{channel::oneshot, prelude::*, ready};
+
use crate::{
- stream::drop_listener::GracefullyClosed,
- stream::framed_dc::FramedDc,
- stream::state::{Closing, State},
+ proto::{Flag, Message},
+ stream::{
+ drop_listener::GracefullyClosed,
+ framed_dc::FramedDc,
+ state::{Closing, State},
+ },
};
mod drop_listener;
@@ -69,7 +71,8 @@ impl Stream
where
T: AsyncRead + AsyncWrite + Unpin + Clone,
{
- /// Returns a new [`Stream`] and a [`DropListener`], which will notify the receiver when/if the stream is dropped.
+ /// Returns a new [`Stream`] and a [`DropListener`],
+ /// which will notify the receiver when/if the stream is dropped.
pub fn new(data_channel: T) -> (Self, DropListener) {
let (sender, receiver) = oneshot::channel();
@@ -175,8 +178,9 @@ where
buf: &[u8],
) -> Poll> {
while self.state.read_flags_in_async_write() {
- // TODO: In case AsyncRead::poll_read encountered an error or returned None earlier, we will poll the
- // underlying I/O resource once more. Is that allowed? How about introducing a state IoReadClosed?
+ // TODO: In case AsyncRead::poll_read encountered an error or returned None earlier, we
+ // will poll the underlying I/O resource once more. Is that allowed? How
+ // about introducing a state IoReadClosed?
let Self {
read_buffer,
@@ -265,11 +269,12 @@ where
#[cfg(test)]
mod tests {
- use super::*;
- use crate::stream::framed_dc::codec;
use asynchronous_codec::Encoder;
use bytes::BytesMut;
+ use super::*;
+ use crate::stream::framed_dc::codec;
+
#[test]
fn max_data_len() {
// Largest possible message.
diff --git a/misc/webrtc-utils/src/stream/drop_listener.rs b/misc/webrtc-utils/src/stream/drop_listener.rs
index 9745e3d4364..ea3f19d2f57 100644
--- a/misc/webrtc-utils/src/stream/drop_listener.rs
+++ b/misc/webrtc-utils/src/stream/drop_listener.rs
@@ -18,17 +18,22 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use futures::channel::oneshot;
-use futures::channel::oneshot::Canceled;
-use futures::{AsyncRead, AsyncWrite, FutureExt, SinkExt};
+use std::{
+ future::Future,
+ io,
+ pin::Pin,
+ task::{Context, Poll},
+};
-use std::future::Future;
-use std::io;
-use std::pin::Pin;
-use std::task::{Context, Poll};
+use futures::{
+ channel::{oneshot, oneshot::Canceled},
+ AsyncRead, AsyncWrite, FutureExt, SinkExt,
+};
-use crate::proto::{Flag, Message};
-use crate::stream::framed_dc::FramedDc;
+use crate::{
+ proto::{Flag, Message},
+ stream::framed_dc::FramedDc,
+};
#[must_use]
pub struct DropListener {
diff --git a/misc/webrtc-utils/src/stream/framed_dc.rs b/misc/webrtc-utils/src/stream/framed_dc.rs
index 721178fdcd3..a7b9b6214e0 100644
--- a/misc/webrtc-utils/src/stream/framed_dc.rs
+++ b/misc/webrtc-utils/src/stream/framed_dc.rs
@@ -21,8 +21,10 @@
use asynchronous_codec::Framed;
use futures::{AsyncRead, AsyncWrite};
-use crate::proto::Message;
-use crate::stream::{MAX_DATA_LEN, MAX_MSG_LEN, VARINT_LEN};
+use crate::{
+ proto::Message,
+ stream::{MAX_DATA_LEN, MAX_MSG_LEN, VARINT_LEN},
+};
pub(crate) type FramedDc = Framed>;
pub(crate) fn new(inner: T) -> FramedDc
diff --git a/misc/webrtc-utils/src/stream/state.rs b/misc/webrtc-utils/src/stream/state.rs
index 082325e4d47..006c1610d00 100644
--- a/misc/webrtc-utils/src/stream/state.rs
+++ b/misc/webrtc-utils/src/stream/state.rs
@@ -18,10 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use bytes::Bytes;
-
use std::io;
+use bytes::Bytes;
+
use crate::proto::Flag;
#[derive(Debug, Copy, Clone)]
@@ -46,8 +46,8 @@ pub(crate) enum State {
/// Represents the state of closing one half (either read or write) of the connection.
///
-/// Gracefully closing the read or write requires sending the `STOP_SENDING` or `FIN` flag respectively
-/// and flushing the underlying connection.
+/// 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(crate) enum Closing {
Requested,
@@ -181,8 +181,8 @@ impl State {
/// Whether we should read from the stream in the [`futures::AsyncWrite`] implementation.
///
- /// This is necessary for read-closed streams because we would otherwise not read any more flags from
- /// the socket.
+ /// This is necessary for read-closed streams because we would otherwise
+ /// not read any more flags from the socket.
pub(crate) fn read_flags_in_async_write(&self) -> bool {
matches!(self, Self::ReadClosed)
}
@@ -324,9 +324,10 @@ impl State {
#[cfg(test)]
mod tests {
- use super::*;
use std::io::ErrorKind;
+ use super::*;
+
#[test]
fn cannot_read_after_receiving_fin() {
let mut open = State::Open;
diff --git a/misc/webrtc-utils/src/transport.rs b/misc/webrtc-utils/src/transport.rs
index 440ad73ed02..60b1934082f 100644
--- a/misc/webrtc-utils/src/transport.rs
+++ b/misc/webrtc-utils/src/transport.rs
@@ -1,7 +1,9 @@
-use crate::fingerprint::Fingerprint;
-use libp2p_core::{multiaddr::Protocol, Multiaddr};
use std::net::{IpAddr, SocketAddr};
+use libp2p_core::{multiaddr::Protocol, Multiaddr};
+
+use crate::fingerprint::Fingerprint;
+
/// Parse the given [`Multiaddr`] into a [`SocketAddr`] and a [`Fingerprint`] for dialing.
pub fn parse_webrtc_dial_addr(addr: &Multiaddr) -> Option<(SocketAddr, Fingerprint)> {
let mut iter = addr.iter();
@@ -38,9 +40,10 @@ pub fn parse_webrtc_dial_addr(addr: &Multiaddr) -> Option<(SocketAddr, Fingerpri
#[cfg(test)]
mod tests {
- use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
+ use super::*;
+
#[test]
fn parse_valid_address_with_certhash_and_p2p() {
let addr = "/ip4/127.0.0.1/udp/39901/webrtc-direct/certhash/uEiDikp5KVUgkLta1EjUN-IKbHk-dUBg8VzKgf5nXxLK46w/p2p/12D3KooWNpDk9w6WrEEcdsEH1y47W71S36yFjw4sd3j7omzgCSMS"
diff --git a/muxers/mplex/CHANGELOG.md b/muxers/mplex/CHANGELOG.md
index f0c2c0353da..651a4d6182e 100644
--- a/muxers/mplex/CHANGELOG.md
+++ b/muxers/mplex/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 0.43.0
+
+
+
## 0.42.0
diff --git a/muxers/mplex/Cargo.toml b/muxers/mplex/Cargo.toml
index 7f887c8b3b8..2bd6a49bbc8 100644
--- a/muxers/mplex/Cargo.toml
+++ b/muxers/mplex/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-mplex"
edition = "2021"
rust-version = { workspace = true }
description = "Mplex multiplexing protocol for libp2p"
-version = "0.42.0"
+version = "0.43.0"
authors = ["Parity Technologies "]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
diff --git a/muxers/mplex/benches/split_send_size.rs b/muxers/mplex/benches/split_send_size.rs
index 44eafa884ac..b0dd4babff7 100644
--- a/muxers/mplex/benches/split_send_size.rs
+++ b/muxers/mplex/benches/split_send_size.rs
@@ -21,21 +21,23 @@
//! A benchmark for the `split_send_size` configuration option
//! using different transports.
+use std::{pin::Pin, time::Duration};
+
use async_std::task;
use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};
-use futures::future::poll_fn;
-use futures::prelude::*;
-use futures::{channel::oneshot, future::join};
-use libp2p_core::muxing::StreamMuxerExt;
-use libp2p_core::transport::ListenerId;
-use libp2p_core::Endpoint;
-use libp2p_core::{multiaddr::multiaddr, muxing, transport, upgrade, Multiaddr, Transport};
+use futures::{
+ channel::oneshot,
+ future::{join, poll_fn},
+ prelude::*,
+};
+use libp2p_core::{
+ multiaddr::multiaddr, muxing, muxing::StreamMuxerExt, transport, transport::ListenerId,
+ upgrade, Endpoint, Multiaddr, Transport,
+};
use libp2p_identity as identity;
use libp2p_identity::PeerId;
use libp2p_mplex as mplex;
use libp2p_plaintext as plaintext;
-use std::pin::Pin;
-use std::time::Duration;
use tracing_subscriber::EnvFilter;
type BenchTransport = transport::Boxed<(PeerId, muxing::StreamMuxerBox)>;
@@ -120,7 +122,8 @@ fn run(
}
transport::TransportEvent::Incoming { upgrade, .. } => {
let (_peer, mut conn) = upgrade.await.unwrap();
- // Just calling `poll_inbound` without `poll` is fine here because mplex makes progress through all `poll_` functions. It is hacky though.
+ // Just calling `poll_inbound` without `poll` is fine here because mplex makes
+ // progress through all `poll_` functions. It is hacky though.
let mut s = poll_fn(|cx| conn.poll_inbound_unpin(cx))
.await
.expect("unexpected error");
@@ -158,7 +161,8 @@ fn run(
.unwrap()
.await
.unwrap();
- // Just calling `poll_outbound` without `poll` is fine here because mplex makes progress through all `poll_` functions. It is hacky though.
+ // Just calling `poll_outbound` without `poll` is fine here because mplex makes progress
+ // through all `poll_` functions. It is hacky though.
let mut stream = poll_fn(|cx| conn.poll_outbound_unpin(cx)).await.unwrap();
let mut off = 0;
loop {
diff --git a/muxers/mplex/src/codec.rs b/muxers/mplex/src/codec.rs
index 014ee899280..20ee6bb4ed6 100644
--- a/muxers/mplex/src/codec.rs
+++ b/muxers/mplex/src/codec.rs
@@ -18,14 +18,15 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use asynchronous_codec::{Decoder, Encoder};
-use bytes::{BufMut, Bytes, BytesMut};
-use libp2p_core::Endpoint;
use std::{
fmt,
hash::{Hash, Hasher},
io, mem,
};
+
+use asynchronous_codec::{Decoder, Encoder};
+use bytes::{BufMut, Bytes, BytesMut};
+use libp2p_core::Endpoint;
use unsigned_varint::{codec, encode};
// Maximum size for a packet: 1MB as per the spec.
@@ -298,7 +299,7 @@ impl Encoder for Codec {
role: Endpoint::Listener,
},
data,
- } => (num << 3 | 1, data),
+ } => ((num << 3) | 1, data),
Frame::Data {
stream_id:
LocalStreamId {
@@ -306,35 +307,35 @@ impl Encoder for Codec {
role: Endpoint::Dialer,
},
data,
- } => (num << 3 | 2, data),
+ } => ((num << 3) | 2, data),
Frame::Close {
stream_id:
LocalStreamId {
num,
role: Endpoint::Listener,
},
- } => (num << 3 | 3, Bytes::new()),
+ } => ((num << 3) | 3, Bytes::new()),
Frame::Close {
stream_id:
LocalStreamId {
num,
role: Endpoint::Dialer,
},
- } => (num << 3 | 4, Bytes::new()),
+ } => ((num << 3) | 4, Bytes::new()),
Frame::Reset {
stream_id:
LocalStreamId {
num,
role: Endpoint::Listener,
},
- } => (num << 3 | 5, Bytes::new()),
+ } => ((num << 3) | 5, Bytes::new()),
Frame::Reset {
stream_id:
LocalStreamId {
num,
role: Endpoint::Dialer,
},
- } => (num << 3 | 6, Bytes::new()),
+ } => ((num << 3) | 6, Bytes::new()),
};
let mut header_buf = encode::u64_buffer();
diff --git a/muxers/mplex/src/config.rs b/muxers/mplex/src/config.rs
index 3bf5e703a18..45bb05b2240 100644
--- a/muxers/mplex/src/config.rs
+++ b/muxers/mplex/src/config.rs
@@ -18,9 +18,10 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::codec::MAX_FRAME_SIZE;
use std::cmp;
+use crate::codec::MAX_FRAME_SIZE;
+
pub(crate) const DEFAULT_MPLEX_PROTOCOL_NAME: &str = "/mplex/6.7.0";
/// Configuration for the multiplexer.
diff --git a/muxers/mplex/src/io.rs b/muxers/mplex/src/io.rs
index 50fc0fc1d3f..ac93fd3865e 100644
--- a/muxers/mplex/src/io.rs
+++ b/muxers/mplex/src/io.rs
@@ -18,23 +18,31 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::codec::{Codec, Frame, LocalStreamId, RemoteStreamId};
-use crate::{MaxBufferBehaviour, MplexConfig};
+pub(crate) use std::io::{Error, Result};
+use std::{
+ cmp,
+ collections::VecDeque,
+ fmt, io, mem,
+ sync::Arc,
+ task::{Context, Poll, Waker},
+};
+
use asynchronous_codec::Framed;
use bytes::Bytes;
-use futures::task::{waker_ref, ArcWake, AtomicWaker, WakerRef};
-use futures::{prelude::*, ready, stream::Fuse};
+use futures::{
+ prelude::*,
+ ready,
+ stream::Fuse,
+ task::{waker_ref, ArcWake, AtomicWaker, WakerRef},
+};
use nohash_hasher::{IntMap, IntSet};
use parking_lot::Mutex;
use smallvec::SmallVec;
-use std::collections::VecDeque;
-use std::{
- cmp, fmt, io, mem,
- sync::Arc,
- task::{Context, Poll, Waker},
-};
-pub(crate) use std::io::{Error, Result};
+use crate::{
+ codec::{Codec, Frame, LocalStreamId, RemoteStreamId},
+ MaxBufferBehaviour, MplexConfig,
+};
/// A connection identifier.
///
/// Randomly generated and mainly intended to improve log output
@@ -302,13 +310,11 @@ where
/// reading and writing immediately. The remote is informed
/// based on the current state of the substream:
///
- /// * If the substream was open, a `Reset` frame is sent at
- /// the next opportunity.
- /// * If the substream was half-closed, i.e. a `Close` frame
- /// has already been sent, nothing further happens.
- /// * If the substream was half-closed by the remote, i.e.
- /// a `Close` frame has already been received, a `Close`
- /// frame is sent at the next opportunity.
+ /// * If the substream was open, a `Reset` frame is sent at the next opportunity.
+ /// * If the substream was half-closed, i.e. a `Close` frame has already been sent, nothing
+ /// further happens.
+ /// * If the substream was half-closed by the remote, i.e. a `Close` frame has already been
+ /// received, a `Close` frame is sent at the next opportunity.
///
/// If the multiplexed stream is closed or encountered
/// an error earlier, or there is no known substream with
@@ -1146,15 +1152,14 @@ const EXTRA_PENDING_FRAMES: usize = 1000;
#[cfg(test)]
mod tests {
- use super::*;
+ use std::{collections::HashSet, num::NonZeroU8, ops::DerefMut, pin::Pin};
+
use async_std::task;
use asynchronous_codec::{Decoder, Encoder};
use bytes::BytesMut;
use quickcheck::*;
- use std::collections::HashSet;
- use std::num::NonZeroU8;
- use std::ops::DerefMut;
- use std::pin::Pin;
+
+ use super::*;
impl Arbitrary for MaxBufferBehaviour {
fn arbitrary(g: &mut Gen) -> MaxBufferBehaviour {
diff --git a/muxers/mplex/src/lib.rs b/muxers/mplex/src/lib.rs
index 17ca9ad46f6..1ef89dc283a 100644
--- a/muxers/mplex/src/lib.rs
+++ b/muxers/mplex/src/lib.rs
@@ -26,15 +26,22 @@ mod codec;
mod config;
mod io;
-pub use config::{MaxBufferBehaviour, MplexConfig};
+use std::{
+ cmp, iter,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+};
use bytes::Bytes;
use codec::LocalStreamId;
+pub use config::{MaxBufferBehaviour, MplexConfig};
use futures::{prelude::*, ready};
-use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent};
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo};
+use libp2p_core::{
+ muxing::{StreamMuxer, StreamMuxerEvent},
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo},
+};
use parking_lot::Mutex;
-use std::{cmp, iter, pin::Pin, sync::Arc, task::Context, task::Poll};
impl UpgradeInfo for MplexConfig {
type Info = &'static str;
diff --git a/muxers/test-harness/src/lib.rs b/muxers/test-harness/src/lib.rs
index 16c71f414f0..489d476f158 100644
--- a/muxers/test-harness/src/lib.rs
+++ b/muxers/test-harness/src/lib.rs
@@ -1,15 +1,20 @@
+use std::{
+ fmt,
+ future::Future,
+ mem,
+ pin::Pin,
+ task::{Context, Poll},
+ time::Duration,
+};
+
+use futures::{future, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, Stream, StreamExt};
+use libp2p_core::{
+ muxing::StreamMuxerExt,
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade},
+ StreamMuxer, UpgradeInfo,
+};
+
use crate::future::{BoxFuture, Either, FutureExt};
-use futures::{future, AsyncRead, AsyncWrite};
-use futures::{AsyncReadExt, Stream};
-use futures::{AsyncWriteExt, StreamExt};
-use libp2p_core::muxing::StreamMuxerExt;
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade};
-use libp2p_core::{StreamMuxer, UpgradeInfo};
-use std::future::Future;
-use std::pin::Pin;
-use std::task::{Context, Poll};
-use std::time::Duration;
-use std::{fmt, mem};
pub async fn connected_muxers_on_memory_ring_buffer() -> (M, M)
where
@@ -41,7 +46,8 @@ where
.unwrap()
}
-/// Verifies that Alice can send a message and immediately close the stream afterwards and Bob can use `read_to_end` to read the entire message.
+/// Verifies that Alice can send a message and immediately close the stream afterwards and Bob can
+/// use `read_to_end` to read the entire message.
pub async fn close_implies_flush(alice: A, bob: B)
where
A: StreamMuxer + Unpin,
@@ -99,7 +105,8 @@ where
.await;
}
-/// Runs the given protocol between the two parties, ensuring commutativity, i.e. either party can be the dialer and listener.
+/// Runs the given protocol between the two parties, ensuring commutativity, i.e. either party can
+/// be the dialer and listener.
async fn run_commutative(
mut alice: A,
mut bob: B,
@@ -120,7 +127,8 @@ async fn run_commutative(
/// Runs a given protocol between the two parties.
///
/// The first party will open a new substream and the second party will wait for this.
-/// The [`StreamMuxer`] is polled until both parties have completed the protocol to ensure that the underlying connection can make progress at all times.
+/// The [`StreamMuxer`] is polled until both parties have completed the protocol to ensure that the
+/// underlying connection can make progress at all times.
async fn run(
dialer: &mut A,
listener: &mut B,
@@ -206,7 +214,7 @@ enum Event {
ProtocolComplete,
}
-impl<'m, M> Stream for Harness<'m, M>
+impl Stream for Harness<'_, M>
where
M: StreamMuxer + Unpin,
{
diff --git a/muxers/yamux/CHANGELOG.md b/muxers/yamux/CHANGELOG.md
index 855b3a33773..ace4c864f63 100644
--- a/muxers/yamux/CHANGELOG.md
+++ b/muxers/yamux/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 0.47.0
+
+
+
## 0.46.0
diff --git a/muxers/yamux/Cargo.toml b/muxers/yamux/Cargo.toml
index 0c52eca3fd4..98beb55982c 100644
--- a/muxers/yamux/Cargo.toml
+++ b/muxers/yamux/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-yamux"
edition = "2021"
rust-version = { workspace = true }
description = "Yamux multiplexing protocol for libp2p"
-version = "0.46.0"
+version = "0.47.0"
authors = ["Parity Technologies "]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
@@ -14,7 +14,7 @@ categories = ["network-programming", "asynchronous"]
either = "1"
futures = { workspace = true }
libp2p-core = { workspace = true }
-thiserror = "1.0"
+thiserror = { workspace = true }
yamux012 = { version = "0.12.1", package = "yamux" }
yamux013 = { version = "0.13.3", package = "yamux" }
tracing = { workspace = true }
diff --git a/muxers/yamux/src/lib.rs b/muxers/yamux/src/lib.rs
index bcfeb62fccf..001eb6b0348 100644
--- a/muxers/yamux/src/lib.rs
+++ b/muxers/yamux/src/lib.rs
@@ -22,17 +22,20 @@
#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
-use either::Either;
-use futures::{prelude::*, ready};
-use libp2p_core::muxing::{StreamMuxer, StreamMuxerEvent};
-use libp2p_core::upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo};
-use std::collections::VecDeque;
-use std::io::{IoSlice, IoSliceMut};
-use std::task::Waker;
use std::{
- io, iter,
+ collections::VecDeque,
+ io,
+ io::{IoSlice, IoSliceMut},
+ iter,
pin::Pin,
- task::{Context, Poll},
+ task::{Context, Poll, Waker},
+};
+
+use either::Either;
+use futures::{prelude::*, ready};
+use libp2p_core::{
+ muxing::{StreamMuxer, StreamMuxerEvent},
+ upgrade::{InboundConnectionUpgrade, OutboundConnectionUpgrade, UpgradeInfo},
};
use thiserror::Error;
@@ -40,10 +43,12 @@ use thiserror::Error;
#[derive(Debug)]
pub struct Muxer {
connection: Either, yamux013::Connection>,
- /// Temporarily buffers inbound streams in case our node is performing backpressure on the remote.
+ /// Temporarily buffers inbound streams in case our node is
+ /// performing backpressure on the remote.
///
- /// The only way how yamux can make progress is by calling [`yamux013::Connection::poll_next_inbound`]. However, the
- /// [`StreamMuxer`] interface is designed to allow a caller to selectively make progress via
+ /// The only way how yamux can make progress is by calling
+ /// [`yamux013::Connection::poll_next_inbound`]. However, the [`StreamMuxer`] interface is
+ /// designed to allow a caller to selectively make progress via
/// [`StreamMuxer::poll_inbound`] and [`StreamMuxer::poll_outbound`] whilst the more general
/// [`StreamMuxer::poll`] is designed to make progress on existing streams etc.
///
@@ -57,7 +62,8 @@ pub struct Muxer {
/// How many streams to buffer before we start resetting them.
///
/// This is equal to the ACK BACKLOG in `rust-yamux`.
-/// Thus, for peers running on a recent version of `rust-libp2p`, we should never need to reset streams because they'll voluntarily stop opening them once they hit the ACK backlog.
+/// Thus, for peers running on a recent version of `rust-libp2p`, we should never need to reset
+/// streams because they'll voluntarily stop opening them once they hit the ACK backlog.
const MAX_BUFFERED_INBOUND_STREAMS: usize = 256;
impl Muxer
diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md
index e171412aa58..e80dc4df437 100644
--- a/protocols/autonat/CHANGELOG.md
+++ b/protocols/autonat/CHANGELOG.md
@@ -1,3 +1,12 @@
+## 0.14.0
+
+- Verify that an incoming AutoNAT dial comes from a connected peer. See [PR 5597](https://github.com/libp2p/rust-libp2p/pull/5597).
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+- Update to `libp2p-request-response` `v0.28.0`.
+
+
+
## 0.13.0
- Due to the refactor of `Transport` it's no longer required to create a seperate transport for
diff --git a/protocols/autonat/Cargo.toml b/protocols/autonat/Cargo.toml
index 2c01d18dceb..f614db56eb1 100644
--- a/protocols/autonat/Cargo.toml
+++ b/protocols/autonat/Cargo.toml
@@ -3,8 +3,12 @@ name = "libp2p-autonat"
edition = "2021"
rust-version = { workspace = true }
description = "NAT and firewall detection for libp2p"
-version = "0.13.0"
-authors = ["David Craven ", "Elena Frank ", "Hannes Furmans "]
+version = "0.14.0"
+authors = [
+ "David Craven ",
+ "Elena Frank ",
+ "Hannes Furmans ",
+]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
keywords = ["peer-to-peer", "libp2p", "networking"]
@@ -14,7 +18,6 @@ categories = ["network-programming", "asynchronous"]
[dependencies]
async-trait = { version = "0.1", optional = true }
asynchronous-codec = { workspace = true }
-bytes = { version = "1", optional = true }
either = { version = "1.9.0", optional = true }
futures = { workspace = true }
futures-bounded = { workspace = true, optional = true }
@@ -29,21 +32,19 @@ tracing = { workspace = true }
quick-protobuf-codec = { workspace = true }
rand = "0.8"
rand_core = { version = "0.6", optional = true }
-thiserror = { version = "1.0.52", optional = true }
-void = { version = "1", optional = true }
+thiserror = { workspace = true, optional = true }
[dev-dependencies]
-tokio = { version = "1", features = ["macros", "rt", "sync"]}
-async-std = { version = "1.10", features = ["attributes"] }
+tokio = { workspace = true, features = ["macros", "rt", "sync"] }
libp2p-swarm-test = { path = "../../swarm-test" }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
libp2p-identify = { workspace = true }
-libp2p-swarm = { workspace = true, features = ["macros"]}
+libp2p-swarm = { workspace = true, features = ["macros"] }
[features]
default = ["v1", "v2"]
v1 = ["dep:libp2p-request-response", "dep:web-time", "dep:async-trait"]
-v2 = ["dep:bytes", "dep:either", "dep:futures-bounded", "dep:thiserror", "dep:void", "dep:rand_core"]
+v2 = ["dep:either", "dep:futures-bounded", "dep:thiserror", "dep:rand_core"]
# Passing arguments to the docsrs builder in order to properly document cfg's.
# More information: https://docs.rs/about/builds#cross-compiling
diff --git a/protocols/autonat/src/v1.rs b/protocols/autonat/src/v1.rs
index c60e4805f40..4de601c5df5 100644
--- a/protocols/autonat/src/v1.rs
+++ b/protocols/autonat/src/v1.rs
@@ -29,6 +29,8 @@
pub(crate) mod behaviour;
pub(crate) mod protocol;
+pub use libp2p_request_response::{InboundFailure, OutboundFailure};
+
pub use self::{
behaviour::{
Behaviour, Config, Event, InboundProbeError, InboundProbeEvent, NatStatus,
@@ -36,7 +38,6 @@ pub use self::{
},
protocol::{ResponseError, DEFAULT_PROTOCOL_NAME},
};
-pub use libp2p_request_response::{InboundFailure, OutboundFailure};
pub(crate) mod proto {
#![allow(unreachable_pub)]
diff --git a/protocols/autonat/src/v1/behaviour.rs b/protocols/autonat/src/v1/behaviour.rs
index 7a717baed8d..24ec1b13be7 100644
--- a/protocols/autonat/src/v1/behaviour.rs
+++ b/protocols/autonat/src/v1/behaviour.rs
@@ -21,15 +21,19 @@
mod as_client;
mod as_server;
-use crate::protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError};
-use crate::DEFAULT_PROTOCOL_NAME;
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ iter,
+ task::{Context, Poll},
+ time::Duration,
+};
+
use as_client::AsClient;
pub use as_client::{OutboundProbeError, OutboundProbeEvent};
use as_server::AsServer;
pub use as_server::{InboundProbeError, InboundProbeEvent};
use futures_timer::Delay;
-use libp2p_core::transport::PortUse;
-use libp2p_core::{multiaddr::Protocol, ConnectedPoint, Endpoint, Multiaddr};
+use libp2p_core::{multiaddr::Protocol, transport::PortUse, ConnectedPoint, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_request_response::{
self as request_response, InboundRequestId, OutboundRequestId, ProtocolSupport, ResponseChannel,
@@ -39,14 +43,13 @@ use libp2p_swarm::{
ConnectionDenied, ConnectionId, ListenAddresses, NetworkBehaviour, THandler, THandlerInEvent,
THandlerOutEvent, ToSwarm,
};
-use std::{
- collections::{HashMap, HashSet, VecDeque},
- iter,
- task::{Context, Poll},
- time::Duration,
-};
use web_time::Instant;
+use crate::{
+ protocol::{AutoNatCodec, DialRequest, DialResponse, ResponseError},
+ DEFAULT_PROTOCOL_NAME,
+};
+
/// Config for the [`Behaviour`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
@@ -148,17 +151,18 @@ pub enum Event {
/// [`NetworkBehaviour`] for AutoNAT.
///
-/// The behaviour frequently runs probes to determine whether the local peer is behind NAT and/ or a firewall, or
-/// publicly reachable.
-/// In a probe, a dial-back request is sent to a peer that is randomly selected from the list of fixed servers and
-/// connected peers. Upon receiving a dial-back request, the remote tries to dial the included addresses. When a
-/// first address was successfully dialed, a status Ok will be send back together with the dialed address. If no address
-/// can be reached a dial-error is send back.
+/// The behaviour frequently runs probes to determine whether the local peer is behind NAT and/ or a
+/// firewall, or publicly reachable.
+/// In a probe, a dial-back request is sent to a peer that is randomly selected from the list of
+/// fixed servers and connected peers. Upon receiving a dial-back request, the remote tries to dial
+/// the included addresses. When a first address was successfully dialed, a status Ok will be send
+/// back together with the dialed address. If no address can be reached a dial-error is send back.
/// Based on the received response, the sender assumes themselves to be public or private.
-/// The status is retried in a frequency of [`Config::retry_interval`] or [`Config::retry_interval`], depending on whether
-/// enough confidence in the assumed NAT status was reached or not.
-/// The confidence increases each time a probe confirms the assumed status, and decreases if a different status is reported.
-/// If the confidence is 0, the status is flipped and the Behaviour will report the new status in an `OutEvent`.
+/// The status is retried in a frequency of [`Config::retry_interval`] or
+/// [`Config::retry_interval`], depending on whether enough confidence in the assumed NAT status was
+/// reached or not. The confidence increases each time a probe confirms the assumed status, and
+/// decreases if a different status is reported. If the confidence is 0, the status is flipped and
+/// the Behaviour will report the new status in an `OutEvent`.
pub struct Behaviour {
// Local peer id
local_peer_id: PeerId,
@@ -195,11 +199,12 @@ pub struct Behaviour {
ongoing_outbound: HashMap,
// Connected peers with the observed address of each connection.
- // If the endpoint of a connection is relayed or not global (in case of Config::only_global_ips),
- // the observed address is `None`.
+ // If the endpoint of a connection is relayed or not global (in case of
+ // Config::only_global_ips), the observed address is `None`.
connected: HashMap>>,
- // Used servers in recent outbound probes that are throttled through Config::throttle_server_period.
+ // Used servers in recent outbound probes that are throttled through
+ // Config::throttle_server_period.
throttled_servers: Vec<(PeerId, Instant)>,
// Recent probes done for clients
@@ -264,8 +269,8 @@ impl Behaviour {
}
/// Add a peer to the list over servers that may be used for probes.
- /// These peers are used for dial-request even if they are currently not connection, in which case a connection will be
- /// establish before sending the dial-request.
+ /// These peers are used for dial-request even if they are currently not connection, in which
+ /// case a connection will be establish before sending the dial-request.
pub fn add_server(&mut self, peer: PeerId, address: Option) {
self.servers.insert(peer);
if let Some(addr) = address {
@@ -564,7 +569,8 @@ impl NetworkBehaviour for Behaviour {
type Action = ToSwarm<::ToSwarm, THandlerInEvent>;
-// Trait implemented for `AsClient` and `AsServer` to handle events from the inner [`request_response::Behaviour`] Protocol.
+// Trait implemented for `AsClient` and `AsServer` to handle events from the inner
+// [`request_response::Behaviour`] Protocol.
trait HandleInnerEvent {
fn handle_event(
&mut self,
@@ -671,7 +677,8 @@ impl GlobalIp for std::net::Ipv6Addr {
// Variation of unstable method [`std::net::Ipv6Addr::multicast_scope`] that instead of the
// `Ipv6MulticastScope` just returns if the scope is global or not.
- // Equivalent to `Ipv6Addr::multicast_scope(..).map(|scope| matches!(scope, Ipv6MulticastScope::Global))`.
+ // Equivalent to `Ipv6Addr::multicast_scope(..).map(|scope| matches!(scope,
+ // Ipv6MulticastScope::Global))`.
fn is_multicast_scope_global(addr: &std::net::Ipv6Addr) -> Option {
match addr.segments()[0] & 0x000f {
14 => Some(true), // Global multicast scope.
diff --git a/protocols/autonat/src/v1/behaviour/as_client.rs b/protocols/autonat/src/v1/behaviour/as_client.rs
index 8960163ccb3..ca8daf6e1ac 100644
--- a/protocols/autonat/src/v1/behaviour/as_client.rs
+++ b/protocols/autonat/src/v1/behaviour/as_client.rs
@@ -18,12 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::ResponseError;
-
-use super::{
- Action, AutoNatCodec, Config, DialRequest, DialResponse, Event, HandleInnerEvent, NatStatus,
- ProbeId,
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ task::{Context, Poll},
+ time::Duration,
};
+
use futures::FutureExt;
use futures_timer::Delay;
use libp2p_core::Multiaddr;
@@ -31,13 +31,14 @@ use libp2p_identity::PeerId;
use libp2p_request_response::{self as request_response, OutboundFailure, OutboundRequestId};
use libp2p_swarm::{ConnectionId, ListenAddresses, ToSwarm};
use rand::{seq::SliceRandom, thread_rng};
-use std::{
- collections::{HashMap, HashSet, VecDeque},
- task::{Context, Poll},
- time::Duration,
-};
use web_time::Instant;
+use super::{
+ Action, AutoNatCodec, Config, DialRequest, DialResponse, Event, HandleInnerEvent, NatStatus,
+ ProbeId,
+};
+use crate::ResponseError;
+
/// Outbound probe failed or was aborted.
#[derive(Debug)]
pub enum OutboundProbeError {
@@ -98,7 +99,7 @@ pub(crate) struct AsClient<'a> {
pub(crate) other_candidates: &'a HashSet,
}
-impl<'a> HandleInnerEvent for AsClient<'a> {
+impl HandleInnerEvent for AsClient<'_> {
fn handle_event(
&mut self,
event: request_response::Event,
@@ -111,6 +112,7 @@ impl<'a> HandleInnerEvent for AsClient<'a> {
request_id,
response,
},
+ ..
} => {
tracing::debug!(?response, "Outbound dial-back request returned response");
@@ -153,6 +155,7 @@ impl<'a> HandleInnerEvent for AsClient<'a> {
peer,
error,
request_id,
+ ..
} => {
tracing::debug!(
%peer,
@@ -179,7 +182,7 @@ impl<'a> HandleInnerEvent for AsClient<'a> {
}
}
-impl<'a> AsClient<'a> {
+impl AsClient<'_> {
pub(crate) fn poll_auto_probe(&mut self, cx: &mut Context<'_>) -> Poll {
match self.schedule_probe.poll_unpin(cx) {
Poll::Ready(()) => {
diff --git a/protocols/autonat/src/v1/behaviour/as_server.rs b/protocols/autonat/src/v1/behaviour/as_server.rs
index 3ecdd3ac26e..32b4120c552 100644
--- a/protocols/autonat/src/v1/behaviour/as_server.rs
+++ b/protocols/autonat/src/v1/behaviour/as_server.rs
@@ -17,10 +17,11 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use super::{
- Action, AutoNatCodec, Config, DialRequest, DialResponse, Event, HandleInnerEvent, ProbeId,
- ResponseError,
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ num::NonZeroU8,
};
+
use libp2p_core::{multiaddr::Protocol, Multiaddr};
use libp2p_identity::PeerId;
use libp2p_request_response::{
@@ -30,12 +31,13 @@ use libp2p_swarm::{
dial_opts::{DialOpts, PeerCondition},
ConnectionId, DialError, ToSwarm,
};
-use std::{
- collections::{HashMap, HashSet, VecDeque},
- num::NonZeroU8,
-};
use web_time::Instant;
+use super::{
+ Action, AutoNatCodec, Config, DialRequest, DialResponse, Event, HandleInnerEvent, ProbeId,
+ ResponseError,
+};
+
/// Inbound probe failed.
#[derive(Debug)]
pub enum InboundProbeError {
@@ -91,7 +93,7 @@ pub(crate) struct AsServer<'a> {
>,
}
-impl<'a> HandleInnerEvent for AsServer<'a> {
+impl HandleInnerEvent for AsServer<'_> {
fn handle_event(
&mut self,
event: request_response::Event,
@@ -105,8 +107,24 @@ impl<'a> HandleInnerEvent for AsServer<'a> {
request,
channel,
},
+ ..
} => {
let probe_id = self.probe_id.next();
+ if !self.connected.contains_key(&peer) {
+ tracing::debug!(
+ %peer,
+ "Reject inbound dial request from peer since it is not connected"
+ );
+
+ return VecDeque::from([ToSwarm::GenerateEvent(Event::InboundProbe(
+ InboundProbeEvent::Error {
+ probe_id,
+ peer,
+ error: InboundProbeError::Response(ResponseError::DialRefused),
+ },
+ ))]);
+ }
+
match self.resolve_inbound_request(peer, request) {
Ok(addrs) => {
tracing::debug!(
@@ -166,6 +184,7 @@ impl<'a> HandleInnerEvent for AsServer<'a> {
peer,
error,
request_id,
+ ..
} => {
tracing::debug!(
%peer,
@@ -193,7 +212,7 @@ impl<'a> HandleInnerEvent for AsServer<'a> {
}
}
-impl<'a> AsServer<'a> {
+impl AsServer<'_> {
pub(crate) fn on_outbound_connection(
&mut self,
peer: &PeerId,
@@ -364,10 +383,10 @@ impl<'a> AsServer<'a> {
#[cfg(test)]
mod test {
- use super::*;
-
use std::net::Ipv4Addr;
+ use super::*;
+
fn random_ip<'a>() -> Protocol<'a> {
Protocol::Ip4(Ipv4Addr::new(
rand::random(),
diff --git a/protocols/autonat/src/v1/protocol.rs b/protocols/autonat/src/v1/protocol.rs
index 2ce538fddf4..6aa0c99167b 100644
--- a/protocols/autonat/src/v1/protocol.rs
+++ b/protocols/autonat/src/v1/protocol.rs
@@ -18,16 +18,20 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use crate::proto;
+use std::io;
+
use async_trait::async_trait;
use asynchronous_codec::{FramedRead, FramedWrite};
-use futures::io::{AsyncRead, AsyncWrite};
-use futures::{SinkExt, StreamExt};
+use futures::{
+ io::{AsyncRead, AsyncWrite},
+ SinkExt, StreamExt,
+};
use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use libp2p_request_response::{self as request_response};
use libp2p_swarm::StreamProtocol;
-use std::io;
+
+use crate::proto;
/// The protocol name used for negotiating with multistream-select.
pub const DEFAULT_PROTOCOL_NAME: StreamProtocol = StreamProtocol::new("/libp2p/autonat/1.0.0");
diff --git a/protocols/autonat/src/v2.rs b/protocols/autonat/src/v2.rs
index cdc807ea303..94decf50a55 100644
--- a/protocols/autonat/src/v2.rs
+++ b/protocols/autonat/src/v2.rs
@@ -4,17 +4,17 @@
//!
//! The new version fixes the issues of the first version:
//! - The server now always dials back over a newly allocated port. This greatly reduces the risk of
-//! false positives that often occurred in the first version, when the clinet-server connection
-//! occurred over a hole-punched port.
+//! false positives that often occurred in the first version, when the clinet-server connection
+//! occurred over a hole-punched port.
//! - The server protects against DoS attacks by requiring the client to send more data to the
-//! server then the dial back puts on the client, thus making the protocol unatractive for an
-//! attacker.
+//! server then the dial back puts on the client, thus making the protocol unatractive for an
+//! attacker.
//!
-//! The protocol is seperated into two parts:
+//! The protocol is separated into two parts:
//! - The client part, which is implemented in the `client` module. (The client is the party that
-//! wants to check if it is reachable from the outside.)
+//! wants to check if it is reachable from the outside.)
//! - The server part, which is implemented in the `server` module. (The server is the party
-//! performing reachability checks on behalf of the client.)
+//! performing reachability checks on behalf of the client.)
//!
//! The two can be used together.
diff --git a/protocols/autonat/src/v2/client.rs b/protocols/autonat/src/v2/client.rs
index d3272512f35..11ddb792839 100644
--- a/protocols/autonat/src/v2/client.rs
+++ b/protocols/autonat/src/v2/client.rs
@@ -1,5 +1,4 @@
mod behaviour;
mod handler;
-pub use behaviour::Event;
-pub use behaviour::{Behaviour, Config};
+pub use behaviour::{Behaviour, Config, Event};
diff --git a/protocols/autonat/src/v2/client/behaviour.rs b/protocols/autonat/src/v2/client/behaviour.rs
index 97509c05443..8e238fc9be4 100644
--- a/protocols/autonat/src/v2/client/behaviour.rs
+++ b/protocols/autonat/src/v2/client/behaviour.rs
@@ -1,5 +1,6 @@
use std::{
collections::{HashMap, VecDeque},
+ fmt::{Debug, Display, Formatter},
task::{Context, Poll},
time::Duration,
};
@@ -15,14 +16,12 @@ use libp2p_swarm::{
};
use rand::prelude::*;
use rand_core::OsRng;
-use std::fmt::{Debug, Display, Formatter};
-
-use crate::v2::{protocol::DialRequest, Nonce};
use super::handler::{
dial_back::{self, IncomingNonce},
dial_request,
};
+use crate::v2::{protocol::DialRequest, Nonce};
#[derive(Debug, Clone, Copy)]
pub struct Config {
@@ -281,10 +280,12 @@ where
}
}
- /// Issues dial requests to random AutoNAT servers for the most frequently reported, untested candidates.
+ /// Issues dial requests to random AutoNAT servers for the most frequently reported, untested
+ /// candidates.
///
/// In the current implementation, we only send a single address to each AutoNAT server.
- /// This spreads our candidates out across all servers we are connected to which should give us pretty fast feedback on all of them.
+ /// This spreads our candidates out across all servers we are connected to which should give us
+ /// pretty fast feedback on all of them.
fn issue_dial_requests_for_untested_candidates(&mut self) {
for addr in self.untested_candidates() {
let Some((conn_id, peer_id)) = self.random_autonat_server() else {
@@ -311,7 +312,8 @@ where
/// Returns all untested candidates, sorted by the frequency they were reported at.
///
- /// More frequently reported candidates are considered to more likely be external addresses and thus tested first.
+ /// More frequently reported candidates are considered to more likely be external addresses and
+ /// thus tested first.
fn untested_candidates(&self) -> impl Iterator- {
let mut entries = self
.address_candidates
@@ -333,7 +335,8 @@ where
.map(|(addr, _)| addr)
}
- /// Chooses an active connection to one of our peers that reported support for the [`DIAL_REQUEST_PROTOCOL`](crate::v2::DIAL_REQUEST_PROTOCOL) protocol.
+ /// Chooses an active connection to one of our peers that reported support for the
+ /// [`DIAL_REQUEST_PROTOCOL`](crate::v2::DIAL_REQUEST_PROTOCOL) protocol.
fn random_autonat_server(&mut self) -> Option<(ConnectionId, PeerId)> {
let (conn_id, info) = self
.peer_info
diff --git a/protocols/autonat/src/v2/client/handler/dial_back.rs b/protocols/autonat/src/v2/client/handler/dial_back.rs
index b94580e69ba..7cdf194343a 100644
--- a/protocols/autonat/src/v2/client/handler/dial_back.rs
+++ b/protocols/autonat/src/v2/client/handler/dial_back.rs
@@ -1,4 +1,5 @@
use std::{
+ convert::Infallible,
io,
task::{Context, Poll},
time::Duration,
@@ -11,7 +12,6 @@ use libp2p_swarm::{
handler::{ConnectionEvent, FullyNegotiatedInbound, ListenUpgradeError},
ConnectionHandler, ConnectionHandlerEvent, StreamProtocol, SubstreamProtocol,
};
-use void::Void;
use crate::v2::{protocol, Nonce, DIAL_BACK_PROTOCOL};
@@ -28,23 +28,21 @@ impl Handler {
}
impl ConnectionHandler for Handler {
- type FromBehaviour = Void;
+ type FromBehaviour = Infallible;
type ToBehaviour = IncomingNonce;
type InboundProtocol = ReadyUpgrade;
type OutboundProtocol = DeniedUpgrade;
type InboundOpenInfo = ();
type OutboundOpenInfo = ();
- fn listen_protocol(&self) -> SubstreamProtocol {
+ fn listen_protocol(&self) -> SubstreamProtocol {
SubstreamProtocol::new(ReadyUpgrade::new(DIAL_BACK_PROTOCOL), ())
}
fn poll(
&mut self,
cx: &mut Context<'_>,
- ) -> Poll<
- ConnectionHandlerEvent,
- > {
+ ) -> Poll> {
loop {
match self.inbound.poll_next_unpin(cx) {
Poll::Pending => return Poll::Pending,
@@ -68,12 +66,7 @@ impl ConnectionHandler for Handler {
fn on_connection_event(
&mut self,
- event: ConnectionEvent<
- Self::InboundProtocol,
- Self::OutboundProtocol,
- Self::InboundOpenInfo,
- Self::OutboundOpenInfo,
- >,
+ event: ConnectionEvent,
) {
match event {
ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound {
@@ -83,8 +76,10 @@ impl ConnectionHandler for Handler {
tracing::warn!("Dial back request dropped, too many requests in flight");
}
}
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error, .. }) => {
- void::unreachable(error);
+ libp2p_core::util::unreachable(error);
}
_ => {}
}
diff --git a/protocols/autonat/src/v2/client/handler/dial_request.rs b/protocols/autonat/src/v2/client/handler/dial_request.rs
index 9d2df8ee6b4..61f564505eb 100644
--- a/protocols/autonat/src/v2/client/handler/dial_request.rs
+++ b/protocols/autonat/src/v2/client/handler/dial_request.rs
@@ -1,10 +1,18 @@
+use std::{
+ collections::VecDeque,
+ convert::Infallible,
+ io,
+ iter::{once, repeat},
+ task::{Context, Poll},
+ time::Duration,
+};
+
use futures::{channel::oneshot, AsyncWrite};
use futures_bounded::FuturesMap;
use libp2p_core::{
upgrade::{DeniedUpgrade, ReadyUpgrade},
Multiaddr,
};
-
use libp2p_swarm::{
handler::{
ConnectionEvent, DialUpgradeError, FullyNegotiatedOutbound, OutboundUpgradeSend,
@@ -13,13 +21,6 @@ use libp2p_swarm::{
ConnectionHandler, ConnectionHandlerEvent, Stream, StreamProtocol, StreamUpgradeError,
SubstreamProtocol,
};
-use std::{
- collections::VecDeque,
- io,
- iter::{once, repeat},
- task::{Context, Poll},
- time::Duration,
-};
use crate::v2::{
generated::structs::{mod_DialResponse::ResponseStatus, DialStatus},
@@ -71,7 +72,7 @@ pub struct Handler {
queued_events: VecDeque<
ConnectionHandlerEvent<
::OutboundProtocol,
- ::OutboundOpenInfo,
+ (),
::ToBehaviour,
>,
>,
@@ -120,16 +121,14 @@ impl ConnectionHandler for Handler {
type InboundOpenInfo = ();
type OutboundOpenInfo = ();
- fn listen_protocol(&self) -> SubstreamProtocol {
+ fn listen_protocol(&self) -> SubstreamProtocol {
SubstreamProtocol::new(DeniedUpgrade, ())
}
fn poll(
&mut self,
cx: &mut Context<'_>,
- ) -> Poll<
- ConnectionHandlerEvent,
- > {
+ ) -> Poll> {
if let Some(event) = self.queued_events.pop_front() {
return Poll::Ready(event);
}
@@ -160,12 +159,7 @@ impl ConnectionHandler for Handler {
fn on_connection_event(
&mut self,
- event: ConnectionEvent<
- Self::InboundProtocol,
- Self::OutboundProtocol,
- Self::InboundOpenInfo,
- Self::OutboundOpenInfo,
- >,
+ event: ConnectionEvent,
) {
match event {
ConnectionEvent::DialUpgradeError(DialUpgradeError { error, .. }) => {
@@ -208,7 +202,7 @@ impl ConnectionHandler for Handler {
async fn start_stream_handle(
req: DialRequest,
- stream_recv: oneshot::Receiver>>,
+ stream_recv: oneshot::Receiver>>,
) -> Result<(Multiaddr, usize), Error> {
let stream = stream_recv
.await
@@ -216,7 +210,9 @@ async fn start_stream_handle(
.map_err(|e| match e {
StreamUpgradeError::NegotiationFailed => Error::UnsupportedProtocol,
StreamUpgradeError::Timeout => Error::Io(io::ErrorKind::TimedOut.into()),
- StreamUpgradeError::Apply(v) => void::unreachable(v),
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ StreamUpgradeError::Apply(v) => libp2p_core::util::unreachable(v),
StreamUpgradeError::Io(e) => Error::Io(e),
})?;
@@ -258,7 +254,9 @@ async fn start_stream_handle(
Ok(_) => {}
Err(err) => {
if err.kind() == io::ErrorKind::ConnectionReset {
- // The AutoNAT server may have already closed the stream (this is normal because the probe is finished), in this case we have this error:
+ // The AutoNAT server may have already closed the stream
+ // (this is normal because the probe is finished),
+ // in this case we have this error:
// Err(Custom { kind: ConnectionReset, error: Stopped(0) })
// so we silently ignore this error
} else {
diff --git a/protocols/autonat/src/v2/protocol.rs b/protocols/autonat/src/v2/protocol.rs
index 4077fd65f5d..70f9f8c37af 100644
--- a/protocols/autonat/src/v2/protocol.rs
+++ b/protocols/autonat/src/v2/protocol.rs
@@ -1,13 +1,10 @@
// change to quick-protobuf-codec
-use std::io;
-use std::io::ErrorKind;
+use std::{io, io::ErrorKind};
use asynchronous_codec::{Framed, FramedRead, FramedWrite};
-
use futures::{AsyncRead, AsyncWrite, SinkExt, StreamExt};
use libp2p_core::Multiaddr;
-
use quick_protobuf_codec::Codec;
use rand::Rng;
@@ -103,7 +100,10 @@ impl From for proto::Message {
);
proto::Message {
msg: proto::mod_Message::OneOfmsg::dialDataResponse(proto::DialDataResponse {
- data: vec![0; val.data_count], // One could use Cow::Borrowed here, but it will require a modification of the generated code and that will fail the CI
+ // One could use Cow::Borrowed here, but it will
+ // require a modification of the generated code
+ // and that will fail the CI
+ data: vec![0; val.data_count],
}),
}
}
diff --git a/protocols/autonat/src/v2/server.rs b/protocols/autonat/src/v2/server.rs
index 25819307784..cd9b1e46b18 100644
--- a/protocols/autonat/src/v2/server.rs
+++ b/protocols/autonat/src/v2/server.rs
@@ -1,5 +1,4 @@
mod behaviour;
mod handler;
-pub use behaviour::Behaviour;
-pub use behaviour::Event;
+pub use behaviour::{Behaviour, Event};
diff --git a/protocols/autonat/src/v2/server/behaviour.rs b/protocols/autonat/src/v2/server/behaviour.rs
index 5f7b21d165b..125955cb53a 100644
--- a/protocols/autonat/src/v2/server/behaviour.rs
+++ b/protocols/autonat/src/v2/server/behaviour.rs
@@ -4,20 +4,19 @@ use std::{
task::{Context, Poll},
};
-use crate::v2::server::handler::dial_request::DialBackStatus;
use either::Either;
use libp2p_core::{transport::PortUse, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
-use libp2p_swarm::dial_opts::PeerCondition;
use libp2p_swarm::{
- dial_opts::DialOpts, dummy, ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure,
- FromSwarm, NetworkBehaviour, ToSwarm,
+ dial_opts::{DialOpts, PeerCondition},
+ dummy, ConnectionDenied, ConnectionHandler, ConnectionId, DialFailure, FromSwarm,
+ NetworkBehaviour, ToSwarm,
};
use rand_core::{OsRng, RngCore};
use crate::v2::server::handler::{
dial_back,
- dial_request::{self, DialBackCommand},
+ dial_request::{self, DialBackCommand, DialBackStatus},
Handler,
};
@@ -112,7 +111,9 @@ where
Either::Left(Either::Left(Err(e))) => {
tracing::debug!("dial back error: {e:?}");
}
- Either::Left(Either::Right(v)) => void::unreachable(v),
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
+ Either::Left(Either::Right(v)) => libp2p_core::util::unreachable(v),
Either::Right(Either::Left(cmd)) => {
let addr = cmd.addr.clone();
let opts = DialOpts::peer_id(peer_id)
diff --git a/protocols/autonat/src/v2/server/handler/dial_back.rs b/protocols/autonat/src/v2/server/handler/dial_back.rs
index 3cacd4ff32b..8adb33509ef 100644
--- a/protocols/autonat/src/v2/server/handler/dial_back.rs
+++ b/protocols/autonat/src/v2/server/handler/dial_back.rs
@@ -14,13 +14,12 @@ use libp2p_swarm::{
SubstreamProtocol,
};
+use super::dial_request::{DialBackCommand, DialBackStatus as DialBackRes};
use crate::v2::{
protocol::{dial_back, recv_dial_back_response},
DIAL_BACK_PROTOCOL,
};
-use super::dial_request::{DialBackCommand, DialBackStatus as DialBackRes};
-
pub(crate) type ToBehaviour = io::Result<()>;
pub struct Handler {
@@ -47,16 +46,14 @@ impl ConnectionHandler for Handler {
type InboundOpenInfo = ();
type OutboundOpenInfo = ();
- fn listen_protocol(&self) -> SubstreamProtocol {
+ fn listen_protocol(&self) -> SubstreamProtocol {
SubstreamProtocol::new(DeniedUpgrade, ())
}
fn poll(
&mut self,
cx: &mut Context<'_>,
- ) -> Poll<
- ConnectionHandlerEvent,
- > {
+ ) -> Poll> {
if let Poll::Ready(result) = self.outbound.poll_unpin(cx) {
return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(
result
@@ -77,12 +74,7 @@ impl ConnectionHandler for Handler {
fn on_connection_event(
&mut self,
- event: ConnectionEvent<
- Self::InboundProtocol,
- Self::OutboundProtocol,
- Self::InboundOpenInfo,
- Self::OutboundOpenInfo,
- >,
+ event: ConnectionEvent,
) {
match event {
ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound {
diff --git a/protocols/autonat/src/v2/server/handler/dial_request.rs b/protocols/autonat/src/v2/server/handler/dial_request.rs
index 9a3729d4ccf..22cab2b9cab 100644
--- a/protocols/autonat/src/v2/server/handler/dial_request.rs
+++ b/protocols/autonat/src/v2/server/handler/dial_request.rs
@@ -1,4 +1,5 @@
use std::{
+ convert::Infallible,
io,
task::{Context, Poll},
time::Duration,
@@ -73,23 +74,21 @@ impl ConnectionHandler for Handler
where
R: RngCore + Send + Clone + 'static,
{
- type FromBehaviour = void::Void;
+ type FromBehaviour = Infallible;
type ToBehaviour = Either;
type InboundProtocol = ReadyUpgrade;
type OutboundProtocol = DeniedUpgrade;
type InboundOpenInfo = ();
type OutboundOpenInfo = ();
- fn listen_protocol(&self) -> SubstreamProtocol {
+ fn listen_protocol(&self) -> SubstreamProtocol {
SubstreamProtocol::new(ReadyUpgrade::new(DIAL_REQUEST_PROTOCOL), ())
}
fn poll(
&mut self,
cx: &mut Context<'_>,
- ) -> Poll<
- ConnectionHandlerEvent,
- > {
+ ) -> Poll> {
loop {
match self.inbound.poll_unpin(cx) {
Poll::Ready(Ok(event)) => {
@@ -116,12 +115,7 @@ where
fn on_connection_event(
&mut self,
- event: ConnectionEvent<
- Self::InboundProtocol,
- Self::OutboundProtocol,
- Self::InboundOpenInfo,
- Self::OutboundOpenInfo,
- >,
+ event: ConnectionEvent,
) {
match event {
ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound {
@@ -143,6 +137,8 @@ where
);
}
}
+ // TODO: remove when Rust 1.82 is MSRV
+ #[allow(unreachable_patterns)]
ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error, .. }) => {
tracing::debug!("inbound request failed: {:?}", error);
}
diff --git a/protocols/autonat/tests/autonatv2.rs b/protocols/autonat/tests/autonatv2.rs
index abd0c4bd8eb..49866a9adb5 100644
--- a/protocols/autonat/tests/autonatv2.rs
+++ b/protocols/autonat/tests/autonatv2.rs
@@ -1,14 +1,15 @@
-use libp2p_autonat::v2::client::{self, Config};
-use libp2p_autonat::v2::server;
-use libp2p_core::transport::TransportError;
-use libp2p_core::Multiaddr;
+use std::{sync::Arc, time::Duration};
+
+use libp2p_autonat::v2::{
+ client::{self, Config},
+ server,
+};
+use libp2p_core::{multiaddr::Protocol, transport::TransportError, Multiaddr};
use libp2p_swarm::{
DialError, FromSwarm, NetworkBehaviour, NewExternalAddrCandidate, Swarm, SwarmEvent,
};
use libp2p_swarm_test::SwarmExt;
use rand_core::OsRng;
-use std::sync::Arc;
-use std::time::Duration;
use tokio::sync::oneshot;
use tracing_subscriber::EnvFilter;
@@ -21,17 +22,10 @@ async fn confirm_successful() {
let cor_server_peer = *alice.local_peer_id();
let cor_client_peer = *bob.local_peer_id();
- let bob_external_addrs = Arc::new(bob.external_addresses().cloned().collect::>());
- let alice_bob_external_addrs = bob_external_addrs.clone();
+ let bob_tcp_listeners = Arc::new(tcp_listeners(&bob));
+ let alice_bob_tcp_listeners = bob_tcp_listeners.clone();
let alice_task = async {
- let _ = alice
- .wait(|event| match event {
- SwarmEvent::NewExternalAddrCandidate { .. } => Some(()),
- _ => None,
- })
- .await;
-
let (dialed_peer_id, dialed_connection_id) = alice
.wait(|event| match event {
SwarmEvent::Dialing {
@@ -76,10 +70,10 @@ async fn confirm_successful() {
})
.await;
- assert_eq!(tested_addr, bob_external_addrs.first().cloned().unwrap());
+ assert_eq!(tested_addr, bob_tcp_listeners.first().cloned().unwrap());
assert_eq!(data_amount, 0);
assert_eq!(client, cor_client_peer);
- assert_eq!(&all_addrs[..], &bob_external_addrs[..]);
+ assert_eq!(&all_addrs[..], &bob_tcp_listeners[..]);
assert!(result.is_ok(), "Result: {result:?}");
};
@@ -122,7 +116,7 @@ async fn confirm_successful() {
.await;
assert_eq!(
tested_addr,
- alice_bob_external_addrs.first().cloned().unwrap()
+ alice_bob_tcp_listeners.first().cloned().unwrap()
);
assert_eq!(bytes_sent, 0);
assert_eq!(server, cor_server_peer);
@@ -238,87 +232,84 @@ async fn dial_back_to_non_libp2p() {
let (mut alice, mut bob) = bootstrap().await;
let alice_peer_id = *alice.local_peer_id();
- for addr_str in ["/ip4/169.150.247.38/tcp/32", "/ip6/::1/tcp/1000"] {
- let addr: Multiaddr = addr_str.parse().unwrap();
- let bob_addr = addr.clone();
- bob.behaviour_mut()
- .autonat
- .on_swarm_event(FromSwarm::NewExternalAddrCandidate(
- NewExternalAddrCandidate { addr: &addr },
- ));
-
- let alice_task = async {
- let (alice_dialing_peer, alice_conn_id) = alice
- .wait(|event| match event {
- SwarmEvent::Dialing {
- peer_id,
- connection_id,
- } => peer_id.map(|p| (p, connection_id)),
- _ => None,
- })
- .await;
- let mut outgoing_conn_error = alice
- .wait(|event| match event {
- SwarmEvent::OutgoingConnectionError {
- connection_id,
- peer_id: Some(peer_id),
- error: DialError::Transport(peers),
- } if connection_id == alice_conn_id && peer_id == alice_dialing_peer => {
- Some(peers)
- }
- _ => None,
- })
- .await;
-
- if let Some((multiaddr, TransportError::Other(o))) = outgoing_conn_error.pop() {
- assert_eq!(
- multiaddr,
- addr.clone().with_p2p(alice_dialing_peer).unwrap()
- );
- let error_string = o.to_string();
- assert!(
- error_string.contains("Connection refused"),
- "Correct error string: {error_string} for {addr_str}"
- );
- } else {
- panic!("No outgoing connection errors");
- }
+ let addr_str = "/ip6/::1/tcp/1000";
+ let addr: Multiaddr = addr_str.parse().unwrap();
+ let bob_addr = addr.clone();
+ bob.behaviour_mut()
+ .autonat
+ .on_swarm_event(FromSwarm::NewExternalAddrCandidate(
+ NewExternalAddrCandidate { addr: &addr },
+ ));
- alice
- .wait(|event| match event {
- SwarmEvent::Behaviour(CombinedServerEvent::Autonat(server::Event {
- all_addrs,
- tested_addr,
- client,
- data_amount,
- result: Ok(()),
- })) if all_addrs == vec![addr.clone()]
- && tested_addr == addr
- && alice_dialing_peer == client =>
- {
- Some(data_amount)
- }
- _ => None,
- })
- .await
- };
- let bob_task = async {
- bob.wait(|event| match event {
- SwarmEvent::Behaviour(CombinedClientEvent::Autonat(client::Event {
+ let alice_task = async {
+ let (alice_dialing_peer, alice_conn_id) = alice
+ .wait(|event| match event {
+ SwarmEvent::Dialing {
+ peer_id,
+ connection_id,
+ } => peer_id.map(|p| (p, connection_id)),
+ _ => None,
+ })
+ .await;
+ let mut outgoing_conn_error = alice
+ .wait(|event| match event {
+ SwarmEvent::OutgoingConnectionError {
+ connection_id,
+ peer_id: Some(peer_id),
+ error: DialError::Transport(peers),
+ } if connection_id == alice_conn_id && peer_id == alice_dialing_peer => Some(peers),
+ _ => None,
+ })
+ .await;
+
+ if let Some((multiaddr, TransportError::Other(o))) = outgoing_conn_error.pop() {
+ assert_eq!(
+ multiaddr,
+ addr.clone().with_p2p(alice_dialing_peer).unwrap()
+ );
+ let error_string = o.to_string();
+ assert!(
+ error_string.contains("Connection refused"),
+ "Correct error string: {error_string} for {addr_str}"
+ );
+ } else {
+ panic!("No outgoing connection errors");
+ }
+
+ alice
+ .wait(|event| match event {
+ SwarmEvent::Behaviour(CombinedServerEvent::Autonat(server::Event {
+ all_addrs,
tested_addr,
- bytes_sent,
- server,
- result: Err(_),
- })) if tested_addr == bob_addr && server == alice_peer_id => Some(bytes_sent),
+ client,
+ data_amount,
+ result: Ok(()),
+ })) if all_addrs == vec![addr.clone()]
+ && tested_addr == addr
+ && alice_dialing_peer == client =>
+ {
+ Some(data_amount)
+ }
_ => None,
})
.await
- };
+ };
+ let bob_task = async {
+ bob.wait(|event| match event {
+ SwarmEvent::Behaviour(CombinedClientEvent::Autonat(client::Event {
+ tested_addr,
+ bytes_sent,
+ server,
+ result: Err(_),
+ })) if tested_addr == bob_addr && server == alice_peer_id => Some(bytes_sent),
+ _ => None,
+ })
+ .await
+ };
- let (alice_bytes_sent, bob_bytes_sent) = tokio::join!(alice_task, bob_task);
- assert_eq!(alice_bytes_sent, bob_bytes_sent);
- bob.behaviour_mut().autonat.validate_addr(&addr);
- }
+ let (alice_bytes_sent, bob_bytes_sent) = tokio::join!(alice_task, bob_task);
+ assert_eq!(alice_bytes_sent, bob_bytes_sent);
+ bob.behaviour_mut().autonat.validate_addr(&addr);
}
#[tokio::test]
@@ -446,7 +437,7 @@ async fn new_client() -> Swarm {
identity.public().clone(),
)),
});
- node.listen().with_tcp_addr_external().await;
+ node.listen().await;
node
}
@@ -490,13 +481,6 @@ async fn bootstrap() -> (Swarm, Swarm) {
let cor_client_peer = *bob.local_peer_id();
let alice_task = async {
- let _ = alice
- .wait(|event| match event {
- SwarmEvent::NewExternalAddrCandidate { .. } => Some(()),
- _ => None,
- })
- .await;
-
let (dialed_peer_id, dialed_connection_id) = alice
.wait(|event| match event {
SwarmEvent::Dialing {
@@ -566,3 +550,14 @@ async fn bootstrap() -> (Swarm, Swarm) {
tokio::join!(alice_task, bob_task);
(alice, bob)
}
+
+fn tcp_listeners(swarm: &Swarm) -> Vec {
+ swarm
+ .listeners()
+ .filter(|addr| {
+ addr.iter()
+ .any(|protocol| matches!(protocol, Protocol::Tcp(_)))
+ })
+ .cloned()
+ .collect::>()
+}
diff --git a/protocols/autonat/tests/test_client.rs b/protocols/autonat/tests/test_client.rs
index 7509d3ef425..49c6c483514 100644
--- a/protocols/autonat/tests/test_client.rs
+++ b/protocols/autonat/tests/test_client.rs
@@ -18,7 +18,8 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
-use async_std::task::JoinHandle;
+use std::time::Duration;
+
use libp2p_autonat::{
Behaviour, Config, Event, NatStatus, OutboundProbeError, OutboundProbeEvent, ResponseError,
};
@@ -26,13 +27,13 @@ use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use libp2p_swarm::{Swarm, SwarmEvent};
use libp2p_swarm_test::SwarmExt as _;
-use std::time::Duration;
+use tokio::task::JoinHandle;
const MAX_CONFIDENCE: usize = 3;
const TEST_RETRY_INTERVAL: Duration = Duration::from_secs(1);
const TEST_REFRESH_INTERVAL: Duration = Duration::from_secs(2);
-#[async_std::test]
+#[tokio::test]
async fn test_auto_probe() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -116,7 +117,8 @@ async fn test_auto_probe() {
// It can happen that the server observed the established connection and
// returned a response before the inbound established connection was reported at the client.
- // In this (rare) case the `ConnectionEstablished` event occurs after the `OutboundProbeEvent::Response`.
+ // In this (rare) case the `ConnectionEstablished` event
+ // occurs after the `OutboundProbeEvent::Response`.
if !had_connection_event {
match client.next_swarm_event().await {
SwarmEvent::ConnectionEstablished {
@@ -133,7 +135,7 @@ async fn test_auto_probe() {
assert!(client.behaviour().public_address().is_some());
}
-#[async_std::test]
+#[tokio::test]
async fn test_confidence() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -217,7 +219,7 @@ async fn test_confidence() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_throttle_server_period() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -268,7 +270,7 @@ async fn test_throttle_server_period() {
assert_eq!(client.behaviour().confidence(), 0);
}
-#[async_std::test]
+#[tokio::test]
async fn test_use_connected_as_server() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -306,7 +308,7 @@ async fn test_use_connected_as_server() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_outbound_failure() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -351,7 +353,7 @@ async fn test_outbound_failure() {
let mut inactive_servers = Vec::new();
for (id, handle) in servers.split_off(1) {
- handle.cancel().await;
+ handle.abort();
inactive_servers.push(id);
}
@@ -375,7 +377,7 @@ async fn test_outbound_failure() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_global_ips_config() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
@@ -426,7 +428,7 @@ async fn new_server_swarm() -> (PeerId, Multiaddr, JoinHandle<()>) {
let (_, multiaddr) = swarm.listen().await;
let peer_id = *swarm.local_peer_id();
- let task = async_std::task::spawn(swarm.loop_on_next());
+ let task = tokio::spawn(swarm.loop_on_next());
(peer_id, multiaddr, task)
}
diff --git a/protocols/autonat/tests/test_server.rs b/protocols/autonat/tests/test_server.rs
index fd97b1a9132..944c4301b20 100644
--- a/protocols/autonat/tests/test_server.rs
+++ b/protocols/autonat/tests/test_server.rs
@@ -18,22 +18,22 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
+use std::{num::NonZeroU32, time::Duration};
+
use libp2p_autonat::{
Behaviour, Config, Event, InboundProbeError, InboundProbeEvent, ResponseError,
};
use libp2p_core::{multiaddr::Protocol, ConnectedPoint, Endpoint, Multiaddr};
use libp2p_identity::PeerId;
-use libp2p_swarm::DialError;
-use libp2p_swarm::{Swarm, SwarmEvent};
+use libp2p_swarm::{DialError, Swarm, SwarmEvent};
use libp2p_swarm_test::SwarmExt as _;
-use std::{num::NonZeroU32, time::Duration};
-#[async_std::test]
+#[tokio::test]
async fn test_dial_back() {
let (mut server, server_id, server_addr) = new_server_swarm(None).await;
let (mut client, client_id) = new_client_swarm(server_id, server_addr).await;
let (_, client_addr) = client.listen().await;
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
let client_port = client_addr
.into_iter()
@@ -128,14 +128,14 @@ async fn test_dial_back() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_dial_error() {
let (mut server, server_id, server_addr) = new_server_swarm(None).await;
let (mut client, client_id) = new_client_swarm(server_id, server_addr).await;
client
.behaviour_mut()
.probe_address("/ip4/127.0.0.1/tcp/12345".parse().unwrap());
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
let request_probe_id = match server.next_behaviour_event().await {
Event::InboundProbe(InboundProbeEvent::Request { peer, probe_id, .. }) => {
@@ -178,7 +178,7 @@ async fn test_dial_error() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_throttle_global_max() {
let (mut server, server_id, server_addr) = new_server_swarm(Some(Config {
throttle_clients_global_max: 1,
@@ -190,7 +190,7 @@ async fn test_throttle_global_max() {
for _ in 0..2 {
let (mut client, _) = new_client_swarm(server_id, server_addr.clone()).await;
client.listen().await;
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
}
let (first_probe_id, first_peer_id) = match server.next_behaviour_event().await {
@@ -218,7 +218,7 @@ async fn test_throttle_global_max() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_throttle_peer_max() {
let (mut server, server_id, server_addr) = new_server_swarm(Some(Config {
throttle_clients_peer_max: 1,
@@ -230,7 +230,7 @@ async fn test_throttle_peer_max() {
let (mut client, client_id) = new_client_swarm(server_id, server_addr.clone()).await;
client.listen().await;
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
let first_probe_id = match server.next_behaviour_event().await {
Event::InboundProbe(InboundProbeEvent::Request { peer, probe_id, .. }) => {
@@ -265,7 +265,7 @@ async fn test_throttle_peer_max() {
};
}
-#[async_std::test]
+#[tokio::test]
async fn test_dial_multiple_addr() {
let (mut server, server_id, server_addr) = new_server_swarm(Some(Config {
throttle_clients_peer_max: 1,
@@ -280,7 +280,7 @@ async fn test_dial_multiple_addr() {
client
.behaviour_mut()
.probe_address("/ip4/127.0.0.1/tcp/12345".parse().unwrap());
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
let dial_addresses = match server.next_behaviour_event().await {
Event::InboundProbe(InboundProbeEvent::Request {
@@ -327,7 +327,7 @@ async fn test_dial_multiple_addr() {
}
}
-#[async_std::test]
+#[tokio::test]
async fn test_global_ips_config() {
let (mut server, server_id, server_addr) = new_server_swarm(Some(Config {
// Enforce that only clients outside of the local network are qualified for dial-backs.
@@ -338,9 +338,10 @@ async fn test_global_ips_config() {
let (mut client, _) = new_client_swarm(server_id, server_addr.clone()).await;
client.listen().await;
- async_std::task::spawn(client.loop_on_next());
+ tokio::spawn(client.loop_on_next());
- // Expect the probe to be refused as both peers run on the same machine and thus in the same local network.
+ // Expect the probe to be refused as both peers run
+ // on the same machine and thus in the same local network.
match server.next_behaviour_event().await {
Event::InboundProbe(InboundProbeEvent::Error { error, .. }) => assert!(matches!(
error,
diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md
index 0ddc4aa1148..7fb02fabcbd 100644
--- a/protocols/dcutr/CHANGELOG.md
+++ b/protocols/dcutr/CHANGELOG.md
@@ -1,3 +1,10 @@
+## 0.13.0
+
+- Deprecate `void` crate.
+ See [PR 5676](https://github.com/libp2p/rust-libp2p/pull/5676).
+
+
+
## 0.12.0
diff --git a/protocols/dcutr/Cargo.toml b/protocols/dcutr/Cargo.toml
index 6b1d04f82f5..be02e890e7a 100644
--- a/protocols/dcutr/Cargo.toml
+++ b/protocols/dcutr/Cargo.toml
@@ -3,7 +3,7 @@ name = "libp2p-dcutr"
edition = "2021"
rust-version = { workspace = true }
description = "Direct connection upgrade through relay"
-version = "0.12.0"
+version = "0.13.0"
authors = ["Max Inden "]
license = "MIT"
repository = "https://github.com/libp2p/rust-libp2p"
@@ -21,27 +21,21 @@ libp2p-swarm = { workspace = true }
libp2p-identity = { workspace = true }
quick-protobuf = "0.8"
quick-protobuf-codec = { workspace = true }
-thiserror = "1.0"
+thiserror = { workspace = true }
tracing = { workspace = true }
-void = "1"
lru = "0.12.3"
futures-bounded = { workspace = true }
[dev-dependencies]
-async-std = { version = "1.12.0", features = ["attributes"] }
-clap = { version = "4.5.6", features = ["derive"] }
-libp2p-dns = { workspace = true, features = ["async-std"] }
libp2p-identify = { workspace = true }
-libp2p-noise = { workspace = true }
-libp2p-ping = { workspace = true }
libp2p-plaintext = { workspace = true }
libp2p-relay = { workspace = true }
libp2p-swarm = { workspace = true, features = ["macros"] }
libp2p-swarm-test = { path = "../../swarm-test" }
libp2p-tcp = { workspace = true, features = ["async-io"] }
libp2p-yamux = { workspace = true }
-rand = "0.8"
tracing-subscriber = { workspace = true, features = ["env-filter"] }
+tokio = { workspace = true, features = ["rt", "macros"] }
# Passing arguments to the docsrs builder in order to properly document cfg's.
# More information: https://docs.rs/about/builds#cross-compiling
diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs
index 574c96205fa..989635c02ba 100644
--- a/protocols/dcutr/src/behaviour.rs
+++ b/protocols/dcutr/src/behaviour.rs
@@ -20,26 +20,28 @@
//! [`NetworkBehaviour`] to act as a direct connection upgrade through relay node.
-use crate::{handler, protocol};
+use std::{
+ collections::{HashMap, HashSet, VecDeque},
+ convert::Infallible,
+ num::NonZeroUsize,
+ task::{Context, Poll},
+};
+
use either::Either;
-use libp2p_core::connection::ConnectedPoint;
-use libp2p_core::multiaddr::Protocol;
-use libp2p_core::transport::PortUse;
-use libp2p_core::{Endpoint, Multiaddr};
+use libp2p_core::{
+ connection::ConnectedPoint, multiaddr::Protocol, transport::PortUse, Endpoint, Multiaddr,
+};
use libp2p_identity::PeerId;
-use libp2p_swarm::behaviour::{ConnectionClosed, DialFailure, FromSwarm};
-use libp2p_swarm::dial_opts::{self, DialOpts};
use libp2p_swarm::{
- dummy, ConnectionDenied, ConnectionHandler, ConnectionId, NewExternalAddrCandidate, THandler,
- THandlerOutEvent,
+ behaviour::{ConnectionClosed, DialFailure, FromSwarm},
+ dial_opts::{self, DialOpts},
+ dummy, ConnectionDenied, ConnectionHandler, ConnectionId, NetworkBehaviour,
+ NewExternalAddrCandidate, NotifyHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm,
};
-use libp2p_swarm::{NetworkBehaviour, NotifyHandler, THandlerInEvent, ToSwarm};
use lru::LruCache;
-use std::collections::{HashMap, HashSet, VecDeque};
-use std::num::NonZeroUsize;
-use std::task::{Context, Poll};
use thiserror::Error;
-use void::Void;
+
+use crate::{handler, protocol};
pub(crate) const MAX_NUMBER_OF_UPGRADE_ATTEMPTS: u8 = 3;
@@ -68,7 +70,7 @@ enum InnerError {
pub struct Behaviour {
/// Queue of actions to return when polled.
- queued_events: VecDeque