From bab5350b58287ec934656b5488e28a7fec95e5c8 Mon Sep 17 00:00:00 2001 From: Teddy Knox Date: Mon, 26 Oct 2026 18:45:38 +0100 Subject: [PATCH] kona-node: share the unsafe-chain walk and check L1 origins by number The cold-start reset kept an unsafe head whenever its L1 origin could be fetched by hash. An L1 node serves a block by hash after a reorg replaces it at the same height, so an unsafe head built on a replaced L1 block survived a cold start. find_starting_forkchoice and the L1-reorg reset now share one walk: it checks each origin by number, checks a replaced origin once, and never walks past a floor, the finalized head on a cold start and the kept safe head on an L1 reorg. Co-Authored-By: Claude Opus 5.5 --- .../kona/crates/node/engine/src/sync/error.rs | 16 ++ rust/kona/crates/node/engine/src/sync/mod.rs | 207 ++++++++++++++---- .../kona/crates/node/engine/src/sync/reorg.rs | 63 ++---- .../node/engine/src/sync/unsafe_head.rs | 90 ++++++++ .../crates/node/engine/src/task_queue/core.rs | 155 +++---------- .../node/engine/src/test_utils/chain.rs | 144 ++++++++++++ .../crates/node/engine/src/test_utils/mod.rs | 3 + .../node/service/src/actors/engine/tests.rs | 30 ++- 8 files changed, 481 insertions(+), 227 deletions(-) create mode 100644 rust/kona/crates/node/engine/src/sync/unsafe_head.rs create mode 100644 rust/kona/crates/node/engine/src/test_utils/chain.rs diff --git a/rust/kona/crates/node/engine/src/sync/error.rs b/rust/kona/crates/node/engine/src/sync/error.rs index d98b69d642b..f852bc171b5 100644 --- a/rust/kona/crates/node/engine/src/sync/error.rs +++ b/rust/kona/crates/node/engine/src/sync/error.rs @@ -29,6 +29,22 @@ pub enum SyncStartError { /// Finalized block mismatch #[error("Finalized block mismatch. Expected {0}, Got {1}")] MismatchedFinalizedBlock(B256, B256), + /// The unsafe chain does not lead back to a block it must descend from. + #[error("Unsafe chain does not lead back to {expected}; found {found}")] + UnsafeChainMismatch { + /// The block the unsafe chain must descend from. + expected: B256, + /// The block the unsafe chain has at that height. + found: B256, + }, + /// The unsafe head is below a block it must descend from. + #[error("Unsafe head {unsafe_head} is below block {floor}, which it must descend from")] + UnsafeHeadBelowFloor { + /// The unsafe head's number. + unsafe_head: u64, + /// The number of the block it must descend from. + floor: u64, + }, /// L1 origin mismatch. #[error("L1 origin mismatch")] L1OriginMismatch, diff --git a/rust/kona/crates/node/engine/src/sync/mod.rs b/rust/kona/crates/node/engine/src/sync/mod.rs index d15a4dc828d..9cfbf3a11ae 100644 --- a/rust/kona/crates/node/engine/src/sync/mod.rs +++ b/rust/kona/crates/node/engine/src/sync/mod.rs @@ -12,22 +12,21 @@ pub use error::SyncStartError; mod reorg; pub use reorg::{DerivedSafeHead, find_reorg_forkchoice}; +mod unsafe_head; +use unsafe_head::find_canonical_unsafe_head; + use tracing::info; use crate::EngineClient; /// Searches for the latest [`L2ForkchoiceState`] that we can use to start the sync process with. /// -/// - The *unsafe L2 block*: This is the highest L2 block whose L1 origin is a *plausible* -/// extension of the canonical L1 chain (as known to the rollup node). +/// - The *unsafe L2 block*: This is the highest L2 block, at or above the finalized one, whose L1 +/// origin is canonical: the L1 node has that block at that height. /// - The *safe L2 block*: This is the highest L2 block whose epoch's sequencing window is /// complete within the canonical L1 chain (as known to the rollup node). /// - The *finalized L2 block*: This is the L2 block which is known to be fully derived from /// finalized L1 block data. -/// -/// Plausible: meaning that the blockhash of the L2 block's L1 origin -/// (as reported in the L1 Attributes deposit within the L2 block) is not canonical at another -/// height in the L1 chain, and the same holds for all its ancestors. pub async fn find_starting_forkchoice( cfg: &RollupConfig, engine_client: &EngineClient, @@ -41,40 +40,15 @@ pub async fn find_starting_forkchoice( "Loaded current L2 EL forkchoice state" ); - // Search for the highest `unsafe` block, relative to the initial `unsafe` block's L1 origin, - loop { - let l1_origin = - engine_client.get_l1_block(current_fc.un_safe.l1_origin.hash.into()).await?; - info!( - target: "sync_start", - l1_origin = %current_fc.un_safe.l1_origin.number, - l2_unsafe = %current_fc.un_safe.block_info.number, - "Searching for L2 unsafe block with canonical L1 origin" - ); - - match l1_origin { - Some(_) => { - // Unsafe block has existing L1 origin. Continue with this head. - info!( - target: "sync_start", - l2_unsafe = %current_fc.un_safe.block_info.number, - "Found L2 unsafe block with canonical L1 origin" - ); - break; - } - None => { - let l2_parent_hash = current_fc.un_safe.block_info.parent_hash.into(); - let l2_parent = engine_client - .get_l2_block(l2_parent_hash) - .full() - .await? - .ok_or(SyncStartError::BlockNotFound(l2_parent_hash))?; - - current_fc.un_safe = - L2BlockInfo::from_block_and_genesis(&l2_parent.into_consensus(), &cfg.genesis)?; - } - } - } + // Search for the highest `unsafe` block whose L1 origin is canonical. The finalized head's + // is, so the walk stops there at the latest. + current_fc.un_safe = + find_canonical_unsafe_head(engine_client, current_fc.un_safe, current_fc.finalized).await?; + info!( + target: "sync_start", + l2_unsafe = %current_fc.un_safe.block_info.number, + "Found L2 unsafe block with canonical L1 origin" + ); // Search for the highest `safe` block that's L1 origin is at least older than the sequencing // window, relative to the L1 origin of the `unsafe` block. @@ -149,3 +123,156 @@ mod test { assert_eq!(rpc_reported_hash, l2_block_info.block_info.hash); } } + +#[cfg(test)] +mod cold_start_tests { + use super::*; + use crate::{ + EngineClient, EngineResetError, + test_utils::{L2RpcBlock, RpcMock, TestChain, expect_l1_block, test_engine_client}, + }; + use rstest::rstest; + use serde_json::json; + use std::sync::Arc; + + /// The test chain, and an engine client over scripted L1 and L2 nodes. The sequencing window + /// is long enough that the safe head search always stops at the finalized head. + fn setup() -> (TestChain, Arc, EngineClient, RpcMock, RpcMock) { + let config = Arc::new(RollupConfig { seq_window_size: 1000, ..Default::default() }); + let (client, l1, l2) = test_engine_client(config.clone()); + (TestChain::new(), config, client, l1, l2) + } + + /// How the L1 node answers for L1 block 105, the unsafe head's L1 origin. + #[derive(Debug, Clone, Copy)] + enum Origin { + Canonical, + ReplacedAtTheSameHeight, + NotSeenYet, + } + + /// A cold start keeps the unsafe head only if the L1 node has its L1 origin at that height. + /// Otherwise it walks back to the highest block with a canonical L1 origin: the replaced + /// origin's other block is still served by hash, so finding it by hash would keep a head + /// that can never become safe. Blocks 25 and 26 share L1 origin 105, checked once; block 24's + /// is 104. The safe head is then searched down to the finalized block 18. + #[rstest] + #[case::canonical(Origin::Canonical, 26)] + #[case::replaced_at_the_same_height(Origin::ReplacedAtTheSameHeight, 24)] + #[case::not_seen_yet(Origin::NotSeenYet, 24)] + #[tokio::test] + async fn cold_start_keeps_only_an_unsafe_head_with_a_canonical_l1_origin( + #[case] origin: Origin, + #[case] unsafe_head: u64, + ) { + let (chain, config, client, l1, l2) = setup(); + chain.expect_heads(&l2, 18, 20, 26); + match origin { + Origin::Canonical => expect_l1_block(&l1, 105, 106), + Origin::ReplacedAtTheSameHeight => expect_l1_block(&l1, 105, 105), + Origin::NotSeenYet => l1.expect_params( + "eth_getBlockByNumber", + json!(["0x69", false]), + Option::::None, + ), + } + if unsafe_head < 26 { + chain.expect_by_hash(&l2, 25); + chain.expect_by_hash(&l2, 24); + expect_l1_block(&l1, 104, 105); + } + for number in (18..unsafe_head).rev() { + chain.expect_by_hash(&l2, number); + } + + let forkchoice = find_starting_forkchoice(&config, &client).await.unwrap(); + + assert_eq!(forkchoice.un_safe, chain.info(unsafe_head)); + assert_eq!(forkchoice.safe, chain.info(18)); + assert_eq!(forkchoice.finalized, chain.info(18)); + l1.assert_finished(); + l2.assert_finished(); + } + + /// Block 18 with a different header, so a different block at the finalized height. + fn other_18(chain: &TestChain) -> L2RpcBlock { + let mut block = chain.rpc(18).clone(); + block.header.inner.timestamp += 1; + block.header.hash = block.header.inner.hash_slow(); + block + } + + /// The walk never passes the finalized head. With every L1 origin above it replaced, the + /// unsafe head becomes the finalized head, which the block above it must link to; an unsafe + /// chain that does not lead there fails the reset for good. + #[rstest] + #[case::leads_to_the_finalized_head(false)] + #[case::does_not_lead_to_the_finalized_head(true)] + #[tokio::test] + async fn cold_start_walks_back_no_further_than_the_finalized_head( + #[case] other_finalized: bool, + ) { + let (chain, config, client, l1, l2) = setup(); + let finalized = if other_finalized { other_18(&chain) } else { chain.rpc(18).clone() }; + l2.expect_params("eth_getBlockByNumber", json!(["finalized", true]), &finalized); + l2.expect_params("eth_getBlockByNumber", json!(["safe", true]), chain.rpc(20)); + l2.expect_params("eth_getBlockByNumber", json!(["latest", true]), chain.rpc(26)); + for number in [105, 104, 103, 102, 101, 100] { + expect_l1_block(&l1, number, 100); + } + for number in (19..26).rev() { + chain.expect_by_hash(&l2, number); + } + + let forkchoice = find_starting_forkchoice(&config, &client).await; + + if other_finalized { + let err = forkchoice.unwrap_err(); + assert!( + matches!(err, SyncStartError::UnsafeChainMismatch { found, .. } if found == chain.info(18).block_info.hash), + "got {err:?}" + ); + assert!(!EngineResetError::SyncStart(err).is_temporary()); + } else { + let forkchoice = forkchoice.unwrap(); + assert_eq!(forkchoice.un_safe, chain.info(18)); + assert_eq!(forkchoice.safe, chain.info(18)); + } + l1.assert_finished(); + l2.assert_finished(); + } + + /// An unsafe head at or below the finalized head needs no L1 lookup: at the finalized head it + /// is kept, and as another block at that height or below it, the reset fails for good. + #[rstest] + #[case::the_finalized_head(18, false)] + #[case::another_block_at_its_height(18, true)] + #[case::below_it(20, false)] + #[tokio::test] + async fn cold_start_checks_an_unsafe_head_at_or_below_the_finalized_head( + #[case] finalized: u64, + #[case] other_unsafe: bool, + ) { + let (chain, config, client, l1, l2) = setup(); + let unsafe_head = if other_unsafe { other_18(&chain) } else { chain.rpc(18).clone() }; + l2.expect_params("eth_getBlockByNumber", json!(["finalized", true]), chain.rpc(finalized)); + l2.expect_params("eth_getBlockByNumber", json!(["safe", true]), chain.rpc(finalized)); + l2.expect_params("eth_getBlockByNumber", json!(["latest", true]), &unsafe_head); + + let forkchoice = find_starting_forkchoice(&config, &client).await; + + match (finalized, other_unsafe) { + (18, false) => assert_eq!(forkchoice.unwrap().un_safe, chain.info(18)), + (18, true) => assert!(matches!( + forkchoice.unwrap_err(), + SyncStartError::UnsafeChainMismatch { expected, .. } if expected == chain.info(18).block_info.hash + )), + _ => assert!(matches!( + forkchoice.unwrap_err(), + SyncStartError::UnsafeHeadBelowFloor { unsafe_head: 18, floor: 20 } + )), + } + l1.assert_finished(); + l2.assert_finished(); + } +} diff --git a/rust/kona/crates/node/engine/src/sync/reorg.rs b/rust/kona/crates/node/engine/src/sync/reorg.rs index aabce5c1ee3..0ba28ac3e91 100644 --- a/rust/kona/crates/node/engine/src/sync/reorg.rs +++ b/rust/kona/crates/node/engine/src/sync/reorg.rs @@ -22,6 +22,7 @@ //! //! [`find_starting_forkchoice`]: crate::find_starting_forkchoice +use super::unsafe_head::{find_canonical_unsafe_head, is_canonical_l1}; use crate::{EngineClient, EngineState, EngineSyncState, L2ForkchoiceState, SyncStartError}; use alloy_eips::{BlockId, BlockNumHash}; use kona_protocol::L2BlockInfo; @@ -53,11 +54,20 @@ pub async fn find_reorg_forkchoice( let Some(safe) = find_reorg_safe_head(engine_client, &sync_state, candidates).await? else { return Ok(None); }; - let Some(un_safe) = - find_reorg_unsafe_head(engine_client, sync_state.unsafe_head(), safe).await? - else { - return Ok(None); - }; + let un_safe = + match find_canonical_unsafe_head(engine_client, sync_state.unsafe_head(), safe).await { + Ok(un_safe) => un_safe, + // An unsafe chain that misses a block or does not lead to the kept safe head is left to + // the full reset. + Err( + SyncStartError::BlockNotFound(_) | + SyncStartError::UnsafeChainMismatch { .. } | + SyncStartError::UnsafeHeadBelowFloor { .. }, + ) => { + return Ok(None); + } + Err(err) => return Err(err), + }; info!( target: "sync_start", @@ -96,46 +106,3 @@ async fn find_reorg_safe_head( Ok(None) } - -/// Walks back from `unsafe_head` to the highest block whose L1 origin is canonical, stopping at -/// `safe_head`. `None` if the walk does not lead to `safe_head`. -async fn find_reorg_unsafe_head( - engine_client: &EngineClient, - mut unsafe_head: L2BlockInfo, - safe_head: L2BlockInfo, -) -> Result, SyncStartError> { - let genesis = &engine_client.cfg().genesis; - // Consecutive blocks mostly share an L1 origin; check each replaced one only once. - let mut replaced_origin = None; - while unsafe_head.block_info.number > safe_head.block_info.number { - if replaced_origin != Some(unsafe_head.l1_origin) { - if is_canonical_l1(engine_client, unsafe_head.l1_origin).await? { - return Ok(Some(unsafe_head)); - } - replaced_origin = Some(unsafe_head.l1_origin); - } - - let parent_hash = unsafe_head.block_info.parent_hash; - if unsafe_head.block_info.number == safe_head.block_info.number + 1 { - return Ok((parent_hash == safe_head.block_info.hash).then_some(safe_head)); - } - let Some(parent) = engine_client.get_l2_block(parent_hash.into()).full().await? else { - return Ok(None); - }; - unsafe_head = L2BlockInfo::from_block_and_genesis(&parent.into_consensus(), genesis)?; - } - - Ok((unsafe_head == safe_head).then_some(unsafe_head)) -} - -/// Whether `block` is the canonical L1 block at its height. A block the L1 node does not have at -/// that height yet is not known to be canonical. -async fn is_canonical_l1( - engine_client: &EngineClient, - block: BlockNumHash, -) -> Result { - Ok(engine_client - .get_l1_block(BlockId::number(block.number)) - .await? - .is_some_and(|canonical| canonical.header.hash == block.hash)) -} diff --git a/rust/kona/crates/node/engine/src/sync/unsafe_head.rs b/rust/kona/crates/node/engine/src/sync/unsafe_head.rs new file mode 100644 index 00000000000..915718e6ff2 --- /dev/null +++ b/rust/kona/crates/node/engine/src/sync/unsafe_head.rs @@ -0,0 +1,90 @@ +//! Finding the highest unsafe block whose L1 origin is canonical. + +use crate::{EngineClient, SyncStartError}; +use alloy_eips::{BlockId, BlockNumHash}; +use kona_protocol::L2BlockInfo; +use tracing::info; + +/// Walks back from `unsafe_head` to the highest block whose L1 origin is canonical, never below +/// `floor`, a block whose L1 data is canonical. +/// +/// An L1 origin is canonical when the L1 node has that block at that height. A block built on an +/// origin the L1 node has replaced cannot become safe. One built on an origin the L1 node has not +/// seen yet is not known to be canonical, and is walked back from too; op-node keeps such a head +/// as plausible. The walk visits only blocks built on such origins, checking each origin once, +/// and links the block just above `floor` to it by its parent hash. +/// +/// Fails with [`SyncStartError::UnsafeHeadBelowFloor`] if `unsafe_head` is below `floor`, with +/// [`SyncStartError::BlockNotFound`] if the engine lacks a block on the way, and with +/// [`SyncStartError::UnsafeChainMismatch`] if the chain does not lead back to `floor`. +pub(super) async fn find_canonical_unsafe_head( + engine_client: &EngineClient, + mut unsafe_head: L2BlockInfo, + floor: L2BlockInfo, +) -> Result { + let (head, floor_number) = (unsafe_head.block_info, floor.block_info.number); + if head.number < floor_number { + return Err(SyncStartError::UnsafeHeadBelowFloor { + unsafe_head: head.number, + floor: floor_number, + }); + } + if head.number == floor_number { + return if head.hash == floor.block_info.hash { + Ok(floor) + } else { + Err(SyncStartError::UnsafeChainMismatch { + expected: floor.block_info.hash, + found: head.hash, + }) + }; + } + + let genesis = &engine_client.cfg().genesis; + // Consecutive blocks mostly share an L1 origin; check each replaced one only once. + let mut replaced_origin = None; + loop { + if replaced_origin != Some(unsafe_head.l1_origin) { + if is_canonical_l1(engine_client, unsafe_head.l1_origin).await? { + return Ok(unsafe_head); + } + info!( + target: "sync_start", + l2_unsafe = %unsafe_head.block_info.number, + l1_origin = ?unsafe_head.l1_origin, + "Unsafe block's L1 origin is not canonical; walking back" + ); + replaced_origin = Some(unsafe_head.l1_origin); + } + + let parent_hash = unsafe_head.block_info.parent_hash; + if unsafe_head.block_info.number == floor_number + 1 { + return if parent_hash == floor.block_info.hash { + Ok(floor) + } else { + Err(SyncStartError::UnsafeChainMismatch { + expected: floor.block_info.hash, + found: parent_hash, + }) + }; + } + let parent = engine_client + .get_l2_block(parent_hash.into()) + .full() + .await? + .ok_or(SyncStartError::BlockNotFound(parent_hash.into()))?; + unsafe_head = L2BlockInfo::from_block_and_genesis(&parent.into_consensus(), genesis)?; + } +} + +/// Whether `block` is the canonical L1 block at its height. A block the L1 node does not have at +/// that height yet is not known to be canonical. +pub(super) async fn is_canonical_l1( + engine_client: &EngineClient, + block: BlockNumHash, +) -> Result { + Ok(engine_client + .get_l1_block(BlockId::number(block.number)) + .await? + .is_some_and(|canonical| canonical.header.hash == block.hash)) +} diff --git a/rust/kona/crates/node/engine/src/task_queue/core.rs b/rust/kona/crates/node/engine/src/task_queue/core.rs index dc44e37f58a..864e1202102 100644 --- a/rust/kona/crates/node/engine/src/task_queue/core.rs +++ b/rust/kona/crates/node/engine/src/task_queue/core.rs @@ -387,22 +387,15 @@ mod recovery_tests { #[cfg(test)] mod l1_reorg_reset_tests { use super::*; - use crate::test_utils::{RpcMock, test_engine_client}; - use alloy_eips::BlockNumHash; - use alloy_primitives::{Address, B256, U256}; + use crate::test_utils::{ + L2RpcBlock, RpcMock, TestChain, expect_l1_block, test_engine_client, test_l1_block, + }; + use alloy_primitives::B256; use alloy_rpc_types_engine::{ForkchoiceUpdated, PayloadStatus, PayloadStatusEnum}; - use kona_protocol::{BlockInfo, L1BlockInfoBedrock}; + use kona_protocol::BlockInfo; use rstest::rstest; use serde_json::json; - type L2RpcBlock = ::BlockResponse; - - /// L1 block `number` on `fork`: fork 0 is the chain derivation read, fork 1 replaced it from - /// the reorg height on. - fn l1_id(number: u64, fork: u8) -> BlockNumHash { - BlockNumHash { number, hash: B256::left_padding_from(&[fork, number as u8]) } - } - fn l2_block(number: u64, l1_origin: u64) -> L2BlockInfo { let hash = |n: u64| B256::left_padding_from(&[0xee, n as u8]); L2BlockInfo { @@ -412,20 +405,11 @@ mod l1_reorg_reset_tests { parent_hash: hash(number - 1), timestamp: number, }, - l1_origin: l1_id(l1_origin, 0), + l1_origin: test_l1_block(l1_origin, 0), seq_num: 0, } } - /// Scripts the L1 lookup of block `number`, answered from the chain reorged at - /// `reorg_height`. - fn expect_l1(l1: &RpcMock, number: u64, reorg_height: u64) { - let mut block = alloy_rpc_types_eth::Block::::default(); - block.header.hash = l1_id(number, u8::from(number >= reorg_height)).hash; - block.header.inner.number = number; - l1.expect_params("eth_getBlockByNumber", json!([format!("{number:#x}"), false]), block); - } - /// Scripts the engine's lookup of L2 block `number`, answered with `hash`. fn expect_l2(l2: &RpcMock, number: u64, hash: B256) { let mut block = L2RpcBlock::default(); @@ -457,8 +441,8 @@ mod l1_reorg_reset_tests { /// 106, and L2 block 18 on L1 data up to block 103. fn recent_safe_heads() -> [DerivedSafeHead; 2] { [ - DerivedSafeHead { safe_head: l2_block(20, 100), derived_from: l1_id(106, 0) }, - DerivedSafeHead { safe_head: l2_block(18, 99), derived_from: l1_id(103, 0) }, + DerivedSafeHead { safe_head: l2_block(20, 100), derived_from: test_l1_block(106, 0) }, + DerivedSafeHead { safe_head: l2_block(18, 99), derived_from: test_l1_block(103, 0) }, ] } @@ -517,12 +501,12 @@ mod l1_reorg_reset_tests { .find(|head| head.block_info.number == kept) .unwrap(); let safe_after = if cross_safe.is_some() { before.safe_head() } else { kept }; - expect_l1(&l1, 106, reorg_height); + expect_l1_block(&l1, 106, reorg_height); if reorg_height <= 106 { - expect_l1(&l1, 103, reorg_height); + expect_l1_block(&l1, 103, reorg_height); } expect_l2(&l2, kept.block_info.number, kept.block_info.hash); - expect_l1(&l1, UNSAFE_ORIGIN, reorg_height); + expect_l1_block(&l1, UNSAFE_ORIGIN, reorg_height); if kept != before.local_safe_head() { expect_forkchoice_update(&l2, before.unsafe_head(), safe_after); } @@ -544,8 +528,8 @@ mod l1_reorg_reset_tests { #[tokio::test] async fn finds_nothing_to_keep_when_every_recent_safe_heads_l1_block_was_replaced() { let (engine, client, l1, l2, _) = setup(); - expect_l1(&l1, 106, 103); - expect_l1(&l1, 103, 103); + expect_l1_block(&l1, 106, 103); + expect_l1_block(&l1, 103, 103); let forkchoice = find_reorg_forkchoice(&client, engine.state(), &recent_safe_heads()).await.unwrap(); @@ -567,12 +551,14 @@ mod l1_reorg_reset_tests { #[case] engine_hash: Option, ) { let (engine, client, l1, l2, _) = setup(); - expect_l1(&l1, 106, 108); + expect_l1_block(&l1, 106, 108); if let Some(hash) = engine_hash { expect_l2(&l2, number, hash); } - let candidate = - DerivedSafeHead { safe_head: l2_block(number, 99), derived_from: l1_id(106, 0) }; + let candidate = DerivedSafeHead { + safe_head: l2_block(number, 99), + derived_from: test_l1_block(106, 0), + }; let forkchoice = find_reorg_forkchoice(&client, engine.state(), &[candidate]).await.unwrap(); @@ -582,80 +568,6 @@ mod l1_reorg_reset_tests { l2.assert_finished(); } - /// A real L2 chain from block 18 to block 26, so the unsafe walk can fetch and decode its - /// blocks. Blocks 18 to 20 have L1 origins 99, 100 and 100, blocks 21 to 24 have L1 origins - /// 101 to 104, and blocks 25 and the unsafe head 26 share L1 origin 105. - fn real_chain() -> Vec<(L2BlockInfo, L2RpcBlock)> { - let mut chain: Vec<(L2BlockInfo, L2RpcBlock)> = Vec::new(); - for number in 18..=26 { - let origin = match number { - 18 => 99, - 19 | 20 => 100, - 25 | 26 => 105, - n => 80 + n, - }; - let info = L1BlockInfoBedrock::new( - origin, - 0, - 0, - l1_id(origin, 0).hash, - 0, - Address::ZERO, - U256::ZERO, - U256::ZERO, - ); - let deposit = op_alloy_consensus::OpTxEnvelope::Deposit(alloy_primitives::Sealed::new( - op_alloy_consensus::TxDeposit { - input: info.encode_calldata(), - ..Default::default() - }, - )); - let header = alloy_consensus::Header { - number, - parent_hash: chain.last().map_or(B256::ZERO, |(parent, _)| parent.block_info.hash), - timestamp: number, - ..Default::default() - }; - let consensus = alloy_consensus::Block:: { - header: header.clone(), - body: alloy_consensus::BlockBody { - transactions: vec![deposit.clone()], - ..Default::default() - }, - }; - let block_info = - L2BlockInfo::from_block_and_genesis(&consensus, &RollupConfig::default().genesis) - .unwrap(); - let rpc = L2RpcBlock { - header: alloy_rpc_types_eth::Header { - hash: block_info.block_info.hash, - inner: header, - ..Default::default() - }, - transactions: alloy_rpc_types_eth::BlockTransactions::Full(vec![ - op_alloy_rpc_types::Transaction { - inner: alloy_rpc_types_eth::Transaction { - inner: alloy_consensus::transaction::Recovered::new_unchecked( - deposit, - Address::ZERO, - ), - block_hash: Some(block_info.block_info.hash), - block_number: Some(number), - effective_gas_price: Some(0), - transaction_index: Some(0), - block_timestamp: None, - }, - deposit_nonce: None, - deposit_receipt_version: None, - }, - ]), - ..Default::default() - }; - chain.push((block_info, rpc)); - } - chain - } - /// When the reorg replaced the unsafe head's L1 origin, the unsafe head moves back to the /// highest block whose L1 origin is canonical, never below the kept safe head. Each walk step /// fetches a parent by hash and checks its L1 origin, skipping an origin already found @@ -675,24 +587,22 @@ mod l1_reorg_reset_tests { #[case] unsafe_after: u64, #[case] l1_lookups: &[u64], ) { - let chain = real_chain(); - let block = |number: u64| chain.iter().find(|(info, _)| info.block_info.number == number); - let head = |number: u64| block(number).unwrap().0; + let chain = TestChain::new(); + let head = |number: u64| chain.info(number); let (mut engine, client, l1, l2, config) = engine_at(head(26), head(20)); let candidates: Vec<_> = candidates .iter() .map(|&(safe_head, derived_from)| DerivedSafeHead { safe_head: head(safe_head), - derived_from: l1_id(derived_from, 0), + derived_from: test_l1_block(derived_from, 0), }) .collect(); for &number in l1_lookups { - expect_l1(&l1, number, reorg_height); + expect_l1_block(&l1, number, reorg_height); } expect_l2(&l2, kept, head(kept).block_info.hash); for number in (unsafe_after.max(kept + 1)..26).rev() { - let (info, rpc) = block(number).unwrap(); - l2.expect_params("eth_getBlockByHash", json!([info.block_info.hash, true]), rpc); + chain.expect_by_hash(&l2, number); } let safe_after = head(kept); expect_forkchoice_update(&l2, head(unsafe_after), safe_after); @@ -711,17 +621,16 @@ mod l1_reorg_reset_tests { /// An unsafe chain that does not lead back to the kept safe head gives nothing to keep. #[tokio::test] async fn finds_nothing_to_keep_when_the_unsafe_chain_does_not_lead_to_the_safe_head() { - let chain = real_chain(); - let head = - |number: u64| chain.iter().find(|(info, _)| info.block_info.number == number).unwrap(); - let mut other_20 = head(20).0; + let chain = TestChain::new(); + let mut other_20 = chain.info(20); other_20.block_info.hash = B256::repeat_byte(0xaa); - let (engine, client, l1, l2, _) = engine_at(head(21).0, other_20); - expect_l1(&l1, 100, 101); + let (engine, client, l1, l2, _) = engine_at(chain.info(21), other_20); + expect_l1_block(&l1, 100, 101); expect_l2(&l2, 20, other_20.block_info.hash); - expect_l1(&l1, 101, 101); + expect_l1_block(&l1, 101, 101); - let candidate = DerivedSafeHead { safe_head: other_20, derived_from: l1_id(100, 0) }; + let candidate = + DerivedSafeHead { safe_head: other_20, derived_from: test_l1_block(100, 0) }; let forkchoice = find_reorg_forkchoice(&client, engine.state(), &[candidate]).await.unwrap(); @@ -735,8 +644,8 @@ mod l1_reorg_reset_tests { #[tokio::test] async fn falls_back_to_the_full_walk() { let (mut engine, client, l1, l2, config) = setup(); - expect_l1(&l1, 106, 103); - expect_l1(&l1, 103, 103); + expect_l1_block(&l1, 106, 103); + expect_l1_block(&l1, 103, 103); l2.expect_error("eth_getBlockByNumber"); let err = diff --git a/rust/kona/crates/node/engine/src/test_utils/chain.rs b/rust/kona/crates/node/engine/src/test_utils/chain.rs new file mode 100644 index 00000000000..f77b554f440 --- /dev/null +++ b/rust/kona/crates/node/engine/src/test_utils/chain.rs @@ -0,0 +1,144 @@ +//! A real L2 chain over a scripted L1 chain, for tests of the sync start and reorg walks. + +use crate::test_utils::RpcMock; +use alloy_eips::BlockNumHash; +use alloy_primitives::{Address, B256, U256}; +use kona_genesis::RollupConfig; +use kona_protocol::{L1BlockInfoBedrock, L2BlockInfo}; +use serde_json::json; + +/// An L2 block as the engine's RPC returns it. +pub type L2RpcBlock = ::BlockResponse; + +/// L1 block `number` on `fork`: fork 0 is the chain derivation read, fork 1 replaced it from +/// some height on. +pub fn test_l1_block(number: u64, fork: u8) -> BlockNumHash { + BlockNumHash { number, hash: B256::left_padding_from(&[fork, number as u8]) } +} + +/// Scripts the L1 node's lookup of block `number`, on the chain whose blocks from +/// `replaced_from` on are on fork 1. +pub fn expect_l1_block(l1: &RpcMock, number: u64, replaced_from: u64) { + let mut block = alloy_rpc_types_eth::Block::::default(); + block.header.hash = test_l1_block(number, u8::from(number >= replaced_from)).hash; + block.header.inner.number = number; + l1.expect_params("eth_getBlockByNumber", json!([format!("{number:#x}"), false]), block); +} + +/// A real L2 chain from block 18 to block 26, so the unsafe walks can fetch and decode its +/// blocks. Blocks 18 to 20 have L1 origins 99, 100 and 100, blocks 21 to 24 have L1 origins +/// 101 to 104, and blocks 25 and 26 share L1 origin 105. +#[derive(Debug)] +pub struct TestChain { + blocks: Vec<(L2BlockInfo, L2RpcBlock)>, +} + +impl Default for TestChain { + fn default() -> Self { + Self::new() + } +} + +impl TestChain { + /// Builds the chain. + pub fn new() -> Self { + let mut blocks: Vec<(L2BlockInfo, L2RpcBlock)> = Vec::new(); + for number in 18..=26 { + let origin = match number { + 18 => 99, + 19 | 20 => 100, + 25 | 26 => 105, + n => 80 + n, + }; + let info = L1BlockInfoBedrock::new( + origin, + 0, + 0, + test_l1_block(origin, 0).hash, + 0, + Address::ZERO, + U256::ZERO, + U256::ZERO, + ); + let deposit = op_alloy_consensus::OpTxEnvelope::Deposit(alloy_primitives::Sealed::new( + op_alloy_consensus::TxDeposit { + input: info.encode_calldata(), + ..Default::default() + }, + )); + let header = alloy_consensus::Header { + number, + parent_hash: blocks.last().map_or(B256::ZERO, |(parent, _)| parent.block_info.hash), + timestamp: number, + ..Default::default() + }; + let consensus = alloy_consensus::Block:: { + header: header.clone(), + body: alloy_consensus::BlockBody { + transactions: vec![deposit.clone()], + ..Default::default() + }, + }; + let block_info = + L2BlockInfo::from_block_and_genesis(&consensus, &RollupConfig::default().genesis) + .unwrap(); + let rpc = L2RpcBlock { + header: alloy_rpc_types_eth::Header { + hash: block_info.block_info.hash, + inner: header, + ..Default::default() + }, + transactions: alloy_rpc_types_eth::BlockTransactions::Full(vec![ + op_alloy_rpc_types::Transaction { + inner: alloy_rpc_types_eth::Transaction { + inner: alloy_consensus::transaction::Recovered::new_unchecked( + deposit, + Address::ZERO, + ), + block_hash: Some(block_info.block_info.hash), + block_number: Some(number), + effective_gas_price: Some(0), + transaction_index: Some(0), + block_timestamp: None, + }, + deposit_nonce: None, + deposit_receipt_version: None, + }, + ]), + ..Default::default() + }; + blocks.push((block_info, rpc)); + } + Self { blocks } + } + + /// Block `number`'s info. + pub fn info(&self, number: u64) -> L2BlockInfo { + self.block(number).0 + } + + /// Block `number` as the engine's RPC returns it. + pub fn rpc(&self, number: u64) -> &L2RpcBlock { + &self.block(number).1 + } + + /// Scripts the engine's lookup of block `number` by hash, with transactions. + pub fn expect_by_hash(&self, l2: &RpcMock, number: u64) { + let (info, rpc) = self.block(number); + l2.expect_params("eth_getBlockByHash", json!([info.block_info.hash, true]), rpc); + } + + /// Scripts the engine's lookups of its finalized, safe and latest blocks. + pub fn expect_heads(&self, l2: &RpcMock, finalized: u64, safe: u64, latest: u64) { + for (tag, number) in [("finalized", finalized), ("safe", safe), ("latest", latest)] { + l2.expect_params("eth_getBlockByNumber", json!([tag, true]), self.rpc(number)); + } + } + + fn block(&self, number: u64) -> &(L2BlockInfo, L2RpcBlock) { + self.blocks + .iter() + .find(|(info, _)| info.block_info.number == number) + .unwrap_or_else(|| panic!("no block {number} in the test chain")) + } +} diff --git a/rust/kona/crates/node/engine/src/test_utils/mod.rs b/rust/kona/crates/node/engine/src/test_utils/mod.rs index a5575963a67..af89fc92067 100644 --- a/rust/kona/crates/node/engine/src/test_utils/mod.rs +++ b/rust/kona/crates/node/engine/src/test_utils/mod.rs @@ -9,3 +9,6 @@ pub use engine_state::TestEngineStateBuilder; mod misc; pub use misc::test_block_info; + +mod chain; +pub use chain::{L2RpcBlock, TestChain, expect_l1_block, test_l1_block}; diff --git a/rust/kona/crates/node/service/src/actors/engine/tests.rs b/rust/kona/crates/node/service/src/actors/engine/tests.rs index eded3d472ca..74096f9f848 100644 --- a/rust/kona/crates/node/service/src/actors/engine/tests.rs +++ b/rust/kona/crates/node/service/src/actors/engine/tests.rs @@ -4,7 +4,7 @@ use alloy_primitives::B256; use alloy_rpc_types_engine::{ForkchoiceUpdated, PayloadStatus, PayloadStatusEnum}; use kona_engine::{ Engine, EngineActorRequest, EngineState, EngineSyncStateUpdate, FinalizeBlockId, NoopBlockSink, - test_utils::test_engine_client, + test_utils::{TestChain, expect_l1_block, test_engine_client}, }; use kona_genesis::RollupConfig; use kona_protocol::{BlockInfo, L2BlockInfo}; @@ -26,18 +26,16 @@ async fn admin_reset_recovers_and_completes_original_request( #[case] l1_failure: bool, #[case] read_delay: Duration, ) { - let block: ::BlockResponse = - Default::default(); - let mut config = RollupConfig::default(); - config.genesis.l2.hash = block.header.inner.hash_slow(); - let config = Arc::new(config); + // Finalized, safe and unsafe heads 18, 20 and 26 of a real chain, so the reset checks the + // unsafe head's L1 origin. The sequencing window is long enough that the safe head search + // stops at the finalized head. + let chain = TestChain::new(); + let config = Arc::new(RollupConfig { seq_window_size: 1000, ..Default::default() }); let (client, l1, l2) = test_engine_client(config.clone()); let client = Arc::new(client); if l1_failure { - for tag in ["finalized", "safe", "latest"] { - l2.expect_params("eth_getBlockByNumber", serde_json::json!([tag, true]), &block); - } - l1.expect_error("eth_getBlockByHash"); + chain.expect_heads(&l2, 18, 20, 26); + l1.expect_error("eth_getBlockByNumber"); } else { l2.expect_error("eth_getBlockByNumber"); } @@ -65,13 +63,13 @@ async fn admin_reset_recovers_and_completes_original_request( actor.step().await.unwrap(); // retain the reset actor.step().await.unwrap(); // failed attempt, then wait for backoff assert!(!reset.is_finished()); - for _ in 0..3 { - l2.expect_with_delay("eth_getBlockByNumber", &block, read_delay); + for number in [18, 20, 26] { + l2.expect_with_delay("eth_getBlockByNumber", chain.rpc(number), read_delay); + } + expect_l1_block(&l1, 105, 106); + for number in (18..26).rev() { + chain.expect_by_hash(&l2, number); } - l1.expect( - "eth_getBlockByHash", - alloy_rpc_types_eth::Block::::default(), - ); l2.expect( "engine_forkchoiceUpdatedV3", ForkchoiceUpdated::new(PayloadStatus::from_status(PayloadStatusEnum::Valid)),