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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use crate::ResponseError;
use super::{
Action, AutoNatCodec, Config, DialRequest, DialResponse, Event, HandleInnerEvent, NatStatus,
ProbeId,
};
use futures::FutureExt;
use futures_timer::Delay;
use instant::Instant;
use libp2p_core::{connection::ConnectionId, Multiaddr, PeerId};
use libp2p_request_response::{
OutboundFailure, RequestId, RequestResponse, RequestResponseEvent, RequestResponseMessage,
};
use libp2p_swarm::{AddressScore, NetworkBehaviourAction, PollParameters};
use rand::{seq::SliceRandom, thread_rng};
use std::{
collections::{HashMap, VecDeque},
task::{Context, Poll},
time::Duration,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboundProbeError {
NoServer,
NoAddresses,
OutboundRequest(OutboundFailure),
Response(ResponseError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutboundProbeEvent {
Request {
probe_id: ProbeId,
peer: PeerId,
},
Response {
probe_id: ProbeId,
peer: PeerId,
address: Multiaddr,
},
Error {
probe_id: ProbeId,
peer: Option<PeerId>,
error: OutboundProbeError,
},
}
pub struct AsClient<'a> {
pub inner: &'a mut RequestResponse<AutoNatCodec>,
pub local_peer_id: PeerId,
pub config: &'a Config,
pub connected: &'a HashMap<PeerId, HashMap<ConnectionId, Option<Multiaddr>>>,
pub probe_id: &'a mut ProbeId,
pub servers: &'a Vec<PeerId>,
pub throttled_servers: &'a mut Vec<(PeerId, Instant)>,
pub nat_status: &'a mut NatStatus,
pub confidence: &'a mut usize,
pub ongoing_outbound: &'a mut HashMap<RequestId, ProbeId>,
pub last_probe: &'a mut Option<Instant>,
pub schedule_probe: &'a mut Delay,
}
impl<'a> HandleInnerEvent for AsClient<'a> {
fn handle_event(
&mut self,
params: &mut impl PollParameters,
event: RequestResponseEvent<DialRequest, DialResponse>,
) -> (VecDeque<Event>, Option<Action>) {
let mut events = VecDeque::new();
let mut action = None;
match event {
RequestResponseEvent::Message {
peer,
message:
RequestResponseMessage::Response {
request_id,
response,
},
} => {
log::debug!("Outbound dial-back request returned {:?}.", response);
let probe_id = self
.ongoing_outbound
.remove(&request_id)
.expect("RequestId exists.");
let event = match response.result.clone() {
Ok(address) => OutboundProbeEvent::Response {
probe_id,
peer,
address,
},
Err(e) => OutboundProbeEvent::Error {
probe_id,
peer: Some(peer),
error: OutboundProbeError::Response(e),
},
};
events.push_back(Event::OutboundProbe(event));
if let Some(old) = self.handle_reported_status(response.result.clone().into()) {
events.push_back(Event::StatusChanged {
old,
new: self.nat_status.clone(),
});
}
if let Ok(address) = response.result {
let score = params
.external_addresses()
.find_map(|r| (r.addr == address).then_some(r.score))
.unwrap_or(AddressScore::Finite(0));
if let AddressScore::Finite(finite_score) = score {
action = Some(NetworkBehaviourAction::ReportObservedAddr {
address,
score: AddressScore::Finite(finite_score + 1),
});
}
}
}
RequestResponseEvent::OutboundFailure {
peer,
error,
request_id,
} => {
log::debug!(
"Outbound Failure {} when on dial-back request to peer {}.",
error,
peer
);
let probe_id = self
.ongoing_outbound
.remove(&request_id)
.unwrap_or_else(|| self.probe_id.next());
events.push_back(Event::OutboundProbe(OutboundProbeEvent::Error {
probe_id,
peer: Some(peer),
error: OutboundProbeError::OutboundRequest(error),
}));
self.schedule_probe.reset(Duration::ZERO);
}
_ => {}
}
(events, action)
}
}
impl<'a> AsClient<'a> {
pub fn poll_auto_probe(
&mut self,
params: &mut impl PollParameters,
cx: &mut Context<'_>,
) -> Poll<OutboundProbeEvent> {
match self.schedule_probe.poll_unpin(cx) {
Poll::Ready(()) => {
self.schedule_probe.reset(self.config.retry_interval);
let mut addresses: Vec<_> = params.external_addresses().map(|r| r.addr).collect();
addresses.extend(params.listened_addresses());
let probe_id = self.probe_id.next();
let event = match self.do_probe(probe_id, addresses) {
Ok(peer) => OutboundProbeEvent::Request { probe_id, peer },
Err(error) => {
self.handle_reported_status(NatStatus::Unknown);
OutboundProbeEvent::Error {
probe_id,
peer: None,
error,
}
}
};
Poll::Ready(event)
}
Poll::Pending => Poll::Pending,
}
}
pub fn on_inbound_connection(&mut self) {
if *self.confidence == self.config.confidence_max {
if self.nat_status.is_public() {
self.schedule_next_probe(self.config.refresh_interval * 2);
} else {
self.schedule_next_probe(self.config.refresh_interval / 5);
}
}
}
pub fn on_new_address(&mut self) {
if !self.nat_status.is_public() {
if *self.confidence > 0 {
*self.confidence -= 1;
}
self.schedule_next_probe(self.config.retry_interval);
}
}
pub fn on_expired_address(&mut self, addr: &Multiaddr) {
if let NatStatus::Public(public_address) = self.nat_status {
if public_address == addr {
*self.confidence = 0;
*self.nat_status = NatStatus::Unknown;
self.schedule_next_probe(Duration::ZERO);
}
}
}
fn random_server(&mut self) -> Option<PeerId> {
let i = self.throttled_servers.partition_point(|(_, time)| {
*time + self.config.throttle_server_period < Instant::now()
});
self.throttled_servers.drain(..i);
let mut servers: Vec<&PeerId> = self.servers.iter().collect();
if self.config.use_connected {
servers.extend(self.connected.iter().filter_map(|(id, addrs)| {
addrs.values().any(|a| a.is_some()).then_some(id)
}));
}
servers.retain(|s| !self.throttled_servers.iter().any(|(id, _)| s == &id));
servers.choose(&mut thread_rng()).map(|&&p| p)
}
fn do_probe(
&mut self,
probe_id: ProbeId,
addresses: Vec<Multiaddr>,
) -> Result<PeerId, OutboundProbeError> {
let _ = self.last_probe.insert(Instant::now());
if addresses.is_empty() {
log::debug!("Outbound dial-back request aborted: No dial-back addresses.");
return Err(OutboundProbeError::NoAddresses);
}
let server = match self.random_server() {
Some(s) => s,
None => {
log::debug!("Outbound dial-back request aborted: No qualified server.");
return Err(OutboundProbeError::NoServer);
}
};
let request_id = self.inner.send_request(
&server,
DialRequest {
peer_id: self.local_peer_id,
addresses,
},
);
self.throttled_servers.push((server, Instant::now()));
log::debug!("Send dial-back request to peer {}.", server);
self.ongoing_outbound.insert(request_id, probe_id);
Ok(server)
}
fn schedule_next_probe(&mut self, delay: Duration) {
let last_probe_instant = match self.last_probe {
Some(instant) => instant,
None => {
return;
}
};
let schedule_next = *last_probe_instant + delay;
self.schedule_probe
.reset(schedule_next.saturating_duration_since(Instant::now()));
}
fn handle_reported_status(&mut self, reported_status: NatStatus) -> Option<NatStatus> {
self.schedule_next_probe(self.config.retry_interval);
if matches!(reported_status, NatStatus::Unknown) {
return None;
}
if reported_status == *self.nat_status {
if *self.confidence < self.config.confidence_max {
*self.confidence += 1;
}
if *self.confidence >= self.config.confidence_max {
self.schedule_next_probe(self.config.refresh_interval);
}
return None;
}
if reported_status.is_public() && self.nat_status.is_public() {
*self.nat_status = reported_status;
return None;
}
if *self.confidence > 0 {
*self.confidence -= 1;
return None;
}
log::debug!(
"Flipped assumed NAT status from {:?} to {:?}",
self.nat_status,
reported_status
);
let old_status = self.nat_status.clone();
*self.nat_status = reported_status;
Some(old_status)
}
}
impl From<Result<Multiaddr, ResponseError>> for NatStatus {
fn from(result: Result<Multiaddr, ResponseError>) -> Self {
match result {
Ok(addr) => NatStatus::Public(addr),
Err(ResponseError::DialError) => NatStatus::Private,
_ => NatStatus::Unknown,
}
}
}