Skip to content

Commit

Permalink
Fix examples and gossipsub/tests/smoke
Browse files Browse the repository at this point in the history
  • Loading branch information
StemCll committed Jan 4, 2023
1 parent 1c56e82 commit e2e3e51
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 37 deletions.
24 changes: 11 additions & 13 deletions examples/gossipsub-chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@
use async_std::io;
use futures::{prelude::*, select};
use libp2p::gossipsub::MessageId;
use libp2p::gossipsub::{
Behaviour as Gossipsub, Event, IdentTopic as Topic, Message, MessageAuthenticity,
ValidationMode,
};
use libp2p::{
gossipsub, identity, mdns, swarm::NetworkBehaviour, swarm::SwarmEvent, PeerId, Swarm,
};
Expand All @@ -73,31 +68,34 @@ async fn main() -> Result<(), Box<dyn Error>> {
// We create a custom network behaviour that combines Gossipsub and Mdns.
#[derive(NetworkBehaviour)]
struct MyBehaviour {
gossipsub: Gossipsub,
gossipsub: gossipsub::Behaviour,
mdns: mdns::async_io::Behaviour,
}

// To content-address message, we can take the hash of message and use it as an ID.
let message_id_fn = |message: &Message| {
let message_id_fn = |message: &gossipsub::Message| {
let mut s = DefaultHasher::new();
message.data.hash(&mut s);
MessageId::from(s.finish().to_string())
gossipsub::MessageId::from(s.finish().to_string())
};

// Set a custom gossipsub configuration
let gossipsub_config = gossipsub::ConfigBuilder::default()
.heartbeat_interval(Duration::from_secs(10)) // This is set to aid debugging by not cluttering the log space
.validation_mode(ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
.validation_mode(gossipsub::ValidationMode::Strict) // This sets the kind of message validation. The default is Strict (enforce message signing)
.message_id_fn(message_id_fn) // content-address messages. No two messages of the same content will be propagated.
.build()
.expect("Valid config");

// build a gossipsub network behaviour
let mut gossipsub = Gossipsub::new(MessageAuthenticity::Signed(local_key), gossipsub_config)
.expect("Correct configuration");
let mut gossipsub = gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(local_key),
gossipsub_config,
)
.expect("Correct configuration");

// Create a Gossipsub topic
let topic = Topic::new("test-net");
let topic = gossipsub::IdentTopic::new("test-net");

// subscribes to our topic
gossipsub.subscribe(&topic)?;
Expand Down Expand Up @@ -140,7 +138,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
swarm.behaviour_mut().gossipsub.remove_explicit_peer(&peer_id);
}
},
SwarmEvent::Behaviour(MyBehaviourEvent::Gossipsub(Event::ProtobufMessage {
SwarmEvent::Behaviour(MyBehaviourEvent::Gossipsub(gossipsub::Event::ProtobufMessage {
propagation_source: peer_id,
message_id: id,
message,
Expand Down
19 changes: 9 additions & 10 deletions examples/ipfs-private.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ use libp2p::{
core::{
either::EitherTransport, muxing::StreamMuxerBox, transport, transport::upgrade::Version,
},
gossipsub::{self, Behaviour as Gossipsub, ConfigBuilder, Event, MessageAuthenticity},
identify, identity,
gossipsub, identify, identity,
multiaddr::Protocol,
noise, ping,
pnet::{PnetConfig, PreSharedKey},
Expand Down Expand Up @@ -151,19 +150,19 @@ async fn main() -> Result<(), Box<dyn Error>> {
#[derive(NetworkBehaviour)]
#[behaviour(out_event = "MyBehaviourEvent")]
struct MyBehaviour {
gossipsub: Gossipsub,
gossipsub: gossipsub::Behaviour,
identify: identify::Behaviour,
ping: ping::Behaviour,
}

enum MyBehaviourEvent {
Gossipsub(Event),
Gossipsub(gossipsub::Event),
Identify(identify::Event),
Ping(ping::Event),
}

impl From<Event> for MyBehaviourEvent {
fn from(event: Event) -> Self {
impl From<gossipsub::Event> for MyBehaviourEvent {
fn from(event: gossipsub::Event) -> Self {
MyBehaviourEvent::Gossipsub(event)
}
}
Expand All @@ -182,13 +181,13 @@ async fn main() -> Result<(), Box<dyn Error>> {

// Create a Swarm to manage peers and events
let mut swarm = {
let gossipsub_config = ConfigBuilder::default()
let gossipsub_config = gossipsub::ConfigBuilder::default()
.max_transmit_size(262144)
.build()
.expect("valid config");
let mut behaviour = MyBehaviour {
gossipsub: Gossipsub::new(
MessageAuthenticity::Signed(local_key.clone()),
gossipsub: gossipsub::Behaviour::new(
gossipsub::MessageAuthenticity::Signed(local_key.clone()),
gossipsub_config,
)
.expect("Valid configuration"),
Expand Down Expand Up @@ -237,7 +236,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
SwarmEvent::Behaviour(MyBehaviourEvent::Identify(event)) => {
println!("identify: {event:?}");
}
SwarmEvent::Behaviour(MyBehaviourEvent::Gossipsub(Event::ProtobufMessage {
SwarmEvent::Behaviour(MyBehaviourEvent::Gossipsub(gossipsub::Event::ProtobufMessage {
propagation_source: peer_id,
message_id: id,
message,
Expand Down
27 changes: 13 additions & 14 deletions protocols/gossipsub/tests/smoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,17 @@ use futures::StreamExt;
use libp2p_core::{
identity, multiaddr::Protocol, transport::MemoryTransport, upgrade, Multiaddr, Transport,
};
use libp2p_gossipsub::{
Behaviour, ConfigBuilder, Event, IdentTopic as Topic, MessageAuthenticity, ValidationMode,
};
use libp2p_gossipsub as gossipsub;
use libp2p_plaintext::PlainText2Config;
use libp2p_swarm::{Swarm, SwarmEvent};
use libp2p_yamux as yamux;

struct Graph {
pub nodes: Vec<(Multiaddr, Swarm<Behaviour>)>,
pub nodes: Vec<(Multiaddr, Swarm<gossipsub::Behaviour>)>,
}

impl Future for Graph {
type Output = (Multiaddr, Event);
type Output = (Multiaddr, gossipsub::Event);

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
for (addr, node) in &mut self.nodes {
Expand Down Expand Up @@ -76,7 +74,7 @@ impl Graph {
.cycle()
.take(num_nodes)
.map(|_| build_node())
.collect::<Vec<(Multiaddr, Swarm<Behaviour>)>>();
.collect::<Vec<(Multiaddr, Swarm<gossipsub::Behaviour>)>>();

let mut connected_nodes = vec![not_connected_nodes.pop().unwrap()];

Expand Down Expand Up @@ -111,7 +109,7 @@ impl Graph {
/// `true`.
///
/// Returns [`true`] on success and [`false`] on timeout.
fn wait_for<F: FnMut(&Event) -> bool>(&mut self, mut f: F) -> bool {
fn wait_for<F: FnMut(&gossipsub::Event) -> bool>(&mut self, mut f: F) -> bool {
let fut = futures::future::poll_fn(move |cx| match self.poll_unpin(cx) {
Poll::Ready((_addr, ev)) if f(&ev) => Poll::Ready(()),
_ => Poll::Pending,
Expand Down Expand Up @@ -142,7 +140,7 @@ impl Graph {
}
}

fn build_node() -> (Multiaddr, Swarm<Behaviour>) {
fn build_node() -> (Multiaddr, Swarm<gossipsub::Behaviour>) {
let key = identity::Keypair::generate_ed25519();
let public_key = key.public();

Expand All @@ -161,15 +159,16 @@ fn build_node() -> (Multiaddr, Swarm<Behaviour>) {
// reduce the default values of the heartbeat, so that all nodes will receive gossip in a
// timely fashion.

let config = ConfigBuilder::default()
let config = gossipsub::ConfigBuilder::default()
.heartbeat_initial_delay(Duration::from_millis(100))
.heartbeat_interval(Duration::from_millis(200))
.history_length(10)
.history_gossip(10)
.validation_mode(ValidationMode::Permissive)
.validation_mode(gossipsub::ValidationMode::Permissive)
.build()
.unwrap();
let behaviour = Behaviour::new(MessageAuthenticity::Author(peer_id), config).unwrap();
let behaviour =
gossipsub::Behaviour::new(gossipsub::MessageAuthenticity::Author(peer_id), config).unwrap();
let mut swarm = Swarm::without_executor(transport, behaviour, peer_id);

let port = 1 + random::<u64>();
Expand All @@ -196,15 +195,15 @@ fn multi_hop_propagation() {
let number_nodes = graph.nodes.len();

// Subscribe each node to the same topic.
let topic = Topic::new("test-net");
let topic = gossipsub::IdentTopic::new("test-net");
for (_addr, node) in &mut graph.nodes {
node.behaviour_mut().subscribe(&topic).unwrap();
}

// Wait for all nodes to be subscribed.
let mut subscribed = 0;
let all_subscribed = graph.wait_for(move |ev| {
if let Event::Subscribed { .. } = ev {
if let gossipsub::Event::Subscribed { .. } = ev {
subscribed += 1;
if subscribed == (number_nodes - 1) * 2 {
return true;
Expand Down Expand Up @@ -233,7 +232,7 @@ fn multi_hop_propagation() {
// Wait for all nodes to receive the published message.
let mut received_msgs = 0;
let all_received = graph.wait_for(move |ev| {
if let Event::ProtobufMessage { .. } = ev {
if let gossipsub::Event::ProtobufMessage { .. } = ev {
received_msgs += 1;
if received_msgs == number_nodes - 1 {
return true;
Expand Down

0 comments on commit e2e3e51

Please sign in to comment.