openethereum/util/src/network/host.rs

1107 lines
38 KiB
Rust
Raw Normal View History

2016-02-05 13:40:41 +01:00
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
2016-02-16 02:05:36 +01:00
use std::net::{SocketAddr};
use std::collections::{HashMap};
use std::hash::{Hasher};
2015-11-29 11:50:28 +01:00
use std::str::{FromStr};
2016-01-21 16:48:37 +01:00
use std::sync::*;
use std::ops::*;
use std::cmp::min;
2016-02-15 18:36:34 +01:00
use std::path::{Path, PathBuf};
use std::io::{Read, Write};
2016-03-11 10:57:58 +01:00
use std::default::Default;
2016-02-15 18:36:34 +01:00
use std::fs;
2015-11-29 11:50:28 +01:00
use mio::*;
use mio::tcp::*;
use hash::*;
2016-02-21 20:00:45 +01:00
use misc::version;
use crypto::*;
2016-01-09 10:27:41 +01:00
use sha3::Hashable;
2015-12-02 20:11:13 +01:00
use rlp::*;
use network::handshake::Handshake;
2015-12-17 11:42:30 +01:00
use network::session::{Session, SessionData};
use error::*;
use io::*;
2016-02-13 22:57:39 +01:00
use network::{NetworkProtocolHandler, PROTOCOL_VERSION};
2016-02-14 01:03:48 +01:00
use network::node_table::*;
2016-01-24 18:53:54 +01:00
use network::stats::NetworkStats;
use network::error::{NetworkError, DisconnectReason};
2016-02-13 22:57:39 +01:00
use network::discovery::{Discovery, TableUpdates, NodeEntry};
2016-02-16 02:05:36 +01:00
use network::ip_utils::{map_external_address, select_public_address};
2016-01-15 00:50:48 +01:00
type Slab<T> = ::slab::Slab<T, usize>;
2015-11-29 11:50:28 +01:00
2016-01-04 13:49:32 +01:00
const _DEFAULT_PORT: u16 = 30304;
const MAX_SESSIONS: usize = 1024;
const MAX_HANDSHAKES: usize = 80;
const MAX_HANDSHAKES_PER_ROUND: usize = 32;
2016-01-14 16:52:10 +01:00
const MAINTENANCE_TIMEOUT: u64 = 1000;
2015-11-29 11:50:28 +01:00
#[derive(Debug)]
2016-01-23 02:36:58 +01:00
/// Network service configuration
pub struct NetworkConfiguration {
2016-02-12 09:52:32 +01:00
/// Directory path to store network configuration. None means nothing will be saved
pub config_path: Option<String>,
2016-02-16 02:05:36 +01:00
/// IP address to listen for incoming connections. Listen to all connections by default
pub listen_address: Option<SocketAddr>,
/// IP address to advertise. Detected automatically if none.
pub public_address: Option<SocketAddr>,
/// Port for UDP connections, same as TCP by default
pub udp_port: Option<u16>,
2016-01-23 02:36:58 +01:00
/// Enable NAT configuration
pub nat_enabled: bool,
/// Enable discovery
pub discovery_enabled: bool,
/// Pin to boot nodes only
pub pin: bool,
/// List of initial node addresses
pub boot_nodes: Vec<String>,
2016-01-24 18:53:54 +01:00
/// Use provided node key instead of default
pub use_secret: Option<Secret>,
2016-02-13 22:57:39 +01:00
/// Number of connected peers to maintain
pub ideal_peers: u32,
2015-11-29 11:50:28 +01:00
}
2016-03-11 10:57:58 +01:00
impl Default for NetworkConfiguration {
fn default() -> Self {
NetworkConfiguration::new()
}
}
2015-11-29 11:50:28 +01:00
impl NetworkConfiguration {
2016-01-23 02:36:58 +01:00
/// Create a new instance of default settings.
2016-03-11 10:57:58 +01:00
pub fn new() -> Self {
2016-01-08 13:49:00 +01:00
NetworkConfiguration {
2016-02-12 09:52:32 +01:00
config_path: None,
2016-02-16 02:05:36 +01:00
listen_address: None,
public_address: None,
udp_port: None,
2016-01-08 13:49:00 +01:00
nat_enabled: true,
discovery_enabled: true,
pin: false,
boot_nodes: Vec::new(),
2016-01-24 18:53:54 +01:00
use_secret: None,
2016-02-14 17:42:03 +01:00
ideal_peers: 25,
2016-01-08 13:49:00 +01:00
}
}
2016-01-24 18:53:54 +01:00
/// Create new default configuration with sepcified listen port.
pub fn new_with_port(port: u16) -> NetworkConfiguration {
let mut config = NetworkConfiguration::new();
2016-02-16 02:05:36 +01:00
config.listen_address = Some(SocketAddr::from_str(&format!("0.0.0.0:{}", port)).unwrap());
2016-01-24 18:53:54 +01:00
config
}
2016-03-20 11:35:46 +01:00
/// Create new default configuration for localhost-only connection with random port (usefull for testing)
pub fn new_local() -> NetworkConfiguration {
let mut config = NetworkConfiguration::new();
config.listen_address = Some(SocketAddr::from_str("127.0.0.1:0").unwrap());
config.nat_enabled = false;
config
}
2015-11-29 11:50:28 +01:00
}
// Tokens
const TCP_ACCEPT: usize = LAST_HANDSHAKE + 1;
const IDLE: usize = LAST_HANDSHAKE + 2;
const DISCOVERY: usize = LAST_HANDSHAKE + 3;
const DISCOVERY_REFRESH: usize = LAST_HANDSHAKE + 4;
const DISCOVERY_ROUND: usize = LAST_HANDSHAKE + 5;
2016-02-23 19:38:06 +01:00
const INIT_PUBLIC: usize = LAST_HANDSHAKE + 6;
const NODE_TABLE: usize = LAST_HANDSHAKE + 7;
const FIRST_SESSION: usize = 0;
const LAST_SESSION: usize = FIRST_SESSION + MAX_SESSIONS - 1;
const FIRST_HANDSHAKE: usize = LAST_SESSION + 1;
const LAST_HANDSHAKE: usize = FIRST_HANDSHAKE + MAX_HANDSHAKES - 1;
const USER_TIMER: usize = LAST_HANDSHAKE + 256;
2015-12-17 11:42:30 +01:00
2016-01-10 22:42:27 +01:00
/// Protocol handler level packet id
2015-12-22 22:23:43 +01:00
pub type PacketId = u8;
2016-01-10 22:42:27 +01:00
/// Protocol / handler id
2015-12-17 11:42:30 +01:00
pub type ProtocolId = &'static str;
2015-11-29 11:50:28 +01:00
2016-01-10 22:42:27 +01:00
/// Messages used to communitate with the event loop from other threads.
2016-01-21 16:48:37 +01:00
#[derive(Clone)]
pub enum NetworkIoMessage<Message> where Message: Send + Sync + Clone {
2016-01-10 22:42:27 +01:00
/// Register a new protocol handler.
2015-12-17 11:42:30 +01:00
AddHandler {
/// Handler shared instance.
2016-01-21 16:48:37 +01:00
handler: Arc<NetworkProtocolHandler<Message> + Sync>,
/// Protocol Id.
2015-12-17 11:42:30 +01:00
protocol: ProtocolId,
/// Supported protocol versions.
2015-12-17 11:42:30 +01:00
versions: Vec<u8>,
},
/// Register a new protocol timer
2016-01-21 16:48:37 +01:00
AddTimer {
/// Protocol Id.
2016-01-21 16:48:37 +01:00
protocol: ProtocolId,
/// Timer token.
2016-01-21 16:48:37 +01:00
token: TimerToken,
/// Timer delay in milliseconds.
2016-01-21 16:48:37 +01:00
delay: u64,
},
/// Disconnect a peer.
2016-02-02 21:10:16 +01:00
Disconnect(PeerId),
/// Disconnect and temporary disable peer.
DisablePeer(PeerId),
/// User message
2016-01-13 23:13:57 +01:00
User(Message),
2015-11-29 11:50:28 +01:00
}
2016-01-10 22:42:27 +01:00
/// Local (temporary) peer session ID.
2015-12-22 22:23:43 +01:00
pub type PeerId = usize;
2015-12-17 11:42:30 +01:00
2015-12-02 20:11:13 +01:00
#[derive(Debug, PartialEq, Eq)]
2016-01-10 22:42:27 +01:00
/// Protocol info
2015-12-02 20:11:13 +01:00
pub struct CapabilityInfo {
2015-12-17 11:42:30 +01:00
pub protocol: ProtocolId,
pub version: u8,
2016-01-10 22:42:27 +01:00
/// Total number of packet IDs this protocol support.
2015-12-17 11:42:30 +01:00
pub packet_count: u8,
2015-12-02 20:11:13 +01:00
}
impl Encodable for CapabilityInfo {
2016-01-27 12:14:57 +01:00
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(2);
s.append(&self.protocol);
s.append(&self.version);
2015-12-02 20:11:13 +01:00
}
}
2016-01-10 22:42:27 +01:00
/// IO access point. This is passed to all IO handlers and provides an interface to the IO subsystem.
2016-01-21 16:48:37 +01:00
pub struct NetworkContext<'s, Message> where Message: Send + Sync + Clone + 'static, 's {
io: &'s IoContext<NetworkIoMessage<Message>>,
2016-01-13 13:56:48 +01:00
protocol: ProtocolId,
sessions: Arc<RwLock<Slab<SharedSession>>>,
2016-03-05 23:09:51 +01:00
session: Option<SharedSession>,
session_id: Option<StreamToken>,
2015-12-17 11:42:30 +01:00
}
2016-01-21 16:48:37 +01:00
impl<'s, Message> NetworkContext<'s, Message> where Message: Send + Sync + Clone + 'static, {
/// Create a new network IO access point. Takes references to all the data that can be updated within the IO handler.
fn new(io: &'s IoContext<NetworkIoMessage<Message>>,
protocol: ProtocolId,
2016-03-05 23:09:51 +01:00
session: Option<SharedSession>, sessions: Arc<RwLock<Slab<SharedSession>>>) -> NetworkContext<'s, Message> {
let id = session.as_ref().map(|s| s.lock().unwrap().token());
NetworkContext {
io: io,
2015-12-17 11:42:30 +01:00
protocol: protocol,
2016-03-05 23:09:51 +01:00
session_id: id,
2015-12-17 11:42:30 +01:00
session: session,
sessions: sessions,
2015-12-17 11:42:30 +01:00
}
}
2016-03-05 23:09:51 +01:00
fn resolve_session(&self, peer: PeerId) -> Option<SharedSession> {
match self.session_id {
Some(id) if id == peer => self.session.clone(),
_ => self.sessions.read().unwrap().get(peer).cloned(),
}
}
2015-12-30 12:23:36 +01:00
/// Send a packet over the network to another peer.
2016-01-21 16:48:37 +01:00
pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
2016-03-05 23:09:51 +01:00
let session = self.resolve_session(peer);
if let Some(session) = session {
2016-03-05 23:09:51 +01:00
try!(session.lock().unwrap().deref_mut().send_packet(self.protocol, packet_id as u8, &data));
try!(self.io.update_registration(peer));
2016-01-21 16:48:37 +01:00
} else {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Send: Peer no longer exist")
2015-12-22 22:23:43 +01:00
}
2015-12-17 11:42:30 +01:00
Ok(())
}
2016-03-05 23:09:51 +01:00
/// Respond to a current network message. Panics if no there is no packet in the context. If the session is expired returns nothing.
2016-01-21 16:48:37 +01:00
pub fn respond(&self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
2016-03-05 23:09:51 +01:00
assert!(self.session.is_some(), "Respond called without network context");
self.send(self.session_id.unwrap(), packet_id, data)
2015-12-17 11:42:30 +01:00
}
2016-02-19 16:34:31 +01:00
/// Send an IO message
pub fn message(&self, msg: Message) {
self.io.message(NetworkIoMessage::User(msg));
}
2015-12-30 12:23:36 +01:00
/// Disable current protocol capability for given peer. If no capabilities left peer gets disconnected.
2016-02-02 14:54:46 +01:00
pub fn disable_peer(&self, peer: PeerId) {
2015-12-22 22:23:43 +01:00
//TODO: remove capability, disconnect if no capabilities left
self.io.message(NetworkIoMessage::DisablePeer(peer));
2016-02-02 14:54:46 +01:00
}
/// Disconnect peer. Reconnect can be attempted later.
pub fn disconnect_peer(&self, peer: PeerId) {
2016-02-02 21:10:16 +01:00
self.io.message(NetworkIoMessage::Disconnect(peer));
2015-12-02 20:11:13 +01:00
}
2015-12-28 11:41:51 +01:00
2016-01-21 16:48:37 +01:00
/// Register a new IO timer. 'IoHandler::timeout' will be called with the token.
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> {
self.io.message(NetworkIoMessage::AddTimer {
token: token,
delay: ms,
protocol: self.protocol,
});
Ok(())
}
2016-01-14 16:52:10 +01:00
/// Returns peer identification string
pub fn peer_info(&self, peer: PeerId) -> String {
2016-03-05 23:09:51 +01:00
let session = self.resolve_session(peer);
if let Some(session) = session {
return session.lock().unwrap().info.client_version.clone()
2016-01-14 16:52:10 +01:00
}
"unknown".to_owned()
2016-01-14 16:52:10 +01:00
}
2015-12-17 11:42:30 +01:00
}
2016-01-10 22:42:27 +01:00
/// Shared host information
pub struct HostInfo {
2016-01-10 22:42:27 +01:00
/// Our private and public keys.
2016-01-08 13:49:00 +01:00
keys: KeyPair,
2016-01-10 22:42:27 +01:00
/// Current network configuration
2016-01-08 13:49:00 +01:00
config: NetworkConfiguration,
2016-01-10 22:42:27 +01:00
/// Connection nonce.
2015-12-02 20:11:13 +01:00
nonce: H256,
2016-01-10 22:42:27 +01:00
/// RLPx protocol version
2015-12-02 20:11:13 +01:00
pub protocol_version: u32,
2016-01-10 22:42:27 +01:00
/// Client identifier
2015-12-02 20:11:13 +01:00
pub client_version: String,
2016-01-10 22:42:27 +01:00
/// Registered capabilities (handlers)
2016-02-23 19:38:06 +01:00
pub capabilities: Vec<CapabilityInfo>,
2016-03-20 11:35:46 +01:00
/// Local address + discovery port
pub local_endpoint: NodeEndpoint,
2016-02-23 19:38:06 +01:00
/// Public address + discovery port
2016-03-20 11:35:46 +01:00
pub public_endpoint: Option<NodeEndpoint>,
}
impl HostInfo {
2016-01-10 22:42:27 +01:00
/// Returns public key
pub fn id(&self) -> &NodeId {
self.keys.public()
}
2016-01-10 22:42:27 +01:00
/// Returns secret key
pub fn secret(&self) -> &Secret {
self.keys.secret()
}
2016-01-10 22:42:27 +01:00
/// Increments and returns connection nonce.
pub fn next_nonce(&mut self) -> H256 {
self.nonce = self.nonce.sha3();
2016-01-19 12:14:29 +01:00
self.nonce.clone()
}
}
type SharedSession = Arc<Mutex<Session>>;
type SharedHandshake = Arc<Mutex<Handshake>>;
2016-01-21 16:48:37 +01:00
#[derive(Copy, Clone)]
struct ProtocolTimer {
pub protocol: ProtocolId,
pub token: TimerToken, // Handler level token
}
2016-01-10 22:42:27 +01:00
/// Root IO handler. Manages protocol handlers, IO timers and network connections.
2016-01-21 16:48:37 +01:00
pub struct Host<Message> where Message: Send + Sync + Clone {
pub info: RwLock<HostInfo>,
2016-03-20 11:35:46 +01:00
tcp_listener: Mutex<TcpListener>,
handshakes: Arc<RwLock<Slab<SharedHandshake>>>,
sessions: Arc<RwLock<Slab<SharedSession>>>,
2016-02-23 19:38:06 +01:00
discovery: Mutex<Option<Discovery>>,
2016-02-12 09:52:32 +01:00
nodes: RwLock<NodeTable>,
2016-01-21 16:48:37 +01:00
handlers: RwLock<HashMap<ProtocolId, Arc<NetworkProtocolHandler<Message>>>>,
timers: RwLock<HashMap<TimerToken, ProtocolTimer>>,
timer_counter: RwLock<usize>,
2016-01-24 18:53:54 +01:00
stats: Arc<NetworkStats>,
pinned_nodes: Vec<NodeId>,
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
impl<Message> Host<Message> where Message: Send + Sync + Clone {
2016-01-23 02:36:58 +01:00
/// Create a new instance
2016-03-20 11:35:46 +01:00
pub fn new(config: NetworkConfiguration) -> Result<Host<Message>, UtilError> {
let mut listen_address = match config.listen_address {
2016-02-16 02:05:36 +01:00
None => SocketAddr::from_str("0.0.0.0:30304").unwrap(),
Some(addr) => addr,
};
let keys = if let Some(ref secret) = config.use_secret {
KeyPair::from_secret(secret.clone()).unwrap()
} else {
2016-02-15 18:36:34 +01:00
config.config_path.clone().and_then(|ref p| load_key(&Path::new(&p)))
.map_or_else(|| {
let key = KeyPair::create().unwrap();
if let Some(path) = config.config_path.clone() {
save_key(&Path::new(&path), &key.secret());
}
key
},
|s| KeyPair::from_secret(s).expect("Error creating node secret key"))
};
2016-02-12 09:52:32 +01:00
let path = config.config_path.clone();
2016-03-20 11:35:46 +01:00
// Setup the server socket
let tcp_listener = try!(TcpListener::bind(&listen_address));
listen_address = SocketAddr::new(listen_address.ip(), try!(tcp_listener.local_addr()).port());
let udp_port = config.udp_port.unwrap_or(listen_address.port());
2016-02-23 19:38:06 +01:00
let local_endpoint = NodeEndpoint { address: listen_address, udp_port: udp_port };
2016-03-20 11:35:46 +01:00
2016-01-21 16:48:37 +01:00
let mut host = Host::<Message> {
info: RwLock::new(HostInfo {
2016-02-12 09:52:32 +01:00
keys: keys,
config: config,
2015-12-02 20:11:13 +01:00
nonce: H256::random(),
2016-02-13 22:57:39 +01:00
protocol_version: PROTOCOL_VERSION,
2016-02-21 20:00:45 +01:00
client_version: version(),
2015-12-17 11:42:30 +01:00
capabilities: Vec::new(),
2016-03-20 11:35:46 +01:00
public_endpoint: None,
local_endpoint: local_endpoint,
2016-01-21 16:48:37 +01:00
}),
2016-02-23 19:38:06 +01:00
discovery: Mutex::new(None),
2016-03-20 11:35:46 +01:00
tcp_listener: Mutex::new(tcp_listener),
handshakes: Arc::new(RwLock::new(Slab::new_starting_at(FIRST_HANDSHAKE, MAX_HANDSHAKES))),
sessions: Arc::new(RwLock::new(Slab::new_starting_at(FIRST_SESSION, MAX_SESSIONS))),
2016-02-12 09:52:32 +01:00
nodes: RwLock::new(NodeTable::new(path)),
2016-01-21 16:48:37 +01:00
handlers: RwLock::new(HashMap::new()),
timers: RwLock::new(HashMap::new()),
timer_counter: RwLock::new(USER_TIMER),
2016-01-24 18:53:54 +01:00
stats: Arc::new(NetworkStats::default()),
pinned_nodes: Vec::new(),
2016-01-21 16:48:37 +01:00
};
2016-01-23 02:36:58 +01:00
let boot_nodes = host.info.read().unwrap().config.boot_nodes.clone();
for n in boot_nodes {
host.add_node(&n);
2016-01-23 02:36:58 +01:00
}
2016-03-20 11:35:46 +01:00
Ok(host)
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
2016-01-24 18:53:54 +01:00
pub fn stats(&self) -> Arc<NetworkStats> {
self.stats.clone()
}
2016-01-21 16:48:37 +01:00
pub fn add_node(&mut self, id: &str) {
2015-11-29 11:50:28 +01:00
match Node::from_str(id) {
Err(e) => { debug!(target: "network", "Could not add node {}: {:?}", id, e); },
2015-12-02 12:07:46 +01:00
Ok(n) => {
2016-02-13 22:57:39 +01:00
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() };
self.pinned_nodes.push(n.id.clone());
2016-02-12 09:52:32 +01:00
self.nodes.write().unwrap().add_node(n);
2016-02-29 23:09:51 +01:00
if let Some(ref mut discovery) = *self.discovery.lock().unwrap().deref_mut() {
2016-02-23 19:38:06 +01:00
discovery.add_node(entry);
}
2015-12-02 12:07:46 +01:00
}
2015-11-29 11:50:28 +01:00
}
}
2016-01-21 16:48:37 +01:00
pub fn client_version(&self) -> String {
self.info.read().unwrap().client_version.clone()
}
2016-03-20 11:35:46 +01:00
pub fn external_url(&self) -> Option<String> {
self.info.read().unwrap().public_endpoint.as_ref().map(|e| format!("{}", Node::new(self.info.read().unwrap().id().clone(), e.clone())))
2016-02-23 19:38:06 +01:00
}
2016-03-20 11:35:46 +01:00
pub fn local_url(&self) -> String {
let r = format!("{}", Node::new(self.info.read().unwrap().id().clone(), self.info.read().unwrap().local_endpoint.clone()));
println!("{}", r);
r
}
fn init_public_interface(&self, io: &IoContext<NetworkIoMessage<Message>>) -> Result<(), UtilError> {
2016-02-23 19:38:06 +01:00
io.clear_timer(INIT_PUBLIC).unwrap();
2016-03-20 11:35:46 +01:00
if self.info.read().unwrap().public_endpoint.is_some() {
return Ok(());
2016-02-23 19:38:06 +01:00
}
2016-03-20 11:35:46 +01:00
let local_endpoint = self.info.read().unwrap().local_endpoint.clone();
2016-03-04 22:01:36 +01:00
let public_address = self.info.read().unwrap().config.public_address.clone();
let public_endpoint = match public_address {
2016-02-23 19:38:06 +01:00
None => {
2016-03-20 11:35:46 +01:00
let public_address = select_public_address(local_endpoint.address.port());
let public_endpoint = NodeEndpoint { address: public_address, udp_port: local_endpoint.udp_port };
2016-02-23 19:38:06 +01:00
if self.info.read().unwrap().config.nat_enabled {
match map_external_address(&local_endpoint) {
Some(endpoint) => {
2016-03-20 11:35:46 +01:00
info!("NAT mapped to external address {}", endpoint.address);
2016-02-23 19:38:06 +01:00
endpoint
},
2016-03-20 11:35:46 +01:00
None => public_endpoint
2016-02-23 19:38:06 +01:00
}
} else {
2016-03-20 11:35:46 +01:00
public_endpoint
2016-02-23 19:38:06 +01:00
}
}
2016-03-20 11:35:46 +01:00
Some(addr) => NodeEndpoint { address: addr, udp_port: local_endpoint.udp_port }
2016-02-23 19:38:06 +01:00
};
2016-02-29 23:09:51 +01:00
2016-03-20 11:35:46 +01:00
self.info.write().unwrap().public_endpoint = Some(public_endpoint.clone());
info!("Public node URL: {}", self.external_url().unwrap());
2016-02-23 19:38:06 +01:00
// Initialize discovery.
let discovery = {
let info = self.info.read().unwrap();
if info.config.discovery_enabled && !info.config.pin {
2016-03-20 11:35:46 +01:00
Some(Discovery::new(&info.keys, public_endpoint.address.clone(), public_endpoint, DISCOVERY))
2016-02-23 19:38:06 +01:00
} else { None }
};
if let Some(mut discovery) = discovery {
discovery.init_node_list(self.nodes.read().unwrap().unordered_entries());
for n in self.nodes.read().unwrap().unordered_entries() {
discovery.add_node(n.clone());
}
2016-03-20 11:35:46 +01:00
*self.discovery.lock().unwrap().deref_mut() = Some(discovery);
2016-02-23 19:38:06 +01:00
io.register_stream(DISCOVERY).expect("Error registering UDP listener");
io.register_timer(DISCOVERY_REFRESH, 7200).expect("Error registering discovery timer");
io.register_timer(DISCOVERY_ROUND, 300).expect("Error registering discovery timer");
io.register_timer(NODE_TABLE, 300_000).expect("Error registering node table timer");
2016-02-23 19:38:06 +01:00
}
2016-03-20 11:35:46 +01:00
try!(io.register_stream(TCP_ACCEPT));
Ok(())
2016-01-21 16:48:37 +01:00
}
fn maintain_network(&self, io: &IoContext<NetworkIoMessage<Message>>) {
2016-02-02 20:58:12 +01:00
self.keep_alive(io);
self.connect_peers(io);
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
fn have_session(&self, id: &NodeId) -> bool {
self.sessions.read().unwrap().iter().any(|e| e.lock().unwrap().info.id.eq(&id))
2016-02-14 01:03:48 +01:00
}
fn session_count(&self) -> usize {
self.sessions.read().unwrap().count()
2015-11-29 11:50:28 +01:00
}
fn connecting_to(&self, id: &NodeId) -> bool {
self.handshakes.read().unwrap().iter().any(|e| e.lock().unwrap().id.eq(&id))
2016-02-14 01:03:48 +01:00
}
fn handshake_count(&self) -> usize {
self.handshakes.read().unwrap().count()
2015-11-29 11:50:28 +01:00
}
2016-02-02 20:58:12 +01:00
fn keep_alive(&self, io: &IoContext<NetworkIoMessage<Message>>) {
let mut to_kill = Vec::new();
for e in self.sessions.write().unwrap().iter_mut() {
let mut s = e.lock().unwrap();
if !s.keep_alive(io) {
s.disconnect(DisconnectReason::PingTimeout);
to_kill.push(s.token());
2016-02-02 20:58:12 +01:00
}
}
for p in to_kill {
trace!(target: "network", "Ping timeout: {}", p);
2016-02-14 01:03:48 +01:00
self.kill_connection(p, io, true);
2016-02-02 20:58:12 +01:00
}
}
2016-01-21 16:48:37 +01:00
fn connect_peers(&self, io: &IoContext<NetworkIoMessage<Message>>) {
2016-02-14 01:03:48 +01:00
let ideal_peers = { self.info.read().unwrap().deref().config.ideal_peers };
let pin = { self.info.read().unwrap().deref().config.pin };
let session_count = self.session_count();
if session_count >= ideal_peers as usize {
2016-02-14 01:03:48 +01:00
return;
2015-11-29 11:50:28 +01:00
}
2016-02-14 01:03:48 +01:00
let handshake_count = self.handshake_count();
2016-02-16 02:05:36 +01:00
// allow 16 slots for incoming connections
let handshake_limit = MAX_HANDSHAKES - 16;
if handshake_count >= handshake_limit {
2016-02-14 01:03:48 +01:00
return;
2015-11-29 11:50:28 +01:00
}
let nodes = if pin { self.pinned_nodes.clone() } else { self.nodes.read().unwrap().nodes() };
for id in nodes.iter().filter(|ref id| !self.have_session(id) && !self.connecting_to(id))
2016-02-16 02:05:36 +01:00
.take(min(MAX_HANDSHAKES_PER_ROUND, handshake_limit - handshake_count)) {
2016-02-14 01:03:48 +01:00
self.connect_peer(&id, io);
2015-11-29 11:50:28 +01:00
}
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Connecting peers: {} sessions, {} pending", self.session_count(), self.handshake_count());
2016-01-08 13:49:00 +01:00
}
2015-11-29 11:50:28 +01:00
2016-03-11 11:16:49 +01:00
#[cfg_attr(feature="dev", allow(single_match))]
2016-01-21 16:48:37 +01:00
fn connect_peer(&self, id: &NodeId, io: &IoContext<NetworkIoMessage<Message>>) {
2015-11-29 11:50:28 +01:00
if self.have_session(id)
{
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Aborted connect. Node already connected.");
2015-11-29 11:50:28 +01:00
return;
}
2016-01-21 16:48:37 +01:00
if self.connecting_to(id) {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Aborted connect. Node already connecting.");
2015-11-29 11:50:28 +01:00
return;
}
let socket = {
2016-01-21 16:48:37 +01:00
let address = {
let mut nodes = self.nodes.write().unwrap();
2016-02-14 17:42:03 +01:00
if let Some(node) = nodes.get_mut(id) {
node.last_attempted = Some(::time::now());
node.endpoint.address
}
2016-02-14 17:45:00 +01:00
else {
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Connection to expired node aborted");
2016-02-14 17:45:00 +01:00
return;
}
2016-01-21 16:48:37 +01:00
};
match TcpStream::connect(&address) {
Ok(socket) => socket,
2016-02-16 17:54:34 +01:00
Err(e) => {
debug!(target: "network", "Can't connect to address {:?}: {:?}", address, e);
return;
}
2015-11-29 11:50:28 +01:00
}
};
2016-01-24 18:53:54 +01:00
self.create_connection(socket, Some(id), io);
}
2015-11-29 11:50:28 +01:00
2016-03-11 11:16:49 +01:00
#[cfg_attr(feature="dev", allow(block_in_if_condition_stmt))]
2016-01-24 18:53:54 +01:00
fn create_connection(&self, socket: TcpStream, id: Option<&NodeId>, io: &IoContext<NetworkIoMessage<Message>>) {
2016-01-21 16:48:37 +01:00
let nonce = self.info.write().unwrap().next_nonce();
let mut handshakes = self.handshakes.write().unwrap();
if handshakes.insert_with(|token| {
2016-01-24 18:53:54 +01:00
let mut handshake = Handshake::new(token, id, socket, &nonce, self.stats.clone()).expect("Can't create handshake");
handshake.start(io, &self.info.read().unwrap(), id.is_some()).and_then(|_| io.register_stream(token)).unwrap_or_else (|e| {
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Handshake create error: {:?}", e);
2016-01-21 16:48:37 +01:00
});
Arc::new(Mutex::new(handshake))
2016-01-21 16:48:37 +01:00
}).is_none() {
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Max handshakes reached");
}
}
2015-11-29 11:50:28 +01:00
2016-01-24 18:53:54 +01:00
fn accept(&self, io: &IoContext<NetworkIoMessage<Message>>) {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Accepting incoming connection");
2016-01-24 18:53:54 +01:00
loop {
2016-03-20 11:35:46 +01:00
let socket = match self.tcp_listener.lock().unwrap().accept() {
2016-01-24 18:53:54 +01:00
Ok(None) => break,
Ok(Some((sock, _addr))) => sock,
Err(e) => {
warn!("Error accepting connection: {:?}", e);
break
},
};
self.create_connection(socket, None, io);
}
io.update_registration(TCP_ACCEPT).expect("Error registering TCP listener");
2015-11-29 11:50:28 +01:00
}
fn handshake_writable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
let handshake = { self.handshakes.read().unwrap().get(token).cloned() };
if let Some(handshake) = handshake {
let mut h = handshake.lock().unwrap();
if let Err(e) = h.writable(io, &self.info.read().unwrap()) {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Handshake write error: {}: {:?}", token, e);
2016-01-08 13:55:44 +01:00
}
}
2015-11-29 11:50:28 +01:00
}
2015-12-17 11:42:30 +01:00
fn session_writable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
let session = { self.sessions.read().unwrap().get(token).cloned() };
if let Some(session) = session {
let mut s = session.lock().unwrap();
if let Err(e) = s.writable(io, &self.info.read().unwrap()) {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Session write error: {}: {:?}", token, e);
}
if s.done() {
io.deregister_stream(token).expect("Error deregistering stream");
} else {
io.update_registration(token).unwrap_or_else(|e| debug!(target: "network", "Session registration error: {:?}", e));
}
}
}
2016-01-21 16:48:37 +01:00
fn connection_closed(&self, token: TimerToken, io: &IoContext<NetworkIoMessage<Message>>) {
trace!(target: "network", "Connection closed: {}", token);
2016-02-14 01:03:48 +01:00
self.kill_connection(token, io, true);
2016-01-10 14:02:01 +01:00
}
2015-12-17 11:42:30 +01:00
fn handshake_readable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2015-12-02 12:07:46 +01:00
let mut create_session = false;
2016-01-21 16:48:37 +01:00
let mut kill = false;
let handshake = { self.handshakes.read().unwrap().get(token).cloned() };
if let Some(handshake) = handshake {
let mut h = handshake.lock().unwrap();
if let Err(e) = h.readable(io, &self.info.read().unwrap()) {
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Handshake read error: {}: {:?}", token, e);
kill = true;
}
if h.done() {
create_session = true;
2016-01-08 13:55:44 +01:00
}
}
2015-12-02 12:07:46 +01:00
if kill {
self.kill_connection(token, io, true);
2016-01-13 13:56:48 +01:00
return;
} else if create_session {
self.start_session(token, io);
return;
2016-01-10 14:02:01 +01:00
}
2016-02-20 01:10:27 +01:00
io.update_registration(token).unwrap_or_else(|e| debug!(target: "network", "Token registration error: {:?}", e));
2015-11-29 11:50:28 +01:00
}
2015-12-17 11:42:30 +01:00
fn session_readable(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
2015-12-22 22:23:43 +01:00
let mut ready_data: Vec<ProtocolId> = Vec::new();
let mut packet_data: Option<(ProtocolId, PacketId, Vec<u8>)> = None;
2016-01-21 16:48:37 +01:00
let mut kill = false;
let session = { self.sessions.read().unwrap().get(token).cloned() };
2016-03-05 23:09:51 +01:00
if let Some(session) = session.clone() {
let mut s = session.lock().unwrap();
match s.readable(io, &self.info.read().unwrap()) {
Err(e) => {
trace!(target: "network", "Session read error: {}:{} ({:?}) {:?}", token, s.id(), s.remote_addr(), e);
match e {
UtilError::Network(NetworkError::Disconnect(DisconnectReason::UselessPeer)) |
UtilError::Network(NetworkError::Disconnect(DisconnectReason::IncompatibleProtocol)) => {
self.nodes.write().unwrap().mark_as_useless(s.id());
}
_ => (),
}
kill = true;
},
Ok(SessionData::Ready) => {
for (p, _) in self.handlers.read().unwrap().iter() {
if s.have_capability(p) {
ready_data.push(p);
}
2016-01-21 16:48:37 +01:00
}
},
Ok(SessionData::Packet {
data,
protocol,
packet_id,
}) => {
match self.handlers.read().unwrap().get(protocol) {
2016-02-20 01:10:27 +01:00
None => { warn!(target: "network", "No handler found for protocol: {:?}", protocol) },
Some(_) => packet_data = Some((protocol, packet_id, data)),
2016-01-21 16:48:37 +01:00
}
},
Ok(SessionData::None) => {},
2016-01-08 13:55:44 +01:00
}
}
2015-12-02 12:07:46 +01:00
if kill {
self.kill_connection(token, io, true);
2015-12-02 12:07:46 +01:00
}
2015-12-22 22:23:43 +01:00
for p in ready_data {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
2016-03-05 23:09:51 +01:00
h.connected(&NetworkContext::new(io, p, session.clone(), self.sessions.clone()), &token);
2015-12-22 22:23:43 +01:00
}
if let Some((p, packet_id, data)) = packet_data {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
2016-03-05 23:09:51 +01:00
h.read(&NetworkContext::new(io, p, session.clone(), self.sessions.clone()), &token, packet_id, &data[1..]);
2016-01-10 14:02:01 +01:00
}
2016-02-20 01:10:27 +01:00
io.update_registration(token).unwrap_or_else(|e| debug!(target: "network", "Token registration error: {:?}", e));
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
fn start_session(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
let mut handshakes = self.handshakes.write().unwrap();
if handshakes.get(token).is_none() {
return;
}
// turn a handshake into a session
let mut sessions = self.sessions.write().unwrap();
let mut h = handshakes.get_mut(token).unwrap().lock().unwrap();
2016-02-20 01:10:27 +01:00
if h.expired {
return;
2016-02-14 11:54:08 +01:00
}
2016-03-14 13:54:06 +01:00
io.deregister_stream(token).expect("Error deleting handshake registration");
h.set_expired();
2016-02-15 19:54:27 +01:00
let originated = h.originated;
let mut session = match Session::new(&mut h, &self.info.read().unwrap()) {
2016-02-14 12:11:18 +01:00
Ok(s) => s,
Err(e) => {
2016-02-20 01:10:27 +01:00
debug!(target: "network", "Session creation error: {:?}", e);
2016-02-14 12:11:18 +01:00
return;
}
};
2016-03-12 19:52:37 +01:00
if !originated {
let session_count = sessions.count();
let ideal_peers = { self.info.read().unwrap().deref().config.ideal_peers };
if session_count >= ideal_peers as usize {
session.disconnect(DisconnectReason::TooManyPeers);
return;
}
}
let result = sessions.insert_with(move |session_token| {
2016-02-14 12:11:18 +01:00
session.set_token(session_token);
io.register_stream(session_token).expect("Error creating session registration");
self.stats.inc_sessions();
trace!(target: "network", "Creating session {} -> {}:{} ({:?})", token, session_token, session.id(), session.remote_addr());
2016-02-15 19:54:27 +01:00
if !originated {
// Add it no node table
if let Ok(address) = session.remote_addr() {
let entry = NodeEntry { id: session.id().clone(), endpoint: NodeEndpoint { address: address, udp_port: address.port() } };
self.nodes.write().unwrap().add_node(Node::new(entry.id.clone(), entry.endpoint.clone()));
2016-02-23 19:38:06 +01:00
let mut discovery = self.discovery.lock().unwrap();
2016-02-29 23:09:51 +01:00
if let Some(ref mut discovery) = *discovery.deref_mut() {
2016-02-23 19:38:06 +01:00
discovery.add_node(entry);
}
2016-02-15 19:54:27 +01:00
}
2015-12-02 12:07:46 +01:00
}
Arc::new(Mutex::new(session))
});
if result.is_none() {
warn!("Max sessions reached");
2016-02-14 02:11:55 +01:00
}
2015-11-29 11:50:28 +01:00
}
2016-01-21 16:48:37 +01:00
fn connection_timeout(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>) {
trace!(target: "network", "Connection timeout: {}", token);
2016-02-14 01:03:48 +01:00
self.kill_connection(token, io, true)
2015-12-02 12:07:46 +01:00
}
2016-01-08 13:55:44 +01:00
2016-02-14 01:03:48 +01:00
fn kill_connection(&self, token: StreamToken, io: &IoContext<NetworkIoMessage<Message>>, remote: bool) {
2016-01-10 14:02:01 +01:00
let mut to_disconnect: Vec<ProtocolId> = Vec::new();
2016-02-14 02:11:55 +01:00
let mut failure_id = None;
let mut deregister = false;
2016-03-05 23:09:51 +01:00
let mut expired_session = None;
match token {
FIRST_HANDSHAKE ... LAST_HANDSHAKE => {
let handshakes = self.handshakes.write().unwrap();
if let Some(handshake) = handshakes.get(token).cloned() {
2016-02-20 01:10:27 +01:00
let mut handshake = handshake.lock().unwrap();
if !handshake.expired() {
handshake.set_expired();
failure_id = Some(handshake.id().clone());
deregister = true;
2016-02-20 01:10:27 +01:00
}
}
},
FIRST_SESSION ... LAST_SESSION => {
let sessions = self.sessions.write().unwrap();
if let Some(session) = sessions.get(token).cloned() {
2016-03-05 23:09:51 +01:00
expired_session = Some(session.clone());
2016-02-20 01:10:27 +01:00
let mut s = session.lock().unwrap();
if !s.expired() {
if s.is_ready() {
for (p, _) in self.handlers.read().unwrap().iter() {
if s.have_capability(p) {
to_disconnect.push(p);
}
2016-01-21 16:48:37 +01:00
}
}
2016-02-20 01:10:27 +01:00
s.set_expired();
failure_id = Some(s.id().clone());
}
deregister = remote || s.done();
2016-01-10 14:02:01 +01:00
}
},
_ => {},
2016-01-10 14:02:01 +01:00
}
2016-02-14 02:11:55 +01:00
if let Some(id) = failure_id {
if remote {
self.nodes.write().unwrap().note_failure(&id);
2016-01-21 16:48:37 +01:00
}
2016-01-10 14:02:01 +01:00
}
for p in to_disconnect {
2016-01-21 16:48:37 +01:00
let h = self.handlers.read().unwrap().get(p).unwrap().clone();
2016-03-05 23:09:51 +01:00
h.disconnected(&NetworkContext::new(io, p, expired_session.clone(), self.sessions.clone()), &token);
2016-01-15 00:50:48 +01:00
}
if deregister {
io.deregister_stream(token).expect("Error deregistering stream");
} else if expired_session.is_some() {
io.update_registration(token).unwrap_or_else(|e| debug!(target: "network", "Connection registration error: {:?}", e));
}
2015-11-29 11:50:28 +01:00
}
2016-02-12 09:52:32 +01:00
fn update_nodes(&self, io: &IoContext<NetworkIoMessage<Message>>, node_changes: TableUpdates) {
let mut to_remove: Vec<PeerId> = Vec::new();
2016-02-14 02:11:55 +01:00
{
{
let handshakes = self.handshakes.write().unwrap();
for c in handshakes.iter() {
let h = c.lock().unwrap();
if node_changes.removed.contains(&h.id()) {
to_remove.push(h.token());
2016-02-12 09:52:32 +01:00
}
}
}
{
let sessions = self.sessions.write().unwrap();
for c in sessions.iter() {
let s = c.lock().unwrap();
if node_changes.removed.contains(&s.id()) {
to_remove.push(s.token());
2016-02-12 09:52:32 +01:00
}
}
}
2016-01-15 00:50:48 +01:00
}
2016-02-12 09:52:32 +01:00
for i in to_remove {
trace!(target: "network", "Removed from node table: {}", i);
2016-02-14 01:03:48 +01:00
self.kill_connection(i, io, false);
2016-02-12 09:52:32 +01:00
}
self.nodes.write().unwrap().update(node_changes);
2015-11-29 11:50:28 +01:00
}
2016-01-08 13:55:44 +01:00
}
2015-11-29 11:50:28 +01:00
2016-01-21 16:48:37 +01:00
impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Message: Send + Sync + Clone + 'static {
/// Initialize networking
2016-01-21 16:48:37 +01:00
fn initialize(&self, io: &IoContext<NetworkIoMessage<Message>>) {
io.register_timer(IDLE, MAINTENANCE_TIMEOUT).expect("Error registering Network idle timer");
2016-02-23 19:38:06 +01:00
io.register_timer(INIT_PUBLIC, 0).expect("Error registering initialization timer");
2016-02-19 16:34:31 +01:00
self.maintain_network(io)
}
2016-01-21 16:48:37 +01:00
fn stream_hup(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
2016-02-20 01:10:27 +01:00
trace!(target: "network", "Hup: {}", stream);
match stream {
FIRST_SESSION ... LAST_SESSION => self.connection_closed(stream, io),
FIRST_HANDSHAKE ... LAST_HANDSHAKE => self.connection_closed(stream, io),
2016-02-20 01:10:27 +01:00
_ => warn!(target: "network", "Unexpected hup"),
};
}
2016-01-21 16:48:37 +01:00
fn stream_readable(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
match stream {
FIRST_SESSION ... LAST_SESSION => self.session_readable(stream, io),
FIRST_HANDSHAKE ... LAST_HANDSHAKE => self.handshake_readable(stream, io),
2016-02-12 09:52:32 +01:00
DISCOVERY => {
2016-02-23 19:38:06 +01:00
let node_changes = { self.discovery.lock().unwrap().as_mut().unwrap().readable() };
2016-02-21 13:58:01 +01:00
if let Some(node_changes) = node_changes {
2016-02-12 09:52:32 +01:00
self.update_nodes(io, node_changes);
}
2016-02-16 23:33:32 +01:00
io.update_registration(DISCOVERY).expect("Error updating discovery registration");
2016-02-12 09:52:32 +01:00
},
TCP_ACCEPT => self.accept(io),
_ => panic!("Received unknown readable token"),
2016-01-08 13:55:44 +01:00
}
}
2016-01-21 16:48:37 +01:00
fn stream_writable(&self, io: &IoContext<NetworkIoMessage<Message>>, stream: StreamToken) {
match stream {
FIRST_SESSION ... LAST_SESSION => self.session_writable(stream, io),
FIRST_HANDSHAKE ... LAST_HANDSHAKE => self.handshake_writable(stream, io),
2016-02-13 22:57:39 +01:00
DISCOVERY => {
2016-02-23 19:38:06 +01:00
self.discovery.lock().unwrap().as_mut().unwrap().writable();
2016-02-16 23:33:32 +01:00
io.update_registration(DISCOVERY).expect("Error updating discovery registration");
2016-02-13 22:57:39 +01:00
}
_ => panic!("Received unknown writable token"),
2015-11-29 11:50:28 +01:00
}
2016-01-08 13:55:44 +01:00
}
2016-01-08 13:49:00 +01:00
2016-01-21 16:48:37 +01:00
fn timeout(&self, io: &IoContext<NetworkIoMessage<Message>>, token: TimerToken) {
match token {
IDLE => self.maintain_network(io),
2016-03-20 11:35:46 +01:00
INIT_PUBLIC => self.init_public_interface(io).unwrap_or_else(|e|
warn!("Error initializing public interface: {:?}", e)),
FIRST_SESSION ... LAST_SESSION => self.connection_timeout(token, io),
FIRST_HANDSHAKE ... LAST_HANDSHAKE => self.connection_timeout(token, io),
2016-02-12 09:52:32 +01:00
DISCOVERY_REFRESH => {
2016-02-23 19:38:06 +01:00
self.discovery.lock().unwrap().as_mut().unwrap().refresh();
2016-02-16 23:33:32 +01:00
io.update_registration(DISCOVERY).expect("Error updating discovery registration");
2016-02-12 09:52:32 +01:00
},
DISCOVERY_ROUND => {
2016-02-23 19:38:06 +01:00
let node_changes = { self.discovery.lock().unwrap().as_mut().unwrap().round() };
2016-02-21 13:58:01 +01:00
if let Some(node_changes) = node_changes {
2016-02-13 22:57:39 +01:00
self.update_nodes(io, node_changes);
}
2016-02-16 23:33:32 +01:00
io.update_registration(DISCOVERY).expect("Error updating discovery registration");
2016-02-12 09:52:32 +01:00
},
NODE_TABLE => {
self.nodes.write().unwrap().clear_useless();
},
_ => match self.timers.read().unwrap().get(&token).cloned() {
Some(timer) => match self.handlers.read().unwrap().get(timer.protocol).cloned() {
2016-02-20 01:10:27 +01:00
None => { warn!(target: "network", "No handler found for protocol: {:?}", timer.protocol) },
Some(h) => { h.timeout(&NetworkContext::new(io, timer.protocol, None, self.sessions.clone()), timer.token); }
2016-01-21 16:48:37 +01:00
},
None => { warn!("Unknown timer token: {}", token); } // timer is not registerd through us
2015-12-17 11:42:30 +01:00
}
}
2016-01-08 13:55:44 +01:00
}
2015-12-17 11:42:30 +01:00
2016-01-21 16:48:37 +01:00
fn message(&self, io: &IoContext<NetworkIoMessage<Message>>, message: &NetworkIoMessage<Message>) {
2016-01-19 12:14:29 +01:00
match *message {
NetworkIoMessage::AddHandler {
2016-01-21 16:48:37 +01:00
ref handler,
ref protocol,
ref versions
2016-01-08 13:55:44 +01:00
} => {
2016-01-21 16:48:37 +01:00
let h = handler.clone();
h.initialize(&NetworkContext::new(io, protocol, None, self.sessions.clone()));
2016-01-21 16:48:37 +01:00
self.handlers.write().unwrap().insert(protocol, h);
let mut info = self.info.write().unwrap();
2016-01-08 13:55:44 +01:00
for v in versions {
2016-01-21 16:48:37 +01:00
info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 });
2016-01-08 13:55:44 +01:00
}
},
NetworkIoMessage::AddTimer {
2016-01-21 16:48:37 +01:00
ref protocol,
ref delay,
ref token,
} => {
let handler_token = {
let mut timer_counter = self.timer_counter.write().unwrap();
let counter = timer_counter.deref_mut();
let handler_token = *counter;
*counter += 1;
handler_token
};
self.timers.write().unwrap().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token });
io.register_timer(handler_token, *delay).expect("Error registering timer");
},
2016-02-02 21:10:16 +01:00
NetworkIoMessage::Disconnect(ref peer) => {
let session = { self.sessions.read().unwrap().get(*peer).cloned() };
if let Some(session) = session {
session.lock().unwrap().disconnect(DisconnectReason::DisconnectRequested);
}
trace!(target: "network", "Disconnect requested {}", peer);
self.kill_connection(*peer, io, false);
},
NetworkIoMessage::DisablePeer(ref peer) => {
let session = { self.sessions.read().unwrap().get(*peer).cloned() };
if let Some(session) = session {
session.lock().unwrap().disconnect(DisconnectReason::DisconnectRequested);
self.nodes.write().unwrap().mark_as_useless(session.lock().unwrap().id());
}
trace!(target: "network", "Disabling peer {}", peer);
2016-02-14 01:03:48 +01:00
self.kill_connection(*peer, io, false);
2016-02-02 14:54:46 +01:00
},
2016-01-19 12:14:29 +01:00
NetworkIoMessage::User(ref message) => {
2016-01-21 16:48:37 +01:00
for (p, h) in self.handlers.read().unwrap().iter() {
h.message(&NetworkContext::new(io, p, None, self.sessions.clone()), &message);
2015-12-28 11:41:51 +01:00
}
}
2015-11-29 11:50:28 +01:00
}
}
2016-01-21 16:48:37 +01:00
fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_SESSION ... LAST_SESSION => {
let session = { self.sessions.read().unwrap().get(stream).cloned() };
if let Some(session) = session {
session.lock().unwrap().register_socket(reg, event_loop).expect("Error registering socket");
}
2016-01-21 16:48:37 +01:00
}
FIRST_HANDSHAKE ... LAST_HANDSHAKE => {
let connection = { self.handshakes.read().unwrap().get(stream).cloned() };
2016-02-14 02:11:55 +01:00
if let Some(connection) = connection {
connection.lock().unwrap().register_socket(reg, event_loop).expect("Error registering socket");
}
2016-01-21 16:48:37 +01:00
}
2016-02-23 19:38:06 +01:00
DISCOVERY => self.discovery.lock().unwrap().as_ref().unwrap().register_socket(event_loop).expect("Error registering discovery socket"),
2016-03-20 11:35:46 +01:00
TCP_ACCEPT => event_loop.register(self.tcp_listener.lock().unwrap().deref(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error registering stream"),
2016-01-21 23:33:52 +01:00
_ => warn!("Unexpected stream registration")
2016-01-21 16:48:37 +01:00
}
}
2016-01-22 18:13:59 +01:00
fn deregister_stream(&self, stream: StreamToken, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_SESSION ... LAST_SESSION => {
let mut connections = self.sessions.write().unwrap();
2016-01-22 18:13:59 +01:00
if let Some(connection) = connections.get(stream).cloned() {
connection.lock().unwrap().deregister_socket(event_loop).expect("Error deregistering socket");
2016-01-22 18:13:59 +01:00
connections.remove(stream);
}
}
FIRST_HANDSHAKE ... LAST_HANDSHAKE => {
let mut connections = self.handshakes.write().unwrap();
if let Some(connection) = connections.get(stream).cloned() {
connection.lock().unwrap().deregister_socket(event_loop).expect("Error deregistering socket");
connections.remove(stream);
}
}
2016-02-12 09:52:32 +01:00
DISCOVERY => (),
2016-01-22 18:13:59 +01:00
_ => warn!("Unexpected stream deregistration")
}
}
2016-01-21 16:48:37 +01:00
fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage<Message>>>) {
match stream {
FIRST_SESSION ... LAST_SESSION => {
let connection = { self.sessions.read().unwrap().get(stream).cloned() };
if let Some(connection) = connection {
connection.lock().unwrap().update_socket(reg, event_loop).expect("Error updating socket");
}
}
FIRST_HANDSHAKE ... LAST_HANDSHAKE => {
let connection = { self.handshakes.read().unwrap().get(stream).cloned() };
if let Some(connection) = connection {
connection.lock().unwrap().update_socket(reg, event_loop).expect("Error updating socket");
}
2016-01-21 16:48:37 +01:00
}
2016-02-23 19:38:06 +01:00
DISCOVERY => self.discovery.lock().unwrap().as_ref().unwrap().update_registration(event_loop).expect("Error reregistering discovery socket"),
2016-03-20 11:35:46 +01:00
TCP_ACCEPT => event_loop.reregister(self.tcp_listener.lock().unwrap().deref(), Token(TCP_ACCEPT), EventSet::all(), PollOpt::edge()).expect("Error reregistering stream"),
2016-01-21 16:48:37 +01:00
_ => warn!("Unexpected stream update")
}
}
2016-01-08 13:55:44 +01:00
}
2016-02-15 18:36:34 +01:00
fn save_key(path: &Path, key: &Secret) {
let mut path_buf = PathBuf::from(path);
if let Err(e) = fs::create_dir_all(path_buf.as_path()) {
warn!("Error creating key directory: {:?}", e);
return;
};
path_buf.push("key");
let mut file = match fs::File::create(path_buf.as_path()) {
Ok(file) => file,
Err(e) => {
warn!("Error creating key file: {:?}", e);
return;
}
};
if let Err(e) = file.write(&key.hex().into_bytes()) {
warn!("Error writing key file: {:?}", e);
}
}
fn load_key(path: &Path) -> Option<Secret> {
let mut path_buf = PathBuf::from(path);
path_buf.push("key");
let mut file = match fs::File::open(path_buf.as_path()) {
Ok(file) => file,
Err(e) => {
debug!("Error opening key file: {:?}", e);
return None;
}
};
let mut buf = String::new();
match file.read_to_string(&mut buf) {
Ok(_) => {},
Err(e) => {
2016-02-15 18:36:34 +01:00
warn!("Error reading key file: {:?}", e);
return None;
}
}
match Secret::from_str(&buf) {
Ok(key) => Some(key),
Err(e) => {
2016-02-15 18:36:34 +01:00
warn!("Error parsing key file: {:?}", e);
None
}
}
}
2016-02-16 21:25:01 +01:00
#[test]
fn key_save_load() {
use ::devtools::RandomTempPath;
2016-02-16 21:25:01 +01:00
let temp_path = RandomTempPath::create_dir();
let key = H256::random();
save_key(temp_path.as_path(), &key);
let r = load_key(temp_path.as_path());
assert_eq!(key, r.unwrap());
}
#[test]
fn host_client_url() {
let mut config = NetworkConfiguration::new();
let key = h256_from_hex("6f7b0d801bc7b5ce7bbd930b84fd0369b3eb25d09be58d64ba811091046f3aa2");
config.use_secret = Some(key);
2016-03-20 11:35:46 +01:00
let host: Host<u32> = Host::new(config).unwrap();
assert!(host.local_url().starts_with("enode://101b3ef5a4ea7a1c7928e24c4c75fd053c235d7b80c22ae5c03d145d0ac7396e2a4ffff9adee3133a7b05044a5cee08115fd65145e5165d646bde371010d803c@"));
}