File size: 15,954 Bytes
f0f4f2b | 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | // Copyright 2021 Protocol Labs.
//
// 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 async_std::task::JoinHandle;
use libp2p_autonat::{
Behaviour, Config, Event, NatStatus, OutboundProbeError, OutboundProbeEvent, ResponseError,
};
use libp2p_core::Multiaddr;
use libp2p_identity::PeerId;
use libp2p_swarm::{Swarm, SwarmEvent};
use libp2p_swarm_test::SwarmExt as _;
use std::time::Duration;
const MAX_CONFIDENCE: usize = 3;
const TEST_RETRY_INTERVAL: Duration = Duration::from_secs(1);
const TEST_REFRESH_INTERVAL: Duration = Duration::from_secs(2);
#[async_std::test]
async fn test_auto_probe() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
only_global_ips: false,
throttle_server_period: Duration::ZERO,
boot_delay: Duration::ZERO,
..Default::default()
},
)
});
let (server_id, addr, _) = new_server_swarm().await;
client.behaviour_mut().add_server(server_id, Some(addr));
// Initial status should be unknown.
assert_eq!(client.behaviour().nat_status(), NatStatus::Unknown);
assert!(client.behaviour().public_address().is_none());
assert_eq!(client.behaviour().confidence(), 0);
// Test no listening addresses
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Error { peer, error, .. }) => {
assert!(peer.is_none());
assert!(matches!(error, OutboundProbeError::NoAddresses));
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
assert_eq!(client.behaviour().nat_status(), NatStatus::Unknown);
assert!(client.behaviour().public_address().is_none());
assert_eq!(client.behaviour().confidence(), 0);
// Test new public listening address
client.listen().await;
let id = match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Request { probe_id, peer }) => {
assert_eq!(peer, server_id);
probe_id
}
other => panic!("Unexpected behaviour event: {other:?}."),
};
let mut had_connection_event = false;
loop {
match client.next_swarm_event().await {
SwarmEvent::ConnectionEstablished {
endpoint, peer_id, ..
} if endpoint.is_listener() => {
assert_eq!(peer_id, server_id);
had_connection_event = true;
}
SwarmEvent::Behaviour(Event::OutboundProbe(OutboundProbeEvent::Response {
probe_id,
peer,
..
})) => {
assert_eq!(peer, server_id);
assert_eq!(probe_id, id);
}
SwarmEvent::Behaviour(Event::StatusChanged { old, new }) => {
// Expect to flip status to public
assert_eq!(old, NatStatus::Unknown);
assert!(matches!(new, NatStatus::Public(_)));
assert!(new.is_public());
break;
}
SwarmEvent::IncomingConnection { .. }
| SwarmEvent::ConnectionEstablished { .. }
| SwarmEvent::Dialing { .. }
| SwarmEvent::NewListenAddr { .. }
| SwarmEvent::ExpiredListenAddr { .. } => {}
other => panic!("Unexpected swarm event: {other:?}."),
}
}
// It can happen that the server observed the established connection and
// returned a response before the inbound established connection was reported at the client.
// In this (rare) case the `ConnectionEstablished` event occurs after the `OutboundProbeEvent::Response`.
if !had_connection_event {
match client.next_swarm_event().await {
SwarmEvent::ConnectionEstablished {
endpoint, peer_id, ..
} if endpoint.is_listener() => {
assert_eq!(peer_id, server_id);
}
other => panic!("Unexpected swarm event: {other:?}."),
}
}
assert_eq!(client.behaviour().confidence(), 0);
assert!(client.behaviour().nat_status().is_public());
assert!(client.behaviour().public_address().is_some());
}
#[async_std::test]
async fn test_confidence() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
only_global_ips: false,
throttle_server_period: Duration::ZERO,
boot_delay: Duration::from_millis(100),
..Default::default()
},
)
});
let (server_id, addr, _) = new_server_swarm().await;
client.behaviour_mut().add_server(server_id, Some(addr));
// Randomly test either for public or for private status the confidence.
let test_public = rand::random::<bool>();
if test_public {
client.listen().with_memory_addr_external().await;
} else {
let unreachable_addr = "/ip4/127.0.0.1/tcp/42".parse().unwrap();
client.behaviour_mut().probe_address(unreachable_addr);
}
for i in 0..MAX_CONFIDENCE + 1 {
let id = match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Request { probe_id, peer }) => {
assert_eq!(peer, server_id);
probe_id
}
other => panic!("Unexpected behaviour event: {other:?}."),
};
match client.next_behaviour_event().await {
Event::OutboundProbe(event) => {
let (peer, probe_id) = match event {
OutboundProbeEvent::Response { probe_id, peer, .. } if test_public => {
(peer, probe_id)
}
OutboundProbeEvent::Error {
probe_id,
peer,
error,
} if !test_public => {
assert!(matches!(
error,
OutboundProbeError::Response(ResponseError::DialError)
));
(peer.unwrap(), probe_id)
}
other => panic!("Unexpected Outbound Event: {other:?}"),
};
assert_eq!(peer, server_id);
assert_eq!(probe_id, id);
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
// Confidence should increase each iteration up to MAX_CONFIDENCE
let expect_confidence = if i <= MAX_CONFIDENCE {
i
} else {
MAX_CONFIDENCE
};
assert_eq!(client.behaviour().confidence(), expect_confidence);
assert_eq!(client.behaviour().nat_status().is_public(), test_public);
// Expect status to flip after first probe
if i == 0 {
match client.next_behaviour_event().await {
Event::StatusChanged { old, new } => {
assert_eq!(old, NatStatus::Unknown);
assert_eq!(new.is_public(), test_public);
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
}
}
#[async_std::test]
async fn test_throttle_server_period() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
only_global_ips: false,
// Throttle servers so they can not be re-used for dial request.
throttle_server_period: Duration::from_secs(1000),
boot_delay: Duration::from_millis(100),
..Default::default()
},
)
});
client.listen().await;
let (server_id, addr, _) = new_server_swarm().await;
client.behaviour_mut().add_server(server_id, Some(addr));
// First probe should be successful and flip status to public.
loop {
match client.next_behaviour_event().await {
Event::StatusChanged { old, new } => {
assert_eq!(old, NatStatus::Unknown);
assert!(new.is_public());
break;
}
Event::OutboundProbe(OutboundProbeEvent::Request { .. }) => {}
Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
assert_eq!(client.behaviour().confidence(), 0);
// Expect following probe to fail because server is throttled
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Error { peer, error, .. }) => {
assert!(peer.is_none());
assert!(matches!(error, OutboundProbeError::NoServer));
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
assert_eq!(client.behaviour().confidence(), 0);
}
#[async_std::test]
async fn test_use_connected_as_server() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
only_global_ips: false,
throttle_server_period: Duration::ZERO,
boot_delay: Duration::from_millis(100),
..Default::default()
},
)
});
let (server_id, addr, _) = new_server_swarm().await;
client.listen().await;
let connected = client.dial_and_wait(addr).await;
assert_eq!(connected, server_id);
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Request { peer, .. }) => {
assert_eq!(peer, server_id);
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Response { peer, .. }) => {
assert_eq!(peer, server_id);
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
#[async_std::test]
async fn test_outbound_failure() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
only_global_ips: false,
throttle_server_period: Duration::ZERO,
boot_delay: Duration::from_millis(100),
..Default::default()
},
)
});
let mut servers = Vec::new();
for _ in 0..5 {
let (id, addr, handle) = new_server_swarm().await;
client.behaviour_mut().add_server(id, Some(addr));
servers.push((id, handle));
}
client.listen().await;
// First probe should be successful and flip status to public.
loop {
match client.next_behaviour_event().await {
Event::StatusChanged { old, new } => {
assert_eq!(old, NatStatus::Unknown);
assert!(new.is_public());
break;
}
Event::OutboundProbe(OutboundProbeEvent::Request { .. }) => {}
Event::OutboundProbe(OutboundProbeEvent::Response { .. }) => {}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
// kill a server
let mut inactive_servers = Vec::new();
for (id, handle) in servers.split_off(1) {
handle.cancel().await;
inactive_servers.push(id);
}
// Expect to retry on outbound failure
loop {
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Request { .. }) => {}
Event::OutboundProbe(OutboundProbeEvent::Response { peer, .. }) => {
assert_eq!(peer, servers[0].0);
break;
}
Event::OutboundProbe(OutboundProbeEvent::Error {
peer: Some(peer),
error: OutboundProbeError::OutboundRequest(_),
..
}) => {
assert!(inactive_servers.contains(&peer));
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
}
#[async_std::test]
async fn test_global_ips_config() {
let mut client = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
retry_interval: TEST_RETRY_INTERVAL,
refresh_interval: TEST_REFRESH_INTERVAL,
confidence_max: MAX_CONFIDENCE,
// Enforce that only peers outside of the local network are used as servers.
only_global_ips: true,
boot_delay: Duration::from_millis(100),
..Default::default()
},
)
});
client.listen().await;
let (server_id, addr, _) = new_server_swarm().await;
// Dial server instead of adding it via `Behaviour::add_server` because the
// `only_global_ips` restriction does not apply for manually added servers.
let connected = client.dial_and_wait(addr).await;
assert_eq!(connected, server_id);
// Expect that the server is not qualified for dial-back because it is observed
// at a local IP.
match client.next_behaviour_event().await {
Event::OutboundProbe(OutboundProbeEvent::Error { error, .. }) => {
assert!(matches!(error, OutboundProbeError::NoServer))
}
other => panic!("Unexpected behaviour event: {other:?}."),
}
}
async fn new_server_swarm() -> (PeerId, Multiaddr, JoinHandle<()>) {
let mut swarm = Swarm::new_ephemeral(|key| {
Behaviour::new(
key.public().to_peer_id(),
Config {
boot_delay: Duration::from_secs(60),
throttle_clients_peer_max: usize::MAX,
only_global_ips: false,
..Default::default()
},
)
});
let (_, multiaddr) = swarm.listen().await;
let peer_id = *swarm.local_peer_id();
let task = async_std::task::spawn(swarm.loop_on_next());
(peer_id, multiaddr, task)
}
|