Merge branch 'master' of github.com:ethcore/parity into move_hash

This commit is contained in:
debris
2016-08-05 10:53:34 +02:00
67 changed files with 468 additions and 348 deletions

View File

@@ -12,11 +12,8 @@ log = "0.3"
env_logger = "0.3"
rustc-serialize = "0.3"
arrayvec = "0.3"
mio = { git = "https://github.com/ethcore/mio", branch = "v0.5.x" }
nix ="0.5.0"
rand = "0.3.12"
time = "0.1.34"
tiny-keccak = "1.0"
rocksdb = { git = "https://github.com/ethcore/rust-rocksdb" }
lazy_static = "0.2"
eth-secp256k1 = { git = "https://github.com/ethcore/rust-secp256k1" }
@@ -24,17 +21,13 @@ rust-crypto = "0.2.34"
elastic-array = { git = "https://github.com/ethcore/elastic-array" }
heapsize = { version = "0.3", features = ["unstable"] }
itertools = "0.4"
crossbeam = "0.2"
slab = "0.2"
sha3 = { path = "sha3" }
clippy = { version = "0.0.80", optional = true}
igd = "0.5.0"
ethcore-devtools = { path = "../devtools" }
libc = "0.2.7"
vergen = "0.1"
target_info = "0.1"
bigint = { path = "bigint" }
chrono = "0.2"
parking_lot = "0.2.6"
using_queue = { path = "using_queue" }
table = { path = "table" }

15
util/io/Cargo.toml Normal file
View File

@@ -0,0 +1,15 @@
[package]
description = "Ethcore IO library"
homepage = "http://ethcore.io"
license = "GPL-3.0"
name = "ethcore-io"
version = "1.3.0"
authors = ["Ethcore <admin@ethcore.io>"]
[dependencies]
mio = { git = "https://github.com/ethcore/mio", branch = "v0.5.x" }
crossbeam = "0.2"
parking_lot = "0.2.6"
log = "0.3"
slab = "0.2"

View File

