Clippy clean (#536)

* Change into_iter to iter

* Fix clippy 'easy' warnings

* Clippy eth2/utils

* Add struct NetworkInfo

* Clippy for types, utils, and beacon_node/store/src/iters.rs

* Cargo fmt

* Change foo to my_foo

* Remove complex signature

* suppress clippy warning for unit_value in benches

* Use enumerate instead of iterating over range

* Allow trivially_copy_pass_by_ref in serde_utils
This commit is contained in:
pscott
2019-09-30 05:58:45 +02:00
committed by Paul Hauner
parent 682b11f248
commit 7eb82125ef
39 changed files with 118 additions and 121 deletions

View File

@@ -125,6 +125,8 @@ pub struct BeaconChain<T: BeaconChainTypes> {
log: Logger,
}
type BeaconInfo<T> = (BeaconBlock<T>, BeaconState<T>);
impl<T: BeaconChainTypes> BeaconChain<T> {
/// Instantiate a new Beacon Chain, from genesis.
pub fn from_genesis(
@@ -1060,7 +1062,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
if block.slot <= finalized_slot {
return Ok(BlockProcessingOutcome::WouldRevertFinalizedSlot {
block_slot: block.slot,
finalized_slot: finalized_slot,
finalized_slot,
});
}
@@ -1258,7 +1260,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
&self,
randao_reveal: Signature,
slot: Slot,
) -> Result<(BeaconBlock<T::EthSpec>, BeaconState<T::EthSpec>), BlockProductionError> {
) -> Result<BeaconInfo<T::EthSpec>, BlockProductionError> {
let state = self
.state_at_slot(slot - 1)
.map_err(|_| BlockProductionError::UnableToProduceAtSlot(slot))?;
@@ -1279,7 +1281,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
mut state: BeaconState<T::EthSpec>,
produce_at_slot: Slot,
randao_reveal: Signature,
) -> Result<(BeaconBlock<T::EthSpec>, BeaconState<T::EthSpec>), BlockProductionError> {
) -> Result<BeaconInfo<T::EthSpec>, BlockProductionError> {
metrics::inc_counter(&metrics::BLOCK_PRODUCTION_REQUESTS);
let timer = metrics::start_timer(&metrics::BLOCK_PRODUCTION_TIMES);
@@ -1457,7 +1459,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
// End fork choice metrics timer.
metrics::stop_timer(timer);
if let Err(_) = result {
if result.is_err() {
metrics::inc_counter(&metrics::FORK_CHOICE_ERRORS);
}

View File

@@ -137,7 +137,7 @@ impl<T: BeaconChainTypes> BeaconChainBuilder<T> {
BuildStrategy::LoadFromStore => {
BeaconChain::from_store(store, eth1_backend, event_handler, self.spec, self.log)
.map_err(|e| format!("Error loading BeaconChain from database: {:?}", e))?
.ok_or_else(|| format!("Unable to find exising BeaconChain in database."))?
.ok_or_else(|| "Unable to find exising BeaconChain in database.".to_string())?
}
BuildStrategy::FromGenesis {
genesis_block,

View File

@@ -228,10 +228,7 @@ fn scrape_head_state<T: BeaconChainTypes>(state: &BeaconState<T::EthSpec>, state
);
set_gauge_by_usize(&HEAD_STATE_SHARDS, state.previous_crosslinks.len());
set_gauge_by_usize(&HEAD_STATE_TOTAL_VALIDATORS, state.validators.len());
set_gauge_by_u64(
&HEAD_STATE_VALIDATOR_BALANCES,
state.balances.iter().fold(0_u64, |acc, i| acc + i),
);
set_gauge_by_u64(&HEAD_STATE_VALIDATOR_BALANCES, state.balances.iter().sum());
set_gauge_by_usize(
&HEAD_STATE_ACTIVE_VALIDATORS,
state

View File

@@ -21,7 +21,7 @@ pub use types::test_utils::generate_deterministic_keypairs;
pub use crate::persisted_beacon_chain::{PersistedBeaconChain, BEACON_CHAIN_DB_KEY};
pub const HARNESS_GENESIS_TIME: u64 = 1567552690; // 4th September 2019
pub const HARNESS_GENESIS_TIME: u64 = 1_567_552_690; // 4th September 2019
/// Indicates how the `BeaconChainHarness` should produce blocks.
#[derive(Clone, Copy, Debug)]

View File

@@ -12,6 +12,7 @@ use beacon_chain::{
use exit_future::Signal;
use futures::{future::Future, Stream};
use network::Service as NetworkService;
use rest_api::NetworkInfo;
use slog::{crit, error, info, o};
use slot_clock::SlotClock;
use std::marker::PhantomData;
@@ -231,12 +232,15 @@ where
// Start the `rest_api` service
let api_exit_signal = if client_config.rest_api.enabled {
let network_info = NetworkInfo {
network_service: network.clone(),
network_chan: network_send.clone(),
};
match rest_api::start_server(
&client_config.rest_api,
executor,
beacon_chain.clone(),
network.clone(),
network_send.clone(),
network_info,
client_config.db_path().expect("unable to read datadir"),
eth2_config.clone(),
&log,

View File

@@ -68,11 +68,11 @@ pub fn parse_pubkey(string: &str) -> Result<PublicKey, ApiError> {
let pubkey = PublicKey::from_bytes(pubkey_bytes.as_slice()).map_err(|e| {
ApiError::BadRequest(format!("Unable to deserialize public key: {:?}.", e))
})?;
return Ok(pubkey);
Ok(pubkey)
} else {
return Err(ApiError::BadRequest(
Err(ApiError::BadRequest(
"Public key must have a '0x' prefix".to_string(),
));
))
}
}

View File

@@ -48,6 +48,11 @@ pub struct ApiService<T: BeaconChainTypes + 'static> {
eth2_config: Arc<Eth2Config>,
}
pub struct NetworkInfo<T: BeaconChainTypes> {
pub network_service: Arc<NetworkService<T>>,
pub network_chan: mpsc::UnboundedSender<NetworkMessage>,
}
fn into_boxfut<F: IntoFuture + 'static>(item: F) -> BoxFut
where
F: IntoFuture<Item = Response<Body>, Error = ApiError>,
@@ -194,8 +199,7 @@ pub fn start_server<T: BeaconChainTypes>(
config: &ApiConfig,
executor: &TaskExecutor,
beacon_chain: Arc<BeaconChain<T>>,
network_service: Arc<NetworkService<T>>,
network_chan: mpsc::UnboundedSender<NetworkMessage>,
network_info: NetworkInfo<T>,
db_path: PathBuf,
eth2_config: Eth2Config,
log: &slog::Logger,
@@ -226,8 +230,8 @@ pub fn start_server<T: BeaconChainTypes>(
log: server_log.clone(),
beacon_chain: server_bc.clone(),
db_path: db_path.clone(),
network_service: network_service.clone(),
network_channel: Arc::new(RwLock::new(network_chan.clone())),
network_service: network_info.network_service.clone(),
network_channel: Arc::new(RwLock::new(network_info.network_chan.clone())),
eth2_config: eth2_config.clone(),
})
};

View File

@@ -27,7 +27,7 @@ impl ResponseBuilder {
e
))
})
.map(|h| String::from(h))?;
.map(String::from)?;
// JSON is our default encoding, unless something else is requested.
let encoding = match content_header {
@@ -85,7 +85,7 @@ impl ResponseBuilder {
Response::builder()
.status(StatusCode::OK)
.header("content-type", content_type)
.body(Body::from(body))
.body(body)
.map_err(|e| ApiError::ServerError(format!("Failed to build response: {:?}", e)))
}

View File

@@ -190,7 +190,7 @@ pub fn get_new_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -
/// HTTP Handler to publish a BeaconBlock, which has been signed by a validator.
pub fn publish_beacon_block<T: BeaconChainTypes + 'static>(req: Request<Body>) -> BoxFut {
let _ = try_future!(check_content_type_for_json(&req));
try_future!(check_content_type_for_json(&req));
let log = get_logger_from_request(&req);
let beacon_chain = try_future!(get_beacon_chain_from_request::<T>(&req));
// Get the network sending channel from the request, for later transmission
@@ -268,9 +268,12 @@ pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) ->
.map_err(|e| {
ApiError::ServerError(format!("Unable to read validator index cache. {:?}", e))
})?
.ok_or(ApiError::BadRequest(
"The provided validator public key does not correspond to a validator index.".into(),
))?;
.ok_or_else(|| {
ApiError::BadRequest(
"The provided validator public key does not correspond to a validator index."
.into(),
)
})?;
// Build cache for the requested epoch
head_state
@@ -286,7 +289,7 @@ pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) ->
e
))
})?
.ok_or(ApiError::BadRequest("No validator duties could be found for the requested validator. Cannot provide valid attestation.".into()))?;
.ok_or_else(|| ApiError::BadRequest("No validator duties could be found for the requested validator. Cannot provide valid attestation.".into()))?;
// Check that we are requesting an attestation during the slot where it is relevant.
let present_slot = beacon_chain.slot().map_err(|e| ApiError::ServerError(
@@ -354,7 +357,7 @@ pub fn get_new_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) ->
/// HTTP Handler to publish an Attestation, which has been signed by a validator.
pub fn publish_attestation<T: BeaconChainTypes + 'static>(req: Request<Body>) -> BoxFut {
let _ = try_future!(check_content_type_for_json(&req));
try_future!(check_content_type_for_json(&req));
let log = get_logger_from_request(&req);
let beacon_chain = try_future!(get_beacon_chain_from_request::<T>(&req));
// Get the network sending channel from the request, for later transmission

View File

@@ -118,7 +118,7 @@ impl<T: BeaconChainTypes> AttestationService for AttestationServiceInstance<T> {
self.network_chan
.try_send(NetworkMessage::Publish {
topics: vec![topic],
message: message,
message,
})
.unwrap_or_else(|e| {
error!(

View File

@@ -121,7 +121,7 @@ impl<T: BeaconChainTypes> BeaconBlockService for BeaconBlockServiceInstance<T> {
self.network_chan
.try_send(NetworkMessage::Publish {
topics: vec![topic],
message: message,
message,
})
.unwrap_or_else(|e| {
error!(

View File

@@ -233,7 +233,7 @@ impl ConfigBuilder {
// directory onto it.
let data_dir: PathBuf = cli_args
.value_of("datadir")
.map(|string| PathBuf::from(string))
.map(PathBuf::from)
.or_else(|| {
dirs::home_dir().map(|mut home| {
home.push(DEFAULT_DATA_DIR);
@@ -528,9 +528,9 @@ impl ConfigBuilder {
.parse::<Ipv4Addr>()
.map_err(|e| format!("Unable to parse default listen address: {:?}", e))?;
self.client_config.network.listen_address = addr.clone().into();
self.client_config.rpc.listen_address = addr.clone();
self.client_config.rest_api.listen_address = addr.clone();
self.client_config.network.listen_address = addr.into();
self.client_config.rpc.listen_address = addr;
self.client_config.rest_api.listen_address = addr;
Ok(())
}
@@ -557,8 +557,8 @@ impl ConfigBuilder {
if self.eth2_config.spec_constants != self.client_config.spec_constants {
crit!(self.log, "Specification constants do not match.";
"client_config" => format!("{}", self.client_config.spec_constants),
"eth2_config" => format!("{}", self.eth2_config.spec_constants)
"client_config" => self.client_config.spec_constants.to_string(),
"eth2_config" => self.eth2_config.spec_constants.to_string()
);
return Err("Specification constant mismatch".into());
}

View File

@@ -214,7 +214,7 @@ mod test {
state_a.slot = Slot::from(slots_per_historical_root);
state_b.slot = Slot::from(slots_per_historical_root * 2);
let mut hashes = (0..).into_iter().map(|i| Hash256::from_low_u64_be(i));
let mut hashes = (0..).map(Hash256::from_low_u64_be);
for root in &mut state_a.block_roots[..] {
*root = hashes.next().unwrap()
@@ -230,7 +230,7 @@ mod test {
let iter = BlockRootsIterator::new(store.clone(), &state_b);
assert!(
iter.clone().find(|(_root, slot)| *slot == 0).is_some(),
iter.clone().any(|(_root, slot)| slot == 0),
"iter should contain zero slot"
);
@@ -241,8 +241,8 @@ mod test {
assert_eq!(collected.len(), expected_len);
for i in 0..expected_len {
assert_eq!(collected[i].0, Hash256::from_low_u64_be(i as u64));
for (i, item) in collected.iter().enumerate() {
assert_eq!(item.0, Hash256::from_low_u64_be(i as u64));
}
}
@@ -257,17 +257,17 @@ mod test {
state_a.slot = Slot::from(slots_per_historical_root);
state_b.slot = Slot::from(slots_per_historical_root * 2);
let mut hashes = (0..).into_iter().map(|i| Hash256::from_low_u64_be(i));
let mut hashes = (0..).map(Hash256::from_low_u64_be);
for slot in 0..slots_per_historical_root {
state_a
.set_state_root(Slot::from(slot), hashes.next().unwrap())
.expect(&format!("should set state_a slot {}", slot));
.unwrap_or_else(|_| panic!("should set state_a slot {}", slot));
}
for slot in slots_per_historical_root..slots_per_historical_root * 2 {
state_b
.set_state_root(Slot::from(slot), hashes.next().unwrap())
.expect(&format!("should set state_b slot {}", slot));
.unwrap_or_else(|_| panic!("should set state_b slot {}", slot));
}
let state_a_root = Hash256::from_low_u64_be(slots_per_historical_root as u64);
@@ -279,7 +279,7 @@ mod test {
let iter = StateRootsIterator::new(store.clone(), &state_b);
assert!(
iter.clone().find(|(_root, slot)| *slot == 0).is_some(),
iter.clone().any(|(_root, slot)| slot == 0),
"iter should contain zero slot"
);
@@ -290,8 +290,8 @@ mod test {
assert_eq!(collected.len(), expected_len, "collection length incorrect");
for i in 0..expected_len {
let (hash, slot) = collected[i];
for (i, item) in collected.iter().enumerate() {
let (hash, slot) = *item;
assert_eq!(slot, i as u64, "slot mismatch at {}: {} vs {}", i, slot, i);

View File

@@ -94,7 +94,7 @@ pub fn scrape_for_metrics(db_path: &PathBuf) {
let db_size = if let Ok(iter) = fs::read_dir(db_path) {
iter.filter_map(std::result::Result::ok)
.map(size_of_dir_entry)
.fold(0_u64, |sum, val| sum + val)
.sum()
} else {
0
};