Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(quic): implement hole punching #3964

Merged
merged 44 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
7a714bf
Implement Transport::dial_as_listener for QUIC
arpankapoor May 21, 2023
145bf11
Merge QUIC dcutr and relay examples
arpankapoor May 23, 2023
0eafaf4
Simplify nested if let
arpankapoor May 23, 2023
fd70f73
Return error when dial_as_listener is called without an active listener
arpankapoor May 23, 2023
ddacaa0
Extract peer_id in multiaddr_to_socketaddr
arpankapoor May 25, 2023
3325dbe
Add peerid to holepunching key
arpankapoor May 25, 2023
271f234
Update dcutr example
arpankapoor May 26, 2023
8b9d778
Check if holepunching is already in progress
arpankapoor May 26, 2023
2290811
Dedup dial and dial_as_listener
arpankapoor May 26, 2023
2621c13
Store random packet on failure
arpankapoor May 30, 2023
3b17e38
Use `Display` formatting instead of `Debug`
arpankapoor May 30, 2023
45446bb
Use slice pattern
arpankapoor May 30, 2023
8a344c7
Resolve merge conflict
arpankapoor May 31, 2023
81988c2
Resolve merge conflict
arpankapoor May 31, 2023
a831f51
Merge branch 'master' into master
arpankapoor Jun 1, 2023
28ece03
Use futures::future::select instead of select! macro
arpankapoor Jun 1, 2023
ce86b7c
Merge branch 'master' into master
arpankapoor Jun 5, 2023
794cabc
Implement HolePuncher as an async function
arpankapoor Jun 5, 2023
e501175
Remove entry from HolePunchMap on timeout
arpankapoor Jun 5, 2023
ad2b644
Run rustfmt
arpankapoor Jun 5, 2023
ba60bba
Implement MaybeHolePunchedConnection as an async function
arpankapoor Jun 5, 2023
6c378ef
Use `SendExt::send` instead of `poll_ready` and `start_send`
arpankapoor Jun 5, 2023
3490940
Swap position of hole_puncher and punch_holes
arpankapoor Jun 6, 2023
26cd328
Clean up maybe_hole_punched_connection
arpankapoor Jun 6, 2023
0b1eaa5
Rename hole_punch_map to hole_punch_attempts
arpankapoor Jun 6, 2023
fbbd1a1
Create newtype HolePunchMap
arpankapoor Jun 6, 2023
2ad9255
Don't mix private/public imports
arpankapoor Jun 6, 2023
bbbf7a1
Return single eligible listener
arpankapoor Jun 7, 2023
26da28d
Return different error on successful holepunch
arpankapoor Jun 7, 2023
8eda5a7
Update external address
arpankapoor Jun 8, 2023
6c2638a
Merge branch 'master' of https://github.com/libp2p/rust-libp2p
arpankapoor Jun 8, 2023
5f58955
Resolve issue after merge
arpankapoor Jun 8, 2023
928314f
Remove peer_id from hole punching key
arpankapoor Jun 10, 2023
6e1b02d
Merge branch 'master' of https://github.com/libp2p/rust-libp2p
arpankapoor Jun 10, 2023
4f4f528
Remove redudant match arm from relay example
arpankapoor Jun 10, 2023
3f6bb59
Update CHANGELOG
arpankapoor Jun 10, 2023
02b1268
Fix imports
arpankapoor Jun 10, 2023
35de850
Review fixes
arpankapoor Jun 10, 2023
e46c170
More review fixes
arpankapoor Jun 11, 2023
36655ee
Move timeout and sleep to Provider trait
arpankapoor Jun 11, 2023
49873f0
Implement timeout using sleep
arpankapoor Jun 11, 2023
0eb9246
Loop through listener events
arpankapoor Jun 11, 2023
05b7a9f
Remove unused TimeoutError
arpankapoor Jun 11, 2023
9d001c7
Merge branch 'master' into master
mergify[bot] Jun 13, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions examples/dcutr/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ env_logger = "0.10.0"
futures = "0.3.28"
futures-timer = "3.0"
libp2p = { path = "../../libp2p", features = ["async-std", "dns", "dcutr", "identify", "macros", "noise", "ping", "relay", "rendezvous", "tcp", "tokio", "yamux"] }
libp2p-quic = { path = "../../transports/quic", features = ["async-std"] }
log = "0.4"
65 changes: 44 additions & 21 deletions examples/dcutr/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@
use clap::Parser;
use futures::{
executor::{block_on, ThreadPool},
future::FutureExt,
future::{Either, FutureExt},
stream::StreamExt,
};
use libp2p::{
core::{
multiaddr::{Multiaddr, Protocol},
muxing::StreamMuxerBox,
transport::{OrTransport, Transport},
upgrade,
},
Expand All @@ -36,6 +37,7 @@ use libp2p::{
swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent},
tcp, yamux, PeerId,
};
use libp2p_quic as quic;
use log::info;
use std::error::Error;
use std::net::Ipv4Addr;
Expand Down Expand Up @@ -89,19 +91,40 @@ fn main() -> Result<(), Box<dyn Error>> {

let (relay_transport, client) = relay::client::new(local_peer_id);

let transport = OrTransport::new(
relay_transport,
block_on(DnsConfig::system(tcp::async_io::Transport::new(
tcp::Config::default().port_reuse(true),
)))
.unwrap(),
)
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::Config::new(&local_key).expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::Config::default())
.boxed();
let is_quic_relay = opts.relay_address.iter().any(|p| p == Protocol::QuicV1);
let transport = if is_quic_relay {
let relay_transport = relay_transport
.upgrade(upgrade::Version::V1)
.authenticate(noise::Config::new(&local_key).unwrap())
.multiplex(yamux::Config::default());

OrTransport::new(
relay_transport,
block_on(DnsConfig::system(quic::async_std::Transport::new(
quic::Config::new(&local_key),
)))
.unwrap(),
)
.map(|either_output, _| match either_output {
Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
Either::Right((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
})
.boxed()
} else {
OrTransport::new(
relay_transport,
block_on(DnsConfig::system(tcp::async_io::Transport::new(
tcp::Config::default().port_reuse(true),
)))
.unwrap(),
)
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::Config::new(&local_key).expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(yamux::Config::default())
.boxed()
};

#[derive(NetworkBehaviour)]
#[behaviour(to_swarm = "Event", event_process = false)]
Expand Down Expand Up @@ -161,13 +184,13 @@ fn main() -> Result<(), Box<dyn Error>> {
}
.build();

swarm
.listen_on(
Multiaddr::empty()
.with("0.0.0.0".parse::<Ipv4Addr>().unwrap().into())
.with(Protocol::Tcp(0)),
)
.unwrap();
let listen_addr = Multiaddr::empty().with("0.0.0.0".parse::<Ipv4Addr>().unwrap().into());
let listen_addr = if is_quic_relay {
listen_addr.with(Protocol::Udp(0)).with(Protocol::QuicV1)
} else {
listen_addr.with(Protocol::Tcp(0))
};
swarm.listen_on(listen_addr).unwrap();

// Wait to listen on all interfaces.
block_on(async {
Expand Down
1 change: 1 addition & 0 deletions examples/relay-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ async-trait = "0.1"
env_logger = "0.10.0"
futures = "0.3.28"
libp2p = { path = "../../libp2p", features = ["async-std", "noise", "macros", "ping", "tcp", "identify", "yamux", "relay"] }
libp2p-quic = { path = "../../transports/quic", features = ["async-std"] }
30 changes: 25 additions & 5 deletions examples/relay-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@
// DEALINGS IN THE SOFTWARE.

use clap::Parser;
use futures::executor::block_on;
use futures::stream::StreamExt;
use futures::{executor::block_on, future::Either};
use libp2p::{
core::multiaddr::Protocol,
core::muxing::StreamMuxerBox,
core::upgrade,
core::{Multiaddr, Transport},
identify, identity,
Expand All @@ -32,6 +33,7 @@ use libp2p::{
swarm::{NetworkBehaviour, SwarmBuilder, SwarmEvent},
tcp,
};
use libp2p_quic as quic;
use std::error::Error;
use std::net::{Ipv4Addr, Ipv6Addr};

Expand All @@ -48,12 +50,21 @@ fn main() -> Result<(), Box<dyn Error>> {

let tcp_transport = tcp::async_io::Transport::default();

let transport = tcp_transport
let tcp_transport = tcp_transport
.upgrade(upgrade::Version::V1Lazy)
.authenticate(
noise::Config::new(&local_key).expect("Signing libp2p-noise static DH keypair failed."),
)
.multiplex(libp2p::yamux::Config::default())
.multiplex(libp2p::yamux::Config::default());

let quic_transport = quic::async_std::Transport::new(quic::Config::new(&local_key));

let transport = quic_transport
.or_transport(tcp_transport)
.map(|either_output, _| match either_output {
Either::Left((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
Either::Right((peer_id, muxer)) => (peer_id, StreamMuxerBox::new(muxer)),
})
.boxed();

let behaviour = Behaviour {
Expand All @@ -68,13 +79,22 @@ fn main() -> Result<(), Box<dyn Error>> {
let mut swarm = SwarmBuilder::without_executor(transport, behaviour, local_peer_id).build();

// Listen on all interfaces
let listen_addr = Multiaddr::empty()
let listen_addr_tcp = Multiaddr::empty()
.with(match opt.use_ipv6 {
Some(true) => Protocol::from(Ipv6Addr::UNSPECIFIED),
_ => Protocol::from(Ipv4Addr::UNSPECIFIED),
})
.with(Protocol::Tcp(opt.port));
swarm.listen_on(listen_addr)?;
swarm.listen_on(listen_addr_tcp)?;

let listen_addr_quic = Multiaddr::empty()
.with(match opt.use_ipv6 {
Some(true) => Protocol::from(Ipv6Addr::UNSPECIFIED),
_ => Protocol::from(Ipv4Addr::UNSPECIFIED),
})
.with(Protocol::Udp(opt.port))
.with(Protocol::QuicV1);
swarm.listen_on(listen_addr_quic)?;

block_on(async {
loop {
Expand Down
82 changes: 32 additions & 50 deletions protocols/dcutr/src/behaviour_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,32 +246,23 @@ impl NetworkBehaviour for Behaviour {
local_addr: &Multiaddr,
remote_addr: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
match self
.outgoing_direct_connection_attempts
thomaseizinger marked this conversation as resolved.
Show resolved Hide resolved
.remove(&(connection_id, peer))
if is_relayed(local_addr) {
Ok(Either::Left(handler::relayed::Handler::new(
ConnectedPoint::Listener {
local_addr: local_addr.clone(),
send_back_addr: remote_addr.clone(),
},
))) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
} else if let Some(&relayed_connection_id) =
self.direct_to_relayed_connections.get(&connection_id)
{
None => {
let handler = if is_relayed(local_addr) {
Either::Left(handler::relayed::Handler::new(ConnectedPoint::Listener {
local_addr: local_addr.clone(),
send_back_addr: remote_addr.clone(),
})) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
} else {
Either::Right(Either::Right(dummy::ConnectionHandler))
};

Ok(handler)
}
Some(_) => {
assert!(
!is_relayed(local_addr),
"`Prototype::DirectConnection` is never created for relayed connection."
);

Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
}
self.outgoing_direct_connection_attempts
.remove(&(relayed_connection_id, peer));
Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
} else {
Ok(Either::Right(Either::Right(dummy::ConnectionHandler)))
}
}

Expand All @@ -282,32 +273,23 @@ impl NetworkBehaviour for Behaviour {
addr: &Multiaddr,
role_override: Endpoint,
) -> Result<THandler<Self>, ConnectionDenied> {
match self
.outgoing_direct_connection_attempts
.remove(&(connection_id, peer))
if is_relayed(addr) {
Ok(Either::Left(handler::relayed::Handler::new(
ConnectedPoint::Dialer {
address: addr.clone(),
role_override,
},
))) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
} else if let Some(&relayed_connection_id) =
self.direct_to_relayed_connections.get(&connection_id)
{
None => {
let handler = if is_relayed(addr) {
Either::Left(handler::relayed::Handler::new(ConnectedPoint::Dialer {
address: addr.clone(),
role_override,
})) // TODO: We could make two `handler::relayed::Handler` here, one inbound one outbound.
} else {
Either::Right(Either::Right(dummy::ConnectionHandler))
};

Ok(handler)
}
Some(_) => {
assert!(
!is_relayed(addr),
"`Prototype::DirectConnection` is never created for relayed connection."
);

Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
}
self.outgoing_direct_connection_attempts
.remove(&(relayed_connection_id, peer));
Ok(Either::Right(Either::Left(
handler::direct::Handler::default(),
)))
} else {
Ok(Either::Right(Either::Right(dummy::ConnectionHandler)))
}
}

Expand Down
4 changes: 4 additions & 0 deletions transports/quic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ pub enum Error {
/// The [`Connecting`] future timed out.
#[error("Handshake with the remote timed out.")]
HandshakeTimedOut,

/// Error when `Transport::dial_as_listener` is called without an active listener.
#[error("Tried to dial as listener without an active listener.")]
NoActiveListenerForDialAsListener,
}

/// Dialing a remote peer failed.
Expand Down
Loading