@@ -19,8 +19,9 @@
//! Example usage for creating a network service and adding an IO handler:
//!
//! ```rust
//! extern crate ethcore_util;
//! use ethcore_util::*;
//! extern crate ethcore_io;
//! use ethcore_io::*;
//! use std::sync::Arc;
//!
//! struct MyHandler;
//!
@@ -52,8 +53,17 @@
//! // Drop the service
//! }
//! ```
extern crate mio;
#[macro_use]
extern crate log as rlog;
extern crate slab;
extern crate crossbeam;
extern crate parking_lot;
mod service;
mod worker;
mod panics;
use mio::{EventLoop, Token};
use std::fmt;
@@ -63,6 +73,8 @@ use std::fmt;
pub enum IoError {
/// Low level error from mio crate
Mio(::std::io::Error),
/// Error concerning the Rust standard library's IO subsystem.
StdIo(::std::io::Error),
}
impl fmt::Display for IoError {
@@ -70,11 +82,18 @@ impl fmt::Display for IoError {
// just defer to the std implementation for now.
// we can refine the formatting when more variants are added.
match *self {
IoError::Mio(ref std_err) => std_err.fmt(f)
IoError::Mio(ref std_err) => std_err.fmt(f),
IoError::StdIo(ref std_err) => std_err.fmt(f),
}
}
}
impl From<::std::io::Error> for IoError {
fn from(err: ::std::io::Error) -> IoError {
IoError::StdIo(err)
}
}
impl<Message> From<::mio::NotifyError<service::IoMessage<Message>>> for IoError where Message: Send + Clone {
fn from(_err: ::mio::NotifyError<service::IoMessage<Message>>) -> IoError {
IoError::Mio(::std::io::Error::new(::std::io::ErrorKind::ConnectionAborted, "Network IO notification error"))
@@ -105,19 +124,20 @@ pub trait IoHandler<Message>: Send + Sync where Message: Send + Sync + Clone + '
fn deregister_stream(&self, _stream: StreamToken, _event_loop: &mut EventLoop<IoManager<Message>>) {}
}
pub use io::service::TimerToken;
pub use io::service::StreamToken;
pub use io::service::IoContext;
pub use io::service::IoService;
pub use io::service::IoChannel;
pub use io::service::IoManager;
pub use io::service::TOKENS_PER_HANDLER;
pub use service::TimerToken;
pub use service::StreamToken;
pub use service::IoContext;
pub use service::IoService;
pub use service::IoChannel;
pub use service::IoManager;
pub use service::TOKENS_PER_HANDLER;
pub use panics::{PanicHandler, MayPanic, OnPanicListener, ForwardPanic};
#[cfg(test)]
mod tests {
use std::sync::Arc;
use io::*;
use super::*;
struct MyHandler;

View File

@@ -20,11 +20,9 @@ use std::collections::HashMap;
use mio::*;
use crossbeam::sync::chase_lev;
use slab::Slab;
use error::*;
use io::{IoError, IoHandler};
use io::worker::{Worker, Work, WorkType};
use {IoError, IoHandler};
use worker::{Worker, Work, WorkType};
use panics::*;
use parking_lot::{RwLock};
use std::sync::{Condvar as SCondvar, Mutex as SMutex};
@@ -92,7 +90,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Register a new IO timer. 'IoHandler::timeout' will be called with the token.
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> {
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), IoError> {
try!(self.channel.send_io(IoMessage::AddTimer {
token: token,
delay: ms,
@@ -102,7 +100,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Delete a timer.
pub fn clear_timer(&self, token: TimerToken) -> Result<(), UtilError> {
pub fn clear_timer(&self, token: TimerToken) -> Result<(), IoError> {
try!(self.channel.send_io(IoMessage::RemoveTimer {
token: token,
handler_id: self.handler,
@@ -111,7 +109,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Register a new IO stream.
pub fn register_stream(&self, token: StreamToken) -> Result<(), UtilError> {
pub fn register_stream(&self, token: StreamToken) -> Result<(), IoError> {
try!(self.channel.send_io(IoMessage::RegisterStream {
token: token,
handler_id: self.handler,
@@ -120,7 +118,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Deregister an IO stream.
pub fn deregister_stream(&self, token: StreamToken) -> Result<(), UtilError> {
pub fn deregister_stream(&self, token: StreamToken) -> Result<(), IoError> {
try!(self.channel.send_io(IoMessage::DeregisterStream {
token: token,
handler_id: self.handler,
@@ -129,7 +127,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Reregister an IO stream.
pub fn update_registration(&self, token: StreamToken) -> Result<(), UtilError> {
pub fn update_registration(&self, token: StreamToken) -> Result<(), IoError> {
try!(self.channel.send_io(IoMessage::UpdateStreamRegistration {
token: token,
handler_id: self.handler,
@@ -138,7 +136,7 @@ impl<Message> IoContext<Message> where Message: Send + Clone + 'static {
}
/// Broadcast a message to other IO clients
pub fn message(&self, message: Message) -> Result<(), UtilError> {
pub fn message(&self, message: Message) -> Result<(), IoError> {
try!(self.channel.send(message));
Ok(())
}
@@ -175,7 +173,7 @@ pub struct IoManager<Message> where Message: Send + Sync {
impl<Message> IoManager<Message> where Message: Send + Sync + Clone + 'static {
/// Creates a new instance and registers it with the event loop.
pub fn start(panic_handler: Arc<PanicHandler>, event_loop: &mut EventLoop<IoManager<Message>>) -> Result<(), UtilError> {
pub fn start(panic_handler: Arc<PanicHandler>, event_loop: &mut EventLoop<IoManager<Message>>) -> Result<(), IoError> {
let (worker, stealer) = chase_lev::deque();
let num_workers = 4;
let work_ready_mutex = Arc::new(SMutex::new(()));
@@ -187,7 +185,7 @@ impl<Message> IoManager<Message> where Message: Send + Sync + Clone + 'static {
IoChannel::new(event_loop.channel()),
work_ready.clone(),
work_ready_mutex.clone(),
panic_handler.clone()
panic_handler.clone(),
)
).collect();
@@ -360,12 +358,12 @@ impl<Message> MayPanic for IoService<Message> where Message: Send + Sync + Clone
impl<Message> IoService<Message> where Message: Send + Sync + Clone + 'static {
/// Starts IO event loop
pub fn start() -> Result<IoService<Message>, UtilError> {
pub fn start() -> Result<IoService<Message>, IoError> {
let panic_handler = PanicHandler::new_in_arc();
let mut config = EventLoopConfig::new();
config.messages_per_tick(1024);
let mut event_loop = EventLoop::configured(config).expect("Error creating event loop");
let channel = event_loop.channel();
let mut event_loop = EventLoop::configured(config).expect("Error creating event loop");
let channel = event_loop.channel();
let panic = panic_handler.clone();
let thread = thread::spawn(move || {
let p = panic.clone();

View File

@@ -19,8 +19,8 @@ use std::mem;
use std::thread::{JoinHandle, self};
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use crossbeam::sync::chase_lev;
use io::service::{HandlerId, IoChannel, IoContext};
use io::{IoHandler};
use service::{HandlerId, IoChannel, IoContext};
use IoHandler;
use panics::*;
use std::sync::{Condvar as SCondvar, Mutex as SMutex};

29
util/network/Cargo.toml Normal file
View File

@@ -0,0 +1,29 @@
[package]
description = "Ethcore network library"
homepage = "http://ethcore.io"
license = "GPL-3.0"
name = "ethcore-network"
version = "1.3.0"
authors = ["Ethcore <admin@ethcore.io>"]
[dependencies]
log = "0.3"
mio = { git = "https://github.com/ethcore/mio", branch = "v0.5.x" }
rand = "0.3.12"
time = "0.1.34"
tiny-keccak = "1.0"
rust-crypto = "0.2.34"
slab = "0.2"
clippy = { version = "0.0.79", optional = true}
igd = "0.5.0"
libc = "0.2.7"
parking_lot = "0.2.6"
ansi_term = "0.7"
rustc-serialize = "0.3"
ethcore-io = { path = "../io" }
ethcore-util = { path = ".." }
ethcore-devtools = { path = "../../devtools" }
[features]
default = []
dev = ["clippy"]

View File

@@ -20,17 +20,16 @@ use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use mio::{Handler, Token, EventSet, EventLoop, PollOpt, TryRead, TryWrite};
use mio::tcp::*;
use hash::*;
use sha3::*;
use bytes::*;
use rlp::*;
use util::hash::*;
use util::sha3::*;
use util::bytes::*;
use util::rlp::*;
use std::io::{self, Cursor, Read, Write};
use error::*;
use io::{IoContext, StreamToken};
use network::error::NetworkError;
use network::handshake::Handshake;
use network::stats::NetworkStats;
use crypto;
use handshake::Handshake;
use stats::NetworkStats;
use util::crypto;
use rcrypto::blockmodes::*;
use rcrypto::aessafe::*;
use rcrypto::symmetriccipher::*;
@@ -121,7 +120,7 @@ impl<Socket: GenericSocket> GenericConnection<Socket> {
}
/// Writable IO handler. Called when the socket is ready to send.
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<WriteStatus, UtilError> where Message: Send + Clone {
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<WriteStatus, NetworkError> where Message: Send + Clone {
if self.send_queue.is_empty() {
return Ok(WriteStatus::Complete)
}
@@ -288,7 +287,7 @@ pub struct EncryptedConnection {
impl EncryptedConnection {
/// Create an encrypted connection out of the handshake.
pub fn new(handshake: &mut Handshake) -> Result<EncryptedConnection, UtilError> {
pub fn new(handshake: &mut Handshake) -> Result<EncryptedConnection, NetworkError> {
let shared = try!(crypto::ecdh::agree(handshake.ecdhe.secret(), &handshake.remote_ephemeral));
let mut nonce_material = H512::new();
if handshake.originated {
@@ -341,7 +340,7 @@ impl EncryptedConnection {
}
/// Send a packet
pub fn send_packet<Message>(&mut self, io: &IoContext<Message>, payload: &[u8]) -> Result<(), UtilError> where Message: Send + Clone {
pub fn send_packet<Message>(&mut self, io: &IoContext<Message>, payload: &[u8]) -> Result<(), NetworkError> where Message: Send + Clone {
let mut header = RlpStream::new();
let len = payload.len() as usize;
header.append_raw(&[(len >> 16) as u8, (len >> 8) as u8, len as u8], 1);
@@ -368,7 +367,7 @@ impl EncryptedConnection {
}
/// Decrypt and authenticate an incoming packet header. Prepare for receiving payload.
fn read_header(&mut self, header: &[u8]) -> Result<(), UtilError> {
fn read_header(&mut self, header: &[u8]) -> Result<(), NetworkError> {
if header.len() != ENCRYPTED_HEADER_LEN {
return Err(From::from(NetworkError::Auth));
}
@@ -398,7 +397,7 @@ impl EncryptedConnection {
}
/// Decrypt and authenticate packet payload.
fn read_payload(&mut self, payload: &[u8]) -> Result<Packet, UtilError> {
fn read_payload(&mut self, payload: &[u8]) -> Result<Packet, NetworkError> {
let padding = (16 - (self.payload_len % 16)) % 16;
let full_length = self.payload_len + padding + 16;
if payload.len() != full_length {
@@ -436,7 +435,7 @@ impl EncryptedConnection {
}
/// Readable IO handler. Tracker receive status and returns decoded packet if avaialable.
pub fn readable<Message>(&mut self, io: &IoContext<Message>) -> Result<Option<Packet>, UtilError> where Message: Send + Clone{
pub fn readable<Message>(&mut self, io: &IoContext<Message>) -> Result<Option<Packet>, NetworkError> where Message: Send + Clone{
try!(io.clear_timer(self.connection.token));
if let EncryptedConnectionState::Header = self.read_state {
if let Some(data) = try!(self.connection.readable()) {
@@ -459,7 +458,7 @@ impl EncryptedConnection {
}
/// Writable IO handler. Processes send queeue.
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Clone {
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Clone {
try!(self.connection.writable(io));
Ok(())
}
@@ -467,7 +466,7 @@ impl EncryptedConnection {
#[test]
pub fn test_encryption() {
use hash::*;
use util::hash::*;
use std::str::FromStr;
let key = H256::from_str("2212767d793a7a3d66f869ae324dd11bd17044b82c9f463b8a541a4d089efec5").unwrap();
let before = H128::from_str("12532abaec065082a3cf1da7d0136f15").unwrap();
@@ -496,7 +495,7 @@ mod tests {
use std::io::{Read, Write, Error, Cursor, ErrorKind};
use mio::{EventSet};
use std::collections::VecDeque;
use bytes::*;
use util::bytes::*;
use devtools::*;
use io::*;

View File

@@ -14,23 +14,23 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use bytes::Bytes;
use util::bytes::Bytes;
use std::net::SocketAddr;
use std::collections::{HashSet, HashMap, BTreeMap, VecDeque};
use std::mem;
use std::default::Default;
use mio::*;
use mio::udp::*;
use sha3::*;
use util::sha3::*;
use time;
use hash::*;
use crypto::*;
use rlp::*;
use network::node_table::*;
use network::error::NetworkError;
use util::hash::*;
use util::crypto::*;
use util::rlp::*;
use node_table::*;
use error::NetworkError;
use io::{StreamToken, IoContext};
use network::PROTOCOL_VERSION;
use PROTOCOL_VERSION;
const ADDRESS_BYTES_SIZE: u32 = 32; // Size of address type in bytes.
const ADDRESS_BITS: u32 = 8 * ADDRESS_BYTES_SIZE; // Denoted by n in [Kademlia].
@@ -533,10 +533,10 @@ impl Discovery {
#[cfg(test)]
mod tests {
use super::*;
use hash::*;
use util::hash::*;
use std::net::*;
use network::node_table::*;
use crypto::KeyPair;
use node_table::*;
use util::crypto::KeyPair;
use std::str::FromStr;
use rustc_serialize::hex::FromHex;

View File

@@ -15,8 +15,9 @@
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use io::IoError;
use crypto::CryptoError;
use rlp::*;
use util::crypto::CryptoError;
use util::rlp::*;
use util::UtilError;
use std::fmt;
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
@@ -94,8 +95,16 @@ pub enum NetworkError {
PeerNotFound,
/// Peer is diconnected.
Disconnect(DisconnectReason),
/// Util error.
Util(UtilError),
/// Socket IO error.
Io(IoError),
/// Error concerning the network address parsing subsystem.
AddressParse(::std::net::AddrParseError),
/// Error concerning the network address resolution subsystem.
AddressResolve(Option<::std::io::Error>),
/// Error concerning the Rust standard library's IO subsystem.
StdIo(::std::io::Error),
}
impl fmt::Display for NetworkError {
@@ -109,6 +118,11 @@ impl fmt::Display for NetworkError {
PeerNotFound => "Peer not found".into(),
Disconnect(ref reason) => format!("Peer disconnected: {}", reason),
Io(ref err) => format!("Socket I/O error: {}", err),
AddressParse(ref err) => format!("{}", err),
AddressResolve(Some(ref err)) => format!("{}", err),
AddressResolve(_) => "Failed to resolve network address.".into(),
StdIo(ref err) => format!("{}", err),
Util(ref err) => format!("{}", err),
};
f.write_fmt(format_args!("Network error ({})", msg))
@@ -121,18 +135,36 @@ impl From<DecoderError> for NetworkError {
}
}
impl From<::std::io::Error> for NetworkError {
fn from(err: ::std::io::Error) -> NetworkError {
NetworkError::StdIo(err)
}
}
impl From<IoError> for NetworkError {
fn from(err: IoError) -> NetworkError {
NetworkError::Io(err)
}
}
impl From<UtilError> for NetworkError {
fn from(err: UtilError) -> NetworkError {
NetworkError::Util(err)
}
}
impl From<CryptoError> for NetworkError {
fn from(_err: CryptoError) -> NetworkError {
NetworkError::Auth
}
}
impl From<::std::net::AddrParseError> for NetworkError {
fn from(err: ::std::net::AddrParseError) -> NetworkError {
NetworkError::AddressParse(err)
}
}
#[test]
fn test_errors() {
assert_eq!(DisconnectReason::ClientQuit, DisconnectReason::from_u8(8));

View File

@@ -17,18 +17,17 @@
use std::sync::Arc;
use rand::random;
use mio::tcp::*;
use hash::*;
use rlp::*;
use sha3::Hashable;
use bytes::Bytes;
use crypto::*;
use crypto;
use network::connection::{Connection};
use network::host::{HostInfo};
use network::node_table::NodeId;
use util::hash::*;
use util::rlp::*;
use util::sha3::Hashable;
use util::bytes::Bytes;
use util::crypto::*;
use util::crypto;
use connection::{Connection};
use host::{HostInfo};
use node_table::NodeId;
use error::*;
use network::error::NetworkError;
use network::stats::NetworkStats;
use stats::NetworkStats;
use io::{IoContext, StreamToken};
#[derive(PartialEq, Eq, Debug)]
@@ -84,7 +83,7 @@ const ECIES_OVERHEAD: usize = 113;
impl Handshake {
/// Create a new handshake object
pub fn new(token: StreamToken, id: Option<&NodeId>, socket: TcpStream, nonce: &H256, stats: Arc<NetworkStats>) -> Result<Handshake, UtilError> {
pub fn new(token: StreamToken, id: Option<&NodeId>, socket: TcpStream, nonce: &H256, stats: Arc<NetworkStats>) -> Result<Handshake, NetworkError> {
Ok(Handshake {
id: if let Some(id) = id { id.clone()} else { NodeId::new() },
connection: Connection::new(token, socket, stats),
@@ -107,7 +106,7 @@ impl Handshake {
}
/// Start a handhsake
pub fn start<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo, originated: bool) -> Result<(), UtilError> where Message: Send + Clone{
pub fn start<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo, originated: bool) -> Result<(), NetworkError> where Message: Send + Clone{
self.originated = originated;
io.register_timer(self.connection.token, HANDSHAKE_TIMEOUT).ok();
if originated {
@@ -126,7 +125,7 @@ impl Handshake {
}
/// Readable IO handler. Drives the state change.
pub fn readable<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), UtilError> where Message: Send + Clone {
pub fn readable<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), NetworkError> where Message: Send + Clone {
if !self.expired() {
while let Some(data) = try!(self.connection.readable()) {
match self.state {
@@ -155,14 +154,14 @@ impl Handshake {
}
/// Writabe IO handler.
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Clone {
pub fn writable<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Clone {
if !self.expired() {
try!(self.connection.writable(io));
}
Ok(())
}
fn set_auth(&mut self, host_secret: &Secret, sig: &[u8], remote_public: &[u8], remote_nonce: &[u8], remote_version: u64) -> Result<(), UtilError> {
fn set_auth(&mut self, host_secret: &Secret, sig: &[u8], remote_public: &[u8], remote_nonce: &[u8], remote_version: u64) -> Result<(), NetworkError> {
self.id.clone_from_slice(remote_public);
self.remote_nonce.clone_from_slice(remote_nonce);
self.remote_version = remote_version;
@@ -173,7 +172,7 @@ impl Handshake {
}
/// Parse, validate and confirm auth message
fn read_auth<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8]) -> Result<(), UtilError> where Message: Send + Clone {
fn read_auth<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8]) -> Result<(), NetworkError> where Message: Send + Clone {
trace!(target: "network", "Received handshake auth from {:?}", self.connection.remote_addr_str());
if data.len() != V4_AUTH_PACKET_SIZE {
debug!(target: "network", "Wrong auth packet size");
@@ -204,7 +203,7 @@ impl Handshake {
Ok(())
}
fn read_auth_eip8<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8]) -> Result<(), UtilError> where Message: Send + Clone {
fn read_auth_eip8<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8]) -> Result<(), NetworkError> where Message: Send + Clone {
trace!(target: "network", "Received EIP8 handshake auth from {:?}", self.connection.remote_addr_str());
self.auth_cipher.extend_from_slice(data);
let auth = try!(ecies::decrypt(secret, &self.auth_cipher[0..2], &self.auth_cipher[2..]));
@@ -219,7 +218,7 @@ impl Handshake {
}
/// Parse and validate ack message
fn read_ack(&mut self, secret: &Secret, data: &[u8]) -> Result<(), UtilError> {
fn read_ack(&mut self, secret: &Secret, data: &[u8]) -> Result<(), NetworkError> {
trace!(target: "network", "Received handshake ack from {:?}", self.connection.remote_addr_str());
if data.len() != V4_ACK_PACKET_SIZE {
debug!(target: "network", "Wrong ack packet size");
@@ -247,7 +246,7 @@ impl Handshake {
Ok(())
}
fn read_ack_eip8(&mut self, secret: &Secret, data: &[u8]) -> Result<(), UtilError> {
fn read_ack_eip8(&mut self, secret: &Secret, data: &[u8]) -> Result<(), NetworkError> {
trace!(target: "network", "Received EIP8 handshake auth from {:?}", self.connection.remote_addr_str());
self.ack_cipher.extend_from_slice(data);
let ack = try!(ecies::decrypt(secret, &self.ack_cipher[0..2], &self.ack_cipher[2..]));
@@ -260,7 +259,7 @@ impl Handshake {
}
/// Sends auth message
fn write_auth<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, public: &Public) -> Result<(), UtilError> where Message: Send + Clone {
fn write_auth<Message>(&mut self, io: &IoContext<Message>, secret: &Secret, public: &Public) -> Result<(), NetworkError> where Message: Send + Clone {
trace!(target: "network", "Sending handshake auth to {:?}", self.connection.remote_addr_str());
let mut data = [0u8; /*Signature::SIZE*/ 65 + /*H256::SIZE*/ 32 + /*Public::SIZE*/ 64 + /*H256::SIZE*/ 32 + 1]; //TODO: use associated constants
let len = data.len();
@@ -287,7 +286,7 @@ impl Handshake {
}
/// Sends ack message
fn write_ack<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Clone {
fn write_ack<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Clone {
trace!(target: "network", "Sending handshake ack to {:?}", self.connection.remote_addr_str());
let mut data = [0u8; 1 + /*Public::SIZE*/ 64 + /*H256::SIZE*/ 32]; //TODO: use associated constants
let len = data.len();
@@ -306,7 +305,7 @@ impl Handshake {
}
/// Sends EIP8 ack message
fn write_ack_eip8<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Clone {
fn write_ack_eip8<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Clone {
trace!(target: "network", "Sending EIP8 handshake ack to {:?}", self.connection.remote_addr_str());
let mut rlp = RlpStream::new_list(3);
rlp.append(self.ecdhe.public());
@@ -335,12 +334,12 @@ mod test {
use std::str::FromStr;
use rustc_serialize::hex::FromHex;
use super::*;
use crypto::*;
use hash::*;
use util::crypto::*;
use util::hash::*;
use io::*;
use std::net::SocketAddr;
use mio::tcp::TcpStream;
use network::stats::NetworkStats;
use stats::NetworkStats;
fn check_auth(h: &Handshake, version: u64) {
assert_eq!(h.id, Public::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap());

View File

@@ -27,21 +27,20 @@ use std::default::Default;
use std::fs;
use mio::*;
use mio::tcp::*;
use hash::*;
use misc::*;
use crypto::*;
use sha3::Hashable;
use rlp::*;
use network::session::{Session, SessionData};
use util::hash::*;
use util::crypto::*;
use util::Hashable;
use util::rlp::*;
use util::version;
use session::{Session, SessionData};
use error::*;
use io::*;
use network::{NetworkProtocolHandler, NonReservedPeerMode, PROTOCOL_VERSION};
use network::node_table::*;
use network::stats::NetworkStats;
use network::error::{NetworkError, DisconnectReason};
use network::discovery::{Discovery, TableUpdates, NodeEntry};
use network::ip_utils::{map_external_address, select_public_address};
use path::restrict_permissions_owner;
use {NetworkProtocolHandler, NonReservedPeerMode, PROTOCOL_VERSION};
use node_table::*;
use stats::NetworkStats;
use discovery::{Discovery, TableUpdates, NodeEntry};
use ip_utils::{map_external_address, select_public_address};
use util::path::restrict_permissions_owner;
use parking_lot::{Mutex, RwLock};
type Slab<T> = ::slab::Slab<T, usize>;
@@ -224,7 +223,7 @@ impl<'s> NetworkContext<'s> {
}
/// Send a packet over the network to another peer.
pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
pub fn send(&self, peer: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), NetworkError> {
let session = self.resolve_session(peer);
if let Some(session) = session {
try!(session.lock().send_packet(self.io, self.protocol, packet_id as u8, &data));
@@ -235,7 +234,7 @@ impl<'s> NetworkContext<'s> {
}
/// Respond to a current network message. Panics if no there is no packet in the context. If the session is expired returns nothing.
pub fn respond(&self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError> {
pub fn respond(&self, packet_id: PacketId, data: Vec<u8>) -> Result<(), NetworkError> {
assert!(self.session.is_some(), "Respond called without network context");
self.send(self.session_id.unwrap(), packet_id, data)
}
@@ -264,7 +263,7 @@ impl<'s> NetworkContext<'s> {
}
/// Register a new IO timer. 'IoHandler::timeout' will be called with the token.
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> {
pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), NetworkError> {
self.io.message(NetworkIoMessage::AddTimer {
token: token,
delay: ms,
@@ -347,7 +346,7 @@ pub struct Host {
impl Host {
/// Create a new instance
pub fn new(config: NetworkConfiguration, stats: Arc<NetworkStats>) -> Result<Host, UtilError> {
pub fn new(config: NetworkConfiguration, stats: Arc<NetworkStats>) -> Result<Host, NetworkError> {
trace!(target: "host", "Creating new Host object");
let mut listen_address = match config.listen_address {
@@ -428,7 +427,7 @@ impl Host {
}
}
pub fn add_reserved_node(&self, id: &str) -> Result<(), UtilError> {
pub fn add_reserved_node(&self, id: &str) -> Result<(), NetworkError> {
let n = try!(Node::from_str(id));
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() };
@@ -472,7 +471,7 @@ impl Host {
}
}
pub fn remove_reserved_node(&self, id: &str) -> Result<(), UtilError> {
pub fn remove_reserved_node(&self, id: &str) -> Result<(), NetworkError> {
let n = try!(Node::from_str(id));
self.reserved_nodes.write().remove(&n.id);
@@ -493,7 +492,7 @@ impl Host {
r
}
pub fn stop(&self, io: &IoContext<NetworkIoMessage>) -> Result<(), UtilError> {
pub fn stop(&self, io: &IoContext<NetworkIoMessage>) -> Result<(), NetworkError> {
self.stopping.store(true, AtomicOrdering::Release);
let mut to_kill = Vec::new();
for e in self.sessions.write().iter_mut() {
@@ -509,7 +508,7 @@ impl Host {
Ok(())
}
fn init_public_interface(&self, io: &IoContext<NetworkIoMessage>) -> Result<(), UtilError> {
fn init_public_interface(&self, io: &IoContext<NetworkIoMessage>) -> Result<(), NetworkError> {
if self.info.read().public_endpoint.is_some() {
return Ok(());
}
@@ -684,7 +683,7 @@ impl Host {
}
#[cfg_attr(feature="dev", allow(block_in_if_condition_stmt))]
fn create_connection(&self, socket: TcpStream, id: Option<&NodeId>, io: &IoContext<NetworkIoMessage>) -> Result<(), UtilError> {
fn create_connection(&self, socket: TcpStream, id: Option<&NodeId>, io: &IoContext<NetworkIoMessage>) -> Result<(), NetworkError> {
let nonce = self.info.write().next_nonce();
let mut sessions = self.sessions.write();
@@ -699,7 +698,7 @@ impl Host {
});
match token {
Some(t) => io.register_stream(t),
Some(t) => Ok(try!(From::from(io.register_stream(t)))),
None => {
debug!(target: "network", "Max sessions reached");
Ok(())
@@ -756,7 +755,7 @@ impl Host {
match session_result {
Err(e) => {
trace!(target: "network", "Session read error: {}:{:?} ({:?}) {:?}", token, s.id(), s.remote_addr(), e);
if let UtilError::Network(NetworkError::Disconnect(DisconnectReason::IncompatibleProtocol)) = e {
if let NetworkError::Disconnect(DisconnectReason::IncompatibleProtocol) = e {
if let Some(id) = s.id() {
if !self.reserved_nodes.read().contains(id) {
self.nodes.write().mark_as_useless(id);

View File

@@ -20,7 +20,7 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use network::node_table::{NodeEndpoint};
use node_table::{NodeEndpoint};
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {

View File

@@ -19,8 +19,9 @@
//! Example usage for craeting a network service and adding an IO handler:
//!
//! ```rust
//! extern crate ethcore_util as util;
//! use util::*;
//! extern crate ethcore_network as net;
//! use net::*;
//! use std::sync::Arc;
//!
//! struct MyHandler;
//!
@@ -40,10 +41,6 @@
//! fn disconnected(&self, io: &NetworkContext, peer: &PeerId) {
//! println!("Disconnected {}", peer);
//! }
//!
//! fn timeout(&self, io: &NetworkContext, timer: TimerToken) {
//! println!("Timeout {}", timer);
//! }
//! }
//!
//! fn main () {
@@ -56,6 +53,26 @@
//! // Drop the service
//! }
//! ```
#[macro_use]
extern crate log;
extern crate ethcore_io as io;
extern crate ethcore_util as util;
extern crate parking_lot;
extern crate mio;
extern crate tiny_keccak;
extern crate crypto as rcrypto;
extern crate rand;
extern crate time;
extern crate ansi_term; //TODO: remove this
extern crate rustc_serialize;
extern crate igd;
extern crate libc;
extern crate slab;
#[cfg(test)]
extern crate ethcore_devtools as devtools;
mod host;
mod connection;
mod handshake;
@@ -70,17 +87,17 @@ mod ip_utils;
#[cfg(test)]
mod tests;
pub use network::host::PeerId;
pub use network::host::PacketId;
pub use network::host::NetworkContext;
pub use network::service::NetworkService;
pub use network::host::NetworkIoMessage;
pub use network::error::NetworkError;
pub use network::host::NetworkConfiguration;
pub use network::stats::NetworkStats;
pub use host::PeerId;
pub use host::PacketId;
pub use host::NetworkContext;
pub use service::NetworkService;
pub use host::NetworkIoMessage;
pub use error::NetworkError;
pub use host::NetworkConfiguration;
pub use stats::NetworkStats;
use io::TimerToken;
pub use network::node_table::is_valid_node_url;
pub use node_table::is_valid_node_url;
const PROTOCOL_VERSION: u32 = 4;

View File

@@ -25,12 +25,12 @@ use std::path::{PathBuf};
use std::fmt;
use std::fs;
use std::io::{Read, Write};
use hash::*;
use rlp::*;
use util::hash::*;
use util::rlp::*;
use time::Tm;
use error::*;
use network::discovery::{TableUpdates, NodeEntry};
use network::ip_utils::*;
use error::NetworkError;
use discovery::{TableUpdates, NodeEntry};
use ip_utils::*;
pub use rustc_serialize::json::Json;
/// Node public key
@@ -107,18 +107,18 @@ impl NodeEndpoint {
}
impl FromStr for NodeEndpoint {
type Err = UtilError;
type Err = NetworkError;
/// Create endpoint from string. Performs name resolution if given a host name.
fn from_str(s: &str) -> Result<NodeEndpoint, UtilError> {
fn from_str(s: &str) -> Result<NodeEndpoint, NetworkError> {
let address = s.to_socket_addrs().map(|mut i| i.next());
match address {
Ok(Some(a)) => Ok(NodeEndpoint {
address: a,
udp_port: a.port()
}),
Ok(_) => Err(UtilError::AddressResolve(None)),
Err(e) => Err(UtilError::AddressResolve(Some(e)))
Ok(_) => Err(NetworkError::AddressResolve(None)),
Err(e) => Err(NetworkError::AddressResolve(Some(e)))
}
}
}
@@ -161,7 +161,7 @@ impl Display for Node {
}
impl FromStr for Node {
type Err = UtilError;
type Err = NetworkError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (id, endpoint) = if s.len() > 136 && &s[0..8] == "enode://" && &s[136..137] == "@" {
(try!(NodeId::from_str(&s[8..136])), try!(NodeEndpoint::from_str(&s[137..])))
@@ -357,7 +357,7 @@ mod tests {
use super::*;
use std::str::FromStr;
use std::net::*;
use hash::*;
use util::hash::*;
use devtools::*;
#[test]

View File

@@ -14,12 +14,10 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use error::*;
use panics::*;
use network::{NetworkProtocolHandler, NetworkConfiguration};
use network::error::NetworkError;
use network::host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use network::stats::NetworkStats;
use {NetworkProtocolHandler, NetworkConfiguration, NonReservedPeerMode};
use error::NetworkError;
use host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use stats::NetworkStats;
use io::*;
use parking_lot::RwLock;
use std::sync::Arc;
@@ -55,7 +53,7 @@ pub struct NetworkService {
impl NetworkService {
/// Starts IO event loop
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, UtilError> {
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, NetworkError> {
let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None) });
let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<NetworkIoMessage>::start());
@@ -117,7 +115,7 @@ impl NetworkService {
}
/// Start network IO
pub fn start(&self) -> Result<(), UtilError> {
pub fn start(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if host.is_none() {
let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone())));
@@ -133,7 +131,7 @@ impl NetworkService {
}
/// Stop network IO
pub fn stop(&self) -> Result<(), UtilError> {
pub fn stop(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if let Some(ref host) = *host {
let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host
@@ -144,7 +142,7 @@ impl NetworkService {
}
/// Try to add a reserved peer.
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), UtilError> {
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.add_reserved_node(peer)
@@ -154,7 +152,7 @@ impl NetworkService {
}
/// Try to remove a reserved peer.
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), UtilError> {
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.remove_reserved_node(peer)
@@ -164,7 +162,7 @@ impl NetworkService {
}
/// Set the non-reserved peer mode.
pub fn set_non_reserved_mode(&self, mode: ::network::NonReservedPeerMode) {
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode) {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);

View File

@@ -19,16 +19,15 @@ use std::io;
use std::sync::*;
use mio::*;
use mio::tcp::*;
use rlp::*;
use hash::*;
use network::connection::{EncryptedConnection, Packet, Connection};
use network::handshake::Handshake;
use error::*;
use util::rlp::*;
use util::hash::*;
use connection::{EncryptedConnection, Packet, Connection};
use handshake::Handshake;
use io::{IoContext, StreamToken};
use network::error::{NetworkError, DisconnectReason};
use network::host::*;
use network::node_table::NodeId;
use network::stats::NetworkStats;
use error::{NetworkError, DisconnectReason};
use host::*;
use node_table::NodeId;
use stats::NetworkStats;
use time;
const PING_TIMEOUT_SEC: u64 = 30;
@@ -125,7 +124,7 @@ impl Session {
/// Create a new session out of comepleted handshake. This clones the handshake connection object
/// and leaves the handhsake in limbo to be deregistered from the event loop.
pub fn new<Message>(io: &IoContext<Message>, socket: TcpStream, token: StreamToken, id: Option<&NodeId>,
nonce: &H256, stats: Arc<NetworkStats>, host: &HostInfo) -> Result<Session, UtilError>
nonce: &H256, stats: Arc<NetworkStats>, host: &HostInfo) -> Result<Session, NetworkError>
where Message: Send + Clone {
let originated = id.is_some();
let mut handshake = Handshake::new(token, id, socket, nonce, stats).expect("Can't create handshake");
@@ -147,7 +146,7 @@ impl Session {
})
}
fn complete_handshake<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), UtilError> where Message: Send + Sync + Clone {
fn complete_handshake<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
let connection = if let State::Handshake(ref mut h) = self.state {
self.info.id = Some(h.id.clone());
try!(EncryptedConnection::new(h))
@@ -201,7 +200,7 @@ impl Session {
}
/// Readable IO handler. Returns packet data if available.
pub fn readable<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<SessionData, UtilError> where Message: Send + Sync + Clone {
pub fn readable<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<SessionData, NetworkError> where Message: Send + Sync + Clone {
if self.expired() {
return Ok(SessionData::None)
}
@@ -232,7 +231,7 @@ impl Session {
}
/// Writable IO handler. Sends pending packets.
pub fn writable<Message>(&mut self, io: &IoContext<Message>, _host: &HostInfo) -> Result<(), UtilError> where Message: Send + Sync + Clone {
pub fn writable<Message>(&mut self, io: &IoContext<Message>, _host: &HostInfo) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
match self.state {
State::Handshake(ref mut h) => h.writable(io),
State::Session(ref mut s) => s.writable(io),
@@ -245,7 +244,7 @@ impl Session {
}
/// Register the session socket with the event loop
pub fn register_socket<Host:Handler<Timeout = Token>>(&self, reg: Token, event_loop: &mut EventLoop<Host>) -> Result<(), UtilError> {
pub fn register_socket<Host:Handler<Timeout = Token>>(&self, reg: Token, event_loop: &mut EventLoop<Host>) -> Result<(), NetworkError> {
if self.expired() {
return Ok(());
}
@@ -254,19 +253,19 @@ impl Session {
}
/// Update registration with the event loop. Should be called at the end of the IO handler.
pub fn update_socket<Host:Handler>(&self, reg:Token, event_loop: &mut EventLoop<Host>) -> Result<(), UtilError> {
pub fn update_socket<Host:Handler>(&self, reg:Token, event_loop: &mut EventLoop<Host>) -> Result<(), NetworkError> {
try!(self.connection().update_socket(reg, event_loop));
Ok(())
}
/// Delete registration
pub fn deregister_socket<Host:Handler>(&self, event_loop: &mut EventLoop<Host>) -> Result<(), UtilError> {
pub fn deregister_socket<Host:Handler>(&self, event_loop: &mut EventLoop<Host>) -> Result<(), NetworkError> {
try!(self.connection().deregister_socket(event_loop));
Ok(())
}
/// Send a protocol packet to peer.
pub fn send_packet<Message>(&mut self, io: &IoContext<Message>, protocol: &str, packet_id: u8, data: &[u8]) -> Result<(), UtilError>
pub fn send_packet<Message>(&mut self, io: &IoContext<Message>, protocol: &str, packet_id: u8, data: &[u8]) -> Result<(), NetworkError>
where Message: Send + Sync + Clone {
if self.info.capabilities.is_empty() || !self.had_hello {
debug!(target: "network", "Sending to unconfirmed session {}, protocol: {}, packet: {}", self.token(), protocol, packet_id);
@@ -313,7 +312,7 @@ impl Session {
self.connection().token()
}
fn read_packet<Message>(&mut self, io: &IoContext<Message>, packet: Packet, host: &HostInfo) -> Result<SessionData, UtilError>
fn read_packet<Message>(&mut self, io: &IoContext<Message>, packet: Packet, host: &HostInfo) -> Result<SessionData, NetworkError>
where Message: Send + Sync + Clone {
if packet.data.len() < 2 {
return Err(From::from(NetworkError::BadProtocol));
@@ -369,7 +368,7 @@ impl Session {
}
}
fn write_hello<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), UtilError> where Message: Send + Sync + Clone {
fn write_hello<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
let mut rlp = RlpStream::new();
rlp.append_raw(&[PACKET_HELLO as u8], 0);
rlp.begin_list(5)
@@ -381,7 +380,7 @@ impl Session {
self.send(io, rlp)
}
fn read_hello<Message>(&mut self, io: &IoContext<Message>, rlp: &UntrustedRlp, host: &HostInfo) -> Result<(), UtilError>
fn read_hello<Message>(&mut self, io: &IoContext<Message>, rlp: &UntrustedRlp, host: &HostInfo) -> Result<(), NetworkError>
where Message: Send + Sync + Clone {
let protocol = try!(rlp.val_at::<u32>(0));
let client_version = try!(rlp.val_at::<String>(1));
@@ -436,14 +435,14 @@ impl Session {
}
/// Senf ping packet
pub fn send_ping<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Sync + Clone {
pub fn send_ping<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
try!(self.send(io, try!(Session::prepare(PACKET_PING))));
self.ping_time_ns = time::precise_time_ns();
self.pong_time_ns = None;
Ok(())
}
fn send_pong<Message>(&mut self, io: &IoContext<Message>) -> Result<(), UtilError> where Message: Send + Sync + Clone {
fn send_pong<Message>(&mut self, io: &IoContext<Message>) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
self.send(io, try!(Session::prepare(PACKET_PONG)))
}
@@ -459,14 +458,14 @@ impl Session {
NetworkError::Disconnect(reason)
}
fn prepare(packet_id: u8) -> Result<RlpStream, UtilError> {
fn prepare(packet_id: u8) -> Result<RlpStream, NetworkError> {
let mut rlp = RlpStream::new();
rlp.append(&(packet_id as u32));
rlp.begin_list(0);
Ok(rlp)
}
fn send<Message>(&mut self, io: &IoContext<Message>, rlp: RlpStream) -> Result<(), UtilError> where Message: Send + Sync + Clone {
fn send<Message>(&mut self, io: &IoContext<Message>, rlp: RlpStream) -> Result<(), NetworkError> where Message: Send + Sync + Clone {
match self.state {
State::Handshake(_) => {
warn!(target:"network", "Unexpected send request");

View File

@@ -14,13 +14,13 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::thread;
use std::time::*;
use common::*;
use network::*;
use util::common::*;
use io::TimerToken;
use crypto::KeyPair;
use util::crypto::KeyPair;
pub struct TestProtocol {
drop_session: bool,
@@ -98,7 +98,7 @@ fn net_service() {
#[test]
fn net_connect() {
::log::init_log();
::util::log::init_log();
let key1 = KeyPair::create().unwrap();
let mut config1 = NetworkConfiguration::new_local();
config1.use_secret = Some(key1.secret().clone());

View File

@@ -17,9 +17,7 @@
//! General error types for use in ethcore.
use rustc_serialize::hex::FromHexError;
use network::NetworkError;
use rlp::DecoderError;
use io;
use std::fmt;
use hash::H256;
@@ -50,18 +48,10 @@ pub enum UtilError {
Crypto(::crypto::CryptoError),
/// Error concerning the Rust standard library's IO subsystem.
StdIo(::std::io::Error),
/// Error concerning our IO utility subsystem.
Io(io::IoError),
/// Error concerning the network address parsing subsystem.
AddressParse(::std::net::AddrParseError),
/// Error concerning the network address resolution subsystem.
AddressResolve(Option<::std::io::Error>),
/// Error concerning the hex conversion logic.
FromHex(FromHexError),
/// Error concerning the database abstraction logic.
BaseData(BaseDataError),
/// Error concerning the network subsystem.
Network(NetworkError),
/// Error concerning the RLP decoder.
Decoder(DecoderError),
/// Miscellaneous error described by a string.
@@ -77,13 +67,8 @@ impl fmt::Display for UtilError {
match *self {
UtilError::Crypto(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::StdIo(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::Io(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::AddressParse(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::AddressResolve(Some(ref err)) => f.write_fmt(format_args!("{}", err)),
UtilError::AddressResolve(_) => f.write_str("Failed to resolve network address."),
UtilError::FromHex(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::BaseData(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::Network(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::Decoder(ref err) => f.write_fmt(format_args!("{}", err)),
UtilError::SimpleString(ref msg) => f.write_str(msg),
UtilError::BadSize => f.write_str("Bad input size."),
@@ -143,36 +128,18 @@ impl From<BaseDataError> for UtilError {
}
}
impl From<NetworkError> for UtilError {
fn from(err: NetworkError) -> UtilError {
UtilError::Network(err)
}
}
impl From<::std::io::Error> for UtilError {
fn from(err: ::std::io::Error) -> UtilError {
UtilError::StdIo(err)
}
}
impl From<io::IoError> for UtilError {
fn from(err: io::IoError) -> UtilError {
UtilError::Io(err)
}
}
impl From<::crypto::CryptoError> for UtilError {
fn from(err: ::crypto::CryptoError) -> UtilError {
UtilError::Crypto(err)
}
}
impl From<::std::net::AddrParseError> for UtilError {
fn from(err: ::std::net::AddrParseError) -> UtilError {
UtilError::AddressParse(err)
}
}
impl From<::rlp::DecoderError> for UtilError {
fn from(err: ::rlp::DecoderError) -> UtilError {
UtilError::Decoder(err)

View File

@@ -85,12 +85,9 @@
//! cargo build --release
//! ```
extern crate slab;
extern crate rustc_serialize;
extern crate mio;
extern crate rand;
extern crate rocksdb;
extern crate tiny_keccak;
#[macro_use]
extern crate heapsize;
#[macro_use]
@@ -98,20 +95,17 @@ extern crate lazy_static;
#[macro_use]
extern crate itertools;
extern crate env_logger;
extern crate time;
extern crate crypto as rcrypto;
extern crate secp256k1;
extern crate arrayvec;
extern crate elastic_array;
extern crate crossbeam;
#[macro_use]
extern crate log as rlog;
extern crate igd;
extern crate time;
extern crate ethcore_devtools as devtools;
extern crate libc;
extern crate target_info;
extern crate bigint;
extern crate chrono;
extern crate parking_lot;
pub extern crate using_queue;
pub extern crate table;
@@ -141,11 +135,7 @@ pub mod trie;
pub mod nibbleslice;
pub mod nibblevec;
pub mod semantic_version;
pub mod io;
pub mod network;
pub mod log;
pub mod panics;
pub mod network_settings;
pub mod path;
pub mod snappy;
mod timer;
@@ -162,8 +152,6 @@ pub use triehash::*;
pub use trie::{Trie, TrieMut, TrieDB, TrieDBMut, TrieFactory, TrieError, SecTrieDB, SecTrieDBMut};
pub use nibbleslice::*;
pub use semantic_version::*;
pub use network::*;
pub use io::*;
pub use log::*;
pub use kvdb::*;
pub use timer::*;

View File

@@ -1,52 +0,0 @@
// 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/>.
//! Structure to hold network settings configured from CLI
/// Networking & RPC settings
#[derive(Debug, PartialEq, Clone)]
pub struct NetworkSettings {
/// Node name
pub name: String,
/// Name of the chain we are connected to
pub chain: String,
/// Min number of peers
pub min_peers: u32,
/// Max number of peers
pub max_peers: u32,
/// Networking port
pub network_port: u16,
/// Is JSON-RPC server enabled?
pub rpc_enabled: bool,
/// Interface that JSON-RPC listens on
pub rpc_interface: String,
/// Port for JSON-RPC server
pub rpc_port: u16,
}
impl Default for NetworkSettings {
fn default() -> Self {
NetworkSettings {
name: "".into(),
chain: "homestead".into(),
min_peers: 25,
max_peers: 50,
network_port: 30303,
rpc_enabled: true,
rpc_interface: "local".into(),
rpc_port: 8545
}
}
}