lighthouse/beacon_chain/chain/src/lib.rs

82 lines
2.2 KiB
Rust
Raw Normal View History

2018-10-20 05:34:08 +00:00
extern crate types;
extern crate validator_induction;
extern crate validator_shuffling;
2018-10-21 15:18:35 +00:00
mod genesis;
use std::collections::HashMap;
2018-10-20 05:34:08 +00:00
use types::{
ActiveState,
ChainConfig,
CrystallizedState,
2018-10-20 08:02:15 +00:00
Hash256,
2018-10-20 05:34:08 +00:00
};
2018-10-20 08:02:15 +00:00
2018-10-21 19:48:44 +00:00
#[derive(Debug, PartialEq)]
2018-10-21 15:18:35 +00:00
pub enum BeaconChainError {
InvalidGenesis,
DBError(String),
}
2018-10-20 05:34:08 +00:00
2018-10-21 15:18:35 +00:00
pub struct BeaconChain {
pub last_finalized_slot: Option<u64>,
pub canonical_latest_block_hash: Hash256,
pub fork_latest_block_hashes: Vec<Hash256>,
pub active_states: HashMap<Hash256, ActiveState>,
pub crystallized_states: HashMap<Hash256, CrystallizedState>,
2018-10-21 19:48:44 +00:00
pub config: ChainConfig,
2018-10-20 05:34:08 +00:00
}
2018-10-21 15:18:35 +00:00
impl BeaconChain {
pub fn new(config: ChainConfig)
-> Result<Self, BeaconChainError>
2018-10-20 05:34:08 +00:00
{
2018-10-21 19:48:44 +00:00
let (active_state, crystallized_state) = BeaconChain::genesis_states(&config)?;
2018-10-20 08:02:15 +00:00
2018-10-21 15:18:35 +00:00
let canonical_latest_block_hash = Hash256::zero();
let fork_latest_block_hashes = vec![];
let mut active_states = HashMap::new();
let mut crystallized_states = HashMap::new();
2018-10-20 08:02:15 +00:00
2018-10-21 15:18:35 +00:00
active_states.insert(canonical_latest_block_hash, active_state);
crystallized_states.insert(canonical_latest_block_hash, crystallized_state);
2018-10-20 08:02:15 +00:00
2018-10-21 15:18:35 +00:00
Ok(Self{
last_finalized_slot: None,
canonical_latest_block_hash,
fork_latest_block_hashes,
active_states,
crystallized_states,
2018-10-21 19:48:44 +00:00
config,
2018-10-20 08:02:15 +00:00
})
2018-10-20 05:34:08 +00:00
}
}
2018-10-21 15:18:35 +00:00
2018-10-20 05:34:08 +00:00
#[cfg(test)]
mod tests {
2018-10-21 15:18:35 +00:00
use super::*;
2018-10-21 19:48:44 +00:00
use types::ValidatorRegistration;
2018-10-21 15:18:35 +00:00
2018-10-20 05:34:08 +00:00
#[test]
2018-10-21 15:18:35 +00:00
fn test_new_chain() {
2018-10-21 19:48:44 +00:00
let mut config = ChainConfig::standard();
for _ in 0..4 {
config.initial_validators.push(ValidatorRegistration::random())
}
let chain = BeaconChain::new(config.clone()).unwrap();
let (act, cry) = BeaconChain::genesis_states(&config).unwrap();
assert_eq!(chain.last_finalized_slot, None);
assert_eq!(chain.canonical_latest_block_hash, Hash256::zero());
let stored_act = chain.active_states.get(&Hash256::zero()).unwrap();
assert_eq!(act, *stored_act);
let stored_cry = chain.crystallized_states.get(&Hash256::zero()).unwrap();
assert_eq!(cry, *stored_cry);
2018-10-20 05:34:08 +00:00
}
}