rendezvous_example/
main.rs

1// Copyright 2021 COMIT Network.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the "Software"),
5// to deal in the Software without restriction, including without limitation
6// the rights to use, copy, modify, merge, publish, distribute, sublicense,
7// and/or sell copies of the Software, and to permit persons to whom the
8// Software is furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
19// DEALINGS IN THE SOFTWARE.
20
21#![doc = include_str!("../README.md")]
22
23use std::{error::Error, time::Duration};
24
25use futures::StreamExt;
26use libp2p::{
27    identify, noise, ping, rendezvous,
28    swarm::{NetworkBehaviour, SwarmEvent},
29    tcp, yamux,
30};
31use tracing_subscriber::EnvFilter;
32
33#[tokio::main]
34async fn main() -> Result<(), Box<dyn Error>> {
35    let _ = tracing_subscriber::fmt()
36        .with_env_filter(EnvFilter::from_default_env())
37        .try_init();
38
39    // Results in PeerID 12D3KooWDpJ7As7BWAwRMfu1VU2WCqNjvq387JEYKDBj4kx6nXTN which is
40    // used as the rendezvous point by the other peer examples.
41    let keypair = libp2p::identity::Keypair::ed25519_from_bytes([0; 32]).unwrap();
42
43    let mut swarm = libp2p::SwarmBuilder::with_existing_identity(keypair)
44        .with_tokio()
45        .with_tcp(
46            tcp::Config::default(),
47            noise::Config::new,
48            yamux::Config::default,
49        )?
50        .with_behaviour(|key| MyBehaviour {
51            identify: identify::Behaviour::new(identify::Config::new(
52                "rendezvous-example/1.0.0".to_string(),
53                key.public(),
54            )),
55            rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()),
56            ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))),
57        })?
58        .build();
59
60    let _ = swarm.listen_on("/ip4/0.0.0.0/tcp/62649".parse().unwrap());
61
62    while let Some(event) = swarm.next().await {
63        match event {
64            SwarmEvent::ConnectionEstablished { peer_id, .. } => {
65                tracing::info!("Connected to {}", peer_id);
66            }
67            SwarmEvent::ConnectionClosed { peer_id, .. } => {
68                tracing::info!("Disconnected from {}", peer_id);
69            }
70            SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
71                rendezvous::server::Event::PeerRegistered { peer, registration },
72            )) => {
73                tracing::info!(
74                    "Peer {} registered for namespace '{}'",
75                    peer,
76                    registration.namespace
77                );
78            }
79            SwarmEvent::Behaviour(MyBehaviourEvent::Rendezvous(
80                rendezvous::server::Event::DiscoverServed {
81                    enquirer,
82                    registrations,
83                },
84            )) => {
85                tracing::info!(
86                    "Served peer {} with {} registrations",
87                    enquirer,
88                    registrations.len()
89                );
90            }
91            other => {
92                tracing::debug!("Unhandled {:?}", other);
93            }
94        }
95    }
96
97    Ok(())
98}
99
100#[derive(NetworkBehaviour)]
101struct MyBehaviour {
102    identify: identify::Behaviour,
103    rendezvous: rendezvous::server::Behaviour,
104    ping: ping::Behaviour,
105}