From 8f3530f60ce900f41d48c2d407e26cb0a727f9b3 Mon Sep 17 00:00:00 2001 From: thojest Date: Fri, 8 Mar 2019 13:48:33 +0100 Subject: [PATCH 01/97] created attester_service and started to create an attester_thread in main of validator_client (lighthouse-255) --- validator_client/Cargo.toml | 1 + validator_client/src/attester_service/mod.rs | 51 ++++++++++++++++++++ validator_client/src/main.rs | 29 ++++++++++- 3 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 validator_client/src/attester_service/mod.rs diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index f76772f28..cdde71774 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -6,6 +6,7 @@ edition = "2018" [dependencies] block_proposer = { path = "../eth2/block_proposer" } +attester = { path = "../eth2/attester" } bls = { path = "../eth2/utils/bls" } clap = "2.32.0" dirs = "1.0.3" diff --git a/validator_client/src/attester_service/mod.rs b/validator_client/src/attester_service/mod.rs new file mode 100644 index 000000000..fbf8bd005 --- /dev/null +++ b/validator_client/src/attester_service/mod.rs @@ -0,0 +1,51 @@ +use attester::{Attester, BeaconNode, DutiesReader, PollOutcome as AttesterPollOutcome, Signer}; +use slog::Logger; +use slot_clock::SlotClock; +use std::time::Duration; + +pub struct AttesterService { + pub attester: Attester, + pub poll_interval_millis: u64, + pub log: Logger, +} + +impl AttesterService { + /// Run a loop which polls the Attester each `poll_interval_millis` millseconds. + /// + /// Logs the results of the polls. + pub fn run(&mut self) { + loop { + match self.attester.poll() { + Err(error) => { + error!(self.log, "Attester poll error"; "error" => format!("{:?}", error)) + } + Ok(AttesterPollOutcome::AttestationProduced(slot)) => { + info!(self.log, "Produced Attestation"; "slot" => slot) + } + Ok(AttesterPollOutcome::SlashableAttestationNotProduced(slot)) => { + warn!(self.log, "Slashable attestation was not produced"; "slot" => slot) + } + Ok(AttesterPollOutcome::AttestationNotRequired(slot)) => { + info!(self.log, "Attestation not required"; "slot" => slot) + } + Ok(AttesterPollOutcome::ProducerDutiesUnknown(slot)) => { + error!(self.log, "Attestation duties unknown"; "slot" => slot) + } + Ok(AttesterPollOutcome::SlotAlreadyProcessed(slot)) => { + warn!(self.log, "Attempted to re-process slot"; "slot" => slot) + } + Ok(AttesterPollOutcome::BeaconNodeUnableToProduceAttestation(slot)) => { + error!(self.log, "Beacon node unable to produce attestation"; "slot" => slot) + } + Ok(AttesterPollOutcome::SignerRejection(slot)) => { + error!(self.log, "The cryptographic signer refused to sign the attestation"; "slot" => slot) + } + Ok(AttesterPollOutcome::ValidatorIsUnknown(slot)) => { + error!(self.log, "The Beacon Node does not recognise the validator"; "slot" => slot) + } + }; + + std::thread::sleep(Duration::from_millis(self.poll_interval_millis)); + } + } +} diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index ebab8538c..2e432ceff 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,7 +1,9 @@ use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; +use crate::attester_service::AttesterService; use crate::config::ClientConfig; -use block_proposer::{test_utils::LocalSigner, BlockProducer}; +use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; +use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; use bls::Keypair; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; @@ -13,7 +15,9 @@ use std::sync::Arc; use std::thread; use types::ChainSpec; +mod attester_service; mod block_producer_service; + mod config; mod duties; @@ -160,7 +164,7 @@ fn main() { // Spawn a new thread to perform block production for the validator. let producer_thread = { let spec = spec.clone(); - let signer = Arc::new(LocalSigner::new(keypair.clone())); + let signer = Arc::new(BlockProposerLocalSigner::new(keypair.clone())); let duties_map = duties_map.clone(); let slot_clock = slot_clock.clone(); let log = log.clone(); @@ -178,6 +182,27 @@ fn main() { }) }; + //Spawn a new thread for attestation for the validator. + let attester_thread = { + let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); + let duties_map = duties_map.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + //TODO: this is wrong, I assume this has to be AttesterGrpcClient, which has to be defined analogous + // to beacon_block_grpc_client.rs + let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); + thread::spawn(move || { + let attester = Attester::new(duties_map, slot_clock, client, signer); + let mut attester_service = AttesterService { + attester, + poll_interval_millis, + log, + }; + + block_producer_service.run(); + }) + }; + threads.push((duties_manager_thread, producer_thread)); } From e942d7533be92f82f9ba4f76a30fa372e58db0d9 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Tue, 12 Mar 2019 21:56:45 +1100 Subject: [PATCH 02/97] A first go at persisting validator keys and handling configuration. Addresses issue #253. - Creates a keystore directory in the config - Fetches serialized keys from the keystore directory - If no keys, generates keys randomly, saves serialized keys to keystore dir. --- eth2/utils/bls/src/keypair.rs | 4 +++ validator_client/Cargo.toml | 1 + validator_client/src/config.rs | 47 +++++++++++++++++++++++++++++++--- validator_client/src/main.rs | 30 ++++++++++++++++++---- 4 files changed, 73 insertions(+), 9 deletions(-) diff --git a/eth2/utils/bls/src/keypair.rs b/eth2/utils/bls/src/keypair.rs index d60a2fc25..6feb2a585 100644 --- a/eth2/utils/bls/src/keypair.rs +++ b/eth2/utils/bls/src/keypair.rs @@ -14,4 +14,8 @@ impl Keypair { let pk = PublicKey::from_secret_key(&sk); Keypair { sk, pk } } + + pub fn identifier(&self) -> String { + self.pk.concatenated_hex_id() + } } diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index f76772f28..e9d66f6d3 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -18,3 +18,4 @@ slog = "^2.2.3" slog-term = "^2.4.0" slog-async = "^2.3.0" ssz = { path = "../eth2/utils/ssz" } +bincode = "^1.1.2" diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 68405ed2f..e400f228c 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,4 +1,7 @@ +use bls::Keypair; use std::fs; +use std::fs::File; +use std::io::{Error, ErrorKind}; use std::path::PathBuf; use types::ChainSpec; @@ -6,27 +9,63 @@ use types::ChainSpec; #[derive(Clone)] pub struct ClientConfig { pub data_dir: PathBuf, + pub key_dir: PathBuf, pub server: String, pub spec: ChainSpec, } const DEFAULT_LIGHTHOUSE_DIR: &str = ".lighthouse-validators"; +const DEFAULT_KEYSTORE_SUBDIR: &str = "keystore"; impl ClientConfig { /// Build a new configuration from defaults. - pub fn default() -> Self { + pub fn default() -> Result { let data_dir = { let home = dirs::home_dir().expect("Unable to determine home dir."); home.join(DEFAULT_LIGHTHOUSE_DIR) }; - fs::create_dir_all(&data_dir) - .unwrap_or_else(|_| panic!("Unable to create {:?}", &data_dir)); + fs::create_dir_all(&data_dir)?; + + let key_dir = data_dir.join(DEFAULT_KEYSTORE_SUBDIR); + fs::create_dir_all(&key_dir)?; + let server = "localhost:50051".to_string(); let spec = ChainSpec::foundation(); - Self { + Ok(Self { data_dir, + key_dir, server, spec, + }) + } + + // Try to load keys from datadir, or fail + pub fn fetch_keys(&self) -> Result>, Error> { + let mut key_files = fs::read_dir(&self.key_dir)?.peekable(); + + if key_files.peek().is_none() { + return Ok(None); } + + let mut key_pairs: Vec = Vec::new(); + + for key_filename in key_files { + let mut key_file = File::open(key_filename?.path())?; + + let key: Keypair = bincode::deserialize_from(&mut key_file) + .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; + + key_pairs.push(key); + } + + Ok(Some(key_pairs)) + } + + pub fn save_key(&self, key: &Keypair) -> Result<(), Error> { + let key_path = self.key_dir.join(key.identifier() + ".key"); + let mut key_file = File::create(&key_path)?; + bincode::serialize_into(&mut key_file, &key) + .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; + Ok(()) } } diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index ebab8538c..2f2903707 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -6,7 +6,7 @@ use bls::Keypair; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient}; -use slog::{error, info, o, Drain}; +use slog::{debug, error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; use std::path::PathBuf; use std::sync::Arc; @@ -17,6 +17,8 @@ mod block_producer_service; mod config; mod duties; +const NUMBER_OF_VALIDATOR_TEST_KEYS: u16 = 3; + fn main() { // Logging let decorator = slog_term::TermDecorator::new().build(); @@ -55,7 +57,7 @@ fn main() { ) .get_matches(); - let mut config = ClientConfig::default(); + let mut config = ClientConfig::default().expect("Unable to create a default configuration."); // Custom datadir if let Some(dir) = matches.value_of("datadir") { @@ -123,9 +125,27 @@ fn main() { * Start threads. */ let mut threads = vec![]; - // TODO: keypairs are randomly generated; they should be loaded from a file or generated. - // https://github.com/sigp/lighthouse/issues/160 - let keypairs = vec![Keypair::random()]; + + let keypairs = config + .fetch_keys() + .expect("Encountered an error while fetching saved keys.") + .unwrap_or_else(|| { + // TODO: Key generation should occur in a separate binary + let mut k = Vec::new(); + info!( + log, + "No key pairs found, generating and saving 3 random key pairs." + ); + for _n in 0..NUMBER_OF_VALIDATOR_TEST_KEYS { + let keypair = Keypair::random(); + config + .save_key(&keypair) + .expect("Unable to save newly generated private key."); + debug!(log, "Keypair generated {:?}", keypair.identifier()); + k.push(keypair); + } + k + }); for keypair in keypairs { info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); From b000a0972e39d9d48f4b5f649f2baf933ef53b93 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Wed, 13 Mar 2019 13:38:28 +1100 Subject: [PATCH 03/97] Minor updates to Paul's comments. - Bubbled up home_dir not found error - Made comment show up in docs --- validator_client/src/config.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index e400f228c..d9d30c64d 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -21,7 +21,8 @@ impl ClientConfig { /// Build a new configuration from defaults. pub fn default() -> Result { let data_dir = { - let home = dirs::home_dir().expect("Unable to determine home dir."); + let home = dirs::home_dir() + .ok_or(Error::new(ErrorKind::NotFound, "Unable to determine home directory."))?; home.join(DEFAULT_LIGHTHOUSE_DIR) }; fs::create_dir_all(&data_dir)?; @@ -39,7 +40,7 @@ impl ClientConfig { }) } - // Try to load keys from datadir, or fail + /// Try to load keys from key_dir, returning None if none are found or an error. pub fn fetch_keys(&self) -> Result>, Error> { let mut key_files = fs::read_dir(&self.key_dir)?.peekable(); From 2215aa4b4640e5bf4a5ace25a184de1dd0ad934c Mon Sep 17 00:00:00 2001 From: thojest Date: Fri, 15 Mar 2019 11:44:39 +0100 Subject: [PATCH 04/97] added protos specification for Attester and created first draft for attestation_grpc_client (lighthouse-255) --- protos/src/services.proto | 47 +++++++++++++++++++ .../attestation_grpc_client.rs | 32 +++++++++++++ validator_client/src/attester_service/mod.rs | 5 +- validator_client/src/main.rs | 21 ++++++--- 4 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 validator_client/src/attester_service/attestation_grpc_client.rs diff --git a/protos/src/services.proto b/protos/src/services.proto index 16e2d4dba..0523cc958 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -23,6 +23,11 @@ service ValidatorService { rpc ValidatorIndex(PublicKey) returns (IndexResponse); } +service AttestationService { + rpc ProduceAttestationData (ProduceAttestationDataRequest) returns (ProduceAttestationDataResponse); + rpc PublishAttestationData (PublishAttestationDataRequest) returns (PublishAttestationDataResponse); +} + message BeaconBlock { uint64 slot = 1; bytes block_root = 2; @@ -30,6 +35,30 @@ message BeaconBlock { bytes signature = 4; } +message Crosslink { + uint64 epoch = 1; + bytes crosslink_data_root = 2; + +} + +message AttestationData { + uint64 slot = 1; + uint64 shard = 2; + bytes beacon_block_root = 3; + bytes epoch_boundary_root = 4; + bytes crosslink_data_root = 5; + Crosslink latest_crosslink = 6; + uint64 justified_epoch = 7; + bytes justified_block_root = 8; + +} + +message FreeAttestation { + AttestationData attestation_data = 1; + bytes signature = 2; + uint64 validator_index = 3; +} + // Validator requests an unsigned proposal. message ProduceBeaconBlockRequest { uint64 slot = 1; @@ -51,6 +80,24 @@ message PublishBeaconBlockResponse { bytes msg = 2; } +message ProduceAttestationDataRequest { + uint64 slot = 1; + uint64 shard = 2; +} + +message ProduceAttestationDataResponse { + AttestationData attestation_data = 1; +} + +message PublishAttestationDataRequest { + FreeAttestation free_attestation = 1; +} + +message PublishAttestationDataResponse { + bool success = 1; + bytes msg = 2; +} + // A validators duties for some epoch. // TODO: add shard duties. message ValidatorAssignment { diff --git a/validator_client/src/attester_service/attestation_grpc_client.rs b/validator_client/src/attester_service/attestation_grpc_client.rs new file mode 100644 index 000000000..b3a0bd134 --- /dev/null +++ b/validator_client/src/attester_service/attestation_grpc_client.rs @@ -0,0 +1,32 @@ +use protos::services_grpc::AttestationServiceClient; +use std::sync::Arc; + +use attester::{BeaconNode, BeaconNodeError, PublishOutcome}; +use types::{AttestationData, FreeAttestation, Slot}; + +pub struct AttestationGrpcClient { + client: Arc, +} + +impl AttestationGrpcClient { + pub fn new(client: Arc) -> Self { + Self { client } + } +} + +impl BeaconNode for AttestationGrpcClient { + fn produce_attestation_data( + &self, + slot: Slot, + shard: u64, + ) -> Result, BeaconNodeError> { + Err(BeaconNodeError::DecodeFailure) + } + + fn publish_attestation_data( + &self, + free_attestation: FreeAttestation, + ) -> Result { + Err(BeaconNodeError::DecodeFailure) + } +} diff --git a/validator_client/src/attester_service/mod.rs b/validator_client/src/attester_service/mod.rs index fbf8bd005..fe5de7647 100644 --- a/validator_client/src/attester_service/mod.rs +++ b/validator_client/src/attester_service/mod.rs @@ -1,8 +1,11 @@ +mod attestation_grpc_client; use attester::{Attester, BeaconNode, DutiesReader, PollOutcome as AttesterPollOutcome, Signer}; -use slog::Logger; +use slog::{error, info, warn, Logger}; use slot_clock::SlotClock; use std::time::Duration; +pub use self::attestation_grpc_client::AttestationGrpcClient; + pub struct AttesterService { pub attester: Attester, pub poll_interval_millis: u64, diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 2e432ceff..60bc76553 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,13 +1,15 @@ use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; -use crate::attester_service::AttesterService; +use crate::attester_service::{AttestationGrpcClient, AttesterService}; use crate::config::ClientConfig; use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; use bls::Keypair; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; -use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient}; +use protos::services_grpc::{ + AttestationServiceClient, BeaconBlockServiceClient, ValidatorServiceClient, +}; use slog::{error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; use std::path::PathBuf; @@ -106,6 +108,13 @@ fn main() { Arc::new(ValidatorServiceClient::new(ch)) }; + //Beacon node gRPC attester endpoints. + let attester_grpc_client = { + let env = Arc::new(EnvBuilder::new().build()); + let ch = ChannelBuilder::new(env).connect(&config.server); + Arc::new(AttestationServiceClient::new(ch)) + }; + // Spec let spec = Arc::new(config.spec.clone()); @@ -182,15 +191,13 @@ fn main() { }) }; - //Spawn a new thread for attestation for the validator. + // Spawn a new thread for attestation for the validator. let attester_thread = { let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); let duties_map = duties_map.clone(); let slot_clock = slot_clock.clone(); let log = log.clone(); - //TODO: this is wrong, I assume this has to be AttesterGrpcClient, which has to be defined analogous - // to beacon_block_grpc_client.rs - let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); + let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); thread::spawn(move || { let attester = Attester::new(duties_map, slot_clock, client, signer); let mut attester_service = AttesterService { @@ -199,7 +206,7 @@ fn main() { log, }; - block_producer_service.run(); + attester_service.run(); }) }; From d8099ae00c735058a88ea8205bfede7ee8c50683 Mon Sep 17 00:00:00 2001 From: thojest Date: Mon, 18 Mar 2019 21:12:06 +0100 Subject: [PATCH 05/97] started implementing BeaconNode for AttestationGrpcClient; included correct epoch_map for instantiation of Attester (lighthouse-255) --- .../attester_service/attestation_grpc_client.rs | 12 ++++++++++++ validator_client/src/main.rs | 14 ++++++++------ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/validator_client/src/attester_service/attestation_grpc_client.rs b/validator_client/src/attester_service/attestation_grpc_client.rs index b3a0bd134..566d74a39 100644 --- a/validator_client/src/attester_service/attestation_grpc_client.rs +++ b/validator_client/src/attester_service/attestation_grpc_client.rs @@ -2,6 +2,7 @@ use protos::services_grpc::AttestationServiceClient; use std::sync::Arc; use attester::{BeaconNode, BeaconNodeError, PublishOutcome}; +use protos::services::ProduceAttestationDataRequest; use types::{AttestationData, FreeAttestation, Slot}; pub struct AttestationGrpcClient { @@ -20,6 +21,16 @@ impl BeaconNode for AttestationGrpcClient { slot: Slot, shard: u64, ) -> Result, BeaconNodeError> { + let mut req = ProduceAttestationDataRequest::new(); + req.set_slot(slot.as_u64()); + req.set_shard(shard); + + let reply = self + .client + .produce_attestation_data(&req) + .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; + + // TODO: return correct AttestationData Err(BeaconNodeError::DecodeFailure) } @@ -27,6 +38,7 @@ impl BeaconNode for AttestationGrpcClient { &self, free_attestation: FreeAttestation, ) -> Result { + // TODO: return correct PublishOutcome Err(BeaconNodeError::DecodeFailure) } } diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 60bc76553..4664d5dc9 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -2,6 +2,7 @@ use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; use crate::attester_service::{AttestationGrpcClient, AttesterService}; use crate::config::ClientConfig; +use attester::test_utils::EpochMap; use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; use bls::Keypair; @@ -19,7 +20,6 @@ use types::ChainSpec; mod attester_service; mod block_producer_service; - mod config; mod duties; @@ -143,6 +143,7 @@ fn main() { for keypair in keypairs { info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); + let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); // Spawn a new thread to maintain the validator's `EpochDuties`. let duties_manager_thread = { @@ -191,15 +192,15 @@ fn main() { }) }; - // Spawn a new thread for attestation for the validator. + // Spawn a new thread for attestation for the validator. let attester_thread = { let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); - let duties_map = duties_map.clone(); + let epoch_map = epoch_map_for_attester.clone(); let slot_clock = slot_clock.clone(); let log = log.clone(); let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); thread::spawn(move || { - let attester = Attester::new(duties_map, slot_clock, client, signer); + let attester = Attester::new(epoch_map, slot_clock, client, signer); let mut attester_service = AttesterService { attester, poll_interval_millis, @@ -210,13 +211,14 @@ fn main() { }) }; - threads.push((duties_manager_thread, producer_thread)); + threads.push((duties_manager_thread, producer_thread, attester_thread)); } // Naively wait for all the threads to complete. for tuple in threads { - let (manager, producer) = tuple; + let (manager, producer, attester) = tuple; let _ = producer.join(); let _ = manager.join(); + let _ = attester.join(); } } From 49f6e7ac659f7daa70a6939f99332976e9bac2af Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Wed, 20 Mar 2019 16:23:33 +1100 Subject: [PATCH 06/97] Moved configuration around for validator client. - Custom datadir/server argument logic moved into configuration, out of main. - Updated the validator config directory structure, as per issue #253 suggestions - Removed the 'generate 3 random keys' function - Updated the README to reflect new structure - Just exit if there are no keys, don't generate any (this is for accounts_manager, in a separate commit). - Created a lib.rs file, so that the validator client configuration can be included by external crates. --- validator_client/Cargo.toml | 9 +++ validator_client/README.md | 29 +++++++-- validator_client/src/config.rs | 107 +++++++++++++++++++++++++-------- validator_client/src/lib.rs | 3 + validator_client/src/main.rs | 72 +++++----------------- 5 files changed, 136 insertions(+), 84 deletions(-) create mode 100644 validator_client/src/lib.rs diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index e9d66f6d3..327fab22b 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -4,6 +4,15 @@ version = "0.1.0" authors = ["Paul Hauner "] edition = "2018" +[[bin]] +name = "validator_client" +path = "src/main.rs" + +[lib] +name = "validator_client" +path = "src/lib.rs" + + [dependencies] block_proposer = { path = "../eth2/block_proposer" } bls = { path = "../eth2/utils/bls" } diff --git a/validator_client/README.md b/validator_client/README.md index aa84fe013..109d9f317 100644 --- a/validator_client/README.md +++ b/validator_client/README.md @@ -57,10 +57,31 @@ complete and return a block from the BN. ### Configuration -Presently the validator specifics (pubkey, etc.) are randomly generated and the -chain specification (slot length, BLS domain, etc.) are fixed to foundation -parameters. This is temporary and will be upgrade so these parameters can be -read from file (or initialized on first-boot). +Validator configurations are stored in a separate data directory from the main Beacon Node +binary. The validator data directory defaults to: +`$HOME/.lighthouse-validator`, however an alternative can be specified on the command line +with `--datadir`. + +The configuration directory structure looks like: +``` +~/.lighthouse-validator +└── validators + ├── 3cf4210d58ec + │   └── private.key + ├── 9b5d8b5be4e7 + │   └── private.key + └── cf6e07188f48 + └── private.key +``` + +Where the hex value of the directory is a portion of the validator public key. + +Validator keys must be generated using the separate `accounts_manager` binary, which will +place the keys into this directory structure in a format compatible with the validator client. + +The chain specification (slot length, BLS domain, etc.) defaults to foundation +parameters, however is temporary and an upgrade will allow these parameters to be +read from a file (or initialized on first-boot). ## BN Communication diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index d9d30c64d..2e109c69d 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,72 +1,131 @@ use bls::Keypair; +use clap::ArgMatches; use std::fs; use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::PathBuf; use types::ChainSpec; +use bincode; /// Stores the core configuration for this validator instance. #[derive(Clone)] -pub struct ClientConfig { +pub struct ValidatorClientConfig { + /// The data directory, which stores all validator databases pub data_dir: PathBuf, - pub key_dir: PathBuf, + /// The directory where the individual validator configuration directories are stored. + pub validator_dir: PathBuf, + /// The server at which the Beacon Node can be contacted pub server: String, + /// The chain specification that we are connecting to pub spec: ChainSpec, } -const DEFAULT_LIGHTHOUSE_DIR: &str = ".lighthouse-validators"; -const DEFAULT_KEYSTORE_SUBDIR: &str = "keystore"; +const DEFAULT_VALIDATOR_DATADIR: &str = ".lighthouse-validator"; +const DEFAULT_VALIDATORS_SUBDIR: &str = "validators"; +const DEFAULT_PRIVATE_KEY_FILENAME: &str = "private.key"; -impl ClientConfig { - /// Build a new configuration from defaults. - pub fn default() -> Result { - let data_dir = { - let home = dirs::home_dir() - .ok_or(Error::new(ErrorKind::NotFound, "Unable to determine home directory."))?; - home.join(DEFAULT_LIGHTHOUSE_DIR) +impl ValidatorClientConfig { + /// Build a new configuration from defaults, which are overrided by arguments provided. + pub fn build_config(arguments: &ArgMatches) -> Result { + // Use the specified datadir, or default in the home directory + let data_dir: PathBuf = match arguments.value_of("datadir") { + Some(path) => PathBuf::from(path.to_string()), + None => { + let home = dirs::home_dir().ok_or_else(|| Error::new( + ErrorKind::NotFound, + "Unable to determine home directory.", + ))?; + home.join(DEFAULT_VALIDATOR_DATADIR) + } }; fs::create_dir_all(&data_dir)?; - let key_dir = data_dir.join(DEFAULT_KEYSTORE_SUBDIR); - fs::create_dir_all(&key_dir)?; + let validator_dir = data_dir.join(DEFAULT_VALIDATORS_SUBDIR); + fs::create_dir_all(&validator_dir)?; + + let server: String = match arguments.value_of("server") { + Some(srv) => { + //TODO: I don't think this parses correctly a server & port combo + srv.parse::() + .map_err(|e| Error::new(ErrorKind::InvalidInput, e))? + .to_string() + } + None => "localhost:50051".to_string(), + }; + + // TODO: Permit loading a custom spec from file. + let spec: ChainSpec = match arguments.value_of("spec") { + Some(spec_str) => { + match spec_str { + "foundation" => ChainSpec::foundation(), + "few_validators" => ChainSpec::few_validators(), + // Should be impossible due to clap's `possible_values(..)` function. + _ => unreachable!(), + } + } + None => ChainSpec::foundation(), + }; - let server = "localhost:50051".to_string(); - let spec = ChainSpec::foundation(); Ok(Self { data_dir, - key_dir, + validator_dir, server, spec, }) } - /// Try to load keys from key_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. pub fn fetch_keys(&self) -> Result>, Error> { - let mut key_files = fs::read_dir(&self.key_dir)?.peekable(); + let mut validator_dirs = fs::read_dir(&self.validator_dir)?.peekable(); - if key_files.peek().is_none() { + // There are no validator directories. + if validator_dirs.peek().is_none() { return Ok(None); } let mut key_pairs: Vec = Vec::new(); - for key_filename in key_files { - let mut key_file = File::open(key_filename?.path())?; + for validator_dir_result in validator_dirs { + let validator_dir = validator_dir_result?; + + // Try to open the key file directly + // TODO skip keyfiles that are not found, and log the error instead of returning it. + let mut key_file = File::open(validator_dir.path().join(DEFAULT_PRIVATE_KEY_FILENAME))?; let key: Keypair = bincode::deserialize_from(&mut key_file) .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; + // TODO skip keyfile if it's not matched, and log the error instead of returning it. + let validator_directory_name = validator_dir.file_name().into_string().map_err(|_| { + Error::new( + ErrorKind::InvalidData, + "The filename cannot be parsed to a string.", + ) + })?; + if key.identifier() != validator_directory_name { + return Err(Error::new( + ErrorKind::InvalidData, + "The validator directory ID did not match the key found inside.", + )); + } + key_pairs.push(key); } Ok(Some(key_pairs)) } - pub fn save_key(&self, key: &Keypair) -> Result<(), Error> { - let key_path = self.key_dir.join(key.identifier() + ".key"); + /// Saves a keypair to a file inside the appropriate validator directory. Returns the saved path filename. + pub fn save_key(&self, key: &Keypair) -> Result { + let validator_config_path = self.validator_dir.join(key.identifier()); + let key_path = validator_config_path.join(DEFAULT_PRIVATE_KEY_FILENAME); + + fs::create_dir_all(&validator_config_path)?; + let mut key_file = File::create(&key_path)?; + bincode::serialize_into(&mut key_file, &key) .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; - Ok(()) + Ok(key_path) } } diff --git a/validator_client/src/lib.rs b/validator_client/src/lib.rs new file mode 100644 index 000000000..133ccd932 --- /dev/null +++ b/validator_client/src/lib.rs @@ -0,0 +1,3 @@ +pub mod config; + +pub use crate::config::ValidatorClientConfig; \ No newline at end of file diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 2f2903707..99523ef9f 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,24 +1,19 @@ use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; -use crate::config::ClientConfig; +use crate::config::ValidatorClientConfig; use block_proposer::{test_utils::LocalSigner, BlockProducer}; -use bls::Keypair; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient}; -use slog::{debug, error, info, o, Drain}; +use slog::{error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; -use std::path::PathBuf; use std::sync::Arc; -use std::thread; -use types::ChainSpec; +use std::{thread, process, time}; mod block_producer_service; mod config; mod duties; -const NUMBER_OF_VALIDATOR_TEST_KEYS: u16 = 3; - fn main() { // Logging let decorator = slog_term::TermDecorator::new().build(); @@ -57,36 +52,11 @@ fn main() { ) .get_matches(); - let mut config = ClientConfig::default().expect("Unable to create a default configuration."); - - // Custom datadir - if let Some(dir) = matches.value_of("datadir") { - config.data_dir = PathBuf::from(dir.to_string()); - } - - // Custom server port - if let Some(server_str) = matches.value_of("server") { - if let Ok(addr) = server_str.parse::() { - config.server = addr.to_string(); - } else { - error!(log, "Invalid address"; "server" => server_str); - return; - } - } - - // TODO: Permit loading a custom spec from file. - // Custom spec - if let Some(spec_str) = matches.value_of("spec") { - match spec_str { - "foundation" => config.spec = ChainSpec::foundation(), - "few_validators" => config.spec = ChainSpec::few_validators(), - // Should be impossible due to clap's `possible_values(..)` function. - _ => unreachable!(), - }; - } + let config = ValidatorClientConfig::build_config(&matches) + .expect("Unable to build a configuration for the validator client."); // Log configuration - info!(log, ""; + info!(log, "Configuration parameters:"; "data_dir" => &config.data_dir.to_str(), "server" => &config.server); @@ -121,31 +91,21 @@ fn main() { let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); + let keypairs = config + .fetch_keys() + .expect("Encountered an error while fetching saved keys.") + .unwrap_or_else(|| { + error!(log, "No key pairs found in configuration, they must first be generated with: account_manager generate."); + // give the logger a chance to flush the error before exiting. + thread::sleep(time::Duration::from_millis(500)); + process::exit(1) + }); + /* * Start threads. */ let mut threads = vec![]; - let keypairs = config - .fetch_keys() - .expect("Encountered an error while fetching saved keys.") - .unwrap_or_else(|| { - // TODO: Key generation should occur in a separate binary - let mut k = Vec::new(); - info!( - log, - "No key pairs found, generating and saving 3 random key pairs." - ); - for _n in 0..NUMBER_OF_VALIDATOR_TEST_KEYS { - let keypair = Keypair::random(); - config - .save_key(&keypair) - .expect("Unable to save newly generated private key."); - debug!(log, "Keypair generated {:?}", keypair.identifier()); - k.push(keypair); - } - k - }); for keypair in keypairs { info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); From dc2fc7a2505a7c4835fb4dd8076780cc4850ed6c Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Wed, 20 Mar 2019 16:24:28 +1100 Subject: [PATCH 07/97] Added a new binary, accounts_manager. - Updated main Cargo.toml file - Created a new readme & binary - Includes configuration options from the validator, which now has it's config as a library. --- Cargo.toml | 1 + account_manager/Cargo.toml | 13 +++++++++ account_manager/README.md | 24 +++++++++++++++ account_manager/src/main.rs | 58 +++++++++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+) create mode 100644 account_manager/Cargo.toml create mode 100644 account_manager/README.md create mode 100644 account_manager/src/main.rs diff --git a/Cargo.toml b/Cargo.toml index c5aae7f43..a43b1052e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,4 +23,5 @@ members = [ "beacon_node/beacon_chain/test_harness", "protos", "validator_client", + "account_manager", ] diff --git a/account_manager/Cargo.toml b/account_manager/Cargo.toml new file mode 100644 index 000000000..c26d4b70a --- /dev/null +++ b/account_manager/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "account_manager" +version = "0.0.1" +authors = ["Luke Anderson "] +edition = "2018" + +[dependencies] +bls = { path = "../eth2/utils/bls" } +clap = "2.32.0" +slog = "^2.2.3" +slog-term = "^2.4.0" +slog-async = "^2.3.0" +validator_client = { path = "../validator_client" } diff --git a/account_manager/README.md b/account_manager/README.md new file mode 100644 index 000000000..bf8891f40 --- /dev/null +++ b/account_manager/README.md @@ -0,0 +1,24 @@ +# Lighthouse Accounts Manager + +The accounts manager (AM) is a stand-alone binary which allows +users to generate and manage the cryptographic keys necessary to +interact with Ethereum Serenity. + +## Roles + +The AM is responsible for the following tasks: +- Generation of cryptographic key pairs + - Must acquire sufficient entropy to ensure keys are generated securely (TBD) +- Secure storage of private keys + - Keys must be encrypted while at rest on the disk (TBD) + - The format is compatible with the validator client +- Produces messages and transactions necessary to initiate +staking on Ethereum 1.x (TPD) + + +## Implementation + +The AM is not a service, and does not run continuously, nor does it +interact with any running services. +It is intended to be executed separately from other Lighthouse binaries +and produce files which can be consumed by them. \ No newline at end of file diff --git a/account_manager/src/main.rs b/account_manager/src/main.rs new file mode 100644 index 000000000..03546c95b --- /dev/null +++ b/account_manager/src/main.rs @@ -0,0 +1,58 @@ +use bls::Keypair; +use clap::{App, Arg, SubCommand}; +use slog::{debug, info, o, Drain}; +use std::path::PathBuf; +use validator_client::config::ValidatorClientConfig; + +fn main() { + // Logging + let decorator = slog_term::TermDecorator::new().build(); + let drain = slog_term::CompactFormat::new(decorator).build().fuse(); + let drain = slog_async::Async::new(drain).build().fuse(); + let log = slog::Logger::root(drain, o!()); + + // CLI + let matches = App::new("Lighthouse Accounts Manager") + .version("0.0.1") + .author("Sigma Prime ") + .about("Eth 2.0 Accounts Manager") + .arg( + Arg::with_name("datadir") + .long("datadir") + .value_name("DIR") + .help("Data directory for keys and databases.") + .takes_value(true), + ) + .subcommand( + SubCommand::with_name("generate") + .about("Generates a new validator private key") + .version("0.0.1") + .author("Sigma Prime "), + ) + .get_matches(); + + let config = ValidatorClientConfig::build_config(&matches) + .expect("Unable to build a configuration for the account manager."); + + // Log configuration + info!(log, ""; + "data_dir" => &config.data_dir.to_str()); + + match matches.subcommand() { + ("generate", Some(_gen_m)) => { + let keypair = Keypair::random(); + let key_path: PathBuf = config + .save_key(&keypair) + .expect("Unable to save newly generated private key."); + debug!( + log, + "Keypair generated {:?}, saved to: {:?}", + keypair.identifier(), + key_path.to_string_lossy() + ); + } + _ => panic!( + "The account manager must be run with a subcommand. See help for more information." + ), + } +} From 9e47cb56e754f7c61d562317ff0045449ddf49c6 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Wed, 20 Mar 2019 16:27:58 +1100 Subject: [PATCH 08/97] Fixed code appearance with rustfmt. --- validator_client/src/config.rs | 14 +++++++------- validator_client/src/lib.rs | 2 +- validator_client/src/main.rs | 3 +-- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 2e109c69d..d056136c9 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,3 +1,4 @@ +use bincode; use bls::Keypair; use clap::ArgMatches; use std::fs; @@ -5,7 +6,6 @@ use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::PathBuf; use types::ChainSpec; -use bincode; /// Stores the core configuration for this validator instance. #[derive(Clone)] @@ -31,10 +31,9 @@ impl ValidatorClientConfig { let data_dir: PathBuf = match arguments.value_of("datadir") { Some(path) => PathBuf::from(path.to_string()), None => { - let home = dirs::home_dir().ok_or_else(|| Error::new( - ErrorKind::NotFound, - "Unable to determine home directory.", - ))?; + let home = dirs::home_dir().ok_or_else(|| { + Error::new(ErrorKind::NotFound, "Unable to determine home directory.") + })?; home.join(DEFAULT_VALIDATOR_DATADIR) } }; @@ -96,13 +95,14 @@ impl ValidatorClientConfig { .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; // TODO skip keyfile if it's not matched, and log the error instead of returning it. - let validator_directory_name = validator_dir.file_name().into_string().map_err(|_| { + let validator_directory_name = + validator_dir.file_name().into_string().map_err(|_| { Error::new( ErrorKind::InvalidData, "The filename cannot be parsed to a string.", ) })?; - if key.identifier() != validator_directory_name { + if key.identifier() != validator_directory_name { return Err(Error::new( ErrorKind::InvalidData, "The validator directory ID did not match the key found inside.", diff --git a/validator_client/src/lib.rs b/validator_client/src/lib.rs index 133ccd932..60361c051 100644 --- a/validator_client/src/lib.rs +++ b/validator_client/src/lib.rs @@ -1,3 +1,3 @@ pub mod config; -pub use crate::config::ValidatorClientConfig; \ No newline at end of file +pub use crate::config::ValidatorClientConfig; diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 99523ef9f..1830bd1a4 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -8,7 +8,7 @@ use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient}; use slog::{error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; use std::sync::Arc; -use std::{thread, process, time}; +use std::{process, thread, time}; mod block_producer_service; mod config; @@ -106,7 +106,6 @@ fn main() { */ let mut threads = vec![]; - for keypair in keypairs { info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); From ca18d4390aff4bfbf78d361be65916de9b21325f Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Thu, 21 Mar 2019 17:17:01 +1100 Subject: [PATCH 09/97] Add first changes to syncing logic - Adds testing framework - Breaks out new `NetworkContext` object --- beacon_node/beacon_chain/src/lib.rs | 1 + .../beacon_chain/src/test_utils/mod.rs | 3 + .../testing_beacon_chain_builder.rs | 50 +++++ .../test_harness/src/beacon_chain_harness.rs | 11 +- beacon_node/libp2p/Cargo.toml | 1 + beacon_node/libp2p/src/rpc/methods.rs | 28 +++ beacon_node/network/Cargo.toml | 4 + beacon_node/network/src/beacon_chain.rs | 41 ++++ beacon_node/network/src/lib.rs | 4 +- beacon_node/network/src/message_handler.rs | 151 +++++++------- beacon_node/network/src/service.rs | 1 + beacon_node/network/src/sync/simple_sync.rs | 115 ++++++++++- beacon_node/network/tests/tests.rs | 184 ++++++++++++++++++ .../testing_beacon_state_builder.rs | 1 + 14 files changed, 513 insertions(+), 82 deletions(-) create mode 100644 beacon_node/beacon_chain/src/test_utils/mod.rs create mode 100644 beacon_node/beacon_chain/src/test_utils/testing_beacon_chain_builder.rs create mode 100644 beacon_node/network/tests/tests.rs diff --git a/beacon_node/beacon_chain/src/lib.rs b/beacon_node/beacon_chain/src/lib.rs index 2137c0edf..5fa7e7a77 100644 --- a/beacon_node/beacon_chain/src/lib.rs +++ b/beacon_node/beacon_chain/src/lib.rs @@ -3,6 +3,7 @@ mod beacon_chain; mod checkpoint; mod errors; pub mod initialise; +pub mod test_utils; pub use self::beacon_chain::{BeaconChain, BlockProcessingOutcome, InvalidBlock, ValidBlock}; pub use self::checkpoint::CheckPoint; diff --git a/beacon_node/beacon_chain/src/test_utils/mod.rs b/beacon_node/beacon_chain/src/test_utils/mod.rs new file mode 100644 index 000000000..ad251a3c9 --- /dev/null +++ b/beacon_node/beacon_chain/src/test_utils/mod.rs @@ -0,0 +1,3 @@ +mod testing_beacon_chain_builder; + +pub use testing_beacon_chain_builder::TestingBeaconChainBuilder; diff --git a/beacon_node/beacon_chain/src/test_utils/testing_beacon_chain_builder.rs b/beacon_node/beacon_chain/src/test_utils/testing_beacon_chain_builder.rs new file mode 100644 index 000000000..5c5477e55 --- /dev/null +++ b/beacon_node/beacon_chain/src/test_utils/testing_beacon_chain_builder.rs @@ -0,0 +1,50 @@ +pub use crate::{BeaconChain, BeaconChainError, CheckPoint}; +use db::{ + stores::{BeaconBlockStore, BeaconStateStore}, + MemoryDB, +}; +use fork_choice::BitwiseLMDGhost; +use slot_clock::TestingSlotClock; +use ssz::TreeHash; +use std::sync::Arc; +use types::test_utils::TestingBeaconStateBuilder; +use types::*; + +type TestingBeaconChain = BeaconChain>; + +pub struct TestingBeaconChainBuilder { + state_builder: TestingBeaconStateBuilder, +} + +impl TestingBeaconChainBuilder { + pub fn build(self, spec: &ChainSpec) -> TestingBeaconChain { + let db = Arc::new(MemoryDB::open()); + let block_store = Arc::new(BeaconBlockStore::new(db.clone())); + let state_store = Arc::new(BeaconStateStore::new(db.clone())); + let slot_clock = TestingSlotClock::new(spec.genesis_slot.as_u64()); + let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); + + let (genesis_state, _keypairs) = self.state_builder.build(); + + let mut genesis_block = BeaconBlock::empty(&spec); + genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root()); + + // Create the Beacon Chain + BeaconChain::from_genesis( + state_store.clone(), + block_store.clone(), + slot_clock, + genesis_state, + genesis_block, + spec.clone(), + fork_choice, + ) + .unwrap() + } +} + +impl From for TestingBeaconChainBuilder { + fn from(state_builder: TestingBeaconStateBuilder) -> TestingBeaconChainBuilder { + TestingBeaconChainBuilder { state_builder } + } +} diff --git a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs index bc5c93b94..800dd3ce6 100644 --- a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs +++ b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs @@ -36,14 +36,21 @@ impl BeaconChainHarness { /// - A keypair, `BlockProducer` and `Attester` for each validator. /// - A new BeaconChain struct where the given validators are in the genesis. pub fn new(spec: ChainSpec, validator_count: usize) -> Self { + let state_builder = + TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(validator_count, &spec); + Self::from_beacon_state_builder(state_builder, spec) + } + + pub fn from_beacon_state_builder( + state_builder: TestingBeaconStateBuilder, + spec: ChainSpec, + ) -> Self { let db = Arc::new(MemoryDB::open()); let block_store = Arc::new(BeaconBlockStore::new(db.clone())); let state_store = Arc::new(BeaconStateStore::new(db.clone())); let slot_clock = TestingSlotClock::new(spec.genesis_slot.as_u64()); let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); - let state_builder = - TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(validator_count, &spec); let (genesis_state, keypairs) = state_builder.build(); let mut genesis_block = BeaconBlock::empty(&spec); diff --git a/beacon_node/libp2p/Cargo.toml b/beacon_node/libp2p/Cargo.toml index dcbc04d0b..e863c4d78 100644 --- a/beacon_node/libp2p/Cargo.toml +++ b/beacon_node/libp2p/Cargo.toml @@ -5,6 +5,7 @@ authors = ["Age Manning "] edition = "2018" [dependencies] +beacon_chain = { path = "../beacon_chain" } # SigP repository until PR is merged libp2p = { git = "https://github.com/SigP/rust-libp2p", branch = "gossipsub" } types = { path = "../../eth2/types" } diff --git a/beacon_node/libp2p/src/rpc/methods.rs b/beacon_node/libp2p/src/rpc/methods.rs index 3014afd0f..f05ade7ff 100644 --- a/beacon_node/libp2p/src/rpc/methods.rs +++ b/beacon_node/libp2p/src/rpc/methods.rs @@ -1,3 +1,4 @@ +use beacon_chain::parking_lot::RwLockReadGuard; /// Available RPC methods types and ids. use ssz_derive::{Decode, Encode}; use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; @@ -60,6 +61,20 @@ pub enum RPCRequest { BeaconChainState(BeaconChainStateRequest), } +impl RPCRequest { + pub fn method_id(&self) -> u16 { + let method = match self { + RPCRequest::Hello(_) => RPCMethod::Hello, + RPCRequest::Goodbye(_) => RPCMethod::Goodbye, + RPCRequest::BeaconBlockRoots(_) => RPCMethod::BeaconBlockRoots, + RPCRequest::BeaconBlockHeaders(_) => RPCMethod::BeaconBlockHeaders, + RPCRequest::BeaconBlockBodies(_) => RPCMethod::BeaconBlockBodies, + RPCRequest::BeaconChainState(_) => RPCMethod::BeaconChainState, + }; + method.into() + } +} + #[derive(Debug, Clone)] pub enum RPCResponse { Hello(HelloMessage), @@ -69,6 +84,19 @@ pub enum RPCResponse { BeaconChainState(BeaconChainStateResponse), } +impl RPCResponse { + pub fn method_id(&self) -> u16 { + let method = match self { + RPCResponse::Hello(_) => RPCMethod::Hello, + RPCResponse::BeaconBlockRoots(_) => RPCMethod::BeaconBlockRoots, + RPCResponse::BeaconBlockHeaders(_) => RPCMethod::BeaconBlockHeaders, + RPCResponse::BeaconBlockBodies(_) => RPCMethod::BeaconBlockBodies, + RPCResponse::BeaconChainState(_) => RPCMethod::BeaconChainState, + }; + method.into() + } +} + /* Request/Response data structures for RPC methods */ /// The HELLO request/response handshake message. diff --git a/beacon_node/network/Cargo.toml b/beacon_node/network/Cargo.toml index 8b87a9d50..260ee0896 100644 --- a/beacon_node/network/Cargo.toml +++ b/beacon_node/network/Cargo.toml @@ -4,6 +4,10 @@ version = "0.1.0" authors = ["Age Manning "] edition = "2018" +[dev-dependencies] +test_harness = { path = "../beacon_chain/test_harness" } +sloggers = "0.3.2" + [dependencies] beacon_chain = { path = "../beacon_chain" } libp2p = { path = "../libp2p" } diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index 91628cc7e..63e1eb6dd 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -7,6 +7,8 @@ use beacon_chain::{ types::{BeaconState, ChainSpec}, CheckPoint, }; +use libp2p::HelloMessage; +use types::{Epoch, Hash256, Slot}; /// The network's API to the beacon chain. pub trait BeaconChain: Send + Sync { @@ -14,9 +16,19 @@ pub trait BeaconChain: Send + Sync { fn get_state(&self) -> RwLockReadGuard; + fn slot(&self) -> Slot; + fn head(&self) -> RwLockReadGuard; + fn best_slot(&self) -> Slot; + + fn best_block_root(&self) -> Hash256; + fn finalized_head(&self) -> RwLockReadGuard; + + fn finalized_epoch(&self) -> Epoch; + + fn hello_message(&self) -> HelloMessage; } impl BeaconChain for RawBeaconChain @@ -33,11 +45,40 @@ where self.state.read() } + fn slot(&self) -> Slot { + self.get_state().slot + } + fn head(&self) -> RwLockReadGuard { self.head() } + fn finalized_epoch(&self) -> Epoch { + self.get_state().finalized_epoch + } + fn finalized_head(&self) -> RwLockReadGuard { self.finalized_head() } + + fn best_slot(&self) -> Slot { + self.head().beacon_block.slot + } + + fn best_block_root(&self) -> Hash256 { + self.head().beacon_block_root + } + + fn hello_message(&self) -> HelloMessage { + let spec = self.get_spec(); + let state = self.get_state(); + + HelloMessage { + network_id: spec.network_id, + latest_finalized_root: state.finalized_root, + latest_finalized_epoch: state.finalized_epoch, + best_root: self.best_block_root(), + best_slot: self.best_slot(), + } + } } diff --git a/beacon_node/network/src/lib.rs b/beacon_node/network/src/lib.rs index 1e47b9a73..822b05509 100644 --- a/beacon_node/network/src/lib.rs +++ b/beacon_node/network/src/lib.rs @@ -1,8 +1,8 @@ /// This crate provides the network server for Lighthouse. pub mod beacon_chain; pub mod error; -mod message_handler; -mod service; +pub mod message_handler; +pub mod service; pub mod sync; pub use libp2p::NetworkConfig; diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 4cd0ab951..8e390b4af 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -5,32 +5,28 @@ use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use futures::future; use libp2p::{ - rpc::{RPCMethod, RPCRequest, RPCResponse}, + rpc::{RPCRequest, RPCResponse}, HelloMessage, PeerId, RPCEvent, }; +use slog::debug; use slog::warn; -use slog::{debug, trace}; use std::collections::HashMap; use std::sync::Arc; -use std::time::{Duration, Instant}; +use std::time::Instant; /// Timeout for RPC requests. -const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +// const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); /// Timeout before banning a peer for non-identification. -const HELLO_TIMEOUT: Duration = Duration::from_secs(30); +// const HELLO_TIMEOUT: Duration = Duration::from_secs(30); /// Handles messages received from the network and client and organises syncing. pub struct MessageHandler { /// Currently loaded and initialised beacon chain. - chain: Arc, + _chain: Arc, /// The syncing framework. sync: SimpleSync, - /// The network channel to relay messages to the Network service. - network_send: crossbeam_channel::Sender, - /// A mapping of peers and the RPC id we have sent an RPC request to. - requests: HashMap<(PeerId, u64), Instant>, - /// A counter of request id for each peer. - request_ids: HashMap, + /// The context required to send messages to, and process messages from peers. + network_context: NetworkContext, /// The `MessageHandler` logger. log: slog::Logger, } @@ -65,13 +61,9 @@ impl MessageHandler { let sync = SimpleSync::new(beacon_chain.clone(), &log); let mut handler = MessageHandler { - // TODO: The handler may not need a chain, perhaps only sync? - chain: beacon_chain.clone(), + _chain: beacon_chain.clone(), sync, - network_send, - requests: HashMap::new(), - request_ids: HashMap::new(), - + network_context: NetworkContext::new(network_send, log.clone()), log: log.clone(), }; @@ -93,8 +85,7 @@ impl MessageHandler { match message { // we have initiated a connection to a peer HandlerMessage::PeerDialed(peer_id) => { - let id = self.generate_request_id(&peer_id); - self.send_hello(peer_id, id, true); + self.sync.on_connect(&peer_id, &mut self.network_context); } // we have received an RPC message request/response HandlerMessage::RPC(peer_id, rpc_event) => { @@ -118,9 +109,11 @@ impl MessageHandler { /// A new RPC request has been received from the network. fn handle_rpc_request(&mut self, peer_id: PeerId, id: u64, request: RPCRequest) { + // TODO: ensure the id is legit match request { RPCRequest::Hello(hello_message) => { - self.handle_hello_request(peer_id, id, hello_message) + self.sync + .on_hello(&peer_id, hello_message, &mut self.network_context) } // TODO: Handle all requests _ => {} @@ -131,7 +124,12 @@ impl MessageHandler { // we match on id and ignore responses past the timeout. fn handle_rpc_response(&mut self, peer_id: PeerId, id: u64, response: RPCResponse) { // if response id is related to a request, ignore (likely RPC timeout) - if self.requests.remove(&(peer_id.clone(), id)).is_none() { + if self + .network_context + .requests + .remove(&(peer_id.clone(), id)) + .is_none() + { debug!(self.log, "Unrecognized response from peer: {:?}", peer_id); return; } @@ -145,16 +143,10 @@ impl MessageHandler { } } - /// Handle a HELLO RPC request message. - fn handle_hello_request(&mut self, peer_id: PeerId, id: u64, hello_message: HelloMessage) { - // send back a HELLO message - self.send_hello(peer_id.clone(), id, false); - // validate the peer - self.validate_hello(peer_id, hello_message); - } - /// Validate a HELLO RPC message. fn validate_hello(&mut self, peer_id: PeerId, message: HelloMessage) { + self.sync + .on_hello(&peer_id, message.clone(), &mut self.network_context); // validate the peer if !self.sync.validate_peer(peer_id.clone(), message) { debug!( @@ -164,8 +156,68 @@ impl MessageHandler { //TODO: block/ban the peer } } +} - /* General RPC helper functions */ +pub struct NetworkContext { + /// The network channel to relay messages to the Network service. + network_send: crossbeam_channel::Sender, + /// A mapping of peers and the RPC id we have sent an RPC request to. + requests: HashMap<(PeerId, u64), Instant>, + /// A counter of request id for each peer. + request_ids: HashMap, + /// The `MessageHandler` logger. + log: slog::Logger, +} + +impl NetworkContext { + pub fn new(network_send: crossbeam_channel::Sender, log: slog::Logger) -> Self { + Self { + network_send, + requests: HashMap::new(), + request_ids: HashMap::new(), + log, + } + } + + pub fn send_rpc_request(&mut self, peer_id: PeerId, rpc_request: RPCRequest) { + let id = self.generate_request_id(&peer_id); + self.send_rpc_event( + peer_id, + RPCEvent::Request { + id, + method_id: rpc_request.method_id(), + body: rpc_request, + }, + ); + } + + pub fn send_rpc_response(&mut self, peer_id: PeerId, rpc_response: RPCResponse) { + let id = self.generate_request_id(&peer_id); + self.send_rpc_event( + peer_id, + RPCEvent::Response { + id, + method_id: rpc_response.method_id(), + result: rpc_response, + }, + ); + } + + fn send_rpc_event(&self, peer_id: PeerId, rpc_event: RPCEvent) { + self.send(peer_id, OutgoingMessage::RPC(rpc_event)) + } + + fn send(&self, peer_id: PeerId, outgoing_message: OutgoingMessage) { + self.network_send + .send(NetworkMessage::Send(peer_id, outgoing_message)) + .unwrap_or_else(|_| { + warn!( + self.log, + "Could not send RPC message to the network service" + ) + }); + // + } /// Generates a new request id for a peer. fn generate_request_id(&mut self, peer_id: &PeerId) -> u64 { @@ -185,41 +237,4 @@ impl MessageHandler { ); id } - - /// Sends a HELLO RPC request or response to a newly connected peer. - //TODO: The boolean determines if sending request/respond, will be cleaner in the RPC re-write - fn send_hello(&mut self, peer_id: PeerId, id: u64, is_request: bool) { - let rpc_event = if is_request { - RPCEvent::Request { - id, - method_id: RPCMethod::Hello.into(), - body: RPCRequest::Hello(self.sync.generate_hello()), - } - } else { - RPCEvent::Response { - id, - method_id: RPCMethod::Hello.into(), - result: RPCResponse::Hello(self.sync.generate_hello()), - } - }; - - // send the hello request to the network - trace!(self.log, "Sending HELLO message to peer {:?}", peer_id); - self.send_rpc(peer_id, rpc_event); - } - - /// Sends an RPC request/response to the network server. - fn send_rpc(&self, peer_id: PeerId, rpc_event: RPCEvent) { - self.network_send - .send(NetworkMessage::Send( - peer_id, - OutgoingMessage::RPC(rpc_event), - )) - .unwrap_or_else(|_| { - warn!( - self.log, - "Could not send RPC message to the network service" - ) - }); - } } diff --git a/beacon_node/network/src/service.rs b/beacon_node/network/src/service.rs index c3045d280..d01188f5d 100644 --- a/beacon_node/network/src/service.rs +++ b/beacon_node/network/src/service.rs @@ -6,6 +6,7 @@ use crossbeam_channel::{unbounded as channel, Sender, TryRecvError}; use futures::prelude::*; use futures::sync::oneshot; use futures::Stream; +use libp2p::rpc::RPCResponse; use libp2p::RPCEvent; use libp2p::Service as LibP2PService; use libp2p::{Libp2pEvent, PeerId}; diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 95c7092c3..ae6a9e7a1 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,11 +1,16 @@ use crate::beacon_chain::BeaconChain; -use libp2p::rpc::HelloMessage; +use crate::message_handler::{MessageHandler, NetworkContext}; +use crate::service::NetworkMessage; +use crossbeam_channel::Sender; +use libp2p::rpc::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; use libp2p::PeerId; use slog::{debug, o}; use std::collections::HashMap; use std::sync::Arc; use types::{Epoch, Hash256, Slot}; +type NetworkSender = Sender; + /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; @@ -17,6 +22,32 @@ pub struct PeerSyncInfo { best_slot: Slot, } +impl PeerSyncInfo { + pub fn is_on_chain(&self, chain: &Arc) -> bool { + // TODO: make useful. + true + } + + pub fn has_higher_finalized_epoch(&self, chain: &Arc) -> bool { + self.latest_finalized_epoch > chain.get_state().finalized_epoch + } + + pub fn has_higher_best_slot(&self, chain: &Arc) -> bool { + self.latest_finalized_epoch > chain.get_state().finalized_epoch + } +} + +impl From for PeerSyncInfo { + fn from(hello: HelloMessage) -> PeerSyncInfo { + PeerSyncInfo { + latest_finalized_root: hello.latest_finalized_root, + latest_finalized_epoch: hello.latest_finalized_epoch, + best_root: hello.best_root, + best_slot: hello.best_slot, + } + } +} + /// The current syncing state. #[derive(PartialEq)] pub enum SyncState { @@ -60,17 +91,81 @@ impl SimpleSync { } } + pub fn on_connect(&self, peer_id: &PeerId, network: &mut NetworkContext) { + network.send_rpc_request( + peer_id.clone(), + RPCRequest::Hello(self.chain.hello_message()), + ); + } + + pub fn on_hello_request( + &self, + peer_id: &PeerId, + hello: HelloMessage, + network: &mut NetworkContext, + ) { + network.send_rpc_response( + peer_id.clone(), + RPCResponse::Hello(self.chain.hello_message()), + ); + self.on_hello(peer_id, hello, network); + } + + pub fn on_hello(&self, peer_id: &PeerId, hello: HelloMessage, network: &mut NetworkContext) { + // network id must match + if hello.network_id != self.network_id { + debug!(self.log, "Bad network id. Peer: {:?}", peer_id); + return; + } + + let peer = PeerSyncInfo::from(hello); + + /* + if peer.has_higher_finalized_epoch(&self.chain) { + // we need blocks + let peer_slot = peer.latest_finalized_epoch.start_slot(spec.slots_per_epoch); + let our_slot = self.chain.finalized_epoch(); + let required_slots = peer_slot - our_slot; + } else { + if !peer.is_on_chain(&self.chain) { + return (true, responses); + } + // + } + */ + + /* + // compare latest epoch and finalized root to see if they exist in our chain + if peer_info.latest_finalized_epoch <= self.latest_finalized_epoch { + // ensure their finalized root is in our chain + // TODO: Get the finalized root at hello_message.latest_epoch and ensure they match + //if (hello_message.latest_finalized_root == self.chain.get_state() { + // return false; + // } + } + + // the client is valid, add it to our list of known_peers and request sync if required + // update peer list if peer already exists + let peer_info = PeerSyncInfo::from(hello); + + debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); + self.known_peers.insert(peer_id, peer_info); + + // set state to sync + if self.state == SyncState::Idle + && hello_message.best_slot > self.latest_slot + SLOT_IMPORT_TOLERANCE + { + self.state = SyncState::Downloading; + //TODO: Start requesting blocks from known peers. Ideally in batches + } + + true + */ + } + /// Generates our current state in the form of a HELLO RPC message. pub fn generate_hello(&self) -> HelloMessage { - let state = &self.chain.get_state(); - //TODO: Paul to verify the logic of these fields. - HelloMessage { - network_id: self.network_id, - latest_finalized_root: state.finalized_root, - latest_finalized_epoch: state.finalized_epoch, - best_root: state.latest_block_roots[0], //TODO: build correct value as a beacon chain function - best_slot: state.slot - 1, - } + self.chain.hello_message() } pub fn validate_peer(&mut self, peer_id: PeerId, hello_message: HelloMessage) -> bool { diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs new file mode 100644 index 000000000..dc0832fed --- /dev/null +++ b/beacon_node/network/tests/tests.rs @@ -0,0 +1,184 @@ +use beacon_chain::test_utils::TestingBeaconChainBuilder; +use crossbeam_channel::{unbounded, Receiver, Sender}; +use libp2p::rpc::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; +use libp2p::{PeerId, RPCEvent}; +use network::beacon_chain::BeaconChain as NetworkBeaconChain; +use network::message_handler::{HandlerMessage, MessageHandler}; +use network::service::{NetworkMessage, OutgoingMessage}; +use sloggers::terminal::{Destination, TerminalLoggerBuilder}; +use sloggers::types::Severity; +use sloggers::Build; +use std::sync::Arc; +use test_harness::BeaconChainHarness; +use tokio::runtime::TaskExecutor; +use types::{test_utils::TestingBeaconStateBuilder, *}; + +pub struct SyncNode { + pub id: usize, + sender: Sender, + receiver: Receiver, +} + +impl SyncNode { + pub fn new( + id: usize, + executor: &TaskExecutor, + chain: Arc, + logger: slog::Logger, + ) -> Self { + let (network_sender, network_receiver) = unbounded(); + let message_handler_sender = + MessageHandler::spawn(chain, network_sender, executor, logger).unwrap(); + + Self { + id, + sender: message_handler_sender, + receiver: network_receiver, + } + } + + fn send(&self, message: HandlerMessage) { + self.sender.send(message).unwrap(); + } + + fn recv(&self) -> NetworkMessage { + self.receiver.recv().unwrap() + } + + fn recv_rpc_response(&self) -> RPCResponse { + let network_message = self.recv(); + match network_message { + NetworkMessage::Send( + _peer_id, + OutgoingMessage::RPC(RPCEvent::Response { + id: _, + method_id: _, + result, + }), + ) => result, + _ => panic!("get_rpc_response failed! got {:?}", network_message), + } + } + + fn recv_rpc_request(&self) -> RPCRequest { + let network_message = self.recv(); + match network_message { + NetworkMessage::Send( + _peer_id, + OutgoingMessage::RPC(RPCEvent::Request { + id: _, + method_id: _, + body, + }), + ) => body, + _ => panic!("get_rpc_request failed! got {:?}", network_message), + } + } +} + +fn get_logger() -> slog::Logger { + let mut builder = TerminalLoggerBuilder::new(); + builder.level(Severity::Debug); + builder.destination(Destination::Stderr); + builder.build().unwrap() +} + +pub struct SyncMaster { + harness: BeaconChainHarness, + peer_id: PeerId, + response_ids: Vec, +} + +impl SyncMaster { + fn from_beacon_state_builder( + state_builder: TestingBeaconStateBuilder, + node_count: usize, + spec: &ChainSpec, + ) -> Self { + let harness = BeaconChainHarness::from_beacon_state_builder(state_builder, spec.clone()); + let peer_id = PeerId::random(); + let response_ids = vec![0; node_count]; + + Self { + harness, + peer_id, + response_ids, + } + } + + pub fn response_id(&mut self, node: &SyncNode) -> u64 { + let id = self.response_ids[node.id]; + self.response_ids[node.id] += 1; + id + } + + pub fn do_hello_with(&mut self, node: &SyncNode) { + let message = HandlerMessage::PeerDialed(self.peer_id.clone()); + node.send(message); + + let request = node.recv_rpc_request(); + + match request { + RPCRequest::Hello(_hello) => { + let hello = self.harness.beacon_chain.hello_message(); + let response = self.rpc_response(node, RPCResponse::Hello(hello)); + node.send(response); + } + _ => panic!("Got message other than hello from node."), + } + } + + fn rpc_response(&mut self, node: &SyncNode, rpc_response: RPCResponse) -> HandlerMessage { + HandlerMessage::RPC( + self.peer_id.clone(), + RPCEvent::Response { + id: self.response_id(node), + method_id: RPCMethod::Hello.into(), + result: rpc_response, + }, + ) + } +} + +fn test_setup( + state_builder: TestingBeaconStateBuilder, + node_count: usize, + spec: &ChainSpec, + logger: slog::Logger, +) -> (tokio::runtime::Runtime, SyncMaster, Vec) { + let runtime = tokio::runtime::Runtime::new().unwrap(); + + let mut nodes = Vec::with_capacity(node_count); + for id in 0..node_count { + let local_chain = TestingBeaconChainBuilder::from(state_builder.clone()).build(&spec); + let node = SyncNode::new( + id, + &runtime.executor(), + Arc::new(local_chain), + logger.clone(), + ); + + nodes.push(node); + } + + let master = SyncMaster::from_beacon_state_builder(state_builder, node_count, &spec); + + (runtime, master, nodes) +} + +#[test] +fn first_test() { + let logger = get_logger(); + let spec = ChainSpec::few_validators(); + let validator_count = 8; + let node_count = 1; + + let state_builder = + TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(validator_count, &spec); + + let (runtime, mut master, nodes) = test_setup(state_builder, node_count, &spec, logger.clone()); + + master.do_hello_with(&nodes[0]); + + runtime.shutdown_now(); +} diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index e76a01e49..7a7a902de 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -23,6 +23,7 @@ pub fn keypairs_path() -> PathBuf { /// Builds a beacon state to be used for testing purposes. /// /// This struct should **never be used for production purposes.** +#[derive(Clone)] pub struct TestingBeaconStateBuilder { state: BeaconState, keypairs: Vec, From 430702b38dbad76a082a252772081af84842e2cb Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Thu, 21 Mar 2019 18:21:26 +1100 Subject: [PATCH 10/97] Clean println's out of state processing --- beacon_node/beacon_chain/src/beacon_chain.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index bf87adf10..01787f95b 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -596,7 +596,6 @@ where // Transition the parent state to the present slot. let mut state = parent_state; - println!("parent process state: {:?}", state.latest_block_header); let previous_block_header = parent_block.into_header(); for _ in state.slot.as_u64()..present_slot.as_u64() { if let Err(e) = per_slot_processing(&mut state, &previous_block_header, &self.spec) { @@ -614,8 +613,6 @@ where )); } - println!("process state: {:?}", state.latest_block_header); - let state_root = state.canonical_root(); if block.state_root != state_root { @@ -706,8 +703,6 @@ where per_block_processing_without_verifying_block_signature(&mut state, &block, &self.spec)?; - println!("produce state: {:?}", state.latest_block_header); - let state_root = state.canonical_root(); block.state_root = state_root; From f3c81cda99ff6e85b79780c4dc8b4d0d84796025 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Thu, 21 Mar 2019 18:21:50 +1100 Subject: [PATCH 11/97] Implement hello responses. --- beacon_node/libp2p/src/rpc/methods.rs | 47 +++--- beacon_node/libp2p/src/rpc/mod.rs | 2 +- beacon_node/network/src/message_handler.rs | 27 ++-- beacon_node/network/src/service.rs | 1 - beacon_node/network/src/sync/simple_sync.rs | 158 +++++++++----------- beacon_node/network/tests/tests.rs | 33 +++- 6 files changed, 136 insertions(+), 132 deletions(-) diff --git a/beacon_node/libp2p/src/rpc/methods.rs b/beacon_node/libp2p/src/rpc/methods.rs index f05ade7ff..381fc8b01 100644 --- a/beacon_node/libp2p/src/rpc/methods.rs +++ b/beacon_node/libp2p/src/rpc/methods.rs @@ -1,4 +1,3 @@ -use beacon_chain::parking_lot::RwLockReadGuard; /// Available RPC methods types and ids. use ssz_derive::{Decode, Encode}; use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; @@ -115,75 +114,75 @@ pub struct HelloMessage { } /// Request a number of beacon block roots from a peer. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockRootsRequest { /// The starting slot of the requested blocks. - start_slot: Slot, + pub start_slot: Slot, /// The number of blocks from the start slot. - count: u64, // this must be less than 32768. //TODO: Enforce this in the lower layers + pub count: u64, // this must be less than 32768. //TODO: Enforce this in the lower layers } /// Response containing a number of beacon block roots from a peer. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockRootsResponse { /// List of requested blocks and associated slots. - roots: Vec, + pub roots: Vec, } /// Contains a block root and associated slot. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BlockRootSlot { /// The block root. - block_root: Hash256, + pub block_root: Hash256, /// The block slot. - slot: Slot, + pub slot: Slot, } /// Request a number of beacon block headers from a peer. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockHeadersRequest { /// The starting header hash of the requested headers. - start_root: Hash256, + pub start_root: Hash256, /// The starting slot of the requested headers. - start_slot: Slot, + pub start_slot: Slot, /// The maximum number of headers than can be returned. - max_headers: u64, + pub max_headers: u64, /// The maximum number of slots to skip between blocks. - skip_slots: u64, + pub skip_slots: u64, } /// Response containing requested block headers. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockHeadersResponse { /// The list of requested beacon block headers. - headers: Vec, + pub headers: Vec, } /// Request a number of beacon block bodies from a peer. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockBodiesRequest { /// The list of beacon block bodies being requested. - block_roots: Hash256, + pub block_roots: Hash256, } /// Response containing the list of requested beacon block bodies. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockBodiesResponse { /// The list of beacon block bodies being requested. - block_bodies: Vec, + pub block_bodies: Vec, } /// Request values for tree hashes which yield a blocks `state_root`. -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconChainStateRequest { /// The tree hashes that a value is requested for. - hashes: Vec, + pub hashes: Vec, } /// Request values for tree hashes which yield a blocks `state_root`. // Note: TBD -#[derive(Encode, Decode, Clone, Debug)] +#[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconChainStateResponse { /// The values corresponding the to the requested tree hashes. - values: bool, //TBD - stubbed with encodeable bool + pub values: bool, //TBD - stubbed with encodeable bool } diff --git a/beacon_node/libp2p/src/rpc/mod.rs b/beacon_node/libp2p/src/rpc/mod.rs index a1cfadafe..a1573ec93 100644 --- a/beacon_node/libp2p/src/rpc/mod.rs +++ b/beacon_node/libp2p/src/rpc/mod.rs @@ -2,7 +2,7 @@ /// /// This is purpose built for Ethereum 2.0 serenity and the protocol listens on /// `/eth/serenity/rpc/1.0.0` -mod methods; +pub mod methods; mod protocol; use futures::prelude::*; diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 8e390b4af..afd407abe 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -6,7 +6,7 @@ use crossbeam_channel::{unbounded as channel, Sender}; use futures::future; use libp2p::{ rpc::{RPCRequest, RPCResponse}, - HelloMessage, PeerId, RPCEvent, + PeerId, RPCEvent, }; use slog::debug; use slog::warn; @@ -85,7 +85,7 @@ impl MessageHandler { match message { // we have initiated a connection to a peer HandlerMessage::PeerDialed(peer_id) => { - self.sync.on_connect(&peer_id, &mut self.network_context); + self.sync.on_connect(peer_id, &mut self.network_context); } // we have received an RPC message request/response HandlerMessage::RPC(peer_id, rpc_event) => { @@ -113,7 +113,7 @@ impl MessageHandler { match request { RPCRequest::Hello(hello_message) => { self.sync - .on_hello(&peer_id, hello_message, &mut self.network_context) + .on_hello(peer_id, hello_message, &mut self.network_context) } // TODO: Handle all requests _ => {} @@ -136,26 +136,13 @@ impl MessageHandler { match response { RPCResponse::Hello(hello_message) => { debug!(self.log, "Hello response received from peer: {:?}", peer_id); - self.validate_hello(peer_id, hello_message); + self.sync + .on_hello(peer_id, hello_message, &mut self.network_context); } // TODO: Handle all responses _ => {} } } - - /// Validate a HELLO RPC message. - fn validate_hello(&mut self, peer_id: PeerId, message: HelloMessage) { - self.sync - .on_hello(&peer_id, message.clone(), &mut self.network_context); - // validate the peer - if !self.sync.validate_peer(peer_id.clone(), message) { - debug!( - self.log, - "Peer dropped due to mismatching HELLO messages: {:?}", peer_id - ); - //TODO: block/ban the peer - } - } } pub struct NetworkContext { @@ -179,6 +166,10 @@ impl NetworkContext { } } + pub fn disconnect(&self, _peer_id: PeerId) { + // TODO: disconnect peers. + } + pub fn send_rpc_request(&mut self, peer_id: PeerId, rpc_request: RPCRequest) { let id = self.generate_request_id(&peer_id); self.send_rpc_event( diff --git a/beacon_node/network/src/service.rs b/beacon_node/network/src/service.rs index d01188f5d..c3045d280 100644 --- a/beacon_node/network/src/service.rs +++ b/beacon_node/network/src/service.rs @@ -6,7 +6,6 @@ use crossbeam_channel::{unbounded as channel, Sender, TryRecvError}; use futures::prelude::*; use futures::sync::oneshot; use futures::Stream; -use libp2p::rpc::RPCResponse; use libp2p::RPCEvent; use libp2p::Service as LibP2PService; use libp2p::{Libp2pEvent, PeerId}; diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index ae6a9e7a1..0d75f3739 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,8 +1,9 @@ use crate::beacon_chain::BeaconChain; -use crate::message_handler::{MessageHandler, NetworkContext}; +use crate::message_handler::NetworkContext; use crate::service::NetworkMessage; use crossbeam_channel::Sender; -use libp2p::rpc::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; +use libp2p::rpc::methods::*; +use libp2p::rpc::{RPCRequest, RPCResponse}; use libp2p::PeerId; use slog::{debug, o}; use std::collections::HashMap; @@ -15,6 +16,7 @@ type NetworkSender = Sender; const SLOT_IMPORT_TOLERANCE: u64 = 100; /// Keeps track of syncing information for known connected peers. +#[derive(Clone, Copy)] pub struct PeerSyncInfo { latest_finalized_root: Hash256, latest_finalized_epoch: Epoch, @@ -23,18 +25,37 @@ pub struct PeerSyncInfo { } impl PeerSyncInfo { - pub fn is_on_chain(&self, chain: &Arc) -> bool { + fn is_on_chain(&self, chain: &Arc) -> bool { // TODO: make useful. true } - pub fn has_higher_finalized_epoch(&self, chain: &Arc) -> bool { + fn has_higher_finalized_epoch(&self, chain: &Arc) -> bool { self.latest_finalized_epoch > chain.get_state().finalized_epoch } - pub fn has_higher_best_slot(&self, chain: &Arc) -> bool { + fn has_higher_best_slot(&self, chain: &Arc) -> bool { self.latest_finalized_epoch > chain.get_state().finalized_epoch } + + pub fn status(&self, chain: &Arc) -> PeerStatus { + if self.has_higher_finalized_epoch(chain) { + PeerStatus::HigherFinalizedEpoch + } else if !self.is_on_chain(chain) { + PeerStatus::HigherFinalizedEpoch + } else if self.has_higher_best_slot(chain) { + PeerStatus::HigherBestSlot + } else { + PeerStatus::NotInteresting + } + } +} + +pub enum PeerStatus { + OnDifferentChain, + HigherFinalizedEpoch, + HigherBestSlot, + NotInteresting, } impl From for PeerSyncInfo { @@ -91,16 +112,13 @@ impl SimpleSync { } } - pub fn on_connect(&self, peer_id: &PeerId, network: &mut NetworkContext) { - network.send_rpc_request( - peer_id.clone(), - RPCRequest::Hello(self.chain.hello_message()), - ); + pub fn on_connect(&self, peer_id: PeerId, network: &mut NetworkContext) { + network.send_rpc_request(peer_id, RPCRequest::Hello(self.chain.hello_message())); } pub fn on_hello_request( - &self, - peer_id: &PeerId, + &mut self, + peer_id: PeerId, hello: HelloMessage, network: &mut NetworkContext, ) { @@ -111,97 +129,63 @@ impl SimpleSync { self.on_hello(peer_id, hello, network); } - pub fn on_hello(&self, peer_id: &PeerId, hello: HelloMessage, network: &mut NetworkContext) { + pub fn on_hello(&mut self, peer_id: PeerId, hello: HelloMessage, network: &mut NetworkContext) { + let spec = self.chain.get_spec(); + // network id must match if hello.network_id != self.network_id { debug!(self.log, "Bad network id. Peer: {:?}", peer_id); + network.disconnect(peer_id); return; } let peer = PeerSyncInfo::from(hello); - - /* - if peer.has_higher_finalized_epoch(&self.chain) { - // we need blocks - let peer_slot = peer.latest_finalized_epoch.start_slot(spec.slots_per_epoch); - let our_slot = self.chain.finalized_epoch(); - let required_slots = peer_slot - our_slot; - } else { - if !peer.is_on_chain(&self.chain) { - return (true, responses); - } - // - } - */ - - /* - // compare latest epoch and finalized root to see if they exist in our chain - if peer_info.latest_finalized_epoch <= self.latest_finalized_epoch { - // ensure their finalized root is in our chain - // TODO: Get the finalized root at hello_message.latest_epoch and ensure they match - //if (hello_message.latest_finalized_root == self.chain.get_state() { - // return false; - // } - } - - // the client is valid, add it to our list of known_peers and request sync if required - // update peer list if peer already exists - let peer_info = PeerSyncInfo::from(hello); - debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); - self.known_peers.insert(peer_id, peer_info); + self.known_peers.insert(peer_id.clone(), peer); - // set state to sync - if self.state == SyncState::Idle - && hello_message.best_slot > self.latest_slot + SLOT_IMPORT_TOLERANCE - { + match peer.status(&self.chain) { + PeerStatus::OnDifferentChain => { + debug!(self.log, "Peer is on different chain. Peer: {:?}", peer_id); + + network.disconnect(peer_id); + } + PeerStatus::HigherFinalizedEpoch => { + let start_slot = peer.latest_finalized_epoch.start_slot(spec.slots_per_epoch); + let required_slots = start_slot - self.chain.slot(); + + self.request_block_roots(peer_id, start_slot, required_slots.as_u64(), network); + } + PeerStatus::HigherBestSlot => { + let start_slot = peer.best_slot; + let required_slots = start_slot - self.chain.slot(); + + self.request_block_roots(peer_id, start_slot, required_slots.as_u64(), network); + } + PeerStatus::NotInteresting => {} + } + } + + fn request_block_roots( + &mut self, + peer_id: PeerId, + start_slot: Slot, + count: u64, + network: &mut NetworkContext, + ) { + // Potentially set state to sync. + if self.state == SyncState::Idle && count > SLOT_IMPORT_TOLERANCE { self.state = SyncState::Downloading; - //TODO: Start requesting blocks from known peers. Ideally in batches } - true - */ + // TODO: handle count > max count. + network.send_rpc_request( + peer_id.clone(), + RPCRequest::BeaconBlockRoots(BeaconBlockRootsRequest { start_slot, count }), + ); } /// Generates our current state in the form of a HELLO RPC message. pub fn generate_hello(&self) -> HelloMessage { self.chain.hello_message() } - - pub fn validate_peer(&mut self, peer_id: PeerId, hello_message: HelloMessage) -> bool { - // network id must match - if hello_message.network_id != self.network_id { - return false; - } - // compare latest epoch and finalized root to see if they exist in our chain - if hello_message.latest_finalized_epoch <= self.latest_finalized_epoch { - // ensure their finalized root is in our chain - // TODO: Get the finalized root at hello_message.latest_epoch and ensure they match - //if (hello_message.latest_finalized_root == self.chain.get_state() { - // return false; - // } - } - - // the client is valid, add it to our list of known_peers and request sync if required - // update peer list if peer already exists - let peer_info = PeerSyncInfo { - latest_finalized_root: hello_message.latest_finalized_root, - latest_finalized_epoch: hello_message.latest_finalized_epoch, - best_root: hello_message.best_root, - best_slot: hello_message.best_slot, - }; - - debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); - self.known_peers.insert(peer_id, peer_info); - - // set state to sync - if self.state == SyncState::Idle - && hello_message.best_slot > self.latest_slot + SLOT_IMPORT_TOLERANCE - { - self.state = SyncState::Downloading; - //TODO: Start requesting blocks from known peers. Ideally in batches - } - - true - } } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index dc0832fed..b5635cf8c 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -1,5 +1,6 @@ use beacon_chain::test_utils::TestingBeaconChainBuilder; use crossbeam_channel::{unbounded, Receiver, Sender}; +use libp2p::rpc::methods::*; use libp2p::rpc::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; use libp2p::{PeerId, RPCEvent}; use network::beacon_chain::BeaconChain as NetworkBeaconChain; @@ -9,6 +10,7 @@ use sloggers::terminal::{Destination, TerminalLoggerBuilder}; use sloggers::types::Severity; use sloggers::Build; use std::sync::Arc; +use std::time::Duration; use test_harness::BeaconChainHarness; use tokio::runtime::TaskExecutor; use types::{test_utils::TestingBeaconStateBuilder, *}; @@ -42,7 +44,9 @@ impl SyncNode { } fn recv(&self) -> NetworkMessage { - self.receiver.recv().unwrap() + self.receiver + .recv_timeout(Duration::from_millis(500)) + .unwrap() } fn recv_rpc_response(&self) -> RPCResponse { @@ -106,6 +110,12 @@ impl SyncMaster { } } + pub fn build_blocks(&mut self, blocks: usize) { + for _ in 0..blocks { + self.harness.advance_chain_with_block(); + } + } + pub fn response_id(&mut self, node: &SyncNode) -> u64 { let id = self.response_ids[node.id]; self.response_ids[node.id] += 1; @@ -140,6 +150,17 @@ impl SyncMaster { } } +fn assert_sent_block_root_request(node: &SyncNode, expected: BeaconBlockRootsRequest) { + let request = node.recv_rpc_request(); + + match request { + RPCRequest::BeaconBlockRoots(response) => { + assert_eq!(expected, response, "Bad block roots response"); + } + _ => assert!(false, "Did not get block root request"), + } +} + fn test_setup( state_builder: TestingBeaconStateBuilder, node_count: usize, @@ -178,7 +199,17 @@ fn first_test() { let (runtime, mut master, nodes) = test_setup(state_builder, node_count, &spec, logger.clone()); + master.build_blocks(10); + master.do_hello_with(&nodes[0]); + assert_sent_block_root_request( + &nodes[0], + BeaconBlockRootsRequest { + start_slot: Slot::new(1), + count: 10, + }, + ); + runtime.shutdown_now(); } From 7cbee46227fb51f581b9d9c9c8dfb4f058e9dd18 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 22 Mar 2019 10:08:40 +1100 Subject: [PATCH 12/97] Add FakeSignature and FakeAggregateSignature They replace Signature and FakeAggregateSignature when compling with debug. Compiling with release uses the real structs. --- .travis.yml | 2 + .../utils/bls/src/fake_aggregate_signature.rs | 117 ++++++++++++++++++ eth2/utils/bls/src/fake_signature.rs | 117 ++++++++++++++++++ eth2/utils/bls/src/lib.rs | 20 ++- 4 files changed, 253 insertions(+), 3 deletions(-) create mode 100644 eth2/utils/bls/src/fake_aggregate_signature.rs create mode 100644 eth2/utils/bls/src/fake_signature.rs diff --git a/.travis.yml b/.travis.yml index d43d21a00..44e78ee04 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,9 @@ before_install: - sudo chown -R $USER /usr/local/include/google script: - cargo build --verbose --all + - cargo build --verbose --release --all - cargo test --verbose --all + - cargo test --verbose --release --all - cargo fmt --all -- --check rust: - stable diff --git a/eth2/utils/bls/src/fake_aggregate_signature.rs b/eth2/utils/bls/src/fake_aggregate_signature.rs new file mode 100644 index 000000000..23e2b54ef --- /dev/null +++ b/eth2/utils/bls/src/fake_aggregate_signature.rs @@ -0,0 +1,117 @@ +use super::{fake_signature::FakeSignature, AggregatePublicKey}; +use serde::de::{Deserialize, Deserializer}; +use serde::ser::{Serialize, Serializer}; +use serde_hex::{encode as hex_encode, PrefixedHexVisitor}; +use ssz::{ + decode_ssz_list, hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash, +}; + +const SIGNATURE_LENGTH: usize = 48; + +/// A BLS aggregate signature. +/// +/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ +/// serialization). +#[derive(Debug, PartialEq, Clone, Default, Eq)] +pub struct FakeAggregateSignature { + bytes: Vec, +} + +impl FakeAggregateSignature { + /// Creates a new all-zero's signature + pub fn new() -> Self { + Self::zero() + } + + /// Creates a new all-zero's signature + pub fn zero() -> Self { + Self { + bytes: vec![0; SIGNATURE_LENGTH], + } + } + + /// Does glorious nothing. + pub fn add(&mut self, _signature: &FakeSignature) { + // Do nothing. + } + + /// _Always_ returns `true`. + pub fn verify( + &self, + _msg: &[u8], + _domain: u64, + _aggregate_public_key: &AggregatePublicKey, + ) -> bool { + true + } + + /// _Always_ returns `true`. + pub fn verify_multiple( + &self, + _messages: &[&[u8]], + _domain: u64, + _aggregate_public_keys: &[&AggregatePublicKey], + ) -> bool { + true + } +} + +impl Encodable for FakeAggregateSignature { + fn ssz_append(&self, s: &mut SszStream) { + s.append_vec(&self.bytes); + } +} + +impl Decodable for FakeAggregateSignature { + fn ssz_decode(bytes: &[u8], i: usize) -> Result<(Self, usize), DecodeError> { + let (sig_bytes, i) = decode_ssz_list(bytes, i)?; + Ok((FakeAggregateSignature { bytes: sig_bytes }, i)) + } +} + +impl Serialize for FakeAggregateSignature { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&hex_encode(ssz_encode(self))) + } +} + +impl<'de> Deserialize<'de> for FakeAggregateSignature { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let bytes = deserializer.deserialize_str(PrefixedHexVisitor)?; + let (obj, _) = <_>::ssz_decode(&bytes[..], 0) + .map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?; + Ok(obj) + } +} + +impl TreeHash for FakeAggregateSignature { + fn hash_tree_root(&self) -> Vec { + hash(&self.bytes) + } +} + +#[cfg(test)] +mod tests { + use super::super::{Keypair, Signature}; + use super::*; + use ssz::ssz_encode; + + #[test] + pub fn test_ssz_round_trip() { + let keypair = Keypair::random(); + + let mut original = FakeAggregateSignature::new(); + original.add(&Signature::new(&[42, 42], 0, &keypair.sk)); + + let bytes = ssz_encode(&original); + let (decoded, _) = FakeAggregateSignature::ssz_decode(&bytes, 0).unwrap(); + + assert_eq!(original, decoded); + } +} diff --git a/eth2/utils/bls/src/fake_signature.rs b/eth2/utils/bls/src/fake_signature.rs new file mode 100644 index 000000000..81b7310c8 --- /dev/null +++ b/eth2/utils/bls/src/fake_signature.rs @@ -0,0 +1,117 @@ +use super::serde_vistors::HexVisitor; +use super::{PublicKey, SecretKey}; +use hex::encode as hex_encode; +use serde::de::{Deserialize, Deserializer}; +use serde::ser::{Serialize, Serializer}; +use ssz::{ + decode_ssz_list, hash, ssz_encode, Decodable, DecodeError, Encodable, SszStream, TreeHash, +}; + +const SIGNATURE_LENGTH: usize = 48; + +/// A single BLS signature. +/// +/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ +/// serialization). +#[derive(Debug, PartialEq, Clone, Eq)] +pub struct FakeSignature { + bytes: Vec, +} + +impl FakeSignature { + /// Creates a new all-zero's signature + pub fn new(_msg: &[u8], _domain: u64, _sk: &SecretKey) -> Self { + FakeSignature::zero() + } + + /// Creates a new all-zero's signature + pub fn zero() -> Self { + Self { + bytes: vec![0; SIGNATURE_LENGTH], + } + } + + /// Creates a new all-zero's signature + pub fn new_hashed(_x_real_hashed: &[u8], _x_imaginary_hashed: &[u8], _sk: &SecretKey) -> Self { + FakeSignature::zero() + } + + /// _Always_ returns `true`. + pub fn verify(&self, _msg: &[u8], _domain: u64, _pk: &PublicKey) -> bool { + true + } + + /// _Always_ returns true. + pub fn verify_hashed( + &self, + _x_real_hashed: &[u8], + _x_imaginary_hashed: &[u8], + _pk: &PublicKey, + ) -> bool { + true + } + + /// Returns a new empty signature. + pub fn empty_signature() -> Self { + FakeSignature::zero() + } +} + +impl Encodable for FakeSignature { + fn ssz_append(&self, s: &mut SszStream) { + s.append_vec(&self.bytes); + } +} + +impl Decodable for FakeSignature { + fn ssz_decode(bytes: &[u8], i: usize) -> Result<(Self, usize), DecodeError> { + let (sig_bytes, i) = decode_ssz_list(bytes, i)?; + Ok((FakeSignature { bytes: sig_bytes }, i)) + } +} + +impl TreeHash for FakeSignature { + fn hash_tree_root(&self) -> Vec { + hash(&self.bytes) + } +} + +impl Serialize for FakeSignature { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&hex_encode(ssz_encode(self))) + } +} + +impl<'de> Deserialize<'de> for FakeSignature { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let bytes = deserializer.deserialize_str(HexVisitor)?; + let (pubkey, _) = <_>::ssz_decode(&bytes[..], 0) + .map_err(|e| serde::de::Error::custom(format!("invalid ssz ({:?})", e)))?; + Ok(pubkey) + } +} + +#[cfg(test)] +mod tests { + use super::super::Keypair; + use super::*; + use ssz::ssz_encode; + + #[test] + pub fn test_ssz_round_trip() { + let keypair = Keypair::random(); + + let original = FakeSignature::new(&[42, 42], 0, &keypair.sk); + + let bytes = ssz_encode(&original); + let (decoded, _) = FakeSignature::ssz_decode(&bytes, 0).unwrap(); + + assert_eq!(original, decoded); + } +} diff --git a/eth2/utils/bls/src/lib.rs b/eth2/utils/bls/src/lib.rs index 38a129908..32cce5471 100644 --- a/eth2/utils/bls/src/lib.rs +++ b/eth2/utils/bls/src/lib.rs @@ -2,19 +2,33 @@ extern crate bls_aggregates; extern crate ssz; mod aggregate_public_key; -mod aggregate_signature; mod keypair; mod public_key; mod secret_key; mod serde_vistors; + +#[cfg(not(debug_assertions))] +mod aggregate_signature; +#[cfg(not(debug_assertions))] mod signature; +#[cfg(not(debug_assertions))] +pub use crate::aggregate_signature::AggregateSignature; +#[cfg(not(debug_assertions))] +pub use crate::signature::Signature; + +#[cfg(debug_assertions)] +mod fake_aggregate_signature; +#[cfg(debug_assertions)] +mod fake_signature; +#[cfg(debug_assertions)] +pub use crate::fake_aggregate_signature::FakeAggregateSignature as AggregateSignature; +#[cfg(debug_assertions)] +pub use crate::fake_signature::FakeSignature as Signature; pub use crate::aggregate_public_key::AggregatePublicKey; -pub use crate::aggregate_signature::AggregateSignature; pub use crate::keypair::Keypair; pub use crate::public_key::PublicKey; pub use crate::secret_key::SecretKey; -pub use crate::signature::Signature; pub const BLS_AGG_SIG_BYTE_SIZE: usize = 96; From 13872dfbb9e01b24de173bf5e169e0e5543936e6 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Fri, 22 Mar 2019 10:38:45 +1100 Subject: [PATCH 13/97] Added the release and debug build/tests to Jenkins, as well as Travis. --- Jenkinsfile | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 42755d5f7..1a3afad87 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,20 +1,22 @@ pipeline { - agent { + agent { dockerfile { filename 'Dockerfile' args '-v cargo-cache:/cargocache:rw -e "CARGO_HOME=/cargocache"' } } - stages { - stage('Build') { - steps { - sh 'cargo build' - } - } - stage('Test') { + stages { + stage('Build') { steps { - sh 'cargo test --all' + sh 'cargo build --verbose --all' + sh 'cargo build --verbose --all --release' } } - } + stage('Test') { + steps { + sh 'cargo test --verbose --all' + sh 'cargo test --verbose --all --release' + } + } + } } From 4fc6e435d2a0c79c93fd1dc474404da6a3a67ce3 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 22 Mar 2019 11:38:57 +1100 Subject: [PATCH 14/97] Add type alias to test_harness --- .../beacon_chain/test_harness/src/beacon_chain_harness.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs index 4b5d5558f..1207fcf28 100644 --- a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs +++ b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs @@ -15,6 +15,8 @@ use std::iter::FromIterator; use std::sync::Arc; use types::{test_utils::TestingBeaconStateBuilder, *}; +type TestingBeaconChain = BeaconChain>; + /// The beacon chain harness simulates a single beacon node with `validator_count` validators connected /// to it. Each validator is provided a borrow to the beacon chain, where it may read /// information and submit blocks/attestations for processing. @@ -23,7 +25,7 @@ use types::{test_utils::TestingBeaconStateBuilder, *}; /// is not useful for testing that multiple beacon nodes can reach consensus. pub struct BeaconChainHarness { pub db: Arc, - pub beacon_chain: Arc>>, + pub beacon_chain: Arc, pub block_store: Arc>, pub state_store: Arc>, pub validators: Vec, From f96a3282b5072b6f30e16b9e94cccbfe64d7a3a7 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 22 Mar 2019 11:39:16 +1100 Subject: [PATCH 15/97] Pass first sync test --- beacon_node/network/src/sync/simple_sync.rs | 85 ++++++++++----------- beacon_node/network/tests/tests.rs | 62 ++++++++++----- 2 files changed, 81 insertions(+), 66 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 6a40ecf60..0b2f736c1 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,7 +1,5 @@ use crate::beacon_chain::BeaconChain; use crate::message_handler::NetworkContext; -use crate::service::NetworkMessage; -use crossbeam_channel::Sender; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse}; use eth2_libp2p::PeerId; @@ -10,14 +8,13 @@ use std::collections::HashMap; use std::sync::Arc; use types::{Epoch, Hash256, Slot}; -type NetworkSender = Sender; - /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; /// Keeps track of syncing information for known connected peers. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug)] pub struct PeerSyncInfo { + network_id: u8, latest_finalized_root: Hash256, latest_finalized_epoch: Epoch, best_root: Hash256, @@ -25,25 +22,24 @@ pub struct PeerSyncInfo { } impl PeerSyncInfo { - fn is_on_chain(&self, chain: &Arc) -> bool { - // TODO: make useful. - true + fn is_on_same_chain(&self, other: Self) -> bool { + self.network_id == other.network_id } - fn has_higher_finalized_epoch(&self, chain: &Arc) -> bool { - self.latest_finalized_epoch > chain.get_state().finalized_epoch + fn has_higher_finalized_epoch_than(&self, other: Self) -> bool { + self.latest_finalized_epoch > other.latest_finalized_epoch } - fn has_higher_best_slot(&self, chain: &Arc) -> bool { - self.latest_finalized_epoch > chain.get_state().finalized_epoch + fn has_higher_best_slot_than(&self, other: Self) -> bool { + self.best_slot > other.best_slot } - pub fn status(&self, chain: &Arc) -> PeerStatus { - if self.has_higher_finalized_epoch(chain) { + pub fn status_compared_to(&self, other: Self) -> PeerStatus { + if self.has_higher_finalized_epoch_than(other) { PeerStatus::HigherFinalizedEpoch - } else if !self.is_on_chain(chain) { - PeerStatus::HigherFinalizedEpoch - } else if self.has_higher_best_slot(chain) { + } else if !self.is_on_same_chain(other) { + PeerStatus::OnDifferentChain + } else if self.has_higher_best_slot_than(other) { PeerStatus::HigherBestSlot } else { PeerStatus::NotInteresting @@ -62,6 +58,7 @@ pub enum PeerStatus { impl From for PeerSyncInfo { fn from(hello: HelloMessage) -> PeerSyncInfo { PeerSyncInfo { + network_id: hello.network_id, latest_finalized_root: hello.latest_finalized_root, latest_finalized_epoch: hello.latest_finalized_epoch, best_root: hello.best_root, @@ -70,6 +67,12 @@ impl From for PeerSyncInfo { } } +impl From<&Arc> for PeerSyncInfo { + fn from(chain: &Arc) -> PeerSyncInfo { + Self::from(chain.hello_message()) + } +} + /// The current syncing state. #[derive(PartialEq)] pub enum SyncState { @@ -88,12 +91,6 @@ pub struct SimpleSync { known_peers: HashMap, /// The current state of the syncing protocol. state: SyncState, - /// The network id, for quick HELLO RPC message lookup. - network_id: u8, - /// The latest epoch of the syncing chain. - latest_finalized_epoch: Epoch, - /// The latest block of the syncing chain. - latest_slot: Slot, /// Sync logger. log: slog::Logger, } @@ -106,9 +103,6 @@ impl SimpleSync { chain: beacon_chain.clone(), known_peers: HashMap::new(), state: SyncState::Idle, - network_id: beacon_chain.get_spec().network_id, - latest_finalized_epoch: state.finalized_epoch, - latest_slot: state.slot - 1, //TODO: Build latest block function into Beacon chain and correct this log: sync_logger, } } @@ -133,40 +127,39 @@ impl SimpleSync { pub fn on_hello(&mut self, peer_id: PeerId, hello: HelloMessage, network: &mut NetworkContext) { let spec = self.chain.get_spec(); + let remote = PeerSyncInfo::from(hello); + let local = PeerSyncInfo::from(&self.chain); + let remote_status = remote.status_compared_to(local); + // network id must match - if hello.network_id != self.network_id { - debug!(self.log, "Bad network id. Peer: {:?}", peer_id); - network.disconnect(peer_id); - return; + if remote_status != PeerStatus::OnDifferentChain { + debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); + self.known_peers.insert(peer_id.clone(), remote); } - let peer = PeerSyncInfo::from(hello); - debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); - self.known_peers.insert(peer_id.clone(), peer); - - debug!( - self.log, - "Peer hello. Status: {:?}", - peer.status(&self.chain) - ); - - match peer.status(&self.chain) { + match remote_status { PeerStatus::OnDifferentChain => { debug!(self.log, "Peer is on different chain. Peer: {:?}", peer_id); network.disconnect(peer_id); } PeerStatus::HigherFinalizedEpoch => { - let start_slot = peer.latest_finalized_epoch.start_slot(spec.slots_per_epoch); - let required_slots = start_slot - self.chain.slot(); + let start_slot = remote + .latest_finalized_epoch + .start_slot(spec.slots_per_epoch); + let required_slots = start_slot - local.best_slot; self.request_block_roots(peer_id, start_slot, required_slots.as_u64(), network); } PeerStatus::HigherBestSlot => { - let start_slot = peer.best_slot; - let required_slots = start_slot - self.chain.slot(); + let required_slots = remote.best_slot - local.best_slot; - self.request_block_roots(peer_id, start_slot, required_slots.as_u64(), network); + self.request_block_roots( + peer_id, + local.best_slot, + required_slots.as_u64(), + network, + ); } PeerStatus::NotInteresting => {} } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index 7941ffb99..dea57982e 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -1,4 +1,3 @@ -use beacon_chain::test_utils::TestingBeaconChainBuilder; use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender}; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCMethod, RPCRequest, RPCResponse}; @@ -9,7 +8,6 @@ use network::service::{NetworkMessage, OutgoingMessage}; use sloggers::terminal::{Destination, TerminalLoggerBuilder}; use sloggers::types::Severity; use sloggers::Build; -use std::sync::Arc; use std::time::Duration; use test_harness::BeaconChainHarness; use tokio::runtime::TaskExecutor; @@ -19,26 +17,40 @@ pub struct SyncNode { pub id: usize, sender: Sender, receiver: Receiver, + harness: BeaconChainHarness, } impl SyncNode { - pub fn new( + fn from_beacon_state_builder( id: usize, executor: &TaskExecutor, - chain: Arc, + state_builder: TestingBeaconStateBuilder, + spec: &ChainSpec, logger: slog::Logger, ) -> Self { + let harness = BeaconChainHarness::from_beacon_state_builder(state_builder, spec.clone()); + let (network_sender, network_receiver) = unbounded(); - let message_handler_sender = - MessageHandler::spawn(chain, network_sender, executor, logger).unwrap(); + let message_handler_sender = MessageHandler::spawn( + harness.beacon_chain.clone(), + network_sender, + executor, + logger, + ) + .unwrap(); Self { id, sender: message_handler_sender, receiver: network_receiver, + harness, } } + fn increment_beacon_chain_slot(&mut self) { + self.harness.increment_beacon_chain_slot(); + } + fn send(&self, message: HandlerMessage) { self.sender.send(message).unwrap(); } @@ -47,7 +59,11 @@ impl SyncNode { self.receiver.recv_timeout(Duration::from_millis(500)) } - fn recv_rpc_response(&self) -> Result { + fn hello_message(&self) -> HelloMessage { + self.harness.beacon_chain.hello_message() + } + + fn _recv_rpc_response(&self) -> Result { let network_message = self.recv()?; Ok(match network_message { NetworkMessage::Send( @@ -108,12 +124,6 @@ impl SyncMaster { } } - pub fn build_blocks(&mut self, blocks: usize) { - for _ in 0..blocks { - self.harness.advance_chain_with_block(); - } - } - pub fn response_id(&mut self, node: &SyncNode) -> u64 { let id = self.response_ids[node.id]; self.response_ids[node.id] += 1; @@ -169,11 +179,11 @@ fn test_setup( let mut nodes = Vec::with_capacity(node_count); for id in 0..node_count { - let local_chain = TestingBeaconChainBuilder::from(state_builder.clone()).build(&spec); - let node = SyncNode::new( + let node = SyncNode::from_beacon_state_builder( id, &runtime.executor(), - Arc::new(local_chain), + state_builder.clone(), + &spec, logger.clone(), ); @@ -185,6 +195,15 @@ fn test_setup( (runtime, master, nodes) } +pub fn build_blocks(blocks: usize, master: &mut SyncMaster, nodes: &mut Vec) { + for _ in 0..blocks { + master.harness.advance_chain_with_block(); + for i in 0..nodes.len() { + nodes[i].increment_beacon_chain_slot(); + } + } +} + #[test] fn first_test() { let logger = get_logger(); @@ -195,17 +214,20 @@ fn first_test() { let state_builder = TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(validator_count, &spec); - let (runtime, mut master, nodes) = test_setup(state_builder, node_count, &spec, logger.clone()); + let (runtime, mut master, mut nodes) = + test_setup(state_builder, node_count, &spec, logger.clone()); - master.build_blocks(10); + let original_node_slot = nodes[0].hello_message().best_slot; + + build_blocks(2, &mut master, &mut nodes); master.do_hello_with(&nodes[0]); assert_sent_block_root_request( &nodes[0], BeaconBlockRootsRequest { - start_slot: Slot::new(1), - count: 10, + start_slot: original_node_slot, + count: 2, }, ); From e758e717533f22ca73223da2047d7bb547cc9f47 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 12:13:48 +1100 Subject: [PATCH 16/97] Tidy services.proto --- protos/src/services.proto | 180 +++++++++++++++++++++----------------- 1 file changed, 98 insertions(+), 82 deletions(-) diff --git a/protos/src/services.proto b/protos/src/services.proto index 0523cc958..79fffd088 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -12,22 +12,52 @@ syntax = "proto3"; package ethereum.beacon.rpc.v1; + +/// Service that handles block production service BeaconBlockService { rpc ProduceBeaconBlock(ProduceBeaconBlockRequest) returns (ProduceBeaconBlockResponse); rpc PublishBeaconBlock(PublishBeaconBlockRequest) returns (PublishBeaconBlockResponse); } +/// Service that provides the validator client with requisite knowledge about +//its public keys service ValidatorService { - // rpc ValidatorAssignment(ValidatorAssignmentRequest) returns (ValidatorAssignmentResponse); rpc ProposeBlockSlot(ProposeBlockSlotRequest) returns (ProposeBlockSlotResponse); rpc ValidatorIndex(PublicKey) returns (IndexResponse); + // rpc ValidatorAssignment(ValidatorAssignmentRequest) returns (ValidatorAssignmentResponse); } +/// Service that handles validator attestations service AttestationService { rpc ProduceAttestationData (ProduceAttestationDataRequest) returns (ProduceAttestationDataResponse); rpc PublishAttestationData (PublishAttestationDataRequest) returns (PublishAttestationDataResponse); } +/* + * Block Production Service Messages + */ + +// Validator requests an unsigned proposal. +message ProduceBeaconBlockRequest { + uint64 slot = 1; +} + +// Beacon node returns an unsigned proposal. +message ProduceBeaconBlockResponse { + BeaconBlock block = 1; +} + +// Validator submits a signed proposal. +message PublishBeaconBlockRequest { + BeaconBlock block = 1; +} + +// Beacon node indicates a sucessfully submitted proposal. +message PublishBeaconBlockResponse { + bool success = 1; + bytes msg = 2; +} + message BeaconBlock { uint64 slot = 1; bytes block_root = 2; @@ -35,6 +65,73 @@ message BeaconBlock { bytes signature = 4; } +/* + * Validator Service Messages + */ +/* +message ValidatorAssignmentRequest { + uint64 epoch = 1; + bytes validator_index = 2; +} + +// A validators duties for some epoch. +// TODO: add shard duties. +message ValidatorAssignment { + oneof block_production_slot_oneof { + bool block_production_slot_none = 1; + uint64 block_production_slot = 2; + } +} +*/ + +// Validator Assignment + +message PublicKey { + bytes public_key = 1; +} + +message IndexResponse { + uint64 index = 1; +} + + +// Propose slot + +message ProposeBlockSlotRequest { + uint64 epoch = 1; + uint64 validator_index = 2; +} + +message ProposeBlockSlotResponse { + oneof slot_oneof { + bool none = 1; + uint64 slot = 2; + } +} + + +/* + * Attestation Service Messages + */ + +message ProduceAttestationDataRequest { + uint64 slot = 1; + uint64 shard = 2; +} + +message ProduceAttestationDataResponse { + AttestationData attestation_data = 1; +} + +message PublishAttestationDataRequest { + FreeAttestation free_attestation = 1; +} + +message PublishAttestationDataResponse { + bool success = 1; + bytes msg = 2; +} + message Crosslink { uint64 epoch = 1; bytes crosslink_data_root = 2; @@ -58,84 +155,3 @@ message FreeAttestation { bytes signature = 2; uint64 validator_index = 3; } - -// Validator requests an unsigned proposal. -message ProduceBeaconBlockRequest { - uint64 slot = 1; -} - -// Beacon node returns an unsigned proposal. -message ProduceBeaconBlockResponse { - BeaconBlock block = 1; -} - -// Validator submits a signed proposal. -message PublishBeaconBlockRequest { - BeaconBlock block = 1; -} - -// Beacon node indicates a sucessfully submitted proposal. -message PublishBeaconBlockResponse { - bool success = 1; - bytes msg = 2; -} - -message ProduceAttestationDataRequest { - uint64 slot = 1; - uint64 shard = 2; -} - -message ProduceAttestationDataResponse { - AttestationData attestation_data = 1; -} - -message PublishAttestationDataRequest { - FreeAttestation free_attestation = 1; -} - -message PublishAttestationDataResponse { - bool success = 1; - bytes msg = 2; -} - -// A validators duties for some epoch. -// TODO: add shard duties. -message ValidatorAssignment { - oneof block_production_slot_oneof { - bool block_production_slot_none = 1; - uint64 block_production_slot = 2; - } -} - -message ValidatorAssignmentRequest { - uint64 epoch = 1; - bytes validator_index = 2; -} - -/* - * Propose slot - */ - -message ProposeBlockSlotRequest { - uint64 epoch = 1; - uint64 validator_index = 2; -} - -message ProposeBlockSlotResponse { - oneof slot_oneof { - bool none = 1; - uint64 slot = 2; - } -} - -/* - * Validator Assignment - */ - -message PublicKey { - bytes public_key = 1; -} - -message IndexResponse { - uint64 index = 1; -} From 0a59a73894b2c3294da08f7a8cc35150f5e24165 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 12:36:45 +1100 Subject: [PATCH 17/97] Add BeaconNodeService to RPC --- protos/src/services.proto | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/protos/src/services.proto b/protos/src/services.proto index 79fffd088..45fcfb120 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -12,6 +12,10 @@ syntax = "proto3"; package ethereum.beacon.rpc.v1; +// Service that currently identifies a beacon node +service BeaconNodeService { + rpc Info(Empty) returns (NodeInfo); +} /// Service that handles block production service BeaconBlockService { @@ -33,6 +37,26 @@ service AttestationService { rpc PublishAttestationData (PublishAttestationDataRequest) returns (PublishAttestationDataResponse); } +/* + * Beacon Node Service Message + */ +message NodeInfo { + string version = 1; + Fork fork = 2; + uint32 chain_id = 3; +} + +message Fork { + bytes previous_version = 1; + bytes current_version = 2; + uint64 epoch = 3; +} + +message Empty { +} + + + /* * Block Production Service Messages */ From 844fdc0fb9122c6ddd21acb849d78421e3560c8e Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 12:39:45 +1100 Subject: [PATCH 18/97] Rename network_id to chain_id --- beacon_node/network/src/sync/simple_sync.rs | 8 ++++---- eth2/types/src/chain_spec.rs | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 0f7de6ab9..d3d0e1475 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -36,7 +36,7 @@ pub struct SimpleSync { /// The current state of the syncing protocol. state: SyncState, /// The network id, for quick HELLO RPC message lookup. - network_id: u8, + chain_id: u8, /// The latest epoch of the syncing chain. latest_finalized_epoch: Epoch, /// The latest block of the syncing chain. @@ -53,7 +53,7 @@ impl SimpleSync { chain: beacon_chain.clone(), known_peers: HashMap::new(), state: SyncState::Idle, - network_id: beacon_chain.get_spec().network_id, + chain_id: beacon_chain.get_spec().chain_id, latest_finalized_epoch: state.finalized_epoch, latest_slot: state.slot - 1, //TODO: Build latest block function into Beacon chain and correct this log: sync_logger, @@ -65,7 +65,7 @@ impl SimpleSync { let state = &self.chain.get_state(); //TODO: Paul to verify the logic of these fields. HelloMessage { - network_id: self.network_id, + network_id: self.chain_id, latest_finalized_root: state.finalized_root, latest_finalized_epoch: state.finalized_epoch, best_root: Hash256::zero(), //TODO: build correct value as a beacon chain function @@ -75,7 +75,7 @@ impl SimpleSync { pub fn validate_peer(&mut self, peer_id: PeerId, hello_message: HelloMessage) -> bool { // network id must match - if hello_message.network_id != self.network_id { + if hello_message.network_id != self.chain_id { return false; } // compare latest epoch and finalized root to see if they exist in our chain diff --git a/eth2/types/src/chain_spec.rs b/eth2/types/src/chain_spec.rs index 65ea5c4d4..5fa28b6ac 100644 --- a/eth2/types/src/chain_spec.rs +++ b/eth2/types/src/chain_spec.rs @@ -118,7 +118,7 @@ pub struct ChainSpec { * */ pub boot_nodes: Vec, - pub network_id: u8, + pub chain_id: u8, } impl ChainSpec { @@ -255,7 +255,7 @@ impl ChainSpec { * Boot nodes */ boot_nodes: vec![], - network_id: 1, // foundation network id + chain_id: 1, // foundation chain id } } @@ -272,7 +272,7 @@ impl ChainSpec { Self { boot_nodes, - network_id: 2, // lighthouse testnet network id + chain_id: 2, // lighthouse testnet chain id ..ChainSpec::few_validators() } } From ee6a0ccb92bca9a49b023533155e8b837ab8bfe0 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 13:37:24 +1100 Subject: [PATCH 19/97] Initial build of server-side BeaconNodeService RPC --- beacon_node/client/src/lib.rs | 2 +- beacon_node/rpc/Cargo.toml | 8 ++--- beacon_node/rpc/src/beacon_node.rs | 50 ++++++++++++++++++++++++++++++ beacon_node/rpc/src/lib.rs | 28 +++++++++++++++-- 4 files changed, 81 insertions(+), 7 deletions(-) create mode 100644 beacon_node/rpc/src/beacon_node.rs diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index 914e47fcf..d8da18cae 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -61,7 +61,7 @@ impl Client { // spawn the RPC server if config.rpc_conf.enabled { - rpc::start_server(&config.rpc_conf, &log); + rpc::start_server(&config.rpc_conf, beacon_chain.clone(), &log); } Ok(Client { diff --git a/beacon_node/rpc/Cargo.toml b/beacon_node/rpc/Cargo.toml index 4c3333ee1..acb68972c 100644 --- a/beacon_node/rpc/Cargo.toml +++ b/beacon_node/rpc/Cargo.toml @@ -7,7 +7,10 @@ edition = "2018" [dependencies] bls = { path = "../../eth2/utils/bls" } beacon_chain = { path = "../beacon_chain" } - +version = { path = "../version" } +types = { path = "../../eth2/types" } +ssz = { path = "../../eth2/utils/ssz" } +slot_clock = { path = "../../eth2/utils/slot_clock" } protos = { path = "../../protos" } grpcio = { version = "0.4", default-features = false, features = ["protobuf-codec"] } protobuf = "2.0.2" @@ -16,8 +19,5 @@ db = { path = "../db" } dirs = "1.0.3" futures = "0.1.23" slog = "^2.2.3" -slot_clock = { path = "../../eth2/utils/slot_clock" } slog-term = "^2.4.0" slog-async = "^2.3.0" -types = { path = "../../eth2/types" } -ssz = { path = "../../eth2/utils/ssz" } diff --git a/beacon_node/rpc/src/beacon_node.rs b/beacon_node/rpc/src/beacon_node.rs new file mode 100644 index 000000000..8dd7721fd --- /dev/null +++ b/beacon_node/rpc/src/beacon_node.rs @@ -0,0 +1,50 @@ +use beacon_chain::{db::ClientDB, fork_choice::ForkChoice, slot_clock::SlotClock, BeaconChain}; +use futures::Future; +use grpcio::{RpcContext, UnarySink}; +use protos::services::{Empty, Fork, NodeInfo}; +use protos::services_grpc::BeaconNodeService; +use slog::{debug, trace, warn}; +use std::sync::Arc; + +#[derive(Clone)] +pub struct BeaconNodeServiceInstance +where + T: ClientDB + Clone, + U: SlotClock + Clone, + F: ForkChoice + Clone, +{ + pub chain: Arc>, + pub log: slog::Logger, +} + +impl BeaconNodeService for BeaconNodeServiceInstance +where + T: ClientDB + Clone, + U: SlotClock + Clone, + F: ForkChoice + Clone, +{ + /// Provides basic node information. + fn info(&mut self, ctx: RpcContext, _req: Empty, sink: UnarySink) { + trace!(self.log, "Node info requested via RPC"); + + let mut node_info = NodeInfo::new(); + node_info.set_version(version::version()); + // get the chain state fork + let state_fork = self.chain.state.read().fork.clone(); + // build the rpc fork struct + let mut fork = Fork::new(); + fork.set_previous_version(state_fork.previous_version.to_vec()); + fork.set_current_version(state_fork.current_version.to_vec()); + fork.set_epoch(state_fork.epoch.into()); + node_info.set_fork(fork); + + node_info.set_chain_id(self.chain.spec.chain_id as u32); + + // send the node_info the requester + let error_log = self.log.clone(); + let f = sink + .success(node_info) + .map_err(move |e| warn!(error_log, "failed to reply {:?}", e)); + ctx.spawn(f) + } +} diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 7f776d7d8..2f2abcc1f 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -1,20 +1,44 @@ mod beacon_block; +mod beacon_node; pub mod config; mod validator; use self::beacon_block::BeaconBlockServiceInstance; +use self::beacon_node::BeaconNodeServiceInstance; use self::validator::ValidatorServiceInstance; +use beacon_chain::{db::ClientDB, fork_choice::ForkChoice, slot_clock::SlotClock, BeaconChain}; pub use config::Config as RPCConfig; use grpcio::{Environment, Server, ServerBuilder}; -use protos::services_grpc::{create_beacon_block_service, create_validator_service}; +use protos::services_grpc::{ + create_beacon_block_service, create_beacon_node_service, create_validator_service, +}; use std::sync::Arc; use slog::{info, o}; -pub fn start_server(config: &RPCConfig, log: &slog::Logger) -> Server { +pub fn start_server( + config: &RPCConfig, + beacon_chain: Arc>, + log: &slog::Logger, +) -> Server +where + T: ClientDB + Clone + 'static, + U: SlotClock + Clone + 'static, + F: ForkChoice + Clone + 'static, +{ let log = log.new(o!("Service"=>"RPC")); let env = Arc::new(Environment::new(1)); + // build the individual rpc services + + let beacon_node_service = { + let instance = BeaconNodeServiceInstance { + chain: beacon_chain.clone(), + log: log.clone(), + }; + create_beacon_node_service(instance) + }; + let beacon_block_service = { let instance = BeaconBlockServiceInstance { log: log.clone() }; create_beacon_block_service(instance) From 858cf4f1f42b4c56a6fbdf71c44fbb06e2e5097a Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 13:51:17 +1100 Subject: [PATCH 20/97] Add beacon_chain trait for gRPC server --- beacon_node/rpc/src/beacon_chain.rs | 31 +++++++++++++++++++++++++++++ beacon_node/rpc/src/beacon_node.rs | 22 ++++++-------------- beacon_node/rpc/src/lib.rs | 14 +++++-------- 3 files changed, 42 insertions(+), 25 deletions(-) create mode 100644 beacon_node/rpc/src/beacon_chain.rs diff --git a/beacon_node/rpc/src/beacon_chain.rs b/beacon_node/rpc/src/beacon_chain.rs new file mode 100644 index 000000000..9b2681876 --- /dev/null +++ b/beacon_node/rpc/src/beacon_chain.rs @@ -0,0 +1,31 @@ +use beacon_chain::BeaconChain as RawBeaconChain; +use beacon_chain::{ + db::ClientDB, + fork_choice::ForkChoice, + parking_lot::RwLockReadGuard, + slot_clock::SlotClock, + types::{BeaconState, ChainSpec}, + CheckPoint, +}; + +/// The RPC's API to the beacon chain. +pub trait BeaconChain: Send + Sync { + fn get_spec(&self) -> &ChainSpec; + + fn get_state(&self) -> RwLockReadGuard; +} + +impl BeaconChain for RawBeaconChain +where + T: ClientDB + Sized, + U: SlotClock, + F: ForkChoice, +{ + fn get_spec(&self) -> &ChainSpec { + &self.spec + } + + fn get_state(&self) -> RwLockReadGuard { + self.state.read() + } +} diff --git a/beacon_node/rpc/src/beacon_node.rs b/beacon_node/rpc/src/beacon_node.rs index 8dd7721fd..5a542cb90 100644 --- a/beacon_node/rpc/src/beacon_node.rs +++ b/beacon_node/rpc/src/beacon_node.rs @@ -1,4 +1,4 @@ -use beacon_chain::{db::ClientDB, fork_choice::ForkChoice, slot_clock::SlotClock, BeaconChain}; +use crate::beacon_chain::BeaconChain; use futures::Future; use grpcio::{RpcContext, UnarySink}; use protos::services::{Empty, Fork, NodeInfo}; @@ -7,22 +7,12 @@ use slog::{debug, trace, warn}; use std::sync::Arc; #[derive(Clone)] -pub struct BeaconNodeServiceInstance -where - T: ClientDB + Clone, - U: SlotClock + Clone, - F: ForkChoice + Clone, -{ - pub chain: Arc>, +pub struct BeaconNodeServiceInstance { + pub chain: Arc, pub log: slog::Logger, } -impl BeaconNodeService for BeaconNodeServiceInstance -where - T: ClientDB + Clone, - U: SlotClock + Clone, - F: ForkChoice + Clone, -{ +impl BeaconNodeService for BeaconNodeServiceInstance { /// Provides basic node information. fn info(&mut self, ctx: RpcContext, _req: Empty, sink: UnarySink) { trace!(self.log, "Node info requested via RPC"); @@ -30,7 +20,7 @@ where let mut node_info = NodeInfo::new(); node_info.set_version(version::version()); // get the chain state fork - let state_fork = self.chain.state.read().fork.clone(); + let state_fork = self.chain.get_state().fork.clone(); // build the rpc fork struct let mut fork = Fork::new(); fork.set_previous_version(state_fork.previous_version.to_vec()); @@ -38,7 +28,7 @@ where fork.set_epoch(state_fork.epoch.into()); node_info.set_fork(fork); - node_info.set_chain_id(self.chain.spec.chain_id as u32); + node_info.set_chain_id(self.chain.get_spec().chain_id as u32); // send the node_info the requester let error_log = self.log.clone(); diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 2f2abcc1f..4565abf7a 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -1,12 +1,13 @@ mod beacon_block; +pub mod beacon_chain; mod beacon_node; pub mod config; mod validator; use self::beacon_block::BeaconBlockServiceInstance; +use self::beacon_chain::BeaconChain; use self::beacon_node::BeaconNodeServiceInstance; use self::validator::ValidatorServiceInstance; -use beacon_chain::{db::ClientDB, fork_choice::ForkChoice, slot_clock::SlotClock, BeaconChain}; pub use config::Config as RPCConfig; use grpcio::{Environment, Server, ServerBuilder}; use protos::services_grpc::{ @@ -16,16 +17,11 @@ use std::sync::Arc; use slog::{info, o}; -pub fn start_server( +pub fn start_server( config: &RPCConfig, - beacon_chain: Arc>, + beacon_chain: Arc, log: &slog::Logger, -) -> Server -where - T: ClientDB + Clone + 'static, - U: SlotClock + Clone + 'static, - F: ForkChoice + Clone + 'static, -{ +) -> Server { let log = log.new(o!("Service"=>"RPC")); let env = Arc::new(Environment::new(1)); From 96ba1c8f77064a24c3a8ab1b03954d80d333c21b Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Fri, 22 Mar 2019 14:20:49 +1100 Subject: [PATCH 21/97] Implement `get_block_roots` for syncing --- beacon_node/beacon_chain/src/beacon_chain.rs | 64 ++++++++++++++++++++ beacon_node/network/src/beacon_chain.rs | 16 ++++- beacon_node/network/src/message_handler.rs | 13 +++- beacon_node/network/src/sync/simple_sync.rs | 12 ++++ beacon_node/network/tests/tests.rs | 61 +++++++++++++------ 5 files changed, 146 insertions(+), 20 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 4b151d70b..dccd9842e 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -122,6 +122,70 @@ where }) } + /// Returns beacon block roots for `count` slots, starting from `start_slot`. + /// + /// ## Errors: + /// + /// - `SlotOutOfBounds`: Unable to return the full specified range. + /// - `SlotOutOfBounds`: Unable to load a state from the DB. + /// - `SlotOutOfBounds`: Start slot is higher than the first slot. + /// - Other: BeaconState` is inconsistent. + pub fn get_block_roots( + &self, + start_slot: Slot, + count: Slot, + ) -> Result, BeaconStateError> { + let spec = &self.spec; + + let mut roots: Vec = vec![]; + let mut state = self.state.read().clone(); + let mut slot = start_slot + count - 1; + + loop { + // Return if the slot required is greater than the current state. + if slot >= state.slot { + return Err(BeaconStateError::SlotOutOfBounds); + } + + // If the slot is within the range of the current state's block roots, append the root + // to the output vec. + // + // If we get `SlotOutOfBounds` error, load the oldest known state to the present state + // from the DB. + match state.get_block_root(slot, spec) { + Ok(root) => { + roots.push(*root); + + if slot == start_slot { + break; + } else { + slot -= 1; + } + } + Err(BeaconStateError::SlotOutOfBounds) => { + // Read the earliest historic state in the current slot. + let earliest_historic_slot = + state.slot - Slot::from(spec.slots_per_historical_root); + // Load the earlier state from disk. + let new_state_root = state.get_state_root(earliest_historic_slot, spec)?; + + // Break if the DB is unable to load the state. + state = match self.state_store.get_deserialized(&new_state_root) { + Ok(Some(state)) => state, + _ => break, + } + } + Err(e) => return Err(e), + }; + } + + if (slot == start_slot) && (roots.len() == count.as_usize()) { + Ok(roots) + } else { + Err(BeaconStateError::SlotOutOfBounds) + } + } + /// Update the canonical head to some new values. pub fn update_canonical_head( &self, diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index 5246c87c2..ba429e688 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -8,7 +8,7 @@ use beacon_chain::{ CheckPoint, }; use eth2_libp2p::HelloMessage; -use types::{Epoch, Hash256, Slot}; +use types::{BeaconStateError, Epoch, Hash256, Slot}; /// The network's API to the beacon chain. pub trait BeaconChain: Send + Sync { @@ -29,6 +29,12 @@ pub trait BeaconChain: Send + Sync { fn finalized_epoch(&self) -> Epoch; fn hello_message(&self) -> HelloMessage; + + fn get_block_roots( + &self, + start_slot: Slot, + count: Slot, + ) -> Result, BeaconStateError>; } impl BeaconChain for RawBeaconChain @@ -81,4 +87,12 @@ where best_slot: self.best_slot(), } } + + fn get_block_roots( + &self, + start_slot: Slot, + count: Slot, + ) -> Result, BeaconStateError> { + self.get_block_roots(start_slot, count) + } } diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 5b39de997..99a263ed8 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -139,8 +139,19 @@ impl MessageHandler { self.sync .on_hello(peer_id, hello_message, &mut self.network_context); } + RPCResponse::BeaconBlockRoots(response) => { + debug!( + self.log, + "BeaconBlockRoots response received from peer: {:?}", peer_id + ); + self.sync.on_beacon_block_roots_response( + peer_id, + response, + &mut self.network_context, + ) + } // TODO: Handle all responses - _ => {} + _ => panic!("Unknown response: {:?}", response), } } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 0b2f736c1..ab29d0db5 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -165,6 +165,15 @@ impl SimpleSync { } } + pub fn on_beacon_block_roots_response( + &mut self, + peer_id: PeerId, + reponse: BeaconBlockRootsResponse, + network: &mut NetworkContext, + ) { + // + } + fn request_block_roots( &mut self, peer_id: PeerId, @@ -174,9 +183,12 @@ impl SimpleSync { ) { // Potentially set state to sync. if self.state == SyncState::Idle && count > SLOT_IMPORT_TOLERANCE { + debug!(self.log, "Entering downloading sync state."); self.state = SyncState::Downloading; } + debug!(self.log, "Requesting {} blocks from {:?}.", count, &peer_id); + // TODO: handle count > max count. network.send_rpc_request( peer_id.clone(), diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index dea57982e..fbfb827f2 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -63,6 +63,15 @@ impl SyncNode { self.harness.beacon_chain.hello_message() } + pub fn get_block_root_request(&self) -> BeaconBlockRootsRequest { + let request = self.recv_rpc_request().expect("No block root request"); + + match request { + RPCRequest::BeaconBlockRoots(response) => response, + _ => panic!("Did not get block root request"), + } + } + fn _recv_rpc_response(&self) -> Result { let network_message = self.recv()?; Ok(match network_message { @@ -146,6 +155,34 @@ impl SyncMaster { } } + pub fn respond_to_block_roots_request( + &mut self, + node: &SyncNode, + request: BeaconBlockRootsRequest, + ) { + let roots = self + .harness + .beacon_chain + .get_block_roots(request.start_slot, Slot::from(request.count)) + .expect("Beacon chain did not give blocks"); + + let roots = roots + .iter() + .enumerate() + .map(|(i, root)| BlockRootSlot { + block_root: *root, + slot: Slot::from(i) + request.start_slot, + }) + .collect(); + + let response = RPCResponse::BeaconBlockRoots(BeaconBlockRootsResponse { roots }); + self.send_rpc_response(node, response) + } + + fn send_rpc_response(&mut self, node: &SyncNode, rpc_response: RPCResponse) { + node.send(self.rpc_response(node, rpc_response)); + } + fn rpc_response(&mut self, node: &SyncNode, rpc_response: RPCResponse) -> HandlerMessage { HandlerMessage::RPC( self.peer_id.clone(), @@ -158,17 +195,6 @@ impl SyncMaster { } } -fn assert_sent_block_root_request(node: &SyncNode, expected: BeaconBlockRootsRequest) { - let request = node.recv_rpc_request().expect("No block root request"); - - match request { - RPCRequest::BeaconBlockRoots(response) => { - assert_eq!(expected, response, "Bad block roots response"); - } - _ => assert!(false, "Did not get block root request"), - } -} - fn test_setup( state_builder: TestingBeaconStateBuilder, node_count: usize, @@ -223,13 +249,12 @@ fn first_test() { master.do_hello_with(&nodes[0]); - assert_sent_block_root_request( - &nodes[0], - BeaconBlockRootsRequest { - start_slot: original_node_slot, - count: 2, - }, - ); + let request = nodes[0].get_block_root_request(); + assert_eq!(request.start_slot, original_node_slot); + assert_eq!(request.count, 2); + master.respond_to_block_roots_request(&nodes[0], request); + + std::thread::sleep(Duration::from_millis(500)); runtime.shutdown_now(); } From a4cfe682726a035b8f4dce4d395074f98205e8f6 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 16:46:52 +1100 Subject: [PATCH 22/97] Thread beacon node RPC server --- beacon_node/client/src/lib.rs | 23 +++++++++++----------- beacon_node/rpc/Cargo.toml | 2 ++ beacon_node/rpc/src/lib.rs | 35 +++++++++++++++++++++++++--------- validator_client/src/config.rs | 2 +- 4 files changed, 41 insertions(+), 21 deletions(-) diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index d8da18cae..a033da87b 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -24,12 +24,8 @@ pub struct Client { beacon_chain: Arc>, /// Reference to the network service. pub network: Arc, - /// Future to stop and begin shutdown of the Client. - //TODO: Decide best way to handle shutdown - pub exit: exit_future::Exit, - /// The sending future to call to terminate the Client. - //TODO: Decide best way to handle shutdown - pub exit_signal: Signal, + /// Signal to terminate the RPC server. + pub rpc_exit_signal: Option, /// The clients logger. log: slog::Logger, /// Marker to pin the beacon chain generics. @@ -43,8 +39,6 @@ impl Client { log: slog::Logger, executor: &TaskExecutor, ) -> error::Result { - let (exit_signal, exit) = exit_future::signal(); - // generate a beacon chain let beacon_chain = TClientType::initialise_beacon_chain(&config); @@ -59,16 +53,23 @@ impl Client { network_logger, )?; + let mut rpc_exit_signal = None; // spawn the RPC server if config.rpc_conf.enabled { - rpc::start_server(&config.rpc_conf, beacon_chain.clone(), &log); + rpc_exit_signal = Some(rpc::start_server( + &config.rpc_conf, + executor, + beacon_chain.clone(), + &log, + )); } + println!("Here"); + Ok(Client { config, beacon_chain, - exit, - exit_signal, + rpc_exit_signal, log, network, phantom: PhantomData, diff --git a/beacon_node/rpc/Cargo.toml b/beacon_node/rpc/Cargo.toml index acb68972c..d405982db 100644 --- a/beacon_node/rpc/Cargo.toml +++ b/beacon_node/rpc/Cargo.toml @@ -21,3 +21,5 @@ futures = "0.1.23" slog = "^2.2.3" slog-term = "^2.4.0" slog-async = "^2.3.0" +tokio = "0.1.17" +exit-future = "0.1.4" diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 4565abf7a..02e34781c 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -9,24 +9,28 @@ use self::beacon_chain::BeaconChain; use self::beacon_node::BeaconNodeServiceInstance; use self::validator::ValidatorServiceInstance; pub use config::Config as RPCConfig; +use futures::{future, Future}; use grpcio::{Environment, Server, ServerBuilder}; use protos::services_grpc::{ create_beacon_block_service, create_beacon_node_service, create_validator_service, }; +use slog::{info, o, warn}; use std::sync::Arc; - -use slog::{info, o}; +use tokio::runtime::TaskExecutor; pub fn start_server( config: &RPCConfig, + executor: &TaskExecutor, beacon_chain: Arc, log: &slog::Logger, -) -> Server { +) -> exit_future::Signal { let log = log.new(o!("Service"=>"RPC")); let env = Arc::new(Environment::new(1)); - // build the individual rpc services + // build a channel to kill the rpc server + let (rpc_exit_signal, rpc_exit) = exit_future::signal(); + // build the individual rpc services let beacon_node_service = { let instance = BeaconNodeServiceInstance { chain: beacon_chain.clone(), @@ -50,9 +54,22 @@ pub fn start_server( .bind(config.listen_address.to_string(), config.port) .build() .unwrap(); - server.start(); - for &(ref host, port) in server.bind_addrs() { - info!(log, "gRPC listening on {}:{}", host, port); - } - server + + let spawn_rpc = { + server.start(); + for &(ref host, port) in server.bind_addrs() { + info!(log, "gRPC listening on {}:{}", host, port); + } + rpc_exit.and_then(move |_| { + info!(log, "RPC Server shutting down"); + server + .shutdown() + .wait() + .map(|_| ()) + .map_err(|e| warn!(log, "RPC server failed to shutdown: {:?}", e))?; + Ok(()) + }) + }; + executor.spawn(spawn_rpc); + rpc_exit_signal } diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 68405ed2f..49e0a506f 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -21,7 +21,7 @@ impl ClientConfig { }; fs::create_dir_all(&data_dir) .unwrap_or_else(|_| panic!("Unable to create {:?}", &data_dir)); - let server = "localhost:50051".to_string(); + let server = "localhost:5051".to_string(); let spec = ChainSpec::foundation(); Self { data_dir, From 4990569f68f8940cf0cff907716094e18999839b Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 16:48:25 +1100 Subject: [PATCH 23/97] Add BeaconNodeInfo RPC to validator client --- validator_client/src/main.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 4664d5dc9..b4da737c8 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,15 +1,17 @@ -use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; -use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; use crate::attester_service::{AttestationGrpcClient, AttesterService}; +use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use crate::config::ClientConfig; +use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; use attester::test_utils::EpochMap; use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; use bls::Keypair; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; +use protos::services::{Empty, NodeInfo}; use protos::services_grpc::{ - AttestationServiceClient, BeaconBlockServiceClient, ValidatorServiceClient, + AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, + ValidatorServiceClient, }; use slog::{error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; @@ -94,6 +96,13 @@ fn main() { "data_dir" => &config.data_dir.to_str(), "server" => &config.server); + // Beacon node gRPC beacon node endpoints. + let beacon_node_grpc_client = { + let env = Arc::new(EnvBuilder::new().build()); + let ch = ChannelBuilder::new(env).connect(&config.server); + Arc::new(BeaconNodeServiceClient::new(ch)) + }; + // Beacon node gRPC beacon block endpoints. let beacon_block_grpc_client = { let env = Arc::new(EnvBuilder::new().build()); @@ -115,12 +124,14 @@ fn main() { Arc::new(AttestationServiceClient::new(ch)) }; + // retrieve node information + let node_info = beacon_node_grpc_client.info(&Empty::new()); + + info!(log, "Beacon node info: {:?}", node_info); + // Spec let spec = Arc::new(config.spec.clone()); - // Clock for determining the present slot. - // TODO: this shouldn't be a static time, instead it should be pulled from the beacon node. - // https://github.com/sigp/lighthouse/issues/160 let genesis_time = 1_549_935_547; let slot_clock = { info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); From a1a5f29caae53c76d9e17b6e333f4d57ba598a38 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 16:56:54 +1100 Subject: [PATCH 24/97] Fix registering of node service --- beacon_node/rpc/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 02e34781c..3c89bda1f 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -51,6 +51,7 @@ pub fn start_server( let mut server = ServerBuilder::new(env) .register_service(beacon_block_service) .register_service(validator_service) + .register_service(beacon_node_service) .bind(config.listen_address.to_string(), config.port) .build() .unwrap(); From b2cd771a4203b07c3c19a3c914ed1016bab3edb6 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 17:04:55 +1100 Subject: [PATCH 25/97] Shift argument passing into config module --- validator_client/src/config.rs | 37 ++++++++++++++++++++++++++++++++++ validator_client/src/main.rs | 37 ++-------------------------------- 2 files changed, 39 insertions(+), 35 deletions(-) diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 49e0a506f..60edc564a 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,3 +1,5 @@ +use clap::ArgMatches; +use slog::{error, info}; use std::fs; use std::path::PathBuf; use types::ChainSpec; @@ -29,4 +31,39 @@ impl ClientConfig { spec, } } + + pub fn parse_args(matches: ArgMatches, log: &slog::Logger) -> Result { + let mut config = ClientConfig::default(); + // Custom datadir + if let Some(dir) = matches.value_of("datadir") { + config.data_dir = PathBuf::from(dir.to_string()); + } + + // Custom server port + if let Some(server_str) = matches.value_of("server") { + if let Ok(addr) = server_str.parse::() { + config.server = addr.to_string(); + } else { + error!(log, "Invalid address"; "server" => server_str); + return Err("Invalid address"); + } + } + + // TODO: Permit loading a custom spec from file. + // Custom spec + if let Some(spec_str) = matches.value_of("spec") { + match spec_str { + "foundation" => config.spec = ChainSpec::foundation(), + "few_validators" => config.spec = ChainSpec::few_validators(), + // Should be impossible due to clap's `possible_values(..)` function. + _ => unreachable!(), + }; + } + + // Log configuration + info!(log, ""; + "data_dir" => &config.data_dir.to_str(), + "server" => &config.server); + Ok(config) + } } diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index b4da737c8..c6cf586f3 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -13,12 +13,10 @@ use protos::services_grpc::{ AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, ValidatorServiceClient, }; -use slog::{error, info, o, Drain}; +use slog::{info, o, Drain}; use slot_clock::SystemTimeSlotClock; -use std::path::PathBuf; use std::sync::Arc; use std::thread; -use types::ChainSpec; mod attester_service; mod block_producer_service; @@ -63,38 +61,7 @@ fn main() { ) .get_matches(); - let mut config = ClientConfig::default(); - - // Custom datadir - if let Some(dir) = matches.value_of("datadir") { - config.data_dir = PathBuf::from(dir.to_string()); - } - - // Custom server port - if let Some(server_str) = matches.value_of("server") { - if let Ok(addr) = server_str.parse::() { - config.server = addr.to_string(); - } else { - error!(log, "Invalid address"; "server" => server_str); - return; - } - } - - // TODO: Permit loading a custom spec from file. - // Custom spec - if let Some(spec_str) = matches.value_of("spec") { - match spec_str { - "foundation" => config.spec = ChainSpec::foundation(), - "few_validators" => config.spec = ChainSpec::few_validators(), - // Should be impossible due to clap's `possible_values(..)` function. - _ => unreachable!(), - }; - } - - // Log configuration - info!(log, ""; - "data_dir" => &config.data_dir.to_str(), - "server" => &config.server); + let config = ClientConfig::parse_args(matches, &log).unwrap(); // Beacon node gRPC beacon node endpoints. let beacon_node_grpc_client = { From c4454289d649e2be37b5e17931d706fe6aecfed2 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 17:27:07 +1100 Subject: [PATCH 26/97] Initial implementation of validator service --- validator_client/Cargo.toml | 2 +- validator_client/src/config.rs | 6 +- validator_client/src/main.rs | 166 ++------------------------------ validator_client/src/service.rs | 166 ++++++++++++++++++++++++++++++++ 4 files changed, 179 insertions(+), 161 deletions(-) create mode 100644 validator_client/src/service.rs diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index cdde71774..4bd63715c 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "validator_client" version = "0.1.0" -authors = ["Paul Hauner "] +authors = ["Paul Hauner ", "Age Manning "] edition = "2018" [dependencies] diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 60edc564a..0bf320b4f 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -6,7 +6,7 @@ use types::ChainSpec; /// Stores the core configuration for this validator instance. #[derive(Clone)] -pub struct ClientConfig { +pub struct Config { pub data_dir: PathBuf, pub server: String, pub spec: ChainSpec, @@ -14,7 +14,7 @@ pub struct ClientConfig { const DEFAULT_LIGHTHOUSE_DIR: &str = ".lighthouse-validators"; -impl ClientConfig { +impl Config { /// Build a new configuration from defaults. pub fn default() -> Self { let data_dir = { @@ -33,7 +33,7 @@ impl ClientConfig { } pub fn parse_args(matches: ArgMatches, log: &slog::Logger) -> Result { - let mut config = ClientConfig::default(); + let mut config = Config::default(); // Custom datadir if let Some(dir) = matches.value_of("datadir") { config.data_dir = PathBuf::from(dir.to_string()); diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index c6cf586f3..0ec392731 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,27 +1,13 @@ -use crate::attester_service::{AttestationGrpcClient, AttesterService}; -use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; -use crate::config::ClientConfig; -use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; -use attester::test_utils::EpochMap; -use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; -use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; -use bls::Keypair; -use clap::{App, Arg}; -use grpcio::{ChannelBuilder, EnvBuilder}; -use protos::services::{Empty, NodeInfo}; -use protos::services_grpc::{ - AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, - ValidatorServiceClient, -}; -use slog::{info, o, Drain}; -use slot_clock::SystemTimeSlotClock; -use std::sync::Arc; -use std::thread; - mod attester_service; mod block_producer_service; mod config; mod duties; +mod service; + +use crate::config::Config as ValidatorConfig; +use clap::{App, Arg}; +use service::Service as ValidatorService; +use slog::{o, Drain}; fn main() { // Logging @@ -61,142 +47,8 @@ fn main() { ) .get_matches(); - let config = ClientConfig::parse_args(matches, &log).unwrap(); + let config = ValidatorConfig::parse_args(matches, &log).unwrap(); - // Beacon node gRPC beacon node endpoints. - let beacon_node_grpc_client = { - let env = Arc::new(EnvBuilder::new().build()); - let ch = ChannelBuilder::new(env).connect(&config.server); - Arc::new(BeaconNodeServiceClient::new(ch)) - }; - - // Beacon node gRPC beacon block endpoints. - let beacon_block_grpc_client = { - let env = Arc::new(EnvBuilder::new().build()); - let ch = ChannelBuilder::new(env).connect(&config.server); - Arc::new(BeaconBlockServiceClient::new(ch)) - }; - - // Beacon node gRPC validator endpoints. - let validator_grpc_client = { - let env = Arc::new(EnvBuilder::new().build()); - let ch = ChannelBuilder::new(env).connect(&config.server); - Arc::new(ValidatorServiceClient::new(ch)) - }; - - //Beacon node gRPC attester endpoints. - let attester_grpc_client = { - let env = Arc::new(EnvBuilder::new().build()); - let ch = ChannelBuilder::new(env).connect(&config.server); - Arc::new(AttestationServiceClient::new(ch)) - }; - - // retrieve node information - let node_info = beacon_node_grpc_client.info(&Empty::new()); - - info!(log, "Beacon node info: {:?}", node_info); - - // Spec - let spec = Arc::new(config.spec.clone()); - - let genesis_time = 1_549_935_547; - let slot_clock = { - info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); - let clock = SystemTimeSlotClock::new(genesis_time, spec.seconds_per_slot) - .expect("Unable to instantiate SystemTimeSlotClock."); - Arc::new(clock) - }; - - let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. - info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); - - /* - * Start threads. - */ - let mut threads = vec![]; - // TODO: keypairs are randomly generated; they should be loaded from a file or generated. - // https://github.com/sigp/lighthouse/issues/160 - let keypairs = vec![Keypair::random()]; - - for keypair in keypairs { - info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); - let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); - let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); - - // Spawn a new thread to maintain the validator's `EpochDuties`. - let duties_manager_thread = { - let spec = spec.clone(); - let duties_map = duties_map.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let beacon_node = validator_grpc_client.clone(); - let pubkey = keypair.pk.clone(); - thread::spawn(move || { - let manager = DutiesManager { - duties_map, - pubkey, - spec, - slot_clock, - beacon_node, - }; - let mut duties_manager_service = DutiesManagerService { - manager, - poll_interval_millis, - log, - }; - - duties_manager_service.run(); - }) - }; - - // Spawn a new thread to perform block production for the validator. - let producer_thread = { - let spec = spec.clone(); - let signer = Arc::new(BlockProposerLocalSigner::new(keypair.clone())); - let duties_map = duties_map.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); - thread::spawn(move || { - let block_producer = - BlockProducer::new(spec, duties_map, slot_clock, client, signer); - let mut block_producer_service = BlockProducerService { - block_producer, - poll_interval_millis, - log, - }; - - block_producer_service.run(); - }) - }; - - // Spawn a new thread for attestation for the validator. - let attester_thread = { - let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); - let epoch_map = epoch_map_for_attester.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); - thread::spawn(move || { - let attester = Attester::new(epoch_map, slot_clock, client, signer); - let mut attester_service = AttesterService { - attester, - poll_interval_millis, - log, - }; - - attester_service.run(); - }) - }; - - threads.push((duties_manager_thread, producer_thread, attester_thread)); - } - - // Naively wait for all the threads to complete. - for tuple in threads { - let (manager, producer, attester) = tuple; - let _ = producer.join(); - let _ = manager.join(); - let _ = attester.join(); - } + // start the validator service. + ValidatorService::start(config, log); } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs new file mode 100644 index 000000000..95f2a2361 --- /dev/null +++ b/validator_client/src/service.rs @@ -0,0 +1,166 @@ +/// The validator service. Connects to a beacon node and signs blocks when required. +use crate::attester_service::{AttestationGrpcClient, AttesterService}; +use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; +use crate::config::Config as ValidatorConfig; +use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; +use attester::test_utils::EpochMap; +use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; +use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; +use bls::Keypair; +use grpcio::{ChannelBuilder, EnvBuilder}; +use protos::services::{Empty, NodeInfo}; +use protos::services_grpc::{ + AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, + ValidatorServiceClient, +}; +use slog::{info, o, Drain}; +use slot_clock::SystemTimeSlotClock; +use std::sync::Arc; +use std::thread; + +/// The validator service. This is the main thread that executes and maintains validator +/// duties. +pub struct Service {} + +impl Service { + pub fn start(config: ValidatorConfig, log: slog::Logger) { + // initialize the RPC clients + + let env = Arc::new(EnvBuilder::new().build()); + // Beacon node gRPC beacon node endpoints. + let beacon_node_grpc_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(BeaconNodeServiceClient::new(ch)) + }; + + // Beacon node gRPC beacon block endpoints. + let beacon_block_grpc_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(BeaconBlockServiceClient::new(ch)) + }; + + // Beacon node gRPC validator endpoints. + let validator_grpc_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(ValidatorServiceClient::new(ch)) + }; + + //Beacon node gRPC attester endpoints. + let attester_grpc_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(AttestationServiceClient::new(ch)) + }; + + // connect to the node and retrieve its properties + // node_info = connect_to_node(beacon_ndoe_grpc_client); + + // retrieve node information + let node_info = beacon_node_grpc_client.info(&Empty::new()); + + info!(log, "Beacon node info: {:?}", node_info); + + // Spec + let spec = Arc::new(config.spec.clone()); + + let genesis_time = 1_549_935_547; + let slot_clock = { + info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); + let clock = SystemTimeSlotClock::new(genesis_time, spec.seconds_per_slot) + .expect("Unable to instantiate SystemTimeSlotClock."); + Arc::new(clock) + }; + + let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. + info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); + + /* + * Start threads. + */ + let mut threads = vec![]; + // TODO: keypairs are randomly generated; they should be loaded from a file or generated. + // https://github.com/sigp/lighthouse/issues/160 + let keypairs = vec![Keypair::random()]; + + for keypair in keypairs { + info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); + let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); + let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); + + // Spawn a new thread to maintain the validator's `EpochDuties`. + let duties_manager_thread = { + let spec = spec.clone(); + let duties_map = duties_map.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + let beacon_node = validator_grpc_client.clone(); + let pubkey = keypair.pk.clone(); + thread::spawn(move || { + let manager = DutiesManager { + duties_map, + pubkey, + spec, + slot_clock, + beacon_node, + }; + let mut duties_manager_service = DutiesManagerService { + manager, + poll_interval_millis, + log, + }; + + duties_manager_service.run(); + }) + }; + + // Spawn a new thread to perform block production for the validator. + let producer_thread = { + let spec = spec.clone(); + let signer = Arc::new(BlockProposerLocalSigner::new(keypair.clone())); + let duties_map = duties_map.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); + thread::spawn(move || { + let block_producer = + BlockProducer::new(spec, duties_map, slot_clock, client, signer); + let mut block_producer_service = BlockProducerService { + block_producer, + poll_interval_millis, + log, + }; + + block_producer_service.run(); + }) + }; + + // Spawn a new thread for attestation for the validator. + let attester_thread = { + let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); + let epoch_map = epoch_map_for_attester.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); + thread::spawn(move || { + let attester = Attester::new(epoch_map, slot_clock, client, signer); + let mut attester_service = AttesterService { + attester, + poll_interval_millis, + log, + }; + + attester_service.run(); + }) + }; + + threads.push((duties_manager_thread, producer_thread, attester_thread)); + } + + // Naively wait for all the threads to complete. + for tuple in threads { + let (manager, producer, attester) = tuple; + let _ = producer.join(); + let _ = manager.join(); + let _ = attester.join(); + } + } +} From 61fc946d54a0de8b937152bf2d799c428ed7b29a Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 22:50:16 +1100 Subject: [PATCH 27/97] Adds initial connection to beacon node with retries --- validator_client/src/service.rs | 79 +++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 13 deletions(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 95f2a2361..3bf2d6104 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -13,16 +13,75 @@ use protos::services_grpc::{ AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, ValidatorServiceClient, }; -use slog::{info, o, Drain}; +use slog::{info, o, warn, Drain}; use slot_clock::SystemTimeSlotClock; use std::sync::Arc; use std::thread; +use std::time::Duration; +use types::{Epoch, Fork}; /// The validator service. This is the main thread that executes and maintains validator /// duties. -pub struct Service {} +#[derive(Debug)] +pub struct Service { + /// The node we currently connected to. + connected_node_version: String, + /// The chain id we are processing on. + chain_id: u16, + /// The fork state we processing on. + fork: Fork, + // /// The slot clock keeping track of time. + // slot_clock: Arc, +} impl Service { + /// Initial connection to the beacon node to determine its properties. + fn connect_to_node( + node_client: Arc, + seconds_per_slot: u64, + log: &slog::Logger, + ) -> Self { + // retrieve node information + let node_info = loop { + let info = match node_client.info(&Empty::new()) { + Err(e) => { + warn!(log, "Could not connect to node. Error: {}", e); + info!(log, "Retrying in 5 seconds..."); + std::thread::sleep(Duration::from_secs(5)); + continue; + } + Ok(info) => break info, + }; + }; + + info!(log,"Beacon node connected"; "Node Version:" => node_info.version.clone(), "Chain ID:" => node_info.chain_id); + + let proto_fork = node_info.get_fork(); + let mut previous_version: [u8; 4] = [0; 4]; + let mut current_version: [u8; 4] = [0; 4]; + previous_version.copy_from_slice(&proto_fork.get_previous_version()[..4]); + current_version.copy_from_slice(&proto_fork.get_current_version()[..4]); + let fork = Fork { + previous_version, + current_version, + epoch: Epoch::from(proto_fork.get_epoch()), + }; + + let genesis_time = 1_549_935_547; + let slot_clock = { + info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); + let clock = SystemTimeSlotClock::new(genesis_time, seconds_per_slot) + .expect("Unable to instantiate SystemTimeSlotClock."); + Arc::new(clock) + }; + + Self { + connected_node_version: node_info.version, + chain_id: node_info.chain_id as u16, + fork, + } + } + pub fn start(config: ValidatorConfig, log: slog::Logger) { // initialize the RPC clients @@ -51,16 +110,13 @@ impl Service { Arc::new(AttestationServiceClient::new(ch)) }; + let spec = Arc::new(config.spec); // connect to the node and retrieve its properties - // node_info = connect_to_node(beacon_ndoe_grpc_client); + let service = + Service::connect_to_node(beacon_node_grpc_client, spec.seconds_per_slot, &log); - // retrieve node information - let node_info = beacon_node_grpc_client.info(&Empty::new()); - - info!(log, "Beacon node info: {:?}", node_info); - - // Spec - let spec = Arc::new(config.spec.clone()); + let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. + info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); let genesis_time = 1_549_935_547; let slot_clock = { @@ -70,9 +126,6 @@ impl Service { Arc::new(clock) }; - let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. - info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); - /* * Start threads. */ From 17cd5bb991985ab9f3bebfd6e8614872f34d27de Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 23:01:10 +1100 Subject: [PATCH 28/97] Adds genesis time to node info. Closes #256 --- beacon_node/rpc/src/beacon_node.rs | 14 ++++++++++---- protos/src/services.proto | 2 +- validator_client/src/service.rs | 14 ++++++++------ 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/beacon_node/rpc/src/beacon_node.rs b/beacon_node/rpc/src/beacon_node.rs index 5a542cb90..7b00f04f4 100644 --- a/beacon_node/rpc/src/beacon_node.rs +++ b/beacon_node/rpc/src/beacon_node.rs @@ -3,7 +3,7 @@ use futures::Future; use grpcio::{RpcContext, UnarySink}; use protos::services::{Empty, Fork, NodeInfo}; use protos::services_grpc::BeaconNodeService; -use slog::{debug, trace, warn}; +use slog::{trace, warn}; use std::sync::Arc; #[derive(Clone)] @@ -17,17 +17,23 @@ impl BeaconNodeService for BeaconNodeServiceInstance { fn info(&mut self, ctx: RpcContext, _req: Empty, sink: UnarySink) { trace!(self.log, "Node info requested via RPC"); + // build the response let mut node_info = NodeInfo::new(); node_info.set_version(version::version()); - // get the chain state fork - let state_fork = self.chain.get_state().fork.clone(); + + // get the chain state + let state = self.chain.get_state(); + let state_fork = state.fork.clone(); + let genesis_time = state.genesis_time.clone(); + // build the rpc fork struct let mut fork = Fork::new(); fork.set_previous_version(state_fork.previous_version.to_vec()); fork.set_current_version(state_fork.current_version.to_vec()); fork.set_epoch(state_fork.epoch.into()); - node_info.set_fork(fork); + node_info.set_fork(fork); + node_info.set_genesis_time(genesis_time); node_info.set_chain_id(self.chain.get_spec().chain_id as u32); // send the node_info the requester diff --git a/protos/src/services.proto b/protos/src/services.proto index 45fcfb120..fbcde922d 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -44,6 +44,7 @@ message NodeInfo { string version = 1; Fork fork = 2; uint32 chain_id = 3; + uint64 genesis_time = 4; } message Fork { @@ -56,7 +57,6 @@ message Empty { } - /* * Block Production Service Messages */ diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 3bf2d6104..df3f64027 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -22,7 +22,6 @@ use types::{Epoch, Fork}; /// The validator service. This is the main thread that executes and maintains validator /// duties. -#[derive(Debug)] pub struct Service { /// The node we currently connected to. connected_node_version: String, @@ -30,8 +29,8 @@ pub struct Service { chain_id: u16, /// The fork state we processing on. fork: Fork, - // /// The slot clock keeping track of time. - // slot_clock: Arc, + /// The slot clock keeping track of time. + slot_clock: Arc, } impl Service { @@ -54,7 +53,10 @@ impl Service { }; }; - info!(log,"Beacon node connected"; "Node Version:" => node_info.version.clone(), "Chain ID:" => node_info.chain_id); + // build requisite objects to form Self + let genesis_time = node_info.get_genesis_time(); + + info!(log,"Beacon node connected"; "Node Version" => node_info.version.clone(), "Chain ID" => node_info.chain_id, "Genesis time" => genesis_time); let proto_fork = node_info.get_fork(); let mut previous_version: [u8; 4] = [0; 4]; @@ -67,9 +69,8 @@ impl Service { epoch: Epoch::from(proto_fork.get_epoch()), }; - let genesis_time = 1_549_935_547; + // build the validator slot clock let slot_clock = { - info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); let clock = SystemTimeSlotClock::new(genesis_time, seconds_per_slot) .expect("Unable to instantiate SystemTimeSlotClock."); Arc::new(clock) @@ -79,6 +80,7 @@ impl Service { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, + slot_clock, } } From 547a750d78443eea0745b9661980ba3b7950a4f2 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Fri, 22 Mar 2019 23:21:26 +1100 Subject: [PATCH 29/97] Setup basic structure before tokio runtime addition --- validator_client/src/service.rs | 119 +++++++++++++++++--------------- 1 file changed, 64 insertions(+), 55 deletions(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index df3f64027..bf3003834 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -31,18 +31,44 @@ pub struct Service { fork: Fork, /// The slot clock keeping track of time. slot_clock: Arc, + // GRPC Clients + /// The beacon block GRPC client. + beacon_block_client: Arc, + /// The validator GRPC client. + validator_client: Arc, + /// The attester GRPC client. + attester_client: Arc, + /// The validator client logger. + log: slog::Logger, } impl Service { + /// Initialise the service then run the core thread. + pub fn start(config: ValidatorConfig, log: slog::Logger) { + // connect to the node and retrieve its properties and initialize the gRPC clients + let service = Service::initialize_service(&config, log); + + // we have connected to a node and established its parameters. Spin up the core service + service.run(config); + } + /// Initial connection to the beacon node to determine its properties. - fn connect_to_node( - node_client: Arc, - seconds_per_slot: u64, - log: &slog::Logger, - ) -> Self { + /// + /// This tries to connect to a beacon node. Once connected, it initialised the gRPC clients + /// and returns an instance of the service. + fn initialize_service(config: &ValidatorConfig, log: slog::Logger) -> Self { + // initialise the beacon node client to check for a connection + + let env = Arc::new(EnvBuilder::new().build()); + // Beacon node gRPC beacon node endpoints. + let beacon_node_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(BeaconNodeServiceClient::new(ch)) + }; + // retrieve node information let node_info = loop { - let info = match node_client.info(&Empty::new()) { + let info = match beacon_node_client.info(&Empty::new()) { Err(e) => { warn!(log, "Could not connect to node. Error: {}", e); info!(log, "Retrying in 5 seconds..."); @@ -71,63 +97,44 @@ impl Service { // build the validator slot clock let slot_clock = { - let clock = SystemTimeSlotClock::new(genesis_time, seconds_per_slot) + let clock = SystemTimeSlotClock::new(genesis_time, config.spec.seconds_per_slot) .expect("Unable to instantiate SystemTimeSlotClock."); Arc::new(clock) }; + // initialize the RPC clients + + // Beacon node gRPC beacon block endpoints. + let beacon_block_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(BeaconBlockServiceClient::new(ch)) + }; + + // Beacon node gRPC validator endpoints. + let validator_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(ValidatorServiceClient::new(ch)) + }; + + //Beacon node gRPC attester endpoints. + let attester_client = { + let ch = ChannelBuilder::new(env.clone()).connect(&config.server); + Arc::new(AttestationServiceClient::new(ch)) + }; + Self { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, slot_clock, + beacon_block_client, + validator_client, + attester_client, + log, } } - pub fn start(config: ValidatorConfig, log: slog::Logger) { - // initialize the RPC clients - - let env = Arc::new(EnvBuilder::new().build()); - // Beacon node gRPC beacon node endpoints. - let beacon_node_grpc_client = { - let ch = ChannelBuilder::new(env.clone()).connect(&config.server); - Arc::new(BeaconNodeServiceClient::new(ch)) - }; - - // Beacon node gRPC beacon block endpoints. - let beacon_block_grpc_client = { - let ch = ChannelBuilder::new(env.clone()).connect(&config.server); - Arc::new(BeaconBlockServiceClient::new(ch)) - }; - - // Beacon node gRPC validator endpoints. - let validator_grpc_client = { - let ch = ChannelBuilder::new(env.clone()).connect(&config.server); - Arc::new(ValidatorServiceClient::new(ch)) - }; - - //Beacon node gRPC attester endpoints. - let attester_grpc_client = { - let ch = ChannelBuilder::new(env.clone()).connect(&config.server); - Arc::new(AttestationServiceClient::new(ch)) - }; - - let spec = Arc::new(config.spec); - // connect to the node and retrieve its properties - let service = - Service::connect_to_node(beacon_node_grpc_client, spec.seconds_per_slot, &log); - - let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. - info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); - - let genesis_time = 1_549_935_547; - let slot_clock = { - info!(log, "Genesis time"; "unix_epoch_seconds" => genesis_time); - let clock = SystemTimeSlotClock::new(genesis_time, spec.seconds_per_slot) - .expect("Unable to instantiate SystemTimeSlotClock."); - Arc::new(clock) - }; - + fn run(&mut self, config: ValidatorConfig) { /* * Start threads. */ @@ -136,8 +143,10 @@ impl Service { // https://github.com/sigp/lighthouse/issues/160 let keypairs = vec![Keypair::random()]; + let spec = config.spec; + for keypair in keypairs { - info!(log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); + info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); @@ -145,9 +154,9 @@ impl Service { let duties_manager_thread = { let spec = spec.clone(); let duties_map = duties_map.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let beacon_node = validator_grpc_client.clone(); + let slot_clock = self.slot_clock.clone(); + let log = self.log.clone(); + let beacon_node = self.validator_client.clone(); let pubkey = keypair.pk.clone(); thread::spawn(move || { let manager = DutiesManager { From 318d6a976e1d2e0100cdd72098e2311d313f07cf Mon Sep 17 00:00:00 2001 From: Age Manning Date: Sat, 23 Mar 2019 00:36:48 +1100 Subject: [PATCH 30/97] Initial tokio timer interval --- validator_client/src/service.rs | 50 +++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index bf3003834..0934a5a16 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -31,6 +31,8 @@ pub struct Service { fork: Fork, /// The slot clock keeping track of time. slot_clock: Arc, + /// The current slot we are processing. + current_slot: Slot, // GRPC Clients /// The beacon block GRPC client. beacon_block_client: Arc, @@ -122,11 +124,14 @@ impl Service { Arc::new(AttestationServiceClient::new(ch)) }; + let current_slot = slot_clock.present_slot().saturating_sub(1); + Self { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, slot_clock, + current_slot, beacon_block_client, validator_client, attester_client, @@ -135,15 +140,50 @@ impl Service { } fn run(&mut self, config: ValidatorConfig) { - /* - * Start threads. - */ - let mut threads = vec![]; + + // generate keypairs + // TODO: keypairs are randomly generated; they should be loaded from a file or generated. // https://github.com/sigp/lighthouse/issues/160 let keypairs = vec![Keypair::random()]; - let spec = config.spec; + // set up the validator service runtime + let runtime = Builder::new().clock(Clock::system()).name_prefix("validator-client-").build().unwrap(); + + // set up the validator work interval - start at next slot and proceed every slot + let interval = { + let time_to_next_slot = { + let syslot_time = SystemTime::now(); + let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH)?; + let mut secs_to_slot = None; + if let Some(duration_since_genesis) = + duration_since_epoch.checked_sub(Duration::from_secs(self.genesis_seconds)) { + // seconds till next slot + secs_to_slot =duration_since_genesis.as_secs().checked_rem(config.spec.seconds_per_slot); + } + secs_to_slot.ok_or_else(0) + } + // Set the interval to start at the next slot, and every slot after + let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); + //TODO: Handle checked add correctly + Interval::new(Instant::now().checked_add(secs_to_slot)?, slot_duration) + } + + // kick off core service + runtime.spawn(interval.for_each(|_| {})); + + + + let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); + let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); + let manager = DutiesManager { + duties_map, + pubkey, + spec, + slot_clock, + beacon_node, + }; + for keypair in keypairs { info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); From 56d33d2e26866e6ebdd02835bb75b5bb3c5a2945 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Sat, 23 Mar 2019 11:48:36 +1100 Subject: [PATCH 31/97] Basic tokio slot stream implementation --- validator_client/Cargo.toml | 4 +- validator_client/src/duties/mod.rs | 13 +- validator_client/src/service.rs | 291 ++++++++++++++++------------- 3 files changed, 170 insertions(+), 138 deletions(-) diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index 4bd63715c..e8cff2622 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" block_proposer = { path = "../eth2/block_proposer" } attester = { path = "../eth2/attester" } bls = { path = "../eth2/utils/bls" } +ssz = { path = "../eth2/utils/ssz" } clap = "2.32.0" dirs = "1.0.3" grpcio = { version = "0.4", default-features = false, features = ["protobuf-codec"] } @@ -18,4 +19,5 @@ types = { path = "../eth2/types" } slog = "^2.2.3" slog-term = "^2.4.0" slog-async = "^2.3.0" -ssz = { path = "../eth2/utils/ssz" } +tokio = "0.1.18" +tokio-timer = "0.2.10" diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 29bd81d0a..c2b95b1c5 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -39,11 +39,11 @@ pub enum Error { /// A polling state machine which ensures the latest `EpochDuties` are obtained from the Beacon /// Node. /// -/// There is a single `DutiesManager` per validator instance. +/// This keeps track of all validator keys and required voting slots. pub struct DutiesManager { pub duties_map: Arc, - /// The validator's public key. - pub pubkey: PublicKey, + /// A list of all public keys known to the validator service. + pub pubkeys: Vec, pub spec: Arc, pub slot_clock: Arc, pub beacon_node: Arc, @@ -54,6 +54,8 @@ impl DutiesManager { /// /// The present `epoch` will be learned from the supplied `SlotClock`. In production this will /// be a wall-clock (e.g., system time, remote server time, etc.). + //TODO: Remove the poll and trust the tokio system-clock timer. Leave for now to ensure the + //timer is accurate. pub fn poll(&self) -> Result { let slot = self .slot_clock @@ -63,7 +65,10 @@ impl DutiesManager { let epoch = slot.epoch(self.spec.slots_per_epoch); - if let Some(duties) = self.beacon_node.request_shuffling(epoch, &self.pubkey)? { + if let Some(duties) = self + .beacon_node + .request_shuffling(epoch, &self.pubkeys[0])? + { // If these duties were known, check to see if they're updates or identical. let result = if let Some(known_duties) = self.duties_map.get(epoch)? { if known_duties == duties { diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 0934a5a16..322c370b5 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -8,17 +8,23 @@ use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; use bls::Keypair; use grpcio::{ChannelBuilder, EnvBuilder}; -use protos::services::{Empty, NodeInfo}; +use protos::services::Empty; use protos::services_grpc::{ AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, ValidatorServiceClient, }; -use slog::{info, o, warn, Drain}; -use slot_clock::SystemTimeSlotClock; +use slog::{debug, info, warn}; +use slot_clock::{SlotClock, SystemTimeSlotClock}; +use std::ops::Sub; use std::sync::Arc; -use std::thread; -use std::time::Duration; -use types::{Epoch, Fork}; +use std::time::{Duration, Instant, SystemTime}; +use tokio::prelude::*; +use tokio::runtime::Builder; +use tokio::timer::Interval; +use tokio_timer::clock::Clock; +use types::{Epoch, Fork, Slot}; + +//TODO: This service should be simplified in the future. Can be made more steamlined. /// The validator service. This is the main thread that executes and maintains validator /// duties. @@ -33,6 +39,8 @@ pub struct Service { slot_clock: Arc, /// The current slot we are processing. current_slot: Slot, + /// Seconds until the next slot. This is used for initializing the tokio timer interval. + seconds_to_next_slot: Duration, // GRPC Clients /// The beacon block GRPC client. beacon_block_client: Arc, @@ -45,15 +53,6 @@ pub struct Service { } impl Service { - /// Initialise the service then run the core thread. - pub fn start(config: ValidatorConfig, log: slog::Logger) { - // connect to the node and retrieve its properties and initialize the gRPC clients - let service = Service::initialize_service(&config, log); - - // we have connected to a node and established its parameters. Spin up the core service - service.run(config); - } - /// Initial connection to the beacon node to determine its properties. /// /// This tries to connect to a beacon node. Once connected, it initialised the gRPC clients @@ -124,7 +123,24 @@ impl Service { Arc::new(AttestationServiceClient::new(ch)) }; - let current_slot = slot_clock.present_slot().saturating_sub(1); + //TODO: Add error chain. Handle errors + let current_slot = slot_clock.present_slot().unwrap().unwrap().sub(1); + + // calculate seconds to the next slot + let seconds_to_next_slot = { + let syslot_time = SystemTime::now(); + let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH).unwrap(); + let mut secs_to_slot = None; + if let Some(duration_since_genesis) = + duration_since_epoch.checked_sub(Duration::from_secs(genesis_time)) + { + // seconds till next slot + secs_to_slot = duration_since_genesis + .as_secs() + .checked_rem(config.spec.seconds_per_slot); + } + secs_to_slot.unwrap_or_else(|| 0) + }; Self { connected_node_version: node_info.version, @@ -132,6 +148,7 @@ impl Service { fork, slot_clock, current_slot, + seconds_to_next_slot: Duration::from_secs(seconds_to_next_slot), beacon_block_client, validator_client, attester_client, @@ -139,132 +156,140 @@ impl Service { } } - fn run(&mut self, config: ValidatorConfig) { + /// Initialise the service then run the core thread. + pub fn start(config: ValidatorConfig, log: slog::Logger) { + // connect to the node and retrieve its properties and initialize the gRPC clients + let service = Service::initialize_service(&config, log); + + // we have connected to a node and established its parameters. Spin up the core service + + // set up the validator service runtime + let mut runtime = Builder::new() + .clock(Clock::system()) + .name_prefix("validator-client-") + .build() + .unwrap(); + + // set up the validator work interval - start at next slot and proceed every slot + // TODO: Error chain handle errors. + let interval = { + // Set the interval to start at the next slot, and every slot after + let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); + //TODO: Handle checked add correctly + Interval::new(Instant::now() + service.seconds_to_next_slot, slot_duration) + }; + + // kick off core service // generate keypairs // TODO: keypairs are randomly generated; they should be loaded from a file or generated. // https://github.com/sigp/lighthouse/issues/160 - let keypairs = vec![Keypair::random()]; + let keypairs = Arc::new(vec![Keypair::random()]); - // set up the validator service runtime - let runtime = Builder::new().clock(Clock::system()).name_prefix("validator-client-").build().unwrap(); - - // set up the validator work interval - start at next slot and proceed every slot - let interval = { - let time_to_next_slot = { - let syslot_time = SystemTime::now(); - let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH)?; - let mut secs_to_slot = None; - if let Some(duration_since_genesis) = - duration_since_epoch.checked_sub(Duration::from_secs(self.genesis_seconds)) { - // seconds till next slot - secs_to_slot =duration_since_genesis.as_secs().checked_rem(config.spec.seconds_per_slot); - } - secs_to_slot.ok_or_else(0) - } - // Set the interval to start at the next slot, and every slot after - let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); - //TODO: Handle checked add correctly - Interval::new(Instant::now().checked_add(secs_to_slot)?, slot_duration) - } - - // kick off core service - runtime.spawn(interval.for_each(|_| {})); - - - - let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); - let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); + // build requisite objects to pass to core thread. + let duties_map = Arc::new(EpochDutiesMap::new(config.spec.slots_per_epoch)); + let epoch_map_for_attester = Arc::new(EpochMap::new(config.spec.slots_per_epoch)); let manager = DutiesManager { duties_map, - pubkey, - spec, - slot_clock, - beacon_node, + pubkeys: keypairs.iter().map(|keypair| keypair.pk.clone()).collect(), + spec: Arc::new(config.spec), + slot_clock: service.slot_clock.clone(), + beacon_node: service.validator_client.clone(), }; - - for keypair in keypairs { - info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); - let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); - let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); - - // Spawn a new thread to maintain the validator's `EpochDuties`. - let duties_manager_thread = { - let spec = spec.clone(); - let duties_map = duties_map.clone(); - let slot_clock = self.slot_clock.clone(); - let log = self.log.clone(); - let beacon_node = self.validator_client.clone(); - let pubkey = keypair.pk.clone(); - thread::spawn(move || { - let manager = DutiesManager { - duties_map, - pubkey, - spec, - slot_clock, - beacon_node, - }; - let mut duties_manager_service = DutiesManagerService { - manager, - poll_interval_millis, - log, - }; - - duties_manager_service.run(); - }) - }; - - // Spawn a new thread to perform block production for the validator. - let producer_thread = { - let spec = spec.clone(); - let signer = Arc::new(BlockProposerLocalSigner::new(keypair.clone())); - let duties_map = duties_map.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); - thread::spawn(move || { - let block_producer = - BlockProducer::new(spec, duties_map, slot_clock, client, signer); - let mut block_producer_service = BlockProducerService { - block_producer, - poll_interval_millis, - log, - }; - - block_producer_service.run(); - }) - }; - - // Spawn a new thread for attestation for the validator. - let attester_thread = { - let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); - let epoch_map = epoch_map_for_attester.clone(); - let slot_clock = slot_clock.clone(); - let log = log.clone(); - let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); - thread::spawn(move || { - let attester = Attester::new(epoch_map, slot_clock, client, signer); - let mut attester_service = AttesterService { - attester, - poll_interval_millis, - log, - }; - - attester_service.run(); - }) - }; - - threads.push((duties_manager_thread, producer_thread, attester_thread)); - } - - // Naively wait for all the threads to complete. - for tuple in threads { - let (manager, producer, attester) = tuple; - let _ = producer.join(); - let _ = manager.join(); - let _ = attester.join(); - } + runtime.block_on(interval.for_each(move |_| { + // update duties + debug!(service.log, "Processing new slot..."); + manager.poll(); + Ok(()) + })); } + + /* + + let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); + let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); + + + for keypair in keypairs { + info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); + + // Spawn a new thread to maintain the validator's `EpochDuties`. + let duties_manager_thread = { + let spec = spec.clone(); + let duties_map = duties_map.clone(); + let slot_clock = self.slot_clock.clone(); + let log = self.log.clone(); + let beacon_node = self.validator_client.clone(); + let pubkey = keypair.pk.clone(); + thread::spawn(move || { + let manager = DutiesManager { + duties_map, + pubkey, + spec, + slot_clock, + beacon_node, + }; + let mut duties_manager_service = DutiesManagerService { + manager, + poll_interval_millis, + log, + }; + + duties_manager_service.run(); + }) + }; + + // Spawn a new thread to perform block production for the validator. + let producer_thread = { + let spec = spec.clone(); + let signer = Arc::new(BlockProposerLocalSigner::new(keypair.clone())); + let duties_map = duties_map.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + let client = Arc::new(BeaconBlockGrpcClient::new(beacon_block_grpc_client.clone())); + thread::spawn(move || { + let block_producer = + BlockProducer::new(spec, duties_map, slot_clock, client, signer); + let mut block_producer_service = BlockProducerService { + block_producer, + poll_interval_millis, + log, + }; + + block_producer_service.run(); + }) + }; + + // Spawn a new thread for attestation for the validator. + let attester_thread = { + let signer = Arc::new(AttesterLocalSigner::new(keypair.clone())); + let epoch_map = epoch_map_for_attester.clone(); + let slot_clock = slot_clock.clone(); + let log = log.clone(); + let client = Arc::new(AttestationGrpcClient::new(attester_grpc_client.clone())); + thread::spawn(move || { + let attester = Attester::new(epoch_map, slot_clock, client, signer); + let mut attester_service = AttesterService { + attester, + poll_interval_millis, + log, + }; + + attester_service.run(); + }) + }; + + threads.push((duties_manager_thread, producer_thread, attester_thread)); + } + + // Naively wait for all the threads to complete. + for tuple in threads { + let (manager, producer, attester) = tuple; + let _ = producer.join(); + let _ = manager.join(); + let _ = attester.join(); + } + */ } From 4b5b5851a64a4cd2920bb7f4ba0a10b6a5d1ac0b Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sat, 23 Mar 2019 13:23:44 +1100 Subject: [PATCH 32/97] Allow sync to to request block bodies. --- beacon_node/beacon_chain/src/beacon_chain.rs | 30 ++- beacon_node/eth2-libp2p/src/rpc/methods.rs | 2 +- beacon_node/network/Cargo.toml | 1 + beacon_node/network/src/beacon_chain.rs | 16 +- beacon_node/network/src/message_handler.rs | 17 +- beacon_node/network/src/sync/simple_sync.rs | 200 +++++++++++++++++-- beacon_node/network/tests/tests.rs | 72 ++++++- 7 files changed, 305 insertions(+), 33 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index dccd9842e..33198f0a3 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -142,8 +142,14 @@ where let mut slot = start_slot + count - 1; loop { - // Return if the slot required is greater than the current state. - if slot >= state.slot { + // If the highest slot requested is that of the current state insert the root of the + // head block, unless the head block's slot is not matching. + if slot == state.slot && self.head().beacon_block.slot == slot { + roots.push(self.head().beacon_block_root); + + slot -= 1; + continue; + } else if slot >= state.slot { return Err(BeaconStateError::SlotOutOfBounds); } @@ -180,12 +186,25 @@ where } if (slot == start_slot) && (roots.len() == count.as_usize()) { - Ok(roots) + // Reverse the ordering of the roots. We extracted them in reverse order to make it + // simpler to lookup historic states. + // + // This is a potential optimisation target. + Ok(roots.iter().rev().cloned().collect()) } else { Err(BeaconStateError::SlotOutOfBounds) } } + /// Returns the block at the given root, if any. + /// + /// ## Errors + /// + /// May return a database error. + pub fn get_block(&self, block_root: &Hash256) -> Result, Error> { + Ok(self.block_store.get_deserialized(block_root)?) + } + /// Update the canonical head to some new values. pub fn update_canonical_head( &self, @@ -622,6 +641,11 @@ where } } + /// Returns `true` if the given block root has not been processed. + pub fn is_new_block_root(&self, beacon_block_root: &Hash256) -> Result { + Ok(!self.block_store.exists(beacon_block_root)?) + } + /// Accept some block and attempt to add it to block DAG. /// /// Will accept blocks from prior slots, however it will reject any block from a future slot. diff --git a/beacon_node/eth2-libp2p/src/rpc/methods.rs b/beacon_node/eth2-libp2p/src/rpc/methods.rs index 381fc8b01..f6a5f2829 100644 --- a/beacon_node/eth2-libp2p/src/rpc/methods.rs +++ b/beacon_node/eth2-libp2p/src/rpc/methods.rs @@ -162,7 +162,7 @@ pub struct BeaconBlockHeadersResponse { #[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockBodiesRequest { /// The list of beacon block bodies being requested. - pub block_roots: Hash256, + pub block_roots: Vec, } /// Response containing the list of requested beacon block bodies. diff --git a/beacon_node/network/Cargo.toml b/beacon_node/network/Cargo.toml index a53097159..c6411a020 100644 --- a/beacon_node/network/Cargo.toml +++ b/beacon_node/network/Cargo.toml @@ -14,6 +14,7 @@ eth2-libp2p = { path = "../eth2-libp2p" } version = { path = "../version" } types = { path = "../../eth2/types" } slog = "2.4.1" +ssz = { path = "../../eth2/utils/ssz" } futures = "0.1.25" error-chain = "0.12.0" crossbeam-channel = "0.3.8" diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index ba429e688..e2829cfa6 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -8,7 +8,9 @@ use beacon_chain::{ CheckPoint, }; use eth2_libp2p::HelloMessage; -use types::{BeaconStateError, Epoch, Hash256, Slot}; +use types::{BeaconBlock, BeaconStateError, Epoch, Hash256, Slot}; + +pub use beacon_chain::BeaconChainError; /// The network's API to the beacon chain. pub trait BeaconChain: Send + Sync { @@ -20,6 +22,8 @@ pub trait BeaconChain: Send + Sync { fn head(&self) -> RwLockReadGuard; + fn get_block(&self, block_root: &Hash256) -> Result, BeaconChainError>; + fn best_slot(&self) -> Slot; fn best_block_root(&self) -> Hash256; @@ -35,6 +39,8 @@ pub trait BeaconChain: Send + Sync { start_slot: Slot, count: Slot, ) -> Result, BeaconStateError>; + + fn is_new_block_root(&self, beacon_block_root: &Hash256) -> Result; } impl BeaconChain for RawBeaconChain @@ -59,6 +65,10 @@ where self.head() } + fn get_block(&self, block_root: &Hash256) -> Result, BeaconChainError> { + self.get_block(block_root) + } + fn finalized_epoch(&self) -> Epoch { self.get_state().finalized_epoch } @@ -95,4 +105,8 @@ where ) -> Result, BeaconStateError> { self.get_block_roots(start_slot, count) } + + fn is_new_block_root(&self, beacon_block_root: &Hash256) -> Result { + self.is_new_block_root(beacon_block_root) + } } diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 99a263ed8..1a790eee1 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -142,7 +142,7 @@ impl MessageHandler { RPCResponse::BeaconBlockRoots(response) => { debug!( self.log, - "BeaconBlockRoots response received from peer: {:?}", peer_id + "BeaconBlockRoots response received"; "peer" => format!("{:?}", peer_id) ); self.sync.on_beacon_block_roots_response( peer_id, @@ -150,6 +150,17 @@ impl MessageHandler { &mut self.network_context, ) } + RPCResponse::BeaconBlockHeaders(response) => { + debug!( + self.log, + "BeaconBlockHeaders response received"; "peer" => format!("{:?}", peer_id) + ); + self.sync.on_beacon_block_headers_response( + peer_id, + response, + &mut self.network_context, + ) + } // TODO: Handle all responses _ => panic!("Unknown response: {:?}", response), } @@ -233,10 +244,6 @@ impl NetworkContext { }; // register RPC request self.requests.insert((peer_id.clone(), id), Instant::now()); - debug!( - self.log, - "Hello request registered with peer: {:?}", peer_id - ); id } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index ab29d0db5..ee0646dbb 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -3,10 +3,12 @@ use crate::message_handler::NetworkContext; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse}; use eth2_libp2p::PeerId; -use slog::{debug, o}; +use slog::{debug, error, o, warn}; +use ssz::TreeHash; use std::collections::HashMap; use std::sync::Arc; -use types::{Epoch, Hash256, Slot}; +use std::time::Instant; +use types::{BeaconBlockHeader, Epoch, Hash256, Slot}; /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; @@ -78,7 +80,7 @@ impl From<&Arc> for PeerSyncInfo { pub enum SyncState { Idle, Downloading, - Stopped, + _Stopped, } /// Simple Syncing protocol. @@ -89,6 +91,8 @@ pub struct SimpleSync { chain: Arc, /// A mapping of Peers to their respective PeerSyncInfo. known_peers: HashMap, + /// A queue to allow importing of blocks + import_queue: ImportQueue, /// The current state of the syncing protocol. state: SyncState, /// Sync logger. @@ -97,11 +101,12 @@ pub struct SimpleSync { impl SimpleSync { pub fn new(beacon_chain: Arc, log: &slog::Logger) -> Self { - let state = beacon_chain.get_state(); let sync_logger = log.new(o!("Service"=> "Sync")); + let import_queue = ImportQueue::new(beacon_chain.clone(), log.clone()); SimpleSync { chain: beacon_chain.clone(), known_peers: HashMap::new(), + import_queue, state: SyncState::Idle, log: sync_logger, } @@ -149,15 +154,24 @@ impl SimpleSync { .start_slot(spec.slots_per_epoch); let required_slots = start_slot - local.best_slot; - self.request_block_roots(peer_id, start_slot, required_slots.as_u64(), network); + self.request_block_roots( + peer_id, + BeaconBlockRootsRequest { + start_slot, + count: required_slots.into(), + }, + network, + ); } PeerStatus::HigherBestSlot => { let required_slots = remote.best_slot - local.best_slot; self.request_block_roots( peer_id, - local.best_slot, - required_slots.as_u64(), + BeaconBlockRootsRequest { + start_slot: local.best_slot + 1, + count: required_slots.into(), + }, network, ); } @@ -168,32 +182,109 @@ impl SimpleSync { pub fn on_beacon_block_roots_response( &mut self, peer_id: PeerId, - reponse: BeaconBlockRootsResponse, + response: BeaconBlockRootsResponse, network: &mut NetworkContext, ) { + if response.roots.is_empty() { + warn!( + self.log, + "Peer returned empty block roots response. PeerId: {:?}", peer_id + ); + return; + } + + let new_root_index = self.import_queue.first_new_root(&response.roots); + + // If a new block root is found, request it and all the headers following it. // + // We make an assumption here that if we don't know a block then we don't know of all + // it's parents. This might not be the case if syncing becomes more sophisticated. + if let Some(i) = new_root_index { + let new = &response.roots[i]; + + self.request_block_headers( + peer_id, + BeaconBlockHeadersRequest { + start_root: new.block_root, + start_slot: new.slot, + max_headers: (response.roots.len() - i) as u64, + skip_slots: 0, + }, + network, + ) + } + } + + pub fn on_beacon_block_headers_response( + &mut self, + peer_id: PeerId, + response: BeaconBlockHeadersResponse, + network: &mut NetworkContext, + ) { + if response.headers.is_empty() { + warn!( + self.log, + "Peer returned empty block headers response. PeerId: {:?}", peer_id + ); + return; + } + + let block_roots = self.import_queue.enqueue_headers(response.headers); + + if !block_roots.is_empty() { + self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); + } } fn request_block_roots( &mut self, peer_id: PeerId, - start_slot: Slot, - count: u64, + request: BeaconBlockRootsRequest, network: &mut NetworkContext, ) { // Potentially set state to sync. - if self.state == SyncState::Idle && count > SLOT_IMPORT_TOLERANCE { + if self.state == SyncState::Idle && request.count > SLOT_IMPORT_TOLERANCE { debug!(self.log, "Entering downloading sync state."); self.state = SyncState::Downloading; } - debug!(self.log, "Requesting {} blocks from {:?}.", count, &peer_id); + debug!( + self.log, + "Requesting {} block roots from {:?}.", request.count, &peer_id + ); // TODO: handle count > max count. - network.send_rpc_request( - peer_id.clone(), - RPCRequest::BeaconBlockRoots(BeaconBlockRootsRequest { start_slot, count }), + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockRoots(request)); + } + + fn request_block_headers( + &mut self, + peer_id: PeerId, + request: BeaconBlockHeadersRequest, + network: &mut NetworkContext, + ) { + debug!( + self.log, + "Requesting {} headers from {:?}.", request.max_headers, &peer_id ); + + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockHeaders(request)); + } + + fn request_block_bodies( + &mut self, + peer_id: PeerId, + request: BeaconBlockBodiesRequest, + network: &mut NetworkContext, + ) { + debug!( + self.log, + "Requesting {} bodies from {:?}.", + request.block_roots.len(), + &peer_id + ); + + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockBodies(request)); } /// Generates our current state in the form of a HELLO RPC message. @@ -201,3 +292,82 @@ impl SimpleSync { self.chain.hello_message() } } + +pub struct ImportQueue { + /// BeaconChain + pub chain: Arc, + /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. + pub partials: HashMap, + /// Logging + log: slog::Logger, +} + +impl ImportQueue { + pub fn new(chain: Arc, log: slog::Logger) -> Self { + Self { + chain, + partials: HashMap::new(), + log, + } + } + + fn is_new_block(&self, block_root: &Hash256) -> bool { + self.chain + .is_new_block_root(&block_root) + .unwrap_or_else(|_| { + error!(self.log, "Unable to determine if block is new."); + true + }) + } + + /// Returns the index of the first new root in the list of block roots. + pub fn first_new_root(&mut self, roots: &[BlockRootSlot]) -> Option { + for root in roots { + println!("root {}", root.block_root); + } + roots + .iter() + .position(|brs| self.is_new_block(&brs.block_root)) + } + + /// Adds the `headers` to the `partials` queue. Returns a list of `Hash256` block roots for + /// which we should use to request `BeaconBlockBodies`. + /// + /// If a `header` is not in the queue and has not been processed by the chain it is added to + /// the queue and it's block root is included in the output. + /// + /// If a `header` is already in the queue, but not yet processed by the chain the block root is + /// included in the output and the `inserted` time for the partial record is set to + /// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale. + pub fn enqueue_headers(&mut self, headers: Vec) -> Vec { + let mut required_bodies: Vec = vec![]; + + for header in headers { + let block_root = Hash256::from_slice(&header.hash_tree_root()[..]); + + if self.is_new_block(&block_root) { + self.insert_partial(block_root, header); + required_bodies.push(block_root) + } + } + + required_bodies + } + + fn insert_partial(&mut self, block_root: Hash256, header: BeaconBlockHeader) { + self.partials.insert( + header.block_body_root, + PartialBeaconBlock { + block_root, + header, + inserted: Instant::now(), + }, + ); + } +} + +pub struct PartialBeaconBlock { + pub block_root: Hash256, + pub header: BeaconBlockHeader, + pub inserted: Instant, +} diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index fbfb827f2..076a3f529 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -67,7 +67,16 @@ impl SyncNode { let request = self.recv_rpc_request().expect("No block root request"); match request { - RPCRequest::BeaconBlockRoots(response) => response, + RPCRequest::BeaconBlockRoots(request) => request, + _ => panic!("Did not get block root request"), + } + } + + pub fn get_block_headers_request(&self) -> BeaconBlockHeadersRequest { + let request = self.recv_rpc_request().expect("No block headers request"); + + match request { + RPCRequest::BeaconBlockHeaders(request) => request, _ => panic!("Did not get block root request"), } } @@ -164,9 +173,7 @@ impl SyncMaster { .harness .beacon_chain .get_block_roots(request.start_slot, Slot::from(request.count)) - .expect("Beacon chain did not give blocks"); - - let roots = roots + .expect("Beacon chain did not give block roots") .iter() .enumerate() .map(|(i, root)| BlockRootSlot { @@ -179,6 +186,43 @@ impl SyncMaster { self.send_rpc_response(node, response) } + pub fn respond_to_block_headers_request( + &mut self, + node: &SyncNode, + request: BeaconBlockHeadersRequest, + ) { + let roots = self + .harness + .beacon_chain + .get_block_roots(request.start_slot, Slot::from(request.max_headers)) + .expect("Beacon chain did not give blocks"); + + if roots.is_empty() { + panic!("Roots was empty when trying to get headers.") + } + + assert_eq!( + roots[0], request.start_root, + "Got the wrong start root when getting headers" + ); + + let headers: Vec = roots + .iter() + .map(|root| { + let block = self + .harness + .beacon_chain + .get_block(root) + .expect("Failed to load block") + .expect("Block did not exist"); + block.block_header() + }) + .collect(); + + let response = RPCResponse::BeaconBlockHeaders(BeaconBlockHeadersResponse { headers }); + self.send_rpc_response(node, response) + } + fn send_rpc_response(&mut self, node: &SyncNode, rpc_response: RPCResponse) { node.send(self.rpc_response(node, rpc_response)); } @@ -228,6 +272,11 @@ pub fn build_blocks(blocks: usize, master: &mut SyncMaster, nodes: &mut Vec Date: Sat, 23 Mar 2019 15:46:51 +1100 Subject: [PATCH 33/97] Updated validator config according to suggestions. - Directory structure changed slightly - Uses a filter_map instead of a for loop. - All errors reading files does not prevent others from being read. - The accounts manager needs to generate files first, with the same structure. --- account_manager/src/main.rs | 4 +- validator_client/README.md | 1 - validator_client/src/config.rs | 172 +++++++++++++++++---------------- validator_client/src/lib.rs | 2 +- validator_client/src/main.rs | 19 ++-- 5 files changed, 100 insertions(+), 98 deletions(-) diff --git a/account_manager/src/main.rs b/account_manager/src/main.rs index 03546c95b..42c78aaea 100644 --- a/account_manager/src/main.rs +++ b/account_manager/src/main.rs @@ -2,7 +2,7 @@ use bls::Keypair; use clap::{App, Arg, SubCommand}; use slog::{debug, info, o, Drain}; use std::path::PathBuf; -use validator_client::config::ValidatorClientConfig; +use validator_client::Config as ValidatorClientConfig; fn main() { // Logging @@ -31,7 +31,7 @@ fn main() { ) .get_matches(); - let config = ValidatorClientConfig::build_config(&matches) + let config = ValidatorClientConfig::parse_args(&matches, &log) .expect("Unable to build a configuration for the account manager."); // Log configuration diff --git a/validator_client/README.md b/validator_client/README.md index 109d9f317..03979fbb8 100644 --- a/validator_client/README.md +++ b/validator_client/README.md @@ -65,7 +65,6 @@ with `--datadir`. The configuration directory structure looks like: ``` ~/.lighthouse-validator -└── validators ├── 3cf4210d58ec │   └── private.key ├── 9b5d8b5be4e7 diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index d056136c9..3ca066c89 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -5,119 +5,129 @@ use std::fs; use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::PathBuf; +use slog::{debug, info, error}; use types::ChainSpec; /// Stores the core configuration for this validator instance. #[derive(Clone)] -pub struct ValidatorClientConfig { +pub struct Config { /// The data directory, which stores all validator databases pub data_dir: PathBuf, - /// The directory where the individual validator configuration directories are stored. - pub validator_dir: PathBuf, /// The server at which the Beacon Node can be contacted pub server: String, /// The chain specification that we are connecting to pub spec: ChainSpec, } -const DEFAULT_VALIDATOR_DATADIR: &str = ".lighthouse-validator"; -const DEFAULT_VALIDATORS_SUBDIR: &str = "validators"; const DEFAULT_PRIVATE_KEY_FILENAME: &str = "private.key"; -impl ValidatorClientConfig { - /// Build a new configuration from defaults, which are overrided by arguments provided. - pub fn build_config(arguments: &ArgMatches) -> Result { - // Use the specified datadir, or default in the home directory - let data_dir: PathBuf = match arguments.value_of("datadir") { - Some(path) => PathBuf::from(path.to_string()), - None => { - let home = dirs::home_dir().ok_or_else(|| { - Error::new(ErrorKind::NotFound, "Unable to determine home directory.") - })?; - home.join(DEFAULT_VALIDATOR_DATADIR) - } +impl Default for Config { + fn default() -> Self { + let data_dir = { + let home = dirs::home_dir().expect("Unable to determine home directory."); + home.join(".lighthouse-validator") }; - fs::create_dir_all(&data_dir)?; + fs::create_dir_all(&data_dir) + .unwrap_or_else(|_| panic!("Unable to create {:?}", &data_dir)); - let validator_dir = data_dir.join(DEFAULT_VALIDATORS_SUBDIR); - fs::create_dir_all(&validator_dir)?; + let server = "localhost:50051".to_string(); - let server: String = match arguments.value_of("server") { - Some(srv) => { - //TODO: I don't think this parses correctly a server & port combo - srv.parse::() - .map_err(|e| Error::new(ErrorKind::InvalidInput, e))? - .to_string() - } - None => "localhost:50051".to_string(), + let spec = ChainSpec::foundation(); + + Self { + data_dir, + server, + spec, + } + } +} + +impl Config { + /// Build a new configuration from defaults, which are overrided by arguments provided. + pub fn parse_args(args: &ArgMatches, log: &slog::Logger) -> Result { + let mut config = Config::default(); + + // Use the specified datadir, or default in the home directory + if let Some(datadir) = args.value_of("datadir") { + config.data_dir = PathBuf::from(datadir); + fs::create_dir_all(&config.data_dir) + .unwrap_or_else(|_| panic!("Unable to create {:?}", &config.data_dir)); + info!(log, "Using custom data dir: {:?}", &config.data_dir); + }; + + if let Some(srv) = args.value_of("server") { + //TODO: I don't think this parses correctly a server & port combo + config.server = srv.to_string(); + info!(log, "Using custom server: {:?}", &config.server); }; // TODO: Permit loading a custom spec from file. - let spec: ChainSpec = match arguments.value_of("spec") { - Some(spec_str) => { - match spec_str { - "foundation" => ChainSpec::foundation(), - "few_validators" => ChainSpec::few_validators(), - // Should be impossible due to clap's `possible_values(..)` function. - _ => unreachable!(), - } - } - None => ChainSpec::foundation(), + if let Some(spec_str) = args.value_of("spec") { + info!(log, "Using custom spec: {:?}", spec_str); + config.spec = match spec_str { + "foundation" => ChainSpec::foundation(), + "few_validators" => ChainSpec::few_validators(), + // Should be impossible due to clap's `possible_values(..)` function. + _ => unreachable!(), + }; }; - Ok(Self { - data_dir, - validator_dir, - server, - spec, - }) + Ok(config) } /// Try to load keys from validator_dir, returning None if none are found or an error. - pub fn fetch_keys(&self) -> Result>, Error> { - let mut validator_dirs = fs::read_dir(&self.validator_dir)?.peekable(); + pub fn fetch_keys(&self, log: &slog::Logger) -> Option> { - // There are no validator directories. - if validator_dirs.peek().is_none() { - return Ok(None); + let key_pairs: Vec = fs::read_dir(&self.data_dir) + .unwrap() + .filter_map( |validator_dir| { + + let validator_dir = validator_dir.ok()?; + + if !(validator_dir.file_type().ok()?.is_dir()) { + // Skip non-directories (i.e. no files/symlinks) + return None; + } + + let key_filename = validator_dir.path().join(DEFAULT_PRIVATE_KEY_FILENAME); + + if !(key_filename.is_file()) { + info!(log, "Private key is not a file: {:?}", key_filename.to_str()); + return None; + } + + debug!(log, "Deserializing private key from file: {:?}", key_filename.to_str()); + + let mut key_file = File::open(key_filename.clone()).ok()?; + + let key: Keypair = if let Ok(key_ok) = bincode::deserialize_from(&mut key_file) { + key_ok + } else { + error!(log, "Unable to deserialize the private key file: {:?}", key_filename); + return None; + }; + + let ki = key.identifier(); + if ki != validator_dir.file_name().into_string().ok()? { + error!(log, "The validator key ({:?}) did not match the directory filename {:?}.", ki, &validator_dir.path().to_string_lossy()); + return None; + } + Some(key) + }) + .collect(); + + // Check if it's an empty vector, and return none. + if key_pairs.is_empty() { + None + } else { + Some(key_pairs) } - let mut key_pairs: Vec = Vec::new(); - - for validator_dir_result in validator_dirs { - let validator_dir = validator_dir_result?; - - // Try to open the key file directly - // TODO skip keyfiles that are not found, and log the error instead of returning it. - let mut key_file = File::open(validator_dir.path().join(DEFAULT_PRIVATE_KEY_FILENAME))?; - - let key: Keypair = bincode::deserialize_from(&mut key_file) - .map_err(|e| Error::new(ErrorKind::InvalidData, e))?; - - // TODO skip keyfile if it's not matched, and log the error instead of returning it. - let validator_directory_name = - validator_dir.file_name().into_string().map_err(|_| { - Error::new( - ErrorKind::InvalidData, - "The filename cannot be parsed to a string.", - ) - })?; - if key.identifier() != validator_directory_name { - return Err(Error::new( - ErrorKind::InvalidData, - "The validator directory ID did not match the key found inside.", - )); - } - - key_pairs.push(key); - } - - Ok(Some(key_pairs)) } /// Saves a keypair to a file inside the appropriate validator directory. Returns the saved path filename. pub fn save_key(&self, key: &Keypair) -> Result { - let validator_config_path = self.validator_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); fs::create_dir_all(&validator_config_path)?; diff --git a/validator_client/src/lib.rs b/validator_client/src/lib.rs index 60361c051..470a070e8 100644 --- a/validator_client/src/lib.rs +++ b/validator_client/src/lib.rs @@ -1,3 +1,3 @@ pub mod config; -pub use crate::config::ValidatorClientConfig; +pub use crate::config::Config; diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 1830bd1a4..bd0e3e0c5 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -1,14 +1,14 @@ use self::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use self::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; -use crate::config::ValidatorClientConfig; +use crate::config::Config; use block_proposer::{test_utils::LocalSigner, BlockProducer}; use clap::{App, Arg}; use grpcio::{ChannelBuilder, EnvBuilder}; use protos::services_grpc::{BeaconBlockServiceClient, ValidatorServiceClient}; -use slog::{error, info, o, Drain}; +use slog::{info, o, Drain}; use slot_clock::SystemTimeSlotClock; use std::sync::Arc; -use std::{process, thread, time}; +use std::thread; mod block_producer_service; mod config; @@ -52,7 +52,7 @@ fn main() { ) .get_matches(); - let config = ValidatorClientConfig::build_config(&matches) + let config = Config::parse_args(&matches, &log) .expect("Unable to build a configuration for the validator client."); // Log configuration @@ -91,15 +91,8 @@ fn main() { let poll_interval_millis = spec.seconds_per_slot * 1000 / 10; // 10% epoch time precision. info!(log, "Starting block producer service"; "polls_per_epoch" => spec.seconds_per_slot * 1000 / poll_interval_millis); - let keypairs = config - .fetch_keys() - .expect("Encountered an error while fetching saved keys.") - .unwrap_or_else(|| { - error!(log, "No key pairs found in configuration, they must first be generated with: account_manager generate."); - // give the logger a chance to flush the error before exiting. - thread::sleep(time::Duration::from_millis(500)); - process::exit(1) - }); + let keypairs = config.fetch_keys(&log) + .expect("No key pairs found in configuration, they must first be generated with: account_manager generate."); /* * Start threads. From cc208670b2bf36cec1faa334c1eed4f89a4365a8 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Sat, 23 Mar 2019 15:52:17 +1100 Subject: [PATCH 34/97] Fixed formatting with rustfmt. --- validator_client/src/config.rs | 39 ++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 3ca066c89..e0bdaea18 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,11 +1,11 @@ use bincode; use bls::Keypair; use clap::ArgMatches; +use slog::{debug, error, info}; use std::fs; use std::fs::File; use std::io::{Error, ErrorKind}; use std::path::PathBuf; -use slog::{debug, info, error}; use types::ChainSpec; /// Stores the core configuration for this validator instance. @@ -77,11 +77,9 @@ impl Config { /// Try to load keys from validator_dir, returning None if none are found or an error. pub fn fetch_keys(&self, log: &slog::Logger) -> Option> { - let key_pairs: Vec = fs::read_dir(&self.data_dir) .unwrap() - .filter_map( |validator_dir| { - + .filter_map(|validator_dir| { let validator_dir = validator_dir.ok()?; if !(validator_dir.file_type().ok()?.is_dir()) { @@ -92,24 +90,40 @@ impl Config { let key_filename = validator_dir.path().join(DEFAULT_PRIVATE_KEY_FILENAME); if !(key_filename.is_file()) { - info!(log, "Private key is not a file: {:?}", key_filename.to_str()); + info!( + log, + "Private key is not a file: {:?}", + key_filename.to_str() + ); return None; } - debug!(log, "Deserializing private key from file: {:?}", key_filename.to_str()); + debug!( + log, + "Deserializing private key from file: {:?}", + key_filename.to_str() + ); let mut key_file = File::open(key_filename.clone()).ok()?; let key: Keypair = if let Ok(key_ok) = bincode::deserialize_from(&mut key_file) { - key_ok - } else { - error!(log, "Unable to deserialize the private key file: {:?}", key_filename); - return None; - }; + key_ok + } else { + error!( + log, + "Unable to deserialize the private key file: {:?}", key_filename + ); + return None; + }; let ki = key.identifier(); if ki != validator_dir.file_name().into_string().ok()? { - error!(log, "The validator key ({:?}) did not match the directory filename {:?}.", ki, &validator_dir.path().to_string_lossy()); + error!( + log, + "The validator key ({:?}) did not match the directory filename {:?}.", + ki, + &validator_dir.path().to_string_lossy() + ); return None; } Some(key) @@ -122,7 +136,6 @@ impl Config { } else { Some(key_pairs) } - } /// Saves a keypair to a file inside the appropriate validator directory. Returns the saved path filename. From a57a7c2394cdfdee0015dc8d6e9b3d25a85d609b Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sat, 23 Mar 2019 18:48:09 +1100 Subject: [PATCH 35/97] Implement block imports for sync --- beacon_node/beacon_chain/src/beacon_chain.rs | 24 ++- beacon_node/network/src/beacon_chain.rs | 12 +- beacon_node/network/src/message_handler.rs | 11 ++ beacon_node/network/src/sync/simple_sync.rs | 160 +++++++++++++++++-- beacon_node/network/tests/tests.rs | 41 ++++- eth2/types/src/beacon_block_header.rs | 13 ++ 6 files changed, 239 insertions(+), 22 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 33198f0a3..eb8df6f2a 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -46,6 +46,26 @@ pub enum BlockProcessingOutcome { InvalidBlock(InvalidBlock), } +impl BlockProcessingOutcome { + /// Returns `true` if the block was objectively invalid and we should disregard the peer who + /// sent it. + pub fn is_invalid(&self) -> bool { + match self { + BlockProcessingOutcome::ValidBlock(_) => false, + BlockProcessingOutcome::InvalidBlock(r) => match r { + InvalidBlock::FutureSlot => true, + InvalidBlock::StateRootMismatch => true, + InvalidBlock::ParentUnknown => false, + InvalidBlock::SlotProcessingError(_) => false, + InvalidBlock::PerBlockProcessingError(e) => match e { + BlockProcessingError::Invalid(_) => true, + BlockProcessingError::BeaconStateError(_) => false, + }, + }, + } + } +} + pub struct BeaconChain { pub block_store: Arc>, pub state_store: Arc>, @@ -685,10 +705,10 @@ where // TODO: check the block proposer signature BEFORE doing a state transition. This will // significantly lower exposure surface to DoS attacks. - // Transition the parent state to the present slot. + // Transition the parent state to the block slot. let mut state = parent_state; let previous_block_header = parent_block.block_header(); - for _ in state.slot.as_u64()..present_slot.as_u64() { + for _ in state.slot.as_u64()..block.slot.as_u64() { if let Err(e) = per_slot_processing(&mut state, &previous_block_header, &self.spec) { return Ok(BlockProcessingOutcome::InvalidBlock( InvalidBlock::SlotProcessingError(e), diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index e2829cfa6..bb4e8e71e 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -10,7 +10,7 @@ use beacon_chain::{ use eth2_libp2p::HelloMessage; use types::{BeaconBlock, BeaconStateError, Epoch, Hash256, Slot}; -pub use beacon_chain::BeaconChainError; +pub use beacon_chain::{BeaconChainError, BlockProcessingOutcome}; /// The network's API to the beacon chain. pub trait BeaconChain: Send + Sync { @@ -34,6 +34,9 @@ pub trait BeaconChain: Send + Sync { fn hello_message(&self) -> HelloMessage; + fn process_block(&self, block: BeaconBlock) + -> Result; + fn get_block_roots( &self, start_slot: Slot, @@ -98,6 +101,13 @@ where } } + fn process_block( + &self, + block: BeaconBlock, + ) -> Result { + self.process_block(block) + } + fn get_block_roots( &self, start_slot: Slot, diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 1a790eee1..2a84616e5 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -161,6 +161,17 @@ impl MessageHandler { &mut self.network_context, ) } + RPCResponse::BeaconBlockBodies(response) => { + debug!( + self.log, + "BeaconBlockBodies response received"; "peer" => format!("{:?}", peer_id) + ); + self.sync.on_beacon_block_bodies_response( + peer_id, + response, + &mut self.network_context, + ) + } // TODO: Handle all responses _ => panic!("Unknown response: {:?}", response), } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index ee0646dbb..b190f787f 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -3,12 +3,12 @@ use crate::message_handler::NetworkContext; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse}; use eth2_libp2p::PeerId; -use slog::{debug, error, o, warn}; +use slog::{debug, error, info, o, warn}; use ssz::TreeHash; use std::collections::HashMap; use std::sync::Arc; -use std::time::Instant; -use types::{BeaconBlockHeader, Epoch, Hash256, Slot}; +use std::time::{Duration, Instant}; +use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; @@ -102,7 +102,11 @@ pub struct SimpleSync { impl SimpleSync { pub fn new(beacon_chain: Arc, log: &slog::Logger) -> Self { let sync_logger = log.new(o!("Service"=> "Sync")); - let import_queue = ImportQueue::new(beacon_chain.clone(), log.clone()); + + let queue_item_stale_time = Duration::from_secs(600); + + let import_queue = + ImportQueue::new(beacon_chain.clone(), queue_item_stale_time, log.clone()); SimpleSync { chain: beacon_chain.clone(), known_peers: HashMap::new(), @@ -229,13 +233,72 @@ impl SimpleSync { return; } - let block_roots = self.import_queue.enqueue_headers(response.headers); + let block_roots = self + .import_queue + .enqueue_headers(response.headers, peer_id.clone()); if !block_roots.is_empty() { self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); } } + pub fn on_beacon_block_bodies_response( + &mut self, + peer_id: PeerId, + response: BeaconBlockBodiesResponse, + network: &mut NetworkContext, + ) { + self.import_queue + .enqueue_bodies(response.block_bodies, peer_id.clone()); + self.process_import_queue(network); + } + + pub fn process_import_queue(&mut self, network: &mut NetworkContext) { + let mut blocks: Vec<(Hash256, BeaconBlock, PeerId)> = self + .import_queue + .partials + .iter() + .filter_map(|(key, partial)| { + if let Some(_) = partial.body { + let (block, _root) = partial.clone().complete().expect("Body must be Some"); + Some((*key, block, partial.sender.clone())) + } else { + None + } + }) + .collect(); + + // Sort the blocks to be in ascending slot order. + blocks.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); + + let mut imported_keys = vec![]; + + for (key, block, sender) in blocks { + match self.chain.process_block(block) { + Ok(outcome) => { + if outcome.is_invalid() { + warn!(self.log, "Invalid block: {:?}", outcome); + network.disconnect(sender); + } else { + imported_keys.push(key) + } + } + Err(e) => { + error!(self.log, "Error during block processing"; "error" => format!("{:?}", e)) + } + } + } + + println!("imported_keys.len: {:?}", imported_keys.len()); + + if !imported_keys.is_empty() { + info!(self.log, "Imported {} blocks", imported_keys.len()); + for key in imported_keys { + self.import_queue.partials.remove(&key); + } + } + } + fn request_block_roots( &mut self, peer_id: PeerId, @@ -298,19 +361,41 @@ pub struct ImportQueue { pub chain: Arc, /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. pub partials: HashMap, + /// Time before a queue entry is consider state. + pub stale_time: Duration, /// Logging log: slog::Logger, } impl ImportQueue { - pub fn new(chain: Arc, log: slog::Logger) -> Self { + pub fn new(chain: Arc, stale_time: Duration, log: slog::Logger) -> Self { Self { chain, partials: HashMap::new(), + stale_time, log, } } + pub fn remove_stale(&mut self) { + let keys: Vec = self + .partials + .iter() + .filter_map(|(key, partial)| { + if partial.inserted + self.stale_time >= Instant::now() { + Some(*key) + } else { + None + } + }) + .collect(); + + keys.iter().for_each(|key| { + self.partials.remove(&key); + }); + } + + /// Returns `true` if `self.chain` has not yet processed this block. fn is_new_block(&self, block_root: &Hash256) -> bool { self.chain .is_new_block_root(&block_root) @@ -322,9 +407,6 @@ impl ImportQueue { /// Returns the index of the first new root in the list of block roots. pub fn first_new_root(&mut self, roots: &[BlockRootSlot]) -> Option { - for root in roots { - println!("root {}", root.block_root); - } roots .iter() .position(|brs| self.is_new_block(&brs.block_root)) @@ -339,14 +421,18 @@ impl ImportQueue { /// If a `header` is already in the queue, but not yet processed by the chain the block root is /// included in the output and the `inserted` time for the partial record is set to /// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale. - pub fn enqueue_headers(&mut self, headers: Vec) -> Vec { + pub fn enqueue_headers( + &mut self, + headers: Vec, + sender: PeerId, + ) -> Vec { let mut required_bodies: Vec = vec![]; for header in headers { let block_root = Hash256::from_slice(&header.hash_tree_root()[..]); if self.is_new_block(&block_root) { - self.insert_partial(block_root, header); + self.insert_header(block_root, header, sender.clone()); required_bodies.push(block_root) } } @@ -354,20 +440,60 @@ impl ImportQueue { required_bodies } - fn insert_partial(&mut self, block_root: Hash256, header: BeaconBlockHeader) { - self.partials.insert( - header.block_body_root, - PartialBeaconBlock { + /// If there is a matching `header` for this `body`, adds it to the queue. + /// + /// If there is no `header` for the `body`, the body is simply discarded. + pub fn enqueue_bodies(&mut self, bodies: Vec, sender: PeerId) { + for body in bodies { + self.insert_body(body, sender.clone()); + } + } + + /// Inserts a header to the queue. + /// + /// If the header already exists, the `inserted` time is set to `now` and not other + /// modifications are made. + fn insert_header(&mut self, block_root: Hash256, header: BeaconBlockHeader, sender: PeerId) { + self.partials + .entry(header.block_body_root) + .and_modify(|p| p.inserted = Instant::now()) + .or_insert(PartialBeaconBlock { block_root, header, + body: None, inserted: Instant::now(), - }, - ); + sender, + }); + } + + /// Updates an existing partial with the `body`. + /// + /// If there is no header for the `body`, the body is simply discarded. + fn insert_body(&mut self, body: BeaconBlockBody, sender: PeerId) { + let body_root = Hash256::from_slice(&body.hash_tree_root()[..]); + + self.partials.entry(body_root).and_modify(|p| { + if body_root == p.header.block_body_root { + p.body = Some(body); + p.inserted = Instant::now(); + p.sender = sender; + } + }); } } +#[derive(Clone, Debug)] pub struct PartialBeaconBlock { pub block_root: Hash256, pub header: BeaconBlockHeader, + pub body: Option, pub inserted: Instant, + pub sender: PeerId, +} + +impl PartialBeaconBlock { + /// Given a `body`, consumes `self` and returns a complete `BeaconBlock` along with its root. + pub fn complete(self) -> Option<(BeaconBlock, Hash256)> { + Some((self.header.into_block(self.body?), self.block_root)) + } } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index 076a3f529..57587717b 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -77,7 +77,16 @@ impl SyncNode { match request { RPCRequest::BeaconBlockHeaders(request) => request, - _ => panic!("Did not get block root request"), + _ => panic!("Did not get block headers request"), + } + } + + pub fn get_block_bodies_request(&self) -> BeaconBlockBodiesRequest { + let request = self.recv_rpc_request().expect("No block bodies request"); + + match request { + RPCRequest::BeaconBlockBodies(request) => request, + _ => panic!("Did not get block bodies request"), } } @@ -223,6 +232,29 @@ impl SyncMaster { self.send_rpc_response(node, response) } + pub fn respond_to_block_bodies_request( + &mut self, + node: &SyncNode, + request: BeaconBlockBodiesRequest, + ) { + let block_bodies: Vec = request + .block_roots + .iter() + .map(|root| { + let block = self + .harness + .beacon_chain + .get_block(root) + .expect("Failed to load block") + .expect("Block did not exist"); + block.body + }) + .collect(); + + let response = RPCResponse::BeaconBlockBodies(BeaconBlockBodiesResponse { block_bodies }); + self.send_rpc_response(node, response) + } + fn send_rpc_response(&mut self, node: &SyncNode, rpc_response: RPCResponse) { node.send(self.rpc_response(node, rpc_response)); } @@ -311,6 +343,11 @@ fn first_test() { master.respond_to_block_headers_request(&nodes[0], headers_request); - std::thread::sleep(Duration::from_millis(500)); + let bodies_request = nodes[0].get_block_bodies_request(); + assert_eq!(bodies_request.block_roots.len(), 2); + + master.respond_to_block_bodies_request(&nodes[0], bodies_request); + + std::thread::sleep(Duration::from_millis(10000)); runtime.shutdown_now(); } diff --git a/eth2/types/src/beacon_block_header.rs b/eth2/types/src/beacon_block_header.rs index 3d8b08cc8..f4bee27e1 100644 --- a/eth2/types/src/beacon_block_header.rs +++ b/eth2/types/src/beacon_block_header.rs @@ -37,6 +37,19 @@ impl BeaconBlockHeader { pub fn canonical_root(&self) -> Hash256 { Hash256::from_slice(&self.hash_tree_root()[..]) } + + /// Given a `body`, consumes `self` and returns a complete `BeaconBlock`. + /// + /// Spec v0.5.0 + pub fn into_block(self, body: BeaconBlockBody) -> BeaconBlock { + BeaconBlock { + slot: self.slot, + previous_block_root: self.previous_block_root, + state_root: self.state_root, + body, + signature: self.signature, + } + } } #[cfg(test)] From 18493a4df4e5ab6569214c8af376269ce3db0d6b Mon Sep 17 00:00:00 2001 From: Age Manning Date: Sun, 24 Mar 2019 09:24:50 +1100 Subject: [PATCH 36/97] Adds microsecond duration to validator client --- validator_client/src/service.rs | 40 +++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 322c370b5..49acd8ad2 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -39,8 +39,8 @@ pub struct Service { slot_clock: Arc, /// The current slot we are processing. current_slot: Slot, - /// Seconds until the next slot. This is used for initializing the tokio timer interval. - seconds_to_next_slot: Duration, + /// Micro seconds until the next slot. This is used for initializing the tokio timer interval. + micros_to_next_slot: Duration, // GRPC Clients /// The beacon block GRPC client. beacon_block_client: Arc, @@ -82,6 +82,7 @@ impl Service { // build requisite objects to form Self let genesis_time = node_info.get_genesis_time(); + let genesis_time = 1_549_935_547; info!(log,"Beacon node connected"; "Node Version" => node_info.version.clone(), "Chain ID" => node_info.chain_id, "Genesis time" => genesis_time); @@ -127,28 +128,45 @@ impl Service { let current_slot = slot_clock.present_slot().unwrap().unwrap().sub(1); // calculate seconds to the next slot - let seconds_to_next_slot = { + let micros_to_next_slot = { let syslot_time = SystemTime::now(); let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let mut secs_to_slot = None; + debug!(log, "Duration since unix epoch {:?}", duration_since_epoch); + let mut micros_to_slot = None; if let Some(duration_since_genesis) = duration_since_epoch.checked_sub(Duration::from_secs(genesis_time)) { // seconds till next slot - secs_to_slot = duration_since_genesis + debug!(log, "Genesis Time {:?}", genesis_time); + debug!(log, "Duration since genesis {:?}", duration_since_genesis); + micros_to_slot = duration_since_genesis .as_secs() .checked_rem(config.spec.seconds_per_slot); } - secs_to_slot.unwrap_or_else(|| 0) + micros_to_slot.unwrap_or_else(|| 0) + /* + let duration_to_slot = duration_since_genesis + .checked_sub(Duration::from( + duration_since_genesis + .checked_div(config.spec.seconds_per_slot as u64) + .unwrap() + .as_secs() + .checked_mul(config.spec.seconds_per_slot) + .unwrap(), + )) + .unwrap(); + */ }; + info!(log, ""; "Micro Seconds to next slot"=>micros_to_next_slot); + Self { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, slot_clock, current_slot, - seconds_to_next_slot: Duration::from_secs(seconds_to_next_slot), + micros_to_next_slot: Duration::from_micros(micros_to_next_slot), beacon_block_client, validator_client, attester_client, @@ -176,7 +194,7 @@ impl Service { // Set the interval to start at the next slot, and every slot after let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); //TODO: Handle checked add correctly - Interval::new(Instant::now() + service.seconds_to_next_slot, slot_duration) + Interval::new(Instant::now() + service.micros_to_next_slot, slot_duration) }; // kick off core service @@ -200,7 +218,11 @@ impl Service { runtime.block_on(interval.for_each(move |_| { // update duties - debug!(service.log, "Processing new slot..."); + debug!( + service.log, + "Processing slot: {}", + service.slot_clock.present_slot().unwrap().unwrap().as_u64() + ); manager.poll(); Ok(()) })); From 3eae7b3fc5258fa611ecab23aa3dc8d72f4e8fb9 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 12:49:59 +1100 Subject: [PATCH 37/97] Add skip slot support to BeaconChain fns --- beacon_node/beacon_chain/src/beacon_chain.rs | 87 ++++++++++++++------ beacon_node/network/src/beacon_chain.rs | 41 +++++++-- 2 files changed, 97 insertions(+), 31 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index eb8df6f2a..d5fd113a8 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -142,7 +142,38 @@ where }) } - /// Returns beacon block roots for `count` slots, starting from `start_slot`. + /// Returns the beacon block body for each beacon block root in `roots`. + /// + /// Fails if any root in `roots` does not have a corresponding block. + pub fn get_block_bodies(&self, roots: &[Hash256]) -> Result, Error> { + let bodies: Result, _> = roots + .iter() + .map(|root| match self.get_block(root)? { + Some(block) => Ok(block.body), + None => Err(Error::DBInconsistent("Missing block".into())), + }) + .collect(); + + Ok(bodies?) + } + + /// Returns the beacon block header for each beacon block root in `roots`. + /// + /// Fails if any root in `roots` does not have a corresponding block. + pub fn get_block_headers(&self, roots: &[Hash256]) -> Result, Error> { + let headers: Result, _> = roots + .iter() + .map(|root| match self.get_block(root)? { + Some(block) => Ok(block.block_header()), + None => Err(Error::DBInconsistent("Missing block".into())), + }) + .collect(); + + Ok(headers?) + } + + /// Returns `count `beacon block roots, starting from `start_slot` with an + /// interval of `skip` slots between each root. /// /// ## Errors: /// @@ -152,40 +183,45 @@ where /// - Other: BeaconState` is inconsistent. pub fn get_block_roots( &self, - start_slot: Slot, - count: Slot, - ) -> Result, BeaconStateError> { + earliest_slot: Slot, + count: usize, + skip: usize, + ) -> Result, Error> { let spec = &self.spec; + let step_by = Slot::from(skip + 1); let mut roots: Vec = vec![]; + + // The state for reading block roots. Will be updated with an older state if slots go too + // far back in history. let mut state = self.state.read().clone(); - let mut slot = start_slot + count - 1; + + // The final slot in this series, will be reduced by `skip` each loop iteration. + let mut slot = earliest_slot + Slot::from(count * (skip + 1)) - 1; + + // If the highest slot requested is that of the current state insert the root of the + // head block, unless the head block's slot is not matching. + if slot == state.slot && self.head().beacon_block.slot == slot { + roots.push(self.head().beacon_block_root); + + slot -= step_by; + } else if slot >= state.slot { + return Err(BeaconStateError::SlotOutOfBounds.into()); + } loop { - // If the highest slot requested is that of the current state insert the root of the - // head block, unless the head block's slot is not matching. - if slot == state.slot && self.head().beacon_block.slot == slot { - roots.push(self.head().beacon_block_root); - - slot -= 1; - continue; - } else if slot >= state.slot { - return Err(BeaconStateError::SlotOutOfBounds); - } - // If the slot is within the range of the current state's block roots, append the root // to the output vec. // - // If we get `SlotOutOfBounds` error, load the oldest known state to the present state - // from the DB. + // If we get `SlotOutOfBounds` error, load the oldest available historic + // state from the DB. match state.get_block_root(slot, spec) { Ok(root) => { - roots.push(*root); - - if slot == start_slot { + if slot < earliest_slot { break; } else { - slot -= 1; + roots.push(*root); + slot -= step_by; } } Err(BeaconStateError::SlotOutOfBounds) => { @@ -201,18 +237,19 @@ where _ => break, } } - Err(e) => return Err(e), + Err(e) => return Err(e.into()), }; } - if (slot == start_slot) && (roots.len() == count.as_usize()) { + // Return the results if they pass a sanity check. + if (slot <= earliest_slot) && (roots.len() == count) { // Reverse the ordering of the roots. We extracted them in reverse order to make it // simpler to lookup historic states. // // This is a potential optimisation target. Ok(roots.iter().rev().cloned().collect()) } else { - Err(BeaconStateError::SlotOutOfBounds) + Err(BeaconStateError::SlotOutOfBounds.into()) } } diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index bb4e8e71e..cc54e8ae0 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -8,7 +8,7 @@ use beacon_chain::{ CheckPoint, }; use eth2_libp2p::HelloMessage; -use types::{BeaconBlock, BeaconStateError, Epoch, Hash256, Slot}; +use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; pub use beacon_chain::{BeaconChainError, BlockProcessingOutcome}; @@ -40,8 +40,19 @@ pub trait BeaconChain: Send + Sync { fn get_block_roots( &self, start_slot: Slot, - count: Slot, - ) -> Result, BeaconStateError>; + count: usize, + skip: usize, + ) -> Result, BeaconChainError>; + + fn get_block_headers( + &self, + start_slot: Slot, + count: usize, + skip: usize, + ) -> Result, BeaconChainError>; + + fn get_block_bodies(&self, roots: &[Hash256]) + -> Result, BeaconChainError>; fn is_new_block_root(&self, beacon_block_root: &Hash256) -> Result; } @@ -111,9 +122,27 @@ where fn get_block_roots( &self, start_slot: Slot, - count: Slot, - ) -> Result, BeaconStateError> { - self.get_block_roots(start_slot, count) + count: usize, + skip: usize, + ) -> Result, BeaconChainError> { + self.get_block_roots(start_slot, count, skip) + } + + fn get_block_headers( + &self, + start_slot: Slot, + count: usize, + skip: usize, + ) -> Result, BeaconChainError> { + let roots = self.get_block_roots(start_slot, count, skip)?; + self.get_block_headers(&roots) + } + + fn get_block_bodies( + &self, + roots: &[Hash256], + ) -> Result, BeaconChainError> { + self.get_block_bodies(roots) } fn is_new_block_root(&self, beacon_block_root: &Hash256) -> Result { From 6b39c693af28675c488202ad8def2980fb3c772d Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 12:50:23 +1100 Subject: [PATCH 38/97] Extend syncing --- beacon_node/network/src/message_handler.rs | 49 ++--- beacon_node/network/src/sync/simple_sync.rs | 158 ++++++++++++++-- beacon_node/network/tests/tests.rs | 196 +++++++++++++++++++- 3 files changed, 364 insertions(+), 39 deletions(-) diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 2a84616e5..58ba0171d 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -113,10 +113,24 @@ impl MessageHandler { match request { RPCRequest::Hello(hello_message) => { self.sync - .on_hello(peer_id, hello_message, &mut self.network_context) + .on_hello_request(peer_id, hello_message, &mut self.network_context) } + RPCRequest::BeaconBlockRoots(request) => { + self.sync + .on_beacon_block_roots_request(peer_id, request, &mut self.network_context) + } + RPCRequest::BeaconBlockHeaders(request) => self.sync.on_beacon_block_headers_request( + peer_id, + request, + &mut self.network_context, + ), + RPCRequest::BeaconBlockBodies(request) => self.sync.on_beacon_block_bodies_request( + peer_id, + request, + &mut self.network_context, + ), // TODO: Handle all requests - _ => {} + _ => panic!("Unknown request: {:?}", request), } } @@ -133,48 +147,41 @@ impl MessageHandler { debug!(self.log, "Unrecognized response from peer: {:?}", peer_id); return; } - match response { + let response_str = match response { RPCResponse::Hello(hello_message) => { - debug!(self.log, "Hello response received from peer: {:?}", peer_id); self.sync - .on_hello(peer_id, hello_message, &mut self.network_context); + .on_hello_response(peer_id, hello_message, &mut self.network_context); + "Hello" } RPCResponse::BeaconBlockRoots(response) => { - debug!( - self.log, - "BeaconBlockRoots response received"; "peer" => format!("{:?}", peer_id) - ); self.sync.on_beacon_block_roots_response( peer_id, response, &mut self.network_context, - ) + ); + "BeaconBlockRoots" } RPCResponse::BeaconBlockHeaders(response) => { - debug!( - self.log, - "BeaconBlockHeaders response received"; "peer" => format!("{:?}", peer_id) - ); self.sync.on_beacon_block_headers_response( peer_id, response, &mut self.network_context, - ) + ); + "BeaconBlockHeaders" } RPCResponse::BeaconBlockBodies(response) => { - debug!( - self.log, - "BeaconBlockBodies response received"; "peer" => format!("{:?}", peer_id) - ); self.sync.on_beacon_block_bodies_response( peer_id, response, &mut self.network_context, - ) + ); + "BeaconBlockBodies" } // TODO: Handle all responses _ => panic!("Unknown response: {:?}", response), - } + }; + + debug!(self.log, "RPCResponse"; "type" => response_str); } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index b190f787f..4726419d5 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -126,14 +126,31 @@ impl SimpleSync { hello: HelloMessage, network: &mut NetworkContext, ) { + // Say hello back. network.send_rpc_response( peer_id.clone(), RPCResponse::Hello(self.chain.hello_message()), ); - self.on_hello(peer_id, hello, network); + + self.process_hello(peer_id, hello, network); } - pub fn on_hello(&mut self, peer_id: PeerId, hello: HelloMessage, network: &mut NetworkContext) { + pub fn on_hello_response( + &mut self, + peer_id: PeerId, + hello: HelloMessage, + network: &mut NetworkContext, + ) { + // Process the hello message, without sending back another hello. + self.process_hello(peer_id, hello, network); + } + + fn process_hello( + &mut self, + peer_id: PeerId, + hello: HelloMessage, + network: &mut NetworkContext, + ) { let spec = self.chain.get_spec(); let remote = PeerSyncInfo::from(hello); @@ -142,7 +159,7 @@ impl SimpleSync { // network id must match if remote_status != PeerStatus::OnDifferentChain { - debug!(self.log, "Handshake successful. Peer: {:?}", peer_id); + info!(self.log, "HandshakeSuccess"; "peer" => format!("{:?}", peer_id)); self.known_peers.insert(peer_id.clone(), remote); } @@ -183,6 +200,44 @@ impl SimpleSync { } } + pub fn on_beacon_block_roots_request( + &mut self, + peer_id: PeerId, + request: BeaconBlockRootsRequest, + network: &mut NetworkContext, + ) { + let roots = match self + .chain + .get_block_roots(request.start_slot, request.count as usize, 0) + { + Ok(roots) => roots, + Err(e) => { + // TODO: return RPC error. + warn!( + self.log, + "RPCRequest"; "peer" => format!("{:?}", peer_id), + "request" => "BeaconBlockRoots", + "error" => format!("{:?}", e) + ); + return; + } + }; + + let roots = roots + .iter() + .enumerate() + .map(|(i, &block_root)| BlockRootSlot { + slot: request.start_slot + Slot::from(i), + block_root, + }) + .collect(); + + network.send_rpc_response( + peer_id, + RPCResponse::BeaconBlockRoots(BeaconBlockRootsResponse { roots }), + ) + } + pub fn on_beacon_block_roots_response( &mut self, peer_id: PeerId, @@ -219,6 +274,36 @@ impl SimpleSync { } } + pub fn on_beacon_block_headers_request( + &mut self, + peer_id: PeerId, + request: BeaconBlockHeadersRequest, + network: &mut NetworkContext, + ) { + let headers = match self.chain.get_block_headers( + request.start_slot, + request.max_headers as usize, + request.skip_slots as usize, + ) { + Ok(headers) => headers, + Err(e) => { + // TODO: return RPC error. + warn!( + self.log, + "RPCRequest"; "peer" => format!("{:?}", peer_id), + "request" => "BeaconBlockHeaders", + "error" => format!("{:?}", e) + ); + return; + } + }; + + network.send_rpc_response( + peer_id, + RPCResponse::BeaconBlockHeaders(BeaconBlockHeadersResponse { headers }), + ) + } + pub fn on_beacon_block_headers_response( &mut self, peer_id: PeerId, @@ -237,9 +322,33 @@ impl SimpleSync { .import_queue .enqueue_headers(response.headers, peer_id.clone()); - if !block_roots.is_empty() { - self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); - } + self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); + } + + pub fn on_beacon_block_bodies_request( + &mut self, + peer_id: PeerId, + request: BeaconBlockBodiesRequest, + network: &mut NetworkContext, + ) { + let block_bodies = match self.chain.get_block_bodies(&request.block_roots) { + Ok(bodies) => bodies, + Err(e) => { + // TODO: return RPC error. + warn!( + self.log, + "RPCRequest"; "peer" => format!("{:?}", peer_id), + "request" => "BeaconBlockBodies", + "error" => format!("{:?}", e) + ); + return; + } + }; + + network.send_rpc_response( + peer_id, + RPCResponse::BeaconBlockBodies(BeaconBlockBodiesResponse { block_bodies }), + ) } pub fn on_beacon_block_bodies_response( @@ -250,6 +359,11 @@ impl SimpleSync { ) { self.import_queue .enqueue_bodies(response.block_bodies, peer_id.clone()); + + // Clear out old entries + self.import_queue.remove_stale(); + + // Import blocks, if possible. self.process_import_queue(network); } @@ -268,10 +382,14 @@ impl SimpleSync { }) .collect(); + if !blocks.is_empty() { + info!(self.log, "Processing blocks"; "count" => blocks.len()); + } + // Sort the blocks to be in ascending slot order. blocks.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); - let mut imported_keys = vec![]; + let mut keys_to_delete = vec![]; for (key, block, sender) in blocks { match self.chain.process_block(block) { @@ -279,8 +397,10 @@ impl SimpleSync { if outcome.is_invalid() { warn!(self.log, "Invalid block: {:?}", outcome); network.disconnect(sender); + keys_to_delete.push(key) } else { - imported_keys.push(key) + // TODO: don't delete if was not invalid but not successfully processed. + keys_to_delete.push(key) } } Err(e) => { @@ -289,11 +409,9 @@ impl SimpleSync { } } - println!("imported_keys.len: {:?}", imported_keys.len()); - - if !imported_keys.is_empty() { - info!(self.log, "Imported {} blocks", imported_keys.len()); - for key in imported_keys { + if !keys_to_delete.is_empty() { + info!(self.log, "Processed {} blocks", keys_to_delete.len()); + for key in keys_to_delete { self.import_queue.partials.remove(&key); } } @@ -313,7 +431,10 @@ impl SimpleSync { debug!( self.log, - "Requesting {} block roots from {:?}.", request.count, &peer_id + "RPCRequest"; + "type" => "BeaconBlockRoots", + "count" => request.count, + "peer" => format!("{:?}", peer_id) ); // TODO: handle count > max count. @@ -328,7 +449,10 @@ impl SimpleSync { ) { debug!( self.log, - "Requesting {} headers from {:?}.", request.max_headers, &peer_id + "RPCRequest"; + "type" => "BeaconBlockHeaders", + "max_headers" => request.max_headers, + "peer" => format!("{:?}", peer_id) ); network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockHeaders(request)); @@ -377,6 +501,10 @@ impl ImportQueue { } } + /// Flushes all stale entries from the queue. + /// + /// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the + /// past. pub fn remove_stale(&mut self) { let keys: Vec = self .partials diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index 57587717b..b951d7d2a 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -17,6 +17,7 @@ pub struct SyncNode { pub id: usize, sender: Sender, receiver: Receiver, + peer_id: PeerId, harness: BeaconChainHarness, } @@ -43,6 +44,7 @@ impl SyncNode { id, sender: message_handler_sender, receiver: network_receiver, + peer_id: PeerId::random(), harness, } } @@ -63,6 +65,138 @@ impl SyncNode { self.harness.beacon_chain.hello_message() } + pub fn connect_to(&mut self, node: &SyncNode) { + let message = HandlerMessage::PeerDialed(self.peer_id.clone()); + node.send(message); + } + + /// Reads the receive queue from one node and passes the message to the other. Also returns a + /// copy of the message. + /// + /// self -----> node + /// | + /// us + /// + /// Named after the unix `tee` command. + fn tee(&mut self, node: &SyncNode) -> NetworkMessage { + let network_message = self.recv().expect("Timeout on tee"); + + let handler_message = match network_message.clone() { + NetworkMessage::Send(peer_id, OutgoingMessage::RPC(event)) => { + HandlerMessage::RPC(peer_id, event) + } + _ => panic!("tee cannot parse {:?}", network_message), + }; + + node.send(handler_message); + + network_message + } + + fn tee_hello_request(&mut self, node: &SyncNode) -> HelloMessage { + let request = self.tee_rpc_request(node); + + match request { + RPCRequest::Hello(message) => message, + _ => panic!("tee_hello_request got: {:?}", request), + } + } + + fn tee_hello_response(&mut self, node: &SyncNode) -> HelloMessage { + let response = self.tee_rpc_response(node); + + match response { + RPCResponse::Hello(message) => message, + _ => panic!("tee_hello_response got: {:?}", response), + } + } + + fn tee_block_root_request(&mut self, node: &SyncNode) -> BeaconBlockRootsRequest { + let msg = self.tee_rpc_request(node); + + match msg { + RPCRequest::BeaconBlockRoots(data) => data, + _ => panic!("tee_block_root_request got: {:?}", msg), + } + } + + fn tee_block_root_response(&mut self, node: &SyncNode) -> BeaconBlockRootsResponse { + let msg = self.tee_rpc_response(node); + + match msg { + RPCResponse::BeaconBlockRoots(data) => data, + _ => panic!("tee_block_root_response got: {:?}", msg), + } + } + + fn tee_block_header_request(&mut self, node: &SyncNode) -> BeaconBlockHeadersRequest { + let msg = self.tee_rpc_request(node); + + match msg { + RPCRequest::BeaconBlockHeaders(data) => data, + _ => panic!("tee_block_header_request got: {:?}", msg), + } + } + + fn tee_block_header_response(&mut self, node: &SyncNode) -> BeaconBlockHeadersResponse { + let msg = self.tee_rpc_response(node); + + match msg { + RPCResponse::BeaconBlockHeaders(data) => data, + _ => panic!("tee_block_header_response got: {:?}", msg), + } + } + + fn tee_block_body_request(&mut self, node: &SyncNode) -> BeaconBlockBodiesRequest { + let msg = self.tee_rpc_request(node); + + match msg { + RPCRequest::BeaconBlockBodies(data) => data, + _ => panic!("tee_block_body_request got: {:?}", msg), + } + } + + fn tee_block_body_response(&mut self, node: &SyncNode) -> BeaconBlockBodiesResponse { + let msg = self.tee_rpc_response(node); + + match msg { + RPCResponse::BeaconBlockBodies(data) => data, + _ => panic!("tee_block_body_response got: {:?}", msg), + } + } + + fn tee_rpc_request(&mut self, node: &SyncNode) -> RPCRequest { + let network_message = self.tee(node); + + match network_message { + NetworkMessage::Send( + _peer_id, + OutgoingMessage::RPC(RPCEvent::Request { + id: _, + method_id: _, + body, + }), + ) => body, + _ => panic!("tee_rpc_request failed! got {:?}", network_message), + } + } + + fn tee_rpc_response(&mut self, node: &SyncNode) -> RPCResponse { + let network_message = self.tee(node); + + match network_message { + NetworkMessage::Send( + _peer_id, + OutgoingMessage::RPC(RPCEvent::Response { + id: _, + method_id: _, + result, + }), + ) => result, + _ => panic!("tee_rpc_response failed! got {:?}", network_message), + } + } + pub fn get_block_root_request(&self) -> BeaconBlockRootsRequest { let request = self.recv_rpc_request().expect("No block root request"); @@ -181,7 +315,7 @@ impl SyncMaster { let roots = self .harness .beacon_chain - .get_block_roots(request.start_slot, Slot::from(request.count)) + .get_block_roots(request.start_slot, request.count as usize, 0) .expect("Beacon chain did not give block roots") .iter() .enumerate() @@ -203,7 +337,11 @@ impl SyncMaster { let roots = self .harness .beacon_chain - .get_block_roots(request.start_slot, Slot::from(request.max_headers)) + .get_block_roots( + request.start_slot, + request.max_headers as usize, + request.skip_slots as usize, + ) .expect("Beacon chain did not give blocks"); if roots.is_empty() { @@ -312,7 +450,7 @@ pub fn build_blocks(blocks: usize, master: &mut SyncMaster, nodes: &mut Vec Date: Sun, 24 Mar 2019 13:06:17 +1100 Subject: [PATCH 39/97] Tidy logging, fix bug with stale time in queue --- beacon_node/network/src/message_handler.rs | 2 +- beacon_node/network/src/sync/simple_sync.rs | 34 +++++++++++++++------ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 58ba0171d..24fe04950 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -181,7 +181,7 @@ impl MessageHandler { _ => panic!("Unknown response: {:?}", response), }; - debug!(self.log, "RPCResponse"; "type" => response_str); + debug!(self.log, "RPCResponse({})", response_str); } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 4726419d5..ff6092be1 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -13,6 +13,9 @@ use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slo /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; +/// The amount of seconds a block (or partial block) may exist in the import queue. +const QUEUE_STALE_SECS: u64 = 60; + /// Keeps track of syncing information for known connected peers. #[derive(Clone, Copy, Debug)] pub struct PeerSyncInfo { @@ -103,7 +106,7 @@ impl SimpleSync { pub fn new(beacon_chain: Arc, log: &slog::Logger) -> Self { let sync_logger = log.new(o!("Service"=> "Sync")); - let queue_item_stale_time = Duration::from_secs(600); + let queue_item_stale_time = Duration::from_secs(QUEUE_STALE_SECS); let import_queue = ImportQueue::new(beacon_chain.clone(), queue_item_stale_time, log.clone()); @@ -165,7 +168,11 @@ impl SimpleSync { match remote_status { PeerStatus::OnDifferentChain => { - debug!(self.log, "Peer is on different chain. Peer: {:?}", peer_id); + info!( + self.log, "Failure"; + "peer" => format!("{:?}", peer_id), + "reason" => "network_id" + ); network.disconnect(peer_id); } @@ -431,8 +438,7 @@ impl SimpleSync { debug!( self.log, - "RPCRequest"; - "type" => "BeaconBlockRoots", + "RPCRequest(BeaconBlockRoots)"; "count" => request.count, "peer" => format!("{:?}", peer_id) ); @@ -449,8 +455,7 @@ impl SimpleSync { ) { debug!( self.log, - "RPCRequest"; - "type" => "BeaconBlockHeaders", + "RPCRequest(BeaconBlockHeaders)"; "max_headers" => request.max_headers, "peer" => format!("{:?}", peer_id) ); @@ -466,9 +471,9 @@ impl SimpleSync { ) { debug!( self.log, - "Requesting {} bodies from {:?}.", - request.block_roots.len(), - &peer_id + "RPCRequest(BeaconBlockBodies)"; + "count" => request.block_roots.len(), + "peer" => format!("{:?}", peer_id) ); network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockBodies(request)); @@ -510,7 +515,7 @@ impl ImportQueue { .partials .iter() .filter_map(|(key, partial)| { - if partial.inserted + self.stale_time >= Instant::now() { + if partial.inserted + self.stale_time <= Instant::now() { Some(*key) } else { None @@ -518,6 +523,15 @@ impl ImportQueue { }) .collect(); + if !keys.is_empty() { + debug!( + self.log, + "ImportQueue removing stale entries"; + "stale_count" => keys.len(), + "stale_time_seconds" => self.stale_time.as_secs() + ); + } + keys.iter().for_each(|key| { self.partials.remove(&key); }); From 15f853416bab576ef9c21e2813e52b8b6c7031e9 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 13:59:27 +1100 Subject: [PATCH 40/97] Add more detail to sync logs --- beacon_node/network/src/message_handler.rs | 13 +-- beacon_node/network/src/sync/simple_sync.rs | 114 ++++++++++++++------ 2 files changed, 85 insertions(+), 42 deletions(-) diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 24fe04950..77a2ab8db 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -8,8 +8,7 @@ use eth2_libp2p::{ PeerId, RPCEvent, }; use futures::future; -use slog::debug; -use slog::warn; +use slog::{debug, warn}; use std::collections::HashMap; use std::sync::Arc; use std::time::Instant; @@ -144,14 +143,13 @@ impl MessageHandler { .remove(&(peer_id.clone(), id)) .is_none() { - debug!(self.log, "Unrecognized response from peer: {:?}", peer_id); + debug!(self.log, "Unrecognised response from peer: {:?}", peer_id); return; } - let response_str = match response { + match response { RPCResponse::Hello(hello_message) => { self.sync .on_hello_response(peer_id, hello_message, &mut self.network_context); - "Hello" } RPCResponse::BeaconBlockRoots(response) => { self.sync.on_beacon_block_roots_response( @@ -159,7 +157,6 @@ impl MessageHandler { response, &mut self.network_context, ); - "BeaconBlockRoots" } RPCResponse::BeaconBlockHeaders(response) => { self.sync.on_beacon_block_headers_response( @@ -167,7 +164,6 @@ impl MessageHandler { response, &mut self.network_context, ); - "BeaconBlockHeaders" } RPCResponse::BeaconBlockBodies(response) => { self.sync.on_beacon_block_bodies_response( @@ -175,13 +171,10 @@ impl MessageHandler { response, &mut self.network_context, ); - "BeaconBlockBodies" } // TODO: Handle all responses _ => panic!("Unknown response: {:?}", response), }; - - debug!(self.log, "RPCResponse({})", response_str); } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index ff6092be1..7609f5750 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -120,6 +120,8 @@ impl SimpleSync { } pub fn on_connect(&self, peer_id: PeerId, network: &mut NetworkContext) { + info!(self.log, "PeerConnect"; "peer" => format!("{:?}", peer_id)); + network.send_rpc_request(peer_id, RPCRequest::Hello(self.chain.hello_message())); } @@ -129,6 +131,8 @@ impl SimpleSync { hello: HelloMessage, network: &mut NetworkContext, ) { + debug!(self.log, "HelloRequest"; "peer" => format!("{:?}", peer_id)); + // Say hello back. network.send_rpc_response( peer_id.clone(), @@ -144,6 +148,8 @@ impl SimpleSync { hello: HelloMessage, network: &mut NetworkContext, ) { + debug!(self.log, "HelloResponse"; "peer" => format!("{:?}", peer_id)); + // Process the hello message, without sending back another hello. self.process_hello(peer_id, hello, network); } @@ -210,12 +216,19 @@ impl SimpleSync { pub fn on_beacon_block_roots_request( &mut self, peer_id: PeerId, - request: BeaconBlockRootsRequest, + req: BeaconBlockRootsRequest, network: &mut NetworkContext, ) { + debug!( + self.log, + "BlockRootsRequest"; + "peer" => format!("{:?}", peer_id), + "count" => req.count, + ); + let roots = match self .chain - .get_block_roots(request.start_slot, request.count as usize, 0) + .get_block_roots(req.start_slot, req.count as usize, 0) { Ok(roots) => roots, Err(e) => { @@ -223,7 +236,7 @@ impl SimpleSync { warn!( self.log, "RPCRequest"; "peer" => format!("{:?}", peer_id), - "request" => "BeaconBlockRoots", + "req" => "BeaconBlockRoots", "error" => format!("{:?}", e) ); return; @@ -234,7 +247,7 @@ impl SimpleSync { .iter() .enumerate() .map(|(i, &block_root)| BlockRootSlot { - slot: request.start_slot + Slot::from(i), + slot: req.start_slot + Slot::from(i), block_root, }) .collect(); @@ -248,10 +261,17 @@ impl SimpleSync { pub fn on_beacon_block_roots_response( &mut self, peer_id: PeerId, - response: BeaconBlockRootsResponse, + res: BeaconBlockRootsResponse, network: &mut NetworkContext, ) { - if response.roots.is_empty() { + debug!( + self.log, + "BlockRootsResponse"; + "peer" => format!("{:?}", peer_id), + "count" => res.roots.len(), + ); + + if res.roots.is_empty() { warn!( self.log, "Peer returned empty block roots response. PeerId: {:?}", peer_id @@ -259,21 +279,21 @@ impl SimpleSync { return; } - let new_root_index = self.import_queue.first_new_root(&response.roots); + let new_root_index = self.import_queue.first_new_root(&res.roots); // If a new block root is found, request it and all the headers following it. // // We make an assumption here that if we don't know a block then we don't know of all // it's parents. This might not be the case if syncing becomes more sophisticated. if let Some(i) = new_root_index { - let new = &response.roots[i]; + let new = &res.roots[i]; self.request_block_headers( peer_id, BeaconBlockHeadersRequest { start_root: new.block_root, start_slot: new.slot, - max_headers: (response.roots.len() - i) as u64, + max_headers: (res.roots.len() - i) as u64, skip_slots: 0, }, network, @@ -284,13 +304,20 @@ impl SimpleSync { pub fn on_beacon_block_headers_request( &mut self, peer_id: PeerId, - request: BeaconBlockHeadersRequest, + req: BeaconBlockHeadersRequest, network: &mut NetworkContext, ) { + debug!( + self.log, + "BlockHeadersRequest"; + "peer" => format!("{:?}", peer_id), + "count" => req.max_headers, + ); + let headers = match self.chain.get_block_headers( - request.start_slot, - request.max_headers as usize, - request.skip_slots as usize, + req.start_slot, + req.max_headers as usize, + req.skip_slots as usize, ) { Ok(headers) => headers, Err(e) => { @@ -298,7 +325,7 @@ impl SimpleSync { warn!( self.log, "RPCRequest"; "peer" => format!("{:?}", peer_id), - "request" => "BeaconBlockHeaders", + "req" => "BeaconBlockHeaders", "error" => format!("{:?}", e) ); return; @@ -314,10 +341,17 @@ impl SimpleSync { pub fn on_beacon_block_headers_response( &mut self, peer_id: PeerId, - response: BeaconBlockHeadersResponse, + res: BeaconBlockHeadersResponse, network: &mut NetworkContext, ) { - if response.headers.is_empty() { + debug!( + self.log, + "BlockHeadersResponse"; + "peer" => format!("{:?}", peer_id), + "count" => res.headers.len(), + ); + + if res.headers.is_empty() { warn!( self.log, "Peer returned empty block headers response. PeerId: {:?}", peer_id @@ -325,9 +359,11 @@ impl SimpleSync { return; } + // Enqueue the headers, obtaining a list of the roots of the headers which were newly added + // to the queue. let block_roots = self .import_queue - .enqueue_headers(response.headers, peer_id.clone()); + .enqueue_headers(res.headers, peer_id.clone()); self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); } @@ -335,17 +371,24 @@ impl SimpleSync { pub fn on_beacon_block_bodies_request( &mut self, peer_id: PeerId, - request: BeaconBlockBodiesRequest, + req: BeaconBlockBodiesRequest, network: &mut NetworkContext, ) { - let block_bodies = match self.chain.get_block_bodies(&request.block_roots) { + debug!( + self.log, + "BlockBodiesRequest"; + "peer" => format!("{:?}", peer_id), + "count" => req.block_roots.len(), + ); + + let block_bodies = match self.chain.get_block_bodies(&req.block_roots) { Ok(bodies) => bodies, Err(e) => { // TODO: return RPC error. warn!( self.log, "RPCRequest"; "peer" => format!("{:?}", peer_id), - "request" => "BeaconBlockBodies", + "req" => "BeaconBlockBodies", "error" => format!("{:?}", e) ); return; @@ -361,11 +404,18 @@ impl SimpleSync { pub fn on_beacon_block_bodies_response( &mut self, peer_id: PeerId, - response: BeaconBlockBodiesResponse, + res: BeaconBlockBodiesResponse, network: &mut NetworkContext, ) { + debug!( + self.log, + "BlockBodiesResponse"; + "peer" => format!("{:?}", peer_id), + "count" => res.block_bodies.len(), + ); + self.import_queue - .enqueue_bodies(response.block_bodies, peer_id.clone()); + .enqueue_bodies(res.block_bodies, peer_id.clone()); // Clear out old entries self.import_queue.remove_stale(); @@ -427,11 +477,11 @@ impl SimpleSync { fn request_block_roots( &mut self, peer_id: PeerId, - request: BeaconBlockRootsRequest, + req: BeaconBlockRootsRequest, network: &mut NetworkContext, ) { // Potentially set state to sync. - if self.state == SyncState::Idle && request.count > SLOT_IMPORT_TOLERANCE { + if self.state == SyncState::Idle && req.count > SLOT_IMPORT_TOLERANCE { debug!(self.log, "Entering downloading sync state."); self.state = SyncState::Downloading; } @@ -439,44 +489,44 @@ impl SimpleSync { debug!( self.log, "RPCRequest(BeaconBlockRoots)"; - "count" => request.count, + "count" => req.count, "peer" => format!("{:?}", peer_id) ); // TODO: handle count > max count. - network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockRoots(request)); + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockRoots(req)); } fn request_block_headers( &mut self, peer_id: PeerId, - request: BeaconBlockHeadersRequest, + req: BeaconBlockHeadersRequest, network: &mut NetworkContext, ) { debug!( self.log, "RPCRequest(BeaconBlockHeaders)"; - "max_headers" => request.max_headers, + "max_headers" => req.max_headers, "peer" => format!("{:?}", peer_id) ); - network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockHeaders(request)); + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockHeaders(req)); } fn request_block_bodies( &mut self, peer_id: PeerId, - request: BeaconBlockBodiesRequest, + req: BeaconBlockBodiesRequest, network: &mut NetworkContext, ) { debug!( self.log, "RPCRequest(BeaconBlockBodies)"; - "count" => request.block_roots.len(), + "count" => req.block_roots.len(), "peer" => format!("{:?}", peer_id) ); - network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockBodies(request)); + network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockBodies(req)); } /// Generates our current state in the form of a HELLO RPC message. From 5f4f67f46f1f089b598f960e9e2b868e4e6c1a6d Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 14:22:12 +1100 Subject: [PATCH 41/97] Swap ImportQueue from a Map to a Vec There's an edge case where different blocks can have the same block body. --- beacon_node/beacon_chain/src/beacon_chain.rs | 9 ++++ beacon_node/network/src/sync/simple_sync.rs | 54 ++++++++++++-------- beacon_node/network/tests/tests.rs | 3 ++ 3 files changed, 45 insertions(+), 21 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index d5fd113a8..966e73210 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -64,6 +64,15 @@ impl BlockProcessingOutcome { }, } } + + /// Returns `true` if the block was successfully processed and can be removed from any import + /// queues or temporary storage. + pub fn sucessfully_processed(&self) -> bool { + match self { + BlockProcessingOutcome::ValidBlock(_) => true, + _ => false, + } + } } pub struct BeaconChain { diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 7609f5750..b77a976b1 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -425,14 +425,15 @@ impl SimpleSync { } pub fn process_import_queue(&mut self, network: &mut NetworkContext) { - let mut blocks: Vec<(Hash256, BeaconBlock, PeerId)> = self + let mut blocks: Vec<(usize, BeaconBlock, PeerId)> = self .import_queue .partials .iter() - .filter_map(|(key, partial)| { + .enumerate() + .filter_map(|(i, partial)| { if let Some(_) = partial.body { let (block, _root) = partial.clone().complete().expect("Body must be Some"); - Some((*key, block, partial.sender.clone())) + Some((i, block, partial.sender.clone())) } else { None } @@ -469,7 +470,7 @@ impl SimpleSync { if !keys_to_delete.is_empty() { info!(self.log, "Processed {} blocks", keys_to_delete.len()); for key in keys_to_delete { - self.import_queue.partials.remove(&key); + self.import_queue.partials.remove(key); } } } @@ -539,7 +540,7 @@ pub struct ImportQueue { /// BeaconChain pub chain: Arc, /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. - pub partials: HashMap, + pub partials: Vec, /// Time before a queue entry is consider state. pub stale_time: Duration, /// Logging @@ -550,7 +551,7 @@ impl ImportQueue { pub fn new(chain: Arc, stale_time: Duration, log: slog::Logger) -> Self { Self { chain, - partials: HashMap::new(), + partials: vec![], stale_time, log, } @@ -561,29 +562,30 @@ impl ImportQueue { /// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the /// past. pub fn remove_stale(&mut self) { - let keys: Vec = self + let stale_indices: Vec = self .partials .iter() - .filter_map(|(key, partial)| { + .enumerate() + .filter_map(|(i, partial)| { if partial.inserted + self.stale_time <= Instant::now() { - Some(*key) + Some(i) } else { None } }) .collect(); - if !keys.is_empty() { + if !stale_indices.is_empty() { debug!( self.log, "ImportQueue removing stale entries"; - "stale_count" => keys.len(), + "stale_items" => stale_indices.len(), "stale_time_seconds" => self.stale_time.as_secs() ); } - keys.iter().for_each(|key| { - self.partials.remove(&key); + stale_indices.iter().for_each(|&i| { + self.partials.remove(i); }); } @@ -646,29 +648,39 @@ impl ImportQueue { /// If the header already exists, the `inserted` time is set to `now` and not other /// modifications are made. fn insert_header(&mut self, block_root: Hash256, header: BeaconBlockHeader, sender: PeerId) { - self.partials - .entry(header.block_body_root) - .and_modify(|p| p.inserted = Instant::now()) - .or_insert(PartialBeaconBlock { + if let Some(i) = self + .partials + .iter() + .position(|p| p.block_root == block_root) + { + self.partials[i].inserted = Instant::now(); + } else { + self.partials.push(PartialBeaconBlock { block_root, header, body: None, inserted: Instant::now(), sender, - }); + }) + } } /// Updates an existing partial with the `body`. /// /// If there is no header for the `body`, the body is simply discarded. + /// + /// If the body already existed, the `inserted` time is set to `now`. fn insert_body(&mut self, body: BeaconBlockBody, sender: PeerId) { let body_root = Hash256::from_slice(&body.hash_tree_root()[..]); - self.partials.entry(body_root).and_modify(|p| { + self.partials.iter_mut().for_each(|mut p| { if body_root == p.header.block_body_root { - p.body = Some(body); p.inserted = Instant::now(); - p.sender = sender; + + if p.body.is_none() { + p.body = Some(body.clone()); + p.sender = sender.clone(); + } } }); } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index b951d7d2a..2952e5105 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -511,7 +511,10 @@ fn sync_two_nodes() { // Node A builds out a longer, better chain. for _ in 0..blocks { + // Node A should build a block. node_a.harness.advance_chain_with_block(); + // Node B should just increment it's slot without a block. + node_b.harness.increment_beacon_chain_slot(); } node_a.harness.run_fork_choice(); From 1ea995963254ea4e4e8cd7f1a52d27d4a1b2e1ba Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 15:18:21 +1100 Subject: [PATCH 42/97] Fix bug with block processing in sync --- beacon_node/network/src/sync/simple_sync.rs | 104 +++++++++++++------- 1 file changed, 66 insertions(+), 38 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index b77a976b1..369564a5e 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -425,54 +425,45 @@ impl SimpleSync { } pub fn process_import_queue(&mut self, network: &mut NetworkContext) { - let mut blocks: Vec<(usize, BeaconBlock, PeerId)> = self - .import_queue - .partials - .iter() - .enumerate() - .filter_map(|(i, partial)| { - if let Some(_) = partial.body { - let (block, _root) = partial.clone().complete().expect("Body must be Some"); - Some((i, block, partial.sender.clone())) - } else { - None - } - }) - .collect(); + let mut successful = 0; + let mut invalid = 0; + let mut errored = 0; - if !blocks.is_empty() { - info!(self.log, "Processing blocks"; "count" => blocks.len()); - } - - // Sort the blocks to be in ascending slot order. - blocks.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); - - let mut keys_to_delete = vec![]; - - for (key, block, sender) in blocks { + // Loop through all of the complete blocks in the queue. + for (queue_index, block, sender) in self.import_queue.complete_blocks() { match self.chain.process_block(block) { Ok(outcome) => { if outcome.is_invalid() { - warn!(self.log, "Invalid block: {:?}", outcome); + invalid += 1; + warn!( + self.log, + "InvalidBlock"; + "sender_peer_id" => format!("{:?}", sender), + "reason" => format!("{:?}", outcome), + ); network.disconnect(sender); - keys_to_delete.push(key) - } else { - // TODO: don't delete if was not invalid but not successfully processed. - keys_to_delete.push(key) + } + + // If this results to true, the item will be removed from the queue. + if outcome.sucessfully_processed() { + successful += 1; + self.import_queue.partials.remove(queue_index); } } Err(e) => { - error!(self.log, "Error during block processing"; "error" => format!("{:?}", e)) + errored += 1; + error!(self.log, "BlockProcessingError"; "error" => format!("{:?}", e)); } } } - if !keys_to_delete.is_empty() { - info!(self.log, "Processed {} blocks", keys_to_delete.len()); - for key in keys_to_delete { - self.import_queue.partials.remove(key); - } - } + info!( + self.log, + "ProcessBlocks"; + "invalid" => invalid, + "successful" => successful, + "errored" => errored, + ) } fn request_block_roots( @@ -557,6 +548,35 @@ impl ImportQueue { } } + /// Completes all possible partials into `BeaconBlock` and returns them, sorted by slot number. + /// Does not delete the partials from the queue, this must be done manually. + /// + /// Returns `(queue_index, block, sender)`: + /// + /// - `queue_index`: used to remove the entry if it is successfully processed. + /// - `block`: the completed block. + /// - `sender`: the `PeerId` the provided the `BeaconBlockBody` which completed the partial. + pub fn complete_blocks(&self) -> Vec<(usize, BeaconBlock, PeerId)> { + let mut completable: Vec<(usize, &PartialBeaconBlock)> = self + .partials + .iter() + .enumerate() + .filter(|(_i, partial)| partial.completable()) + .collect(); + + // Sort the completable partials to be in ascending slot order. + completable.sort_unstable_by(|a, b| a.1.header.slot.partial_cmp(&b.1.header.slot).unwrap()); + + completable + .iter() + .map(|(i, partial)| { + let (block, _root, sender) = + (*partial).clone().complete().expect("Body must be Some"); + (*i, block, sender) + }) + .collect() + } + /// Flushes all stale entries from the queue. /// /// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the @@ -696,8 +716,16 @@ pub struct PartialBeaconBlock { } impl PartialBeaconBlock { + pub fn completable(&self) -> bool { + self.body.is_some() + } + /// Given a `body`, consumes `self` and returns a complete `BeaconBlock` along with its root. - pub fn complete(self) -> Option<(BeaconBlock, Hash256)> { - Some((self.header.into_block(self.body?), self.block_root)) + pub fn complete(self) -> Option<(BeaconBlock, Hash256, PeerId)> { + Some(( + self.header.into_block(self.body?), + self.block_root, + self.sender, + )) } } From 3dc5595a6fbbc3fd22e09fbcd36ca978d4b4186b Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 16:35:07 +1100 Subject: [PATCH 43/97] Fix last errors stopping full chain sync --- beacon_node/beacon_chain/src/beacon_chain.rs | 87 +++++++++++++------ beacon_node/beacon_chain/src/checkpoint.rs | 2 +- beacon_node/beacon_chain/src/errors.rs | 5 ++ .../test_harness/src/beacon_chain_harness.rs | 4 +- beacon_node/network/src/sync/simple_sync.rs | 60 ++++++------- beacon_node/network/tests/tests.rs | 24 ++++- 6 files changed, 121 insertions(+), 61 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 966e73210..745ba5155 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -26,7 +26,10 @@ pub enum ValidBlock { #[derive(Debug, PartialEq)] pub enum InvalidBlock { /// The block slot is greater than the present slot. - FutureSlot, + FutureSlot { + present_slot: Slot, + block_slot: Slot, + }, /// The block state_root does not match the generated state. StateRootMismatch, /// The blocks parent_root is unknown. @@ -53,7 +56,7 @@ impl BlockProcessingOutcome { match self { BlockProcessingOutcome::ValidBlock(_) => false, BlockProcessingOutcome::InvalidBlock(r) => match r { - InvalidBlock::FutureSlot => true, + InvalidBlock::FutureSlot { .. } => true, InvalidBlock::StateRootMismatch => true, InvalidBlock::ParentUnknown => false, InvalidBlock::SlotProcessingError(_) => false, @@ -302,6 +305,49 @@ where self.canonical_head.read() } + /// Updates the canonical `BeaconState` with the supplied state. + /// + /// Advances the chain forward to the present slot. This method is better than just setting + /// state and calling `catchup_state` as it will not result in an old state being installed and + /// then having it iteratively updated -- in such a case it's possible for another thread to + /// find the state at an old slot. + pub fn update_state(&self, mut state: BeaconState) -> Result<(), Error> { + let latest_block_header = self.head().beacon_block.block_header(); + + let present_slot = match self.slot_clock.present_slot() { + Ok(Some(slot)) => slot, + _ => return Err(Error::UnableToReadSlot), + }; + + // If required, transition the new state to the present slot. + for _ in state.slot.as_u64()..present_slot.as_u64() { + per_slot_processing(&mut state, &latest_block_header, &self.spec)?; + } + + *self.state.write() = state; + + Ok(()) + } + + /// Ensures the current canonical `BeaconState` has been transitioned to match the `slot_clock`. + pub fn catchup_state(&self) -> Result<(), Error> { + let latest_block_header = self.head().beacon_block.block_header(); + + let present_slot = match self.slot_clock.present_slot() { + Ok(Some(slot)) => slot, + _ => return Err(Error::UnableToReadSlot), + }; + + let mut state = self.state.write(); + + // If required, transition the new state to the present slot. + for _ in state.slot.as_u64()..present_slot.as_u64() { + per_slot_processing(&mut *state, &latest_block_header, &self.spec)?; + } + + Ok(()) + } + /// Update the justified head to some new values. pub fn update_finalized_head( &self, @@ -325,28 +371,6 @@ where self.finalized_head.read() } - /// Advance the `self.state` `BeaconState` to the supplied slot. - /// - /// This will perform per_slot and per_epoch processing as required. - /// - /// The `previous_block_root` will be set to the root of the current head block (as determined - /// by the fork-choice rule). - /// - /// It is important to note that this is _not_ the state corresponding to the canonical head - /// block, instead it is that state which may or may not have had additional per slot/epoch - /// processing applied to it. - pub fn advance_state(&self, slot: Slot) -> Result<(), SlotProcessingError> { - let state_slot = self.state.read().slot; - - let latest_block_header = self.head().beacon_block.block_header(); - - for _ in state_slot.as_u64()..slot.as_u64() { - per_slot_processing(&mut *self.state.write(), &latest_block_header, &self.spec)?; - } - - Ok(()) - } - /// Returns the validator index (if any) for the given public key. /// /// Information is retrieved from the present `beacon_state.validator_registry`. @@ -724,7 +748,10 @@ where if block.slot > present_slot { return Ok(BlockProcessingOutcome::InvalidBlock( - InvalidBlock::FutureSlot, + InvalidBlock::FutureSlot { + present_slot, + block_slot: block.slot, + }, )); } @@ -800,8 +827,9 @@ where // run instead. if self.head().beacon_block_root == parent_block_root { self.update_canonical_head(block.clone(), block_root, state.clone(), state_root); - // Update the local state variable. - *self.state.write() = state; + + // Update the canonical `BeaconState`. + self.update_state(state)?; } Ok(BlockProcessingOutcome::ValidBlock(ValidBlock::Processed)) @@ -891,7 +919,10 @@ where .ok_or_else(|| Error::MissingBeaconState(block.state_root))?; let state_root = state.canonical_root(); - self.update_canonical_head(block, block_root, state, state_root); + self.update_canonical_head(block, block_root, state.clone(), state_root); + + // Update the canonical `BeaconState`. + self.update_state(state)?; } Ok(()) diff --git a/beacon_node/beacon_chain/src/checkpoint.rs b/beacon_node/beacon_chain/src/checkpoint.rs index 828e462de..78227e5c8 100644 --- a/beacon_node/beacon_chain/src/checkpoint.rs +++ b/beacon_node/beacon_chain/src/checkpoint.rs @@ -3,7 +3,7 @@ use types::{BeaconBlock, BeaconState, Hash256}; /// Represents some block and it's associated state. Generally, this will be used for tracking the /// head, justified head and finalized head. -#[derive(Clone, Serialize)] +#[derive(Clone, Serialize, PartialEq, Debug)] pub struct CheckPoint { pub beacon_block: BeaconBlock, pub beacon_block_root: Hash256, diff --git a/beacon_node/beacon_chain/src/errors.rs b/beacon_node/beacon_chain/src/errors.rs index b5f17efd2..a84e4b10e 100644 --- a/beacon_node/beacon_chain/src/errors.rs +++ b/beacon_node/beacon_chain/src/errors.rs @@ -1,5 +1,6 @@ use fork_choice::ForkChoiceError; use state_processing::BlockProcessingError; +use state_processing::SlotProcessingError; use types::*; macro_rules! easy_from_to { @@ -16,14 +17,18 @@ macro_rules! easy_from_to { pub enum BeaconChainError { InsufficientValidators, BadRecentBlockRoots, + UnableToReadSlot, BeaconStateError(BeaconStateError), DBInconsistent(String), DBError(String), ForkChoiceError(ForkChoiceError), MissingBeaconBlock(Hash256), MissingBeaconState(Hash256), + SlotProcessingError(SlotProcessingError), } +easy_from_to!(SlotProcessingError, BeaconChainError); + #[derive(Debug, PartialEq)] pub enum BlockProductionError { UnableToGetBlockRootFromState, diff --git a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs index 1207fcf28..1498796b1 100644 --- a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs +++ b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs @@ -131,7 +131,9 @@ impl BeaconChainHarness { ); self.beacon_chain.slot_clock.set_slot(slot.as_u64()); - self.beacon_chain.advance_state(slot).unwrap(); + self.beacon_chain + .catchup_state() + .expect("Failed to catch state"); slot } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 369564a5e..76d630b9a 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -430,7 +430,7 @@ impl SimpleSync { let mut errored = 0; // Loop through all of the complete blocks in the queue. - for (queue_index, block, sender) in self.import_queue.complete_blocks() { + for (block_root, block, sender) in self.import_queue.complete_blocks() { match self.chain.process_block(block) { Ok(outcome) => { if outcome.is_invalid() { @@ -447,7 +447,7 @@ impl SimpleSync { // If this results to true, the item will be removed from the queue. if outcome.sucessfully_processed() { successful += 1; - self.import_queue.partials.remove(queue_index); + self.import_queue.remove(block_root); } } Err(e) => { @@ -457,13 +457,15 @@ impl SimpleSync { } } - info!( - self.log, - "ProcessBlocks"; - "invalid" => invalid, - "successful" => successful, - "errored" => errored, - ) + if successful > 0 { + info!(self.log, "Imported {} blocks", successful) + } + if invalid > 0 { + warn!(self.log, "Rejected {} invalid blocks", invalid) + } + if errored > 0 { + warn!(self.log, "Failed to process {} blocks", errored) + } } fn request_block_roots( @@ -548,33 +550,35 @@ impl ImportQueue { } } - /// Completes all possible partials into `BeaconBlock` and returns them, sorted by slot number. - /// Does not delete the partials from the queue, this must be done manually. + /// Completes all possible partials into `BeaconBlock` and returns them, sorted by increasing + /// slot number. Does not delete the partials from the queue, this must be done manually. /// /// Returns `(queue_index, block, sender)`: /// - /// - `queue_index`: used to remove the entry if it is successfully processed. + /// - `block_root`: may be used to remove the entry if it is successfully processed. /// - `block`: the completed block. /// - `sender`: the `PeerId` the provided the `BeaconBlockBody` which completed the partial. - pub fn complete_blocks(&self) -> Vec<(usize, BeaconBlock, PeerId)> { - let mut completable: Vec<(usize, &PartialBeaconBlock)> = self + pub fn complete_blocks(&self) -> Vec<(Hash256, BeaconBlock, PeerId)> { + let mut complete: Vec<(Hash256, BeaconBlock, PeerId)> = self .partials .iter() - .enumerate() - .filter(|(_i, partial)| partial.completable()) + .filter_map(|partial| partial.clone().complete()) .collect(); // Sort the completable partials to be in ascending slot order. - completable.sort_unstable_by(|a, b| a.1.header.slot.partial_cmp(&b.1.header.slot).unwrap()); + complete.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); - completable + complete + } + + /// Removes the first `PartialBeaconBlock` with a matching `block_root`, returning the partial + /// if it exists. + pub fn remove(&mut self, block_root: Hash256) -> Option { + let position = self + .partials .iter() - .map(|(i, partial)| { - let (block, _root, sender) = - (*partial).clone().complete().expect("Body must be Some"); - (*i, block, sender) - }) - .collect() + .position(|p| p.block_root == block_root)?; + Some(self.partials.remove(position)) } /// Flushes all stale entries from the queue. @@ -716,15 +720,11 @@ pub struct PartialBeaconBlock { } impl PartialBeaconBlock { - pub fn completable(&self) -> bool { - self.body.is_some() - } - /// Given a `body`, consumes `self` and returns a complete `BeaconBlock` along with its root. - pub fn complete(self) -> Option<(BeaconBlock, Hash256, PeerId)> { + pub fn complete(self) -> Option<(Hash256, BeaconBlock, PeerId)> { Some(( - self.header.into_block(self.body?), self.block_root, + self.header.into_block(self.body?), self.sender, )) } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index 2952e5105..e12bf2628 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -541,6 +541,28 @@ fn sync_two_nodes() { // A provides block bodies to B. node_a.tee_block_body_response(&node_b); - std::thread::sleep(Duration::from_secs(60)); + std::thread::sleep(Duration::from_secs(10)); + + node_b.harness.run_fork_choice(); + + let node_a_chain = node_a + .harness + .beacon_chain + .chain_dump() + .expect("Can't dump node a chain"); + + let node_b_chain = node_b + .harness + .beacon_chain + .chain_dump() + .expect("Can't dump node b chain"); + + assert_eq!( + node_a_chain.len(), + node_b_chain.len(), + "Chains should be equal length" + ); + assert_eq!(node_a_chain, node_b_chain, "Chains should be identical"); + runtime.shutdown_now(); } From 796b68dc042920a49336aa646cbb04ed16da1add Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 17:51:32 +1100 Subject: [PATCH 44/97] Implement Goodbye and BeaconState msg handlers --- beacon_node/eth2-libp2p/src/rpc/methods.rs | 52 ++++++++++++++++++++- beacon_node/eth2-libp2p/src/rpc/protocol.rs | 4 +- beacon_node/network/src/message_handler.rs | 22 ++++++--- beacon_node/network/src/sync/simple_sync.rs | 10 ++++ 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/rpc/methods.rs b/beacon_node/eth2-libp2p/src/rpc/methods.rs index f6a5f2829..85ef7e06f 100644 --- a/beacon_node/eth2-libp2p/src/rpc/methods.rs +++ b/beacon_node/eth2-libp2p/src/rpc/methods.rs @@ -1,3 +1,4 @@ +use ssz::{Decodable, DecodeError, Encodable, SszStream}; /// Available RPC methods types and ids. use ssz_derive::{Decode, Encode}; use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; @@ -53,7 +54,7 @@ impl Into for RPCMethod { #[derive(Debug, Clone)] pub enum RPCRequest { Hello(HelloMessage), - Goodbye(u64), + Goodbye(GoodbyeReason), BeaconBlockRoots(BeaconBlockRootsRequest), BeaconBlockHeaders(BeaconBlockHeadersRequest), BeaconBlockBodies(BeaconBlockBodiesRequest), @@ -113,6 +114,55 @@ pub struct HelloMessage { pub best_slot: Slot, } +/// The reason given for a `Goodbye` message. +/// +/// Note: any unknown `u64::into(n)` will resolve to `GoodbyeReason::Unknown` for any unknown `n`, +/// however `GoodbyeReason::Unknown.into()` will go into `0_u64`. Therefore de-serializing then +/// re-serializing may not return the same bytes. +#[derive(Debug, Clone)] +pub enum GoodbyeReason { + ClientShutdown, + IrreleventNetwork, + Fault, + Unknown, +} + +impl From for GoodbyeReason { + fn from(id: u64) -> GoodbyeReason { + match id { + 1 => GoodbyeReason::ClientShutdown, + 2 => GoodbyeReason::IrreleventNetwork, + 3 => GoodbyeReason::Fault, + _ => GoodbyeReason::Unknown, + } + } +} + +impl Into for GoodbyeReason { + fn into(self) -> u64 { + match self { + GoodbyeReason::Unknown => 0, + GoodbyeReason::ClientShutdown => 1, + GoodbyeReason::IrreleventNetwork => 2, + GoodbyeReason::Fault => 3, + } + } +} + +impl Encodable for GoodbyeReason { + fn ssz_append(&self, s: &mut SszStream) { + let id: u64 = (*self).clone().into(); + id.ssz_append(s); + } +} + +impl Decodable for GoodbyeReason { + fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), DecodeError> { + let (id, index) = u64::ssz_decode(bytes, index)?; + Ok((Self::from(id), index)) + } +} + /// Request a number of beacon block roots from a peer. #[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BeaconBlockRootsRequest { diff --git a/beacon_node/eth2-libp2p/src/rpc/protocol.rs b/beacon_node/eth2-libp2p/src/rpc/protocol.rs index f4fe26fac..b328dd0dd 100644 --- a/beacon_node/eth2-libp2p/src/rpc/protocol.rs +++ b/beacon_node/eth2-libp2p/src/rpc/protocol.rs @@ -82,8 +82,8 @@ fn decode(packet: Vec) -> Result { RPCRequest::Hello(hello_body) } RPCMethod::Goodbye => { - let (goodbye_code, _index) = u64::ssz_decode(&packet, index)?; - RPCRequest::Goodbye(goodbye_code) + let (goodbye_reason, _index) = GoodbyeReason::ssz_decode(&packet, index)?; + RPCRequest::Goodbye(goodbye_reason) } RPCMethod::BeaconBlockRoots => { let (block_roots_request, _index) = diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 77a2ab8db..57923b2c3 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -107,13 +107,14 @@ impl MessageHandler { } /// A new RPC request has been received from the network. - fn handle_rpc_request(&mut self, peer_id: PeerId, id: u64, request: RPCRequest) { - // TODO: ensure the id is legit + fn handle_rpc_request(&mut self, peer_id: PeerId, _id: u64, request: RPCRequest) { + // TODO: process the `id`. match request { RPCRequest::Hello(hello_message) => { self.sync .on_hello_request(peer_id, hello_message, &mut self.network_context) } + RPCRequest::Goodbye(goodbye_reason) => self.sync.on_goodbye(peer_id, goodbye_reason), RPCRequest::BeaconBlockRoots(request) => { self.sync .on_beacon_block_roots_request(peer_id, request, &mut self.network_context) @@ -128,8 +129,11 @@ impl MessageHandler { request, &mut self.network_context, ), - // TODO: Handle all requests - _ => panic!("Unknown request: {:?}", request), + RPCRequest::BeaconChainState(_) => { + // We do not implement this endpoint, it is not required and will only likely be + // useful for light-client support in later phases. + warn!(self.log, "BeaconChainState RPC call is not supported."); + } } } @@ -172,8 +176,14 @@ impl MessageHandler { &mut self.network_context, ); } - // TODO: Handle all responses - _ => panic!("Unknown response: {:?}", response), + RPCResponse::BeaconChainState(_) => { + // We do not implement this endpoint, it is not required and will only likely be + // useful for light-client support in later phases. + // + // Theoretically, we shouldn't reach this code because we should never send a + // beacon state RPC request. + warn!(self.log, "BeaconChainState RPC call is not supported."); + } }; } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 76d630b9a..14564aa37 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -119,6 +119,16 @@ impl SimpleSync { } } + pub fn on_goodbye(&mut self, peer_id: PeerId, reason: GoodbyeReason) { + info!( + self.log, "PeerGoodbye"; + "peer" => format!("{:?}", peer_id), + "reason" => format!("{:?}", reason), + ); + + self.known_peers.remove(&peer_id); + } + pub fn on_connect(&self, peer_id: PeerId, network: &mut NetworkContext) { info!(self.log, "PeerConnect"; "peer" => format!("{:?}", peer_id)); From 07b6f7084292c864b3d0f969c36abd6c6dde4ecd Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 17:58:30 +1100 Subject: [PATCH 45/97] Ignore syncing tests (they run too long) --- beacon_node/network/tests/tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index e12bf2628..110450dc9 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -450,6 +450,7 @@ pub fn build_blocks(blocks: usize, master: &mut SyncMaster, nodes: &mut Vec Date: Sun, 24 Mar 2019 18:31:03 +1100 Subject: [PATCH 46/97] Add comments to SimpleSync --- beacon_node/network/src/sync/simple_sync.rs | 75 +++++++++++++++++++-- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 14564aa37..d6b9e63ae 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -27,18 +27,22 @@ pub struct PeerSyncInfo { } impl PeerSyncInfo { + /// Returns `true` if the peer is on the same chain as `other`. fn is_on_same_chain(&self, other: Self) -> bool { self.network_id == other.network_id } + /// Returns `true` if the peer has a higher finalized epoch than `other`. fn has_higher_finalized_epoch_than(&self, other: Self) -> bool { self.latest_finalized_epoch > other.latest_finalized_epoch } + /// Returns `true` if the peer has a higher best slot than `other`. fn has_higher_best_slot_than(&self, other: Self) -> bool { self.best_slot > other.best_slot } + /// Returns the `PeerStatus` of `self` in relation to `other`. pub fn status_compared_to(&self, other: Self) -> PeerStatus { if self.has_higher_finalized_epoch_than(other) { PeerStatus::HigherFinalizedEpoch @@ -52,11 +56,17 @@ impl PeerSyncInfo { } } +/// The status of a peers view on the chain, relative to some other view of the chain (presumably +/// our view). #[derive(PartialEq, Clone, Copy, Debug)] pub enum PeerStatus { + /// The peer is on a completely different chain. OnDifferentChain, + /// The peer has a higher finalized epoch. HigherFinalizedEpoch, + /// The peer has a higher best slot. HigherBestSlot, + /// The peer has the same or lesser view of the chain. We have nothing to request of them. NotInteresting, } @@ -87,8 +97,6 @@ pub enum SyncState { } /// Simple Syncing protocol. -//TODO: Decide for HELLO messages whether its better to keep current in RAM or build on the fly -//when asked. pub struct SimpleSync { /// A reference to the underlying beacon chain. chain: Arc, @@ -103,6 +111,7 @@ pub struct SimpleSync { } impl SimpleSync { + /// Instantiate a `SimpleSync` instance, with no peers and an empty queue. pub fn new(beacon_chain: Arc, log: &slog::Logger) -> Self { let sync_logger = log.new(o!("Service"=> "Sync")); @@ -119,7 +128,15 @@ impl SimpleSync { } } - pub fn on_goodbye(&mut self, peer_id: PeerId, reason: GoodbyeReason) { + /// Handle a `Goodbye` message from a peer. + /// + /// Removes the peer from `known_peers`. + pub fn on_goodbye( + &mut self, + peer_id: PeerId, + reason: GoodbyeReason, + ddnetwork: &mut NetworkContext, + ) { info!( self.log, "PeerGoodbye"; "peer" => format!("{:?}", peer_id), @@ -129,12 +146,18 @@ impl SimpleSync { self.known_peers.remove(&peer_id); } + /// Handle the connection of a new peer. + /// + /// Sends a `Hello` message to the peer. pub fn on_connect(&self, peer_id: PeerId, network: &mut NetworkContext) { info!(self.log, "PeerConnect"; "peer" => format!("{:?}", peer_id)); network.send_rpc_request(peer_id, RPCRequest::Hello(self.chain.hello_message())); } + /// Handle a `Hello` request. + /// + /// Processes the `HelloMessage` from the remote peer and sends back our `Hello`. pub fn on_hello_request( &mut self, peer_id: PeerId, @@ -152,6 +175,7 @@ impl SimpleSync { self.process_hello(peer_id, hello, network); } + /// Process a `Hello` response from a peer. pub fn on_hello_response( &mut self, peer_id: PeerId, @@ -164,6 +188,9 @@ impl SimpleSync { self.process_hello(peer_id, hello, network); } + /// Process a `Hello` message, requesting new blocks if appropriate. + /// + /// Disconnects the peer if required. fn process_hello( &mut self, peer_id: PeerId, @@ -223,6 +250,7 @@ impl SimpleSync { } } + /// Handle a `BeaconBlockRoots` request from the peer. pub fn on_beacon_block_roots_request( &mut self, peer_id: PeerId, @@ -268,6 +296,7 @@ impl SimpleSync { ) } + /// Handle a `BeaconBlockRoots` response from the peer. pub fn on_beacon_block_roots_response( &mut self, peer_id: PeerId, @@ -311,6 +340,7 @@ impl SimpleSync { } } + /// Handle a `BeaconBlockHeaders` request from the peer. pub fn on_beacon_block_headers_request( &mut self, peer_id: PeerId, @@ -348,6 +378,7 @@ impl SimpleSync { ) } + /// Handle a `BeaconBlockHeaders` response from the peer. pub fn on_beacon_block_headers_response( &mut self, peer_id: PeerId, @@ -378,6 +409,7 @@ impl SimpleSync { self.request_block_bodies(peer_id, BeaconBlockBodiesRequest { block_roots }, network); } + /// Handle a `BeaconBlockBodies` request from the peer. pub fn on_beacon_block_bodies_request( &mut self, peer_id: PeerId, @@ -411,6 +443,7 @@ impl SimpleSync { ) } + /// Handle a `BeaconBlockBodies` response from the peer. pub fn on_beacon_block_bodies_response( &mut self, peer_id: PeerId, @@ -434,6 +467,10 @@ impl SimpleSync { self.process_import_queue(network); } + /// Iterate through the `import_queue` and process any complete blocks. + /// + /// If a block is successfully processed it is removed from the queue, otherwise it remains in + /// the queue. pub fn process_import_queue(&mut self, network: &mut NetworkContext) { let mut successful = 0; let mut invalid = 0; @@ -478,6 +515,7 @@ impl SimpleSync { } } + /// Request some `BeaconBlockRoots` from the remote peer. fn request_block_roots( &mut self, peer_id: PeerId, @@ -501,6 +539,7 @@ impl SimpleSync { network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockRoots(req)); } + /// Request some `BeaconBlockHeaders` from the remote peer. fn request_block_headers( &mut self, peer_id: PeerId, @@ -517,6 +556,7 @@ impl SimpleSync { network.send_rpc_request(peer_id.clone(), RPCRequest::BeaconBlockHeaders(req)); } + /// Request some `BeaconBlockBodies` from the remote peer. fn request_block_bodies( &mut self, peer_id: PeerId, @@ -539,18 +579,30 @@ impl SimpleSync { } } +/// Provides a queue for fully and partially built `BeaconBlock`s. +/// +/// The queue is fundamentally a `Vec` where no two items have the same +/// `item.block_root`. This struct it backed by a `Vec` not a `HashMap` for the following two +/// reasons: +/// +/// - When we receive a `BeaconBlockBody`, the only way we can find it's matching +/// `BeaconBlockHeader` is to find a header such that `header.beacon_block_body == +/// hash_tree_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of +/// `BeaconBlockBody` as the key. +/// - It is possible for multiple distinct blocks to have identical `BeaconBlockBodies`. Therefore +/// we cannot use a `HashMap` keyed by the root of `BeaconBlockBody`. pub struct ImportQueue { - /// BeaconChain pub chain: Arc, /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. pub partials: Vec, - /// Time before a queue entry is consider state. + /// Time before a queue entry is considered state. pub stale_time: Duration, /// Logging log: slog::Logger, } impl ImportQueue { + /// Return a new, empty queue. pub fn new(chain: Arc, stale_time: Duration, log: slog::Logger) -> Self { Self { chain, @@ -649,6 +701,10 @@ impl ImportQueue { /// If a `header` is already in the queue, but not yet processed by the chain the block root is /// included in the output and the `inserted` time for the partial record is set to /// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale. + /// + /// Presently the queue enforces that a `BeaconBlockHeader` _must_ be received before its + /// `BeaconBlockBody`. This is not a natural requirement and we could enhance the queue to lift + /// this restraint. pub fn enqueue_headers( &mut self, headers: Vec, @@ -720,17 +776,24 @@ impl ImportQueue { } } +/// Individual components of a `BeaconBlock`, potentially all that are required to form a full +/// `BeaconBlock`. #[derive(Clone, Debug)] pub struct PartialBeaconBlock { + /// `BeaconBlock` root. pub block_root: Hash256, pub header: BeaconBlockHeader, pub body: Option, + /// The instant at which this record was created or last meaningfully modified. Used to + /// determine if an entry is stale and should be removed. pub inserted: Instant, + /// The `PeerId` that last meaningfully contributed to this item. pub sender: PeerId, } impl PartialBeaconBlock { - /// Given a `body`, consumes `self` and returns a complete `BeaconBlock` along with its root. + /// Consumes `self` and returns a full built `BeaconBlock`, it's root and the `sender` + /// `PeerId`, if enough information exists to complete the block. Otherwise, returns `None`. pub fn complete(self) -> Option<(Hash256, BeaconBlock, PeerId)> { Some(( self.block_root, From 755a09d164f7790cd74fda8efd3ae8d033579a88 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 18:34:44 +1100 Subject: [PATCH 47/97] Move ImportQueue into own file --- beacon_node/network/src/sync/import_queue.rs | 232 +++++++++++++++++++ beacon_node/network/src/sync/mod.rs | 1 + beacon_node/network/src/sync/simple_sync.rs | 230 +----------------- 3 files changed, 236 insertions(+), 227 deletions(-) create mode 100644 beacon_node/network/src/sync/import_queue.rs diff --git a/beacon_node/network/src/sync/import_queue.rs b/beacon_node/network/src/sync/import_queue.rs new file mode 100644 index 000000000..6508af89e --- /dev/null +++ b/beacon_node/network/src/sync/import_queue.rs @@ -0,0 +1,232 @@ +use crate::beacon_chain::BeaconChain; +use eth2_libp2p::rpc::methods::*; +use eth2_libp2p::PeerId; +use slog::{debug, error}; +use ssz::TreeHash; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Hash256}; + +/// Provides a queue for fully and partially built `BeaconBlock`s. +/// +/// The queue is fundamentally a `Vec` where no two items have the same +/// `item.block_root`. This struct it backed by a `Vec` not a `HashMap` for the following two +/// reasons: +/// +/// - When we receive a `BeaconBlockBody`, the only way we can find it's matching +/// `BeaconBlockHeader` is to find a header such that `header.beacon_block_body == +/// hash_tree_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of +/// `BeaconBlockBody` as the key. +/// - It is possible for multiple distinct blocks to have identical `BeaconBlockBodies`. Therefore +/// we cannot use a `HashMap` keyed by the root of `BeaconBlockBody`. +pub struct ImportQueue { + pub chain: Arc, + /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. + pub partials: Vec, + /// Time before a queue entry is considered state. + pub stale_time: Duration, + /// Logging + log: slog::Logger, +} + +impl ImportQueue { + /// Return a new, empty queue. + pub fn new(chain: Arc, stale_time: Duration, log: slog::Logger) -> Self { + Self { + chain, + partials: vec![], + stale_time, + log, + } + } + + /// Completes all possible partials into `BeaconBlock` and returns them, sorted by increasing + /// slot number. Does not delete the partials from the queue, this must be done manually. + /// + /// Returns `(queue_index, block, sender)`: + /// + /// - `block_root`: may be used to remove the entry if it is successfully processed. + /// - `block`: the completed block. + /// - `sender`: the `PeerId` the provided the `BeaconBlockBody` which completed the partial. + pub fn complete_blocks(&self) -> Vec<(Hash256, BeaconBlock, PeerId)> { + let mut complete: Vec<(Hash256, BeaconBlock, PeerId)> = self + .partials + .iter() + .filter_map(|partial| partial.clone().complete()) + .collect(); + + // Sort the completable partials to be in ascending slot order. + complete.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); + + complete + } + + /// Removes the first `PartialBeaconBlock` with a matching `block_root`, returning the partial + /// if it exists. + pub fn remove(&mut self, block_root: Hash256) -> Option { + let position = self + .partials + .iter() + .position(|p| p.block_root == block_root)?; + Some(self.partials.remove(position)) + } + + /// Flushes all stale entries from the queue. + /// + /// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the + /// past. + pub fn remove_stale(&mut self) { + let stale_indices: Vec = self + .partials + .iter() + .enumerate() + .filter_map(|(i, partial)| { + if partial.inserted + self.stale_time <= Instant::now() { + Some(i) + } else { + None + } + }) + .collect(); + + if !stale_indices.is_empty() { + debug!( + self.log, + "ImportQueue removing stale entries"; + "stale_items" => stale_indices.len(), + "stale_time_seconds" => self.stale_time.as_secs() + ); + } + + stale_indices.iter().for_each(|&i| { + self.partials.remove(i); + }); + } + + /// Returns `true` if `self.chain` has not yet processed this block. + fn is_new_block(&self, block_root: &Hash256) -> bool { + self.chain + .is_new_block_root(&block_root) + .unwrap_or_else(|_| { + error!(self.log, "Unable to determine if block is new."); + true + }) + } + + /// Returns the index of the first new root in the list of block roots. + pub fn first_new_root(&mut self, roots: &[BlockRootSlot]) -> Option { + roots + .iter() + .position(|brs| self.is_new_block(&brs.block_root)) + } + + /// Adds the `headers` to the `partials` queue. Returns a list of `Hash256` block roots for + /// which we should use to request `BeaconBlockBodies`. + /// + /// If a `header` is not in the queue and has not been processed by the chain it is added to + /// the queue and it's block root is included in the output. + /// + /// If a `header` is already in the queue, but not yet processed by the chain the block root is + /// included in the output and the `inserted` time for the partial record is set to + /// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale. + /// + /// Presently the queue enforces that a `BeaconBlockHeader` _must_ be received before its + /// `BeaconBlockBody`. This is not a natural requirement and we could enhance the queue to lift + /// this restraint. + pub fn enqueue_headers( + &mut self, + headers: Vec, + sender: PeerId, + ) -> Vec { + let mut required_bodies: Vec = vec![]; + + for header in headers { + let block_root = Hash256::from_slice(&header.hash_tree_root()[..]); + + if self.is_new_block(&block_root) { + self.insert_header(block_root, header, sender.clone()); + required_bodies.push(block_root) + } + } + + required_bodies + } + + /// If there is a matching `header` for this `body`, adds it to the queue. + /// + /// If there is no `header` for the `body`, the body is simply discarded. + pub fn enqueue_bodies(&mut self, bodies: Vec, sender: PeerId) { + for body in bodies { + self.insert_body(body, sender.clone()); + } + } + + /// Inserts a header to the queue. + /// + /// If the header already exists, the `inserted` time is set to `now` and not other + /// modifications are made. + fn insert_header(&mut self, block_root: Hash256, header: BeaconBlockHeader, sender: PeerId) { + if let Some(i) = self + .partials + .iter() + .position(|p| p.block_root == block_root) + { + self.partials[i].inserted = Instant::now(); + } else { + self.partials.push(PartialBeaconBlock { + block_root, + header, + body: None, + inserted: Instant::now(), + sender, + }) + } + } + + /// Updates an existing partial with the `body`. + /// + /// If there is no header for the `body`, the body is simply discarded. + /// + /// If the body already existed, the `inserted` time is set to `now`. + fn insert_body(&mut self, body: BeaconBlockBody, sender: PeerId) { + let body_root = Hash256::from_slice(&body.hash_tree_root()[..]); + + self.partials.iter_mut().for_each(|mut p| { + if body_root == p.header.block_body_root { + p.inserted = Instant::now(); + + if p.body.is_none() { + p.body = Some(body.clone()); + p.sender = sender.clone(); + } + } + }); + } +} + +/// Individual components of a `BeaconBlock`, potentially all that are required to form a full +/// `BeaconBlock`. +#[derive(Clone, Debug)] +pub struct PartialBeaconBlock { + /// `BeaconBlock` root. + pub block_root: Hash256, + pub header: BeaconBlockHeader, + pub body: Option, + /// The instant at which this record was created or last meaningfully modified. Used to + /// determine if an entry is stale and should be removed. + pub inserted: Instant, + /// The `PeerId` that last meaningfully contributed to this item. + pub sender: PeerId, +} + +impl PartialBeaconBlock { + /// Consumes `self` and returns a full built `BeaconBlock`, it's root and the `sender` + /// `PeerId`, if enough information exists to complete the block. Otherwise, returns `None`. + pub fn complete(self) -> Option<(Hash256, BeaconBlock, PeerId)> { + Some(( + self.block_root, + self.header.into_block(self.body?), + self.sender, + )) + } +} diff --git a/beacon_node/network/src/sync/mod.rs b/beacon_node/network/src/sync/mod.rs index 8f5216b85..fac1b46eb 100644 --- a/beacon_node/network/src/sync/mod.rs +++ b/beacon_node/network/src/sync/mod.rs @@ -1,3 +1,4 @@ +mod import_queue; /// Syncing for lighthouse. /// /// Stores the various syncing methods for the beacon chain. diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index d6b9e63ae..c23a6ec56 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,14 +1,14 @@ +use super::import_queue::ImportQueue; use crate::beacon_chain::BeaconChain; use crate::message_handler::NetworkContext; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse}; use eth2_libp2p::PeerId; use slog::{debug, error, info, o, warn}; -use ssz::TreeHash; use std::collections::HashMap; use std::sync::Arc; -use std::time::{Duration, Instant}; -use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; +use std::time::Duration; +use types::{Epoch, Hash256, Slot}; /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; @@ -578,227 +578,3 @@ impl SimpleSync { self.chain.hello_message() } } - -/// Provides a queue for fully and partially built `BeaconBlock`s. -/// -/// The queue is fundamentally a `Vec` where no two items have the same -/// `item.block_root`. This struct it backed by a `Vec` not a `HashMap` for the following two -/// reasons: -/// -/// - When we receive a `BeaconBlockBody`, the only way we can find it's matching -/// `BeaconBlockHeader` is to find a header such that `header.beacon_block_body == -/// hash_tree_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of -/// `BeaconBlockBody` as the key. -/// - It is possible for multiple distinct blocks to have identical `BeaconBlockBodies`. Therefore -/// we cannot use a `HashMap` keyed by the root of `BeaconBlockBody`. -pub struct ImportQueue { - pub chain: Arc, - /// Partially imported blocks, keyed by the root of `BeaconBlockBody`. - pub partials: Vec, - /// Time before a queue entry is considered state. - pub stale_time: Duration, - /// Logging - log: slog::Logger, -} - -impl ImportQueue { - /// Return a new, empty queue. - pub fn new(chain: Arc, stale_time: Duration, log: slog::Logger) -> Self { - Self { - chain, - partials: vec![], - stale_time, - log, - } - } - - /// Completes all possible partials into `BeaconBlock` and returns them, sorted by increasing - /// slot number. Does not delete the partials from the queue, this must be done manually. - /// - /// Returns `(queue_index, block, sender)`: - /// - /// - `block_root`: may be used to remove the entry if it is successfully processed. - /// - `block`: the completed block. - /// - `sender`: the `PeerId` the provided the `BeaconBlockBody` which completed the partial. - pub fn complete_blocks(&self) -> Vec<(Hash256, BeaconBlock, PeerId)> { - let mut complete: Vec<(Hash256, BeaconBlock, PeerId)> = self - .partials - .iter() - .filter_map(|partial| partial.clone().complete()) - .collect(); - - // Sort the completable partials to be in ascending slot order. - complete.sort_unstable_by(|a, b| a.1.slot.partial_cmp(&b.1.slot).unwrap()); - - complete - } - - /// Removes the first `PartialBeaconBlock` with a matching `block_root`, returning the partial - /// if it exists. - pub fn remove(&mut self, block_root: Hash256) -> Option { - let position = self - .partials - .iter() - .position(|p| p.block_root == block_root)?; - Some(self.partials.remove(position)) - } - - /// Flushes all stale entries from the queue. - /// - /// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the - /// past. - pub fn remove_stale(&mut self) { - let stale_indices: Vec = self - .partials - .iter() - .enumerate() - .filter_map(|(i, partial)| { - if partial.inserted + self.stale_time <= Instant::now() { - Some(i) - } else { - None - } - }) - .collect(); - - if !stale_indices.is_empty() { - debug!( - self.log, - "ImportQueue removing stale entries"; - "stale_items" => stale_indices.len(), - "stale_time_seconds" => self.stale_time.as_secs() - ); - } - - stale_indices.iter().for_each(|&i| { - self.partials.remove(i); - }); - } - - /// Returns `true` if `self.chain` has not yet processed this block. - fn is_new_block(&self, block_root: &Hash256) -> bool { - self.chain - .is_new_block_root(&block_root) - .unwrap_or_else(|_| { - error!(self.log, "Unable to determine if block is new."); - true - }) - } - - /// Returns the index of the first new root in the list of block roots. - pub fn first_new_root(&mut self, roots: &[BlockRootSlot]) -> Option { - roots - .iter() - .position(|brs| self.is_new_block(&brs.block_root)) - } - - /// Adds the `headers` to the `partials` queue. Returns a list of `Hash256` block roots for - /// which we should use to request `BeaconBlockBodies`. - /// - /// If a `header` is not in the queue and has not been processed by the chain it is added to - /// the queue and it's block root is included in the output. - /// - /// If a `header` is already in the queue, but not yet processed by the chain the block root is - /// included in the output and the `inserted` time for the partial record is set to - /// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale. - /// - /// Presently the queue enforces that a `BeaconBlockHeader` _must_ be received before its - /// `BeaconBlockBody`. This is not a natural requirement and we could enhance the queue to lift - /// this restraint. - pub fn enqueue_headers( - &mut self, - headers: Vec, - sender: PeerId, - ) -> Vec { - let mut required_bodies: Vec = vec![]; - - for header in headers { - let block_root = Hash256::from_slice(&header.hash_tree_root()[..]); - - if self.is_new_block(&block_root) { - self.insert_header(block_root, header, sender.clone()); - required_bodies.push(block_root) - } - } - - required_bodies - } - - /// If there is a matching `header` for this `body`, adds it to the queue. - /// - /// If there is no `header` for the `body`, the body is simply discarded. - pub fn enqueue_bodies(&mut self, bodies: Vec, sender: PeerId) { - for body in bodies { - self.insert_body(body, sender.clone()); - } - } - - /// Inserts a header to the queue. - /// - /// If the header already exists, the `inserted` time is set to `now` and not other - /// modifications are made. - fn insert_header(&mut self, block_root: Hash256, header: BeaconBlockHeader, sender: PeerId) { - if let Some(i) = self - .partials - .iter() - .position(|p| p.block_root == block_root) - { - self.partials[i].inserted = Instant::now(); - } else { - self.partials.push(PartialBeaconBlock { - block_root, - header, - body: None, - inserted: Instant::now(), - sender, - }) - } - } - - /// Updates an existing partial with the `body`. - /// - /// If there is no header for the `body`, the body is simply discarded. - /// - /// If the body already existed, the `inserted` time is set to `now`. - fn insert_body(&mut self, body: BeaconBlockBody, sender: PeerId) { - let body_root = Hash256::from_slice(&body.hash_tree_root()[..]); - - self.partials.iter_mut().for_each(|mut p| { - if body_root == p.header.block_body_root { - p.inserted = Instant::now(); - - if p.body.is_none() { - p.body = Some(body.clone()); - p.sender = sender.clone(); - } - } - }); - } -} - -/// Individual components of a `BeaconBlock`, potentially all that are required to form a full -/// `BeaconBlock`. -#[derive(Clone, Debug)] -pub struct PartialBeaconBlock { - /// `BeaconBlock` root. - pub block_root: Hash256, - pub header: BeaconBlockHeader, - pub body: Option, - /// The instant at which this record was created or last meaningfully modified. Used to - /// determine if an entry is stale and should be removed. - pub inserted: Instant, - /// The `PeerId` that last meaningfully contributed to this item. - pub sender: PeerId, -} - -impl PartialBeaconBlock { - /// Consumes `self` and returns a full built `BeaconBlock`, it's root and the `sender` - /// `PeerId`, if enough information exists to complete the block. Otherwise, returns `None`. - pub fn complete(self) -> Option<(Hash256, BeaconBlock, PeerId)> { - Some(( - self.block_root, - self.header.into_block(self.body?), - self.sender, - )) - } -} From 267477ffc248e35487358a7f8d57b2a0de23e3a2 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Sun, 24 Mar 2019 18:37:23 +1100 Subject: [PATCH 48/97] Fix typo from previous commit --- beacon_node/network/src/sync/simple_sync.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index c23a6ec56..4ee349043 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -131,12 +131,7 @@ impl SimpleSync { /// Handle a `Goodbye` message from a peer. /// /// Removes the peer from `known_peers`. - pub fn on_goodbye( - &mut self, - peer_id: PeerId, - reason: GoodbyeReason, - ddnetwork: &mut NetworkContext, - ) { + pub fn on_goodbye(&mut self, peer_id: PeerId, reason: GoodbyeReason) { info!( self.log, "PeerGoodbye"; "peer" => format!("{:?}", peer_id), From 708d9b5674aeb1921778a489a4129ba4194e6713 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Mon, 25 Mar 2019 14:27:20 +1100 Subject: [PATCH 49/97] Add basic Gossip sync handlers --- beacon_node/beacon_chain/src/lib.rs | 1 + beacon_node/eth2-libp2p/src/rpc/methods.rs | 20 ++++++- beacon_node/eth2-libp2p/src/rpc/mod.rs | 2 +- beacon_node/network/src/beacon_chain.rs | 21 ++++++- beacon_node/network/src/message_handler.rs | 23 +++++++- beacon_node/network/src/sync/import_queue.rs | 2 +- beacon_node/network/src/sync/simple_sync.rs | 58 ++++++++++++++++++++ 7 files changed, 119 insertions(+), 8 deletions(-) diff --git a/beacon_node/beacon_chain/src/lib.rs b/beacon_node/beacon_chain/src/lib.rs index 5fa7e7a77..48a42b941 100644 --- a/beacon_node/beacon_chain/src/lib.rs +++ b/beacon_node/beacon_chain/src/lib.rs @@ -8,6 +8,7 @@ pub mod test_utils; pub use self::beacon_chain::{BeaconChain, BlockProcessingOutcome, InvalidBlock, ValidBlock}; pub use self::checkpoint::CheckPoint; pub use self::errors::BeaconChainError; +pub use attestation_aggregator::Outcome as AggregationOutcome; pub use db; pub use fork_choice; pub use parking_lot; diff --git a/beacon_node/eth2-libp2p/src/rpc/methods.rs b/beacon_node/eth2-libp2p/src/rpc/methods.rs index 85ef7e06f..47e47f3eb 100644 --- a/beacon_node/eth2-libp2p/src/rpc/methods.rs +++ b/beacon_node/eth2-libp2p/src/rpc/methods.rs @@ -1,7 +1,7 @@ use ssz::{Decodable, DecodeError, Encodable, SszStream}; /// Available RPC methods types and ids. use ssz_derive::{Decode, Encode}; -use types::{BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; +use types::{Attestation, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; #[derive(Debug)] /// Available Serenity Libp2p RPC methods @@ -97,6 +97,12 @@ impl RPCResponse { } } +#[derive(Debug, Clone)] +pub enum IncomingGossip { + Block(BlockGossip), + Attestation(AttestationGossip), +} + /* Request/Response data structures for RPC methods */ /// The HELLO request/response handshake message. @@ -236,3 +242,15 @@ pub struct BeaconChainStateResponse { /// The values corresponding the to the requested tree hashes. pub values: bool, //TBD - stubbed with encodeable bool } + +/// Gossipsub message providing notification of a new block. +#[derive(Encode, Decode, Clone, Debug, PartialEq)] +pub struct BlockGossip { + pub root: BlockRootSlot, +} + +/// Gossipsub message providing notification of a new attestation. +#[derive(Encode, Decode, Clone, Debug, PartialEq)] +pub struct AttestationGossip { + pub attestation: Attestation, +} diff --git a/beacon_node/eth2-libp2p/src/rpc/mod.rs b/beacon_node/eth2-libp2p/src/rpc/mod.rs index a1573ec93..925c36616 100644 --- a/beacon_node/eth2-libp2p/src/rpc/mod.rs +++ b/beacon_node/eth2-libp2p/src/rpc/mod.rs @@ -11,7 +11,7 @@ use libp2p::core::swarm::{ ConnectedPoint, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use libp2p::{Multiaddr, PeerId}; -pub use methods::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; +pub use methods::{HelloMessage, IncomingGossip, RPCMethod, RPCRequest, RPCResponse}; pub use protocol::{RPCEvent, RPCProtocol}; use slog::o; use std::marker::PhantomData; diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index cc54e8ae0..26cea0065 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -5,10 +5,10 @@ use beacon_chain::{ parking_lot::RwLockReadGuard, slot_clock::SlotClock, types::{BeaconState, ChainSpec}, - CheckPoint, + AggregationOutcome, CheckPoint, }; use eth2_libp2p::HelloMessage; -use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; +use types::{Attestation, BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; pub use beacon_chain::{BeaconChainError, BlockProcessingOutcome}; @@ -37,6 +37,11 @@ pub trait BeaconChain: Send + Sync { fn process_block(&self, block: BeaconBlock) -> Result; + fn process_attestation( + &self, + attestation: Attestation, + ) -> Result; + fn get_block_roots( &self, start_slot: Slot, @@ -119,6 +124,18 @@ where self.process_block(block) } + fn process_attestation( + &self, + _attestation: Attestation, + ) -> Result { + // Awaiting a proper operations pool before we can import attestations. + // + // Returning a useless error for now. + // + // https://github.com/sigp/lighthouse/issues/281 + return Err(BeaconChainError::DBInconsistent("CANNOT PROCESS".into())); + } + fn get_block_roots( &self, start_slot: Slot, diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 57923b2c3..a788e83c9 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -4,7 +4,7 @@ use crate::service::{NetworkMessage, OutgoingMessage}; use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use eth2_libp2p::{ - rpc::{RPCRequest, RPCResponse}, + rpc::{IncomingGossip, RPCRequest, RPCResponse}, PeerId, RPCEvent, }; use futures::future; @@ -39,8 +39,8 @@ pub enum HandlerMessage { PeerDisconnected(PeerId), /// An RPC response/request has been received. RPC(PeerId, RPCEvent), - /// A block has been imported. - BlockImported(), //TODO: This comes from pub-sub - decide its contents + /// A gossip message has been received. + IncomingGossip(PeerId, IncomingGossip), } impl MessageHandler { @@ -90,6 +90,10 @@ impl MessageHandler { HandlerMessage::RPC(peer_id, rpc_event) => { self.handle_rpc_message(peer_id, rpc_event); } + // we have received an RPC message request/response + HandlerMessage::IncomingGossip(peer_id, gossip) => { + self.handle_gossip(peer_id, gossip); + } //TODO: Handle all messages _ => {} } @@ -186,6 +190,19 @@ impl MessageHandler { } }; } + + /// Handle RPC messages + fn handle_gossip(&mut self, peer_id: PeerId, gossip_message: IncomingGossip) { + match gossip_message { + IncomingGossip::Block(message) => { + self.sync + .on_block_gossip(peer_id, message, &mut self.network_context) + } + IncomingGossip::Attestation(message) => { + // + } + } + } } pub struct NetworkContext { diff --git a/beacon_node/network/src/sync/import_queue.rs b/beacon_node/network/src/sync/import_queue.rs index 6508af89e..17cbd2f12 100644 --- a/beacon_node/network/src/sync/import_queue.rs +++ b/beacon_node/network/src/sync/import_queue.rs @@ -104,7 +104,7 @@ impl ImportQueue { } /// Returns `true` if `self.chain` has not yet processed this block. - fn is_new_block(&self, block_root: &Hash256) -> bool { + pub fn is_new_block(&self, block_root: &Hash256) -> bool { self.chain .is_new_block_root(&block_root) .unwrap_or_else(|_| { diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 4ee349043..06ccbafd3 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -204,6 +204,8 @@ impl SimpleSync { self.known_peers.insert(peer_id.clone(), remote); } + // TODO: boot peer if finalization is wrong. + match remote_status { PeerStatus::OnDifferentChain => { info!( @@ -462,6 +464,62 @@ impl SimpleSync { self.process_import_queue(network); } + /// Process a gossip message declaring a new block. + pub fn on_block_gossip( + &mut self, + peer_id: PeerId, + msg: BlockGossip, + network: &mut NetworkContext, + ) { + debug!( + self.log, + "BlockGossip"; + "peer" => format!("{:?}", peer_id), + ); + // TODO: filter out messages that a prior to the finalized slot. + // + // TODO: if the block is a few more slots ahead, try to get all block roots from then until + // now. + // + // Note: only requests the new block -- will fail if we don't have its parents. + if self.import_queue.is_new_block(&msg.root.block_root) { + self.request_block_headers( + peer_id, + BeaconBlockHeadersRequest { + start_root: msg.root.block_root, + start_slot: msg.root.slot, + max_headers: 1, + skip_slots: 0, + }, + network, + ) + } + } + + /// Process a gossip message declaring a new attestation. + /// + /// Not currently implemented. + pub fn on_attestation_gossip( + &mut self, + peer_id: PeerId, + msg: AttestationGossip, + _network: &mut NetworkContext, + ) { + debug!( + self.log, + "AttestationGossip"; + "peer" => format!("{:?}", peer_id), + ); + + // Awaiting a proper operations pool before we can import attestations. + // + // https://github.com/sigp/lighthouse/issues/281 + match self.chain.process_attestation(msg.attestation) { + Ok(_) => panic!("Impossible, method not implemented."), + Err(_) => error!(self.log, "Attestation processing not implemented!"), + } + } + /// Iterate through the `import_queue` and process any complete blocks. /// /// If a block is successfully processed it is removed from the queue, otherwise it remains in From 4fdb01e5f06df069aa2d0a1e10237d3135004bc8 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 15:10:26 +1100 Subject: [PATCH 50/97] Correct slot duration interval timer --- validator_client/src/service.rs | 67 ++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 49acd8ad2..c88db29b8 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -39,8 +39,8 @@ pub struct Service { slot_clock: Arc, /// The current slot we are processing. current_slot: Slot, - /// Micro seconds until the next slot. This is used for initializing the tokio timer interval. - micros_to_next_slot: Duration, + /// Duration until the next slot. This is used for initializing the tokio timer interval. + duration_to_next_slot: Duration, // GRPC Clients /// The beacon block GRPC client. beacon_block_client: Arc, @@ -76,13 +76,25 @@ impl Service { std::thread::sleep(Duration::from_secs(5)); continue; } - Ok(info) => break info, + Ok(info) => { + if SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + > Duration::from_secs(info.genesis_time) + { + warn!( + log, + "Beacon Node's genesis time is in the future. No work to do.\n Exiting" + ); + // return Err("Genesis Time in the future"); + } + break info; + } }; }; // build requisite objects to form Self let genesis_time = node_info.get_genesis_time(); - let genesis_time = 1_549_935_547; info!(log,"Beacon node connected"; "Node Version" => node_info.version.clone(), "Chain ID" => node_info.chain_id, "Genesis time" => genesis_time); @@ -127,46 +139,38 @@ impl Service { //TODO: Add error chain. Handle errors let current_slot = slot_clock.present_slot().unwrap().unwrap().sub(1); - // calculate seconds to the next slot - let micros_to_next_slot = { + // calculate the duration to the next slot + let duration_to_next_slot = { let syslot_time = SystemTime::now(); let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH).unwrap(); - debug!(log, "Duration since unix epoch {:?}", duration_since_epoch); - let mut micros_to_slot = None; + let mut duration_to_next_slot = None; if let Some(duration_since_genesis) = duration_since_epoch.checked_sub(Duration::from_secs(genesis_time)) { - // seconds till next slot - debug!(log, "Genesis Time {:?}", genesis_time); - debug!(log, "Duration since genesis {:?}", duration_since_genesis); - micros_to_slot = duration_since_genesis + let elapsed_slots = duration_since_epoch .as_secs() - .checked_rem(config.spec.seconds_per_slot); + .checked_div(config.spec.seconds_per_slot as u64) + .unwrap(); + duration_to_next_slot = Some( + Duration::from_secs( + (elapsed_slots + 1) + .checked_mul(config.spec.seconds_per_slot) + .unwrap(), + ) + .checked_sub(duration_since_genesis) + .expect("This should never saturate"), + ); } - micros_to_slot.unwrap_or_else(|| 0) - /* - let duration_to_slot = duration_since_genesis - .checked_sub(Duration::from( - duration_since_genesis - .checked_div(config.spec.seconds_per_slot as u64) - .unwrap() - .as_secs() - .checked_mul(config.spec.seconds_per_slot) - .unwrap(), - )) - .unwrap(); - */ + duration_to_next_slot.unwrap_or_else(|| Duration::from_secs(0)) }; - info!(log, ""; "Micro Seconds to next slot"=>micros_to_next_slot); - Self { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, slot_clock, current_slot, - micros_to_next_slot: Duration::from_micros(micros_to_next_slot), + duration_to_next_slot, beacon_block_client, validator_client, attester_client, @@ -194,7 +198,10 @@ impl Service { // Set the interval to start at the next slot, and every slot after let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); //TODO: Handle checked add correctly - Interval::new(Instant::now() + service.micros_to_next_slot, slot_duration) + Interval::new( + Instant::now() + service.duration_to_next_slot, + slot_duration, + ) }; // kick off core service From ebb9ced0a47331980ed74c42ffe4f638ff55979a Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Mon, 25 Mar 2019 15:30:46 +1100 Subject: [PATCH 51/97] Improve peer status handling --- beacon_node/network/src/message_handler.rs | 8 +- beacon_node/network/src/sync/simple_sync.rs | 108 ++++++++++++++------ 2 files changed, 81 insertions(+), 35 deletions(-) diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index a788e83c9..5b3fe1a63 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -4,7 +4,7 @@ use crate::service::{NetworkMessage, OutgoingMessage}; use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use eth2_libp2p::{ - rpc::{IncomingGossip, RPCRequest, RPCResponse}, + rpc::{methods::GoodbyeReason, IncomingGossip, RPCRequest, RPCResponse}, PeerId, RPCEvent, }; use futures::future; @@ -199,7 +199,8 @@ impl MessageHandler { .on_block_gossip(peer_id, message, &mut self.network_context) } IncomingGossip::Attestation(message) => { - // + self.sync + .on_attestation_gossip(peer_id, message, &mut self.network_context) } } } @@ -226,7 +227,8 @@ impl NetworkContext { } } - pub fn disconnect(&self, _peer_id: PeerId) { + pub fn disconnect(&mut self, peer_id: PeerId, reason: GoodbyeReason) { + self.send_rpc_request(peer_id, RPCRequest::Goodbye(reason)) // TODO: disconnect peers. } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 06ccbafd3..05c1a0430 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -27,9 +27,9 @@ pub struct PeerSyncInfo { } impl PeerSyncInfo { - /// Returns `true` if the peer is on the same chain as `other`. - fn is_on_same_chain(&self, other: Self) -> bool { - self.network_id == other.network_id + /// Returns `true` if the has a different network ID to `other`. + fn has_different_network_id_to(&self, other: Self) -> bool { + self.network_id != other.network_id } /// Returns `true` if the peer has a higher finalized epoch than `other`. @@ -41,19 +41,6 @@ impl PeerSyncInfo { fn has_higher_best_slot_than(&self, other: Self) -> bool { self.best_slot > other.best_slot } - - /// Returns the `PeerStatus` of `self` in relation to `other`. - pub fn status_compared_to(&self, other: Self) -> PeerStatus { - if self.has_higher_finalized_epoch_than(other) { - PeerStatus::HigherFinalizedEpoch - } else if !self.is_on_same_chain(other) { - PeerStatus::OnDifferentChain - } else if self.has_higher_best_slot_than(other) { - PeerStatus::HigherBestSlot - } else { - PeerStatus::NotInteresting - } - } } /// The status of a peers view on the chain, relative to some other view of the chain (presumably @@ -61,7 +48,9 @@ impl PeerSyncInfo { #[derive(PartialEq, Clone, Copy, Debug)] pub enum PeerStatus { /// The peer is on a completely different chain. - OnDifferentChain, + DifferentNetworkId, + /// The peer lists a finalized epoch for which we have a different root. + FinalizedEpochNotInChain, /// The peer has a higher finalized epoch. HigherFinalizedEpoch, /// The peer has a higher best slot. @@ -70,6 +59,18 @@ pub enum PeerStatus { NotInteresting, } +impl PeerStatus { + pub fn should_handshake(&self) -> bool { + match self { + PeerStatus::DifferentNetworkId => false, + PeerStatus::FinalizedEpochNotInChain => false, + PeerStatus::HigherFinalizedEpoch => true, + PeerStatus::HigherBestSlot => true, + PeerStatus::NotInteresting => true, + } + } +} + impl From for PeerSyncInfo { fn from(hello: HelloMessage) -> PeerSyncInfo { PeerSyncInfo { @@ -183,6 +184,51 @@ impl SimpleSync { self.process_hello(peer_id, hello, network); } + /// Returns a `PeerStatus` for some peer. + fn peer_status(&self, peer: PeerSyncInfo) -> PeerStatus { + let local = PeerSyncInfo::from(&self.chain); + + if peer.has_different_network_id_to(local) { + return PeerStatus::DifferentNetworkId; + } + + if local.has_higher_finalized_epoch_than(peer) { + let peer_finalized_slot = peer + .latest_finalized_epoch + .start_slot(self.chain.get_spec().slots_per_epoch); + + let local_roots = self.chain.get_block_roots(peer_finalized_slot, 1, 0); + + if let Ok(local_roots) = local_roots { + if let Some(local_root) = local_roots.get(0) { + if *local_root != peer.latest_finalized_root { + return PeerStatus::FinalizedEpochNotInChain; + } + } else { + error!( + self.log, + "Cannot get root for peer finalized slot."; + "error" => "empty roots" + ); + } + } else { + error!( + self.log, + "Cannot get root for peer finalized slot."; + "error" => format!("{:?}", local_roots) + ); + } + } + + if peer.has_higher_finalized_epoch_than(local) { + PeerStatus::HigherFinalizedEpoch + } else if peer.has_higher_best_slot_than(local) { + PeerStatus::HigherBestSlot + } else { + PeerStatus::NotInteresting + } + } + /// Process a `Hello` message, requesting new blocks if appropriate. /// /// Disconnects the peer if required. @@ -196,26 +242,22 @@ impl SimpleSync { let remote = PeerSyncInfo::from(hello); let local = PeerSyncInfo::from(&self.chain); - let remote_status = remote.status_compared_to(local); + let remote_status = self.peer_status(remote); - // network id must match - if remote_status != PeerStatus::OnDifferentChain { + if remote_status.should_handshake() { info!(self.log, "HandshakeSuccess"; "peer" => format!("{:?}", peer_id)); self.known_peers.insert(peer_id.clone(), remote); + } else { + info!( + self.log, "HandshakeFailure"; + "peer" => format!("{:?}", peer_id), + "reason" => "network_id" + ); + network.disconnect(peer_id.clone(), GoodbyeReason::IrreleventNetwork); } - // TODO: boot peer if finalization is wrong. - + // If required, send requests for blocks. match remote_status { - PeerStatus::OnDifferentChain => { - info!( - self.log, "Failure"; - "peer" => format!("{:?}", peer_id), - "reason" => "network_id" - ); - - network.disconnect(peer_id); - } PeerStatus::HigherFinalizedEpoch => { let start_slot = remote .latest_finalized_epoch @@ -243,6 +285,8 @@ impl SimpleSync { network, ); } + PeerStatus::FinalizedEpochNotInChain => {} + PeerStatus::DifferentNetworkId => {} PeerStatus::NotInteresting => {} } } @@ -541,7 +585,7 @@ impl SimpleSync { "sender_peer_id" => format!("{:?}", sender), "reason" => format!("{:?}", outcome), ); - network.disconnect(sender); + network.disconnect(sender, GoodbyeReason::Fault); } // If this results to true, the item will be removed from the queue. From 32a025bdf78d818939bfa047f3389246d23eb6d8 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Mon, 25 Mar 2019 16:48:44 +1100 Subject: [PATCH 52/97] Introduced `RequestId` newtype --- beacon_node/eth2-libp2p/src/rpc/mod.rs | 2 +- beacon_node/eth2-libp2p/src/rpc/protocol.rs | 58 +++++++++++++- beacon_node/network/src/message_handler.rs | 88 ++++++++++++--------- beacon_node/network/src/sync/simple_sync.rs | 12 ++- beacon_node/network/tests/tests.rs | 16 ++-- 5 files changed, 125 insertions(+), 51 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/rpc/mod.rs b/beacon_node/eth2-libp2p/src/rpc/mod.rs index 925c36616..e04540416 100644 --- a/beacon_node/eth2-libp2p/src/rpc/mod.rs +++ b/beacon_node/eth2-libp2p/src/rpc/mod.rs @@ -12,7 +12,7 @@ use libp2p::core::swarm::{ }; use libp2p::{Multiaddr, PeerId}; pub use methods::{HelloMessage, IncomingGossip, RPCMethod, RPCRequest, RPCResponse}; -pub use protocol::{RPCEvent, RPCProtocol}; +pub use protocol::{RPCEvent, RPCProtocol, RequestId}; use slog::o; use std::marker::PhantomData; use tokio::io::{AsyncRead, AsyncWrite}; diff --git a/beacon_node/eth2-libp2p/src/rpc/protocol.rs b/beacon_node/eth2-libp2p/src/rpc/protocol.rs index b328dd0dd..2c8945cb8 100644 --- a/beacon_node/eth2-libp2p/src/rpc/protocol.rs +++ b/beacon_node/eth2-libp2p/src/rpc/protocol.rs @@ -1,6 +1,7 @@ use super::methods::*; use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo}; -use ssz::{ssz_encode, Decodable, Encodable, SszStream}; +use ssz::{ssz_encode, Decodable, DecodeError as SSZDecodeError, Encodable, SszStream}; +use std::hash::{Hash, Hasher}; use std::io; use std::iter; use tokio::io::{AsyncRead, AsyncWrite}; @@ -29,16 +30,65 @@ impl Default for RPCProtocol { } } +/// A monotonic counter for ordering `RPCRequest`s. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct RequestId(u64); + +impl RequestId { + /// Increment the request id. + pub fn increment(&mut self) { + self.0 += 1 + } + + /// Return the previous id. + pub fn previous(&self) -> Self { + Self(self.0 - 1) + } +} + +impl Eq for RequestId {} + +impl Hash for RequestId { + fn hash(&self, state: &mut H) { + self.0.hash(state); + } +} + +impl From for RequestId { + fn from(x: u64) -> RequestId { + RequestId(x) + } +} + +impl Into for RequestId { + fn into(self) -> u64 { + self.0 + } +} + +impl Encodable for RequestId { + fn ssz_append(&self, s: &mut SszStream) { + self.0.ssz_append(s); + } +} + +impl Decodable for RequestId { + fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), SSZDecodeError> { + let (id, index) = u64::ssz_decode(bytes, index)?; + Ok((Self::from(id), index)) + } +} + /// The RPC types which are sent/received in this protocol. #[derive(Debug, Clone)] pub enum RPCEvent { Request { - id: u64, + id: RequestId, method_id: u16, body: RPCRequest, }, Response { - id: u64, + id: RequestId, method_id: u16, //TODO: Remove and process decoding upstream result: RPCResponse, }, @@ -72,7 +122,7 @@ fn decode(packet: Vec) -> Result { // decode the header of the rpc // request/response let (request, index) = bool::ssz_decode(&packet, 0)?; - let (id, index) = u64::ssz_decode(&packet, index)?; + let (id, index) = RequestId::ssz_decode(&packet, index)?; let (method_id, index) = u16::ssz_decode(&packet, index)?; if request { diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 5b3fe1a63..12fb2fa6e 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -4,7 +4,7 @@ use crate::service::{NetworkMessage, OutgoingMessage}; use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use eth2_libp2p::{ - rpc::{methods::GoodbyeReason, IncomingGossip, RPCRequest, RPCResponse}, + rpc::{methods::GoodbyeReason, IncomingGossip, RPCRequest, RPCResponse, RequestId}, PeerId, RPCEvent, }; use futures::future; @@ -111,25 +111,31 @@ impl MessageHandler { } /// A new RPC request has been received from the network. - fn handle_rpc_request(&mut self, peer_id: PeerId, _id: u64, request: RPCRequest) { + fn handle_rpc_request(&mut self, peer_id: PeerId, request_id: RequestId, request: RPCRequest) { // TODO: process the `id`. match request { - RPCRequest::Hello(hello_message) => { - self.sync - .on_hello_request(peer_id, hello_message, &mut self.network_context) - } + RPCRequest::Hello(hello_message) => self.sync.on_hello_request( + peer_id, + request_id, + hello_message, + &mut self.network_context, + ), RPCRequest::Goodbye(goodbye_reason) => self.sync.on_goodbye(peer_id, goodbye_reason), - RPCRequest::BeaconBlockRoots(request) => { - self.sync - .on_beacon_block_roots_request(peer_id, request, &mut self.network_context) - } + RPCRequest::BeaconBlockRoots(request) => self.sync.on_beacon_block_roots_request( + peer_id, + request_id, + request, + &mut self.network_context, + ), RPCRequest::BeaconBlockHeaders(request) => self.sync.on_beacon_block_headers_request( peer_id, + request_id, request, &mut self.network_context, ), RPCRequest::BeaconBlockBodies(request) => self.sync.on_beacon_block_bodies_request( peer_id, + request_id, request, &mut self.network_context, ), @@ -143,17 +149,23 @@ impl MessageHandler { /// An RPC response has been received from the network. // we match on id and ignore responses past the timeout. - fn handle_rpc_response(&mut self, peer_id: PeerId, id: u64, response: RPCResponse) { - // if response id is related to a request, ignore (likely RPC timeout) + fn handle_rpc_response(&mut self, peer_id: PeerId, id: RequestId, response: RPCResponse) { + // if response id is not related to a request, ignore (likely RPC timeout) if self .network_context - .requests - .remove(&(peer_id.clone(), id)) + .outstanding_outgoing_request_ids + .remove(&(peer_id.clone(), id.clone())) .is_none() { - debug!(self.log, "Unrecognised response from peer: {:?}", peer_id); + warn!( + self.log, + "Unknown ResponseId for incoming RPCRequest"; + "peer" => format!("{:?}", peer_id), + "request_id" => format!("{:?}", id) + ); return; } + match response { RPCResponse::Hello(hello_message) => { self.sync @@ -210,9 +222,9 @@ pub struct NetworkContext { /// The network channel to relay messages to the Network service. network_send: crossbeam_channel::Sender, /// A mapping of peers and the RPC id we have sent an RPC request to. - requests: HashMap<(PeerId, u64), Instant>, - /// A counter of request id for each peer. - request_ids: HashMap, + outstanding_outgoing_request_ids: HashMap<(PeerId, RequestId), Instant>, + /// Stores the next `RequestId` we should include on an outgoing `RPCRequest` to a `PeerId`. + outgoing_request_ids: HashMap, /// The `MessageHandler` logger. log: slog::Logger, } @@ -221,8 +233,8 @@ impl NetworkContext { pub fn new(network_send: crossbeam_channel::Sender, log: slog::Logger) -> Self { Self { network_send, - requests: HashMap::new(), - request_ids: HashMap::new(), + outstanding_outgoing_request_ids: HashMap::new(), + outgoing_request_ids: HashMap::new(), log, } } @@ -234,6 +246,10 @@ impl NetworkContext { pub fn send_rpc_request(&mut self, peer_id: PeerId, rpc_request: RPCRequest) { let id = self.generate_request_id(&peer_id); + + self.outstanding_outgoing_request_ids + .insert((peer_id.clone(), id.clone()), Instant::now()); + self.send_rpc_event( peer_id, RPCEvent::Request { @@ -244,12 +260,16 @@ impl NetworkContext { ); } - pub fn send_rpc_response(&mut self, peer_id: PeerId, rpc_response: RPCResponse) { - let id = self.generate_request_id(&peer_id); + pub fn send_rpc_response( + &mut self, + peer_id: PeerId, + request_id: RequestId, + rpc_response: RPCResponse, + ) { self.send_rpc_event( peer_id, RPCEvent::Response { - id, + id: request_id, method_id: rpc_response.method_id(), result: rpc_response, }, @@ -272,18 +292,14 @@ impl NetworkContext { // } - /// Generates a new request id for a peer. - fn generate_request_id(&mut self, peer_id: &PeerId) -> u64 { - // generate a unique id for the peer - let id = { - let borrowed_id = self.request_ids.entry(peer_id.clone()).or_insert_with(|| 0); - let id = borrowed_id.clone(); - //increment the counter - *borrowed_id += 1; - id - }; - // register RPC request - self.requests.insert((peer_id.clone(), id), Instant::now()); - id + /// Returns the next `RequestId` for sending an `RPCRequest` to the `peer_id`. + fn generate_request_id(&mut self, peer_id: &PeerId) -> RequestId { + let next_id = self + .outgoing_request_ids + .entry(peer_id.clone()) + .and_modify(|id| id.increment()) + .or_insert_with(|| RequestId::from(1)); + + next_id.previous() } } diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 05c1a0430..37c2c4c26 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -2,7 +2,7 @@ use super::import_queue::ImportQueue; use crate::beacon_chain::BeaconChain; use crate::message_handler::NetworkContext; use eth2_libp2p::rpc::methods::*; -use eth2_libp2p::rpc::{RPCRequest, RPCResponse}; +use eth2_libp2p::rpc::{RPCRequest, RPCResponse, RequestId}; use eth2_libp2p::PeerId; use slog::{debug, error, info, o, warn}; use std::collections::HashMap; @@ -157,6 +157,7 @@ impl SimpleSync { pub fn on_hello_request( &mut self, peer_id: PeerId, + request_id: RequestId, hello: HelloMessage, network: &mut NetworkContext, ) { @@ -165,6 +166,7 @@ impl SimpleSync { // Say hello back. network.send_rpc_response( peer_id.clone(), + request_id, RPCResponse::Hello(self.chain.hello_message()), ); @@ -256,7 +258,7 @@ impl SimpleSync { network.disconnect(peer_id.clone(), GoodbyeReason::IrreleventNetwork); } - // If required, send requests for blocks. + // If required, send additional requests. match remote_status { PeerStatus::HigherFinalizedEpoch => { let start_slot = remote @@ -295,6 +297,7 @@ impl SimpleSync { pub fn on_beacon_block_roots_request( &mut self, peer_id: PeerId, + request_id: RequestId, req: BeaconBlockRootsRequest, network: &mut NetworkContext, ) { @@ -333,6 +336,7 @@ impl SimpleSync { network.send_rpc_response( peer_id, + request_id, RPCResponse::BeaconBlockRoots(BeaconBlockRootsResponse { roots }), ) } @@ -385,6 +389,7 @@ impl SimpleSync { pub fn on_beacon_block_headers_request( &mut self, peer_id: PeerId, + request_id: RequestId, req: BeaconBlockHeadersRequest, network: &mut NetworkContext, ) { @@ -415,6 +420,7 @@ impl SimpleSync { network.send_rpc_response( peer_id, + request_id, RPCResponse::BeaconBlockHeaders(BeaconBlockHeadersResponse { headers }), ) } @@ -454,6 +460,7 @@ impl SimpleSync { pub fn on_beacon_block_bodies_request( &mut self, peer_id: PeerId, + request_id: RequestId, req: BeaconBlockBodiesRequest, network: &mut NetworkContext, ) { @@ -480,6 +487,7 @@ impl SimpleSync { network.send_rpc_response( peer_id, + request_id, RPCResponse::BeaconBlockBodies(BeaconBlockBodiesResponse { block_bodies }), ) } diff --git a/beacon_node/network/tests/tests.rs b/beacon_node/network/tests/tests.rs index 110450dc9..9cead1b55 100644 --- a/beacon_node/network/tests/tests.rs +++ b/beacon_node/network/tests/tests.rs @@ -1,6 +1,6 @@ use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender}; use eth2_libp2p::rpc::methods::*; -use eth2_libp2p::rpc::{RPCMethod, RPCRequest, RPCResponse}; +use eth2_libp2p::rpc::{RPCMethod, RPCRequest, RPCResponse, RequestId}; use eth2_libp2p::{PeerId, RPCEvent}; use network::beacon_chain::BeaconChain as NetworkBeaconChain; use network::message_handler::{HandlerMessage, MessageHandler}; @@ -82,8 +82,8 @@ impl SyncNode { let network_message = self.recv().expect("Timeout on tee"); let handler_message = match network_message.clone() { - NetworkMessage::Send(peer_id, OutgoingMessage::RPC(event)) => { - HandlerMessage::RPC(peer_id, event) + NetworkMessage::Send(_to_peer_id, OutgoingMessage::RPC(event)) => { + HandlerMessage::RPC(self.peer_id.clone(), event) } _ => panic!("tee cannot parse {:?}", network_message), }; @@ -265,7 +265,7 @@ fn get_logger() -> slog::Logger { pub struct SyncMaster { harness: BeaconChainHarness, peer_id: PeerId, - response_ids: Vec, + response_ids: Vec, } impl SyncMaster { @@ -276,7 +276,7 @@ impl SyncMaster { ) -> Self { let harness = BeaconChainHarness::from_beacon_state_builder(state_builder, spec.clone()); let peer_id = PeerId::random(); - let response_ids = vec![0; node_count]; + let response_ids = vec![RequestId::from(0); node_count]; Self { harness, @@ -285,9 +285,9 @@ impl SyncMaster { } } - pub fn response_id(&mut self, node: &SyncNode) -> u64 { - let id = self.response_ids[node.id]; - self.response_ids[node.id] += 1; + pub fn response_id(&mut self, node: &SyncNode) -> RequestId { + let id = self.response_ids[node.id].clone(); + self.response_ids[node.id].increment(); id } From ca9af49d4eac240abcf3c4b87237a815f20c03df Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 16:50:15 +1100 Subject: [PATCH 53/97] Adds error handling to validator client service --- beacon_node/client/src/lib.rs | 2 - validator_client/Cargo.toml | 1 + validator_client/src/error.rs | 22 ++++++++ validator_client/src/main.rs | 8 ++- validator_client/src/service.rs | 96 ++++++++++++++++++--------------- 5 files changed, 83 insertions(+), 46 deletions(-) create mode 100644 validator_client/src/error.rs diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index a033da87b..44eab4fe2 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -64,8 +64,6 @@ impl Client { )); } - println!("Here"); - Ok(Client { config, beacon_chain, diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index e8cff2622..ea97ef5d4 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -21,3 +21,4 @@ slog-term = "^2.4.0" slog-async = "^2.3.0" tokio = "0.1.18" tokio-timer = "0.2.10" +error-chain = "0.12.0" diff --git a/validator_client/src/error.rs b/validator_client/src/error.rs new file mode 100644 index 000000000..29d7ba882 --- /dev/null +++ b/validator_client/src/error.rs @@ -0,0 +1,22 @@ +use slot_clock; + +use error_chain::{ + error_chain, error_chain_processing, impl_error_chain_kind, impl_error_chain_processed, + impl_extract_backtrace, +}; + +error_chain! { + links { } + + errors { + SlotClockError(e: slot_clock::SystemTimeSlotClockError) { + description("Error reading system time"), + display("SlotClockError: '{:?}'", e) + } + + SystemTimeError(t: String ) { + description("Error reading system time"), + display("SystemTimeError: '{}'", t) + } + } +} diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 0ec392731..127df8494 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -2,12 +2,13 @@ mod attester_service; mod block_producer_service; mod config; mod duties; +pub mod error; mod service; use crate::config::Config as ValidatorConfig; use clap::{App, Arg}; use service::Service as ValidatorService; -use slog::{o, Drain}; +use slog::{error, info, o, Drain}; fn main() { // Logging @@ -50,5 +51,8 @@ fn main() { let config = ValidatorConfig::parse_args(matches, &log).unwrap(); // start the validator service. - ValidatorService::start(config, log); + match ValidatorService::start(config, log.clone()) { + Ok(_) => info!(log, "Validator client shutdown successfully."), + Err(e) => error!(log, "Validator exited due to {:?}", e), + } } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index c88db29b8..9eeb308db 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -3,6 +3,8 @@ use crate::attester_service::{AttestationGrpcClient, AttesterService}; use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use crate::config::Config as ValidatorConfig; use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; +use crate::error as error_chain; +use crate::error::ErrorKind; use attester::test_utils::EpochMap; use attester::{test_utils::LocalSigner as AttesterLocalSigner, Attester}; use block_proposer::{test_utils::LocalSigner as BlockProposerLocalSigner, BlockProducer}; @@ -13,9 +15,8 @@ use protos::services_grpc::{ AttestationServiceClient, BeaconBlockServiceClient, BeaconNodeServiceClient, ValidatorServiceClient, }; -use slog::{debug, info, warn}; +use slog::{debug, error, info, warn}; use slot_clock::{SlotClock, SystemTimeSlotClock}; -use std::ops::Sub; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime}; use tokio::prelude::*; @@ -57,7 +58,10 @@ impl Service { /// /// This tries to connect to a beacon node. Once connected, it initialised the gRPC clients /// and returns an instance of the service. - fn initialize_service(config: &ValidatorConfig, log: slog::Logger) -> Self { + fn initialize_service( + config: &ValidatorConfig, + log: slog::Logger, + ) -> error_chain::Result { // initialise the beacon node client to check for a connection let env = Arc::new(EnvBuilder::new().build()); @@ -86,7 +90,7 @@ impl Service { log, "Beacon Node's genesis time is in the future. No work to do.\n Exiting" ); - // return Err("Genesis Time in the future"); + return Err("Genesis time in the future".into()); } break info; } @@ -136,35 +140,37 @@ impl Service { Arc::new(AttestationServiceClient::new(ch)) }; - //TODO: Add error chain. Handle errors - let current_slot = slot_clock.present_slot().unwrap().unwrap().sub(1); + let current_slot = slot_clock + .present_slot() + .map_err(|e| ErrorKind::SlotClockError(e))? + .expect("Genesis must be in the future"); // calculate the duration to the next slot let duration_to_next_slot = { + let seconds_per_slot = config.spec.seconds_per_slot; let syslot_time = SystemTime::now(); - let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let mut duration_to_next_slot = None; - if let Some(duration_since_genesis) = - duration_since_epoch.checked_sub(Duration::from_secs(genesis_time)) - { - let elapsed_slots = duration_since_epoch - .as_secs() - .checked_div(config.spec.seconds_per_slot as u64) - .unwrap(); - duration_to_next_slot = Some( - Duration::from_secs( - (elapsed_slots + 1) - .checked_mul(config.spec.seconds_per_slot) - .unwrap(), - ) - .checked_sub(duration_since_genesis) - .expect("This should never saturate"), - ); - } - duration_to_next_slot.unwrap_or_else(|| Duration::from_secs(0)) + let duration_since_epoch = syslot_time + .duration_since(SystemTime::UNIX_EPOCH) + .map_err(|e| ErrorKind::SystemTimeError(e.to_string()))?; + let duration_since_genesis = duration_since_epoch + .checked_sub(Duration::from_secs(genesis_time)) + .expect("Genesis must be in the future. Checked on connection"); + let elapsed_slots = duration_since_epoch + .as_secs() + .checked_div(seconds_per_slot as u64) + .expect("Seconds per slot should not be 0"); + + // the duration to the next slot + Duration::from_secs( + (elapsed_slots + 1) + .checked_mul(seconds_per_slot) + .expect("Next slot time should not overflow u64"), + ) + .checked_sub(duration_since_genesis) + .expect("This should never saturate") }; - Self { + Ok(Self { connected_node_version: node_info.version, chain_id: node_info.chain_id as u16, fork, @@ -175,13 +181,13 @@ impl Service { validator_client, attester_client, log, - } + }) } /// Initialise the service then run the core thread. - pub fn start(config: ValidatorConfig, log: slog::Logger) { + pub fn start(config: ValidatorConfig, log: slog::Logger) -> error_chain::Result<()> { // connect to the node and retrieve its properties and initialize the gRPC clients - let service = Service::initialize_service(&config, log); + let service = Service::initialize_service(&config, log)?; // we have connected to a node and established its parameters. Spin up the core service @@ -190,10 +196,9 @@ impl Service { .clock(Clock::system()) .name_prefix("validator-client-") .build() - .unwrap(); + .map_err(|e| format!("Tokio runtime failed: {}", e))?; // set up the validator work interval - start at next slot and proceed every slot - // TODO: Error chain handle errors. let interval = { // Set the interval to start at the next slot, and every slot after let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); @@ -223,16 +228,23 @@ impl Service { beacon_node: service.validator_client.clone(), }; - runtime.block_on(interval.for_each(move |_| { - // update duties - debug!( - service.log, - "Processing slot: {}", - service.slot_clock.present_slot().unwrap().unwrap().as_u64() - ); - manager.poll(); - Ok(()) - })); + runtime + .block_on(interval.for_each(move |_| { + // update duties + let current_slot = match service.slot_clock.present_slot() { + Err(e) => { + error!(service.log, "SystemTimeError {:?}", e); + return Ok(()); + } + Ok(slot) => slot.expect("Genesis is in the future"), + }; + + debug!(service.log, "Processing slot: {}", current_slot.as_u64()); + manager.poll(); + Ok(()) + })) + .map_err(|e| format!("Service thread failed: {:?}", e))?; + Ok(()) } /* From 3ad18b4367047b4fab37b3946004c06086c8b080 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 17:47:23 +1100 Subject: [PATCH 54/97] Adds manager duties to validator runtime --- validator_client/src/main.rs | 2 +- validator_client/src/service.rs | 30 ++++++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 1c59513a7..84d0cbff7 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -54,6 +54,6 @@ fn main() { // start the validator service. match ValidatorService::start(config, log.clone()) { Ok(_) => info!(log, "Validator client shutdown successfully."), - Err(e) => error!(log, "Validator exited due to {:?}", e), + Err(e) => error!(log, "Validator exited due to: {}", e.to_string()), } } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 9eeb308db..720388a61 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -2,6 +2,7 @@ use crate::attester_service::{AttestationGrpcClient, AttesterService}; use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use crate::config::Config as ValidatorConfig; +use crate::duties::PollOutcome; use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; use crate::error as error_chain; use crate::error::ErrorKind; @@ -84,7 +85,8 @@ impl Service { if SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() - > Duration::from_secs(info.genesis_time) + .as_secs() + < info.genesis_time { warn!( log, @@ -239,8 +241,32 @@ impl Service { Ok(slot) => slot.expect("Genesis is in the future"), }; + debug_assert!( + current_slot > service.current_slot, + "The Timer should poll a new slot" + ); + debug!(service.log, "Processing slot: {}", current_slot.as_u64()); - manager.poll(); + + // check for new duties + match manager.poll() { + Err(error) => { + error!(service.log, "Epoch duties poll error"; "error" => format!("{:?}", error)) + } + Ok(PollOutcome::NoChange(epoch)) => { + debug!(service.log, "No change in duties"; "epoch" => epoch) + } + Ok(PollOutcome::DutiesChanged(epoch, duties)) => { + info!(service.log, "Duties changed (potential re-org)"; "epoch" => epoch, "duties" => format!("{:?}", duties)) + } + Ok(PollOutcome::NewDuties(epoch, duties)) => { + info!(service.log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) + } + Ok(PollOutcome::UnknownValidatorOrEpoch(epoch)) => { + error!(service.log, "Epoch or validator unknown"; "epoch" => epoch) + } + }; + Ok(()) })) .map_err(|e| format!("Service thread failed: {:?}", e))?; From a8a3f1c31881b65e47a7f6c02e5c6135c2e95514 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 18:03:23 +1100 Subject: [PATCH 55/97] Removes duty manager service in favour of tokio timer --- validator_client/src/duties/mod.rs | 26 ++++++----------- validator_client/src/duties/service.rs | 40 -------------------------- validator_client/src/service.rs | 20 +++++++------ 3 files changed, 19 insertions(+), 67 deletions(-) delete mode 100644 validator_client/src/duties/service.rs diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index c2b95b1c5..f6460afd2 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -1,21 +1,19 @@ mod epoch_duties; mod grpc; -mod service; #[cfg(test)] mod test_node; mod traits; pub use self::epoch_duties::EpochDutiesMap; use self::epoch_duties::{EpochDuties, EpochDutiesMapError}; -pub use self::service::DutiesManagerService; use self::traits::{BeaconNode, BeaconNodeError}; use bls::PublicKey; use slot_clock::SlotClock; use std::sync::Arc; -use types::{ChainSpec, Epoch}; +use types::{ChainSpec, Epoch, Slot}; #[derive(Debug, PartialEq, Clone, Copy)] -pub enum PollOutcome { +pub enum UpdateOutcome { /// The `EpochDuties` were not updated during this poll. NoChange(Epoch), /// The `EpochDuties` for the `epoch` were previously unknown, but obtained in the poll. @@ -50,19 +48,11 @@ pub struct DutiesManager { } impl DutiesManager { - /// Poll the Beacon Node for `EpochDuties`. + /// Check the Beacon Node for `EpochDuties`. /// /// The present `epoch` will be learned from the supplied `SlotClock`. In production this will /// be a wall-clock (e.g., system time, remote server time, etc.). - //TODO: Remove the poll and trust the tokio system-clock timer. Leave for now to ensure the - //timer is accurate. - pub fn poll(&self) -> Result { - let slot = self - .slot_clock - .present_slot() - .map_err(|_| Error::SlotClockError)? - .ok_or(Error::SlotUnknowable)?; - + pub fn update(&self, slot: Slot) -> Result { let epoch = slot.epoch(self.spec.slots_per_epoch); if let Some(duties) = self @@ -72,17 +62,17 @@ impl DutiesManager { // If these duties were known, check to see if they're updates or identical. let result = if let Some(known_duties) = self.duties_map.get(epoch)? { if known_duties == duties { - Ok(PollOutcome::NoChange(epoch)) + Ok(UpdateOutcome::NoChange(epoch)) } else { - Ok(PollOutcome::DutiesChanged(epoch, duties)) + Ok(UpdateOutcome::DutiesChanged(epoch, duties)) } } else { - Ok(PollOutcome::NewDuties(epoch, duties)) + Ok(UpdateOutcome::NewDuties(epoch, duties)) }; self.duties_map.insert(epoch, duties)?; result } else { - Ok(PollOutcome::UnknownValidatorOrEpoch(epoch)) + Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) } } } diff --git a/validator_client/src/duties/service.rs b/validator_client/src/duties/service.rs deleted file mode 100644 index bdb6faefa..000000000 --- a/validator_client/src/duties/service.rs +++ /dev/null @@ -1,40 +0,0 @@ -use super::traits::BeaconNode; -use super::{DutiesManager, PollOutcome}; -use slog::{debug, error, info, Logger}; -use slot_clock::SlotClock; -use std::time::Duration; - -pub struct DutiesManagerService { - pub manager: DutiesManager, - pub poll_interval_millis: u64, - pub log: Logger, -} - -impl DutiesManagerService { - /// Run a loop which polls the manager each `poll_interval_millis` milliseconds. - /// - /// Logs the results of the polls. - pub fn run(&mut self) { - loop { - match self.manager.poll() { - Err(error) => { - error!(self.log, "Epoch duties poll error"; "error" => format!("{:?}", error)) - } - Ok(PollOutcome::NoChange(epoch)) => { - debug!(self.log, "No change in duties"; "epoch" => epoch) - } - Ok(PollOutcome::DutiesChanged(epoch, duties)) => { - info!(self.log, "Duties changed (potential re-org)"; "epoch" => epoch, "duties" => format!("{:?}", duties)) - } - Ok(PollOutcome::NewDuties(epoch, duties)) => { - info!(self.log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) - } - Ok(PollOutcome::UnknownValidatorOrEpoch(epoch)) => { - error!(self.log, "Epoch or validator unknown"; "epoch" => epoch) - } - }; - - std::thread::sleep(Duration::from_millis(self.poll_interval_millis)); - } - } -} diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 720388a61..8a7e90d10 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -2,8 +2,8 @@ use crate::attester_service::{AttestationGrpcClient, AttesterService}; use crate::block_producer_service::{BeaconBlockGrpcClient, BlockProducerService}; use crate::config::Config as ValidatorConfig; -use crate::duties::PollOutcome; -use crate::duties::{DutiesManager, DutiesManagerService, EpochDutiesMap}; +use crate::duties::UpdateOutcome; +use crate::duties::{DutiesManager, EpochDutiesMap}; use crate::error as error_chain; use crate::error::ErrorKind; use attester::test_utils::EpochMap; @@ -230,9 +230,10 @@ impl Service { beacon_node: service.validator_client.clone(), }; + // run the core thread runtime .block_on(interval.for_each(move |_| { - // update duties + // get the current slot let current_slot = match service.slot_clock.present_slot() { Err(e) => { error!(service.log, "SystemTimeError {:?}", e); @@ -246,23 +247,24 @@ impl Service { "The Timer should poll a new slot" ); - debug!(service.log, "Processing slot: {}", current_slot.as_u64()); + info!(service.log, "Processing slot: {}", current_slot.as_u64()); // check for new duties - match manager.poll() { + // TODO: Convert to its own thread + match manager.update(current_slot) { Err(error) => { error!(service.log, "Epoch duties poll error"; "error" => format!("{:?}", error)) } - Ok(PollOutcome::NoChange(epoch)) => { + Ok(UpdateOutcome::NoChange(epoch)) => { debug!(service.log, "No change in duties"; "epoch" => epoch) } - Ok(PollOutcome::DutiesChanged(epoch, duties)) => { + Ok(UpdateOutcome::DutiesChanged(epoch, duties)) => { info!(service.log, "Duties changed (potential re-org)"; "epoch" => epoch, "duties" => format!("{:?}", duties)) } - Ok(PollOutcome::NewDuties(epoch, duties)) => { + Ok(UpdateOutcome::NewDuties(epoch, duties)) => { info!(service.log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) } - Ok(PollOutcome::UnknownValidatorOrEpoch(epoch)) => { + Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) => { error!(service.log, "Epoch or validator unknown"; "epoch" => epoch) } }; From 4cdeb6abe50f96860921eaab58d938e75793b423 Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Mon, 25 Mar 2019 18:32:27 +1100 Subject: [PATCH 56/97] Progress towards validator signing attestations. - Added a 'beacon_attester' RPC endpoint, so the BeaconNode can supply attestation data. - Renamed 'attestation_data' to just 'attestation' throughout (except where it is actually just the data structure). --- beacon_node/beacon_chain/src/beacon_chain.rs | 4 +- .../validator_harness/direct_beacon_node.rs | 6 +- beacon_node/rpc/src/beacon_attester.rs | 61 +++++++++++++++++++ eth2/attester/src/lib.rs | 4 +- .../src/test_utils/simulated_beacon_node.rs | 4 +- eth2/attester/src/traits.rs | 4 +- protos/src/services.proto | 18 +++--- .../attestation_grpc_client.rs | 12 ++-- 8 files changed, 87 insertions(+), 26 deletions(-) create mode 100644 beacon_node/rpc/src/beacon_attester.rs diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 816a570c0..61b5fb58b 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -280,8 +280,8 @@ where } /// Produce an `AttestationData` that is valid for the present `slot` and given `shard`. - pub fn produce_attestation_data(&self, shard: u64) -> Result { - trace!("BeaconChain::produce_attestation_data: shard: {}", shard); + pub fn produce_attestation(&self, shard: u64) -> Result { + trace!("BeaconChain::produce_attestation: shard: {}", shard); let source_epoch = self.state.read().current_justified_epoch; let source_root = *self.state.read().get_block_root( source_epoch.start_slot(self.spec.slots_per_epoch), diff --git a/beacon_node/beacon_chain/test_harness/src/validator_harness/direct_beacon_node.rs b/beacon_node/beacon_chain/test_harness/src/validator_harness/direct_beacon_node.rs index d2de354d7..fde8211ab 100644 --- a/beacon_node/beacon_chain/test_harness/src/validator_harness/direct_beacon_node.rs +++ b/beacon_node/beacon_chain/test_harness/src/validator_harness/direct_beacon_node.rs @@ -50,18 +50,18 @@ impl DirectBeaconNode { } impl AttesterBeaconNode for DirectBeaconNode { - fn produce_attestation_data( + fn produce_attestation( &self, _slot: Slot, shard: u64, ) -> Result, NodeError> { - match self.beacon_chain.produce_attestation_data(shard) { + match self.beacon_chain.produce_attestation(shard) { Ok(attestation_data) => Ok(Some(attestation_data)), Err(e) => Err(NodeError::RemoteFailure(format!("{:?}", e))), } } - fn publish_attestation_data( + fn publish_attestation( &self, free_attestation: FreeAttestation, ) -> Result { diff --git a/beacon_node/rpc/src/beacon_attester.rs b/beacon_node/rpc/src/beacon_attester.rs new file mode 100644 index 000000000..36b6a40b2 --- /dev/null +++ b/beacon_node/rpc/src/beacon_attester.rs @@ -0,0 +1,61 @@ +use futures::Future; +use grpcio::{RpcContext, UnarySink}; +use protos::services::{ + Attestation as AttestationProto, ProduceAttestation, ProduceAttestationResponse, + ProduceAttestationRequest, PublishAttestationResponse, PublishAttestationRequest, + PublishAttestation +}; +use protos::services_grpc::BeaconBlockService; +use slog::Logger; + +#[derive(Clone)] +pub struct AttestationServiceInstance { + pub log: Logger, +} + +impl AttestationService for AttestationServiceInstance { + /// Produce a `BeaconBlock` for signing by a validator. + fn produce_attestation( + &mut self, + ctx: RpcContext, + req: ProduceAttestationRequest, + sink: UnarySink, + ) { + println!("producing attestation at slot {}", req.get_slot()); + + // TODO: build a legit block. + let mut attestation = AttestationProto::new(); + attestation.set_slot(req.get_slot()); + // TODO Set the shard to something legit. + attestation.set_shard(0); + attestation.set_block_root(b"cats".to_vec()); + + let mut resp = ProduceAttestationResponse::new(); + resp.set_attestation_data(attestation); + + let f = sink + .success(resp) + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + ctx.spawn(f) + } + + /// Accept some fully-formed `BeaconBlock`, process and publish it. + fn publish_attestation( + &mut self, + ctx: RpcContext, + req: PublishAttestationRequest, + sink: UnarySink, + ) { + println!("publishing attestation {:?}", req.get_block()); + + // TODO: actually process the block. + let mut resp = PublishAttestationResponse::new(); + + resp.set_success(true); + + let f = sink + .success(resp) + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + ctx.spawn(f) + } +} diff --git a/eth2/attester/src/lib.rs b/eth2/attester/src/lib.rs index 8838f022d..065fdc923 100644 --- a/eth2/attester/src/lib.rs +++ b/eth2/attester/src/lib.rs @@ -94,7 +94,7 @@ impl Attester Result { - let attestation_data = match self.beacon_node.produce_attestation_data(slot, shard)? { + let attestation_data = match self.beacon_node.produce_attestation(slot, shard)? { Some(attestation_data) => attestation_data, None => return Ok(PollOutcome::BeaconNodeUnableToProduceAttestation(slot)), }; @@ -120,7 +120,7 @@ impl Attester ProduceResult { + fn produce_attestation(&self, slot: Slot, shard: u64) -> ProduceResult { *self.produce_input.write().unwrap() = Some((slot, shard)); match *self.produce_result.read().unwrap() { Some(ref r) => r.clone(), @@ -34,7 +34,7 @@ impl BeaconNode for SimulatedBeaconNode { } } - fn publish_attestation_data(&self, free_attestation: FreeAttestation) -> PublishResult { + fn publish_attestation(&self, free_attestation: FreeAttestation) -> PublishResult { *self.publish_input.write().unwrap() = Some(free_attestation.clone()); match *self.publish_result.read().unwrap() { Some(ref r) => r.clone(), diff --git a/eth2/attester/src/traits.rs b/eth2/attester/src/traits.rs index 6062460cb..749c6e1a2 100644 --- a/eth2/attester/src/traits.rs +++ b/eth2/attester/src/traits.rs @@ -14,13 +14,13 @@ pub enum PublishOutcome { /// Defines the methods required to produce and publish blocks on a Beacon Node. pub trait BeaconNode: Send + Sync { - fn produce_attestation_data( + fn produce_attestation( &self, slot: Slot, shard: u64, ) -> Result, BeaconNodeError>; - fn publish_attestation_data( + fn publish_attestation( &self, free_attestation: FreeAttestation, ) -> Result; diff --git a/protos/src/services.proto b/protos/src/services.proto index fbcde922d..80d512c54 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -33,8 +33,8 @@ service ValidatorService { /// Service that handles validator attestations service AttestationService { - rpc ProduceAttestationData (ProduceAttestationDataRequest) returns (ProduceAttestationDataResponse); - rpc PublishAttestationData (PublishAttestationDataRequest) returns (PublishAttestationDataResponse); + rpc ProduceAttestation(ProduceAttestationRequest) returns (ProduceAttestationResponse); + rpc PublishAttestation(PublishAttestationRequest) returns (PublishAttestationResponse); } /* @@ -138,20 +138,20 @@ message ProposeBlockSlotResponse { * Attestation Service Messages */ -message ProduceAttestationDataRequest { +message ProduceAttestationRequest { uint64 slot = 1; uint64 shard = 2; } -message ProduceAttestationDataResponse { - AttestationData attestation_data = 1; +message ProduceAttestationResponse { + Attestation attestation_data = 1; } -message PublishAttestationDataRequest { +message PublishAttestationRequest { FreeAttestation free_attestation = 1; } -message PublishAttestationDataResponse { +message PublishAttestationResponse { bool success = 1; bytes msg = 2; } @@ -162,7 +162,7 @@ message Crosslink { } -message AttestationData { +message Attestation { uint64 slot = 1; uint64 shard = 2; bytes beacon_block_root = 3; @@ -175,7 +175,7 @@ message AttestationData { } message FreeAttestation { - AttestationData attestation_data = 1; + Attestation attestation_data = 1; bytes signature = 2; uint64 validator_index = 3; } diff --git a/validator_client/src/attester_service/attestation_grpc_client.rs b/validator_client/src/attester_service/attestation_grpc_client.rs index 566d74a39..5a4701ba9 100644 --- a/validator_client/src/attester_service/attestation_grpc_client.rs +++ b/validator_client/src/attester_service/attestation_grpc_client.rs @@ -2,7 +2,7 @@ use protos::services_grpc::AttestationServiceClient; use std::sync::Arc; use attester::{BeaconNode, BeaconNodeError, PublishOutcome}; -use protos::services::ProduceAttestationDataRequest; +use protos::services::ProduceAttestationRequest; use types::{AttestationData, FreeAttestation, Slot}; pub struct AttestationGrpcClient { @@ -16,25 +16,25 @@ impl AttestationGrpcClient { } impl BeaconNode for AttestationGrpcClient { - fn produce_attestation_data( + fn produce_attestation( &self, slot: Slot, shard: u64, ) -> Result, BeaconNodeError> { - let mut req = ProduceAttestationDataRequest::new(); + let mut req = ProduceAttestationRequest::new(); req.set_slot(slot.as_u64()); req.set_shard(shard); let reply = self .client - .produce_attestation_data(&req) + .produce_attestation(&req) .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; - // TODO: return correct AttestationData + // TODO: return correct Attestation Err(BeaconNodeError::DecodeFailure) } - fn publish_attestation_data( + fn publish_attestation( &self, free_attestation: FreeAttestation, ) -> Result { From 098e63ac327ea8a7b64df2d4fbdbe5f794f37671 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Mon, 25 Mar 2019 18:59:50 +1100 Subject: [PATCH 57/97] Move gossip structs into behaviour --- beacon_node/eth2-libp2p/src/behaviour.rs | 21 +++++++++++++++++++++ beacon_node/eth2-libp2p/src/rpc/methods.rs | 18 ------------------ beacon_node/eth2-libp2p/src/rpc/mod.rs | 2 +- beacon_node/network/src/message_handler.rs | 3 ++- beacon_node/network/src/sync/simple_sync.rs | 1 + 5 files changed, 25 insertions(+), 20 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index 458b32cf9..3d5b94353 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -1,3 +1,4 @@ +use crate::rpc::methods::BlockRootSlot; use crate::rpc::{RPCEvent, RPCMessage, Rpc}; use crate::NetworkConfig; use futures::prelude::*; @@ -13,6 +14,8 @@ use libp2p::{ NetworkBehaviour, PeerId, }; use slog::{debug, o}; +use ssz_derive::{Decode, Encode}; +use types::Attestation; use types::Topic; /// Builds the network behaviour for the libp2p Swarm. @@ -154,3 +157,21 @@ pub enum BehaviourEvent { // TODO: This is a stub at the moment Message(String), } + +#[derive(Debug, Clone)] +pub enum IncomingGossip { + Block(BlockGossip), + Attestation(AttestationGossip), +} + +/// Gossipsub message providing notification of a new block. +#[derive(Encode, Decode, Clone, Debug, PartialEq)] +pub struct BlockGossip { + pub root: BlockRootSlot, +} + +/// Gossipsub message providing notification of a new attestation. +#[derive(Encode, Decode, Clone, Debug, PartialEq)] +pub struct AttestationGossip { + pub attestation: Attestation, +} diff --git a/beacon_node/eth2-libp2p/src/rpc/methods.rs b/beacon_node/eth2-libp2p/src/rpc/methods.rs index 47e47f3eb..ad3233be7 100644 --- a/beacon_node/eth2-libp2p/src/rpc/methods.rs +++ b/beacon_node/eth2-libp2p/src/rpc/methods.rs @@ -97,12 +97,6 @@ impl RPCResponse { } } -#[derive(Debug, Clone)] -pub enum IncomingGossip { - Block(BlockGossip), - Attestation(AttestationGossip), -} - /* Request/Response data structures for RPC methods */ /// The HELLO request/response handshake message. @@ -242,15 +236,3 @@ pub struct BeaconChainStateResponse { /// The values corresponding the to the requested tree hashes. pub values: bool, //TBD - stubbed with encodeable bool } - -/// Gossipsub message providing notification of a new block. -#[derive(Encode, Decode, Clone, Debug, PartialEq)] -pub struct BlockGossip { - pub root: BlockRootSlot, -} - -/// Gossipsub message providing notification of a new attestation. -#[derive(Encode, Decode, Clone, Debug, PartialEq)] -pub struct AttestationGossip { - pub attestation: Attestation, -} diff --git a/beacon_node/eth2-libp2p/src/rpc/mod.rs b/beacon_node/eth2-libp2p/src/rpc/mod.rs index e04540416..08573aa52 100644 --- a/beacon_node/eth2-libp2p/src/rpc/mod.rs +++ b/beacon_node/eth2-libp2p/src/rpc/mod.rs @@ -11,7 +11,7 @@ use libp2p::core::swarm::{ ConnectedPoint, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use libp2p::{Multiaddr, PeerId}; -pub use methods::{HelloMessage, IncomingGossip, RPCMethod, RPCRequest, RPCResponse}; +pub use methods::{HelloMessage, RPCMethod, RPCRequest, RPCResponse}; pub use protocol::{RPCEvent, RPCProtocol, RequestId}; use slog::o; use std::marker::PhantomData; diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index 12fb2fa6e..dcfee96a0 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -4,7 +4,8 @@ use crate::service::{NetworkMessage, OutgoingMessage}; use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use eth2_libp2p::{ - rpc::{methods::GoodbyeReason, IncomingGossip, RPCRequest, RPCResponse, RequestId}, + behaviour::IncomingGossip, + rpc::{methods::GoodbyeReason, RPCRequest, RPCResponse, RequestId}, PeerId, RPCEvent, }; use futures::future; diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 37c2c4c26..4c08a6871 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,6 +1,7 @@ use super::import_queue::ImportQueue; use crate::beacon_chain::BeaconChain; use crate::message_handler::NetworkContext; +use eth2_libp2p::behaviour::{AttestationGossip, BlockGossip}; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse, RequestId}; use eth2_libp2p::PeerId; From 05369df7e8a8d82a875224b4f4dea242723081ee Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 22:00:11 +1100 Subject: [PATCH 58/97] Add PubsubMessage and publish function to behaviour --- beacon_node/client/src/lib.rs | 3 +- beacon_node/eth2-libp2p/src/behaviour.rs | 56 +++++++++++++++++++++--- beacon_node/network/src/beacon_chain.rs | 2 +- beacon_node/network/src/service.rs | 13 +++++- beacon_node/rpc/src/beacon_block.rs | 11 ++++- beacon_node/rpc/src/lib.rs | 5 ++- 6 files changed, 78 insertions(+), 12 deletions(-) diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index 44eab4fe2..b24d2cb7f 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -46,7 +46,7 @@ impl Client { // TODO: Add beacon_chain reference to network parameters let network_config = &config.net_conf; let network_logger = log.new(o!("Service" => "Network")); - let (network, _network_send) = NetworkService::new( + let (network, network_send) = NetworkService::new( beacon_chain.clone(), network_config, executor, @@ -59,6 +59,7 @@ impl Client { rpc_exit_signal = Some(rpc::start_server( &config.rpc_conf, executor, + network_send, beacon_chain.clone(), &log, )); diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index 3d5b94353..b3c4213b1 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -14,6 +14,7 @@ use libp2p::{ NetworkBehaviour, PeerId, }; use slog::{debug, o}; +use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream}; use ssz_derive::{Decode, Encode}; use types::Attestation; use types::Topic; @@ -124,6 +125,15 @@ impl Behaviour { } } + /* Behaviour functions */ + + /// Publishes a message on the pubsub (gossipsub) behaviour. + pub fn publish(&mut self, topic: Topic, message: PubsubMessage) { + //encode the message + let message_bytes = ssz_encode(&message); + self.gossipsub.publish(topic, message_bytes); + } + /// Consumes the events list when polled. fn poll( &mut self, @@ -158,12 +168,6 @@ pub enum BehaviourEvent { Message(String), } -#[derive(Debug, Clone)] -pub enum IncomingGossip { - Block(BlockGossip), - Attestation(AttestationGossip), -} - /// Gossipsub message providing notification of a new block. #[derive(Encode, Decode, Clone, Debug, PartialEq)] pub struct BlockGossip { @@ -175,3 +179,43 @@ pub struct BlockGossip { pub struct AttestationGossip { pub attestation: Attestation, } + +/// Messages that are passed to and from the pubsub (Gossipsub) behaviour. +#[derive(Debug, Clone)] +pub enum PubsubMessage { + Block(BlockGossip), + Attestation(AttestationGossip), +} + +//TODO: Correctly encode/decode enums. Prefixing with integer for now. +impl Encodable for PubsubMessage { + fn ssz_append(&self, s: &mut SszStream) { + match self { + PubsubMessage::Block(block_gossip) => { + 0u32.ssz_append(s); + block_gossip.ssz_append(s); + } + PubsubMessage::Attestation(attestation_gossip) => { + 1u32.ssz_append(s); + attestation_gossip.ssz_append(s); + } + } + } +} + +impl Decodable for PubsubMessage { + fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), DecodeError> { + let (id, index) = u32::ssz_decode(bytes, index)?; + match id { + 1 => { + let (block, index) = BlockGossip::ssz_decode(bytes, index)?; + Ok((PubsubMessage::Block(block), index)) + } + 2 => { + let (attestation, index) = AttestationGossip::ssz_decode(bytes, index)?; + Ok((PubsubMessage::Attestation(attestation), index)) + } + _ => Err(DecodeError::Invalid), + } + } +} diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index 26cea0065..c627912a4 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -109,7 +109,7 @@ where let state = self.get_state(); HelloMessage { - network_id: spec.network_id, + network_id: spec.chain_id, latest_finalized_root: state.finalized_root, latest_finalized_epoch: state.finalized_epoch, best_root: self.best_block_root(), diff --git a/beacon_node/network/src/service.rs b/beacon_node/network/src/service.rs index a3eb6f0d9..33ea79c1a 100644 --- a/beacon_node/network/src/service.rs +++ b/beacon_node/network/src/service.rs @@ -3,7 +3,7 @@ use crate::error; use crate::message_handler::{HandlerMessage, MessageHandler}; use crate::NetworkConfig; use crossbeam_channel::{unbounded as channel, Sender, TryRecvError}; -use eth2_libp2p::RPCEvent; +use eth2_libp2p::{RPCEvent, PublishMessage}; use eth2_libp2p::Service as LibP2PService; use eth2_libp2p::{Libp2pEvent, PeerId}; use futures::prelude::*; @@ -12,6 +12,7 @@ use futures::Stream; use slog::{debug, info, o, trace}; use std::sync::Arc; use tokio::runtime::TaskExecutor; +use types::{BeaconBlock, Topic}; /// Service that handles communication between internal services and the eth2_libp2p network service. pub struct Service { @@ -161,7 +162,12 @@ fn network_service( return Err(eth2_libp2p::error::Error::from( "Network channel disconnected", )); - } + }, + Ok(NetworkMessage::Publish(topic, message) => { + debug!(log, "Sending message on topic {:?}", topic); + libp2p_service.swarm.publish(topic,message) + + } } Ok(Async::NotReady) @@ -174,6 +180,8 @@ pub enum NetworkMessage { /// Send a message to libp2p service. //TODO: Define typing for messages across the wire Send(PeerId, OutgoingMessage), + /// Publish a message to gossipsub + Publish(Topic, PublishMessage), } /// Type of outgoing messages that can be sent through the network service. @@ -184,3 +192,4 @@ pub enum OutgoingMessage { //TODO: Remove NotifierTest, } + diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index 96f64e0dd..9169d695d 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -9,6 +9,7 @@ use slog::Logger; #[derive(Clone)] pub struct BeaconBlockServiceInstance { + network_chan: crossbeam_channel::Sender, pub log: Logger, } @@ -43,7 +44,15 @@ impl BeaconBlockService for BeaconBlockServiceInstance { req: PublishBeaconBlockRequest, sink: UnarySink, ) { - println!("publishing {:?}", req.get_block()); + let block = req.get_block(); + println!("publishing {:?}", block); + + + // TODO: Build properly + let topic = types::TopicBuilder:: + println!("Sending beacon block to gossipsub"); + network_chan.send(NetworkMessage::Publish( + // TODO: actually process the block. let mut resp = PublishBeaconBlockResponse::new(); diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 3c89bda1f..e1267270c 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -21,6 +21,7 @@ use tokio::runtime::TaskExecutor; pub fn start_server( config: &RPCConfig, executor: &TaskExecutor, + network_chan: crossbeam_channel::Sender, beacon_chain: Arc, log: &slog::Logger, ) -> exit_future::Signal { @@ -40,7 +41,9 @@ pub fn start_server( }; let beacon_block_service = { - let instance = BeaconBlockServiceInstance { log: log.clone() }; + let instance = BeaconBlockServiceInstance { + network_chan + log: log.clone() }; create_beacon_block_service(instance) }; let validator_service = { From 52b31b200940850b265ae585d567f3a286f0fae1 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 23:02:51 +1100 Subject: [PATCH 59/97] Implement initial pubsub message handling --- beacon_node/eth2-libp2p/src/behaviour.rs | 57 +++++++++++++++------- beacon_node/eth2-libp2p/src/lib.rs | 3 +- beacon_node/eth2-libp2p/src/service.rs | 26 +++++++--- beacon_node/network/src/beacon_chain.rs | 2 +- beacon_node/network/src/message_handler.rs | 12 ++--- beacon_node/network/src/service.rs | 36 ++++++++------ beacon_node/rpc/Cargo.toml | 2 + beacon_node/rpc/src/beacon_block.rs | 6 ++- eth2/types/src/lib.rs | 2 +- 9 files changed, 95 insertions(+), 51 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index b3c4213b1..0229d06d5 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -13,11 +13,11 @@ use libp2p::{ tokio_io::{AsyncRead, AsyncWrite}, NetworkBehaviour, PeerId, }; -use slog::{debug, o}; +use slog::{debug, o, warn}; use ssz::{ssz_encode, Decodable, DecodeError, Encodable, SszStream}; use ssz_derive::{Decode, Encode}; use types::Attestation; -use types::Topic; +use types::{Topic, TopicHash}; /// Builds the network behaviour for the libp2p Swarm. /// Implements gossipsub message routing. @@ -48,13 +48,33 @@ impl NetworkBehaviourEventProcess { - let gs_message = String::from_utf8_lossy(&message.data); - // TODO: Remove this type - debug only - self.events - .push(BehaviourEvent::Message(gs_message.to_string())) + GossipsubEvent::Message(gs_msg) => { + let pubsub_message = match PubsubMessage::ssz_decode(&gs_msg.data, 0) { + //TODO: Punish peer on error + Err(e) => { + warn!( + self.log, + "Received undecodable message from Peer {:?}", gs_msg.source + ); + return; + } + Ok((msg, _index)) => msg, + }; + + self.events.push(BehaviourEvent::GossipMessage { + source: gs_msg.source, + topics: gs_msg.topics, + message: pubsub_message, + }); } - _ => {} + GossipsubEvent::Subscribed { + peer_id: _, + topic: _, + } + | GossipsubEvent::Unsubscribed { + peer_id: _, + topic: _, + } => {} } } } @@ -125,15 +145,6 @@ impl Behaviour { } } - /* Behaviour functions */ - - /// Publishes a message on the pubsub (gossipsub) behaviour. - pub fn publish(&mut self, topic: Topic, message: PubsubMessage) { - //encode the message - let message_bytes = ssz_encode(&message); - self.gossipsub.publish(topic, message_bytes); - } - /// Consumes the events list when polled. fn poll( &mut self, @@ -157,6 +168,12 @@ impl Behaviour { pub fn send_rpc(&mut self, peer_id: PeerId, rpc_event: RPCEvent) { self.serenity_rpc.send_rpc(peer_id, rpc_event); } + + /// Publishes a message on the pubsub (gossipsub) behaviour. + pub fn publish(&mut self, topic: Topic, message: PubsubMessage) { + let message_bytes = ssz_encode(&message); + self.gossipsub.publish(topic, message_bytes); + } } /// The types of events than can be obtained from polling the behaviour. @@ -165,7 +182,11 @@ pub enum BehaviourEvent { PeerDialed(PeerId), Identified(PeerId, IdentifyInfo), // TODO: This is a stub at the moment - Message(String), + GossipMessage { + source: PeerId, + topics: Vec, + message: PubsubMessage, + }, } /// Gossipsub message providing notification of a new block. diff --git a/beacon_node/eth2-libp2p/src/lib.rs b/beacon_node/eth2-libp2p/src/lib.rs index f7a961bb2..659d6b01c 100644 --- a/beacon_node/eth2-libp2p/src/lib.rs +++ b/beacon_node/eth2-libp2p/src/lib.rs @@ -8,12 +8,13 @@ pub mod error; pub mod rpc; mod service; +pub use behaviour::PubsubMessage; pub use config::Config as NetworkConfig; pub use libp2p::{ gossipsub::{GossipsubConfig, GossipsubConfigBuilder}, PeerId, }; -pub use rpc::{HelloMessage, RPCEvent}; +pub use rpc::RPCEvent; pub use service::Libp2pEvent; pub use service::Service; pub use types::multiaddr; diff --git a/beacon_node/eth2-libp2p/src/service.rs b/beacon_node/eth2-libp2p/src/service.rs index e68df2d38..73facee72 100644 --- a/beacon_node/eth2-libp2p/src/service.rs +++ b/beacon_node/eth2-libp2p/src/service.rs @@ -1,4 +1,4 @@ -use crate::behaviour::{Behaviour, BehaviourEvent}; +use crate::behaviour::{Behaviour, BehaviourEvent, PubsubMessage}; use crate::error; use crate::multiaddr::Protocol; use crate::rpc::RPCEvent; @@ -16,7 +16,7 @@ use libp2p::{core, secio, PeerId, Swarm, Transport}; use slog::{debug, info, trace, warn}; use std::io::{Error, ErrorKind}; use std::time::Duration; -use types::TopicBuilder; +use types::{TopicBuilder, TopicHash}; /// The configuration and state of the libp2p components for the beacon node. pub struct Service { @@ -107,9 +107,17 @@ impl Stream for Service { //Behaviour events Ok(Async::Ready(Some(event))) => match event { // TODO: Stub here for debugging - BehaviourEvent::Message(m) => { - debug!(self.log, "Message received: {}", m); - return Ok(Async::Ready(Some(Libp2pEvent::Message(m)))); + BehaviourEvent::GossipMessage { + source, + topics, + message, + } => { + debug!(self.log, "Pubsub message received: {:?}", message); + return Ok(Async::Ready(Some(Libp2pEvent::PubsubMessage { + source, + topics, + message, + }))); } BehaviourEvent::RPC(peer_id, event) => { return Ok(Async::Ready(Some(Libp2pEvent::RPC(peer_id, event)))); @@ -173,6 +181,10 @@ pub enum Libp2pEvent { PeerDialed(PeerId), /// Received information about a peer on the network. Identified(PeerId, IdentifyInfo), - // TODO: Pub-sub testing only. - Message(String), + /// Received pubsub message. + PubsubMessage { + source: PeerId, + topics: Vec, + message: PubsubMessage, + }, } diff --git a/beacon_node/network/src/beacon_chain.rs b/beacon_node/network/src/beacon_chain.rs index c627912a4..8ec8162ff 100644 --- a/beacon_node/network/src/beacon_chain.rs +++ b/beacon_node/network/src/beacon_chain.rs @@ -7,7 +7,7 @@ use beacon_chain::{ types::{BeaconState, ChainSpec}, AggregationOutcome, CheckPoint, }; -use eth2_libp2p::HelloMessage; +use eth2_libp2p::rpc::HelloMessage; use types::{Attestation, BeaconBlock, BeaconBlockBody, BeaconBlockHeader, Epoch, Hash256, Slot}; pub use beacon_chain::{BeaconChainError, BlockProcessingOutcome}; diff --git a/beacon_node/network/src/message_handler.rs b/beacon_node/network/src/message_handler.rs index dcfee96a0..0efa6b96f 100644 --- a/beacon_node/network/src/message_handler.rs +++ b/beacon_node/network/src/message_handler.rs @@ -4,7 +4,7 @@ use crate::service::{NetworkMessage, OutgoingMessage}; use crate::sync::SimpleSync; use crossbeam_channel::{unbounded as channel, Sender}; use eth2_libp2p::{ - behaviour::IncomingGossip, + behaviour::PubsubMessage, rpc::{methods::GoodbyeReason, RPCRequest, RPCResponse, RequestId}, PeerId, RPCEvent, }; @@ -41,7 +41,7 @@ pub enum HandlerMessage { /// An RPC response/request has been received. RPC(PeerId, RPCEvent), /// A gossip message has been received. - IncomingGossip(PeerId, IncomingGossip), + PubsubMessage(PeerId, PubsubMessage), } impl MessageHandler { @@ -92,7 +92,7 @@ impl MessageHandler { self.handle_rpc_message(peer_id, rpc_event); } // we have received an RPC message request/response - HandlerMessage::IncomingGossip(peer_id, gossip) => { + HandlerMessage::PubsubMessage(peer_id, gossip) => { self.handle_gossip(peer_id, gossip); } //TODO: Handle all messages @@ -205,13 +205,13 @@ impl MessageHandler { } /// Handle RPC messages - fn handle_gossip(&mut self, peer_id: PeerId, gossip_message: IncomingGossip) { + fn handle_gossip(&mut self, peer_id: PeerId, gossip_message: PubsubMessage) { match gossip_message { - IncomingGossip::Block(message) => { + PubsubMessage::Block(message) => { self.sync .on_block_gossip(peer_id, message, &mut self.network_context) } - IncomingGossip::Attestation(message) => { + PubsubMessage::Attestation(message) => { self.sync .on_attestation_gossip(peer_id, message, &mut self.network_context) } diff --git a/beacon_node/network/src/service.rs b/beacon_node/network/src/service.rs index 33ea79c1a..55c43e4ec 100644 --- a/beacon_node/network/src/service.rs +++ b/beacon_node/network/src/service.rs @@ -3,16 +3,16 @@ use crate::error; use crate::message_handler::{HandlerMessage, MessageHandler}; use crate::NetworkConfig; use crossbeam_channel::{unbounded as channel, Sender, TryRecvError}; -use eth2_libp2p::{RPCEvent, PublishMessage}; use eth2_libp2p::Service as LibP2PService; use eth2_libp2p::{Libp2pEvent, PeerId}; +use eth2_libp2p::{PubsubMessage, RPCEvent}; use futures::prelude::*; use futures::sync::oneshot; use futures::Stream; use slog::{debug, info, o, trace}; use std::sync::Arc; use tokio::runtime::TaskExecutor; -use types::{BeaconBlock, Topic}; +use types::Topic; /// Service that handles communication between internal services and the eth2_libp2p network service. pub struct Service { @@ -100,6 +100,7 @@ fn spawn_service( Ok(network_exit) } +//TODO: Potentially handle channel errors fn network_service( mut libp2p_service: LibP2PService, network_recv: crossbeam_channel::Receiver, @@ -129,10 +130,17 @@ fn network_service( "We have identified peer: {:?} with {:?}", peer_id, info ); } - Libp2pEvent::Message(m) => debug!( - libp2p_service.log, - "Network Service: Message received: {}", m - ), + Libp2pEvent::PubsubMessage { + source, + topics: _, + message, + } => { + //TODO: Decide if we need to propagate the topic upwards. (Potentially for + //attestations) + message_handler_send + .send(HandlerMessage::PubsubMessage(source, message)) + .map_err(|_| " failed to send pubsub message to handler")?; + } }, Ok(Async::Ready(None)) => unreachable!("Stream never ends"), Ok(Async::NotReady) => break, @@ -157,17 +165,16 @@ fn network_service( } }; } + Ok(NetworkMessage::Publish(topic, message)) => { + debug!(log, "Sending pubsub message on topic {:?}", topic); + libp2p_service.swarm.publish(topic, message); + } Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => { return Err(eth2_libp2p::error::Error::from( "Network channel disconnected", )); - }, - Ok(NetworkMessage::Publish(topic, message) => { - debug!(log, "Sending message on topic {:?}", topic); - libp2p_service.swarm.publish(topic,message) - - + } } } Ok(Async::NotReady) @@ -180,8 +187,8 @@ pub enum NetworkMessage { /// Send a message to libp2p service. //TODO: Define typing for messages across the wire Send(PeerId, OutgoingMessage), - /// Publish a message to gossipsub - Publish(Topic, PublishMessage), + /// Publish a message to pubsub mechanism. + Publish(Topic, PubsubMessage), } /// Type of outgoing messages that can be sent through the network service. @@ -192,4 +199,3 @@ pub enum OutgoingMessage { //TODO: Remove NotifierTest, } - diff --git a/beacon_node/rpc/Cargo.toml b/beacon_node/rpc/Cargo.toml index d405982db..e9709c1ce 100644 --- a/beacon_node/rpc/Cargo.toml +++ b/beacon_node/rpc/Cargo.toml @@ -7,6 +7,7 @@ edition = "2018" [dependencies] bls = { path = "../../eth2/utils/bls" } beacon_chain = { path = "../beacon_chain" } +network = { path = "../network" } version = { path = "../version" } types = { path = "../../eth2/types" } ssz = { path = "../../eth2/utils/ssz" } @@ -23,3 +24,4 @@ slog-term = "^2.4.0" slog-async = "^2.3.0" tokio = "0.1.17" exit-future = "0.1.4" +crossbeam-channel = "0.3.8" diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index 9169d695d..d124152f1 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -6,6 +6,8 @@ use protos::services::{ }; use protos::services_grpc::BeaconBlockService; use slog::Logger; +use crossbeam_channel; +use network::NetworkMessage; #[derive(Clone)] pub struct BeaconBlockServiceInstance { @@ -48,8 +50,8 @@ impl BeaconBlockService for BeaconBlockServiceInstance { println!("publishing {:?}", block); - // TODO: Build properly - let topic = types::TopicBuilder:: + // TODO: Obtain from the network properly. + let topic = types::TopicBuilder::from("beacon_chain").build(); println!("Sending beacon block to gossipsub"); network_chan.send(NetworkMessage::Publish( diff --git a/eth2/types/src/lib.rs b/eth2/types/src/lib.rs index 953a9508f..118e862e8 100644 --- a/eth2/types/src/lib.rs +++ b/eth2/types/src/lib.rs @@ -85,6 +85,6 @@ pub type AttesterMap = HashMap<(u64, u64), Vec>; pub type ProposerMap = HashMap; pub use bls::{AggregatePublicKey, AggregateSignature, Keypair, PublicKey, SecretKey, Signature}; -pub use libp2p::floodsub::{Topic, TopicBuilder}; +pub use libp2p::floodsub::{Topic, TopicBuilder, TopicHash}; pub use libp2p::multiaddr; pub use libp2p::Multiaddr; From f7131c2f871fa521c2418ba51f56b22014a25507 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 25 Mar 2019 23:39:39 +1100 Subject: [PATCH 60/97] Fix compile issues and modify type names --- beacon_node/eth2-libp2p/src/behaviour.rs | 28 ++++++++------------- beacon_node/network/src/lib.rs | 1 + beacon_node/network/src/service.rs | 11 +++++--- beacon_node/network/src/sync/simple_sync.rs | 19 +++++++------- beacon_node/rpc/Cargo.toml | 1 + beacon_node/rpc/src/beacon_block.rs | 28 ++++++++++++++------- beacon_node/rpc/src/lib.rs | 6 +++-- 7 files changed, 51 insertions(+), 43 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index 0229d06d5..41b7c8965 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -170,9 +170,11 @@ impl Behaviour { } /// Publishes a message on the pubsub (gossipsub) behaviour. - pub fn publish(&mut self, topic: Topic, message: PubsubMessage) { + pub fn publish(&mut self, topics: Vec, message: PubsubMessage) { let message_bytes = ssz_encode(&message); - self.gossipsub.publish(topic, message_bytes); + for topic in topics { + self.gossipsub.publish(topic, message_bytes.clone()); + } } } @@ -189,23 +191,13 @@ pub enum BehaviourEvent { }, } -/// Gossipsub message providing notification of a new block. -#[derive(Encode, Decode, Clone, Debug, PartialEq)] -pub struct BlockGossip { - pub root: BlockRootSlot, -} - -/// Gossipsub message providing notification of a new attestation. -#[derive(Encode, Decode, Clone, Debug, PartialEq)] -pub struct AttestationGossip { - pub attestation: Attestation, -} - /// Messages that are passed to and from the pubsub (Gossipsub) behaviour. #[derive(Debug, Clone)] pub enum PubsubMessage { - Block(BlockGossip), - Attestation(AttestationGossip), + /// Gossipsub message providing notification of a new block. + Block(BlockRootSlot), + /// Gossipsub message providing notification of a new attestation. + Attestation(Attestation), } //TODO: Correctly encode/decode enums. Prefixing with integer for now. @@ -229,11 +221,11 @@ impl Decodable for PubsubMessage { let (id, index) = u32::ssz_decode(bytes, index)?; match id { 1 => { - let (block, index) = BlockGossip::ssz_decode(bytes, index)?; + let (block, index) = BlockRootSlot::ssz_decode(bytes, index)?; Ok((PubsubMessage::Block(block), index)) } 2 => { - let (attestation, index) = AttestationGossip::ssz_decode(bytes, index)?; + let (attestation, index) = Attestation::ssz_decode(bytes, index)?; Ok((PubsubMessage::Attestation(attestation), index)) } _ => Err(DecodeError::Invalid), diff --git a/beacon_node/network/src/lib.rs b/beacon_node/network/src/lib.rs index 87f8368a5..c298e31b4 100644 --- a/beacon_node/network/src/lib.rs +++ b/beacon_node/network/src/lib.rs @@ -6,4 +6,5 @@ pub mod service; pub mod sync; pub use eth2_libp2p::NetworkConfig; +pub use service::NetworkMessage; pub use service::Service; diff --git a/beacon_node/network/src/service.rs b/beacon_node/network/src/service.rs index 55c43e4ec..b2d2b5a24 100644 --- a/beacon_node/network/src/service.rs +++ b/beacon_node/network/src/service.rs @@ -165,9 +165,9 @@ fn network_service( } }; } - Ok(NetworkMessage::Publish(topic, message)) => { - debug!(log, "Sending pubsub message on topic {:?}", topic); - libp2p_service.swarm.publish(topic, message); + Ok(NetworkMessage::Publish { topics, message }) => { + debug!(log, "Sending pubsub message on topics {:?}", topics); + libp2p_service.swarm.publish(topics, message); } Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => { @@ -188,7 +188,10 @@ pub enum NetworkMessage { //TODO: Define typing for messages across the wire Send(PeerId, OutgoingMessage), /// Publish a message to pubsub mechanism. - Publish(Topic, PubsubMessage), + Publish { + topics: Vec, + message: PubsubMessage, + }, } /// Type of outgoing messages that can be sent through the network service. diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 4c08a6871..2aa0a1d7d 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -1,7 +1,6 @@ use super::import_queue::ImportQueue; use crate::beacon_chain::BeaconChain; use crate::message_handler::NetworkContext; -use eth2_libp2p::behaviour::{AttestationGossip, BlockGossip}; use eth2_libp2p::rpc::methods::*; use eth2_libp2p::rpc::{RPCRequest, RPCResponse, RequestId}; use eth2_libp2p::PeerId; @@ -9,7 +8,7 @@ use slog::{debug, error, info, o, warn}; use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use types::{Epoch, Hash256, Slot}; +use types::{Attestation, Epoch, Hash256, Slot}; /// The number of slots that we can import blocks ahead of us, before going into full Sync mode. const SLOT_IMPORT_TOLERANCE: u64 = 100; @@ -521,12 +520,12 @@ impl SimpleSync { pub fn on_block_gossip( &mut self, peer_id: PeerId, - msg: BlockGossip, + msg: BlockRootSlot, network: &mut NetworkContext, ) { debug!( self.log, - "BlockGossip"; + "BlockSlot"; "peer" => format!("{:?}", peer_id), ); // TODO: filter out messages that a prior to the finalized slot. @@ -535,12 +534,12 @@ impl SimpleSync { // now. // // Note: only requests the new block -- will fail if we don't have its parents. - if self.import_queue.is_new_block(&msg.root.block_root) { + if self.import_queue.is_new_block(&msg.block_root) { self.request_block_headers( peer_id, BeaconBlockHeadersRequest { - start_root: msg.root.block_root, - start_slot: msg.root.slot, + start_root: msg.block_root, + start_slot: msg.slot, max_headers: 1, skip_slots: 0, }, @@ -555,19 +554,19 @@ impl SimpleSync { pub fn on_attestation_gossip( &mut self, peer_id: PeerId, - msg: AttestationGossip, + msg: Attestation, _network: &mut NetworkContext, ) { debug!( self.log, - "AttestationGossip"; + "Attestation"; "peer" => format!("{:?}", peer_id), ); // Awaiting a proper operations pool before we can import attestations. // // https://github.com/sigp/lighthouse/issues/281 - match self.chain.process_attestation(msg.attestation) { + match self.chain.process_attestation(msg) { Ok(_) => panic!("Impossible, method not implemented."), Err(_) => error!(self.log, "Attestation processing not implemented!"), } diff --git a/beacon_node/rpc/Cargo.toml b/beacon_node/rpc/Cargo.toml index e9709c1ce..3fc52c6b1 100644 --- a/beacon_node/rpc/Cargo.toml +++ b/beacon_node/rpc/Cargo.toml @@ -8,6 +8,7 @@ edition = "2018" bls = { path = "../../eth2/utils/bls" } beacon_chain = { path = "../beacon_chain" } network = { path = "../network" } +eth2-libp2p = { path = "../eth2-libp2p" } version = { path = "../version" } types = { path = "../../eth2/types" } ssz = { path = "../../eth2/utils/ssz" } diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index d124152f1..4e1875665 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -1,17 +1,20 @@ +use crossbeam_channel; +use eth2_libp2p::rpc::methods::BlockRootSlot; +use eth2_libp2p::PubsubMessage; use futures::Future; use grpcio::{RpcContext, UnarySink}; +use network::NetworkMessage; use protos::services::{ BeaconBlock as BeaconBlockProto, ProduceBeaconBlockRequest, ProduceBeaconBlockResponse, PublishBeaconBlockRequest, PublishBeaconBlockResponse, }; use protos::services_grpc::BeaconBlockService; use slog::Logger; -use crossbeam_channel; -use network::NetworkMessage; +use types::{Hash256, Slot}; #[derive(Clone)] pub struct BeaconBlockServiceInstance { - network_chan: crossbeam_channel::Sender, + pub network_chan: crossbeam_channel::Sender, pub log: Logger, } @@ -47,14 +50,21 @@ impl BeaconBlockService for BeaconBlockServiceInstance { sink: UnarySink, ) { let block = req.get_block(); - println!("publishing {:?}", block); + let block_root = Hash256::from_slice(block.get_block_root()); + let block_slot = BlockRootSlot { + block_root, + slot: Slot::from(block.get_slot()), + }; + println!("publishing block with root {:?}", block_root); - - // TODO: Obtain from the network properly. - let topic = types::TopicBuilder::from("beacon_chain").build(); + // TODO: Obtain topics from the network service properly. + let topic = types::TopicBuilder::new("beacon_chain".to_string()).build(); + let message = PubsubMessage::Block(block_slot); println!("Sending beacon block to gossipsub"); - network_chan.send(NetworkMessage::Publish( - + self.network_chan.send(NetworkMessage::Publish { + topics: vec![topic], + message, + }); // TODO: actually process the block. let mut resp = PublishBeaconBlockResponse::new(); diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index e1267270c..4dfd33487 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -11,6 +11,7 @@ use self::validator::ValidatorServiceInstance; pub use config::Config as RPCConfig; use futures::{future, Future}; use grpcio::{Environment, Server, ServerBuilder}; +use network::NetworkMessage; use protos::services_grpc::{ create_beacon_block_service, create_beacon_node_service, create_validator_service, }; @@ -42,8 +43,9 @@ pub fn start_server( let beacon_block_service = { let instance = BeaconBlockServiceInstance { - network_chan - log: log.clone() }; + network_chan, + log: log.clone(), + }; create_beacon_block_service(instance) }; let validator_service = { From a145824c51fdb872ea600ef756f8312dc4e4e0dc Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 09:46:26 +1100 Subject: [PATCH 61/97] Set BeaconChainHarness to return block This is useful if you want to inspect the block. --- .../beacon_chain/test_harness/src/beacon_chain_harness.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs index 1498796b1..942497476 100644 --- a/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs +++ b/beacon_node/beacon_chain/test_harness/src/beacon_chain_harness.rs @@ -207,13 +207,13 @@ impl BeaconChainHarness { /// /// This is the ideal scenario for the Beacon Chain, 100% honest participation from /// validators. - pub fn advance_chain_with_block(&mut self) { + pub fn advance_chain_with_block(&mut self) -> BeaconBlock { self.increment_beacon_chain_slot(); // Produce a new block. let block = self.produce_block(); debug!("Submitting block for processing..."); - match self.beacon_chain.process_block(block) { + match self.beacon_chain.process_block(block.clone()) { Ok(BlockProcessingOutcome::ValidBlock(_)) => {} other => panic!("block processing failed with {:?}", other), }; @@ -233,6 +233,8 @@ impl BeaconChainHarness { }); debug!("Free attestations processed."); + + block } /// Signs a message using some validators secret key with the `Fork` info from the latest state From 33d0f29221f6b816fd05641eba618e49f6bf4401 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 11:33:24 +1100 Subject: [PATCH 62/97] Remove old tests --- validator_client/src/duties/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index f6460afd2..fa53180a6 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -91,6 +91,7 @@ impl From for Error { } } +/* TODO: Modify tests for new Duties Manager form #[cfg(test)] mod tests { use super::test_node::TestBeaconNode; @@ -104,6 +105,7 @@ mod tests { // // These tests should serve as a good example for future tests. + #[test] pub fn polling() { let spec = Arc::new(ChainSpec::foundation()); @@ -154,3 +156,4 @@ mod tests { ); } } +*/ From ffb3d943556935d50b9815596e876296ec1c1283 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 11:59:48 +1100 Subject: [PATCH 63/97] Wrap the duty manager in a future for its own thread --- validator_client/Cargo.toml | 1 + validator_client/src/duties/mod.rs | 25 +++++++++++++++++++++- validator_client/src/service.rs | 33 +++++++++--------------------- 3 files changed, 35 insertions(+), 24 deletions(-) diff --git a/validator_client/Cargo.toml b/validator_client/Cargo.toml index eace153fa..570e06d74 100644 --- a/validator_client/Cargo.toml +++ b/validator_client/Cargo.toml @@ -32,3 +32,4 @@ tokio = "0.1.18" tokio-timer = "0.2.10" error-chain = "0.12.0" bincode = "^1.1.2" +futures = "0.1.25" diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index fa53180a6..185f80d6d 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -8,6 +8,8 @@ pub use self::epoch_duties::EpochDutiesMap; use self::epoch_duties::{EpochDuties, EpochDutiesMapError}; use self::traits::{BeaconNode, BeaconNodeError}; use bls::PublicKey; +use futures::Async; +use slog::{debug, error, info}; use slot_clock::SlotClock; use std::sync::Arc; use types::{ChainSpec, Epoch, Slot}; @@ -52,7 +54,7 @@ impl DutiesManager { /// /// The present `epoch` will be learned from the supplied `SlotClock`. In production this will /// be a wall-clock (e.g., system time, remote server time, etc.). - pub fn update(&self, slot: Slot) -> Result { + fn update(&self, slot: Slot) -> Result { let epoch = slot.epoch(self.spec.slots_per_epoch); if let Some(duties) = self @@ -75,6 +77,27 @@ impl DutiesManager { Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) } } + + /// A future wrapping around `update()`. This will perform logic based upon the update + /// process and complete once the update has completed. + pub fn run_update(&self, slot: Slot, log: slog::Logger) -> Result, ()> { + match self.update(slot) { + Err(error) => error!(log, "Epoch duties poll error"; "error" => format!("{:?}", error)), + Ok(UpdateOutcome::NoChange(epoch)) => { + debug!(log, "No change in duties"; "epoch" => epoch) + } + Ok(UpdateOutcome::DutiesChanged(epoch, duties)) => { + info!(log, "Duties changed (potential re-org)"; "epoch" => epoch, "duties" => format!("{:?}", duties)) + } + Ok(UpdateOutcome::NewDuties(epoch, duties)) => { + info!(log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) + } + Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) => { + error!(log, "Epoch or validator unknown"; "epoch" => epoch) + } + }; + Ok(Async::Ready(())) + } } impl From for Error { diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 8a7e90d10..9ca591b92 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -222,21 +222,22 @@ impl Service { // build requisite objects to pass to core thread. let duties_map = Arc::new(EpochDutiesMap::new(config.spec.slots_per_epoch)); let epoch_map_for_attester = Arc::new(EpochMap::new(config.spec.slots_per_epoch)); - let manager = DutiesManager { + let manager = Arc::new(DutiesManager { duties_map, pubkeys: keypairs.iter().map(|keypair| keypair.pk.clone()).collect(), spec: Arc::new(config.spec), slot_clock: service.slot_clock.clone(), beacon_node: service.validator_client.clone(), - }; + }); // run the core thread runtime .block_on(interval.for_each(move |_| { + let log = service.log.clone(); // get the current slot let current_slot = match service.slot_clock.present_slot() { Err(e) => { - error!(service.log, "SystemTimeError {:?}", e); + error!(log, "SystemTimeError {:?}", e); return Ok(()); } Ok(slot) => slot.expect("Genesis is in the future"), @@ -247,28 +248,14 @@ impl Service { "The Timer should poll a new slot" ); - info!(service.log, "Processing slot: {}", current_slot.as_u64()); + info!(log, "Processing slot: {}", current_slot.as_u64()); + + let cloned_manager = manager.clone(); // check for new duties - // TODO: Convert to its own thread - match manager.update(current_slot) { - Err(error) => { - error!(service.log, "Epoch duties poll error"; "error" => format!("{:?}", error)) - } - Ok(UpdateOutcome::NoChange(epoch)) => { - debug!(service.log, "No change in duties"; "epoch" => epoch) - } - Ok(UpdateOutcome::DutiesChanged(epoch, duties)) => { - info!(service.log, "Duties changed (potential re-org)"; "epoch" => epoch, "duties" => format!("{:?}", duties)) - } - Ok(UpdateOutcome::NewDuties(epoch, duties)) => { - info!(service.log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) - } - Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) => { - error!(service.log, "Epoch or validator unknown"; "epoch" => epoch) - } - }; - + tokio::spawn(futures::future::poll_fn(move || { + cloned_manager.run_update(current_slot.clone(), log.clone()) + })); Ok(()) })) .map_err(|e| format!("Service thread failed: {:?}", e))?; From d4fecd8a84e92060ce2da6f2102b6dc9c5449d0a Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 12:32:38 +1100 Subject: [PATCH 64/97] Set GRPC block to be just SSZ --- beacon_node/rpc/src/beacon_block.rs | 58 +++++++++++-------- protos/src/services.proto | 5 +- .../beacon_block_grpc_client.rs | 38 +++--------- 3 files changed, 43 insertions(+), 58 deletions(-) diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index 4e1875665..6317414b0 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -9,8 +9,10 @@ use protos::services::{ PublishBeaconBlockRequest, PublishBeaconBlockResponse, }; use protos::services_grpc::BeaconBlockService; +use slog::debug; use slog::Logger; -use types::{Hash256, Slot}; +use ssz::{Decodable, TreeHash}; +use types::{BeaconBlock, Hash256, Slot}; #[derive(Clone)] pub struct BeaconBlockServiceInstance { @@ -30,8 +32,7 @@ impl BeaconBlockService for BeaconBlockServiceInstance { // TODO: build a legit block. let mut block = BeaconBlockProto::new(); - block.set_slot(req.get_slot()); - block.set_block_root(b"cats".to_vec()); + block.set_ssz(b"cats".to_vec()); let mut resp = ProduceBeaconBlockResponse::new(); resp.set_block(block); @@ -49,30 +50,39 @@ impl BeaconBlockService for BeaconBlockServiceInstance { req: PublishBeaconBlockRequest, sink: UnarySink, ) { + debug!(self.log, "PublishBeaconBlock"); + let block = req.get_block(); - let block_root = Hash256::from_slice(block.get_block_root()); - let block_slot = BlockRootSlot { - block_root, - slot: Slot::from(block.get_slot()), - }; - println!("publishing block with root {:?}", block_root); - // TODO: Obtain topics from the network service properly. - let topic = types::TopicBuilder::new("beacon_chain".to_string()).build(); - let message = PubsubMessage::Block(block_slot); - println!("Sending beacon block to gossipsub"); - self.network_chan.send(NetworkMessage::Publish { - topics: vec![topic], - message, - }); + match BeaconBlock::ssz_decode(block.get_ssz(), 0) { + Ok((block, _i)) => { + let block_root = Hash256::from_slice(&block.hash_tree_root()[..]); - // TODO: actually process the block. - let mut resp = PublishBeaconBlockResponse::new(); - resp.set_success(true); + // TODO: Obtain topics from the network service properly. + let topic = types::TopicBuilder::new("beacon_chain".to_string()).build(); + let message = PubsubMessage::Block(BlockRootSlot { + block_root, + slot: block.slot, + }); - let f = sink - .success(resp) - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - ctx.spawn(f) + println!("Sending beacon block to gossipsub"); + self.network_chan.send(NetworkMessage::Publish { + topics: vec![topic], + message, + }); + + // TODO: actually process the block. + let mut resp = PublishBeaconBlockResponse::new(); + resp.set_success(true); + + let f = sink + .success(resp) + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + ctx.spawn(f) + } + Err(e) => { + // + } + } } } diff --git a/protos/src/services.proto b/protos/src/services.proto index 80d512c54..38c9d0b24 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -83,10 +83,7 @@ message PublishBeaconBlockResponse { } message BeaconBlock { - uint64 slot = 1; - bytes block_root = 2; - bytes randao_reveal = 3; - bytes signature = 4; + bytes ssz = 1; } /* diff --git a/validator_client/src/block_producer_service/beacon_block_grpc_client.rs b/validator_client/src/block_producer_service/beacon_block_grpc_client.rs index 04a02a221..ba2acfffb 100644 --- a/validator_client/src/block_producer_service/beacon_block_grpc_client.rs +++ b/validator_client/src/block_producer_service/beacon_block_grpc_client.rs @@ -5,7 +5,7 @@ use protos::services::{ use protos::services_grpc::BeaconBlockServiceClient; use ssz::{ssz_encode, Decodable}; use std::sync::Arc; -use types::{BeaconBlock, BeaconBlockBody, Eth1Data, Hash256, Signature, Slot}; +use types::{BeaconBlock, Signature, Slot}; /// A newtype designed to wrap the gRPC-generated service so the `BeaconNode` trait may be /// implemented upon it. @@ -40,33 +40,12 @@ impl BeaconNode for BeaconBlockGrpcClient { if reply.has_block() { let block = reply.get_block(); + let ssz = block.get_ssz(); - let (signature, _) = Signature::ssz_decode(block.get_signature(), 0) - .map_err(|_| BeaconNodeError::DecodeFailure)?; + let (block, _i) = + BeaconBlock::ssz_decode(&ssz, 0).map_err(|_| BeaconNodeError::DecodeFailure)?; - let (randao_reveal, _) = Signature::ssz_decode(block.get_randao_reveal(), 0) - .map_err(|_| BeaconNodeError::DecodeFailure)?; - - // TODO: this conversion is incomplete; fix it. - Ok(Some(BeaconBlock { - slot: Slot::new(block.get_slot()), - previous_block_root: Hash256::zero(), - state_root: Hash256::zero(), - signature, - body: BeaconBlockBody { - randao_reveal, - eth1_data: Eth1Data { - deposit_root: Hash256::zero(), - block_hash: Hash256::zero(), - }, - proposer_slashings: vec![], - attester_slashings: vec![], - attestations: vec![], - deposits: vec![], - voluntary_exits: vec![], - transfers: vec![], - }, - })) + Ok(Some(block)) } else { Ok(None) } @@ -79,12 +58,11 @@ impl BeaconNode for BeaconBlockGrpcClient { fn publish_beacon_block(&self, block: BeaconBlock) -> Result { let mut req = PublishBeaconBlockRequest::new(); + let ssz = ssz_encode(&block); + // TODO: this conversion is incomplete; fix it. let mut grpc_block = GrpcBeaconBlock::new(); - grpc_block.set_slot(block.slot.as_u64()); - grpc_block.set_block_root(vec![0]); - grpc_block.set_randao_reveal(ssz_encode(&block.body.randao_reveal)); - grpc_block.set_signature(ssz_encode(&block.signature)); + grpc_block.set_ssz(ssz); req.set_block(grpc_block); From 56c9a295936c48b40707dfad596996aec0e17bf7 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 13:28:01 +1100 Subject: [PATCH 65/97] Add logging --- beacon_node/eth2-libp2p/src/behaviour.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index 41b7c8965..592fd6fb1 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -49,12 +49,15 @@ impl NetworkBehaviourEventProcess { + debug!(self.log, "Received GossipEvent"; "msg" => format!("{:?}", gs_msg)); + let pubsub_message = match PubsubMessage::ssz_decode(&gs_msg.data, 0) { //TODO: Punish peer on error Err(e) => { warn!( self.log, - "Received undecodable message from Peer {:?}", gs_msg.source + "Received undecodable message from Peer {:?} error", gs_msg.source; + "error" => format!("{:?}", e) ); return; } From e702896bee1784079f58eeab57966227e62fa3c7 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 13:28:21 +1100 Subject: [PATCH 66/97] Fix ssz decoding bug --- beacon_node/eth2-libp2p/src/behaviour.rs | 28 +++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/behaviour.rs b/beacon_node/eth2-libp2p/src/behaviour.rs index 592fd6fb1..286597183 100644 --- a/beacon_node/eth2-libp2p/src/behaviour.rs +++ b/beacon_node/eth2-libp2p/src/behaviour.rs @@ -195,7 +195,7 @@ pub enum BehaviourEvent { } /// Messages that are passed to and from the pubsub (Gossipsub) behaviour. -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq)] pub enum PubsubMessage { /// Gossipsub message providing notification of a new block. Block(BlockRootSlot), @@ -223,11 +223,11 @@ impl Decodable for PubsubMessage { fn ssz_decode(bytes: &[u8], index: usize) -> Result<(Self, usize), DecodeError> { let (id, index) = u32::ssz_decode(bytes, index)?; match id { - 1 => { + 0 => { let (block, index) = BlockRootSlot::ssz_decode(bytes, index)?; Ok((PubsubMessage::Block(block), index)) } - 2 => { + 1 => { let (attestation, index) = Attestation::ssz_decode(bytes, index)?; Ok((PubsubMessage::Attestation(attestation), index)) } @@ -235,3 +235,25 @@ impl Decodable for PubsubMessage { } } } + +#[cfg(test)] +mod test { + use super::*; + use types::*; + + #[test] + fn ssz_encoding() { + let original = PubsubMessage::Block(BlockRootSlot { + block_root: Hash256::from_slice(&[42; 32]), + slot: Slot::new(4), + }); + + let encoded = ssz_encode(&original); + + println!("{:?}", encoded); + + let (decoded, _i) = PubsubMessage::ssz_decode(&encoded, 0).unwrap(); + + assert_eq!(original, decoded); + } +} From 5b40152873b0972834dcef601d8632ce06d1fe35 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 15:01:05 +1100 Subject: [PATCH 67/97] Update to latest libp2p and gossipsub --- beacon_node/eth2-libp2p/src/config.rs | 4 +++- beacon_node/eth2-libp2p/src/rpc/protocol.rs | 13 ++++++++----- beacon_node/eth2-libp2p/src/service.rs | 11 +++++------ 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/beacon_node/eth2-libp2p/src/config.rs b/beacon_node/eth2-libp2p/src/config.rs index 2b4972237..265100658 100644 --- a/beacon_node/eth2-libp2p/src/config.rs +++ b/beacon_node/eth2-libp2p/src/config.rs @@ -29,7 +29,9 @@ impl Default for Config { .parse() .expect("is a correct multi-address")], listen_port: 9000, - gs_config: GossipsubConfigBuilder::new().build(), + gs_config: GossipsubConfigBuilder::new() + .max_gossip_size(4_000_000) + .build(), identify_config: IdentifyConfig::default(), boot_nodes: Vec::new(), client_version: version::version(), diff --git a/beacon_node/eth2-libp2p/src/rpc/protocol.rs b/beacon_node/eth2-libp2p/src/rpc/protocol.rs index f4fe26fac..dc3f70a9b 100644 --- a/beacon_node/eth2-libp2p/src/rpc/protocol.rs +++ b/beacon_node/eth2-libp2p/src/rpc/protocol.rs @@ -60,10 +60,13 @@ where { type Output = RPCEvent; type Error = DecodeError; - type Future = - upgrade::ReadOneThen, ()) -> Result>; + type Future = upgrade::ReadOneThen< + upgrade::Negotiated, + (), + fn(Vec, ()) -> Result, + >; - fn upgrade_inbound(self, socket: TSocket, _: Self::Info) -> Self::Future { + fn upgrade_inbound(self, socket: upgrade::Negotiated, _: Self::Info) -> Self::Future { upgrade::read_one_then(socket, MAX_READ_SIZE, (), |packet, ()| Ok(decode(packet)?)) } } @@ -154,10 +157,10 @@ where { type Output = (); type Error = io::Error; - type Future = upgrade::WriteOne; + type Future = upgrade::WriteOne>; #[inline] - fn upgrade_outbound(self, socket: TSocket, _: Self::Info) -> Self::Future { + fn upgrade_outbound(self, socket: upgrade::Negotiated, _: Self::Info) -> Self::Future { let bytes = ssz_encode(&self); upgrade::write_one(socket, bytes) } diff --git a/beacon_node/eth2-libp2p/src/service.rs b/beacon_node/eth2-libp2p/src/service.rs index e68df2d38..b20874427 100644 --- a/beacon_node/eth2-libp2p/src/service.rs +++ b/beacon_node/eth2-libp2p/src/service.rs @@ -6,6 +6,7 @@ use crate::NetworkConfig; use futures::prelude::*; use futures::Stream; use libp2p::core::{ + identity, muxing::StreamMuxerBox, nodes::Substream, transport::boxed::Boxed, @@ -36,10 +37,10 @@ impl Service { // TODO: Currently using secp256k1 key pairs. Wire protocol specifies RSA. Waiting for this // PR to be merged to generate RSA keys: https://github.com/briansmith/ring/pull/733 // TODO: Save and recover node key from disk - let local_private_key = secio::SecioKeyPair::secp256k1_generated().unwrap(); + let local_private_key = identity::Keypair::generate_secp256k1(); - let local_public_key = local_private_key.to_public_key(); - let local_peer_id = local_private_key.to_peer_id(); + let local_public_key = local_private_key.public(); + let local_peer_id = PeerId::from(local_private_key.public()); info!(log, "Local peer id: {:?}", local_peer_id); let mut swarm = { @@ -132,9 +133,7 @@ impl Stream for Service { /// The implementation supports TCP/IP, WebSockets over TCP/IP, secio as the encryption layer, and /// mplex or yamux as the multiplexing layer. -fn build_transport( - local_private_key: secio::SecioKeyPair, -) -> Boxed<(PeerId, StreamMuxerBox), Error> { +fn build_transport(local_private_key: identity::Keypair) -> Boxed<(PeerId, StreamMuxerBox), Error> { // TODO: The Wire protocol currently doesn't specify encryption and this will need to be customised // in the future. let transport = libp2p::tcp::TcpConfig::new(); From 3756d8d6816ce37c85dd5f7ebf4ca1d62948902e Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 15:04:39 +1100 Subject: [PATCH 68/97] Rename proto NodeInfo -> NodeInfoResponse --- beacon_node/rpc/src/beacon_node.rs | 6 +++--- protos/src/services.proto | 7 +++---- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/beacon_node/rpc/src/beacon_node.rs b/beacon_node/rpc/src/beacon_node.rs index 7b00f04f4..54984c5c2 100644 --- a/beacon_node/rpc/src/beacon_node.rs +++ b/beacon_node/rpc/src/beacon_node.rs @@ -1,7 +1,7 @@ use crate::beacon_chain::BeaconChain; use futures::Future; use grpcio::{RpcContext, UnarySink}; -use protos::services::{Empty, Fork, NodeInfo}; +use protos::services::{Empty, Fork, NodeInfoResponse}; use protos::services_grpc::BeaconNodeService; use slog::{trace, warn}; use std::sync::Arc; @@ -14,11 +14,11 @@ pub struct BeaconNodeServiceInstance { impl BeaconNodeService for BeaconNodeServiceInstance { /// Provides basic node information. - fn info(&mut self, ctx: RpcContext, _req: Empty, sink: UnarySink) { + fn info(&mut self, ctx: RpcContext, _req: Empty, sink: UnarySink) { trace!(self.log, "Node info requested via RPC"); // build the response - let mut node_info = NodeInfo::new(); + let mut node_info = NodeInfoResponse::new(); node_info.set_version(version::version()); // get the chain state diff --git a/protos/src/services.proto b/protos/src/services.proto index 38c9d0b24..ee4f58d1b 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -14,7 +14,7 @@ package ethereum.beacon.rpc.v1; // Service that currently identifies a beacon node service BeaconNodeService { - rpc Info(Empty) returns (NodeInfo); + rpc Info(Empty) returns (NodeInfoResponse); } /// Service that handles block production @@ -40,7 +40,7 @@ service AttestationService { /* * Beacon Node Service Message */ -message NodeInfo { +message NodeInfoResponse { string version = 1; Fork fork = 2; uint32 chain_id = 3; @@ -53,8 +53,7 @@ message Fork { uint64 epoch = 3; } -message Empty { -} +message Empty {} /* From b2ae54043ced3c61de0c651a58368ccd39a3eb04 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 15:06:41 +1100 Subject: [PATCH 69/97] Fix libp2p version to specific commit --- beacon_node/eth2-libp2p/Cargo.toml | 2 +- eth2/types/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beacon_node/eth2-libp2p/Cargo.toml b/beacon_node/eth2-libp2p/Cargo.toml index 4dd2e9c7b..beb1a0234 100644 --- a/beacon_node/eth2-libp2p/Cargo.toml +++ b/beacon_node/eth2-libp2p/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] # SigP repository until PR is merged -libp2p = { git = "https://github.com/SigP/rust-libp2p", branch = "gossipsub" } +libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "987fec350b5c2eb55e5f0139615adab49ce493ff" } types = { path = "../../eth2/types" } ssz = { path = "../../eth2/utils/ssz" } ssz_derive = { path = "../../eth2/utils/ssz_derive" } diff --git a/eth2/types/Cargo.toml b/eth2/types/Cargo.toml index e4ccfd63e..d0e23b7dd 100644 --- a/eth2/types/Cargo.toml +++ b/eth2/types/Cargo.toml @@ -25,7 +25,7 @@ ssz = { path = "../utils/ssz" } ssz_derive = { path = "../utils/ssz_derive" } swap_or_not_shuffle = { path = "../utils/swap_or_not_shuffle" } test_random_derive = { path = "../utils/test_random_derive" } -libp2p = { git = "https://github.com/SigP/rust-libp2p", branch = "gossipsub" } +libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "987fec350b5c2eb55e5f0139615adab49ce493ff" } [dev-dependencies] env_logger = "0.6.0" From 0768d24ffc317be445e8e998db11368a4251ef0f Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 15:26:05 +1100 Subject: [PATCH 70/97] Add untested block processing from GRPC --- beacon_node/rpc/src/beacon_block.rs | 107 +++++++++++++++++++++------- beacon_node/rpc/src/beacon_chain.rs | 13 +++- beacon_node/rpc/src/lib.rs | 1 + 3 files changed, 94 insertions(+), 27 deletions(-) diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index 6317414b0..29a61766e 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -1,3 +1,4 @@ +use crate::beacon_chain::BeaconChain; use crossbeam_channel; use eth2_libp2p::rpc::methods::BlockRootSlot; use eth2_libp2p::PubsubMessage; @@ -9,13 +10,15 @@ use protos::services::{ PublishBeaconBlockRequest, PublishBeaconBlockResponse, }; use protos::services_grpc::BeaconBlockService; -use slog::debug; use slog::Logger; +use slog::{debug, error, info, warn}; use ssz::{Decodable, TreeHash}; +use std::sync::Arc; use types::{BeaconBlock, Hash256, Slot}; #[derive(Clone)] pub struct BeaconBlockServiceInstance { + pub chain: Arc, pub network_chan: crossbeam_channel::Sender, pub log: Logger, } @@ -50,39 +53,91 @@ impl BeaconBlockService for BeaconBlockServiceInstance { req: PublishBeaconBlockRequest, sink: UnarySink, ) { - debug!(self.log, "PublishBeaconBlock"); + let mut resp = PublishBeaconBlockResponse::new(); - let block = req.get_block(); + let ssz_serialized_block = req.get_block().get_ssz(); - match BeaconBlock::ssz_decode(block.get_ssz(), 0) { + match BeaconBlock::ssz_decode(ssz_serialized_block, 0) { Ok((block, _i)) => { let block_root = Hash256::from_slice(&block.hash_tree_root()[..]); - // TODO: Obtain topics from the network service properly. - let topic = types::TopicBuilder::new("beacon_chain".to_string()).build(); - let message = PubsubMessage::Block(BlockRootSlot { - block_root, - slot: block.slot, - }); + match self.chain.process_block(block.clone()) { + Ok(outcome) => { + if outcome.sucessfully_processed() { + // Block was successfully processed. + info!( + self.log, + "PublishBeaconBlock"; + "type" => "invalid_block", + "outcome" => format!("{:?}", outcome) + ); - println!("Sending beacon block to gossipsub"); - self.network_chan.send(NetworkMessage::Publish { - topics: vec![topic], - message, - }); + // TODO: Obtain topics from the network service properly. + let topic = + types::TopicBuilder::new("beacon_chain".to_string()).build(); + let message = PubsubMessage::Block(BlockRootSlot { + block_root, + slot: block.slot, + }); + + println!("Sending beacon block to gossipsub"); + self.network_chan.send(NetworkMessage::Publish { + topics: vec![topic], + message, + }); + + resp.set_success(true); + } else if outcome.is_invalid() { + // Block was invalid. + warn!( + self.log, + "PublishBeaconBlock"; + "type" => "invalid_block", + "outcome" => format!("{:?}", outcome) + ); + + resp.set_success(false); + resp.set_msg( + format!("InvalidBlock: {:?}", outcome).as_bytes().to_vec(), + ); + } else { + // Some failure during processing. + error!( + self.log, + "PublishBeaconBlock"; + "type" => "other", + "outcome" => format!("{:?}", outcome) + ); + + resp.set_success(false); + resp.set_msg(format!("other: {:?}", outcome).as_bytes().to_vec()); + } + } + Err(e) => { + // Some failure during processing. + error!( + self.log, + "PublishBeaconBlock"; + "type" => "failed_to_process", + "error" => format!("{:?}", e) + ); + + resp.set_success(false); + resp.set_msg(format!("failed_to_process: {:?}", e).as_bytes().to_vec()); + } + } - // TODO: actually process the block. - let mut resp = PublishBeaconBlockResponse::new(); resp.set_success(true); + } + Err(_) => { + resp.set_success(false); + resp.set_msg(b"Invalid SSZ".to_vec()); + } + }; - let f = sink - .success(resp) - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - ctx.spawn(f) - } - Err(e) => { - // - } - } + let f = sink + .success(resp) + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + ctx.spawn(f) } } diff --git a/beacon_node/rpc/src/beacon_chain.rs b/beacon_node/rpc/src/beacon_chain.rs index 9b2681876..0551a8024 100644 --- a/beacon_node/rpc/src/beacon_chain.rs +++ b/beacon_node/rpc/src/beacon_chain.rs @@ -5,14 +5,18 @@ use beacon_chain::{ parking_lot::RwLockReadGuard, slot_clock::SlotClock, types::{BeaconState, ChainSpec}, - CheckPoint, }; +pub use beacon_chain::{BeaconChainError, BlockProcessingOutcome}; +use types::BeaconBlock; /// The RPC's API to the beacon chain. pub trait BeaconChain: Send + Sync { fn get_spec(&self) -> &ChainSpec; fn get_state(&self) -> RwLockReadGuard; + + fn process_block(&self, block: BeaconBlock) + -> Result; } impl BeaconChain for RawBeaconChain @@ -28,4 +32,11 @@ where fn get_state(&self) -> RwLockReadGuard { self.state.read() } + + fn process_block( + &self, + block: BeaconBlock, + ) -> Result { + self.process_block(block) + } } diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 4dfd33487..289a81f3a 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -43,6 +43,7 @@ pub fn start_server( let beacon_block_service = { let instance = BeaconBlockServiceInstance { + chain: beacon_chain.clone(), network_chan, log: log.clone(), }; From 00b546e6b8c120f6629de3261282c77fae170665 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 15:44:28 +1100 Subject: [PATCH 71/97] Update slot clock to use genesis slot --- beacon_node/beacon_chain/src/initialise.rs | 16 ++++++++++++---- beacon_node/rpc/src/beacon_node.rs | 1 + .../slot_clock/src/system_time_slot_clock.rs | 11 ++++++++++- protos/src/services.proto | 1 + validator_client/src/service.rs | 6 ++++-- 5 files changed, 28 insertions(+), 7 deletions(-) diff --git a/beacon_node/beacon_chain/src/initialise.rs b/beacon_node/beacon_chain/src/initialise.rs index 7d3c87965..58b3aee84 100644 --- a/beacon_node/beacon_chain/src/initialise.rs +++ b/beacon_node/beacon_chain/src/initialise.rs @@ -35,8 +35,12 @@ pub fn initialise_beacon_chain( genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root()); // Slot clock - let slot_clock = SystemTimeSlotClock::new(genesis_state.genesis_time, spec.seconds_per_slot) - .expect("Unable to load SystemTimeSlotClock"); + let slot_clock = SystemTimeSlotClock::new( + spec.genesis_slot, + genesis_state.genesis_time, + spec.seconds_per_slot, + ) + .expect("Unable to load SystemTimeSlotClock"); // Choose the fork choice let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); @@ -72,8 +76,12 @@ pub fn initialise_test_beacon_chain( genesis_block.state_root = Hash256::from_slice(&genesis_state.hash_tree_root()); // Slot clock - let slot_clock = SystemTimeSlotClock::new(genesis_state.genesis_time, spec.seconds_per_slot) - .expect("Unable to load SystemTimeSlotClock"); + let slot_clock = SystemTimeSlotClock::new( + spec.genesis_slot, + genesis_state.genesis_time, + spec.seconds_per_slot, + ) + .expect("Unable to load SystemTimeSlotClock"); // Choose the fork choice let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); diff --git a/beacon_node/rpc/src/beacon_node.rs b/beacon_node/rpc/src/beacon_node.rs index 54984c5c2..c92ab6616 100644 --- a/beacon_node/rpc/src/beacon_node.rs +++ b/beacon_node/rpc/src/beacon_node.rs @@ -34,6 +34,7 @@ impl BeaconNodeService for BeaconNodeServiceInstance { node_info.set_fork(fork); node_info.set_genesis_time(genesis_time); + 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); // send the node_info the requester diff --git a/eth2/utils/slot_clock/src/system_time_slot_clock.rs b/eth2/utils/slot_clock/src/system_time_slot_clock.rs index 99f051985..816180d6e 100644 --- a/eth2/utils/slot_clock/src/system_time_slot_clock.rs +++ b/eth2/utils/slot_clock/src/system_time_slot_clock.rs @@ -13,6 +13,7 @@ pub enum Error { /// Determines the present slot based upon the present system time. #[derive(Clone)] pub struct SystemTimeSlotClock { + genesis_slot: Slot, genesis_seconds: u64, slot_duration_seconds: u64, } @@ -22,6 +23,7 @@ impl SystemTimeSlotClock { /// /// Returns an Error if `slot_duration_seconds == 0`. pub fn new( + genesis_slot: Slot, genesis_seconds: u64, slot_duration_seconds: u64, ) -> Result { @@ -29,6 +31,7 @@ impl SystemTimeSlotClock { Err(Error::SlotDurationIsZero) } else { Ok(Self { + genesis_slot, genesis_seconds, slot_duration_seconds, }) @@ -44,9 +47,11 @@ impl SlotClock for SystemTimeSlotClock { let duration_since_epoch = syslot_time.duration_since(SystemTime::UNIX_EPOCH)?; let duration_since_genesis = duration_since_epoch.checked_sub(Duration::from_secs(self.genesis_seconds)); + match duration_since_genesis { None => Ok(None), - Some(d) => Ok(slot_from_duration(self.slot_duration_seconds, d)), + Some(d) => Ok(slot_from_duration(self.slot_duration_seconds, d) + .and_then(|s| Some(s + self.genesis_slot))), } } } @@ -74,6 +79,7 @@ mod tests { #[test] fn test_slot_now() { let slot_time = 100; + let genesis_slot = Slot::new(0); let now = SystemTime::now(); let since_epoch = now.duration_since(SystemTime::UNIX_EPOCH).unwrap(); @@ -81,18 +87,21 @@ mod tests { let genesis = since_epoch.as_secs() - slot_time * 89; let clock = SystemTimeSlotClock { + genesis_slot, genesis_seconds: genesis, slot_duration_seconds: slot_time, }; assert_eq!(clock.present_slot().unwrap(), Some(Slot::new(89))); let clock = SystemTimeSlotClock { + genesis_slot, genesis_seconds: since_epoch.as_secs(), slot_duration_seconds: slot_time, }; assert_eq!(clock.present_slot().unwrap(), Some(Slot::new(0))); let clock = SystemTimeSlotClock { + genesis_slot, genesis_seconds: since_epoch.as_secs() - slot_time * 42 - 5, slot_duration_seconds: slot_time, }; diff --git a/protos/src/services.proto b/protos/src/services.proto index ee4f58d1b..6b2afceeb 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -45,6 +45,7 @@ message NodeInfoResponse { Fork fork = 2; uint32 chain_id = 3; uint64 genesis_time = 4; + uint64 genesis_slot = 5; } message Fork { diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 8a7e90d10..eb0771049 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -101,6 +101,7 @@ impl Service { // build requisite objects to form Self let genesis_time = node_info.get_genesis_time(); + let genesis_slot = Slot::from(node_info.get_genesis_slot()); info!(log,"Beacon node connected"; "Node Version" => node_info.version.clone(), "Chain ID" => node_info.chain_id, "Genesis time" => genesis_time); @@ -117,8 +118,9 @@ impl Service { // build the validator slot clock let slot_clock = { - let clock = SystemTimeSlotClock::new(genesis_time, config.spec.seconds_per_slot) - .expect("Unable to instantiate SystemTimeSlotClock."); + let clock = + SystemTimeSlotClock::new(genesis_slot, genesis_time, config.spec.seconds_per_slot) + .expect("Unable to instantiate SystemTimeSlotClock."); Arc::new(clock) }; From 9224558e060c0982908104aed29bde9fead539de Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 26 Mar 2019 15:53:49 +1100 Subject: [PATCH 72/97] Set genesis time for testing state builder --- eth2/types/src/test_utils/testing_beacon_state_builder.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index 473cd4166..fcdbb00ae 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -120,8 +120,10 @@ impl TestingBeaconStateBuilder { }) .collect(); + let genesis_time = 1549929600; // 12/2/2019 (arbitrary) + let mut state = BeaconState::genesis( - 0, + genesis_time, Eth1Data { deposit_root: Hash256::zero(), block_hash: Hash256::zero(), From 7c31c052f3589a7930a2e7277b23a43ca9aaad28 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 15:59:00 +1100 Subject: [PATCH 73/97] Temp commit - Re-building validator RPC API --- protos/src/services.proto | 29 ++++++++++++++++++--------- validator_client/src/duties/grpc.rs | 12 ++++++----- validator_client/src/duties/mod.rs | 19 ++++++------------ validator_client/src/duties/traits.rs | 5 ++--- validator_client/src/service.rs | 17 ++++++++-------- 5 files changed, 44 insertions(+), 38 deletions(-) diff --git a/protos/src/services.proto b/protos/src/services.proto index 80d512c54..bcfd353c7 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -27,7 +27,8 @@ service BeaconBlockService { //its public keys service ValidatorService { rpc ProposeBlockSlot(ProposeBlockSlotRequest) returns (ProposeBlockSlotResponse); - rpc ValidatorIndex(PublicKey) returns (IndexResponse); + /// Given a set of public keys, returns their respective indicies + rpc ValidatorIndex(PublicKeys) returns (Indicies); // rpc ValidatorAssignment(ValidatorAssignmentRequest) returns (ValidatorAssignmentResponse); } @@ -110,12 +111,12 @@ message ValidatorAssignment { // Validator Assignment -message PublicKey { - bytes public_key = 1; +message PublicKeys { + repeated bytes public_key = 1; } -message IndexResponse { - uint64 index = 1; +message Indicies { + repeated uint64 index = 1; } @@ -123,16 +124,26 @@ message IndexResponse { message ProposeBlockSlotRequest { uint64 epoch = 1; - uint64 validator_index = 2; + repeated uint64 validator_index = 2; } -message ProposeBlockSlotResponse { - oneof slot_oneof { +message GetDutiesResponse { + repeated oneof slot_oneof { bool none = 1; - uint64 slot = 2; + ValidatorDuty duty = 2; } } +ValidatorDuty { + oneof block_oneof { + bool none = 1; + uint64 block_produce_slot = 2; + } + uint64 committee_slot = 1; + uint64 committee_shard = 2; + uint64 committee_index = 3; +} + /* * Attestation Service Messages diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index 94f843b63..1f7297f0e 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -1,6 +1,6 @@ use super::traits::{BeaconNode, BeaconNodeError}; use super::EpochDuties; -use protos::services::{ProposeBlockSlotRequest, PublicKey as IndexRequest}; +use protos::services::{ProposeBlockSlotRequest, PublicKeys as IndexRequest}; use protos::services_grpc::ValidatorServiceClient; use ssz::ssz_encode; use types::{Epoch, PublicKey, Slot}; @@ -15,12 +15,14 @@ impl BeaconNode for ValidatorServiceClient { fn request_shuffling( &self, epoch: Epoch, - public_key: &PublicKey, + pubkeys: &[PublicKey], ) -> Result, BeaconNodeError> { - // Lookup the validator index for the supplied public key. - let validator_index = { + // Lookup the validator indexes for all the supplied public keys. + let validator_indices = { let mut req = IndexRequest::new(); - req.set_public_key(ssz_encode(public_key).to_vec()); + for public_key in pubkeys { + req.mut_public_key().push(ssz_encode(public_key)); + } let resp = self .validator_index(&req) .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 185f80d6d..77d6d43b6 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -10,9 +10,8 @@ use self::traits::{BeaconNode, BeaconNodeError}; use bls::PublicKey; use futures::Async; use slog::{debug, error, info}; -use slot_clock::SlotClock; use std::sync::Arc; -use types::{ChainSpec, Epoch, Slot}; +use types::{Epoch, Slot}; #[derive(Debug, PartialEq, Clone, Copy)] pub enum UpdateOutcome { @@ -30,8 +29,6 @@ pub enum UpdateOutcome { #[derive(Debug, PartialEq)] pub enum Error { - SlotClockError, - SlotUnknowable, EpochMapPoisoned, BeaconNodeError(BeaconNodeError), } @@ -40,27 +37,23 @@ pub enum Error { /// Node. /// /// This keeps track of all validator keys and required voting slots. -pub struct DutiesManager { +pub struct DutiesManager { pub duties_map: Arc, /// A list of all public keys known to the validator service. pub pubkeys: Vec, - pub spec: Arc, - pub slot_clock: Arc, + pub slots_per_epoch: u64, pub beacon_node: Arc, } -impl DutiesManager { +impl DutiesManager { /// Check the Beacon Node for `EpochDuties`. /// /// The present `epoch` will be learned from the supplied `SlotClock`. In production this will /// be a wall-clock (e.g., system time, remote server time, etc.). fn update(&self, slot: Slot) -> Result { - let epoch = slot.epoch(self.spec.slots_per_epoch); + let epoch = slot.epoch(self.slots_per_epoch); - if let Some(duties) = self - .beacon_node - .request_shuffling(epoch, &self.pubkeys[0])? - { + if let Some(duties) = self.beacon_node.request_shuffling(epoch, &self.pubkeys)? { // If these duties were known, check to see if they're updates or identical. let result = if let Some(known_duties) = self.duties_map.get(epoch)? { if known_duties == duties { diff --git a/validator_client/src/duties/traits.rs b/validator_client/src/duties/traits.rs index 5bf7da1fd..a3dcade4b 100644 --- a/validator_client/src/duties/traits.rs +++ b/validator_client/src/duties/traits.rs @@ -1,6 +1,5 @@ use super::EpochDuties; -use bls::PublicKey; -use types::Epoch; +use types::{Epoch, PublicKey}; #[derive(Debug, PartialEq, Clone)] pub enum BeaconNodeError { @@ -15,6 +14,6 @@ pub trait BeaconNode: Send + Sync { fn request_shuffling( &self, epoch: Epoch, - public_key: &PublicKey, + pubkeys: &[PublicKey], ) -> Result, BeaconNodeError>; } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 9ca591b92..e32271299 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -222,11 +222,11 @@ impl Service { // build requisite objects to pass to core thread. let duties_map = Arc::new(EpochDutiesMap::new(config.spec.slots_per_epoch)); let epoch_map_for_attester = Arc::new(EpochMap::new(config.spec.slots_per_epoch)); + let manager = Arc::new(DutiesManager { duties_map, pubkeys: keypairs.iter().map(|keypair| keypair.pk.clone()).collect(), - spec: Arc::new(config.spec), - slot_clock: service.slot_clock.clone(), + slots_per_epoch: config.spec.slots_per_epoch.clone(), beacon_node: service.validator_client.clone(), }); @@ -234,6 +234,7 @@ impl Service { runtime .block_on(interval.for_each(move |_| { let log = service.log.clone(); + // get the current slot let current_slot = match service.slot_clock.present_slot() { Err(e) => { @@ -250,24 +251,24 @@ impl Service { info!(log, "Processing slot: {}", current_slot.as_u64()); - let cloned_manager = manager.clone(); - // check for new duties + let cloned_manager = manager.clone(); tokio::spawn(futures::future::poll_fn(move || { cloned_manager.run_update(current_slot.clone(), log.clone()) })); + + // execute any specified duties + Ok(()) })) .map_err(|e| format!("Service thread failed: {:?}", e))?; + + // completed a slot process Ok(()) } /* - let duties_map = Arc::new(EpochDutiesMap::new(spec.slots_per_epoch)); - let epoch_map_for_attester = Arc::new(EpochMap::new(spec.slots_per_epoch)); - - for keypair in keypairs { info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); From 507c8efbfbd4f5aa0a719aa6781abe8ae1f5f124 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 26 Mar 2019 16:38:50 +1100 Subject: [PATCH 74/97] Update to latest gossipsub --- beacon_node/eth2-libp2p/Cargo.toml | 2 +- eth2/types/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/beacon_node/eth2-libp2p/Cargo.toml b/beacon_node/eth2-libp2p/Cargo.toml index beb1a0234..f3914b04e 100644 --- a/beacon_node/eth2-libp2p/Cargo.toml +++ b/beacon_node/eth2-libp2p/Cargo.toml @@ -6,7 +6,7 @@ edition = "2018" [dependencies] # SigP repository until PR is merged -libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "987fec350b5c2eb55e5f0139615adab49ce493ff" } +libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "b3c32d9a821ae6cc89079499cc6e8a6bab0bffc3" } types = { path = "../../eth2/types" } ssz = { path = "../../eth2/utils/ssz" } ssz_derive = { path = "../../eth2/utils/ssz_derive" } diff --git a/eth2/types/Cargo.toml b/eth2/types/Cargo.toml index d0e23b7dd..6fe5ce6e8 100644 --- a/eth2/types/Cargo.toml +++ b/eth2/types/Cargo.toml @@ -25,7 +25,7 @@ ssz = { path = "../utils/ssz" } ssz_derive = { path = "../utils/ssz_derive" } swap_or_not_shuffle = { path = "../utils/swap_or_not_shuffle" } test_random_derive = { path = "../utils/test_random_derive" } -libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "987fec350b5c2eb55e5f0139615adab49ce493ff" } +libp2p = { git = "https://github.com/SigP/rust-libp2p", rev = "b3c32d9a821ae6cc89079499cc6e8a6bab0bffc3" } [dev-dependencies] env_logger = "0.6.0" From c27fdbe37fbceab145e6b4e99844705a7e630c47 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 10:28:27 +1100 Subject: [PATCH 75/97] Try to load keys from file when starting client --- beacon_node/beacon_chain/src/initialise.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/beacon_node/beacon_chain/src/initialise.rs b/beacon_node/beacon_chain/src/initialise.rs index 58b3aee84..0951e06fb 100644 --- a/beacon_node/beacon_chain/src/initialise.rs +++ b/beacon_node/beacon_chain/src/initialise.rs @@ -28,7 +28,7 @@ pub fn initialise_beacon_chain( let block_store = Arc::new(BeaconBlockStore::new(db.clone())); let state_store = Arc::new(BeaconStateStore::new(db.clone())); - let state_builder = TestingBeaconStateBuilder::from_deterministic_keypairs(8, &spec); + let state_builder = TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(8, &spec); let (genesis_state, _keypairs) = state_builder.build(); let mut genesis_block = BeaconBlock::empty(&spec); @@ -69,7 +69,7 @@ pub fn initialise_test_beacon_chain( let block_store = Arc::new(BeaconBlockStore::new(db.clone())); let state_store = Arc::new(BeaconStateStore::new(db.clone())); - let state_builder = TestingBeaconStateBuilder::from_deterministic_keypairs(8, spec); + let state_builder = TestingBeaconStateBuilder::from_default_keypairs_file_if_exists(8, spec); let (genesis_state, _keypairs) = state_builder.build(); let mut genesis_block = BeaconBlock::empty(spec); From c82bad7602ba8257a432cba9ab4ba05859d0af9e Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 10:34:52 +1100 Subject: [PATCH 76/97] Add cache builds when advancing chain slot --- beacon_node/beacon_chain/src/beacon_chain.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index f0290d939..2caee2f98 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -342,6 +342,10 @@ where // If required, transition the new state to the present slot. for _ in state.slot.as_u64()..present_slot.as_u64() { + // Ensure the next epoch state caches are built in case of an epoch transition. + state.build_epoch_cache(RelativeEpoch::NextWithoutRegistryChange, &self.spec)?; + state.build_epoch_cache(RelativeEpoch::NextWithRegistryChange, &self.spec)?; + per_slot_processing(&mut *state, &latest_block_header, &self.spec)?; } From b88750960736f94b3b20f1d71dcbdf634debd798 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 10:35:21 +1100 Subject: [PATCH 77/97] Fix double advance-cache calls bug --- eth2/state_processing/src/per_slot_processing.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/eth2/state_processing/src/per_slot_processing.rs b/eth2/state_processing/src/per_slot_processing.rs index 8f02b70e3..c6b5312c7 100644 --- a/eth2/state_processing/src/per_slot_processing.rs +++ b/eth2/state_processing/src/per_slot_processing.rs @@ -20,7 +20,6 @@ pub fn per_slot_processing( if (state.slot + 1) % spec.slots_per_epoch == 0 { per_epoch_processing(state, spec)?; - state.advance_caches(); } state.slot += 1; From b006586d19d44d40882747d10f5b04346b9f0895 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 10:36:20 +1100 Subject: [PATCH 78/97] Add slot timer to beacon node --- beacon_node/Cargo.toml | 1 + beacon_node/beacon_chain/src/beacon_chain.rs | 14 ++++ beacon_node/client/Cargo.toml | 1 + beacon_node/client/src/lib.rs | 76 ++++++++++++++++++- beacon_node/client/src/notifier.rs | 4 +- beacon_node/src/run.rs | 2 + eth2/utils/slot_clock/src/lib.rs | 3 + .../slot_clock/src/system_time_slot_clock.rs | 28 +++++++ .../slot_clock/src/testing_slot_clock.rs | 6 ++ 9 files changed, 132 insertions(+), 3 deletions(-) diff --git a/beacon_node/Cargo.toml b/beacon_node/Cargo.toml index e7aaf938d..a090c1cc5 100644 --- a/beacon_node/Cargo.toml +++ b/beacon_node/Cargo.toml @@ -14,6 +14,7 @@ slog-term = "^2.4.0" slog-async = "^2.3.0" ctrlc = { version = "3.1.1", features = ["termination"] } tokio = "0.1.15" +tokio-timer = "0.2.10" futures = "0.1.25" exit-future = "0.1.3" state_processing = { path = "../eth2/state_processing" } diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 2caee2f98..6fcb3fde4 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -409,6 +409,20 @@ where } } + /// Reads the slot clock (see `self.read_slot_clock()` and returns the number of slots since + /// genesis. + pub fn slots_since_genesis(&self) -> Option { + let now = self.read_slot_clock()?; + + if now < self.spec.genesis_slot { + None + } else { + Some(SlotHeight::from( + now.as_u64() - self.spec.genesis_slot.as_u64(), + )) + } + } + /// Returns slot of the present state. /// /// This is distinct to `read_slot_clock`, which reads from the actual system clock. If diff --git a/beacon_node/client/Cargo.toml b/beacon_node/client/Cargo.toml index 12c1b5c80..8956dbb07 100644 --- a/beacon_node/client/Cargo.toml +++ b/beacon_node/client/Cargo.toml @@ -14,6 +14,7 @@ types = { path = "../../eth2/types" } slot_clock = { path = "../../eth2/utils/slot_clock" } error-chain = "0.12.0" slog = "^2.2.3" +ssz = { path = "../../eth2/utils/ssz" } tokio = "0.1.15" clap = "2.32.0" dirs = "1.0.3" diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index b24d2cb7f..2ce181aa1 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -9,11 +9,17 @@ use beacon_chain::BeaconChain; pub use client_config::ClientConfig; pub use client_types::ClientTypes; use exit_future::Signal; +use futures::{future::Future, Stream}; use network::Service as NetworkService; -use slog::o; +use slog::{error, info, o}; +use slot_clock::SlotClock; +use ssz::TreeHash; use std::marker::PhantomData; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::runtime::TaskExecutor; +use tokio::timer::Interval; +use types::Hash256; /// Main beacon node client service. This provides the connection and initialisation of the clients /// sub-services in multiple threads. @@ -26,6 +32,8 @@ pub struct Client { pub network: Arc, /// Signal to terminate the RPC server. pub rpc_exit_signal: Option, + /// Signal to terminate the slot timer. + pub slot_timer_exit_signal: Option, /// The clients logger. log: slog::Logger, /// Marker to pin the beacon chain generics. @@ -42,6 +50,17 @@ impl Client { // generate a beacon chain let beacon_chain = TClientType::initialise_beacon_chain(&config); + { + let state = beacon_chain.state.read(); + let state_root = Hash256::from_slice(&state.hash_tree_root()); + info!( + log, + "ChainInitialized"; + "state_root" => format!("{}", state_root), + "genesis_time" => format!("{}", state.genesis_time), + ); + } + // Start the network service, libp2p and syncing threads // TODO: Add beacon_chain reference to network parameters let network_config = &config.net_conf; @@ -65,10 +84,65 @@ impl Client { )); } + 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() { + // set up the validator work interval - start at next slot and proceed every slot + let interval = { + // Set the interval to start at the next slot, and every slot after + let slot_duration = Duration::from_secs(config.spec.seconds_per_slot); + //TODO: Handle checked add correctly + Interval::new(Instant::now() + duration_to_next_slot, slot_duration) + }; + + let chain = beacon_chain.clone(); + let log = log.new(o!("Service" => "SlotTimer")); + + let state_slot = chain.state.read().slot; + let wall_clock_slot = chain.read_slot_clock().unwrap(); + let slots_since_genesis = chain.slots_since_genesis().unwrap(); + info!( + log, + "Starting SlotTimer"; + "state_slot" => state_slot, + "wall_clock_slot" => wall_clock_slot, + "slots_since_genesis" => slots_since_genesis, + "catchup_distance" => wall_clock_slot - state_slot, + ); + executor.spawn( + exit.until( + interval + .for_each(move |_| { + if let Some(genesis_height) = chain.slots_since_genesis() { + match chain.catchup_state() { + Ok(_) => info!( + log, + "NewSlot"; + "slot" => chain.state.read().slot, + "slots_since_genesis" => genesis_height, + ), + Err(e) => error!( + log, + "StateCatchupFailed"; + "state_slot" => chain.state.read().slot, + "slots_since_genesis" => genesis_height, + "error" => format!("{:?}", e), + ), + }; + } + + Ok(()) + }) + .map_err(|_| ()), + ) + .map(|_| ()), + ); + } + Ok(Client { config, beacon_chain, rpc_exit_signal, + slot_timer_exit_signal: Some(slot_timer_exit_signal), log, network, phantom: PhantomData, diff --git a/beacon_node/client/src/notifier.rs b/beacon_node/client/src/notifier.rs index 335183c7d..91a9f3a26 100644 --- a/beacon_node/client/src/notifier.rs +++ b/beacon_node/client/src/notifier.rs @@ -2,7 +2,7 @@ use crate::Client; use crate::ClientTypes; use exit_future::Exit; use futures::{Future, Stream}; -use slog::{debug, info, o}; +use slog::{debug, o}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use tokio::runtime::TaskExecutor; @@ -22,7 +22,7 @@ pub fn run(client: &Client, executor: TaskExecutor, exit: Exi // build heartbeat logic here let heartbeat = move |_| { - info!(log, "Temp heartbeat output"); + debug!(log, "Temp heartbeat output"); //TODO: Remove this logic. Testing only let mut count = counter.lock().unwrap(); *count += 1; diff --git a/beacon_node/src/run.rs b/beacon_node/src/run.rs index b3b284452..1d9156124 100644 --- a/beacon_node/src/run.rs +++ b/beacon_node/src/run.rs @@ -6,10 +6,12 @@ use futures::Future; use slog::info; use std::cell::RefCell; use tokio::runtime::Builder; +use tokio_timer::clock::Clock; pub fn run_beacon_node(config: ClientConfig, log: &slog::Logger) -> error::Result<()> { let mut runtime = Builder::new() .name_prefix("main-") + .clock(Clock::system()) .build() .map_err(|e| format!("{:?}", e))?; diff --git a/eth2/utils/slot_clock/src/lib.rs b/eth2/utils/slot_clock/src/lib.rs index 0379d50d9..fd5a2d1d7 100644 --- a/eth2/utils/slot_clock/src/lib.rs +++ b/eth2/utils/slot_clock/src/lib.rs @@ -3,10 +3,13 @@ mod testing_slot_clock; pub use crate::system_time_slot_clock::{Error as SystemTimeSlotClockError, SystemTimeSlotClock}; pub use crate::testing_slot_clock::{Error as TestingSlotClockError, TestingSlotClock}; +use std::time::Duration; pub use types::Slot; pub trait SlotClock: Send + Sync { type Error; fn present_slot(&self) -> Result, Self::Error>; + + fn duration_to_next_slot(&self) -> Result, Self::Error>; } diff --git a/eth2/utils/slot_clock/src/system_time_slot_clock.rs b/eth2/utils/slot_clock/src/system_time_slot_clock.rs index 816180d6e..4dfc6b37d 100644 --- a/eth2/utils/slot_clock/src/system_time_slot_clock.rs +++ b/eth2/utils/slot_clock/src/system_time_slot_clock.rs @@ -54,6 +54,10 @@ impl SlotClock for SystemTimeSlotClock { .and_then(|s| Some(s + self.genesis_slot))), } } + + fn duration_to_next_slot(&self) -> Result, Error> { + duration_to_next_slot(self.genesis_seconds, self.slot_duration_seconds) + } } impl From for Error { @@ -67,6 +71,30 @@ fn slot_from_duration(slot_duration_seconds: u64, duration: Duration) -> Option< duration.as_secs().checked_div(slot_duration_seconds)?, )) } +// calculate the duration to the next slot +fn duration_to_next_slot( + genesis_time: u64, + seconds_per_slot: u64, +) -> Result, Error> { + let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?; + let genesis_time = Duration::from_secs(genesis_time); + + if now < genesis_time { + return Ok(None); + } + + let since_genesis = now - genesis_time; + + let elapsed_slots = since_genesis.as_secs() / seconds_per_slot; + + let next_slot_start_seconds = (elapsed_slots + 1) + .checked_mul(seconds_per_slot) + .expect("Next slot time should not overflow u64"); + + let time_to_next_slot = Duration::from_secs(next_slot_start_seconds) - since_genesis; + + Ok(Some(time_to_next_slot)) +} #[cfg(test)] mod tests { diff --git a/eth2/utils/slot_clock/src/testing_slot_clock.rs b/eth2/utils/slot_clock/src/testing_slot_clock.rs index 80ee40539..b5c36dfa0 100644 --- a/eth2/utils/slot_clock/src/testing_slot_clock.rs +++ b/eth2/utils/slot_clock/src/testing_slot_clock.rs @@ -1,5 +1,6 @@ use super::SlotClock; use std::sync::RwLock; +use std::time::Duration; use types::Slot; #[derive(Debug, PartialEq)] @@ -32,6 +33,11 @@ impl SlotClock for TestingSlotClock { let slot = *self.slot.read().expect("TestingSlotClock poisoned."); Ok(Some(Slot::new(slot))) } + + /// Always returns a duration of 1 second. + fn duration_to_next_slot(&self) -> Result, Error> { + Ok(Some(Duration::from_secs(1))) + } } #[cfg(test)] From 8733740f8b08ff44d30977a4b089fd3eec471b85 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 10:36:37 +1100 Subject: [PATCH 79/97] Move genesis time closer to now --- eth2/types/src/test_utils/testing_beacon_state_builder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index fcdbb00ae..493f234a2 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -120,7 +120,7 @@ impl TestingBeaconStateBuilder { }) .collect(); - let genesis_time = 1549929600; // 12/2/2019 (arbitrary) + let genesis_time = 1553638359; // arbitrary let mut state = BeaconState::genesis( genesis_time, From f18941a01c21e4854ca9342e5bcd084ccfd37af6 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 11:25:15 +1100 Subject: [PATCH 80/97] Block client startup until state is ready --- beacon_node/client/src/lib.rs | 93 ++++++++++++++++++----------- beacon_node/rpc/src/beacon_block.rs | 7 ++- 2 files changed, 63 insertions(+), 37 deletions(-) diff --git a/beacon_node/client/src/lib.rs b/beacon_node/client/src/lib.rs index 2ce181aa1..807fd9301 100644 --- a/beacon_node/client/src/lib.rs +++ b/beacon_node/client/src/lib.rs @@ -8,7 +8,9 @@ pub mod notifier; use beacon_chain::BeaconChain; pub use client_config::ClientConfig; pub use client_types::ClientTypes; +use db::ClientDB; use exit_future::Signal; +use fork_choice::ForkChoice; use futures::{future::Future, Stream}; use network::Service as NetworkService; use slog::{error, info, o}; @@ -50,16 +52,34 @@ impl Client { // generate a beacon chain let beacon_chain = TClientType::initialise_beacon_chain(&config); + if beacon_chain.read_slot_clock().is_none() { + panic!("Cannot start client before genesis!") + } + + // Block starting the client until we have caught the state up to the current slot. + // + // If we don't block here we create an initial scenario where we're unable to process any + // blocks and we're basically useless. { - let state = beacon_chain.state.read(); - let state_root = Hash256::from_slice(&state.hash_tree_root()); + let state_slot = beacon_chain.state.read().slot; + let wall_clock_slot = beacon_chain.read_slot_clock().unwrap(); + let slots_since_genesis = beacon_chain.slots_since_genesis().unwrap(); info!( log, - "ChainInitialized"; - "state_root" => format!("{}", state_root), - "genesis_time" => format!("{}", state.genesis_time), + "Initializing state"; + "state_slot" => state_slot, + "wall_clock_slot" => wall_clock_slot, + "slots_since_genesis" => slots_since_genesis, + "catchup_distance" => wall_clock_slot - state_slot, ); } + do_state_catchup(&beacon_chain, &log); + info!( + log, + "State initialized"; + "state_slot" => beacon_chain.state.read().slot, + "wall_clock_slot" => beacon_chain.read_slot_clock().unwrap(), + ); // Start the network service, libp2p and syncing threads // TODO: Add beacon_chain reference to network parameters @@ -96,39 +116,11 @@ impl Client { let chain = beacon_chain.clone(); let log = log.new(o!("Service" => "SlotTimer")); - - let state_slot = chain.state.read().slot; - let wall_clock_slot = chain.read_slot_clock().unwrap(); - let slots_since_genesis = chain.slots_since_genesis().unwrap(); - info!( - log, - "Starting SlotTimer"; - "state_slot" => state_slot, - "wall_clock_slot" => wall_clock_slot, - "slots_since_genesis" => slots_since_genesis, - "catchup_distance" => wall_clock_slot - state_slot, - ); executor.spawn( exit.until( interval .for_each(move |_| { - if let Some(genesis_height) = chain.slots_since_genesis() { - match chain.catchup_state() { - Ok(_) => info!( - log, - "NewSlot"; - "slot" => chain.state.read().slot, - "slots_since_genesis" => genesis_height, - ), - Err(e) => error!( - log, - "StateCatchupFailed"; - "state_slot" => chain.state.read().slot, - "slots_since_genesis" => genesis_height, - "error" => format!("{:?}", e), - ), - }; - } + do_state_catchup(&chain, &log); Ok(()) }) @@ -149,3 +141,36 @@ impl Client { }) } } + +fn do_state_catchup(chain: &Arc>, log: &slog::Logger) +where + T: ClientDB, + U: SlotClock, + F: ForkChoice, +{ + if let Some(genesis_height) = chain.slots_since_genesis() { + let result = chain.catchup_state(); + + let common = o!( + "best_slot" => chain.head().beacon_block.slot, + "latest_block_root" => format!("{}", chain.head().beacon_block_root), + "wall_clock_slot" => chain.read_slot_clock().unwrap(), + "state_slot" => chain.state.read().slot, + "slots_since_genesis" => genesis_height, + ); + + match result { + Ok(_) => info!( + log, + "NewSlot"; + common + ), + Err(e) => error!( + log, + "StateCatchupFailed"; + "error" => format!("{:?}", e), + common + ), + }; + } +} diff --git a/beacon_node/rpc/src/beacon_block.rs b/beacon_node/rpc/src/beacon_block.rs index 29a61766e..f6b426c18 100644 --- a/beacon_node/rpc/src/beacon_block.rs +++ b/beacon_node/rpc/src/beacon_block.rs @@ -68,7 +68,8 @@ impl BeaconBlockService for BeaconBlockServiceInstance { info!( self.log, "PublishBeaconBlock"; - "type" => "invalid_block", + "type" => "valid_block", + "block_slot" => block.slot, "outcome" => format!("{:?}", outcome) ); @@ -102,10 +103,10 @@ impl BeaconBlockService for BeaconBlockServiceInstance { ); } else { // Some failure during processing. - error!( + warn!( self.log, "PublishBeaconBlock"; - "type" => "other", + "type" => "unable_to_import", "outcome" => format!("{:?}", outcome) ); From 0c4306cd1876a3d5375510fb25440408d4d87028 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 11:57:38 +1100 Subject: [PATCH 81/97] Move genesis time forward --- eth2/types/src/test_utils/testing_beacon_state_builder.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index 493f234a2..3951820d8 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -120,7 +120,7 @@ impl TestingBeaconStateBuilder { }) .collect(); - let genesis_time = 1553638359; // arbitrary + let genesis_time = 1553647464; // arbitrary let mut state = BeaconState::genesis( genesis_time, From 12936e73a777abc1d876747b0b5dd1248a55c1db Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Wed, 27 Mar 2019 12:57:05 +1100 Subject: [PATCH 82/97] Set gossip logs to `info` --- beacon_node/network/src/sync/simple_sync.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/beacon_node/network/src/sync/simple_sync.rs b/beacon_node/network/src/sync/simple_sync.rs index 2aa0a1d7d..85949fa98 100644 --- a/beacon_node/network/src/sync/simple_sync.rs +++ b/beacon_node/network/src/sync/simple_sync.rs @@ -523,9 +523,9 @@ impl SimpleSync { msg: BlockRootSlot, network: &mut NetworkContext, ) { - debug!( + info!( self.log, - "BlockSlot"; + "NewGossipBlock"; "peer" => format!("{:?}", peer_id), ); // TODO: filter out messages that a prior to the finalized slot. @@ -557,9 +557,9 @@ impl SimpleSync { msg: Attestation, _network: &mut NetworkContext, ) { - debug!( + info!( self.log, - "Attestation"; + "NewAttestationGossip"; "peer" => format!("{:?}", peer_id), ); From bc8ec51fe5235da040f4dbf608b152b776331abd Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 15:41:51 +1100 Subject: [PATCH 83/97] Update EpochDuty RPC and core functionality --- protos/src/services.proto | 50 +++++-------- validator_client/src/duties/epoch_duties.rs | 30 +++++--- validator_client/src/duties/grpc.rs | 78 ++++++++++----------- validator_client/src/duties/traits.rs | 9 +-- 4 files changed, 79 insertions(+), 88 deletions(-) diff --git a/protos/src/services.proto b/protos/src/services.proto index bcfd353c7..dea9b7a37 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -26,10 +26,9 @@ service BeaconBlockService { /// Service that provides the validator client with requisite knowledge about //its public keys service ValidatorService { - rpc ProposeBlockSlot(ProposeBlockSlotRequest) returns (ProposeBlockSlotResponse); - /// Given a set of public keys, returns their respective indicies - rpc ValidatorIndex(PublicKeys) returns (Indicies); - // rpc ValidatorAssignment(ValidatorAssignmentRequest) returns (ValidatorAssignmentResponse); + // Gets the block proposer slot and comittee slot that a validator needs to + // perform work on. + rpc GetValidatorDuties(GetDutiesRequest) returns (GetDutiesResponse); } /// Service that handles validator attestations @@ -93,58 +92,41 @@ message BeaconBlock { /* * Validator Service Messages */ -/* -message ValidatorAssignmentRequest { - uint64 epoch = 1; - bytes validator_index = 2; -} - -// A validators duties for some epoch. -// TODO: add shard duties. -message ValidatorAssignment { - oneof block_production_slot_oneof { - bool block_production_slot_none = 1; - uint64 block_production_slot = 2; - } -} -*/ // Validator Assignment -message PublicKeys { +// the public keys of the validators +message Validators { repeated bytes public_key = 1; } -message Indicies { - repeated uint64 index = 1; -} - - // Propose slot - -message ProposeBlockSlotRequest { +message GetDutiesRequest { uint64 epoch = 1; - repeated uint64 validator_index = 2; + Validators validators = 2; } message GetDutiesResponse { - repeated oneof slot_oneof { + repeated ActiveValidator active_validator = 1; +} + +message ActiveValidator { + oneof slot_oneof { bool none = 1; ValidatorDuty duty = 2; } } -ValidatorDuty { +message ValidatorDuty { oneof block_oneof { bool none = 1; uint64 block_produce_slot = 2; } - uint64 committee_slot = 1; - uint64 committee_shard = 2; - uint64 committee_index = 3; + uint64 committee_slot = 3; + uint64 committee_shard = 4; + uint64 committee_index = 5; } - /* * Attestation Service Messages */ diff --git a/validator_client/src/duties/epoch_duties.rs b/validator_client/src/duties/epoch_duties.rs index 71f5f26ab..41d3a24c2 100644 --- a/validator_client/src/duties/epoch_duties.rs +++ b/validator_client/src/duties/epoch_duties.rs @@ -1,30 +1,40 @@ use block_proposer::{DutiesReader, DutiesReaderError}; use std::collections::HashMap; use std::sync::RwLock; -use types::{Epoch, Fork, Slot}; +use types::{Epoch, Fork, PublicKey, Slot}; /// The information required for a validator to propose and attest during some epoch. /// /// Generally obtained from a Beacon Node, this information contains the validators canonical index -/// (thier sequence in the global validator induction process) and the "shuffling" for that index +/// (their sequence in the global validator induction process) and the "shuffling" for that index /// for some epoch. #[derive(Debug, PartialEq, Clone, Copy, Default)] -pub struct EpochDuties { - pub validator_index: u64, +pub struct EpochDuty { pub block_production_slot: Option, - // Future shard info + pub committee_slot: Slot, + pub committee_shard: u64, + pub committee_index: u64, } -impl EpochDuties { - /// Returns `true` if the supplied `slot` is a slot in which the validator should produce a - /// block. - pub fn is_block_production_slot(&self, slot: Slot) -> bool { +impl EpochDuty { + /// Returns `true` if work needs to be done in the supplied `slot` + pub fn is_work_slot(&self, slot: Slot) -> bool { + // if validator is required to produce a slot return true match self.block_production_slot { - Some(s) if s == slot => true, + Some(s) if s == slot => return true, _ => false, } + + if self.committee_slot == slot { + return true; + } + return false; } } +/// Maps a list of public keys (many validators) to an EpochDuty. +pub struct EpochDuties { + inner: HashMap>, +} pub enum EpochDutiesMapError { Poisoned, diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index 1f7297f0e..91da512e3 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -1,56 +1,54 @@ +use super::epoch_duties::{EpochDuties, EpochDuty}; use super::traits::{BeaconNode, BeaconNodeError}; -use super::EpochDuties; -use protos::services::{ProposeBlockSlotRequest, PublicKeys as IndexRequest}; +use protos::services::{ + ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty, Validators, +}; use protos::services_grpc::ValidatorServiceClient; use ssz::ssz_encode; +use std::collections::HashMap; use types::{Epoch, PublicKey, Slot}; impl BeaconNode for ValidatorServiceClient { - /// Request the shuffling from the Beacon Node (BN). - /// - /// As this function takes a `PublicKey`, it will first attempt to resolve the public key into - /// a validator index, then call the BN for production/attestation duties. - /// - /// Note: presently only block production information is returned. - fn request_shuffling( + /// Requests all duties (block signing and committee attesting) from the Beacon Node (BN). + fn request_duties( &self, epoch: Epoch, pubkeys: &[PublicKey], - ) -> Result, BeaconNodeError> { - // Lookup the validator indexes for all the supplied public keys. - let validator_indices = { - let mut req = IndexRequest::new(); - for public_key in pubkeys { - req.mut_public_key().push(ssz_encode(public_key)); - } - let resp = self - .validator_index(&req) - .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; - resp.get_index() - }; - - let mut req = ProposeBlockSlotRequest::new(); - req.set_validator_index(validator_index); + ) -> Result { + // Get the required duties from all validators + // build the request + let mut req = GetDutiesRequest::new(); req.set_epoch(epoch.as_u64()); + let validators = Validators::new().mut_public_key(); + for pubkey in pubkeys { + validators.push(pubkey); + } + req.set_validators(validators); + // send the request, get the duties reply let reply = self - .propose_block_slot(&req) + .get_validator_duties(&req) .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; - let block_production_slot = if reply.has_slot() { - Some(reply.get_slot()) - } else { - None - }; - - let block_production_slot = match block_production_slot { - Some(slot) => Some(Slot::new(slot)), - None => None, - }; - - Ok(Some(EpochDuties { - validator_index, - block_production_slot, - })) + let mut epoch_duties: HashMap> = HashMap::new(); + for (index, validator_duty) in reply.get_active_validator().enumerate() { + if let Some(duty) = validator_duty.has_slot() { + // the validator is active + //build the EpochDuty + let active_duty = duty.get_duty(); + let block_produce_slot = active_duty.get_block_produce_slot(); + let epoch_duty = EpochDuty { + block_produce_slot, + committee_slot: active_duty.get_committee_slot(), + committee_shard: active_duty.get_committee_shard(), + committee_index: active_duty.get_committee_index(), + }; + epoch_duties.insert(pubkeys[index], Some(epoch_duty)); + } else { + // validator is not active and has no duties + epoch_duties.insert(pubkeys[index], None); + } + } + Ok(epoch_duties) } } diff --git a/validator_client/src/duties/traits.rs b/validator_client/src/duties/traits.rs index a3dcade4b..3aa8fbab2 100644 --- a/validator_client/src/duties/traits.rs +++ b/validator_client/src/duties/traits.rs @@ -8,12 +8,13 @@ pub enum BeaconNodeError { /// Defines the methods required to obtain a validators shuffling from a Beacon Node. pub trait BeaconNode: Send + Sync { - /// Get the shuffling for the given epoch and public key. + /// Gets the duties for all validators. /// - /// Returns Ok(None) if the public key is unknown, or the shuffling for that epoch is unknown. - fn request_shuffling( + /// Returns a vector of EpochDuties for each validator public key. The entry will be None for + /// validators that are not activated. + fn request_duties( &self, epoch: Epoch, pubkeys: &[PublicKey], - ) -> Result, BeaconNodeError>; + ) -> Result>, BeaconNodeError>; } From 46181408ba566a528214a8bd1b29b4f4af55870a Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 19:47:08 +1100 Subject: [PATCH 84/97] Epoch duties update --- protos/src/services.proto | 8 +- validator_client/src/duties/epoch_duties.rs | 117 +++++++++++--------- validator_client/src/duties/grpc.rs | 49 ++++---- validator_client/src/duties/mod.rs | 60 +++++----- validator_client/src/duties/traits.rs | 2 +- validator_client/src/service.rs | 40 ++++--- 6 files changed, 152 insertions(+), 124 deletions(-) diff --git a/protos/src/services.proto b/protos/src/services.proto index dea9b7a37..7a4bbc977 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -97,7 +97,7 @@ message BeaconBlock { // the public keys of the validators message Validators { - repeated bytes public_key = 1; + repeated bytes public_keys = 1; } // Propose slot @@ -107,11 +107,11 @@ message GetDutiesRequest { } message GetDutiesResponse { - repeated ActiveValidator active_validator = 1; + repeated ActiveValidator active_validators = 1; } message ActiveValidator { - oneof slot_oneof { + oneof duty_oneof { bool none = 1; ValidatorDuty duty = 2; } @@ -120,7 +120,7 @@ message ActiveValidator { message ValidatorDuty { oneof block_oneof { bool none = 1; - uint64 block_produce_slot = 2; + uint64 block_production_slot = 2; } uint64 committee_slot = 3; uint64 committee_shard = 4; diff --git a/validator_client/src/duties/epoch_duties.rs b/validator_client/src/duties/epoch_duties.rs index 41d3a24c2..de787c4b8 100644 --- a/validator_client/src/duties/epoch_duties.rs +++ b/validator_client/src/duties/epoch_duties.rs @@ -1,7 +1,13 @@ -use block_proposer::{DutiesReader, DutiesReaderError}; use std::collections::HashMap; -use std::sync::RwLock; -use types::{Epoch, Fork, PublicKey, Slot}; +use std::ops::{Deref, DerefMut}; +use types::{Epoch, PublicKey, Slot}; + +/// The type of work a validator is required to do in a given slot. +#[derive(Debug, Clone)] +pub struct WorkType { + produce_block: bool, + produce_attestation: bool, +} /// The information required for a validator to propose and attest during some epoch. /// @@ -17,84 +23,91 @@ pub struct EpochDuty { } impl EpochDuty { - /// Returns `true` if work needs to be done in the supplied `slot` - pub fn is_work_slot(&self, slot: Slot) -> bool { + /// Returns `WorkType` if work needs to be done in the supplied `slot` + pub fn is_work_slot(&self, slot: Slot) -> Option { // if validator is required to produce a slot return true - match self.block_production_slot { - Some(s) if s == slot => return true, + let produce_block = match self.block_production_slot { + Some(s) if s == slot => true, _ => false, + }; + + let mut produce_attestation = false; + if self.committee_slot == slot { + produce_attestation = true; } - if self.committee_slot == slot { - return true; + if produce_block | produce_attestation { + return Some(WorkType { + produce_block, + produce_attestation, + }); } - return false; + None } } /// Maps a list of public keys (many validators) to an EpochDuty. -pub struct EpochDuties { - inner: HashMap>, -} +pub type EpochDuties = HashMap>; pub enum EpochDutiesMapError { Poisoned, + UnknownEpoch, + UnknownValidator, } /// Maps an `epoch` to some `EpochDuties` for a single validator. pub struct EpochDutiesMap { pub slots_per_epoch: u64, - pub map: RwLock>, + pub map: HashMap, } impl EpochDutiesMap { pub fn new(slots_per_epoch: u64) -> Self { Self { slots_per_epoch, - map: RwLock::new(HashMap::new()), + map: HashMap::new(), } } - - pub fn get(&self, epoch: Epoch) -> Result, EpochDutiesMapError> { - let map = self.map.read().map_err(|_| EpochDutiesMapError::Poisoned)?; - match map.get(&epoch) { - Some(duties) => Ok(Some(*duties)), - None => Ok(None), - } - } - - pub fn insert( - &self, - epoch: Epoch, - epoch_duties: EpochDuties, - ) -> Result, EpochDutiesMapError> { - let mut map = self - .map - .write() - .map_err(|_| EpochDutiesMapError::Poisoned)?; - Ok(map.insert(epoch, epoch_duties)) - } } -impl DutiesReader for EpochDutiesMap { - fn is_block_production_slot(&self, slot: Slot) -> Result { +// Expose the hashmap methods +impl Deref for EpochDutiesMap { + type Target = HashMap; + + fn deref(&self) -> &Self::Target { + &self.map + } +} +impl DerefMut for EpochDutiesMap { + fn deref_mut(&mut self) -> &mut HashMap { + &mut self.map + } +} + +impl EpochDutiesMap { + /// Checks if the validator has work to do. + fn is_work_slot( + &self, + slot: Slot, + pubkey: &PublicKey, + ) -> Result, EpochDutiesMapError> { let epoch = slot.epoch(self.slots_per_epoch); - let map = self.map.read().map_err(|_| DutiesReaderError::Poisoned)?; - let duties = map + let epoch_duties = self + .map .get(&epoch) - .ok_or_else(|| DutiesReaderError::UnknownEpoch)?; - Ok(duties.is_block_production_slot(slot)) - } - - fn fork(&self) -> Result { - // TODO: this is garbage data. - // - // It will almost certainly cause signatures to fail verification. - Ok(Fork { - previous_version: [0; 4], - current_version: [0; 4], - epoch: Epoch::new(0), - }) + .ok_or_else(|| EpochDutiesMapError::UnknownEpoch)?; + if let Some(epoch_duty) = epoch_duties.get(pubkey) { + if let Some(duty) = epoch_duty { + // Retrieves the duty for a validator at a given slot + return Ok(duty.is_work_slot(slot)); + } else { + // the validator isn't active + return Ok(None); + } + } else { + // validator isn't known + return Err(EpochDutiesMapError::UnknownValidator); + } } } diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index 91da512e3..32ac86435 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -1,8 +1,6 @@ use super::epoch_duties::{EpochDuties, EpochDuty}; use super::traits::{BeaconNode, BeaconNodeError}; -use protos::services::{ - ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty, Validators, -}; +use protos::services::{GetDutiesRequest, Validators}; use protos::services_grpc::ValidatorServiceClient; use ssz::ssz_encode; use std::collections::HashMap; @@ -19,10 +17,8 @@ impl BeaconNode for ValidatorServiceClient { // build the request let mut req = GetDutiesRequest::new(); req.set_epoch(epoch.as_u64()); - let validators = Validators::new().mut_public_key(); - for pubkey in pubkeys { - validators.push(pubkey); - } + let mut validators = Validators::new(); + validators.set_public_keys(pubkeys.iter().map(|v| ssz_encode(v)).collect()); req.set_validators(validators); // send the request, get the duties reply @@ -30,24 +26,29 @@ impl BeaconNode for ValidatorServiceClient { .get_validator_duties(&req) .map_err(|err| BeaconNodeError::RemoteFailure(format!("{:?}", err)))?; - let mut epoch_duties: HashMap> = HashMap::new(); - for (index, validator_duty) in reply.get_active_validator().enumerate() { - if let Some(duty) = validator_duty.has_slot() { - // the validator is active - //build the EpochDuty - let active_duty = duty.get_duty(); - let block_produce_slot = active_duty.get_block_produce_slot(); - let epoch_duty = EpochDuty { - block_produce_slot, - committee_slot: active_duty.get_committee_slot(), - committee_shard: active_duty.get_committee_shard(), - committee_index: active_duty.get_committee_index(), - }; - epoch_duties.insert(pubkeys[index], Some(epoch_duty)); - } else { - // validator is not active and has no duties - epoch_duties.insert(pubkeys[index], None); + let mut epoch_duties: HashMap> = HashMap::new(); + for (index, validator_duty) in reply.get_active_validators().iter().enumerate() { + if !validator_duty.has_duty() { + // validator is inactive + epoch_duties.insert(pubkeys[index].clone(), None); + break; } + // active validator + let active_duty = validator_duty.get_duty(); + let block_production_slot = { + if active_duty.has_block_production_slot() { + Some(Slot::from(active_duty.get_block_production_slot())) + } else { + None + } + }; + let epoch_duty = EpochDuty { + block_production_slot, + committee_slot: Slot::from(active_duty.get_committee_slot()), + committee_shard: active_duty.get_committee_shard(), + committee_index: active_duty.get_committee_index(), + }; + epoch_duties.insert(pubkeys[index].clone(), Some(epoch_duty)); } Ok(epoch_duties) } diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 77d6d43b6..20a477910 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -1,7 +1,8 @@ mod epoch_duties; mod grpc; -#[cfg(test)] -mod test_node; +// TODO: reintroduce tests +//#[cfg(test)] +//mod test_node; mod traits; pub use self::epoch_duties::EpochDutiesMap; @@ -11,9 +12,10 @@ use bls::PublicKey; use futures::Async; use slog::{debug, error, info}; use std::sync::Arc; -use types::{Epoch, Slot}; +use std::sync::RwLock; +use types::Epoch; -#[derive(Debug, PartialEq, Clone, Copy)] +#[derive(Debug, PartialEq, Clone)] pub enum UpdateOutcome { /// The `EpochDuties` were not updated during this poll. NoChange(Epoch), @@ -29,8 +31,11 @@ pub enum UpdateOutcome { #[derive(Debug, PartialEq)] pub enum Error { + DutiesMapPoisoned, EpochMapPoisoned, BeaconNodeError(BeaconNodeError), + UnknownEpoch, + UnknownValidator, } /// A polling state machine which ensures the latest `EpochDuties` are obtained from the Beacon @@ -38,43 +43,37 @@ pub enum Error { /// /// This keeps track of all validator keys and required voting slots. pub struct DutiesManager { - pub duties_map: Arc, + pub duties_map: RwLock, /// A list of all public keys known to the validator service. pub pubkeys: Vec, - pub slots_per_epoch: u64, pub beacon_node: Arc, } impl DutiesManager { /// Check the Beacon Node for `EpochDuties`. /// - /// The present `epoch` will be learned from the supplied `SlotClock`. In production this will /// be a wall-clock (e.g., system time, remote server time, etc.). - fn update(&self, slot: Slot) -> Result { - let epoch = slot.epoch(self.slots_per_epoch); - - if let Some(duties) = self.beacon_node.request_shuffling(epoch, &self.pubkeys)? { - // If these duties were known, check to see if they're updates or identical. - let result = if let Some(known_duties) = self.duties_map.get(epoch)? { - if known_duties == duties { - Ok(UpdateOutcome::NoChange(epoch)) - } else { - Ok(UpdateOutcome::DutiesChanged(epoch, duties)) - } + fn update(&self, epoch: Epoch) -> Result { + let duties = self.beacon_node.request_duties(epoch, &self.pubkeys)?; + // If these duties were known, check to see if they're updates or identical. + let result = if let Some(known_duties) = self.duties_map.read()?.get(&epoch) { + if *known_duties == duties { + return Ok(UpdateOutcome::NoChange(epoch)); } else { - Ok(UpdateOutcome::NewDuties(epoch, duties)) - }; - self.duties_map.insert(epoch, duties)?; - result + //TODO: Duties could be large here. Remove from display and avoid the clone. + return Ok(UpdateOutcome::DutiesChanged(epoch, duties.clone())); + } } else { - Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) - } + Ok(UpdateOutcome::NewDuties(epoch, duties.clone())) + }; + self.duties_map.write()?.insert(epoch, duties); + result } /// A future wrapping around `update()`. This will perform logic based upon the update /// process and complete once the update has completed. - pub fn run_update(&self, slot: Slot, log: slog::Logger) -> Result, ()> { - match self.update(slot) { + pub fn run_update(&self, epoch: Epoch, log: slog::Logger) -> Result, ()> { + match self.update(epoch) { Err(error) => error!(log, "Epoch duties poll error"; "error" => format!("{:?}", error)), Ok(UpdateOutcome::NoChange(epoch)) => { debug!(log, "No change in duties"; "epoch" => epoch) @@ -93,16 +92,25 @@ impl DutiesManager { } } +//TODO: Use error_chain to handle errors impl From for Error { fn from(e: BeaconNodeError) -> Error { Error::BeaconNodeError(e) } } +//TODO: Use error_chain to handle errors +impl From> for Error { + fn from(e: std::sync::PoisonError) -> Error { + Error::DutiesMapPoisoned + } +} impl From for Error { fn from(e: EpochDutiesMapError) -> Error { match e { EpochDutiesMapError::Poisoned => Error::EpochMapPoisoned, + EpochDutiesMapError::UnknownEpoch => Error::UnknownEpoch, + EpochDutiesMapError::UnknownValidator => Error::UnknownValidator, } } } diff --git a/validator_client/src/duties/traits.rs b/validator_client/src/duties/traits.rs index 3aa8fbab2..374bed9f6 100644 --- a/validator_client/src/duties/traits.rs +++ b/validator_client/src/duties/traits.rs @@ -16,5 +16,5 @@ pub trait BeaconNode: Send + Sync { &self, epoch: Epoch, pubkeys: &[PublicKey], - ) -> Result>, BeaconNodeError>; + ) -> Result; } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index e32271299..c8e03e73d 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -37,12 +37,14 @@ pub struct Service { chain_id: u16, /// The fork state we processing on. fork: Fork, - /// The slot clock keeping track of time. - slot_clock: Arc, + /// The slot clock for this service. + slot_clock: SystemTimeSlotClock, /// The current slot we are processing. current_slot: Slot, /// Duration until the next slot. This is used for initializing the tokio timer interval. duration_to_next_slot: Duration, + /// The number of slots per epoch to allow for converting slots to epochs. + slots_per_epoch: u64, // GRPC Clients /// The beacon block GRPC client. beacon_block_client: Arc, @@ -74,7 +76,7 @@ impl Service { // retrieve node information let node_info = loop { - let info = match beacon_node_client.info(&Empty::new()) { + match beacon_node_client.info(&Empty::new()) { Err(e) => { warn!(log, "Could not connect to node. Error: {}", e); info!(log, "Retrying in 5 seconds..."); @@ -115,13 +117,6 @@ impl Service { epoch: Epoch::from(proto_fork.get_epoch()), }; - // build the validator slot clock - let slot_clock = { - let clock = SystemTimeSlotClock::new(genesis_time, config.spec.seconds_per_slot) - .expect("Unable to instantiate SystemTimeSlotClock."); - Arc::new(clock) - }; - // initialize the RPC clients // Beacon node gRPC beacon block endpoints. @@ -142,6 +137,10 @@ impl Service { Arc::new(AttestationServiceClient::new(ch)) }; + // build the validator slot clock + let slot_clock = SystemTimeSlotClock::new(genesis_time, config.spec.seconds_per_slot) + .expect("Unable to instantiate SystemTimeSlotClock."); + let current_slot = slot_clock .present_slot() .map_err(|e| ErrorKind::SlotClockError(e))? @@ -179,6 +178,7 @@ impl Service { slot_clock, current_slot, duration_to_next_slot, + slots_per_epoch: config.spec.slots_per_epoch, beacon_block_client, validator_client, attester_client, @@ -211,7 +211,7 @@ impl Service { ) }; - // kick off core service + /* kick off core service */ // generate keypairs @@ -219,14 +219,18 @@ impl Service { // https://github.com/sigp/lighthouse/issues/160 let keypairs = Arc::new(vec![Keypair::random()]); - // build requisite objects to pass to core thread. - let duties_map = Arc::new(EpochDutiesMap::new(config.spec.slots_per_epoch)); - let epoch_map_for_attester = Arc::new(EpochMap::new(config.spec.slots_per_epoch)); + /* build requisite objects to pass to core thread */ + // Builds a mapping of Epoch -> Map(PublicKey, EpochDuty) + // where EpochDuty contains slot numbers and attestation data that each validator needs to + // produce work on. + let duties_map = EpochDutiesMap::new(config.spec.slots_per_epoch); + + // builds a manager which maintains the list of current duties for all known validators + // and can check when a validator needs to perform a task. let manager = Arc::new(DutiesManager { duties_map, pubkeys: keypairs.iter().map(|keypair| keypair.pk.clone()).collect(), - slots_per_epoch: config.spec.slots_per_epoch.clone(), beacon_node: service.validator_client.clone(), }); @@ -244,6 +248,8 @@ impl Service { Ok(slot) => slot.expect("Genesis is in the future"), }; + let current_epoch = current_slot.epoch(service.slots_per_epoch); + debug_assert!( current_slot > service.current_slot, "The Timer should poll a new slot" @@ -252,9 +258,9 @@ impl Service { info!(log, "Processing slot: {}", current_slot.as_u64()); // check for new duties - let cloned_manager = manager.clone(); + let mut cloned_manager = manager.clone(); tokio::spawn(futures::future::poll_fn(move || { - cloned_manager.run_update(current_slot.clone(), log.clone()) + cloned_manager.run_update(current_epoch.clone(), log.clone()) })); // execute any specified duties From cde049df1f16bc5cd39fb1de499b904410577043 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 19:52:05 +1100 Subject: [PATCH 85/97] Adds RwLock to EpochDuty --- validator_client/src/service.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index c8e03e73d..f47570f74 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -19,6 +19,7 @@ use protos::services_grpc::{ use slog::{debug, error, info, warn}; use slot_clock::{SlotClock, SystemTimeSlotClock}; use std::sync::Arc; +use std::sync::RwLock; use std::time::{Duration, Instant, SystemTime}; use tokio::prelude::*; use tokio::runtime::Builder; @@ -224,7 +225,7 @@ impl Service { // Builds a mapping of Epoch -> Map(PublicKey, EpochDuty) // where EpochDuty contains slot numbers and attestation data that each validator needs to // produce work on. - let duties_map = EpochDutiesMap::new(config.spec.slots_per_epoch); + let duties_map = RwLock::new(EpochDutiesMap::new(config.spec.slots_per_epoch)); // builds a manager which maintains the list of current duties for all known validators // and can check when a validator needs to perform a task. From 1f437a3e7b939a57fe98e5902b3f5bf8daa00926 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 21:08:28 +1100 Subject: [PATCH 86/97] Implements RPC Server side of epoch duties --- beacon_node/rpc/src/lib.rs | 5 +- beacon_node/rpc/src/validator.rs | 131 ++++++++++++++++++++++++------- protos/src/services.proto | 4 +- 3 files changed, 108 insertions(+), 32 deletions(-) diff --git a/beacon_node/rpc/src/lib.rs b/beacon_node/rpc/src/lib.rs index 4dfd33487..20cd62b1d 100644 --- a/beacon_node/rpc/src/lib.rs +++ b/beacon_node/rpc/src/lib.rs @@ -49,7 +49,10 @@ pub fn start_server( create_beacon_block_service(instance) }; let validator_service = { - let instance = ValidatorServiceInstance { log: log.clone() }; + let instance = ValidatorServiceInstance { + chain: beacon_chain.clone(), + log: log.clone(), + }; create_validator_service(instance) }; diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index f894deca6..8071fac5c 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -2,59 +2,132 @@ use bls::PublicKey; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; use protos::services::{ - IndexResponse, ProposeBlockSlotRequest, ProposeBlockSlotResponse, PublicKey as PublicKeyRequest, -}; + GetDutiesRequest, GetDutiesResponse, Validators}; use protos::services_grpc::ValidatorService; use slog::{debug, Logger}; use ssz::Decodable; +use std::sync::Arc; +use crate::beacon_chain::BeaconChain; #[derive(Clone)] pub struct ValidatorServiceInstance { + pub chain: Arc, pub log: Logger, } +//TODO: Refactor Errors impl ValidatorService for ValidatorServiceInstance { - fn validator_index( + + /// For a list of validator public keys, this function returns the slot at which each + /// validator must propose a block, attest to a shard, their shard committee and the shard they + /// need to attest to. + fn get_validator_duties ( &mut self, ctx: RpcContext, - req: PublicKeyRequest, - sink: UnarySink, + req: GetDutiesRequest, + sink: UnarySink, ) { - if let Ok((public_key, _)) = PublicKey::ssz_decode(req.get_public_key(), 0) { - debug!(self.log, "RPC request"; "endpoint" => "ValidatorIndex", "public_key" => public_key.concatenated_hex_id()); + let validators = req.get_validators(); + debug!(self.log, "RPC request"; "endpoint" => "GetValidatorDuties", "epoch" => req.get_epoch()); - let mut resp = IndexResponse::new(); + let epoch = req.get_epoch(); + let mut resp = GetDutiesResponse::new(); - // TODO: return a legit value. - resp.set_index(1); + let spec = self.chain.spec; + let state = self.chain.state.read(); - let f = sink - .success(resp) - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - ctx.spawn(f) - } else { - let f = sink + //TODO: Decide whether to rebuild the cache + //TODO: Get the active validator indicies + //let active_validator_indices = self.chain.state.read().get_cached_active_validator_indices( + let active_validator_indices = &[1,2,3,4,5,6,7,8]; + // TODO: Is this the most efficient? Perhaps we cache this data structure. + + // this is an array of validators who are to propose this epoch + // TODO: RelativeEpoch? + let validator_proposers = 0..spec.slots_per_epoch.to_iter().map(|slot| state.get_beacon_proposer_index(slot, epoch, &spec)).collect(); + + // get the duties for each validator + for validator in validators { + let active_validator = ActiveValidator::new(); + + + let public_key = match PublicKey::ssz_decode(validator, 0) { + Ok((v_) => v, + Err(_) => { + let f = sink .fail(RpcStatus::new( RpcStatusCode::InvalidArgument, Some("Invalid public_key".to_string()), )) + //TODO: Handle error correctly .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - ctx.spawn(f) - } - } + return ctx.spawn(f); + } + }; - fn propose_block_slot( - &mut self, - ctx: RpcContext, - req: ProposeBlockSlotRequest, - sink: UnarySink, - ) { - debug!(self.log, "RPC request"; "endpoint" => "ProposeBlockSlot", "epoch" => req.get_epoch(), "validator_index" => req.get_validator_index()); + // is the validator active + let val_index = match state.get_validator_index(&public_key) { + Ok(index) => { + if active_validator_indices.contains(index) { + // validator is active, return the index + index + } + else { + // validator is inactive, go to the next validator + active_validator.set_none(); + resp.push(active_validator); + break; + } + }, + // the cache is not built, throw an error + Err(_) =>{ + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::FailedPreCondition, + Some("Beacon state cache is not built".to_string()), + )) + //TODO: Handle error correctly + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + return ctx.spawn(f); + } + }; - let mut resp = ProposeBlockSlotResponse::new(); + // we have an active validator, set its duties + let duty = ValidatorDuty::new(); + + // check if it needs to propose a block + let Some(slot) = validator_proposers.iter().position(|&v| val_index ==v) { + duty.set_block_production_slot(slot); + } + else { + // no blocks to propose this epoch + duty.set_none() + } + + // get attestation duties + let attestation_duties = match state.get_attestation_duties(val_index, &spec) { + Ok(v) => v, + // the cache is not built, throw an error + Err(_) =>{ + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::FailedPreCondition, + Some("Beacon state cache is not built".to_string()), + )) + //TODO: Handle error correctly + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + return ctx.spawn(f); + } + }; + + duty.set_committee_index(attestation_duties.committee_index); + duty.set_attestation_slot(attestation_duties.slot); + duty.set_attestation_shard(attestation_duties.shard); + + active_validator.set_duty(duty); + resp.push(active_validator); + } - // TODO: return a legit value. - resp.set_slot(1); let f = sink .success(resp) diff --git a/protos/src/services.proto b/protos/src/services.proto index 7a4bbc977..82a2703e6 100644 --- a/protos/src/services.proto +++ b/protos/src/services.proto @@ -122,8 +122,8 @@ message ValidatorDuty { bool none = 1; uint64 block_production_slot = 2; } - uint64 committee_slot = 3; - uint64 committee_shard = 4; + uint64 attestation_slot = 3; + uint64 attestation_shard = 4; uint64 committee_index = 5; } From 086ebb1485cb558cddd5441b7971ccd9ac8ff96c Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 21:32:53 +1100 Subject: [PATCH 87/97] Fix beacon node rpc compilation issues --- beacon_node/rpc/src/validator.rs | 122 ++++++++++++++++--------------- 1 file changed, 64 insertions(+), 58 deletions(-) diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index 8071fac5c..47886a9df 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -1,13 +1,12 @@ +use crate::beacon_chain::BeaconChain; use bls::PublicKey; use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; -use protos::services::{ - GetDutiesRequest, GetDutiesResponse, Validators}; +use protos::services::{ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty}; use protos::services_grpc::ValidatorService; use slog::{debug, Logger}; use ssz::Decodable; use std::sync::Arc; -use crate::beacon_chain::BeaconChain; #[derive(Clone)] pub struct ValidatorServiceInstance { @@ -17,11 +16,10 @@ pub struct ValidatorServiceInstance { //TODO: Refactor Errors impl ValidatorService for ValidatorServiceInstance { - /// For a list of validator public keys, this function returns the slot at which each /// validator must propose a block, attest to a shard, their shard committee and the shard they /// need to attest to. - fn get_validator_duties ( + fn get_validator_duties( &mut self, ctx: RpcContext, req: GetDutiesRequest, @@ -32,102 +30,110 @@ impl ValidatorService for ValidatorServiceInstance { let epoch = req.get_epoch(); let mut resp = GetDutiesResponse::new(); + let resp_validators = resp.mut_active_validators(); - let spec = self.chain.spec; - let state = self.chain.state.read(); + let spec = self.chain.get_spec(); + let state = self.chain.get_state(); //TODO: Decide whether to rebuild the cache //TODO: Get the active validator indicies //let active_validator_indices = self.chain.state.read().get_cached_active_validator_indices( - let active_validator_indices = &[1,2,3,4,5,6,7,8]; + let active_validator_indices = vec![1, 2, 3, 4, 5, 6, 7, 8]; // TODO: Is this the most efficient? Perhaps we cache this data structure. // this is an array of validators who are to propose this epoch // TODO: RelativeEpoch? - let validator_proposers = 0..spec.slots_per_epoch.to_iter().map(|slot| state.get_beacon_proposer_index(slot, epoch, &spec)).collect(); + //let validator_proposers = [0..spec.slots_per_epoch].iter().map(|slot| state.get_beacon_proposer_index(Slot::from(slot), epoch, &spec)).collect(); + let validator_proposers: Vec = vec![1, 2, 3, 4, 5]; // get the duties for each validator - for validator in validators { - let active_validator = ActiveValidator::new(); + for validator_pk in validators.get_public_keys() { + let mut active_validator = ActiveValidator::new(); - - let public_key = match PublicKey::ssz_decode(validator, 0) { - Ok((v_) => v, - Err(_) => { - let f = sink - .fail(RpcStatus::new( - RpcStatusCode::InvalidArgument, - Some("Invalid public_key".to_string()), - )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - return ctx.spawn(f); - } + let public_key = match PublicKey::ssz_decode(validator_pk, 0) { + Ok((v, _index)) => v, + Err(_) => { + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::InvalidArgument, + Some("Invalid public_key".to_string()), + )) + //TODO: Handle error correctly + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + return ctx.spawn(f); + } }; // is the validator active let val_index = match state.get_validator_index(&public_key) { - Ok(index) => { - if active_validator_indices.contains(index) { + Ok(Some(index)) => { + if active_validator_indices.contains(&index) { // validator is active, return the index index - } - else { + } else { // validator is inactive, go to the next validator - active_validator.set_none(); - resp.push(active_validator); + active_validator.set_none(false); + resp_validators.push(active_validator); break; } - }, + } + // validator index is not known, skip it + Ok(_) => { + active_validator.set_none(false); + resp_validators.push(active_validator); + break; + } // the cache is not built, throw an error - Err(_) =>{ + Err(_) => { let f = sink - .fail(RpcStatus::new( - RpcStatusCode::FailedPreCondition, - Some("Beacon state cache is not built".to_string()), - )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + .fail(RpcStatus::new( + RpcStatusCode::FailedPrecondition, + Some("Beacon state cache is not built".to_string()), + )) + //TODO: Handle error correctly + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); return ctx.spawn(f); } }; // we have an active validator, set its duties - let duty = ValidatorDuty::new(); + let mut duty = ValidatorDuty::new(); - // check if it needs to propose a block - let Some(slot) = validator_proposers.iter().position(|&v| val_index ==v) { - duty.set_block_production_slot(slot); - } - else { + // check if the validator needs to propose a block + if let Some(slot) = validator_proposers + .iter() + .position(|&v| val_index as u64 == v) + { + duty.set_block_production_slot(epoch * spec.slots_per_epoch + slot as u64); + } else { // no blocks to propose this epoch - duty.set_none() + duty.set_none(false) } // get attestation duties let attestation_duties = match state.get_attestation_duties(val_index, &spec) { - Ok(v) => v, + Ok(Some(v)) => v, + Ok(_) => unreachable!(), //we've checked the validator index // the cache is not built, throw an error - Err(_) =>{ + Err(_) => { let f = sink - .fail(RpcStatus::new( - RpcStatusCode::FailedPreCondition, - Some("Beacon state cache is not built".to_string()), - )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + .fail(RpcStatus::new( + RpcStatusCode::FailedPrecondition, + Some("Beacon state cache is not built".to_string()), + )) + //TODO: Handle error correctly + .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); return ctx.spawn(f); } }; - duty.set_committee_index(attestation_duties.committee_index); - duty.set_attestation_slot(attestation_duties.slot); + duty.set_committee_index(attestation_duties.committee_index as u64); + duty.set_attestation_slot(attestation_duties.slot.as_u64()); duty.set_attestation_shard(attestation_duties.shard); active_validator.set_duty(duty); - resp.push(active_validator); - } - + resp_validators.push(active_validator); + } let f = sink .success(resp) From a315e9da493a0c7d9abab637f4dda7c0c06e0aa4 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 21:36:06 +1100 Subject: [PATCH 88/97] Rename fields in validator client EpochDuties --- validator_client/src/duties/epoch_duties.rs | 6 +++--- validator_client/src/duties/grpc.rs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/validator_client/src/duties/epoch_duties.rs b/validator_client/src/duties/epoch_duties.rs index de787c4b8..24b01e620 100644 --- a/validator_client/src/duties/epoch_duties.rs +++ b/validator_client/src/duties/epoch_duties.rs @@ -17,8 +17,8 @@ pub struct WorkType { #[derive(Debug, PartialEq, Clone, Copy, Default)] pub struct EpochDuty { pub block_production_slot: Option, - pub committee_slot: Slot, - pub committee_shard: u64, + pub attestation_slot: Slot, + pub attestation_shard: u64, pub committee_index: u64, } @@ -32,7 +32,7 @@ impl EpochDuty { }; let mut produce_attestation = false; - if self.committee_slot == slot { + if self.attestation_slot == slot { produce_attestation = true; } diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index 32ac86435..0a4b3dffe 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -44,8 +44,8 @@ impl BeaconNode for ValidatorServiceClient { }; let epoch_duty = EpochDuty { block_production_slot, - committee_slot: Slot::from(active_duty.get_committee_slot()), - committee_shard: active_duty.get_committee_shard(), + attestation_slot: Slot::from(active_duty.get_attestation_slot()), + attestation_shard: active_duty.get_attestation_shard(), committee_index: active_duty.get_committee_index(), }; epoch_duties.insert(pubkeys[index].clone(), Some(epoch_duty)); From 75195bbbf46bf1b027c2a84ec5b0872cc16e312d Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 22:22:51 +1100 Subject: [PATCH 89/97] Implement work finding logic in validator client --- validator_client/src/duties/epoch_duties.rs | 6 +-- validator_client/src/duties/mod.rs | 45 ++++++++++++++------- validator_client/src/service.rs | 20 +++++++-- 3 files changed, 49 insertions(+), 22 deletions(-) diff --git a/validator_client/src/duties/epoch_duties.rs b/validator_client/src/duties/epoch_duties.rs index 24b01e620..a74ded18b 100644 --- a/validator_client/src/duties/epoch_duties.rs +++ b/validator_client/src/duties/epoch_duties.rs @@ -5,8 +5,8 @@ use types::{Epoch, PublicKey, Slot}; /// The type of work a validator is required to do in a given slot. #[derive(Debug, Clone)] pub struct WorkType { - produce_block: bool, - produce_attestation: bool, + pub produce_block: bool, + pub produce_attestation: bool, } /// The information required for a validator to propose and attest during some epoch. @@ -85,7 +85,7 @@ impl DerefMut for EpochDutiesMap { impl EpochDutiesMap { /// Checks if the validator has work to do. - fn is_work_slot( + pub fn is_work_slot( &self, slot: Slot, pubkey: &PublicKey, diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 20a477910..94b845083 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -5,15 +5,14 @@ mod grpc; //mod test_node; mod traits; -pub use self::epoch_duties::EpochDutiesMap; use self::epoch_duties::{EpochDuties, EpochDutiesMapError}; +pub use self::epoch_duties::{EpochDutiesMap, WorkType}; use self::traits::{BeaconNode, BeaconNodeError}; -use bls::PublicKey; use futures::Async; use slog::{debug, error, info}; use std::sync::Arc; use std::sync::RwLock; -use types::Epoch; +use types::{Epoch, PublicKey, Slot}; #[derive(Debug, PartialEq, Clone)] pub enum UpdateOutcome { @@ -24,9 +23,6 @@ pub enum UpdateOutcome { /// New `EpochDuties` were obtained, different to those which were previously known. This is /// likely to be the result of chain re-organisation. DutiesChanged(Epoch, EpochDuties), - /// The Beacon Node was unable to return the duties as the validator is unknown, or the - /// shuffling for the epoch is unknown. - UnknownValidatorOrEpoch(Epoch), } #[derive(Debug, PartialEq)] @@ -56,18 +52,19 @@ impl DutiesManager { fn update(&self, epoch: Epoch) -> Result { let duties = self.beacon_node.request_duties(epoch, &self.pubkeys)?; // If these duties were known, check to see if they're updates or identical. - let result = if let Some(known_duties) = self.duties_map.read()?.get(&epoch) { + if let Some(known_duties) = self.duties_map.read()?.get(&epoch) { if *known_duties == duties { return Ok(UpdateOutcome::NoChange(epoch)); } else { //TODO: Duties could be large here. Remove from display and avoid the clone. - return Ok(UpdateOutcome::DutiesChanged(epoch, duties.clone())); + self.duties_map.write()?.insert(epoch, duties.clone()); + return Ok(UpdateOutcome::DutiesChanged(epoch, duties)); } } else { - Ok(UpdateOutcome::NewDuties(epoch, duties.clone())) + //TODO: Remove clone by removing duties from outcome + self.duties_map.write()?.insert(epoch, duties.clone()); + return Ok(UpdateOutcome::NewDuties(epoch, duties)); }; - self.duties_map.write()?.insert(epoch, duties); - result } /// A future wrapping around `update()`. This will perform logic based upon the update @@ -84,12 +81,30 @@ impl DutiesManager { Ok(UpdateOutcome::NewDuties(epoch, duties)) => { info!(log, "New duties obtained"; "epoch" => epoch, "duties" => format!("{:?}", duties)) } - Ok(UpdateOutcome::UnknownValidatorOrEpoch(epoch)) => { - error!(log, "Epoch or validator unknown"; "epoch" => epoch) - } }; Ok(Async::Ready(())) } + + /// Returns a list of (Public, WorkType) indicating all the validators that have work to perform + /// this slot. + pub fn get_current_work(&self, slot: Slot) -> Option> { + let mut current_work: Vec<(PublicKey, WorkType)> = Vec::new(); + + // if the map is poisoned, return None + let duties = self.duties_map.read().ok()?; + + for validator_pk in &self.pubkeys { + match duties.is_work_slot(slot, &validator_pk) { + Ok(Some(work_type)) => current_work.push((validator_pk.clone(), work_type)), + Ok(None) => {} // No work for this validator + Err(_) => {} // Unknown epoch or validator, no work + } + } + if current_work.is_empty() { + return None; + } + Some(current_work) + } } //TODO: Use error_chain to handle errors @@ -101,7 +116,7 @@ impl From for Error { //TODO: Use error_chain to handle errors impl From> for Error { - fn from(e: std::sync::PoisonError) -> Error { + fn from(_e: std::sync::PoisonError) -> Error { Error::DutiesMapPoisoned } } diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index f47570f74..07d88d344 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -240,7 +240,7 @@ impl Service { .block_on(interval.for_each(move |_| { let log = service.log.clone(); - // get the current slot + /* get the current slot and epoch */ let current_slot = match service.slot_clock.present_slot() { Err(e) => { error!(log, "SystemTimeError {:?}", e); @@ -258,13 +258,25 @@ impl Service { info!(log, "Processing slot: {}", current_slot.as_u64()); - // check for new duties - let mut cloned_manager = manager.clone(); + /* check for new duties */ + + let cloned_manager = manager.clone(); tokio::spawn(futures::future::poll_fn(move || { cloned_manager.run_update(current_epoch.clone(), log.clone()) })); - // execute any specified duties + /* execute any specified duties */ + + if let Some(work) = manager.get_current_work(current_slot) { + for (_public_key, work_type) in work { + if work_type.produce_block { + // TODO: Produce a beacon block in a new thread + } + if work_type.produce_attestation { + //TODO: Produce an attestation in a new thread + } + } + } Ok(()) })) From d3af95d1eba1725b21370447f6d02611c010ecf6 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 27 Mar 2019 22:41:55 +1100 Subject: [PATCH 90/97] Returns attestation duty for validator client processing --- validator_client/src/duties/epoch_duties.rs | 34 +++++++++++++-------- validator_client/src/duties/mod.rs | 8 ++--- validator_client/src/service.rs | 5 ++- 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/validator_client/src/duties/epoch_duties.rs b/validator_client/src/duties/epoch_duties.rs index a74ded18b..5c23e82b1 100644 --- a/validator_client/src/duties/epoch_duties.rs +++ b/validator_client/src/duties/epoch_duties.rs @@ -1,12 +1,17 @@ use std::collections::HashMap; use std::ops::{Deref, DerefMut}; -use types::{Epoch, PublicKey, Slot}; +use types::{AttestationDuty, Epoch, PublicKey, Slot}; -/// The type of work a validator is required to do in a given slot. +/// When work needs to be performed by a validator, this type is given back to the main service +/// which indicates all the information that required to process the work. +/// +/// Note: This is calculated per slot, so a validator knows which slot is related to this struct. #[derive(Debug, Clone)] -pub struct WorkType { +pub struct WorkInfo { + /// Validator needs to produce a block. pub produce_block: bool, - pub produce_attestation: bool, + /// Validator needs to produce an attestation. This supplies the required attestation data. + pub attestation_duty: Option, } /// The information required for a validator to propose and attest during some epoch. @@ -23,23 +28,28 @@ pub struct EpochDuty { } impl EpochDuty { - /// Returns `WorkType` if work needs to be done in the supplied `slot` - pub fn is_work_slot(&self, slot: Slot) -> Option { + /// Returns `WorkInfo` if work needs to be done in the supplied `slot` + pub fn is_work_slot(&self, slot: Slot) -> Option { // if validator is required to produce a slot return true let produce_block = match self.block_production_slot { Some(s) if s == slot => true, _ => false, }; - let mut produce_attestation = false; + // if the validator is required to attest to a shard, create the data + let mut attestation_duty = None; if self.attestation_slot == slot { - produce_attestation = true; + attestation_duty = Some(AttestationDuty { + slot, + shard: self.attestation_shard, + committee_index: self.committee_index as usize, + }); } - if produce_block | produce_attestation { - return Some(WorkType { + if produce_block | attestation_duty.is_some() { + return Some(WorkInfo { produce_block, - produce_attestation, + attestation_duty, }); } None @@ -89,7 +99,7 @@ impl EpochDutiesMap { &self, slot: Slot, pubkey: &PublicKey, - ) -> Result, EpochDutiesMapError> { + ) -> Result, EpochDutiesMapError> { let epoch = slot.epoch(self.slots_per_epoch); let epoch_duties = self diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 94b845083..51470827c 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -6,7 +6,7 @@ mod grpc; mod traits; use self::epoch_duties::{EpochDuties, EpochDutiesMapError}; -pub use self::epoch_duties::{EpochDutiesMap, WorkType}; +pub use self::epoch_duties::{EpochDutiesMap, WorkInfo}; use self::traits::{BeaconNode, BeaconNodeError}; use futures::Async; use slog::{debug, error, info}; @@ -85,10 +85,10 @@ impl DutiesManager { Ok(Async::Ready(())) } - /// Returns a list of (Public, WorkType) indicating all the validators that have work to perform + /// Returns a list of (Public, WorkInfo) indicating all the validators that have work to perform /// this slot. - pub fn get_current_work(&self, slot: Slot) -> Option> { - let mut current_work: Vec<(PublicKey, WorkType)> = Vec::new(); + pub fn get_current_work(&self, slot: Slot) -> Option> { + let mut current_work: Vec<(PublicKey, WorkInfo)> = Vec::new(); // if the map is poisoned, return None let duties = self.duties_map.read().ok()?; diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 07d88d344..f62ade97e 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -272,7 +272,10 @@ impl Service { if work_type.produce_block { // TODO: Produce a beacon block in a new thread } - if work_type.produce_attestation { + if work_type.attestation_duty.is_some() { + // available AttestationDuty info + let attestation_duty = + work_type.attestation_duty.expect("Cannot be None"); //TODO: Produce an attestation in a new thread } } From 4caaf82892378d05c1c45d9f166a65729c08c4d8 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Thu, 28 Mar 2019 13:14:41 +1100 Subject: [PATCH 91/97] Correct validator get duties RPC server logic --- beacon_node/rpc/src/validator.rs | 133 +++++++++++++++++++------------ validator_client/src/service.rs | 29 ------- 2 files changed, 80 insertions(+), 82 deletions(-) diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index 47886a9df..af902ca73 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -4,9 +4,10 @@ use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; use protos::services::{ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty}; use protos::services_grpc::ValidatorService; -use slog::{debug, Logger}; +use slog::{debug, warn, Logger}; use ssz::Decodable; use std::sync::Arc; +use types::{Epoch, RelativeEpoch}; #[derive(Clone)] pub struct ValidatorServiceInstance { @@ -28,23 +29,47 @@ impl ValidatorService for ValidatorServiceInstance { let validators = req.get_validators(); debug!(self.log, "RPC request"; "endpoint" => "GetValidatorDuties", "epoch" => req.get_epoch()); - let epoch = req.get_epoch(); + let epoch = Epoch::from(req.get_epoch()); let mut resp = GetDutiesResponse::new(); let resp_validators = resp.mut_active_validators(); let spec = self.chain.get_spec(); let state = self.chain.get_state(); - //TODO: Decide whether to rebuild the cache - //TODO: Get the active validator indicies - //let active_validator_indices = self.chain.state.read().get_cached_active_validator_indices( - let active_validator_indices = vec![1, 2, 3, 4, 5, 6, 7, 8]; - // TODO: Is this the most efficient? Perhaps we cache this data structure. + let relative_epoch = + match RelativeEpoch::from_epoch(state.slot.epoch(spec.slots_per_epoch), epoch) { + Ok(v) => v, + Err(e) => { + // incorrect epoch + let log_clone = self.log.clone(); + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::FailedPrecondition, + Some(format!("Invalid epoch: {:?}", e)), + )) + .map_err(move |e| warn!(log_clone, "failed to reply {:?}: {:?}", req, e)); + return ctx.spawn(f); + } + }; - // this is an array of validators who are to propose this epoch - // TODO: RelativeEpoch? - //let validator_proposers = [0..spec.slots_per_epoch].iter().map(|slot| state.get_beacon_proposer_index(Slot::from(slot), epoch, &spec)).collect(); - let validator_proposers: Vec = vec![1, 2, 3, 4, 5]; + let validator_proposers: Result, _> = epoch + .slot_iter(spec.slots_per_epoch) + .map(|slot| state.get_beacon_proposer_index(slot, relative_epoch, &spec)) + .collect(); + let validator_proposers = match validator_proposers { + Ok(v) => v, + Err(_) => { + // could not get the validator proposer index + let log_clone = self.log.clone(); + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::InvalidArgument, + Some("Invalid public_key".to_string()), + )) + .map_err(move |e| warn!(log_clone, "failed to reply {:?} : {:?}", req, e)); + return ctx.spawn(f); + } + }; // get the duties for each validator for validator_pk in validators.get_public_keys() { @@ -53,45 +78,65 @@ impl ValidatorService for ValidatorServiceInstance { let public_key = match PublicKey::ssz_decode(validator_pk, 0) { Ok((v, _index)) => v, Err(_) => { + let log_clone = self.log.clone(); let f = sink .fail(RpcStatus::new( RpcStatusCode::InvalidArgument, Some("Invalid public_key".to_string()), )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + .map_err(move |e| warn!(log_clone, "failed to reply {:?}", req)); return ctx.spawn(f); } }; - // is the validator active + // get the validator index let val_index = match state.get_validator_index(&public_key) { - Ok(Some(index)) => { - if active_validator_indices.contains(&index) { - // validator is active, return the index - index - } else { - // validator is inactive, go to the next validator - active_validator.set_none(false); - resp_validators.push(active_validator); - break; - } - } - // validator index is not known, skip it - Ok(_) => { + Ok(Some(index)) => index, + Ok(None) => { + // index not present in registry, set the duties for this key to None + warn!( + self.log, + "RPC requested a public key that is not in the registry: {:?}", public_key + ); active_validator.set_none(false); resp_validators.push(active_validator); break; } // the cache is not built, throw an error - Err(_) => { + Err(e) => { + let log_clone = self.log.clone(); let f = sink .fail(RpcStatus::new( RpcStatusCode::FailedPrecondition, - Some("Beacon state cache is not built".to_string()), + Some(format!("Beacon state error {:?}", e)), )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); + .map_err(move |e| warn!(log_clone, "Failed to reply {:?}: {:?}", req, e)); + return ctx.spawn(f); + } + }; + + // get attestation duties and check if validator is active + let attestation_duties = match state.get_attestation_duties(val_index, &spec) { + Ok(Some(v)) => v, + Ok(_) => { + // validator is inactive, go to the next validator + warn!( + self.log, + "RPC requested an inactive validator key: {:?}", public_key + ); + active_validator.set_none(false); + resp_validators.push(active_validator); + break; + } + // the cache is not built, throw an error + Err(e) => { + let log_clone = self.log.clone(); + let f = sink + .fail(RpcStatus::new( + RpcStatusCode::FailedPrecondition, + Some(format!("Beacon state error {:?}", e)), + )) + .map_err(move |e| warn!(log_clone, "Failed to reply {:?}: {:?}", req, e)); return ctx.spawn(f); } }; @@ -100,33 +145,15 @@ impl ValidatorService for ValidatorServiceInstance { let mut duty = ValidatorDuty::new(); // check if the validator needs to propose a block - if let Some(slot) = validator_proposers - .iter() - .position(|&v| val_index as u64 == v) - { - duty.set_block_production_slot(epoch * spec.slots_per_epoch + slot as u64); + if let Some(slot) = validator_proposers.iter().position(|&v| val_index == v) { + duty.set_block_production_slot( + epoch.start_slot(spec.slots_per_epoch).as_u64() + slot as u64, + ); } else { // no blocks to propose this epoch duty.set_none(false) } - // get attestation duties - let attestation_duties = match state.get_attestation_duties(val_index, &spec) { - Ok(Some(v)) => v, - Ok(_) => unreachable!(), //we've checked the validator index - // the cache is not built, throw an error - Err(_) => { - let f = sink - .fail(RpcStatus::new( - RpcStatusCode::FailedPrecondition, - Some("Beacon state cache is not built".to_string()), - )) - //TODO: Handle error correctly - .map_err(move |e| println!("failed to reply {:?}: {:?}", req, e)); - return ctx.spawn(f); - } - }; - duty.set_committee_index(attestation_duties.committee_index as u64); duty.set_attestation_slot(attestation_duties.slot.as_u64()); duty.set_attestation_shard(attestation_duties.shard); diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index f62ade97e..6c4468414 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -291,35 +291,6 @@ impl Service { /* - for keypair in keypairs { - info!(self.log, "Starting validator services"; "validator" => keypair.pk.concatenated_hex_id()); - - // Spawn a new thread to maintain the validator's `EpochDuties`. - let duties_manager_thread = { - let spec = spec.clone(); - let duties_map = duties_map.clone(); - let slot_clock = self.slot_clock.clone(); - let log = self.log.clone(); - let beacon_node = self.validator_client.clone(); - let pubkey = keypair.pk.clone(); - thread::spawn(move || { - let manager = DutiesManager { - duties_map, - pubkey, - spec, - slot_clock, - beacon_node, - }; - let mut duties_manager_service = DutiesManagerService { - manager, - poll_interval_millis, - log, - }; - - duties_manager_service.run(); - }) - }; - // Spawn a new thread to perform block production for the validator. let producer_thread = { let spec = spec.clone(); From 6f0c0e47c368f1f231786516ebeb4e0ea925deed Mon Sep 17 00:00:00 2001 From: Age Manning Date: Thu, 28 Mar 2019 14:32:02 +1100 Subject: [PATCH 92/97] Update Validator RPC and cache building --- beacon_node/beacon_chain/src/beacon_chain.rs | 5 +++++ beacon_node/rpc/src/validator.rs | 8 ++++---- eth2/types/src/test_utils/testing_beacon_state_builder.rs | 2 +- validator_client/src/config.rs | 3 ++- validator_client/src/main.rs | 4 ++-- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index 6fcb3fde4..27398b6c9 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -348,6 +348,11 @@ where per_slot_processing(&mut *state, &latest_block_header, &self.spec)?; } + state.build_epoch_cache(RelativeEpoch::Previous, &self.spec)?; + state.build_epoch_cache(RelativeEpoch::Current, &self.spec)?; + state.build_epoch_cache(RelativeEpoch::NextWithoutRegistryChange, &self.spec)?; + state.build_epoch_cache(RelativeEpoch::NextWithRegistryChange, &self.spec)?; + state.update_pubkey_cache()?; Ok(()) } diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index af902ca73..e9e10b1d0 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -58,13 +58,13 @@ impl ValidatorService for ValidatorServiceInstance { .collect(); let validator_proposers = match validator_proposers { Ok(v) => v, - Err(_) => { + Err(e) => { // could not get the validator proposer index let log_clone = self.log.clone(); let f = sink .fail(RpcStatus::new( - RpcStatusCode::InvalidArgument, - Some("Invalid public_key".to_string()), + RpcStatusCode::FailedPrecondition, + Some(format!("Could not find beacon proposers: {:?}", e)), )) .map_err(move |e| warn!(log_clone, "failed to reply {:?} : {:?}", req, e)); return ctx.spawn(f); @@ -82,7 +82,7 @@ impl ValidatorService for ValidatorServiceInstance { let f = sink .fail(RpcStatus::new( RpcStatusCode::InvalidArgument, - Some("Invalid public_key".to_string()), + Some("apurple Invalid public_key".to_string()), )) .map_err(move |e| warn!(log_clone, "failed to reply {:?}", req)); return ctx.spawn(f); diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index 3951820d8..79977c277 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -120,7 +120,7 @@ impl TestingBeaconStateBuilder { }) .collect(); - let genesis_time = 1553647464; // arbitrary + let genesis_time = 1553740824; // arbitrary let mut state = BeaconState::genesis( genesis_time, diff --git a/validator_client/src/config.rs b/validator_client/src/config.rs index 78900374a..3d426e8c7 100644 --- a/validator_client/src/config.rs +++ b/validator_client/src/config.rs @@ -1,6 +1,6 @@ -use clap::ArgMatches; use bincode; use bls::Keypair; +use clap::ArgMatches; use slog::{debug, error, info}; use std::fs; use std::fs::File; @@ -67,6 +67,7 @@ impl Config { config.spec = match spec_str { "foundation" => ChainSpec::foundation(), "few_validators" => ChainSpec::few_validators(), + "lighthouse_testnet" => ChainSpec::lighthouse_testnet(), // Should be impossible due to clap's `possible_values(..)` function. _ => unreachable!(), }; diff --git a/validator_client/src/main.rs b/validator_client/src/main.rs index 84d0cbff7..d044030fe 100644 --- a/validator_client/src/main.rs +++ b/validator_client/src/main.rs @@ -43,8 +43,8 @@ fn main() { .short("s") .help("Configuration of Beacon Chain") .takes_value(true) - .possible_values(&["foundation", "few_validators"]) - .default_value("foundation"), + .possible_values(&["foundation", "few_validators", "lighthouse_testnet"]) + .default_value("lighthouse_testnet"), ) .get_matches(); From cc4ccd4017c0e85bdbfed08fc92454da6b110285 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Thu, 28 Mar 2019 17:16:43 +1100 Subject: [PATCH 93/97] Corrects read/write race condition --- beacon_node/rpc/src/validator.rs | 6 +- validator_client/src/duties/grpc.rs | 5 ++ validator_client/src/duties/mod.rs | 23 ++++--- validator_client/src/service.rs | 95 +++++++++++++++-------------- 4 files changed, 72 insertions(+), 57 deletions(-) diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index e9e10b1d0..c2e10885d 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -4,7 +4,7 @@ use futures::Future; use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink}; use protos::services::{ActiveValidator, GetDutiesRequest, GetDutiesResponse, ValidatorDuty}; use protos::services_grpc::ValidatorService; -use slog::{debug, warn, Logger}; +use slog::{debug, info, warn, Logger}; use ssz::Decodable; use std::sync::Arc; use types::{Epoch, RelativeEpoch}; @@ -72,6 +72,7 @@ impl ValidatorService for ValidatorServiceInstance { }; // get the duties for each validator + dbg!(validators.get_public_keys()); for validator_pk in validators.get_public_keys() { let mut active_validator = ActiveValidator::new(); @@ -82,12 +83,13 @@ impl ValidatorService for ValidatorServiceInstance { let f = sink .fail(RpcStatus::new( RpcStatusCode::InvalidArgument, - Some("apurple Invalid public_key".to_string()), + Some("Invalid public_key".to_string()), )) .map_err(move |e| warn!(log_clone, "failed to reply {:?}", req)); return ctx.spawn(f); } }; + info!(self.log,""; "Public key" => format!("{:?}",public_key)); // get the validator index let val_index = match state.get_validator_index(&public_key) { diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index 0a4b3dffe..a3ec6f52b 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -1,9 +1,11 @@ use super::epoch_duties::{EpochDuties, EpochDuty}; use super::traits::{BeaconNode, BeaconNodeError}; +use grpcio::CallOption; use protos::services::{GetDutiesRequest, Validators}; use protos::services_grpc::ValidatorServiceClient; use ssz::ssz_encode; use std::collections::HashMap; +use std::time::Duration; use types::{Epoch, PublicKey, Slot}; impl BeaconNode for ValidatorServiceClient { @@ -21,6 +23,9 @@ impl BeaconNode for ValidatorServiceClient { validators.set_public_keys(pubkeys.iter().map(|v| ssz_encode(v)).collect()); req.set_validators(validators); + // set a timeout for requests + // let call_opt = CallOption::default().timeout(Duration::from_secs(2)); + // send the request, get the duties reply let reply = self .get_validator_duties(&req) diff --git a/validator_client/src/duties/mod.rs b/validator_client/src/duties/mod.rs index 51470827c..0e962053e 100644 --- a/validator_client/src/duties/mod.rs +++ b/validator_client/src/duties/mod.rs @@ -51,20 +51,23 @@ impl DutiesManager { /// be a wall-clock (e.g., system time, remote server time, etc.). fn update(&self, epoch: Epoch) -> Result { let duties = self.beacon_node.request_duties(epoch, &self.pubkeys)?; - // If these duties were known, check to see if they're updates or identical. - if let Some(known_duties) = self.duties_map.read()?.get(&epoch) { - if *known_duties == duties { - return Ok(UpdateOutcome::NoChange(epoch)); - } else { - //TODO: Duties could be large here. Remove from display and avoid the clone. - self.duties_map.write()?.insert(epoch, duties.clone()); - return Ok(UpdateOutcome::DutiesChanged(epoch, duties)); + { + // If these duties were known, check to see if they're updates or identical. + if let Some(known_duties) = self.duties_map.read()?.get(&epoch) { + if *known_duties == duties { + return Ok(UpdateOutcome::NoChange(epoch)); + } } - } else { + } + if !self.duties_map.read()?.contains_key(&epoch) { //TODO: Remove clone by removing duties from outcome self.duties_map.write()?.insert(epoch, duties.clone()); return Ok(UpdateOutcome::NewDuties(epoch, duties)); - }; + } + // duties have changed + //TODO: Duties could be large here. Remove from display and avoid the clone. + self.duties_map.write()?.insert(epoch, duties.clone()); + return Ok(UpdateOutcome::DutiesChanged(epoch, duties)); } /// A future wrapping around `update()`. This will perform logic based upon the update diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index cd427337c..1cb086b9e 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -195,8 +195,8 @@ impl Service { // TODO: keypairs are randomly generated; they should be loaded from a file or generated. // https://github.com/sigp/lighthouse/issues/160 - let keypairs = Arc::new(vec![Keypair::random()]); - + let keypairs: Arc> = + Arc::new((0..10).into_iter().map(|_| Keypair::random()).collect()); /* build requisite objects to pass to core thread */ // Builds a mapping of Epoch -> Map(PublicKey, EpochDuty) @@ -213,54 +213,59 @@ impl Service { }); // run the core thread - runtime - .block_on(interval.for_each(move |_| { - let log = service.log.clone(); + runtime.block_on( + interval + .for_each(move |_| { + let log = service.log.clone(); - /* get the current slot and epoch */ - let current_slot = match service.slot_clock.present_slot() { - Err(e) => { - error!(log, "SystemTimeError {:?}", e); - return Ok(()); - } - Ok(slot) => slot.expect("Genesis is in the future"), - }; - - let current_epoch = current_slot.epoch(service.slots_per_epoch); - - debug_assert!( - current_slot > service.current_slot, - "The Timer should poll a new slot" - ); - - info!(log, "Processing slot: {}", current_slot.as_u64()); - - /* check for new duties */ - - let cloned_manager = manager.clone(); - tokio::spawn(futures::future::poll_fn(move || { - cloned_manager.run_update(current_epoch.clone(), log.clone()) - })); - - /* execute any specified duties */ - - if let Some(work) = manager.get_current_work(current_slot) { - for (_public_key, work_type) in work { - if work_type.produce_block { - // TODO: Produce a beacon block in a new thread + /* get the current slot and epoch */ + let current_slot = match service.slot_clock.present_slot() { + Err(e) => { + error!(log, "SystemTimeError {:?}", e); + return Ok(()); } - if work_type.attestation_duty.is_some() { - // available AttestationDuty info - let attestation_duty = - work_type.attestation_duty.expect("Cannot be None"); - //TODO: Produce an attestation in a new thread + Ok(slot) => slot.expect("Genesis is in the future"), + }; + + let current_epoch = current_slot.epoch(service.slots_per_epoch); + + debug_assert!( + current_slot > service.current_slot, + "The Timer should poll a new slot" + ); + + info!(log, "Processing slot: {}", current_slot.as_u64()); + + /* check for new duties */ + + let cloned_manager = manager.clone(); + let cloned_log = log.clone(); + // spawn a new thread separate to the runtime + std::thread::spawn(move || { + cloned_manager.run_update(current_epoch.clone(), cloned_log.clone()); + dbg!("Finished thread"); + }); + + /* execute any specified duties */ + + if let Some(work) = manager.get_current_work(current_slot) { + for (_public_key, work_type) in work { + if work_type.produce_block { + // TODO: Produce a beacon block in a new thread + } + if work_type.attestation_duty.is_some() { + // available AttestationDuty info + let attestation_duty = + work_type.attestation_duty.expect("Cannot be None"); + //TODO: Produce an attestation in a new thread + } } } - } - Ok(()) - })) - .map_err(|e| format!("Service thread failed: {:?}", e))?; + Ok(()) + }) + .map_err(|e| format!("Service thread failed: {:?}", e)), + ); // completed a slot process Ok(()) From 2a2660ce620351784370c66d673a1bb5d811c58e Mon Sep 17 00:00:00 2001 From: Age Manning Date: Thu, 28 Mar 2019 17:22:09 +1100 Subject: [PATCH 94/97] Cleanup debug issues, corrects RPC server logic --- beacon_node/rpc/src/validator.rs | 6 ++---- eth2/types/src/test_utils/testing_beacon_state_builder.rs | 2 +- validator_client/src/duties/grpc.rs | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/beacon_node/rpc/src/validator.rs b/beacon_node/rpc/src/validator.rs index c2e10885d..936c95f52 100644 --- a/beacon_node/rpc/src/validator.rs +++ b/beacon_node/rpc/src/validator.rs @@ -72,7 +72,6 @@ impl ValidatorService for ValidatorServiceInstance { }; // get the duties for each validator - dbg!(validators.get_public_keys()); for validator_pk in validators.get_public_keys() { let mut active_validator = ActiveValidator::new(); @@ -89,7 +88,6 @@ impl ValidatorService for ValidatorServiceInstance { return ctx.spawn(f); } }; - info!(self.log,""; "Public key" => format!("{:?}",public_key)); // get the validator index let val_index = match state.get_validator_index(&public_key) { @@ -102,7 +100,7 @@ impl ValidatorService for ValidatorServiceInstance { ); active_validator.set_none(false); resp_validators.push(active_validator); - break; + continue; } // the cache is not built, throw an error Err(e) => { @@ -128,7 +126,7 @@ impl ValidatorService for ValidatorServiceInstance { ); active_validator.set_none(false); resp_validators.push(active_validator); - break; + continue; } // the cache is not built, throw an error Err(e) => { diff --git a/eth2/types/src/test_utils/testing_beacon_state_builder.rs b/eth2/types/src/test_utils/testing_beacon_state_builder.rs index 79977c277..b38e8b527 100644 --- a/eth2/types/src/test_utils/testing_beacon_state_builder.rs +++ b/eth2/types/src/test_utils/testing_beacon_state_builder.rs @@ -120,7 +120,7 @@ impl TestingBeaconStateBuilder { }) .collect(); - let genesis_time = 1553740824; // arbitrary + let genesis_time = 1553753928; // arbitrary let mut state = BeaconState::genesis( genesis_time, diff --git a/validator_client/src/duties/grpc.rs b/validator_client/src/duties/grpc.rs index a3ec6f52b..511ffa34a 100644 --- a/validator_client/src/duties/grpc.rs +++ b/validator_client/src/duties/grpc.rs @@ -36,7 +36,7 @@ impl BeaconNode for ValidatorServiceClient { if !validator_duty.has_duty() { // validator is inactive epoch_duties.insert(pubkeys[index].clone(), None); - break; + continue; } // active validator let active_duty = validator_duty.get_duty(); From 6937da09943f08710e2f4ba56a62dbbf7243d98b Mon Sep 17 00:00:00 2001 From: Luke Anderson Date: Thu, 28 Mar 2019 18:58:00 +1100 Subject: [PATCH 95/97] Added deterministic key generation for testing purposes. --- validator_client/src/service.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index f62ade97e..745fb42b9 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -26,6 +26,7 @@ use tokio::runtime::Builder; use tokio::timer::Interval; use tokio_timer::clock::Clock; use types::{Epoch, Fork, Slot}; +use types::test_utils::generate_deterministic_keypairs; //TODO: This service should be simplified in the future. Can be made more steamlined. @@ -218,7 +219,7 @@ impl Service { // TODO: keypairs are randomly generated; they should be loaded from a file or generated. // https://github.com/sigp/lighthouse/issues/160 - let keypairs = Arc::new(vec![Keypair::random()]); + let keypairs = generate_deterministic_keypairs(8); /* build requisite objects to pass to core thread */ From ca0849edc5f670936c1b8223c9f0a482c527fdf0 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Thu, 28 Mar 2019 19:02:33 +1100 Subject: [PATCH 96/97] Fix cargo fmt error It's a rookie mistake and you hate to see it --- eth2/attester/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/eth2/attester/src/lib.rs b/eth2/attester/src/lib.rs index 065fdc923..270c1e4d7 100644 --- a/eth2/attester/src/lib.rs +++ b/eth2/attester/src/lib.rs @@ -119,8 +119,7 @@ impl Attester Date: Thu, 28 Mar 2019 19:52:36 +1100 Subject: [PATCH 97/97] rustfmt fix. --- validator_client/src/service.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validator_client/src/service.rs b/validator_client/src/service.rs index 178a998fe..83e760855 100644 --- a/validator_client/src/service.rs +++ b/validator_client/src/service.rs @@ -25,8 +25,8 @@ use tokio::prelude::*; use tokio::runtime::Builder; use tokio::timer::Interval; use tokio_timer::clock::Clock; -use types::{Epoch, Fork, Slot}; use types::test_utils::generate_deterministic_keypairs; +use types::{Epoch, Fork, Slot}; //TODO: This service should be simplified in the future. Can be made more steamlined.