From cec6588c40aa751067d7a2d74645ae1ed037b520 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Fri, 4 Dec 2026 19:01:54 -0300 Subject: [PATCH 1/3] fix(storage): keep the payload verdict the finalized block's execution_optimistic flag is read from From gloas a block's flag is the verdict of the latest FULL payload it builds on. For the finalized block that payload is below it, and the finality prune dropped every verdict below the checkpoint's slot, so the finalized block and every block below it read as optimistic on a synced node. A skipped epoch boundary also dropped the finalized block's own verdict, which a child on its FULL branch reads. The prune now keeps both. A block below the finalized one answers with the finalized block's flag. A restart seeds the kept verdict, and a VALID answer for a head that builds on that payload validates it, since the execution-chain walk stops at the finalized block. Closes #981 (cherry picked from commit a4379c76a2f28a8824575fa11042f7f16010fa72) --- crates/blockchain/src/beacon_payloads.rs | 180 ++++++++++++++++++++- crates/blockchain/src/lib.rs | 5 +- crates/net/rpc/src/shared/optimistic.rs | 136 +++++++++++++++- crates/storage/src/execution_optimistic.rs | 146 +++++++++++++++-- crates/storage/src/store.rs | 46 +++++- docs/rpc.md | 19 ++- 6 files changed, 510 insertions(+), 22 deletions(-) diff --git a/crates/blockchain/src/beacon_payloads.rs b/crates/blockchain/src/beacon_payloads.rs index a3a960f7d..3046c3db5 100644 --- a/crates/blockchain/src/beacon_payloads.rs +++ b/crates/blockchain/src/beacon_payloads.rs @@ -316,12 +316,14 @@ pub(crate) fn resolve_invalid_payload( /// chain skipped past was not part of what the execution client validated. /// /// Skipped entirely when nothing is optimistic, and bounded at finality -/// otherwise. +/// otherwise, plus the one payload below it that +/// [`validate_finalized_payload_base`] names. pub(crate) fn mark_payloads_validated(store: &mut Store, root: H256) { if !store.has_unvalidated_block_payloads() && !store.has_beacon_optimistic_roots() { return; } - for block in el_chain(store, root) { + let chain = el_chain(store, root); + for &block in &chain { store.remove_beacon_optimistic_root(block); if store.has_verified_payload(&block) && store.beacon_block_payload_status(block).is_not_validated() @@ -330,6 +332,50 @@ pub(crate) fn mark_payloads_validated(store: &mut Store, root: H256) { store.insert_beacon_block_payload_status(block, slot, PayloadStatusEnum::Valid); } } + let lowest = *chain.last().expect("the chain holds its start"); + validate_finalized_payload_base(store, lowest); +} + +/// The gloas payload the finalized block builds on: its block's root and +/// slot, and its execution hash. `None` when the finalized block's flag is not +/// read from a gloas verdict (see [`Store::beacon_finalized_payload_base`]). +fn finalized_payload_base(store: &Store) -> Option<(H256, u64, ExecutionBlockHash)> { + let base = store.beacon_finalized_payload_base()?; + let block = store.get_signed_block(&base).ok().flatten()?; + let hash = bid_of(&block)?.block_hash; + Some((base, block.slot(), hash)) +} + +/// Moves the payload the finalized block builds on to `VALID`, when `lowest`, +/// the last block of a validated EL chain, builds on it. +/// +/// The `execution_optimistic` flag of the finalized block, and of every block +/// below it, is read from that payload's verdict, which is why finality's +/// prune keeps it. It is one step below where [`el_chain`] stops, so the walk +/// in [`mark_payloads_validated`] never promotes it: left alone, a verdict +/// kept while `NOT_VALIDATED` (the execution client was syncing when finality +/// moved, or a restart seeded it) would stay so until finality moves again. +/// +/// `lowest` is either the finalized block, whose payload is then on the +/// chain, or the first block above it whose payload is, when the finalized +/// block's is not. Both name the same parent payload in their bid, and a +/// `VALID` payload's parent is valid. The hashes are compared rather than +/// assumed, so a chain that stopped anywhere else promotes nothing. +fn validate_finalized_payload_base(store: &mut Store, lowest: H256) { + let Some((base, slot, hash)) = finalized_payload_base(store) else { + return; + }; + if !store.beacon_block_payload_status(base).is_not_validated() { + return; + } + let builds_on = store + .get_signed_block(&lowest) + .ok() + .flatten() + .and_then(|block| bid_of(&block).map(|bid| bid.parent_block_hash)); + if builds_on == Some(hash) { + store.insert_beacon_block_payload_status(base, slot, PayloadStatusEnum::Valid); + } } /// Gives a payload restored from disk a verdict: the status map is scratch, so @@ -349,6 +395,13 @@ pub(crate) fn seed_resumed_payload_statuses(store: &mut Store, engine_configured store.insert_beacon_block_payload_status(root, slot, status); } } + // The payload the finalized block builds on is below the window the + // verified set is rebuilt for, and the finalized block could not have been + // imported without it. Its verdict is what the finalized block's + // `execution_optimistic` flag is read from. + if let Some((base, slot, _hash)) = finalized_payload_base(store) { + store.insert_beacon_block_payload_status(base, slot, status); + } } impl BlockChainServer { @@ -667,4 +720,127 @@ mod tests { .expect("move head"); assert_eq!(get_safe_execution_block_hash(&store), hash_a); } + /// Three gloas blocks above the zero anchor, the second finalized under a + /// checkpoint at its own slot, the third the head. The first two are FULL + /// on their parent; `head_parent_hash` says which payload the head builds + /// on. Returns the store, the roots and the three payload hashes. + /// + /// ```text + /// anchor(fulu) - b1 - b2 (finalized) - b3 (head) + /// ``` + /// + /// `b1`'s payload is the one `b2`'s `execution_optimistic` flag is read + /// from. No verdict is recorded for any of them. + fn finalized_gloas_chain(head_builds_on: usize) -> (Store, [H256; 3], [H256; 3]) { + let mut store = beacon_store(0, 0); + let hashes = [ + H256::repeat_byte(0x31), + H256::repeat_byte(0x32), + H256::repeat_byte(0x33), + ]; + let parent_hashes = [H256::repeat_byte(0x30), hashes[0], hashes[head_builds_on]]; + let mut roots = [H256::ZERO; 3]; + let mut parent = H256::ZERO; + for i in 0..3 { + let slot = i as u64 + 1; + let block = gloas_block(slot, parent, parent_hashes[i], hashes[i]); + let root = block.message_hash_tree_root(); + store.insert_pending_block(root, block).expect("insert"); + store.insert_live_chain_entry(slot, root, parent); + store.insert_beacon_el_block_hash(root, slot, hashes[i]); + roots[i] = root; + parent = root; + } + make_head(&mut store, roots[2], PayloadStatus::Full); + let finalized = ethlambda_types::checkpoint::Checkpoint { + root: roots[1], + slot: 2, + }; + let checkpoints = ethlambda_storage::ForkCheckpoints::new(roots[2], None, Some(finalized)); + store.update_checkpoints(checkpoints).expect("finalize"); + (store, roots, hashes) + } + + /// A restart reloads payloads at or above the finalized block only, and + /// the one the finalized block builds on is below it. Without a verdict + /// of its own the finalized block would read as optimistic for the life + /// of the process (#981). + #[test] + fn a_restart_seeds_the_payload_the_finalized_block_builds_on() { + let (mut store, [b1, b2, _], _) = finalized_gloas_chain(1); + assert_eq!(store.beacon_finalized_payload_base(), Some(b1)); + + // With an execution client it waits for a `VALID` answer. + seed_resumed_payload_statuses(&mut store, true); + assert_eq!( + store.beacon_block_payload_status(b1), + PayloadStatusEnum::Syncing + ); + assert!(store.is_beacon_block_optimistic(b2)); + + // Without one the follower trusts it, as it does every envelope. + seed_resumed_payload_statuses(&mut store, false); + assert_eq!( + store.beacon_block_payload_status(b1), + PayloadStatusEnum::Valid + ); + assert!(!store.is_beacon_block_optimistic(b2)); + } + + /// The walk a `VALID` answer starts stops at the finalized block, one + /// payload above the one that block's flag is read from. + #[test] + fn a_valid_head_validates_the_payload_the_finalized_block_builds_on() { + let (mut store, [b1, b2, b3], _) = finalized_gloas_chain(1); + seed_resumed_payload_statuses(&mut store, true); + assert!(store.is_beacon_block_optimistic(b2)); + + mark_payloads_validated(&mut store, b3); + + assert_eq!( + store.beacon_block_payload_status(b1), + PayloadStatusEnum::Valid + ); + assert!(!store.is_beacon_block_optimistic(b2)); + assert!(!store.has_unvalidated_block_payloads()); + } + + /// When the head's chain skipped the finalized block's own payload, the + /// walk ends above that block, on a block that names the same parent + /// payload in its bid. + #[test] + fn a_valid_head_that_skipped_the_finalized_payload_validates_the_one_below_it() { + let (mut store, [b1, b2, b3], _) = finalized_gloas_chain(0); + seed_resumed_payload_statuses(&mut store, true); + + mark_payloads_validated(&mut store, b3); + + assert_eq!( + store.beacon_block_payload_status(b1), + PayloadStatusEnum::Valid + ); + assert!(!store.is_beacon_block_optimistic(b2)); + } + + /// A validated chain that does not build on that payload says nothing + /// about it. + #[test] + fn a_valid_block_off_the_finalized_payload_validates_nothing_below_finality() { + let (mut store, [b1, b2, _], _) = finalized_gloas_chain(1); + seed_resumed_payload_statuses(&mut store, true); + let stray = gloas_block(4, b2, H256::repeat_byte(0x77), H256::repeat_byte(0x78)); + let stray_root = stray.message_hash_tree_root(); + store + .insert_pending_block(stray_root, stray) + .expect("insert"); + store.insert_live_chain_entry(4, stray_root, b2); + + mark_payloads_validated(&mut store, stray_root); + + assert_eq!( + store.beacon_block_payload_status(b1), + PayloadStatusEnum::Syncing + ); + assert!(store.is_beacon_block_optimistic(b2)); + } } diff --git a/crates/blockchain/src/lib.rs b/crates/blockchain/src/lib.rs index d66347af1..ab2907fa1 100644 --- a/crates/blockchain/src/lib.rs +++ b/crates/blockchain/src/lib.rs @@ -3959,8 +3959,11 @@ impl BlockChainServer { // that follows the import cascade runs. self.store .prune_beacon_optimistic_roots(finalized_slot, finalized.root); + // The gloas verdicts share the horizon and keep two entries: the + // finalized block's own, and the one of the payload it builds on, + // which every finalized block's flag is read from. self.store - .prune_beacon_block_payload_statuses(finalized_slot); + .prune_beacon_block_payload_statuses(finalized_slot, finalized.root); // Same horizon again: the states of finalized snapshot intervals. Beacon // only, since lean prunes them inside `Store::prune_old_data`, and doing diff --git a/crates/net/rpc/src/shared/optimistic.rs b/crates/net/rpc/src/shared/optimistic.rs index bebfdc37c..bb1b52e63 100644 --- a/crates/net/rpc/src/shared/optimistic.rs +++ b/crates/net/rpc/src/shared/optimistic.rs @@ -24,10 +24,28 @@ pub(crate) fn block_is_optimistic(store: &Store, root: H256) -> bool { #[cfg(test)] mod tests { - use ethlambda_types::beacon::fork_choice::PayloadStatusEnum; + use ethlambda_storage::ForkCheckpoints; + use ethlambda_types::{beacon::fork_choice::PayloadStatusEnum, checkpoint::Checkpoint}; use super::*; - use crate::test_utils::{beacon_fixture, gloas_fixture}; + use crate::test_utils::{beacon_fixture, gloas_beacon_block, gloas_fixture}; + + /// Finalizes `root` under a checkpoint stored at `checkpoint_slot` (a + /// beacon checkpoint's stored slot is its epoch's start, which may be + /// above the block's own), then prunes as the chain actor's finality + /// sweep does. + fn finalize(store: &mut Store, root: H256, checkpoint_slot: u64) { + let head = store.head().expect("head"); + let finalized = Checkpoint { + root, + slot: checkpoint_slot, + }; + store + .update_checkpoints(ForkCheckpoints::new(head, None, Some(finalized))) + .expect("move finality"); + store.prune_beacon_optimistic_roots(checkpoint_slot, root); + store.prune_beacon_block_payload_statuses(checkpoint_slot, root); + } #[test] fn a_pre_gloas_block_reads_the_optimistic_set() { @@ -103,6 +121,120 @@ mod tests { assert!(!block_is_optimistic(&fixture.store, root)); } + /// The finalized block reads the payload it builds on, which is below it, + /// where finality prunes verdicts. Dropping that one reported every + /// finalized gloas block as optimistic (#981). + #[test] + fn a_finalized_gloas_block_keeps_its_flag_when_finality_prunes() { + let mut fixture = gloas_fixture(); + let (g1, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + let (g3, _) = fixture.g3; + fixture + .store + .insert_beacon_block_payload_status(g1, g1_slot, PayloadStatusEnum::Valid); + assert!(!block_is_optimistic(&fixture.store, g2)); + + finalize(&mut fixture.store, g2, g2_slot); + + assert_eq!(fixture.store.beacon_finalized_payload_base(), Some(g1)); + assert!(!block_is_optimistic(&fixture.store, g2)); + // g3 skipped g2's payload, so it rests on the same one. + assert!(!block_is_optimistic(&fixture.store, g3)); + } + + /// The kept verdict is read, not assumed: a finalized block on a payload + /// the execution client has not vouched for is optimistic until it does. + #[test] + fn a_finalized_gloas_block_on_an_unvalidated_payload_is_optimistic() { + let mut fixture = gloas_fixture(); + let (g1, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + fixture + .store + .insert_beacon_block_payload_status(g1, g1_slot, PayloadStatusEnum::Syncing); + + finalize(&mut fixture.store, g2, g2_slot); + assert!(block_is_optimistic(&fixture.store, g2)); + + fixture + .store + .insert_beacon_block_payload_status(g1, g1_slot, PayloadStatusEnum::Valid); + assert!(!block_is_optimistic(&fixture.store, g2)); + } + + /// A skipped epoch boundary leaves the finalized block below its + /// checkpoint's slot, and its own verdict is what a child on its FULL + /// branch reads. + #[test] + fn a_finalized_block_below_its_checkpoint_slot_keeps_its_own_verdict() { + let mut fixture = gloas_fixture(); + let (g1, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + for (root, slot) in [(g1, g1_slot), (g2, g2_slot)] { + fixture + .store + .insert_beacon_block_payload_status(root, slot, PayloadStatusEnum::Valid); + } + // g2's payload hash in the fixture is `[2; 32]`. + let child = gloas_beacon_block(g2_slot + 2, g2, H256::from([2; 32]), H256::from([4; 32])); + let child_root = child.message_hash_tree_root(); + fixture + .store + .insert_signed_block(child_root, child) + .expect("insert"); + assert!(!block_is_optimistic(&fixture.store, child_root)); + + finalize(&mut fixture.store, g2, g2_slot + 1); + + assert!(!block_is_optimistic(&fixture.store, child_root)); + } + + /// Nothing below finality is validated apart from the finalized block, + /// and its own verdict is pruned, so it answers with that block's flag. + #[test] + fn a_block_below_the_finalized_one_answers_with_its_flag() { + let mut fixture = gloas_fixture(); + let (g1, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + let below = [g1, fixture.head_root]; + fixture + .store + .insert_beacon_block_payload_status(g1, g1_slot, PayloadStatusEnum::Syncing); + // On their own, both rest on a validated pre-gloas payload. + for root in below { + assert!(!block_is_optimistic(&fixture.store, root)); + } + + finalize(&mut fixture.store, g2, g2_slot); + for root in below { + assert!(block_is_optimistic(&fixture.store, root)); + } + + fixture + .store + .insert_beacon_block_payload_status(g1, g1_slot, PayloadStatusEnum::Valid); + for root in below { + assert!(!block_is_optimistic(&fixture.store, root)); + } + } + + /// The same rule before gloas, where the finalized block's flag is its + /// place in the optimistic set. + #[test] + fn a_block_below_an_optimistic_pre_gloas_finalized_block_is_optimistic() { + let mut fixture = beacon_fixture(64); + let (head, slot) = (fixture.head_root, fixture.head_slot); + fixture.store.insert_beacon_optimistic_root(head, slot); + assert!(!block_is_optimistic(&fixture.store, fixture.anchor_root)); + + finalize(&mut fixture.store, head, slot); + assert!(block_is_optimistic(&fixture.store, fixture.anchor_root)); + + fixture.store.remove_beacon_optimistic_root(head); + assert!(!block_is_optimistic(&fixture.store, fixture.anchor_root)); + } + #[test] fn judging_a_block_records_nothing_in_the_store() { let fixture = gloas_fixture(); diff --git a/crates/storage/src/execution_optimistic.rs b/crates/storage/src/execution_optimistic.rs index 81b2fccfd..a1c98ebca 100644 --- a/crates/storage/src/execution_optimistic.rs +++ b/crates/storage/src/execution_optimistic.rs @@ -21,6 +21,14 @@ //! chain actor's event stream answer the question, and the chain actor's //! crate cannot depend on the API's. //! +//! Finality prunes both records, and a block's flag is still asked for after +//! it. A block below the finalized one answers with the finalized block's +//! flag: nothing below finality can be validated apart from it, and its own +//! verdict is gone by design. The finalized block itself reads the payload +//! it builds on, which is below it, so that one verdict is kept through the +//! prune ([`Store::beacon_finalized_payload_base`], +//! [`Store::prune_beacon_block_payload_statuses`]). +//! //! Everything here only reads the store, and an answer that cannot be worked //! out is optimistic: this flag gates signing, so an unknown gets the cautious //! reading. The payload links are therefore looked up or derived here instead @@ -37,6 +45,23 @@ use ethlambda_types::{ use crate::Store; +/// Where a block's `execution_optimistic` flag is read from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum VerdictSource { + /// The optimistic set's entry for the pre-gloas block named here: the + /// block itself, or the pre-gloas ancestor whose payload a gloas block + /// builds on. + OptimisticSet(H256), + /// The recorded verdict on the payload of the gloas block named here: the + /// latest FULL payload the block builds on, which belongs to an ancestor. + PayloadVerdict(H256), + /// The chain ran out below the block (an anchor whose parent is not + /// stored), so nothing is left to doubt. + Settled, + /// A block or a link could not be read, so the cautious reading applies. + Unknown, +} + impl Store { /// Whether the payload of the block at `root` is not yet vouched for by /// the execution layer: the flag an envelope response or event carries. @@ -50,35 +75,132 @@ impl Store { /// Whether the block at `root` rests on a payload that is not `VALID`: the /// flag a block, state, header or head response or event carries. /// - /// Walks back from `root` through the blocks whose payload branch the - /// child skipped (`Empty`) until it reaches the FULL payload the chain - /// actually builds on, then reads that payload's verdict. A pre-gloas - /// block is its own payload, so it reads the optimistic set. A chain that - /// runs out (an anchor whose parent is below the retained window) has - /// nothing left to doubt, so it is not optimistic. A block or link that - /// cannot be read is optimistic. + /// A block below the finalized one answers with the finalized block's + /// flag (see the module documentation). Any other is read from + /// [`Self::verdict_source`]: a pre-gloas block from the optimistic set, + /// a gloas block from the verdict of the FULL payload it builds on, where + /// none recorded is `NOT_VALIDATED`. A + /// chain that runs out (an anchor whose parent is below the retained + /// window) has nothing left to doubt, so it is not optimistic. A block or + /// link that cannot be read is optimistic. pub fn is_beacon_block_optimistic(&self, root: H256) -> bool { + let finalized = self.beacon_finalized_checkpoint().root; + let source = if root == finalized || self.is_below_block(root, finalized) { + self.finalized_verdict_source(finalized) + } else { + self.verdict_source(root) + }; + match source { + VerdictSource::OptimisticSet(block) => self.is_beacon_optimistic(block), + VerdictSource::PayloadVerdict(block) => { + self.beacon_block_payload_status(block) != PayloadStatusEnum::Valid + } + VerdictSource::Settled => false, + VerdictSource::Unknown => true, + } + } + + /// The gloas block whose payload verdict the finalized block's flag is + /// read from: the latest FULL payload the finalized block builds on. + /// + /// `None` when there is no such verdict to keep: the finalized block is + /// pre-gloas, the payload it builds on is a pre-gloas block's (which the + /// optimistic set answers for), it is an anchor with nothing stored below + /// it, or it cannot be read. + /// + /// That block is below the finalized one, where finality prunes verdicts + /// and neither a resume nor a `VALID` answer's walk reaches. So the prune + /// keeps it, and the chain actor seeds and validates it by name. + pub fn beacon_finalized_payload_base(&self) -> Option { + let finalized = self.beacon_finalized_checkpoint().root; + self.gloas_payload_base(finalized) + } + + /// [`Self::beacon_finalized_payload_base`] for a finalized root the + /// caller already holds. + pub(crate) fn gloas_payload_base(&self, finalized: H256) -> Option { + match self.finalized_verdict_source(finalized) { + VerdictSource::PayloadVerdict(base) => Some(base), + VerdictSource::OptimisticSet(_) | VerdictSource::Settled | VerdictSource::Unknown => { + None + } + } + } + + /// [`Self::verdict_source`] for the finalized block, remembered per + /// finalized root. + /// + /// Finality's sweep runs on every tick and every import and needs this to + /// know which verdict to keep, and every answer for a block at or below + /// finality reads it. The walk decodes at least one block, so it is done + /// once per finalized block rather than each time, and what is remembered + /// names the entry to read with no further lookup. The answer follows + /// from the stored blocks alone, so it does not change while the + /// finalized root does not. An `Unknown` is not remembered: it is a + /// failed read, which a later one may not repeat. + fn finalized_verdict_source(&self, finalized: H256) -> VerdictSource { + if let Some((root, source)) = self.beacon.lock().unwrap().finalized_verdict_source + && root == finalized + { + return source; + } + let source = self.verdict_source(finalized); + if source != VerdictSource::Unknown { + self.beacon.lock().unwrap().finalized_verdict_source = Some((finalized, source)); + } + source + } + + /// Where `root`'s flag is read from. + /// + /// A pre-gloas block is its own payload. A gloas block walks back through + /// the blocks whose payload branch the child skipped (`Empty`) until it + /// reaches the FULL payload the chain actually builds on, which is a + /// gloas block's or, at the fork boundary, a pre-gloas one's. + fn verdict_source(&self, root: H256) -> VerdictSource { let mut current = root; loop { let Some(link) = self.payload_link_or_derived(current) else { - return true; + return VerdictSource::Unknown; }; if !link.is_gloas() { - return self.is_beacon_optimistic(current); + return VerdictSource::OptimisticSet(current); } let parent = match self.get_signed_block(¤t) { Ok(Some(block)) => block.parent_root(), - Ok(None) | Err(_) => return true, + Ok(None) | Err(_) => return VerdictSource::Unknown, }; match link.parent_status() { - Some(PayloadStatus::Full) => return self.payload_is_not_valid(parent), + Some(PayloadStatus::Full) => { + return match self.payload_link_or_derived(parent) { + Some(BlockPayloadLink::PreGloas) => VerdictSource::OptimisticSet(parent), + Some(BlockPayloadLink::Gloas { .. }) => { + VerdictSource::PayloadVerdict(parent) + } + None => VerdictSource::Unknown, + }; + } Some(PayloadStatus::Empty) => current = parent, // A pending parent status never comes out of a block's own bid. - Some(PayloadStatus::Pending) | None => return false, + Some(PayloadStatus::Pending) | None => return VerdictSource::Settled, } } } + /// Whether `root` is a stored block at a lower slot than `other`'s. + /// + /// `false` when either slot cannot be read, which leaves `root` to be + /// judged on its own. + fn is_below_block(&self, root: H256, other: H256) -> bool { + match ( + self.try_beacon_block_slot(&root), + self.try_beacon_block_slot(&other), + ) { + (Some(slot), Some(other_slot)) => slot < other_slot, + _ => false, + } + } + /// `root`'s payload link: the one fork choice recorded, or one derived /// from the stored blocks without recording it. `None` when it cannot be /// worked out. diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 926267f6c..7770820f6 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -11,6 +11,7 @@ use crate::active_balance_cache::ActiveBalanceCache; use crate::api::{StorageBackend, StorageReadView, StorageReadViewExt, StorageWriteBatch, Table}; use crate::committee_cache::CommitteeCache; use crate::error::Error; +use crate::execution_optimistic::VerdictSource; use crate::liveness::ObservedLiveness; use crate::pools::{AttestationPool, OperationPool}; use crate::proto_array::{ProtoArray, ProtoArrayError, RebuildReason, WeightRules}; @@ -1123,6 +1124,10 @@ pub(crate) struct BeaconScratch { /// `prune_beacon_el_block_hashes`; a restart forgets it, which can only /// turn a late `payload_present` into `false` for the one slot in flight. pub(crate) envelope_seen_ms: HashMap, + /// The finalized root and where its `execution_optimistic` flag is read + /// from, remembered so finality's sweep does not walk for it on every + /// tick. See `Store::finalized_verdict_source`. + pub(crate) finalized_verdict_source: Option<(H256, VerdictSource)>, } /// Encode a LiveChain key (slot, root) to bytes. @@ -3431,6 +3436,16 @@ impl Store { Some((slot, root)) } + /// `root`'s block slot on a beacon store, or `None` when no such block is + /// on record or it cannot be read. [`beacon_block_slot`] for a caller that + /// must not panic on a failed read. + pub(crate) fn try_beacon_block_slot(&self, root: &H256) -> Option { + let view = self.backend.begin_read().ok()?; + try_block_slot_in(view.as_ref(), Chain::Beacon, root) + .ok() + .flatten() + } + /// `root`'s slot and parent root, without decoding its body. /// /// The two chains keep different shapes in `Table::BlockHeaders`: a lean @@ -5332,13 +5347,27 @@ impl Store { } /// Drops payload verdicts strictly below `finalized_slot`, which no - /// attestation rule can ask about any more. - pub fn prune_beacon_block_payload_statuses(&mut self, finalized_slot: u64) { + /// attestation rule can ask about any more, always keeping two: `keep`'s + /// own and the one of the payload `keep` builds on. + /// + /// `keep` is the finalized checkpoint's root. Its own verdict is exempted + /// for the reason [`Store::prune_beacon_el_block_hashes`] gives: a skipped + /// epoch boundary leaves the block below the slot bound, and a child that + /// builds on its payload reads this verdict for its `execution_optimistic` + /// flag. The payload `keep` builds on is always below the bound, and its + /// verdict is what `keep`'s own flag, and so every finalized block's, is + /// read from ([`Store::beacon_finalized_payload_base`]). Dropping either + /// reports a validated block as optimistic. + pub fn prune_beacon_block_payload_statuses(&mut self, finalized_slot: u64, keep: H256) { + // Worked out before the lock: the walk reads the scratch itself. + let base = self.gloas_payload_base(keep); self.beacon .lock() .unwrap() .block_payload_statuses - .retain(|_root, (slot, _status)| *slot >= finalized_slot); + .retain(|root, (slot, _status)| { + *slot >= finalized_slot || *root == keep || Some(*root) == base + }); } /// Records an execution client's answer for a payload. The fixture format @@ -11007,13 +11036,22 @@ mod tests { PayloadStatusEnum::Valid ); - store.prune_beacon_block_payload_statuses(5); + // The finalized root is exempt from the slot bound, as in the other + // prunes at this horizon. + let finalized = H256::repeat_byte(3); + store.insert_beacon_block_payload_status(finalized, 3, PayloadStatusEnum::Valid); + + store.prune_beacon_block_payload_statuses(5, finalized); assert!(store.beacon_block_payload_status(below).is_not_validated()); assert_eq!( store.beacon_block_payload_status(at), PayloadStatusEnum::Invalid ); + assert_eq!( + store.beacon_block_payload_status(finalized), + PayloadStatusEnum::Valid + ); } #[test] diff --git a/docs/rpc.md b/docs/rpc.md index 4475a9c92..b74e663d5 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -999,7 +999,24 @@ object that may arrive late or never, and two rules share the flag: the optimistic set. The block's own payload does not count, so a withheld payload does not make the chain look unverified. -Pre-gloas responses are unchanged. `Store::is_beacon_block_optimistic` and +Finality prunes both records, so at and below it the flag is read differently: + +- the **finalized block** reads the payload it builds on like any other block. + That payload is below the finalized block, so its verdict is the one entry + finality's prune keeps below its bound, beside the finalized block's own + (which a skipped epoch boundary also leaves below the bound, and which a + child on its FULL branch reads). A restart seeds that verdict with the + unfinalized window's, and a `VALID` answer for a head that builds on it + validates it, since the walk a `VALID` answer starts stops at the finalized + block; +- a **block below the finalized one**, gloas or not, answers with the finalized + block's flag. Its own verdict is gone, and nothing below finality is + validated apart from the finalized block. Before gloas this differs from + reading the optimistic set only while the finalized block itself is + optimistic: an older block then reads `true` where the pruned set alone + would have said `false`. + +Pre-gloas responses are otherwise unchanged. `Store::is_beacon_block_optimistic` and `Store::is_beacon_payload_optimistic` (`ethlambda-storage`'s `execution_optimistic` module) implement the two rules, and every response that carries the flag goes through them, as do `/eth/v1/events`'s `head`, From 4157d59376d83d65da41204920643f0ed17e35b8 Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Fri, 4 Dec 2026 19:51:55 -0300 Subject: [PATCH 2/3] fix(storage): give the finalized block's flag only to the blocks it descends from A block below the finalized one answered with the finalized block's execution_optimistic flag on its slot alone. A block of a fork that lost stays stored after finality passes its slot and can be asked for by root, so it reported the finalized chain's verdict although nothing vouched for its own fork's payloads. The flag now goes only to a block the canonical index names at its slot, which below the finalized block are its ancestors. Any other block is read on its own, as before: with its verdict pruned a gloas one reads as optimistic. --- crates/net/rpc/src/shared/optimistic.rs | 46 +++++++++++++++++++++- crates/storage/src/execution_optimistic.rs | 44 +++++++++++++-------- crates/storage/src/store.rs | 14 +++++++ docs/rpc.md | 13 ++++-- 4 files changed, 95 insertions(+), 22 deletions(-) diff --git a/crates/net/rpc/src/shared/optimistic.rs b/crates/net/rpc/src/shared/optimistic.rs index bb1b52e63..339d3070a 100644 --- a/crates/net/rpc/src/shared/optimistic.rs +++ b/crates/net/rpc/src/shared/optimistic.rs @@ -34,14 +34,17 @@ mod tests { /// beacon checkpoint's stored slot is its epoch's start, which may be /// above the block's own), then prunes as the chain actor's finality /// sweep does. + /// + /// The head moves to `root` with it: a finalized block is on the head's + /// branch, and that is what puts it and its ancestors in the canonical + /// index. fn finalize(store: &mut Store, root: H256, checkpoint_slot: u64) { - let head = store.head().expect("head"); let finalized = Checkpoint { root, slot: checkpoint_slot, }; store - .update_checkpoints(ForkCheckpoints::new(head, None, Some(finalized))) + .update_checkpoints(ForkCheckpoints::new(root, None, Some(finalized))) .expect("move finality"); store.prune_beacon_optimistic_roots(checkpoint_slot, root); store.prune_beacon_block_payload_statuses(checkpoint_slot, root); @@ -219,6 +222,45 @@ mod tests { } } + /// A block of a fork that lost stays stored below finality and can be + /// asked for by root. The finalized chain's verdict is not its own: it + /// rests on a payload of its own fork, which nothing vouched for. + #[test] + fn a_block_of_a_losing_fork_below_finality_does_not_take_the_finalized_flag() { + let mut fixture = gloas_fixture(); + let (g1, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + let (g3, g3_slot) = fixture.g3; + for (root, slot) in [(g1, g1_slot), (g2, g2_slot)] { + fixture + .store + .insert_beacon_block_payload_status(root, slot, PayloadStatusEnum::Valid); + } + // A fork off the pre-gloas head, beside g1 and g2: `s2` builds on + // `s1`'s payload, which has no verdict. + let hash = |n: u8| H256::from([n; 32]); + let s1 = gloas_beacon_block(g1_slot, fixture.head_root, hash(0), hash(7)); + let s1_root = s1.message_hash_tree_root(); + let s2 = gloas_beacon_block(g2_slot, s1_root, hash(7), hash(8)); + let s2_root = s2.message_hash_tree_root(); + for (root, block) in [(s1_root, s1), (s2_root, s2)] { + fixture + .store + .insert_signed_block(root, block) + .expect("insert"); + } + assert!(block_is_optimistic(&fixture.store, s2_root)); + + finalize(&mut fixture.store, g3, g3_slot); + + // The finalized block and its ancestors are validated... + for root in [g3, g2, g1] { + assert!(!block_is_optimistic(&fixture.store, root)); + } + // ...and the fork beside them is as unvalidated as it was. + assert!(block_is_optimistic(&fixture.store, s2_root)); + } + /// The same rule before gloas, where the finalized block's flag is its /// place in the optimistic set. #[test] diff --git a/crates/storage/src/execution_optimistic.rs b/crates/storage/src/execution_optimistic.rs index a1c98ebca..17cc449a8 100644 --- a/crates/storage/src/execution_optimistic.rs +++ b/crates/storage/src/execution_optimistic.rs @@ -22,9 +22,12 @@ //! crate cannot depend on the API's. //! //! Finality prunes both records, and a block's flag is still asked for after -//! it. A block below the finalized one answers with the finalized block's -//! flag: nothing below finality can be validated apart from it, and its own -//! verdict is gone by design. The finalized block itself reads the payload +//! it. A block the finalized one descends from answers with the finalized +//! block's flag: nothing below finality can be validated apart from it, and +//! its own verdict is gone by design. A stored block below it on a fork that +//! lost is not such a block, so it is still read on its own: the finalized +//! chain's verdict says nothing about that fork's payloads, and with its +//! verdict pruned a gloas one reads as optimistic. The finalized block itself reads the payload //! it builds on, which is below it, so that one verdict is kept through the //! prune ([`Store::beacon_finalized_payload_base`], //! [`Store::prune_beacon_block_payload_statuses`]). @@ -75,8 +78,9 @@ impl Store { /// Whether the block at `root` rests on a payload that is not `VALID`: the /// flag a block, state, header or head response or event carries. /// - /// A block below the finalized one answers with the finalized block's - /// flag (see the module documentation). Any other is read from + /// A block the finalized one descends from answers with the finalized + /// block's flag (see the module documentation). Any other, a block of a + /// fork that lost below finality included, is read from /// [`Self::verdict_source`]: a pre-gloas block from the optimistic set, /// a gloas block from the verdict of the FULL payload it builds on, where /// none recorded is `NOT_VALIDATED`. A @@ -85,7 +89,7 @@ impl Store { /// link that cannot be read is optimistic. pub fn is_beacon_block_optimistic(&self, root: H256) -> bool { let finalized = self.beacon_finalized_checkpoint().root; - let source = if root == finalized || self.is_below_block(root, finalized) { + let source = if root == finalized || self.is_finalized_ancestor(root, finalized) { self.finalized_verdict_source(finalized) } else { self.verdict_source(root) @@ -187,18 +191,26 @@ impl Store { } } - /// Whether `root` is a stored block at a lower slot than `other`'s. + /// Whether `root` is a block the finalized one descends from: a stored + /// block at a lower slot that the canonical index names at that slot. /// - /// `false` when either slot cannot be read, which leaves `root` to be - /// judged on its own. - fn is_below_block(&self, root: H256, other: H256) -> bool { - match ( + /// The slot alone is not enough. A block of a fork that lost stays stored + /// after finality passes its slot, and can be asked for by root. The + /// finalized chain's verdict says nothing about its payloads. The index + /// holds one root per slot on the branch ending at the head, which the + /// finalized block is on, so below that block it names its ancestors only. + /// + /// `false` when a slot cannot be read or the index does not name `root` + /// (a slot below the index's first row included), which leaves `root` to + /// be judged on its own. + fn is_finalized_ancestor(&self, root: H256, finalized: H256) -> bool { + let (Some(slot), Some(finalized_slot)) = ( self.try_beacon_block_slot(&root), - self.try_beacon_block_slot(&other), - ) { - (Some(slot), Some(other_slot)) => slot < other_slot, - _ => false, - } + self.try_beacon_block_slot(&finalized), + ) else { + return false; + }; + slot < finalized_slot && self.try_canonical_root_at_slot(slot) == Some(root) } /// `root`'s payload link: the one fork choice recorded, or one derived diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 7770820f6..5b7c61a16 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -3446,6 +3446,20 @@ impl Store { .flatten() } + /// [`canonical_root_at_slot`](Self::canonical_root_at_slot) for a caller + /// that must not panic on a failed read: `None` then too, as for a slot + /// the index does not name. + pub(crate) fn try_canonical_root_at_slot(&self, slot: u64) -> Option { + let view = self.backend.begin_read().ok()?; + let key = encode_block_root_key(slot); + view.read_with(Table::BlockRoots, &key, |bytes| { + H256::from_ssz_bytes(bytes).ok() + }) + .ok() + .flatten() + .flatten() + } + /// `root`'s slot and parent root, without decoding its body. /// /// The two chains keep different shapes in `Table::BlockHeaders`: a lean diff --git a/docs/rpc.md b/docs/rpc.md index b74e663d5..afdc0f3e9 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -1009,12 +1009,17 @@ Finality prunes both records, so at and below it the flag is read differently: unfinalized window's, and a `VALID` answer for a head that builds on it validates it, since the walk a `VALID` answer starts stops at the finalized block; -- a **block below the finalized one**, gloas or not, answers with the finalized - block's flag. Its own verdict is gone, and nothing below finality is - validated apart from the finalized block. Before gloas this differs from +- a **block the finalized one descends from**, gloas or not, answers with the + finalized block's flag. Its own verdict is gone, and nothing below finality + is validated apart from the finalized block. Before gloas this differs from reading the optimistic set only while the finalized block itself is optimistic: an older block then reads `true` where the pruned set alone - would have said `false`. + would have said `false`; +- a **block of a fork that lost**, which stays stored below finality and can + be asked for by root, does not take that flag: the canonical index + (`BlockRoots`) does not name it at its slot, so it is read on its own. With + its verdict pruned a gloas one reads `true`, and a pre-gloas one `false`, + as the pruned optimistic set says. Pre-gloas responses are otherwise unchanged. `Store::is_beacon_block_optimistic` and `Store::is_beacon_payload_optimistic` (`ethlambda-storage`'s From 11cb3497e897107efd1ac249ea6ccd531d9a113d Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Fri, 4 Dec 2026 20:24:29 -0300 Subject: [PATCH 3/3] fix(storage): believe the canonical index only once it names the finalized block The check that a block is an ancestor of the finalized one asks the canonical index, which follows the stored head. An import moves the finalized checkpoint first and recomputes the head after. In between the index still names the old head's branch, so when finality moved to another branch a block of the old one passed for an ancestor of the finalized block and took its execution_optimistic flag. The index now has to name the finalized block as well, asked first. Until the head has followed finality no block below the finalized one takes its flag, and each is read on its own. --- crates/net/rpc/src/shared/optimistic.rs | 68 ++++++++++++++++++++++ crates/storage/src/execution_optimistic.rs | 29 ++++++--- crates/storage/src/store.rs | 26 +++++---- docs/rpc.md | 5 +- 4 files changed, 108 insertions(+), 20 deletions(-) diff --git a/crates/net/rpc/src/shared/optimistic.rs b/crates/net/rpc/src/shared/optimistic.rs index 339d3070a..ef5fb7808 100644 --- a/crates/net/rpc/src/shared/optimistic.rs +++ b/crates/net/rpc/src/shared/optimistic.rs @@ -261,6 +261,74 @@ mod tests { assert!(block_is_optimistic(&fixture.store, s2_root)); } + /// An import moves the finalized checkpoint before the head is + /// recomputed. Until it is, the canonical index still names the old + /// head's branch, which the finalized block is not on, so a block of that + /// branch must not pass for one of its ancestors. + #[test] + fn a_block_of_the_old_heads_branch_does_not_take_the_finalized_flag() { + let mut fixture = gloas_fixture(); + let (_, g1_slot) = fixture.g1; + let (g2, g2_slot) = fixture.g2; + let (g3, g3_slot) = fixture.g3; + // The head is on g1..g3, whose payloads nothing vouched for. + fixture + .store + .update_checkpoints(ForkCheckpoints::new(g3, None, None)) + .expect("move the head"); + // A validated fork beside it, off the pre-gloas block. + let hash = |n: u8| H256::from([n; 32]); + let mut fork = Vec::new(); + let mut parent = (fixture.head_root, hash(0)); + for (slot, block_hash) in [(g1_slot, hash(7)), (g2_slot, hash(8)), (g3_slot, hash(9))] { + let block = gloas_beacon_block(slot, parent.0, parent.1, block_hash); + let root = block.message_hash_tree_root(); + fixture + .store + .insert_signed_block(root, block) + .expect("insert"); + fixture + .store + .insert_beacon_block_payload_status(root, slot, PayloadStatusEnum::Valid); + fork.push(root); + parent = (root, block_hash); + } + let [s1, s2, s3] = fork[..] else { + unreachable!("three blocks were built") + }; + assert!(block_is_optimistic(&fixture.store, g2)); + + // Finality moves to the fork's tip with the head left where it was, + // then finality's sweep prunes. + let finalized = Checkpoint { + root: s3, + slot: g3_slot, + }; + fixture + .store + .update_checkpoints(ForkCheckpoints::new(g3, None, Some(finalized))) + .expect("move finality"); + fixture.store.prune_beacon_optimistic_roots(g3_slot, s3); + fixture + .store + .prune_beacon_block_payload_statuses(g3_slot, s3); + + assert!(!block_is_optimistic(&fixture.store, s3)); + // The index still names g2 at its slot, and it is not below s3: it + // rests on g1's payload, as unvalidated as before. + assert!(block_is_optimistic(&fixture.store, g2)); + + // The head follows, and the index names the finalized branch. + fixture + .store + .update_checkpoints(ForkCheckpoints::new(s3, None, None)) + .expect("move the head"); + for root in [s3, s2, s1] { + assert!(!block_is_optimistic(&fixture.store, root)); + } + assert!(block_is_optimistic(&fixture.store, g2)); + } + /// The same rule before gloas, where the finalized block's flag is its /// place in the optimistic set. #[test] diff --git a/crates/storage/src/execution_optimistic.rs b/crates/storage/src/execution_optimistic.rs index 17cc449a8..299755d7f 100644 --- a/crates/storage/src/execution_optimistic.rs +++ b/crates/storage/src/execution_optimistic.rs @@ -192,17 +192,26 @@ impl Store { } /// Whether `root` is a block the finalized one descends from: a stored - /// block at a lower slot that the canonical index names at that slot. + /// block at a lower slot, on the branch of the canonical index that the + /// finalized block is on too. /// /// The slot alone is not enough. A block of a fork that lost stays stored /// after finality passes its slot, and can be asked for by root. The - /// finalized chain's verdict says nothing about its payloads. The index - /// holds one root per slot on the branch ending at the head, which the - /// finalized block is on, so below that block it names its ancestors only. + /// finalized chain's verdict says nothing about its payloads. /// - /// `false` when a slot cannot be read or the index does not name `root` - /// (a slot below the index's first row included), which leaves `root` to - /// be judged on its own. + /// The index holds one root per slot on the branch ending at the stored + /// head. That is the finalized block's branch only once the head has + /// followed finality there: an import moves the finalized checkpoint + /// first and recomputes the head after, and in between the index still + /// names the old head's branch, which the finalized block may not be on. + /// So the index has to name the finalized block as well, and that is + /// asked first: an index that held the finalized block when it was read + /// holds nothing but its ancestors below it from then on, since no later + /// head leaves a finalized block's branch. + /// + /// `false` when a slot cannot be read or the index names either block + /// differently or not at all (a slot below its first row included), which + /// leaves `root` to be judged on its own. fn is_finalized_ancestor(&self, root: H256, finalized: H256) -> bool { let (Some(slot), Some(finalized_slot)) = ( self.try_beacon_block_slot(&root), @@ -210,7 +219,11 @@ impl Store { ) else { return false; }; - slot < finalized_slot && self.try_canonical_root_at_slot(slot) == Some(root) + if slot >= finalized_slot { + return false; + } + let [at_finalized, at_block] = self.try_canonical_roots_at_slots([finalized_slot, slot]); + at_finalized == Some(finalized) && at_block == Some(root) } /// `root`'s payload link: the one fork choice recorded, or one derived diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 5b7c61a16..579a0d9a1 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -3446,18 +3446,22 @@ impl Store { .flatten() } - /// [`canonical_root_at_slot`](Self::canonical_root_at_slot) for a caller - /// that must not panic on a failed read: `None` then too, as for a slot - /// the index does not name. - pub(crate) fn try_canonical_root_at_slot(&self, slot: u64) -> Option { - let view = self.backend.begin_read().ok()?; - let key = encode_block_root_key(slot); - view.read_with(Table::BlockRoots, &key, |bytes| { - H256::from_ssz_bytes(bytes).ok() + /// [`canonical_root_at_slot`](Self::canonical_root_at_slot) for two slots, + /// read in the order given, for a caller that must not panic on a failed + /// read: `None` then too, as for a slot the index does not name. + /// + /// The order is the caller's to choose because the index follows the + /// head, and the head moves between two reads of it. + pub(crate) fn try_canonical_roots_at_slots(&self, slots: [u64; 2]) -> [Option; 2] { + slots.map(|slot| { + let view = self.backend.begin_read().ok()?; + let key = encode_block_root_key(slot); + let decode = |bytes: &[u8]| H256::from_ssz_bytes(bytes).ok(); + view.read_with(Table::BlockRoots, &key, decode) + .ok() + .flatten() + .flatten() }) - .ok() - .flatten() - .flatten() } /// `root`'s slot and parent root, without decoding its body. diff --git a/docs/rpc.md b/docs/rpc.md index afdc0f3e9..c1d1f9201 100644 --- a/docs/rpc.md +++ b/docs/rpc.md @@ -1019,7 +1019,10 @@ Finality prunes both records, so at and below it the flag is read differently: be asked for by root, does not take that flag: the canonical index (`BlockRoots`) does not name it at its slot, so it is read on its own. With its verdict pruned a gloas one reads `true`, and a pre-gloas one `false`, - as the pruned optimistic set says. + as the pruned optimistic set says. The index follows the head, which an + import recomputes after it has moved the finalized checkpoint, so the index + must name the finalized block too before it is believed: until the head has + followed finality, no block below the finalized one takes its flag. Pre-gloas responses are otherwise unchanged. `Store::is_beacon_block_optimistic` and `Store::is_beacon_payload_optimistic` (`ethlambda-storage`'s