Skip to main content

reth_engine_tree/tree/
sync.rs

1//! Backfill sync and block download handling of the engine API tree handler.
2
3use crate::{
4    backfill::{BackfillAction, BackfillSyncState},
5    engine::{DownloadRequest, EngineApiEvent, FromEngine},
6    tree::{
7        error::{
8            InsertBlockError, InsertBlockFatalError, InsertBlockProcessingError, InsertPayloadError,
9        },
10        payload_validator::EngineValidator,
11        BlockStatus, EngineApiTreeHandler, InsertPayloadOk, TreeAction, TreeEvent, WaitForCaches,
12    },
13};
14use alloy_consensus::BlockHeader;
15use alloy_eips::BlockNumHash;
16use alloy_primitives::B256;
17use alloy_rpc_types_engine::ForkchoiceState;
18use reth_errors::ProviderResult;
19use reth_evm::ConfigureEvm;
20use reth_network_p2p::full_block::SealedBlockWithAccessList;
21use reth_payload_primitives::{BuiltPayload, PayloadTypes};
22use reth_primitives_traits::{NodePrimitives, SealedHeader};
23use reth_provider::{
24    BalProvider, BlockReader, ChangeSetReader, DatabaseProviderFactory, HeaderProvider,
25    PruneCheckpointReader, StageCheckpointReader, StateProviderFactory, StateReader,
26    StorageChangeSetReader, StorageSettingsCache,
27};
28use reth_stages_api::ControlFlow;
29use tracing::{debug, instrument, trace, warn};
30
31impl<N, P, T, V, C> EngineApiTreeHandler<N, P, T, V, C>
32where
33    N: NodePrimitives,
34    P: DatabaseProviderFactory
35        + BlockReader<Block = N::Block, Header = N::BlockHeader>
36        + StateProviderFactory
37        + StateReader<Receipt = N::Receipt>
38        + BalProvider
39        + Clone
40        + 'static,
41    P::Provider: BlockReader<Block = N::Block, Header = N::BlockHeader>
42        + PruneCheckpointReader
43        + StageCheckpointReader
44        + ChangeSetReader
45        + StorageChangeSetReader
46        + StorageSettingsCache
47        + 'static,
48    C: ConfigureEvm<Primitives = N> + 'static,
49    T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
50    V: EngineValidator<T> + WaitForCaches,
51{
52    /// Invoked when previously requested blocks were downloaded.
53    ///
54    /// If the block count exceeds the configured batch size we're allowed to execute at once, this
55    /// will execute the first batch and send the remaining blocks back through the channel so that
56    /// block request processing isn't blocked for a long time.
57    pub(super) fn on_downloaded(
58        &mut self,
59        mut blocks: Vec<SealedBlockWithAccessList<N::Block>>,
60    ) -> Result<Option<TreeEvent>, InsertBlockFatalError> {
61        if blocks.is_empty() {
62            // nothing to execute
63            return Ok(None)
64        }
65
66        trace!(target: "engine::tree", block_count = %blocks.len(), "received downloaded blocks");
67        let batch = self.config.max_execute_block_batch_size().min(blocks.len());
68        for block in blocks.drain(..batch) {
69            if let Some(event) = self.on_downloaded_block(block)? {
70                let needs_backfill = event.is_backfill_action();
71                self.on_tree_event(event)?;
72                if needs_backfill {
73                    // can exit early if backfill is needed
74                    return Ok(None)
75                }
76            }
77        }
78
79        // if we still have blocks to execute, send them as a followup request
80        if !blocks.is_empty() {
81            let _ = self.incoming_tx.send(FromEngine::DownloadedBlocks(blocks));
82        }
83
84        Ok(None)
85    }
86
87    /// Invoked if the backfill sync has finished to target.
88    ///
89    /// At this point we consider the block synced to the backfill target.
90    ///
91    /// Checks the tracked finalized block against the block on disk and requests another backfill
92    /// run if the distance to the tip exceeds the threshold for another backfill run.
93    ///
94    /// This will also do the necessary housekeeping of the in-memory state, this includes:
95    ///  - removing all blocks below the backfill height
96    ///  - moving the remaining canonical in-memory blocks to the non-canonical section
97    ///  - making the backfill block the canonical head
98    ///
99    /// In case backfill resulted in an unwind, this will remove all in-memory blocks.
100    ///
101    /// If the header of the backfill block is not found in the database, the in-memory blocks, the
102    /// canonical head and the persisted block stay as they are. An error reading it is returned
103    /// at the same point.
104    pub(super) fn on_backfill_sync_finished(
105        &mut self,
106        ctrl: ControlFlow,
107    ) -> Result<(), InsertBlockFatalError> {
108        debug!(target: "engine::tree", "received backfill sync finished event");
109        self.backfill_sync_state = BackfillSyncState::Idle;
110
111        // Pipeline unwound, memorize the invalid block and wait for CL for next sync target.
112        let backfill_height = if let ControlFlow::Unwind { bad_block, target } = &ctrl {
113            warn!(target: "engine::tree", invalid_block=?bad_block, "Bad block detected in unwind");
114            // update the `invalid_headers` cache with the new invalid header
115            self.state.invalid_headers.insert(**bad_block);
116
117            // if this was an unwind then the target is the new height
118            Some(*target)
119        } else {
120            // backfill height is the block number that the backfill finished at
121            ctrl.block_number()
122        };
123
124        // backfill height is the block number that the backfill finished at
125        let Some(backfill_height) = backfill_height else { return Ok(()) };
126
127        // state house keeping after backfill sync
128        // remove all executed blocks below the backfill height
129        //
130        // The header is read from the database, because the provider prefers the canonical
131        // in-memory blocks, which can still hold a block that backfill replaced at this height.
132        let Some(backfill_head) =
133            self.provider.database_provider_ro()?.sealed_header(backfill_height)?
134        else {
135            debug!(target: "engine::tree", ?ctrl, "Backfill block not found");
136            return Ok(())
137        };
138        let backfill_num_hash = backfill_head.num_hash();
139
140        if ctrl.is_unwind() {
141            // the node reset so we need to clear everything above that height so that backfill
142            // height is the new canonical block.
143            self.state.set_pending_sparse_trie_prune(false);
144            self.state.tree_state.set_canonical_head(backfill_num_hash);
145            self.canonical_in_memory_state_writer.clear_state(backfill_head);
146        } else {
147            // The in-memory state drops the blocks up to the backfill height and the blocks that
148            // conflict with the backfill block. The other executed blocks stay in it, but none of
149            // them is canonical.
150            self.canonical_in_memory_state_writer.on_backfill_finished(
151                self.persistence_state.last_persisted_block.hash,
152                backfill_head,
153            );
154        }
155
156        self.metrics.engine.executed_blocks.set(self.state.tree_state.block_count() as f64);
157        self.metrics.tree.canonical_chain_height.set(backfill_height as f64);
158
159        // remove all buffered blocks below the backfill height
160        self.state.buffer.remove_old_blocks(backfill_height);
161        self.purge_timing_stats(backfill_height, None);
162
163        // update the tracked chain height, after backfill sync both the canonical height and
164        // persisted height are the same
165        self.state.tree_state.set_canonical_head(backfill_num_hash);
166        self.persistence_state.finish(backfill_num_hash, backfill_num_hash);
167
168        // If the pipeline reached the head of the syncing FCU, apply its safe and finalized
169        // blocks now that the head is canonical. An unwind must wait for a new FCU because the
170        // supplied sync target may have been invalidated.
171        if !ctrl.is_unwind() {
172            self.on_canonicalized_sync_target(backfill_num_hash.hash);
173        }
174
175        // check if we need to run backfill again by comparing the most recent backfill target
176        // height to the backfill height
177        let Some(sync_target_state) = self.state.forkchoice_state_tracker.sync_target_state()
178        else {
179            return Ok(())
180        };
181        if !self.engine_kind.is_opstack() && sync_target_state.finalized_block_hash.is_zero() {
182            // no finalized block, can't check distance on non-OP Stack chains
183            return Ok(())
184        }
185        let target_hash = self.backfill_target_hash(sync_target_state);
186        if target_hash.is_zero() {
187            return Ok(())
188        }
189        // get the block number of the backfill target block, if we have it buffered
190        let newest_target = self.state.buffer.block(&target_hash).map(|block| block.number());
191
192        // The block number that the backfill finished at - if the progress or newest target is
193        // None then we can't check the distance anyways.
194        //
195        // If both are Some, we perform another distance check and return the desired backfill
196        // target
197        if let Some(backfill_target) =
198            ctrl.block_number().zip(newest_target).and_then(|(progress, target_number)| {
199                // Determines whether or not we should run backfill again, in case
200                // the new gap is still large enough and requires running backfill again
201                self.backfill_sync_target(progress, target_number, None)
202            })
203        {
204            // request another backfill run
205            self.emit_event(EngineApiEvent::BackfillAction(BackfillAction::Start(
206                backfill_target.into(),
207            )));
208            return Ok(())
209        };
210
211        // A head on a rejected block has nothing left to download.
212        let lowest_ancestor = self.lowest_buffered_ancestor_or(sync_target_state.head_block_hash);
213        if self.state.invalid_headers.get(&lowest_ancestor).is_some() {
214            return self.try_connect_buffered_blocks(self.state.tree_state.current_canonical_head)
215        }
216
217        // Check if there are more blocks to sync between current head and FCU target
218        if let Some(lowest_buffered) =
219            self.state.buffer.lowest_ancestor(&sync_target_state.head_block_hash)
220        {
221            let current_head_num = self.state.tree_state.current_canonical_head.number;
222            let target_head_num = lowest_buffered.number();
223
224            if let Some(distance) = self.distance_from_local_tip(current_head_num, target_head_num)
225            {
226                // There are blocks between current head and FCU target, download them
227                debug!(
228                    target: "engine::tree",
229                    %current_head_num,
230                    %target_head_num,
231                    %distance,
232                    "Backfill complete, downloading remaining blocks to reach FCU target"
233                );
234
235                self.emit_event(EngineApiEvent::Download(
236                    DownloadRequest::block_range(lowest_buffered.parent_num_hash(), distance)
237                        .with_access_lists(self.should_download_access_lists()),
238                ));
239                return Ok(());
240            }
241        } else {
242            // We don't have the head block or any of its ancestors buffered. Request
243            // a download for the head block which will then trigger further sync.
244            debug!(
245                target: "engine::tree",
246                head_hash = %sync_target_state.head_block_hash,
247                "Backfill complete but head block not buffered, requesting download"
248            );
249            self.emit_event(EngineApiEvent::Download(
250                DownloadRequest::single_block(sync_target_state.head_block_hash)
251                    .with_access_lists(self.should_download_access_lists()),
252            ));
253            return Ok(());
254        }
255
256        // try to close the gap by executing buffered blocks that are child blocks of the new head
257        self.try_connect_buffered_blocks(self.state.tree_state.current_canonical_head)
258    }
259
260    /// Re-evaluates whether a deferred backfill is still required after persistence catches up.
261    pub(super) fn revalidate_pending_backfill(&mut self) -> ProviderResult<()> {
262        debug_assert!(self.backfill_sync_state.is_pending_revalidation());
263
264        let sync_target_state = self.state.forkchoice_state_tracker.sync_target_state();
265        let backfill_target = if let Some(state) = sync_target_state {
266            let configured_target = self.backfill_target_hash(state);
267            let target_hash =
268                if configured_target.is_zero() { state.head_block_hash } else { configured_target };
269            let target_number = if let Some(block) = self.state.buffer.block(&target_hash) {
270                Some(block.number())
271            } else {
272                self.sealed_header_by_hash(target_hash)?.map(|header| header.number())
273            };
274
275            target_number.and_then(|target_number| {
276                self.backfill_sync_target(
277                    self.state.tree_state.canonical_block_number(),
278                    target_number,
279                    None,
280                )
281            })
282        } else {
283            None
284        };
285
286        if let Some(target) = backfill_target {
287            self.dispatch_backfill_action(BackfillAction::Start(target.into()));
288            return Ok(())
289        }
290
291        self.backfill_sync_state = BackfillSyncState::Idle;
292        debug!(target: "engine::tree", "dropping deferred backfill after re-evaluation");
293
294        // The target may have changed while persistence was draining. Resume the live-sync
295        // download flow so a newer target can produce a fresh backfill decision.
296        if let Some(state) = sync_target_state &&
297            state.head_block_hash != self.state.tree_state.canonical_block_hash()
298        {
299            let target = self.lowest_buffered_ancestor_or(state.head_block_hash);
300            self.send_event(EngineApiEvent::Download(DownloadRequest::single_block(target)));
301        }
302
303        Ok(())
304    }
305
306    /// Dispatches a validated backfill action to the orchestrator.
307    pub(super) fn dispatch_backfill_action(&mut self, action: BackfillAction) {
308        debug_assert!(
309            self.backfill_sync_state.is_idle() ||
310                self.backfill_sync_state.is_pending_revalidation(),
311            "backfill action can only be dispatched while idle or pending revalidation"
312        );
313        self.backfill_sync_state = BackfillSyncState::Pending;
314        self.metrics.engine.pipeline_runs.increment(1);
315        // Forkchoice updates only forward finality to a running backfill, so the run starting here
316        // gets the latest one up front.
317        if let Some(state) = self.state.forkchoice_state_tracker.latest_state() {
318            self.forward_finalized(state.finalized_block_hash);
319        }
320        debug!(target: "engine::tree", "emitting backfill action event");
321        self.send_event(EngineApiEvent::BackfillAction(action));
322    }
323
324    // Forwards `finalized` to the backfill unless the forkchoice leaves it unset.
325    pub(super) fn forward_finalized(&self, finalized: B256) {
326        if !finalized.is_zero() {
327            self.send_event(EngineApiEvent::BackfillAction(BackfillAction::UpdateFinalized(
328                finalized,
329            )));
330        }
331    }
332
333    /// Returns whether block downloads should also attempt to fetch the blocks' access lists.
334    ///
335    /// This is the case once Amsterdam is active at the current canonical head, indicated by the
336    /// head header carrying a block access list hash.
337    ///
338    /// This is a coarse gate: a download issued while the head is still pre-Amsterdam won't ask
339    /// for access lists of blocks past the fork. Access list downloads are best-effort anyway, so
340    /// those blocks simply take the regular execution path.
341    pub(super) fn should_download_access_lists(&self) -> bool {
342        self.canonical_in_memory_state().get_canonical_head().block_access_list_hash().is_some()
343    }
344
345    /// Returns true if the distance from the local tip to the block is greater than the configured
346    /// threshold.
347    ///
348    /// If the `local_tip` is greater than the `block`, then this will return false.
349    #[inline]
350    pub(super) const fn exceeds_backfill_run_threshold(&self, local_tip: u64, block: u64) -> bool {
351        block > local_tip && block - local_tip > self.config.backfill_run_threshold()
352    }
353
354    /// Returns how far the local tip is from the given block. If the local tip is at the same
355    /// height or its block number is greater than the given block, this returns None.
356    #[inline]
357    const fn distance_from_local_tip(&self, local_tip: u64, block: u64) -> Option<u64> {
358        if block > local_tip {
359            Some(block - local_tip)
360        } else {
361            None
362        }
363    }
364
365    /// Returns the block hash that backfill should target.
366    ///
367    /// Defaults to the finalized block hash. On OP Stack, the CL finalizes in large batches and the
368    /// finalized hash can lag the canonical tip by a wide margin, so backfill targets the head.
369    ///
370    /// The zero-finalized optimistic-sync fallback for non-OP Stack chains is handled by
371    /// [`Self::backfill_sync_target`].
372    pub(super) const fn backfill_target_hash(&self, state: ForkchoiceState) -> B256 {
373        if self.engine_kind.is_opstack() {
374            state.head_block_hash
375        } else {
376            state.finalized_block_hash
377        }
378    }
379
380    /// Returns the target hash to sync to if the distance from the local tip is greater than the
381    /// threshold and we're not yet synced to the backfill target (see
382    /// [`Self::backfill_target_hash`]).
383    ///
384    /// If this is invoked after a new block has been downloaded, the downloaded block could be
385    /// the (missing) target block.
386    pub(super) fn backfill_sync_target(
387        &self,
388        canonical_tip_num: u64,
389        target_block_number: u64,
390        downloaded_block: Option<BlockNumHash>,
391    ) -> Option<B256> {
392        let state = self.state.forkchoice_state_tracker.sync_target_state()?;
393        let target_hash = self.backfill_target_hash(state);
394
395        // check if the downloaded block is the tracked backfill target
396        let exceeds_backfill_threshold = match downloaded_block.as_ref() {
397            // if we downloaded the target block we can now check how far we're off
398            Some(downloaded_block) if downloaded_block.hash == target_hash => {
399                self.exceeds_backfill_run_threshold(canonical_tip_num, downloaded_block.number)
400            }
401            _ => match self.state.buffer.block(&target_hash) {
402                // if we have buffered the target block, we should check how far we're off
403                Some(buffered_target) => {
404                    self.exceeds_backfill_run_threshold(canonical_tip_num, buffered_target.number())
405                }
406                // check if the distance exceeds the threshold for backfill sync
407                None => self.exceeds_backfill_run_threshold(canonical_tip_num, target_block_number),
408            },
409        };
410
411        if !exceeds_backfill_threshold {
412            return None
413        }
414
415        // if we have already canonicalized the target block, we should skip backfill
416        match self.provider.header_by_hash_or_number(target_hash.into()) {
417            Err(err) => {
418                warn!(target: "engine::tree", %err, "Failed to get backfill target block header");
419                None
420            }
421            // we don't have the block yet and the distance exceeds the allowed threshold
422            Ok(None) if !target_hash.is_zero() => Some(target_hash),
423            Ok(None) => {
424                // OPTIMISTIC SYNCING
425                //
426                // It can happen when the node is doing an
427                // optimistic sync, where the CL has no knowledge of the finalized hash,
428                // but is expecting the EL to sync as high
429                // as possible before finalizing.
430                //
431                // This usually doesn't happen on ETH mainnet since CLs use the more
432                // secure checkpoint syncing.
433                //
434                // However, optimism chains will do this. The risk of a reorg is however
435                // low.
436                debug!(target: "engine::tree", hash=?state.head_block_hash, "Setting head hash as an optimistic backfill target.");
437                Some(state.head_block_hash)
438            }
439            // we're fully synced to the target block
440            Ok(Some(_)) => None,
441        }
442    }
443
444    /// This handles downloaded blocks that are shown to be disconnected from the canonical chain.
445    ///
446    /// This mainly compares the missing parent of the downloaded block with the current canonical
447    /// tip, and decides whether or not backfill sync should be triggered.
448    pub(super) fn on_disconnected_downloaded_block(
449        &self,
450        downloaded_block: BlockNumHash,
451        missing_parent: BlockNumHash,
452        head: BlockNumHash,
453    ) -> Option<TreeEvent> {
454        // compare the missing parent with the canonical tip
455        if let Some(target) =
456            self.backfill_sync_target(head.number, missing_parent.number, Some(downloaded_block))
457        {
458            trace!(target: "engine::tree", %target, "triggering backfill on downloaded block");
459            return Some(TreeEvent::BackfillAction(BackfillAction::Start(target.into())));
460        }
461
462        // continue downloading the missing parent
463        //
464        // this happens if either:
465        //  * the missing parent block num < canonical tip num
466        //    * this case represents a missing block on a fork that is shorter than the canonical
467        //      chain
468        //  * the missing parent block num >= canonical tip num, but the number of missing blocks is
469        //    less than the backfill threshold
470        //    * this case represents a potentially long range of blocks to download and execute
471        let request = if let Some(distance) =
472            self.distance_from_local_tip(head.number, missing_parent.number)
473        {
474            trace!(target: "engine::tree", %distance, missing=?missing_parent, "downloading missing parent block range");
475            DownloadRequest::block_range(missing_parent, distance)
476        } else {
477            trace!(target: "engine::tree", missing=?missing_parent, "downloading missing parent block");
478            // This happens when the missing parent is on an outdated
479            // sidechain and we can only download the missing block itself
480            DownloadRequest::single_block(missing_parent.hash)
481        };
482
483        Some(TreeEvent::Download(request.with_access_lists(self.should_download_access_lists())))
484    }
485
486    /// Handles a downloaded block that was successfully inserted as valid.
487    ///
488    /// If the block matches the sync target head, returns [`TreeAction::MakeCanonical`].
489    /// If it matches a non-head sync target (safe or finalized), makes it canonical inline
490    /// and triggers a download for the remaining blocks towards the actual head.
491    /// Otherwise, tries to connect buffered blocks.
492    pub(super) fn on_valid_downloaded_block(
493        &mut self,
494        block_num_hash: BlockNumHash,
495    ) -> Result<Option<TreeEvent>, InsertBlockFatalError> {
496        // check if we just inserted a block that's part of sync targets,
497        // i.e. head, safe, or finalized
498        if let Some(sync_target) = self.state.forkchoice_state_tracker.sync_target_state() &&
499            sync_target.contains(block_num_hash.hash)
500        {
501            debug!(target: "engine::tree", ?sync_target, "appended downloaded sync target block");
502
503            if sync_target.head_block_hash == block_num_hash.hash {
504                // we just inserted the sync target head block, make it canonical
505                return Ok(Some(TreeEvent::TreeAction(TreeAction::MakeCanonical {
506                    sync_target_head: block_num_hash.hash,
507                })))
508            }
509
510            // This block is part of the sync target (safe or finalized) but not the
511            // head. Make it canonical and try to connect any buffered children, then
512            // continue downloading towards the actual head if needed.
513            self.make_canonical(block_num_hash.hash)?;
514            self.try_connect_buffered_blocks(block_num_hash)?;
515
516            // Check if we've reached the sync target head after connecting buffered
517            // blocks (e.g. the head block may have already been buffered).
518            if self.state.tree_state.canonical_block_hash() != sync_target.head_block_hash {
519                let target = self.lowest_buffered_ancestor_or(sync_target.head_block_hash);
520                trace!(target: "engine::tree", %target, "sync target head not yet reached, downloading head block");
521                return Ok(Some(TreeEvent::Download(
522                    DownloadRequest::single_block(target)
523                        .with_access_lists(self.should_download_access_lists()),
524                )))
525            }
526
527            return Ok(None)
528        }
529        trace!(target: "engine::tree", "appended downloaded block");
530        self.try_connect_buffered_blocks(block_num_hash)?;
531        Ok(None)
532    }
533
534    /// Invoked with a block downloaded from the network
535    ///
536    /// Returns an event with the appropriate action to take, such as:
537    ///  - download more missing blocks
538    ///  - try to canonicalize the target if the `block` is the tracked target (head) block.
539    #[instrument(level = "debug", target = "engine::tree", skip_all, fields(block_hash = %block.hash(), block_num = %block.number()))]
540    fn on_downloaded_block(
541        &mut self,
542        block: SealedBlockWithAccessList<N::Block>,
543    ) -> Result<Option<TreeEvent>, InsertBlockFatalError> {
544        let block_num_hash = block.num_hash();
545        let lowest_buffered_ancestor = self.lowest_buffered_ancestor_or(block_num_hash.hash);
546        if self.check_invalid_ancestor_with_head(lowest_buffered_ancestor, &block)?.is_some() {
547            return Ok(None)
548        }
549
550        if !self.backfill_sync_state.is_idle() {
551            return Ok(None)
552        }
553
554        // try to append the block
555        match self.insert_block(block) {
556            Ok(InsertPayloadOk::Inserted(BlockStatus::Valid)) => {
557                return self.on_valid_downloaded_block(block_num_hash);
558            }
559            Ok(InsertPayloadOk::Inserted(BlockStatus::Disconnected { head, missing_ancestor })) => {
560                // block is not connected to the canonical head, we need to download
561                // its missing branch first
562                return Ok(self.on_disconnected_downloaded_block(
563                    block_num_hash,
564                    missing_ancestor,
565                    head,
566                ))
567            }
568            Ok(InsertPayloadOk::AlreadySeen(_)) => {
569                trace!(target: "engine::tree", "downloaded block already executed");
570            }
571            Err(err) => {
572                if let InsertPayloadError::Block(err) = err {
573                    debug!(target: "engine::tree", err=%err.kind(), "failed to insert downloaded block");
574                    if let Err(InsertBlockProcessingError::Fatal(fatal)) =
575                        self.on_insert_block_error(err)
576                    {
577                        warn!(target: "engine::tree", %fatal, "fatal error occurred while inserting downloaded block");
578                    }
579                }
580            }
581        }
582        Ok(None)
583    }
584
585    /// Rejects the buffered children of `parent` that do not validate against it, after a range
586    /// download found `parent` at a number they do not imply.
587    pub(super) fn on_start_number_mismatch(&mut self, parent: SealedHeader<N::BlockHeader>) {
588        let children = self
589            .state
590            .buffer
591            .parent_to_child
592            .get(&parent.hash())
593            .into_iter()
594            .flatten()
595            .copied()
596            .collect::<Vec<_>>();
597        for hash in children {
598            if let Some(child) = self.state.buffer.block(&hash) &&
599                let Err(err) =
600                    self.consensus.validate_header_against_parent(child.sealed_header(), &parent)
601            {
602                // Descendants go back into the buffer, where the invalid child rejects them.
603                let mut blocks = self.state.buffer.remove_block_with_children(&hash).into_iter();
604                if let Some(child) = blocks.next() &&
605                    let Err(InsertBlockProcessingError::Fatal(fatal)) = self
606                        .on_insert_block_error(InsertBlockError::consensus_error(
607                            err,
608                            child.split().0,
609                        ))
610                {
611                    warn!(target: "engine::tree", %fatal, "fatal error occurred while rejecting buffered block");
612                }
613                for block in blocks {
614                    self.state.buffer.insert_block(block);
615                }
616            }
617        }
618    }
619}