refactor: move examples to common location

Refactor examples into separate binary crates.

Fixes https://github.com/libp2p/rust-libp2p/issues/3111.

Pull-Request: #3509.
This commit is contained in:
Oleg Kubrakov
2023-03-08 16:17:33 +08:00
committed by GitHub
parent 2c10cd838a
commit b63e05dad6
30 changed files with 1169 additions and 1495 deletions

View File

@ -0,0 +1,131 @@
// Copyright 2021 COMIT Network.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 futures::StreamExt;
use libp2p::{
core::transport::upgrade::Version,
identity,
multiaddr::Protocol,
noise, ping, rendezvous,
swarm::{keep_alive, NetworkBehaviour, Swarm, SwarmEvent},
tcp, yamux, Multiaddr, PeerId, Transport,
};
use std::time::Duration;
const NAMESPACE: &str = "rendezvous";
#[tokio::main]
async fn main() {
env_logger::init();
let key_pair = identity::Keypair::generate_ed25519();
let rendezvous_point_address = "/ip4/127.0.0.1/tcp/62649".parse::<Multiaddr>().unwrap();
let rendezvous_point = "12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN"
.parse()
.unwrap();
let mut swarm = Swarm::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {
rendezvous: rendezvous::client::Behaviour::new(key_pair.clone()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(key_pair.public()),
);
log::info!("Local peer id: {}", swarm.local_peer_id());
swarm.dial(rendezvous_point_address.clone()).unwrap();
let mut discover_tick = tokio::time::interval(Duration::from_secs(30));
let mut cookie = None;
loop {
tokio::select! {
event = swarm.select_next_some() => match event {
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == rendezvous_point => {
log::info!(
"Connected to rendezvous point, discovering nodes in '{}' namespace ...",
NAMESPACE
);
swarm.behaviour_mut().rendezvous.discover(
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
None,
None,
rendezvous_point,
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(rendezvous::client::Event::Discovered {
registrations,
cookie: new_cookie,
..
})) => {
cookie.replace(new_cookie);
for registration in registrations {
for address in registration.record.addresses() {
let peer = registration.record.peer_id();
log::info!("Discovered peer {} at {}", peer, address);
let p2p_suffix = Protocol::P2p(*peer.as_ref());
let address_with_p2p =
if !address.ends_with(&Multiaddr::empty().with(p2p_suffix.clone())) {
address.clone().with(p2p_suffix)
} else {
address.clone()
};
swarm.dial(address_with_p2p).unwrap();
}
}
}
SwarmEvent::Behaviour(MyBehaviourEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
})) if peer != rendezvous_point => {
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
}
other => {
log::debug!("Unhandled {:?}", other);
}
},
_ = discover_tick.tick(), if cookie.is_some() =>
swarm.behaviour_mut().rendezvous.discover(
Some(rendezvous::Namespace::new(NAMESPACE.to_string()).unwrap()),
cookie.clone(),
None,
rendezvous_point
)
}
}
}
#[derive(NetworkBehaviour)]
struct MyBehaviour {
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -0,0 +1,125 @@
// Copyright 2021 COMIT Network.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 futures::StreamExt;
use libp2p::{
core::transport::upgrade::Version,
identify, identity, noise, ping, rendezvous,
swarm::{keep_alive, NetworkBehaviour, Swarm, SwarmEvent},
tcp, yamux, Multiaddr, PeerId, Transport,
};
use std::time::Duration;
#[tokio::main]
async fn main() {
env_logger::init();
let key_pair = identity::Keypair::generate_ed25519();
let rendezvous_point_address = "/ip4/127.0.0.1/tcp/62649".parse::<Multiaddr>().unwrap();
let rendezvous_point = "12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN"
.parse()
.unwrap();
let mut swarm = Swarm::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {
identify: identify::Behaviour::new(identify::Config::new(
"rendezvous-example/1.0.0".to_string(),
key_pair.public(),
)),
rendezvous: rendezvous::client::Behaviour::new(key_pair.clone()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(key_pair.public()),
);
log::info!("Local peer id: {}", swarm.local_peer_id());
let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap());
swarm.dial(rendezvous_point_address.clone()).unwrap();
while let Some(event) = swarm.next().await {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
log::info!("Listening on {}", address);
}
SwarmEvent::ConnectionClosed {
peer_id,
cause: Some(error),
..
} if peer_id == rendezvous_point => {
log::error!("Lost connection to rendezvous point {}", error);
}
// once `/identify` did its job, we know our external address and can register
SwarmEvent::Behaviour(MyBehaviourEvent::Identify(identify::Event::Received {
..
})) => {
swarm.behaviour_mut().rendezvous.register(
rendezvous::Namespace::from_static("rendezvous"),
rendezvous_point,
None,
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::client::Event::Registered {
namespace,
ttl,
rendezvous_node,
},
)) => {
log::info!(
"Registered for namespace '{}' at rendezvous point {} for the next {} seconds",
namespace,
rendezvous_node,
ttl
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::client::Event::RegisterFailed(error),
)) => {
log::error!("Failed to register {}", error);
return;
}
SwarmEvent::Behaviour(MyBehaviourEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
})) if peer != rendezvous_point => {
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
}
other => {
log::debug!("Unhandled {:?}", other);
}
}
}
}
#[derive(NetworkBehaviour)]
struct MyBehaviour {
identify: identify::Behaviour,
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -0,0 +1,122 @@
// Copyright 2021 COMIT Network.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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 futures::StreamExt;
use libp2p::{
core::transport::upgrade::Version,
identity, noise, ping, rendezvous,
swarm::{keep_alive, AddressScore, NetworkBehaviour, Swarm, SwarmEvent},
tcp, yamux, Multiaddr, PeerId, Transport,
};
use std::time::Duration;
#[tokio::main]
async fn main() {
env_logger::init();
let key_pair = identity::Keypair::generate_ed25519();
let rendezvous_point_address = "/ip4/127.0.0.1/tcp/62649".parse::<Multiaddr>().unwrap();
let rendezvous_point = "12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN"
.parse()
.unwrap();
let mut swarm = Swarm::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {
rendezvous: rendezvous::client::Behaviour::new(key_pair.clone()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(key_pair.public()),
);
// 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::<Multiaddr>().unwrap();
swarm.add_external_address(external_address, AddressScore::Infinite);
log::info!("Local peer id: {}", swarm.local_peer_id());
swarm.dial(rendezvous_point_address.clone()).unwrap();
while let Some(event) = swarm.next().await {
match event {
SwarmEvent::NewListenAddr { address, .. } => {
log::info!("Listening on {}", address);
}
SwarmEvent::ConnectionClosed {
peer_id,
cause: Some(error),
..
} if peer_id == rendezvous_point => {
log::error!("Lost connection to rendezvous point {}", error);
}
SwarmEvent::ConnectionEstablished { peer_id, .. } if peer_id == rendezvous_point => {
swarm.behaviour_mut().rendezvous.register(
rendezvous::Namespace::from_static("rendezvous"),
rendezvous_point,
None,
);
log::info!("Connection established with rendezvous point {}", peer_id);
}
// once `/identify` did its job, we know our external address and can register
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::client::Event::Registered {
namespace,
ttl,
rendezvous_node,
},
)) => {
log::info!(
"Registered for namespace '{}' at rendezvous point {} for the next {} seconds",
namespace,
rendezvous_node,
ttl
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::client::Event::RegisterFailed(error),
)) => {
log::error!("Failed to register {}", error);
return;
}
SwarmEvent::Behaviour(MyBehaviourEvent::Ping(ping::Event {
peer,
result: Ok(ping::Success::Ping { rtt }),
})) if peer != rendezvous_point => {
log::info!("Ping to {} is {}ms", peer, rtt.as_millis())
}
other => {
log::debug!("Unhandled {:?}", other);
}
}
}
}
#[derive(NetworkBehaviour)]
struct MyBehaviour {
rendezvous: rendezvous::client::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}

