Skip to content

Manual finalization endpoint #7059

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion beacon_node/beacon_chain/src/beacon_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ use crate::light_client_optimistic_update_verification::{
Error as LightClientOptimisticUpdateError, VerifiedLightClientOptimisticUpdate,
};
use crate::light_client_server_cache::LightClientServerCache;
use crate::migrate::BackgroundMigrator;
use crate::migrate::{BackgroundMigrator, ManualFinalizationNotification};
use crate::naive_aggregation_pool::{
AggregatedAttestationMap, Error as NaiveAggregationError, NaiveAggregationPool,
SyncContributionAggregateMap,
Expand Down Expand Up @@ -1707,6 +1707,16 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
}
}

pub fn manually_finalize_state(&self, state_root: Hash256, checkpoint: Checkpoint) {
let notif = ManualFinalizationNotification {
state_root: state_root.into(),
checkpoint,
head_tracker: self.head_tracker.clone(),
genesis_block_root: self.genesis_block_root,
};
self.store_migrator.process_manual_finalization(notif)
}

/// Returns an aggregated `Attestation`, if any, that has a matching `attestation.data`.
///
/// The attestation will be obtained from `self.naive_aggregation_pool`.
Expand Down
7 changes: 6 additions & 1 deletion beacon_node/beacon_chain/src/block_verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1782,7 +1782,12 @@ pub fn check_block_is_finalized_checkpoint_or_descendant<
fork_choice: &BeaconForkChoice<T>,
block: B,
) -> Result<B, BlockError> {
if fork_choice.is_finalized_checkpoint_or_descendant(block.parent_root()) {
// If we have a split block newer than finalization then we also ban blocks which are not
// descended from that split block.
let split = chain.store.get_split_info();
if fork_choice.is_finalized_checkpoint_or_descendant(block.parent_root())
&& fork_choice.is_descendant(split.block_root, block.parent_root())
{
Ok(block)
} else {
// If fork choice does *not* consider the parent to be a descendant of the finalized block,
Expand Down
56 changes: 51 additions & 5 deletions beacon_node/beacon_chain/src/migrate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,22 @@ pub enum Notification {
Finalization(FinalizationNotification),
Reconstruction,
PruneBlobs(Epoch),
ManualFinalization(ManualFinalizationNotification),
}

pub struct ManualFinalizationNotification {
pub state_root: BeaconStateHash,
pub checkpoint: Checkpoint,
pub head_tracker: Arc<HeadTracker>,
pub genesis_block_root: Hash256,
}

pub struct FinalizationNotification {
finalized_state_root: BeaconStateHash,
finalized_checkpoint: Checkpoint,
head_tracker: Arc<HeadTracker>,
prev_migration: Arc<Mutex<PrevMigration>>,
genesis_block_root: Hash256,
pub finalized_state_root: BeaconStateHash,
pub finalized_checkpoint: Checkpoint,
pub head_tracker: Arc<HeadTracker>,
pub prev_migration: Arc<Mutex<PrevMigration>>,
pub genesis_block_root: Hash256,
}

impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Hot, Cold> {
Expand Down Expand Up @@ -190,6 +198,10 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
Ok(())
}

pub fn process_manual_finalization(&self, notif: ManualFinalizationNotification) {
let _ = self.send_background_notification(Notification::ManualFinalization(notif));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we ever run store migrator in the foreground other than testing, but probably should support it given we do it for all 3 other notifications, and if we want to test this with BeaconChainHarness, it won't be immediately obvious why this doesn't get run.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. We should do this for the clean version of this PR

}

pub fn process_reconstruction(&self) {
if let Some(Notification::Reconstruction) =
self.send_background_notification(Notification::Reconstruction)
Expand Down Expand Up @@ -289,6 +301,26 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
}
}

fn run_manual_migration(
db: Arc<HotColdDB<E, Hot, Cold>>,
notif: ManualFinalizationNotification,
log: &Logger,
) {
// We create a "dummy" prev migration
let prev_migration = PrevMigration {
epoch: Epoch::new(1),
epochs_per_migration: 2,
};
let notif = FinalizationNotification {
finalized_state_root: notif.state_root,
finalized_checkpoint: notif.checkpoint,
head_tracker: notif.head_tracker,
prev_migration: Arc::new(prev_migration.into()),
genesis_block_root: notif.genesis_block_root,
};
Self::run_migration(db, notif, log);
}

/// Perform the actual work of `process_finalization`.
fn run_migration(
db: Arc<HotColdDB<E, Hot, Cold>>,
Expand Down Expand Up @@ -422,16 +454,27 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
while let Ok(notif) = rx.recv() {
let mut reconstruction_notif = None;
let mut finalization_notif = None;
let mut manual_finalization_notif = None;
let mut prune_blobs_notif = None;
match notif {
Notification::Reconstruction => reconstruction_notif = Some(notif),
Notification::Finalization(fin) => finalization_notif = Some(fin),
Notification::ManualFinalization(fin) => manual_finalization_notif = Some(fin),
Notification::PruneBlobs(dab) => prune_blobs_notif = Some(dab),
}
// Read the rest of the messages in the channel, taking the best of each type.
for notif in rx.try_iter() {
match notif {
Notification::Reconstruction => reconstruction_notif = Some(notif),
Notification::ManualFinalization(fin) => {
if let Some(current) = manual_finalization_notif.as_mut() {
if fin.checkpoint.epoch > current.checkpoint.epoch {
*current = fin;
}
} else {
manual_finalization_notif = Some(fin);
}
}
Notification::Finalization(fin) => {
if let Some(current) = finalization_notif.as_mut() {
if fin.finalized_checkpoint.epoch
Expand All @@ -454,6 +497,9 @@ impl<E: EthSpec, Hot: ItemStore<E>, Cold: ItemStore<E>> BackgroundMigrator<E, Ho
if let Some(fin) = finalization_notif {
Self::run_migration(db.clone(), fin, &log);
}
if let Some(fin) = manual_finalization_notif {
Self::run_manual_migration(db.clone(), fin, &log);
}
if let Some(dab) = prune_blobs_notif {
Self::run_prune_blobs(db.clone(), dab, &log);
}
Expand Down
34 changes: 29 additions & 5 deletions beacon_node/http_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ use tokio_stream::{
};
use types::{
fork_versioned_response::EmptyMetadata, Attestation, AttestationData, AttestationShufflingId,
AttesterSlashing, BeaconStateError, ChainSpec, CommitteeCache, ConfigAndPreset, Epoch, EthSpec,
ForkName, ForkVersionedResponse, Hash256, ProposerPreparationData, ProposerSlashing,
RelativeEpoch, SignedAggregateAndProof, SignedBlindedBeaconBlock, SignedBlsToExecutionChange,
SignedContributionAndProof, SignedValidatorRegistrationData, SignedVoluntaryExit, Slot,
SyncCommitteeMessage, SyncContributionData,
AttesterSlashing, BeaconStateError, ChainSpec, Checkpoint, CommitteeCache, ConfigAndPreset,
Epoch, EthSpec, ForkName, ForkVersionedResponse, Hash256, ProposerPreparationData,
ProposerSlashing, RelativeEpoch, SignedAggregateAndProof, SignedBlindedBeaconBlock,
SignedBlsToExecutionChange, SignedContributionAndProof, SignedValidatorRegistrationData,
SignedVoluntaryExit, Slot, SyncCommitteeMessage, SyncContributionData,
};
use validator::pubkey_to_validator_index;
use version::{
Expand Down Expand Up @@ -4133,6 +4133,29 @@ pub fn serve<T: BeaconChainTypes>(
},
);

// POST lighthouse/finalize
let post_lighthouse_finalize = warp::path("lighthouse")
.and(warp::path("finalize"))
.and(warp::path::end())
.and(warp_utils::json::json())
.and(task_spawner_filter.clone())
.and(chain_filter.clone())
.then(
|request_data: api_types::ManualFinalizationRequestData,
task_spawner: TaskSpawner<T::EthSpec>,
chain: Arc<BeaconChain<T>>| {
task_spawner.blocking_json_task(Priority::P0, move || {
let checkpoint = Checkpoint {
epoch: request_data.epoch,
root: request_data.block_root,
};
chain.manually_finalize_state(request_data.state_root, checkpoint);

Ok(api_types::GenericResponse::from(request_data))
})
},
);

// POST lighthouse/liveness
let post_lighthouse_liveness = warp::path("lighthouse")
.and(warp::path("liveness"))
Expand Down Expand Up @@ -4932,6 +4955,7 @@ pub fn serve<T: BeaconChainTypes>(
.uor(post_lighthouse_block_rewards)
.uor(post_lighthouse_ui_validator_metrics)
.uor(post_lighthouse_ui_validator_info)
.uor(post_lighthouse_finalize)
.recover(warp_utils::reject::handle_rejection),
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,19 @@ impl<T: BeaconChainTypes> NetworkBeaconProcessor<T> {
debug!(self.log, "Finalized or earlier block processed";);
Ok(())
}
BlockError::NotFinalizedDescendant { block_parent_root } => {
debug!(
self.log,
"Not syncing to a chain that conflicts with the canonical or manual finalized checkpoint"
);
Err(ChainSegmentFailed {
message: format!(
"Block with parent_root {} conflicts with our checkpoint state",
block_parent_root
),
peer_action: Some(PeerAction::Fatal),
})
}
BlockError::GenesisBlock => {
debug!(self.log, "Genesis block was processed");
Ok(())
Expand Down
7 changes: 7 additions & 0 deletions common/eth2/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1424,6 +1424,13 @@ pub struct StandardLivenessResponseData {
pub is_live: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ManualFinalizationRequestData {
pub state_root: Hash256,
pub epoch: Epoch,
pub block_root: Hash256,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LivenessRequestData {
pub epoch: Epoch,
Expand Down
5 changes: 5 additions & 0 deletions consensus/fork_choice/src/fork_choice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,11 @@ where
.is_finalized_checkpoint_or_descendant::<E>(block_root)
}

pub fn is_descendant(&self, ancestor_root: Hash256, descendant_root: Hash256) -> bool {
self.proto_array
.is_descendant(ancestor_root, descendant_root)
}

/// Returns `Ok(true)` if `block_root` has been imported optimistically or deemed invalid.
///
/// Returns `Ok(false)` if `block_root`'s execution payload has been elected as fully VALID, if
Expand Down
Loading