Skip to content

Commit 1c57bb9

Browse files
author
Roman S. Borschel
committed
Remove background task. Enhance documentation.
To avoid spawning a background task and thread within `TcpConfig::new()`, with communication via unbounded channels, a `TcpConfig` now keeps track of the listening addresses for port reuse in an `Arc<RwLock>`. Furthermore, an `IfWatcher` is only used by a `TcpListenStream` if it listens on any interface and directly polls the `IfWatcher` both for initialisation and new events. Includes some documentation and test enhancements.
1 parent 38f63f8 commit 1c57bb9

File tree

24 files changed

+529
-331
lines changed

24 files changed

+529
-331
lines changed

core/src/connection/listeners.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,10 @@ use std::{collections::VecDeque, fmt, pin::Pin};
4141
/// # Example
4242
///
4343
/// ```no_run
44-
/// # #[async_std::main]
45-
/// # async fn main() {
4644
/// use futures::prelude::*;
4745
/// use libp2p_core::connection::{ListenersEvent, ListenersStream};
4846
///
49-
/// let mut listeners = ListenersStream::new(libp2p_tcp::TcpConfig::new().await.unwrap());
47+
/// let mut listeners = ListenersStream::new(libp2p_tcp::TcpConfig::new());
5048
///
5149
/// // Ask the `listeners` to start listening on the given multiaddress.
5250
/// listeners.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap()).unwrap();
@@ -76,7 +74,6 @@ use std::{collections::VecDeque, fmt, pin::Pin};
7674
/// }
7775
/// }
7876
/// })
79-
/// # }
8077
/// ```
8178
pub struct ListenersStream<TTrans>
8279
where

core/src/network.rs

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -175,22 +175,18 @@ where
175175
self.listeners.listen_addrs()
176176
}
177177

178-
/// Call this function in order to know which address remotes should dial to
179-
/// access your local node.
178+
/// Maps the given `observed_addr`, representing an address of the local
179+
/// node observed by a remote peer, onto the locally known listen addresses
180+
/// to yield one or more addresses of the local node that may be publicly
181+
/// reachable.
180182
///
181-
/// When receiving an observed address on a tcp connection that we initiated, the observed
182-
/// address contains our tcp dial port, not our tcp listen port. We know which port we are
183-
/// listening on, thereby we can replace the port within the observed address.
184-
///
185-
/// When receiving an observed address on a tcp connection that we did **not** initiated, the
186-
/// observed address should contain our listening port. In case it differs from our listening
187-
/// port there might be a proxy along the path.
188-
///
189-
/// # Arguments
190-
///
191-
/// * `observed_addr` - should be an address a remote observes you as, which can be obtained for
192-
/// example with the identify protocol.
183+
/// I.e. this method incorporates the view of other peers into the listen
184+
/// addresses seen by the local node to account for possible IP and port
185+
/// mappings performed by intermediate network devices in an effort to
186+
/// obtain addresses for the local peer that are also reachable for peers
187+
/// other than the peer who reported the `observed_addr`.
193188
///
189+
/// The translation is transport-specific. See [`Transport::address_translation`].
194190
pub fn address_translation<'a>(&'a self, observed_addr: &'a Multiaddr)
195191
-> impl Iterator<Item = Multiaddr> + 'a
196192
where

