Merge readiness endpoint (#3349)

## Issue Addressed

Resolves final task in https://github.com/sigp/lighthouse/issues/3260

## Proposed Changes

Adds a lighthouse http endpoint to indicate merge readiness.

Blocked on #3339
This commit is contained in:
Pawan Dhananjay 2022-07-21 05:45:39 +00:00
parent e32868458f
commit 612cdb7092
4 changed files with 63 additions and 14 deletions

View File

@ -2,7 +2,7 @@
//! transition. //! transition.
use crate::{BeaconChain, BeaconChainTypes}; use crate::{BeaconChain, BeaconChainTypes};
use execution_layer::Error as EngineError; use serde::{Deserialize, Serialize, Serializer};
use std::fmt; use std::fmt;
use std::fmt::Write; use std::fmt::Write;
use types::*; use types::*;
@ -11,10 +11,13 @@ use types::*;
const SECONDS_IN_A_WEEK: u64 = 604800; const SECONDS_IN_A_WEEK: u64 = 604800;
pub const MERGE_READINESS_PREPARATION_SECONDS: u64 = SECONDS_IN_A_WEEK; pub const MERGE_READINESS_PREPARATION_SECONDS: u64 = SECONDS_IN_A_WEEK;
#[derive(Default, Debug)] #[derive(Default, Debug, Serialize, Deserialize)]
pub struct MergeConfig { pub struct MergeConfig {
#[serde(serialize_with = "serialize_uint256")]
pub terminal_total_difficulty: Option<Uint256>, pub terminal_total_difficulty: Option<Uint256>,
#[serde(skip_serializing_if = "Option::is_none")]
pub terminal_block_hash: Option<ExecutionBlockHash>, pub terminal_block_hash: Option<ExecutionBlockHash>,
#[serde(skip_serializing_if = "Option::is_none")]
pub terminal_block_hash_epoch: Option<Epoch>, pub terminal_block_hash_epoch: Option<Epoch>,
} }
@ -73,15 +76,19 @@ impl MergeConfig {
} }
/// Indicates if a node is ready for the Bellatrix upgrade and subsequent merge transition. /// Indicates if a node is ready for the Bellatrix upgrade and subsequent merge transition.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum MergeReadiness { pub enum MergeReadiness {
/// The node is ready, as far as we can tell. /// The node is ready, as far as we can tell.
Ready { Ready {
config: MergeConfig, config: MergeConfig,
current_difficulty: Result<Uint256, String>, #[serde(serialize_with = "serialize_uint256")]
current_difficulty: Option<Uint256>,
}, },
/// The transition configuration with the EL failed, there might be a problem with /// The transition configuration with the EL failed, there might be a problem with
/// connectivity, authentication or a difference in configuration. /// connectivity, authentication or a difference in configuration.
ExchangeTransitionConfigurationFailed(EngineError), ExchangeTransitionConfigurationFailed { error: String },
/// The EL can be reached and has the correct configuration, however it's not yet synced. /// The EL can be reached and has the correct configuration, however it's not yet synced.
NotSynced, NotSynced,
/// The user has not configured this node to use an execution endpoint. /// The user has not configured this node to use an execution endpoint.
@ -102,11 +109,11 @@ impl fmt::Display for MergeReadiness {
params, current_difficulty params, current_difficulty
) )
} }
MergeReadiness::ExchangeTransitionConfigurationFailed(e) => write!( MergeReadiness::ExchangeTransitionConfigurationFailed { error } => write!(
f, f,
"Could not confirm the transition configuration with the \ "Could not confirm the transition configuration with the \
execution endpoint: {:?}", execution endpoint: {:?}",
e error
), ),
MergeReadiness::NotSynced => write!( MergeReadiness::NotSynced => write!(
f, f,
@ -145,7 +152,9 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
if let Err(e) = el.exchange_transition_configuration(&self.spec).await { if let Err(e) = el.exchange_transition_configuration(&self.spec).await {
// The EL was either unreachable, responded with an error or has a different // The EL was either unreachable, responded with an error or has a different
// configuration. // configuration.
return MergeReadiness::ExchangeTransitionConfigurationFailed(e); return MergeReadiness::ExchangeTransitionConfigurationFailed {
error: format!("{:?}", e),
};
} }
if !el.is_synced_for_notifier().await { if !el.is_synced_for_notifier().await {
@ -153,10 +162,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
return MergeReadiness::NotSynced; return MergeReadiness::NotSynced;
} }
let params = MergeConfig::from_chainspec(&self.spec); let params = MergeConfig::from_chainspec(&self.spec);
let current_difficulty = el let current_difficulty = el.get_current_difficulty().await.ok();
.get_current_difficulty()
.await
.map_err(|_| "Failed to get current difficulty from execution node".to_string());
MergeReadiness::Ready { MergeReadiness::Ready {
config: params, config: params,
current_difficulty, current_difficulty,
@ -167,3 +173,14 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
} }
} }
} }
/// Utility function to serialize a Uint256 as a decimal string.
fn serialize_uint256<S>(val: &Option<Uint256>, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match val {
Some(v) => v.to_string().serialize(s),
None => s.serialize_none(),
}
}

