Skip to content

Commit

Permalink
fix(network): filter out localhost when identify notifies kademlia
Browse files Browse the repository at this point in the history
  • Loading branch information
ShahakShama authored and eitanm-starkware committed Aug 18, 2024
1 parent 7e04ae8 commit 6d48a42
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 18 deletions.
13 changes: 12 additions & 1 deletion crates/papyrus_network/src/discovery/identify_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use libp2p::{identify, Multiaddr, PeerId};

use crate::mixed_behaviour;
use crate::mixed_behaviour::BridgedBehaviour;
use crate::utils::is_localhost;

pub const IDENTIFY_PROTOCOL_VERSION: &str = "/staknet/identify/0.1.0-rc.0";

Expand All @@ -14,11 +15,21 @@ impl From<identify::Event> for mixed_behaviour::Event {
fn from(event: identify::Event) -> Self {
match event {
identify::Event::Received { peer_id, info } => {
// Filtering out localhost since it might collide with our own listen address if we
// use the same port.
// No need to filter out in discovery since there the address comes from the
// config, so if the user specified it they should make sure it doesn't collide
// with our own address
let listen_addresses = info
.listen_addrs
.into_iter()
.filter(|address| !is_localhost(address))
.collect();
mixed_behaviour::Event::ToOtherBehaviourEvent(
mixed_behaviour::ToOtherBehaviourEvent::Identify(
IdentifyToOtherBehaviourEvent::FoundListenAddresses {
peer_id,
listen_addresses: info.listen_addrs,
listen_addresses,
},
),
)
Expand Down
6 changes: 5 additions & 1 deletion crates/papyrus_network/src/discovery/kad_impl.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use libp2p::kad;
use tracing::error;
use tracing::{error, info};

use super::identify_impl::IdentifyToOtherBehaviourEvent;
use crate::mixed_behaviour::BridgedBehaviour;
Expand Down Expand Up @@ -48,6 +48,10 @@ impl<TStore: kad::store::RecordStore + Send + 'static> BridgedBehaviour for kad:
| mixed_behaviour::ToOtherBehaviourEvent::Discovery(
super::ToOtherBehaviourEvent::FoundListenAddresses { peer_id, listen_addresses },
) => {
info!(
"Adding new listen addresses to routing table for peer {peer_id:?}: \
{listen_addresses:?}"
);
for address in listen_addresses {
self.add_address(peer_id, address.clone());
}
Expand Down
17 changes: 2 additions & 15 deletions crates/papyrus_network/src/network_manager/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
mod swarm_trait;
use core::net::Ipv4Addr;

#[cfg(test)]
mod test;
Expand All @@ -14,10 +13,9 @@ use futures::future::{ready, BoxFuture, Ready};
use futures::sink::With;
use futures::stream::{self, FuturesUnordered, Map, Stream};
use futures::{pin_mut, FutureExt, Sink, SinkExt, StreamExt};
use libp2p::core::multiaddr::Protocol;
use libp2p::gossipsub::{SubscriptionError, TopicHash};
use libp2p::swarm::SwarmEvent;
use libp2p::{Multiaddr, PeerId, StreamProtocol, Swarm};
use libp2p::{PeerId, StreamProtocol, Swarm};
use metrics::gauge;
use papyrus_common::metrics as papyrus_metrics;
use sqmr::Bytes;
Expand All @@ -28,7 +26,7 @@ use crate::bin_utils::build_swarm;
use crate::gossipsub_impl::Topic;
use crate::mixed_behaviour::{self, BridgedBehaviour};
use crate::sqmr::{self, InboundSessionId, OutboundSessionId, SessionId};
use crate::utils::StreamHashMap;
use crate::utils::{is_localhost, StreamHashMap};
use crate::{gossipsub_impl, NetworkConfig};

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -924,14 +922,3 @@ pub struct TestSubscriberChannels<T: TryFrom<Bytes>> {
pub subscriber_channels: BroadcastSubscriberChannels<T>,
pub mock_network: BroadcastNetworkMock<T>,
}

fn is_localhost(address: &Multiaddr) -> bool {
let maybe_ip4_address = address.iter().find_map(|protocol| match protocol {
Protocol::Ip4(ip4_address) => Some(ip4_address),
_ => None,
});
let Some(ip4_address) = maybe_ip4_address else {
return false;
};
ip4_address == Ipv4Addr::LOCALHOST
}
16 changes: 15 additions & 1 deletion crates/papyrus_network/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
use core::net::Ipv4Addr;
use std::collections::hash_map::{Keys, ValuesMut};
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

use futures::stream::{Stream, StreamExt};
use libp2p::core::multiaddr::Protocol;
use libp2p::Multiaddr;

// This is an implementation of `StreamMap` from tokio_stream. The reason we're implementing it
// ourselves is that the implementation in tokio_stream requires that the values implement the
// Stream trait from tokio_stream and not from futures.
pub(crate) struct StreamHashMap<K: Unpin + Clone + Eq + Hash, V: Stream + Unpin> {
pub struct StreamHashMap<K: Unpin + Clone + Eq + Hash, V: Stream + Unpin> {
map: HashMap<K, V>,
wakers_waiting_for_new_stream: Vec<Waker>,
}
Expand Down Expand Up @@ -66,3 +69,14 @@ impl<K: Unpin + Clone + Eq + Hash, V: Stream + Unpin> Stream for StreamHashMap<K
Poll::Pending
}
}

pub fn is_localhost(address: &Multiaddr) -> bool {
let maybe_ip4_address = address.iter().find_map(|protocol| match protocol {
Protocol::Ip4(ip4_address) => Some(ip4_address),
_ => None,
});
let Some(ip4_address) = maybe_ip4_address else {
return false;
};
ip4_address == Ipv4Addr::LOCALHOST
}

0 comments on commit 6d48a42

Please sign in to comment.