Fix clippy warnings (#813)

* Clippy account manager

* Clippy account_manager

* Clippy beacon_node/beacon_chain

* Clippy beacon_node/client

* Clippy beacon_node/eth1

* Clippy beacon_node/eth2-libp2p

* Clippy beacon_node/genesis

* Clippy beacon_node/network

* Clippy beacon_node/rest_api

* Clippy beacon_node/src

* Clippy beacon_node/store

* Clippy eth2/lmd_ghost

* Clippy eth2/operation_pool

* Clippy eth2/state_processing

* Clippy eth2/types

* Clippy eth2/utils/bls

* Clippy eth2/utils/cahced_tree_hash

* Clippy eth2/utils/deposit_contract

* Clippy eth2/utils/eth2_interop_keypairs

* Clippy eth2/utils/eth2_testnet_config

* Clippy eth2/utils/lighthouse_metrics

* Clippy eth2/utils/ssz

* Clippy eth2/utils/ssz_types

* Clippy eth2/utils/tree_hash_derive

* Clippy lcli

* Clippy tests/beacon_chain_sim

* Clippy validator_client

* Cargo fmt
This commit is contained in:
pscott
2020-01-21 18:38:56 +11:00
committed by Age Manning
parent 1abb964652
commit 7396cd2cab
78 changed files with 387 additions and 416 deletions
+17 -12
View File
@@ -8,6 +8,7 @@ use itertools::Itertools;
use parking_lot::RwLock;
use ssz::{Decode, Encode};
use ssz_derive::{Decode, Encode};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt;
use std::marker::PhantomData;
@@ -182,13 +183,15 @@ impl ReducedTreeSsz {
}
}
pub fn to_reduced_tree<T, E>(
pub fn into_reduced_tree<T, E>(
self,
store: Arc<T>,
block_root_tree: Arc<BlockRootTree>,
) -> Result<ReducedTree<T, E>> {
if self.node_hashes.len() != self.nodes.len() {
Error::InvalidReducedTreeSsz("node_hashes and nodes should have equal length".into());
return Err(Error::InvalidReducedTreeSsz(
"node_hashes and nodes should have equal length".to_string(),
));
}
let nodes: HashMap<_, _> = self
.node_hashes
@@ -740,16 +743,19 @@ where
if a_slot < self.root.1 || b_slot < self.root.1 {
None
} else {
if a_slot < b_slot {
for _ in a_slot.as_u64()..b_slot.as_u64() {
b_root = b_iter.next()?.0;
match a_slot.cmp(&b_slot) {
Ordering::Less => {
for _ in a_slot.as_u64()..b_slot.as_u64() {
b_root = b_iter.next()?.0;
}
}
} else if a_slot > b_slot {
for _ in b_slot.as_u64()..a_slot.as_u64() {
a_root = a_iter.next()?.0;
Ordering::Greater => {
for _ in b_slot.as_u64()..a_slot.as_u64() {
a_root = a_iter.next()?.0;
}
}
Ordering::Equal => (),
}
Some((a_root, b_root))
}
}
@@ -876,7 +882,7 @@ where
block_root_tree: Arc<BlockRootTree>,
) -> Result<Self> {
let reduced_tree_ssz = ReducedTreeSsz::from_ssz_bytes(bytes)?;
Ok(reduced_tree_ssz.to_reduced_tree(store, block_root_tree)?)
Ok(reduced_tree_ssz.into_reduced_tree(store, block_root_tree)?)
}
}
@@ -1013,8 +1019,7 @@ mod tests {
);
let ssz_tree = ReducedTreeSsz::from_reduced_tree(&tree);
let bytes = tree.as_bytes();
let recovered_tree =
ReducedTree::from_bytes(&bytes, store.clone(), block_root_tree).unwrap();
let recovered_tree = ReducedTree::from_bytes(&bytes, store, block_root_tree).unwrap();
let recovered_ssz = ReducedTreeSsz::from_reduced_tree(&recovered_tree);
assert_eq!(ssz_tree, recovered_ssz);
+2 -2
View File
@@ -167,7 +167,7 @@ mod test {
HashSet::from_iter(vec![5, 6, 7, 8]), // 4, 4*
HashSet::from_iter(vec![0, 1, 2, 3, 4]), // 5*
];
let cover = maximum_cover(sets.clone(), 3);
let cover = maximum_cover(sets, 3);
assert_eq!(quality(&cover), 11);
}
@@ -182,7 +182,7 @@ mod test {
HashSet::from_iter(vec![1, 5, 6, 8]),
HashSet::from_iter(vec![1, 7, 11, 19]),
];
let cover = maximum_cover(sets.clone(), 5);
let cover = maximum_cover(sets, 5);
assert_eq!(quality(&cover), 19);
assert_eq!(cover.len(), 5);
}
+4 -12
View File
@@ -311,11 +311,7 @@ fn bench_block<T: EthSpec>(
)
.expect("should get indexed attestation");
(
local_spec.clone(),
local_state.clone(),
indexed_attestation.clone(),
)
(local_spec.clone(), local_state.clone(), indexed_attestation)
},
|(spec, ref mut state, indexed_attestation)| {
black_box(
@@ -349,11 +345,7 @@ fn bench_block<T: EthSpec>(
)
.expect("should get indexed attestation");
(
local_spec.clone(),
local_state.clone(),
indexed_attestation.clone(),
)
(local_spec.clone(), local_state.clone(), indexed_attestation)
},
|(spec, ref mut state, indexed_attestation)| {
black_box(
@@ -373,7 +365,7 @@ fn bench_block<T: EthSpec>(
);
let local_block = block.clone();
let local_state = state.clone();
let local_state = state;
c.bench(
&title,
Benchmark::new("get_attesting_indices", move |b| {
@@ -409,7 +401,7 @@ fn bench_block<T: EthSpec>(
.sample_size(10),
);
let local_block = block.clone();
let local_block = block;
c.bench(
&title,
Benchmark::new("ssz_block_len", move |b| {
+2 -2
View File
@@ -29,7 +29,7 @@ where
F: FnMut(&mut BlockBuilder<T>),
G: FnMut(&mut BeaconBlock<T>),
{
let (mut block, state) = get_block::<T, _>(mutate_builder);
let (mut block, mut state) = get_block::<T, _>(mutate_builder);
/*
* Control check to ensure the valid block should pass verification.
@@ -79,7 +79,7 @@ where
assert_eq!(
per_block_processing(
&mut state.clone(),
&mut state,
&block,
None,
BlockSignatureStrategy::VerifyBulk,
+1 -2
View File
@@ -22,7 +22,6 @@ fn get_state<E: EthSpec>(validator_count: usize) -> BeaconState<E> {
}
state.validators = (0..validator_count)
.into_iter()
.collect::<Vec<_>>()
.par_iter()
.map(|&i| Validator {
@@ -91,7 +90,7 @@ fn all_benches(c: &mut Criterion) {
.sample_size(10),
);
let inner_state = state.clone();
let inner_state = state;
c.bench(
&format!("{}_validators", validator_count),
Benchmark::new("clone_without_caches/beacon_state", move |b| {
+2 -2
View File
@@ -71,13 +71,13 @@ impl<T: EthSpec> Attestation<T> {
if self
.aggregation_bits
.get(committee_position)
.map_err(|e| Error::SszTypesError(e))?
.map_err(Error::SszTypesError)?
{
Err(Error::AlreadySigned(committee_position))
} else {
self.aggregation_bits
.set(committee_position, true)
.map_err(|e| Error::SszTypesError(e))?;
.map_err(Error::SszTypesError)?;
let message = self.data.tree_hash_root();
let domain = spec.get_domain(self.data.target.epoch, Domain::BeaconAttester, fork);
+2 -2
View File
@@ -897,7 +897,7 @@ impl<T: EthSpec> BeaconState<T> {
.enumerate()
.skip(self.pubkey_cache.len())
{
let success = self.pubkey_cache.insert(validator.pubkey.clone().into(), i);
let success = self.pubkey_cache.insert(validator.pubkey.clone(), i);
if !success {
return Err(Error::PubkeyCacheInconsistent);
}
@@ -957,7 +957,7 @@ impl<T: EthSpec> BeaconState<T> {
validator
.pubkey
.decompress()
.map_err(|e| Error::InvalidValidatorPubkey(e))
.map_err(Error::InvalidValidatorPubkey)
} else {
Ok(())
}
@@ -24,9 +24,8 @@ impl<T: EthSpec> TestingAttestationBuilder<T> {
let mut aggregation_bits_len = committee.len();
match test_task {
AttestationTestTask::BadAggregationBitfieldLen => aggregation_bits_len += 1,
_ => (),
if test_task == AttestationTestTask::BadAggregationBitfieldLen {
aggregation_bits_len += 1
}
let mut aggregation_bits = BitList::with_capacity(aggregation_bits_len).unwrap();
@@ -15,7 +15,7 @@ pub const KEYPAIRS_FILE: &str = "keypairs.raw_keypairs";
/// `./keypairs.raw_keypairs`.
pub fn keypairs_path() -> PathBuf {
let dir = dirs::home_dir()
.and_then(|home| Some(home.join(".lighthouse")))
.map(|home| (home.join(".lighthouse")))
.unwrap_or_else(|| PathBuf::from(""));
dir.join(KEYPAIRS_FILE)
}
@@ -42,7 +42,7 @@ impl<T: EthSpec> TestingBeaconStateBuilder<T> {
/// If the file does not contain enough keypairs or is invalid.
pub fn from_default_keypairs_file_if_exists(validator_count: usize, spec: &ChainSpec) -> Self {
let dir = dirs::home_dir()
.and_then(|home| Some(home.join(".lighthouse")))
.map(|home| home.join(".lighthouse"))
.unwrap_or_else(|| PathBuf::from(""));
let file = dir.join(KEYPAIRS_FILE);
@@ -30,7 +30,7 @@ impl TestingProposerSlashingBuilder {
let slot = Slot::new(0);
let hash_1 = Hash256::from([1; 32]);
let hash_2 = if test_task == ProposerSlashingTestTask::ProposalsIdentical {
hash_1.clone()
hash_1
} else {
Hash256::from([2; 32])
};
+4 -3
View File
@@ -99,9 +99,10 @@ impl AggregateSignature {
for byte in bytes {
if *byte != 0 {
let sig = RawAggregateSignature::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(
format!("Invalid AggregateSignature bytes: {:?}", bytes).to_string(),
)
DecodeError::BytesInvalid(format!(
"Invalid AggregateSignature bytes: {:?}",
bytes
))
})?;
return Ok(Self {
+1 -1
View File
@@ -39,7 +39,7 @@ impl PublicKey {
/// Converts compressed bytes to PublicKey
pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
let pubkey = RawPublicKey::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(format!("Invalid PublicKey bytes: {:?}", bytes).to_string())
DecodeError::BytesInvalid(format!("Invalid PublicKey bytes: {:?}", bytes))
})?;
Ok(PublicKey(pubkey))
+1 -3
View File
@@ -81,9 +81,7 @@ impl Signature {
for byte in bytes {
if *byte != 0 {
let raw_signature = RawSignature::from_bytes(&bytes).map_err(|_| {
DecodeError::BytesInvalid(
format!("Invalid Signature bytes: {:?}", bytes).to_string(),
)
DecodeError::BytesInvalid(format!("Invalid Signature bytes: {:?}", bytes))
})?;
return Ok(Signature {
signature: raw_signature,
+3 -3
View File
@@ -158,17 +158,17 @@ fn aggregate_public_keys<'a>(public_keys: &'a [Cow<'a, G1Point>]) -> G1Point {
}
pub trait G1Ref {
fn g1_ref<'a>(&'a self) -> Cow<'a, G1Point>;
fn g1_ref(&self) -> Cow<'_, G1Point>;
}
impl G1Ref for AggregatePublicKey {
fn g1_ref<'a>(&'a self) -> Cow<'a, G1Point> {
fn g1_ref(&self) -> Cow<'_, G1Point> {
Cow::Borrowed(&self.as_raw().point)
}
}
impl G1Ref for PublicKey {
fn g1_ref<'a>(&'a self) -> Cow<'a, G1Point> {
fn g1_ref(&self) -> Cow<'_, G1Point> {
Cow::Borrowed(&self.as_raw().point)
}
}
+4 -6
View File
@@ -131,17 +131,15 @@ fn variable_list_h256_test<Len: Unsigned>(leaves_and_skips: Vec<(u64, bool)>) ->
for (end, (_, update_cache)) in leaves_and_skips.into_iter().enumerate() {
list = VariableList::new(leaves[..end].to_vec()).unwrap();
if update_cache {
if list
if update_cache
&& list
.recalculate_tree_hash_root(&mut cache)
.unwrap()
.as_bytes()
!= &list.tree_hash_root()[..]
{
return false;
}
{
return false;
}
}
true
}
+1 -1
View File
@@ -58,7 +58,7 @@ mod tests {
let spec = &E::default_spec();
let keypair = generate_deterministic_keypair(42);
let deposit = get_deposit(keypair.clone(), spec);
let deposit = get_deposit(keypair, spec);
let data = eth1_tx_data(&deposit).expect("should produce tx data");
+1 -2
View File
@@ -123,8 +123,7 @@ fn string_to_bytes(string: &str) -> Result<Vec<u8>, String> {
/// Uses this as reference:
/// https://github.com/ethereum/eth2.0-pm/blob/9a9dbcd95e2b8e10287797bd768014ab3d842e99/interop/mocked_start/keygen_10_validators.yaml
pub fn keypairs_from_yaml_file(path: PathBuf) -> Result<Vec<Keypair>, String> {
let file =
File::open(path.clone()).map_err(|e| format!("Unable to open YAML key file: {}", e))?;
let file = File::open(path).map_err(|e| format!("Unable to open YAML key file: {}", e))?;
serde_yaml::from_reader::<_, Vec<YamlKeypair>>(file)
.map_err(|e| format!("Could not parse YAML: {:?}", e))?
+4 -4
View File
@@ -227,7 +227,7 @@ mod tests {
let genesis_state = Some(BeaconState::new(42, eth1_data, spec));
let yaml_config = Some(YamlConfig::from_spec::<E>(spec));
do_test::<E>(boot_enr, genesis_state.clone(), yaml_config.clone());
do_test::<E>(boot_enr, genesis_state, yaml_config);
do_test::<E>(None, None, None);
}
@@ -237,13 +237,13 @@ mod tests {
yaml_config: Option<YamlConfig>,
) {
let temp_dir = TempDir::new("eth2_testnet_test").expect("should create temp dir");
let base_dir = PathBuf::from(temp_dir.path().join("my_testnet"));
let base_dir = temp_dir.path().join("my_testnet");
let deposit_contract_address = "0xBB9bc244D798123fDe783fCc1C72d3Bb8C189413".to_string();
let deposit_contract_deploy_block = 42;
let testnet: Eth2TestnetConfig<E> = Eth2TestnetConfig {
deposit_contract_address: deposit_contract_address.clone(),
deposit_contract_deploy_block: deposit_contract_deploy_block,
deposit_contract_address,
deposit_contract_deploy_block,
boot_enr,
genesis_state,
yaml_config,
+1
View File
@@ -1,3 +1,4 @@
#![allow(clippy::needless_doctest_main)]
//! A wrapper around the `prometheus` crate that provides a global, `lazy_static` metrics registry
//! and functions to add and use the following components (more info at
//! [Prometheus docs](https://prometheus.io/docs/concepts/metric_types/)):
+2 -2
View File
@@ -99,7 +99,7 @@ impl<'a> SszDecoderBuilder<'a> {
let previous_offset = self
.offsets
.last()
.and_then(|o| Some(o.offset))
.map(|o| o.offset)
.unwrap_or_else(|| BYTES_PER_LENGTH_OFFSET);
if (previous_offset > offset) || (offset > self.bytes.len()) {
@@ -179,7 +179,7 @@ impl<'a> SszDecoderBuilder<'a> {
/// b: Vec<u16>,
/// }
///
/// fn main() {
/// fn ssz_decoding_example() {
/// let foo = Foo {
/// a: 42,
/// b: vec![1, 3, 3, 7]
+4 -3
View File
@@ -207,9 +207,10 @@ impl Decode for bool {
match bytes[0] {
0b0000_0000 => Ok(false),
0b0000_0001 => Ok(true),
_ => Err(DecodeError::BytesInvalid(
format!("Out-of-range for boolean: {}", bytes[0]).to_string(),
)),
_ => Err(DecodeError::BytesInvalid(format!(
"Out-of-range for boolean: {}",
bytes[0]
))),
}
}
}
+1 -1
View File
@@ -64,7 +64,7 @@ pub trait Encode {
/// b: Vec<u16>,
/// }
///
/// fn main() {
/// fn ssz_encode_example() {
/// let foo = Foo {
/// a: 42,
/// b: vec![1, 3, 3, 7]
+1 -1
View File
@@ -17,7 +17,7 @@
//! b: Vec<u16>,
//! }
//!
//! fn main() {
//! fn ssz_encode_decode_example() {
//! let foo = Foo {
//! a: 42,
//! b: vec![1, 3, 3, 7]
+1
View File
@@ -2,6 +2,7 @@ use ethereum_types::H256;
use ssz::{Decode, DecodeError, Encode};
use ssz_derive::{Decode, Encode};
#[allow(clippy::zero_prefixed_literal)]
mod round_trip {
use super::*;
+3 -5
View File
@@ -739,6 +739,7 @@ mod bitvector {
}
#[cfg(test)]
#[allow(clippy::cognitive_complexity)]
mod bitlist {
use super::*;
use crate::BitList;
@@ -937,7 +938,7 @@ mod bitlist {
fn test_set_unset(num_bits: usize) {
let mut bitfield = BitList1024::with_capacity(num_bits).unwrap();
for i in 0..num_bits + 1 {
for i in 0..=num_bits {
if i < num_bits {
// Starts as false
assert_eq!(bitfield.get(i), Ok(false));
@@ -1023,10 +1024,7 @@ mod bitlist {
vec![0b1111_1111, 0b0000_0000]
);
bitfield.set(8, true).unwrap();
assert_eq!(
bitfield.clone().into_raw_bytes(),
vec![0b1111_1111, 0b0000_0001]
);
assert_eq!(bitfield.into_raw_bytes(), vec![0b1111_1111, 0b0000_0001]);
}
#[test]
+4 -4
View File
@@ -261,15 +261,15 @@ mod test {
#[test]
fn new() {
let vec = vec![42; 5];
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec.clone());
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec);
assert!(fixed.is_err());
let vec = vec![42; 3];
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec.clone());
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec);
assert!(fixed.is_err());
let vec = vec![42; 4];
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec.clone());
let fixed: Result<FixedVector<u64, U4>, _> = FixedVector::new(vec);
assert!(fixed.is_ok());
}
@@ -299,7 +299,7 @@ mod test {
assert_eq!(&fixed[..], &vec![42, 42, 42, 0][..]);
let vec = vec![];
let fixed: FixedVector<u64, U4> = FixedVector::from(vec.clone());
let fixed: FixedVector<u64, U4> = FixedVector::from(vec);
assert_eq!(&fixed[..], &vec![0, 0, 0, 0][..]);
}
+4 -4
View File
@@ -247,15 +247,15 @@ mod test {
#[test]
fn new() {
let vec = vec![42; 5];
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec.clone());
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec);
assert!(fixed.is_err());
let vec = vec![42; 3];
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec.clone());
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec);
assert!(fixed.is_ok());
let vec = vec![42; 4];
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec.clone());
let fixed: Result<VariableList<u64, U4>, _> = VariableList::new(vec);
assert!(fixed.is_ok());
}
@@ -285,7 +285,7 @@ mod test {
assert_eq!(&fixed[..], &vec![42, 42, 42][..]);
let vec = vec![];
let fixed: VariableList<u64, U4> = VariableList::from(vec.clone());
let fixed: VariableList<u64, U4> = VariableList::from(vec);
assert_eq!(&fixed[..], &vec![][..]);
}
+1 -1
View File
@@ -46,7 +46,7 @@ fn get_hashable_fields_and_their_caches<'a>(
///
/// Return `Some(cache_field_name)` if the field has a cached tree hash attribute,
/// or `None` otherwise.
fn get_cache_field_for<'a>(field: &'a syn::Field) -> Option<syn::Ident> {
fn get_cache_field_for(field: &syn::Field) -> Option<syn::Ident> {
use syn::{MetaList, NestedMeta};
let parsed_attrs = cached_tree_hash_attr_metas(&field.attrs);