From 2914aa7c4f564fe44f120d5e321f5657e729c526 Mon Sep 17 00:00:00 2001 From: blacktemplar Date: Fri, 11 Dec 2020 16:45:43 +0100 Subject: [PATCH 1/5] rename generic types + add default types + update documentation links --- protocols/gossipsub/src/behaviour.rs | 105 ++++++++-------- protocols/gossipsub/src/behaviour/tests.rs | 22 ++-- protocols/gossipsub/src/config.rs | 117 ++++++++---------- protocols/gossipsub/src/error.rs | 9 +- protocols/gossipsub/src/lib.rs | 32 +++-- protocols/gossipsub/src/mcache.rs | 2 +- protocols/gossipsub/src/peer_score.rs | 8 +- protocols/gossipsub/src/peer_score/params.rs | 13 +- .../gossipsub/src/subscription_filter.rs | 4 +- protocols/gossipsub/src/topic.rs | 4 +- protocols/gossipsub/src/types.rs | 19 ++- 11 files changed, 164 insertions(+), 171 deletions(-) diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index ca3cb8f77f5..413813af817 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -47,7 +47,7 @@ use libp2p_swarm::{ }; use crate::backoff::BackoffStorage; -use crate::config::{Config, ValidationMode}; +use crate::config::{GossipsubConfig, ValidationMode}; use crate::error::{PublishError, SubscriptionError}; use crate::gossip_promises::GossipPromises; use crate::handler::{GossipsubHandler, HandlerEvent}; @@ -58,7 +58,7 @@ use crate::subscription_filter::{AllowAllSubscriptionFilter, TopicSubscriptionFi use crate::time_cache::{DuplicateCache, TimeCache}; use crate::topic::{Hasher, Topic, TopicHash}; use crate::types::{ - FastMessageId, GenericGossipsubMessage, GossipsubControlAction, GossipsubMessageWithId, + FastMessageId, GossipsubControlAction, GossipsubMessage, GossipsubMessageWithId, GossipsubSubscription, GossipsubSubscriptionAction, MessageAcceptance, MessageId, PeerInfo, RawGossipsubMessage, }; @@ -75,7 +75,7 @@ mod tests; /// Without signing, a number of privacy preserving modes can be selected. /// /// NOTE: The default validation settings are to require signatures. The [`ValidationMode`] -/// should be updated in the [`Config`] to allow for unsigned messages. +/// should be updated in the [`GossipsubConfig`] to allow for unsigned messages. #[derive(Clone)] pub enum MessageAuthenticity { /// Message signing is enabled. The author will be the owner of the key and the sequence number @@ -83,12 +83,12 @@ pub enum MessageAuthenticity { Signed(Keypair), /// Message signing is disabled. /// - /// The specified `PeerId` will be used as the author of all published messages. The sequence + /// The specified [`PeerId`] will be used as the author of all published messages. The sequence /// number will be randomized. Author(PeerId), /// Message signing is disabled. /// - /// A random `PeerId` will be used when publishing each message. The sequence number will be + /// A random [`PeerId`] will be used when publishing each message. The sequence number will be /// randomized. RandomAuthor, /// Message signing is disabled. @@ -96,7 +96,7 @@ pub enum MessageAuthenticity { /// The author of the message and the sequence numbers are excluded from the message. /// /// NOTE: Excluding these fields may make these messages invalid by other nodes who - /// enforce validation of these fields. See [`ValidationMode`] in the `Config` + /// enforce validation of these fields. See [`ValidationMode`] in the [`GossipsubConfig`] /// for how to customise this for rust-libp2p gossipsub. A custom `message_id` /// function will need to be set to prevent all messages from a peer being filtered /// as duplicates. @@ -116,12 +116,12 @@ impl MessageAuthenticity { /// Event that can be emitted by the gossipsub behaviour. #[derive(Debug)] -pub enum Event> { +pub enum GossipsubEvent = Vec> { /// A message has been received. Message { /// The peer that forwarded us this message. propagation_source: PeerId, - /// The `MessageId` of the message. This should be referenced by the application when + /// The [`MessageId`] of the message. This should be referenced by the application when /// validating a message (if required). message_id: MessageId, /// The message itself. @@ -142,8 +142,6 @@ pub enum Event> { topic: TopicHash, }, } -// For general use cases -pub type GossipsubEvent = Event>; /// A data structure for storing configuration for publishing messages. See [`MessageAuthenticity`] /// for further details. @@ -196,16 +194,20 @@ impl From for PublishConfig { } } -type GossipsubNetworkBehaviourAction = NetworkBehaviourAction, Event>; +type GossipsubNetworkBehaviourAction = + NetworkBehaviourAction, GossipsubEvent>; /// Network behaviour that handles the gossipsub protocol. /// -/// NOTE: Initialisation requires a [`MessageAuthenticity`] and [`Config`] instance. If message signing is -/// disabled, the [`ValidationMode`] in the config should be adjusted to an appropriate level to -/// accept unsigned messages. -pub struct GenericGossipsub, Filter: TopicSubscriptionFilter> { +/// NOTE: Initialisation requires a [`MessageAuthenticity`] and [`GossipsubConfig`] instance. If +/// message signing is disabled, the [`ValidationMode`] in the config should be adjusted to an +/// appropriate level to accept unsigned messages. +pub struct Gossipsub< + T: AsRef<[u8]> = Vec, + Filter: TopicSubscriptionFilter = AllowAllSubscriptionFilter, +> { /// Configuration providing gossipsub performance parameters. - config: Config, + config: GossipsubConfig, /// Events that need to be yielded to the outside when polling. events: VecDeque>, @@ -291,29 +293,31 @@ pub struct GenericGossipsub, Filter: TopicSubscriptionFilter> { subscription_filter: Filter, } -// For general use and convenience. -pub type Gossipsub = GenericGossipsub, AllowAllSubscriptionFilter>; - -impl GenericGossipsub +impl Gossipsub where T: Clone + Into> + From> + AsRef<[u8]>, F: TopicSubscriptionFilter + Default, { - /// Creates a `GenericGossipsub` struct given a set of parameters specified via a `GenericGossipsubConfig`. - pub fn new(privacy: MessageAuthenticity, config: Config) -> Result { + /// Creates a [`Gossipsub`] struct given a set of parameters specified via a + /// [`GossipsubConfig`]. + pub fn new( + privacy: MessageAuthenticity, + config: GossipsubConfig, + ) -> Result { Self::new_with_subscription_filter(privacy, config, F::default()) } } -impl GenericGossipsub +impl Gossipsub where T: Clone + Into> + From> + AsRef<[u8]>, F: TopicSubscriptionFilter, { - /// Creates a `GenericGossipsub` struct given a set of parameters specified via a `Config`. + /// Creates a [`Gossipsub`] struct given a set of parameters specified via a + /// [`GossipsubConfig`]. pub fn new_with_subscription_filter( privacy: MessageAuthenticity, - config: Config, + config: GossipsubConfig, subscription_filter: F, ) -> Result { // Set up the router given the configuration settings. @@ -324,7 +328,7 @@ where // Set up message publishing parameters. - Ok(GenericGossipsub { + Ok(Gossipsub { events: VecDeque::new(), control_pool: HashMap::new(), publish_config: privacy.into(), @@ -631,10 +635,10 @@ where Ok(msg_id) } - /// This function should be called when `config.validate_messages()` is `true` after the message - /// got validated by the caller. Messages are stored in the ['Memcache'] and validation is - /// expected to be fast enough that the messages should still exist in the cache. There are - /// three possible validation outcomes and the outcome is given in acceptance. + /// This function should be called when [`GossipsubConfig::validate_messages()`] is `true` after + /// the message got validated by the caller. Messages are stored in the ['Memcache'] and + /// validation is expected to be fast enough that the messages should still exist in the cache. + /// There are three possible validation outcomes and the outcome is given in acceptance. /// /// If acceptance = [`MessageAcceptance::Accept`] the message will get propagated to the /// network. The `propagation_source` parameter indicates who the message was received by and @@ -752,7 +756,7 @@ where /// Sets scoring parameters for a topic. /// - /// The `with_peer_score()` must first be called to initialise peer scoring. + /// The [`Self::with_peer_score()`] must first be called to initialise peer scoring. pub fn set_topic_params( &mut self, topic: Topic, @@ -951,7 +955,7 @@ where } } - /// Determines if a peer's score is below a given `PeerScoreThreshold` chosen via the + /// Determines if a peer's score is below a given [`PeerScoreThreshold`] chosen via the /// `threshold` parameter. fn score_below_threshold( &self, @@ -1472,7 +1476,7 @@ where return; } } - let msg = GenericGossipsubMessage::from(msg); + let msg = GossipsubMessage::from(msg); let msg_id = self.config.message_id(&msg); let mut msg = GossipsubMessageWithId::new(msg, msg_id); @@ -1515,12 +1519,13 @@ where // Dispatch the message to the user if we are subscribed to any of the topics if self.mesh.contains_key(&msg.topic) { debug!("Sending received message to user"); - self.events - .push_back(NetworkBehaviourAction::GenerateEvent(Event::Message { + self.events.push_back(NetworkBehaviourAction::GenerateEvent( + GossipsubEvent::Message { propagation_source: propagation_source.clone(), message_id: msg.message_id().clone(), message: msg.clone(), - })); + }, + )); } else { debug!( "Received message on a topic we are not subscribed to: {:?}", @@ -1649,7 +1654,7 @@ where } // generates a subscription event to be polled application_event.push(NetworkBehaviourAction::GenerateEvent( - Event::Subscribed { + GossipsubEvent::Subscribed { peer_id: propagation_source.clone(), topic: subscription.topic_hash.clone(), }, @@ -1669,7 +1674,7 @@ where .push((propagation_source.clone(), subscription.topic_hash.clone())); // generate an unsubscribe event to be polled application_event.push(NetworkBehaviourAction::GenerateEvent( - Event::Unsubscribed { + GossipsubEvent::Unsubscribed { peer_id: propagation_source.clone(), topic: subscription.topic_hash.clone(), }, @@ -2308,12 +2313,12 @@ where } } - /// Constructs a [`GenericGossipsubMessage`] performing message signing if required. + /// Constructs a [`GossipsubMessage`] performing message signing if required. pub(crate) fn build_message( &self, topic: TopicHash, data: T, - ) -> Result, SigningError> { + ) -> Result, SigningError> { match &self.publish_config { PublishConfig::Signing { ref keypair, @@ -2344,7 +2349,7 @@ where Some(keypair.sign(&signature_bytes)?) }; - Ok(GenericGossipsubMessage { + Ok(GossipsubMessage { source: Some(author.clone()), data, // To be interoperable with the go-implementation this is treated as a 64-bit @@ -2357,7 +2362,7 @@ where }) } PublishConfig::Author(peer_id) => { - Ok(GenericGossipsubMessage { + Ok(GossipsubMessage { source: Some(peer_id.clone()), data, // To be interoperable with the go-implementation this is treated as a 64-bit @@ -2370,7 +2375,7 @@ where }) } PublishConfig::RandomAuthor => { - Ok(GenericGossipsubMessage { + Ok(GossipsubMessage { source: Some(PeerId::random()), data, // To be interoperable with the go-implementation this is treated as a 64-bit @@ -2383,7 +2388,7 @@ where }) } PublishConfig::Anonymous => { - Ok(GenericGossipsubMessage { + Ok(GossipsubMessage { source: None, data, // To be interoperable with the go-implementation this is treated as a 64-bit @@ -2642,13 +2647,13 @@ fn get_ip_addr(addr: &Multiaddr) -> Option { }) } -impl NetworkBehaviour for GenericGossipsub +impl NetworkBehaviour for Gossipsub where T: Send + 'static + Clone + Into> + From> + AsRef<[u8]>, F: Send + 'static + TopicSubscriptionFilter, { type ProtocolsHandler = GossipsubHandler; - type OutEvent = Event; + type OutEvent = GossipsubEvent; fn new_handler(&mut self) -> Self::ProtocolsHandler { GossipsubHandler::new( @@ -2926,7 +2931,7 @@ where peer_score.reject_message(&propagation_source, &message, reason); gossip_promises.reject_message(msg_id, &reason); } else { - let message = GenericGossipsubMessage::from(message); + let message = GossipsubMessage::from(message); let id = self.config.message_id(&message); let message = GossipsubMessageWithId::new(message, id); peer_score.reject_message(&propagation_source, &message, reason); @@ -3072,7 +3077,7 @@ fn validate_config( Ok(()) } -impl, F: TopicSubscriptionFilter> fmt::Debug for GenericGossipsub { +impl, F: TopicSubscriptionFilter> fmt::Debug for Gossipsub { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Gossipsub") .field("config", &self.config) @@ -3168,7 +3173,7 @@ mod local_test { /// Tests RPC message fragmentation fn test_message_fragmentation_deterministic() { let max_transmit_size = 500; - let config = crate::ConfigBuilder::default() + let config = crate::GossipsubConfigBuilder::default() .max_transmit_size(max_transmit_size) .validation_mode(ValidationMode::Permissive) .build() @@ -3216,7 +3221,7 @@ mod local_test { fn test_message_fragmentation() { fn prop(rpc: GossipsubRpc) { let max_transmit_size = 500; - let config = crate::ConfigBuilder::default() + let config = crate::GossipsubConfigBuilder::default() .max_transmit_size(max_transmit_size) .validation_mode(ValidationMode::Permissive) .build() diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index ed367795a72..8cc94bfb037 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -29,7 +29,7 @@ mod tests { use rand::Rng; use crate::{ - ConfigBuilder, GossipsubConfig, GossipsubConfigBuilder, GossipsubMessage, + GossipsubConfig, GossipsubConfigBuilder, GossipsubConfigBuilder, GossipsubMessage, IdentTopic as Topic, TopicScoreParams, }; @@ -52,7 +52,7 @@ mod tests { peer_no: usize, topics: Vec, to_subscribe: bool, - gs_config: Config, + gs_config: GossipsubConfig, explicit: usize, outbound: usize, scoring: Option<(PeerScoreParams, PeerScoreThresholds)>, @@ -64,10 +64,10 @@ mod tests { T: Send + 'static + Default + Clone + Into> + From> + AsRef<[u8]>, F: TopicSubscriptionFilter + Clone + Default + Send + 'static, { - pub fn create_network(self) -> (GenericGossipsub, Vec, Vec) { + pub fn create_network(self) -> (Gossipsub, Vec, Vec) { let keypair = libp2p_core::identity::Keypair::generate_secp256k1(); // create a gossipsub struct - let mut gs: GenericGossipsub = GenericGossipsub::new_with_subscription_filter( + let mut gs: Gossipsub = Gossipsub::new_with_subscription_filter( MessageAuthenticity::Signed(keypair), self.gs_config, self.subscription_filter, @@ -114,7 +114,7 @@ mod tests { T: Send + 'static + Default + Clone + Into> + From> + AsRef<[u8]>, F: TopicSubscriptionFilter + Clone + Default + Send + 'static, { - pub fn create_network(&self) -> (GenericGossipsub, Vec, Vec) { + pub fn create_network(&self) -> (Gossipsub, Vec, Vec) { self.build().unwrap().create_network() } } @@ -141,7 +141,7 @@ mod tests { // helper functions for testing fn add_peer( - gs: &mut GenericGossipsub, + gs: &mut Gossipsub, topic_hashes: &Vec, outbound: bool, explicit: bool, @@ -154,7 +154,7 @@ mod tests { } fn add_peer_with_addr( - gs: &mut GenericGossipsub, + gs: &mut Gossipsub, topic_hashes: &Vec, outbound: bool, explicit: bool, @@ -175,7 +175,7 @@ mod tests { } fn add_peer_with_addr_and_kind( - gs: &mut GenericGossipsub, + gs: &mut Gossipsub, topic_hashes: &Vec, outbound: bool, explicit: bool, @@ -200,7 +200,7 @@ mod tests { } }, ); - as NetworkBehaviour>::inject_connected(gs, &peer); + as NetworkBehaviour>::inject_connected(gs, &peer); if let Some(kind) = kind { gs.inject_event( peer.clone(), @@ -4924,7 +4924,7 @@ mod tests { }}; } - let message_id_fn = |m: &GenericGossipsubMessage| -> MessageId { + let message_id_fn = |m: &GossipsubMessage| -> MessageId { let (mut id, mut counters_pointer): (MessageId, *mut Pointers) = get_counters_and_hash!(&m.data.0); unsafe { @@ -4940,7 +4940,7 @@ mod tests { } id }; - let config = ConfigBuilder::default() + let config = GossipsubConfigBuilder::default() .message_id_fn(message_id_fn) .fast_message_id_fn(fast_message_id_fn) .build() diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index 8ff0453e1d0..e416ee0006b 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -23,17 +23,18 @@ use std::time::Duration; use libp2p_core::PeerId; -use crate::types::{FastMessageId, GenericGossipsubMessage, MessageId}; +use crate::types::{FastMessageId, GossipsubMessage, MessageId}; use crate::RawGossipsubMessage; /// The types of message validation that can be employed by gossipsub. #[derive(Debug, Clone)] pub enum ValidationMode { - /// This is the default setting. This requires the message author to be a valid `PeerId` and to + /// This is the default setting. This requires the message author to be a valid [`PeerId`] and to /// be present as well as the sequence number. All messages must have valid signatures. /// - /// NOTE: This setting will reject messages from nodes using `PrivacyMode::Anonymous` and - /// all messages that do not have signatures. + /// NOTE: This setting will reject messages from nodes using + /// [`crate::behaviour::MessageAuthenticity::Anonymous`] and all messages that do not have + /// signatures. Strict, /// This setting permits messages that have no author, sequence number or signature. If any of /// these fields exist in the message these are validated. @@ -48,12 +49,9 @@ pub enum ValidationMode { None, } -// For general use cases. -pub type GossipsubConfig = Config>; - /// Configuration parameters that define the performance of the gossipsub network. #[derive(Clone)] -pub struct Config { +pub struct GossipsubConfig> { /// The protocol id prefix to negotiate this protocol. The protocol id is of the form /// `//`. As gossipsub supports version 1.0 and 1.1, there are two /// protocol id's supported. @@ -122,8 +120,8 @@ pub struct Config { /// When set to `true`, prevents automatic forwarding of all received messages. This setting /// allows a user to validate the messages before propagating them to their peers. If set to - /// true, the user must manually call [crate::GenericGossipsub::report_message_validation_result()] on the behaviour to forward message - /// once validated (default is `false`). + /// true, the user must manually call [crate::Gossipsub::report_message_validation_result()] + /// on the behaviour to forward message once validated (default is `false`). validate_messages: bool, /// Determines the level of validation used when receiving messages. See [`ValidationMode`] @@ -136,21 +134,21 @@ pub struct Config { /// addressing, where this function may be set to `hash(message)`. This would prevent messages /// of the same content from being duplicated. /// - /// The function takes a `GenericGossipsubMessage` as input and outputs a String to be + /// The function takes a [`GossipsubMessage`] as input and outputs a String to be /// interpreted as the message id. - message_id_fn: fn(&GenericGossipsubMessage) -> MessageId, + message_id_fn: fn(&GossipsubMessage) -> MessageId, /// A user-defined optional function that computes fast ids from raw messages. This can be used - /// to avoid possibly expensive transformations from `RawGossipsubMessage` to - /// `GenericGossipsubMessage` for duplicates. Two semantically different messages must always + /// to avoid possibly expensive transformations from [`RawGossipsubMessage`] to + /// [`GossipsubMessage`] for duplicates. Two semantically different messages must always /// have different fast message ids, but it is allowed that two semantically identical messages /// have different fast message ids as long as the message_id_fn produces the same id for them. /// - /// On high intensive networks with lots of messages, where the message_id is based on the result of - /// decompressed traffic, it is beneficial to specify a `fast-message-id` that can identify and - /// filter duplicates quickly without performing the overhead of decompression. + /// On high intensive networks with lots of messages, where the message_id is based on the + /// result of decompressed traffic, it is beneficial to specify a `fast-message-id` that can + /// identify and filter duplicates quickly without performing the overhead of decompression. /// - /// The function takes a `RawGossipsubMessage` as input and outputs a String to be + /// The function takes a [`RawGossipsubMessage`] as input and outputs a String to be /// interpreted as the fast message id. Default is None. fast_message_id_fn: Option FastMessageId>, @@ -239,7 +237,7 @@ pub struct Config { published_message_ids_cache_time: Duration, } -impl Config { +impl GossipsubConfig { // All the getters /// The protocol id prefix to negotiate this protocol. The protocol id is of the form @@ -279,9 +277,9 @@ impl Config { } /// Affects how peers are selected when pruning a mesh due to over subscription. - // - // At least `retain_scores` of the retained peers will be high-scoring, while the remainder are - // chosen randomly (D_score in the spec, default is 4). + /// + /// At least `retain_scores` of the retained peers will be high-scoring, while the remainder are + /// chosen randomly (D_score in the spec, default is 4). pub fn retain_scores(&self) -> usize { self.retain_scores } @@ -341,10 +339,9 @@ impl Config { /// When set to `true`, prevents automatic forwarding of all received messages. This setting /// allows a user to validate the messages before propagating them to their peers. If set to - /// true, the user must manually call `validate_message()` on the behaviour to forward message - /// once validated (default is `false`). Furthermore, the application may optionally call - /// `invalidate_message()` on the behaviour to remove the message from the memcache. The - /// default is false. + /// true, the user must manually call [`crate::Gossipsub::report_message_validation_result()`] + /// on the behaviour to forward message once validated (default is `false`). + /// The default is `false`. pub fn validate_messages(&self) -> bool { self.validate_messages } @@ -361,19 +358,19 @@ impl Config { /// addressing, where this function may be set to `hash(message)`. This would prevent messages /// of the same content from being duplicated. /// - /// The function takes a `GenericGossipsubMessage` as input and outputs a String to be interpreted as + /// The function takes a [`GossipsubMessage`] as input and outputs a String to be interpreted as /// the message id. - pub fn message_id(&self, message: &GenericGossipsubMessage) -> MessageId { + pub fn message_id(&self, message: &GossipsubMessage) -> MessageId { (self.message_id_fn)(message) } /// A user-defined optional function that computes fast ids from raw messages. This can be used - /// to avoid possibly expensive transformations from `RawGossipsubMessage` to - /// `GenericGossipsubMessage` for duplicates. Two semantically different messages must always + /// to avoid possibly expensive transformations from [`RawGossipsubMessage`] to + /// [`GossipsubMessage`] for duplicates. Two semantically different messages must always /// have different fast message ids, but it is allowed that two semantically identical messages /// have different fast message ids as long as the message_id_fn produces the same id for them. /// - /// The function takes a `RawGossipsubMessage` as input and outputs a String to be + /// The function takes a [`RawGossipsubMessage`] as input and outputs a String to be /// interpreted as the fast message id. Default is None. pub fn fast_message_id(&self, message: &RawGossipsubMessage) -> Option { self.fast_message_id_fn @@ -497,27 +494,24 @@ impl Config { } } -impl Default for Config { +impl Default for GossipsubConfig { fn default() -> Self { // use ConfigBuilder to also validate defaults - ConfigBuilder::default() + GossipsubConfigBuilder::default() .build() .expect("Default config parameters should be valid parameters") } } /// The builder struct for constructing a gossipsub configuration. -pub struct ConfigBuilder { - config: Config, +pub struct GossipsubConfigBuilder> { + config: GossipsubConfig, } -// For general use cases. -pub type GossipsubConfigBuilder = ConfigBuilder>; - -impl Default for ConfigBuilder { +impl Default for GossipsubConfigBuilder { fn default() -> Self { - ConfigBuilder { - config: Config { + GossipsubConfigBuilder { + config: GossipsubConfig { protocol_id_prefix: Cow::Borrowed("meshsub"), history_length: 5, history_gossip: 3, @@ -571,13 +565,13 @@ impl Default for ConfigBuilder { } } -impl From> for ConfigBuilder { - fn from(config: Config) -> Self { - ConfigBuilder { config } +impl From> for GossipsubConfigBuilder { + fn from(config: GossipsubConfig) -> Self { + GossipsubConfigBuilder { config } } } -impl ConfigBuilder { +impl GossipsubConfigBuilder { /// The protocol id to negotiate this protocol (default is `/meshsub/1.0.0`). pub fn protocol_id_prefix(&mut self, protocol_id: impl Into>) -> &mut Self { self.config.protocol_id_prefix = protocol_id.into(); @@ -617,7 +611,7 @@ impl ConfigBuilder { /// Affects how peers are selected when pruning a mesh due to over subscription. /// - /// At least `retain_scores` of the retained peers will be high-scoring, while the remainder are + /// At least [`Self::retain_scores`] of the retained peers will be high-scoring, while the remainder are /// chosen randomly (D_score in the spec, default is 4). pub fn retain_scores(&mut self, retain_scores: usize) -> &mut Self { self.config.retain_scores = retain_scores; @@ -682,8 +676,8 @@ impl ConfigBuilder { /// When set, prevents automatic forwarding of all received messages. This setting /// allows a user to validate the messages before propagating them to their peers. If set, - /// the user must manually call `validate_message()` on the behaviour to forward a message - /// once validated. + /// the user must manually call [`crate::Gossipsub::report_message_validation_result()`] on the + /// behaviour to forward a message once validated. pub fn validate_messages(&mut self) -> &mut Self { self.config.validate_messages = true; self @@ -702,19 +696,16 @@ impl ConfigBuilder { /// addressing, where this function may be set to `hash(message)`. This would prevent messages /// of the same content from being duplicated. /// - /// The function takes a [`GenericGossipsubMessage`] as input and outputs a String to be + /// The function takes a [`GossipsubMessage`] as input and outputs a String to be /// interpreted as the message id. - pub fn message_id_fn( - &mut self, - id_fn: fn(&GenericGossipsubMessage) -> MessageId, - ) -> &mut Self { + pub fn message_id_fn(&mut self, id_fn: fn(&GossipsubMessage) -> MessageId) -> &mut Self { self.config.message_id_fn = id_fn; self } /// A user-defined optional function that computes fast ids from raw messages. This can be used - /// to avoid possibly expensive transformations from `RawGossipsubMessage` to - /// [`GenericGossipsubMessage`] for duplicates. Two semantically different messages must always + /// to avoid possibly expensive transformations from [`RawGossipsubMessage`] to + /// [`GossipsubMessage`] for duplicates. Two semantically different messages must always /// have different fast message ids, but it is allowed that two semantically identical messages /// have different fast message ids as long as the message_id_fn produces the same id for them. /// @@ -738,9 +729,9 @@ impl ConfigBuilder { /// Controls the number of peers to include in prune Peer eXchange. /// /// When we prune a peer that's eligible for PX (has a good score, etc), we will try to - /// send them signed peer records for up to `prune_peers` other peers that we - /// know of. It is recommended that this value is larger than `mesh_n_high` so that the pruned - /// peer can reliably form a full mesh. The default is 16. + /// send them signed peer records for up to [`Self::prune_peers] other peers that we + /// know of. It is recommended that this value is larger than [`Self::mesh_n_high`] so that the + /// pruned peer can reliably form a full mesh. The default is 16. pub fn prune_peers(&mut self, prune_peers: usize) -> &mut Self { self.config.prune_peers = prune_peers; self @@ -748,9 +739,9 @@ impl ConfigBuilder { /// Controls the backoff time for pruned peers. This is how long /// a peer must wait before attempting to graft into our mesh again after being pruned. - /// When pruning a peer, we send them our value of `prune_backoff` so they know + /// When pruning a peer, we send them our value of [`Self::prune_backoff`] so they know /// the minimum time to wait. Peers running older versions may not send a backoff time, - /// so if we receive a prune message without one, we will wait at least `prune_backoff` + /// so if we receive a prune message without one, we will wait at least [`Self::prune_backoff`] /// before attempting to re-graft. The default is one minute. pub fn prune_backoff(&mut self, prune_backoff: Duration) -> &mut Self { self.config.prune_backoff = prune_backoff; @@ -863,8 +854,8 @@ impl ConfigBuilder { self } - /// Constructs a `GenericGossipsubConfig` from the given configuration and validates the settings. - pub fn build(&self) -> Result, &str> { + /// Constructs a [`GossipsubConfig`] from the given configuration and validates the settings. + pub fn build(&self) -> Result, &str> { // check all constraints on config if self.config.max_transmit_size < 100 { @@ -895,7 +886,7 @@ impl ConfigBuilder { } } -impl std::fmt::Debug for Config { +impl std::fmt::Debug for GossipsubConfig { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut builder = f.debug_struct("GossipsubConfig"); let _ = builder.field("protocol_id_prefix", &self.protocol_id_prefix); diff --git a/protocols/gossipsub/src/error.rs b/protocols/gossipsub/src/error.rs index 5827c5c5c5b..269efc286d4 100644 --- a/protocols/gossipsub/src/error.rs +++ b/protocols/gossipsub/src/error.rs @@ -80,11 +80,14 @@ pub enum ValidationError { InvalidSequenceNumber, /// The PeerId was invalid InvalidPeerId, - /// Signature existed when validation has been sent to `Anonymous`. + /// Signature existed when validation has been sent to + /// [`crate::behaviour::MessageAuthenticity::Anonymous`]. SignaturePresent, - /// Sequence number existed when validation has been sent to `Anonymous`. + /// Sequence number existed when validation has been sent to + /// [`crate::behaviour::MessageAuthenticity::Anonymous`]. SequenceNumberPresent, - /// Message source existed when validation has been sent to `Anonymous`. + /// Message source existed when validation has been sent to + /// [`crate::behaviour::MessageAuthenticity::Anonymous`]. MessageSourcePresent, } diff --git a/protocols/gossipsub/src/lib.rs b/protocols/gossipsub/src/lib.rs index 8c885547d34..206171f4690 100644 --- a/protocols/gossipsub/src/lib.rs +++ b/protocols/gossipsub/src/lib.rs @@ -46,8 +46,8 @@ //! encoded) by setting the `hash_topics` configuration parameter to true. //! //! - **Sequence Numbers** - A message on the gossipsub network is identified by the source -//! `PeerId` and a nonce (sequence number) of the message. The sequence numbers in this -//! implementation are sent as raw bytes across the wire. They are 64-bit big-endian unsigned +//! [`libp2p_core::PeerId`] and a nonce (sequence number) of the message. The sequence numbers in +//! this implementation are sent as raw bytes across the wire. They are 64-bit big-endian unsigned //! integers. They are chosen at random in this implementation of gossipsub, but are sequential in //! the current go implementation. //! @@ -55,22 +55,22 @@ //! //! ## GossipsubConfig //! -//! The [`Config`] struct specifies various network performance/tuning configuration +//! The [`GossipsubConfig`] struct specifies various network performance/tuning configuration //! parameters. Specifically it specifies: //! -//! [`Config`]: struct.Config.html +//! [`GossipsubConfig`]: struct.Config.html //! -//! This struct implements the `Default` trait and can be initialised via -//! `Config::default()`. +//! This struct implements the [`Default`] trait and can be initialised via +//! [`GossipsubConfig::default()`]. //! //! //! ## Gossipsub //! -//! The [`GenericGossipsub`] struct implements the `NetworkBehaviour` trait allowing it to act as the -//! routing behaviour in a `Swarm`. This struct requires an instance of `PeerId` and -//! [`Config`]. +//! The [`Gossipsub`] struct implements the [`libp2p_swarm::NetworkBehaviour`] trait allowing it to +//! act as the routing behaviour in a [`libp2p_swarm::Swarm`]. This struct requires an instance of +//! [`libp2p_core::PeerId`] and [`GossipsubConfig`]. //! -//! [`GenericGossipsub`]: struct.GenericGossipsub.html +//! [`Gossipsub`]: struct.Gossipsub.html //! ## Example //! @@ -143,20 +143,16 @@ extern crate derive_builder; mod rpc_proto; -pub use self::behaviour::{ - Event, GenericGossipsub, Gossipsub, GossipsubEvent, MessageAuthenticity, -}; -pub use self::config::{ - Config, ConfigBuilder, GossipsubConfig, GossipsubConfigBuilder, ValidationMode, -}; +pub use self::behaviour::{Gossipsub, GossipsubEvent, MessageAuthenticity}; +pub use self::config::{GossipsubConfig, GossipsubConfigBuilder, ValidationMode}; pub use self::peer_score::{ score_parameter_decay, score_parameter_decay_with_base, PeerScoreParams, PeerScoreThresholds, TopicScoreParams, }; pub use self::topic::{Hasher, Topic, TopicHash}; pub use self::types::{ - FastMessageId, GenericGossipsubMessage, GossipsubMessage, GossipsubRpc, MessageAcceptance, - MessageId, RawGossipsubMessage, + FastMessageId, GossipsubMessage, GossipsubRpc, MessageAcceptance, MessageId, + RawGossipsubMessage, }; pub type IdentTopic = Topic; pub type Sha256Topic = Topic; diff --git a/protocols/gossipsub/src/mcache.rs b/protocols/gossipsub/src/mcache.rs index 79165e4d4fa..1f08c86892e 100644 --- a/protocols/gossipsub/src/mcache.rs +++ b/protocols/gossipsub/src/mcache.rs @@ -124,7 +124,7 @@ impl MessageCache { }) } - /// Get a list of `MessageIds` for a given topic. + /// Get a list of [`MessageId`]s for a given topic. pub fn get_gossip_message_ids(&self, topic: &TopicHash) -> Vec { self.history[..self.gossip] .iter() diff --git a/protocols/gossipsub/src/peer_score.rs b/protocols/gossipsub/src/peer_score.rs index 8f1da06a9b3..f1ada2a0517 100644 --- a/protocols/gossipsub/src/peer_score.rs +++ b/protocols/gossipsub/src/peer_score.rs @@ -49,7 +49,7 @@ pub(crate) struct PeerScore { peer_stats: HashMap, /// Tracking peers per IP. peer_ips: HashMap>, - /// Message delivery tracking. This is a time-cache of `DeliveryRecord`s. + /// Message delivery tracking. This is a time-cache of [`DeliveryRecord`]s. deliveries: TimeCache, /// callback for monitoring message delivery times message_delivery_time_callback: Option, @@ -141,7 +141,7 @@ enum MeshStatus { } impl MeshStatus { - /// Initialises a new `Active` mesh status. + /// Initialises a new [`Active`] mesh status. pub fn new_active() -> Self { MeshStatus::Active { graft_time: Instant::now(), @@ -193,7 +193,7 @@ impl Default for DeliveryRecord { } impl PeerScore { - /// Creates a new `PeerScore` using a given set of peer scoring parameters. + /// Creates a new [`PeerScore`] using a given set of peer scoring parameters. #[allow(dead_code)] pub fn new(params: PeerScoreParams) -> Self { Self::new_with_message_delivery_time_callback(params, None) @@ -421,7 +421,7 @@ impl PeerScore { }); } - /// Adds a connected peer to `PeerScore`, initialising with empty ips (ips get added later + /// Adds a connected peer to [`PeerScore`], initialising with empty ips (ips get added later /// through add_ip. pub fn add_peer(&mut self, peer_id: PeerId) { let peer_stats = self.peer_stats.entry(peer_id).or_default(); diff --git a/protocols/gossipsub/src/peer_score/params.rs b/protocols/gossipsub/src/peer_score/params.rs index 17ad3114823..c4159bb6ec1 100644 --- a/protocols/gossipsub/src/peer_score/params.rs +++ b/protocols/gossipsub/src/peer_score/params.rs @@ -57,7 +57,8 @@ pub struct PeerScoreThresholds { pub publish_threshold: f64, /// The score threshold below which message processing is suppressed altogether, - /// implementing an effective graylist according to peer score; should be negative and <= `publish_threshold`. + /// implementing an effective graylist according to peer score; should be negative and + /// <= `publish_threshold`. pub graylist_threshold: f64, /// The score threshold below which px will be ignored; this should be positive @@ -247,11 +248,11 @@ pub struct TopicScoreParams { pub first_message_deliveries_cap: f64, /// P3: mesh message deliveries - /// This is the number of message deliveries in the mesh, within the `mesh_message_deliveries_window` of - /// message validation; deliveries during validation also count and are retroactively applied - /// when validation succeeds. - /// This window accounts for the minimum time before a hostile mesh peer trying to game the score - /// could replay back a valid message we just sent them. + /// This is the number of message deliveries in the mesh, within the + /// `mesh_message_deliveries_window` of message validation; deliveries during validation also + /// count and are retroactively applied when validation succeeds. + /// This window accounts for the minimum time before a hostile mesh peer trying to game the + /// score could replay back a valid message we just sent them. /// It effectively tracks first and near-first deliveries, ie a message seen from a mesh peer /// before we have forwarded it to them. /// The parameter has an associated counter, decaying with `mesh_message_deliveries_decay`. diff --git a/protocols/gossipsub/src/subscription_filter.rs b/protocols/gossipsub/src/subscription_filter.rs index 0f38157623a..7aa94416183 100644 --- a/protocols/gossipsub/src/subscription_filter.rs +++ b/protocols/gossipsub/src/subscription_filter.rs @@ -29,7 +29,7 @@ pub trait TopicSubscriptionFilter { /// Filters a list of incoming subscriptions and returns a filtered set /// By default this deduplicates the subscriptions and calls - /// `Self::filter_incoming_subscription_set` on the filtered set. + /// [`Self::filter_incoming_subscription_set`] on the filtered set. fn filter_incoming_subscriptions<'a>( &mut self, subscriptions: &'a [GossipsubSubscription], @@ -56,7 +56,7 @@ pub trait TopicSubscriptionFilter { } /// Filters a set of deduplicated subscriptions - /// By default this filters the elements based on `Self::allow_incoming_subscription`. + /// By default this filters the elements based on [`Self::allow_incoming_subscription`]. fn filter_incoming_subscription_set<'a>( &mut self, mut subscriptions: HashSet<&'a GossipsubSubscription>, diff --git a/protocols/gossipsub/src/topic.rs b/protocols/gossipsub/src/topic.rs index 2139243158e..7e8afca2d9e 100644 --- a/protocols/gossipsub/src/topic.rs +++ b/protocols/gossipsub/src/topic.rs @@ -34,7 +34,7 @@ pub trait Hasher { #[derive(Debug, Clone)] pub struct IdentityHash {} impl Hasher for IdentityHash { - /// Creates a `TopicHash` as a raw string. + /// Creates a [`TopicHash`] as a raw string. fn hash(topic_string: String) -> TopicHash { TopicHash { hash: topic_string } } @@ -43,7 +43,7 @@ impl Hasher for IdentityHash { #[derive(Debug, Clone)] pub struct Sha256Hash {} impl Hasher for Sha256Hash { - /// Creates a `TopicHash` by SHA256 hashing the topic then base64 encoding the + /// Creates a [`TopicHash`] by SHA256 hashing the topic then base64 encoding the /// hash. fn hash(topic_string: String) -> TopicHash { let topic_descripter = rpc_proto::TopicDescriptor { diff --git a/protocols/gossipsub/src/types.rs b/protocols/gossipsub/src/types.rs index e53b9885cf6..bfe10c2c150 100644 --- a/protocols/gossipsub/src/types.rs +++ b/protocols/gossipsub/src/types.rs @@ -95,7 +95,7 @@ pub enum PeerKind { /// A message received by the gossipsub system. #[derive(Clone, PartialEq, Eq, Hash)] -pub struct GenericGossipsubMessage { +pub struct GossipsubMessage>> { /// Id of the peer that published this message. pub source: Option, @@ -111,15 +111,15 @@ pub struct GenericGossipsubMessage { /// The signature of the message if it's signed. pub signature: Option>, - /// The public key of the message if it is signed and the source `PeerId` cannot be inlined. + /// The public key of the message if it is signed and the source [`PeerId`] cannot be inlined. pub key: Option>, /// Flag indicating if this message has been validated by the application or not. pub validated: bool, } -impl GenericGossipsubMessage { - pub fn from>(m: GenericGossipsubMessage) -> Self { +impl GossipsubMessage { + pub fn from>(m: GossipsubMessage) -> Self { Self { source: m.source, data: m.data.into(), @@ -132,7 +132,7 @@ impl GenericGossipsubMessage { } } -pub type RawGossipsubMessage = GenericGossipsubMessage>; +pub type RawGossipsubMessage = GossipsubMessage>; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct DataWithId { @@ -152,10 +152,10 @@ impl> AsRef<[u8]> for DataWithId { } } -pub type GossipsubMessageWithId = GenericGossipsubMessage>; +pub type GossipsubMessageWithId = GossipsubMessage>; impl GossipsubMessageWithId { - pub fn new(m: GenericGossipsubMessage, id: MessageId) -> Self { + pub fn new(m: GossipsubMessage, id: MessageId) -> Self { Self { source: m.source, data: DataWithId { id, data: m.data }, @@ -176,10 +176,7 @@ impl GossipsubMessageWithId { } } -// for backwards compatibility -pub type GossipsubMessage = GossipsubMessageWithId>; - -impl> fmt::Debug for GenericGossipsubMessage { +impl> fmt::Debug for GossipsubMessage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GossipsubMessage") .field( From 8d7f318cc9f7a18480b4b25c9ee186b3a00a8a94 Mon Sep 17 00:00:00 2001 From: blacktemplar Date: Fri, 11 Dec 2020 16:56:31 +0100 Subject: [PATCH 2/5] fix broken intra links --- protocols/gossipsub/src/behaviour.rs | 2 +- protocols/gossipsub/src/peer_score.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 413813af817..e0617ce0994 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -955,7 +955,7 @@ where } } - /// Determines if a peer's score is below a given [`PeerScoreThreshold`] chosen via the + /// Determines if a peer's score is below a given `PeerScoreThreshold` chosen via the /// `threshold` parameter. fn score_below_threshold( &self, diff --git a/protocols/gossipsub/src/peer_score.rs b/protocols/gossipsub/src/peer_score.rs index f1ada2a0517..96ccc2e26b1 100644 --- a/protocols/gossipsub/src/peer_score.rs +++ b/protocols/gossipsub/src/peer_score.rs @@ -141,7 +141,7 @@ enum MeshStatus { } impl MeshStatus { - /// Initialises a new [`Active`] mesh status. + /// Initialises a new [`MeshStatus::Active`] mesh status. pub fn new_active() -> Self { MeshStatus::Active { graft_time: Instant::now(), From 30a6cd339563ff2bdef3d3971f3c0435f2e6be41 Mon Sep 17 00:00:00 2001 From: blacktemplar Date: Fri, 11 Dec 2020 17:37:52 +0100 Subject: [PATCH 3/5] fix tests --- protocols/gossipsub/src/behaviour.rs | 130 +++++++-------- protocols/gossipsub/src/behaviour/tests.rs | 181 ++++++++++----------- protocols/gossipsub/src/config.rs | 2 +- protocols/gossipsub/src/protocol.rs | 2 +- 4 files changed, 150 insertions(+), 165 deletions(-) diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index e0617ce0994..48900cf5049 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -308,6 +308,61 @@ where } } +/// Helper function to get a subset of random gossipsub peers for a `topic_hash` +/// filtered by the function `f`. The number of peers to get equals the output of `n_map` +/// that gets as input the number of filtered peers. +fn get_random_peers_dynamic( + topic_peers: &HashMap>, + peer_protocols: &HashMap, + topic_hash: &TopicHash, + // maps the number of total peers to the number of selected peers + n_map: impl Fn(usize) -> usize, + mut f: impl FnMut(&PeerId) -> bool, +) -> BTreeSet { + let mut gossip_peers = match topic_peers.get(topic_hash) { + // if they exist, filter the peers by `f` + Some(peer_list) => peer_list + .iter() + .cloned() + .filter(|p| { + f(p) && match peer_protocols.get(p) { + Some(PeerKind::Gossipsub) => true, + Some(PeerKind::Gossipsubv1_1) => true, + _ => false, + } + }) + .collect(), + None => Vec::new(), + }; + + // if we have less than needed, return them + let n = n_map(gossip_peers.len()); + if gossip_peers.len() <= n { + debug!("RANDOM PEERS: Got {:?} peers", gossip_peers.len()); + return gossip_peers.into_iter().collect(); + } + + // we have more peers than needed, shuffle them and return n of them + let mut rng = thread_rng(); + gossip_peers.partial_shuffle(&mut rng, n); + + debug!("RANDOM PEERS: Got {:?} peers", n); + + gossip_peers.into_iter().take(n).collect() +} + +/// Helper function to get a set of `n` random gossipsub peers for a `topic_hash` +/// filtered by the function `f`. +fn get_random_peers( + topic_peers: &HashMap>, + peer_protocols: &HashMap, + topic_hash: &TopicHash, + n: usize, + f: impl FnMut(&PeerId) -> bool, +) -> BTreeSet { + get_random_peers_dynamic(topic_peers, peer_protocols, topic_hash, |_| n, f) +} + impl Gossipsub where T: Clone + Into> + From> + AsRef<[u8]>, @@ -593,7 +648,7 @@ where } else { // We have no fanout peers, select mesh_n of them and add them to the fanout let mesh_n = self.config.mesh_n(); - let new_peers = Self::get_random_peers( + let new_peers = get_random_peers( &self.topic_peers, &self.peer_protocols, &topic_hash, @@ -829,7 +884,7 @@ where // check if we need to get more peers, which we randomly select if added_peers.len() < self.config.mesh_n() { // get the peers - let new_peers = Self::get_random_peers( + let new_peers = get_random_peers( &self.topic_peers, &self.peer_protocols, topic_hash, @@ -902,7 +957,7 @@ where // Select peers for peer exchange let peers = if do_px { - Self::get_random_peers( + get_random_peers( &self.topic_peers, &self.peer_protocols, &topic_hash, @@ -1809,7 +1864,7 @@ where ); // not enough peers - get mesh_n - current_length more let desired_peers = self.config.mesh_n() - peers.len(); - let peer_list = Self::get_random_peers( + let peer_list = get_random_peers( topic_peers, &self.peer_protocols, topic_hash, @@ -1891,7 +1946,7 @@ where // if we have not enough outbound peers, graft to some new outbound peers if outbound < self.config.mesh_outbound_min() { let needed = self.config.mesh_outbound_min() - outbound; - let peer_list = Self::get_random_peers( + let peer_list = get_random_peers( topic_peers, &self.peer_protocols, topic_hash, @@ -1948,7 +2003,7 @@ where // if the median score is below the threshold, select a better peer (if any) and // GRAFT if median < thresholds.opportunistic_graft_threshold { - let peer_list = Self::get_random_peers( + let peer_list = get_random_peers( topic_peers, &self.peer_protocols, topic_hash, @@ -2032,7 +2087,7 @@ where ); let needed_peers = self.config.mesh_n() - peers.len(); let explicit_peers = &self.explicit_peers; - let new_peers = Self::get_random_peers( + let new_peers = get_random_peers( &self.topic_peers, &self.peer_protocols, topic_hash, @@ -2126,7 +2181,7 @@ where ) }; // get gossip_lazy random peers - let to_msg_peers = Self::get_random_peers_dynamic( + let to_msg_peers = get_random_peers_dynamic( &self.topic_peers, &self.peer_protocols, &topic_hash, @@ -2403,61 +2458,6 @@ where } } - /// Helper function to get a subset of random gossipsub peers for a `topic_hash` - /// filtered by the function `f`. The number of peers to get equals the output of `n_map` - /// that gets as input the number of filtered peers. - fn get_random_peers_dynamic( - topic_peers: &HashMap>, - peer_protocols: &HashMap, - topic_hash: &TopicHash, - // maps the number of total peers to the number of selected peers - n_map: impl Fn(usize) -> usize, - mut f: impl FnMut(&PeerId) -> bool, - ) -> BTreeSet { - let mut gossip_peers = match topic_peers.get(topic_hash) { - // if they exist, filter the peers by `f` - Some(peer_list) => peer_list - .iter() - .cloned() - .filter(|p| { - f(p) && match peer_protocols.get(p) { - Some(PeerKind::Gossipsub) => true, - Some(PeerKind::Gossipsubv1_1) => true, - _ => false, - } - }) - .collect(), - None => Vec::new(), - }; - - // if we have less than needed, return them - let n = n_map(gossip_peers.len()); - if gossip_peers.len() <= n { - debug!("RANDOM PEERS: Got {:?} peers", gossip_peers.len()); - return gossip_peers.into_iter().collect(); - } - - // we have more peers than needed, shuffle them and return n of them - let mut rng = thread_rng(); - gossip_peers.partial_shuffle(&mut rng, n); - - debug!("RANDOM PEERS: Got {:?} peers", n); - - gossip_peers.into_iter().take(n).collect() - } - - /// Helper function to get a set of `n` random gossipsub peers for a `topic_hash` - /// filtered by the function `f`. - fn get_random_peers( - topic_peers: &HashMap>, - peer_protocols: &HashMap, - topic_hash: &TopicHash, - n: usize, - f: impl FnMut(&PeerId) -> bool, - ) -> BTreeSet { - Self::get_random_peers_dynamic(topic_peers, peer_protocols, topic_hash, |_| n, f) - } - // adds a control action to control_pool fn control_pool_add( control_pool: &mut HashMap>, @@ -3178,7 +3178,7 @@ mod local_test { .validation_mode(ValidationMode::Permissive) .build() .unwrap(); - let gs = Gossipsub::new(MessageAuthenticity::RandomAuthor, config).unwrap(); + let gs: Gossipsub = Gossipsub::new(MessageAuthenticity::RandomAuthor, config).unwrap(); // Message under the limit should be fine. let mut rpc = empty_rpc(); @@ -3226,7 +3226,7 @@ mod local_test { .validation_mode(ValidationMode::Permissive) .build() .unwrap(); - let gs = Gossipsub::new(MessageAuthenticity::RandomAuthor, config).unwrap(); + let gs: Gossipsub = Gossipsub::new(MessageAuthenticity::RandomAuthor, config).unwrap(); let mut length_codec = unsigned_varint::codec::UviBytes::default(); length_codec.set_max_len(max_transmit_size); diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index 8cc94bfb037..54b4e5bd2b8 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -29,8 +29,8 @@ mod tests { use rand::Rng; use crate::{ - GossipsubConfig, GossipsubConfigBuilder, GossipsubConfigBuilder, GossipsubMessage, - IdentTopic as Topic, TopicScoreParams, + GossipsubConfig, GossipsubConfigBuilder, GossipsubMessage, IdentTopic as Topic, + TopicScoreParams, }; use super::super::*; @@ -565,7 +565,7 @@ mod tests { .unwrap(); let publish_topic = String::from("test_publish"); - let (mut gs, _, topic_hashes) = inject_nodes1() + let (mut gs, _, topic_hashes) = inject_nodes2() .peer_no(20) .topics(vec![publish_topic.clone()]) .to_subscribe(true) @@ -607,7 +607,7 @@ mod tests { .config .message_id(&publishes.first().expect("Should contain > 0 entries")); - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); assert_eq!( publishes.len(), config.mesh_n_low(), @@ -635,7 +635,7 @@ mod tests { .unwrap(); let fanout_topic = String::from("test_fanout"); - let (mut gs, _, topic_hashes) = inject_nodes1() + let (mut gs, _, topic_hashes) = inject_nodes2() .peer_no(20) .topics(vec![fanout_topic.clone()]) .to_subscribe(true) @@ -864,57 +864,42 @@ mod tests { .map(|p| (p.clone(), PeerKind::Gossipsubv1_1)) .collect(); - let random_peers = Gossipsub::get_random_peers( - &gs.topic_peers, - &gs.peer_protocols, - &topic_hash, - 5, - |_| true, - ); + let random_peers = + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 5, |_| { + true + }); assert_eq!(random_peers.len(), 5, "Expected 5 peers to be returned"); - let random_peers = Gossipsub::get_random_peers( - &gs.topic_peers, - &gs.peer_protocols, - &topic_hash, - 30, - |_| true, - ); + let random_peers = + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 30, |_| { + true + }); assert!(random_peers.len() == 20, "Expected 20 peers to be returned"); assert!( random_peers == peers.iter().cloned().collect(), "Expected no shuffling" ); - let random_peers = Gossipsub::get_random_peers( - &gs.topic_peers, - &gs.peer_protocols, - &topic_hash, - 20, - |_| true, - ); + let random_peers = + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 20, |_| { + true + }); assert!(random_peers.len() == 20, "Expected 20 peers to be returned"); assert!( random_peers == peers.iter().cloned().collect(), "Expected no shuffling" ); - let random_peers = Gossipsub::get_random_peers( - &gs.topic_peers, - &gs.peer_protocols, - &topic_hash, - 0, - |_| true, - ); + let random_peers = + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 0, |_| { + true + }); assert!(random_peers.len() == 0, "Expected 0 peers to be returned"); // test the filter - let random_peers = Gossipsub::get_random_peers( - &gs.topic_peers, - &gs.peer_protocols, - &topic_hash, - 5, - |_| false, - ); + let random_peers = + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 5, |_| { + false + }); assert!(random_peers.len() == 0, "Expected 0 peers to be returned"); let random_peers = - Gossipsub::get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 10, { + get_random_peers(&gs.topic_peers, &gs.peer_protocols, &topic_hash, 10, { |peer| peers.contains(peer) }); assert!(random_peers.len() == 10, "Expected 10 peers to be returned"); @@ -1293,7 +1278,7 @@ mod tests { .check_explicit_peers_ticks(2) .build() .unwrap(); - let (mut gs, others, _) = inject_nodes1() + let (mut gs, others, _) = inject_nodes2() .peer_no(1) .topics(Vec::new()) .to_subscribe(true) @@ -1349,7 +1334,7 @@ mod tests { #[test] fn test_handle_graft_explicit_peer() { - let (mut gs, peers, topic_hashes) = inject_nodes1() + let (mut gs, peers, topic_hashes) = inject_nodes2() .peer_no(1) .topics(vec![String::from("topic1"), String::from("topic2")]) .to_subscribe(true) @@ -1380,7 +1365,7 @@ mod tests { #[test] fn explicit_peers_not_added_to_mesh_on_receiving_subscription() { - let (gs, peers, topic_hashes) = inject_nodes1() + let (gs, peers, topic_hashes) = inject_nodes2() .peer_no(2) .topics(vec![String::from("topic1")]) .to_subscribe(true) @@ -1419,7 +1404,7 @@ mod tests { #[test] fn do_not_graft_explicit_peer() { - let (mut gs, others, topic_hashes) = inject_nodes1() + let (mut gs, others, topic_hashes) = inject_nodes2() .peer_no(1) .topics(vec![String::from("topic")]) .to_subscribe(true) @@ -1446,7 +1431,7 @@ mod tests { #[test] fn do_forward_messages_to_explicit_peers() { - let (mut gs, peers, topic_hashes) = inject_nodes1() + let (mut gs, peers, topic_hashes) = inject_nodes2() .peer_no(2) .topics(vec![String::from("topic1"), String::from("topic2")]) .to_subscribe(true) @@ -1491,7 +1476,7 @@ mod tests { #[test] fn explicit_peers_not_added_to_mesh_on_subscribe() { - let (mut gs, peers, _) = inject_nodes1() + let (mut gs, peers, _) = inject_nodes2() .peer_no(2) .topics(Vec::new()) .to_subscribe(true) @@ -1546,7 +1531,7 @@ mod tests { #[test] fn explicit_peers_not_added_to_mesh_from_fanout_on_subscribe() { - let (mut gs, peers, _) = inject_nodes1() + let (mut gs, peers, _) = inject_nodes2() .peer_no(2) .topics(Vec::new()) .to_subscribe(true) @@ -1604,7 +1589,7 @@ mod tests { #[test] fn no_gossip_gets_sent_to_explicit_peers() { - let (mut gs, peers, topic_hashes) = inject_nodes1() + let (mut gs, peers, topic_hashes) = inject_nodes2() .peer_no(2) .topics(vec![String::from("topic1"), String::from("topic2")]) .to_subscribe(true) @@ -1651,7 +1636,7 @@ mod tests { // Tests the mesh maintenance addition #[test] fn test_mesh_addition() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); // Adds mesh_low peers and PRUNE 2 giving us a deficit. let (mut gs, peers, topics) = inject_nodes2() @@ -1690,7 +1675,7 @@ mod tests { // Adds mesh_low peers and PRUNE 2 giving us a deficit. let n = config.mesh_n_high() + 10; //make all outbound connections so that we allow grafting to all - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(n) .topics(vec!["test".into()]) .to_subscribe(true) @@ -1712,7 +1697,7 @@ mod tests { #[test] fn test_connect_to_px_peers_on_handle_prune() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) @@ -1768,7 +1753,7 @@ mod tests { #[test] fn test_send_px_and_backoff_in_prune() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); //build mesh with enough peers for px let (mut gs, peers, topics) = inject_nodes2() @@ -1809,7 +1794,7 @@ mod tests { #[test] fn test_prune_backoffed_peer_on_graft() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); //build mesh with enough peers for px let (mut gs, peers, topics) = inject_nodes2() @@ -1861,7 +1846,7 @@ mod tests { .build() .unwrap(); //only one peer => mesh too small and will try to regraft as early as possible - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -1918,7 +1903,7 @@ mod tests { .build() .unwrap(); //only one peer => mesh too small and will try to regraft as early as possible - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -1965,7 +1950,7 @@ mod tests { #[test] fn test_flood_publish() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); let topic = "test"; // Adds more peers than mesh can hold to test flood publishing @@ -1998,7 +1983,7 @@ mod tests { .config .message_id(&publishes.first().expect("Should contain > 0 entries")); - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); assert_eq!( publishes.len(), config.mesh_n_high() + 10, @@ -2013,7 +1998,7 @@ mod tests { #[test] fn test_gossip_to_at_least_gossip_lazy_peers() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); //add more peers than in mesh to test gossipping //by default only mesh_n_low peers will get added to mesh @@ -2054,7 +2039,7 @@ mod tests { #[test] fn test_gossip_to_at_most_gossip_factor_peers() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); //add a lot of peers let m = @@ -2096,7 +2081,7 @@ mod tests { #[test] fn test_accept_only_outbound_peer_grafts_when_mesh_full() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); //enough peers to fill the mesh let (mut gs, peers, topics) = inject_nodes2() @@ -2145,7 +2130,7 @@ mod tests { .unwrap(); //fill the mesh with inbound connections - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(n) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2180,7 +2165,7 @@ mod tests { #[test] fn test_add_outbound_peers_if_min_is_not_satisfied() { - let config = GossipsubConfig::default(); + let config: GossipsubConfig = GossipsubConfig::default(); // Fill full mesh with inbound peers let (mut gs, peers, topics) = inject_nodes2() @@ -2223,7 +2208,7 @@ mod tests { let config = GossipsubConfig::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2268,7 +2253,7 @@ mod tests { fn test_dont_graft_to_negative_scored_peers() { let config = GossipsubConfig::default(); //init full mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2307,7 +2292,7 @@ mod tests { let config = GossipsubConfig::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2357,7 +2342,7 @@ mod tests { .unwrap(); // Build mesh with three peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(3) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2408,7 +2393,7 @@ mod tests { peer_score_thresholds.gossip_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; // Build full mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2477,7 +2462,7 @@ mod tests { peer_score_thresholds.gossip_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; // Build full mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2554,7 +2539,7 @@ mod tests { peer_score_thresholds.gossip_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; //build full mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2625,7 +2610,7 @@ mod tests { peer_score_thresholds.publish_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; //build mesh with no peers and no subscribed topics - let (mut gs, _, _) = inject_nodes1() + let (mut gs, _, _) = inject_nodes2() .gs_config(config.clone()) .scoring(Some((peer_score_params, peer_score_thresholds))) .create_network(); @@ -2682,7 +2667,7 @@ mod tests { peer_score_thresholds.publish_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; //build mesh with no peers - let (mut gs, _, topics) = inject_nodes1() + let (mut gs, _, topics) = inject_nodes2() .topics(vec!["test".into()]) .gs_config(config.clone()) .scoring(Some((peer_score_params, peer_score_thresholds))) @@ -2737,7 +2722,7 @@ mod tests { peer_score_thresholds.graylist_threshold = 3.0 * peer_score_params.behaviour_penalty_weight; //build mesh with no peers - let (mut gs, _, topics) = inject_nodes1() + let (mut gs, _, topics) = inject_nodes2() .topics(vec!["test".into()]) .gs_config(config.clone()) .scoring(Some((peer_score_params, peer_score_thresholds))) @@ -2866,7 +2851,7 @@ mod tests { peer_score_thresholds.accept_px_threshold = peer_score_params.app_specific_weight; // Build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(2) .topics(vec!["test".into()]) .to_subscribe(true) @@ -2943,7 +2928,7 @@ mod tests { //build mesh with more peers than mesh can hold let n = config.mesh_n_high() + 1; - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(n) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3001,7 +2986,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, _) = inject_nodes1() + let (mut gs, peers, _) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3084,7 +3069,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(2) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3184,7 +3169,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(2) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3285,7 +3270,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3378,7 +3363,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3434,7 +3419,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3492,7 +3477,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3542,7 +3527,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3598,7 +3583,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3657,7 +3642,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with two peers - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(2) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3724,7 +3709,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3800,7 +3785,7 @@ mod tests { let peer_score_thresholds = PeerScoreThresholds::default(); //build mesh with one peer - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3850,7 +3835,7 @@ mod tests { peer_score_params.app_specific_weight = 2.0; //build mesh with one peer - let (mut gs, peers, _) = inject_nodes1() + let (mut gs, peers, _) = inject_nodes2() .peer_no(1) .topics(vec!["test".into()]) .to_subscribe(true) @@ -3874,7 +3859,7 @@ mod tests { peer_score_params.ip_colocation_factor_threshold = 5.0; peer_score_params.ip_colocation_factor_weight = -2.0; - let (mut gs, _, _) = inject_nodes1() + let (mut gs, _, _) = inject_nodes2() .peer_no(0) .topics(vec![]) .to_subscribe(false) @@ -3993,7 +3978,7 @@ mod tests { peer_score_params.behaviour_penalty_weight = -2.0; peer_score_params.behaviour_penalty_decay = 0.9; - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(2) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4068,7 +4053,7 @@ mod tests { let mut thresholds = PeerScoreThresholds::default(); thresholds.opportunistic_graft_threshold = 2.0; - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(5) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4218,7 +4203,7 @@ mod tests { .build() .unwrap(); //build gossipsub with full mesh - let (mut gs, _, topics) = inject_nodes1() + let (mut gs, _, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4305,7 +4290,7 @@ mod tests { .build() .unwrap(); //build gossipsub with full mesh - let (mut gs, _, topics) = inject_nodes1() + let (mut gs, _, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4398,7 +4383,7 @@ mod tests { .build() .unwrap(); //build gossipsub with full mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4481,7 +4466,7 @@ mod tests { peer_score_params.behaviour_penalty_weight = -1.0; //fill the mesh - let (mut gs, peers, topics) = inject_nodes1() + let (mut gs, peers, topics) = inject_nodes2() .peer_no(config.mesh_n_high()) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4586,7 +4571,7 @@ mod tests { .flood_publish(false) .build() .unwrap(); - let (mut gs, _, topics) = inject_nodes1() + let (mut gs, _, topics) = inject_nodes2() .peer_no(config.mesh_n_low() - 1) .topics(vec!["test".into()]) .to_subscribe(false) @@ -4642,7 +4627,7 @@ mod tests { .flood_publish(false) .build() .unwrap(); - let (mut gs, _, _) = inject_nodes1() + let (mut gs, _, _) = inject_nodes2() .peer_no(config.mesh_n_low() - 1) .topics(Vec::new()) .to_subscribe(false) @@ -4989,7 +4974,7 @@ mod tests { #[test] fn test_subscribe_and_graft_with_negative_score() { //simulate a communication between two gossipsub instances - let (mut gs1, _, topic_hashes) = inject_nodes1() + let (mut gs1, _, topic_hashes) = inject_nodes2() .topics(vec!["test".into()]) .scoring(Some(( PeerScoreParams::default(), diff --git a/protocols/gossipsub/src/config.rs b/protocols/gossipsub/src/config.rs index e416ee0006b..dd2e63bb4aa 100644 --- a/protocols/gossipsub/src/config.rs +++ b/protocols/gossipsub/src/config.rs @@ -933,7 +933,7 @@ mod test { #[test] fn create_thing() { - let builder = GossipsubConfigBuilder::default() + let builder: GossipsubConfig = GossipsubConfigBuilder::default() .protocol_id_prefix("purple") .build() .unwrap(); diff --git a/protocols/gossipsub/src/protocol.rs b/protocols/gossipsub/src/protocol.rs index 7b8bae3c243..084bc8d2e77 100644 --- a/protocols/gossipsub/src/protocol.rs +++ b/protocols/gossipsub/src/protocol.rs @@ -566,7 +566,7 @@ mod tests { // generate an arbitrary GossipsubMessage using the behaviour signing functionality let config = GossipsubConfig::default(); - let gs = Gossipsub::new( + let gs: Gossipsub = Gossipsub::new( crate::MessageAuthenticity::Signed(keypair.0.clone()), config, ) From 49ddb3c91e02b867708b415d30b1510a5e0e6eea Mon Sep 17 00:00:00 2001 From: blacktemplar Date: Fri, 11 Dec 2020 18:13:46 +0100 Subject: [PATCH 4/5] type annotation in example --- examples/gossipsub-chat.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/gossipsub-chat.rs b/examples/gossipsub-chat.rs index 1bfa386a8d6..e82f4e918a9 100644 --- a/examples/gossipsub-chat.rs +++ b/examples/gossipsub-chat.rs @@ -94,7 +94,7 @@ fn main() -> Result<(), Box> { .build() .expect("Valid config"); // build a gossipsub network behaviour - let mut gossipsub = + let mut gossipsub: gossipsub::Gossipsub = gossipsub::Gossipsub::new(MessageAuthenticity::Signed(local_key), gossipsub_config) .expect("Correct configuration"); From b7d329cb63ac093144ccbeb986bbeb404b7c1c97 Mon Sep 17 00:00:00 2001 From: blacktemplar Date: Fri, 11 Dec 2020 22:02:43 +0100 Subject: [PATCH 5/5] fix doc example --- protocols/gossipsub/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protocols/gossipsub/src/lib.rs b/protocols/gossipsub/src/lib.rs index 206171f4690..9c48fee7c25 100644 --- a/protocols/gossipsub/src/lib.rs +++ b/protocols/gossipsub/src/lib.rs @@ -104,7 +104,7 @@ //! // set default parameters for gossipsub //! let gossipsub_config = libp2p_gossipsub::GossipsubConfig::default(); //! // build a gossipsub network behaviour -//! let mut gossipsub = +//! let mut gossipsub: libp2p_gossipsub::Gossipsub = //! libp2p_gossipsub::Gossipsub::new(message_authenticity, gossipsub_config).unwrap(); //! // subscribe to the topic //! gossipsub.subscribe(&topic);