Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 1 addition & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions substrate/cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ exit-future = "0.1"
substrate-client = { path = "../../substrate/client" }
substrate-extrinsic-pool = { path = "../../substrate/extrinsic-pool" }
substrate-network = { path = "../../substrate/network" }
substrate-network-libp2p = { path = "../../substrate/network-libp2p" }
substrate-runtime-primitives = { path = "../../substrate/runtime/primitives" }
substrate-service = { path = "../../substrate/service" }
substrate-telemetry = { path = "../../substrate/telemetry" }
Expand Down
9 changes: 7 additions & 2 deletions substrate/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ extern crate backtrace;

extern crate substrate_client as client;
extern crate substrate_network as network;
extern crate substrate_network_libp2p as network_libp2p;
extern crate substrate_runtime_primitives as runtime_primitives;
extern crate substrate_extrinsic_pool;
extern crate substrate_service as service;
Expand All @@ -54,15 +55,17 @@ pub mod error;
pub mod informant;
mod panic_hook;

use network_libp2p::AddrComponent;
use runtime_primitives::traits::As;
use service::{
ServiceFactory, FactoryFullConfiguration, RuntimeGenesis,
FactoryGenesis, PruningMode, ChainSpec,
};

use std::io::{Write, Read, stdin, stdout};
use std::iter;
use std::fs::File;
use std::net::SocketAddr;
use std::net::{Ipv4Addr, SocketAddr};
use std::path::{Path, PathBuf};
use names::{Generator, Name};
use regex::Regex;
Expand Down Expand Up @@ -281,7 +284,9 @@ where
None => 30333,
};

