2022-07-25 08:23:00 +00:00
|
|
|
use crate::ExecutionOptimistic;
|
|
|
|
use beacon_chain::{BeaconChain, BeaconChainError, BeaconChainTypes};
|
2020-09-29 03:46:54 +00:00
|
|
|
use eth2::types::StateId as CoreStateId;
|
2022-07-25 08:23:00 +00:00
|
|
|
use std::fmt;
|
2020-09-29 03:46:54 +00:00
|
|
|
use std::str::FromStr;
|
2022-07-25 08:23:00 +00:00
|
|
|
use types::{BeaconState, Checkpoint, EthSpec, Fork, Hash256, Slot};
|
2020-09-29 03:46:54 +00:00
|
|
|
|
|
|
|
/// Wraps `eth2::types::StateId` and provides common state-access functionality. E.g., reading
|
|
|
|
/// states or parts of states from the database.
|
2022-07-25 08:23:00 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct StateId(pub CoreStateId);
|
2020-09-29 03:46:54 +00:00
|
|
|
|
|
|
|
impl StateId {
|
2022-07-25 08:23:00 +00:00
|
|
|
pub fn from_slot(slot: Slot) -> Self {
|
2020-09-29 03:46:54 +00:00
|
|
|
Self(CoreStateId::Slot(slot))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the state root identified by `self`.
|
|
|
|
pub fn root<T: BeaconChainTypes>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
2022-07-25 08:23:00 +00:00
|
|
|
) -> Result<(Hash256, ExecutionOptimistic), warp::Rejection> {
|
|
|
|
let (slot, execution_optimistic) = match &self.0 {
|
|
|
|
CoreStateId::Head => {
|
|
|
|
let (cached_head, execution_status) = chain
|
|
|
|
.canonical_head
|
|
|
|
.head_and_execution_status()
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
return Ok((
|
|
|
|
cached_head.head_state_root(),
|
2022-07-30 05:08:57 +00:00
|
|
|
execution_status.is_optimistic_or_invalid(),
|
2022-07-25 08:23:00 +00:00
|
|
|
));
|
|
|
|
}
|
|
|
|
CoreStateId::Genesis => return Ok((chain.genesis_state_root, false)),
|
|
|
|
CoreStateId::Finalized => {
|
|
|
|
let finalized_checkpoint =
|
|
|
|
chain.canonical_head.cached_head().finalized_checkpoint();
|
|
|
|
checkpoint_slot_and_execution_optimistic(chain, finalized_checkpoint)?
|
|
|
|
}
|
|
|
|
CoreStateId::Justified => {
|
|
|
|
let justified_checkpoint =
|
|
|
|
chain.canonical_head.cached_head().justified_checkpoint();
|
|
|
|
checkpoint_slot_and_execution_optimistic(chain, justified_checkpoint)?
|
|
|
|
}
|
|
|
|
CoreStateId::Slot(slot) => (
|
|
|
|
*slot,
|
|
|
|
chain
|
2022-07-30 05:08:57 +00:00
|
|
|
.is_optimistic_or_invalid_head()
|
2022-07-25 08:23:00 +00:00
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?,
|
|
|
|
),
|
|
|
|
CoreStateId::Root(root) => {
|
|
|
|
if let Some(hot_summary) = chain
|
|
|
|
.store
|
|
|
|
.load_hot_state_summary(root)
|
|
|
|
.map_err(BeaconChainError::DBError)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?
|
|
|
|
{
|
|
|
|
let execution_optimistic = chain
|
|
|
|
.canonical_head
|
|
|
|
.fork_choice_read_lock()
|
2022-07-30 05:08:57 +00:00
|
|
|
.is_optimistic_or_invalid_block_no_fallback(&hot_summary.latest_block_root)
|
2022-07-25 08:23:00 +00:00
|
|
|
.map_err(BeaconChainError::ForkChoiceError)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
return Ok((*root, execution_optimistic));
|
|
|
|
} else if let Some(_cold_state_slot) = chain
|
|
|
|
.store
|
|
|
|
.load_cold_state_slot(root)
|
|
|
|
.map_err(BeaconChainError::DBError)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?
|
|
|
|
{
|
|
|
|
let fork_choice = chain.canonical_head.fork_choice_read_lock();
|
|
|
|
let finalized_root = fork_choice
|
|
|
|
.cached_fork_choice_view()
|
|
|
|
.finalized_checkpoint
|
|
|
|
.root;
|
|
|
|
let execution_optimistic = fork_choice
|
2022-07-30 05:08:57 +00:00
|
|
|
.is_optimistic_or_invalid_block_no_fallback(&finalized_root)
|
2022-07-25 08:23:00 +00:00
|
|
|
.map_err(BeaconChainError::ForkChoiceError)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
return Ok((*root, execution_optimistic));
|
|
|
|
} else {
|
|
|
|
return Err(warp_utils::reject::custom_not_found(format!(
|
|
|
|
"beacon state for state root {}",
|
|
|
|
root
|
|
|
|
)));
|
|
|
|
}
|
|
|
|
}
|
Use async code when interacting with EL (#3244)
## Overview
This rather extensive PR achieves two primary goals:
1. Uses the finalized/justified checkpoints of fork choice (FC), rather than that of the head state.
2. Refactors fork choice, block production and block processing to `async` functions.
Additionally, it achieves:
- Concurrent forkchoice updates to the EL and cache pruning after a new head is selected.
- Concurrent "block packing" (attestations, etc) and execution payload retrieval during block production.
- Concurrent per-block-processing and execution payload verification during block processing.
- The `Arc`-ification of `SignedBeaconBlock` during block processing (it's never mutated, so why not?):
- I had to do this to deal with sending blocks into spawned tasks.
- Previously we were cloning the beacon block at least 2 times during each block processing, these clones are either removed or turned into cheaper `Arc` clones.
- We were also `Box`-ing and un-`Box`-ing beacon blocks as they moved throughout the networking crate. This is not a big deal, but it's nice to avoid shifting things between the stack and heap.
- Avoids cloning *all the blocks* in *every chain segment* during sync.
- It also has the potential to clean up our code where we need to pass an *owned* block around so we can send it back in the case of an error (I didn't do much of this, my PR is already big enough :sweat_smile:)
- The `BeaconChain::HeadSafetyStatus` struct was removed. It was an old relic from prior merge specs.
For motivation for this change, see https://github.com/sigp/lighthouse/pull/3244#issuecomment-1160963273
## Changes to `canonical_head` and `fork_choice`
Previously, the `BeaconChain` had two separate fields:
```
canonical_head: RwLock<Snapshot>,
fork_choice: RwLock<BeaconForkChoice>
```
Now, we have grouped these values under a single struct:
```
canonical_head: CanonicalHead {
cached_head: RwLock<Arc<Snapshot>>,
fork_choice: RwLock<BeaconForkChoice>
}
```
Apart from ergonomics, the only *actual* change here is wrapping the canonical head snapshot in an `Arc`. This means that we no longer need to hold the `cached_head` (`canonical_head`, in old terms) lock when we want to pull some values from it. This was done to avoid deadlock risks by preventing functions from acquiring (and holding) the `cached_head` and `fork_choice` locks simultaneously.
## Breaking Changes
### The `state` (root) field in the `finalized_checkpoint` SSE event
Consider the scenario where epoch `n` is just finalized, but `start_slot(n)` is skipped. There are two state roots we might in the `finalized_checkpoint` SSE event:
1. The state root of the finalized block, which is `get_block(finalized_checkpoint.root).state_root`.
4. The state root at slot of `start_slot(n)`, which would be the state from (1), but "skipped forward" through any skip slots.
Previously, Lighthouse would choose (2). However, we can see that when [Teku generates that event](https://github.com/ConsenSys/teku/blob/de2b2801c89ef5abf983d6bf37867c37fc47121f/data/beaconrestapi/src/main/java/tech/pegasys/teku/beaconrestapi/handlers/v1/events/EventSubscriptionManager.java#L171-L182) it uses [`getStateRootFromBlockRoot`](https://github.com/ConsenSys/teku/blob/de2b2801c89ef5abf983d6bf37867c37fc47121f/data/provider/src/main/java/tech/pegasys/teku/api/ChainDataProvider.java#L336-L341) which uses (1).
I have switched Lighthouse from (2) to (1). I think it's a somewhat arbitrary choice between the two, where (1) is easier to compute and is consistent with Teku.
## Notes for Reviewers
I've renamed `BeaconChain::fork_choice` to `BeaconChain::recompute_head`. Doing this helped ensure I broke all previous uses of fork choice and I also find it more descriptive. It describes an action and can't be confused with trying to get a reference to the `ForkChoice` struct.
I've changed the ordering of SSE events when a block is received. It used to be `[block, finalized, head]` and now it's `[block, head, finalized]`. It was easier this way and I don't think we were making any promises about SSE event ordering so it's not "breaking".
I've made it so fork choice will run when it's first constructed. I did this because I wanted to have a cached version of the last call to `get_head`. Ensuring `get_head` has been run *at least once* means that the cached values doesn't need to wrapped in an `Option`. This was fairly simple, it just involved passing a `slot` to the constructor so it knows *when* it's being run. When loading a fork choice from the store and a slot clock isn't handy I've just used the `slot` that was saved in the `fork_choice_store`. That seems like it would be a faithful representation of the slot when we saved it.
I added the `genesis_time: u64` to the `BeaconChain`. It's small, constant and nice to have around.
Since we're using FC for the fin/just checkpoints, we no longer get the `0x00..00` roots at genesis. You can see I had to remove a work-around in `ef-tests` here: b56be3bc2. I can't find any reason why this would be an issue, if anything I think it'll be better since the genesis-alias has caught us out a few times (0x00..00 isn't actually a real root). Edit: I did find a case where the `network` expected the 0x00..00 alias and patched it here: 3f26ac3e2.
You'll notice a lot of changes in tests. Generally, tests should be functionally equivalent. Here are the things creating the most diff-noise in tests:
- Changing tests to be `tokio::async` tests.
- Adding `.await` to fork choice, block processing and block production functions.
- Refactor of the `canonical_head` "API" provided by the `BeaconChain`. E.g., `chain.canonical_head.cached_head()` instead of `chain.canonical_head.read()`.
- Wrapping `SignedBeaconBlock` in an `Arc`.
- In the `beacon_chain/tests/block_verification`, we can't use the `lazy_static` `CHAIN_SEGMENT` variable anymore since it's generated with an async function. We just generate it in each test, not so efficient but hopefully insignificant.
I had to disable `rayon` concurrent tests in the `fork_choice` tests. This is because the use of `rayon` and `block_on` was causing a panic.
Co-authored-by: Mac L <mjladson@pm.me>
2022-07-03 05:36:50 +00:00
|
|
|
};
|
2020-09-29 03:46:54 +00:00
|
|
|
|
2022-07-25 08:23:00 +00:00
|
|
|
let root = chain
|
2020-09-29 03:46:54 +00:00
|
|
|
.state_root_at_slot(slot)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?
|
|
|
|
.ok_or_else(|| {
|
|
|
|
warp_utils::reject::custom_not_found(format!("beacon state at slot {}", slot))
|
2022-07-25 08:23:00 +00:00
|
|
|
})?;
|
|
|
|
|
|
|
|
Ok((root, execution_optimistic))
|
2020-09-29 03:46:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the `fork` field of the state identified by `self`.
|
2022-07-25 08:23:00 +00:00
|
|
|
/// Also returns the `execution_optimistic` value of the state.
|
|
|
|
pub fn fork_and_execution_optimistic<T: BeaconChainTypes>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
|
|
|
) -> Result<(Fork, bool), warp::Rejection> {
|
|
|
|
self.map_state_and_execution_optimistic(chain, |state, execution_optimistic| {
|
|
|
|
Ok((state.fork(), execution_optimistic))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convenience function to compute `fork` when `execution_optimistic` isn't desired.
|
2020-09-29 03:46:54 +00:00
|
|
|
pub fn fork<T: BeaconChainTypes>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
|
|
|
) -> Result<Fork, warp::Rejection> {
|
2022-07-25 08:23:00 +00:00
|
|
|
self.fork_and_execution_optimistic(chain)
|
|
|
|
.map(|(fork, _)| fork)
|
2020-09-29 03:46:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return the `BeaconState` identified by `self`.
|
|
|
|
pub fn state<T: BeaconChainTypes>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
2022-07-25 08:23:00 +00:00
|
|
|
) -> Result<(BeaconState<T::EthSpec>, ExecutionOptimistic), warp::Rejection> {
|
|
|
|
let ((state_root, execution_optimistic), slot_opt) = match &self.0 {
|
|
|
|
CoreStateId::Head => {
|
|
|
|
let (cached_head, execution_status) = chain
|
|
|
|
.canonical_head
|
|
|
|
.head_and_execution_status()
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
return Ok((
|
|
|
|
cached_head
|
|
|
|
.snapshot
|
|
|
|
.beacon_state
|
|
|
|
.clone_with_only_committee_caches(),
|
2022-07-30 05:08:57 +00:00
|
|
|
execution_status.is_optimistic_or_invalid(),
|
2022-07-25 08:23:00 +00:00
|
|
|
));
|
|
|
|
}
|
2020-09-29 03:46:54 +00:00
|
|
|
CoreStateId::Slot(slot) => (self.root(chain)?, Some(*slot)),
|
|
|
|
_ => (self.root(chain)?, None),
|
|
|
|
};
|
|
|
|
|
2022-07-25 08:23:00 +00:00
|
|
|
let state = chain
|
2020-09-29 03:46:54 +00:00
|
|
|
.get_state(&state_root, slot_opt)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)
|
|
|
|
.and_then(|opt| {
|
|
|
|
opt.ok_or_else(|| {
|
|
|
|
warp_utils::reject::custom_not_found(format!(
|
|
|
|
"beacon state at root {}",
|
|
|
|
state_root
|
|
|
|
))
|
|
|
|
})
|
2022-07-25 08:23:00 +00:00
|
|
|
})?;
|
|
|
|
|
|
|
|
Ok((state, execution_optimistic))
|
2020-09-29 03:46:54 +00:00
|
|
|
}
|
|
|
|
|
2022-07-25 08:23:00 +00:00
|
|
|
/*
|
2020-09-29 03:46:54 +00:00
|
|
|
/// Map a function across the `BeaconState` identified by `self`.
|
|
|
|
///
|
|
|
|
/// This function will avoid instantiating/copying a new state when `self` points to the head
|
|
|
|
/// of the chain.
|
2022-07-25 08:23:00 +00:00
|
|
|
#[allow(dead_code)]
|
2020-09-29 03:46:54 +00:00
|
|
|
pub fn map_state<T: BeaconChainTypes, F, U>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
|
|
|
func: F,
|
|
|
|
) -> Result<U, warp::Rejection>
|
|
|
|
where
|
|
|
|
F: Fn(&BeaconState<T::EthSpec>) -> Result<U, warp::Rejection>,
|
|
|
|
{
|
|
|
|
match &self.0 {
|
|
|
|
CoreStateId::Head => chain
|
|
|
|
.with_head(|snapshot| Ok(func(&snapshot.beacon_state)))
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?,
|
|
|
|
_ => func(&self.state(chain)?),
|
|
|
|
}
|
|
|
|
}
|
2022-07-25 08:23:00 +00:00
|
|
|
*/
|
|
|
|
|
|
|
|
/// Functions the same as `map_state` but additionally computes the value of
|
|
|
|
/// `execution_optimistic` of the state identified by `self`.
|
|
|
|
///
|
|
|
|
/// This is to avoid re-instantiating `state` unnecessarily.
|
|
|
|
pub fn map_state_and_execution_optimistic<T: BeaconChainTypes, F, U>(
|
|
|
|
&self,
|
|
|
|
chain: &BeaconChain<T>,
|
|
|
|
func: F,
|
|
|
|
) -> Result<U, warp::Rejection>
|
|
|
|
where
|
|
|
|
F: Fn(&BeaconState<T::EthSpec>, bool) -> Result<U, warp::Rejection>,
|
|
|
|
{
|
|
|
|
let (state, execution_optimistic) = match &self.0 {
|
|
|
|
CoreStateId::Head => {
|
|
|
|
let (head, execution_status) = chain
|
|
|
|
.canonical_head
|
|
|
|
.head_and_execution_status()
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
return func(
|
|
|
|
&head.snapshot.beacon_state,
|
2022-07-30 05:08:57 +00:00
|
|
|
execution_status.is_optimistic_or_invalid(),
|
2022-07-25 08:23:00 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
_ => self.state(chain)?,
|
|
|
|
};
|
|
|
|
|
|
|
|
func(&state, execution_optimistic)
|
|
|
|
}
|
2020-09-29 03:46:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FromStr for StateId {
|
|
|
|
type Err = String;
|
|
|
|
|
|
|
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
|
|
CoreStateId::from_str(s).map(Self)
|
|
|
|
}
|
|
|
|
}
|
2022-07-25 08:23:00 +00:00
|
|
|
|
|
|
|
impl fmt::Display for StateId {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
write!(f, "{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the first slot of the checkpoint's `epoch` and the execution status of the checkpoint's
|
|
|
|
/// `root`.
|
|
|
|
pub fn checkpoint_slot_and_execution_optimistic<T: BeaconChainTypes>(
|
|
|
|
chain: &BeaconChain<T>,
|
|
|
|
checkpoint: Checkpoint,
|
|
|
|
) -> Result<(Slot, ExecutionOptimistic), warp::reject::Rejection> {
|
|
|
|
let slot = checkpoint.epoch.start_slot(T::EthSpec::slots_per_epoch());
|
|
|
|
let fork_choice = chain.canonical_head.fork_choice_read_lock();
|
|
|
|
let finalized_checkpoint = fork_choice.cached_fork_choice_view().finalized_checkpoint;
|
|
|
|
|
|
|
|
// If the checkpoint is pre-finalization, just use the optimistic status of the finalized
|
|
|
|
// block.
|
|
|
|
let root = if checkpoint.epoch < finalized_checkpoint.epoch {
|
|
|
|
&finalized_checkpoint.root
|
|
|
|
} else {
|
|
|
|
&checkpoint.root
|
|
|
|
};
|
|
|
|
|
|
|
|
let execution_optimistic = fork_choice
|
2022-07-30 05:08:57 +00:00
|
|
|
.is_optimistic_or_invalid_block_no_fallback(root)
|
2022-07-25 08:23:00 +00:00
|
|
|
.map_err(BeaconChainError::ForkChoiceError)
|
|
|
|
.map_err(warp_utils::reject::beacon_chain_error)?;
|
|
|
|
|
|
|
|
Ok((slot, execution_optimistic))
|
|
|
|
}
|