Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions rust/kona/crates/node/engine/src/sync/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
207 changes: 167 additions & 40 deletions rust/kona/crates/node/engine/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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<RollupConfig>, 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::<alloy_rpc_types_eth::Block>::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();
}
}
63 changes: 15 additions & 48 deletions rust/kona/crates/node/engine/src/sync/reorg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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<Option<L2BlockInfo>, 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<bool, SyncStartError> {
Ok(engine_client
.get_l1_block(BlockId::number(block.number))
.await?
.is_some_and(|canonical| canonical.header.hash == block.hash))
}
Loading
Loading