[devp2p] Update to 2018 edition (#10716)

* Run cargo fix

* Optimize imports

* compiles

* cleanup

* Use Secret to store mac-key
Truncate payload properly

* cleanup

* Reorg imports

* brwchk hand waving

* Fix a bunch of imports

* Fixup imports

* Sort

* indentation

* WIP

* Revert "WIP"

This reverts commit 85f7e74f4bd1990db865cf6acfa8d494798eeeaa.

* inclusive range pattern syntax is changing

* remove usless todo
This commit is contained in:
David 2019-06-19 12:20:50 +02:00 committed by GitHub
parent d2120ded56
commit 859a41308c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 131 additions and 168 deletions

24
Cargo.lock generated
View File

@ -1149,10 +1149,8 @@ dependencies = [
"parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.39 (registry+https://github.com/rust-lang/crates.io-index)",
"slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "slab 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)",
"tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", "tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
@ -1607,11 +1605,6 @@ dependencies = [
"byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.6 (registry+https://github.com/rust-lang/crates.io-index)",
] ]
[[package]]
name = "gcc"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.9.0" version = "0.9.0"
@ -3665,18 +3658,6 @@ name = "rprompt"
version = "1.0.3" version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "rust-crypto"
version = "0.2.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)",
"libc 0.2.48 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)",
"time 0.1.40 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "rustc-demangle" name = "rustc-demangle"
version = "0.1.9" version = "0.1.9"
@ -3790,6 +3771,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
name = "serde" name = "serde"
version = "1.0.89" version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"serde_derive 1.0.89 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
@ -4889,7 +4873,6 @@ dependencies = [
"checksum futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)" = "49e7653e374fe0d0c12de4250f0bdb60680b8c80eed558c5c7538eec9c89e21b" "checksum futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)" = "49e7653e374fe0d0c12de4250f0bdb60680b8c80eed558c5c7538eec9c89e21b"
"checksum futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4" "checksum futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4"
"checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
"checksum gcc 0.3.55 (registry+https://github.com/rust-lang/crates.io-index)" = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
"checksum generic-array 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0f28c2f5bfb5960175af447a2da7c18900693738343dc896ffbcabd9839592" "checksum generic-array 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c0f28c2f5bfb5960175af447a2da7c18900693738343dc896ffbcabd9839592"
"checksum generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d" "checksum generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d"
"checksum getopts 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "0a7292d30132fb5424b354f5dc02512a86e4c516fe544bb7a25e7f266951b797" "checksum getopts 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "0a7292d30132fb5424b354f5dc02512a86e4c516fe544bb7a25e7f266951b797"
@ -5062,7 +5045,6 @@ dependencies = [
"checksum rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3b0d56c1450bfbef1181fdeb78b902dc1d23178de77c23d705317508e03d1b7c" "checksum rlp 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3b0d56c1450bfbef1181fdeb78b902dc1d23178de77c23d705317508e03d1b7c"
"checksum rpassword 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b273c91bd242ca03ad6d71c143b6f17a48790e61f21a6c78568fa2b6774a24a4" "checksum rpassword 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b273c91bd242ca03ad6d71c143b6f17a48790e61f21a6c78568fa2b6774a24a4"
"checksum rprompt 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1601f32bc5858aae3cbfa1c645c96c4d820cc5c16be0194f089560c00b6eb625" "checksum rprompt 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1601f32bc5858aae3cbfa1c645c96c4d820cc5c16be0194f089560c00b6eb625"
"checksum rust-crypto 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)" = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a"
"checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395" "checksum rustc-demangle 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "bcfe5b13211b4d78e5c2cadfebd7769197d95c639c35a50057eb4c05de811395"
"checksum rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0ceb8ce7a5e520de349e1fa172baeba4a9e8d5ef06c47471863530bc4972ee1e" "checksum rustc-hex 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0ceb8ce7a5e520de349e1fa172baeba4a9e8d5ef06c47471863530bc4972ee1e"
"checksum rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "403bb3a286107a04825a5f82e1270acc1e14028d3d554d7a1e08914549575ab8" "checksum rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "403bb3a286107a04825a5f82e1270acc1e14028d3d554d7a1e08914549575ab8"

View File

@ -5,6 +5,7 @@ license = "GPL-3.0"
name = "ethcore-network-devp2p" name = "ethcore-network-devp2p"
version = "1.12.0" version = "1.12.0"
authors = ["Parity Technologies <admin@parity.io>"] authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
[dependencies] [dependencies]
log = "0.4" log = "0.4"
@ -12,7 +13,6 @@ mio = "0.6.8"
bytes = "0.4" bytes = "0.4"
rand = "0.6" rand = "0.6"
tiny-keccak = "1.4" tiny-keccak = "1.4"
rust-crypto = "0.2.34"
slab = "0.2" slab = "0.2"
igd = "0.7" igd = "0.7"
libc = "0.2.7" libc = "0.2.7"
@ -21,8 +21,8 @@ ansi_term = "0.10"
rustc-hex = "1.0" rustc-hex = "1.0"
ethcore-io = { path = "../io", features = ["mio"] } ethcore-io = { path = "../io", features = ["mio"] }
parity-bytes = "0.1" parity-bytes = "0.1"
parity-crypto = "0.4.0" crypto = { package = "parity-crypto", version = "0.4.0"}
ethcore-network = { path = "../network" } network = { package = "ethcore-network", path = "../network" }
ethereum-types = "0.6.0" ethereum-types = "0.6.0"
ethkey = { path = "../../accounts/ethkey" } ethkey = { path = "../../accounts/ethkey" }
rlp = "0.4.0" rlp = "0.4.0"
@ -30,9 +30,8 @@ parity-path = "0.1"
ipnetwork = "0.12.6" ipnetwork = "0.12.6"
keccak-hash = "0.2.0" keccak-hash = "0.2.0"
parity-snappy = "0.1" parity-snappy = "0.1"
serde = "1.0" serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
serde_derive = "1.0"
error-chain = { version = "0.12", default-features = false } error-chain = { version = "0.12", default-features = false }
lru-cache = "0.1" lru-cache = "0.1"

View File

@ -21,21 +21,23 @@ use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::time::Duration; use std::time::Duration;
use bytes::{Buf, BufMut}; use bytes::{Buf, BufMut};
use crypto::aes::{AesCtr256, AesEcb256};
use ethereum_types::{H128, H256, H512}; use ethereum_types::{H128, H256, H512};
use hash::{keccak, write_keccak}; use keccak_hash::{keccak, write_keccak};
use log::{debug, trace, warn};
use mio::{PollOpt, Ready, Token}; use mio::{PollOpt, Ready, Token};
use mio::deprecated::{EventLoop, Handler, TryRead, TryWrite}; use mio::deprecated::{EventLoop, Handler, TryRead, TryWrite};
use mio::tcp::*; use mio::tcp::TcpStream;
use parity_bytes::*; use parity_bytes::Bytes;
use crypto::aes::{AesCtr256, AesEcb256};
use rlp::{Rlp, RlpStream}; use rlp::{Rlp, RlpStream};
use tiny_keccak::Keccak; use tiny_keccak::Keccak;
use ethkey::{crypto, Secret}; use ethcore_io::{IoContext, StreamToken};
use handshake::Handshake; use ethkey::{crypto as ethcrypto, Secret};
use io::{IoContext, StreamToken};
use network::Error; use network::Error;
use crate::handshake::Handshake;
const ENCRYPTED_HEADER_LEN: usize = 32; const ENCRYPTED_HEADER_LEN: usize = 32;
const RECEIVE_PAYLOAD: Duration = Duration::from_secs(30); const RECEIVE_PAYLOAD: Duration = Duration::from_secs(30);
pub const MAX_PAYLOAD_SIZE: usize = (1 << 24) - 1; pub const MAX_PAYLOAD_SIZE: usize = (1 << 24) - 1;
@ -297,7 +299,7 @@ const NULL_IV : [u8; 16] = [0;16];
impl EncryptedConnection { impl EncryptedConnection {
/// Create an encrypted connection out of the handshake. /// Create an encrypted connection out of the handshake.
pub fn new(handshake: &mut Handshake) -> Result<EncryptedConnection, Error> { pub fn new(handshake: &mut Handshake) -> Result<EncryptedConnection, Error> {
let shared = crypto::ecdh::agree(handshake.ecdhe.secret(), &handshake.remote_ephemeral)?; let shared = ethcrypto::ecdh::agree(handshake.ecdhe.secret(), &handshake.remote_ephemeral)?;
let mut nonce_material = H512::default(); let mut nonce_material = H512::default();
if handshake.originated { if handshake.originated {
(&mut nonce_material[0..32]).copy_from_slice(handshake.remote_nonce.as_bytes()); (&mut nonce_material[0..32]).copy_from_slice(handshake.remote_nonce.as_bytes());
@ -391,13 +393,11 @@ impl EncryptedConnection {
return Err(Error::Auth); return Err(Error::Auth);
} }
EncryptedConnection::update_mac(&mut self.ingress_mac, &self.mac_encoder_key, &header[0..16])?; EncryptedConnection::update_mac(&mut self.ingress_mac, &self.mac_encoder_key, &header[0..16])?;
{ let mac = &header[16..];
let mac = &header[16..]; let mut expected = H256::zero();
let mut expected = H256::zero(); self.ingress_mac.clone().finalize(expected.as_bytes_mut());
self.ingress_mac.clone().finalize(expected.as_bytes_mut()); if mac != &expected[0..16] {
if mac != &expected[0..16] { return Err(Error::Auth);
return Err(Error::Auth);
}
} }
self.decoder.decrypt(&mut header[..16])?; self.decoder.decrypt(&mut header[..16])?;
@ -426,13 +426,11 @@ impl EncryptedConnection {
self.ingress_mac.update(&payload[0..payload.len() - 16]); self.ingress_mac.update(&payload[0..payload.len() - 16]);
EncryptedConnection::update_mac(&mut self.ingress_mac, &self.mac_encoder_key, &[0u8; 0])?; EncryptedConnection::update_mac(&mut self.ingress_mac, &self.mac_encoder_key, &[0u8; 0])?;
{ let mac = &payload[(payload.len() - 16)..];
let mac = &payload[(payload.len() - 16)..]; let mut expected = H128::default();
let mut expected = H128::default(); self.ingress_mac.clone().finalize(expected.as_bytes_mut());
self.ingress_mac.clone().finalize(expected.as_bytes_mut()); if mac != &expected[..] {
if mac != &expected[..] { return Err(Error::Auth);
return Err(Error::Auth);
}
} }
self.decoder.decrypt(&mut payload[..self.payload_len + padding])?; self.decoder.decrypt(&mut payload[..self.payload_len + padding])?;
payload.truncate(self.payload_len); payload.truncate(self.payload_len);
@ -496,7 +494,7 @@ mod tests {
use mio::Ready; use mio::Ready;
use parity_bytes::Bytes; use parity_bytes::Bytes;
use io::*; use ethcore_io::*;
use super::*; use super::*;

View File

@ -21,7 +21,8 @@ use std::net::SocketAddr;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use ethereum_types::{H256, H520}; use ethereum_types::{H256, H520};
use hash::keccak; use keccak_hash::keccak;
use log::{debug, trace, warn};
use lru_cache::LruCache; use lru_cache::LruCache;
use parity_bytes::Bytes; use parity_bytes::Bytes;
use rlp::{Rlp, RlpStream}; use rlp::{Rlp, RlpStream};
@ -29,8 +30,9 @@ use rlp::{Rlp, RlpStream};
use ethkey::{KeyPair, recover, Secret, sign}; use ethkey::{KeyPair, recover, Secret, sign};
use network::Error; use network::Error;
use network::IpFilter; use network::IpFilter;
use node_table::*;
use PROTOCOL_VERSION; use crate::node_table::*;
use crate::PROTOCOL_VERSION;
const ADDRESS_BYTES_SIZE: usize = 32; // Size of address type in bytes. const ADDRESS_BYTES_SIZE: usize = 32; // Size of address type in bytes.
const ADDRESS_BITS: usize = 8 * ADDRESS_BYTES_SIZE; // Denoted by n in [Kademlia]. const ADDRESS_BITS: usize = 8 * ADDRESS_BYTES_SIZE; // Denoted by n in [Kademlia].
@ -900,7 +902,8 @@ mod tests {
use rustc_hex::FromHex; use rustc_hex::FromHex;
use ethkey::{Generator, Random}; use ethkey::{Generator, Random};
use node_table::{Node, NodeEndpoint, NodeId};
use crate::node_table::{Node, NodeEndpoint, NodeId};
use super::*; use super::*;

View File

@ -17,19 +17,21 @@
use std::time::Duration; use std::time::Duration;
use ethereum_types::{H256, H520}; use ethereum_types::{H256, H520};
use hash::write_keccak; use keccak_hash::write_keccak;
use log::{debug, trace};
use mio::tcp::*; use mio::tcp::*;
use parity_bytes::Bytes; use parity_bytes::Bytes;
use rand::random; use rand::random;
use rlp::{Rlp, RlpStream}; use rlp::{Rlp, RlpStream};
use connection::Connection; use ethcore_io::{IoContext, StreamToken};
use ethkey::{Generator, KeyPair, Public, Random, recover, Secret, sign}; use ethkey::{Generator, KeyPair, Public, Random, recover, Secret, sign};
use ethkey::crypto::{ecdh, ecies}; use ethkey::crypto::{ecdh, ecies};
use host::HostInfo;
use io::{IoContext, StreamToken};
use network::Error; use network::Error;
use node_table::NodeId;
use crate::connection::Connection;
use crate::host::HostInfo;
use crate::node_table::NodeId;
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug)]
enum HandshakeState { enum HandshakeState {
@ -320,18 +322,18 @@ impl Handshake {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::str::FromStr; use std::str::FromStr;
use ethereum_types::{H256, H512}; use ethereum_types::{H256, H512};
use mio::tcp::TcpStream; use mio::tcp::TcpStream;
use rustc_hex::FromHex; use rustc_hex::FromHex;
use ethkey::Public; use ethcore_io::*;
use io::*; use ethkey::Public;
use super::*; use super::*;
fn check_auth(h: &Handshake, version: u64) { fn check_auth(h: &Handshake, version: u64) {
assert_eq!( assert_eq!(
h.id, h.id,
H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap(), H512::from_str("fda1cff674c90c9a197539fe3dfb53086ace64f83ed7c6eabec741f7f381cc803e52ab2cd55d5569bce4347107a310dfd5f88a010cd2ffd1005ca406f1842877").unwrap(),

View File

@ -27,29 +27,34 @@ use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::time::Duration; use std::time::Duration;
use ethereum_types::H256; use ethereum_types::H256;
use hash::keccak; use keccak_hash::keccak;
use mio::*; use log::{debug, info, trace, warn};
use mio::deprecated::EventLoop; use mio::{
use mio::tcp::*; deprecated::EventLoop, PollOpt, Ready, tcp::{TcpListener, TcpStream},
use mio::udp::*; Token,
udp::UdpSocket
};
use parity_path::restrict_permissions_owner; use parity_path::restrict_permissions_owner;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use rlp::{Encodable, RlpStream}; use rlp::{Encodable, RlpStream};
use rustc_hex::ToHex; use rustc_hex::ToHex;
use connection::PAYLOAD_SOFT_LIMIT; use ethcore_io::{IoContext, IoHandler, IoManager, StreamToken, TimerToken};
use discovery::{Discovery, MAX_DATAGRAM_SIZE, NodeEntry, TableUpdates};
use ethkey::{Generator, KeyPair, Random, Secret}; use ethkey::{Generator, KeyPair, Random, Secret};
use io::*; use network::{
use ip_utils::{map_external_address, select_public_address}; client_version::ClientVersion, ConnectionDirection, ConnectionFilter, DisconnectReason, Error,
use network::{NetworkConfiguration, NetworkIoMessage, PacketId, PeerId, ProtocolId}; NetworkConfiguration, NetworkContext as NetworkContextTrait, NetworkIoMessage, NetworkProtocolHandler,
use network::{NetworkContext as NetworkContextTrait, NonReservedPeerMode}; NonReservedPeerMode, PacketId, PeerId, ProtocolId, SessionInfo
use network::{DisconnectReason, Error, NetworkProtocolHandler, SessionInfo}; };
use network::{ConnectionDirection, ConnectionFilter};
use network::client_version::ClientVersion; use crate::{
use node_table::*; connection::PAYLOAD_SOFT_LIMIT,
use PROTOCOL_VERSION; discovery::{Discovery, MAX_DATAGRAM_SIZE, NodeEntry, TableUpdates},
use session::{Session, SessionData}; ip_utils::{map_external_address, select_public_address},
node_table::*,
PROTOCOL_VERSION,
session::{Session, SessionData}
};
type Slab<T> = ::slab::Slab<T, usize>; type Slab<T> = ::slab::Slab<T, usize>;
@ -263,17 +268,17 @@ pub struct Host {
sessions: Arc<RwLock<Slab<SharedSession>>>, sessions: Arc<RwLock<Slab<SharedSession>>>,
discovery: Mutex<Option<Discovery<'static>>>, discovery: Mutex<Option<Discovery<'static>>>,
nodes: RwLock<NodeTable>, nodes: RwLock<NodeTable>,
handlers: RwLock<HashMap<ProtocolId, Arc<NetworkProtocolHandler + Sync>>>, handlers: RwLock<HashMap<ProtocolId, Arc<dyn NetworkProtocolHandler + Sync>>>,
timers: RwLock<HashMap<TimerToken, ProtocolTimer>>, timers: RwLock<HashMap<TimerToken, ProtocolTimer>>,
timer_counter: RwLock<usize>, timer_counter: RwLock<usize>,
reserved_nodes: RwLock<HashSet<NodeId>>, reserved_nodes: RwLock<HashSet<NodeId>>,
stopping: AtomicBool, stopping: AtomicBool,
filter: Option<Arc<ConnectionFilter>>, filter: Option<Arc<dyn ConnectionFilter>>,
} }
impl Host { impl Host {
/// Create a new instance /// Create a new instance
pub fn new(mut config: NetworkConfiguration, filter: Option<Arc<ConnectionFilter>>) -> Result<Host, Error> { pub fn new(mut config: NetworkConfiguration, filter: Option<Arc<dyn ConnectionFilter>>) -> Result<Host, Error> {
let mut listen_address = match config.listen_address { let mut listen_address = match config.listen_address {
None => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), DEFAULT_PORT)), None => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), DEFAULT_PORT)),
Some(addr) => addr, Some(addr) => addr,
@ -924,7 +929,7 @@ impl Host {
let mut failure_id = None; let mut failure_id = None;
let mut deregister = false; let mut deregister = false;
let mut expired_session = None; let mut expired_session = None;
if let FIRST_SESSION ... LAST_SESSION = token { if let FIRST_SESSION ..= LAST_SESSION = token {
let sessions = self.sessions.read(); let sessions = self.sessions.read();
if let Some(session) = sessions.get(token).cloned() { if let Some(session) = sessions.get(token).cloned() {
expired_session = Some(session.clone()); expired_session = Some(session.clone());
@ -978,14 +983,14 @@ impl Host {
self.nodes.write().update(node_changes, &*self.reserved_nodes.read()); self.nodes.write().update(node_changes, &*self.reserved_nodes.read());
} }
pub fn with_context<F>(&self, protocol: ProtocolId, io: &IoContext<NetworkIoMessage>, action: F) where F: FnOnce(&NetworkContextTrait) { pub fn with_context<F>(&self, protocol: ProtocolId, io: &IoContext<NetworkIoMessage>, action: F) where F: FnOnce(&dyn NetworkContextTrait) {
let reserved = { self.reserved_nodes.read() }; let reserved = { self.reserved_nodes.read() };
let context = NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved); let context = NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved);
action(&context); action(&context);
} }
pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, io: &IoContext<NetworkIoMessage>, action: F) -> T where F: FnOnce(&NetworkContextTrait) -> T { pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, io: &IoContext<NetworkIoMessage>, action: F) -> T where F: FnOnce(&dyn NetworkContextTrait) -> T {
let reserved = { self.reserved_nodes.read() }; let reserved = { self.reserved_nodes.read() };
let context = NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved); let context = NetworkContext::new(io, protocol, None, self.sessions.clone(), &reserved);
@ -1004,7 +1009,7 @@ impl IoHandler<NetworkIoMessage> for Host {
fn stream_hup(&self, io: &IoContext<NetworkIoMessage>, stream: StreamToken) { fn stream_hup(&self, io: &IoContext<NetworkIoMessage>, stream: StreamToken) {
trace!(target: "network", "Hup: {}", stream); trace!(target: "network", "Hup: {}", stream);
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => self.connection_closed(stream, io), FIRST_SESSION ..= LAST_SESSION => self.connection_closed(stream, io),
_ => warn!(target: "network", "Unexpected hup"), _ => warn!(target: "network", "Unexpected hup"),
}; };
} }
@ -1014,7 +1019,7 @@ impl IoHandler<NetworkIoMessage> for Host {
return; return;
} }
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => self.session_readable(stream, io), FIRST_SESSION ..= LAST_SESSION => self.session_readable(stream, io),
DISCOVERY => self.discovery_readable(io), DISCOVERY => self.discovery_readable(io),
TCP_ACCEPT => self.accept(io), TCP_ACCEPT => self.accept(io),
_ => panic!("Received unknown readable token"), _ => panic!("Received unknown readable token"),
@ -1026,7 +1031,7 @@ impl IoHandler<NetworkIoMessage> for Host {
return; return;
} }
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => self.session_writable(stream, io), FIRST_SESSION ..= LAST_SESSION => self.session_writable(stream, io),
DISCOVERY => self.discovery_writable(io), DISCOVERY => self.discovery_writable(io),
_ => panic!("Received unknown writable token"), _ => panic!("Received unknown writable token"),
} }
@ -1038,7 +1043,7 @@ impl IoHandler<NetworkIoMessage> for Host {
} }
match token { match token {
IDLE => self.maintain_network(io), IDLE => self.maintain_network(io),
FIRST_SESSION ... LAST_SESSION => self.connection_timeout(token, io), FIRST_SESSION ..= LAST_SESSION => self.connection_timeout(token, io),
DISCOVERY_REFRESH => { DISCOVERY_REFRESH => {
// Run the _slow_ discovery if enough peers are connected // Run the _slow_ discovery if enough peers are connected
if !self.has_enough_peers() { if !self.has_enough_peers() {
@ -1146,7 +1151,7 @@ impl IoHandler<NetworkIoMessage> for Host {
fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) { fn register_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) {
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => { FIRST_SESSION ..= LAST_SESSION => {
let session = { self.sessions.read().get(stream).cloned() }; let session = { self.sessions.read().get(stream).cloned() };
if let Some(session) = session { if let Some(session) = session {
session.lock().register_socket(reg, event_loop).expect("Error registering socket"); session.lock().register_socket(reg, event_loop).expect("Error registering socket");
@ -1166,7 +1171,7 @@ impl IoHandler<NetworkIoMessage> for Host {
fn deregister_stream(&self, stream: StreamToken, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) { fn deregister_stream(&self, stream: StreamToken, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) {
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => { FIRST_SESSION ..= LAST_SESSION => {
let mut connections = self.sessions.write(); let mut connections = self.sessions.write();
if let Some(connection) = connections.get(stream).cloned() { if let Some(connection) = connections.get(stream).cloned() {
let c = connection.lock(); let c = connection.lock();
@ -1183,7 +1188,7 @@ impl IoHandler<NetworkIoMessage> for Host {
fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) { fn update_stream(&self, stream: StreamToken, reg: Token, event_loop: &mut EventLoop<IoManager<NetworkIoMessage>>) {
match stream { match stream {
FIRST_SESSION ... LAST_SESSION => { FIRST_SESSION ..= LAST_SESSION => {
let connection = { self.sessions.read().get(stream).cloned() }; let connection = { self.sessions.read().get(stream).cloned() };
if let Some(connection) = connection { if let Some(connection) = connection {
connection.lock().update_socket(reg, event_loop).expect("Error updating socket"); connection.lock().update_socket(reg, event_loop).expect("Error updating socket");

View File

@ -22,8 +22,9 @@ use std::time::Duration;
use igd::{PortMappingProtocol, search_gateway_from_timeout}; use igd::{PortMappingProtocol, search_gateway_from_timeout};
use ipnetwork::IpNetwork; use ipnetwork::IpNetwork;
use log::debug;
use node_table::NodeEndpoint; use crate::node_table::NodeEndpoint;
/// Socket address extension for rustc beta. To be replaces with now unstable API /// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt { pub trait SocketAddrExt {
@ -214,13 +215,13 @@ impl SocketAddrExt for IpAddr {
#[cfg(not(any(windows, target_os = "android")))] #[cfg(not(any(windows, target_os = "android")))]
mod getinterfaces { mod getinterfaces {
use std::{io, mem}; use std::{io, mem};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use libc::{AF_INET, AF_INET6}; use libc::{AF_INET, AF_INET6};
use libc::{freeifaddrs, getifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6}; use libc::{freeifaddrs, getifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
fn convert_sockaddr(sa: *mut sockaddr) -> Option<IpAddr> { fn convert_sockaddr(sa: *mut sockaddr) -> Option<IpAddr> {
if sa.is_null() { return None; } if sa.is_null() { return None; }
let (addr, _) = match i32::from(unsafe { *sa }.sa_family) { let (addr, _) = match i32::from(unsafe { *sa }.sa_family) {

View File

@ -19,7 +19,7 @@
//! Example usage for creating a network service and adding an IO handler: //! Example usage for creating a network service and adding an IO handler:
//! //!
//! ```rust //! ```rust
//! extern crate ethcore_network as net; //! extern crate network as net;
//! extern crate ethcore_network_devp2p as devp2p; //! extern crate ethcore_network_devp2p as devp2p;
//! use net::*; //! use net::*;
//! use devp2p::NetworkService; //! use devp2p::NetworkService;
@ -60,44 +60,8 @@
//TODO: use Poll from mio //TODO: use Poll from mio
#![allow(deprecated)] #![allow(deprecated)]
//TODO: remove this pub use ethcore_io::TimerToken;
extern crate ansi_term;
#[cfg(test)] #[macro_use]
extern crate assert_matches;
extern crate bytes;
#[cfg(test)]
extern crate env_logger;
extern crate ethcore_io as io;
extern crate ethcore_network as network;
extern crate ethereum_types;
extern crate ethkey;
extern crate igd;
extern crate ipnetwork;
extern crate keccak_hash as hash;
extern crate libc;
#[macro_use]
extern crate log;
extern crate lru_cache;
extern crate mio;
extern crate parity_bytes;
extern crate parity_crypto as crypto;
extern crate parity_path;
extern crate parity_snappy as snappy;
extern crate parking_lot;
extern crate rand;
extern crate rlp;
extern crate rustc_hex;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate slab;
#[cfg(test)]
extern crate tempdir;
extern crate tiny_keccak;
pub use host::NetworkContext; pub use host::NetworkContext;
pub use io::TimerToken;
pub use node_table::{MAX_NODES_IN_TABLE, NodeId, validate_node_url}; pub use node_table::{MAX_NODES_IN_TABLE, NodeId, validate_node_url};
pub use service::NetworkService; pub use service::NetworkService;

View File

@ -25,14 +25,19 @@ use std::str::FromStr;
use std::time::{self, Duration, SystemTime}; use std::time::{self, Duration, SystemTime};
use ethereum_types::H512; use ethereum_types::H512;
use log::{debug, warn};
use rand::{self, Rng}; use rand::{self, Rng};
use rlp::{DecoderError, Rlp, RlpStream}; use rlp::{DecoderError, Rlp, RlpStream};
use serde::{Deserialize, Serialize};
use serde_json; use serde_json;
use discovery::{NodeEntry, TableUpdates};
use ip_utils::*;
use network::{AllowIP, Error, IpFilter}; use network::{AllowIP, Error, IpFilter};
use crate::{
discovery::{NodeEntry, TableUpdates},
ip_utils::*,
};
/// Node public key /// Node public key
pub type NodeId = H512; pub type NodeId = H512;
@ -612,6 +617,8 @@ mod tests {
use ipnetwork::IpNetwork; use ipnetwork::IpNetwork;
use tempdir::TempDir; use tempdir::TempDir;
use assert_matches::assert_matches;
use super::*; use super::*;
#[test] #[test]

View File

@ -19,13 +19,17 @@ use std::ops::RangeInclusive;
use std::sync::Arc; use std::sync::Arc;
use ansi_term::Colour; use ansi_term::Colour;
use log::info;
use parking_lot::RwLock; use parking_lot::RwLock;
use host::Host; use ethcore_io::{IoContext, IoHandler, IoService};
use io::*; use network::{
use network::{Error, NetworkConfiguration, NetworkProtocolHandler, NonReservedPeerMode}; ConnectionFilter, Error, NetworkConfiguration, NetworkContext,
use network::{NetworkContext, NetworkIoMessage, PeerId, ProtocolId}; NetworkIoMessage, NetworkProtocolHandler, NonReservedPeerMode, PeerId, ProtocolId,
use network::ConnectionFilter;
};
use crate::host::Host;
struct HostHandler { struct HostHandler {
public_url: RwLock<Option<String>> public_url: RwLock<Option<String>>

View File

@ -20,20 +20,24 @@ use std::net::SocketAddr;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use ethereum_types::H256; use ethereum_types::H256;
use log::{debug, trace, warn};
use mio::*; use mio::*;
use mio::deprecated::{EventLoop, Handler}; use mio::deprecated::{EventLoop, Handler};
use mio::tcp::*; use mio::tcp::*;
use parity_snappy as snappy;
use rlp::{EMPTY_LIST_RLP, Rlp, RlpStream}; use rlp::{EMPTY_LIST_RLP, Rlp, RlpStream};
use snappy;
use connection::{Connection, EncryptedConnection, MAX_PAYLOAD_SIZE, Packet}; use ethcore_io::{IoContext, StreamToken};
use handshake::Handshake;
use host::*;
use io::{IoContext, StreamToken};
use network::{DisconnectReason, Error, PeerCapabilityInfo, ProtocolId, SessionInfo}; use network::{DisconnectReason, Error, PeerCapabilityInfo, ProtocolId, SessionInfo};
use network::client_version::ClientVersion; use network::client_version::ClientVersion;
use network::SessionCapabilityInfo; use network::SessionCapabilityInfo;
use node_table::NodeId;
use crate::{
connection::{Connection, EncryptedConnection, MAX_PAYLOAD_SIZE, Packet},
handshake::Handshake,
host::HostInfo,
node_table::NodeId,
};
// Timeout must be less than (interval - 1). // Timeout must be less than (interval - 1).
const PING_TIMEOUT: Duration = Duration::from_secs(60); const PING_TIMEOUT: Duration = Duration::from_secs(60);
@ -372,7 +376,7 @@ impl Session {
}, },
PACKET_GET_PEERS => Ok(SessionData::None), //TODO; PACKET_GET_PEERS => Ok(SessionData::None), //TODO;
PACKET_PEERS => Ok(SessionData::None), PACKET_PEERS => Ok(SessionData::None),
PACKET_USER ... PACKET_LAST => { PACKET_USER ..= PACKET_LAST => {
let mut i = 0usize; let mut i = 0usize;
while packet_id >= self.info.capabilities[i].id_offset + self.info.capabilities[i].packet_count { while packet_id >= self.info.capabilities[i].id_offset + self.info.capabilities[i].packet_count {
i += 1; i += 1;

View File

@ -14,26 +14,20 @@
// You should have received a copy of the GNU General Public License // You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>. // along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
extern crate env_logger; use std::sync::{
extern crate ethcore_io as io; Arc,
extern crate ethcore_network; atomic::{AtomicBool, Ordering as AtomicOrdering}
extern crate ethcore_network_devp2p; };
extern crate ethkey;
extern crate parity_bytes;
extern crate parking_lot;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
use std::thread; use std::thread;
use std::time::*; use std::time::Duration;
use parity_bytes::Bytes; use parity_bytes::Bytes;
use parking_lot::Mutex; use parking_lot::Mutex;
use ethcore_network::*; use network::{PeerId, NetworkContext, NetworkProtocolHandler, NetworkConfiguration};
use ethcore_network_devp2p::NetworkService; use ethcore_network_devp2p::NetworkService;
use ethkey::{Generator, Random}; use ethkey::{Generator, Random};
use io::TimerToken; use ethcore_io::TimerToken;
pub struct TestProtocol { pub struct TestProtocol {
drop_session: bool, drop_session: bool,
@ -48,7 +42,7 @@ impl TestProtocol {
packet: Mutex::new(Vec::new()), packet: Mutex::new(Vec::new()),
got_timeout: AtomicBool::new(false), got_timeout: AtomicBool::new(false),
got_disconnect: AtomicBool::new(false), got_disconnect: AtomicBool::new(false),
drop_session: drop_session, drop_session,
} }
} }
/// Creates and register protocol with the network service /// Creates and register protocol with the network service