Skip to content

Commit

Permalink
First compiling version of validator
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Sep 11, 2020
1 parent 086c449 commit 21f8a3a
Show file tree
Hide file tree
Showing 8 changed files with 200 additions and 238 deletions.
6 changes: 6 additions & 0 deletions common/eth2/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,12 @@ impl fmt::Display for Graffiti {
}
}

impl From<[u8; GRAFFITI_BYTES_LEN]> for Graffiti {
fn from(bytes: [u8; GRAFFITI_BYTES_LEN]) -> Self {
Self(bytes)
}
}

impl Into<[u8; GRAFFITI_BYTES_LEN]> for Graffiti {
fn into(self) -> [u8; GRAFFITI_BYTES_LEN] {
self.0
Expand Down
330 changes: 142 additions & 188 deletions validator_client/src/attestation_service.rs

Large diffs are not rendered by default.

44 changes: 16 additions & 28 deletions validator_client/src/block_service.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use crate::validator_store::ValidatorStore;
use environment::RuntimeContext;
use eth2::{types::Graffiti, BeaconNodeClient};
use futures::channel::mpsc::Receiver;
use futures::{StreamExt, TryFutureExt};
use remote_beacon_node::{PublishStatus, RemoteBeaconNode};
use slog::{crit, debug, error, info, trace, warn};
use slot_clock::SlotClock;
use std::ops::Deref;
use std::sync::Arc;
use types::{EthSpec, Graffiti, PublicKey, Slot};
use types::{EthSpec, PublicKey, Slot};

/// Builds a `BlockService`.
pub struct BlockServiceBuilder<T, E: EthSpec> {
validator_store: Option<ValidatorStore<T, E>>,
slot_clock: Option<Arc<T>>,
beacon_node: Option<RemoteBeaconNode<E>>,
beacon_node: Option<BeaconNodeClient>,
context: Option<RuntimeContext<E>>,
graffiti: Option<Graffiti>,
}
Expand All @@ -39,7 +39,7 @@ impl<T: SlotClock + 'static, E: EthSpec> BlockServiceBuilder<T, E> {
self
}

pub fn beacon_node(mut self, beacon_node: RemoteBeaconNode<E>) -> Self {
pub fn beacon_node(mut self, beacon_node: BeaconNodeClient) -> Self {
self.beacon_node = Some(beacon_node);
self
}
Expand Down Expand Up @@ -79,7 +79,7 @@ impl<T: SlotClock + 'static, E: EthSpec> BlockServiceBuilder<T, E> {
pub struct Inner<T, E: EthSpec> {
validator_store: ValidatorStore<T, E>,
slot_clock: Arc<T>,
beacon_node: RemoteBeaconNode<E>,
beacon_node: BeaconNodeClient,
context: RuntimeContext<E>,
graffiti: Option<Graffiti>,
}
Expand Down Expand Up @@ -221,11 +221,10 @@ impl<T: SlotClock + 'static, E: EthSpec> BlockService<T, E> {

let block = self
.beacon_node
.http
.validator()
.produce_block(slot, randao_reveal, self.graffiti)
.get_validator_blocks(slot, randao_reveal.into(), self.graffiti.as_ref())
.await
.map_err(|e| format!("Error from beacon node when producing block: {:?}", e))?;
.map_err(|e| format!("Error from beacon node when producing block: {:?}", e))?
.data;

let signed_block = self
.validator_store
Expand All @@ -234,28 +233,17 @@ impl<T: SlotClock + 'static, E: EthSpec> BlockService<T, E> {

let publish_status = self
.beacon_node
.http
.validator()
.publish_block(signed_block.clone())
.post_beacon_blocks(&signed_block)
.await
.map_err(|e| format!("Error from beacon node when publishing block: {:?}", e))?;

match publish_status {
PublishStatus::Valid => info!(
log,
"Successfully published block";
"deposits" => signed_block.message.body.deposits.len(),
"attestations" => signed_block.message.body.attestations.len(),
"slot" => signed_block.slot().as_u64(),
),
PublishStatus::Invalid(msg) => crit!(
log,
"Published block was invalid";
"message" => msg,
"slot" => signed_block.slot().as_u64(),
),
PublishStatus::Unknown => crit!(log, "Unknown condition when publishing block"),
}
info!(
log,
"Successfully published block";
"deposits" => signed_block.message.body.deposits.len(),
"attestations" => signed_block.message.body.attestations.len(),
"slot" => signed_block.slot().as_u64(),
);

Ok(())
}
Expand Down
8 changes: 4 additions & 4 deletions validator_client/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use clap::ArgMatches;
use clap_utils::{parse_optional, parse_path_with_default_in_home_dir};
use eth2::types::Graffiti;
use serde_derive::{Deserialize, Serialize};
use std::path::PathBuf;
use types::{Graffiti, GRAFFITI_BYTES_LEN};
use types::GRAFFITI_BYTES_LEN;

pub const DEFAULT_HTTP_SERVER: &str = "http://localhost:5052/";
pub const DEFAULT_DATA_DIR: &str = ".lighthouse/validators";
Expand Down Expand Up @@ -92,15 +93,14 @@ impl Config {
GRAFFITI_BYTES_LEN
));
} else {
// Default graffiti to all 0 bytes.
let mut graffiti = Graffiti::default();
let mut graffiti = [0; 32];

// Copy the provided bytes over.
//
// Panic-free because `graffiti_bytes.len()` <= `GRAFFITI_BYTES_LEN`.
graffiti[..graffiti_bytes.len()].copy_from_slice(&graffiti_bytes);

config.graffiti = Some(graffiti);
config.graffiti = Some(graffiti.into());
}
}

