2019-03-02 04:52:33 +00:00
|
|
|
//! The optimised bitwise LMD-GHOST fork choice rule.
|
2019-02-19 00:58:17 +00:00
|
|
|
extern crate bit_vec;
|
|
|
|
|
2019-02-14 01:09:18 +00:00
|
|
|
use crate::{ForkChoice, ForkChoiceError};
|
2019-02-19 00:58:17 +00:00
|
|
|
use bit_vec::BitVec;
|
2019-02-14 01:09:18 +00:00
|
|
|
use db::{
|
|
|
|
stores::{BeaconBlockStore, BeaconStateStore},
|
|
|
|
ClientDB,
|
|
|
|
};
|
2019-02-20 01:15:41 +00:00
|
|
|
use log::{debug, trace};
|
2019-02-14 01:09:18 +00:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use types::{
|
2019-03-17 06:59:29 +00:00
|
|
|
validator_registry::get_active_validator_indices, BeaconBlock, ChainSpec, Hash256, Slot,
|
|
|
|
SlotHeight,
|
2019-02-14 01:09:18 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
//TODO: Pruning - Children
|
|
|
|
//TODO: Handle Syncing
|
|
|
|
|
2019-03-02 04:52:33 +00:00
|
|
|
// 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.
|
|
|
|
|
|
|
|
/// Compute the base-2 logarithm of an integer, floored (rounded down)
|
2019-02-14 01:09:18 +00:00
|
|
|
#[inline]
|
2019-03-03 02:35:15 +00:00
|
|
|
fn log2_int(x: u64) -> u32 {
|
2019-02-19 00:58:17 +00:00
|
|
|
if x == 0 {
|
|
|
|
return 0;
|
|
|
|
}
|
2019-03-03 02:35:15 +00:00
|
|
|
63 - x.leading_zeros()
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
2019-03-03 02:35:15 +00:00
|
|
|
fn power_of_2_below(x: u64) -> u64 {
|
|
|
|
2u64.pow(log2_int(x))
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
2019-02-20 01:36:54 +00:00
|
|
|
/// Stores the necessary data structures to run the optimised bitwise lmd ghost algorithm.
|
2019-02-20 00:56:58 +00:00
|
|
|
pub struct BitwiseLMDGhost<T: ClientDB + Sized> {
|
2019-02-14 01:09:18 +00:00
|
|
|
/// A cache of known ancestors at given heights for a specific block.
|
|
|
|
//TODO: Consider FnvHashMap
|
2019-03-03 02:35:15 +00:00
|
|
|
cache: HashMap<CacheKey<u64>, Hash256>,
|
2019-02-14 01:09:18 +00:00
|
|
|
/// Log lookup table for blocks to their ancestors.
|
|
|
|
//TODO: Verify we only want/need a size 16 log lookup
|
|
|
|
ancestors: Vec<HashMap<Hash256, Hash256>>,
|
|
|
|
/// Stores the children for any given parent.
|
|
|
|
children: HashMap<Hash256, Vec<Hash256>>,
|
|
|
|
/// The latest attestation targets as a map of validator index to block hash.
|
|
|
|
//TODO: Could this be a fixed size vec
|
|
|
|
latest_attestation_targets: HashMap<u64, Hash256>,
|
|
|
|
/// Block storage access.
|
|
|
|
block_store: Arc<BeaconBlockStore<T>>,
|
|
|
|
/// State storage access.
|
|
|
|
state_store: Arc<BeaconStateStore<T>>,
|
2019-02-14 05:53:53 +00:00
|
|
|
max_known_height: SlotHeight,
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
2019-02-20 00:56:58 +00:00
|
|
|
impl<T> BitwiseLMDGhost<T>
|
2019-02-14 01:09:18 +00:00
|
|
|
where
|
|
|
|
T: ClientDB + Sized,
|
|
|
|
{
|
|
|
|
pub fn new(
|
|
|
|
block_store: Arc<BeaconBlockStore<T>>,
|
|
|
|
state_store: Arc<BeaconStateStore<T>>,
|
|
|
|
) -> Self {
|
2019-02-20 00:56:58 +00:00
|
|
|
BitwiseLMDGhost {
|
2019-02-14 01:09:18 +00:00
|
|
|
cache: HashMap::new(),
|
|
|
|
ancestors: vec![HashMap::new(); 16],
|
|
|
|
latest_attestation_targets: HashMap::new(),
|
|
|
|
children: HashMap::new(),
|
2019-02-14 05:53:53 +00:00
|
|
|
max_known_height: SlotHeight::new(0),
|
2019-02-14 01:09:18 +00:00
|
|
|
block_store,
|
|
|
|
state_store,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Finds the latest votes weighted by validator balance. Returns a hashmap of block_hash to
|
|
|
|
/// weighted votes.
|
|
|
|
pub fn get_latest_votes(
|
|
|
|
&self,
|
|
|
|
state_root: &Hash256,
|
2019-02-19 00:58:17 +00:00
|
|
|
block_slot: Slot,
|
2019-02-18 06:42:07 +00:00
|
|
|
spec: &ChainSpec,
|
2019-02-14 01:09:18 +00:00
|
|
|
) -> Result<HashMap<Hash256, u64>, 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
|
|
|
|
let mut latest_votes: HashMap<Hash256, u64> = HashMap::new();
|
|
|
|
// gets the current weighted votes
|
|
|
|
let current_state = self
|
|
|
|
.state_store
|
|
|
|
.get_deserialized(&state_root)?
|
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconState(*state_root))?;
|
|
|
|
|
|
|
|
let active_validator_indices = get_active_validator_indices(
|
2019-02-14 05:53:53 +00:00
|
|
|
¤t_state.validator_registry[..],
|
2019-03-04 06:51:54 +00:00
|
|
|
block_slot.epoch(spec.slots_per_epoch),
|
2019-02-14 01:09:18 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
for index in active_validator_indices {
|
2019-02-18 06:42:07 +00:00
|
|
|
let balance = std::cmp::min(
|
|
|
|
current_state.validator_balances[index],
|
|
|
|
spec.max_deposit_amount,
|
|
|
|
) / spec.fork_choice_balance_increment;
|
2019-02-14 01:09:18 +00:00
|
|
|
if balance > 0 {
|
|
|
|
if let Some(target) = self.latest_attestation_targets.get(&(index as u64)) {
|
|
|
|
*latest_votes.entry(*target).or_insert_with(|| 0) += balance;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Latest votes: {:?}", latest_votes);
|
2019-02-14 01:09:18 +00:00
|
|
|
Ok(latest_votes)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Gets the ancestor at a given height `at_height` of a block specified by `block_hash`.
|
2019-02-18 06:42:07 +00:00
|
|
|
fn get_ancestor(
|
|
|
|
&mut self,
|
|
|
|
block_hash: Hash256,
|
2019-02-19 00:58:17 +00:00
|
|
|
target_height: SlotHeight,
|
2019-02-18 06:42:07 +00:00
|
|
|
spec: &ChainSpec,
|
|
|
|
) -> Option<Hash256> {
|
2019-02-14 01:09:18 +00:00
|
|
|
// return None if we can't get the block from the db.
|
|
|
|
let block_height = {
|
|
|
|
let block_slot = self
|
|
|
|
.block_store
|
|
|
|
.get_deserialized(&block_hash)
|
|
|
|
.ok()?
|
|
|
|
.expect("Should have returned already if None")
|
|
|
|
.slot;
|
|
|
|
|
2019-02-19 00:58:17 +00:00
|
|
|
block_slot.height(spec.genesis_slot)
|
2019-02-14 01:09:18 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// verify we haven't exceeded the block height
|
2019-02-19 00:58:17 +00:00
|
|
|
if target_height >= block_height {
|
|
|
|
if target_height > block_height {
|
2019-02-14 01:09:18 +00:00
|
|
|
return None;
|
|
|
|
} else {
|
|
|
|
return Some(block_hash);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// check if the result is stored in our cache
|
2019-03-03 02:35:15 +00:00
|
|
|
let cache_key = CacheKey::new(&block_hash, target_height.as_u64());
|
2019-02-14 01:09:18 +00:00
|
|
|
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
|
2019-03-03 02:35:15 +00:00
|
|
|
[log2_int((block_height - target_height - 1u64).as_u64()) as usize]
|
2019-02-14 01:09:18 +00:00
|
|
|
.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");
|
2019-02-19 00:58:17 +00:00
|
|
|
self.get_ancestor(*ancestor_lookup, target_height, &spec)
|
2019-02-14 01:09:18 +00:00
|
|
|
} {
|
|
|
|
// add the result to the cache
|
|
|
|
self.cache.insert(cache_key, ancestor);
|
|
|
|
return Some(ancestor);
|
|
|
|
}
|
|
|
|
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
// looks for an obvious block winner given the latest votes for a specific height
|
|
|
|
fn get_clear_winner(
|
|
|
|
&mut self,
|
|
|
|
latest_votes: &HashMap<Hash256, u64>,
|
2019-02-14 05:53:53 +00:00
|
|
|
block_height: SlotHeight,
|
2019-02-18 06:42:07 +00:00
|
|
|
spec: &ChainSpec,
|
2019-02-14 01:09:18 +00:00
|
|
|
) -> Option<Hash256> {
|
|
|
|
// map of vote counts for every hash at this height
|
|
|
|
let mut current_votes: HashMap<Hash256, u64> = HashMap::new();
|
|
|
|
let mut total_vote_count = 0;
|
|
|
|
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Clear winner at block height: {}", block_height);
|
2019-02-14 01:09:18 +00:00
|
|
|
// loop through the latest votes and count all votes
|
|
|
|
// these have already been weighted by balance
|
|
|
|
for (hash, votes) in latest_votes.iter() {
|
2019-02-18 06:42:07 +00:00
|
|
|
if let Some(ancestor) = self.get_ancestor(*hash, block_height, spec) {
|
2019-02-14 01:09:18 +00:00
|
|
|
let current_vote_value = current_votes.get(&ancestor).unwrap_or_else(|| &0);
|
|
|
|
current_votes.insert(ancestor, current_vote_value + *votes);
|
|
|
|
total_vote_count += votes;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Check if there is a clear block winner at this height. If so return it.
|
|
|
|
for (hash, votes) in current_votes.iter() {
|
2019-03-01 03:38:07 +00:00
|
|
|
if *votes > total_vote_count / 2 {
|
2019-02-14 01:09:18 +00:00
|
|
|
// we have a clear winner, return it
|
|
|
|
return Some(*hash);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// didn't find a clear winner
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
2019-02-20 01:52:03 +00:00
|
|
|
// Finds the best child, splitting children into a binary tree, based on their hashes (Bitwise
|
|
|
|
// LMD Ghost)
|
2019-02-14 01:09:18 +00:00
|
|
|
fn choose_best_child(&self, votes: &HashMap<Hash256, u64>) -> Option<Hash256> {
|
2019-02-19 00:58:17 +00:00
|
|
|
if votes.is_empty() {
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let mut bitmask: BitVec = BitVec::new();
|
2019-02-20 01:52:03 +00:00
|
|
|
// loop through all bits
|
2019-02-19 12:06:35 +00:00
|
|
|
for bit in 0..=256 {
|
2019-02-14 01:09:18 +00:00
|
|
|
let mut zero_votes = 0;
|
|
|
|
let mut one_votes = 0;
|
2019-02-19 12:06:35 +00:00
|
|
|
let mut single_candidate = (None, false);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Child vote length: {}", votes.len());
|
2019-02-14 01:09:18 +00:00
|
|
|
for (candidate, votes) in votes.iter() {
|
2019-03-04 06:19:25 +00:00
|
|
|
let candidate_bit: BitVec = BitVec::from_bytes(candidate.as_bytes());
|
2019-02-20 01:52:03 +00:00
|
|
|
|
|
|
|
// if the bitmasks don't match, exclude candidate
|
2019-02-19 00:58:17 +00:00
|
|
|
if !bitmask.iter().eq(candidate_bit.iter().take(bit)) {
|
|
|
|
trace!(
|
2019-02-20 01:39:00 +00:00
|
|
|
"Child: {} was removed in bit: {} with the bitmask: {:?}",
|
2019-02-19 00:58:17 +00:00
|
|
|
candidate,
|
|
|
|
bit,
|
|
|
|
bitmask
|
|
|
|
);
|
2019-02-14 01:09:18 +00:00
|
|
|
continue;
|
|
|
|
}
|
2019-02-19 00:58:17 +00:00
|
|
|
if candidate_bit.get(bit) == Some(false) {
|
2019-02-14 01:09:18 +00:00
|
|
|
zero_votes += votes;
|
|
|
|
} else {
|
|
|
|
one_votes += votes;
|
|
|
|
}
|
|
|
|
|
2019-02-19 12:06:35 +00:00
|
|
|
if single_candidate.0.is_none() {
|
|
|
|
single_candidate.0 = Some(candidate);
|
|
|
|
single_candidate.1 = true;
|
2019-02-14 01:09:18 +00:00
|
|
|
} else {
|
2019-02-19 12:06:35 +00:00
|
|
|
single_candidate.1 = false;
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|
2019-02-19 00:58:17 +00:00
|
|
|
bitmask.push(one_votes > zero_votes);
|
2019-02-19 12:06:35 +00:00
|
|
|
if single_candidate.1 {
|
|
|
|
return Some(*single_candidate.0.expect("Cannot reach this"));
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// should never reach here
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-20 00:56:58 +00:00
|
|
|
impl<T: ClientDB + Sized> ForkChoice for BitwiseLMDGhost<T> {
|
2019-02-14 01:09:18 +00:00
|
|
|
fn add_block(
|
|
|
|
&mut self,
|
|
|
|
block: &BeaconBlock,
|
|
|
|
block_hash: &Hash256,
|
2019-02-18 06:42:07 +00:00
|
|
|
spec: &ChainSpec,
|
2019-02-14 01:09:18 +00:00
|
|
|
) -> Result<(), ForkChoiceError> {
|
|
|
|
// get the height of the parent
|
|
|
|
let parent_height = self
|
|
|
|
.block_store
|
2019-03-17 06:59:29 +00:00
|
|
|
.get_deserialized(&block.previous_block_root)?
|
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconBlock(block.previous_block_root))?
|
|
|
|
.slot
|
2019-02-19 00:58:17 +00:00
|
|
|
.height(spec.genesis_slot);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
2019-03-17 06:59:29 +00:00
|
|
|
let parent_hash = &block.previous_block_root;
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
// add the new block to the children of parent
|
|
|
|
(*self
|
|
|
|
.children
|
2019-03-17 06:59:29 +00:00
|
|
|
.entry(block.previous_block_root)
|
2019-02-14 01:09:18 +00:00
|
|
|
.or_insert_with(|| vec![]))
|
|
|
|
.push(block_hash.clone());
|
|
|
|
|
|
|
|
// build the ancestor data structure
|
|
|
|
for index in 0..16 {
|
|
|
|
if parent_height % (1 << index) == 0 {
|
|
|
|
self.ancestors[index].insert(*block_hash, *parent_hash);
|
|
|
|
} else {
|
|
|
|
// TODO: This is unsafe. Will panic if parent_hash doesn't exist. Using it for debugging
|
|
|
|
let parent_ancestor = self.ancestors[index][parent_hash];
|
|
|
|
self.ancestors[index].insert(*block_hash, parent_ancestor);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// update the max height
|
|
|
|
self.max_known_height = std::cmp::max(self.max_known_height, parent_height + 1);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
fn add_attestation(
|
|
|
|
&mut self,
|
|
|
|
validator_index: u64,
|
|
|
|
target_block_root: &Hash256,
|
2019-02-18 06:42:07 +00:00
|
|
|
spec: &ChainSpec,
|
2019-02-14 01:09:18 +00:00
|
|
|
) -> Result<(), ForkChoiceError> {
|
|
|
|
// simply add the attestation to the latest_attestation_target if the block_height is
|
|
|
|
// larger
|
2019-02-18 06:32:13 +00:00
|
|
|
trace!(
|
2019-02-20 01:39:00 +00:00
|
|
|
"Adding attestation of validator: {:?} for block: {}",
|
2019-02-18 06:32:13 +00:00
|
|
|
validator_index,
|
|
|
|
target_block_root
|
|
|
|
);
|
2019-02-14 01:09:18 +00:00
|
|
|
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 {
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Old attestation found: {:?}", attestation_target);
|
2019-02-14 01:09:18 +00:00
|
|
|
// get the height of the target block
|
|
|
|
let block_height = self
|
|
|
|
.block_store
|
|
|
|
.get_deserialized(&target_block_root)?
|
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*target_block_root))?
|
2019-03-17 06:59:29 +00:00
|
|
|
.slot
|
2019-02-19 00:58:17 +00:00
|
|
|
.height(spec.genesis_slot);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
// get the height of the past target block
|
|
|
|
let past_block_height = self
|
|
|
|
.block_store
|
|
|
|
.get_deserialized(&attestation_target)?
|
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*attestation_target))?
|
2019-03-17 06:59:29 +00:00
|
|
|
.slot
|
2019-02-19 00:58:17 +00:00
|
|
|
.height(spec.genesis_slot);
|
2019-02-14 01:09:18 +00:00
|
|
|
// update the attestation only if the new target is higher
|
|
|
|
if past_block_height < block_height {
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Updating old attestation");
|
2019-02-14 01:09:18 +00:00
|
|
|
*attestation_target = *target_block_root;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Perform lmd_ghost on the current chain to find the head.
|
2019-02-18 06:42:07 +00:00
|
|
|
fn find_head(
|
|
|
|
&mut self,
|
|
|
|
justified_block_start: &Hash256,
|
|
|
|
spec: &ChainSpec,
|
|
|
|
) -> Result<Hash256, ForkChoiceError> {
|
2019-02-19 00:58:17 +00:00
|
|
|
debug!(
|
|
|
|
"Starting optimised fork choice at block: {}",
|
|
|
|
justified_block_start
|
|
|
|
);
|
2019-02-14 01:09:18 +00:00
|
|
|
let block = self
|
|
|
|
.block_store
|
|
|
|
.get_deserialized(&justified_block_start)?
|
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconBlock(*justified_block_start))?;
|
|
|
|
|
2019-03-17 06:59:29 +00:00
|
|
|
let block_slot = block.slot;
|
|
|
|
let state_root = block.state_root;
|
2019-02-19 00:58:17 +00:00
|
|
|
let mut block_height = block_slot.height(spec.genesis_slot);
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
let mut current_head = *justified_block_start;
|
|
|
|
|
2019-02-19 00:58:17 +00:00
|
|
|
let mut latest_votes = self.get_latest_votes(&state_root, block_slot, spec)?;
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
// remove any votes that don't relate to our current head.
|
2019-02-18 06:42:07 +00:00
|
|
|
latest_votes
|
|
|
|
.retain(|hash, _| self.get_ancestor(*hash, block_height, spec) == Some(current_head));
|
2019-02-14 01:09:18 +00:00
|
|
|
|
|
|
|
// begin searching for the head
|
|
|
|
loop {
|
2019-02-19 00:58:17 +00:00
|
|
|
debug!(
|
2019-02-20 01:39:00 +00:00
|
|
|
"Iteration for block: {} with vote length: {}",
|
2019-02-19 00:58:17 +00:00
|
|
|
current_head,
|
|
|
|
latest_votes.len()
|
|
|
|
);
|
2019-02-14 01:09:18 +00:00
|
|
|
// if there are no children, we are done, return the current_head
|
|
|
|
let children = match self.children.get(¤t_head) {
|
|
|
|
Some(children) => children.clone(),
|
2019-03-01 03:38:07 +00:00
|
|
|
None => {
|
|
|
|
debug!("Head found: {}", current_head);
|
|
|
|
return Ok(current_head);
|
|
|
|
}
|
2019-02-14 01:09:18 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// logarithmic lookup blocks to see if there are obvious winners, if so,
|
|
|
|
// progress to the next iteration.
|
|
|
|
let mut step =
|
2019-03-03 02:35:15 +00:00
|
|
|
power_of_2_below(self.max_known_height.saturating_sub(block_height).as_u64()) / 2;
|
2019-02-14 01:09:18 +00:00
|
|
|
while step > 0 {
|
2019-02-19 00:58:17 +00:00
|
|
|
trace!("Current Step: {}", step);
|
2019-02-14 01:09:18 +00:00
|
|
|
if let Some(clear_winner) = self.get_clear_winner(
|
|
|
|
&latest_votes,
|
2019-03-07 05:15:38 +00:00
|
|
|
block_height - (block_height % step) + step,
|
2019-02-18 06:49:05 +00:00
|
|
|
spec,
|
2019-02-14 01:09:18 +00:00
|
|
|
) {
|
|
|
|
current_head = clear_winner;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
step /= 2;
|
|
|
|
}
|
|
|
|
if step > 0 {
|
2019-03-01 03:38:07 +00:00
|
|
|
trace!("Found clear winner: {}", current_head);
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
// if our skip lookup failed and we only have one child, progress to that child
|
|
|
|
else if children.len() == 1 {
|
|
|
|
current_head = children[0];
|
2019-02-18 06:32:13 +00:00
|
|
|
trace!(
|
2019-02-20 01:39:00 +00:00
|
|
|
"Lookup failed, only one child, proceeding to child: {}",
|
2019-02-18 06:32:13 +00:00
|
|
|
current_head
|
|
|
|
);
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
// we need to find the best child path to progress down.
|
|
|
|
else {
|
2019-02-20 01:39:00 +00:00
|
|
|
trace!("Searching for best child");
|
2019-02-14 01:09:18 +00:00
|
|
|
let mut child_votes = HashMap::new();
|
|
|
|
for (voted_hash, vote) in latest_votes.iter() {
|
|
|
|
// if the latest votes correspond to a child
|
2019-02-18 06:42:07 +00:00
|
|
|
if let Some(child) = self.get_ancestor(*voted_hash, block_height + 1, spec) {
|
2019-02-14 01:09:18 +00:00
|
|
|
// add up the votes for each child
|
|
|
|
*child_votes.entry(child).or_insert_with(|| 0) += vote;
|
|
|
|
}
|
|
|
|
}
|
2019-03-14 04:22:45 +00:00
|
|
|
// check if we have votes of children, if not select the smallest hash child
|
|
|
|
if child_votes.is_empty() {
|
|
|
|
current_head = *children
|
|
|
|
.iter()
|
|
|
|
.min_by(|child1, child2| child1.cmp(child2))
|
|
|
|
.expect("Must be children here");
|
|
|
|
trace!(
|
|
|
|
"Children have no votes - smallest hash chosen: {}",
|
|
|
|
current_head
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
// given the votes on the children, find the best child
|
|
|
|
current_head = self
|
|
|
|
.choose_best_child(&child_votes)
|
|
|
|
.ok_or(ForkChoiceError::CannotFindBestChild)?;
|
|
|
|
trace!("Best child found: {}", current_head);
|
|
|
|
}
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
|
2019-02-19 00:58:17 +00:00
|
|
|
// didn't find head yet, proceed to next iteration
|
|
|
|
// update block height
|
|
|
|
block_height = self
|
2019-02-14 01:09:18 +00:00
|
|
|
.block_store
|
|
|
|
.get_deserialized(¤t_head)?
|
2019-02-19 00:58:17 +00:00
|
|
|
.ok_or_else(|| ForkChoiceError::MissingBeaconBlock(current_head))?
|
2019-03-17 06:59:29 +00:00
|
|
|
.slot
|
2019-02-19 00:58:17 +00:00
|
|
|
.height(spec.genesis_slot);
|
2019-02-14 01:09:18 +00:00
|
|
|
// 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
|
2019-02-19 00:58:17 +00:00
|
|
|
for hash in latest_votes.keys() {
|
|
|
|
trace!(
|
2019-02-20 01:39:00 +00:00
|
|
|
"Ancestor for vote: {} at height: {} is: {:?}",
|
2019-02-19 00:58:17 +00:00
|
|
|
hash,
|
|
|
|
block_height,
|
|
|
|
self.get_ancestor(*hash, block_height, spec)
|
|
|
|
);
|
|
|
|
}
|
2019-02-18 06:42:07 +00:00
|
|
|
latest_votes.retain(|hash, _| {
|
|
|
|
self.get_ancestor(*hash, block_height, spec) == Some(current_head)
|
|
|
|
});
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Type for storing blocks in a memory cache. Key is comprised of block-hash plus the height.
|
|
|
|
#[derive(PartialEq, Eq, Hash)]
|
|
|
|
pub struct CacheKey<T> {
|
|
|
|
block_hash: Hash256,
|
|
|
|
block_height: T,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> CacheKey<T> {
|
|
|
|
pub fn new(block_hash: &Hash256, block_height: T) -> Self {
|
|
|
|
CacheKey {
|
|
|
|
block_hash: *block_hash,
|
|
|
|
block_height,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
pub fn test_power_of_2_below() {
|
|
|
|
assert_eq!(power_of_2_below(4), 4);
|
|
|
|
assert_eq!(power_of_2_below(5), 4);
|
|
|
|
assert_eq!(power_of_2_below(7), 4);
|
|
|
|
assert_eq!(power_of_2_below(24), 16);
|
|
|
|
assert_eq!(power_of_2_below(32), 32);
|
|
|
|
assert_eq!(power_of_2_below(33), 32);
|
|
|
|
assert_eq!(power_of_2_below(63), 32);
|
|
|
|
}
|
2019-03-02 04:52:33 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
pub fn test_power_of_2_below_large() {
|
2019-03-03 02:35:15 +00:00
|
|
|
let pow: u64 = 1 << 24;
|
2019-03-02 04:52:33 +00:00
|
|
|
for x in (pow - 20)..(pow + 20) {
|
|
|
|
assert!(power_of_2_below(x) <= x, "{}", x);
|
|
|
|
}
|
|
|
|
}
|
2019-02-14 01:09:18 +00:00
|
|
|
}
|