config.network.listen_address = Some(SocketAddr::new("0.0.0.0".parse().unwrap(), port));
config.network.listen_address = iter::once(AddrComponent::IP4(Ipv4Addr::new(0, 0, 0, 0)))
.chain(iter::once(AddrComponent::TCP(port)))
.collect();
config.network.public_address = None;
config.network.client_version = config.client_id();
config.network.use_secret = match matches.value_of("node-key").map(|s| s.parse()) {
Expand Down
1 change: 0 additions & 1 deletion substrate/network-libp2p/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ libp2p = { git = "https://github.com/tomaka/libp2p-rs", branch = "polkadot-2", d
ethcore-io = { git = "https://github.com/paritytech/parity.git" }
ethkey = { git = "https://github.com/paritytech/parity.git" }
ethereum-types = "0.3"
ipnetwork = "0.12.6"
parking_lot = "0.5"
libc = "0.2"
log = "0.3"
Expand Down
2 changes: 1 addition & 1 deletion substrate/network-libp2p/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ extern crate varint;

extern crate ethcore_io as io;
extern crate ethereum_types;
extern crate ipnetwork;

#[macro_use]
extern crate error_chain;
Expand All @@ -44,6 +43,7 @@ extern crate assert_matches;
pub use connection_filter::{ConnectionFilter, ConnectionDirection};
pub use io::TimerToken;
pub use error::{Error, ErrorKind, DisconnectReason};
pub use libp2p::{Multiaddr, multiaddr::AddrComponent};
pub use traits::*;

mod connection_filter;
Expand Down
2 changes: 1 addition & 1 deletion substrate/network-libp2p/src/network_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ impl NetworkState {
peer_by_nodeid: FnvHashMap::with_capacity_and_hasher(expected_max_peers, Default::default()),
info_by_peer: FnvHashMap::with_capacity_and_hasher(expected_max_peers, Default::default()),
}),
reserved_only: atomic::AtomicBool::new(false),
reserved_only: atomic::AtomicBool::new(config.non_reserved_mode == NonReservedPeerMode::Deny),
reserved_peers,
next_node_index: atomic::AtomicUsize::new(0),
disabled_nodes: Mutex::new(Default::default()),
Expand Down
63 changes: 22 additions & 41 deletions substrate/network-libp2p/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,10 @@ use libp2p::core::{Endpoint, PeerId as PeerstorePeerId, PublicKey};
use libp2p::core::{SwarmController, UniqueConnecState};
use libp2p::ping;
use libp2p::transport_timeout::TransportTimeout;
use {PacketId, SessionInfo, ConnectionFilter, TimerToken};
use {PacketId, SessionInfo, TimerToken};
use rand;
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use std::iter;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::mpsc as sync_mpsc;
use std::thread;
Expand Down Expand Up @@ -104,17 +103,13 @@ impl NetworkService {
/// generic here is too much and crashes the Rust compiler.
pub fn new(
config: NetworkConfiguration,
protocols: Vec<(Arc<NetworkProtocolHandler + Send + Sync>, ProtocolId, &[(u8, u8)])>,
filter: Option<Arc<ConnectionFilter>>
protocols: Vec<(Arc<NetworkProtocolHandler + Send + Sync>, ProtocolId, &[(u8, u8)])>
) -> Result<NetworkService, Error> {
// TODO: for now `filter` is always `None` ; remove it from the code or implement it
assert!(filter.is_none());

let network_state = NetworkState::new(&config)?;

let local_peer_id = network_state.local_public_key().clone()
.into_peer_id();
let mut listen_addr = config_to_listen_addr(&config);
let mut listen_addr = config.listen_address.clone();
listen_addr.append(AddrComponent::P2P(local_peer_id.clone().into_bytes()));
info!(target: "sub-libp2p", "Local node address is: {}", listen_addr);

Expand All @@ -134,6 +129,11 @@ impl NetworkService {
let (close_tx, close_rx) = oneshot::channel();
let (timeouts_register_tx, timeouts_register_rx) = mpsc::unbounded();

let mut listened_addrs = Vec::new();
if let Some(ref addr) = config.public_address {
listened_addrs.push(addr.clone());
}

let shared = Arc::new(Shared {
network_state,
protocols: RegisteredProtocols(protocols.into_iter()
Expand All @@ -146,7 +146,7 @@ impl NetworkService {
config,
timeouts_register_tx,
original_listened_addr: RwLock::new(None),
listened_addrs: RwLock::new(Vec::new()),
listened_addrs: RwLock::new(listened_addrs),
});

// Initialize all the protocols now.
Expand Down Expand Up @@ -446,20 +446,18 @@ fn init_thread(
};

// Listen on multiaddress.
// TODO: change the network config to directly contain a `Multiaddr`
{
let listen_addr = config_to_listen_addr(&shared.config);
debug!(target: "sub-libp2p", "Libp2p listening on {}", listen_addr);
match swarm_controller.listen_on(listen_addr.clone()) {
Ok(new_addr) => {
*shared.original_listened_addr.write() = Some(new_addr.clone());
},
Err(_) => {
warn!(target: "sub-libp2p", "Can't listen on {}, protocol not supported", listen_addr);
return Err(ErrorKind::BadProtocol.into())
},
}
match swarm_controller.listen_on(shared.config.listen_address.clone()) {
Ok(new_addr) => {
debug!(target: "sub-libp2p", "Libp2p listening on {}", new_addr);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that we print new_addr instead of listen_address.
The only practical difference is that if the user specifies port 0, then new_addr will contain the actual port we're listening on, and not 0.

Copy link
Contributor

@pepyakin pepyakin Aug 7, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what would happen if there is something already listening on the specified multiaddr?

*shared.original_listened_addr.write() = Some(new_addr.clone());
},
Err(_) => {
warn!(target: "sub-libp2p", "Can't listen on {}, protocol not supported",
shared.config.listen_address);
return Err(ErrorKind::BadProtocol.into())
},
}

// Explicitely connect to _all_ the boostrap nodes as a temporary measure.
for bootnode in shared.config.boot_nodes.iter() {
match shared.network_state.add_peer(bootnode) {
Expand Down Expand Up @@ -841,23 +839,6 @@ fn handle_custom_connection(
future::Either::B(final_fut)
}

/// Builds the multiaddress corresponding to the address we need to listen to
/// according to the config.
// TODO: put the `Multiaddr` directly in the `NetworkConfiguration`
fn config_to_listen_addr(config: &NetworkConfiguration) -> Multiaddr {
if let Some(addr) = config.listen_address {
let ip = match addr.ip() {
IpAddr::V4(addr) => AddrComponent::IP4(addr),
IpAddr::V6(addr) => AddrComponent::IP6(addr),
};
iter::once(ip).chain(iter::once(AddrComponent::TCP(addr.port()))).collect()
} else {
let host = AddrComponent::IP4(Ipv4Addr::new(0, 0, 0, 0));
let port = AddrComponent::TCP(0);
iter::once(host).chain(iter::once(port)).collect()
}
}

/// Randomly discovers peers to connect to.
/// This works by running a round at a regular interval, and skipping if we
/// reached `min_peers`. When we are over `min_peers`, we stop trying to dial
Expand Down Expand Up @@ -1402,6 +1383,6 @@ mod tests {
#[test]
fn builds_and_finishes_in_finite_time() {
// Checks that merely starting the network doesn't end up in an infinite loop.
let _service = NetworkService::new(Default::default(), vec![], None).unwrap();
let _service = NetworkService::new(Default::default(), vec![]).unwrap();
}
}
Loading