mirror of
https://github.com/sigp/lighthouse.git
synced 2026-06-17 02:38:34 +00:00
Merge remote-tracking branch 'origin/unstable' into tree-states
This commit is contained in:
@@ -51,7 +51,7 @@ use crate::{metrics, BeaconChainError};
|
||||
use eth2::types::{
|
||||
EventKind, SseBlock, SseChainReorg, SseFinalizedCheckpoint, SseHead, SseLateHead, SyncDuty,
|
||||
};
|
||||
use execution_layer::ExecutionLayer;
|
||||
use execution_layer::{ExecutionLayer, PayloadStatus};
|
||||
use fork_choice::{AttestationFromBlock, ForkChoice};
|
||||
use futures::channel::mpsc::Sender;
|
||||
use itertools::process_results;
|
||||
@@ -108,6 +108,10 @@ pub const FORK_CHOICE_DB_KEY: Hash256 = Hash256::zero();
|
||||
/// Defines how old a block can be before it's no longer a candidate for the early attester cache.
|
||||
const EARLY_ATTESTER_CACHE_HISTORIC_SLOTS: u64 = 4;
|
||||
|
||||
/// Reported to the user when the justified block has an invalid execution payload.
|
||||
pub const INVALID_JUSTIFIED_PAYLOAD_SHUTDOWN_REASON: &str =
|
||||
"Justified block has an invalid execution payload.";
|
||||
|
||||
/// Defines the behaviour when a block/block-root for a skipped slot is requested.
|
||||
pub enum WhenSlotSkipped {
|
||||
/// If the slot is a skip slot, return `None`.
|
||||
@@ -197,7 +201,7 @@ pub struct HeadInfo {
|
||||
pub genesis_validators_root: Hash256,
|
||||
pub proposer_shuffling_decision_root: Hash256,
|
||||
pub is_merge_transition_complete: bool,
|
||||
pub execution_payload_block_hash: Option<Hash256>,
|
||||
pub execution_payload_block_hash: Option<ExecutionBlockHash>,
|
||||
}
|
||||
|
||||
pub trait BeaconChainTypes: Send + Sync + 'static {
|
||||
@@ -216,15 +220,15 @@ pub enum HeadSafetyStatus {
|
||||
///
|
||||
/// If the block is post-terminal-block, `Some(execution_payload.block_hash)` is included with
|
||||
/// the variant.
|
||||
Safe(Option<Hash256>),
|
||||
Safe(Option<ExecutionBlockHash>),
|
||||
/// The head block execution payload has not yet been verified by an EL.
|
||||
///
|
||||
/// The `execution_payload.block_hash` of the head block is returned.
|
||||
Unsafe(Hash256),
|
||||
Unsafe(ExecutionBlockHash),
|
||||
/// The head block execution payload was deemed to be invalid by an EL.
|
||||
///
|
||||
/// The `execution_payload.block_hash` of the head block is returned.
|
||||
Invalid(Hash256),
|
||||
Invalid(ExecutionBlockHash),
|
||||
}
|
||||
|
||||
pub type BeaconForkChoice<T> = ForkChoice<
|
||||
@@ -2283,7 +2287,7 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
|
||||
.position(|(_root, block)| {
|
||||
block.slot().epoch(T::EthSpec::slots_per_epoch()) > start_epoch
|
||||
})
|
||||
.unwrap_or_else(|| filtered_chain_segment.len());
|
||||
.unwrap_or(filtered_chain_segment.len());
|
||||
|
||||
// Split off the first section blocks that are all either within the current epoch of
|
||||
// the first block. These blocks can all be signature-verified with the same
|
||||
@@ -3128,6 +3132,101 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
|
||||
Ok((block, state))
|
||||
}
|
||||
|
||||
/// This method must be called whenever an execution engine indicates that a payload is
|
||||
/// invalid.
|
||||
///
|
||||
/// If the `latest_root` is known to fork-choice it will be invalidated. If it is not known, an
|
||||
/// error will be returned.
|
||||
///
|
||||
/// If `latest_valid_hash` is `None` or references a block unknown to fork choice, no other
|
||||
/// blocks will be invalidated. If `latest_valid_hash` is a block known to fork choice, all
|
||||
/// blocks between the `latest_root` and the `latest_valid_hash` will be invalidated (which may
|
||||
/// cause further, second-order invalidations).
|
||||
///
|
||||
/// ## Notes
|
||||
///
|
||||
/// Use these rules to set `latest_root`:
|
||||
///
|
||||
/// - When `forkchoiceUpdated` indicates an invalid block, set `latest_root` to be the
|
||||
/// block root that was the head of the chain when `forkchoiceUpdated` was called.
|
||||
/// - When `executePayload` returns an invalid block *during* block import, set
|
||||
/// `latest_root` to be the parent of the beacon block containing the invalid
|
||||
/// payload (because the block containing the payload is not present in fork choice).
|
||||
/// - When `executePayload` returns an invalid block *after* block import, set
|
||||
/// `latest_root` to be root of the beacon block containing the invalid payload.
|
||||
pub fn process_invalid_execution_payload(
|
||||
&self,
|
||||
latest_root: Hash256,
|
||||
latest_valid_hash: Option<ExecutionBlockHash>,
|
||||
) -> Result<(), Error> {
|
||||
debug!(
|
||||
self.log,
|
||||
"Invalid execution payload in block";
|
||||
"latest_valid_hash" => ?latest_valid_hash,
|
||||
"latest_root" => ?latest_root,
|
||||
);
|
||||
|
||||
// Update fork choice.
|
||||
if let Err(e) = self
|
||||
.fork_choice
|
||||
.write()
|
||||
.on_invalid_execution_payload(latest_root, latest_valid_hash)
|
||||
{
|
||||
crit!(
|
||||
self.log,
|
||||
"Failed to process invalid payload";
|
||||
"error" => ?e,
|
||||
"latest_valid_hash" => ?latest_valid_hash,
|
||||
"latest_root" => ?latest_root,
|
||||
);
|
||||
}
|
||||
|
||||
// Run fork choice since it's possible that the payload invalidation might result in a new
|
||||
// head.
|
||||
//
|
||||
// Don't return early though, since invalidating the justified checkpoint might cause an
|
||||
// error here.
|
||||
if let Err(e) = self.fork_choice() {
|
||||
crit!(
|
||||
self.log,
|
||||
"Failed to run fork choice routine";
|
||||
"error" => ?e,
|
||||
);
|
||||
}
|
||||
|
||||
// Atomically obtain the justified root from fork choice.
|
||||
let justified_block = self.fork_choice.read().get_justified_block()?;
|
||||
|
||||
if justified_block.execution_status.is_invalid() {
|
||||
crit!(
|
||||
self.log,
|
||||
"The justified checkpoint is invalid";
|
||||
"msg" => "ensure you are not connected to a malicious network. This error is not \
|
||||
recoverable, please reach out to the lighthouse developers for assistance."
|
||||
);
|
||||
|
||||
let mut shutdown_sender = self.shutdown_sender();
|
||||
if let Err(e) = shutdown_sender.try_send(ShutdownReason::Failure(
|
||||
INVALID_JUSTIFIED_PAYLOAD_SHUTDOWN_REASON,
|
||||
)) {
|
||||
crit!(
|
||||
self.log,
|
||||
"Unable to trigger client shut down";
|
||||
"msg" => "shut down may already be under way",
|
||||
"error" => ?e
|
||||
);
|
||||
}
|
||||
|
||||
// Return an error here to try and prevent progression by upstream functions.
|
||||
return Err(Error::JustifiedPayloadInvalid {
|
||||
justified_root: justified_block.root,
|
||||
execution_block_hash: justified_block.execution_status.block_hash(),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute the fork choice algorithm and enthrone the result as the canonical head.
|
||||
pub fn fork_choice(&self) -> Result<(), Error> {
|
||||
metrics::inc_counter(&metrics::FORK_CHOICE_REQUESTS);
|
||||
@@ -3143,19 +3242,47 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
|
||||
}
|
||||
|
||||
fn fork_choice_internal(&self) -> Result<(), Error> {
|
||||
// Determine the root of the block that is the head of the chain.
|
||||
let beacon_block_root = self
|
||||
.fork_choice
|
||||
.write()
|
||||
.get_head(self.slot()?, &self.spec)?;
|
||||
// Atomically obtain the head block root and the finalized block.
|
||||
let (beacon_block_root, finalized_block) = {
|
||||
let mut fork_choice = self.fork_choice.write();
|
||||
|
||||
// Determine the root of the block that is the head of the chain.
|
||||
let beacon_block_root = fork_choice.get_head(self.slot()?, &self.spec)?;
|
||||
|
||||
(beacon_block_root, fork_choice.get_finalized_block()?)
|
||||
};
|
||||
|
||||
let current_head = self.head_info()?;
|
||||
let old_finalized_checkpoint = current_head.finalized_checkpoint;
|
||||
|
||||
// Exit early if the head hasn't changed.
|
||||
if beacon_block_root == current_head.block_root {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Check to ensure that this finalized block hasn't been marked as invalid.
|
||||
if let ExecutionStatus::Invalid(block_hash) = finalized_block.execution_status {
|
||||
crit!(
|
||||
self.log,
|
||||
"Finalized block has an invalid payload";
|
||||
"msg" => "You must use the `--purge-db` flag to clear the database and restart sync. \
|
||||
You may be on a hostile network.",
|
||||
"block_hash" => ?block_hash
|
||||
);
|
||||
let mut shutdown_sender = self.shutdown_sender();
|
||||
shutdown_sender
|
||||
.try_send(ShutdownReason::Failure(
|
||||
"Finalized block has an invalid execution payload.",
|
||||
))
|
||||
.map_err(BeaconChainError::InvalidFinalizedPayloadShutdownError)?;
|
||||
|
||||
// Exit now, the node is in an invalid state.
|
||||
return Err(Error::InvalidFinalizedPayload {
|
||||
finalized_root: finalized_block.root,
|
||||
execution_block_hash: block_hash,
|
||||
});
|
||||
}
|
||||
|
||||
let lag_timer = metrics::start_timer(&metrics::FORK_CHOICE_SET_HEAD_LAG_TIMES);
|
||||
|
||||
// At this point we know that the new head block is not the same as the previous one
|
||||
@@ -3372,33 +3499,6 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
|
||||
}
|
||||
|
||||
if new_finalized_checkpoint.epoch != old_finalized_checkpoint.epoch {
|
||||
// Check to ensure that this finalized block hasn't been marked as invalid.
|
||||
let finalized_block = self
|
||||
.fork_choice
|
||||
.read()
|
||||
.get_block(&new_finalized_checkpoint.root)
|
||||
.ok_or(BeaconChainError::FinalizedBlockMissingFromForkChoice(
|
||||
new_finalized_checkpoint.root,
|
||||
))?;
|
||||
if let ExecutionStatus::Invalid(block_hash) = finalized_block.execution_status {
|
||||
crit!(
|
||||
self.log,
|
||||
"Finalized block has an invalid payload";
|
||||
"msg" => "You must use the `--purge-db` flag to clear the database and restart sync. \
|
||||
You may be on a hostile network.",
|
||||
"block_hash" => ?block_hash
|
||||
);
|
||||
let mut shutdown_sender = self.shutdown_sender();
|
||||
shutdown_sender
|
||||
.try_send(ShutdownReason::Failure(
|
||||
"Finalized block has an invalid execution payload.",
|
||||
))
|
||||
.map_err(BeaconChainError::InvalidFinalizedPayloadShutdownError)?;
|
||||
|
||||
// Exit now, the node is in an invalid state.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Due to race conditions, it's technically possible that the head we load here is
|
||||
// different to the one earlier in this function.
|
||||
//
|
||||
@@ -3499,69 +3599,119 @@ impl<T: BeaconChainTypes> BeaconChain<T> {
|
||||
// If this is a post-merge block, update the execution layer.
|
||||
if let Some(new_head_execution_block_hash) = new_head_execution_block_hash_opt {
|
||||
if is_merge_transition_complete {
|
||||
let execution_layer = self
|
||||
.execution_layer
|
||||
.clone()
|
||||
.ok_or(Error::ExecutionLayerMissing)?;
|
||||
let store = self.store.clone();
|
||||
let log = self.log.clone();
|
||||
|
||||
// Spawn the update task, without waiting for it to complete.
|
||||
execution_layer.spawn(
|
||||
move |execution_layer| async move {
|
||||
if let Err(e) = Self::update_execution_engine_forkchoice(
|
||||
execution_layer,
|
||||
store,
|
||||
new_finalized_checkpoint.root,
|
||||
new_head_execution_block_hash,
|
||||
)
|
||||
.await
|
||||
{
|
||||
debug!(
|
||||
log,
|
||||
"Failed to update execution head";
|
||||
"error" => ?e
|
||||
);
|
||||
}
|
||||
},
|
||||
"update_execution_engine_forkchoice",
|
||||
)
|
||||
let finalized_execution_block_hash = finalized_block
|
||||
.execution_status
|
||||
.block_hash()
|
||||
.unwrap_or_else(ExecutionBlockHash::zero);
|
||||
if let Err(e) = self.update_execution_engine_forkchoice_blocking(
|
||||
finalized_execution_block_hash,
|
||||
beacon_block_root,
|
||||
new_head_execution_block_hash,
|
||||
) {
|
||||
crit!(
|
||||
self.log,
|
||||
"Failed to update execution head";
|
||||
"error" => ?e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn update_execution_engine_forkchoice(
|
||||
execution_layer: ExecutionLayer,
|
||||
store: BeaconStore<T>,
|
||||
finalized_beacon_block_root: Hash256,
|
||||
head_execution_block_hash: Hash256,
|
||||
pub fn update_execution_engine_forkchoice_blocking(
|
||||
&self,
|
||||
finalized_execution_block_hash: ExecutionBlockHash,
|
||||
head_block_root: Hash256,
|
||||
head_execution_block_hash: ExecutionBlockHash,
|
||||
) -> Result<(), Error> {
|
||||
// Loading the finalized block from the store is not ideal. Perhaps it would be better to
|
||||
// store it on fork-choice so we can do a lookup without hitting the database.
|
||||
//
|
||||
// See: https://github.com/sigp/lighthouse/pull/2627#issuecomment-927537245
|
||||
let finalized_block = store
|
||||
.get_block(&finalized_beacon_block_root)?
|
||||
.ok_or(Error::MissingBeaconBlock(finalized_beacon_block_root))?;
|
||||
|
||||
let finalized_execution_block_hash = finalized_block
|
||||
.message()
|
||||
.body()
|
||||
.execution_payload()
|
||||
.ok()
|
||||
.map(|ep| ep.block_hash)
|
||||
.unwrap_or_else(Hash256::zero);
|
||||
let execution_layer = self
|
||||
.execution_layer
|
||||
.as_ref()
|
||||
.ok_or(Error::ExecutionLayerMissing)?;
|
||||
|
||||
execution_layer
|
||||
.block_on_generic(|_| {
|
||||
self.update_execution_engine_forkchoice_async(
|
||||
finalized_execution_block_hash,
|
||||
head_block_root,
|
||||
head_execution_block_hash,
|
||||
)
|
||||
})
|
||||
.map_err(Error::ForkchoiceUpdate)?
|
||||
}
|
||||
|
||||
pub async fn update_execution_engine_forkchoice_async(
|
||||
&self,
|
||||
finalized_execution_block_hash: ExecutionBlockHash,
|
||||
head_block_root: Hash256,
|
||||
head_execution_block_hash: ExecutionBlockHash,
|
||||
) -> Result<(), Error> {
|
||||
let forkchoice_updated_response = self
|
||||
.execution_layer
|
||||
.as_ref()
|
||||
.ok_or(Error::ExecutionLayerMissing)?
|
||||
.notify_forkchoice_updated(
|
||||
head_execution_block_hash,
|
||||
finalized_execution_block_hash,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(Error::ExecutionForkChoiceUpdateFailed)
|
||||
.map_err(Error::ExecutionForkChoiceUpdateFailed);
|
||||
|
||||
match forkchoice_updated_response {
|
||||
Ok(status) => match &status {
|
||||
PayloadStatus::Valid | PayloadStatus::Syncing => Ok(()),
|
||||
// The specification doesn't list `ACCEPTED` as a valid response to a fork choice
|
||||
// update. This response *seems* innocent enough, so we won't return early with an
|
||||
// error. However, we create a log to bring attention to the issue.
|
||||
PayloadStatus::Accepted => {
|
||||
warn!(
|
||||
self.log,
|
||||
"Fork choice update received ACCEPTED";
|
||||
"msg" => "execution engine provided an unexpected response to a fork \
|
||||
choice update. although this is not a serious issue, please raise \
|
||||
an issue."
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
PayloadStatus::Invalid {
|
||||
latest_valid_hash, ..
|
||||
} => {
|
||||
warn!(
|
||||
self.log,
|
||||
"Fork choice update invalidated payload";
|
||||
"status" => ?status
|
||||
);
|
||||
// The execution engine has stated that all blocks between the
|
||||
// `head_execution_block_hash` and `latest_valid_hash` are invalid.
|
||||
self.process_invalid_execution_payload(
|
||||
head_block_root,
|
||||
Some(*latest_valid_hash),
|
||||
)?;
|
||||
|
||||
Err(BeaconChainError::ExecutionForkChoiceUpdateInvalid { status })
|
||||
}
|
||||
PayloadStatus::InvalidTerminalBlock { .. }
|
||||
| PayloadStatus::InvalidBlockHash { .. } => {
|
||||
warn!(
|
||||
self.log,
|
||||
"Fork choice update invalidated payload";
|
||||
"status" => ?status
|
||||
);
|
||||
// The execution engine has stated that the head block is invalid, however it
|
||||
// hasn't returned a latest valid ancestor.
|
||||
//
|
||||
// Using a `None` latest valid ancestor will result in only the head block
|
||||
// being invalidated (no ancestors).
|
||||
self.process_invalid_execution_payload(head_block_root, None)?;
|
||||
|
||||
Err(BeaconChainError::ExecutionForkChoiceUpdateInvalid { status })
|
||||
}
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the status of the current head block, regarding the validity of the execution
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
//! ```
|
||||
use crate::beacon_snapshot::PreProcessingSnapshot;
|
||||
use crate::execution_payload::{
|
||||
execute_payload, validate_execution_payload_for_gossip, validate_merge_block,
|
||||
notify_new_payload, validate_execution_payload_for_gossip, validate_merge_block,
|
||||
};
|
||||
use crate::validator_monitor::HISTORIC_EPOCHS as VALIDATOR_MONITOR_HISTORIC_EPOCHS;
|
||||
use crate::validator_pubkey_cache::ValidatorPubkeyCache;
|
||||
@@ -51,6 +51,7 @@ use crate::{
|
||||
metrics, BeaconChain, BeaconChainError, BeaconChainTypes,
|
||||
};
|
||||
use eth2::types::EventKind;
|
||||
use execution_layer::PayloadStatus;
|
||||
use fork_choice::{ForkChoice, ForkChoiceStore, PayloadVerificationStatus};
|
||||
use parking_lot::RwLockReadGuard;
|
||||
use proto_array::Block as ProtoBlock;
|
||||
@@ -72,9 +73,9 @@ use std::io::Write;
|
||||
use store::{Error as DBError, HotColdDB, KeyValueStore, StoreOp};
|
||||
use tree_hash::TreeHash;
|
||||
use types::{
|
||||
BeaconBlockRef, BeaconState, BeaconStateError, ChainSpec, CloneConfig, Epoch, EthSpec, Hash256,
|
||||
InconsistentFork, PublicKey, PublicKeyBytes, RelativeEpoch, SignedBeaconBlock,
|
||||
SignedBeaconBlockHeader, Slot,
|
||||
BeaconBlockRef, BeaconState, BeaconStateError, ChainSpec, CloneConfig, Epoch, EthSpec,
|
||||
ExecutionBlockHash, Hash256, InconsistentFork, PublicKey, PublicKeyBytes, RelativeEpoch,
|
||||
SignedBeaconBlock, SignedBeaconBlockHeader, Slot,
|
||||
};
|
||||
|
||||
/// Maximum block slot number. Block with slots bigger than this constant will NOT be processed.
|
||||
@@ -266,7 +267,7 @@ pub enum ExecutionPayloadError {
|
||||
/// ## Peer scoring
|
||||
///
|
||||
/// The block is invalid and the peer is faulty
|
||||
RejectedByExecutionEngine,
|
||||
RejectedByExecutionEngine { status: PayloadStatus },
|
||||
/// The execution payload timestamp does not match the slot
|
||||
///
|
||||
/// ## Peer scoring
|
||||
@@ -279,7 +280,7 @@ pub enum ExecutionPayloadError {
|
||||
///
|
||||
/// The block is invalid and the peer sent us a block that passes gossip propagation conditions,
|
||||
/// but is invalid upon further verification.
|
||||
InvalidTerminalPoWBlock { parent_hash: Hash256 },
|
||||
InvalidTerminalPoWBlock { parent_hash: ExecutionBlockHash },
|
||||
/// The `TERMINAL_BLOCK_HASH` is set, but the block has not reached the
|
||||
/// `TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH`.
|
||||
///
|
||||
@@ -298,8 +299,8 @@ pub enum ExecutionPayloadError {
|
||||
/// The block is invalid and the peer sent us a block that passes gossip propagation conditions,
|
||||
/// but is invalid upon further verification.
|
||||
InvalidTerminalBlockHash {
|
||||
terminal_block_hash: Hash256,
|
||||
payload_parent_hash: Hash256,
|
||||
terminal_block_hash: ExecutionBlockHash,
|
||||
payload_parent_hash: ExecutionBlockHash,
|
||||
},
|
||||
/// The execution node failed to provide a parent block to a known block. This indicates an
|
||||
/// issue with the execution node.
|
||||
@@ -307,7 +308,7 @@ pub enum ExecutionPayloadError {
|
||||
/// ## Peer scoring
|
||||
///
|
||||
/// The peer is not necessarily invalid.
|
||||
PoWParentMissing(Hash256),
|
||||
PoWParentMissing(ExecutionBlockHash),
|
||||
}
|
||||
|
||||
impl From<execution_layer::Error> for ExecutionPayloadError {
|
||||
@@ -1121,7 +1122,7 @@ impl<'a, T: BeaconChainTypes> FullyVerifiedBlock<'a, T> {
|
||||
//
|
||||
// It is important that this function is called *after* `per_slot_processing`, since the
|
||||
// `randao` may change.
|
||||
let payload_verification_status = execute_payload(chain, &state, block.message())?;
|
||||
let payload_verification_status = notify_new_payload(chain, &state, block.message())?;
|
||||
|
||||
// If the block is sufficiently recent, notify the validator monitor.
|
||||
if let Some(slot) = chain.slot_clock.now() {
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::naive_aggregation_pool::Error as NaiveAggregationError;
|
||||
use crate::observed_aggregates::Error as ObservedAttestationsError;
|
||||
use crate::observed_attesters::Error as ObservedAttestersError;
|
||||
use crate::observed_block_producers::Error as ObservedBlockProducersError;
|
||||
use execution_layer::PayloadStatus;
|
||||
use futures::channel::mpsc::TrySendError;
|
||||
use operation_pool::OpPoolError;
|
||||
use safe_arith::ArithError;
|
||||
@@ -137,12 +138,28 @@ pub enum BeaconChainError {
|
||||
AltairForkDisabled,
|
||||
ExecutionLayerMissing,
|
||||
ExecutionForkChoiceUpdateFailed(execution_layer::Error),
|
||||
ExecutionForkChoiceUpdateInvalid {
|
||||
status: PayloadStatus,
|
||||
},
|
||||
BlockRewardSlotError,
|
||||
BlockRewardAttestationError,
|
||||
BlockRewardSyncError,
|
||||
HeadMissingFromForkChoice(Hash256),
|
||||
FinalizedBlockMissingFromForkChoice(Hash256),
|
||||
InvalidFinalizedPayload {
|
||||
finalized_root: Hash256,
|
||||
execution_block_hash: ExecutionBlockHash,
|
||||
},
|
||||
InvalidFinalizedPayloadShutdownError(TrySendError<ShutdownReason>),
|
||||
JustifiedPayloadInvalid {
|
||||
justified_root: Hash256,
|
||||
execution_block_hash: Option<ExecutionBlockHash>,
|
||||
},
|
||||
ForkchoiceUpdate(execution_layer::Error),
|
||||
FinalizedCheckpointMismatch {
|
||||
head_state: Checkpoint,
|
||||
fork_choice: Hash256,
|
||||
},
|
||||
}
|
||||
|
||||
easy_from_to!(SlotProcessingError, BeaconChainError);
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::{
|
||||
BeaconChain, BeaconChainError, BeaconChainTypes, BlockError, BlockProductionError,
|
||||
ExecutionPayloadError,
|
||||
};
|
||||
use execution_layer::ExecutePayloadResponseStatus;
|
||||
use execution_layer::PayloadStatus;
|
||||
use fork_choice::PayloadVerificationStatus;
|
||||
use proto_array::{Block as ProtoBlock, ExecutionStatus};
|
||||
use slog::debug;
|
||||
@@ -27,11 +27,11 @@ use types::*;
|
||||
///
|
||||
/// ## Specification
|
||||
///
|
||||
/// Equivalent to the `execute_payload` function in the merge Beacon Chain Changes, although it
|
||||
/// Equivalent to the `notify_new_payload` function in the merge Beacon Chain Changes, although it
|
||||
/// contains a few extra checks by running `partially_verify_execution_payload` first:
|
||||
///
|
||||
/// https://github.com/ethereum/consensus-specs/blob/v1.1.5/specs/merge/beacon-chain.md#execute_payload
|
||||
pub fn execute_payload<T: BeaconChainTypes>(
|
||||
/// https://github.com/ethereum/consensus-specs/blob/v1.1.9/specs/bellatrix/beacon-chain.md#notify_new_payload
|
||||
pub fn notify_new_payload<T: BeaconChainTypes>(
|
||||
chain: &BeaconChain<T>,
|
||||
state: &BeaconState<T::EthSpec>,
|
||||
block: BeaconBlockRef<T::EthSpec>,
|
||||
@@ -53,19 +53,33 @@ pub fn execute_payload<T: BeaconChainTypes>(
|
||||
.execution_layer
|
||||
.as_ref()
|
||||
.ok_or(ExecutionPayloadError::NoExecutionConnection)?;
|
||||
let execute_payload_response = execution_layer
|
||||
.block_on(|execution_layer| execution_layer.execute_payload(execution_payload));
|
||||
let new_payload_response = execution_layer
|
||||
.block_on(|execution_layer| execution_layer.notify_new_payload(execution_payload));
|
||||
|
||||
match execute_payload_response {
|
||||
Ok((status, _latest_valid_hash)) => match status {
|
||||
ExecutePayloadResponseStatus::Valid => Ok(PayloadVerificationStatus::Verified),
|
||||
// TODO(merge): invalidate any invalid ancestors of this block in fork choice.
|
||||
ExecutePayloadResponseStatus::Invalid => {
|
||||
Err(ExecutionPayloadError::RejectedByExecutionEngine.into())
|
||||
match new_payload_response {
|
||||
Ok(status) => match status {
|
||||
PayloadStatus::Valid => Ok(PayloadVerificationStatus::Verified),
|
||||
PayloadStatus::Syncing | PayloadStatus::Accepted => {
|
||||
Ok(PayloadVerificationStatus::NotVerified)
|
||||
}
|
||||
PayloadStatus::Invalid {
|
||||
latest_valid_hash, ..
|
||||
} => {
|
||||
// This block has not yet been applied to fork choice, so the latest block that was
|
||||
// imported to fork choice was the parent.
|
||||
let latest_root = block.parent_root();
|
||||
chain.process_invalid_execution_payload(latest_root, Some(latest_valid_hash))?;
|
||||
|
||||
Err(ExecutionPayloadError::RejectedByExecutionEngine { status }.into())
|
||||
}
|
||||
PayloadStatus::InvalidTerminalBlock { .. } | PayloadStatus::InvalidBlockHash { .. } => {
|
||||
// Returning an error here should be sufficient to invalidate the block. We have no
|
||||
// information to indicate its parent is invalid, so no need to run
|
||||
// `BeaconChain::process_invalid_execution_payload`.
|
||||
Err(ExecutionPayloadError::RejectedByExecutionEngine { status }.into())
|
||||
}
|
||||
ExecutePayloadResponseStatus::Syncing => Ok(PayloadVerificationStatus::NotVerified),
|
||||
},
|
||||
Err(_) => Err(ExecutionPayloadError::RejectedByExecutionEngine.into()),
|
||||
Err(e) => Err(ExecutionPayloadError::RequestFailed(e).into()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,7 +103,7 @@ pub fn validate_merge_block<T: BeaconChainTypes>(
|
||||
let block_epoch = block.slot().epoch(T::EthSpec::slots_per_epoch());
|
||||
let execution_payload = block.execution_payload()?;
|
||||
|
||||
if spec.terminal_block_hash != Hash256::zero() {
|
||||
if spec.terminal_block_hash != ExecutionBlockHash::zero() {
|
||||
if block_epoch < spec.terminal_block_hash_activation_epoch {
|
||||
return Err(ExecutionPayloadError::InvalidActivationEpoch {
|
||||
activation_epoch: spec.terminal_block_hash_activation_epoch,
|
||||
@@ -253,7 +267,7 @@ pub async fn prepare_execution_payload<T: BeaconChainTypes>(
|
||||
.ok_or(BlockProductionError::ExecutionLayerMissing)?;
|
||||
|
||||
let parent_hash = if !is_merge_transition_complete(state) {
|
||||
let is_terminal_block_hash_set = spec.terminal_block_hash != Hash256::zero();
|
||||
let is_terminal_block_hash_set = spec.terminal_block_hash != ExecutionBlockHash::zero();
|
||||
let is_activation_epoch_reached =
|
||||
state.current_epoch() >= spec.terminal_block_hash_activation_epoch;
|
||||
|
||||
@@ -304,7 +318,7 @@ pub async fn prepare_execution_payload<T: BeaconChainTypes>(
|
||||
parent_hash,
|
||||
timestamp,
|
||||
random,
|
||||
finalized_block_hash.unwrap_or_else(Hash256::zero),
|
||||
finalized_block_hash.unwrap_or_else(ExecutionBlockHash::zero),
|
||||
proposer_index,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -40,7 +40,7 @@ mod validator_pubkey_cache;
|
||||
pub use self::beacon_chain::{
|
||||
AttestationProcessingOutcome, BeaconChain, BeaconChainTypes, BeaconStore, ChainSegmentResult,
|
||||
ForkChoiceError, HeadInfo, HeadSafetyStatus, StateSkipConfig, WhenSlotSkipped,
|
||||
MAXIMUM_GOSSIP_CLOCK_DISPARITY,
|
||||
INVALID_JUSTIFIED_PAYLOAD_SHUTDOWN_REASON, MAXIMUM_GOSSIP_CLOCK_DISPARITY,
|
||||
};
|
||||
pub use self::beacon_snapshot::BeaconSnapshot;
|
||||
pub use self::chain_config::ChainConfig;
|
||||
|
||||
@@ -421,10 +421,7 @@ impl<T: AggregateMap> NaiveAggregationPool<T> {
|
||||
|
||||
/// Iterate all items in all slots of `self`.
|
||||
pub fn iter(&self) -> impl Iterator<Item = &T::Value> {
|
||||
self.maps
|
||||
.iter()
|
||||
.map(|(_slot, map)| map.get_map().iter().map(|(_key, value)| value))
|
||||
.flatten()
|
||||
self.maps.values().flat_map(|map| map.get_map().values())
|
||||
}
|
||||
|
||||
/// Removes any items with a slot lower than `current_slot` and bars any future
|
||||
|
||||
@@ -635,7 +635,7 @@ pub fn verify_sync_committee_message<T: BeaconChainTypes>(
|
||||
let pubkey = pubkey_cache
|
||||
.get_pubkey_from_pubkey_bytes(pubkey_bytes)
|
||||
.map(Cow::Borrowed)
|
||||
.ok_or_else(|| Error::UnknownValidatorPubkey(*pubkey_bytes))?;
|
||||
.ok_or(Error::UnknownValidatorPubkey(*pubkey_bytes))?;
|
||||
|
||||
let next_slot_epoch = (sync_message.get_slot() + 1).epoch(T::EthSpec::slots_per_epoch());
|
||||
let fork = chain.spec.fork_at_epoch(next_slot_epoch);
|
||||
|
||||
@@ -432,7 +432,7 @@ where
|
||||
spec: chain.spec.clone(),
|
||||
chain: Arc::new(chain),
|
||||
validator_keypairs,
|
||||
shutdown_receiver,
|
||||
shutdown_receiver: Arc::new(Mutex::new(shutdown_receiver)),
|
||||
mock_execution_layer: self.mock_execution_layer,
|
||||
execution_layer_runtime: self.execution_layer_runtime,
|
||||
rng: make_rng(),
|
||||
@@ -449,7 +449,7 @@ pub struct BeaconChainHarness<T: BeaconChainTypes> {
|
||||
|
||||
pub chain: Arc<BeaconChain<T>>,
|
||||
pub spec: ChainSpec,
|
||||
pub shutdown_receiver: Receiver<ShutdownReason>,
|
||||
pub shutdown_receiver: Arc<Mutex<Receiver<ShutdownReason>>>,
|
||||
|
||||
pub mock_execution_layer: Option<MockExecutionLayer<T::EthSpec>>,
|
||||
pub execution_layer_runtime: Option<ExecutionLayerRuntime>,
|
||||
@@ -502,6 +502,17 @@ where
|
||||
epoch.start_slot(E::slots_per_epoch()).into()
|
||||
}
|
||||
|
||||
pub fn shutdown_reasons(&self) -> Vec<ShutdownReason> {
|
||||
let mutex = self.shutdown_receiver.clone();
|
||||
let mut receiver = mutex.lock();
|
||||
std::iter::from_fn(move || match receiver.try_next() {
|
||||
Ok(Some(s)) => Some(s),
|
||||
Ok(None) => panic!("shutdown sender dropped"),
|
||||
Err(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn get_current_state(&self) -> BeaconState<E> {
|
||||
self.chain.head().unwrap().beacon_state
|
||||
}
|
||||
|
||||
@@ -198,14 +198,11 @@ impl MonitoredValidator {
|
||||
/// as the value recorded by the validator monitor ignores skip slots.
|
||||
fn min_inclusion_distance(&self, epoch: &Epoch) -> Option<u64> {
|
||||
let summaries = self.summaries.read();
|
||||
summaries
|
||||
.get(epoch)
|
||||
.map(|summary| {
|
||||
summary
|
||||
.attestation_min_block_inclusion_distance
|
||||
.map(Into::into)
|
||||
})
|
||||
.flatten()
|
||||
summaries.get(epoch).and_then(|summary| {
|
||||
summary
|
||||
.attestation_min_block_inclusion_distance
|
||||
.map(Into::into)
|
||||
})
|
||||
}
|
||||
|
||||
/// Maps `func` across the `self.summaries`.
|
||||
|
||||
@@ -177,9 +177,7 @@ impl<T: BeaconChainTypes> ValidatorPubkeyCache<T> {
|
||||
|
||||
/// Get the `PublicKey` for a validator with `PublicKeyBytes`.
|
||||
pub fn get_pubkey_from_pubkey_bytes(&self, pubkey: &PublicKeyBytes) -> Option<&PublicKey> {
|
||||
self.get_index(pubkey)
|
||||
.map(|index| self.get(index))
|
||||
.flatten()
|
||||
self.get_index(pubkey).and_then(|index| self.get(index))
|
||||
}
|
||||
|
||||
/// Get the public key (in bytes form) for a validator with index `i`.
|
||||
|
||||
Reference in New Issue
Block a user