Fix some nits using clippy (#8731)

* fix some nits using clippy

* fix tests
This commit is contained in:
Niklas Adolfsson 2018-05-31 13:38:46 +02:00 committed by Afri Schoedon
parent 6b9314eaa9
commit 118588ef6c
7 changed files with 75 additions and 72 deletions

View File

@ -84,12 +84,12 @@ impl Handshake {
/// Create a new handshake object
pub fn new(token: StreamToken, id: Option<&NodeId>, socket: TcpStream, nonce: &H256) -> Result<Handshake, Error> {
Ok(Handshake {
id: if let Some(id) = id { id.clone()} else { NodeId::new() },
id: if let Some(id) = id { *id } else { NodeId::new() },
connection: Connection::new(token, socket),
originated: false,
state: HandshakeState::New,
ecdhe: Random.generate()?,
nonce: nonce.clone(),
nonce: *nonce,
remote_ephemeral: Public::new(),
remote_nonce: H256::new(),
remote_version: PROTOCOL_VERSION,
@ -166,7 +166,7 @@ impl Handshake {
self.remote_version = remote_version;
let shared = *ecdh::agree(host_secret, &self.id)?;
let signature = H520::from_slice(sig);
self.remote_ephemeral = recover(&signature.into(), &(&shared ^ &self.remote_nonce))?;
self.remote_ephemeral = recover(&signature.into(), &(shared ^ self.remote_nonce))?;
Ok(())
}
@ -189,7 +189,7 @@ impl Handshake {
}
Err(_) => {
// Try to interpret as EIP-8 packet
let total = (((data[0] as u16) << 8 | (data[1] as u16)) as usize) + 2;
let total = ((u16::from(data[0]) << 8 | (u16::from(data[1]))) as usize) + 2;
if total < V4_AUTH_PACKET_SIZE {
debug!(target: "network", "Wrong EIP8 auth packet size");
return Err(ErrorKind::BadProtocol.into());
@ -232,7 +232,7 @@ impl Handshake {
}
Err(_) => {
// Try to interpret as EIP-8 packet
let total = (((data[0] as u16) << 8 | (data[1] as u16)) as usize) + 2;
let total = (((u16::from(data[0])) << 8 | (u16::from(data[1]))) as usize) + 2;
if total < V4_ACK_PACKET_SIZE {
debug!(target: "network", "Wrong EIP8 ack packet size");
return Err(ErrorKind::BadProtocol.into());

View File

@ -116,11 +116,11 @@ impl<'s> NetworkContext<'s> {
) -> NetworkContext<'s> {
let id = session.as_ref().map(|s| s.lock().token());
NetworkContext {
io: io,
protocol: protocol,
io,
protocol,
session_id: id,
session: session,
sessions: sessions,
session,
sessions,
_reserved_peers: reserved_peers,
}
}
@ -280,7 +280,7 @@ impl Host {
let tcp_listener = TcpListener::bind(&listen_address)?;
listen_address = SocketAddr::new(listen_address.ip(), tcp_listener.local_addr()?.port());
debug!(target: "network", "Listening at {:?}", listen_address);
let udp_port = config.udp_port.unwrap_or(listen_address.port());
let udp_port = config.udp_port.unwrap_or_else(|| listen_address.port());
let local_endpoint = NodeEndpoint { address: listen_address, udp_port: udp_port };
let boot_nodes = config.boot_nodes.clone();
@ -325,7 +325,7 @@ impl Host {
match Node::from_str(id) {
Err(e) => { debug!(target: "network", "Could not add node {}: {:?}", id, e); },
Ok(n) => {
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() };
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id };
self.nodes.write().add_node(n);
if let Some(ref mut discovery) = *self.discovery.lock() {
@ -338,9 +338,9 @@ impl Host {
pub fn add_reserved_node(&self, id: &str) -> Result<(), Error> {
let n = Node::from_str(id)?;
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id.clone() };
self.reserved_nodes.write().insert(n.id.clone());
self.nodes.write().add_node(Node::new(entry.id.clone(), entry.endpoint.clone()));
let entry = NodeEntry { endpoint: n.endpoint.clone(), id: n.id };
self.reserved_nodes.write().insert(n.id);
self.nodes.write().add_node(Node::new(entry.id, entry.endpoint.clone()));
if let Some(ref mut discovery) = *self.discovery.lock() {
discovery.add_node(entry);
@ -349,10 +349,10 @@ impl Host {
Ok(())
}
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode, io: &IoContext<NetworkIoMessage>) {
pub fn set_non_reserved_mode(&self, mode: &NonReservedPeerMode, io: &IoContext<NetworkIoMessage>) {
let mut info = self.info.write();
if info.config.non_reserved_mode != mode {
if &info.config.non_reserved_mode != mode {
info.config.non_reserved_mode = mode.clone();
drop(info);
if let NonReservedPeerMode::Deny = mode {
@ -388,12 +388,12 @@ impl Host {
pub fn external_url(&self) -> Option<String> {
let info = self.info.read();
info.public_endpoint.as_ref().map(|e| format!("{}", Node::new(info.id().clone(), e.clone())))
info.public_endpoint.as_ref().map(|e| format!("{}", Node::new(*info.id(), e.clone())))
}
pub fn local_url(&self) -> String {
let info = self.info.read();
format!("{}", Node::new(info.id().clone(), info.local_endpoint.clone()))
format!("{}", Node::new(*info.id(), info.local_endpoint.clone()))
}
pub fn stop(&self, io: &IoContext<NetworkIoMessage>) {
@ -554,7 +554,7 @@ impl Host {
// iterate over all nodes, reserved ones coming first.
// if we are pinned to only reserved nodes, ignore all others.
let nodes = reserved_nodes.iter().cloned().chain(if !pin {
self.nodes.read().nodes(allow_ips)
self.nodes.read().nodes(&allow_ips)
} else {
Vec::new()
});
@ -752,7 +752,7 @@ impl Host {
let entry = NodeEntry { id: id, endpoint: endpoint };
let mut nodes = self.nodes.write();
if !nodes.contains(&entry.id) {
nodes.add_node(Node::new(entry.id.clone(), entry.endpoint.clone()));
nodes.add_node(Node::new(entry.id, entry.endpoint.clone()));
let mut discovery = self.discovery.lock();
if let Some(ref mut discovery) = *discovery {
discovery.add_node(entry);

View File

@ -109,7 +109,7 @@ impl SocketAddrExt for Ipv4Addr {
fn is_within(&self, ipnet: &IpNetwork) -> bool {
match ipnet {
&IpNetwork::V4(ipnet) => ipnet.contains(*self),
IpNetwork::V4(ipnet) => ipnet.contains(*self),
_ => false
}
}
@ -167,7 +167,7 @@ impl SocketAddrExt for Ipv6Addr {
fn is_within(&self, ipnet: &IpNetwork) -> bool {
match ipnet {
&IpNetwork::V6(ipnet) => ipnet.contains(*self),
IpNetwork::V6(ipnet) => ipnet.contains(*self),
_ => false
}
}
@ -212,28 +212,28 @@ impl SocketAddrExt for IpAddr {
#[cfg(not(any(windows, target_os = "android")))]
mod getinterfaces {
use std::{mem, io, ptr};
use std::{mem, io};
use libc::{AF_INET, AF_INET6};
use libc::{getifaddrs, freeifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
fn convert_sockaddr(sa: *mut sockaddr) -> Option<IpAddr> {
if sa == ptr::null_mut() { return None; }
if sa.is_null() { return None; }
let (addr, _) = match unsafe { *sa }.sa_family as i32 {
let (addr, _) = match i32::from(unsafe { *sa }.sa_family) {
AF_INET => {
let sa: *const sockaddr_in = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let sa: *const sockaddr_in = sa as *const sockaddr_in;
let sa = unsafe { &*sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x000000FF) as u8,
((addr & 0x0000FF00) >> 8) as u8,
((addr & 0x00FF0000) >> 16) as u8,
((addr & 0xFF000000) >> 24) as u8)),
(addr & 0x0000_00FF) as u8,
((addr & 0x0000_FF00) >> 8) as u8,
((addr & 0x00FF_0000) >> 16) as u8,
((addr & 0xFF00_0000) >> 24) as u8)),
port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = unsafe { mem::transmute(sa) };
let sa: *const sockaddr_in6 = sa as *const sockaddr_in6;
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
@ -266,7 +266,7 @@ mod getinterfaces {
let mut ret = Vec::new();
let mut cur: *mut ifaddrs = ifap;
while cur != ptr::null_mut() {
while !cur.is_null() {
if let Some(ip_addr) = convert_ifaddrs(cur) {
ret.push(ip_addr);
}
@ -297,16 +297,16 @@ pub fn select_public_address(port: u16) -> SocketAddr {
//prefer IPV4 bindings
for addr in &list { //TODO: use better criteria than just the first in the list
match addr {
&IpAddr::V4(a) if !a.is_reserved() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
IpAddr::V4(a) if !a.is_reserved() => {
return SocketAddr::V4(SocketAddrV4::new(*a, port));
},
_ => {},
}
}
for addr in &list {
match addr {
&IpAddr::V6(a) if !a.is_reserved() => {
return SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0));
IpAddr::V6(a) if !a.is_reserved() => {
return SocketAddr::V6(SocketAddrV6::new(*a, port, 0, 0));
},
_ => {},
}
@ -319,7 +319,7 @@ pub fn select_public_address(port: u16) -> SocketAddr {
pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
match search_gateway_from_timeout(*local_addr.ip(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => {
match gateway.get_external_ip() {
@ -327,17 +327,17 @@ pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(*local_addr.ip(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(tcp_port) => {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(local_addr.ip().clone(), local.udp_port), 0, "Parity Node/UDP") {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(*local_addr.ip(), local.udp_port), 0, "Parity Node/UDP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(udp_port) => {
return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port });
},
}
},

View File

@ -26,7 +26,7 @@ use std::hash::{Hash, Hasher};
use std::net::{SocketAddr, ToSocketAddrs, SocketAddrV4, SocketAddrV6, Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;
use std::str::FromStr;
use std::{fs, mem, slice};
use std::{fs, slice};
use std::time::{self, Duration, SystemTime};
use rand::{self, Rng};
@ -45,8 +45,8 @@ pub struct NodeEndpoint {
impl NodeEndpoint {
pub fn udp_address(&self) -> SocketAddr {
match self.address {
SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(a.ip().clone(), self.udp_port)),
SocketAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(a.ip().clone(), self.udp_port, a.flowinfo(), a.scope_id())),
SocketAddr::V4(a) => SocketAddr::V4(SocketAddrV4::new(*a.ip(), self.udp_port)),
SocketAddr::V6(a) => SocketAddr::V6(SocketAddrV6::new(*a.ip(), self.udp_port, a.flowinfo(), a.scope_id())),
}
}
@ -61,10 +61,10 @@ impl NodeEndpoint {
pub fn is_allowed_by_predefined(&self, filter: &AllowIP) -> bool {
match filter {
&AllowIP::All => true,
&AllowIP::Private => self.address.ip().is_usable_private(),
&AllowIP::Public => self.address.ip().is_usable_public(),
&AllowIP::None => false,
AllowIP::All => true,
AllowIP::Private => self.address.ip().is_usable_private(),
AllowIP::Public => self.address.ip().is_usable_public(),
AllowIP::None => false,
}
}
@ -75,13 +75,13 @@ impl NodeEndpoint {
let address = match addr_bytes.len() {
4 => Ok(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(addr_bytes[0], addr_bytes[1], addr_bytes[2], addr_bytes[3]), tcp_port))),
16 => unsafe {
let o: *const u16 = mem::transmute(addr_bytes.as_ptr());
let o: *const u16 = addr_bytes.as_ptr() as *const u16;
let o = slice::from_raw_parts(o, 8);
Ok(SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::new(o[0], o[1], o[2], o[3], o[4], o[5], o[6], o[7]), tcp_port, 0, 0)))
},
_ => Err(DecoderError::RlpInconsistentLengthAndData)
}?;
Ok(NodeEndpoint { address: address, udp_port: udp_port })
Ok(NodeEndpoint { address, udp_port })
}
pub fn to_rlp(&self, rlp: &mut RlpStream) {
@ -90,7 +90,7 @@ impl NodeEndpoint {
rlp.append(&(&a.ip().octets()[..]));
}
SocketAddr::V6(a) => unsafe {
let o: *const u8 = mem::transmute(a.ip().segments().as_ptr());
let o: *const u8 = a.ip().segments().as_ptr() as *const u8;
rlp.append(&slice::from_raw_parts(o, 16));
}
};
@ -184,8 +184,8 @@ pub struct Node {
impl Node {
pub fn new(id: NodeId, endpoint: NodeEndpoint) -> Node {
Node {
id: id,
endpoint: endpoint,
id,
endpoint,
peer_type: PeerType::Optional,
last_contact: None,
}
@ -214,8 +214,8 @@ impl FromStr for Node {
};
Ok(Node {
id: id,
endpoint: endpoint,
id,
endpoint,
peer_type: PeerType::Optional,
last_contact: None,
})
@ -258,7 +258,7 @@ impl NodeTable {
pub fn add_node(&mut self, mut node: Node) {
// preserve node last_contact
node.last_contact = self.nodes.get(&node.id).and_then(|n| n.last_contact);
self.nodes.insert(node.id.clone(), node);
self.nodes.insert(node.id, node);
}
/// Returns a list of ordered nodes according to their most recent contact
@ -315,7 +315,7 @@ impl NodeTable {
/// Returns node ids sorted by failure percentage, for nodes with the same failure percentage the absolute number of
/// failures is considered.
pub fn nodes(&self, filter: IpFilter) -> Vec<NodeId> {
pub fn nodes(&self, filter: &IpFilter) -> Vec<NodeId> {
self.ordered_entries().iter()
.filter(|n| n.endpoint.is_allowed(&filter))
.map(|n| n.id)
@ -327,7 +327,7 @@ impl NodeTable {
pub fn entries(&self) -> Vec<NodeEntry> {
self.ordered_entries().iter().map(|n| NodeEntry {
endpoint: n.endpoint.clone(),
id: n.id.clone(),
id: n.id,
}).collect()
}
@ -344,7 +344,7 @@ impl NodeTable {
/// Apply table changes coming from discovery
pub fn update(&mut self, mut update: TableUpdates, reserved: &HashSet<NodeId>) {
for (_, node) in update.added.drain() {
let entry = self.nodes.entry(node.id.clone()).or_insert_with(|| Node::new(node.id.clone(), node.endpoint.clone()));
let entry = self.nodes.entry(node.id).or_insert_with(|| Node::new(node.id, node.endpoint.clone()));
entry.endpoint = node.endpoint;
}
for r in update.removed {
@ -389,7 +389,7 @@ impl NodeTable {
return;
}
path.push(NODES_FILE);
let node_ids = self.nodes(IpFilter::default());
let node_ids = self.nodes(&IpFilter::default());
let nodes = node_ids.into_iter()
.map(|id| self.nodes.get(&id).expect("self.nodes() only returns node IDs from self.nodes"))
.take(MAX_NODES)
@ -428,7 +428,7 @@ impl NodeTable {
Ok(table) => {
table.nodes.into_iter()
.filter_map(|n| n.into_node())
.map(|n| (n.id.clone(), n))
.map(|n| (n.id, n))
.collect()
},
Err(e) => {
@ -625,7 +625,7 @@ mod tests {
// unknown - node 6
let r = table.nodes(IpFilter::default());
let r = table.nodes(&IpFilter::default());
assert_eq!(r[0][..], id4[..]); // most recent success
assert_eq!(r[1][..], id3[..]);
@ -662,7 +662,7 @@ mod tests {
{
let table = NodeTable::new(Some(tempdir.path().to_str().unwrap().to_owned()));
let r = table.nodes(IpFilter::default());
let r = table.nodes(&IpFilter::default());
assert_eq!(r[0][..], id2[..]); // latest success
assert_eq!(r[1][..], id1[..]); // unknown
assert_eq!(r[2][..], id3[..]); // oldest failure

View File

@ -165,7 +165,7 @@ impl NetworkService {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);
host.set_non_reserved_mode(mode, &io_ctxt);
host.set_non_reserved_mode(&mode, &io_ctxt);
}
}

View File

@ -117,7 +117,7 @@ impl Session {
capabilities: Vec::new(),
peer_capabilities: Vec::new(),
ping: None,
originated: originated,
originated,
remote_address: "Handshake".to_owned(),
local_address: local_addr,
},
@ -131,7 +131,7 @@ impl Session {
fn complete_handshake<Message>(&mut self, io: &IoContext<Message>, host: &HostInfo) -> Result<(), Error> where Message: Send + Sync + Clone {
let connection = if let State::Handshake(ref mut h) = self.state {
self.info.id = Some(h.id.clone());
self.info.id = Some(h.id);
self.info.remote_address = h.connection.remote_addr_str();
EncryptedConnection::new(h)?
} else {
@ -204,7 +204,7 @@ impl Session {
}
}
if let Some(data) = packet_data {
return Ok(self.read_packet(io, data, host)?);
return Ok(self.read_packet(io, &data, host)?);
}
if create_session {
self.complete_handshake(io, host)?;
@ -277,7 +277,7 @@ impl Session {
None => packet_id
};
let mut rlp = RlpStream::new();
rlp.append(&(pid as u32));
rlp.append(&(u32::from(pid)));
let mut compressed = Vec::new();
let mut payload = data; // create a reference with local lifetime
if self.compression {
@ -329,7 +329,7 @@ impl Session {
}
}
fn read_packet<Message>(&mut self, io: &IoContext<Message>, packet: Packet, host: &HostInfo) -> Result<SessionData, Error>
fn read_packet<Message>(&mut self, io: &IoContext<Message>, packet: &Packet, host: &HostInfo) -> Result<SessionData, Error>
where Message: Send + Sync + Clone {
if packet.data.len() < 2 {
return Err(ErrorKind::BadProtocol.into());
@ -390,7 +390,7 @@ impl Session {
match *self.protocol_states.entry(protocol).or_insert_with(|| ProtocolState::Pending(Vec::new())) {
ProtocolState::Connected => {
trace!(target: "network", "Packet {} mapped to {:?}:{}, i={}, capabilities={:?}", packet_id, protocol, protocol_packet_id, i, self.info.capabilities);
Ok(SessionData::Packet { data: data, protocol: protocol, packet_id: protocol_packet_id } )
Ok(SessionData::Packet { data, protocol, packet_id: protocol_packet_id } )
}
ProtocolState::Pending(ref mut pending) => {
trace!(target: "network", "Packet {} deferred until protocol connection event completion", packet_id);
@ -468,11 +468,11 @@ impl Session {
self.info.peer_capabilities = peer_caps;
if self.info.capabilities.is_empty() {
trace!(target: "network", "No common capabilities with peer.");
return Err(From::from(self.disconnect(io, DisconnectReason::UselessPeer)));
return Err(self.disconnect(io, DisconnectReason::UselessPeer));
}
if protocol < MIN_PROTOCOL_VERSION {
trace!(target: "network", "Peer protocol version mismatch: {}", protocol);
return Err(From::from(self.disconnect(io, DisconnectReason::UselessPeer)));
return Err(self.disconnect(io, DisconnectReason::UselessPeer));
}
self.compression = protocol >= MIN_COMPRESSION_PROTOCOL_VERSION;
self.send_ping(io)?;

View File

@ -19,6 +19,9 @@
//! Spawns an Ethereum network instance and attaches the Whisper protocol RPCs to it.
//!
#![warn(missing_docs)]
#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))]
extern crate docopt;
extern crate ethcore_network_devp2p as devp2p;
extern crate ethcore_network as net;