View File

@ -359,7 +359,7 @@ async fn merge_readiness_logging<T: BeaconChainTypes>(
"terminal_total_difficulty" => %ttd, "terminal_total_difficulty" => %ttd,
"current_difficulty" => current_difficulty "current_difficulty" => current_difficulty
.map(|d| d.to_string()) .map(|d| d.to_string())
.unwrap_or_else(|_| "??".into()), .unwrap_or_else(|| "??".into()),
) )
} }
MergeConfig { MergeConfig {
@ -382,7 +382,7 @@ async fn merge_readiness_logging<T: BeaconChainTypes>(
"config" => ?other "config" => ?other
), ),
}, },
readiness @ MergeReadiness::ExchangeTransitionConfigurationFailed(_) => { readiness @ MergeReadiness::ExchangeTransitionConfigurationFailed { error: _ } => {
error!( error!(
log, log,
"Not ready for merge"; "Not ready for merge";

View File

@ -2887,6 +2887,18 @@ pub fn serve<T: BeaconChainTypes>(
}) })
}); });
// GET lighthouse/merge_readiness
let get_lighthouse_merge_readiness = warp::path("lighthouse")
.and(warp::path("merge_readiness"))
.and(warp::path::end())
.and(chain_filter.clone())
.and_then(|chain: Arc<BeaconChain<T>>| async move {
let merge_readiness = chain.check_merge_readiness().await;
Ok::<_, warp::reject::Rejection>(warp::reply::json(&api_types::GenericResponse::from(
merge_readiness,
)))
});
let get_events = eth1_v1 let get_events = eth1_v1
.and(warp::path("events")) .and(warp::path("events"))
.and(warp::path::end()) .and(warp::path::end())
@ -3015,6 +3027,7 @@ pub fn serve<T: BeaconChainTypes>(
.or(get_lighthouse_block_rewards.boxed()) .or(get_lighthouse_block_rewards.boxed())
.or(get_lighthouse_attestation_performance.boxed()) .or(get_lighthouse_attestation_performance.boxed())
.or(get_lighthouse_block_packing_efficiency.boxed()) .or(get_lighthouse_block_packing_efficiency.boxed())
.or(get_lighthouse_merge_readiness.boxed())
.or(get_events.boxed()), .or(get_events.boxed()),
) )
.or(warp::post().and( .or(warp::post().and(

View File

@ -453,4 +453,23 @@ Caveats:
loading a state on a boundary is most efficient. loading a state on a boundary is most efficient.
[block_reward_src]: [block_reward_src]:
https://github.com/sigp/lighthouse/tree/unstable/common/eth2/src/lighthouse/block_rewards.rs https://github.com/sigp/lighthouse/tree/unstable/common/eth2/src/lighthouse/block_rewards.rs
### `/lighthouse/merge_readiness`
```bash
curl -X GET "http://localhost:5052/lighthouse/merge_readiness"
```
```
{
"data":{
"type":"ready",
"config":{
"terminal_total_difficulty":"6400"
},
"current_difficulty":"4800"
}
}
```