diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index 684226fa..ba46dfdf 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -167,17 +167,30 @@ impl Floodsub { true } - /// Publishes a message to the network. - /// - /// > **Note**: Doesn't do anything if we're not subscribed to the topic. + /// Publishes a message to the network, if we're subscribed to the topic only. pub fn publish(&mut self, topic: impl Into, data: impl Into>) { self.publish_many(iter::once(topic), data) } + /// Publishes a message to the network, even if we're not subscribed to the topic. + pub fn publish_any(&mut self, topic: impl Into, data: impl Into>) { + self.publish_many_any(iter::once(topic), data) + } + /// Publishes a message with multiple topics to the network. /// + /// /// > **Note**: Doesn't do anything if we're not subscribed to any of the topics. pub fn publish_many(&mut self, topic: impl IntoIterator>, data: impl Into>) { + self.publish_many_inner(topic, data, true) + } + + /// Publishes a message with multiple topics to the network, even if we're not subscribed to any of the topics. + pub fn publish_many_any(&mut self, topic: impl IntoIterator>, data: impl Into>) { + self.publish_many_inner(topic, data, false) + } + + fn publish_many_inner(&mut self, topic: impl IntoIterator>, data: impl Into>, check_self_subscriptions: bool) { let message = FloodsubMessage { source: self.local_peer_id.clone(), data: data.into(), @@ -188,12 +201,15 @@ impl Floodsub { topics: topic.into_iter().map(|t| t.into().clone()).collect(), }; - // Don't publish the message if we're not subscribed ourselves to any of the topics. - if !self.subscribed_topics.iter().any(|t| message.topics.iter().any(|u| t.hash() == u)) { - return; + let self_subscribed = self.subscribed_topics.iter().any(|t| message.topics.iter().any(|u| t.hash() == u)); + if self_subscribed { + self.received.add(&message); + } + // Don't publish the message if we have to check subscriptions + // and we're not subscribed ourselves to any of the topics. + if check_self_subscriptions && !self_subscribed { + return } - - self.received.add(&message); // Send to peers we know are subscribed to the topic. for (peer_id, sub_topic) in self.connected_peers.iter() {