1use crate::tree::{payload_validator::EngineValidator, EngineApiTreeHandler, WaitForCaches};
4use alloy_consensus::BlockHeader;
5use alloy_eips::NumHash;
6use alloy_primitives::B256;
7use reth_chain_state::{ExecutedBlock, NewCanonicalChain};
8use reth_concurrency::sync::time::FastInstant as Instant;
9use reth_engine_primitives::ConsensusEngineEvent;
10use reth_errors::ProviderResult;
11use reth_evm::{debug_unreachable, ConfigureEvm};
12use reth_payload_primitives::{BuiltPayload, PayloadTypes};
13use reth_primitives_traits::{NodePrimitives, RecoveredBlock, SealedHeader};
14use reth_provider::{
15 BalProvider, BlockExecutionOutput, BlockExecutionResult, BlockReader, ChangeSetReader,
16 DatabaseProviderFactory, ProviderError, PruneCheckpointReader, StageCheckpointReader,
17 StateProviderFactory, StateReader, StorageChangeSetReader, StorageSettingsCache,
18 TransactionVariant,
19};
20use reth_trie::{HashedPostState, KeccakKeyHasher, SortedTrieData};
21use std::sync::Arc;
22use tracing::{debug, instrument, trace, warn};
23
24impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
25where
26 N: NodePrimitives,
27 P: DatabaseProviderFactory
28 + BlockReader<Block = N::Block, Header = N::BlockHeader>
29 + StateProviderFactory
30 + StateReader<Receipt = N::Receipt>
31 + BalProvider
32 + Clone
33 + 'static,
34 P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
35 + PruneCheckpointReader
36 + StageCheckpointReader
37 + ChangeSetReader
38 + StorageChangeSetReader
39 + StorageSettingsCache
40 + 'static,
41 C: ConfigureEvm<Primitives = N> + 'static,
42 T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
43 V: EngineValidator<T> + WaitForCaches,
44{
45 pub(super) fn on_new_head(
52 &self,
53 new_head: B256,
54 ) -> ProviderResult<Option<NewCanonicalChain<N>>> {
55 let Some(new_head_block) = self.state.tree_state.executed_block_by_hash(new_head) else {
57 debug!(target: "engine::tree", new_head=?new_head, "New head block not found in inmemory tree state");
58 self.metrics.engine.executed_new_block_cache_miss.increment(1);
59 return Ok(None)
60 };
61
62 let new_head_number = new_head_block.recovered_block().number();
63 let mut current_canonical_number = self.state.tree_state.current_canonical_head.number;
64
65 let Some(mut current_number) = new_head_number.checked_sub(1) else { return Ok(None) };
68 let mut current_hash = new_head_block.recovered_block().parent_hash();
69 let mut new_chain = vec![new_head_block];
70
71 while current_number > current_canonical_number {
76 if let Some(block) = self.state.tree_state.executed_block_by_hash(current_hash) {
77 current_hash = block.recovered_block().parent_hash();
78 current_number -= 1;
79 new_chain.push(block);
80 } else {
81 warn!(target: "engine::tree", current_hash=?current_hash, "Sidechain block not found in TreeState");
82 return Ok(None)
85 }
86 }
87
88 if current_hash == self.state.tree_state.current_canonical_head.hash {
91 new_chain.reverse();
92
93 return Ok(Some(NewCanonicalChain::Commit { new: new_chain }))
95 }
96
97 let mut old_chain = Vec::new();
99 let mut old_hash = self.state.tree_state.current_canonical_head.hash;
100
101 while current_canonical_number > current_number {
104 let block = self.canonical_block_by_hash(old_hash)?;
105 old_hash = block.recovered_block().parent_hash();
106 old_chain.push(block);
107 current_canonical_number -= 1;
108 }
109
110 debug_assert_eq!(current_number, current_canonical_number);
112
113 while old_hash != current_hash {
116 let block = self.canonical_block_by_hash(old_hash)?;
117 old_hash = block.recovered_block().parent_hash();
118 old_chain.push(block);
119
120 if let Some(block) = self.state.tree_state.executed_block_by_hash(current_hash) {
121 current_hash = block.recovered_block().parent_hash();
122 new_chain.push(block);
123 } else {
124 warn!(target: "engine::tree", invalid_hash=?current_hash, "New chain block not found in TreeState");
126 return Ok(None)
127 }
128 }
129 new_chain.reverse();
130 old_chain.reverse();
131
132 Ok(Some(NewCanonicalChain::Reorg { new: new_chain, old: old_chain }))
133 }
134
135 pub(super) fn update_latest_block_to_canonical_ancestor(
147 &mut self,
148 canonical_header: &SealedHeader<N::BlockHeader>,
149 ) -> ProviderResult<()> {
150 debug!(target: "engine::tree", head = ?canonical_header.num_hash(), "Update latest block to canonical ancestor");
151 let current_head_number = self.state.tree_state.canonical_block_number();
152 let new_head_number = canonical_header.number();
153 let new_head_hash = canonical_header.hash();
154
155 self.state.tree_state.set_canonical_head(canonical_header.num_hash());
157
158 if new_head_number < current_head_number {
160 debug!(
161 target: "engine::tree",
162 current_head = current_head_number,
163 new_head = new_head_number,
164 new_head_hash = ?new_head_hash,
165 "FCU unwind detected: reverting to canonical ancestor"
166 );
167
168 self.handle_canonical_chain_unwind(current_head_number, canonical_header)
169 } else {
170 debug!(
171 target: "engine::tree",
172 previous_head = current_head_number,
173 new_head = new_head_number,
174 new_head_hash = ?new_head_hash,
175 "Advancing latest block to canonical ancestor"
176 );
177 self.handle_chain_advance_or_same_height(canonical_header)
178 }
179 }
180
181 fn handle_canonical_chain_unwind(
184 &mut self,
185 current_head_number: u64,
186 canonical_header: &SealedHeader<N::BlockHeader>,
187 ) -> ProviderResult<()> {
188 let new_head_number = canonical_header.number();
189 debug!(
190 target: "engine::tree",
191 from = current_head_number,
192 to = new_head_number,
193 "Handling unwind: collecting blocks to remove from in-memory state"
194 );
195
196 let old_blocks =
198 self.collect_blocks_for_canonical_unwind(new_head_number, current_head_number);
199
200 self.apply_canonical_ancestor_via_reorg(canonical_header, old_blocks)
202 }
203
204 fn collect_blocks_for_canonical_unwind(
206 &self,
207 new_head_number: u64,
208 current_head_number: u64,
209 ) -> Vec<ExecutedBlock<N>> {
210 let mut old_blocks =
211 Vec::with_capacity((current_head_number.saturating_sub(new_head_number)) as usize);
212
213 for block_num in (new_head_number + 1)..=current_head_number {
214 if let Some(block_state) = self.canonical_in_memory_state().state_by_number(block_num) {
215 let executed_block = block_state.block_ref().clone();
216 old_blocks.push(executed_block);
217 debug!(
218 target: "engine::tree",
219 block_number = block_num,
220 "Collected block for removal from in-memory state"
221 );
222 }
223 }
224
225 if old_blocks.is_empty() {
226 debug!(
227 target: "engine::tree",
228 "No blocks found in memory to remove, will clear and reset state"
229 );
230 }
231
232 old_blocks
233 }
234
235 fn apply_canonical_ancestor_via_reorg(
237 &mut self,
238 canonical_header: &SealedHeader<N::BlockHeader>,
239 old_blocks: Vec<ExecutedBlock<N>>,
240 ) -> ProviderResult<()> {
241 let new_head_hash = canonical_header.hash();
242 let new_head_number = canonical_header.number();
243
244 let executed_block = self.canonical_block_by_hash(new_head_hash)?;
246 self.canonical_in_memory_state_writer
249 .update_chain(NewCanonicalChain::Reorg { new: vec![executed_block], old: old_blocks });
250 self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
251
252 debug!(
253 target: "engine::tree",
254 block_number = new_head_number,
255 block_hash = ?new_head_hash,
256 "Successfully loaded canonical ancestor into memory via reorg"
257 );
258
259 Ok(())
260 }
261
262 fn handle_chain_advance_or_same_height(
264 &mut self,
265 canonical_header: &SealedHeader<N::BlockHeader>,
266 ) -> ProviderResult<()> {
267 self.ensure_block_in_memory(canonical_header.number(), canonical_header.hash())?;
269
270 self.canonical_in_memory_state_writer.set_canonical_head(canonical_header.clone());
273
274 Ok(())
275 }
276
277 fn ensure_block_in_memory(
279 &mut self,
280 block_number: u64,
281 block_hash: B256,
282 ) -> ProviderResult<()> {
283 if self.canonical_in_memory_state().state_by_number(block_number).is_some() {
285 return Ok(());
286 }
287
288 let executed_block = self.canonical_block_by_hash(block_hash)?;
290 self.canonical_in_memory_state_writer
291 .update_chain(NewCanonicalChain::Commit { new: vec![executed_block] });
292 self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
293
294 debug!(
295 target: "engine::tree",
296 block_number,
297 block_hash = ?block_hash,
298 "Added canonical block to in-memory state"
299 );
300
301 Ok(())
302 }
303
304 pub(super) fn make_canonical(&mut self, target: B256) -> ProviderResult<()> {
308 if let Some(chain_update) = self.on_new_head(target)? {
309 self.on_canonical_chain_update(chain_update);
310 }
311
312 self.on_canonicalized_sync_target(target);
313
314 Ok(())
315 }
316
317 pub(super) fn on_canonicalized_sync_target(&mut self, target: B256) {
319 let Some(sync_target_state) = self
320 .state
321 .forkchoice_state_tracker
322 .sync_target_state()
323 .filter(|state| state.head_block_hash == target)
324 else {
325 return;
326 };
327
328 if let Err(outcome) = self.ensure_consistent_forkchoice_state(sync_target_state) {
329 debug!(
330 target: "engine::tree",
331 head = %sync_target_state.head_block_hash,
332 safe = %sync_target_state.safe_block_hash,
333 finalized = %sync_target_state.finalized_block_hash,
334 ?outcome,
335 "Canonicalized sync target head before safe/finalized could be applied"
336 );
337 return;
338 }
339
340 self.state.forkchoice_state_tracker.promote_sync_target_to_valid(sync_target_state);
341 }
342
343 #[instrument(level = "debug", target = "engine::tree", skip(self))]
350 fn canonical_block_by_hash(&self, hash: B256) -> ProviderResult<ExecutedBlock<N>> {
351 trace!(target: "engine::tree", ?hash, "Fetching executed block by hash");
352 if let Some(block) = self.state.tree_state.executed_block_by_hash(hash) {
354 return Ok(block)
355 }
356
357 let (block, senders) = self
358 .provider
359 .sealed_block_with_senders(hash.into(), TransactionVariant::WithHash)?
360 .ok_or_else(|| ProviderError::HeaderNotFound(hash.into()))?
361 .split_sealed();
362 let mut execution_output = self
363 .provider
364 .get_state(block.header().number())?
365 .ok_or_else(|| ProviderError::StateForNumberNotFound(block.header().number()))?;
366 let bundle_state = execution_output.state();
367 let hashed_state = if block.parent_hash().is_zero() {
372 HashedPostState::from_bundle_state::<KeccakKeyHasher>(bundle_state.state())
373 } else {
374 self.provider
375 .state_by_block_hash(block.parent_hash())?
376 .hashed_post_state(bundle_state)?
377 };
378
379 debug!(
380 target: "engine::tree",
381 number = ?block.number(),
382 "computing block trie updates",
383 );
384 let db_provider = self.provider.database_provider_ro()?;
385 let trie_updates = self
386 .state
387 .tree_state
388 .overlay_manager
389 .compute_block_trie_updates(&db_provider, block.number())?;
390
391 let sorted_hashed_state = Arc::new(hashed_state.into_sorted());
392 let sorted_trie_updates = Arc::new(trie_updates);
393 let trie_data = SortedTrieData::new(sorted_hashed_state, sorted_trie_updates);
394
395 let execution_output = Arc::new(BlockExecutionOutput {
396 state: execution_output.bundle,
397 result: BlockExecutionResult {
398 receipts: execution_output.receipts.pop().unwrap_or_default(),
399 requests: execution_output.requests.pop().unwrap_or_default(),
400 gas_used: block.gas_used(),
401 blob_gas_used: block.blob_gas_used().unwrap_or_default(),
402 },
403 });
404
405 Ok(ExecutedBlock::new(
406 Arc::new(RecoveredBlock::new_sealed(block, senders)),
407 execution_output,
408 trie_data,
409 ))
410 }
411
412 pub(super) fn on_canonical_chain_update(&mut self, chain_update: NewCanonicalChain<N>) {
416 trace!(target: "engine::tree", new_blocks = %chain_update.new_block_count(), reorged_blocks = %chain_update.reorged_block_count(), "applying new chain update");
417 let start = Instant::now();
418
419 self.state.tree_state.set_canonical_head(chain_update.tip().num_hash());
421
422 let tip = chain_update.tip().clone_sealed_header();
423 let notification = chain_update.to_chain_notification();
424
425 if let NewCanonicalChain::Reorg { new, old } = &chain_update {
426 let new_first = new.first().map(|first| first.recovered_block().num_hash());
427 let old_first = old.first().map(|first| first.recovered_block().num_hash());
428 trace!(target: "engine::tree", ?new_first, ?old_first, "Reorg detected, new and old first blocks");
429
430 self.state.set_pending_sparse_trie_prune(false);
431 self.update_reorg_metrics(old.len(), old_first);
432 }
433
434 self.canonical_in_memory_state_writer.update_chain(chain_update);
437 self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
438 self.payload_validator.on_canonical_head_changed(tip.hash(), &self.state);
439
440 self.metrics.tree.canonical_chain_height.set(tip.number() as f64);
442
443 self.canonical_in_memory_state_writer.notify_canon_state(notification);
445
446 self.emit_event(ConsensusEngineEvent::CanonicalChainCommitted(
448 Box::new(tip),
449 start.elapsed(),
450 ));
451 }
452
453 pub(super) fn update_reorg_metrics(
455 &self,
456 old_chain_length: usize,
457 first_reorged_block: Option<NumHash>,
458 ) {
459 if let Some(first_reorged_block) = first_reorged_block.map(|block| block.number) {
460 if let Some(finalized) = self.canonical_in_memory_state().get_finalized_num_hash() &&
461 first_reorged_block <= finalized.number
462 {
463 self.metrics.tree.reorgs.finalized.increment(1);
464 } else if let Some(safe) = self.canonical_in_memory_state().get_safe_num_hash() &&
465 first_reorged_block <= safe.number
466 {
467 self.metrics.tree.reorgs.safe.increment(1);
468 } else {
469 self.metrics.tree.reorgs.head.increment(1);
470 }
471 } else {
472 debug_unreachable!("Reorged chain doesn't have any blocks");
473 }
474 self.metrics.tree.latest_reorg_depth.set(old_chain_length as f64);
475 }
476}