lighthouse/beacon_node/client/src/lib.rs

219 lines
7.3 KiB
Rust
Raw Normal View History

extern crate slog;
mod beacon_chain_types;
mod client_config;
pub mod error;
pub mod notifier;
2019-03-19 12:47:58 +00:00
use beacon_chain::BeaconChain;
2019-03-19 11:53:51 +00:00
use exit_future::Signal;
2019-03-26 23:36:20 +00:00
use futures::{future::Future, Stream};
use network::Service as NetworkService;
use prometheus::Registry;
2019-03-26 23:36:20 +00:00
use slog::{error, info, o};
use slot_clock::SlotClock;
use std::marker::PhantomData;
use std::sync::Arc;
2019-03-26 23:36:20 +00:00
use std::time::{Duration, Instant};
use tokio::runtime::TaskExecutor;
2019-03-26 23:36:20 +00:00
use tokio::timer::Interval;
pub use beacon_chain::BeaconChainTypes;
2019-06-08 13:46:04 +00:00
pub use beacon_chain_types::ClientType;
2019-06-07 23:44:27 +00:00
pub use beacon_chain_types::InitialiseBeaconChain;
pub use client_config::ClientConfig;
2019-06-08 17:17:03 +00:00
pub use eth2_config::Eth2Config;
2019-05-09 03:35:00 +00:00
/// Main beacon node client service. This provides the connection and initialisation of the clients
/// sub-services in multiple threads.
pub struct Client<T: BeaconChainTypes> {
/// Configuration for the lighthouse client.
2019-06-08 17:17:03 +00:00
_client_config: ClientConfig,
/// The beacon chain for the running client.
beacon_chain: Arc<BeaconChain<T>>,
/// Reference to the network service.
pub network: Arc<NetworkService<T>>,
2019-03-22 05:46:52 +00:00
/// Signal to terminate the RPC server.
pub rpc_exit_signal: Option<Signal>,
2019-05-25 07:25:21 +00:00
/// Signal to terminate the HTTP server.
pub http_exit_signal: Option<Signal>,
2019-03-26 23:36:20 +00:00
/// Signal to terminate the slot timer.
pub slot_timer_exit_signal: Option<Signal>,
/// The clients logger.
log: slog::Logger,
/// Marker to pin the beacon chain generics.
phantom: PhantomData<T>,
}
impl<T> Client<T>
where
T: BeaconChainTypes + InitialiseBeaconChain<T> + Clone + 'static,
{
/// Generate an instance of the client. Spawn and link all internal sub-processes.
pub fn new(
2019-06-08 17:17:03 +00:00
client_config: ClientConfig,
eth2_config: Eth2Config,
store: T::Store,
log: slog::Logger,
executor: &TaskExecutor,
) -> error::Result<Self> {
let metrics_registry = Registry::new();
let store = Arc::new(store);
2019-06-08 17:17:03 +00:00
let seconds_per_slot = eth2_config.spec.seconds_per_slot;
// Load a `BeaconChain` from the store, or create a new one if it does not exist.
let beacon_chain = Arc::new(T::initialise_beacon_chain(
store,
2019-06-08 17:17:03 +00:00
eth2_config.spec.clone(),
log.clone(),
));
// Registry all beacon chain metrics with the global registry.
beacon_chain
.metrics
.register(&metrics_registry)
.expect("Failed to registry metrics");
if beacon_chain.read_slot_clock().is_none() {
panic!("Cannot start client before genesis!")
}
// Block starting the client until we have caught the state up to the current slot.
//
// If we don't block here we create an initial scenario where we're unable to process any
// blocks and we're basically useless.
2019-03-26 23:36:20 +00:00
{
let state_slot = beacon_chain.head().beacon_state.slot;
let wall_clock_slot = beacon_chain.read_slot_clock().unwrap();
let slots_since_genesis = beacon_chain.slots_since_genesis().unwrap();
2019-03-26 23:36:20 +00:00
info!(
log,
"Initializing state";
"state_slot" => state_slot,
"wall_clock_slot" => wall_clock_slot,
"slots_since_genesis" => slots_since_genesis,
"catchup_distance" => wall_clock_slot - state_slot,
2019-03-26 23:36:20 +00:00
);
}
do_state_catchup(&beacon_chain, &log);
info!(
log,
"State initialized";
"state_slot" => beacon_chain.head().beacon_state.slot,
"wall_clock_slot" => beacon_chain.read_slot_clock().unwrap(),
);
2019-03-26 23:36:20 +00:00
// Start the network service, libp2p and syncing threads
// TODO: Add beacon_chain reference to network parameters
2019-06-08 17:17:03 +00:00
let network_config = &client_config.network;
let network_logger = log.new(o!("Service" => "Network"));
let (network, network_send) = NetworkService::new(
beacon_chain.clone(),
network_config,
executor,
network_logger,
)?;
2019-03-19 12:47:58 +00:00
// spawn the RPC server
2019-06-08 17:17:03 +00:00
let rpc_exit_signal = if client_config.rpc.enabled {
2019-04-03 05:23:09 +00:00
Some(rpc::start_server(
2019-06-08 17:17:03 +00:00
&client_config.rpc,
2019-03-22 05:46:52 +00:00
executor,
network_send.clone(),
2019-03-22 05:46:52 +00:00
beacon_chain.clone(),
&log,
2019-04-03 05:23:09 +00:00
))
} else {
None
};
2019-03-19 12:47:58 +00:00
// Start the `http_server` service.
//
// Note: presently we are ignoring the config and _always_ starting a HTTP server.
2019-06-08 17:17:03 +00:00
let http_exit_signal = if client_config.http.enabled {
2019-05-28 03:50:51 +00:00
Some(http_server::start_service(
2019-06-08 17:17:03 +00:00
&client_config.http,
2019-05-28 03:50:51 +00:00
executor,
network_send,
beacon_chain.clone(),
2019-06-08 17:17:03 +00:00
client_config.db_path().expect("unable to read datadir"),
metrics_registry,
2019-05-28 03:50:51 +00:00
&log,
))
} else {
None
};
2019-03-26 23:36:20 +00:00
let (slot_timer_exit_signal, exit) = exit_future::signal();
if let Ok(Some(duration_to_next_slot)) = beacon_chain.slot_clock.duration_to_next_slot() {
// set up the validator work interval - start at next slot and proceed every slot
let interval = {
// Set the interval to start at the next slot, and every slot after
let slot_duration = Duration::from_secs(seconds_per_slot);
2019-03-26 23:36:20 +00:00
//TODO: Handle checked add correctly
Interval::new(Instant::now() + duration_to_next_slot, slot_duration)
};
let chain = beacon_chain.clone();
let log = log.new(o!("Service" => "SlotTimer"));
executor.spawn(
exit.until(
interval
.for_each(move |_| {
do_state_catchup(&chain, &log);
2019-03-26 23:36:20 +00:00
Ok(())
})
.map_err(|_| ()),
)
.map(|_| ()),
);
}
Ok(Client {
2019-06-08 17:17:03 +00:00
_client_config: client_config,
beacon_chain,
2019-05-25 07:25:21 +00:00
http_exit_signal,
2019-03-22 05:46:52 +00:00
rpc_exit_signal,
2019-03-26 23:36:20 +00:00
slot_timer_exit_signal: Some(slot_timer_exit_signal),
log,
2019-03-19 12:20:39 +00:00
network,
phantom: PhantomData,
})
}
}
impl<T: BeaconChainTypes> Drop for Client<T> {
fn drop(&mut self) {
// Save the beacon chain to it's store before dropping.
let _result = self.beacon_chain.persist();
}
}
fn do_state_catchup<T: BeaconChainTypes>(chain: &Arc<BeaconChain<T>>, log: &slog::Logger) {
if let Some(genesis_height) = chain.slots_since_genesis() {
let result = chain.catchup_state();
let common = o!(
"best_slot" => chain.head().beacon_block.slot,
"latest_block_root" => format!("{}", chain.head().beacon_block_root),
"wall_clock_slot" => chain.read_slot_clock().unwrap(),
"state_slot" => chain.head().beacon_state.slot,
"slots_since_genesis" => genesis_height,
);
match result {
Ok(_) => info!(
log,
"NewSlot";
common
),
Err(e) => error!(
log,
"StateCatchupFailed";
"error" => format!("{:?}", e),
common
),
};
}
}