From ab2b8accd4503011eaeb399acd45988f46fba906 Mon Sep 17 00:00:00 2001 From: Paul Hauner Date: Tue, 3 Sep 2019 15:22:00 +1000 Subject: [PATCH] Add first pass at Eth1Chain trait --- beacon_node/beacon_chain/src/eth1_chain.rs | 61 ++++++++++++++++++++++ beacon_node/beacon_chain/src/lib.rs | 1 + 2 files changed, 62 insertions(+) create mode 100644 beacon_node/beacon_chain/src/eth1_chain.rs diff --git a/beacon_node/beacon_chain/src/eth1_chain.rs b/beacon_node/beacon_chain/src/eth1_chain.rs new file mode 100644 index 000000000..5f148cd9b --- /dev/null +++ b/beacon_node/beacon_chain/src/eth1_chain.rs @@ -0,0 +1,61 @@ +use crate::BeaconChainTypes; +use eth2_hashing::hash; +use std::marker::PhantomData; +use types::{BeaconState, Deposit, DepositData, Eth1Data, EthSpec, Hash256}; + +type Result = std::result::Result; + +pub enum Error { + /// Unable to return an Eth1Data for the given epoch. + EpochUnavailable, + /// An error from the backend service (e.g., the web3 data fetcher). + BackendError(String), +} + +pub trait Eth1Chain { + /// Returns the `Eth1Data` that should be included in a block being produced for the given + /// `state`. + fn eth1_data_for_epoch(&self, beacon_state: &BeaconState) -> Result; + + /// Returns all `Deposits` between `state.eth1_deposit_index` and + /// `state.eth1_data.deposit_count`. + /// + /// # Note: + /// + /// It is possible that not all returned `Deposits` can be included in a block. E.g., there may + /// be more than `MAX_DEPOSIT_COUNT` or the churn may be too high. + fn queued_deposits(&self, beacon_state: &BeaconState) -> Result>; +} + +pub struct InteropEth1Chain { + _phantom: PhantomData, +} + +impl Eth1Chain for InteropEth1Chain { + fn eth1_data_for_epoch(&self, state: &BeaconState) -> Result { + let current_epoch = state.current_epoch(); + let slots_per_voting_period = T::EthSpec::slots_per_eth1_voting_period() as u64; + let current_voting_period: u64 = current_epoch.as_u64() / slots_per_voting_period; + + // TODO: confirm that `int_to_bytes32` is correct. + let deposit_root = hash(&int_to_bytes32(current_voting_period)); + let block_hash = hash(&deposit_root); + + Ok(Eth1Data { + deposit_root: Hash256::from_slice(&deposit_root), + deposit_count: state.eth1_deposit_index, + block_hash: Hash256::from_slice(&block_hash), + }) + } + + fn queued_deposits(&self, beacon_state: &BeaconState) -> Result> { + Ok(vec![]) + } +} + +/// Returns `int` as little-endian bytes with a length of 32. +fn int_to_bytes32(int: u64) -> Vec { + let mut vec = int.to_le_bytes().to_vec(); + vec.resize(32, 0); + vec +} diff --git a/beacon_node/beacon_chain/src/lib.rs b/beacon_node/beacon_chain/src/lib.rs index 9c833f778..25f8b74eb 100644 --- a/beacon_node/beacon_chain/src/lib.rs +++ b/beacon_node/beacon_chain/src/lib.rs @@ -6,6 +6,7 @@ mod beacon_chain; mod beacon_chain_builder; mod checkpoint; mod errors; +mod eth1_chain; mod fork_choice; mod iter; mod metrics;