| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| use crate::protocol::{ |
| FloodsubMessage, FloodsubProtocol, FloodsubRpc, FloodsubSubscription, |
| FloodsubSubscriptionAction, |
| }; |
| use crate::topic::Topic; |
| use crate::FloodsubConfig; |
| use bytes::Bytes; |
| use cuckoofilter::{CuckooError, CuckooFilter}; |
| use fnv::FnvHashSet; |
| use libp2p_core::transport::PortUse; |
| use libp2p_core::{Endpoint, Multiaddr}; |
| use libp2p_identity::PeerId; |
| use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}; |
| use libp2p_swarm::{ |
| dial_opts::DialOpts, CloseConnection, ConnectionDenied, ConnectionId, NetworkBehaviour, |
| NotifyHandler, OneShotHandler, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, |
| }; |
| use smallvec::SmallVec; |
| use std::collections::hash_map::{DefaultHasher, HashMap}; |
| use std::task::{Context, Poll}; |
| use std::{collections::VecDeque, iter}; |
|
|
| |
| pub struct Floodsub { |
| |
| events: VecDeque<ToSwarm<FloodsubEvent, FloodsubRpc>>, |
|
|
| config: FloodsubConfig, |
|
|
| |
| target_peers: FnvHashSet<PeerId>, |
|
|
| |
| |
| |
| connected_peers: HashMap<PeerId, SmallVec<[Topic; 8]>>, |
|
|
| |
| |
| subscribed_topics: SmallVec<[Topic; 16]>, |
|
|
| |
| |
| received: CuckooFilter<DefaultHasher>, |
| } |
|
|
| impl Floodsub { |
| |
| pub fn new(local_peer_id: PeerId) -> Self { |
| Self::from_config(FloodsubConfig::new(local_peer_id)) |
| } |
|
|
| |
| pub fn from_config(config: FloodsubConfig) -> Self { |
| Floodsub { |
| events: VecDeque::new(), |
| config, |
| target_peers: FnvHashSet::default(), |
| connected_peers: HashMap::new(), |
| subscribed_topics: SmallVec::new(), |
| received: CuckooFilter::new(), |
| } |
| } |
|
|
| |
| #[inline] |
| pub fn add_node_to_partial_view(&mut self, peer_id: PeerId) { |
| |
| if self.connected_peers.contains_key(&peer_id) { |
| for topic in self.subscribed_topics.iter().cloned() { |
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id, |
| handler: NotifyHandler::Any, |
| event: FloodsubRpc { |
| messages: Vec::new(), |
| subscriptions: vec![FloodsubSubscription { |
| topic, |
| action: FloodsubSubscriptionAction::Subscribe, |
| }], |
| }, |
| }); |
| } |
| } |
|
|
| if self.target_peers.insert(peer_id) { |
| self.events.push_back(ToSwarm::Dial { |
| opts: DialOpts::peer_id(peer_id).build(), |
| }); |
| } |
| } |
|
|
| |
| #[inline] |
| pub fn remove_node_from_partial_view(&mut self, peer_id: &PeerId) { |
| self.target_peers.remove(peer_id); |
| } |
|
|
| |
| |
| |
| pub fn subscribe(&mut self, topic: Topic) -> bool { |
| if self.subscribed_topics.iter().any(|t| t.id() == topic.id()) { |
| return false; |
| } |
|
|
| for peer in self.connected_peers.keys() { |
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id: *peer, |
| handler: NotifyHandler::Any, |
| event: FloodsubRpc { |
| messages: Vec::new(), |
| subscriptions: vec![FloodsubSubscription { |
| topic: topic.clone(), |
| action: FloodsubSubscriptionAction::Subscribe, |
| }], |
| }, |
| }); |
| } |
|
|
| self.subscribed_topics.push(topic); |
| true |
| } |
|
|
| |
| |
| |
| |
| |
| pub fn unsubscribe(&mut self, topic: Topic) -> bool { |
| let Some(pos) = self.subscribed_topics.iter().position(|t| *t == topic) else { |
| return false; |
| }; |
|
|
| self.subscribed_topics.remove(pos); |
|
|
| for peer in self.connected_peers.keys() { |
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id: *peer, |
| handler: NotifyHandler::Any, |
| event: FloodsubRpc { |
| messages: Vec::new(), |
| subscriptions: vec![FloodsubSubscription { |
| topic: topic.clone(), |
| action: FloodsubSubscriptionAction::Unsubscribe, |
| }], |
| }, |
| }); |
| } |
|
|
| true |
| } |
|
|
| |
| pub fn publish(&mut self, topic: impl Into<Topic>, data: impl Into<Bytes>) { |
| self.publish_many(iter::once(topic), data) |
| } |
|
|
| |
| pub fn publish_any(&mut self, topic: impl Into<Topic>, data: impl Into<Bytes>) { |
| self.publish_many_any(iter::once(topic), data) |
| } |
|
|
| |
| |
| |
| |
| pub fn publish_many( |
| &mut self, |
| topic: impl IntoIterator<Item = impl Into<Topic>>, |
| data: impl Into<Bytes>, |
| ) { |
| self.publish_many_inner(topic, data, true) |
| } |
|
|
| |
| pub fn publish_many_any( |
| &mut self, |
| topic: impl IntoIterator<Item = impl Into<Topic>>, |
| data: impl Into<Bytes>, |
| ) { |
| self.publish_many_inner(topic, data, false) |
| } |
|
|
| fn publish_many_inner( |
| &mut self, |
| topic: impl IntoIterator<Item = impl Into<Topic>>, |
| data: impl Into<Bytes>, |
| check_self_subscriptions: bool, |
| ) { |
| let message = FloodsubMessage { |
| source: self.config.local_peer_id, |
| data: data.into(), |
| |
| |
| |
| sequence_number: rand::random::<[u8; 20]>().to_vec(), |
| topics: topic.into_iter().map(Into::into).collect(), |
| }; |
|
|
| let self_subscribed = self |
| .subscribed_topics |
| .iter() |
| .any(|t| message.topics.iter().any(|u| t == u)); |
| if self_subscribed { |
| if let Err(e @ CuckooError::NotEnoughSpace) = self.received.add(&message) { |
| tracing::warn!( |
| "Message was added to 'received' Cuckoofilter but some \ |
| other message was removed as a consequence: {}", |
| e, |
| ); |
| } |
| if self.config.subscribe_local_messages { |
| self.events |
| .push_back(ToSwarm::GenerateEvent(FloodsubEvent::Message( |
| message.clone(), |
| ))); |
| } |
| } |
| |
| |
| if check_self_subscriptions && !self_subscribed { |
| return; |
| } |
|
|
| |
| for (peer_id, sub_topic) in self.connected_peers.iter() { |
| |
| if !self.target_peers.contains(peer_id) { |
| continue; |
| } |
|
|
| |
| if !sub_topic |
| .iter() |
| .any(|t| message.topics.iter().any(|u| t == u)) |
| { |
| continue; |
| } |
|
|
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id: *peer_id, |
| handler: NotifyHandler::Any, |
| event: FloodsubRpc { |
| subscriptions: Vec::new(), |
| messages: vec![message.clone()], |
| }, |
| }); |
| } |
| } |
|
|
| fn on_connection_established( |
| &mut self, |
| ConnectionEstablished { |
| peer_id, |
| other_established, |
| .. |
| }: ConnectionEstablished, |
| ) { |
| if other_established > 0 { |
| |
| return; |
| } |
|
|
| |
| if self.target_peers.contains(&peer_id) { |
| for topic in self.subscribed_topics.iter().cloned() { |
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id, |
| handler: NotifyHandler::Any, |
| event: FloodsubRpc { |
| messages: Vec::new(), |
| subscriptions: vec![FloodsubSubscription { |
| topic, |
| action: FloodsubSubscriptionAction::Subscribe, |
| }], |
| }, |
| }); |
| } |
| } |
|
|
| self.connected_peers.insert(peer_id, SmallVec::new()); |
| } |
|
|
| fn on_connection_closed( |
| &mut self, |
| ConnectionClosed { |
| peer_id, |
| remaining_established, |
| .. |
| }: ConnectionClosed, |
| ) { |
| if remaining_established > 0 { |
| |
| return; |
| } |
|
|
| let was_in = self.connected_peers.remove(&peer_id); |
| debug_assert!(was_in.is_some()); |
|
|
| |
| |
| if self.target_peers.contains(&peer_id) { |
| self.events.push_back(ToSwarm::Dial { |
| opts: DialOpts::peer_id(peer_id).build(), |
| }); |
| } |
| } |
| } |
|
|
| impl NetworkBehaviour for Floodsub { |
| type ConnectionHandler = OneShotHandler<FloodsubProtocol, FloodsubRpc, InnerMessage>; |
| type ToSwarm = FloodsubEvent; |
|
|
| fn handle_established_inbound_connection( |
| &mut self, |
| _: ConnectionId, |
| _: PeerId, |
| _: &Multiaddr, |
| _: &Multiaddr, |
| ) -> Result<THandler<Self>, ConnectionDenied> { |
| Ok(Default::default()) |
| } |
|
|
| fn handle_established_outbound_connection( |
| &mut self, |
| _: ConnectionId, |
| _: PeerId, |
| _: &Multiaddr, |
| _: Endpoint, |
| _: PortUse, |
| ) -> Result<THandler<Self>, ConnectionDenied> { |
| Ok(Default::default()) |
| } |
|
|
| fn on_connection_handler_event( |
| &mut self, |
| propagation_source: PeerId, |
| connection_id: ConnectionId, |
| event: THandlerOutEvent<Self>, |
| ) { |
| |
| let event = match event { |
| Ok(InnerMessage::Rx(event)) => event, |
| Ok(InnerMessage::Sent) => return, |
| Err(e) => { |
| tracing::debug!("Failed to send floodsub message: {e}"); |
| self.events.push_back(ToSwarm::CloseConnection { |
| peer_id: propagation_source, |
| connection: CloseConnection::One(connection_id), |
| }); |
| return; |
| } |
| }; |
|
|
| |
| for subscription in event.subscriptions { |
| let remote_peer_topics = self.connected_peers |
| .get_mut(&propagation_source) |
| .expect("connected_peers is kept in sync with the peers we are connected to; we are guaranteed to only receive events from connected peers; QED"); |
| match subscription.action { |
| FloodsubSubscriptionAction::Subscribe => { |
| if !remote_peer_topics.contains(&subscription.topic) { |
| remote_peer_topics.push(subscription.topic.clone()); |
| } |
| self.events |
| .push_back(ToSwarm::GenerateEvent(FloodsubEvent::Subscribed { |
| peer_id: propagation_source, |
| topic: subscription.topic, |
| })); |
| } |
| FloodsubSubscriptionAction::Unsubscribe => { |
| if let Some(pos) = remote_peer_topics |
| .iter() |
| .position(|t| t == &subscription.topic) |
| { |
| remote_peer_topics.remove(pos); |
| } |
| self.events |
| .push_back(ToSwarm::GenerateEvent(FloodsubEvent::Unsubscribed { |
| peer_id: propagation_source, |
| topic: subscription.topic, |
| })); |
| } |
| } |
| } |
|
|
| |
| let mut rpcs_to_dispatch: Vec<(PeerId, FloodsubRpc)> = Vec::new(); |
|
|
| for message in event.messages { |
| |
| |
| match self.received.test_and_add(&message) { |
| Ok(true) => {} |
| Ok(false) => continue, |
| Err(e @ CuckooError::NotEnoughSpace) => { |
| |
| tracing::warn!( |
| "Message was added to 'received' Cuckoofilter but some \ |
| other message was removed as a consequence: {}", |
| e, |
| ); |
| } |
| } |
|
|
| |
| if self |
| .subscribed_topics |
| .iter() |
| .any(|t| message.topics.iter().any(|u| t == u)) |
| { |
| let event = FloodsubEvent::Message(message.clone()); |
| self.events.push_back(ToSwarm::GenerateEvent(event)); |
| } |
|
|
| |
| for (peer_id, subscr_topics) in self.connected_peers.iter() { |
| if peer_id == &propagation_source { |
| continue; |
| } |
|
|
| |
| if !self.target_peers.contains(peer_id) { |
| continue; |
| } |
|
|
| |
| if !subscr_topics |
| .iter() |
| .any(|t| message.topics.iter().any(|u| t == u)) |
| { |
| continue; |
| } |
|
|
| if let Some(pos) = rpcs_to_dispatch.iter().position(|(p, _)| p == peer_id) { |
| rpcs_to_dispatch[pos].1.messages.push(message.clone()); |
| } else { |
| rpcs_to_dispatch.push(( |
| *peer_id, |
| FloodsubRpc { |
| subscriptions: Vec::new(), |
| messages: vec![message.clone()], |
| }, |
| )); |
| } |
| } |
| } |
|
|
| for (peer_id, rpc) in rpcs_to_dispatch { |
| self.events.push_back(ToSwarm::NotifyHandler { |
| peer_id, |
| handler: NotifyHandler::Any, |
| event: rpc, |
| }); |
| } |
| } |
|
|
| #[tracing::instrument(level = "trace", name = "NetworkBehaviour::poll", skip(self))] |
| fn poll(&mut self, _: &mut Context<'_>) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> { |
| if let Some(event) = self.events.pop_front() { |
| return Poll::Ready(event); |
| } |
|
|
| Poll::Pending |
| } |
|
|
| fn on_swarm_event(&mut self, event: FromSwarm) { |
| match event { |
| FromSwarm::ConnectionEstablished(connection_established) => { |
| self.on_connection_established(connection_established) |
| } |
| FromSwarm::ConnectionClosed(connection_closed) => { |
| self.on_connection_closed(connection_closed) |
| } |
| _ => {} |
| } |
| } |
| } |
|
|
| |
| #[derive(Debug)] |
| pub enum InnerMessage { |
| |
| Rx(FloodsubRpc), |
| |
| Sent, |
| } |
|
|
| impl From<FloodsubRpc> for InnerMessage { |
| #[inline] |
| fn from(rpc: FloodsubRpc) -> InnerMessage { |
| InnerMessage::Rx(rpc) |
| } |
| } |
|
|
| impl From<()> for InnerMessage { |
| #[inline] |
| fn from(_: ()) -> InnerMessage { |
| InnerMessage::Sent |
| } |
| } |
|
|
| |
| #[derive(Debug)] |
| pub enum FloodsubEvent { |
| |
| Message(FloodsubMessage), |
|
|
| |
| Subscribed { |
| |
| peer_id: PeerId, |
| |
| topic: Topic, |
| }, |
|
|
| |
| Unsubscribed { |
| |
| peer_id: PeerId, |
| |
| topic: Topic, |
| }, |
| } |
|
|