Apply clippy fixes

This commit is contained in:
Henry de Valence 2020-02-04 22:53:24 -08:00
parent a0d0d297d9
commit f04f4f0b98
23 changed files with 61 additions and 66 deletions

1
clippy.toml Normal file
View File

@ -0,0 +1 @@
type-complexity-threshold = 999999

View File

@ -7,7 +7,6 @@ mod tests;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use hex;
use std::{fmt, io}; use std::{fmt, io};
#[cfg(test)] #[cfg(test)]

View File

@ -31,6 +31,8 @@ use crate::types::{BlockHeight, LockTime};
/// internally by different enum variants. Because we checkpoint on Sapling /// internally by different enum variants. Because we checkpoint on Sapling
/// activation, we do not parse any pre-Sapling transaction types. /// activation, we do not parse any pre-Sapling transaction types.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
// XXX consider boxing the Optional fields of V4 txs
#[allow(clippy::large_enum_variant)]
pub enum Transaction { pub enum Transaction {
/// A fully transparent transaction (`version = 1`). /// A fully transparent transaction (`version = 1`).
V1 { V1 {

View File

@ -1,7 +1,5 @@
use std::fmt; use std::fmt;
use hex;
#[cfg(test)] #[cfg(test)]
use proptest_derive::Arbitrary; use proptest_derive::Arbitrary;

View File

@ -105,8 +105,8 @@ impl<P: ZkSnarkProof + Arbitrary + 'static> Arbitrary for JoinSplitData<P> {
) )
.prop_map(|(first, rest, pub_key_bytes, sig_bytes)| { .prop_map(|(first, rest, pub_key_bytes, sig_bytes)| {
return Self { return Self {
first: first, first,
rest: rest, rest,
pub_key: ed25519_zebra::PublicKeyBytes::from(pub_key_bytes), pub_key: ed25519_zebra::PublicKeyBytes::from(pub_key_bytes),
sig: ed25519_zebra::Signature::from({ sig: ed25519_zebra::Signature::from({
let mut b = [0u8; 64]; let mut b = [0u8; 64];

View File

@ -12,8 +12,8 @@ use crate::types::Script;
use super::*; use super::*;
const OVERWINTER_VERSION_GROUP_ID: u32 = 0x03C48270; const OVERWINTER_VERSION_GROUP_ID: u32 = 0x03C4_8270;
const SAPLING_VERSION_GROUP_ID: u32 = 0x892F2085; const SAPLING_VERSION_GROUP_ID: u32 = 0x892F_2085;
impl ZcashSerialize for OutPoint { impl ZcashSerialize for OutPoint {
fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), SerializationError> { fn zcash_serialize<W: io::Write>(&self, mut writer: W) -> Result<(), SerializationError> {
@ -373,14 +373,14 @@ impl ZcashDeserialize for Transaction {
let joinsplit_data = OptV4JSD::zcash_deserialize(&mut reader)?; let joinsplit_data = OptV4JSD::zcash_deserialize(&mut reader)?;
use futures::future::Either::*; use futures::future::Either::*;
let shielded_data = if shielded_spends.len() > 0 { let shielded_data = if !shielded_spends.is_empty() {
Some(ShieldedData { Some(ShieldedData {
first: Left(shielded_spends.remove(0)), first: Left(shielded_spends.remove(0)),
rest_spends: shielded_spends, rest_spends: shielded_spends,
rest_outputs: shielded_outputs, rest_outputs: shielded_outputs,
binding_sig: reader.read_64_bytes()?.into(), binding_sig: reader.read_64_bytes()?.into(),
}) })
} else if shielded_outputs.len() > 0 { } else if !shielded_outputs.is_empty() {
Some(ShieldedData { Some(ShieldedData {
first: Right(shielded_outputs.remove(0)), first: Right(shielded_outputs.remove(0)),
rest_spends: shielded_spends, rest_spends: shielded_spends,

View File

@ -53,8 +53,8 @@ impl Arbitrary for SpendDescription {
.prop_map( .prop_map(
|(cv_bytes, anchor, nullifier_bytes, rpk_bytes, proof, sig_bytes)| { |(cv_bytes, anchor, nullifier_bytes, rpk_bytes, proof, sig_bytes)| {
return Self { return Self {
anchor,
cv: cv_bytes, cv: cv_bytes,
anchor: anchor,
nullifier: nullifier_bytes, nullifier: nullifier_bytes,
rk: redjubjub::PublicKeyBytes::from(rpk_bytes), rk: redjubjub::PublicKeyBytes::from(rpk_bytes),
zkproof: proof, zkproof: proof,
@ -186,14 +186,14 @@ impl Arbitrary for ShieldedData {
vec(any::<OutputDescription>(), 0..10), vec(any::<OutputDescription>(), 0..10),
vec(any::<u8>(), 64), vec(any::<u8>(), 64),
) )
.prop_map(|(first, rest_spends, rest_outputs, sig)| { .prop_map(|(first, rest_spends, rest_outputs, sig_bytes)| {
return Self { return Self {
first: first, first,
rest_spends: rest_spends, rest_spends,
rest_outputs: rest_outputs, rest_outputs,
binding_sig: redjubjub::Signature::from({ binding_sig: redjubjub::Signature::from({
let mut b = [0u8; 64]; let mut b = [0u8; 64];
b.copy_from_slice(sig.as_slice()); b.copy_from_slice(sig_bytes.as_slice());
b b
}), }),
}; };

View File

@ -7,7 +7,6 @@ use std::{
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use chrono::{DateTime, TimeZone, Utc}; use chrono::{DateTime, TimeZone, Utc};
use hex;
#[cfg(test)] #[cfg(test)]
use proptest_derive::Arbitrary; use proptest_derive::Arbitrary;

View File

@ -24,6 +24,7 @@ pub struct AddressBook {
span: Span, span: Span,
} }
#[allow(clippy::len_without_is_empty)]
impl AddressBook { impl AddressBook {
/// Construct an `AddressBook` with the given [`tracing::Span`]. /// Construct an `AddressBook` with the given [`tracing::Span`].
pub fn new(span: Span) -> AddressBook { pub fn new(span: Span) -> AddressBook {
@ -76,17 +77,14 @@ impl AddressBook {
#[cfg(test)] #[cfg(test)]
self.assert_consistency(); self.assert_consistency();
match self.get_by_addr(new.addr) { if let Some(prev) = self.get_by_addr(new.addr) {
Some(prev) => { if prev.last_seen > new.last_seen {
if prev.last_seen > new.last_seen { return;
return; } else {
} else { self.by_time
self.by_time .take(&prev)
.take(&prev) .expect("cannot have by_addr entry without by_time entry");
.expect("cannot have by_addr entry without by_time entry");
}
} }
None => {}
} }
self.by_time.insert(new); self.by_time.insert(new);
self.by_addr.insert(new.addr, (new.last_seen, new.services)); self.by_addr.insert(new.addr, (new.last_seen, new.services));
@ -115,7 +113,7 @@ impl AddressBook {
pub fn is_potentially_connected(&self, addr: &SocketAddr) -> bool { pub fn is_potentially_connected(&self, addr: &SocketAddr) -> bool {
let _guard = self.span.enter(); let _guard = self.span.enter();
match self.by_addr.get(addr) { match self.by_addr.get(addr) {
None => return false, None => false,
Some((ref last_seen, _)) => last_seen > &AddressBook::cutoff_time(), Some((ref last_seen, _)) => last_seen > &AddressBook::cutoff_time(),
} }
} }
@ -192,9 +190,9 @@ impl<'a> Iterator for Drain<'a> {
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
let next_item = if self.newest_first { let next_item = if self.newest_first {
self.book.by_time.iter().next()?.clone() *self.book.by_time.iter().next()?
} else { } else {
self.book.by_time.iter().rev().next()?.clone() *self.book.by_time.iter().rev().next()?
}; };
self.book.by_time.remove(&next_item); self.book.by_time.remove(&next_item);
self.book self.book

View File

@ -32,7 +32,7 @@ pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(60);
pub const TIMESTAMP_TRUNCATION_SECONDS: i64 = 30 * 60; pub const TIMESTAMP_TRUNCATION_SECONDS: i64 = 30 * 60;
/// The User-Agent string provided by the node. /// The User-Agent string provided by the node.
pub const USER_AGENT: &'static str = "🦓Zebra v2.0.0-alpha.0🦓"; pub const USER_AGENT: &str = "🦓Zebra v2.0.0-alpha.0🦓";
/// The Zcash network protocol version used on mainnet. /// The Zcash network protocol version used on mainnet.
pub const CURRENT_VERSION: Version = Version(170_007); pub const CURRENT_VERSION: Version = Version(170_007);

View File

@ -11,7 +11,7 @@ pub enum Network {
impl Network { impl Network {
/// Get the magic value associated to this `Network`. /// Get the magic value associated to this `Network`.
pub fn magic(&self) -> Magic { pub fn magic(self) -> Magic {
match self { match self {
Network::Mainnet => magics::MAINNET, Network::Mainnet => magics::MAINNET,
Network::Testnet => magics::TESTNET, Network::Testnet => magics::TESTNET,

View File

@ -39,7 +39,7 @@ impl Service<Request> for Client {
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if let Err(_) = ready!(self.server_tx.poll_ready(cx)) { if ready!(self.server_tx.poll_ready(cx)).is_err() {
Poll::Ready(Err(self Poll::Ready(Err(self
.error_slot .error_slot
.try_get_error() .try_get_error()

View File

@ -347,9 +347,8 @@ where
} }
}; };
match req { if let Some(req) = req {
Some(req) => self.drive_peer_request(req).await, self.drive_peer_request(req).await
None => {}
} }
} }
@ -362,7 +361,7 @@ where
trace!(?req); trace!(?req);
use tower::{load_shed::error::Overloaded, ServiceExt}; use tower::{load_shed::error::Overloaded, ServiceExt};
if let Err(_) = self.svc.ready().await { if self.svc.ready().await.is_err() {
// Treat all service readiness errors as Overloaded // Treat all service readiness errors as Overloaded
self.fail_with(PeerError::Overloaded); self.fail_with(PeerError::Overloaded);
} }

View File

@ -63,7 +63,7 @@ impl ErrorSlot {
.lock() .lock()
.expect("error mutex should be unpoisoned") .expect("error mutex should be unpoisoned")
.as_ref() .as_ref()
.map(|e| e.clone()) .cloned()
} }
} }
@ -72,7 +72,7 @@ impl ErrorSlot {
pub enum HandshakeError { pub enum HandshakeError {
/// The remote peer sent an unexpected message during the handshake. /// The remote peer sent an unexpected message during the handshake.
#[error("The remote peer sent an unexpected message: {0:?}")] #[error("The remote peer sent an unexpected message: {0:?}")]
UnexpectedMessage(crate::protocol::external::Message), UnexpectedMessage(Box<crate::protocol::external::Message>),
/// The peer connector detected handshake nonce reuse, possibly indicating self-connection. /// The peer connector detected handshake nonce reuse, possibly indicating self-connection.
#[error("Detected nonce reuse, possible self-connection")] #[error("Detected nonce reuse, possible self-connection")]
NonceReuse, NonceReuse,

View File

@ -102,7 +102,7 @@ where
let internal_service = self.internal_service.clone(); let internal_service = self.internal_service.clone();
let timestamp_collector = self.timestamp_collector.clone(); let timestamp_collector = self.timestamp_collector.clone();
let user_agent = self.config.user_agent.clone(); let user_agent = self.config.user_agent.clone();
let network = self.config.network.clone(); let network = self.config.network;
let fut = async move { let fut = async move {
info!("connecting to remote peer"); info!("connecting to remote peer");
@ -149,17 +149,18 @@ where
{ {
(nonce, services) (nonce, services)
} else { } else {
return Err(HandshakeError::UnexpectedMessage(remote_msg)); return Err(HandshakeError::UnexpectedMessage(Box::new(remote_msg)));
}; };
// Check for nonce reuse, indicating self-connection. // Check for nonce reuse, indicating self-connection.
if { let nonce_reuse = {
let mut locked_nonces = nonces.lock().expect("mutex should be unpoisoned"); let mut locked_nonces = nonces.lock().expect("mutex should be unpoisoned");
let nonce_reuse = locked_nonces.contains(&remote_nonce); let nonce_reuse = locked_nonces.contains(&remote_nonce);
// Regardless of whether we observed nonce reuse, clean up the nonce set. // Regardless of whether we observed nonce reuse, clean up the nonce set.
locked_nonces.remove(&local_nonce); locked_nonces.remove(&local_nonce);
nonce_reuse nonce_reuse
} { };
if nonce_reuse {
return Err(HandshakeError::NonceReuse); return Err(HandshakeError::NonceReuse);
} }
@ -172,7 +173,7 @@ where
if let Message::Verack = remote_msg { if let Message::Verack = remote_msg {
debug!("got verack from remote peer"); debug!("got verack from remote peer");
} else { } else {
return Err(HandshakeError::UnexpectedMessage(remote_msg)); return Err(HandshakeError::UnexpectedMessage(Box::new(remote_msg)));
} }
// XXX here is where we would set the version to the minimum of the // XXX here is where we would set the version to the minimum of the
@ -208,7 +209,7 @@ where
.then(move |msg| { .then(move |msg| {
let mut timestamp_collector = timestamp_collector.clone(); let mut timestamp_collector = timestamp_collector.clone();
async move { async move {
if let Ok(_) = msg { if msg.is_ok() {
use futures::sink::SinkExt; use futures::sink::SinkExt;
let _ = timestamp_collector let _ = timestamp_collector
.send(MetaAddr { .send(MetaAddr {

View File

@ -152,8 +152,7 @@ where
.drain_oldest() .drain_oldest()
.chain(self.gossiped.drain_newest()) .chain(self.gossiped.drain_newest())
.chain(self.failed.drain_oldest()) .chain(self.failed.drain_oldest())
.filter(|meta| !guard.is_potentially_connected(&meta.addr)) .find(|meta| !guard.is_potentially_connected(&meta.addr))
.next()
} }
pub fn report_failed(&mut self, mut addr: MetaAddr) { pub fn report_failed(&mut self, mut addr: MetaAddr) {

View File

@ -220,6 +220,7 @@ where
type Future = type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
#[allow(clippy::cognitive_complexity)]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// Process peer discovery updates. // Process peer discovery updates.
let _ = self.poll_discover(cx)?; let _ = self.poll_discover(cx)?;

View File

@ -293,6 +293,7 @@ impl Decoder for Codec {
type Item = Message; type Item = Message;
type Error = Error; type Error = Error;
#[allow(clippy::cognitive_complexity)]
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
use Error::Parse; use Error::Parse;
match self.state { match self.state {
@ -467,7 +468,7 @@ impl Codec {
fn read_block<R: Read>(&self, mut reader: R) -> Result<Message, Error> { fn read_block<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
Ok(Message::Block { Ok(Message::Block {
version: Version(reader.read_u32::<LittleEndian>()?), version: Version(reader.read_u32::<LittleEndian>()?),
block: Block::zcash_deserialize(&mut reader)?, block: Box::new(Block::zcash_deserialize(&mut reader)?),
}) })
} }
@ -511,7 +512,7 @@ impl Codec {
fn read_tx<R: Read>(&self, mut reader: R) -> Result<Message, Error> { fn read_tx<R: Read>(&self, mut reader: R) -> Result<Message, Error> {
Ok(Message::Tx { Ok(Message::Tx {
version: Version(reader.read_u32::<LittleEndian>()?), version: Version(reader.read_u32::<LittleEndian>()?),
transaction: Transaction::zcash_deserialize(&mut reader)?, transaction: Box::new(Transaction::zcash_deserialize(&mut reader)?),
}) })
} }
@ -546,9 +547,7 @@ impl Codec {
let mut bytes = Vec::new(); let mut bytes = Vec::new();
// Maximum size of data is 520 bytes. // Maximum size of data is 520 bytes.
let mut handle = reader.take(520); reader.take(520).read_exact(&mut bytes)?;
handle.read(&mut bytes)?;
Ok(Message::FilterAdd { data: bytes }) Ok(Message::FilterAdd { data: bytes })
} }

View File

@ -134,10 +134,11 @@ pub enum Message {
/// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#block) /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#block)
Block { Block {
/// Transaction data format version (note, this is signed). /// Transaction data format version (note, this is signed).
// XXX does this get folded into the Block struct?
version: Version, version: Version,
/// The block itself. /// The block itself.
block: Block, block: Box<Block>,
}, },
/// A `getblocks` message. /// A `getblocks` message.
@ -255,10 +256,11 @@ pub enum Message {
// `tx_witnesses` aren't either, as they go if `flag` goes. // `tx_witnesses` aren't either, as they go if `flag` goes.
Tx { Tx {
/// Transaction data format version (note, this is signed). /// Transaction data format version (note, this is signed).
// XXX do we still need this with the transaction data handling?
version: Version, version: Version,
/// The `Transaction` type itself. /// The `Transaction` type itself.
transaction: Transaction, transaction: Box<Transaction>,
}, },
/// A `mempool` message. /// A `mempool` message.

View File

@ -1,4 +1,3 @@
use hex;
use std::fmt; use std::fmt;
#[cfg(test)] #[cfg(test)]
@ -29,7 +28,7 @@ bitflags! {
/// NODE_NETWORK means that the node is a full node capable of serving /// NODE_NETWORK means that the node is a full node capable of serving
/// blocks, as opposed to a light client that makes network requests but /// blocks, as opposed to a light client that makes network requests but
/// does not provide network services. /// does not provide network services.
const NODE_NETWORK = (1 << 0); const NODE_NETWORK = 1;
} }
} }

View File

@ -57,7 +57,7 @@ impl Configurable<ZebradConfig> for ZebradCmd {
let if_exists = |f: PathBuf| if f.exists() { Some(f) } else { None }; let if_exists = |f: PathBuf| if f.exists() { Some(f) } else { None };
filename.and_then(|f| if_exists(f)) filename.and_then(if_exists)
} }
/// Apply changes to the config after it's been loaded, e.g. overriding /// Apply changes to the config after it's been loaded, e.g. overriding

View File

@ -49,11 +49,9 @@ impl ConnectCmd {
use tower::{buffer::Buffer, service_fn, Service, ServiceExt}; use tower::{buffer::Buffer, service_fn, Service, ServiceExt};
let node = Buffer::new( let node = Buffer::new(
service_fn(|req| { service_fn(|req| async move {
async move { info!(?req);
info!(?req); Ok::<Response, Error>(Response::Ok)
Ok::<Response, Error>(Response::Ok)
}
}), }),
1, 1,
); );

View File

@ -41,20 +41,20 @@ impl Service<Request> for SeedService {
#[instrument(skip(self, _cx))] #[instrument(skip(self, _cx))]
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.state { match self.state {
SeederState::Ready(_) => return Poll::Ready(Ok(())), SeederState::Ready(_) => Poll::Ready(Ok(())),
SeederState::AwaitingAddressBook(ref mut rx) => match rx.try_recv() { SeederState::AwaitingAddressBook(ref mut rx) => match rx.try_recv() {
Err(e) => { Err(e) => {
error!("oneshot sender dropped, failing service: {:?}", e); error!("oneshot sender dropped, failing service: {:?}", e);
return Poll::Ready(Err(e.into())); Poll::Ready(Err(e.into()))
} }
Ok(None) => { Ok(None) => {
trace!("awaiting address book, service is unready"); trace!("awaiting address book, service is unready");
return Poll::Pending; Poll::Pending
} }
Ok(Some(address_book)) => { Ok(Some(address_book)) => {
debug!("received address_book via oneshot, service becomes ready"); debug!("received address_book via oneshot, service becomes ready");
self.state = SeederState::Ready(address_book); self.state = SeederState::Ready(address_book);
return Poll::Ready(Ok(())); Poll::Ready(Ok(()))
} }
}, },
} }
@ -95,7 +95,7 @@ impl Service<Request> for SeedService {
Ok(Response::Ok) Ok(Response::Ok)
} }
}; };
return Box::pin(futures::future::ready(response)); Box::pin(futures::future::ready(response))
} }
} }