From 3c4d34e4c308a3b2090a0035b6161a3a6598ded6 Mon Sep 17 00:00:00 2001 From: StemCll Date: Mon, 11 Sep 2023 22:48:46 +0200 Subject: [PATCH] Add basic kad behaviour test --- protocols/kad/src/behaviour/test.rs | 83 +++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/protocols/kad/src/behaviour/test.rs b/protocols/kad/src/behaviour/test.rs index cd4337e9094c..ade1bc8ddf77 100644 --- a/protocols/kad/src/behaviour/test.rs +++ b/protocols/kad/src/behaviour/test.rs @@ -1378,6 +1378,89 @@ fn network_behaviour_on_address_change() { ); } +#[test] +fn network_behaviour_on_new_external_address_of_peer_for_present_entry() { + let local_peer_id = PeerId::random(); + + let remote_peer_id = PeerId::random(); + let connection_id = ConnectionId::new_unchecked(0); + let address: Multiaddr = Protocol::Memory(1).into(); + let discovered_address: Multiaddr = Protocol::Memory(2).into(); + + let mut kademlia = Kademlia::new(local_peer_id, MemoryStore::new(local_peer_id)); + + let endpoint = ConnectedPoint::Dialer { + address: address.clone(), + role_override: Endpoint::Dialer, + }; + + // Mimick a connection being established. + kademlia.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: remote_peer_id, + connection_id, + endpoint: &endpoint, + failed_addresses: &[], + other_established: 0, + })); + + // At this point the remote is not yet known to support the + // configured protocol name, so the peer is not yet in the + // local routing table and hence no addresses are known. + assert!(kademlia + .handle_pending_outbound_connection( + connection_id, + Some(remote_peer_id), + &[], + Endpoint::Dialer + ) + .unwrap() + .is_empty()); + + // Mimick the connection handler confirming the protocol for + // the test connection, so that the peer is added to the routing table. + kademlia.on_connection_handler_event( + remote_peer_id, + connection_id, + KademliaHandlerEvent::ProtocolConfirmed { endpoint }, + ); + + let key = kbucket::Key::from(remote_peer_id); + + assert!(matches!( + kademlia.kbuckets.entry(&key), + kbucket::Entry::Present(_, _) + )); + + assert_eq!( + vec![address.clone()], + kademlia + .handle_pending_outbound_connection( + connection_id, + Some(remote_peer_id), + &[], + Endpoint::Dialer + ) + .unwrap(), + ); + + kademlia.on_new_address_event(NewExternalAddrOfPeer { + addr: &discovered_address, + peer_id: &remote_peer_id, + }); + + assert_eq!( + vec![address, discovered_address], + kademlia + .handle_pending_outbound_connection( + connection_id, + Some(remote_peer_id), + &[], + Endpoint::Dialer + ) + .unwrap(), + ); +} + #[test] fn get_providers_single() { fn prop(key: record_priv::Key) {