Skip to content

Commit 3034901

Browse files
wngrmxinden
andauthored
protocols/rendezvous: Improve examples (#2229)
* Add support for the `Identify` protocol to the server, such that the `register_with_identify` example works as intended * Add discovery loop to the `discovery` example and demonstrate cookie usage * Drop explicit dependency on async_std Co-authored-by: Max Inden <mail@max-inden.de>
1 parent f030b15 commit 3034901

File tree

5 files changed

+108
-62
lines changed

5 files changed

+108
-62
lines changed

protocols/rendezvous/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,10 @@ rand = "0.8"
2525
wasm-timer = "0.2"
2626

2727
[dev-dependencies]
28+
async-trait = "0.1"
29+
env_logger = "0.8"
2830
libp2p = { path = "../.." }
2931
rand = "0.8"
30-
async-std = { version = "1", features = ["attributes"] }
31-
env_logger = "0.8"
32-
async-trait = "0.1"
3332
tokio = { version = "1", features = [ "rt-multi-thread", "time", "macros", "sync", "process", "fs", "net" ] }
3433

3534
[build-dependencies]

protocols/rendezvous/examples/discover.rs

Lines changed: 74 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -23,14 +23,14 @@ use libp2p::core::identity;
2323
use libp2p::core::PeerId;
2424
use libp2p::multiaddr::Protocol;
2525
use libp2p::ping::{Ping, PingConfig, PingEvent, PingSuccess};
26-
use libp2p::swarm::Swarm;
2726
use libp2p::swarm::SwarmEvent;
27+
use libp2p::Swarm;
2828
use libp2p::{development_transport, rendezvous, Multiaddr};
2929
use std::time::Duration;
3030

3131
const NAMESPACE: &str = "rendezvous";
3232

33-
#[async_std::main]
33+
#[tokio::main]
3434
async fn main() {
3535
env_logger::init();
3636

@@ -44,7 +44,11 @@ async fn main() {
4444
development_transport(identity.clone()).await.unwrap(),
4545
MyBehaviour {
4646
rendezvous: rendezvous::client::Behaviour::new(identity.clone()),
47-
ping: Ping::new(PingConfig::new().with_interval(Duration::from_secs(1))),
47+
ping: Ping::new(
48+
PingConfig::new()
49+
.with_interval(Duration::from_secs(1))
50+
.with_keep_alive(true),
51+
),
4852
},
4953
PeerId::from(identity.public()),
5054
);
@@ -53,62 +57,77 @@ async fn main() {
5357

5458
let _ = swarm.dial_addr(rendezvous_point_address.clone());
5559

56-
while let Some(event) = swarm.next().await {
57-
match event {
58-
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == rendezvous_point => {
59-
log::info!(
60-
"Connected to rendezvous point, discovering nodes in '{}' namespace ...",
61-
NAMESPACE
62-
);
60+
let mut discover_tick = tokio::time::interval(Duration::from_secs(30));
61+
let mut cookie = None;
6362

63+
loop {
64+
tokio::select! {
65+
event = swarm.select_next_some() => match event {
66+
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == rendezvous_point => {
67+
log::info!(
68+
"Connected to rendezvous point, discovering nodes in '{}' namespace ...",
69+
NAMESPACE
70+
);
71+
72+
swarm.behaviour_mut().rendezvous.discover(
73+
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
74+
None,
75+
None,
76+
rendezvous_point,
77+
);
78+
}
79+
SwarmEvent::UnreachableAddr { error, address, .. }
80+
| SwarmEvent::UnknownPeerUnreachableAddr { error, address, .. }
81+
if address == rendezvous_point_address =>
82+
{
83+
log::error!(
84+
"Failed to connect to rendezvous point at {}: {}",
85+
address,
86+
error
87+
);
88+
return;
89+
}
90+
SwarmEvent::Behaviour(MyEvent::Rendezvous(rendezvous::client::Event::Discovered {
91+
registrations,
92+
cookie: new_cookie,
93+
..
94+
})) => {
95+
cookie.replace(new_cookie);
96+
97+
for registration in registrations {
98+
for address in registration.record.addresses() {
99+
let peer = registration.record.peer_id();
100+
log::info!("Discovered peer {} at {}", peer, address);
101+
102+
let p2p_suffix = Protocol::P2p(*peer.as_ref());
103+
let address_with_p2p =
104+
if !address.ends_with(&Multiaddr::empty().with(p2p_suffix.clone())) {
105+
address.clone().with(p2p_suffix)
106+
} else {
107+
address.clone()
108+
};
109+
110+
swarm.dial_addr(address_with_p2p).unwrap()
111+
}
112+
}
113+
}
114+
SwarmEvent::Behaviour(MyEvent::Ping(PingEvent {
115+
peer,
116+
result: Ok(PingSuccess::Ping { rtt }),
117+
})) if peer != rendezvous_point => {
118+
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
119+
}
120+
other => {
121+
log::debug!("Unhandled {:?}", other);
122+
}
123+
},
124+
_ = discover_tick.tick(), if cookie.is_some() =>
64125
swarm.behaviour_mut().rendezvous.discover(
65126
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
127+
cookie.clone(),
66128
None,
67-
None,
68-
rendezvous_point,
69-
);
70-
}
71-
SwarmEvent::UnreachableAddr { error, address, .. }
72-
| SwarmEvent::UnknownPeerUnreachableAddr { error, address, .. }
73-
if address == rendezvous_point_address =>
74-
{
75-
log::error!(
76-
"Failed to connect to rendezvous point at {}: {}",
77-
address,
78-
error
79-
);
80-
return;
81-
}
82-
SwarmEvent::Behaviour(MyEvent::Rendezvous(rendezvous::client::Event::Discovered {
83-
registrations,
84-
..
85-
})) => {
86-
for registration in registrations {
87-
for address in registration.record.addresses() {
88-
let peer = registration.record.peer_id();
89-
log::info!("Discovered peer {} at {}", peer, address);
90-
91-
let p2p_suffix = Protocol::P2p(*peer.as_ref());
92-
let address_with_p2p =
93-
if !address.ends_with(&Multiaddr::empty().with(p2p_suffix.clone())) {
94-
address.clone().with(p2p_suffix)
95-
} else {
96-
address.clone()
97-
};
98-
99-
swarm.dial_addr(address_with_p2p).unwrap()
100-
}
101-
}
102-
}
103-
SwarmEvent::Behaviour(MyEvent::Ping(PingEvent {
104-
peer,
105-
result: Ok(PingSuccess::Ping { rtt }),
106-
})) if peer != rendezvous_point => {
107-
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
108-
}
109-
other => {
110-
log::debug!("Unhandled {:?}", other);
111-
}
129+
rendezvous_point
130+
)
112131
}
113132
}
114133
}

protocols/rendezvous/examples/register.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use libp2p::{Multiaddr, NetworkBehaviour};
2929
use libp2p_swarm::AddressScore;
3030
use std::time::Duration;
3131

32-
#[async_std::main]
32+
#[tokio::main]
3333
async fn main() {
3434
env_logger::init();
3535

protocols/rendezvous/examples/register_with_identify.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use libp2p::{development_transport, rendezvous};
2929
use libp2p::{Multiaddr, NetworkBehaviour};
3030
use std::time::Duration;
3131

32-
#[async_std::main]
32+
#[tokio::main]
3333
async fn main() {
3434
env_logger::init();
3535

@@ -48,7 +48,11 @@ async fn main() {
4848
identity.public(),
4949
)),
5050
rendezvous: rendezvous::client::Behaviour::new(identity.clone()),
51-
ping: Ping::new(PingConfig::new().with_interval(Duration::from_secs(1))),
51+
ping: Ping::new(
52+
PingConfig::new()
53+
.with_interval(Duration::from_secs(1))
54+
.with_keep_alive(true),
55+
),
5256
},
5357
PeerId::from(identity.public()),
5458
);

protocols/rendezvous/examples/rendezvous_point.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,23 @@
2121
use futures::StreamExt;
2222
use libp2p::core::identity;
2323
use libp2p::core::PeerId;
24+
use libp2p::identify::Identify;
25+
use libp2p::identify::IdentifyConfig;
26+
use libp2p::identify::IdentifyEvent;
27+
use libp2p::ping;
2428
use libp2p::ping::{Ping, PingEvent};
2529
use libp2p::swarm::{Swarm, SwarmEvent};
2630
use libp2p::NetworkBehaviour;
2731
use libp2p::{development_transport, rendezvous};
2832

33+
/// Examples for the rendezvous protocol:
34+
///
35+
/// 1. Run the rendezvous server:
36+
/// RUST_LOG=info cargo run --example rendezvous_point
37+
/// 2. Register a peer:
38+
/// RUST_LOG=info cargo run --example register_with_identify
39+
/// 3. Try to discover the peer from (2):
40+
/// RUST_LOG=info cargo run --example discover
2941
#[tokio::main]
3042
async fn main() {
3143
env_logger::init();
@@ -37,8 +49,12 @@ async fn main() {
3749
let mut swarm = Swarm::new(
3850
development_transport(identity.clone()).await.unwrap(),
3951
MyBehaviour {
52+
identify: Identify::new(IdentifyConfig::new(
53+
"rendezvous-example/1.0.0".to_string(),
54+
identity.public(),
55+
)),
4056
rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
41-
ping: Ping::default(),
57+
ping: Ping::new(ping::Config::new().with_keep_alive(true)),
4258
},
4359
PeerId::from(identity.public()),
4460
);
@@ -89,6 +105,7 @@ async fn main() {
89105
enum MyEvent {
90106
Rendezvous(rendezvous::server::Event),
91107
Ping(PingEvent),
108+
Identify(IdentifyEvent),
92109
}
93110

94111
impl From<rendezvous::server::Event> for MyEvent {
@@ -103,10 +120,17 @@ impl From<PingEvent> for MyEvent {
103120
}
104121
}
105122

123+
impl From<IdentifyEvent> for MyEvent {
124+
fn from(event: IdentifyEvent) -> Self {
125+
MyEvent::Identify(event)
126+
}
127+
}
128+
106129
#[derive(NetworkBehaviour)]
107130
#[behaviour(event_process = false)]
108131
#[behaviour(out_event = "MyEvent")]
109132
struct MyBehaviour {
133+
identify: Identify,
110134
rendezvous: rendezvous::server::Behaviour,
111135
ping: Ping,
112136
}

0 commit comments

Comments
 (0)