Add support for mDNS (#2153)

* Use libp2p 0.6.0 instead of a custom branch

* Add support for mDNS

* Fix tests

* Nit
This commit is contained in:
Pierre Krieger
2019-03-31 20:47:15 -03:00
committed by DemiMarie-parity
parent d4a4022dd1
commit 3dfda381d5
6 changed files with 42 additions and 1 deletions
+2
View File
@@ -359,6 +359,8 @@ fn fill_network_configuration(
config.in_peers = cli.in_peers; config.in_peers = cli.in_peers;
config.out_peers = cli.out_peers; config.out_peers = cli.out_peers;
config.enable_mdns = !cli.no_mdns;
Ok(()) Ok(())
} }
+5
View File
@@ -118,6 +118,11 @@ pub struct NetworkConfigurationParams {
#[structopt(long = "in-peers", value_name = "IN_PEERS", default_value = "25")] #[structopt(long = "in-peers", value_name = "IN_PEERS", default_value = "25")]
pub in_peers: u32, pub in_peers: u32,
/// By default, the network will use mDNS to discover other nodes on the local network. This
/// disables it.
#[structopt(long = "no-mdns")]
pub no_mdns: bool,
#[allow(missing_docs)] #[allow(missing_docs)]
#[structopt(flatten)] #[structopt(flatten)]
pub node_key_params: NodeKeyParams pub node_key_params: NodeKeyParams
@@ -20,8 +20,10 @@ use libp2p::NetworkBehaviour;
use libp2p::core::{Multiaddr, PeerId, ProtocolsHandler, PublicKey}; use libp2p::core::{Multiaddr, PeerId, ProtocolsHandler, PublicKey};
use libp2p::core::swarm::{ConnectedPoint, NetworkBehaviour, NetworkBehaviourAction}; use libp2p::core::swarm::{ConnectedPoint, NetworkBehaviour, NetworkBehaviourAction};
use libp2p::core::swarm::{NetworkBehaviourEventProcess, PollParameters}; use libp2p::core::swarm::{NetworkBehaviourEventProcess, PollParameters};
use libp2p::core::swarm::toggle::Toggle;
use libp2p::identify::{Identify, IdentifyEvent, protocol::IdentifyInfo}; use libp2p::identify::{Identify, IdentifyEvent, protocol::IdentifyInfo};
use libp2p::kad::{Kademlia, KademliaOut}; use libp2p::kad::{Kademlia, KademliaOut};
use libp2p::mdns::{Mdns, MdnsEvent};
use libp2p::ping::{Ping, PingEvent}; use libp2p::ping::{Ping, PingEvent};
use log::{debug, trace, warn}; use log::{debug, trace, warn};
use std::{cmp, io, fmt, time::Duration, time::Instant}; use std::{cmp, io, fmt, time::Duration, time::Instant};
@@ -41,6 +43,8 @@ pub struct Behaviour<TMessage, TSubstream> {
discovery: DiscoveryBehaviour<TSubstream>, discovery: DiscoveryBehaviour<TSubstream>,
/// Periodically identifies the remote and responds to incoming requests. /// Periodically identifies the remote and responds to incoming requests.
identify: Identify<TSubstream>, identify: Identify<TSubstream>,
/// Discovers nodes on the local network.
mdns: Toggle<Mdns<TSubstream>>,
/// Queue of events to produce for the outside. /// Queue of events to produce for the outside.
#[behaviour(ignore)] #[behaviour(ignore)]
@@ -55,6 +59,7 @@ impl<TMessage, TSubstream> Behaviour<TMessage, TSubstream> {
protocol: RegisteredProtocol<TMessage>, protocol: RegisteredProtocol<TMessage>,
known_addresses: Vec<(PeerId, Multiaddr)>, known_addresses: Vec<(PeerId, Multiaddr)>,
peerset: substrate_peerset::PeersetMut, peerset: substrate_peerset::PeersetMut,
enable_mdns: bool,
) -> Self { ) -> Self {
let identify = { let identify = {
let proto_version = "/substrate/1.0".to_string(); let proto_version = "/substrate/1.0".to_string();
@@ -78,6 +83,17 @@ impl<TMessage, TSubstream> Behaviour<TMessage, TSubstream> {
duration_to_next_kad: Duration::from_secs(1), duration_to_next_kad: Duration::from_secs(1),
}, },
identify, identify,
mdns: if enable_mdns {
match Mdns::new() {
Ok(mdns) => Some(mdns).into(),
Err(err) => {
warn!(target: "sub-libp2p", "Failed to initialize mDNS: {:?}", err);
None.into()
}
}
} else {
None.into()
},
events: Vec::new(), events: Vec::new(),
} }
} }
@@ -283,6 +299,19 @@ impl<TMessage, TSubstream> NetworkBehaviourEventProcess<PingEvent> for Behaviour
} }
} }
impl<TMessage, TSubstream> NetworkBehaviourEventProcess<MdnsEvent> for Behaviour<TMessage, TSubstream> {
fn inject_event(&mut self, event: MdnsEvent) {
match event {
MdnsEvent::Discovered(list) => {
for (peer_id, _) in list {
self.custom_protocols.add_discovered_node(&peer_id);
}
},
MdnsEvent::Expired(_) => {}
}
}
}
impl<TMessage, TSubstream> Behaviour<TMessage, TSubstream> { impl<TMessage, TSubstream> Behaviour<TMessage, TSubstream> {
fn poll<TEv>(&mut self) -> Async<NetworkBehaviourAction<TEv, BehaviourOut<TMessage>>> { fn poll<TEv>(&mut self) -> Async<NetworkBehaviourAction<TEv, BehaviourOut<TMessage>>> {
if !self.events.is_empty() { if !self.events.is_empty() {
@@ -48,6 +48,9 @@ pub struct NetworkConfiguration {
pub client_version: String, pub client_version: String,
/// Name of the node. Sent over the wire for debugging purposes. /// Name of the node. Sent over the wire for debugging purposes.
pub node_name: String, pub node_name: String,
/// If true, the network will use mDNS to discover other libp2p nodes on the local network
/// and connect to them if they support the same chain.
pub enable_mdns: bool,
} }
impl Default for NetworkConfiguration { impl Default for NetworkConfiguration {
@@ -65,6 +68,7 @@ impl Default for NetworkConfiguration {
non_reserved_mode: NonReservedPeerMode::Accept, non_reserved_mode: NonReservedPeerMode::Accept,
client_version: "unknown".into(), client_version: "unknown".into(),
node_name: "unknown".into(), node_name: "unknown".into(),
enable_mdns: false,
} }
} }
} }
@@ -88,7 +88,7 @@ where TMessage: CustomMessage + Send + 'static {
// Build the swarm. // Build the swarm.
let (mut swarm, bandwidth) = { let (mut swarm, bandwidth) = {
let user_agent = format!("{} ({})", config.client_version, config.node_name); let user_agent = format!("{} ({})", config.client_version, config.node_name);
let behaviour = Behaviour::new(user_agent, local_public, registered_custom, known_addresses, peerset_receiver); let behaviour = Behaviour::new(user_agent, local_public, registered_custom, known_addresses, peerset_receiver, config.enable_mdns);
let (transport, bandwidth) = transport::build_transport(local_identity); let (transport, bandwidth) = transport::build_transport(local_identity);
(Swarm::new(transport, behaviour, local_peer_id.clone()), bandwidth) (Swarm::new(transport, behaviour, local_peer_id.clone()), bandwidth)
}; };
+1
View File
@@ -99,6 +99,7 @@ fn node_config<F: ServiceFactory> (
non_reserved_mode: NonReservedPeerMode::Accept, non_reserved_mode: NonReservedPeerMode::Accept,
client_version: "network/test/0.1".to_owned(), client_version: "network/test/0.1".to_owned(),
node_name: "unknown".to_owned(), node_name: "unknown".to_owned(),
enable_mdns: false,
}; };
Configuration { Configuration {