View File

@ -0,0 +1,118 @@
// Copyright 2021 COMIT Network.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// 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.
/// Examples for the rendezvous protocol:
///
/// 1. Run the rendezvous server:
/// ```
/// RUST_LOG=info cargo run --bin rendezvous-example
/// ```
/// 2. Register a peer:
/// ```
/// RUST_LOG=info cargo run --bin rzv-register
/// ```
/// 3. Try to discover the peer from (2):
/// ```
/// RUST_LOG=info cargo run --bin rzv-discover
/// ```
/// 4. Try to discover with identify:
/// ```
/// RUST_LOG=info cargo run --bin rzv-identify
/// ```
use futures::StreamExt;
use libp2p::{
core::transport::upgrade::Version,
identify, identity, noise, ping, rendezvous,
swarm::{keep_alive, NetworkBehaviour, Swarm, SwarmEvent},
tcp, yamux, PeerId, Transport,
};
use std::time::Duration;
#[tokio::main]
async fn main() {
env_logger::init();
let key_pair = identity::Keypair::generate_ed25519();
let mut swarm = Swarm::with_tokio_executor(
tcp::tokio::Transport::default()
.upgrade(Version::V1)
.authenticate(noise::NoiseAuthenticated::xx(&key_pair).unwrap())
.multiplex(yamux::YamuxConfig::default())
.boxed(),
MyBehaviour {
identify: identify::Behaviour::new(identify::Config::new(
"rendezvous-example/1.0.0".to_string(),
key_pair.public(),
)),
rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
keep_alive: keep_alive::Behaviour,
},
PeerId::from(key_pair.public()),
);
log::info!("Local peer id: {}", swarm.local_peer_id());
let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/0".parse().unwrap());
while let Some(event) = swarm.next().await {
match event {
SwarmEvent::ConnectionEstablished { peer_id, .. } => {
log::info!("Connected to {}", peer_id);
}
SwarmEvent::ConnectionClosed { peer_id, .. } => {
log::info!("Disconnected from {}", peer_id);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::server::Event::PeerRegistered { peer, registration },
)) => {
log::info!(
"Peer {} registered for namespace '{}'",
peer,
registration.namespace
);
}
SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
rendezvous::server::Event::DiscoverServed {
enquirer,
registrations,
},
)) => {
log::info!(
"Served peer {} with {} registrations",
enquirer,
registrations.len()
);
}
other => {
log::debug!("Unhandled {:?}", other);
}
}
}
}
#[derive(NetworkBehaviour)]
struct MyBehaviour {
identify: identify::Behaviour,
rendezvous: rendezvous::server::Behaviour,
ping: ping::Behaviour,
keep_alive: keep_alive::Behaviour,
}