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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
use std::collections::HashSet;
use std::net::Ipv4Addr;
use std::time::Duration;
use calimero_network_primitives::config::{AutonatConfig, RelayConfig, RendezvousConfig};
use eyre::{bail, ContextCompat, Result as EyreResult};
use libp2p::rendezvous::client::RegisterError;
use libp2p::PeerId;
use multiaddr::{Multiaddr, Protocol};
use tracing::{debug, error, info};
use super::NetworkManager;
use crate::discovery::state::{
DiscoveryState, RelayReservationStatus, RendezvousRegistrationStatus,
};
pub mod state;
#[derive(Debug)]
pub struct Discovery {
pub(crate) state: DiscoveryState,
pub(crate) rendezvous_config: RendezvousConfig,
pub(crate) relay_config: RelayConfig,
pub(crate) advertise: Option<AdvertiseState>,
pub(crate) _autonat_config: AutonatConfig,
}
#[derive(Debug)]
pub(crate) struct AdvertiseState {
pub(crate) ip: Ipv4Addr,
pub(crate) ports: HashSet<u16>,
}
impl Discovery {
pub(crate) async fn new(
rendezvous_config: &RendezvousConfig,
relay_config: &RelayConfig,
autonat_config: &AutonatConfig,
listening_on: &[Multiaddr],
) -> EyreResult<Self> {
let advertise = if listening_on.is_empty() {
None
} else {
let ports = listening_on
.iter()
.filter_map(|addr| {
addr.iter().find_map(|p| match p {
Protocol::Tcp(port) | Protocol::Udp(port) => Some(port),
_ => None,
})
})
.collect();
Some(AdvertiseState {
ip: Self::get_public_ip().await?,
ports,
})
};
let this = Self {
state: DiscoveryState::default(),
rendezvous_config: rendezvous_config.clone(),
relay_config: relay_config.clone(),
advertise,
_autonat_config: autonat_config.clone(),
};
Ok(this)
}
async fn get_public_ip() -> EyreResult<Ipv4Addr> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(3))
.build()?;
let ip_addr = client
.get("https://api.ipify.org")
.send()
.await?
.text()
.await?
.parse()?;
Ok(ip_addr)
}
}
impl NetworkManager {
// Sends rendezvous discovery request to the rendezvous peer if not throttled.
// This function expectes that the rendezvous peer is already connected.
pub(crate) fn rendezvous_discover(&mut self, rendezvous_peer: &PeerId) -> EyreResult<()> {
let peer_info = self
.discovery
.state
.get_peer_info(rendezvous_peer)
.wrap_err("Failed to get peer info {}")?;
if peer_info
.is_rendezvous_discover_throttled(self.discovery.rendezvous_config.discovery_rpm)
{
return Ok(());
}
self.swarm.behaviour_mut().rendezvous.discover(
Some(self.discovery.rendezvous_config.namespace.clone()),
peer_info
.rendezvous()
.and_then(|info| info.cookie())
.cloned(),
None,
*rendezvous_peer,
);
debug!(
%rendezvous_peer,
?peer_info,
rendezvous_namespace=%(self.discovery.rendezvous_config.namespace),
"Sent discover request to rendezvous node"
);
Ok(())
}
// Sends rendezvous registrations request to all rendezvous peers which require registration.
// If rendezvous peer is not connected, it will be dialed which will trigger the registration during identify exchange.
pub(crate) fn broadcast_rendezvous_registrations(&mut self) {
#[expect(clippy::needless_collect, reason = "Necessary here; false positive")]
for peer_id in self
.discovery
.state
.get_rendezvous_peer_ids()
.collect::<Vec<_>>()
{
let Some(peer_info) = self.discovery.state.get_peer_info(&peer_id) else {
error!(%peer_id, "Failed to lookup peer info");
continue;
};
if !self.discovery.state.is_rendezvous_registration_required(
self.discovery.rendezvous_config.registrations_limit,
) {
continue;
}
if !self.swarm.is_connected(&peer_id) {
for addr in peer_info.addrs().cloned() {
if let Err(err) = self.swarm.dial(addr) {
error!(%err, "Failed to dial relay peer");
}
}
} else if let Err(err) = self.rendezvous_register(&peer_id) {
error!(%err, "Failed to update rendezvous registration");
}
}
}
// Sends rendezvous registration request to rendezvous peer if one is required.
// If there are no external addresses for the node, the registration is considered successful.
// This function expectes that the rendezvous peer is already connected.
pub(crate) fn rendezvous_register(&mut self, rendezvous_peer: &PeerId) -> EyreResult<()> {
let peer_info = self
.discovery
.state
.get_peer_info(rendezvous_peer)
.wrap_err("Failed to get peer info")?;
if !self.discovery.state.is_rendezvous_registration_required(
self.discovery.rendezvous_config.registrations_limit,
) {
return Ok(());
}
if let Err(err) = self.swarm.behaviour_mut().rendezvous.register(
self.discovery.rendezvous_config.namespace.clone(),
*rendezvous_peer,
None,
) {
match err {
RegisterError::NoExternalAddresses => {
info!("No external addresses to register at rendezvous");
return Ok(());
}
err @ RegisterError::FailedToMakeRecord(_) => {
bail!(err)
}
}
}
debug!(
%rendezvous_peer,
?peer_info,
rendezvous_namespace=%(self.discovery.rendezvous_config.namespace),
"Sent register request to rendezvous node"
);
self.discovery.state.update_rendezvous_registration_status(
rendezvous_peer,
RendezvousRegistrationStatus::Requested,
);
Ok(())
}
// We unregister from a rendezvous peer if we were previously registered.
// This function expectes that the rendezvous peer is already connected.
// pub(crate) fn rendezvous_unregister(&mut self, rendezvous_peer: &PeerId) -> EyreResult<()> {
// let peer_info = self
// .discovery
// .state
// .get_peer_info(rendezvous_peer)
// .wrap_err("Failed to get peer info")?
// .rendezvous()
// .wrap_err("Peer isn't rendezvous")?;
// if matches!(
// peer_info.registration_status(),
// RendezvousRegistrationStatus::Registered
// ) {
// self.swarm.behaviour_mut().rendezvous.unregister(
// self.discovery.rendezvous_config.namespace.clone(),
// *rendezvous_peer,
// );
// }
// Ok(())
// }
// Finds a new rendezvous peer for registration.
// Prioritizes Discovered peers, falls back to dialing Expired peers if necessary.
// Returns Some(PeerId) if a suitable peer is found, None otherwise.
pub(crate) fn find_new_rendezvous_peer(&self) -> Option<PeerId> {
let mut candidate = None;
for peer_id in self.discovery.state.get_rendezvous_peer_ids() {
if let Some(peer_info) = self.discovery.state.get_peer_info(&peer_id) {
if let Some(rendezvous_info) = peer_info.rendezvous() {
match rendezvous_info.registration_status() {
RendezvousRegistrationStatus::Discovered => {
// If we find a Discovered peer, return it right away
return Some(peer_id);
}
RendezvousRegistrationStatus::Expired if candidate.is_none() => {
candidate = Some(peer_id);
}
RendezvousRegistrationStatus::Requested
| RendezvousRegistrationStatus::Registered
| RendezvousRegistrationStatus::Expired => {}
}
}
}
}
candidate
}
// Requests relay reservation on relay peer if one is required.
// This function expectes that the relay peer is already connected.
pub(crate) fn create_relay_reservation(&mut self, relay_peer: &PeerId) -> EyreResult<()> {
let peer_info = self
.discovery
.state
.get_peer_info(relay_peer)
.wrap_err("Failed to get peer info")?;
if !self
.discovery
.state
.is_relay_reservation_required(self.discovery.relay_config.registrations_limit)
{
return Ok(());
}
debug!(
%relay_peer,
?peer_info,
"Attempting to register with rendezvous node"
);
let preferred_addr = peer_info
.get_preferred_addr()
.wrap_err("Failed to get preferred addr for relay peer")?;
let relayed_addr = match preferred_addr
.clone()
.with(Protocol::P2pCircuit)
.with_p2p(*self.swarm.local_peer_id())
{
Ok(addr) => addr,
Err(err) => {
bail!("Failed to construct relayed addr for relay peer: {:?}", err)
}
};
let _ = self.swarm.listen_on(relayed_addr)?;
self.discovery
.state
.update_relay_reservation_status(relay_peer, RelayReservationStatus::Requested);
Ok(())
}
// TODO: Revisit AutoNAT protocol integration
// // Add a peer to the list of servers that may be used for determining our NAT status.
// // These peers are used for dial-request even if they are currently not connected,
// // in which case a connection will be established before sending the dial-request.
// pub(crate) fn add_autonat_server(&mut self, autonat_peer: &PeerId) -> EyreResult<()> {
// let peer_info = self
// .discovery
// .state
// .get_peer_info(autonat_peer)
// .wrap_err("Failed to get peer info")?;
// debug!(
// %autonat_peer,
// ?peer_info,
// "Adding peer to the list of autonat servers"
// );
// self.swarm
// .behaviour_mut()
// .autonat
// .add_server(*autonat_peer, None);
// Ok(())
// }
}