-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathautonatv2_server.rs
More file actions
87 lines (78 loc) · 2.65 KB
/
autonatv2_server.rs
File metadata and controls
87 lines (78 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::{error::Error, net::Ipv4Addr, time::Duration};
use cfg_if::cfg_if;
use clap::Parser;
use libp2p::{
autonat,
futures::StreamExt,
identify, identity,
multiaddr::Protocol,
noise,
swarm::{NetworkBehaviour, SwarmEvent},
tcp, yamux, Multiaddr, SwarmBuilder,
};
use rand::SeedableRng;
#[derive(Debug, Parser)]
#[command(name = "libp2p autonatv2 server")]
struct Opt {
#[arg(short, long, default_value_t = 0)]
listen_port: u16,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
cfg_if! {
if #[cfg(feature = "jaeger")] {
use tracing_subscriber::layer::SubscriberExt;
use opentelemetry_sdk::runtime::Tokio;
let tracer = opentelemetry_jaeger::new_agent_pipeline()
.with_endpoint("jaeger:6831")
.with_service_name("autonatv2")
.install_batch(Tokio)?;
let telemetry = tracing_opentelemetry::layer().with_tracer(tracer);
let subscriber = tracing_subscriber::Registry::default()
.with(telemetry);
} else {
let subscriber = tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.finish();
}
}
tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
let opt = Opt::parse();
let mut swarm = SwarmBuilder::with_new_identity()
.with_tokio()
.with_tcp(
tcp::Config::default(),
noise::Config::new,
yamux::Config::default,
)?
.with_quic()
.with_dns()?
.with_behaviour(|key| Behaviour::new(key.public()))?
.with_swarm_config(|c| c.with_idle_connection_timeout(Duration::from_secs(60)))
.build();
swarm.listen_on(
Multiaddr::empty()
.with(Protocol::Ip4(Ipv4Addr::UNSPECIFIED))
.with(Protocol::Tcp(opt.listen_port)),
)?;
loop {
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
SwarmEvent::Behaviour(event) => println!("{event:?}"),
e => println!("{e:?}"),
}
}
}
#[derive(NetworkBehaviour)]
pub struct Behaviour {
autonat: autonat::v2::server::Behaviour,
identify: identify::Behaviour,
}
impl Behaviour {
pub fn new(key: identity::PublicKey) -> Self {
Self {
autonat: autonat::v2::server::Behaviour::new(rand::rngs::StdRng::from_rng(&mut rand::rng())),
identify: identify::Behaviour::new(identify::Config::new("/ipfs/0.1.0".into(), key)),
}
}
}