Rust 1.54.0 lints (#2483)

## Issue Addressed

N/A

## Proposed Changes

- Removing a bunch of unnecessary references
- Updated `Error::VariantError` to `Error::Variant`
- There were additional enum variant lints that I ignored, because I thought our variant names were fine
- removed `MonitoredValidator`'s `pubkey` field, because I couldn't find it used anywhere. It looks like we just use the string version of the pubkey (the `id` field) if there is no index

## Additional Info



Co-authored-by: realbigsean <seananderson33@gmail.com>
This commit is contained in:
realbigsean
2021-07-30 01:11:47 +00:00
parent 8efd9fc324
commit 303deb9969
104 changed files with 307 additions and 313 deletions
+4 -4
View File
@@ -60,7 +60,7 @@ impl<N: Unsigned> CachedTreeHash<TreeHashCache> for FixedVector<Hash256, N> {
arena: &mut CacheArena,
cache: &mut TreeHashCache,
) -> Result<Hash256, Error> {
cache.recalculate_merkle_root(arena, hash256_iter(&self))
cache.recalculate_merkle_root(arena, hash256_iter(self))
}
}
@@ -79,7 +79,7 @@ impl<N: Unsigned> CachedTreeHash<TreeHashCache> for FixedVector<u64, N> {
arena: &mut CacheArena,
cache: &mut TreeHashCache,
) -> Result<Hash256, Error> {
cache.recalculate_merkle_root(arena, u64_iter(&self))
cache.recalculate_merkle_root(arena, u64_iter(self))
}
}
@@ -98,7 +98,7 @@ impl<N: Unsigned> CachedTreeHash<TreeHashCache> for VariableList<Hash256, N> {
cache: &mut TreeHashCache,
) -> Result<Hash256, Error> {
Ok(mix_in_length(
&cache.recalculate_merkle_root(arena, hash256_iter(&self))?,
&cache.recalculate_merkle_root(arena, hash256_iter(self))?,
self.len(),
))
}
@@ -120,7 +120,7 @@ impl<N: Unsigned> CachedTreeHash<TreeHashCache> for VariableList<u64, N> {
cache: &mut TreeHashCache,
) -> Result<Hash256, Error> {
Ok(mix_in_length(
&cache.recalculate_merkle_root(arena, u64_iter(&self))?,
&cache.recalculate_merkle_root(arena, u64_iter(self))?,
self.len(),
))
}
+2 -2
View File
@@ -270,11 +270,11 @@ mod tests {
return TestResult::discard();
}
let leaves: Vec<_> = int_leaves.into_iter().map(H256::from_low_u64_be).collect();
let leaves_iter = int_leaves.into_iter().map(H256::from_low_u64_be);
let mut merkle_tree = MerkleTree::create(&[], depth);
let proofs_ok = leaves.into_iter().enumerate().all(|(i, leaf)| {
let proofs_ok = leaves_iter.enumerate().all(|(i, leaf)| {
assert_eq!(merkle_tree.push_leaf(leaf, depth), Ok(()));
let (stored_leaf, branch) = merkle_tree.generate_proof(i, depth);
stored_leaf == leaf && verify_merkle_proof(leaf, &branch, depth, i, merkle_tree.hash())
+48 -48
View File
@@ -210,7 +210,7 @@ impl ProtoArray {
.ok_or(Error::InvalidBestDescendant(best_descendant_index))?;
// Perform a sanity check that the node is indeed valid to be the head.
if !self.node_is_viable_for_head(&best_node) {
if !self.node_is_viable_for_head(best_node) {
return Err(Error::InvalidBestNode {
start_root: *justified_root,
justified_epoch: self.justified_epoch,
@@ -321,7 +321,7 @@ impl ProtoArray {
.get(parent_index)
.ok_or(Error::InvalidNodeIndex(parent_index))?;
let child_leads_to_viable_head = self.node_leads_to_viable_head(&child)?;
let child_leads_to_viable_head = self.node_leads_to_viable_head(child)?;
// These three variables are aliases to the three options that we may set the
// `parent.best_child` and `parent.best_descendant` to.
@@ -334,54 +334,54 @@ impl ProtoArray {
);
let no_change = (parent.best_child, parent.best_descendant);
let (new_best_child, new_best_descendant) =
if let Some(best_child_index) = parent.best_child {
if best_child_index == child_index && !child_leads_to_viable_head {
// If the child is already the best-child of the parent but it's not viable for
// the head, remove it.
change_to_none
} else if best_child_index == child_index {
// If the child is the best-child already, set it again to ensure that the
// best-descendant of the parent is updated.
change_to_child
} else {
let best_child = self
.nodes
.get(best_child_index)
.ok_or(Error::InvalidBestDescendant(best_child_index))?;
let best_child_leads_to_viable_head =
self.node_leads_to_viable_head(&best_child)?;
if child_leads_to_viable_head && !best_child_leads_to_viable_head {
// The child leads to a viable head, but the current best-child doesn't.
change_to_child
} else if !child_leads_to_viable_head && best_child_leads_to_viable_head {
// The best child leads to a viable head, but the child doesn't.
no_change
} else if child.weight == best_child.weight {
// Tie-breaker of equal weights by root.
if child.root >= best_child.root {
change_to_child
} else {
no_change
}
} else {
// Choose the winner by weight.
if child.weight >= best_child.weight {
change_to_child
} else {
no_change
}
}
}
} else if child_leads_to_viable_head {
// There is no current best-child and the child is viable.
let (new_best_child, new_best_descendant) = if let Some(best_child_index) =
parent.best_child
{
if best_child_index == child_index && !child_leads_to_viable_head {
// If the child is already the best-child of the parent but it's not viable for
// the head, remove it.
change_to_none
} else if best_child_index == child_index {
// If the child is the best-child already, set it again to ensure that the
// best-descendant of the parent is updated.
change_to_child
} else {
// There is no current best-child but the child is not viable.
no_change
};
let best_child = self
.nodes
.get(best_child_index)
.ok_or(Error::InvalidBestDescendant(best_child_index))?;
let best_child_leads_to_viable_head = self.node_leads_to_viable_head(best_child)?;
if child_leads_to_viable_head && !best_child_leads_to_viable_head {
// The child leads to a viable head, but the current best-child doesn't.
change_to_child
} else if !child_leads_to_viable_head && best_child_leads_to_viable_head {
// The best child leads to a viable head, but the child doesn't.
no_change
} else if child.weight == best_child.weight {
// Tie-breaker of equal weights by root.
if child.root >= best_child.root {
change_to_child
} else {
no_change
}
} else {
// Choose the winner by weight.
if child.weight >= best_child.weight {
change_to_child
} else {
no_change
}
}
}
} else if child_leads_to_viable_head {
// There is no current best-child and the child is viable.
change_to_child
} else {
// There is no current best-child but the child is not viable.
no_change
};
let parent = self
.nodes
@@ -148,8 +148,8 @@ impl ProtoArrayForkChoice {
let deltas = compute_deltas(
&self.proto_array.indices,
&mut self.votes,
&old_balances,
&new_balances,
old_balances,
new_balances,
)
.map_err(|e| format!("find_head compute_deltas failed: {:?}", e))?;
+1 -1
View File
@@ -9,7 +9,7 @@ mod round_trip {
for item in items {
let encoded = &item.as_ssz_bytes();
assert_eq!(item.ssz_bytes_len(), encoded.len());
assert_eq!(T::from_ssz_bytes(&encoded), Ok(item));
assert_eq!(T::from_ssz_bytes(encoded), Ok(item));
}
}
+2 -2
View File
@@ -17,7 +17,7 @@ fn get_serializable_named_field_idents(struct_data: &syn::DataStruct) -> Vec<&sy
.fields
.iter()
.filter_map(|f| {
if should_skip_serializing(&f) {
if should_skip_serializing(f) {
None
} else {
Some(match &f.ident {
@@ -36,7 +36,7 @@ fn get_serializable_field_types(struct_data: &syn::DataStruct) -> Vec<&syn::Type
.fields
.iter()
.filter_map(|f| {
if should_skip_serializing(&f) {
if should_skip_serializing(f) {
None
} else {
Some(&f.ty)
+1 -1
View File
@@ -364,7 +364,7 @@ mod test {
fn ssz_round_trip<T: Encode + Decode + std::fmt::Debug + PartialEq>(item: T) {
let encoded = &item.as_ssz_bytes();
assert_eq!(item.ssz_bytes_len(), encoded.len());
assert_eq!(T::from_ssz_bytes(&encoded), Ok(item));
assert_eq!(T::from_ssz_bytes(encoded), Ok(item));
}
#[test]
+1 -1
View File
@@ -345,7 +345,7 @@ mod test {
fn round_trip<T: Encode + Decode + std::fmt::Debug + PartialEq>(item: T) {
let encoded = &item.as_ssz_bytes();
assert_eq!(item.ssz_bytes_len(), encoded.len());
assert_eq!(T::from_ssz_bytes(&encoded), Ok(item));
assert_eq!(T::from_ssz_bytes(encoded), Ok(item));
}
#[test]
+1 -1
View File
@@ -34,7 +34,7 @@ pub fn initialize_beacon_state_from_eth1<T: EthSpec>(
.push_leaf(deposit.data.tree_hash_root())
.map_err(BlockProcessingError::MerkleTreeError)?;
state.eth1_data_mut().deposit_root = deposit_tree.root();
process_deposit(&mut state, &deposit, spec, true)?;
process_deposit(&mut state, deposit, spec, true)?;
}
process_activations(&mut state, spec)?;
@@ -244,10 +244,10 @@ where
.iter()
.try_for_each(|attester_slashing| {
let (set_1, set_2) = attester_slashing_signature_sets(
&self.state,
self.state,
self.get_pubkey.clone(),
attester_slashing,
&self.spec,
self.spec,
)?;
self.sets.push(set_1);
@@ -280,11 +280,11 @@ where
get_indexed_attestation(committee.committee, attestation)?;
self.sets.push(indexed_attestation_signature_set(
&self.state,
self.state,
self.get_pubkey.clone(),
&attestation.signature,
&indexed_attestation,
&self.spec,
self.spec,
)?);
vec.push(indexed_attestation);
@@ -307,7 +307,7 @@ where
.iter()
.try_for_each(|exit| {
let exit =
exit_signature_set(&self.state, self.get_pubkey.clone(), exit, &self.spec)?;
exit_signature_set(self.state, self.get_pubkey.clone(), exit, self.spec)?;
self.sets.push(exit);
@@ -323,8 +323,8 @@ where
sync_aggregate,
block.slot(),
block.parent_root(),
&self.state,
&self.spec,
self.state,
self.spec,
)? {
self.sets.push(signature_set);
}
@@ -44,7 +44,7 @@ pub fn is_valid_indexed_attestation<T: EthSpec>(
state,
|i| get_pubkey_from_state(state, i),
&indexed_attestation.signature,
&indexed_attestation,
indexed_attestation,
spec
)?
.verify(),
@@ -177,7 +177,7 @@ pub fn process_proposer_slashings<T: EthSpec>(
.iter()
.enumerate()
.try_for_each(|(i, proposer_slashing)| {
verify_proposer_slashing(proposer_slashing, &state, verify_signatures, spec)
verify_proposer_slashing(proposer_slashing, state, verify_signatures, spec)
.map_err(|e| e.into_with_index(i))?;
slash_validator(
@@ -202,11 +202,11 @@ pub fn process_attester_slashings<T: EthSpec>(
spec: &ChainSpec,
) -> Result<(), BlockProcessingError> {
for (i, attester_slashing) in attester_slashings.iter().enumerate() {
verify_attester_slashing(&state, &attester_slashing, verify_signatures, spec)
verify_attester_slashing(state, attester_slashing, verify_signatures, spec)
.map_err(|e| e.into_with_index(i))?;
let slashable_indices =
get_slashable_indices(&state, &attester_slashing).map_err(|e| e.into_with_index(i))?;
get_slashable_indices(state, attester_slashing).map_err(|e| e.into_with_index(i))?;
for i in slashable_indices {
slash_validator(state, i as usize, None, spec)?;
@@ -254,7 +254,7 @@ pub fn process_exits<T: EthSpec>(
// Verify and apply each exit in series. We iterate in series because higher-index exits may
// become invalid due to the application of lower-index ones.
for (i, exit) in voluntary_exits.iter().enumerate() {
verify_exit(&state, exit, verify_signatures, spec).map_err(|e| e.into_with_index(i))?;
verify_exit(state, exit, verify_signatures, spec).map_err(|e| e.into_with_index(i))?;
initiate_validator_exit(state, exit.message.validator_index as usize, spec)?;
}
@@ -257,7 +257,7 @@ where
let domain = spec.get_domain(
indexed_attestation.data.target.epoch,
Domain::BeaconAttester,
&fork,
fork,
genesis_validators_root,
);
@@ -494,7 +494,7 @@ where
pubkeys.push(get_pubkey(pubkey).ok_or_else(|| Error::ValidatorPubkeyUnknown(*pubkey))?);
}
let domain = spec.get_domain(epoch, Domain::SyncCommittee, &fork, genesis_validators_root);
let domain = spec.get_domain(epoch, Domain::SyncCommittee, fork, genesis_validators_root);
let message = beacon_block_root.signing_root(domain);
@@ -513,7 +513,7 @@ pub fn sync_committee_message_set_from_pubkeys<'a, T>(
where
T: EthSpec,
{
let domain = spec.get_domain(epoch, Domain::SyncCommittee, &fork, genesis_validators_root);
let domain = spec.get_domain(epoch, Domain::SyncCommittee, fork, genesis_validators_root);
let message = beacon_block_root.signing_root(domain);
@@ -33,9 +33,9 @@ pub fn verify_attester_slashing<T: EthSpec>(
Invalid::NotSlashable
);
is_valid_indexed_attestation(state, &attestation_1, verify_signatures, spec)
is_valid_indexed_attestation(state, attestation_1, verify_signatures, spec)
.map_err(|e| error(Invalid::IndexedAttestation1Invalid(e)))?;
is_valid_indexed_attestation(state, &attestation_2, verify_signatures, spec)
is_valid_indexed_attestation(state, attestation_2, verify_signatures, spec)
.map_err(|e| error(Invalid::IndexedAttestation2Invalid(e)))?;
Ok(())
@@ -15,7 +15,7 @@ fn error(reason: DepositInvalid) -> BlockOperationError<DepositInvalid> {
///
/// Spec v0.12.1
pub fn verify_deposit_signature(deposit_data: &DepositData, spec: &ChainSpec) -> Result<()> {
let (public_key, signature, msg) = deposit_pubkey_signature_message(&deposit_data, spec)
let (public_key, signature, msg) = deposit_pubkey_signature_message(deposit_data, spec)
.ok_or_else(|| error(DepositInvalid::BadBlsBytes))?;
verify!(
@@ -28,7 +28,7 @@ pub fn process_epoch<T: EthSpec>(
//
// E.g., attestation in the previous epoch, attested to the head, etc.
let mut validator_statuses = ValidatorStatuses::new(state, spec)?;
validator_statuses.process_attestations(&state)?;
validator_statuses.process_attestations(state)?;
// Justification and finalization.
process_justification_and_finalization(state, &validator_statuses.total_balances, spec)?;
@@ -60,7 +60,7 @@ pub fn process_rewards_and_penalties<T: EthSpec>(
return Err(Error::ValidatorStatusesInconsistent);
}
let deltas = get_attestation_deltas(state, &validator_statuses, spec)?;
let deltas = get_attestation_deltas(state, validator_statuses, spec)?;
// Apply the deltas, erroring on overflow above but not on overflow below (saturating at 0
// instead).
@@ -26,7 +26,7 @@ pub fn translate_participation<E: EthSpec>(
// Apply flags to all attesting validators.
let committee = state.get_beacon_committee(data.slot, data.index)?;
let attesting_indices =
get_attesting_indices::<E>(&committee.committee, &attestation.aggregation_bits)?;
get_attesting_indices::<E>(committee.committee, &attestation.aggregation_bits)?;
let epoch_participation = state.previous_epoch_participation_mut()?;
for index in attesting_indices {
+2 -2
View File
@@ -221,7 +221,7 @@ mod test {
use crate::ZERO_HASHES_MAX_INDEX;
pub fn reference_root(bytes: &[u8]) -> Hash256 {
crate::merkleize_standard(&bytes)
crate::merkleize_standard(bytes)
}
macro_rules! common_tests {
@@ -322,7 +322,7 @@ mod test {
assert_eq!(
reference_root(&reference_input),
merkleize_padded(&input, min_nodes),
merkleize_padded(input, min_nodes),
"input.len(): {:?}",
input.len()
);
+3 -3
View File
@@ -23,14 +23,14 @@ fn get_hashable_fields_and_their_caches(
.fields
.iter()
.filter_map(|f| {
if should_skip_hashing(&f) {
if should_skip_hashing(f) {
None
} else {
let ident = f
.ident
.as_ref()
.expect("tree_hash_derive only supports named struct fields");
let opt_cache_field = get_cache_field_for(&f);
let opt_cache_field = get_cache_field_for(f);
Some((ident, f.ty.clone(), opt_cache_field))
}
})
@@ -94,7 +94,7 @@ fn tree_hash_derive_struct(item: &DeriveInput, struct_data: &DataStruct) -> Toke
let name = &item.ident;
let (impl_generics, ty_generics, where_clause) = &item.generics.split_for_impl();
let idents = get_hashable_fields(&struct_data);
let idents = get_hashable_fields(struct_data);
let num_leaves = idents.len();
let output = quote! {
+4 -4
View File
@@ -489,7 +489,7 @@ impl<T: EthSpec> BeaconState<T> {
) -> Result<&[usize], Error> {
let cache = self.committee_cache(relative_epoch)?;
Ok(&cache.active_validator_indices())
Ok(cache.active_validator_indices())
}
/// Returns the active validator indices for the given epoch.
@@ -770,7 +770,7 @@ impl<T: EthSpec> BeaconState<T> {
.pubkeys
.iter()
.map(|pubkey| {
self.get_validator_index(&pubkey)?
self.get_validator_index(pubkey)?
.ok_or(Error::PubkeyCacheInconsistent)
})
.collect()
@@ -1326,7 +1326,7 @@ impl<T: EthSpec> BeaconState<T> {
epoch: Epoch,
spec: &ChainSpec,
) -> Result<CommitteeCache, Error> {
CommitteeCache::initialized(&self, epoch, spec)
CommitteeCache::initialized(self, epoch, spec)
}
/// Advances the cache for this state into the next epoch.
@@ -1438,7 +1438,7 @@ impl<T: EthSpec> BeaconState<T> {
if let Some(mut cache) = cache {
// Note: we return early if the tree hash fails, leaving `self.tree_hash_cache` as
// None. There's no need to keep a cache that fails.
let root = cache.recalculate_tree_hash_root(&self)?;
let root = cache.recalculate_tree_hash_root(self)?;
self.tree_hash_cache_mut().restore(cache);
Ok(root)
} else {
@@ -67,13 +67,13 @@ fn initializes_with_the_right_epoch() {
let cache = CommitteeCache::default();
assert!(!cache.is_initialized_at(state.current_epoch()));
let cache = CommitteeCache::initialized(&state, state.current_epoch(), &spec).unwrap();
let cache = CommitteeCache::initialized(&state, state.current_epoch(), spec).unwrap();
assert!(cache.is_initialized_at(state.current_epoch()));
let cache = CommitteeCache::initialized(&state, state.previous_epoch(), &spec).unwrap();
let cache = CommitteeCache::initialized(&state, state.previous_epoch(), spec).unwrap();
assert!(cache.is_initialized_at(state.previous_epoch()));
let cache = CommitteeCache::initialized(&state, state.next_epoch().unwrap(), &spec).unwrap();
let cache = CommitteeCache::initialized(&state, state.next_epoch().unwrap(), spec).unwrap();
assert!(cache.is_initialized_at(state.next_epoch().unwrap()));
}
+2 -2
View File
@@ -59,7 +59,7 @@ fn test_beacon_proposer_index<T: EthSpec>() {
// Get the i'th candidate proposer for the given state and slot
let ith_candidate = |state: &BeaconState<T>, slot: Slot, i: usize, spec: &ChainSpec| {
let epoch = slot.epoch(T::slots_per_epoch());
let seed = state.get_beacon_proposer_seed(slot, &spec).unwrap();
let seed = state.get_beacon_proposer_seed(slot, spec).unwrap();
let active_validators = state.get_active_validator_indices(epoch, spec).unwrap();
active_validators[compute_shuffled_index(
i,
@@ -338,7 +338,7 @@ mod committees {
new_head_state,
cache_epoch,
validator_count as usize,
&spec,
spec,
);
}
@@ -247,7 +247,7 @@ impl<T: EthSpec> BeaconTreeHashCacheInner<T> {
hasher.write(state.eth1_data().tree_hash_root().as_bytes())?;
hasher.write(
self.eth1_data_votes
.recalculate_tree_hash_root(&state)?
.recalculate_tree_hash_root(state)?
.as_bytes(),
)?;
hasher.write(state.eth1_deposit_index().tree_hash_root().as_bytes())?;
+1 -1
View File
@@ -84,7 +84,7 @@ impl Into<Graffiti> for GraffitiString {
graffiti
.get_mut(..graffiti_len)
.expect("graffiti_len <= GRAFFITI_BYTES_LEN")
.copy_from_slice(&graffiti_bytes);
.copy_from_slice(graffiti_bytes);
graffiti.into()
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ impl<'a, N: Unsigned> CachedTreeHash<TreeHashCache> for ParticipationList<'a, N>
cache: &mut TreeHashCache,
) -> Result<Hash256, Error> {
Ok(mix_in_length(
&cache.recalculate_merkle_root(arena, leaf_iter(&self.inner))?,
&cache.recalculate_merkle_root(arena, leaf_iter(self.inner))?,
self.inner.len(),
))
}
+1 -1
View File
@@ -24,7 +24,7 @@ pub struct SubnetId(#[serde(with = "serde_utils::quoted_u64")] u64);
pub fn subnet_id_to_string(i: u64) -> &'static str {
if i < MAX_SUBNET_ID as u64 {
&SUBNET_ID_TO_STRING
SUBNET_ID_TO_STRING
.get(i as usize)
.expect("index below MAX_SUBNET_ID")
} else {
+1 -1
View File
@@ -21,7 +21,7 @@ pub struct SyncSubnetId(#[serde(with = "serde_utils::quoted_u64")] u64);
pub fn sync_subnet_id_to_string(i: u64) -> &'static str {
if i < SYNC_COMMITTEE_SUBNET_COUNT {
&SYNC_SUBNET_ID_TO_STRING
SYNC_SUBNET_ID_TO_STRING
.get(i as usize)
.expect("index below SYNC_COMMITTEE_SUBNET_COUNT")
} else {
+1 -1
View File
@@ -77,7 +77,7 @@ fn process_pubkey_bytes_field(
fn process_slice_field(new_tree_hash: &[u8], leaf: &mut Hash256, force_update: bool) -> bool {
if force_update || leaf.as_bytes() != new_tree_hash {
leaf.assign_from_slice(&new_tree_hash);
leaf.assign_from_slice(new_tree_hash);
true
} else {
false