Expand Down
13 changes: 3 additions & 10 deletions validator_client/src/duties_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ impl DutyAndProof {

/// Returns the information required for an attesting validator, if they are scheduled to
/// attest.
pub fn attestation_duties(&self) -> Option<(Slot, CommitteeIndex, usize, u64, u64)> {
pub fn attestation_duties(&self) -> Option<(Slot, CommitteeIndex, usize, u64, u64, u64)> {
Some((
self.duty.attestation_slot?,
self.duty.attestation_committee_index?,
self.duty.attestation_committee_position?,
self.duty.validator_index?,
self.duty.committee_count_at_slot?,
self.duty.committee_length?,
))
}

Expand All @@ -111,15 +112,7 @@ impl DutyAndProof {
impl Into<DutyAndProof> for ValidatorDuty {
fn into(self) -> DutyAndProof {
DutyAndProof {
duty: ValidatorDuty {
validator_pubkey: self.validator_pubkey,
validator_index: self.validator_index,
attestation_slot: self.attestation_slot,
attestation_committee_index: self.attestation_committee_index,
attestation_committee_position: self.attestation_committee_position,
committee_count_at_slot: self.committee_count_at_slot,
block_proposal_slots: self.block_proposal_slots,
},
duty: self,
selection_proof: None,
}
}
Expand Down
22 changes: 18 additions & 4 deletions validator_client/src/is_synced.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use eth2::BeaconNodeClient;
use slog::{debug, error, Logger};
use slog::{debug, error, warn, Logger};
use slot_clock::SlotClock;

/// A distance in slots.
Expand Down Expand Up @@ -37,21 +37,35 @@ pub async fn is_synced<T: SlotClock>(

let is_synced = !resp.data.is_syncing || (resp.data.sync_distance.as_u64() < SYNC_TOLERANCE);

if !is_synced {
if let Some(log) = log_opt {
if let Some(log) = log_opt {
if !is_synced {
debug!(
log,
"Beacon node sync status";
"status" => format!("{:?}", resp),
);
error!(

warn!(
log,
"Beacon node is syncing";
"msg" => "not receiving new duties",
"sync_distance" => resp.data.sync_distance.as_u64(),
"head_slot" => resp.data.head_slot.as_u64(),
);
}

if let Some(local_slot) = slot_clock.now() {
let remote_slot = resp.data.head_slot + resp.data.sync_distance;
if remote_slot + 1 < local_slot || local_slot + 1 < remote_slot {
error!(
log,
"Time discrepancy with beacon node";
"msg" => "check the system time on this host and the beacon node",
"beacon_node_slot" => remote_slot,
"local_slot" => local_slot,
);
}
}
}

is_synced
Expand Down
11 changes: 7 additions & 4 deletions validator_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ use clap::ArgMatches;
use duties_service::{DutiesService, DutiesServiceBuilder};
use environment::RuntimeContext;
use eth2::{reqwest::ClientBuilder, BeaconNodeClient, StatusCode, Url};
use eth2_config::Eth2Config;
use fork_service::{ForkService, ForkServiceBuilder};
use futures::channel::mpsc;
use initialized_validators::InitializedValidators;
use notifier::spawn_notifier;
use slog::{error, info, Logger};
use slot_clock::SlotClock;
use slot_clock::SystemTimeSlotClock;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::time::{delay_for, Duration};
use types::{EthSpec, Hash256, YamlConfig};
Expand Down Expand Up @@ -62,7 +62,7 @@ impl<T: EthSpec> ProductionValidatorClient<T> {

/// Instantiates the validator client, _without_ starting the timers to trigger block
/// and attestation production.
pub async fn new(mut context: RuntimeContext<T>, config: Config) -> Result<Self, String> {
pub async fn new(context: RuntimeContext<T>, config: Config) -> Result<Self, String> {
let log = context.log().clone();

info!(
Expand Down Expand Up @@ -122,7 +122,7 @@ impl<T: EthSpec> ProductionValidatorClient<T> {
tuple = init_from_beacon_node(&beacon_node, &context) => tuple?,
() = context.executor.exit() => return Err("Shutting down".to_string())
};
let mut beacon_node_spec = yaml_config.apply_to_chain_spec(&T::default_spec())
let beacon_node_spec = yaml_config.apply_to_chain_spec::<T>(&T::default_spec())
.ok_or_else(|| format!(
"The minimal/mainnet spec type of the beacon node does not match the validator client. \
See the --testnet command."
Expand Down Expand Up @@ -208,7 +208,10 @@ impl<T: EthSpec> ProductionValidatorClient<T> {

self.duties_service
.clone()
.start_update_service(block_service_tx, &self.context.eth2_config.spec)
.start_update_service(
block_service_tx,
Arc::new(self.context.eth2_config.spec.clone()),
)
.map_err(|e| format!("Unable to start duties service: {}", e))?;

self.fork_service
Expand Down
4 changes: 4 additions & 0 deletions validator_client/src/validator_duty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ pub struct ValidatorDuty {
pub attestation_committee_position: Option<usize>,
/// The committee count at `attestation_slot`.
pub committee_count_at_slot: Option<u64>,
/// The number of validators in the committee.
pub committee_length: Option<u64>,
/// The slots in which a validator must propose a block (can be empty).
///
/// Should be set to `None` when duties are not yet known (before the current epoch).
Expand All @@ -38,6 +40,7 @@ impl ValidatorDuty {
attestation_committee_index: None,
attestation_committee_position: None,
committee_count_at_slot: None,
committee_length: None,
block_proposal_slots: None,
}
}
Expand Down Expand Up @@ -87,6 +90,7 @@ impl ValidatorDuty {
attestation_committee_index: Some(attester.committee_index),
attestation_committee_position: Some(attester.validator_committee_index as usize),
committee_count_at_slot: Some(attester.committees_at_slot),
committee_length: Some(attester.committee_length),
block_proposal_slots: Some(block_proposal_slots),
})
} else {
Expand Down

0 comments on commit 21f8a3a

Please sign in to comment.