1use crate::{
2 BackfillJobFactory, ExExEvent, ExExNotification, RevertReceipt, StreamBackfillJob, WalHandle,
3};
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockNumHash;
6use futures::{Stream, StreamExt};
7use reth_ethereum_primitives::EthPrimitives;
8use reth_evm::ConfigureEvm;
9use reth_exex_types::ExExHead;
10use reth_node_api::NodePrimitives;
11use reth_provider::{BlockNumReader, BlockReader, Chain, ProviderResult, StateProviderFactory};
12use reth_stages_api::ExecutionStageThresholds;
13use std::{
14 collections::VecDeque,
15 fmt::Debug,
16 pin::Pin,
17 sync::Arc,
18 task::{ready, Context, Poll},
19};
20use tokio::sync::mpsc::{Receiver, UnboundedSender};
21use tracing::debug;
22
23#[derive(Debug)]
27pub struct ExExNotifications<P, E>
28where
29 E: ConfigureEvm,
30{
31 inner: ExExNotificationsInner<P, E>,
32}
33
34pub trait ExExNotificationsStream<N: NodePrimitives = EthPrimitives>:
38 Stream<Item = eyre::Result<ExExNotification<N>>> + Unpin
39{
40 fn set_without_head(&mut self);
46
47 fn set_with_head(&mut self, exex_head: ExExHead);
54
55 fn without_head(self) -> Self
59 where
60 Self: Sized;
61
62 fn with_head(self, exex_head: ExExHead) -> Self
66 where
67 Self: Sized;
68
69 fn set_backfill_thresholds(&mut self, _thresholds: ExecutionStageThresholds) {}
77}
78
79#[derive(Debug)]
80enum ExExNotificationsInner<P, E>
81where
82 E: ConfigureEvm,
83{
84 WithoutHead(ExExNotificationsWithoutHead<P, E>),
86 WithHead(Box<ExExNotificationsWithHead<P, E>>),
89 Invalid,
92}
93
94impl<P, E> ExExNotificationsInner<P, E>
95where
96 E: ConfigureEvm,
97{
98 fn provider(&self) -> &P {
100 match self {
101 Self::WithoutHead(n) => &n.provider,
102 Self::WithHead(n) => &n.provider,
103 Self::Invalid => unreachable!(),
104 }
105 }
106}
107
108impl<P, E> ExExNotifications<P, E>
109where
110 E: ConfigureEvm,
111{
112 pub const fn new(
114 node_head: BlockNumHash,
115 provider: P,
116 evm_config: E,
117 notifications: Receiver<ExExNotification<E::Primitives>>,
118 wal_handle: WalHandle<E::Primitives>,
119 ) -> Self {
120 Self {
121 inner: ExExNotificationsInner::WithoutHead(ExExNotificationsWithoutHead::new(
122 node_head,
123 provider,
124 evm_config,
125 notifications,
126 wal_handle,
127 )),
128 }
129 }
130
131 pub(crate) fn with_revert_receipts(mut self, events: UnboundedSender<ExExEvent>) -> Self {
134 if let ExExNotificationsInner::WithoutHead(notifications) = &mut self.inner {
135 notifications.notifications.revert_receipts = Some(events);
136 }
137 self
138 }
139
140 pub fn catch_up_with_head(&mut self, exex_head: ExExHead) -> eyre::Result<()>
143 where
144 P: BlockNumReader,
145 {
146 let local_head: BlockNumHash = self.inner.provider().chain_info()?.into();
149
150 let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
151 let (provider, evm_config, notifications, wal_handle, backfill_thresholds) = match current {
152 ExExNotificationsInner::WithoutHead(n) => {
153 (n.provider, n.evm_config, n.notifications, n.wal_handle, None)
154 }
155 ExExNotificationsInner::WithHead(mut n) => {
156 n.drop_pending_notifications();
157 (n.provider, n.evm_config, n.notifications, n.wal_handle, n.backfill_thresholds)
158 }
159 ExExNotificationsInner::Invalid => unreachable!(),
160 };
161 let mut with_head = ExExNotificationsWithHead::new(
162 local_head,
163 provider,
164 evm_config,
165 notifications,
166 wal_handle,
167 exex_head,
168 );
169 with_head.backfill_thresholds = backfill_thresholds;
172 self.inner = ExExNotificationsInner::WithHead(Box::new(with_head));
173 Ok(())
174 }
175}
176
177impl<P, E> ExExNotificationsStream<E::Primitives> for ExExNotifications<P, E>
178where
179 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
180 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
181{
182 fn set_without_head(&mut self) {
183 let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
184 self.inner = ExExNotificationsInner::WithoutHead(match current {
185 ExExNotificationsInner::WithoutHead(notifications) => notifications,
186 ExExNotificationsInner::WithHead(mut notifications) => {
187 notifications.drop_pending_notifications();
188 ExExNotificationsWithoutHead {
189 node_head: notifications.initial_local_head,
190 provider: notifications.provider,
191 evm_config: notifications.evm_config,
192 notifications: notifications.notifications,
193 wal_handle: notifications.wal_handle,
194 }
195 }
196 ExExNotificationsInner::Invalid => unreachable!(),
197 });
198 }
199
200 fn set_with_head(&mut self, exex_head: ExExHead) {
201 let current = std::mem::replace(&mut self.inner, ExExNotificationsInner::Invalid);
202 self.inner = ExExNotificationsInner::WithHead(match current {
203 ExExNotificationsInner::WithoutHead(notifications) => {
204 Box::new(notifications.with_head(exex_head))
205 }
206 ExExNotificationsInner::WithHead(mut notifications) => {
207 notifications.drop_pending_notifications();
208 Box::new(ExExNotificationsWithHead::new(
209 notifications.initial_local_head,
210 notifications.provider,
211 notifications.evm_config,
212 notifications.notifications,
213 notifications.wal_handle,
214 exex_head,
215 ))
216 }
217 ExExNotificationsInner::Invalid => unreachable!(),
218 });
219 }
220
221 fn without_head(mut self) -> Self {
222 self.set_without_head();
223 self
224 }
225
226 fn with_head(mut self, exex_head: ExExHead) -> Self {
227 self.set_with_head(exex_head);
228 self
229 }
230
231 fn set_backfill_thresholds(&mut self, thresholds: ExecutionStageThresholds) {
232 if let ExExNotificationsInner::WithHead(notifications) = &mut self.inner {
233 notifications.backfill_thresholds = Some(thresholds);
234 }
235 }
236}
237
238impl<P, E> Stream for ExExNotifications<P, E>
239where
240 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
241 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
242{
243 type Item = eyre::Result<ExExNotification<E::Primitives>>;
244
245 fn poll_next(
246 self: std::pin::Pin<&mut Self>,
247 cx: &mut std::task::Context<'_>,
248 ) -> std::task::Poll<Option<Self::Item>> {
249 match &mut self.get_mut().inner {
250 ExExNotificationsInner::WithoutHead(notifications) => {
251 notifications.poll_next_unpin(cx).map(|result| result.map(Ok))
252 }
253 ExExNotificationsInner::WithHead(notifications) => notifications.poll_next_unpin(cx),
254 ExExNotificationsInner::Invalid => unreachable!(),
255 }
256 }
257}
258
259pub struct ExExNotificationsWithoutHead<P, E>
261where
262 E: ConfigureEvm,
263{
264 node_head: BlockNumHash,
265 provider: P,
266 evm_config: E,
267 notifications: ManagerNotifications<E::Primitives>,
268 wal_handle: WalHandle<E::Primitives>,
269}
270
271impl<P: Debug, E> Debug for ExExNotificationsWithoutHead<P, E>
272where
273 E: ConfigureEvm,
274{
275 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276 f.debug_struct("ExExNotifications")
277 .field("provider", &self.provider)
278 .field("evm_config", &self.evm_config)
279 .field("notifications", &self.notifications)
280 .finish()
281 }
282}
283
284impl<P, E> ExExNotificationsWithoutHead<P, E>
285where
286 E: ConfigureEvm,
287{
288 const fn new(
290 node_head: BlockNumHash,
291 provider: P,
292 evm_config: E,
293 notifications: Receiver<ExExNotification<E::Primitives>>,
294 wal_handle: WalHandle<E::Primitives>,
295 ) -> Self {
296 Self {
297 node_head,
298 provider,
299 evm_config,
300 notifications: ManagerNotifications { receiver: notifications, revert_receipts: None },
301 wal_handle,
302 }
303 }
304
305 fn with_head(self, head: ExExHead) -> ExExNotificationsWithHead<P, E> {
307 ExExNotificationsWithHead::new(
308 self.node_head,
309 self.provider,
310 self.evm_config,
311 self.notifications,
312 self.wal_handle,
313 head,
314 )
315 }
316}
317
318impl<P: Unpin, E> Stream for ExExNotificationsWithoutHead<P, E>
319where
320 E: ConfigureEvm,
321{
322 type Item = ExExNotification<E::Primitives>;
323
324 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
325 let notifications = &mut self.get_mut().notifications;
326 let notification = ready!(notifications.poll_recv(cx));
327 if let Some(notification) = ¬ification {
328 notifications.acknowledge(notification);
329 }
330 Poll::Ready(notification)
331 }
332}
333
334#[derive(Debug)]
345pub struct ExExNotificationsWithHead<P, E>
346where
347 E: ConfigureEvm,
348{
349 initial_local_head: BlockNumHash,
351 provider: P,
352 evm_config: E,
353 notifications: ManagerNotifications<E::Primitives>,
354 wal_handle: WalHandle<E::Primitives>,
355 exex_head: ExExHead,
358
359 pending_check_canonical: bool,
362 pending_check_backfill: bool,
365 backfill_job: Option<StreamBackfillJob<E, P, Chain<E::Primitives>>>,
367 backfill_thresholds: Option<ExecutionStageThresholds>,
369 pending_notifications: VecDeque<ExExNotification<E::Primitives>>,
372}
373
374impl<P, E> ExExNotificationsWithHead<P, E>
375where
376 E: ConfigureEvm,
377{
378 const fn new(
380 node_head: BlockNumHash,
381 provider: P,
382 evm_config: E,
383 notifications: ManagerNotifications<E::Primitives>,
384 wal_handle: WalHandle<E::Primitives>,
385 exex_head: ExExHead,
386 ) -> Self {
387 Self {
388 initial_local_head: node_head,
389 provider,
390 evm_config,
391 notifications,
392 wal_handle,
393 exex_head,
394 pending_check_canonical: true,
395 pending_check_backfill: true,
396 backfill_job: None,
397 backfill_thresholds: None,
398 pending_notifications: VecDeque::new(),
399 }
400 }
401
402 pub const fn with_backfill_thresholds(mut self, thresholds: ExecutionStageThresholds) -> Self {
411 self.backfill_thresholds = Some(thresholds);
412 self
413 }
414
415 fn drop_pending_notifications(&mut self) {
419 for notification in self.pending_notifications.drain(..) {
420 self.notifications.acknowledge(¬ification);
421 }
422 }
423}
424
425impl<P, E> ExExNotificationsWithHead<P, E>
426where
427 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
428 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
429{
430 fn check_canonical(&mut self) -> eyre::Result<Option<ExExNotification<E::Primitives>>> {
436 if self.provider.is_known(self.exex_head.block.hash)? &&
437 self.exex_head.block.number <= self.initial_local_head.number
438 {
439 debug!(target: "exex::notifications", "ExEx head is on the canonical chain");
441 return Ok(None)
442 }
443
444 let Some(notification) =
449 self.wal_handle.get_committed_notification_by_block_hash(&self.exex_head.block.hash)?
450 else {
451 if self.exex_head.block.number > self.initial_local_head.number {
453 debug!(target: "exex::notifications", "ExEx head is ahead of the canonical chain");
454 return Ok(None);
455 }
456
457 return Err(eyre::eyre!(
458 "Could not find notification for block hash {:?} in the WAL",
459 self.exex_head.block.hash
460 ))
461 };
462
463 let committed_chain = notification.committed_chain().unwrap();
465 let new_exex_head =
466 (committed_chain.first().parent_hash(), committed_chain.first().number() - 1).into();
467 debug!(target: "exex::notifications", old_exex_head = ?self.exex_head.block, new_exex_head = ?new_exex_head, "ExEx head updated");
468 self.exex_head.block = new_exex_head;
469
470 Ok(Some(notification.into_inverted()))
473 }
474
475 fn check_backfill(&mut self) -> eyre::Result<()> {
486 let mut backfill_job_factory =
487 BackfillJobFactory::new(self.evm_config.clone(), self.provider.clone());
488 if let Some(thresholds) = self.backfill_thresholds.clone() {
489 backfill_job_factory = backfill_job_factory.with_thresholds(thresholds);
490 }
491 match self.exex_head.block.number.cmp(&self.initial_local_head.number) {
492 std::cmp::Ordering::Less => {
493 debug!(target: "exex::notifications", "ExEx is behind the node head and on the canonical chain, starting backfill");
495 let backfill = backfill_job_factory
496 .backfill(self.exex_head.block.number + 1..=self.initial_local_head.number)
497 .into_stream();
498 self.backfill_job = Some(backfill);
499 }
500 std::cmp::Ordering::Equal => {
501 debug!(target: "exex::notifications", "ExEx is at the node head");
502 }
503 std::cmp::Ordering::Greater => {
504 debug!(target: "exex::notifications", "ExEx is ahead of the node head");
505 }
506 };
507
508 Ok(())
509 }
510
511 fn advance_exex_head(
521 &mut self,
522 notification: &ExExNotification<E::Primitives>,
523 ) -> ProviderResult<bool> {
524 let head = self.exex_head.block;
525 let committed = notification.committed_chain();
526 let Some(reverted) = notification.reverted_chain() else {
527 let Some(committed) = committed else { return Ok(false) };
528 if head.number >= committed.tip().number() {
530 return Ok(false)
531 }
532 self.exex_head.block = committed.tip().num_hash();
533 return Ok(true)
534 };
535 let tip = committed.as_ref().map_or_else(|| reverted.fork_block(), |c| c.tip().num_hash());
536
537 if let Some(committed) = &committed &&
539 committed.block_number(head.hash).is_some()
540 {
541 if head == tip {
542 return Ok(false)
543 }
544 self.exex_head.block = tip;
545 return Ok(true)
546 }
547
548 let is_canonical = |block: BlockNumHash| -> ProviderResult<bool> {
549 Ok(self.provider.block_hash(block.number)? == Some(block.hash))
550 };
551 let first_reverted = reverted.first().num_hash();
554 let has_reverted_blocks = first_reverted.number <= head.number &&
555 !(is_canonical(head)? && !is_canonical(first_reverted)?);
556 if !has_reverted_blocks && tip.number <= head.number && is_canonical(tip)? {
559 return Ok(false)
560 }
561
562 if committed.is_some() || has_reverted_blocks {
563 self.exex_head.block = tip;
564 }
565 Ok(true)
566 }
567}
568
569#[derive(Debug)]
571struct ManagerNotifications<N: NodePrimitives> {
572 receiver: Receiver<ExExNotification<N>>,
573 revert_receipts: Option<UnboundedSender<ExExEvent>>,
575}
576
577impl<N: NodePrimitives> ManagerNotifications<N> {
578 fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<ExExNotification<N>>> {
579 self.receiver.poll_recv(cx)
580 }
581
582 fn acknowledge(&self, notification: &ExExNotification<N>) {
587 if let Some(events) = &self.revert_receipts &&
588 notification.reverted_chain().is_some() &&
589 events.send(ExExEvent::RevertReceived(RevertReceipt(()))).is_err()
590 {
591 debug!(target: "exex::notifications", "ExEx manager is gone, revert receipt not sent");
592 }
593 }
594}
595
596impl<P, E> Stream for ExExNotificationsWithHead<P, E>
597where
598 P: BlockReader + StateProviderFactory + Clone + Unpin + 'static,
599 E: ConfigureEvm<Primitives: NodePrimitives<Block = P::Block>> + 'static,
600{
601 type Item = eyre::Result<ExExNotification<E::Primitives>>;
602
603 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
604 let this = self.get_mut();
605
606 if this.pending_check_canonical {
608 if let Some(canonical_notification) = this.check_canonical()? {
609 return Poll::Ready(Some(Ok(canonical_notification)))
610 }
611
612 this.pending_check_canonical = false;
614 }
615
616 if this.pending_check_backfill {
618 this.check_backfill()?;
619 this.pending_check_backfill = false;
620 }
621
622 if let Some(backfill_job) = &mut this.backfill_job {
624 debug!(target: "exex::notifications", "Polling backfill job");
625
626 while let Poll::Ready(Some(notification)) = this.notifications.poll_recv(cx) {
635 if notification.reverted_chain().is_some() {
640 this.pending_notifications.push_back(notification);
641 continue;
642 }
643 if this.pending_notifications.is_empty() &&
647 let Some(committed) = notification.committed_chain() &&
648 committed.tip().number() <= this.initial_local_head.number
649 {
650 continue;
651 }
652 this.pending_notifications.push_back(notification);
654 }
655
656 if let Some(chain) = ready!(backfill_job.poll_next_unpin(cx)).transpose()? {
657 debug!(target: "exex::notifications", range = ?chain.range(), "Backfill job returned a chain");
658 this.exex_head.block = chain.tip().num_hash();
659 return Poll::Ready(Some(Ok(ExExNotification::ChainCommitted {
660 new: Arc::new(chain),
661 })))
662 }
663
664 this.backfill_job = None;
666 }
667
668 loop {
671 let notification = match this.pending_notifications.pop_front() {
672 Some(notification) => notification,
673 None => match ready!(this.notifications.poll_recv(cx)) {
674 Some(notification) => notification,
675 None => return Poll::Ready(None),
676 },
677 };
678
679 let needed = match this.advance_exex_head(¬ification) {
680 Ok(needed) => needed,
681 Err(err) => {
682 this.pending_notifications.push_front(notification);
684 return Poll::Ready(Some(Err(err.into())))
685 }
686 };
687 this.notifications.acknowledge(¬ification);
688 if needed {
689 return Poll::Ready(Some(Ok(notification)))
690 }
691 }
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use crate::Wal;
699 use alloy_consensus::Header;
700 use alloy_eips::BlockNumHash;
701 use alloy_primitives::B256;
702 use eyre::OptionExt;
703 use futures::{StreamExt, TryStreamExt};
704 use rand::Rng;
705 use reth_chain_state::CanonicalInMemoryStateWriter;
706 use reth_chainspec::MAINNET;
707 use reth_db_common::init::init_genesis;
708 use reth_ethereum_primitives::Block;
709 use reth_evm_ethereum::EthEvmConfig;
710 use reth_primitives_traits::{Block as _, RecoveredBlock};
711 use reth_provider::{
712 providers::BlockchainProvider,
713 test_utils::{
714 create_test_provider_factory, create_test_provider_factory_with_in_memory_state_writer,
715 MockNodeTypesWithDB,
716 },
717 BlockWriter, Chain, DBProvider, DatabaseProviderFactory,
718 };
719 use reth_testing_utils::generators::{self, random_block, BlockParams};
720 use std::collections::BTreeMap;
721 use tokio::sync::mpsc;
722
723 #[tokio::test]
724 async fn exex_notifications_behind_head_canonical() -> eyre::Result<()> {
725 let mut rng = generators::rng();
726
727 let temp_dir = tempfile::tempdir().unwrap();
728 let wal = Wal::new(temp_dir.path()).unwrap();
729
730 let provider_factory = create_test_provider_factory();
731 let genesis_hash = init_genesis(&provider_factory)?;
732 let genesis_block = provider_factory
733 .block(genesis_hash.into())?
734 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
735
736 let provider = BlockchainProvider::new(provider_factory.clone())?;
737
738 let node_head_block = random_block(
739 &mut rng,
740 genesis_block.number + 1,
741 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
742 )
743 .try_recover()?;
744 let node_head = node_head_block.num_hash();
745 let provider_rw = provider_factory.provider_rw()?;
746 provider_rw.insert_block(&node_head_block)?;
747 provider_rw.commit()?;
748 let exex_head =
749 ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
750
751 let notification = ExExNotification::ChainCommitted {
752 new: Arc::new(Chain::new(
753 vec![random_block(
754 &mut rng,
755 node_head.number + 1,
756 BlockParams { parent: Some(node_head.hash), ..Default::default() },
757 )
758 .try_recover()?],
759 Default::default(),
760 BTreeMap::new(),
761 )),
762 };
763
764 let (notifications_tx, notifications_rx) = mpsc::channel(1);
765
766 notifications_tx.send(notification.clone()).await?;
767
768 let mut notifications = ExExNotificationsWithoutHead::new(
769 node_head,
770 provider,
771 EthEvmConfig::mainnet(),
772 notifications_rx,
773 wal.handle(),
774 )
775 .with_head(exex_head);
776
777 assert_eq!(
779 notifications.next().await.transpose()?,
780 Some(ExExNotification::ChainCommitted {
781 new: Arc::new(
782 BackfillJobFactory::new(
783 notifications.evm_config.clone(),
784 notifications.provider.clone()
785 )
786 .backfill(1..=1)
787 .next()
788 .ok_or_eyre("failed to backfill")??
789 )
790 })
791 );
792
793 assert_eq!(notifications.next().await.transpose()?, Some(notification));
795
796 Ok(())
797 }
798
799 #[tokio::test]
800 async fn catch_up_with_head_after_pause_backfills_missed_blocks() -> eyre::Result<()> {
801 let mut rng = generators::rng();
802
803 let temp_dir = tempfile::tempdir().unwrap();
804 let wal = Wal::new(temp_dir.path()).unwrap();
805
806 let (provider_factory, in_memory_state_writer) =
807 create_test_provider_factory_with_in_memory_state_writer(MAINNET.clone());
808 let genesis_hash = init_genesis(&provider_factory)?;
809 let genesis_block = provider_factory
810 .block(genesis_hash.into())?
811 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
812 let mut canonical_in_memory_state_writer = CanonicalInMemoryStateWriter::new(
813 provider_factory.chain_info_headers()?,
814 in_memory_state_writer,
815 );
816 let provider = BlockchainProvider::with_canonical_in_memory_state(
817 provider_factory.clone(),
818 canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
819 );
820
821 let exex_head =
822 ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
823 let (notifications_tx, notifications_rx) = mpsc::channel(1);
824
825 let evm_config = EthEvmConfig::mainnet();
826 let mut notifications = ExExNotifications::new(
827 BlockNumHash { number: genesis_block.number, hash: genesis_hash },
828 provider.clone(),
829 evm_config.clone(),
830 notifications_rx,
831 wal.handle(),
832 );
833 notifications.set_with_head(exex_head);
835
836 let node_head_block = random_block(
838 &mut rng,
839 genesis_block.number + 1,
840 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
841 )
842 .try_recover()?;
843 let node_head = node_head_block.num_hash();
844 let block_1_notification = ExExNotification::ChainCommitted {
845 new: Arc::new(Chain::new(
846 vec![node_head_block.clone()],
847 Default::default(),
848 BTreeMap::new(),
849 )),
850 };
851 notifications_tx.send(block_1_notification.clone()).await?;
852 assert_eq!(notifications.next().await.transpose()?, Some(block_1_notification));
853
854 let provider_rw = provider_factory.provider_rw()?;
857 provider_rw.insert_block(&node_head_block)?;
858 provider_rw.commit()?;
859 canonical_in_memory_state_writer.set_canonical_head(node_head_block.clone_sealed_header());
860
861 notifications.catch_up_with_head(exex_head)?;
864
865 let block_2_notification = ExExNotification::ChainCommitted {
866 new: Arc::new(Chain::new(
867 vec![random_block(
868 &mut rng,
869 node_head.number + 1,
870 BlockParams { parent: Some(node_head.hash), ..Default::default() },
871 )
872 .try_recover()?],
873 Default::default(),
874 BTreeMap::new(),
875 )),
876 };
877 notifications_tx.send(block_2_notification.clone()).await?;
878
879 assert_eq!(
881 notifications.next().await.transpose()?,
882 Some(ExExNotification::ChainCommitted {
883 new: Arc::new(
884 BackfillJobFactory::new(evm_config, provider)
885 .backfill(1..=1)
886 .next()
887 .ok_or_eyre("failed to backfill")??
888 )
889 })
890 );
891 assert_eq!(notifications.next().await.transpose()?, Some(block_2_notification));
893
894 Ok(())
895 }
896
897 #[tokio::test]
898 async fn exex_notifications_same_head_canonical() -> eyre::Result<()> {
899 let temp_dir = tempfile::tempdir().unwrap();
900 let wal = Wal::new(temp_dir.path()).unwrap();
901
902 let provider_factory = create_test_provider_factory();
903 let genesis_hash = init_genesis(&provider_factory)?;
904 let genesis_block = provider_factory
905 .block(genesis_hash.into())?
906 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
907
908 let provider = BlockchainProvider::new(provider_factory)?;
909
910 let node_head = BlockNumHash { number: genesis_block.number, hash: genesis_hash };
911 let exex_head = ExExHead { block: node_head };
912
913 let notification = ExExNotification::ChainCommitted {
914 new: Arc::new(Chain::new(
915 vec![Block {
916 header: Header {
917 parent_hash: node_head.hash,
918 number: node_head.number + 1,
919 ..Default::default()
920 },
921 ..Default::default()
922 }
923 .seal_slow()
924 .try_recover()?],
925 Default::default(),
926 BTreeMap::new(),
927 )),
928 };
929
930 let (notifications_tx, notifications_rx) = mpsc::channel(1);
931
932 notifications_tx.send(notification.clone()).await?;
933
934 let mut notifications = ExExNotificationsWithoutHead::new(
935 node_head,
936 provider,
937 EthEvmConfig::mainnet(),
938 notifications_rx,
939 wal.handle(),
940 )
941 .with_head(exex_head);
942
943 let new_notification = notifications.next().await.transpose()?;
944 assert_eq!(new_notification, Some(notification));
945
946 Ok(())
947 }
948
949 #[tokio::test]
952 async fn exex_notifications_same_head_reorg_at_head() -> eyre::Result<()> {
953 let temp_dir = tempfile::tempdir().unwrap();
954 let wal = Wal::new(temp_dir.path()).unwrap();
955 let (provider, node_head_block, new_block) = same_head_setup()?;
956 let node_head = node_head_block.num_hash();
957 let exex_head = ExExHead { block: node_head };
958
959 let notification = ExExNotification::ChainReorged {
960 old: Arc::new(Chain::new(vec![node_head_block], Default::default(), BTreeMap::new())),
961 new: Arc::new(Chain::new(vec![new_block], Default::default(), BTreeMap::new())),
962 };
963
964 let (notifications_tx, notifications_rx) = mpsc::channel(1);
965
966 notifications_tx.send(notification.clone()).await?;
967 drop(notifications_tx);
968
969 let mut notifications = ExExNotificationsWithoutHead::new(
970 node_head,
971 provider,
972 EthEvmConfig::mainnet(),
973 notifications_rx,
974 wal.handle(),
975 )
976 .with_head(exex_head);
977
978 assert_eq!(notifications.next().await.transpose()?, Some(notification));
979
980 Ok(())
981 }
982
983 #[tokio::test]
986 async fn exex_notifications_commit_after_revert_buffered_during_backfill() -> eyre::Result<()> {
987 let temp_dir = tempfile::tempdir().unwrap();
988 let wal = Wal::new(temp_dir.path()).unwrap();
989 let (provider, a1, b1) = same_head_setup()?;
990 let a2 = random_block(
991 &mut generators::rng(),
992 2,
993 BlockParams { parent: Some(a1.hash()), tx_count: Some(0), ..Default::default() },
994 )
995 .try_recover()?;
996 let provider_rw = provider.database_provider_rw()?;
997 provider_rw.insert_block(&a2)?;
998 provider_rw.commit()?;
999
1000 let revert = ExExNotification::ChainReverted {
1001 old: Arc::new(Chain::new(
1002 vec![a1.clone(), a2.clone()],
1003 Default::default(),
1004 BTreeMap::new(),
1005 )),
1006 };
1007 let commit = ExExNotification::ChainCommitted {
1008 new: Arc::new(Chain::new(vec![b1], Default::default(), BTreeMap::new())),
1009 };
1010 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1011 notifications_tx.send(revert.clone()).await?;
1012
1013 let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1014 let mut notifications = ExExNotificationsWithoutHead::new(
1015 a2.num_hash(),
1016 provider,
1017 EthEvmConfig::mainnet(),
1018 notifications_rx,
1019 wal.handle(),
1020 );
1021 notifications.notifications.revert_receipts = Some(events_tx);
1022 let mut notifications = notifications.with_head(ExExHead { block: a1.num_hash() });
1023
1024 let Some(ExExNotification::ChainCommitted { new }) =
1026 notifications.next().await.transpose()?
1027 else {
1028 panic!("expected the backfill of A2")
1029 };
1030 assert_eq!(new.tip().num_hash(), a2.num_hash());
1031 assert!(events_rx.try_recv().is_err());
1032 assert_eq!(notifications.next().await.transpose()?, Some(revert));
1034 assert_eq!(events_rx.try_recv()?, ExExEvent::RevertReceived(RevertReceipt(())));
1035
1036 notifications_tx.send(commit.clone()).await?;
1037 drop(notifications_tx);
1038 assert_eq!(notifications.next().await.transpose()?, Some(commit));
1039 assert_eq!(notifications.next().await.transpose()?, None);
1040
1041 Ok(())
1042 }
1043
1044 #[tokio::test]
1047 async fn exex_notifications_acknowledge_reverts_dropped_on_reconfiguration() -> eyre::Result<()>
1048 {
1049 for reconfiguration in ["catch_up_with_head", "set_with_head", "set_without_head"] {
1050 let temp_dir = tempfile::tempdir()?;
1051 let wal = Wal::new(temp_dir.path())?;
1052 let (provider, a1, _) = same_head_setup()?;
1053 let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1054 insert(&provider, &[&a2])?;
1055
1056 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1057 notifications_tx
1058 .send(ExExNotification::ChainReverted { old: chain(vec![a2.clone()]) })
1059 .await?;
1060 let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1061 let mut notifications = ExExNotifications::new(
1062 a2.num_hash(),
1063 provider,
1064 EthEvmConfig::mainnet(),
1065 notifications_rx,
1066 wal.handle(),
1067 )
1068 .with_revert_receipts(events_tx);
1069 let head = ExExHead { block: a1.num_hash() };
1070 notifications.set_with_head(head);
1071
1072 assert!(matches!(
1074 notifications.next().await.transpose()?,
1075 Some(ExExNotification::ChainCommitted { .. })
1076 ));
1077 assert!(events_rx.try_recv().is_err());
1078
1079 match reconfiguration {
1080 "catch_up_with_head" => notifications.catch_up_with_head(head)?,
1081 "set_with_head" => notifications.set_with_head(head),
1082 _ => notifications.set_without_head(),
1083 }
1084 assert_eq!(
1085 events_rx.try_recv(),
1086 Ok(ExExEvent::RevertReceived(RevertReceipt(()))),
1087 "{reconfiguration}"
1088 );
1089 }
1090
1091 Ok(())
1092 }
1093
1094 fn same_head_setup() -> eyre::Result<(
1097 BlockchainProvider<MockNodeTypesWithDB>,
1098 RecoveredBlock<Block>,
1099 RecoveredBlock<Block>,
1100 )> {
1101 let mut rng = generators::rng();
1102 let provider_factory = create_test_provider_factory();
1103 let genesis_hash = init_genesis(&provider_factory)?;
1104 let provider = BlockchainProvider::new(provider_factory)?;
1105
1106 let mut block = || {
1107 let block_params =
1108 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() };
1109 random_block(&mut rng, 1, block_params).try_recover()
1110 };
1111 let head_block = block()?;
1112 let sibling_block = block()?;
1113 let provider_rw = provider.database_provider_rw()?;
1114 provider_rw.insert_block(&head_block)?;
1115 provider_rw.commit()?;
1116
1117 Ok((provider, head_block, sibling_block))
1118 }
1119
1120 fn block(rng: &mut impl Rng, number: u64, parent: B256) -> eyre::Result<RecoveredBlock<Block>> {
1122 let block_params =
1123 BlockParams { parent: Some(parent), tx_count: Some(0), ..Default::default() };
1124 Ok(random_block(rng, number, block_params).try_recover()?)
1125 }
1126
1127 fn chain(blocks: Vec<RecoveredBlock<Block>>) -> Arc<Chain> {
1129 Arc::new(Chain::new(blocks, Default::default(), BTreeMap::new()))
1130 }
1131
1132 fn insert(
1134 provider: &BlockchainProvider<MockNodeTypesWithDB>,
1135 blocks: &[&RecoveredBlock<Block>],
1136 ) -> eyre::Result<()> {
1137 let provider_rw = provider.database_provider_rw()?;
1138 for block in blocks {
1139 provider_rw.insert_block(block)?;
1140 }
1141 provider_rw.commit()?;
1142 Ok(())
1143 }
1144
1145 async fn run_with_head(
1148 provider: BlockchainProvider<MockNodeTypesWithDB>,
1149 node_head: BlockNumHash,
1150 exex_head: BlockNumHash,
1151 notifications: Vec<ExExNotification>,
1152 ) -> eyre::Result<(Vec<ExExNotification>, usize)> {
1153 let temp_dir = tempfile::tempdir()?;
1154 let wal = Wal::new(temp_dir.path())?;
1155 let (notifications_tx, notifications_rx) = mpsc::channel(notifications.len());
1156 for notification in notifications {
1157 notifications_tx.send(notification).await?;
1158 }
1159 drop(notifications_tx);
1160
1161 let (events_tx, mut events_rx) = mpsc::unbounded_channel();
1162 let mut stream = ExExNotificationsWithoutHead::new(
1163 node_head,
1164 provider,
1165 EthEvmConfig::mainnet(),
1166 notifications_rx,
1167 wal.handle(),
1168 );
1169 stream.notifications.revert_receipts = Some(events_tx);
1170 let yielded = stream.with_head(ExExHead { block: exex_head }).try_collect().await?;
1171
1172 let mut receipts = 0;
1173 while events_rx.try_recv().is_ok() {
1174 receipts += 1;
1175 }
1176 Ok((yielded, receipts))
1177 }
1178
1179 #[tokio::test]
1182 async fn exex_notifications_same_head_skips_reorg_to_head() -> eyre::Result<()> {
1183 let (provider, head_block, sibling_block) = same_head_setup()?;
1184 let head = head_block.num_hash();
1185
1186 let sequence = vec![ExExNotification::ChainReorged {
1187 old: chain(vec![sibling_block]),
1188 new: chain(vec![head_block]),
1189 }];
1190 let (yielded, receipts) = run_with_head(provider, head, head, sequence).await?;
1191 assert_eq!(yielded, vec![]);
1192 assert_eq!(receipts, 1);
1194
1195 Ok(())
1196 }
1197
1198 #[tokio::test]
1201 async fn exex_notifications_skip_reverts_behind_restored_head() -> eyre::Result<()> {
1202 let (provider, a1, b1) = same_head_setup()?;
1203 let mut rng = generators::rng();
1204 let a2 = block(&mut rng, 2, a1.hash())?;
1205 let c2 = block(&mut rng, 2, a1.hash())?;
1206 let a3 = block(&mut rng, 3, a2.hash())?;
1207 insert(&provider, &[&a2])?;
1208
1209 let commit_a3 = ExExNotification::ChainCommitted { new: chain(vec![a3]) };
1211 let sequence = vec![
1212 ExExNotification::ChainReorged { old: chain(vec![b1]), new: chain(vec![a1]) },
1213 ExExNotification::ChainReverted { old: chain(vec![c2]) },
1214 ExExNotification::ChainCommitted { new: chain(vec![a2.clone()]) },
1215 commit_a3.clone(),
1216 ];
1217 let (yielded, receipts) =
1218 run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence).await?;
1219 assert_eq!(yielded, vec![commit_a3]);
1220 assert_eq!(receipts, 2);
1221
1222 Ok(())
1223 }
1224
1225 #[tokio::test]
1228 async fn exex_notifications_deliver_revert_of_head_ancestors() -> eyre::Result<()> {
1229 let (provider, a1, _) = same_head_setup()?;
1230 let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1231 insert(&provider, &[&a2])?;
1232
1233 let sequence = vec![
1234 ExExNotification::ChainReverted { old: chain(vec![a1.clone()]) },
1235 ExExNotification::ChainCommitted { new: chain(vec![a1, a2.clone()]) },
1236 ];
1237 let (yielded, _) =
1238 run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence.clone()).await?;
1239 assert_eq!(yielded, sequence);
1240
1241 Ok(())
1242 }
1243
1244 #[tokio::test]
1247 async fn exex_notifications_deliver_reorg_to_non_canonical_chain() -> eyre::Result<()> {
1248 let (provider, a1, b1) = same_head_setup()?;
1249 let mut rng = generators::rng();
1250 let c1 = block(&mut rng, 1, a1.parent_hash())?;
1251 let a2 = block(&mut rng, 2, a1.hash())?;
1252 insert(&provider, &[&a2])?;
1253
1254 let sequence =
1255 vec![ExExNotification::ChainReorged { old: chain(vec![c1]), new: chain(vec![b1]) }];
1256 let (yielded, _) =
1257 run_with_head(provider, a2.num_hash(), a2.num_hash(), sequence.clone()).await?;
1258 assert_eq!(yielded, sequence);
1259
1260 Ok(())
1261 }
1262
1263 #[tokio::test]
1267 async fn exex_notifications_skip_backlog_applied_by_backfill() -> eyre::Result<()> {
1268 let (provider, b1, a1) = same_head_setup()?;
1269 let genesis = BlockNumHash::new(0, b1.parent_hash());
1270 let b2 = block(&mut generators::rng(), 2, b1.hash())?;
1271 insert(&provider, &[&b2])?;
1272
1273 let sequence = vec![
1274 ExExNotification::ChainReorged { old: chain(vec![a1]), new: chain(vec![b1]) },
1275 ExExNotification::ChainCommitted { new: chain(vec![b2.clone()]) },
1276 ];
1277 let (yielded, _) = run_with_head(provider, b2.num_hash(), genesis, sequence).await?;
1278 assert_eq!(yielded.len(), 1);
1280 assert_eq!(yielded[0].committed_chain().map(|c| c.tip().num_hash()), Some(b2.num_hash()));
1281
1282 Ok(())
1283 }
1284
1285 #[tokio::test]
1288 async fn exex_notifications_deliver_reverts_of_delivered_blocks() -> eyre::Result<()> {
1289 let (provider, a1, b1) = same_head_setup()?;
1290 let c1 = block(&mut generators::rng(), 1, a1.parent_hash())?;
1291
1292 let sequence = vec![
1293 ExExNotification::ChainReorged {
1294 old: chain(vec![a1.clone()]),
1295 new: chain(vec![b1.clone()]),
1296 },
1297 ExExNotification::ChainReverted { old: chain(vec![b1]) },
1298 ExExNotification::ChainCommitted { new: chain(vec![c1.clone()]) },
1299 ExExNotification::ChainReverted { old: chain(vec![c1]) },
1300 ];
1301 let (yielded, _) =
1302 run_with_head(provider, a1.num_hash(), a1.num_hash(), sequence.clone()).await?;
1303 assert_eq!(yielded, sequence);
1304
1305 Ok(())
1306 }
1307
1308 #[tokio::test]
1311 async fn exex_notifications_deliver_reorg_past_head() -> eyre::Result<()> {
1312 let (provider, a1, _) = same_head_setup()?;
1313 let mut rng = generators::rng();
1314 let a2 = block(&mut rng, 2, a1.hash())?;
1315 let a3 = block(&mut rng, 3, a2.hash())?;
1316 let b2 = block(&mut rng, 2, a1.hash())?;
1317 insert(&provider, &[&a2, &a3])?;
1318
1319 let sequence =
1320 vec![ExExNotification::ChainReorged { old: chain(vec![b2]), new: chain(vec![a2, a3]) }];
1321 let (yielded, _) =
1322 run_with_head(provider, a1.num_hash(), a1.num_hash(), sequence.clone()).await?;
1323 assert_eq!(yielded, sequence);
1324
1325 Ok(())
1326 }
1327
1328 #[tokio::test]
1331 async fn exex_notifications_commit_buffered_after_revert_during_backfill() -> eyre::Result<()> {
1332 let (provider, a1, b1) = same_head_setup()?;
1333 let a2 = block(&mut generators::rng(), 2, a1.hash())?;
1334 insert(&provider, &[&a2])?;
1335
1336 let sequence = vec![
1337 ExExNotification::ChainReverted { old: chain(vec![a1.clone(), a2.clone()]) },
1338 ExExNotification::ChainCommitted { new: chain(vec![b1]) },
1339 ];
1340 let (yielded, _) =
1341 run_with_head(provider, a2.num_hash(), a1.num_hash(), sequence.clone()).await?;
1342 assert_eq!(yielded[0].committed_chain().map(|c| c.tip().num_hash()), Some(a2.num_hash()));
1344 assert_eq!(yielded[1..], sequence);
1345
1346 Ok(())
1347 }
1348
1349 #[tokio::test]
1352 async fn exex_notifications_deliver_revert_below_non_canonical_head() -> eyre::Result<()> {
1353 let (provider, a1, c1) = same_head_setup()?;
1354 let c2 = block(&mut generators::rng(), 2, c1.hash())?;
1355
1356 let sequence = vec![ExExNotification::ChainReverted { old: chain(vec![c1]) }];
1358 let (yielded, _) =
1359 run_with_head(provider, a1.num_hash(), c2.num_hash(), sequence.clone()).await?;
1360 assert_eq!(yielded, sequence);
1361
1362 Ok(())
1363 }
1364
1365 #[tokio::test]
1368 async fn exex_notifications_same_head_reorg_above_head() -> eyre::Result<()> {
1369 let temp_dir = tempfile::tempdir().unwrap();
1370 let wal = Wal::new(temp_dir.path()).unwrap();
1371 let (provider, head_block, sibling_block) = same_head_setup()?;
1372 let head = head_block.num_hash();
1373
1374 let child_block = random_block(
1375 &mut generators::rng(),
1376 2,
1377 BlockParams { parent: Some(head.hash), tx_count: Some(0), ..Default::default() },
1378 )
1379 .try_recover()?;
1380 let reorg = ExExNotification::ChainReorged {
1381 old: Arc::new(Chain::new(vec![sibling_block], Default::default(), BTreeMap::new())),
1382 new: Arc::new(Chain::new(
1383 vec![head_block, child_block],
1384 Default::default(),
1385 BTreeMap::new(),
1386 )),
1387 };
1388 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1389 notifications_tx.send(reorg.clone()).await?;
1390 drop(notifications_tx);
1391
1392 let mut notifications = ExExNotificationsWithoutHead::new(
1393 head,
1394 provider,
1395 EthEvmConfig::mainnet(),
1396 notifications_rx,
1397 wal.handle(),
1398 )
1399 .with_head(ExExHead { block: head });
1400
1401 assert_eq!(notifications.next().await.transpose()?, Some(reorg));
1402
1403 Ok(())
1404 }
1405
1406 #[tokio::test]
1409 async fn exex_notifications_same_head_commit_after_revert() -> eyre::Result<()> {
1410 let temp_dir = tempfile::tempdir().unwrap();
1411 let wal = Wal::new(temp_dir.path()).unwrap();
1412 let (provider, head_block, sibling_block) = same_head_setup()?;
1413 let head = head_block.num_hash();
1414
1415 let revert = ExExNotification::ChainReverted {
1416 old: Arc::new(Chain::new(vec![head_block], Default::default(), BTreeMap::new())),
1417 };
1418 let commit = ExExNotification::ChainCommitted {
1419 new: Arc::new(Chain::new(vec![sibling_block], Default::default(), BTreeMap::new())),
1420 };
1421 let (notifications_tx, notifications_rx) = mpsc::channel(2);
1422 notifications_tx.send(revert.clone()).await?;
1423 notifications_tx.send(commit.clone()).await?;
1424 drop(notifications_tx);
1425
1426 let mut notifications = ExExNotificationsWithoutHead::new(
1427 head,
1428 provider,
1429 EthEvmConfig::mainnet(),
1430 notifications_rx,
1431 wal.handle(),
1432 )
1433 .with_head(ExExHead { block: head });
1434
1435 assert_eq!(notifications.next().await.transpose()?, Some(revert));
1436 assert_eq!(notifications.next().await.transpose()?, Some(commit));
1437 assert_eq!(notifications.next().await.transpose()?, None);
1438
1439 Ok(())
1440 }
1441
1442 #[tokio::test]
1443 async fn exex_notifications_same_head_non_canonical() -> eyre::Result<()> {
1444 let mut rng = generators::rng();
1445
1446 let temp_dir = tempfile::tempdir().unwrap();
1447 let wal = Wal::new(temp_dir.path()).unwrap();
1448
1449 let provider_factory = create_test_provider_factory();
1450 let genesis_hash = init_genesis(&provider_factory)?;
1451 let genesis_block = provider_factory
1452 .block(genesis_hash.into())?
1453 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1454
1455 let provider = BlockchainProvider::new(provider_factory)?;
1456
1457 let node_head_block = random_block(
1458 &mut rng,
1459 genesis_block.number + 1,
1460 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1461 )
1462 .try_recover()?;
1463 let node_head = node_head_block.num_hash();
1464 let provider_rw = provider.database_provider_rw()?;
1465 provider_rw.insert_block(&node_head_block)?;
1466 provider_rw.commit()?;
1467 let node_head_notification = ExExNotification::ChainCommitted {
1468 new: Arc::new(
1469 BackfillJobFactory::new(EthEvmConfig::mainnet(), provider.clone())
1470 .backfill(node_head.number..=node_head.number)
1471 .next()
1472 .ok_or_else(|| eyre::eyre!("failed to backfill"))??,
1473 ),
1474 };
1475
1476 let exex_head_block = random_block(
1477 &mut rng,
1478 genesis_block.number + 1,
1479 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1480 );
1481 let exex_head = ExExHead { block: exex_head_block.num_hash() };
1482 let exex_head_notification = ExExNotification::ChainCommitted {
1483 new: Arc::new(Chain::new(
1484 vec![exex_head_block.clone().try_recover()?],
1485 Default::default(),
1486 BTreeMap::new(),
1487 )),
1488 };
1489 wal.commit(&exex_head_notification)?;
1490
1491 let new_notification = ExExNotification::ChainCommitted {
1492 new: Arc::new(Chain::new(
1493 vec![random_block(
1494 &mut rng,
1495 node_head.number + 1,
1496 BlockParams { parent: Some(node_head.hash), ..Default::default() },
1497 )
1498 .try_recover()?],
1499 Default::default(),
1500 BTreeMap::new(),
1501 )),
1502 };
1503
1504 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1505
1506 notifications_tx.send(new_notification.clone()).await?;
1507
1508 let mut notifications = ExExNotificationsWithoutHead::new(
1509 node_head,
1510 provider,
1511 EthEvmConfig::mainnet(),
1512 notifications_rx,
1513 wal.handle(),
1514 )
1515 .with_head(exex_head);
1516
1517 assert_eq!(
1520 notifications.next().await.transpose()?,
1521 Some(exex_head_notification.into_inverted())
1522 );
1523 assert_eq!(notifications.next().await.transpose()?, Some(node_head_notification));
1526 assert_eq!(notifications.next().await.transpose()?, Some(new_notification));
1528
1529 Ok(())
1530 }
1531
1532 #[tokio::test]
1533 async fn test_notifications_ahead_of_head() -> eyre::Result<()> {
1534 reth_tracing::init_test_tracing();
1535 let mut rng = generators::rng();
1536
1537 let temp_dir = tempfile::tempdir().unwrap();
1538 let wal = Wal::new(temp_dir.path()).unwrap();
1539
1540 let provider_factory = create_test_provider_factory();
1541 let genesis_hash = init_genesis(&provider_factory)?;
1542 let genesis_block = provider_factory
1543 .block(genesis_hash.into())?
1544 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1545
1546 let provider = BlockchainProvider::new(provider_factory)?;
1547
1548 let exex_head_block = random_block(
1549 &mut rng,
1550 genesis_block.number + 1,
1551 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1552 );
1553 let exex_head_notification = ExExNotification::ChainCommitted {
1554 new: Arc::new(Chain::new(
1555 vec![exex_head_block.clone().try_recover()?],
1556 Default::default(),
1557 BTreeMap::new(),
1558 )),
1559 };
1560 wal.commit(&exex_head_notification)?;
1561
1562 let node_head = BlockNumHash { number: genesis_block.number, hash: genesis_hash };
1563 let exex_head = ExExHead {
1564 block: BlockNumHash { number: exex_head_block.number, hash: exex_head_block.hash() },
1565 };
1566
1567 let new_notification = ExExNotification::ChainCommitted {
1568 new: Arc::new(Chain::new(
1569 vec![random_block(
1570 &mut rng,
1571 genesis_block.number + 1,
1572 BlockParams { parent: Some(genesis_hash), ..Default::default() },
1573 )
1574 .try_recover()?],
1575 Default::default(),
1576 BTreeMap::new(),
1577 )),
1578 };
1579
1580 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1581
1582 notifications_tx.send(new_notification.clone()).await?;
1583
1584 let mut notifications = ExExNotificationsWithoutHead::new(
1585 node_head,
1586 provider,
1587 EthEvmConfig::mainnet(),
1588 notifications_rx,
1589 wal.handle(),
1590 )
1591 .with_head(exex_head);
1592
1593 assert_eq!(
1596 notifications.next().await.transpose()?,
1597 Some(exex_head_notification.into_inverted())
1598 );
1599
1600 assert_eq!(notifications.next().await.transpose()?, Some(new_notification));
1602
1603 Ok(())
1604 }
1605
1606 #[tokio::test]
1619 async fn exex_notifications_backfill_drains_channel() -> eyre::Result<()> {
1620 let mut rng = generators::rng();
1621
1622 let temp_dir = tempfile::tempdir().unwrap();
1623 let wal = Wal::new(temp_dir.path()).unwrap();
1624
1625 let provider_factory = create_test_provider_factory();
1626 let genesis_hash = init_genesis(&provider_factory)?;
1627 let genesis_block = provider_factory
1628 .block(genesis_hash.into())?
1629 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1630
1631 let provider = BlockchainProvider::new(provider_factory.clone())?;
1632
1633 let node_head_block = random_block(
1635 &mut rng,
1636 genesis_block.number + 1,
1637 BlockParams { parent: Some(genesis_hash), tx_count: Some(0), ..Default::default() },
1638 )
1639 .try_recover()?;
1640 let node_head = node_head_block.num_hash();
1641 let provider_rw = provider_factory.provider_rw()?;
1642 provider_rw.insert_block(&node_head_block)?;
1643 provider_rw.commit()?;
1644
1645 let exex_head =
1647 ExExHead { block: BlockNumHash { number: genesis_block.number, hash: genesis_hash } };
1648
1649 let post_backfill_notification = ExExNotification::ChainCommitted {
1651 new: Arc::new(Chain::new(
1652 vec![random_block(
1653 &mut rng,
1654 node_head.number + 1,
1655 BlockParams { parent: Some(node_head.hash), ..Default::default() },
1656 )
1657 .try_recover()?],
1658 Default::default(),
1659 BTreeMap::new(),
1660 )),
1661 };
1662
1663 let probe_notification = ExExNotification::ChainCommitted {
1665 new: Arc::new(Chain::new(
1666 vec![random_block(
1667 &mut rng,
1668 node_head.number + 2,
1669 BlockParams { parent: None, ..Default::default() },
1670 )
1671 .try_recover()?],
1672 Default::default(),
1673 BTreeMap::new(),
1674 )),
1675 };
1676
1677 let (notifications_tx, notifications_rx) = mpsc::channel(1);
1678
1679 notifications_tx.send(post_backfill_notification.clone()).await?;
1681
1682 assert!(
1685 notifications_tx.try_send(probe_notification.clone()).is_err(),
1686 "channel should be full before backfill poll"
1687 );
1688
1689 let mut notifications = ExExNotificationsWithoutHead::new(
1690 node_head,
1691 provider,
1692 EthEvmConfig::mainnet(),
1693 notifications_rx,
1694 wal.handle(),
1695 )
1696 .with_head(exex_head);
1697
1698 let backfill_result = notifications.next().await.transpose()?;
1702 assert_eq!(
1703 backfill_result,
1704 Some(ExExNotification::ChainCommitted {
1705 new: Arc::new(
1706 BackfillJobFactory::new(
1707 notifications.evm_config.clone(),
1708 notifications.provider.clone()
1709 )
1710 .backfill(1..=1)
1711 .next()
1712 .ok_or_eyre("failed to backfill")??
1713 )
1714 })
1715 );
1716
1717 assert!(
1721 notifications_tx.try_send(probe_notification.clone()).is_ok(),
1722 "channel should have been drained during backfill poll"
1723 );
1724
1725 let buffered = notifications.next().await.transpose()?;
1728 assert_eq!(buffered, Some(post_backfill_notification));
1729
1730 let probe = notifications.next().await.transpose()?;
1732 assert_eq!(probe, Some(probe_notification));
1733
1734 Ok(())
1735 }
1736}