Fix clippy warnings (#1385)

## Issue Addressed

NA

## Proposed Changes

Fixes most clippy warnings and ignores the rest of them, see issue #1388.
This commit is contained in:
blacktemplar
2020-07-23 14:18:00 +00:00
parent ba10c80633
commit 23a8f31f83
93 changed files with 396 additions and 396 deletions

View File

@@ -287,7 +287,7 @@ impl<T: BeaconChainTypes> VerifiedAggregatedAttestation<T> {
if chain
.observed_aggregators
.observe_validator(&attestation, aggregator_index as usize)
.map_err(|e| BeaconChainError::from(e))?
.map_err(BeaconChainError::from)?
{
return Err(Error::PriorAttestationKnown {
validator_index: aggregator_index,
@@ -370,7 +370,7 @@ impl<T: BeaconChainTypes> VerifiedUnaggregatedAttestation<T> {
if chain
.observed_attesters
.validator_has_been_observed(&attestation, validator_index as usize)
.map_err(|e| BeaconChainError::from(e))?
.map_err(BeaconChainError::from)?
{
return Err(Error::PriorAttestationKnown {
validator_index,
@@ -390,7 +390,7 @@ impl<T: BeaconChainTypes> VerifiedUnaggregatedAttestation<T> {
if chain
.observed_attesters
.observe_validator(&attestation, validator_index as usize)
.map_err(|e| BeaconChainError::from(e))?
.map_err(BeaconChainError::from)?
{
return Err(Error::PriorAttestationKnown {
validator_index,
@@ -504,7 +504,7 @@ pub fn verify_attestation_signature<T: BeaconChainTypes>(
.canonical_head
.try_read_for(HEAD_LOCK_TIMEOUT)
.ok_or_else(|| BeaconChainError::CanonicalHeadLockTimeout)
.map(|head| head.beacon_state.fork.clone())?;
.map(|head| head.beacon_state.fork)?;
let signature_set = indexed_attestation_signature_set_from_pubkeys(
|validator_index| pubkey_cache.get(validator_index).map(Cow::Borrowed),
@@ -559,7 +559,7 @@ pub fn verify_signed_aggregate_signatures<T: BeaconChainTypes>(
.canonical_head
.try_read_for(HEAD_LOCK_TIMEOUT)
.ok_or_else(|| BeaconChainError::CanonicalHeadLockTimeout)
.map(|head| head.beacon_state.fork.clone())?;
.map(|head| head.beacon_state.fork)?;
let signature_sets = vec![
signed_aggregate_selection_proof_signature_set(
@@ -694,7 +694,7 @@ where
// The state roots are not useful for the shuffling, so there's no need to
// compute them.
per_slot_processing(&mut state, Some(Hash256::zero()), &chain.spec)
.map_err(|e| BeaconChainError::from(e))?;
.map_err(BeaconChainError::from)?;
}
metrics::stop_timer(state_skip_timer);
@@ -706,11 +706,11 @@ where
state
.build_committee_cache(relative_epoch, &chain.spec)
.map_err(|e| BeaconChainError::from(e))?;
.map_err(BeaconChainError::from)?;
let committee_cache = state
.committee_cache(relative_epoch)
.map_err(|e| BeaconChainError::from(e))?;
.map_err(BeaconChainError::from)?;
chain
.shuffling_cache

View File

@@ -199,6 +199,8 @@ pub struct BeaconChain<T: BeaconChainTypes> {
pub genesis_block_root: Hash256,
/// The root of the list of genesis validators, used during syncing.
pub genesis_validators_root: Hash256,
#[allow(clippy::type_complexity)]
/// A state-machine that is updated with information from the network and chooses a canonical
/// head block.
pub fork_choice: RwLock<
@@ -493,9 +495,9 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
slot: head.beacon_block.slot(),
block_root: head.beacon_block_root,
state_root: head.beacon_state_root,
current_justified_checkpoint: head.beacon_state.current_justified_checkpoint.clone(),
finalized_checkpoint: head.beacon_state.finalized_checkpoint.clone(),
fork: head.beacon_state.fork.clone(),
current_justified_checkpoint: head.beacon_state.current_justified_checkpoint,
finalized_checkpoint: head.beacon_state.finalized_checkpoint,
fork: head.beacon_state.fork,
genesis_time: head.beacon_state.genesis_time,
genesis_validators_root: head.beacon_state.genesis_validators_root,
})
@@ -853,8 +855,8 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
data: AttestationData {
slot,
index,
beacon_block_root: beacon_block_root,
source: state.current_justified_checkpoint.clone(),
beacon_block_root,
source: state.current_justified_checkpoint,
target: Checkpoint {
epoch,
root: target_root,
@@ -986,8 +988,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
.try_read_for(HEAD_LOCK_TIMEOUT)
.ok_or_else(|| Error::CanonicalHeadLockTimeout)?
.beacon_state
.fork
.clone();
.fork;
self.op_pool
.insert_attestation(
@@ -1348,7 +1349,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
};
// Verify and import the block.
let result = match import_block(unverified_block) {
match import_block(unverified_block) {
// The block was successfully verified and imported. Yay.
Ok(block_root) => {
trace!(
@@ -1362,7 +1363,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
metrics::inc_counter(&metrics::BLOCK_PROCESSING_SUCCESSES);
let _ = self.event_handler.register(EventKind::BeaconBlockImported {
block_root: block_root,
block_root,
block: Box::new(block),
});
@@ -1399,9 +1400,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
Err(other)
}
};
result
}
}
/// Accepts a fully-verified block and imports it into the chain without performing any
@@ -1642,7 +1641,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
body: BeaconBlockBody {
randao_reveal,
eth1_data,
graffiti: self.graffiti.clone(),
graffiti: self.graffiti,
proposer_slashings: proposer_slashings.into(),
attester_slashings: attester_slashings.into(),
attestations: self
@@ -1718,7 +1717,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
.snapshot_cache
.try_read_for(BLOCK_PROCESSING_CACHE_LOCK_TIMEOUT)
.and_then(|snapshot_cache| snapshot_cache.get_cloned(beacon_block_root))
.map::<Result<_, Error>, _>(|snapshot| Ok(snapshot))
.map::<Result<_, Error>, _>(Ok)
.unwrap_or_else(|| {
let beacon_block = self
.get_block(&beacon_block_root)?
@@ -2010,8 +2009,8 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
let mut finalized_blocks: HashSet<Hash256> = HashSet::new();
let genesis_block_hash = Hash256::zero();
write!(output, "digraph beacon {{\n").unwrap();
write!(output, "\t_{:?}[label=\"genesis\"];\n", genesis_block_hash).unwrap();
writeln!(output, "digraph beacon {{").unwrap();
writeln!(output, "\t_{:?}[label=\"genesis\"];", genesis_block_hash).unwrap();
// Canonical head needs to be processed first as otherwise finalized blocks aren't detected
// properly.
@@ -2045,36 +2044,36 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
}
if block_hash == canonical_head_hash {
write!(
writeln!(
output,
"\t_{:?}[label=\"{} ({})\" shape=box3d];\n",
"\t_{:?}[label=\"{} ({})\" shape=box3d];",
block_hash,
block_hash,
signed_beacon_block.slot()
)
.unwrap();
} else if finalized_blocks.contains(&block_hash) {
write!(
writeln!(
output,
"\t_{:?}[label=\"{} ({})\" shape=Msquare];\n",
"\t_{:?}[label=\"{} ({})\" shape=Msquare];",
block_hash,
block_hash,
signed_beacon_block.slot()
)
.unwrap();
} else {
write!(
writeln!(
output,
"\t_{:?}[label=\"{} ({})\" shape=box];\n",
"\t_{:?}[label=\"{} ({})\" shape=box];",
block_hash,
block_hash,
signed_beacon_block.slot()
)
.unwrap();
}
write!(
writeln!(
output,
"\t_{:?} -> _{:?};\n",
"\t_{:?} -> _{:?};",
block_hash,
signed_beacon_block.parent_root()
)
@@ -2082,7 +2081,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
}
}
write!(output, "}}\n").unwrap();
writeln!(output, "}}").unwrap();
}
// Used for debugging
@@ -2135,7 +2134,7 @@ impl From<BeaconStateError> for Error {
}
impl ChainSegmentResult {
pub fn to_block_error(self) -> Result<(), BlockError> {
pub fn into_block_error(self) -> Result<(), BlockError> {
match self {
ChainSegmentResult::Failed { error, .. } => Err(error),
ChainSegmentResult::Successful { .. } => Ok(()),

View File

@@ -584,8 +584,9 @@ impl<'a, T: BeaconChainTypes> FullyVerifiedBlock<'a, T> {
state_root
};
per_slot_processing(&mut state, Some(state_root), &chain.spec)?
.map(|summary| summaries.push(summary));
if let Some(summary) = per_slot_processing(&mut state, Some(state_root), &chain.spec)? {
summaries.push(summary)
}
}
expose_participation_metrics(&summaries);

View File

@@ -93,6 +93,7 @@ where
///
/// See the tests for an example of a complete working example.
pub struct BeaconChainBuilder<T: BeaconChainTypes> {
#[allow(clippy::type_complexity)]
store: Option<Arc<HotColdDB<T::EthSpec, T::HotStore, T::ColdStore>>>,
store_migrator: Option<T::StoreMigrator>,
canonical_head: Option<BeaconSnapshot<T::EthSpec>>,
@@ -461,13 +462,10 @@ where
.pubkey_cache_path
.ok_or_else(|| "Cannot build without a pubkey cache path".to_string())?;
let validator_pubkey_cache = self
.validator_pubkey_cache
.map(|cache| Ok(cache))
.unwrap_or_else(|| {
ValidatorPubkeyCache::new(&canonical_head.beacon_state, pubkey_cache_path)
.map_err(|e| format!("Unable to init validator pubkey cache: {:?}", e))
})?;
let validator_pubkey_cache = self.validator_pubkey_cache.map(Ok).unwrap_or_else(|| {
ValidatorPubkeyCache::new(&canonical_head.beacon_state, pubkey_cache_path)
.map_err(|e| format!("Unable to init validator pubkey cache: {:?}", e))
})?;
let persisted_fork_choice = store
.get_item::<PersistedForkChoice>(&Hash256::from_slice(&FORK_CHOICE_DB_KEY))

View File

@@ -331,7 +331,7 @@ impl<T: EthSpec> Eth1ChainBackend<T> for CachingEth1Backend<T> {
//
// Here we choose the eth1_data corresponding to the latest block in our voting window.
// If no votes exist, choose `state.eth1_data` as default vote.
let default_vote = votes_to_consider
votes_to_consider
.iter()
.max_by(|(_, x), (_, y)| x.cmp(y))
.map(|vote| {
@@ -355,8 +355,7 @@ impl<T: EthSpec> Eth1ChainBackend<T> for CachingEth1Backend<T> {
);
metrics::inc_counter(&metrics::DEFAULT_ETH1_VOTES);
vote
});
default_vote
})
};
debug!(

View File

@@ -37,7 +37,7 @@ impl<T: EthSpec> ServerSentEvents<T> {
let arc = Arc::new(mutex);
let this = Self {
head_changed_queue: arc.clone(),
log: log,
log,
_phantom: PhantomData,
};
(this, arc)
@@ -52,7 +52,10 @@ impl<T: EthSpec> EventHandler<T> for ServerSentEvents<T> {
..
} => {
let mut guard = self.head_changed_queue.lock();
if let Err(_) = guard.try_broadcast(current_head_beacon_block_root.into()) {
if guard
.try_broadcast(current_head_beacon_block_root.into())
.is_err()
{
error!(
self.log,
"Head change streaming queue full";
@@ -75,14 +78,15 @@ pub struct TeeEventHandler<E: EthSpec> {
}
impl<E: EthSpec> TeeEventHandler<E> {
#[allow(clippy::type_complexity)]
pub fn new(
log: Logger,
websockets_handler: WebSocketSender<E>,
) -> Result<(Self, Arc<Mutex<Bus<SignedBeaconBlockHash>>>), String> {
let (sse_handler, bus) = ServerSentEvents::new(log);
let result = Self {
websockets_handler: websockets_handler,
sse_handler: sse_handler,
websockets_handler,
sse_handler,
};
Ok((result, bus))
}

View File

@@ -154,7 +154,7 @@ pub trait Migrate<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>>:
let batch: Vec<StoreOp<E>> = abandoned_blocks
.into_iter()
.map(|block_hash| StoreOp::DeleteBlock(block_hash))
.map(StoreOp::DeleteBlock)
.chain(
abandoned_states
.into_iter()
@@ -296,6 +296,7 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
finality_distance > max_finality_distance
}
#[allow(clippy::type_complexity)]
/// Spawn a new child thread to run the migration process.
///
/// Return a channel handle for sending new finalized states to the thread.

View File

@@ -88,9 +88,9 @@ impl Item for EpochBitfield {
.unwrap_or_else(|| {
self.bitfield
.resize(validator_index.saturating_add(1), false);
self.bitfield
.get_mut(validator_index)
.map(|mut bit| *bit = true);
if let Some(mut bit) = self.bitfield.get_mut(validator_index) {
*bit = true;
}
false
})
}

View File

@@ -393,6 +393,7 @@ where
(block_root.into(), new_state)
}
#[allow(clippy::type_complexity)]
/// `add_block()` repeated `num_blocks` times.
pub fn add_blocks(
&self,
@@ -422,6 +423,7 @@ where
(blocks, states, slot, head_hash, state)
}
#[allow(clippy::type_complexity)]
/// A wrapper on `add_blocks()` to avoid passing enums explicitly.
pub fn add_canonical_chain_blocks(
&self,
@@ -446,6 +448,7 @@ where
)
}
#[allow(clippy::type_complexity)]
/// A wrapper on `add_blocks()` to avoid passing enums explicitly.
pub fn add_stray_blocks(
&self,

View File

@@ -138,8 +138,8 @@ struct ValidatorPubkeyCacheFile(File);
#[derive(Debug)]
enum Error {
IoError(io::Error),
SszError(DecodeError),
Io(io::Error),
Ssz(DecodeError),
/// The file read from disk does not have a contiguous list of validator public keys. The file
/// has become corrupted.
InconsistentIndex {
@@ -162,7 +162,7 @@ impl ValidatorPubkeyCacheFile {
.write(true)
.open(path)
.map(Self)
.map_err(Error::IoError)
.map_err(Error::Io)
}
/// Opens an existing file for reading and writing.
@@ -174,7 +174,7 @@ impl ValidatorPubkeyCacheFile {
.append(true)
.open(path)
.map(Self)
.map_err(Error::IoError)
.map_err(Error::Io)
}
/// Append a public key to file.
@@ -188,10 +188,9 @@ impl ValidatorPubkeyCacheFile {
/// Creates a `ValidatorPubkeyCache` by reading and parsing the underlying file.
pub fn into_cache(mut self) -> Result<ValidatorPubkeyCache, Error> {
let mut bytes = vec![];
self.0.read_to_end(&mut bytes).map_err(Error::IoError)?;
self.0.read_to_end(&mut bytes).map_err(Error::Io)?;
let list: Vec<(usize, PublicKeyBytes)> =
Vec::from_ssz_bytes(&bytes).map_err(Error::SszError)?;
let list: Vec<(usize, PublicKeyBytes)> = Vec::from_ssz_bytes(&bytes).map_err(Error::Ssz)?;
let mut last = None;
let mut pubkeys = Vec::with_capacity(list.len());
@@ -201,7 +200,7 @@ impl ValidatorPubkeyCacheFile {
let expected = last.map(|n| n + 1);
if expected.map_or(true, |expected| index == expected) {
last = Some(index);
pubkeys.push((&pubkey).try_into().map_err(Error::SszError)?);
pubkeys.push((&pubkey).try_into().map_err(Error::Ssz)?);
indices.insert(pubkey, index);
} else {
return Err(Error::InconsistentIndex {
@@ -225,7 +224,7 @@ fn append_to_file(file: &mut File, index: usize, pubkey: &PublicKeyBytes) -> Res
index.ssz_append(&mut line);
pubkey.ssz_append(&mut line);
file.write_all(&mut line).map_err(Error::IoError)
file.write_all(&line).map_err(Error::Io)
}
#[cfg(test)]