From 8b34bc490b60e0534a1a10c0f736070e0ff06d03 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 18 Feb 2019 17:32:13 +1100 Subject: [PATCH 01/14] Add fork-choice yaml tests. --- eth2/fork_choice/Cargo.toml | 2 + eth2/fork_choice/src/lib.rs | 2 + eth2/fork_choice/src/optimised_lmd_ghost.rs | 51 ++-- .../tests/fork_choice_test_vectors.yaml | 21 ++ .../tests/optimised_lmd_ghost_test.rs | 248 ++++++++++++++++++ 5 files changed, 302 insertions(+), 22 deletions(-) create mode 100644 eth2/fork_choice/tests/fork_choice_test_vectors.yaml create mode 100644 eth2/fork_choice/tests/optimised_lmd_ghost_test.rs diff --git a/eth2/fork_choice/Cargo.toml b/eth2/fork_choice/Cargo.toml index 72a653032..2765622d1 100644 --- a/eth2/fork_choice/Cargo.toml +++ b/eth2/fork_choice/Cargo.toml @@ -10,9 +10,11 @@ ssz = { path = "../utils/ssz" } types = { path = "../types" } fast-math = "0.1.1" byteorder = "1.3.1" +log = "0.4.6" [dev-dependencies] yaml-rust = "0.4.2" bls = { path = "../utils/bls" } slot_clock = { path = "../utils/slot_clock" } beacon_chain = { path = "../../beacon_node/beacon_chain" } +env_logger = "0.6.0" diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index c0df820c6..7b97fdc0e 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -41,6 +41,8 @@ extern crate db; extern crate ssz; extern crate types; +#[macro_use] +extern crate log; pub mod longest_chain; pub mod optimised_lmd_ghost; diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/optimised_lmd_ghost.rs index 6b21e39f8..8f538da0a 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/optimised_lmd_ghost.rs @@ -1,23 +1,3 @@ -// Copyright 2019 Sigma Prime Pty Ltd. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the "Software"), -// to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, -// and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - extern crate byteorder; extern crate fast_math; use crate::{ForkChoice, ForkChoiceError}; @@ -108,6 +88,7 @@ where // Note: Votes are weighted by min(balance, MAX_DEPOSIT_AMOUNT) // // FORK_CHOICE_BALANCE_INCREMENT // build a hashmap of block_hash to weighted votes + trace!("FORKCHOICE: Getting the latest votes"); let mut latest_votes: HashMap = HashMap::new(); // gets the current weighted votes let current_state = self @@ -119,6 +100,10 @@ where ¤t_state.validator_registry[..], block_slot.epoch(EPOCH_LENGTH), ); + trace!( + "FORKCHOICE: Active validator indicies: {:?}", + active_validator_indices + ); for index in active_validator_indices { let balance = @@ -130,7 +115,7 @@ where } } } - + trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); Ok(latest_votes) } @@ -212,6 +197,7 @@ where // Finds the best child, splitting children into a binary tree, based on their hashes fn choose_best_child(&self, votes: &HashMap) -> Option { + println!("Votes: {:?}", votes); let mut bitmask = 0; for bit in (0..=255).rev() { let mut zero_votes = 0; @@ -298,12 +284,21 @@ impl ForkChoice for OptimisedLMDGhost { ) -> Result<(), ForkChoiceError> { // simply add the attestation to the latest_attestation_target if the block_height is // larger + trace!( + "FORKCHOICE: Adding attestation of validator: {:?} for block: {:?}", + validator_index, + target_block_root + ); let attestation_target = self .latest_attestation_targets .entry(validator_index) .or_insert_with(|| *target_block_root); // if we already have a value if attestation_target != target_block_root { + trace!( + "FORKCHOICE: Old attestation found: {:?}", + attestation_target + ); // get the height of the target block let block_height = self .block_store @@ -319,8 +314,11 @@ impl ForkChoice for OptimisedLMDGhost { .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))? .slot() .height(Slot::from(GENESIS_SLOT)); + trace!("FORKCHOICE: Old block height: {:?}", past_block_height); + trace!("FORKCHOICE: New block height: {:?}", block_height); // update the attestation only if the new target is higher if past_block_height < block_height { + trace!("FORKCHOICE: Updating old attestation"); *attestation_target = *target_block_root; } } @@ -329,6 +327,7 @@ impl ForkChoice for OptimisedLMDGhost { /// Perform lmd_ghost on the current chain to find the head. fn find_head(&mut self, justified_block_start: &Hash256) -> Result { + trace!("Starting optimised fork choice"); let block = self .block_store .get_deserialized(&justified_block_start)? @@ -344,6 +343,7 @@ impl ForkChoice for OptimisedLMDGhost { // remove any votes that don't relate to our current head. latest_votes.retain(|hash, _| self.get_ancestor(*hash, block_height) == Some(current_head)); + trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); // begin searching for the head loop { @@ -368,13 +368,19 @@ impl ForkChoice for OptimisedLMDGhost { step /= 2; } if step > 0 { + trace!("FORKCHOICE: Found clear winner in log lookup"); } // if our skip lookup failed and we only have one child, progress to that child else if children.len() == 1 { current_head = children[0]; + trace!( + "FORKCHOICE: Lookup failed, only one child, proceeding to child: {}", + current_head + ); } // we need to find the best child path to progress down. else { + trace!("FORKCHOICE: Searching for best child"); let mut child_votes = HashMap::new(); for (voted_hash, vote) in latest_votes.iter() { // if the latest votes correspond to a child @@ -383,14 +389,15 @@ impl ForkChoice for OptimisedLMDGhost { *child_votes.entry(child).or_insert_with(|| 0) += vote; } } + println!("Child votes: {:?}", child_votes); // given the votes on the children, find the best child current_head = self .choose_best_child(&child_votes) .ok_or(ForkChoiceError::CannotFindBestChild)?; + trace!("FORKCHOICE: Best child found: {}", current_head); } // No head was found, re-iterate - // update the block height for the next iteration let block_height = self .block_store diff --git a/eth2/fork_choice/tests/fork_choice_test_vectors.yaml b/eth2/fork_choice/tests/fork_choice_test_vectors.yaml new file mode 100644 index 000000000..5a8869e8b --- /dev/null +++ b/eth2/fork_choice/tests/fork_choice_test_vectors.yaml @@ -0,0 +1,21 @@ +title: Fork-choice Tests +summary: A collection of abstract fork-choice tests. +test_suite: Fork-Choice + +test_cases: +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b1' + - id: 'b3' + parent: 'b1' + weights: + - b0: 0 + - b1: 0 + - b2: 5 + - b3: 10 + heads: + - id: 'b3' diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs b/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs new file mode 100644 index 000000000..ac0b6888c --- /dev/null +++ b/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs @@ -0,0 +1,248 @@ +// Tests the optimised LMD Ghost Algorithm + +extern crate beacon_chain; +extern crate bls; +extern crate db; +extern crate env_logger; +extern crate fork_choice; +extern crate log; +extern crate slot_clock; +extern crate types; +extern crate yaml_rust; + +pub use beacon_chain::BeaconChain; +use bls::{PublicKey, Signature}; +use db::stores::{BeaconBlockStore, BeaconStateStore}; +use db::MemoryDB; +use env_logger::{Builder, Env}; +use fork_choice::{ForkChoice, ForkChoiceError, OptimisedLMDGhost}; +use ssz::ssz_encode; +use std::collections::HashMap; +use std::sync::Arc; +use std::{fs::File, io::prelude::*, path::PathBuf, str::FromStr}; +use types::test_utils::{SeedableRng, TestRandom, XorShiftRng}; +use types::validator_registry::get_active_validator_indices; +use types::{ + BeaconBlock, BeaconBlockBody, BeaconState, ChainSpec, Deposit, DepositData, DepositInput, + Eth1Data, Hash256, Slot, Validator, +}; +use yaml_rust::yaml; + +// initialise a single validator and state. All blocks will reference this state root. +fn setup_inital_state( + no_validators: usize, +) -> (impl ForkChoice, Arc>, Hash256) { + let zero_hash = Hash256::zero(); + + let db = Arc::new(MemoryDB::open()); + let block_store = Arc::new(BeaconBlockStore::new(db.clone())); + let state_store = Arc::new(BeaconStateStore::new(db.clone())); + + // the fork choice instantiation + let optimised_lmd_ghost = OptimisedLMDGhost::new(block_store.clone(), state_store.clone()); + + // misc vars for setting up the state + let genesis_time = 1_550_381_159; + + let latest_eth1_data = Eth1Data { + deposit_root: zero_hash.clone(), + block_hash: zero_hash.clone(), + }; + + let initial_validator_deposits = vec![]; + + /* + (0..no_validators) + .map(|_| Deposit { + branch: vec![], + index: 0, + deposit_data: DepositData { + amount: 32_000_000_000, // 32 ETH (in Gwei) + timestamp: genesis_time - 1, + deposit_input: DepositInput { + pubkey: PublicKey::default(), + withdrawal_credentials: zero_hash.clone(), + proof_of_possession: Signature::empty_signature(), + }, + }, + }) + .collect(); + */ + + let spec = ChainSpec::foundation(); + + // create the state + let mut state = BeaconState::genesis( + genesis_time, + initial_validator_deposits, + latest_eth1_data, + &spec, + ) + .unwrap(); + + // activate the validators + for _ in 0..no_validators { + let validator = Validator { + pubkey: PublicKey::default(), + withdrawal_credentials: zero_hash, + activation_epoch: spec.far_future_epoch, + exit_epoch: spec.far_future_epoch, + withdrawal_epoch: spec.far_future_epoch, + penalized_epoch: spec.far_future_epoch, + status_flags: None, + }; + state.validator_registry.push(validator); + state.validator_balances.push(32_000_000_000); + } + + let state_root = state.canonical_root(); + state_store + .put(&state_root, &ssz_encode(&state)[..]) + .unwrap(); + + println!( + "Active: {:?}", + get_active_validator_indices( + &state.validator_registry, + Slot::from(5u64).epoch(spec.EPOCH_LENGTH) + ) + ); + // return initialised vars + (optimised_lmd_ghost, block_store, state_root) +} + +// YAML test vectors +#[test] +fn test_optimised_lmd_ghost() { + // set up logging + Builder::from_env(Env::default().default_filter_or("trace")).init(); + + // load the yaml + let mut file = { + let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + file_path_buf.push("tests/fork_choice_test_vectors.yaml"); + + File::open(file_path_buf).unwrap() + }; + + let mut yaml_str = String::new(); + file.read_to_string(&mut yaml_str).unwrap(); + let docs = yaml::YamlLoader::load_from_str(&yaml_str).unwrap(); + let doc = &docs[0]; + let test_cases = doc["test_cases"].as_vec().unwrap(); + + // set up the test + let total_emulated_validators = 20; // the number of validators used to give weights. + let (mut fork_choice, block_store, state_root) = setup_inital_state(total_emulated_validators); + + // keep a hashmap of block_id's to block_hashes (random hashes to abstract block_id) + let mut block_id_map: HashMap = HashMap::new(); + // keep a list of hash to slot + let mut block_slot: HashMap = HashMap::new(); + + // default vars + let zero_hash = Hash256::zero(); + let eth1_data = Eth1Data { + deposit_root: zero_hash.clone(), + block_hash: zero_hash.clone(), + }; + let randao_reveal = Signature::empty_signature(); + let signature = Signature::empty_signature(); + let body = BeaconBlockBody { + proposer_slashings: vec![], + attester_slashings: vec![], + attestations: vec![], + deposits: vec![], + exits: vec![], + }; + + // process the tests + for test_case in test_cases { + // assume the block tree is given to us in order. + for block in test_case["blocks"].clone().into_vec().unwrap() { + let block_id = block["id"].as_str().unwrap().to_string(); + let parent_id = block["parent"].as_str().unwrap(); + + // default params for genesis + let mut block_hash = zero_hash.clone(); + let mut slot = Slot::from(0u64); + let mut parent_root = zero_hash; + + // set the slot and parent based off the YAML. Start with genesis; + // if not the genesis, update slot and parent + if parent_id != block_id { + // generate a random hash for the block_hash + block_hash = Hash256::random(); + // find the parent hash + parent_root = *block_id_map + .get(parent_id) + .expect(&format!("Parent not found: {}", parent_id)); + slot = *(block_slot + .get(&parent_root) + .expect("Parent should have a slot number")) + + 1; + } + + block_id_map.insert(block_id.clone(), block_hash.clone()); + + // update slot mapping + block_slot.insert(block_hash, slot); + + // build the BeaconBlock + let beacon_block = BeaconBlock { + slot, + parent_root, + state_root: state_root.clone(), + randao_reveal: randao_reveal.clone(), + eth1_data: eth1_data.clone(), + signature: signature.clone(), + body: body.clone(), + }; + + // Store the block and state. + block_store + .put(&block_hash, &ssz_encode(&beacon_block)[..]) + .unwrap(); + + // run add block for fork choice if not genesis + if parent_id != block_id { + fork_choice.add_block(&beacon_block, &block_hash).unwrap(); + } + } + + // add the weights (attestations) + let mut current_validator = 0; + for id_map in test_case["weights"].clone().into_vec().unwrap() { + // get the block id and weights + for (map_id, map_weight) in id_map.as_hash().unwrap().iter() { + let id = map_id.as_str().unwrap(); + let block_root = block_id_map + .get(id) + .expect(&format!("Cannot find block id: {} in weights", id)); + let weight = map_weight.as_i64().unwrap(); + // we assume a validator has a value 1 and add an attestation for to achieve the + // correct weight + for _ in 0..weight { + assert!(current_validator <= total_emulated_validators); + fork_choice + .add_attestation(current_validator as u64, &block_root) + .unwrap(); + current_validator += 1; + } + } + } + + // everything is set up, run the fork choice, using genesis as the head + println!("Running fork choice"); + let head = fork_choice.find_head(&zero_hash).unwrap(); + + let mut found_id = None; + for (id, block_hash) in block_id_map.iter() { + if *block_hash == head { + found_id = Some(id); + } + } + + println!("Head Block ID: {:?}", found_id); + } +} From 6e6d45197894481a3cdc5f7f211c93c60c888503 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 18 Feb 2019 17:42:07 +1100 Subject: [PATCH 02/14] Updates optimised ghost to use chainspec for consts. --- eth2/fork_choice/src/lib.rs | 10 +++- eth2/fork_choice/src/optimised_lmd_ghost.rs | 62 ++++++++++++--------- 2 files changed, 44 insertions(+), 28 deletions(-) diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index 7b97fdc0e..11da12304 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -50,7 +50,7 @@ pub mod slow_lmd_ghost; use db::stores::BeaconBlockAtSlotError; use db::DBError; -use types::{BeaconBlock, Hash256}; +use types::{BeaconBlock, ChainSpec, Hash256}; pub use longest_chain::LongestChain; pub use optimised_lmd_ghost::OptimisedLMDGhost; @@ -65,6 +65,7 @@ pub trait ForkChoice: Send + Sync { &mut self, block: &BeaconBlock, block_hash: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError>; /// Called when an attestation has been added. Allows generic attestation-level data structures to be built for a given fork choice. // This can be generalised to a full attestation if required later. @@ -72,10 +73,15 @@ pub trait ForkChoice: Send + Sync { &mut self, validator_index: u64, target_block_hash: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError>; /// The fork-choice algorithm to find the current canonical head of the chain. // TODO: Remove the justified_start_block parameter and make it internal - fn find_head(&mut self, justified_start_block: &Hash256) -> Result; + fn find_head( + &mut self, + justified_start_block: &Hash256, + spec: &ChainSpec, + ) -> Result; } /// Possible fork choice errors that can occur. diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/optimised_lmd_ghost.rs index 8f538da0a..b88aa09bd 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/optimised_lmd_ghost.rs @@ -11,18 +11,12 @@ use std::collections::HashMap; use std::sync::Arc; use types::{ readers::BeaconBlockReader, validator_registry::get_active_validator_indices, BeaconBlock, - Hash256, Slot, SlotHeight, + ChainSpec, Hash256, Slot, SlotHeight, }; //TODO: Pruning - Children //TODO: Handle Syncing -//TODO: Sort out global constants -const GENESIS_SLOT: u64 = 0; -const FORK_CHOICE_BALANCE_INCREMENT: u64 = 1e9 as u64; -const MAX_DEPOSIT_AMOUNT: u64 = 32e9 as u64; -const EPOCH_LENGTH: u64 = 64; - /// The optimised LMD-GHOST fork choice rule. /// NOTE: This uses u32 to represent difference between block heights. Thus this is only /// applicable for block height differences in the range of a u32. @@ -82,7 +76,8 @@ where pub fn get_latest_votes( &self, state_root: &Hash256, - block_slot: Slot, + block_slot: &Slot, + spec: &ChainSpec, ) -> Result, ForkChoiceError> { // get latest votes // Note: Votes are weighted by min(balance, MAX_DEPOSIT_AMOUNT) // @@ -98,7 +93,7 @@ where let active_validator_indices = get_active_validator_indices( ¤t_state.validator_registry[..], - block_slot.epoch(EPOCH_LENGTH), + block_slot.epoch(spec.epoch_length), ); trace!( "FORKCHOICE: Active validator indicies: {:?}", @@ -106,9 +101,10 @@ where ); for index in active_validator_indices { - let balance = - std::cmp::min(current_state.validator_balances[index], MAX_DEPOSIT_AMOUNT) - / FORK_CHOICE_BALANCE_INCREMENT; + let balance = std::cmp::min( + current_state.validator_balances[index], + spec.max_deposit_amount, + ) / spec.fork_choice_balance_increment; if balance > 0 { if let Some(target) = self.latest_attestation_targets.get(&(index as u64)) { *latest_votes.entry(*target).or_insert_with(|| 0) += balance; @@ -120,7 +116,12 @@ where } /// Gets the ancestor at a given height `at_height` of a block specified by `block_hash`. - fn get_ancestor(&mut self, block_hash: Hash256, at_height: SlotHeight) -> Option { + fn get_ancestor( + &mut self, + block_hash: Hash256, + at_height: SlotHeight, + spec: &ChainSpec, + ) -> Option { // return None if we can't get the block from the db. let block_height = { let block_slot = self @@ -130,7 +131,7 @@ where .expect("Should have returned already if None") .slot; - block_slot.height(Slot::from(GENESIS_SLOT)) + block_slot.height(Slot::from(spec.genesis_slot)) }; // verify we haven't exceeded the block height @@ -155,7 +156,7 @@ where .get(&block_hash) //TODO: Panic if we can't lookup and fork choice fails .expect("All blocks should be added to the ancestor log lookup table"); - self.get_ancestor(*ancestor_lookup, at_height) + self.get_ancestor(*ancestor_lookup, at_height, &spec) } { // add the result to the cache self.cache.insert(cache_key, ancestor); @@ -170,6 +171,7 @@ where &mut self, latest_votes: &HashMap, block_height: SlotHeight, + spec: &ChainSpec, ) -> Option { // map of vote counts for every hash at this height let mut current_votes: HashMap = HashMap::new(); @@ -178,7 +180,7 @@ where // loop through the latest votes and count all votes // these have already been weighted by balance for (hash, votes) in latest_votes.iter() { - if let Some(ancestor) = self.get_ancestor(*hash, block_height) { + if let Some(ancestor) = self.get_ancestor(*hash, block_height, spec) { let current_vote_value = current_votes.get(&ancestor).unwrap_or_else(|| &0); current_votes.insert(ancestor, current_vote_value + *votes); total_vote_count += votes; @@ -244,6 +246,7 @@ impl ForkChoice for OptimisedLMDGhost { &mut self, block: &BeaconBlock, block_hash: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError> { // get the height of the parent let parent_height = self @@ -251,7 +254,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&block.parent_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(block.parent_root))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); let parent_hash = &block.parent_root; @@ -281,6 +284,7 @@ impl ForkChoice for OptimisedLMDGhost { &mut self, validator_index: u64, target_block_root: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError> { // simply add the attestation to the latest_attestation_target if the block_height is // larger @@ -305,7 +309,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&target_block_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*target_block_root))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); // get the height of the past target block let past_block_height = self @@ -313,7 +317,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&attestation_target)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); trace!("FORKCHOICE: Old block height: {:?}", past_block_height); trace!("FORKCHOICE: New block height: {:?}", block_height); // update the attestation only if the new target is higher @@ -326,7 +330,11 @@ impl ForkChoice for OptimisedLMDGhost { } /// Perform lmd_ghost on the current chain to find the head. - fn find_head(&mut self, justified_block_start: &Hash256) -> Result { + fn find_head( + &mut self, + justified_block_start: &Hash256, + spec: &ChainSpec, + ) -> Result { trace!("Starting optimised fork choice"); let block = self .block_store @@ -334,7 +342,7 @@ impl ForkChoice for OptimisedLMDGhost { .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*justified_block_start))?; let block_slot = block.slot(); - let block_height = block_slot.height(Slot::from(GENESIS_SLOT)); + let block_height = block_slot.height(Slot::from(spec.genesis_slot)); let state_root = block.state_root(); let mut current_head = *justified_block_start; @@ -342,7 +350,8 @@ impl ForkChoice for OptimisedLMDGhost { let mut latest_votes = self.get_latest_votes(&state_root, block_slot)?; // remove any votes that don't relate to our current head. - latest_votes.retain(|hash, _| self.get_ancestor(*hash, block_height) == Some(current_head)); + latest_votes + .retain(|hash, _| self.get_ancestor(*hash, block_height, spec) == Some(current_head)); trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); // begin searching for the head @@ -384,7 +393,7 @@ impl ForkChoice for OptimisedLMDGhost { let mut child_votes = HashMap::new(); for (voted_hash, vote) in latest_votes.iter() { // if the latest votes correspond to a child - if let Some(child) = self.get_ancestor(*voted_hash, block_height + 1) { + if let Some(child) = self.get_ancestor(*voted_hash, block_height + 1, spec) { // add up the votes for each child *child_votes.entry(child).or_insert_with(|| 0) += vote; } @@ -404,12 +413,13 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(¤t_head)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*justified_block_start))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); // prune the latest votes for votes that are not part of current chosen chain // more specifically, only keep votes that have head as an ancestor - latest_votes - .retain(|hash, _| self.get_ancestor(*hash, block_height) == Some(current_head)); + latest_votes.retain(|hash, _| { + self.get_ancestor(*hash, block_height, spec) == Some(current_head) + }); } } } From 4eddb47fd059e887de56b7941976eb7721bfc9e7 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Mon, 18 Feb 2019 17:49:05 +1100 Subject: [PATCH 03/14] Updates all fork-choices to use ChainSpec for consts. --- beacon_node/beacon_chain/src/beacon_chain.rs | 10 ++++- eth2/fork_choice/src/longest_chain.rs | 12 ++++-- eth2/fork_choice/src/optimised_lmd_ghost.rs | 3 +- eth2/fork_choice/src/slow_lmd_ghost.rs | 43 ++++++++++++-------- 4 files changed, 44 insertions(+), 24 deletions(-) diff --git a/beacon_node/beacon_chain/src/beacon_chain.rs b/beacon_node/beacon_chain/src/beacon_chain.rs index b2d041654..40e30b2fb 100644 --- a/beacon_node/beacon_chain/src/beacon_chain.rs +++ b/beacon_node/beacon_chain/src/beacon_chain.rs @@ -357,6 +357,7 @@ where self.fork_choice.write().add_attestation( free_attestation.validator_index, &free_attestation.data.beacon_block_root, + &self.spec, )?; Ok(aggregation_outcome) } @@ -486,7 +487,9 @@ where self.state_store.put(&state_root, &ssz_encode(&state)[..])?; // run the fork_choice add_block logic - self.fork_choice.write().add_block(&block, &block_root)?; + self.fork_choice + .write() + .add_block(&block, &block_root, &self.spec)?; // If the parent block was the parent_block, automatically update the canonical head. // @@ -575,7 +578,10 @@ where pub fn fork_choice(&self) -> Result<(), Error> { let present_head = self.finalized_head().beacon_block_root; - let new_head = self.fork_choice.write().find_head(&present_head)?; + let new_head = self + .fork_choice + .write() + .find_head(&present_head, &self.spec)?; if new_head != present_head { let block = self diff --git a/eth2/fork_choice/src/longest_chain.rs b/eth2/fork_choice/src/longest_chain.rs index 8056c11f2..ea2cc33bb 100644 --- a/eth2/fork_choice/src/longest_chain.rs +++ b/eth2/fork_choice/src/longest_chain.rs @@ -1,7 +1,7 @@ use crate::{ForkChoice, ForkChoiceError}; use db::{stores::BeaconBlockStore, ClientDB}; use std::sync::Arc; -use types::{BeaconBlock, Hash256, Slot}; +use types::{BeaconBlock, ChainSpec, Hash256, Slot}; pub struct LongestChain where @@ -30,6 +30,7 @@ impl ForkChoice for LongestChain { &mut self, block: &BeaconBlock, block_hash: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError> { // add the block hash to head_block_hashes removing the parent if it exists self.head_block_hashes @@ -38,12 +39,17 @@ impl ForkChoice for LongestChain { Ok(()) } - fn add_attestation(&mut self, _: u64, _: &Hash256) -> Result<(), ForkChoiceError> { + fn add_attestation( + &mut self, + _: u64, + _: &Hash256, + _: &ChainSpec, + ) -> Result<(), ForkChoiceError> { // do nothing Ok(()) } - fn find_head(&mut self, _: &Hash256) -> Result { + fn find_head(&mut self, _: &Hash256, _: &ChainSpec) -> Result { let mut head_blocks: Vec<(usize, BeaconBlock)> = vec![]; /* * Load all the head_block hashes from the DB as SszBeaconBlocks. diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/optimised_lmd_ghost.rs index b88aa09bd..e60af4e66 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/optimised_lmd_ghost.rs @@ -347,7 +347,7 @@ impl ForkChoice for OptimisedLMDGhost { let mut current_head = *justified_block_start; - let mut latest_votes = self.get_latest_votes(&state_root, block_slot)?; + let mut latest_votes = self.get_latest_votes(&state_root, &block_slot, spec)?; // remove any votes that don't relate to our current head. latest_votes @@ -370,6 +370,7 @@ impl ForkChoice for OptimisedLMDGhost { if let Some(clear_winner) = self.get_clear_winner( &latest_votes, block_height - (block_height % u64::from(step)) + u64::from(step), + spec, ) { current_head = clear_winner; break; diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index 3184150fd..81bc5d628 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -29,17 +29,11 @@ use std::collections::HashMap; use std::sync::Arc; use types::{ readers::BeaconBlockReader, validator_registry::get_active_validator_indices, BeaconBlock, - Hash256, Slot, + ChainSpec, Hash256, Slot, }; //TODO: Pruning and syncing -//TODO: Sort out global constants -const GENESIS_SLOT: u64 = 0; -const FORK_CHOICE_BALANCE_INCREMENT: u64 = 1e9 as u64; -const MAX_DEPOSIT_AMOUNT: u64 = 32e9 as u64; -const EPOCH_LENGTH: u64 = 64; - pub struct SlowLMDGhost { /// The latest attestation targets as a map of validator index to block hash. //TODO: Could this be a fixed size vec @@ -70,12 +64,14 @@ where pub fn get_latest_votes( &self, state_root: &Hash256, - block_slot: Slot, + block_slot: &Slot, + spec: &ChainSpec, ) -> Result, ForkChoiceError> { // get latest votes // Note: Votes are weighted by min(balance, MAX_DEPOSIT_AMOUNT) // // FORK_CHOICE_BALANCE_INCREMENT // build a hashmap of block_hash to weighted votes + trace!("FORKCHOICE: Getting the latest votes"); let mut latest_votes: HashMap = HashMap::new(); // gets the current weighted votes let current_state = self @@ -84,21 +80,26 @@ where .ok_or_else(|| ForkChoiceError::MissingBeaconState(*state_root))?; let active_validator_indices = get_active_validator_indices( - ¤t_state.validator_registry, - block_slot.epoch(EPOCH_LENGTH), + ¤t_state.validator_registry[..], + block_slot.epoch(spec.epoch_length), + ); + trace!( + "FORKCHOICE: Active validator indicies: {:?}", + active_validator_indices ); for index in active_validator_indices { - let balance = - std::cmp::min(current_state.validator_balances[index], MAX_DEPOSIT_AMOUNT) - / FORK_CHOICE_BALANCE_INCREMENT; + let balance = std::cmp::min( + current_state.validator_balances[index], + spec.max_deposit_amount, + ) / spec.fork_choice_balance_increment; if balance > 0 { if let Some(target) = self.latest_attestation_targets.get(&(index as u64)) { *latest_votes.entry(*target).or_insert_with(|| 0) += balance; } } } - + trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); Ok(latest_votes) } @@ -136,6 +137,7 @@ impl ForkChoice for SlowLMDGhost { &mut self, block: &BeaconBlock, block_hash: &Hash256, + _: &ChainSpec, ) -> Result<(), ForkChoiceError> { // build the children hashmap // add the new block to the children of parent @@ -153,6 +155,7 @@ impl ForkChoice for SlowLMDGhost { &mut self, validator_index: u64, target_block_root: &Hash256, + spec: &ChainSpec, ) -> Result<(), ForkChoiceError> { // simply add the attestation to the latest_attestation_target if the block_height is // larger @@ -168,7 +171,7 @@ impl ForkChoice for SlowLMDGhost { .get_deserialized(&target_block_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*target_block_root))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); // get the height of the past target block let past_block_height = self @@ -176,7 +179,7 @@ impl ForkChoice for SlowLMDGhost { .get_deserialized(&attestation_target)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))? .slot() - .height(Slot::from(GENESIS_SLOT)); + .height(Slot::from(spec.genesis_slot)); // update the attestation only if the new target is higher if past_block_height < block_height { *attestation_target = *target_block_root; @@ -186,7 +189,11 @@ impl ForkChoice for SlowLMDGhost { } /// A very inefficient implementation of LMD ghost. - fn find_head(&mut self, justified_block_start: &Hash256) -> Result { + fn find_head( + &mut self, + justified_block_start: &Hash256, + spec: &ChainSpec, + ) -> Result { let start = self .block_store .get_deserialized(&justified_block_start)? @@ -194,7 +201,7 @@ impl ForkChoice for SlowLMDGhost { let start_state_root = start.state_root(); - let latest_votes = self.get_latest_votes(&start_state_root, start.slot())?; + let latest_votes = self.get_latest_votes(&start_state_root, &start.slot(), spec)?; let mut head_hash = Hash256::zero(); From 8baae0e02ee79bdb79190a4d9a31ea16af27ae64 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 11:58:17 +1100 Subject: [PATCH 04/14] Updates optimised fork choice. - Bug fixes in optimised fork choice. - YAML tests functioning. - Implement Clippy suggestions. - Remove Copywrite notices. --- eth2/fork_choice/Cargo.toml | 2 +- eth2/fork_choice/src/lib.rs | 20 ---- eth2/fork_choice/src/longest_chain.rs | 2 +- eth2/fork_choice/src/optimised_lmd_ghost.rs | 110 ++++++++++-------- eth2/fork_choice/src/slow_lmd_ghost.rs | 30 +---- .../tests/optimised_lmd_ghost_test.rs | 89 ++++++-------- 6 files changed, 104 insertions(+), 149 deletions(-) diff --git a/eth2/fork_choice/Cargo.toml b/eth2/fork_choice/Cargo.toml index 2765622d1..d12f5ae7a 100644 --- a/eth2/fork_choice/Cargo.toml +++ b/eth2/fork_choice/Cargo.toml @@ -9,8 +9,8 @@ db = { path = "../../beacon_node/db" } ssz = { path = "../utils/ssz" } types = { path = "../types" } fast-math = "0.1.1" -byteorder = "1.3.1" log = "0.4.6" +bit-vec = "0.5.0" [dev-dependencies] yaml-rust = "0.4.2" diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index 11da12304..3923fca9b 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -1,23 +1,3 @@ -// Copyright 2019 Sigma Prime Pty Ltd. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the "Software"), -// to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, -// and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - //! This crate stores the various implementations of fork-choice rules that can be used for the //! beacon blockchain. //! diff --git a/eth2/fork_choice/src/longest_chain.rs b/eth2/fork_choice/src/longest_chain.rs index ea2cc33bb..333553c02 100644 --- a/eth2/fork_choice/src/longest_chain.rs +++ b/eth2/fork_choice/src/longest_chain.rs @@ -30,7 +30,7 @@ impl ForkChoice for LongestChain { &mut self, block: &BeaconBlock, block_hash: &Hash256, - spec: &ChainSpec, + _: &ChainSpec, ) -> Result<(), ForkChoiceError> { // add the block hash to head_block_hashes removing the parent if it exists self.head_block_hashes diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/optimised_lmd_ghost.rs index e60af4e66..f211359ea 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/optimised_lmd_ghost.rs @@ -1,7 +1,8 @@ -extern crate byteorder; +extern crate bit_vec; extern crate fast_math; + use crate::{ForkChoice, ForkChoiceError}; -use byteorder::{BigEndian, ByteOrder}; +use bit_vec::BitVec; use db::{ stores::{BeaconBlockStore, BeaconStateStore}, ClientDB, @@ -25,6 +26,9 @@ use types::{ // the comparison. Log2_raw takes 2ns according to the documentation. #[inline] fn log2_int(x: u32) -> u32 { + if x == 0 { + return 0; + } log2_raw(x as f32) as u32 } @@ -76,14 +80,13 @@ where pub fn get_latest_votes( &self, state_root: &Hash256, - block_slot: &Slot, + block_slot: Slot, spec: &ChainSpec, ) -> Result, ForkChoiceError> { // get latest votes // Note: Votes are weighted by min(balance, MAX_DEPOSIT_AMOUNT) // // FORK_CHOICE_BALANCE_INCREMENT // build a hashmap of block_hash to weighted votes - trace!("FORKCHOICE: Getting the latest votes"); let mut latest_votes: HashMap = HashMap::new(); // gets the current weighted votes let current_state = self @@ -95,10 +98,6 @@ where ¤t_state.validator_registry[..], block_slot.epoch(spec.epoch_length), ); - trace!( - "FORKCHOICE: Active validator indicies: {:?}", - active_validator_indices - ); for index in active_validator_indices { let balance = std::cmp::min( @@ -119,7 +118,7 @@ where fn get_ancestor( &mut self, block_hash: Hash256, - at_height: SlotHeight, + target_height: SlotHeight, spec: &ChainSpec, ) -> Option { // return None if we can't get the block from the db. @@ -131,32 +130,31 @@ where .expect("Should have returned already if None") .slot; - block_slot.height(Slot::from(spec.genesis_slot)) + block_slot.height(spec.genesis_slot) }; // verify we haven't exceeded the block height - if at_height >= block_height { - if at_height > block_height { + if target_height >= block_height { + if target_height > block_height { return None; } else { return Some(block_hash); } } // check if the result is stored in our cache - let cache_key = CacheKey::new(&block_hash, at_height.as_u32()); + let cache_key = CacheKey::new(&block_hash, target_height.as_u32()); if let Some(ancestor) = self.cache.get(&cache_key) { return Some(*ancestor); } // not in the cache recursively search for ancestors using a log-lookup - if let Some(ancestor) = { let ancestor_lookup = self.ancestors - [log2_int((block_height - at_height - 1u64).as_u32()) as usize] + [log2_int((block_height - target_height - 1u64).as_u32()) as usize] .get(&block_hash) //TODO: Panic if we can't lookup and fork choice fails .expect("All blocks should be added to the ancestor log lookup table"); - self.get_ancestor(*ancestor_lookup, at_height, &spec) + self.get_ancestor(*ancestor_lookup, target_height, &spec) } { // add the result to the cache self.cache.insert(cache_key, ancestor); @@ -177,6 +175,7 @@ where let mut current_votes: HashMap = HashMap::new(); let mut total_vote_count = 0; + trace!("FORKCHOICE: Clear winner at block height: {}", block_height); // loop through the latest votes and count all votes // these have already been weighted by balance for (hash, votes) in latest_votes.iter() { @@ -199,19 +198,30 @@ where // Finds the best child, splitting children into a binary tree, based on their hashes fn choose_best_child(&self, votes: &HashMap) -> Option { - println!("Votes: {:?}", votes); - let mut bitmask = 0; - for bit in (0..=255).rev() { + if votes.is_empty() { + return None; + } + let mut bitmask: BitVec = BitVec::new(); + // loop through bytes then bits + for bit in 0..256 { let mut zero_votes = 0; let mut one_votes = 0; let mut single_candidate = None; for (candidate, votes) in votes.iter() { - let candidate_uint = BigEndian::read_u32(candidate); - if candidate_uint >> (bit + 1) != bitmask { + let candidate_bit: BitVec = BitVec::from_bytes(&candidate); + + // if the bitmasks don't match + if !bitmask.iter().eq(candidate_bit.iter().take(bit)) { + trace!( + "FORKCHOICE: Child: {} was removed in bit: {} with the bitmask: {:?}", + candidate, + bit, + bitmask + ); continue; } - if (candidate_uint >> bit) % 2 == 0 { + if candidate_bit.get(bit) == Some(false) { zero_votes += votes; } else { one_votes += votes; @@ -223,18 +233,10 @@ where single_candidate = None; } } - bitmask = (bitmask * 2) + { - if one_votes > zero_votes { - 1 - } else { - 0 - } - }; + bitmask.push(one_votes > zero_votes); if let Some(candidate) = single_candidate { return Some(*candidate); } - //TODO Remove this during benchmark after testing - assert!(bit >= 1); } // should never reach here None @@ -254,7 +256,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&block.parent_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(block.parent_root))? .slot() - .height(Slot::from(spec.genesis_slot)); + .height(spec.genesis_slot); let parent_hash = &block.parent_root; @@ -289,7 +291,7 @@ impl ForkChoice for OptimisedLMDGhost { // simply add the attestation to the latest_attestation_target if the block_height is // larger trace!( - "FORKCHOICE: Adding attestation of validator: {:?} for block: {:?}", + "FORKCHOICE: Adding attestation of validator: {:?} for block: {}", validator_index, target_block_root ); @@ -309,7 +311,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&target_block_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*target_block_root))? .slot() - .height(Slot::from(spec.genesis_slot)); + .height(spec.genesis_slot); // get the height of the past target block let past_block_height = self @@ -317,9 +319,7 @@ impl ForkChoice for OptimisedLMDGhost { .get_deserialized(&attestation_target)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))? .slot() - .height(Slot::from(spec.genesis_slot)); - trace!("FORKCHOICE: Old block height: {:?}", past_block_height); - trace!("FORKCHOICE: New block height: {:?}", block_height); + .height(spec.genesis_slot); // update the attestation only if the new target is higher if past_block_height < block_height { trace!("FORKCHOICE: Updating old attestation"); @@ -335,27 +335,34 @@ impl ForkChoice for OptimisedLMDGhost { justified_block_start: &Hash256, spec: &ChainSpec, ) -> Result { - trace!("Starting optimised fork choice"); + debug!( + "Starting optimised fork choice at block: {}", + justified_block_start + ); let block = self .block_store .get_deserialized(&justified_block_start)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*justified_block_start))?; let block_slot = block.slot(); - let block_height = block_slot.height(Slot::from(spec.genesis_slot)); let state_root = block.state_root(); + let mut block_height = block_slot.height(spec.genesis_slot); let mut current_head = *justified_block_start; - let mut latest_votes = self.get_latest_votes(&state_root, &block_slot, spec)?; + let mut latest_votes = self.get_latest_votes(&state_root, block_slot, spec)?; // remove any votes that don't relate to our current head. latest_votes .retain(|hash, _| self.get_ancestor(*hash, block_height, spec) == Some(current_head)); - trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); // begin searching for the head loop { + debug!( + "FORKCHOICE: Iteration for block: {} with vote length: {}", + current_head, + latest_votes.len() + ); // if there are no children, we are done, return the current_head let children = match self.children.get(¤t_head) { Some(children) => children.clone(), @@ -367,6 +374,7 @@ impl ForkChoice for OptimisedLMDGhost { let mut step = power_of_2_below(self.max_known_height.saturating_sub(block_height).as_u32()) / 2; while step > 0 { + trace!("Current Step: {}", step); if let Some(clear_winner) = self.get_clear_winner( &latest_votes, block_height - (block_height % u64::from(step)) + u64::from(step), @@ -399,7 +407,6 @@ impl ForkChoice for OptimisedLMDGhost { *child_votes.entry(child).or_insert_with(|| 0) += vote; } } - println!("Child votes: {:?}", child_votes); // given the votes on the children, find the best child current_head = self .choose_best_child(&child_votes) @@ -407,17 +414,24 @@ impl ForkChoice for OptimisedLMDGhost { trace!("FORKCHOICE: Best child found: {}", current_head); } - // No head was found, re-iterate - // update the block height for the next iteration - let block_height = self + // didn't find head yet, proceed to next iteration + // update block height + block_height = self .block_store .get_deserialized(¤t_head)? - .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*justified_block_start))? + .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(current_head))? .slot() - .height(Slot::from(spec.genesis_slot)); - + .height(spec.genesis_slot); // prune the latest votes for votes that are not part of current chosen chain // more specifically, only keep votes that have head as an ancestor + for hash in latest_votes.keys() { + trace!( + "FORKCHOICE: Ancestor for vote: {} at height: {} is: {:?}", + hash, + block_height, + self.get_ancestor(*hash, block_height, spec) + ); + } latest_votes.retain(|hash, _| { self.get_ancestor(*hash, block_height, spec) == Some(current_head) }); diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index 81bc5d628..7041b1b46 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -1,23 +1,3 @@ -// Copyright 2019 Sigma Prime Pty Ltd. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the "Software"), -// to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, -// and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - extern crate db; use crate::{ForkChoice, ForkChoiceError}; @@ -64,7 +44,7 @@ where pub fn get_latest_votes( &self, state_root: &Hash256, - block_slot: &Slot, + block_slot: Slot, spec: &ChainSpec, ) -> Result, ForkChoiceError> { // get latest votes @@ -122,7 +102,7 @@ where let (root_at_slot, _) = self .block_store .block_at_slot(&block_root, block_slot)? - .ok_or(ForkChoiceError::MissingBeaconBlock(*block_root))?; + .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*block_root))?; if root_at_slot == *target_hash { count += votes; } @@ -171,7 +151,7 @@ impl ForkChoice for SlowLMDGhost { .get_deserialized(&target_block_root)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*target_block_root))? .slot() - .height(Slot::from(spec.genesis_slot)); + .height(spec.genesis_slot); // get the height of the past target block let past_block_height = self @@ -179,7 +159,7 @@ impl ForkChoice for SlowLMDGhost { .get_deserialized(&attestation_target)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))? .slot() - .height(Slot::from(spec.genesis_slot)); + .height(spec.genesis_slot); // update the attestation only if the new target is higher if past_block_height < block_height { *attestation_target = *target_block_root; @@ -201,7 +181,7 @@ impl ForkChoice for SlowLMDGhost { let start_state_root = start.state_root(); - let latest_votes = self.get_latest_votes(&start_state_root, &start.slot(), spec)?; + let latest_votes = self.get_latest_votes(&start_state_root, start.slot(), spec)?; let mut head_hash = Hash256::zero(); diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs b/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs index ac0b6888c..3cff5b546 100644 --- a/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs +++ b/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs @@ -15,16 +15,13 @@ use bls::{PublicKey, Signature}; use db::stores::{BeaconBlockStore, BeaconStateStore}; use db::MemoryDB; use env_logger::{Builder, Env}; -use fork_choice::{ForkChoice, ForkChoiceError, OptimisedLMDGhost}; +use fork_choice::{ForkChoice, OptimisedLMDGhost}; use ssz::ssz_encode; use std::collections::HashMap; use std::sync::Arc; -use std::{fs::File, io::prelude::*, path::PathBuf, str::FromStr}; -use types::test_utils::{SeedableRng, TestRandom, XorShiftRng}; -use types::validator_registry::get_active_validator_indices; +use std::{fs::File, io::prelude::*, path::PathBuf}; use types::{ - BeaconBlock, BeaconBlockBody, BeaconState, ChainSpec, Deposit, DepositData, DepositInput, - Eth1Data, Hash256, Slot, Validator, + BeaconBlock, BeaconBlockBody, BeaconState, ChainSpec, Epoch, Eth1Data, Hash256, Slot, Validator, }; use yaml_rust::yaml; @@ -50,25 +47,6 @@ fn setup_inital_state( }; let initial_validator_deposits = vec![]; - - /* - (0..no_validators) - .map(|_| Deposit { - branch: vec![], - index: 0, - deposit_data: DepositData { - amount: 32_000_000_000, // 32 ETH (in Gwei) - timestamp: genesis_time - 1, - deposit_input: DepositInput { - pubkey: PublicKey::default(), - withdrawal_credentials: zero_hash.clone(), - proof_of_possession: Signature::empty_signature(), - }, - }, - }) - .collect(); - */ - let spec = ChainSpec::foundation(); // create the state @@ -80,18 +58,18 @@ fn setup_inital_state( ) .unwrap(); + let default_validator = Validator { + pubkey: PublicKey::default(), + withdrawal_credentials: zero_hash, + activation_epoch: Epoch::from(0u64), + exit_epoch: spec.far_future_epoch, + withdrawal_epoch: spec.far_future_epoch, + penalized_epoch: spec.far_future_epoch, + status_flags: None, + }; // activate the validators for _ in 0..no_validators { - let validator = Validator { - pubkey: PublicKey::default(), - withdrawal_credentials: zero_hash, - activation_epoch: spec.far_future_epoch, - exit_epoch: spec.far_future_epoch, - withdrawal_epoch: spec.far_future_epoch, - penalized_epoch: spec.far_future_epoch, - status_flags: None, - }; - state.validator_registry.push(validator); + state.validator_registry.push(default_validator.clone()); state.validator_balances.push(32_000_000_000); } @@ -100,13 +78,6 @@ fn setup_inital_state( .put(&state_root, &ssz_encode(&state)[..]) .unwrap(); - println!( - "Active: {:?}", - get_active_validator_indices( - &state.validator_registry, - Slot::from(5u64).epoch(spec.EPOCH_LENGTH) - ) - ); // return initialised vars (optimised_lmd_ghost, block_store, state_root) } @@ -115,7 +86,7 @@ fn setup_inital_state( #[test] fn test_optimised_lmd_ghost() { // set up logging - Builder::from_env(Env::default().default_filter_or("trace")).init(); + Builder::from_env(Env::default().default_filter_or("debug")).init(); // load the yaml let mut file = { @@ -141,6 +112,7 @@ fn test_optimised_lmd_ghost() { let mut block_slot: HashMap = HashMap::new(); // default vars + let spec = ChainSpec::foundation(); let zero_hash = Hash256::zero(); let eth1_data = Eth1Data { deposit_root: zero_hash.clone(), @@ -165,7 +137,7 @@ fn test_optimised_lmd_ghost() { // default params for genesis let mut block_hash = zero_hash.clone(); - let mut slot = Slot::from(0u64); + let mut slot = spec.genesis_slot; let mut parent_root = zero_hash; // set the slot and parent based off the YAML. Start with genesis; @@ -206,7 +178,9 @@ fn test_optimised_lmd_ghost() { // run add block for fork choice if not genesis if parent_id != block_id { - fork_choice.add_block(&beacon_block, &block_hash).unwrap(); + fork_choice + .add_block(&beacon_block, &block_hash, &spec) + .unwrap(); } } @@ -225,7 +199,7 @@ fn test_optimised_lmd_ghost() { for _ in 0..weight { assert!(current_validator <= total_emulated_validators); fork_choice - .add_attestation(current_validator as u64, &block_root) + .add_attestation(current_validator as u64, &block_root, &spec) .unwrap(); current_validator += 1; } @@ -233,16 +207,23 @@ fn test_optimised_lmd_ghost() { } // everything is set up, run the fork choice, using genesis as the head - println!("Running fork choice"); - let head = fork_choice.find_head(&zero_hash).unwrap(); + let head = fork_choice.find_head(&zero_hash, &spec).unwrap(); - let mut found_id = None; - for (id, block_hash) in block_id_map.iter() { - if *block_hash == head { - found_id = Some(id); - } - } + let (found_id, _) = block_id_map + .iter() + .find(|(_, hash)| **hash == head) + .unwrap(); + + // compare the result to the expected test + let success = test_case["heads"] + .clone() + .into_vec() + .unwrap() + .iter() + .find(|heads| heads["id"].as_str().unwrap() == found_id) + .is_some(); println!("Head Block ID: {:?}", found_id); + assert!(success, "Did not find one of the possible heads"); } } From 846cbdd7f7debf49713f221ffb0b792a41a3c9d6 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 14:37:17 +1100 Subject: [PATCH 05/14] Generalise fork choice tests. --- beacon_node/beacon_chain/src/lib.rs | 2 +- eth2/fork_choice/src/lib.rs | 13 +- eth2/fork_choice/src/slow_lmd_ghost.rs | 9 +- ... => optimised_lmd_ghost_test_vectors.yaml} | 0 .../{optimised_lmd_ghost_test.rs => tests.rs} | 176 ++++++++++-------- 5 files changed, 115 insertions(+), 85 deletions(-) rename eth2/fork_choice/tests/{fork_choice_test_vectors.yaml => optimised_lmd_ghost_test_vectors.yaml} (100%) rename eth2/fork_choice/tests/{optimised_lmd_ghost_test.rs => tests.rs} (82%) diff --git a/beacon_node/beacon_chain/src/lib.rs b/beacon_node/beacon_chain/src/lib.rs index bc9085fbe..fdacdd2b1 100644 --- a/beacon_node/beacon_chain/src/lib.rs +++ b/beacon_node/beacon_chain/src/lib.rs @@ -5,4 +5,4 @@ mod checkpoint; pub use self::beacon_chain::{BeaconChain, Error}; pub use self::checkpoint::CheckPoint; -pub use fork_choice::{ForkChoice, ForkChoiceAlgorithms, ForkChoiceError}; +pub use fork_choice::{ForkChoice, ForkChoiceAlgorithm, ForkChoiceError}; diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index 3923fca9b..90fb0e82b 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -1,22 +1,20 @@ //! This crate stores the various implementations of fork-choice rules that can be used for the //! beacon blockchain. //! -//! There are four implementations. One is the naive longest chain rule (primarily for testing -//! purposes). The other three are proposed implementations of the LMD-GHOST fork-choice rule with various forms of optimisation. +//! There are three implementations. One is the naive longest chain rule (primarily for testing +//! purposes). The other two are proposed implementations of the LMD-GHOST fork-choice rule with various forms of optimisation. //! //! The current implementations are: //! - [`longest-chain`]: Simplistic longest-chain fork choice - primarily for testing, **not for //! production**. //! - [`slow_lmd_ghost`]: This is a simple and very inefficient implementation given in the ethereum 2.0 //! specifications (https://github.com/ethereum/eth2.0-specs/blob/v0.1/specs/core/0_beacon-chain.md#get_block_root). -//! - [`optimised_lmd_ghost`]: This is an optimised version of the naive implementation as proposed +//! - [`optimised_lmd_ghost`]: This is an optimised version of bitwise LMD-GHOST as proposed //! by Vitalik. The reference implementation can be found at: https://github.com/ethereum/research/blob/master/ghost/ghost.py -//! - [`protolambda_lmd_ghost`]: Another optimised version of LMD-GHOST designed by @protolambda. -//! The go implementation can be found here: https://github.com/protolambda/lmd-ghost. //! +//! [`longest-chain`]: struct.LongestChain.html //! [`slow_lmd_ghost`]: struct.SlowLmdGhost.html //! [`optimised_lmd_ghost`]: struct.OptimisedLmdGhost.html -//! [`protolambda_lmd_ghost`]: struct.ProtolambdaLmdGhost.html extern crate db; extern crate ssz; @@ -34,6 +32,7 @@ use types::{BeaconBlock, ChainSpec, Hash256}; pub use longest_chain::LongestChain; pub use optimised_lmd_ghost::OptimisedLMDGhost; +pub use slow_lmd_ghost::SlowLMDGhost; /// Defines the interface for Fork Choices. Each Fork choice will define their own data structures /// which can be built in block processing through the `add_block` and `add_attestation` functions. @@ -97,7 +96,7 @@ impl From for ForkChoiceError { } /// Fork choice options that are currently implemented. -pub enum ForkChoiceAlgorithms { +pub enum ForkChoiceAlgorithm { /// Chooses the longest chain becomes the head. Not for production. LongestChain, /// A simple and highly inefficient implementation of LMD ghost. diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index 7041b1b46..3412f5473 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -30,12 +30,15 @@ impl SlowLMDGhost where T: ClientDB + Sized, { - pub fn new(block_store: BeaconBlockStore, state_store: BeaconStateStore) -> Self { + pub fn new( + block_store: Arc>, + state_store: Arc>, + ) -> Self { SlowLMDGhost { latest_attestation_targets: HashMap::new(), children: HashMap::new(), - block_store: Arc::new(block_store), - state_store: Arc::new(state_store), + block_store, + state_store, } } diff --git a/eth2/fork_choice/tests/fork_choice_test_vectors.yaml b/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml similarity index 100% rename from eth2/fork_choice/tests/fork_choice_test_vectors.yaml rename to eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs b/eth2/fork_choice/tests/tests.rs similarity index 82% rename from eth2/fork_choice/tests/optimised_lmd_ghost_test.rs rename to eth2/fork_choice/tests/tests.rs index 3cff5b546..83baa8bd8 100644 --- a/eth2/fork_choice/tests/optimised_lmd_ghost_test.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -15,7 +15,7 @@ use bls::{PublicKey, Signature}; use db::stores::{BeaconBlockStore, BeaconStateStore}; use db::MemoryDB; use env_logger::{Builder, Env}; -use fork_choice::{ForkChoice, OptimisedLMDGhost}; +use fork_choice::{ForkChoice, ForkChoiceAlgorithm, LongestChain, OptimisedLMDGhost, SlowLMDGhost}; use ssz::ssz_encode; use std::collections::HashMap; use std::sync::Arc; @@ -25,86 +25,32 @@ use types::{ }; use yaml_rust::yaml; -// initialise a single validator and state. All blocks will reference this state root. -fn setup_inital_state( - no_validators: usize, -) -> (impl ForkChoice, Arc>, Hash256) { - let zero_hash = Hash256::zero(); - - let db = Arc::new(MemoryDB::open()); - let block_store = Arc::new(BeaconBlockStore::new(db.clone())); - let state_store = Arc::new(BeaconStateStore::new(db.clone())); - - // the fork choice instantiation - let optimised_lmd_ghost = OptimisedLMDGhost::new(block_store.clone(), state_store.clone()); - - // misc vars for setting up the state - let genesis_time = 1_550_381_159; - - let latest_eth1_data = Eth1Data { - deposit_root: zero_hash.clone(), - block_hash: zero_hash.clone(), - }; - - let initial_validator_deposits = vec![]; - let spec = ChainSpec::foundation(); - - // create the state - let mut state = BeaconState::genesis( - genesis_time, - initial_validator_deposits, - latest_eth1_data, - &spec, - ) - .unwrap(); - - let default_validator = Validator { - pubkey: PublicKey::default(), - withdrawal_credentials: zero_hash, - activation_epoch: Epoch::from(0u64), - exit_epoch: spec.far_future_epoch, - withdrawal_epoch: spec.far_future_epoch, - penalized_epoch: spec.far_future_epoch, - status_flags: None, - }; - // activate the validators - for _ in 0..no_validators { - state.validator_registry.push(default_validator.clone()); - state.validator_balances.push(32_000_000_000); - } - - let state_root = state.canonical_root(); - state_store - .put(&state_root, &ssz_encode(&state)[..]) - .unwrap(); - - // return initialised vars - (optimised_lmd_ghost, block_store, state_root) -} - -// YAML test vectors +// run tests #[test] fn test_optimised_lmd_ghost() { + test_yaml_vectors( + ForkChoiceAlgorithm::OptimisedLMDGhost, + "tests/optimised_lmd_ghost_test_vectors.yaml", + 100, + ); +} + +// run a generic test over given YAML test vectors +fn test_yaml_vectors( + fork_choice_algo: ForkChoiceAlgorithm, + yaml_file_path: &str, + max_validators: usize, +) { // set up logging Builder::from_env(Env::default().default_filter_or("debug")).init(); - // load the yaml - let mut file = { - let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - file_path_buf.push("tests/fork_choice_test_vectors.yaml"); - - File::open(file_path_buf).unwrap() - }; - - let mut yaml_str = String::new(); - file.read_to_string(&mut yaml_str).unwrap(); - let docs = yaml::YamlLoader::load_from_str(&yaml_str).unwrap(); - let doc = &docs[0]; - let test_cases = doc["test_cases"].as_vec().unwrap(); + // load test cases from yaml + let test_cases = load_test_cases_from_yaml(yaml_file_path); // set up the test - let total_emulated_validators = 20; // the number of validators used to give weights. - let (mut fork_choice, block_store, state_root) = setup_inital_state(total_emulated_validators); + let total_emulated_validators = max_validators; // the number of validators used to give weights. + let (mut fork_choice, block_store, state_root) = + setup_inital_state(fork_choice_algo, total_emulated_validators); // keep a hashmap of block_id's to block_hashes (random hashes to abstract block_id) let mut block_id_map: HashMap = HashMap::new(); @@ -227,3 +173,85 @@ fn test_optimised_lmd_ghost() { assert!(success, "Did not find one of the possible heads"); } } + +// loads the test_cases from the supplied yaml file +fn load_test_cases_from_yaml(file_path: &str) -> Vec { + // load the yaml + let mut file = { + let mut file_path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + file_path_buf.push(file_path); + File::open(file_path_buf).unwrap() + }; + let mut yaml_str = String::new(); + file.read_to_string(&mut yaml_str).unwrap(); + let docs = yaml::YamlLoader::load_from_str(&yaml_str).unwrap(); + let doc = &docs[0]; + doc["test_cases"].as_vec().unwrap().clone() +} + +// initialise a single validator and state. All blocks will reference this state root. +fn setup_inital_state( + fork_choice_algo: ForkChoiceAlgorithm, + no_validators: usize, +) -> (Box, Arc>, Hash256) { + let zero_hash = Hash256::zero(); + + let db = Arc::new(MemoryDB::open()); + let block_store = Arc::new(BeaconBlockStore::new(db.clone())); + let state_store = Arc::new(BeaconStateStore::new(db.clone())); + + // the fork choice instantiation + let fork_choice: Box = match fork_choice_algo { + ForkChoiceAlgorithm::OptimisedLMDGhost => Box::new(OptimisedLMDGhost::new( + block_store.clone(), + state_store.clone(), + )), + ForkChoiceAlgorithm::SlowLMDGhost => { + Box::new(SlowLMDGhost::new(block_store.clone(), state_store.clone())) + } + ForkChoiceAlgorithm::LongestChain => Box::new(LongestChain::new(block_store.clone())), + }; + + // misc vars for setting up the state + let genesis_time = 1_550_381_159; + + let latest_eth1_data = Eth1Data { + deposit_root: zero_hash.clone(), + block_hash: zero_hash.clone(), + }; + + let initial_validator_deposits = vec![]; + let spec = ChainSpec::foundation(); + + // create the state + let mut state = BeaconState::genesis( + genesis_time, + initial_validator_deposits, + latest_eth1_data, + &spec, + ) + .unwrap(); + + let default_validator = Validator { + pubkey: PublicKey::default(), + withdrawal_credentials: zero_hash, + activation_epoch: Epoch::from(0u64), + exit_epoch: spec.far_future_epoch, + withdrawal_epoch: spec.far_future_epoch, + penalized_epoch: spec.far_future_epoch, + status_flags: None, + }; + // activate the validators + for _ in 0..no_validators { + state.validator_registry.push(default_validator.clone()); + state.validator_balances.push(32_000_000_000); + } + + let state_root = state.canonical_root(); + state_store + .put(&state_root, &ssz_encode(&state)[..]) + .unwrap(); + + // return initialised vars + (fork_choice, block_store, state_root) +} From bd66a02cb351e179ea97a6d6cba4297494b55e70 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 15:08:55 +1100 Subject: [PATCH 06/14] Add slow LMD Ghost working tests. --- eth2/fork_choice/src/slow_lmd_ghost.rs | 38 ++++++++++++++----- .../tests/lmd_ghost_test_vectors.yaml | 21 ++++++++++ .../optimised_lmd_ghost_test_vectors.yaml | 2 +- eth2/fork_choice/tests/tests.rs | 15 +++++++- 4 files changed, 64 insertions(+), 12 deletions(-) create mode 100644 eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index 3412f5473..c7cd9bde2 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -54,7 +54,6 @@ where // Note: Votes are weighted by min(balance, MAX_DEPOSIT_AMOUNT) // // FORK_CHOICE_BALANCE_INCREMENT // build a hashmap of block_hash to weighted votes - trace!("FORKCHOICE: Getting the latest votes"); let mut latest_votes: HashMap = HashMap::new(); // gets the current weighted votes let current_state = self @@ -66,10 +65,6 @@ where ¤t_state.validator_registry[..], block_slot.epoch(spec.epoch_length), ); - trace!( - "FORKCHOICE: Active validator indicies: {:?}", - active_validator_indices - ); for index in active_validator_indices { let balance = std::cmp::min( @@ -101,12 +96,12 @@ where .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*block_root))? .slot(); - for (target_hash, votes) in latest_votes.iter() { + for (vote_hash, votes) in latest_votes.iter() { let (root_at_slot, _) = self .block_store - .block_at_slot(&block_root, block_slot)? + .block_at_slot(&vote_hash, block_slot)? .ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*block_root))?; - if root_at_slot == *target_hash { + if root_at_slot == *block_root { count += votes; } } @@ -142,12 +137,21 @@ impl ForkChoice for SlowLMDGhost { ) -> Result<(), ForkChoiceError> { // simply add the attestation to the latest_attestation_target if the block_height is // larger + trace!( + "FORKCHOICE: Adding attestation of validator: {:?} for block: {}", + validator_index, + target_block_root + ); let attestation_target = self .latest_attestation_targets .entry(validator_index) .or_insert_with(|| *target_block_root); // if we already have a value if attestation_target != target_block_root { + trace!( + "FORKCHOICE: Old attestation found: {:?}", + attestation_target + ); // get the height of the target block let block_height = self .block_store @@ -165,6 +169,7 @@ impl ForkChoice for SlowLMDGhost { .height(spec.genesis_slot); // update the attestation only if the new target is higher if past_block_height < block_height { + trace!("FORKCHOICE: Updating old attestation"); *attestation_target = *target_block_root; } } @@ -177,6 +182,7 @@ impl ForkChoice for SlowLMDGhost { justified_block_start: &Hash256, spec: &ChainSpec, ) -> Result { + debug!("FORKCHOICE: Running LMD Ghost Fork-choice rule"); let start = self .block_store .get_deserialized(&justified_block_start)? @@ -189,7 +195,7 @@ impl ForkChoice for SlowLMDGhost { let mut head_hash = Hash256::zero(); loop { - let mut head_vote_count = 0; + debug!("FORKCHOICE: Iteration for block: {}", head_hash); let children = match self.children.get(&head_hash) { Some(children) => children, @@ -197,8 +203,22 @@ impl ForkChoice for SlowLMDGhost { None => break, }; + // if we only have one child, use it + if children.len() == 1 { + trace!("FORKCHOICE: Single child found."); + head_hash = children[0]; + continue; + } + trace!("FORKCHOICE: Children found: {:?}", children); + + let mut head_vote_count = 0; for child_hash in children { let vote_count = self.get_vote_count(&latest_votes, &child_hash)?; + trace!( + "FORKCHOICE: Vote count for child: {} is: {}", + child_hash, + vote_count + ); if vote_count > head_vote_count { head_hash = *child_hash; diff --git a/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml b/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml new file mode 100644 index 000000000..3c2118222 --- /dev/null +++ b/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml @@ -0,0 +1,21 @@ +title: Fork-choice Tests +summary: A collection of abstract fork-choice tests for lmd ghost. +test_suite: Fork-Choice + +test_cases: +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b1' + - id: 'b3' + parent: 'b1' + weights: + - b0: 0 + - b1: 0 + - b2: 5 + - b3: 10 + heads: + - id: 'b3' diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml b/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml index 5a8869e8b..1c2f6b696 100644 --- a/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml +++ b/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml @@ -1,5 +1,5 @@ title: Fork-choice Tests -summary: A collection of abstract fork-choice tests. +summary: A collection of abstract fork-choice tests for bitwise lmd ghost. test_suite: Fork-Choice test_cases: diff --git a/eth2/fork_choice/tests/tests.rs b/eth2/fork_choice/tests/tests.rs index 83baa8bd8..0eafb58ab 100644 --- a/eth2/fork_choice/tests/tests.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -25,13 +25,23 @@ use types::{ }; use yaml_rust::yaml; -// run tests #[test] fn test_optimised_lmd_ghost() { test_yaml_vectors( ForkChoiceAlgorithm::OptimisedLMDGhost, "tests/optimised_lmd_ghost_test_vectors.yaml", 100, + "debug", + ); +} + +#[test] +fn test_slow_lmd_ghost() { + test_yaml_vectors( + ForkChoiceAlgorithm::SlowLMDGhost, + "tests/lmd_ghost_test_vectors.yaml", + 100, + "debug", ); } @@ -40,9 +50,10 @@ fn test_yaml_vectors( fork_choice_algo: ForkChoiceAlgorithm, yaml_file_path: &str, max_validators: usize, + log_level: &str, ) { // set up logging - Builder::from_env(Env::default().default_filter_or("debug")).init(); + Builder::from_env(Env::default().default_filter_or(log_level)).init(); // load test cases from yaml let test_cases = load_test_cases_from_yaml(yaml_file_path); From 2394f64329f4f9bcd08d9f31bce66517a2fc9e7c Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 15:22:35 +1100 Subject: [PATCH 07/14] Add longest chain tests and test vectors. --- .../tests/longest_chain_test_vectors.yaml | 51 +++++++++++++++++++ eth2/fork_choice/tests/tests.rs | 10 ++++ 2 files changed, 61 insertions(+) create mode 100644 eth2/fork_choice/tests/longest_chain_test_vectors.yaml diff --git a/eth2/fork_choice/tests/longest_chain_test_vectors.yaml b/eth2/fork_choice/tests/longest_chain_test_vectors.yaml new file mode 100644 index 000000000..e1cd61f06 --- /dev/null +++ b/eth2/fork_choice/tests/longest_chain_test_vectors.yaml @@ -0,0 +1,51 @@ +title: Fork-choice Tests +summary: A collection of abstract fork-choice tests to verify the longest chain fork-choice rule. +test_suite: Fork-Choice + +test_cases: +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b1' + - id: 'b3' + parent: 'b1' + - id: 'b4' + parent: 'b3' + weights: + - b0: 0 + - b1: 0 + - b2: 10 + - b3: 1 + heads: + - id: 'b4' +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b1' + - id: 'b3' + parent: 'b2' + - id: 'b4' + parent: 'b3' + - id: 'b5' + parent: 'b0' + - id: 'b6' + parent: 'b5' + - id: 'b7' + parent: 'b6' + - id: 'b8' + parent: 'b7' + - id: 'b9' + parent: 'b8' + weights: + - b0: 5 + - b1: 20 + - b2: 10 + - b3: 10 + heads: + - id: 'b9' diff --git a/eth2/fork_choice/tests/tests.rs b/eth2/fork_choice/tests/tests.rs index 0eafb58ab..b08c7031e 100644 --- a/eth2/fork_choice/tests/tests.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -45,6 +45,16 @@ fn test_slow_lmd_ghost() { ); } +#[test] +fn test_longest_chain() { + test_yaml_vectors( + ForkChoiceAlgorithm::LongestChain, + "tests/longest_chain_test_vectors.yaml", + 100, + "debug", + ); +} + // run a generic test over given YAML test vectors fn test_yaml_vectors( fork_choice_algo: ForkChoiceAlgorithm, From fd1edaf8056471e552905e29ff06c93807ab963a Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 23:06:35 +1100 Subject: [PATCH 08/14] Add fork choice bug fixes. - Further bug fixes from testing. - Simplify the testing framework. - Add tests for longest chain and GHOST vs bitwise GHOST. --- eth2/fork_choice/Cargo.toml | 1 + eth2/fork_choice/src/optimised_lmd_ghost.rs | 24 +++-- eth2/fork_choice/src/slow_lmd_ghost.rs | 2 +- .../tests/lmd_ghost_test_vectors.yaml | 16 ++++ .../optimised_lmd_ghost_test_vectors.yaml | 16 ++++ eth2/fork_choice/tests/tests.rs | 93 ++++++++++--------- 6 files changed, 99 insertions(+), 53 deletions(-) diff --git a/eth2/fork_choice/Cargo.toml b/eth2/fork_choice/Cargo.toml index d12f5ae7a..210f3c235 100644 --- a/eth2/fork_choice/Cargo.toml +++ b/eth2/fork_choice/Cargo.toml @@ -13,6 +13,7 @@ log = "0.4.6" bit-vec = "0.5.0" [dev-dependencies] +hex = "0.3.2" yaml-rust = "0.4.2" bls = { path = "../utils/bls" } slot_clock = { path = "../utils/slot_clock" } diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/optimised_lmd_ghost.rs index f211359ea..e85a052ca 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/optimised_lmd_ghost.rs @@ -203,13 +203,22 @@ where } let mut bitmask: BitVec = BitVec::new(); // loop through bytes then bits - for bit in 0..256 { + for bit in 0..=256 { let mut zero_votes = 0; let mut one_votes = 0; - let mut single_candidate = None; + let mut single_candidate = (None, false); + trace!("FORKCHOICE: Child vote length: {}", votes.len()); for (candidate, votes) in votes.iter() { let candidate_bit: BitVec = BitVec::from_bytes(&candidate); + /* + trace!( + "FORKCHOICE: Child: {} in bits: {:?}", + candidate, + candidate_bit + ); + trace!("FORKCHOICE: Current bitmask: {:?}", bitmask); + */ // if the bitmasks don't match if !bitmask.iter().eq(candidate_bit.iter().take(bit)) { @@ -227,15 +236,16 @@ where one_votes += votes; } - if single_candidate.is_none() { - single_candidate = Some(candidate); + if single_candidate.0.is_none() { + single_candidate.0 = Some(candidate); + single_candidate.1 = true; } else { - single_candidate = None; + single_candidate.1 = false; } } bitmask.push(one_votes > zero_votes); - if let Some(candidate) = single_candidate { - return Some(*candidate); + if single_candidate.1 { + return Some(*single_candidate.0.expect("Cannot reach this")); } } // should never reach here diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index c7cd9bde2..d7dc4d1ad 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -192,7 +192,7 @@ impl ForkChoice for SlowLMDGhost { let latest_votes = self.get_latest_votes(&start_state_root, start.slot(), spec)?; - let mut head_hash = Hash256::zero(); + let mut head_hash = *justified_block_start; loop { debug!("FORKCHOICE: Iteration for block: {}", head_hash); diff --git a/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml b/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml index 3c2118222..4676d8201 100644 --- a/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml +++ b/eth2/fork_choice/tests/lmd_ghost_test_vectors.yaml @@ -19,3 +19,19 @@ test_cases: - b3: 10 heads: - id: 'b3' +# bitwise LMD ghost example. GHOST gives b1 +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b0' + - id: 'b3' + parent: 'b0' + weights: + - b1: 5 + - b2: 4 + - b3: 3 + heads: + - id: 'b1' diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml b/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml index 1c2f6b696..1578673cd 100644 --- a/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml +++ b/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml @@ -19,3 +19,19 @@ test_cases: - b3: 10 heads: - id: 'b3' +# bitwise LMD ghost example. bitwise GHOST gives b2 +- blocks: + - id: 'b0' + parent: 'b0' + - id: 'b1' + parent: 'b0' + - id: 'b2' + parent: 'b0' + - id: 'b3' + parent: 'b0' + weights: + - b1: 5 + - b2: 4 + - b3: 3 + heads: + - id: 'b2' diff --git a/eth2/fork_choice/tests/tests.rs b/eth2/fork_choice/tests/tests.rs index b08c7031e..01627eb73 100644 --- a/eth2/fork_choice/tests/tests.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -3,8 +3,9 @@ extern crate beacon_chain; extern crate bls; extern crate db; -extern crate env_logger; +//extern crate env_logger; // for debugging extern crate fork_choice; +extern crate hex; extern crate log; extern crate slot_clock; extern crate types; @@ -14,7 +15,7 @@ pub use beacon_chain::BeaconChain; use bls::{PublicKey, Signature}; use db::stores::{BeaconBlockStore, BeaconStateStore}; use db::MemoryDB; -use env_logger::{Builder, Env}; +//use env_logger::{Builder, Env}; use fork_choice::{ForkChoice, ForkChoiceAlgorithm, LongestChain, OptimisedLMDGhost, SlowLMDGhost}; use ssz::ssz_encode; use std::collections::HashMap; @@ -25,13 +26,17 @@ use types::{ }; use yaml_rust::yaml; +// Note: We Assume the block Id's are hex-encoded. + #[test] fn test_optimised_lmd_ghost() { + // set up logging + //Builder::from_env(Env::default().default_filter_or("trace")).init(); + test_yaml_vectors( ForkChoiceAlgorithm::OptimisedLMDGhost, "tests/optimised_lmd_ghost_test_vectors.yaml", 100, - "debug", ); } @@ -41,7 +46,6 @@ fn test_slow_lmd_ghost() { ForkChoiceAlgorithm::SlowLMDGhost, "tests/lmd_ghost_test_vectors.yaml", 100, - "debug", ); } @@ -51,7 +55,6 @@ fn test_longest_chain() { ForkChoiceAlgorithm::LongestChain, "tests/longest_chain_test_vectors.yaml", 100, - "debug", ); } @@ -59,25 +62,11 @@ fn test_longest_chain() { fn test_yaml_vectors( fork_choice_algo: ForkChoiceAlgorithm, yaml_file_path: &str, - max_validators: usize, - log_level: &str, + emulated_validators: usize, // the number of validators used to give weights. ) { - // set up logging - Builder::from_env(Env::default().default_filter_or(log_level)).init(); - // load test cases from yaml let test_cases = load_test_cases_from_yaml(yaml_file_path); - // set up the test - let total_emulated_validators = max_validators; // the number of validators used to give weights. - let (mut fork_choice, block_store, state_root) = - setup_inital_state(fork_choice_algo, total_emulated_validators); - - // keep a hashmap of block_id's to block_hashes (random hashes to abstract block_id) - let mut block_id_map: HashMap = HashMap::new(); - // keep a list of hash to slot - let mut block_slot: HashMap = HashMap::new(); - // default vars let spec = ChainSpec::foundation(); let zero_hash = Hash256::zero(); @@ -97,33 +86,37 @@ fn test_yaml_vectors( // process the tests for test_case in test_cases { + // setup a fresh test + let (mut fork_choice, block_store, state_root) = + setup_inital_state(&fork_choice_algo, emulated_validators); + + // keep a hashmap of block_id's to block_hashes (random hashes to abstract block_id) + //let mut block_id_map: HashMap = HashMap::new(); + // keep a list of hash to slot + let mut block_slot: HashMap = HashMap::new(); // assume the block tree is given to us in order. + let mut genesis_hash = None; for block in test_case["blocks"].clone().into_vec().unwrap() { let block_id = block["id"].as_str().unwrap().to_string(); - let parent_id = block["parent"].as_str().unwrap(); + let parent_id = block["parent"].as_str().unwrap().to_string(); // default params for genesis - let mut block_hash = zero_hash.clone(); + let block_hash = id_to_hash(&block_id); let mut slot = spec.genesis_slot; - let mut parent_root = zero_hash; + let parent_root = id_to_hash(&parent_id); // set the slot and parent based off the YAML. Start with genesis; - // if not the genesis, update slot and parent + // if not the genesis, update slot if parent_id != block_id { - // generate a random hash for the block_hash - block_hash = Hash256::random(); - // find the parent hash - parent_root = *block_id_map - .get(parent_id) - .expect(&format!("Parent not found: {}", parent_id)); + // find parent slot slot = *(block_slot .get(&parent_root) .expect("Parent should have a slot number")) + 1; + } else { + genesis_hash = Some(block_hash); } - block_id_map.insert(block_id.clone(), block_hash.clone()); - // update slot mapping block_slot.insert(block_hash, slot); @@ -138,7 +131,7 @@ fn test_yaml_vectors( body: body.clone(), }; - // Store the block and state. + // Store the block. block_store .put(&block_hash, &ssz_encode(&beacon_block)[..]) .unwrap(); @@ -157,14 +150,15 @@ fn test_yaml_vectors( // get the block id and weights for (map_id, map_weight) in id_map.as_hash().unwrap().iter() { let id = map_id.as_str().unwrap(); - let block_root = block_id_map - .get(id) - .expect(&format!("Cannot find block id: {} in weights", id)); + let block_root = id_to_hash(&id.to_string()); let weight = map_weight.as_i64().unwrap(); // we assume a validator has a value 1 and add an attestation for to achieve the // correct weight for _ in 0..weight { - assert!(current_validator <= total_emulated_validators); + assert!( + current_validator <= emulated_validators, + "Not enough validators to emulate weights" + ); fork_choice .add_attestation(current_validator as u64, &block_root, &spec) .unwrap(); @@ -174,11 +168,8 @@ fn test_yaml_vectors( } // everything is set up, run the fork choice, using genesis as the head - let head = fork_choice.find_head(&zero_hash, &spec).unwrap(); - - let (found_id, _) = block_id_map - .iter() - .find(|(_, hash)| **hash == head) + let head = fork_choice + .find_head(&genesis_hash.unwrap(), &spec) .unwrap(); // compare the result to the expected test @@ -187,10 +178,10 @@ fn test_yaml_vectors( .into_vec() .unwrap() .iter() - .find(|heads| heads["id"].as_str().unwrap() == found_id) + .find(|heads| id_to_hash(&heads["id"].as_str().unwrap().to_string()) == head) .is_some(); - println!("Head Block ID: {:?}", found_id); + println!("Head found: {}", head); assert!(success, "Did not find one of the possible heads"); } } @@ -212,7 +203,7 @@ fn load_test_cases_from_yaml(file_path: &str) -> Vec { // initialise a single validator and state. All blocks will reference this state root. fn setup_inital_state( - fork_choice_algo: ForkChoiceAlgorithm, + fork_choice_algo: &ForkChoiceAlgorithm, no_validators: usize, ) -> (Box, Arc>, Hash256) { let zero_hash = Hash256::zero(); @@ -276,3 +267,15 @@ fn setup_inital_state( // return initialised vars (fork_choice, block_store, state_root) } + +// convert a block_id into a Hash256 -- assume input is hex encoded; +fn id_to_hash(id: &String) -> Hash256 { + let bytes = hex::decode(id).expect("Block ID should be hex"); + + let len = std::cmp::min(bytes.len(), 32); + let mut fixed_bytes = [0u8; 32]; + for (index, byte) in bytes.iter().take(32).enumerate() { + fixed_bytes[32 - len + index] = *byte; + } + Hash256::from(fixed_bytes) +} From 6f74ffc7e6967be56637b567c2e032fdc60baa6b Mon Sep 17 00:00:00 2001 From: Age Manning Date: Tue, 19 Feb 2019 23:20:45 +1100 Subject: [PATCH 09/14] Correct minor comment. --- eth2/fork_choice/tests/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eth2/fork_choice/tests/tests.rs b/eth2/fork_choice/tests/tests.rs index 01627eb73..0bebe6a77 100644 --- a/eth2/fork_choice/tests/tests.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -1,4 +1,4 @@ -// Tests the optimised LMD Ghost Algorithm +// Tests the available fork-choice algorithms extern crate beacon_chain; extern crate bls; From c7acde4fc27ad7c05aa65aa341a83930d6c17b17 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 20 Feb 2019 11:56:58 +1100 Subject: [PATCH 10/14] Rename OptimisedLMDGhost to BitwiseLMDGhost. --- .../test_harness/src/beacon_chain_harness.rs | 6 +++--- .../test_harness/src/validator_harness/mod.rs | 16 ++++++++-------- beacon_node/src/main.rs | 4 ++-- ...timised_lmd_ghost.rs => bitwise_lmd_ghost.rs} | 8 ++++---- eth2/fork_choice/src/lib.rs | 12 ++++++------ ....yaml => bitwise_lmd_ghost_test_vectors.yaml} | 0 eth2/fork_choice/tests/tests.rs | 10 +++++----- 7 files changed, 28 insertions(+), 28 deletions(-) rename eth2/fork_choice/src/{optimised_lmd_ghost.rs => bitwise_lmd_ghost.rs} (99%) rename eth2/fork_choice/tests/{optimised_lmd_ghost_test_vectors.yaml => bitwise_lmd_ghost_test_vectors.yaml} (100%) 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 9d61952f0..a20441beb 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 @@ -6,7 +6,7 @@ use db::{ stores::{BeaconBlockStore, BeaconStateStore}, MemoryDB, }; -use fork_choice::OptimisedLMDGhost; +use fork_choice::BitwiseLMDGhost; use log::debug; use rayon::prelude::*; use slot_clock::TestingSlotClock; @@ -28,7 +28,7 @@ use types::{ /// 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, @@ -46,7 +46,7 @@ impl BeaconChainHarness { let state_store = Arc::new(BeaconStateStore::new(db.clone())); let genesis_time = 1_549_935_547; // 12th Feb 2018 (arbitrary value in the past). let slot_clock = TestingSlotClock::new(spec.genesis_slot.as_u64()); - let fork_choice = OptimisedLMDGhost::new(block_store.clone(), state_store.clone()); + let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); let latest_eth1_data = Eth1Data { deposit_root: Hash256::zero(), block_hash: Hash256::zero(), diff --git a/beacon_node/beacon_chain/test_harness/src/validator_harness/mod.rs b/beacon_node/beacon_chain/test_harness/src/validator_harness/mod.rs index f48309541..60c2f8ecf 100644 --- a/beacon_node/beacon_chain/test_harness/src/validator_harness/mod.rs +++ b/beacon_node/beacon_chain/test_harness/src/validator_harness/mod.rs @@ -10,7 +10,7 @@ use block_proposer::{BlockProducer, Error as BlockPollError}; use db::MemoryDB; use direct_beacon_node::DirectBeaconNode; use direct_duties::DirectDuties; -use fork_choice::OptimisedLMDGhost; +use fork_choice::BitwiseLMDGhost; use local_signer::LocalSigner; use slot_clock::TestingSlotClock; use std::sync::Arc; @@ -36,20 +36,20 @@ pub enum AttestationProduceError { pub struct ValidatorHarness { pub block_producer: BlockProducer< TestingSlotClock, - DirectBeaconNode>, - DirectDuties>, + DirectBeaconNode>, + DirectDuties>, LocalSigner, >, pub attester: Attester< TestingSlotClock, - DirectBeaconNode>, - DirectDuties>, + DirectBeaconNode>, + DirectDuties>, LocalSigner, >, pub spec: Arc, - pub epoch_map: Arc>>, + pub epoch_map: Arc>>, pub keypair: Keypair, - pub beacon_node: Arc>>, + pub beacon_node: Arc>>, pub slot_clock: Arc, pub signer: Arc, } @@ -61,7 +61,7 @@ impl ValidatorHarness { /// A `BlockProducer` and `Attester` is created.. pub fn new( keypair: Keypair, - beacon_chain: Arc>>, + beacon_chain: Arc>>, spec: Arc, ) -> Self { let slot_clock = Arc::new(TestingSlotClock::new(spec.genesis_slot.as_u64())); diff --git a/beacon_node/src/main.rs b/beacon_node/src/main.rs index 2b6cdddcd..b9ef2c8a7 100644 --- a/beacon_node/src/main.rs +++ b/beacon_node/src/main.rs @@ -14,7 +14,7 @@ use db::{ stores::{BeaconBlockStore, BeaconStateStore}, MemoryDB, }; -use fork_choice::optimised_lmd_ghost::OptimisedLMDGhost; +use fork_choice::BitwiseLMDGhost; use slog::{error, info, o, Drain}; use slot_clock::SystemTimeSlotClock; use std::sync::Arc; @@ -81,7 +81,7 @@ fn main() { let slot_clock = SystemTimeSlotClock::new(genesis_time, spec.slot_duration) .expect("Unable to load SystemTimeSlotClock"); // Choose the fork choice - let fork_choice = OptimisedLMDGhost::new(block_store.clone(), state_store.clone()); + let fork_choice = BitwiseLMDGhost::new(block_store.clone(), state_store.clone()); /* * Generate some random data to start a chain with. diff --git a/eth2/fork_choice/src/optimised_lmd_ghost.rs b/eth2/fork_choice/src/bitwise_lmd_ghost.rs similarity index 99% rename from eth2/fork_choice/src/optimised_lmd_ghost.rs rename to eth2/fork_choice/src/bitwise_lmd_ghost.rs index e85a052ca..c09de1529 100644 --- a/eth2/fork_choice/src/optimised_lmd_ghost.rs +++ b/eth2/fork_choice/src/bitwise_lmd_ghost.rs @@ -37,7 +37,7 @@ fn power_of_2_below(x: u32) -> u32 { } /// Stores the necessary data structures to run the optimised lmd ghost algorithm. -pub struct OptimisedLMDGhost { +pub struct BitwiseLMDGhost { /// A cache of known ancestors at given heights for a specific block. //TODO: Consider FnvHashMap cache: HashMap, Hash256>, @@ -56,7 +56,7 @@ pub struct OptimisedLMDGhost { max_known_height: SlotHeight, } -impl OptimisedLMDGhost +impl BitwiseLMDGhost where T: ClientDB + Sized, { @@ -64,7 +64,7 @@ where block_store: Arc>, state_store: Arc>, ) -> Self { - OptimisedLMDGhost { + BitwiseLMDGhost { cache: HashMap::new(), ancestors: vec![HashMap::new(); 16], latest_attestation_targets: HashMap::new(), @@ -253,7 +253,7 @@ where } } -impl ForkChoice for OptimisedLMDGhost { +impl ForkChoice for BitwiseLMDGhost { fn add_block( &mut self, block: &BeaconBlock, diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index 90fb0e82b..4a58e3057 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -9,12 +9,12 @@ //! production**. //! - [`slow_lmd_ghost`]: This is a simple and very inefficient implementation given in the ethereum 2.0 //! specifications (https://github.com/ethereum/eth2.0-specs/blob/v0.1/specs/core/0_beacon-chain.md#get_block_root). -//! - [`optimised_lmd_ghost`]: This is an optimised version of bitwise LMD-GHOST as proposed +//! - [`bitwise_lmd_ghost`]: This is an optimised version of bitwise LMD-GHOST as proposed //! by Vitalik. The reference implementation can be found at: https://github.com/ethereum/research/blob/master/ghost/ghost.py //! //! [`longest-chain`]: struct.LongestChain.html //! [`slow_lmd_ghost`]: struct.SlowLmdGhost.html -//! [`optimised_lmd_ghost`]: struct.OptimisedLmdGhost.html +//! [`bitwise_lmd_ghost`]: struct.OptimisedLmdGhost.html extern crate db; extern crate ssz; @@ -22,16 +22,16 @@ extern crate types; #[macro_use] extern crate log; +pub mod bitwise_lmd_ghost; pub mod longest_chain; -pub mod optimised_lmd_ghost; pub mod slow_lmd_ghost; use db::stores::BeaconBlockAtSlotError; use db::DBError; use types::{BeaconBlock, ChainSpec, Hash256}; +pub use bitwise_lmd_ghost::BitwiseLMDGhost; pub use longest_chain::LongestChain; -pub use optimised_lmd_ghost::OptimisedLMDGhost; pub use slow_lmd_ghost::SlowLMDGhost; /// Defines the interface for Fork Choices. Each Fork choice will define their own data structures @@ -101,6 +101,6 @@ pub enum ForkChoiceAlgorithm { LongestChain, /// A simple and highly inefficient implementation of LMD ghost. SlowLMDGhost, - /// An optimised version of LMD-GHOST by Vitalik. - OptimisedLMDGhost, + /// An optimised version of bitwise LMD-GHOST by Vitalik. + BitwiseLMDGhost, } diff --git a/eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml b/eth2/fork_choice/tests/bitwise_lmd_ghost_test_vectors.yaml similarity index 100% rename from eth2/fork_choice/tests/optimised_lmd_ghost_test_vectors.yaml rename to eth2/fork_choice/tests/bitwise_lmd_ghost_test_vectors.yaml diff --git a/eth2/fork_choice/tests/tests.rs b/eth2/fork_choice/tests/tests.rs index 0bebe6a77..1d93cd0db 100644 --- a/eth2/fork_choice/tests/tests.rs +++ b/eth2/fork_choice/tests/tests.rs @@ -16,7 +16,7 @@ use bls::{PublicKey, Signature}; use db::stores::{BeaconBlockStore, BeaconStateStore}; use db::MemoryDB; //use env_logger::{Builder, Env}; -use fork_choice::{ForkChoice, ForkChoiceAlgorithm, LongestChain, OptimisedLMDGhost, SlowLMDGhost}; +use fork_choice::{BitwiseLMDGhost, ForkChoice, ForkChoiceAlgorithm, LongestChain, SlowLMDGhost}; use ssz::ssz_encode; use std::collections::HashMap; use std::sync::Arc; @@ -29,13 +29,13 @@ use yaml_rust::yaml; // Note: We Assume the block Id's are hex-encoded. #[test] -fn test_optimised_lmd_ghost() { +fn test_bitwise_lmd_ghost() { // set up logging //Builder::from_env(Env::default().default_filter_or("trace")).init(); test_yaml_vectors( - ForkChoiceAlgorithm::OptimisedLMDGhost, - "tests/optimised_lmd_ghost_test_vectors.yaml", + ForkChoiceAlgorithm::BitwiseLMDGhost, + "tests/bitwise_lmd_ghost_test_vectors.yaml", 100, ); } @@ -214,7 +214,7 @@ fn setup_inital_state( // the fork choice instantiation let fork_choice: Box = match fork_choice_algo { - ForkChoiceAlgorithm::OptimisedLMDGhost => Box::new(OptimisedLMDGhost::new( + ForkChoiceAlgorithm::BitwiseLMDGhost => Box::new(BitwiseLMDGhost::new( block_store.clone(), state_store.clone(), )), From d8584cbed27e70ec15dacf39a17312988de5f61d Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 20 Feb 2019 12:15:41 +1100 Subject: [PATCH 11/14] Update to rust 2018 importing macros. --- eth2/fork_choice/src/bitwise_lmd_ghost.rs | 1 + eth2/fork_choice/src/lib.rs | 2 -- eth2/fork_choice/src/slow_lmd_ghost.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/eth2/fork_choice/src/bitwise_lmd_ghost.rs b/eth2/fork_choice/src/bitwise_lmd_ghost.rs index c09de1529..e057fa1ee 100644 --- a/eth2/fork_choice/src/bitwise_lmd_ghost.rs +++ b/eth2/fork_choice/src/bitwise_lmd_ghost.rs @@ -8,6 +8,7 @@ use db::{ ClientDB, }; use fast_math::log2_raw; +use log::{debug, trace}; use std::collections::HashMap; use std::sync::Arc; use types::{ diff --git a/eth2/fork_choice/src/lib.rs b/eth2/fork_choice/src/lib.rs index 4a58e3057..6062c19b1 100644 --- a/eth2/fork_choice/src/lib.rs +++ b/eth2/fork_choice/src/lib.rs @@ -19,8 +19,6 @@ extern crate db; extern crate ssz; extern crate types; -#[macro_use] -extern crate log; pub mod bitwise_lmd_ghost; pub mod longest_chain; diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index d7dc4d1ad..7cad73285 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -5,6 +5,7 @@ use db::{ stores::{BeaconBlockStore, BeaconStateStore}, ClientDB, }; +use log::{debug, trace}; use std::collections::HashMap; use std::sync::Arc; use types::{ From 2fbdc531471414bb11627a5912db3bf4cccdcbe4 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 20 Feb 2019 12:36:54 +1100 Subject: [PATCH 12/14] Add asserts to ensure block heights are not too large. --- eth2/fork_choice/src/bitwise_lmd_ghost.rs | 8 ++++++-- eth2/types/src/slot_epoch_macros.rs | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/eth2/fork_choice/src/bitwise_lmd_ghost.rs b/eth2/fork_choice/src/bitwise_lmd_ghost.rs index e057fa1ee..013c901b9 100644 --- a/eth2/fork_choice/src/bitwise_lmd_ghost.rs +++ b/eth2/fork_choice/src/bitwise_lmd_ghost.rs @@ -19,7 +19,7 @@ use types::{ //TODO: Pruning - Children //TODO: Handle Syncing -/// The optimised LMD-GHOST fork choice rule. +/// The optimised bitwise LMD-GHOST fork choice rule. /// NOTE: This uses u32 to represent difference between block heights. Thus this is only /// applicable for block height differences in the range of a u32. /// This can potentially be parallelized in some parts. @@ -30,6 +30,10 @@ fn log2_int(x: u32) -> u32 { if x == 0 { return 0; } + assert!( + x <= std::f32::MAX as u32, + "Height too large for fast log in bitwise fork choice" + ); log2_raw(x as f32) as u32 } @@ -37,7 +41,7 @@ fn power_of_2_below(x: u32) -> u32 { 2u32.pow(log2_int(x)) } -/// Stores the necessary data structures to run the optimised lmd ghost algorithm. +/// Stores the necessary data structures to run the optimised bitwise lmd ghost algorithm. pub struct BitwiseLMDGhost { /// A cache of known ancestors at given heights for a specific block. //TODO: Consider FnvHashMap diff --git a/eth2/types/src/slot_epoch_macros.rs b/eth2/types/src/slot_epoch_macros.rs index 54a8f2ce9..b0550f2f8 100644 --- a/eth2/types/src/slot_epoch_macros.rs +++ b/eth2/types/src/slot_epoch_macros.rs @@ -25,12 +25,14 @@ macro_rules! impl_into_u32 { ($main: ident) => { impl Into for $main { fn into(self) -> u32 { + assert!(self.0 < u64::from(std::u32::MAX), "Lossy conversion to u32"); self.0 as u32 } } impl $main { pub fn as_u32(&self) -> u32 { + assert!(self.0 < u64::from(std::u32::MAX), "Lossy conversion to u32"); self.0 as u32 } } From 0f7167992b8171fd1c9170630018b04e30872b00 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 20 Feb 2019 12:39:00 +1100 Subject: [PATCH 13/14] Removes topic from logs. --- eth2/fork_choice/src/bitwise_lmd_ghost.rs | 33 +++++++++++------------ eth2/fork_choice/src/slow_lmd_ghost.rs | 25 +++++++---------- 2 files changed, 24 insertions(+), 34 deletions(-) diff --git a/eth2/fork_choice/src/bitwise_lmd_ghost.rs b/eth2/fork_choice/src/bitwise_lmd_ghost.rs index 013c901b9..c467545ea 100644 --- a/eth2/fork_choice/src/bitwise_lmd_ghost.rs +++ b/eth2/fork_choice/src/bitwise_lmd_ghost.rs @@ -115,7 +115,7 @@ where } } } - trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); + trace!("Latest votes: {:?}", latest_votes); Ok(latest_votes) } @@ -180,7 +180,7 @@ where let mut current_votes: HashMap = HashMap::new(); let mut total_vote_count = 0; - trace!("FORKCHOICE: Clear winner at block height: {}", block_height); + trace!("Clear winner at block height: {}", block_height); // loop through the latest votes and count all votes // these have already been weighted by balance for (hash, votes) in latest_votes.iter() { @@ -213,22 +213,22 @@ where let mut one_votes = 0; let mut single_candidate = (None, false); - trace!("FORKCHOICE: Child vote length: {}", votes.len()); + trace!("Child vote length: {}", votes.len()); for (candidate, votes) in votes.iter() { let candidate_bit: BitVec = BitVec::from_bytes(&candidate); /* trace!( - "FORKCHOICE: Child: {} in bits: {:?}", + "Child: {} in bits: {:?}", candidate, candidate_bit ); - trace!("FORKCHOICE: Current bitmask: {:?}", bitmask); + trace!("Current bitmask: {:?}", bitmask); */ // if the bitmasks don't match if !bitmask.iter().eq(candidate_bit.iter().take(bit)) { trace!( - "FORKCHOICE: Child: {} was removed in bit: {} with the bitmask: {:?}", + "Child: {} was removed in bit: {} with the bitmask: {:?}", candidate, bit, bitmask @@ -306,7 +306,7 @@ impl ForkChoice for BitwiseLMDGhost { // simply add the attestation to the latest_attestation_target if the block_height is // larger trace!( - "FORKCHOICE: Adding attestation of validator: {:?} for block: {}", + "Adding attestation of validator: {:?} for block: {}", validator_index, target_block_root ); @@ -316,10 +316,7 @@ impl ForkChoice for BitwiseLMDGhost { .or_insert_with(|| *target_block_root); // if we already have a value if attestation_target != target_block_root { - trace!( - "FORKCHOICE: Old attestation found: {:?}", - attestation_target - ); + trace!("Old attestation found: {:?}", attestation_target); // get the height of the target block let block_height = self .block_store @@ -337,7 +334,7 @@ impl ForkChoice for BitwiseLMDGhost { .height(spec.genesis_slot); // update the attestation only if the new target is higher if past_block_height < block_height { - trace!("FORKCHOICE: Updating old attestation"); + trace!("Updating old attestation"); *attestation_target = *target_block_root; } } @@ -374,7 +371,7 @@ impl ForkChoice for BitwiseLMDGhost { // begin searching for the head loop { debug!( - "FORKCHOICE: Iteration for block: {} with vote length: {}", + "Iteration for block: {} with vote length: {}", current_head, latest_votes.len() ); @@ -401,19 +398,19 @@ impl ForkChoice for BitwiseLMDGhost { step /= 2; } if step > 0 { - trace!("FORKCHOICE: Found clear winner in log lookup"); + trace!("Found clear winner in log lookup"); } // if our skip lookup failed and we only have one child, progress to that child else if children.len() == 1 { current_head = children[0]; trace!( - "FORKCHOICE: Lookup failed, only one child, proceeding to child: {}", + "Lookup failed, only one child, proceeding to child: {}", current_head ); } // we need to find the best child path to progress down. else { - trace!("FORKCHOICE: Searching for best child"); + trace!("Searching for best child"); let mut child_votes = HashMap::new(); for (voted_hash, vote) in latest_votes.iter() { // if the latest votes correspond to a child @@ -426,7 +423,7 @@ impl ForkChoice for BitwiseLMDGhost { current_head = self .choose_best_child(&child_votes) .ok_or(ForkChoiceError::CannotFindBestChild)?; - trace!("FORKCHOICE: Best child found: {}", current_head); + trace!("Best child found: {}", current_head); } // didn't find head yet, proceed to next iteration @@ -441,7 +438,7 @@ impl ForkChoice for BitwiseLMDGhost { // more specifically, only keep votes that have head as an ancestor for hash in latest_votes.keys() { trace!( - "FORKCHOICE: Ancestor for vote: {} at height: {} is: {:?}", + "Ancestor for vote: {} at height: {} is: {:?}", hash, block_height, self.get_ancestor(*hash, block_height, spec) diff --git a/eth2/fork_choice/src/slow_lmd_ghost.rs b/eth2/fork_choice/src/slow_lmd_ghost.rs index 7cad73285..3aafb3924 100644 --- a/eth2/fork_choice/src/slow_lmd_ghost.rs +++ b/eth2/fork_choice/src/slow_lmd_ghost.rs @@ -78,7 +78,7 @@ where } } } - trace!("FORKCHOICE: Latest votes: {:?}", latest_votes); + trace!("Latest votes: {:?}", latest_votes); Ok(latest_votes) } @@ -139,7 +139,7 @@ impl ForkChoice for SlowLMDGhost { // simply add the attestation to the latest_attestation_target if the block_height is // larger trace!( - "FORKCHOICE: Adding attestation of validator: {:?} for block: {}", + "Adding attestation of validator: {:?} for block: {}", validator_index, target_block_root ); @@ -149,10 +149,7 @@ impl ForkChoice for SlowLMDGhost { .or_insert_with(|| *target_block_root); // if we already have a value if attestation_target != target_block_root { - trace!( - "FORKCHOICE: Old attestation found: {:?}", - attestation_target - ); + trace!("Old attestation found: {:?}", attestation_target); // get the height of the target block let block_height = self .block_store @@ -170,7 +167,7 @@ impl ForkChoice for SlowLMDGhost { .height(spec.genesis_slot); // update the attestation only if the new target is higher if past_block_height < block_height { - trace!("FORKCHOICE: Updating old attestation"); + trace!("Updating old attestation"); *attestation_target = *target_block_root; } } @@ -183,7 +180,7 @@ impl ForkChoice for SlowLMDGhost { justified_block_start: &Hash256, spec: &ChainSpec, ) -> Result { - debug!("FORKCHOICE: Running LMD Ghost Fork-choice rule"); + debug!("Running LMD Ghost Fork-choice rule"); let start = self .block_store .get_deserialized(&justified_block_start)? @@ -196,7 +193,7 @@ impl ForkChoice for SlowLMDGhost { let mut head_hash = *justified_block_start; loop { - debug!("FORKCHOICE: Iteration for block: {}", head_hash); + debug!("Iteration for block: {}", head_hash); let children = match self.children.get(&head_hash) { Some(children) => children, @@ -206,20 +203,16 @@ impl ForkChoice for SlowLMDGhost { // if we only have one child, use it if children.len() == 1 { - trace!("FORKCHOICE: Single child found."); + trace!("Single child found."); head_hash = children[0]; continue; } - trace!("FORKCHOICE: Children found: {:?}", children); + trace!("Children found: {:?}", children); let mut head_vote_count = 0; for child_hash in children { let vote_count = self.get_vote_count(&latest_votes, &child_hash)?; - trace!( - "FORKCHOICE: Vote count for child: {} is: {}", - child_hash, - vote_count - ); + trace!("Vote count for child: {} is: {}", child_hash, vote_count); if vote_count > head_vote_count { head_hash = *child_hash; From efa8aa19e73f98cdd085cf00fff951bcbf5da3d6 Mon Sep 17 00:00:00 2001 From: Age Manning Date: Wed, 20 Feb 2019 12:52:03 +1100 Subject: [PATCH 14/14] Corrects small comments. --- eth2/fork_choice/src/bitwise_lmd_ghost.rs | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/eth2/fork_choice/src/bitwise_lmd_ghost.rs b/eth2/fork_choice/src/bitwise_lmd_ghost.rs index c467545ea..e1d246e92 100644 --- a/eth2/fork_choice/src/bitwise_lmd_ghost.rs +++ b/eth2/fork_choice/src/bitwise_lmd_ghost.rs @@ -201,13 +201,14 @@ where None } - // Finds the best child, splitting children into a binary tree, based on their hashes + // Finds the best child, splitting children into a binary tree, based on their hashes (Bitwise + // LMD Ghost) fn choose_best_child(&self, votes: &HashMap) -> Option { if votes.is_empty() { return None; } let mut bitmask: BitVec = BitVec::new(); - // loop through bytes then bits + // loop through all bits for bit in 0..=256 { let mut zero_votes = 0; let mut one_votes = 0; @@ -216,16 +217,8 @@ where trace!("Child vote length: {}", votes.len()); for (candidate, votes) in votes.iter() { let candidate_bit: BitVec = BitVec::from_bytes(&candidate); - /* - trace!( - "Child: {} in bits: {:?}", - candidate, - candidate_bit - ); - trace!("Current bitmask: {:?}", bitmask); - */ - // if the bitmasks don't match + // if the bitmasks don't match, exclude candidate if !bitmask.iter().eq(candidate_bit.iter().take(bit)) { trace!( "Child: {} was removed in bit: {} with the bitmask: {:?}",