core/src/transport.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,8 +128,10 @@ pub trait Transport {
128128
where
129129
Self: Sized;
130130

131-
/// Perform transport specific multiaddr translation.
132-
fn address_translation(&self, _server: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr>;
131+
/// Performs a transport-specific mapping of an address `observed` by
132+
/// a remote onto a local `listen` address to yield an address for
133+
/// the local node that may be reachable for other peers.
134+
fn address_translation(&self, listen: &Multiaddr, observed: &Multiaddr) -> Option<Multiaddr>;
133135

134136
/// Boxes the transport, including custom transport errors.
135137
fn boxed(self) -> boxed::Boxed<Self::Output>

core/tests/util.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ pub fn test_network(cfg: NetworkConfig) -> TestNetwork {
3131
let local_key = identity::Keypair::generate_ed25519();
3232
let local_public_key = local_key.public();
3333
let noise_keys = noise::Keypair::<noise::X25519Spec>::new().into_authentic(&local_key).unwrap();
34-
let transport: TestTransport = async_std::task::block_on(tcp::TcpConfig::new())
35-
.unwrap()
34+
let transport: TestTransport = tcp::TcpConfig::new()
3635
.upgrade(upgrade::Version::V1)
3736
.authenticate(noise::NoiseConfig::xx(noise_keys).into_authenticated())
3837
.multiplex(mplex::MplexConfig::new())

examples/chat.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,7 @@ use libp2p::{
6363
};
6464
use std::{error::Error, task::{Context, Poll}};
6565

66-
#[async_std::main]
67-
async fn main() -> Result<(), Box<dyn Error>> {
66+
fn main() -> Result<(), Box<dyn Error>> {
6867
env_logger::init();
6968

7069
// Create a random PeerId
@@ -73,7 +72,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
7372
println!("Local peer id: {:?}", local_peer_id);
7473

7574
// Set up a an encrypted DNS-enabled TCP Transport over the Mplex and Yamux protocols
76-
let transport = libp2p::build_development_transport(local_key).await?;
75+
let transport = libp2p::build_development_transport(local_key)?;
7776

7877
// Create a Floodsub topic
7978
let floodsub_topic = floodsub::Topic::new("chat");

examples/distributed-key-value-store.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,16 +65,15 @@ use libp2p::{
6565
};
6666
use std::{error::Error, task::{Context, Poll}};
6767

68-
#[async_std::main]
69-
async fn main() -> Result<(), Box<dyn Error>> {
68+
fn main() -> Result<(), Box<dyn Error>> {
7069
env_logger::init();
7170

7271
// Create a random key for ourselves.
7372
let local_key = identity::Keypair::generate_ed25519();
7473
let local_peer_id = PeerId::from(local_key.public());
7574

7675
// Set up a an encrypted DNS-enabled TCP Transport over the Mplex protocol.
77-
let transport = build_development_transport(local_key).await?;
76+
let transport = build_development_transport(local_key)?;
7877

7978
// We create a custom network behaviour that combines Kademlia and mDNS.
8079
#[derive(NetworkBehaviour)]

examples/gossipsub-chat.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,7 @@ use std::{
6060
task::{Context, Poll},
6161
};
6262

63-
#[async_std::main]
64-
async fn main() -> Result<(), Box<dyn Error>> {
63+
fn main() -> Result<(), Box<dyn Error>> {
6564
Builder::from_env(Env::default().default_filter_or("info")).init();
6665

6766
// Create a random PeerId
@@ -70,7 +69,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
7069
println!("Local peer id: {:?}", local_peer_id);
7170

7271
// Set up an encrypted TCP Transport over the Mplex and Yamux protocols
73-
let transport = libp2p::build_development_transport(local_key.clone()).await?;
72+
let transport = libp2p::build_development_transport(local_key.clone())?;
7473

7574
// Create a Gossipsub topic
7675
let topic = Topic::new("test-net".into());

examples/ipfs-kad.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,15 @@ use libp2p::kad::{
4040
use libp2p::kad::record::store::MemoryStore;
4141
use std::{env, error::Error, time::Duration};
4242

43-
#[async_std::main]
44-
async fn main() -> Result<(), Box<dyn Error>> {
43+
fn main() -> Result<(), Box<dyn Error>> {
4544
env_logger::init();
4645

4746
// Create a random key for ourselves.
4847
let local_key = identity::Keypair::generate_ed25519();
4948
let local_peer_id = PeerId::from(local_key.public());
5049

5150
// Set up a an encrypted DNS-enabled TCP Transport over the Mplex protocol
52-
let transport = build_development_transport(local_key).await?;
51+
let transport = build_development_transport(local_key)?;
5352

5453
// Create a swarm to manage peers and events.
5554
let mut swarm = {

examples/ipfs-private.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ use std::{
5858
};
5959

6060
/// Builds the transport that serves as a common ground for all connections.
61-
pub async fn build_transport(
61+
pub fn build_transport(
6262
key_pair: identity::Keypair,
6363
psk: Option<PreSharedKey>,
6464
) -> transport::Boxed<(PeerId, StreamMuxerBox)>
@@ -67,7 +67,7 @@ pub async fn build_transport(
6767
let noise_config = noise::NoiseConfig::xx(noise_keys).into_authenticated();
6868
let yamux_config = YamuxConfig::default();
6969

70-
let base_transport = TcpConfig::new().await.unwrap().nodelay(true);
70+
let base_transport = TcpConfig::new().nodelay(true);
7171
let maybe_encrypted = match psk {
7272
Some(psk) => EitherTransport::Left(
7373
base_transport.and_then(move |socket, _| PnetConfig::new(psk).handshake(socket)),
@@ -136,8 +136,7 @@ fn parse_legacy_multiaddr(text: &str) -> Result<Multiaddr, Box<dyn Error>> {
136136
Ok(res)
137137
}
138138

139-
#[async_std::main]
140-
async fn main() -> Result<(), Box<dyn Error>> {
139+
fn main() -> Result<(), Box<dyn Error>> {
141140
env_logger::init();
142141

143142
let ipfs_path: Box<Path> = get_ipfs_path();
@@ -155,7 +154,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
155154
}
156155

157156
// Set up a an encrypted DNS-enabled TCP Transport over and Yamux protocol
158-
let transport = build_transport(local_key.clone(), psk).await;
157+
let transport = build_transport(local_key.clone(), psk);
159158

160159
// Create a Gosspipsub topic
161160
let gossipsub_topic = gossipsub::Topic::new("chat".into());

examples/ping.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ use futures::{future, prelude::*};
4343
use libp2p::{identity, PeerId, ping::{Ping, PingConfig}, Swarm};
4444
use std::{error::Error, task::{Context, Poll}};
4545

46-
#[async_std::main]
47-
async fn main() -> Result<(), Box<dyn Error>> {
46+
fn main() -> Result<(), Box<dyn Error>> {
4847
env_logger::init();
4948

5049
// Create a random PeerId.
@@ -53,7 +52,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
5352
println!("Local peer id: {:?}", peer_id);
5453

5554
// Create a transport.
56-
let transport = libp2p::build_development_transport(id_keys).await?;
55+
let transport = libp2p::build_development_transport(id_keys)?;
5756

5857
// Create a ping network behaviour.
5958
//

0 commit comments

Comments
 (0)