mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-14 10:22:38 +00:00
Eth1 Integration (#542)
* Refactor to cache Eth1Data * Fix merge conflicts and minor refactorings * Rename Eth1Cache to Eth1DataCache * Refactor events subscription * Add deposits module to interface with BeaconChain deposits * Remove utils * Rename to types.rs and add trait constraints to Eth1DataFetcher * Confirm to trait constraints. Make Web3DataFetcher cloneable * Make fetcher object member of deposit and eth1_data cache and other fixes * Fix update_cache function * Move fetch_eth1_data to impl block * Fix deposit tests * Create Eth1 object for interfacing with Beacon chain * Add `run` function for running update_cache and subscribe_deposit_logs tasks * Add logging * Run `cargo fmt` and make tests pass * Convert sync functions to async * Add timeouts to web3 functions * Return futures from cache functions * Add failed chaining of futures * Working cache updation * Clean up tests and `update_cache` function * Refactor `get_eth1_data` functions to work with future returning functions * Refactor eth1 `run` function to work with modified `update_cache` api * Minor changes * Add distance parameter to `update_cache` * Fix tests and other minor fixes * Working integration with cache and deposits * Add merkle_tree construction, proof generation and verification code * Add function to construct and fetch Deposits for BeaconNode * Add error handling * Import ssz * Add error handling to eth1 cache and fix minor errors * Run rustfmt * Fix minor bug * Rename Eth1Error and change to Result<T> * Change deposit fetching mechanism from notification based to poll based * Add deposits from eth1 chain in a given range every `x` blocks * Modify `run` function to accommodate changes * Minor fixes * Fix formatting * Initial commit. web3 api working. * Tidied up lib. Add function for fetching logs. * Refactor with `Eth1DataFetcher` trait * Add parsing for deposit contract logs and get_eth1_data function * Add `get_eth1_votes` function * Refactor to cache Eth1Data * Fix merge conflicts and minor refactorings * Rename Eth1Cache to Eth1DataCache * Refactor events subscription * Add deposits module to interface with BeaconChain deposits * Remove utils * Rename to types.rs and add trait constraints to Eth1DataFetcher * Confirm to trait constraints. Make Web3DataFetcher cloneable * Make fetcher object member of deposit and eth1_data cache and other fixes * Fix update_cache function * Move fetch_eth1_data to impl block * Fix deposit tests * Create Eth1 object for interfacing with Beacon chain * Add `run` function for running update_cache and subscribe_deposit_logs tasks * Add logging * Run `cargo fmt` and make tests pass * Convert sync functions to async * Add timeouts to web3 functions * Return futures from cache functions * Add failed chaining of futures * Working cache updation * Clean up tests and `update_cache` function * Refactor `get_eth1_data` functions to work with future returning functions * Refactor eth1 `run` function to work with modified `update_cache` api * Minor changes * Add distance parameter to `update_cache` * Fix tests and other minor fixes * Working integration with cache and deposits * Add merkle_tree construction, proof generation and verification code * Add function to construct and fetch Deposits for BeaconNode * Add error handling * Import ssz * Add error handling to eth1 cache and fix minor errors * Run rustfmt * Fix minor bug * Rename Eth1Error and change to Result<T> * Change deposit fetching mechanism from notification based to poll based * Add deposits from eth1 chain in a given range every `x` blocks * Modify `run` function to accommodate changes * Minor fixes * Fix formatting * Fix merge issue * Refactor with `Config` struct. Remote `ContractConfig` * Rename eth1_chain crate to eth1 * Rename files and read abi file using `fs::read` * Move eth1 to lib * Remove unnecessary mutability constraint * Add `Web3Backend` for returning actual eth1 data * Refactor `get_eth1_votes` to return a Result * Delete `eth1_chain` crate * Return `Result` from `get_deposits` * Fix range of deposits to return to beacon chain * Add `get_block_height_by_hash` trait function * Add naive method for getting `previous_eth1_distance` * Add eth1 config params to main config * Add instructions for setting up eth1 testing environment * Add build script to fetch deposit contract abi * Contract ABI is part of compiled binary * Fix minor bugs * Move docs to lib * Add timeout to config * Remove print statements * Change warn to error * Fix typos * Removed prints in test and get timeout value from config * Fixed error types * Added logging to web3_fetcher * Refactor for modified web3 api * Fix minor stuff * Add build script * Tidy, hide eth1 integration tests behind flag * Add http crate * Add first stages of eth1_test_rig * Fix deposits on test rig * Fix bug with deposit count method * Add block hash getter to http eth1 * Clean eth1 http crate and tests * Add script to start ganache * Adds deposit tree to eth1-http * Extend deposit tree tests * Tidy tests in eth1-http * Add more detail to get block request * Add block cache to eth1-http * Rename deposit tree to deposit cache * Add inital updating to eth1-http * Tidy updater * Fix compile bugs in tests * Adds an Eth1DataCache builder * Reorg eth1-http files * Add (failing) tests for eth1 updater * Rename files, fix bug in eth1-http * Ensure that ganache timestamps are increasing * Fix bugs with getting eth1data ancestors * Improve eth1 testing, fix bugs * Add truncate method to block cache * Add pruning to block cache update process * Add tests for block pruning * Allow for dropping an expired cache. * Add more comments * Add first compiling version of deposit updater * Add common fn for getting range of required blocks * Add passing deposit update test * Improve tests * Fix block pruning bug * Add tests for running two updates at once * Add updater services to eth1 * Add deposit collection to beacon chain * Add incomplete builder experiments * Add first working version of beacon chain builder * Update test harness to new beacon chain type * Rename builder file, tidy * Add first working client builder * Progress further on client builder * Update becaon node binary to use client builder * Ensure release tests compile * Remove old eth1 crate * Add first pass of new lighthouse binary * Fix websocket server startup * Remove old binary code from beacon_node crate * Add first working beacon node tests * Add genesis crate, new eth1 cache_2 * Add Serivce to Eth1Cache * Refactor with general eth1 improvements * Add passing genesis test * Tidy, add comments * Add more comments to eth1 service * Add further eth1 progress * Fix some bugs with genesis * Fix eth1 bugs, make eth1 linking more efficient * Shift logic in genesis service * Add more comments to genesis service * Add gzip, max request values, timeouts to http * Update testnet parameters to suit goerli testnet * Add ability to vary Fork, fix custom spec * Be more explicit about deposit fork version * Start adding beacon chain eth1 option * Add more flexibility to prod client * Further runtime refactoring * Allow for starting from store * Add bootstrapping to client config * Add remote_beacon_node crate * Update eth1 service for more configurability * Update eth1 tests to use less runtimes * Patch issues with tests using too many files * Move dummy eth1 backend flag * Ensure all tests pass * Add ganache-cli to Dockerfile * Use a special docker hub image for testing * Appease clippy * Move validator client into lighthouse binary * Allow starting with dummy eth1 backend * Improve logging * Fix dummy eth1 backend from cli * Add extra testnet command * Ensure consistent spec in beacon node * Update eth1 rig to work on goerli * Tidy lcli, start adding support for yaml config * Add incomplete YamlConfig struct * Remove efforts at YamlConfig * Add incomplete eth1 voting. Blocked on spec issues * Add (untested) first pass at eth1 vote algo * Add tests for winning vote * Add more tests for eth1 chain * Add more eth1 voting tests * Added more eth1 voting testing * Change test name * Add more tests to eth1 chain * Tidy eth1 generics, add more tests * Improve comments * Tidy beacon_node tests * Tidy, rename JsonRpc.. to Caching.. * Tidy voting logic * Tidy builder docs * Add comments, tidy eth1 * Add more comments to eth1 * Fix bug with winning_vote * Add doc comments to the `ClientBuilder` * Remove commented-out code * Improve `ClientBuilder` docs * Add comments to client config * Add decoding test for `ClientConfig` * Remove unused `DepositSet` struct * Tidy `block_cache` * Remove commented out lines * Remove unused code in `eth1` crate * Remove old validator binary `main.rs` * Tidy, fix tests compile error * Add initial tests for get_deposits * Remove dead code in eth1_test_rig * Update TestingDepositBuilder * Add testing for getting eth1 deposits * Fix duplicate rand dep * Remove dead code * Remove accidentally-added files * Fix comment in eth1_genesis_service * Add .gitignore for eth1_test_rig * Fix bug in eth1_genesis_service * Remove dead code from eth2_config * Fix tabs/spaces in root Cargo.toml * Tidy eth1 crate * Allow for re-use of eth1 service after genesis * Update docs for new CLI * Change README gif * Tidy eth1 http module * Tidy eth1 service * Tidy environment crate * Remove unused file * Tidy, add comments * Remove commented-out code * Address majority of Michael's comments * Address other PR comments * Add link to issue alongside TODO
This commit is contained in:
@@ -1,22 +1,9 @@
|
||||
mod config;
|
||||
mod run;
|
||||
|
||||
use clap::{App, Arg, SubCommand};
|
||||
use config::get_configs;
|
||||
use env_logger::{Builder, Env};
|
||||
use slog::{crit, o, warn, Drain, Level};
|
||||
|
||||
pub const DEFAULT_DATA_DIR: &str = ".lighthouse";
|
||||
pub const CLIENT_CONFIG_FILENAME: &str = "beacon-node.toml";
|
||||
pub const ETH2_CONFIG_FILENAME: &str = "eth2-spec.toml";
|
||||
pub const TESTNET_CONFIG_FILENAME: &str = "testnet.toml";
|
||||
|
||||
fn main() {
|
||||
// debugging output for libp2p and external crates
|
||||
Builder::from_env(Env::default()).init();
|
||||
|
||||
let matches = App::new("Lighthouse")
|
||||
.version(version::version().as_str())
|
||||
pub fn cli_app<'a, 'b>() -> App<'a, 'b> {
|
||||
App::new("Beacon Node")
|
||||
.visible_aliases(&["b", "bn", "beacon", "beacon_node"])
|
||||
.version(crate_version!())
|
||||
.author("Sigma Prime <contact@sigmaprime.io>")
|
||||
.about("Eth 2.0 Client")
|
||||
/*
|
||||
@@ -30,13 +17,6 @@ fn main() {
|
||||
.takes_value(true)
|
||||
.global(true)
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("logfile")
|
||||
.long("logfile")
|
||||
.value_name("FILE")
|
||||
.help("File path where output will be written.")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("network-dir")
|
||||
.long("network-dir")
|
||||
@@ -197,35 +177,44 @@ fn main() {
|
||||
* Eth1 Integration
|
||||
*/
|
||||
.arg(
|
||||
Arg::with_name("eth1-server")
|
||||
.long("eth1-server")
|
||||
.value_name("SERVER")
|
||||
Arg::with_name("dummy-eth1")
|
||||
.long("dummy-eth1")
|
||||
.help("If present, uses an eth1 backend that generates static dummy data.\
|
||||
Identical to the method used at the 2019 Canada interop.")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("eth1-endpoint")
|
||||
.long("eth1-endpoint")
|
||||
.value_name("HTTP-ENDPOINT")
|
||||
.help("Specifies the server for a web3 connection to the Eth1 chain.")
|
||||
.takes_value(true)
|
||||
.default_value("http://localhost:8545")
|
||||
)
|
||||
/*
|
||||
* Database parameters.
|
||||
*/
|
||||
.arg(
|
||||
Arg::with_name("db")
|
||||
.long("db")
|
||||
.value_name("DB")
|
||||
.help("Type of database to use.")
|
||||
Arg::with_name("eth1-follow")
|
||||
.long("eth1-follow")
|
||||
.value_name("BLOCK_COUNT")
|
||||
.help("Specifies how many blocks we should cache behind the eth1 head. A larger number means a smaller cache.")
|
||||
.takes_value(true)
|
||||
.possible_values(&["disk", "memory"])
|
||||
.default_value("disk"),
|
||||
// TODO: set this higher once we're not using testnets all the time.
|
||||
.default_value("0")
|
||||
)
|
||||
/*
|
||||
* Logging.
|
||||
*/
|
||||
.arg(
|
||||
Arg::with_name("debug-level")
|
||||
.long("debug-level")
|
||||
.value_name("LEVEL")
|
||||
.help("The title of the spec constants for chain config.")
|
||||
Arg::with_name("deposit-contract")
|
||||
.long("deposit-contract")
|
||||
.short("e")
|
||||
.value_name("DEPOSIT-CONTRACT")
|
||||
.help("Specifies the deposit contract address on the Eth1 chain.")
|
||||
.takes_value(true)
|
||||
.possible_values(&["info", "debug", "trace", "warn", "error", "crit"])
|
||||
.default_value("trace"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("deposit-contract-deploy")
|
||||
.long("deposit-contract-deploy")
|
||||
.value_name("BLOCK_NUMBER")
|
||||
.help("Specifies the block number that the deposit contract was deployed at.")
|
||||
.takes_value(true)
|
||||
// TODO: set this higher once we're not using testnets all the time.
|
||||
.default_value("0")
|
||||
)
|
||||
/*
|
||||
* The "testnet" sub-command.
|
||||
@@ -234,17 +223,6 @@ fn main() {
|
||||
*/
|
||||
.subcommand(SubCommand::with_name("testnet")
|
||||
.about("Create a new Lighthouse datadir using a testnet strategy.")
|
||||
.arg(
|
||||
Arg::with_name("spec")
|
||||
.short("s")
|
||||
.long("spec")
|
||||
.value_name("TITLE")
|
||||
.help("Specifies the default eth2 spec type. Only effective when creating a new datadir.")
|
||||
.takes_value(true)
|
||||
.required(true)
|
||||
.possible_values(&["mainnet", "minimal", "interop"])
|
||||
.default_value("minimal")
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("eth2-config")
|
||||
.long("eth2-config")
|
||||
@@ -347,68 +325,25 @@ fn main() {
|
||||
* Start a new node, using a genesis state loaded from a YAML file
|
||||
*/
|
||||
.subcommand(SubCommand::with_name("file")
|
||||
.about("Creates a new datadir where the genesis state is read from YAML. May fail to parse \
|
||||
.about("Creates a new datadir where the genesis state is read from file. May fail to parse \
|
||||
a file that was generated to a different spec than that specified by --spec.")
|
||||
.arg(Arg::with_name("format")
|
||||
.value_name("FORMAT")
|
||||
.required(true)
|
||||
.possible_values(&["yaml", "ssz", "json"])
|
||||
.possible_values(&["ssz"])
|
||||
.help("The encoding of the state in the file."))
|
||||
.arg(Arg::with_name("file")
|
||||
.value_name("YAML_FILE")
|
||||
.value_name("FILE")
|
||||
.required(true)
|
||||
.help("A YAML file from which to read the state"))
|
||||
.help("A file from which to read the state"))
|
||||
)
|
||||
/*
|
||||
* `prysm`
|
||||
*
|
||||
* Connect to the Prysmatic Labs testnet.
|
||||
*/
|
||||
.subcommand(SubCommand::with_name("prysm")
|
||||
.about("Connect to the Prysmatic Labs testnet on Goerli.")
|
||||
)
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
// build the initial logger
|
||||
let decorator = slog_term::TermDecorator::new().build();
|
||||
let decorator = logging::AlignedTermDecorator::new(decorator, logging::MAX_MESSAGE_WIDTH);
|
||||
let drain = slog_term::FullFormat::new(decorator).build().fuse();
|
||||
let drain = slog_async::Async::new(drain).build();
|
||||
|
||||
let drain = match matches.value_of("debug-level") {
|
||||
Some("info") => drain.filter_level(Level::Info),
|
||||
Some("debug") => drain.filter_level(Level::Debug),
|
||||
Some("trace") => drain.filter_level(Level::Trace),
|
||||
Some("warn") => drain.filter_level(Level::Warning),
|
||||
Some("error") => drain.filter_level(Level::Error),
|
||||
Some("crit") => drain.filter_level(Level::Critical),
|
||||
_ => unreachable!("guarded by clap"),
|
||||
};
|
||||
|
||||
let log = slog::Logger::root(drain.fuse(), o!());
|
||||
|
||||
if std::mem::size_of::<usize>() != 8 {
|
||||
crit!(
|
||||
log,
|
||||
"Lighthouse only supports 64bit CPUs";
|
||||
"detected" => format!("{}bit", std::mem::size_of::<usize>() * 8)
|
||||
);
|
||||
}
|
||||
|
||||
warn!(
|
||||
log,
|
||||
"Ethereum 2.0 is pre-release. This software is experimental."
|
||||
);
|
||||
|
||||
let log_clone = log.clone();
|
||||
|
||||
// Load the process-wide configuration.
|
||||
//
|
||||
// May load this from disk or create a new configuration, depending on the CLI flags supplied.
|
||||
let (client_config, eth2_config, log) = match get_configs(&matches, log) {
|
||||
Ok(configs) => configs,
|
||||
Err(e) => {
|
||||
crit!(log_clone, "Failed to load configuration. Exiting"; "error" => e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Start the node using a `tokio` executor.
|
||||
match run::run_beacon_node(client_config, eth2_config, &log) {
|
||||
Ok(_) => {}
|
||||
Err(e) => crit!(log, "Beacon node failed to start"; "reason" => format!("{:}", e)),
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
use clap::ArgMatches;
|
||||
use client::{BeaconChainStartMethod, ClientConfig, Eth1BackendMethod, Eth2Config};
|
||||
use client::{ClientConfig, ClientGenesis, Eth2Config};
|
||||
use eth2_config::{read_from_file, write_to_file};
|
||||
use genesis::recent_genesis_time;
|
||||
use lighthouse_bootstrap::Bootstrapper;
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
use slog::{crit, info, warn, Logger};
|
||||
use std::fs;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use types::{Address, Epoch, Fork};
|
||||
|
||||
pub const DEFAULT_DATA_DIR: &str = ".lighthouse";
|
||||
pub const CLIENT_CONFIG_FILENAME: &str = "beacon-node.toml";
|
||||
@@ -27,12 +29,33 @@ pub fn get_configs(cli_args: &ArgMatches, core_log: Logger) -> Result<Config> {
|
||||
|
||||
let mut builder = ConfigBuilder::new(cli_args, core_log)?;
|
||||
|
||||
if let Some(server) = cli_args.value_of("eth1-server") {
|
||||
builder.set_eth1_backend_method(Eth1BackendMethod::Web3 {
|
||||
server: server.into(),
|
||||
})
|
||||
} else {
|
||||
builder.set_eth1_backend_method(Eth1BackendMethod::Interop)
|
||||
if cli_args.is_present("dummy-eth1") {
|
||||
builder.client_config.dummy_eth1_backend = true;
|
||||
}
|
||||
|
||||
if let Some(val) = cli_args.value_of("eth1-endpoint") {
|
||||
builder.set_eth1_endpoint(val)
|
||||
}
|
||||
|
||||
if let Some(val) = cli_args.value_of("deposit-contract") {
|
||||
builder.set_deposit_contract(
|
||||
val.parse::<Address>()
|
||||
.map_err(|e| format!("Unable to parse deposit-contract address: {:?}", e))?,
|
||||
)
|
||||
}
|
||||
|
||||
if let Some(val) = cli_args.value_of("deposit-contract-deploy") {
|
||||
builder.set_deposit_contract_deploy_block(
|
||||
val.parse::<u64>()
|
||||
.map_err(|e| format!("Unable to parse deposit-contract-deploy: {:?}", e))?,
|
||||
)
|
||||
}
|
||||
|
||||
if let Some(val) = cli_args.value_of("eth1-follow") {
|
||||
builder.set_eth1_follow(
|
||||
val.parse::<u64>()
|
||||
.map_err(|e| format!("Unable to parse follow distance: {:?}", e))?,
|
||||
)
|
||||
}
|
||||
|
||||
match cli_args.subcommand() {
|
||||
@@ -49,7 +72,7 @@ pub fn get_configs(cli_args: &ArgMatches, core_log: Logger) -> Result<Config> {
|
||||
|
||||
// If no primary subcommand was given, start the beacon chain from an existing
|
||||
// database.
|
||||
builder.set_beacon_chain_start_method(BeaconChainStartMethod::Resume);
|
||||
builder.set_genesis(ClientGenesis::Resume);
|
||||
|
||||
// Whilst there is no large testnet or mainnet force the user to specify how they want
|
||||
// to start a new chain (e.g., from a genesis YAML file, another node, etc).
|
||||
@@ -142,7 +165,7 @@ fn process_testnet_subcommand(
|
||||
builder.import_bootstrap_enr_address(server)?;
|
||||
builder.import_bootstrap_eth2_config(server)?;
|
||||
|
||||
builder.set_beacon_chain_start_method(BeaconChainStartMethod::HttpBootstrap {
|
||||
builder.set_genesis(ClientGenesis::RemoteNode {
|
||||
server: server.to_string(),
|
||||
port,
|
||||
})
|
||||
@@ -160,9 +183,11 @@ fn process_testnet_subcommand(
|
||||
.parse::<u64>()
|
||||
.map_err(|e| format!("Unable to parse minutes: {:?}", e))?;
|
||||
|
||||
builder.set_beacon_chain_start_method(BeaconChainStartMethod::RecentGenesis {
|
||||
builder.client_config.dummy_eth1_backend = true;
|
||||
|
||||
builder.set_genesis(ClientGenesis::Interop {
|
||||
validator_count,
|
||||
minutes,
|
||||
genesis_time: recent_genesis_time(minutes),
|
||||
})
|
||||
}
|
||||
("quick", Some(cli_args)) => {
|
||||
@@ -178,13 +203,15 @@ fn process_testnet_subcommand(
|
||||
.parse::<u64>()
|
||||
.map_err(|e| format!("Unable to parse genesis time: {:?}", e))?;
|
||||
|
||||
builder.set_beacon_chain_start_method(BeaconChainStartMethod::Generated {
|
||||
builder.client_config.dummy_eth1_backend = true;
|
||||
|
||||
builder.set_genesis(ClientGenesis::Interop {
|
||||
validator_count,
|
||||
genesis_time,
|
||||
})
|
||||
}
|
||||
("file", Some(cli_args)) => {
|
||||
let file = cli_args
|
||||
let path = cli_args
|
||||
.value_of("file")
|
||||
.ok_or_else(|| "No filename specified")?
|
||||
.parse::<PathBuf>()
|
||||
@@ -195,13 +222,34 @@ fn process_testnet_subcommand(
|
||||
.ok_or_else(|| "No file format specified")?;
|
||||
|
||||
let start_method = match format {
|
||||
"yaml" => BeaconChainStartMethod::Yaml { file },
|
||||
"ssz" => BeaconChainStartMethod::Ssz { file },
|
||||
"json" => BeaconChainStartMethod::Json { file },
|
||||
"ssz" => ClientGenesis::SszFile { path },
|
||||
other => return Err(format!("Unknown genesis file format: {}", other)),
|
||||
};
|
||||
|
||||
builder.set_beacon_chain_start_method(start_method)
|
||||
builder.set_genesis(start_method)
|
||||
}
|
||||
("prysm", Some(_)) => {
|
||||
let mut spec = &mut builder.eth2_config.spec;
|
||||
let mut client_config = &mut builder.client_config;
|
||||
|
||||
spec.min_deposit_amount = 100;
|
||||
spec.max_effective_balance = 3_200_000_000;
|
||||
spec.ejection_balance = 1_600_000_000;
|
||||
spec.effective_balance_increment = 100_000_000;
|
||||
spec.min_genesis_time = 0;
|
||||
spec.genesis_fork = Fork {
|
||||
previous_version: [0; 4],
|
||||
current_version: [0, 0, 0, 2],
|
||||
epoch: Epoch::new(0),
|
||||
};
|
||||
|
||||
client_config.eth1.deposit_contract_address =
|
||||
"0x802dF6aAaCe28B2EEb1656bb18dF430dDC42cc2e".to_string();
|
||||
client_config.eth1.deposit_contract_deploy_block = 1487270;
|
||||
client_config.eth1.follow_distance = 16;
|
||||
client_config.dummy_eth1_backend = false;
|
||||
|
||||
builder.set_genesis(ClientGenesis::DepositContract)
|
||||
}
|
||||
(cmd, Some(_)) => {
|
||||
return Err(format!(
|
||||
@@ -220,8 +268,8 @@ fn process_testnet_subcommand(
|
||||
/// Allows for building a set of configurations based upon `clap` arguments.
|
||||
struct ConfigBuilder {
|
||||
log: Logger,
|
||||
eth2_config: Eth2Config,
|
||||
client_config: ClientConfig,
|
||||
pub eth2_config: Eth2Config,
|
||||
pub client_config: ClientConfig,
|
||||
}
|
||||
|
||||
impl ConfigBuilder {
|
||||
@@ -294,14 +342,24 @@ impl ConfigBuilder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sets the method for starting the beacon chain.
|
||||
pub fn set_beacon_chain_start_method(&mut self, method: BeaconChainStartMethod) {
|
||||
self.client_config.beacon_chain_start_method = method;
|
||||
pub fn set_eth1_endpoint(&mut self, endpoint: &str) {
|
||||
self.client_config.eth1.endpoint = endpoint.to_string();
|
||||
}
|
||||
|
||||
/// Sets the method for starting the beacon chain.
|
||||
pub fn set_eth1_backend_method(&mut self, method: Eth1BackendMethod) {
|
||||
self.client_config.eth1_backend_method = method;
|
||||
pub fn set_deposit_contract(&mut self, deposit_contract: Address) {
|
||||
self.client_config.eth1.deposit_contract_address = format!("{:?}", deposit_contract);
|
||||
}
|
||||
|
||||
pub fn set_deposit_contract_deploy_block(&mut self, eth1_block_number: u64) {
|
||||
self.client_config.eth1.deposit_contract_deploy_block = eth1_block_number;
|
||||
}
|
||||
|
||||
pub fn set_eth1_follow(&mut self, distance: u64) {
|
||||
self.client_config.eth1.follow_distance = distance;
|
||||
}
|
||||
|
||||
pub fn set_genesis(&mut self, method: ClientGenesis) {
|
||||
self.client_config.genesis = method;
|
||||
}
|
||||
|
||||
/// Import the libp2p address for `server` into the list of libp2p nodes to connect with.
|
||||
@@ -540,7 +598,6 @@ impl ConfigBuilder {
|
||||
/// The supplied `cli_args` should be the base-level `clap` cli_args (i.e., not a subcommand
|
||||
/// cli_args).
|
||||
pub fn build(mut self, cli_args: &ArgMatches) -> Result<Config> {
|
||||
self.eth2_config.apply_cli_args(cli_args)?;
|
||||
self.client_config.apply_cli_args(cli_args, &mut self.log)?;
|
||||
|
||||
if let Some(bump) = cli_args.value_of("port-bump") {
|
||||
|
||||
153
beacon_node/src/lib.rs
Normal file
153
beacon_node/src/lib.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
#[macro_use]
|
||||
extern crate clap;
|
||||
|
||||
mod cli;
|
||||
mod config;
|
||||
|
||||
pub use beacon_chain;
|
||||
pub use cli::cli_app;
|
||||
pub use client::{Client, ClientBuilder, ClientConfig, ClientGenesis};
|
||||
pub use eth2_config::Eth2Config;
|
||||
|
||||
use beacon_chain::{
|
||||
builder::Witness, eth1_chain::CachingEth1Backend, events::WebSocketSender,
|
||||
lmd_ghost::ThreadSafeReducedTree, slot_clock::SystemTimeSlotClock,
|
||||
};
|
||||
use clap::ArgMatches;
|
||||
use config::get_configs;
|
||||
use environment::RuntimeContext;
|
||||
use futures::{Future, IntoFuture};
|
||||
use slog::{info, warn};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use store::DiskStore;
|
||||
use types::EthSpec;
|
||||
|
||||
/// A type-alias to the tighten the definition of a production-intended `Client`.
|
||||
pub type ProductionClient<E> = Client<
|
||||
Witness<
|
||||
DiskStore,
|
||||
SystemTimeSlotClock,
|
||||
ThreadSafeReducedTree<DiskStore, E>,
|
||||
CachingEth1Backend<E, DiskStore>,
|
||||
E,
|
||||
WebSocketSender<E>,
|
||||
>,
|
||||
>;
|
||||
|
||||
/// The beacon node `Client` that will be used in production.
|
||||
///
|
||||
/// Generic over some `EthSpec`.
|
||||
///
|
||||
/// ## Notes:
|
||||
///
|
||||
/// Despite being titled `Production...`, this code is not ready for production. The name
|
||||
/// demonstrates an intention, not a promise.
|
||||
pub struct ProductionBeaconNode<E: EthSpec>(ProductionClient<E>);
|
||||
|
||||
impl<E: EthSpec> ProductionBeaconNode<E> {
|
||||
/// Starts a new beacon node `Client` in the given `environment`.
|
||||
///
|
||||
/// Identical to `start_from_client_config`, however the `client_config` is generated from the
|
||||
/// given `matches` and potentially configuration files on the local filesystem or other
|
||||
/// configurations hosted remotely.
|
||||
pub fn new_from_cli<'a, 'b>(
|
||||
mut context: RuntimeContext<E>,
|
||||
matches: &ArgMatches<'b>,
|
||||
) -> impl Future<Item = Self, Error = String> + 'a {
|
||||
let log = context.log.clone();
|
||||
|
||||
// TODO: the eth2 config in the env is being completely ignored.
|
||||
//
|
||||
// See https://github.com/sigp/lighthouse/issues/602
|
||||
get_configs(&matches, log).into_future().and_then(
|
||||
move |(client_config, eth2_config, _log)| {
|
||||
context.eth2_config = eth2_config;
|
||||
Self::new(context, client_config)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts a new beacon node `Client` in the given `environment`.
|
||||
///
|
||||
/// Client behaviour is defined by the given `client_config`.
|
||||
pub fn new(
|
||||
context: RuntimeContext<E>,
|
||||
client_config: ClientConfig,
|
||||
) -> impl Future<Item = Self, Error = String> {
|
||||
let http_eth2_config = context.eth2_config().clone();
|
||||
let spec = context.eth2_config().spec.clone();
|
||||
let genesis_eth1_config = client_config.eth1.clone();
|
||||
let client_genesis = client_config.genesis.clone();
|
||||
let log = context.log.clone();
|
||||
|
||||
client_config
|
||||
.db_path()
|
||||
.ok_or_else(|| "Unable to access database path".to_string())
|
||||
.into_future()
|
||||
.and_then(move |db_path| {
|
||||
Ok(ClientBuilder::new(context.eth_spec_instance.clone())
|
||||
.runtime_context(context)
|
||||
.disk_store(&db_path)?
|
||||
.chain_spec(spec))
|
||||
})
|
||||
.and_then(move |builder| {
|
||||
builder.beacon_chain_builder(client_genesis, genesis_eth1_config)
|
||||
})
|
||||
.and_then(move |builder| {
|
||||
let builder = if client_config.sync_eth1_chain && !client_config.dummy_eth1_backend
|
||||
{
|
||||
info!(
|
||||
log,
|
||||
"Block production enabled";
|
||||
"endpoint" => &client_config.eth1.endpoint,
|
||||
"method" => "json rpc via http"
|
||||
);
|
||||
builder.caching_eth1_backend(client_config.eth1.clone())?
|
||||
} else if client_config.dummy_eth1_backend {
|
||||
warn!(
|
||||
log,
|
||||
"Block production impaired";
|
||||
"reason" => "dummy eth1 backend is enabled"
|
||||
);
|
||||
builder.dummy_eth1_backend()?
|
||||
} else {
|
||||
info!(
|
||||
log,
|
||||
"Block production disabled";
|
||||
"reason" => "no eth1 backend configured"
|
||||
);
|
||||
builder.no_eth1_backend()?
|
||||
};
|
||||
|
||||
let builder = builder
|
||||
.system_time_slot_clock()?
|
||||
.websocket_event_handler(client_config.websocket_server.clone())?
|
||||
.build_beacon_chain()?
|
||||
.libp2p_network(&client_config.network)?
|
||||
.http_server(&client_config, &http_eth2_config)?
|
||||
.grpc_server(&client_config.rpc)?
|
||||
.peer_count_notifier()?
|
||||
.slot_notifier()?;
|
||||
|
||||
Ok(Self(builder.build()))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn into_inner(self) -> ProductionClient<E> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: EthSpec> Deref for ProductionBeaconNode<E> {
|
||||
type Target = ProductionClient<E>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: EthSpec> DerefMut for ProductionBeaconNode<E> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
use client::{error, notifier, Client, ClientConfig, Eth1BackendMethod, Eth2Config};
|
||||
use futures::sync::oneshot;
|
||||
use futures::Future;
|
||||
use slog::{error, info};
|
||||
use std::cell::RefCell;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use store::Store;
|
||||
use store::{DiskStore, MemoryStore};
|
||||
use tokio::runtime::Builder;
|
||||
use tokio::runtime::Runtime;
|
||||
use tokio::runtime::TaskExecutor;
|
||||
use tokio_timer::clock::Clock;
|
||||
use types::{EthSpec, InteropEthSpec, MainnetEthSpec, MinimalEthSpec};
|
||||
|
||||
/// Reads the configuration and initializes a `BeaconChain` with the required types and parameters.
|
||||
///
|
||||
/// Spawns an executor which performs syncing, networking, block production, etc.
|
||||
///
|
||||
/// Blocks the current thread, returning after the `BeaconChain` has exited or a `Ctrl+C`
|
||||
/// signal.
|
||||
pub fn run_beacon_node(
|
||||
client_config: ClientConfig,
|
||||
eth2_config: Eth2Config,
|
||||
log: &slog::Logger,
|
||||
) -> error::Result<()> {
|
||||
let runtime = Builder::new()
|
||||
.name_prefix("main-")
|
||||
.clock(Clock::system())
|
||||
.build()
|
||||
.map_err(|e| format!("{:?}", e))?;
|
||||
|
||||
let executor = runtime.executor();
|
||||
|
||||
let db_path: PathBuf = client_config
|
||||
.db_path()
|
||||
.ok_or_else::<error::Error, _>(|| "Unable to access database path".into())?;
|
||||
let db_type = &client_config.db_type;
|
||||
let spec_constants = eth2_config.spec_constants.clone();
|
||||
|
||||
let other_client_config = client_config.clone();
|
||||
|
||||
info!(
|
||||
log,
|
||||
"Starting beacon node";
|
||||
"p2p_listen_address" => format!("{}", &other_client_config.network.listen_address),
|
||||
"db_type" => &other_client_config.db_type,
|
||||
"spec_constants" => &spec_constants,
|
||||
);
|
||||
|
||||
macro_rules! run_client {
|
||||
($store: ty, $eth_spec: ty) => {
|
||||
run::<$store, $eth_spec>(&db_path, client_config, eth2_config, executor, runtime, log)
|
||||
};
|
||||
}
|
||||
|
||||
if let Eth1BackendMethod::Web3 { .. } = client_config.eth1_backend_method {
|
||||
return Err("Starting from web3 backend is not supported for interop.".into());
|
||||
}
|
||||
|
||||
match (db_type.as_str(), spec_constants.as_str()) {
|
||||
("disk", "minimal") => run_client!(DiskStore, MinimalEthSpec),
|
||||
("disk", "mainnet") => run_client!(DiskStore, MainnetEthSpec),
|
||||
("disk", "interop") => run_client!(DiskStore, InteropEthSpec),
|
||||
("memory", "minimal") => run_client!(MemoryStore, MinimalEthSpec),
|
||||
("memory", "mainnet") => run_client!(MemoryStore, MainnetEthSpec),
|
||||
("memory", "interop") => run_client!(MemoryStore, InteropEthSpec),
|
||||
(db_type, spec) => {
|
||||
error!(log, "Unknown runtime configuration"; "spec_constants" => spec, "db_type" => db_type);
|
||||
Err("Unknown specification and/or db_type.".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the type-generic parts of launching a `BeaconChain`.
|
||||
fn run<S, E>(
|
||||
db_path: &Path,
|
||||
client_config: ClientConfig,
|
||||
eth2_config: Eth2Config,
|
||||
executor: TaskExecutor,
|
||||
mut runtime: Runtime,
|
||||
log: &slog::Logger,
|
||||
) -> error::Result<()>
|
||||
where
|
||||
S: Store + Clone + 'static + OpenDatabase,
|
||||
E: EthSpec,
|
||||
{
|
||||
let store = S::open_database(&db_path)?;
|
||||
|
||||
let client: Client<S, E> =
|
||||
Client::new(client_config, eth2_config, store, log.clone(), &executor)?;
|
||||
|
||||
// run service until ctrl-c
|
||||
let (ctrlc_send, ctrlc_oneshot) = oneshot::channel();
|
||||
let ctrlc_send_c = RefCell::new(Some(ctrlc_send));
|
||||
ctrlc::set_handler(move || {
|
||||
if let Some(ctrlc_send) = ctrlc_send_c.try_borrow_mut().unwrap().take() {
|
||||
ctrlc_send.send(()).expect("Error sending ctrl-c message");
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("Could not set ctrlc handler: {:?}", e))?;
|
||||
|
||||
let (exit_signal, exit) = exit_future::signal();
|
||||
|
||||
notifier::run(&client, executor, exit);
|
||||
|
||||
runtime
|
||||
.block_on(ctrlc_oneshot)
|
||||
.map_err(|e| format!("Ctrlc oneshot failed: {:?}", e))?;
|
||||
|
||||
// perform global shutdown operations.
|
||||
info!(log, "Shutting down..");
|
||||
exit_signal.fire();
|
||||
// shutdown the client
|
||||
// client.exit_signal.fire();
|
||||
drop(client);
|
||||
runtime.shutdown_on_idle().wait().unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A convenience trait, providing a method to open a database.
|
||||
///
|
||||
/// Panics if unable to open the database.
|
||||
pub trait OpenDatabase: Sized {
|
||||
fn open_database(path: &Path) -> error::Result<Self>;
|
||||
}
|
||||
|
||||
impl OpenDatabase for MemoryStore {
|
||||
fn open_database(_path: &Path) -> error::Result<Self> {
|
||||
Ok(MemoryStore::open())
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenDatabase for DiskStore {
|
||||
fn open_database(path: &Path) -> error::Result<Self> {
|
||||
DiskStore::open(path).map_err(|e| format!("Unable to open database: {:?}", e).into())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user