More style
This commit is contained in:
parent
e6623c0edd
commit
396a1755e3
@ -313,8 +313,6 @@ pub mod aes {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
|
||||||
use std::str::FromStr;
|
|
||||||
use hash::*;
|
use hash::*;
|
||||||
use crypto::*;
|
use crypto::*;
|
||||||
|
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
#![allow(dead_code)] //TODO: remove this after everything is done
|
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use mio::{Token, EventSet, EventLoop, Timeout, PollOpt, TryRead, TryWrite};
|
use mio::{Token, EventSet, EventLoop, Timeout, PollOpt, TryRead, TryWrite};
|
||||||
use mio::tcp::*;
|
use mio::tcp::*;
|
||||||
@ -183,7 +182,6 @@ impl EncryptedConnection {
|
|||||||
|
|
||||||
key_material.sha3().copy_to(&mut key_material[32..64]);
|
key_material.sha3().copy_to(&mut key_material[32..64]);
|
||||||
let mac_encoder = EcbEncryptor::new(AesSafe256Encryptor::new(&key_material[32..64]), NoPadding);
|
let mac_encoder = EcbEncryptor::new(AesSafe256Encryptor::new(&key_material[32..64]), NoPadding);
|
||||||
println!("SESSION key: {}", H256::from_slice(&key_material[32..64]).hex());
|
|
||||||
|
|
||||||
let mut egress_mac = Keccak::new_keccak256();
|
let mut egress_mac = Keccak::new_keccak256();
|
||||||
let mut mac_material = &H256::from_slice(&key_material[32..64]) ^ &handshake.remote_nonce;
|
let mut mac_material = &H256::from_slice(&key_material[32..64]) ^ &handshake.remote_nonce;
|
||||||
@ -292,17 +290,10 @@ impl EncryptedConnection {
|
|||||||
let mut prev = H128::new();
|
let mut prev = H128::new();
|
||||||
mac.clone().finalize(&mut prev);
|
mac.clone().finalize(&mut prev);
|
||||||
let mut enc = H128::new();
|
let mut enc = H128::new();
|
||||||
println!("before: {}", prev.hex());
|
|
||||||
mac_encoder.encrypt(&mut RefReadBuffer::new(&prev), &mut RefWriteBuffer::new(&mut enc), true).unwrap();
|
mac_encoder.encrypt(&mut RefReadBuffer::new(&prev), &mut RefWriteBuffer::new(&mut enc), true).unwrap();
|
||||||
mac_encoder.reset();
|
mac_encoder.reset();
|
||||||
println!("after {}", enc.hex());
|
|
||||||
|
|
||||||
if !seed.is_empty() {
|
enc = enc ^ if seed.is_empty() { prev } else { H128::from_slice(seed) };
|
||||||
enc = enc ^ H128::from_slice(seed);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
enc = enc ^ prev;
|
|
||||||
}
|
|
||||||
mac.update(&enc);
|
mac.update(&enc);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -349,7 +340,7 @@ impl EncryptedConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
pub fn ctest() {
|
pub fn test_encryption() {
|
||||||
use hash::*;
|
use hash::*;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
let key = H256::from_str("2212767d793a7a3d66f869ae324dd11bd17044b82c9f463b8a541a4d089efec5").unwrap();
|
let key = H256::from_str("2212767d793a7a3d66f869ae324dd11bd17044b82c9f463b8a541a4d089efec5").unwrap();
|
||||||
@ -363,7 +354,6 @@ pub fn ctest() {
|
|||||||
let mut encoder = EcbEncryptor::new(AesSafe256Encryptor::new(&key), NoPadding);
|
let mut encoder = EcbEncryptor::new(AesSafe256Encryptor::new(&key), NoPadding);
|
||||||
encoder.encrypt(&mut RefReadBuffer::new(&before), &mut RefWriteBuffer::new(&mut got), true).unwrap();
|
encoder.encrypt(&mut RefReadBuffer::new(&before), &mut RefWriteBuffer::new(&mut got), true).unwrap();
|
||||||
encoder.reset();
|
encoder.reset();
|
||||||
println!("got: {} ", got.hex());
|
|
||||||
assert_eq!(got, after);
|
assert_eq!(got, after);
|
||||||
got = H128::new();
|
got = H128::new();
|
||||||
encoder.encrypt(&mut RefReadBuffer::new(&before2), &mut RefWriteBuffer::new(&mut got), true).unwrap();
|
encoder.encrypt(&mut RefReadBuffer::new(&before2), &mut RefWriteBuffer::new(&mut got), true).unwrap();
|
||||||
|
@ -30,8 +30,8 @@ pub struct Handshake {
|
|||||||
pub ack_cipher: Bytes
|
pub ack_cipher: Bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
const AUTH_PACKET_SIZE:usize = 307;
|
const AUTH_PACKET_SIZE: usize = 307;
|
||||||
const ACK_PACKET_SIZE:usize = 210;
|
const ACK_PACKET_SIZE: usize = 210;
|
||||||
|
|
||||||
impl Handshake {
|
impl Handshake {
|
||||||
pub fn new(token: Token, id: &NodeId, socket: TcpStream, nonce: &H256) -> Result<Handshake, Error> {
|
pub fn new(token: Token, id: &NodeId, socket: TcpStream, nonce: &H256) -> Result<Handshake, Error> {
|
||||||
@ -106,7 +106,7 @@ impl Handshake {
|
|||||||
|
|
||||||
pub fn register(&mut self, event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
pub fn register(&mut self, event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
||||||
self.idle_timeout.map(|t| event_loop.clear_timeout(t));
|
self.idle_timeout.map(|t| event_loop.clear_timeout(t));
|
||||||
self.idle_timeout = event_loop.timeout_ms(self.connection.token, 1800).ok();
|
self.idle_timeout = event_loop.timeout_ms(self.connection.token, 1800).ok();
|
||||||
try!(self.connection.register(event_loop));
|
try!(self.connection.register(event_loop));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,3 @@
|
|||||||
//TODO: remove all unwraps
|
|
||||||
use std::net::{SocketAddr, ToSocketAddrs};
|
use std::net::{SocketAddr, ToSocketAddrs};
|
||||||
use std::collections::{HashMap};
|
use std::collections::{HashMap};
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
@ -19,42 +18,41 @@ const _DEFAULT_PORT: u16 = 30304;
|
|||||||
|
|
||||||
const MAX_CONNECTIONS: usize = 1024;
|
const MAX_CONNECTIONS: usize = 1024;
|
||||||
const MAX_USER_TIMERS: usize = 32;
|
const MAX_USER_TIMERS: usize = 32;
|
||||||
const IDEAL_PEERS:u32 = 10;
|
const IDEAL_PEERS: u32 = 10;
|
||||||
|
|
||||||
pub type NodeId = H512;
|
pub type NodeId = H512;
|
||||||
pub type TimerToken = usize;
|
pub type TimerToken = usize;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct NetworkConfiguration {
|
struct NetworkConfiguration {
|
||||||
listen_address: SocketAddr,
|
listen_address: SocketAddr,
|
||||||
public_address: SocketAddr,
|
public_address: SocketAddr,
|
||||||
no_nat: bool,
|
nat_enabled: bool,
|
||||||
no_discovery: bool,
|
discovery_enabled: bool,
|
||||||
pin: bool,
|
pin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NetworkConfiguration {
|
impl NetworkConfiguration {
|
||||||
fn new() -> NetworkConfiguration {
|
fn new() -> NetworkConfiguration {
|
||||||
NetworkConfiguration {
|
NetworkConfiguration {
|
||||||
listen_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
listen_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
||||||
public_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
public_address: SocketAddr::from_str("0.0.0.0:30304").unwrap(),
|
||||||
no_nat: false,
|
nat_enabled: true,
|
||||||
no_discovery: false,
|
discovery_enabled: true,
|
||||||
pin: false,
|
pin: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct NodeEndpoint {
|
pub struct NodeEndpoint {
|
||||||
address: SocketAddr,
|
address: SocketAddr,
|
||||||
address_str: String,
|
address_str: String,
|
||||||
udp_port: u16
|
udp_port: u16
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NodeEndpoint {
|
impl NodeEndpoint {
|
||||||
fn from_str(s: &str) -> Result<NodeEndpoint, Error> {
|
fn from_str(s: &str) -> Result<NodeEndpoint, Error> {
|
||||||
println!("{:?}", s);
|
|
||||||
let address = s.to_socket_addrs().map(|mut i| i.next());
|
let address = s.to_socket_addrs().map(|mut i| i.next());
|
||||||
match address {
|
match address {
|
||||||
Ok(Some(a)) => Ok(NodeEndpoint {
|
Ok(Some(a)) => Ok(NodeEndpoint {
|
||||||
@ -65,19 +63,19 @@ impl NodeEndpoint {
|
|||||||
Ok(_) => Err(Error::AddressResolve(None)),
|
Ok(_) => Err(Error::AddressResolve(None)),
|
||||||
Err(e) => Err(Error::AddressResolve(Some(e)))
|
Err(e) => Err(Error::AddressResolve(Some(e)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Copy, Clone)]
|
#[derive(PartialEq, Eq, Copy, Clone)]
|
||||||
enum PeerType {
|
enum PeerType {
|
||||||
Required,
|
Required,
|
||||||
Optional
|
Optional
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Node {
|
struct Node {
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
endpoint: NodeEndpoint,
|
endpoint: NodeEndpoint,
|
||||||
peer_type: PeerType,
|
peer_type: PeerType,
|
||||||
last_attempted: Option<Tm>,
|
last_attempted: Option<Tm>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,26 +89,26 @@ impl FromStr for Node {
|
|||||||
(NodeId::new(), try!(NodeEndpoint::from_str(s)))
|
(NodeId::new(), try!(NodeEndpoint::from_str(s)))
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Node {
|
Ok(Node {
|
||||||
id: id,
|
id: id,
|
||||||
endpoint: endpoint,
|
endpoint: endpoint,
|
||||||
peer_type: PeerType::Optional,
|
peer_type: PeerType::Optional,
|
||||||
last_attempted: None,
|
last_attempted: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PartialEq for Node {
|
impl PartialEq for Node {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
self.id == other.id
|
self.id == other.id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Eq for Node { }
|
impl Eq for Node { }
|
||||||
|
|
||||||
impl Hash for Node {
|
impl Hash for Node {
|
||||||
fn hash<H>(&self, state: &mut H) where H: Hasher {
|
fn hash<H>(&self, state: &mut H) where H: Hasher {
|
||||||
self.id.hash(state)
|
self.id.hash(state)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tokens
|
// Tokens
|
||||||
@ -128,7 +126,7 @@ pub type PacketId = u8;
|
|||||||
pub type ProtocolId = &'static str;
|
pub type ProtocolId = &'static str;
|
||||||
|
|
||||||
pub enum HostMessage {
|
pub enum HostMessage {
|
||||||
Shutdown,
|
Shutdown,
|
||||||
AddHandler {
|
AddHandler {
|
||||||
handler: Box<ProtocolHandler+Send>,
|
handler: Box<ProtocolHandler+Send>,
|
||||||
protocol: ProtocolId,
|
protocol: ProtocolId,
|
||||||
@ -172,8 +170,8 @@ impl Encodable for CapabilityInfo {
|
|||||||
/// IO access point
|
/// IO access point
|
||||||
pub struct HostIo<'s> {
|
pub struct HostIo<'s> {
|
||||||
protocol: ProtocolId,
|
protocol: ProtocolId,
|
||||||
connections: &'s mut Slab<ConnectionEntry>,
|
connections: &'s mut Slab<ConnectionEntry>,
|
||||||
timers: &'s mut Slab<UserTimer>,
|
timers: &'s mut Slab<UserTimer>,
|
||||||
session: Option<Token>,
|
session: Option<Token>,
|
||||||
event_loop: &'s mut EventLoop<Host>,
|
event_loop: &'s mut EventLoop<Host>,
|
||||||
}
|
}
|
||||||
@ -217,9 +215,9 @@ impl<'s> HostIo<'s> {
|
|||||||
/// Register a new IO timer. Returns a new timer toke. 'ProtocolHandler::timeout' will be called with the token.
|
/// Register a new IO timer. Returns a new timer toke. 'ProtocolHandler::timeout' will be called with the token.
|
||||||
pub fn register_timer(&mut self, ms: u64) -> Result<TimerToken, Error>{
|
pub fn register_timer(&mut self, ms: u64) -> Result<TimerToken, Error>{
|
||||||
match self.timers.insert(UserTimer {
|
match self.timers.insert(UserTimer {
|
||||||
delay: ms,
|
delay: ms,
|
||||||
protocol: self.protocol,
|
protocol: self.protocol,
|
||||||
}) {
|
}) {
|
||||||
Ok(token) => {
|
Ok(token) => {
|
||||||
self.event_loop.timeout_ms(token, ms).expect("Error registering user timer");
|
self.event_loop.timeout_ms(token, ms).expect("Error registering user timer");
|
||||||
Ok(token.as_usize())
|
Ok(token.as_usize())
|
||||||
@ -253,8 +251,8 @@ struct UserTimer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct HostInfo {
|
pub struct HostInfo {
|
||||||
keys: KeyPair,
|
keys: KeyPair,
|
||||||
config: NetworkConfiguration,
|
config: NetworkConfiguration,
|
||||||
nonce: H256,
|
nonce: H256,
|
||||||
pub protocol_version: u32,
|
pub protocol_version: u32,
|
||||||
pub client_version: String,
|
pub client_version: String,
|
||||||
@ -283,42 +281,38 @@ enum ConnectionEntry {
|
|||||||
|
|
||||||
pub struct Host {
|
pub struct Host {
|
||||||
info: HostInfo,
|
info: HostInfo,
|
||||||
_udp_socket: UdpSocket,
|
_udp_socket: UdpSocket,
|
||||||
_listener: TcpListener,
|
_listener: TcpListener,
|
||||||
connections: Slab<ConnectionEntry>,
|
connections: Slab<ConnectionEntry>,
|
||||||
timers: Slab<UserTimer>,
|
timers: Slab<UserTimer>,
|
||||||
nodes: HashMap<NodeId, Node>,
|
nodes: HashMap<NodeId, Node>,
|
||||||
handlers: HashMap<ProtocolId, Box<ProtocolHandler>>,
|
handlers: HashMap<ProtocolId, Box<ProtocolHandler>>,
|
||||||
_idle_timeout: Timeout,
|
_idle_timeout: Timeout,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Host {
|
impl Host {
|
||||||
pub fn start(event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
pub fn start(event_loop: &mut EventLoop<Host>) -> Result<(), Error> {
|
||||||
let config = NetworkConfiguration::new();
|
let config = NetworkConfiguration::new();
|
||||||
/*
|
/*
|
||||||
match ::ifaces::Interface::get_all().unwrap().into_iter().filter(|x| x.kind == ::ifaces::Kind::Packet && x.addr.is_some()).next() {
|
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(),
|
Some(iface) => config.public_address = iface.addr.unwrap(),
|
||||||
None => warn!("No public network interface"),
|
None => warn!("No public network interface"),
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
let addr = config.listen_address;
|
let addr = config.listen_address;
|
||||||
// Setup the server socket
|
// Setup the server socket
|
||||||
let listener = TcpListener::bind(&addr).unwrap();
|
let listener = TcpListener::bind(&addr).unwrap();
|
||||||
// Start listening for incoming connections
|
// Start listening for incoming connections
|
||||||
event_loop.register(&listener, Token(TCP_ACCEPT), EventSet::readable(), PollOpt::edge()).unwrap();
|
event_loop.register(&listener, Token(TCP_ACCEPT), EventSet::readable(), PollOpt::edge()).unwrap();
|
||||||
// Setup the client socket
|
let idle_timeout = event_loop.timeout_ms(Token(IDLE), 1000).unwrap(); //TODO: check delay
|
||||||
//let sock = TcpStream::connect(&addr).unwrap();
|
// open the udp socket
|
||||||
// Register the socket
|
let udp_socket = UdpSocket::bound(&addr).unwrap();
|
||||||
//self.event_loop.register(&sock, CLIENT, EventSet::readable(), PollOpt::edge()).unwrap();
|
event_loop.register(&udp_socket, Token(NODETABLE_RECEIVE), EventSet::readable(), PollOpt::edge()).unwrap();
|
||||||
let idle_timeout = event_loop.timeout_ms(Token(IDLE), 1000).unwrap(); //TODO: check delay
|
event_loop.timeout_ms(Token(NODETABLE_MAINTAIN), 7200).unwrap();
|
||||||
// open the udp socket
|
|
||||||
let udp_socket = UdpSocket::bound(&addr).unwrap();
|
|
||||||
event_loop.register(&udp_socket, Token(NODETABLE_RECEIVE), EventSet::readable(), PollOpt::edge()).unwrap();
|
|
||||||
event_loop.timeout_ms(Token(NODETABLE_MAINTAIN), 7200).unwrap();
|
|
||||||
let port = config.listen_address.port();
|
let port = config.listen_address.port();
|
||||||
|
|
||||||
let mut host = Host {
|
let mut host = Host {
|
||||||
info: HostInfo {
|
info: HostInfo {
|
||||||
keys: KeyPair::create().unwrap(),
|
keys: KeyPair::create().unwrap(),
|
||||||
config: config,
|
config: config,
|
||||||
@ -326,17 +320,16 @@ impl Host {
|
|||||||
protocol_version: 4,
|
protocol_version: 4,
|
||||||
client_version: "parity".to_string(),
|
client_version: "parity".to_string(),
|
||||||
listen_port: port,
|
listen_port: port,
|
||||||
//capabilities: vec![ CapabilityInfo { protocol: "eth".to_string(), version: 63 }],
|
|
||||||
capabilities: Vec::new(),
|
capabilities: Vec::new(),
|
||||||
},
|
},
|
||||||
_udp_socket: udp_socket,
|
_udp_socket: udp_socket,
|
||||||
_listener: listener,
|
_listener: listener,
|
||||||
connections: Slab::new_starting_at(Token(FIRST_CONNECTION), MAX_CONNECTIONS),
|
connections: Slab::new_starting_at(Token(FIRST_CONNECTION), MAX_CONNECTIONS),
|
||||||
timers: Slab::new_starting_at(Token(USER_TIMER), MAX_USER_TIMERS),
|
timers: Slab::new_starting_at(Token(USER_TIMER), MAX_USER_TIMERS),
|
||||||
nodes: HashMap::new(),
|
nodes: HashMap::new(),
|
||||||
handlers: HashMap::new(),
|
handlers: HashMap::new(),
|
||||||
_idle_timeout: idle_timeout,
|
_idle_timeout: idle_timeout,
|
||||||
};
|
};
|
||||||
|
|
||||||
host.add_node("enode://c022e7a27affdd1632f2e67dffeb87f02bf506344bb142e08d12b28e7e5c6e5dbb8183a46a77bff3631b51c12e8cf15199f797feafdc8834aaf078ad1a2bcfa0@127.0.0.1:30303");
|
host.add_node("enode://c022e7a27affdd1632f2e67dffeb87f02bf506344bb142e08d12b28e7e5c6e5dbb8183a46a77bff3631b51c12e8cf15199f797feafdc8834aaf078ad1a2bcfa0@127.0.0.1:30303");
|
||||||
host.add_node("enode://5374c1bff8df923d3706357eeb4983cd29a63be40a269aaa2296ee5f3b2119a8978c0ed68b8f6fc84aad0df18790417daadf91a4bfbb786a16c9b0a199fa254a@gav.ethdev.com:30300");
|
host.add_node("enode://5374c1bff8df923d3706357eeb4983cd29a63be40a269aaa2296ee5f3b2119a8978c0ed68b8f6fc84aad0df18790417daadf91a4bfbb786a16c9b0a199fa254a@gav.ethdev.com:30300");
|
||||||
@ -345,9 +338,9 @@ impl Host {
|
|||||||
host.add_node("enode://7f25d3eab333a6b98a8b5ed68d962bb22c876ffcd5561fca54e3c2ef27f754df6f7fd7c9b74cc919067abac154fb8e1f8385505954f161ae440abc355855e034@54.207.93.166:30303");
|
host.add_node("enode://7f25d3eab333a6b98a8b5ed68d962bb22c876ffcd5561fca54e3c2ef27f754df6f7fd7c9b74cc919067abac154fb8e1f8385505954f161ae440abc355855e034@54.207.93.166:30303");
|
||||||
host.add_node("enode://5374c1bff8df923d3706357eeb4983cd29a63be40a269aaa2296ee5f3b2119a8978c0ed68b8f6fc84aad0df18790417daadf91a4bfbb786a16c9b0a199fa254a@92.51.165.126:30303");
|
host.add_node("enode://5374c1bff8df923d3706357eeb4983cd29a63be40a269aaa2296ee5f3b2119a8978c0ed68b8f6fc84aad0df18790417daadf91a4bfbb786a16c9b0a199fa254a@92.51.165.126:30303");
|
||||||
|
|
||||||
try!(event_loop.run(&mut host));
|
try!(event_loop.run(&mut host));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_node(&mut self, id: &str) {
|
fn add_node(&mut self, id: &str) {
|
||||||
match Node::from_str(id) {
|
match Node::from_str(id) {
|
||||||
@ -358,9 +351,9 @@ impl Host {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn maintain_network(&mut self, event_loop: &mut EventLoop<Host>) {
|
fn maintain_network(&mut self, event_loop: &mut EventLoop<Host>) {
|
||||||
self.connect_peers(event_loop);
|
self.connect_peers(event_loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn have_session(&self, id: &NodeId) -> bool {
|
fn have_session(&self, id: &NodeId) -> bool {
|
||||||
self.connections.iter().any(|e| match e { &ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
|
self.connections.iter().any(|e| match e { &ConnectionEntry::Session(ref s) => s.info.id.eq(&id), _ => false })
|
||||||
@ -370,7 +363,7 @@ impl Host {
|
|||||||
self.connections.iter().any(|e| match e { &ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
|
self.connections.iter().any(|e| match e { &ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn connect_peers(&mut self, event_loop: &mut EventLoop<Host>) {
|
fn connect_peers(&mut self, event_loop: &mut EventLoop<Host>) {
|
||||||
|
|
||||||
struct NodeInfo {
|
struct NodeInfo {
|
||||||
id: NodeId,
|
id: NodeId,
|
||||||
@ -416,7 +409,7 @@ impl Host {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn connect_peer(&mut self, id: &NodeId, event_loop: &mut EventLoop<Host>) {
|
fn connect_peer(&mut self, id: &NodeId, event_loop: &mut EventLoop<Host>) {
|
||||||
if self.have_session(id)
|
if self.have_session(id)
|
||||||
@ -434,8 +427,6 @@ impl Host {
|
|||||||
let node = self.nodes.get_mut(id).unwrap();
|
let node = self.nodes.get_mut(id).unwrap();
|
||||||
node.last_attempted = Some(::time::now());
|
node.last_attempted = Some(::time::now());
|
||||||
|
|
||||||
|
|
||||||
//blog(NetConnect) << "Attempting connection to node" << _p->id << "@" << ep << "from" << id();
|
|
||||||
match TcpStream::connect(&node.endpoint.address) {
|
match TcpStream::connect(&node.endpoint.address) {
|
||||||
Ok(socket) => socket,
|
Ok(socket) => socket,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
@ -573,7 +564,7 @@ impl Host {
|
|||||||
debug!(target: "net", "Session construction error: {:?}", e);
|
debug!(target: "net", "Session construction error: {:?}", e);
|
||||||
None
|
None
|
||||||
}),
|
}),
|
||||||
_ => { panic!("No handshake to create a session from"); }
|
_ => { panic!("No handshake to create a session from"); }
|
||||||
}
|
}
|
||||||
}).expect("Error updating slab with session");
|
}).expect("Error updating slab with session");
|
||||||
}
|
}
|
||||||
@ -584,90 +575,90 @@ impl Host {
|
|||||||
fn kill_connection(&mut self, token: Token, _event_loop: &mut EventLoop<Host>) {
|
fn kill_connection(&mut self, token: Token, _event_loop: &mut EventLoop<Host>) {
|
||||||
self.connections.remove(token);
|
self.connections.remove(token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Handler for Host {
|
impl Handler for Host {
|
||||||
type Timeout = Token;
|
type Timeout = Token;
|
||||||
type Message = HostMessage;
|
type Message = HostMessage;
|
||||||
|
|
||||||
fn ready(&mut self, event_loop: &mut EventLoop<Host>, token: Token, events: EventSet) {
|
fn ready(&mut self, event_loop: &mut EventLoop<Host>, token: Token, events: EventSet) {
|
||||||
if events.is_readable() {
|
if events.is_readable() {
|
||||||
|
match token.as_usize() {
|
||||||
|
TCP_ACCEPT => self.accept(event_loop),
|
||||||
|
IDLE => self.maintain_network(event_loop),
|
||||||
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_readable(token, event_loop),
|
||||||
|
NODETABLE_RECEIVE => {},
|
||||||
|
_ => panic!("Received unknown readable token"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if events.is_writable() {
|
||||||
|
match token.as_usize() {
|
||||||
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_writable(token, event_loop),
|
||||||
|
_ => panic!("Received unknown writable token"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timeout(&mut self, event_loop: &mut EventLoop<Host>, token: Token) {
|
||||||
match token.as_usize() {
|
match token.as_usize() {
|
||||||
TCP_ACCEPT => self.accept(event_loop),
|
|
||||||
IDLE => self.maintain_network(event_loop),
|
IDLE => self.maintain_network(event_loop),
|
||||||
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_readable(token, event_loop),
|
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, event_loop),
|
||||||
NODETABLE_RECEIVE => {},
|
NODETABLE_DISCOVERY => {},
|
||||||
_ => panic!("Received unknown readable token"),
|
NODETABLE_MAINTAIN => {},
|
||||||
}
|
USER_TIMER ... LAST_USER_TIMER => {
|
||||||
}
|
let (protocol, delay) = {
|
||||||
else if events.is_writable() {
|
let timer = self.timers.get_mut(token).expect("Unknown user timer token");
|
||||||
match token.as_usize() {
|
(timer.protocol, timer.delay)
|
||||||
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_writable(token, event_loop),
|
};
|
||||||
_ => panic!("Received unknown writable token"),
|
match self.handlers.get_mut(protocol) {
|
||||||
}
|
None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) },
|
||||||
}
|
Some(h) => {
|
||||||
}
|
h.timeout(&mut HostIo::new(protocol, None, event_loop, &mut self.connections, &mut self.timers), token.as_usize());
|
||||||
|
event_loop.timeout_ms(token, delay).expect("Error re-registering user timer");
|
||||||
fn timeout(&mut self, event_loop: &mut EventLoop<Host>, token: Token) {
|
}
|
||||||
match token.as_usize() {
|
|
||||||
IDLE => self.maintain_network(event_loop),
|
|
||||||
FIRST_CONNECTION ... LAST_CONNECTION => self.connection_timeout(token, event_loop),
|
|
||||||
NODETABLE_DISCOVERY => {},
|
|
||||||
NODETABLE_MAINTAIN => {},
|
|
||||||
USER_TIMER ... LAST_USER_TIMER => {
|
|
||||||
let (protocol, delay) = {
|
|
||||||
let timer = self.timers.get_mut(token).expect("Unknown user timer token");
|
|
||||||
(timer.protocol, timer.delay)
|
|
||||||
};
|
|
||||||
match self.handlers.get_mut(protocol) {
|
|
||||||
None => { warn!(target: "net", "No handler found for protocol: {:?}", protocol) },
|
|
||||||
Some(h) => {
|
|
||||||
h.timeout(&mut HostIo::new(protocol, None, event_loop, &mut self.connections, &mut self.timers), token.as_usize());
|
|
||||||
event_loop.timeout_ms(token, delay).expect("Error re-registering user timer");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
_ => panic!("Unknown timer token"),
|
||||||
}
|
}
|
||||||
_ => panic!("Unknown timer token"),
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn notify(&mut self, event_loop: &mut EventLoop<Self>, msg: Self::Message) {
|
fn notify(&mut self, event_loop: &mut EventLoop<Self>, msg: Self::Message) {
|
||||||
match msg {
|
match msg {
|
||||||
HostMessage::Shutdown => event_loop.shutdown(),
|
HostMessage::Shutdown => event_loop.shutdown(),
|
||||||
HostMessage::AddHandler {
|
HostMessage::AddHandler {
|
||||||
handler,
|
handler,
|
||||||
protocol,
|
protocol,
|
||||||
versions
|
versions
|
||||||
} => {
|
} => {
|
||||||
self.handlers.insert(protocol, handler);
|
self.handlers.insert(protocol, handler);
|
||||||
for v in versions {
|
for v in versions {
|
||||||
self.info.capabilities.push(CapabilityInfo { protocol: protocol, version: v, packet_count:0 });
|
self.info.capabilities.push(CapabilityInfo { protocol: protocol, version: v, packet_count:0 });
|
||||||
}
|
|
||||||
},
|
|
||||||
HostMessage::Send {
|
|
||||||
peer,
|
|
||||||
packet_id,
|
|
||||||
protocol,
|
|
||||||
data,
|
|
||||||
} => {
|
|
||||||
match self.connections.get_mut(Token(peer as usize)) {
|
|
||||||
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
|
||||||
s.send_packet(protocol, packet_id as u8, &data).unwrap_or_else(|e| {
|
|
||||||
warn!(target: "net", "Send error: {:?}", e);
|
|
||||||
}); //TODO: don't copy vector data
|
|
||||||
},
|
|
||||||
_ => {
|
|
||||||
warn!(target: "net", "Send: Peer does not exist");
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
},
|
HostMessage::Send {
|
||||||
HostMessage::UserMessage(message) => {
|
peer,
|
||||||
for (p, h) in self.handlers.iter_mut() {
|
packet_id,
|
||||||
if p != &message.protocol {
|
protocol,
|
||||||
h.message(&mut HostIo::new(message.protocol, None, event_loop, &mut self.connections, &mut self.timers), &message);
|
data,
|
||||||
|
} => {
|
||||||
|
match self.connections.get_mut(Token(peer as usize)) {
|
||||||
|
Some(&mut ConnectionEntry::Session(ref mut s)) => {
|
||||||
|
s.send_packet(protocol, packet_id as u8, &data).unwrap_or_else(|e| {
|
||||||
|
warn!(target: "net", "Send error: {:?}", e);
|
||||||
|
}); //TODO: don't copy vector data
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
warn!(target: "net", "Send: Peer does not exist");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
HostMessage::UserMessage(message) => {
|
||||||
|
for (p, h) in self.handlers.iter_mut() {
|
||||||
|
if p != &message.protocol {
|
||||||
|
h.message(&mut HostIo::new(message.protocol, None, event_loop, &mut self.connections, &mut self.timers), &message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
Loading…
Reference in New Issue
Block a user