2016-01-13 11:31:37 +01:00
|
|
|
use std::mem;
|
2016-01-13 13:56:48 +01:00
|
|
|
use std::net::{SocketAddr};
|
2015-12-03 15:11:40 +01:00
|
|
|
use std::collections::{HashMap};
|
2016-01-13 11:31:37 +01:00
|
|
|
use std::hash::{Hasher};
|
2015-11-29 11:50:28 +01:00
|
|
|
use std::str::{FromStr};
|
|
|
|
use mio::*;
|
|
|
|
use mio::tcp::*;
|
|
|
|
use mio::udp::*;
|
|
|
|
use hash::*;
|
2015-11-30 16:38:55 +01:00
|
|
|
use crypto::*;
|
2016-01-09 10:27:41 +01:00
|
|
|
use sha3::Hashable;
|
2015-12-02 20:11:13 +01:00
|
|
|
use rlp::*;
|
2015-11-30 16:38:55 +01:00
|
|
|
use network::handshake::Handshake;
|
2015-12-17 11:42:30 +01:00
|
|
|
use network::session::{Session, SessionData};
|
2016-01-10 12:53:55 +01:00
|
|
|
use error::*;
|
2016-01-13 11:31:37 +01:00
|
|
|
use io::*;
|
|
|
|
use network::NetworkProtocolHandler;
|
|
|
|
use network::node::*;
|
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;
|
2015-11-29 11:50:28 +01:00
|
|
|
|
|
|
|
const MAX_CONNECTIONS: usize = 1024;
|
2016-01-08 13:49:00 +01:00
|
|
|
const IDEAL_PEERS: u32 = 10;
|
2015-11-29 11:50:28 +01:00
|
|
|
|
2016-01-14 16:52:10 +01:00
|
|
|
const MAINTENANCE_TIMEOUT: u64 = 1000;
|
|
|
|
|
2015-11-29 11:50:28 +01:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct NetworkConfiguration {
|
2016-01-08 13:49:00 +01:00
|
|
|
listen_address: SocketAddr,
|
|
|
|
public_address: SocketAddr,
|
|
|
|
nat_enabled: bool,
|
|
|
|
discovery_enabled: bool,
|
|
|
|
pin: bool,
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl NetworkConfiguration {
|
2016-01-08 13:49:00 +01:00
|
|
|
fn new() -> NetworkConfiguration {
|
|
|
|
NetworkConfiguration {
|
|
|
|
listen_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
|
|
|
public_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
|
|
|
nat_enabled: true,
|
|
|
|
discovery_enabled: true,
|
|
|
|
pin: false,
|
|
|
|
}
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Tokens
|
2016-01-13 15:08:36 +01:00
|
|
|
//const TOKEN_BEGIN: usize = USER_TOKEN_START; // TODO: ICE in rustc 1.7.0-nightly (49c382779 2016-01-12)
|
|
|
|
const TOKEN_BEGIN: usize = 32;
|
|
|
|
const TCP_ACCEPT: usize = TOKEN_BEGIN + 1;
|
|
|
|
const IDLE: usize = TOKEN_BEGIN + 2;
|
|
|
|
const NODETABLE_RECEIVE: usize = TOKEN_BEGIN + 3;
|
|
|
|
const NODETABLE_MAINTAIN: usize = TOKEN_BEGIN + 4;
|
|
|
|
const NODETABLE_DISCOVERY: usize = TOKEN_BEGIN + 5;
|
2016-01-13 11:31:37 +01:00
|
|
|
const FIRST_CONNECTION: usize = TOKEN_BEGIN + 16;
|
2015-11-29 11:50:28 +01:00
|
|
|
const LAST_CONNECTION: usize = FIRST_CONNECTION + MAX_CONNECTIONS - 1;
|
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-13 11:31:37 +01:00
|
|
|
pub enum NetworkIoMessage<Message> where Message: Send {
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Register a new protocol handler.
|
2015-12-17 11:42:30 +01:00
|
|
|
AddHandler {
|
2016-01-13 11:31:37 +01:00
|
|
|
handler: Option<Box<NetworkProtocolHandler<Message>+Send>>,
|
2015-12-17 11:42:30 +01:00
|
|
|
protocol: ProtocolId,
|
|
|
|
versions: Vec<u8>,
|
|
|
|
},
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Send data over the network.
|
2015-12-17 11:42:30 +01:00
|
|
|
Send {
|
|
|
|
peer: PeerId,
|
|
|
|
packet_id: PacketId,
|
|
|
|
protocol: ProtocolId,
|
|
|
|
data: Vec<u8>,
|
|
|
|
},
|
2016-01-13 11:31:37 +01:00
|
|
|
/// 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 {
|
|
|
|
fn encode<E>(&self, encoder: &mut E) -> () where E: Encoder {
|
2015-12-03 15:11:40 +01:00
|
|
|
encoder.emit_list(|e| {
|
2015-12-02 20:11:13 +01:00
|
|
|
self.protocol.encode(e);
|
2015-12-17 11:42:30 +01:00
|
|
|
(self.version as u32).encode(e);
|
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-13 13:56:48 +01:00
|
|
|
pub struct NetworkContext<'s, 'io, Message> where Message: Send + 'static, 'io: 's {
|
|
|
|
io: &'s mut IoContext<'io, NetworkIoMessage<Message>>,
|
|
|
|
protocol: ProtocolId,
|
2016-01-08 13:49:00 +01:00
|
|
|
connections: &'s mut Slab<ConnectionEntry>,
|
2016-01-13 11:31:37 +01:00
|
|
|
timers: &'s mut HashMap<TimerToken, ProtocolId>,
|
|
|
|
session: Option<StreamToken>,
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
impl<'s, 'io, Message> NetworkContext<'s, 'io, Message> where Message: Send + 'static, {
|
2016-01-13 11:31:37 +01:00
|
|
|
/// Create a new network IO access point. Takes references to all the data that can be updated within the IO handler.
|
2016-01-13 13:56:48 +01:00
|
|
|
fn new(io: &'s mut IoContext<'io, NetworkIoMessage<Message>>,
|
|
|
|
protocol: ProtocolId,
|
2016-01-13 11:31:37 +01:00
|
|
|
session: Option<StreamToken>, connections: &'s mut Slab<ConnectionEntry>,
|
2016-01-13 13:56:48 +01:00
|
|
|
timers: &'s mut HashMap<TimerToken, ProtocolId>) -> NetworkContext<'s, 'io, Message> {
|
2016-01-13 11:31:37 +01:00
|
|
|
NetworkContext {
|
|
|
|
io: io,
|
2015-12-17 11:42:30 +01:00
|
|
|
protocol: protocol,
|
|
|
|
session: session,
|
2015-12-22 22:23:43 +01:00
|
|
|
connections: connections,
|
|
|
|
timers: timers,
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-30 12:23:36 +01:00
|
|
|
/// Send a packet over the network to another peer.
|
2016-01-10 12:53:55 +01:00
|
|
|
pub fn send(&mut self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(peer) {
|
2015-12-22 22:23:43 +01:00
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 13:56:48 +01:00
|
|
|
s.send_packet(self.protocol, packet_id as u8, &data).unwrap_or_else(|e| {
|
2015-12-22 22:23:43 +01:00
|
|
|
warn!(target: "net", "Send error: {:?}", e);
|
|
|
|
}); //TODO: don't copy vector data
|
|
|
|
},
|
|
|
|
_ => {
|
|
|
|
warn!(target: "net", "Send: Peer does not exist");
|
|
|
|
}
|
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2015-12-30 12:23:36 +01:00
|
|
|
/// Respond to a current network message. Panics if no there is no packet in the context.
|
2016-01-10 12:53:55 +01:00
|
|
|
pub fn respond(&mut self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
|
2015-12-22 22:23:43 +01:00
|
|
|
match self.session {
|
2016-01-13 11:31:37 +01:00
|
|
|
Some(session) => self.send(session, packet_id, data),
|
2015-12-17 11:42:30 +01:00
|
|
|
None => {
|
|
|
|
panic!("Respond: Session does not exist")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-30 12:23:36 +01:00
|
|
|
/// Disable current protocol capability for given peer. If no capabilities left peer gets disconnected.
|
2015-12-22 22:23:43 +01:00
|
|
|
pub fn disable_peer(&mut self, _peer: PeerId) {
|
|
|
|
//TODO: remove capability, disconnect if no capabilities left
|
2015-12-02 20:11:13 +01:00
|
|
|
}
|
2015-12-28 11:41:51 +01:00
|
|
|
|
2016-01-13 11:31:37 +01:00
|
|
|
/// Register a new IO timer. Returns a new timer token. 'NetworkProtocolHandler::timeout' will be called with the token.
|
|
|
|
pub fn register_timer(&mut self, ms: u64) -> Result<TimerToken, UtilError>{
|
|
|
|
match self.io.register_timer(ms) {
|
|
|
|
Ok(token) => {
|
2016-01-13 13:56:48 +01:00
|
|
|
self.timers.insert(token, self.protocol);
|
2016-01-13 11:31:37 +01:00
|
|
|
Ok(token)
|
|
|
|
},
|
2016-01-15 16:19:21 +01:00
|
|
|
e => e,
|
2016-01-13 11:31:37 +01:00
|
|
|
}
|
|
|
|
}
|
2016-01-14 16:52:10 +01:00
|
|
|
|
|
|
|
/// Returns peer identification string
|
|
|
|
pub fn peer_info(&self, peer: PeerId) -> String {
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get(peer) {
|
2016-01-14 16:52:10 +01:00
|
|
|
Some(&ConnectionEntry::Session(ref s)) => {
|
|
|
|
s.info.client_version.clone()
|
|
|
|
},
|
|
|
|
_ => {
|
|
|
|
"unknown".to_string()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Shared host information
|
2015-11-30 16:38:55 +01:00
|
|
|
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
|
|
|
/// TCP connection port.
|
2015-12-02 20:11:13 +01:00
|
|
|
pub listen_port: u16,
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Registered capabilities (handlers)
|
2015-12-02 20:11:13 +01:00
|
|
|
pub capabilities: Vec<CapabilityInfo>
|
2015-11-30 16:38:55 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl HostInfo {
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Returns public key
|
2015-11-30 16:38:55 +01:00
|
|
|
pub fn id(&self) -> &NodeId {
|
|
|
|
self.keys.public()
|
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Returns secret key
|
2015-11-30 16:38:55 +01:00
|
|
|
pub fn secret(&self) -> &Secret {
|
|
|
|
self.keys.secret()
|
|
|
|
}
|
2016-01-10 22:42:27 +01:00
|
|
|
|
|
|
|
/// Increments and returns connection nonce.
|
2015-11-30 16:38:55 +01:00
|
|
|
pub fn next_nonce(&mut self) -> H256 {
|
|
|
|
self.nonce = self.nonce.sha3();
|
|
|
|
return self.nonce.clone();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-12-02 12:07:46 +01:00
|
|
|
enum ConnectionEntry {
|
|
|
|
Handshake(Handshake),
|
|
|
|
Session(Session)
|
|
|
|
}
|
|
|
|
|
2016-01-10 22:42:27 +01:00
|
|
|
/// Root IO handler. Manages protocol handlers, IO timers and network connections.
|
2016-01-13 11:31:37 +01:00
|
|
|
pub struct Host<Message> where Message: Send {
|
2016-01-14 19:04:13 +01:00
|
|
|
pub info: HostInfo,
|
2016-01-13 11:31:37 +01:00
|
|
|
udp_socket: UdpSocket,
|
|
|
|
listener: TcpListener,
|
2016-01-08 13:49:00 +01:00
|
|
|
connections: Slab<ConnectionEntry>,
|
2016-01-13 11:31:37 +01:00
|
|
|
timers: HashMap<TimerToken, ProtocolId>,
|
2015-11-29 11:50:28 +01:00
|
|
|
nodes: HashMap<NodeId, Node>,
|
2016-01-13 11:31:37 +01:00
|
|
|
handlers: HashMap<ProtocolId, Box<NetworkProtocolHandler<Message>>>,
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 11:31:37 +01:00
|
|
|
impl<Message> Host<Message> where Message: Send {
|
|
|
|
pub fn new() -> Host<Message> {
|
2016-01-08 13:49:00 +01:00
|
|
|
let config = NetworkConfiguration::new();
|
|
|
|
let addr = config.listen_address;
|
|
|
|
// Setup the server socket
|
|
|
|
let listener = TcpListener::bind(&addr).unwrap();
|
|
|
|
let udp_socket = UdpSocket::bound(&addr).unwrap();
|
2016-01-13 11:31:37 +01:00
|
|
|
Host::<Message> {
|
2015-12-03 15:11:40 +01:00
|
|
|
info: HostInfo {
|
2015-11-30 16:38:55 +01:00
|
|
|
keys: KeyPair::create().unwrap(),
|
|
|
|
config: config,
|
2015-12-02 20:11:13 +01:00
|
|
|
nonce: H256::random(),
|
|
|
|
protocol_version: 4,
|
|
|
|
client_version: "parity".to_string(),
|
2016-01-13 11:31:37 +01:00
|
|
|
listen_port: 0,
|
2015-12-17 11:42:30 +01:00
|
|
|
capabilities: Vec::new(),
|
2015-11-30 16:38:55 +01:00
|
|
|
},
|
2016-01-13 11:31:37 +01:00
|
|
|
udp_socket: udp_socket,
|
|
|
|
listener: listener,
|
2016-01-15 00:50:48 +01:00
|
|
|
connections: Slab::new_starting_at(FIRST_CONNECTION, MAX_CONNECTIONS),
|
2016-01-13 11:31:37 +01:00
|
|
|
timers: HashMap::new(),
|
2015-11-29 11:50:28 +01:00
|
|
|
nodes: HashMap::new(),
|
2015-12-17 11:42:30 +01:00
|
|
|
handlers: HashMap::new(),
|
2016-01-13 11:31:37 +01:00
|
|
|
}
|
2016-01-08 13:49:00 +01:00
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
|
|
|
|
fn add_node(&mut self, id: &str) {
|
|
|
|
match Node::from_str(id) {
|
|
|
|
Err(e) => { warn!("Could not add node: {:?}", e); },
|
2015-12-02 12:07:46 +01:00
|
|
|
Ok(n) => {
|
2015-12-03 15:11:40 +01:00
|
|
|
self.nodes.insert(n.id.clone(), n);
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn maintain_network(&mut self, io: &mut IoContext<NetworkIoMessage<Message>>) {
|
2016-01-13 11:31:37 +01:00
|
|
|
self.connect_peers(io);
|
2016-01-14 16:52:10 +01:00
|
|
|
io.event_loop.timeout_ms(Token(IDLE), MAINTENANCE_TIMEOUT).unwrap();
|
2016-01-08 13:49:00 +01:00
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
|
|
|
|
fn have_session(&self, id: &NodeId) -> bool {
|
2015-12-02 20:11:13 +01:00
|
|
|
self.connections.iter().any(|e| match e { &ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn connecting_to(&self, id: &NodeId) -> bool {
|
2015-12-02 12:07:46 +01:00
|
|
|
self.connections.iter().any(|e| match e { &ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn connect_peers(&mut self, io: &mut IoContext<NetworkIoMessage<Message>>) {
|
2015-11-29 11:50:28 +01:00
|
|
|
struct NodeInfo {
|
|
|
|
id: NodeId,
|
|
|
|
peer_type: PeerType
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut to_connect: Vec<NodeInfo> = Vec::new();
|
|
|
|
|
|
|
|
let mut req_conn = 0;
|
2015-12-03 15:11:40 +01:00
|
|
|
//TODO: use nodes from discovery here
|
|
|
|
//for n in self.node_buckets.iter().flat_map(|n| &n.nodes).map(|id| NodeInfo { id: id.clone(), peer_type: self.nodes.get(id).unwrap().peer_type}) {
|
|
|
|
for n in self.nodes.values().map(|n| NodeInfo { id: n.id.clone(), peer_type: n.peer_type }) {
|
2015-11-29 11:50:28 +01:00
|
|
|
let connected = self.have_session(&n.id) || self.connecting_to(&n.id);
|
|
|
|
let required = n.peer_type == PeerType::Required;
|
|
|
|
if connected && required {
|
|
|
|
req_conn += 1;
|
|
|
|
}
|
2015-11-30 16:38:55 +01:00
|
|
|
else if !connected && (!self.info.config.pin || required) {
|
2015-11-29 11:50:28 +01:00
|
|
|
to_connect.push(n);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for n in to_connect.iter() {
|
|
|
|
if n.peer_type == PeerType::Required {
|
|
|
|
if req_conn < IDEAL_PEERS {
|
2016-01-13 13:56:48 +01:00
|
|
|
self.connect_peer(&n.id, io);
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
req_conn += 1;
|
|
|
|
}
|
|
|
|
}
|
2015-12-03 15:11:40 +01:00
|
|
|
|
2015-11-30 16:38:55 +01:00
|
|
|
if !self.info.config.pin
|
2015-11-29 11:50:28 +01:00
|
|
|
{
|
|
|
|
let pending_count = 0; //TODO:
|
|
|
|
let peer_count = 0;
|
|
|
|
let mut open_slots = IDEAL_PEERS - peer_count - pending_count + req_conn;
|
|
|
|
if open_slots > 0 {
|
|
|
|
for n in to_connect.iter() {
|
|
|
|
if n.peer_type == PeerType::Optional && open_slots > 0 {
|
|
|
|
open_slots -= 1;
|
2016-01-13 13:56:48 +01:00
|
|
|
self.connect_peer(&n.id, io);
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-01-08 13:49:00 +01:00
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
|
2016-01-13 11:31:37 +01:00
|
|
|
fn connect_peer(&mut self, id: &NodeId, io: &mut IoContext<NetworkIoMessage<Message>>) {
|
2015-11-29 11:50:28 +01:00
|
|
|
if self.have_session(id)
|
|
|
|
{
|
|
|
|
warn!("Aborted connect. Node already connected.");
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if self.connecting_to(id)
|
|
|
|
{
|
|
|
|
warn!("Aborted connect. Node already connecting.");
|
|
|
|
return;
|
|
|
|
}
|
2015-11-30 16:38:55 +01:00
|
|
|
|
|
|
|
let socket = {
|
|
|
|
let node = self.nodes.get_mut(id).unwrap();
|
|
|
|
node.last_attempted = Some(::time::now());
|
2015-12-03 15:11:40 +01:00
|
|
|
|
2015-11-30 16:38:55 +01:00
|
|
|
match TcpStream::connect(&node.endpoint.address) {
|
|
|
|
Ok(socket) => socket,
|
|
|
|
Err(_) => {
|
|
|
|
warn!("Cannot connect to node");
|
|
|
|
return;
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-11-30 16:38:55 +01:00
|
|
|
let nonce = self.info.next_nonce();
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.insert_with(|token| ConnectionEntry::Handshake(Handshake::new(Token(token), id, socket, &nonce).expect("Can't create handshake"))) {
|
2015-12-03 15:11:40 +01:00
|
|
|
Some(token) => {
|
2015-12-02 12:07:46 +01:00
|
|
|
match self.connections.get_mut(token) {
|
|
|
|
Some(&mut ConnectionEntry::Handshake(ref mut h)) => {
|
|
|
|
h.start(&self.info, true)
|
2016-01-13 11:31:37 +01:00
|
|
|
.and_then(|_| h.register(io.event_loop))
|
2015-12-02 12:07:46 +01:00
|
|
|
.unwrap_or_else (|e| {
|
|
|
|
debug!(target: "net", "Handshake create error: {:?}", e);
|
|
|
|
});
|
|
|
|
},
|
|
|
|
_ => {}
|
|
|
|
}
|
2015-11-30 16:38:55 +01:00
|
|
|
},
|
|
|
|
None => { warn!("Max connections reached") }
|
|
|
|
}
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn accept(&mut self, _io: &mut IoContext<NetworkIoMessage<Message>>) {
|
2016-01-10 22:42:27 +01:00
|
|
|
trace!(target: "net", "accept");
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn connection_writable<'s>(&'s mut self, token: StreamToken, io: &mut IoContext<'s, NetworkIoMessage<Message>>) {
|
2015-12-02 12:07:46 +01:00
|
|
|
let mut kill = false;
|
|
|
|
let mut create_session = false;
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(token) {
|
2016-01-08 13:55:44 +01:00
|
|
|
Some(&mut ConnectionEntry::Handshake(ref mut h)) => {
|
2016-01-13 11:31:37 +01:00
|
|
|
h.writable(io.event_loop, &self.info).unwrap_or_else(|e| {
|
2016-01-08 13:55:44 +01:00
|
|
|
debug!(target: "net", "Handshake write error: {:?}", e);
|
|
|
|
kill = true;
|
|
|
|
});
|
|
|
|
create_session = h.done();
|
|
|
|
},
|
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 11:31:37 +01:00
|
|
|
s.writable(io.event_loop, &self.info).unwrap_or_else(|e| {
|
2016-01-08 13:55:44 +01:00
|
|
|
debug!(target: "net", "Session write error: {:?}", e);
|
|
|
|
kill = true;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
warn!(target: "net", "Received event for unknown connection");
|
|
|
|
}
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
|
|
|
if kill {
|
2016-01-13 13:56:48 +01:00
|
|
|
self.kill_connection(token, io);
|
|
|
|
return;
|
|
|
|
} else if create_session {
|
|
|
|
self.start_session(token, io);
|
2015-11-30 16:38:55 +01:00
|
|
|
}
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(token) {
|
2016-01-10 14:02:01 +01:00
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 13:56:48 +01:00
|
|
|
s.reregister(io.event_loop).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e));
|
2016-01-10 14:02:01 +01:00
|
|
|
},
|
|
|
|
_ => (),
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn connection_closed<'s>(&'s mut self, token: TimerToken, io: &mut IoContext<'s, NetworkIoMessage<Message>>) {
|
|
|
|
self.kill_connection(token, io);
|
2016-01-10 14:02:01 +01:00
|
|
|
}
|
2015-12-17 11:42:30 +01:00
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn connection_readable<'s>(&'s mut self, token: StreamToken, io: &mut IoContext<'s, NetworkIoMessage<Message>>) {
|
2015-12-02 12:07:46 +01:00
|
|
|
let mut kill = false;
|
|
|
|
let mut create_session = false;
|
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-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(token) {
|
2016-01-08 13:55:44 +01:00
|
|
|
Some(&mut ConnectionEntry::Handshake(ref mut h)) => {
|
2016-01-13 11:31:37 +01:00
|
|
|
h.readable(io.event_loop, &self.info).unwrap_or_else(|e| {
|
2016-01-08 13:55:44 +01:00
|
|
|
debug!(target: "net", "Handshake read error: {:?}", e);
|
|
|
|
kill = true;
|
|
|
|
});
|
|
|
|
create_session = h.done();
|
|
|
|
},
|
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 11:31:37 +01:00
|
|
|
let sd = { s.readable(io.event_loop, &self.info).unwrap_or_else(|e| {
|
2016-01-08 13:55:44 +01:00
|
|
|
debug!(target: "net", "Session read error: {:?}", e);
|
|
|
|
kill = true;
|
|
|
|
SessionData::None
|
|
|
|
}) };
|
|
|
|
match sd {
|
|
|
|
SessionData::Ready => {
|
|
|
|
for (p, _) in self.handlers.iter_mut() {
|
|
|
|
if s.have_capability(p) {
|
|
|
|
ready_data.push(p);
|
2015-12-17 11:42:30 +01:00
|
|
|
}
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|
|
|
|
},
|
|
|
|
SessionData::Packet {
|
|
|
|
data,
|
|
|
|
protocol,
|
|
|
|
packet_id,
|
|
|
|
} => {
|
|
|
|
match self.handlers.get_mut(protocol) {
|
|
|
|
None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) },
|
|
|
|
Some(_) => packet_data = Some((protocol, packet_id, data)),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
SessionData::None => {},
|
2015-11-30 16:38:55 +01:00
|
|
|
}
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
warn!(target: "net", "Received event for unknown connection");
|
|
|
|
}
|
2015-11-30 16:38:55 +01:00
|
|
|
}
|
2015-12-02 12:07:46 +01:00
|
|
|
if kill {
|
2016-01-13 13:56:48 +01:00
|
|
|
self.kill_connection(token, io);
|
|
|
|
return;
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
|
|
|
if create_session {
|
2016-01-13 13:56:48 +01:00
|
|
|
self.start_session(token, io);
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2015-12-22 22:23:43 +01:00
|
|
|
for p in ready_data {
|
|
|
|
let mut h = self.handlers.get_mut(p).unwrap();
|
2016-01-13 13:56:48 +01:00
|
|
|
h.connected(&mut NetworkContext::new(io, p, Some(token), &mut self.connections, &mut self.timers), &token);
|
2015-12-22 22:23:43 +01:00
|
|
|
}
|
|
|
|
if let Some((p, packet_id, data)) = packet_data {
|
|
|
|
let mut h = self.handlers.get_mut(p).unwrap();
|
2016-01-13 13:56:48 +01:00
|
|
|
h.read(&mut NetworkContext::new(io, p, Some(token), &mut self.connections, &mut self.timers), &token, packet_id, &data[1..]);
|
2015-12-22 22:23:43 +01:00
|
|
|
}
|
|
|
|
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(token) {
|
2016-01-10 14:02:01 +01:00
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 13:56:48 +01:00
|
|
|
s.reregister(io.event_loop).unwrap_or_else(|e| debug!(target: "net", "Session registration error: {:?}", e));
|
2016-01-10 14:02:01 +01:00
|
|
|
},
|
|
|
|
_ => (),
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn start_session(&mut self, token: StreamToken, io: &mut IoContext<NetworkIoMessage<Message>>) {
|
|
|
|
let info = &self.info;
|
2016-01-14 16:52:10 +01:00
|
|
|
// TODO: use slab::replace_with (currently broken)
|
2016-01-15 00:50:48 +01:00
|
|
|
/*
|
|
|
|
match self.connections.remove(token) {
|
2016-01-14 16:52:10 +01:00
|
|
|
Some(ConnectionEntry::Handshake(h)) => {
|
|
|
|
match Session::new(h, io.event_loop, info) {
|
|
|
|
Ok(session) => {
|
2016-01-15 00:50:48 +01:00
|
|
|
assert!(token == self.connections.insert(ConnectionEntry::Session(session)).ok().unwrap());
|
2016-01-14 16:52:10 +01:00
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
debug!(target: "net", "Session construction error: {:?}", e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
_ => panic!("Error updating slab with session")
|
2016-01-15 00:50:48 +01:00
|
|
|
}*/
|
|
|
|
self.connections.replace_with(token, |c| {
|
2015-12-02 12:07:46 +01:00
|
|
|
match c {
|
2016-01-13 13:56:48 +01:00
|
|
|
ConnectionEntry::Handshake(h) => Session::new(h, io.event_loop, info)
|
2015-12-02 12:07:46 +01:00
|
|
|
.map(|s| Some(ConnectionEntry::Session(s)))
|
2015-12-03 15:11:40 +01:00
|
|
|
.unwrap_or_else(|e| {
|
2015-12-02 12:07:46 +01:00
|
|
|
debug!(target: "net", "Session construction error: {:?}", e);
|
|
|
|
None
|
|
|
|
}),
|
2016-01-08 13:49:00 +01:00
|
|
|
_ => { panic!("No handshake to create a session from"); }
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
|
|
|
}).expect("Error updating slab with session");
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn connection_timeout<'s>(&'s mut self, token: StreamToken, io: &mut IoContext<'s, NetworkIoMessage<Message>>) {
|
|
|
|
self.kill_connection(token, io)
|
2015-12-02 12:07:46 +01:00
|
|
|
}
|
2016-01-08 13:55:44 +01:00
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn kill_connection<'s>(&'s mut self, token: StreamToken, io: &mut IoContext<'s, NetworkIoMessage<Message>>) {
|
2016-01-10 14:02:01 +01:00
|
|
|
let mut to_disconnect: Vec<ProtocolId> = Vec::new();
|
2016-01-15 00:50:48 +01:00
|
|
|
let mut remove = true;
|
|
|
|
match self.connections.get_mut(token) {
|
2016-01-10 14:02:01 +01:00
|
|
|
Some(&mut ConnectionEntry::Handshake(_)) => (), // just abandon handshake
|
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) if s.is_ready() => {
|
2016-01-13 13:56:48 +01:00
|
|
|
for (p, _) in self.handlers.iter_mut() {
|
2016-01-10 14:02:01 +01:00
|
|
|
if s.have_capability(p) {
|
|
|
|
to_disconnect.push(p);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2016-01-15 00:50:48 +01:00
|
|
|
_ => {
|
|
|
|
remove = false;
|
|
|
|
},
|
2016-01-10 14:02:01 +01:00
|
|
|
}
|
|
|
|
for p in to_disconnect {
|
2016-01-13 13:56:48 +01:00
|
|
|
let mut h = self.handlers.get_mut(p).unwrap();
|
|
|
|
h.disconnected(&mut NetworkContext::new(io, p, Some(token), &mut self.connections, &mut self.timers), &token);
|
2016-01-10 14:02:01 +01:00
|
|
|
}
|
2016-01-15 00:50:48 +01:00
|
|
|
if remove {
|
|
|
|
self.connections.remove(token);
|
|
|
|
}
|
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-13 11:31:37 +01:00
|
|
|
impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Message: Send + 'static {
|
|
|
|
/// Initialize networking
|
2016-01-13 13:56:48 +01:00
|
|
|
fn initialize(&mut self, io: &mut IoContext<NetworkIoMessage<Message>>) {
|
2016-01-13 11:31:37 +01:00
|
|
|
/*
|
|
|
|
match ::ifaces::Interface::get_all().unwrap().into_iter().filter(|x| x.kind == ::ifaces::Kind::Packet && x.addr.is_some()).next() {
|
|
|
|
Some(iface) => config.public_address = iface.addr.unwrap(),
|
|
|
|
None => warn!("No public network interface"),
|
|
|
|
*/
|
|
|
|
|
|
|
|
// Start listening for incoming connections
|
|
|
|
io.event_loop.register(&self.listener, Token(TCP_ACCEPT), EventSet::readable(), PollOpt::edge()).unwrap();
|
2016-01-14 16:52:10 +01:00
|
|
|
io.event_loop.timeout_ms(Token(IDLE), MAINTENANCE_TIMEOUT).unwrap();
|
2016-01-13 11:31:37 +01:00
|
|
|
// open the udp socket
|
|
|
|
io.event_loop.register(&self.udp_socket, Token(NODETABLE_RECEIVE), EventSet::readable(), PollOpt::edge()).unwrap();
|
|
|
|
io.event_loop.timeout_ms(Token(NODETABLE_MAINTAIN), 7200).unwrap();
|
|
|
|
let port = self.info.config.listen_address.port();
|
|
|
|
self.info.listen_port = port;
|
|
|
|
|
2016-01-15 16:19:21 +01:00
|
|
|
//self.add_node("enode://c022e7a27affdd1632f2e67dffeb87f02bf506344bb142e08d12b28e7e5c6e5dbb8183a46a77bff3631b51c12e8cf15199f797feafdc8834aaf078ad1a2bcfa0@127.0.0.1:30303");
|
|
|
|
// GO bootnodes
|
|
|
|
self.add_node("enode://a979fb575495b8d6db44f750317d0f4622bf4c2aa3365d6af7c284339968eef29b69ad0dce72a4d8db5ebb4968de0e3bec910127f134779fbcb0cb6d3331163c@52.16.188.185:30303"); // IE
|
|
|
|
self.add_node("enode://de471bccee3d042261d52e9bff31458daecc406142b401d4cd848f677479f73104b9fdeb090af9583d3391b7f10cb2ba9e26865dd5fca4fcdc0fb1e3b723c786@54.94.239.50:30303"); // BR
|
|
|
|
self.add_node("enode://1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082@52.74.57.123:30303"); // SG
|
|
|
|
// ETH/DEV cpp-ethereum (poc-9.ethdev.com)
|
|
|
|
self.add_node("enode://979b7fa28feeb35a4741660a16076f1943202cb72b6af70d327f053e248bab9ba81760f39d0701ef1d8f89cc1fbd2cacba0710a12cd5314d5e0c9021aa3637f9@5.1.83.226:30303");
|
2016-01-13 11:31:37 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn stream_hup<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage<Message>>, stream: StreamToken) {
|
2016-01-13 11:31:37 +01:00
|
|
|
trace!(target: "net", "Hup: {}", stream);
|
|
|
|
match stream {
|
|
|
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_closed(stream, io),
|
|
|
|
_ => warn!(target: "net", "Unexpected hup"),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn stream_readable<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage<Message>>, stream: StreamToken) {
|
2016-01-13 11:31:37 +01:00
|
|
|
match stream {
|
|
|
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_readable(stream, io),
|
|
|
|
NODETABLE_RECEIVE => {},
|
2016-01-13 15:08:36 +01:00
|
|
|
TCP_ACCEPT => self.accept(io),
|
2016-01-13 11:31:37 +01:00
|
|
|
_ => panic!("Received unknown readable token"),
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|
2016-01-13 11:31:37 +01:00
|
|
|
}
|
|
|
|
|
2016-01-13 13:56:48 +01:00
|
|
|
fn stream_writable<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage<Message>>, stream: StreamToken) {
|
2016-01-13 11:31:37 +01:00
|
|
|
match stream {
|
|
|
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_writable(stream, io),
|
|
|
|
_ => 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-13 13:56:48 +01:00
|
|
|
fn timeout<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage<Message>>, token: TimerToken) {
|
2016-01-13 11:31:37 +01:00
|
|
|
match token {
|
|
|
|
IDLE => self.maintain_network(io),
|
|
|
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, io),
|
2016-01-08 13:55:44 +01:00
|
|
|
NODETABLE_DISCOVERY => {},
|
|
|
|
NODETABLE_MAINTAIN => {},
|
2016-01-13 11:31:37 +01:00
|
|
|
_ => {
|
2016-01-13 13:56:48 +01:00
|
|
|
let protocol = *self.timers.get_mut(&token).expect("Unknown user timer token");
|
2016-01-08 13:55:44 +01:00
|
|
|
match self.handlers.get_mut(protocol) {
|
|
|
|
None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) },
|
|
|
|
Some(h) => {
|
2016-01-13 13:56:48 +01:00
|
|
|
h.timeout(&mut NetworkContext::new(io, protocol, Some(token), &mut self.connections, &mut self.timers), token);
|
2016-01-04 13:49:32 +01:00
|
|
|
}
|
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-13 13:56:48 +01:00
|
|
|
fn message<'s>(&'s mut self, io: &mut IoContext<'s, NetworkIoMessage<Message>>, message: &'s mut NetworkIoMessage<Message>) {
|
2016-01-13 11:31:37 +01:00
|
|
|
match message {
|
|
|
|
&mut NetworkIoMessage::AddHandler {
|
|
|
|
ref mut handler,
|
|
|
|
ref protocol,
|
|
|
|
ref versions
|
2016-01-08 13:55:44 +01:00
|
|
|
} => {
|
2016-01-13 13:56:48 +01:00
|
|
|
let mut h = mem::replace(handler, None).unwrap();
|
|
|
|
h.initialize(&mut NetworkContext::new(io, protocol, None, &mut self.connections, &mut self.timers));
|
|
|
|
self.handlers.insert(protocol, h);
|
2016-01-08 13:55:44 +01:00
|
|
|
for v in versions {
|
2016-01-13 11:31:37 +01:00
|
|
|
self.info.capabilities.push(CapabilityInfo { protocol: protocol, version: *v, packet_count:0 });
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|
|
|
|
},
|
2016-01-13 11:31:37 +01:00
|
|
|
&mut NetworkIoMessage::Send {
|
|
|
|
ref peer,
|
|
|
|
ref packet_id,
|
|
|
|
ref protocol,
|
|
|
|
ref data,
|
2016-01-08 13:55:44 +01:00
|
|
|
} => {
|
2016-01-15 00:50:48 +01:00
|
|
|
match self.connections.get_mut(*peer as usize) {
|
2016-01-08 13:55:44 +01:00
|
|
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
2016-01-13 11:31:37 +01:00
|
|
|
s.send_packet(protocol, *packet_id as u8, &data).unwrap_or_else(|e| {
|
2016-01-08 13:55:44 +01:00
|
|
|
warn!(target: "net", "Send error: {:?}", e);
|
|
|
|
}); //TODO: don't copy vector data
|
|
|
|
},
|
|
|
|
_ => {
|
|
|
|
warn!(target: "net", "Send: Peer does not exist");
|
2016-01-08 13:49:00 +01:00
|
|
|
}
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|
|
|
|
},
|
2016-01-13 23:13:57 +01:00
|
|
|
&mut NetworkIoMessage::User(ref message) => {
|
2016-01-08 13:55:44 +01:00
|
|
|
for (p, h) in self.handlers.iter_mut() {
|
2016-01-13 23:13:57 +01:00
|
|
|
h.message(&mut NetworkContext::new(io, p, None, &mut self.connections, &mut self.timers), &message);
|
2015-12-28 11:41:51 +01:00
|
|
|
}
|
|
|
|
}
|
2015-11-29 11:50:28 +01:00
|
|
|
}
|
|
|
|
}
|
2016-01-08 13:55:44 +01:00
|
|
|
}
|