Integrate fork choice into beacon_chain.

- Adds fork_choice to beacon_chain struct.
- Adds add_attestation inside process_free_attestation.
- Adds add_block inside process_block.
- Shifts core fork-choice logic into lib.rs.
This commit is contained in:
Age Manning
2019-02-12 21:49:24 +11:00
parent fb270a5a41
commit eae68865d1
4 changed files with 107 additions and 91 deletions

View File

@@ -23,8 +23,51 @@ pub mod longest_chain;
pub mod optimised_lmd_ghost;
pub mod protolambda_lmd_ghost;
use db::DBError;
use types::{BeaconBlock, Hash256};
/// 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.
/// The main fork choice algorithm is specified in `find_head`.
pub trait ForkChoice {
/// Called when a block has been added. Allows generic block-level data structures to be
/// built for a given fork-choice.
fn add_block(
&mut self,
block: &BeaconBlock,
block_hash: &Hash256,
) -> 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.
fn add_attestation(
&mut self,
validator_index: u64,
target_block_hash: &Hash256,
) -> 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<Hash256, ForkChoiceError>;
}
/// Possible fork choice errors that can occur.
#[derive(Debug, PartialEq)]
pub enum ForkChoiceError {
MissingBeaconBlock(Hash256),
MissingBeaconState(Hash256),
IncorrectBeaconState(Hash256),
CannotFindBestChild,
ChildrenNotFound,
StorageError(String),
}
impl From<DBError> for ForkChoiceError {
fn from(e: DBError) -> ForkChoiceError {
ForkChoiceError::StorageError(e.message)
}
}
/// Fork choice options that are currently implemented.
pub enum ForkChoice {
pub enum ForkChoiceAlgorithms {
/// Chooses the longest chain becomes the head. Not for production.
LongestChain,
/// A simple and highly inefficient implementation of LMD ghost.