Fix clippy lints

This commit is contained in:
Paul Hauner 2019-04-03 16:23:09 +11:00
parent 1d34e2b2a5
commit 1913be0c6f
No known key found for this signature in database
GPG Key ID: D362883A9218FCC6
22 changed files with 76 additions and 105 deletions

View File

@ -497,21 +497,17 @@ where
} else { } else {
// If the current head block is not from this slot, use the slot from the previous // If the current head block is not from this slot, use the slot from the previous
// epoch. // epoch.
let root = *self.state.read().get_block_root( *self.state.read().get_block_root(
current_epoch_start_slot - self.spec.slots_per_epoch, current_epoch_start_slot - self.spec.slots_per_epoch,
&self.spec, &self.spec,
)?; )?
root
} }
} else { } else {
// If we're not on the first slot of the epoch. // If we're not on the first slot of the epoch.
let root = *self *self
.state .state
.read() .read()
.get_block_root(current_epoch_start_slot, &self.spec)?; .get_block_root(current_epoch_start_slot, &self.spec)?
root
}; };
Ok(AttestationData { Ok(AttestationData {

View File

@ -211,9 +211,8 @@ impl BeaconChainHarness {
// Ensure the validators slot clock is accurate. // Ensure the validators slot clock is accurate.
self.validators[proposer].set_slot(present_slot); self.validators[proposer].set_slot(present_slot);
let block = self.validators[proposer].produce_block().unwrap();
block self.validators[proposer].produce_block().unwrap()
} }
/// Advances the chain with a BeaconBlock and attestations from all validators. /// Advances the chain with a BeaconBlock and attestations from all validators.
@ -245,7 +244,7 @@ impl BeaconChainHarness {
.for_each(|(i, attestation)| { .for_each(|(i, attestation)| {
self.beacon_chain self.beacon_chain
.process_attestation(attestation.clone()) .process_attestation(attestation.clone())
.expect(&format!("Attestation {} invalid: {:?}", i, attestation)); .unwrap_or_else(|_| panic!("Attestation {} invalid: {:?}", i, attestation));
}); });
debug!("Attestations processed."); debug!("Attestations processed.");

View File

@ -52,6 +52,7 @@ impl StateCheck {
/// # Panics /// # Panics
/// ///
/// Panics with an error message if any test fails. /// Panics with an error message if any test fails.
#[allow(clippy::cyclomatic_complexity)]
pub fn assert_valid(&self, state: &BeaconState, spec: &ChainSpec) { pub fn assert_valid(&self, state: &BeaconState, spec: &ChainSpec) {
let state_epoch = state.slot.epoch(spec.slots_per_epoch); let state_epoch = state.slot.epoch(spec.slots_per_epoch);

View File

@ -14,9 +14,6 @@ use slot_clock::SlotClock;
use std::sync::Arc; use std::sync::Arc;
use types::{AttestationData, BeaconBlock, FreeAttestation, Signature, Slot}; use types::{AttestationData, BeaconBlock, FreeAttestation, Signature, Slot};
// mod attester;
// mod producer;
/// Connect directly to a borrowed `BeaconChain` instance so an attester/producer can request/submit /// Connect directly to a borrowed `BeaconChain` instance so an attester/producer can request/submit
/// blocks/attestations. /// blocks/attestations.
/// ///
@ -42,11 +39,6 @@ impl<T: ClientDB, U: SlotClock, F: ForkChoice> DirectBeaconNode<T, U, F> {
pub fn last_published_block(&self) -> Option<BeaconBlock> { pub fn last_published_block(&self) -> Option<BeaconBlock> {
Some(self.published_blocks.read().last()?.clone()) Some(self.published_blocks.read().last()?.clone())
} }
/// Get the last published attestation (if any).
pub fn last_published_free_attestation(&self) -> Option<FreeAttestation> {
Some(self.published_attestations.read().last()?.clone())
}
} }
impl<T: ClientDB, U: SlotClock, F: ForkChoice> AttesterBeaconNode for DirectBeaconNode<T, U, F> { impl<T: ClientDB, U: SlotClock, F: ForkChoice> AttesterBeaconNode for DirectBeaconNode<T, U, F> {

View File

@ -2,8 +2,7 @@ mod direct_beacon_node;
mod direct_duties; mod direct_duties;
mod local_signer; mod local_signer;
use attester::PollOutcome as AttestationPollOutcome; use attester::Attester;
use attester::{Attester, Error as AttestationPollError};
use beacon_chain::BeaconChain; use beacon_chain::BeaconChain;
use block_proposer::PollOutcome as BlockPollOutcome; use block_proposer::PollOutcome as BlockPollOutcome;
use block_proposer::{BlockProducer, Error as BlockPollError}; use block_proposer::{BlockProducer, Error as BlockPollError};
@ -14,7 +13,7 @@ use fork_choice::BitwiseLMDGhost;
use local_signer::LocalSigner; use local_signer::LocalSigner;
use slot_clock::TestingSlotClock; use slot_clock::TestingSlotClock;
use std::sync::Arc; use std::sync::Arc;
use types::{BeaconBlock, ChainSpec, FreeAttestation, Keypair, Slot}; use types::{BeaconBlock, ChainSpec, Keypair, Slot};
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum BlockProduceError { pub enum BlockProduceError {
@ -22,12 +21,6 @@ pub enum BlockProduceError {
PollError(BlockPollError), PollError(BlockPollError),
} }
#[derive(Debug, PartialEq)]
pub enum AttestationProduceError {
DidNotProduce(AttestationPollOutcome),
PollError(AttestationPollError),
}
type TestingBlockProducer = BlockProducer< type TestingBlockProducer = BlockProducer<
TestingSlotClock, TestingSlotClock,
DirectBeaconNode<MemoryDB, TestingSlotClock, BitwiseLMDGhost<MemoryDB>>, DirectBeaconNode<MemoryDB, TestingSlotClock, BitwiseLMDGhost<MemoryDB>>,
@ -117,21 +110,6 @@ impl ValidatorHarness {
.expect("Unable to obtain produced block.")) .expect("Unable to obtain produced block."))
} }
/// Run the `poll` function on the `Attester` and produce a `FreeAttestation`.
///
/// An error is returned if the attester refuses to attest.
pub fn produce_free_attestation(&mut self) -> Result<FreeAttestation, AttestationProduceError> {
match self.attester.poll() {
Ok(AttestationPollOutcome::AttestationProduced(_)) => {}
Ok(outcome) => return Err(AttestationProduceError::DidNotProduce(outcome)),
Err(error) => return Err(AttestationProduceError::PollError(error)),
};
Ok(self
.beacon_node
.last_published_free_attestation()
.expect("Unable to obtain produced attestation."))
}
/// Set the validators slot clock to the specified slot. /// Set the validators slot clock to the specified slot.
/// ///
/// The validators slot clock will always read this value until it is set to something else. /// The validators slot clock will always read this value until it is set to something else.

View File

@ -25,9 +25,9 @@ use tokio::timer::Interval;
/// sub-services in multiple threads. /// sub-services in multiple threads.
pub struct Client<T: ClientTypes> { pub struct Client<T: ClientTypes> {
/// Configuration for the lighthouse client. /// Configuration for the lighthouse client.
config: ClientConfig, _config: ClientConfig,
/// The beacon chain for the running client. /// The beacon chain for the running client.
beacon_chain: Arc<BeaconChain<T::DB, T::SlotClock, T::ForkChoice>>, _beacon_chain: Arc<BeaconChain<T::DB, T::SlotClock, T::ForkChoice>>,
/// Reference to the network service. /// Reference to the network service.
pub network: Arc<NetworkService>, pub network: Arc<NetworkService>,
/// Signal to terminate the RPC server. /// Signal to terminate the RPC server.
@ -90,17 +90,18 @@ impl<TClientType: ClientTypes> Client<TClientType> {
network_logger, network_logger,
)?; )?;
let mut rpc_exit_signal = None;
// spawn the RPC server // spawn the RPC server
if config.rpc_conf.enabled { let rpc_exit_signal = if config.rpc_conf.enabled {
rpc_exit_signal = Some(rpc::start_server( Some(rpc::start_server(
&config.rpc_conf, &config.rpc_conf,
executor, executor,
network_send, network_send,
beacon_chain.clone(), beacon_chain.clone(),
&log, &log,
)); ))
} } else {
None
};
let (slot_timer_exit_signal, exit) = exit_future::signal(); let (slot_timer_exit_signal, exit) = exit_future::signal();
if let Ok(Some(duration_to_next_slot)) = beacon_chain.slot_clock.duration_to_next_slot() { if let Ok(Some(duration_to_next_slot)) = beacon_chain.slot_clock.duration_to_next_slot() {
@ -129,8 +130,8 @@ impl<TClientType: ClientTypes> Client<TClientType> {
} }
Ok(Client { Ok(Client {
config, _config: config,
beacon_chain, _beacon_chain: beacon_chain,
rpc_exit_signal, rpc_exit_signal,
slot_timer_exit_signal: Some(slot_timer_exit_signal), slot_timer_exit_signal: Some(slot_timer_exit_signal),
log, log,

View File

@ -14,7 +14,7 @@ pub fn run<T: ClientTypes>(client: &Client<T>, executor: TaskExecutor, exit: Exi
// notification heartbeat // notification heartbeat
let interval = Interval::new(Instant::now(), Duration::from_secs(5)); let interval = Interval::new(Instant::now(), Duration::from_secs(5));
let log = client.log.new(o!("Service" => "Notifier")); let _log = client.log.new(o!("Service" => "Notifier"));
// TODO: Debugging only // TODO: Debugging only
let counter = Arc::new(Mutex::new(0)); let counter = Arc::new(Mutex::new(0));

View File

@ -65,17 +65,11 @@ impl<TSubstream: AsyncRead + AsyncWrite> NetworkBehaviourEventProcess<GossipsubE
self.events.push(BehaviourEvent::GossipMessage { self.events.push(BehaviourEvent::GossipMessage {
source: gs_msg.source, source: gs_msg.source,
topics: gs_msg.topics, topics: gs_msg.topics,
message: pubsub_message, message: Box::new(pubsub_message),
}); });
} }
GossipsubEvent::Subscribed { GossipsubEvent::Subscribed { .. } => {}
peer_id: _, GossipsubEvent::Unsubscribed { .. } => {}
topic: _,
}
| GossipsubEvent::Unsubscribed {
peer_id: _,
topic: _,
} => {}
} }
} }
} }
@ -110,7 +104,8 @@ impl<TSubstream: AsyncRead + AsyncWrite> NetworkBehaviourEventProcess<IdentifyEv
); );
info.listen_addrs.truncate(20); info.listen_addrs.truncate(20);
} }
self.events.push(BehaviourEvent::Identified(peer_id, info)); self.events
.push(BehaviourEvent::Identified(peer_id, Box::new(info)));
} }
IdentifyEvent::Error { .. } => {} IdentifyEvent::Error { .. } => {}
IdentifyEvent::SendBack { .. } => {} IdentifyEvent::SendBack { .. } => {}
@ -183,12 +178,12 @@ impl<TSubstream: AsyncRead + AsyncWrite> Behaviour<TSubstream> {
pub enum BehaviourEvent { pub enum BehaviourEvent {
RPC(PeerId, RPCEvent), RPC(PeerId, RPCEvent),
PeerDialed(PeerId), PeerDialed(PeerId),
Identified(PeerId, IdentifyInfo), Identified(PeerId, Box<IdentifyInfo>),
// TODO: This is a stub at the moment // TODO: This is a stub at the moment
GossipMessage { GossipMessage {
source: PeerId, source: PeerId,
topics: Vec<TopicHash>, topics: Vec<TopicHash>,
message: PubsubMessage, message: Box<PubsubMessage>,
}, },
} }

View File

@ -26,7 +26,7 @@ pub struct Rpc<TSubstream> {
/// Pins the generic substream. /// Pins the generic substream.
marker: PhantomData<TSubstream>, marker: PhantomData<TSubstream>,
/// Slog logger for RPC behaviour. /// Slog logger for RPC behaviour.
log: slog::Logger, _log: slog::Logger,
} }
impl<TSubstream> Rpc<TSubstream> { impl<TSubstream> Rpc<TSubstream> {
@ -35,7 +35,7 @@ impl<TSubstream> Rpc<TSubstream> {
Rpc { Rpc {
events: Vec::new(), events: Vec::new(),
marker: PhantomData, marker: PhantomData,
log, _log: log,
} }
} }
@ -65,7 +65,7 @@ where
fn inject_connected(&mut self, peer_id: PeerId, connected_point: ConnectedPoint) { fn inject_connected(&mut self, peer_id: PeerId, connected_point: ConnectedPoint) {
// if initialised the connection, report this upwards to send the HELLO request // if initialised the connection, report this upwards to send the HELLO request
if let ConnectedPoint::Dialer { address: _ } = connected_point { if let ConnectedPoint::Dialer { .. } = connected_point {
self.events.push(NetworkBehaviourAction::GenerateEvent( self.events.push(NetworkBehaviourAction::GenerateEvent(
RPCMessage::PeerDialed(peer_id), RPCMessage::PeerDialed(peer_id),
)); ));

View File

@ -31,7 +31,7 @@ impl Default for RPCProtocol {
} }
/// A monotonic counter for ordering `RPCRequest`s. /// A monotonic counter for ordering `RPCRequest`s.
#[derive(Debug, Clone, PartialEq, Default)] #[derive(Debug, Clone, Default)]
pub struct RequestId(u64); pub struct RequestId(u64);
impl RequestId { impl RequestId {
@ -48,6 +48,12 @@ impl RequestId {
impl Eq for RequestId {} impl Eq for RequestId {}
impl PartialEq for RequestId {
fn eq(&self, other: &RequestId) -> bool {
self.0 == other.0
}
}
impl Hash for RequestId { impl Hash for RequestId {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state); self.0.hash(state);
@ -104,17 +110,15 @@ impl UpgradeInfo for RPCEvent {
} }
} }
type FnDecodeRPCEvent = fn(Vec<u8>, ()) -> Result<RPCEvent, DecodeError>;
impl<TSocket> InboundUpgrade<TSocket> for RPCProtocol impl<TSocket> InboundUpgrade<TSocket> for RPCProtocol
where where
TSocket: AsyncRead + AsyncWrite, TSocket: AsyncRead + AsyncWrite,
{ {
type Output = RPCEvent; type Output = RPCEvent;
type Error = DecodeError; type Error = DecodeError;
type Future = upgrade::ReadOneThen< type Future = upgrade::ReadOneThen<upgrade::Negotiated<TSocket>, (), FnDecodeRPCEvent>;
upgrade::Negotiated<TSocket>,
(),
fn(Vec<u8>, ()) -> Result<RPCEvent, DecodeError>,
>;
fn upgrade_inbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future { fn upgrade_inbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future {
upgrade::read_one_then(socket, MAX_READ_SIZE, (), |packet, ()| Ok(decode(packet)?)) upgrade::read_one_then(socket, MAX_READ_SIZE, (), |packet, ()| Ok(decode(packet)?))

View File

@ -19,13 +19,16 @@ use std::io::{Error, ErrorKind};
use std::time::Duration; use std::time::Duration;
use types::{TopicBuilder, TopicHash}; use types::{TopicBuilder, TopicHash};
type Libp2pStream = Boxed<(PeerId, StreamMuxerBox), Error>;
type Libp2pBehaviour = Behaviour<Substream<StreamMuxerBox>>;
/// The configuration and state of the libp2p components for the beacon node. /// The configuration and state of the libp2p components for the beacon node.
pub struct Service { pub struct Service {
/// The libp2p Swarm handler. /// The libp2p Swarm handler.
//TODO: Make this private //TODO: Make this private
pub swarm: Swarm<Boxed<(PeerId, StreamMuxerBox), Error>, Behaviour<Substream<StreamMuxerBox>>>, pub swarm: Swarm<Libp2pStream, Libp2pBehaviour>,
/// This node's PeerId. /// This node's PeerId.
local_peer_id: PeerId, _local_peer_id: PeerId,
/// The libp2p logger handle. /// The libp2p logger handle.
pub log: slog::Logger, pub log: slog::Logger,
} }
@ -89,7 +92,7 @@ impl Service {
info!(log, "Subscribed to topics: {:?}", subscribed_topics); info!(log, "Subscribed to topics: {:?}", subscribed_topics);
Ok(Service { Ok(Service {
local_peer_id, _local_peer_id: local_peer_id,
swarm, swarm,
log, log,
}) })
@ -179,11 +182,11 @@ pub enum Libp2pEvent {
/// Initiated the connection to a new peer. /// Initiated the connection to a new peer.
PeerDialed(PeerId), PeerDialed(PeerId),
/// Received information about a peer on the network. /// Received information about a peer on the network.
Identified(PeerId, IdentifyInfo), Identified(PeerId, Box<IdentifyInfo>),
/// Received pubsub message. /// Received pubsub message.
PubsubMessage { PubsubMessage {
source: PeerId, source: PeerId,
topics: Vec<TopicHash>, topics: Vec<TopicHash>,
message: PubsubMessage, message: Box<PubsubMessage>,
}, },
} }

View File

@ -41,7 +41,7 @@ pub enum HandlerMessage {
/// An RPC response/request has been received. /// An RPC response/request has been received.
RPC(PeerId, RPCEvent), RPC(PeerId, RPCEvent),
/// A gossip message has been received. /// A gossip message has been received.
PubsubMessage(PeerId, PubsubMessage), PubsubMessage(PeerId, Box<PubsubMessage>),
} }
impl MessageHandler { impl MessageHandler {
@ -93,7 +93,7 @@ impl MessageHandler {
} }
// we have received an RPC message request/response // we have received an RPC message request/response
HandlerMessage::PubsubMessage(peer_id, gossip) => { HandlerMessage::PubsubMessage(peer_id, gossip) => {
self.handle_gossip(peer_id, gossip); self.handle_gossip(peer_id, *gossip);
} }
//TODO: Handle all messages //TODO: Handle all messages
_ => {} _ => {}

View File

@ -17,7 +17,7 @@ use types::Topic;
/// Service that handles communication between internal services and the eth2_libp2p network service. /// Service that handles communication between internal services and the eth2_libp2p network service.
pub struct Service { pub struct Service {
//libp2p_service: Arc<Mutex<LibP2PService>>, //libp2p_service: Arc<Mutex<LibP2PService>>,
libp2p_exit: oneshot::Sender<()>, _libp2p_exit: oneshot::Sender<()>,
network_send: crossbeam_channel::Sender<NetworkMessage>, network_send: crossbeam_channel::Sender<NetworkMessage>,
//message_handler: MessageHandler, //message_handler: MessageHandler,
//message_handler_send: Sender<HandlerMessage>, //message_handler_send: Sender<HandlerMessage>,
@ -54,7 +54,7 @@ impl Service {
log, log,
)?; )?;
let network_service = Service { let network_service = Service {
libp2p_exit, _libp2p_exit: libp2p_exit,
network_send: network_send.clone(), network_send: network_send.clone(),
}; };
@ -131,9 +131,7 @@ fn network_service(
); );
} }
Libp2pEvent::PubsubMessage { Libp2pEvent::PubsubMessage {
source, source, message, ..
topics: _,
message,
} => { } => {
//TODO: Decide if we need to propagate the topic upwards. (Potentially for //TODO: Decide if we need to propagate the topic upwards. (Potentially for
//attestations) //attestations)
@ -167,7 +165,7 @@ fn network_service(
} }
Ok(NetworkMessage::Publish { topics, message }) => { Ok(NetworkMessage::Publish { topics, message }) => {
debug!(log, "Sending pubsub message on topics {:?}", topics); debug!(log, "Sending pubsub message on topics {:?}", topics);
libp2p_service.swarm.publish(topics, message); libp2p_service.swarm.publish(topics, *message);
} }
Err(TryRecvError::Empty) => break, Err(TryRecvError::Empty) => break,
Err(TryRecvError::Disconnected) => { Err(TryRecvError::Disconnected) => {
@ -190,7 +188,7 @@ pub enum NetworkMessage {
/// Publish a message to pubsub mechanism. /// Publish a message to pubsub mechanism.
Publish { Publish {
topics: Vec<Topic>, topics: Vec<Topic>,
message: PubsubMessage, message: Box<PubsubMessage>,
}, },
} }

View File

@ -65,7 +65,7 @@ pub enum PeerStatus {
} }
impl PeerStatus { impl PeerStatus {
pub fn should_handshake(&self) -> bool { pub fn should_handshake(self) -> bool {
match self { match self {
PeerStatus::DifferentNetworkId => false, PeerStatus::DifferentNetworkId => false,
PeerStatus::FinalizedEpochNotInChain => false, PeerStatus::FinalizedEpochNotInChain => false,

View File

@ -43,9 +43,9 @@ impl AttestationService for AttestationServiceInstance {
let f = sink let f = sink
.fail(RpcStatus::new( .fail(RpcStatus::new(
RpcStatusCode::OutOfRange, RpcStatusCode::OutOfRange,
Some(format!( Some(
"AttestationData request for a slot that is in the future." "AttestationData request for a slot that is in the future.".to_string(),
)), ),
)) ))
.map_err(move |e| { .map_err(move |e| {
error!(log_clone, "Failed to reply with failure {:?}: {:?}", req, e) error!(log_clone, "Failed to reply with failure {:?}: {:?}", req, e)
@ -58,9 +58,7 @@ impl AttestationService for AttestationServiceInstance {
let f = sink let f = sink
.fail(RpcStatus::new( .fail(RpcStatus::new(
RpcStatusCode::InvalidArgument, RpcStatusCode::InvalidArgument,
Some(format!( Some("AttestationData request for a slot that is in the past.".to_string()),
"AttestationData request for a slot that is in the past."
)),
)) ))
.map_err(move |e| { .map_err(move |e| {
error!(log_clone, "Failed to reply with failure {:?}: {:?}", req, e) error!(log_clone, "Failed to reply with failure {:?}: {:?}", req, e)

View File

@ -43,7 +43,7 @@ impl BeaconBlockService for BeaconBlockServiceInstance {
let f = sink let f = sink
.fail(RpcStatus::new( .fail(RpcStatus::new(
RpcStatusCode::InvalidArgument, RpcStatusCode::InvalidArgument,
Some(format!("Invalid randao reveal signature")), Some("Invalid randao reveal signature".to_string()),
)) ))
.map_err(move |e| warn!(log_clone, "failed to reply {:?}: {:?}", req, e)); .map_err(move |e| warn!(log_clone, "failed to reply {:?}: {:?}", req, e));
return ctx.spawn(f); return ctx.spawn(f);
@ -114,7 +114,7 @@ impl BeaconBlockService for BeaconBlockServiceInstance {
self.network_chan self.network_chan
.send(NetworkMessage::Publish { .send(NetworkMessage::Publish {
topics: vec![topic], topics: vec![topic],
message, message: Box::new(message),
}) })
.unwrap_or_else(|e| { .unwrap_or_else(|e| {
error!( error!(

View File

@ -24,7 +24,7 @@ impl BeaconNodeService for BeaconNodeServiceInstance {
// get the chain state // get the chain state
let state = self.chain.get_state(); let state = self.chain.get_state();
let state_fork = state.fork.clone(); let state_fork = state.fork.clone();
let genesis_time = state.genesis_time.clone(); let genesis_time = state.genesis_time;
// build the rpc fork struct // build the rpc fork struct
let mut fork = Fork::new(); let mut fork = Fork::new();
@ -35,7 +35,7 @@ impl BeaconNodeService for BeaconNodeServiceInstance {
node_info.set_fork(fork); node_info.set_fork(fork);
node_info.set_genesis_time(genesis_time); node_info.set_genesis_time(genesis_time);
node_info.set_genesis_slot(self.chain.get_spec().genesis_slot.as_u64()); node_info.set_genesis_slot(self.chain.get_spec().genesis_slot.as_u64());
node_info.set_chain_id(self.chain.get_spec().chain_id as u32); node_info.set_chain_id(u32::from(self.chain.get_spec().chain_id));
// send the node_info the requester // send the node_info the requester
let error_log = self.log.clone(); let error_log = self.log.clone();

View File

@ -82,8 +82,7 @@ fn run_state_transition_tests_small() {
for block in test_case.blocks.iter() { for block in test_case.blocks.iter() {
while block.slot > state.slot { while block.slot > state.slot {
let latest_block_header = state.latest_block_header.clone(); let latest_block_header = state.latest_block_header.clone();
let res = per_slot_processing(&mut state, &latest_block_header, &test_case.config) per_slot_processing(&mut state, &latest_block_header, &test_case.config).unwrap();
.unwrap();
} }
if test_case.verify_signatures { if test_case.verify_signatures {
let res = per_block_processing(&mut state, &block, &test_case.config); let res = per_block_processing(&mut state, &block, &test_case.config);

View File

@ -6,8 +6,7 @@ use dirs;
use log::debug; use log::debug;
use rayon::prelude::*; use rayon::prelude::*;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
//TODO: testing only use std::time::SystemTime;
use std::time::{Duration, SystemTime};
pub const KEYPAIRS_FILE: &str = "keypairs.raw_keypairs"; pub const KEYPAIRS_FILE: &str = "keypairs.raw_keypairs";

View File

@ -3,7 +3,7 @@ use serde_derive::{Deserialize, Serialize};
use std::fmt; use std::fmt;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Eq, Serialize, Deserialize)]
pub struct Keypair { pub struct Keypair {
pub sk: SecretKey, pub sk: SecretKey,
pub pk: PublicKey, pub pk: PublicKey,
@ -22,6 +22,12 @@ impl Keypair {
} }
} }
impl PartialEq for Keypair {
fn eq(&self, other: &Keypair) -> bool {
self == other
}
}
impl Hash for Keypair { impl Hash for Keypair {
/// Note: this is distinct from consensus serialization, it will produce a different hash. /// Note: this is distinct from consensus serialization, it will produce a different hash.
/// ///

View File

@ -81,6 +81,7 @@ impl Config {
} }
/// Try to load keys from validator_dir, returning None if none are found or an error. /// Try to load keys from validator_dir, returning None if none are found or an error.
#[allow(dead_code)]
pub fn fetch_keys(&self, log: &slog::Logger) -> Option<Vec<Keypair>> { pub fn fetch_keys(&self, log: &slog::Logger) -> Option<Vec<Keypair>> {
let key_pairs: Vec<Keypair> = fs::read_dir(&self.data_dir) let key_pairs: Vec<Keypair> = fs::read_dir(&self.data_dir)
.unwrap() .unwrap()
@ -144,6 +145,7 @@ impl Config {
} }
/// Saves a keypair to a file inside the appropriate validator directory. Returns the saved path filename. /// Saves a keypair to a file inside the appropriate validator directory. Returns the saved path filename.
#[allow(dead_code)]
pub fn save_key(&self, key: &Keypair) -> Result<PathBuf, Error> { pub fn save_key(&self, key: &Keypair) -> Result<PathBuf, Error> {
let validator_config_path = self.data_dir.join(key.identifier()); let validator_config_path = self.data_dir.join(key.identifier());
let key_path = validator_config_path.join(DEFAULT_PRIVATE_KEY_FILENAME); let key_path = validator_config_path.join(DEFAULT_PRIVATE_KEY_FILENAME);

View File

@ -29,7 +29,7 @@ use std::sync::RwLock;
use std::time::{Duration, Instant, SystemTime}; use std::time::{Duration, Instant, SystemTime};
use tokio::prelude::*; use tokio::prelude::*;
use tokio::runtime::Builder; use tokio::runtime::Builder;
use tokio::timer::{Delay, Interval}; use tokio::timer::Interval;
use tokio_timer::clock::Clock; use tokio_timer::clock::Clock;
use types::test_utils::generate_deterministic_keypairs; use types::test_utils::generate_deterministic_keypairs;
use types::{ChainSpec, Epoch, Fork, Slot}; use types::{ChainSpec, Epoch, Fork, Slot};