1use crate::{
2 wal::Wal, ExExEvent, ExExNotification, ExExNotifications, FinishedExExHeight, WalHandle,
3};
4use alloy_consensus::BlockHeader;
5use alloy_eips::BlockNumHash;
6use futures::StreamExt;
7use itertools::Itertools;
8use metrics::Gauge;
9use reth_chain_state::ForkChoiceStream;
10use reth_ethereum_primitives::EthPrimitives;
11use reth_evm::ConfigureEvm;
12use reth_metrics::{metrics::Counter, Metrics};
13use reth_node_api::NodePrimitives;
14use reth_primitives_traits::SealedHeader;
15use reth_provider::{Chain, HeaderProvider};
16use std::{
17 collections::VecDeque,
18 fmt::Debug,
19 future::{poll_fn, Future},
20 ops::Not,
21 pin::Pin,
22 sync::{
23 atomic::{AtomicUsize, Ordering},
24 Arc,
25 },
26 task::{ready, Context, Poll},
27};
28use tokio::sync::{
29 mpsc::{self, error::SendError, UnboundedReceiver, UnboundedSender},
30 watch,
31};
32use tokio_util::sync::{PollSendError, PollSender, ReusableBoxFuture};
33use tracing::{debug, warn};
34
35pub const DEFAULT_EXEX_MANAGER_CAPACITY: usize = 1024;
40
41pub const DEFAULT_WAL_BLOCKS_WARNING: usize = 128;
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum ExExNotificationSource {
56 Pipeline,
58 BlockchainTree,
60}
61
62#[derive(Metrics)]
64#[metrics(scope = "exex")]
65struct ExExMetrics {
66 notifications_sent_total: Counter,
68 events_sent_total: Counter,
70}
71
72#[derive(Debug)]
78pub struct ExExHandle<N: NodePrimitives = EthPrimitives> {
79 id: String,
81 metrics: ExExMetrics,
83 sender: PollSender<ExExNotification<N>>,
85 receiver: UnboundedReceiver<ExExEvent>,
87 next_notification_id: usize,
89 finished_height: Option<BlockNumHash>,
93 unacknowledged_reverts: usize,
99}
100
101impl<N: NodePrimitives> ExExHandle<N> {
102 pub fn new<P, E: ConfigureEvm<Primitives = N>>(
107 id: String,
108 node_head: BlockNumHash,
109 provider: P,
110 evm_config: E,
111 wal_handle: WalHandle<N>,
112 ) -> (Self, UnboundedSender<ExExEvent>, ExExNotifications<P, E>) {
113 let (notification_tx, notification_rx) = mpsc::channel(1);
114 let (event_tx, event_rx) = mpsc::unbounded_channel();
115 let notifications =
116 ExExNotifications::new(node_head, provider, evm_config, notification_rx, wal_handle)
117 .with_revert_receipts(event_tx.clone());
118
119 (
120 Self {
121 id: id.clone(),
122 metrics: ExExMetrics::new_with_labels(&[("exex", id)]),
123 sender: PollSender::new(notification_tx),
124 receiver: event_rx,
125 next_notification_id: 0,
126 finished_height: None,
127 unacknowledged_reverts: 0,
128 },
129 event_tx,
130 notifications,
131 )
132 }
133
134 fn send(
139 &mut self,
140 cx: &mut Context<'_>,
141 (notification_id, notification): &(usize, ExExNotification<N>),
142 ) -> Poll<Result<(), PollSendError<ExExNotification<N>>>> {
143 if let Some(finished_height) = self.finished_height &&
149 let ExExNotification::ChainCommitted { new } = notification &&
150 finished_height.number >= new.tip().number()
151 {
152 debug!(
153 target: "exex::manager",
154 exex_id = %self.id,
155 %notification_id,
156 ?finished_height,
157 new_tip = %new.tip().number(),
158 "Skipping notification"
159 );
160
161 self.next_notification_id = notification_id + 1;
162 return Poll::Ready(Ok(()))
163 }
164
165 let reverted = notification.reverted_chain();
169 if let Some(reverted) = &reverted &&
170 let Some(finished_height) = &mut self.finished_height
171 {
172 rewind_to_fork_block(finished_height, reverted);
173 }
174
175 debug!(
176 target: "exex::manager",
177 exex_id = %self.id,
178 %notification_id,
179 "Reserving slot for notification"
180 );
181 match self.sender.poll_reserve(cx) {
182 Poll::Ready(Ok(())) => (),
183 other => return other,
184 }
185
186 debug!(
187 target: "exex::manager",
188 exex_id = %self.id,
189 %notification_id,
190 "Sending notification"
191 );
192 match self.sender.send_item(notification.clone()) {
193 Ok(()) => {
194 self.next_notification_id = notification_id + 1;
195 self.metrics.notifications_sent_total.increment(1);
196 if reverted.is_some() {
197 self.unacknowledged_reverts += 1;
198 }
199 Poll::Ready(Ok(()))
200 }
201 Err(err) => Poll::Ready(Err(err)),
202 }
203 }
204}
205
206#[derive(Metrics)]
208#[metrics(scope = "exex.manager")]
209pub struct ExExManagerMetrics {
210 max_capacity: Gauge,
212 current_capacity: Gauge,
214 buffer_size: Gauge,
218 num_exexs: Gauge,
220 queued_notifications: Gauge,
222}
223
224#[derive(Debug)]
234pub struct ExExManager<P, N: NodePrimitives> {
235 provider: P,
237
238 exex_handles: Vec<ExExHandle<N>>,
240
241 handle_rx: UnboundedReceiver<(ExExNotificationSource, ExExNotification<N>)>,
243
244 queued_notifications: VecDeque<QueuedNotification<N>>,
246
247 min_id: usize,
249 next_id: usize,
251 buffer: VecDeque<(usize, ExExNotification<N>)>,
256 max_capacity: usize,
258 current_capacity: Arc<AtomicUsize>,
262
263 is_ready: watch::Sender<bool>,
265
266 finished_height: watch::Sender<FinishedExExHeight>,
268
269 wal: Wal<N>,
271 finalized_header_stream: ForkChoiceStream<SealedHeader<N::BlockHeader>>,
273 wal_blocks_warning: usize,
275
276 handle: ExExManagerHandle<N>,
278 metrics: ExExManagerMetrics,
280}
281
282impl<P, N> ExExManager<P, N>
283where
284 N: NodePrimitives,
285{
286 pub fn new(
294 provider: P,
295 handles: Vec<ExExHandle<N>>,
296 max_capacity: usize,
297 wal: Wal<N>,
298 finalized_header_stream: ForkChoiceStream<SealedHeader<N::BlockHeader>>,
299 ) -> Self {
300 let num_exexs = handles.len();
301
302 let (handle_tx, handle_rx) = mpsc::unbounded_channel();
303 let (is_ready_tx, is_ready_rx) = watch::channel(true);
304 let (finished_height_tx, finished_height_rx) = watch::channel(if num_exexs == 0 {
305 FinishedExExHeight::NoExExs
306 } else {
307 FinishedExExHeight::NotReady
308 });
309
310 let current_capacity = Arc::new(AtomicUsize::new(max_capacity));
311
312 let metrics = ExExManagerMetrics::default();
313 metrics.max_capacity.set(max_capacity as f64);
314 metrics.num_exexs.set(num_exexs as f64);
315
316 Self {
317 provider,
318
319 exex_handles: handles,
320
321 handle_rx,
322
323 queued_notifications: VecDeque::new(),
324
325 min_id: 0,
326 next_id: 0,
327 buffer: VecDeque::with_capacity(max_capacity),
328 max_capacity,
329 current_capacity: Arc::clone(¤t_capacity),
330
331 is_ready: is_ready_tx,
332 finished_height: finished_height_tx,
333
334 wal,
335 finalized_header_stream,
336 wal_blocks_warning: DEFAULT_WAL_BLOCKS_WARNING,
337
338 handle: ExExManagerHandle {
339 exex_tx: handle_tx,
340 num_exexs,
341 is_ready_receiver: is_ready_rx.clone(),
342 is_ready: ReusableBoxFuture::new(make_wait_future(is_ready_rx)),
343 current_capacity,
344 finished_height: finished_height_rx,
345 },
346 metrics,
347 }
348 }
349
350 pub fn handle(&self) -> ExExManagerHandle<N> {
352 self.handle.clone()
353 }
354
355 pub const fn with_wal_blocks_warning(mut self, threshold: usize) -> Self {
361 self.wal_blocks_warning = threshold;
362 self
363 }
364
365 fn update_capacity(&self) {
368 let capacity = self
369 .max_capacity
370 .saturating_sub(self.buffer.len().saturating_add(self.queued_notifications.len()));
371 self.current_capacity.store(capacity, Ordering::Relaxed);
372 self.metrics.current_capacity.set(capacity as f64);
373 self.metrics.buffer_size.set(self.buffer.len() as f64);
374
375 let _ = self.is_ready.send(capacity > 0);
378 }
379
380 fn push_notification(&mut self, notification: ExExNotification<N>) {
383 let next_id = self.next_id;
384 self.buffer.push_back((next_id, notification));
385 self.next_id += 1;
386 }
387
388 fn can_push_notification(&self) -> bool {
390 self.queued_notifications.is_empty() && self.buffer.len() < self.max_capacity
391 }
392}
393
394impl<P, N> ExExManager<P, N>
395where
396 P: HeaderProvider,
397 N: NodePrimitives,
398{
399 fn finalize_wal(&self, finalized_header: SealedHeader<N::BlockHeader>) -> eyre::Result<()> {
404 debug!(target: "exex::manager", header = ?finalized_header.num_hash(), "Received finalized header");
405
406 let exex_finished_heights = self
408 .exex_handles
409 .iter()
410 .map(|exex_handle| (&exex_handle.id, exex_handle.finished_height))
412 .unique_by(|(_, num_hash)| num_hash.map(|num_hash| num_hash.hash))
414 .map(|(exex_id, num_hash)| {
416 num_hash.map_or(Ok((exex_id, num_hash, false)), |num_hash| {
417 self.provider
418 .is_known(num_hash.hash)
419 .map(|is_canonical| (exex_id, Some(num_hash), is_canonical))
421 })
422 })
423 .collect::<Result<Vec<_>, _>>()?;
425 if exex_finished_heights.iter().all(|(_, _, is_canonical)| *is_canonical) {
426 let lowest_finished_height = exex_finished_heights
430 .iter()
431 .copied()
432 .filter_map(|(_, num_hash, _)| num_hash)
433 .chain([(finalized_header.num_hash())])
434 .min_by_key(|num_hash| num_hash.number)
435 .unwrap();
436
437 let retain_from = self.queued_notifications.iter().find_map(|queued| match queued {
441 QueuedNotification::Wal(file_id) => Some(*file_id),
442 QueuedNotification::Handle(_) => None,
443 });
444 self.wal.finalize_retaining(lowest_finished_height, retain_from)?;
445 if self.wal.num_blocks() > self.wal_blocks_warning {
446 warn!(
447 target: "exex::manager",
448 blocks = ?self.wal.num_blocks(),
449 threshold = self.wal_blocks_warning,
450 queued_notifications = self.queued_notifications.len(),
451 "WAL contains too many blocks and is not getting cleared. That will lead to increased disk space usage. Check that you emit the FinishedHeight event from your ExExes."
452 );
453 }
454 } else {
455 let unfinalized_exexes = exex_finished_heights
456 .into_iter()
457 .filter_map(|(exex_id, num_hash, is_canonical)| {
458 is_canonical.not().then_some((exex_id, num_hash))
459 })
460 .format_with(", ", |(exex_id, num_hash), f| {
461 f(&format_args!("{exex_id} = {num_hash:?}"))
462 })
463 .to_string();
466 debug!(
467 target: "exex::manager",
468 %unfinalized_exexes,
469 "Not all ExExes are on the canonical chain, can't finalize the WAL"
470 );
471 }
472
473 Ok(())
474 }
475}
476
477impl<P, N> Future for ExExManager<P, N>
478where
479 P: HeaderProvider + Unpin + 'static,
480 N: NodePrimitives,
481{
482 type Output = eyre::Result<()>;
483
484 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
498 let this = self.get_mut();
499
500 for exex in &mut this.exex_handles {
502 while let Poll::Ready(Some(event)) = exex.receiver.poll_recv(cx) {
503 debug!(target: "exex::manager", exex_id = %exex.id, ?event, "Received event from ExEx");
504 if !matches!(event, ExExEvent::RevertReceived(_)) {
506 exex.metrics.events_sent_total.increment(1);
507 }
508 match event {
509 ExExEvent::FinishedHeight(height) if exex.unacknowledged_reverts == 0 => {
510 exex.finished_height = Some(height)
511 }
512 ExExEvent::FinishedHeight(height) => {
513 debug!(
514 target: "exex::manager",
515 exex_id = %exex.id,
516 ?height,
517 unacknowledged_reverts = exex.unacknowledged_reverts,
518 "Ignoring finished height sent before the ExEx received a revert"
519 );
520 }
521 ExExEvent::RevertReceived(_) => {
522 debug_assert!(exex.unacknowledged_reverts > 0, "unexpected revert receipt");
525 exex.unacknowledged_reverts = exex.unacknowledged_reverts.saturating_sub(1);
526 }
527 }
528 }
529 }
530
531 while let Poll::Ready(Some((source, notification))) = this.handle_rx.poll_recv(cx) {
533 let committed_tip = notification.committed_chain().map(|chain| chain.tip().number());
534 let reverted_tip = notification.reverted_chain().map(|chain| chain.tip().number());
535 debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Received new notification");
536
537 let file_id = match source {
540 ExExNotificationSource::BlockchainTree => {
541 debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Committing notification to WAL");
542 Some(this.wal.commit(¬ification)?)
543 }
544 ExExNotificationSource::Pipeline => {
545 debug!(target: "exex::manager", ?committed_tip, ?reverted_tip, "Notification was sent from pipeline, skipping WAL commit");
546 None
547 }
548 };
549
550 if this.can_push_notification() {
551 this.push_notification(notification);
552 } else if let Some(file_id) = file_id {
553 this.queued_notifications.push_back(QueuedNotification::Wal(file_id));
555 } else {
556 this.queued_notifications.push_back(QueuedNotification::Handle(notification));
557 }
558 }
559
560 let mut last_finalized_header = None;
562 while let Poll::Ready(finalized_header) = this.finalized_header_stream.poll_next_unpin(cx) {
563 last_finalized_header = finalized_header;
564 }
565 if let Some(header) = last_finalized_header {
566 this.finalize_wal(header)?;
567 }
568
569 while this.buffer.len() < this.max_capacity &&
571 let Some(queued) = this.queued_notifications.pop_front()
572 {
573 let notification = match queued {
574 QueuedNotification::Wal(file_id) => this.wal.read_notification(file_id)?,
575 QueuedNotification::Handle(notification) => notification,
576 };
577 this.push_notification(notification);
578 }
579 this.metrics.queued_notifications.set(this.queued_notifications.len() as f64);
580 let buffer_full = this.buffer.len() >= this.max_capacity;
581
582 let mut min_id = usize::MAX;
584 for idx in (0..this.exex_handles.len()).rev() {
585 let mut exex = this.exex_handles.swap_remove(idx);
586
587 let notification_index = exex
590 .next_notification_id
591 .checked_sub(this.min_id)
592 .expect("exex expected notification ID outside the manager's range");
593 if let Some(notification) = this.buffer.get(notification_index) &&
594 let Poll::Ready(Err(err)) = exex.send(cx, notification)
595 {
596 return Poll::Ready(Err(err.into()))
598 }
599 min_id = min_id.min(exex.next_notification_id);
600 this.exex_handles.push(exex);
601 }
602
603 debug!(target: "exex::manager", %min_id, "Updating lowest notification id in buffer");
605 this.buffer.retain(|&(id, _)| id >= min_id);
606 this.min_id = min_id;
607
608 this.update_capacity();
610
611 if buffer_full && this.buffer.len() < this.max_capacity {
613 debug!(target: "exex::manager", "Buffer has space again, waking up senders");
614 cx.waker().wake_by_ref();
615 }
616
617 let finished_height = this.exex_handles.iter_mut().try_fold(u64::MAX, |curr, exex| {
619 exex.finished_height.map_or(Err(()), |height| Ok(height.number.min(curr)))
620 });
621 if let Ok(finished_height) = finished_height {
622 let _ = this.finished_height.send(FinishedExExHeight::Height(finished_height));
623 }
624
625 Poll::Pending
626 }
627}
628
629#[derive(Debug)]
631pub struct ExExManagerHandle<N: NodePrimitives = EthPrimitives> {
632 exex_tx: UnboundedSender<(ExExNotificationSource, ExExNotification<N>)>,
634 num_exexs: usize,
636 is_ready_receiver: watch::Receiver<bool>,
642 is_ready: ReusableBoxFuture<'static, watch::Receiver<bool>>,
645 current_capacity: Arc<AtomicUsize>,
647 finished_height: watch::Receiver<FinishedExExHeight>,
649}
650
651impl<N: NodePrimitives> ExExManagerHandle<N> {
652 pub fn empty() -> Self {
658 let (exex_tx, _) = mpsc::unbounded_channel();
659 let (_, is_ready_rx) = watch::channel(true);
660 let (_, finished_height_rx) = watch::channel(FinishedExExHeight::NoExExs);
661
662 Self {
663 exex_tx,
664 num_exexs: 0,
665 is_ready_receiver: is_ready_rx.clone(),
666 is_ready: ReusableBoxFuture::new(make_wait_future(is_ready_rx)),
667 current_capacity: Arc::new(AtomicUsize::new(0)),
668 finished_height: finished_height_rx,
669 }
670 }
671
672 pub fn send(
676 &self,
677 source: ExExNotificationSource,
678 notification: ExExNotification<N>,
679 ) -> Result<(), SendError<(ExExNotificationSource, ExExNotification<N>)>> {
680 self.exex_tx.send((source, notification))
681 }
682
683 pub async fn send_async(
688 &mut self,
689 source: ExExNotificationSource,
690 notification: ExExNotification<N>,
691 ) -> Result<(), SendError<(ExExNotificationSource, ExExNotification<N>)>> {
692 self.ready().await;
693 self.exex_tx.send((source, notification))
694 }
695
696 pub fn capacity(&self) -> usize {
698 self.current_capacity.load(Ordering::Relaxed)
699 }
700
701 pub fn has_capacity(&self) -> bool {
706 self.capacity() > 0
707 }
708
709 pub const fn has_exexs(&self) -> bool {
711 self.num_exexs > 0
712 }
713
714 pub fn finished_height(&self) -> watch::Receiver<FinishedExExHeight> {
716 self.finished_height.clone()
717 }
718
719 pub async fn ready(&mut self) {
721 poll_fn(|cx| self.poll_ready(cx)).await
722 }
723
724 pub fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<()> {
726 let rx = ready!(self.is_ready.poll(cx));
727 self.is_ready.set(make_wait_future(rx));
728 Poll::Ready(())
729 }
730}
731
732fn rewind_to_fork_block<N: NodePrimitives>(block: &mut BlockNumHash, reverted: &Chain<N>) {
739 if reverted.block_number(block.hash) == Some(block.number) {
740 *block = reverted.fork_block();
741 }
742}
743
744async fn make_wait_future(mut rx: watch::Receiver<bool>) -> watch::Receiver<bool> {
746 let _ = rx.wait_for(|ready| *ready).await;
749 rx
750}
751
752impl<N: NodePrimitives> Clone for ExExManagerHandle<N> {
753 fn clone(&self) -> Self {
754 Self {
755 exex_tx: self.exex_tx.clone(),
756 num_exexs: self.num_exexs,
757 is_ready_receiver: self.is_ready_receiver.clone(),
758 is_ready: ReusableBoxFuture::new(make_wait_future(self.is_ready_receiver.clone())),
759 current_capacity: self.current_capacity.clone(),
760 finished_height: self.finished_height.clone(),
761 }
762 }
763}
764
765#[derive(Debug)]
767enum QueuedNotification<N: NodePrimitives> {
768 Wal(u32),
770 Handle(ExExNotification<N>),
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777 use crate::wal::{WalError, WalResult};
778 use alloy_primitives::B256;
779 use futures::{FutureExt, StreamExt, TryStreamExt};
780 use rand::Rng;
781 use reth_chain_state::CanonStateNotification;
782 use reth_db_common::init::init_genesis;
783 use reth_evm_ethereum::EthEvmConfig;
784 use reth_primitives_traits::RecoveredBlock;
785 use reth_provider::{
786 providers::BlockchainProvider,
787 test_utils::{create_test_provider_factory, MockEthProvider},
788 BlockReader, BlockWriter, Chain, DBProvider, DatabaseProviderFactory, TransactionVariant,
789 };
790 use reth_testing_utils::generators::{
791 self, random_block, random_block_range, BlockParams, BlockRangeParams,
792 };
793 use std::time::Duration;
794
795 fn empty_finalized_header_stream() -> ForkChoiceStream<SealedHeader> {
796 let (tx, rx) = watch::channel(None);
797 std::mem::forget(tx);
799 ForkChoiceStream::new(rx)
800 }
801
802 #[tokio::test]
803 async fn test_delivers_events() {
804 let temp_dir = tempfile::tempdir().unwrap();
805 let wal = Wal::new(temp_dir.path()).unwrap();
806
807 let (mut exex_handle, event_tx, mut _notification_rx) = ExExHandle::new(
808 "test_exex".to_string(),
809 Default::default(),
810 (),
811 EthEvmConfig::mainnet(),
812 wal.handle(),
813 );
814
815 let event = ExExEvent::FinishedHeight(BlockNumHash::new(42, B256::random()));
817 event_tx.send(event).unwrap();
818 let received_event = exex_handle.receiver.recv().await.unwrap();
819 assert_eq!(received_event, event);
820 }
821
822 #[tokio::test]
823 async fn test_has_exexs() {
824 let temp_dir = tempfile::tempdir().unwrap();
825 let wal = Wal::new(temp_dir.path()).unwrap();
826
827 let (exex_handle_1, _, _) = ExExHandle::new(
828 "test_exex_1".to_string(),
829 Default::default(),
830 (),
831 EthEvmConfig::mainnet(),
832 wal.handle(),
833 );
834
835 assert!(!ExExManager::new((), vec![], 0, wal.clone(), empty_finalized_header_stream())
836 .handle
837 .has_exexs());
838
839 assert!(ExExManager::new((), vec![exex_handle_1], 0, wal, empty_finalized_header_stream())
840 .handle
841 .has_exexs());
842 }
843
844 #[tokio::test]
845 async fn test_has_capacity() {
846 let temp_dir = tempfile::tempdir().unwrap();
847 let wal = Wal::new(temp_dir.path()).unwrap();
848
849 let (exex_handle_1, _, _) = ExExHandle::new(
850 "test_exex_1".to_string(),
851 Default::default(),
852 (),
853 EthEvmConfig::mainnet(),
854 wal.handle(),
855 );
856
857 assert!(!ExExManager::new((), vec![], 0, wal.clone(), empty_finalized_header_stream())
858 .handle
859 .has_capacity());
860
861 assert!(ExExManager::new(
862 (),
863 vec![exex_handle_1],
864 10,
865 wal,
866 empty_finalized_header_stream()
867 )
868 .handle
869 .has_capacity());
870 }
871
872 #[test]
873 fn test_push_notification() {
874 let temp_dir = tempfile::tempdir().unwrap();
875 let wal = Wal::new(temp_dir.path()).unwrap();
876
877 let (exex_handle, _, _) = ExExHandle::new(
878 "test_exex".to_string(),
879 Default::default(),
880 (),
881 EthEvmConfig::mainnet(),
882 wal.handle(),
883 );
884
885 let mut exex_manager =
887 ExExManager::new((), vec![exex_handle], 10, wal, empty_finalized_header_stream());
888
889 let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
891 block1.set_hash(B256::repeat_byte(0x01));
892 block1.set_block_number(10);
893
894 let notification1 = ExExNotification::ChainCommitted {
895 new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
896 };
897
898 exex_manager.push_notification(notification1.clone());
900
901 assert_eq!(exex_manager.buffer.len(), 1);
903 assert_eq!(exex_manager.buffer.front().unwrap().0, 0);
904 assert_eq!(exex_manager.buffer.front().unwrap().1, notification1);
905 assert_eq!(exex_manager.next_id, 1);
906
907 let mut block2: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
909 block2.set_hash(B256::repeat_byte(0x02));
910 block2.set_block_number(20);
911
912 let notification2 = ExExNotification::ChainCommitted {
913 new: Arc::new(Chain::new(vec![block2.clone()], Default::default(), Default::default())),
914 };
915
916 exex_manager.push_notification(notification2.clone());
917
918 assert_eq!(exex_manager.buffer.len(), 2);
920 assert_eq!(exex_manager.buffer.front().unwrap().0, 0);
921 assert_eq!(exex_manager.buffer.front().unwrap().1, notification1);
922 assert_eq!(exex_manager.buffer.get(1).unwrap().0, 1);
923 assert_eq!(exex_manager.buffer.get(1).unwrap().1, notification2);
924 assert_eq!(exex_manager.next_id, 2);
925 }
926
927 #[test]
928 fn test_update_capacity() {
929 let temp_dir = tempfile::tempdir().unwrap();
930 let wal = Wal::new(temp_dir.path()).unwrap();
931
932 let (exex_handle, _, _) = ExExHandle::new(
933 "test_exex".to_string(),
934 Default::default(),
935 (),
936 EthEvmConfig::mainnet(),
937 wal.handle(),
938 );
939
940 let max_capacity = 5;
942 let mut exex_manager = ExExManager::new(
943 (),
944 vec![exex_handle],
945 max_capacity,
946 wal,
947 empty_finalized_header_stream(),
948 );
949
950 let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
952 block1.set_hash(B256::repeat_byte(0x01));
953 block1.set_block_number(10);
954
955 let notification1 = ExExNotification::ChainCommitted {
956 new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
957 };
958
959 exex_manager.push_notification(notification1.clone());
960 exex_manager.push_notification(notification1);
961
962 exex_manager.update_capacity();
964
965 assert_eq!(exex_manager.current_capacity.load(Ordering::Relaxed), max_capacity - 2);
967
968 exex_manager.buffer.clear();
970 exex_manager.update_capacity();
971
972 assert_eq!(exex_manager.current_capacity.load(Ordering::Relaxed), max_capacity);
974 }
975
976 #[tokio::test]
977 async fn test_updates_block_height() {
978 let temp_dir = tempfile::tempdir().unwrap();
979 let wal = Wal::new(temp_dir.path()).unwrap();
980
981 let provider_factory = create_test_provider_factory();
982
983 let (exex_handle, event_tx, mut _notification_rx) = ExExHandle::new(
984 "test_exex".to_string(),
985 Default::default(),
986 (),
987 EthEvmConfig::mainnet(),
988 wal.handle(),
989 );
990
991 assert!(exex_handle.finished_height.is_none());
993
994 let block = BlockNumHash::new(42, B256::random());
996 event_tx.send(ExExEvent::FinishedHeight(block)).unwrap();
997
998 let exex_manager = ExExManager::new(
1000 provider_factory,
1001 vec![exex_handle],
1002 10,
1003 Wal::new(temp_dir.path()).unwrap(),
1004 empty_finalized_header_stream(),
1005 );
1006
1007 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1008
1009 let mut pinned_manager = std::pin::pin!(exex_manager);
1011 let _ = pinned_manager.as_mut().poll(&mut cx);
1012
1013 let updated_exex_handle = &pinned_manager.exex_handles[0];
1015 assert_eq!(updated_exex_handle.finished_height, Some(block));
1016
1017 let mut receiver = pinned_manager.handle.finished_height();
1019
1020 receiver.changed().await.unwrap();
1022
1023 let finished_height = *receiver.borrow();
1025
1026 assert_eq!(finished_height, FinishedExExHeight::Height(42));
1028 }
1029
1030 #[tokio::test]
1031 async fn test_updates_block_height_lower() {
1032 let temp_dir = tempfile::tempdir().unwrap();
1033 let wal = Wal::new(temp_dir.path()).unwrap();
1034
1035 let provider_factory = create_test_provider_factory();
1036
1037 let (exex_handle1, event_tx1, _) = ExExHandle::new(
1039 "test_exex1".to_string(),
1040 Default::default(),
1041 (),
1042 EthEvmConfig::mainnet(),
1043 wal.handle(),
1044 );
1045 let (exex_handle2, event_tx2, _) = ExExHandle::new(
1046 "test_exex2".to_string(),
1047 Default::default(),
1048 (),
1049 EthEvmConfig::mainnet(),
1050 wal.handle(),
1051 );
1052
1053 let block1 = BlockNumHash::new(42, B256::random());
1054 let block2 = BlockNumHash::new(10, B256::random());
1055
1056 event_tx1.send(ExExEvent::FinishedHeight(block1)).unwrap();
1058 event_tx2.send(ExExEvent::FinishedHeight(block2)).unwrap();
1059
1060 let exex_manager = ExExManager::new(
1061 provider_factory,
1062 vec![exex_handle1, exex_handle2],
1063 10,
1064 Wal::new(temp_dir.path()).unwrap(),
1065 empty_finalized_header_stream(),
1066 );
1067
1068 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1069
1070 let mut pinned_manager = std::pin::pin!(exex_manager);
1071
1072 let _ = pinned_manager.as_mut().poll(&mut cx);
1073
1074 let mut receiver = pinned_manager.handle.finished_height();
1076
1077 receiver.changed().await.unwrap();
1079
1080 let finished_height = *receiver.borrow();
1082
1083 assert_eq!(finished_height, FinishedExExHeight::Height(10));
1085 }
1086
1087 #[tokio::test]
1088 async fn test_updates_block_height_greater() {
1089 let temp_dir = tempfile::tempdir().unwrap();
1090 let wal = Wal::new(temp_dir.path()).unwrap();
1091
1092 let provider_factory = create_test_provider_factory();
1093
1094 let (exex_handle1, event_tx1, _) = ExExHandle::new(
1096 "test_exex1".to_string(),
1097 Default::default(),
1098 (),
1099 EthEvmConfig::mainnet(),
1100 wal.handle(),
1101 );
1102 let (exex_handle2, event_tx2, _) = ExExHandle::new(
1103 "test_exex2".to_string(),
1104 Default::default(),
1105 (),
1106 EthEvmConfig::mainnet(),
1107 wal.handle(),
1108 );
1109
1110 assert!(exex_handle1.finished_height.is_none());
1112
1113 let block1 = BlockNumHash::new(42, B256::random());
1114 let block2 = BlockNumHash::new(100, B256::random());
1115
1116 event_tx1.send(ExExEvent::FinishedHeight(block1)).unwrap();
1118 event_tx2.send(ExExEvent::FinishedHeight(block2)).unwrap();
1119
1120 let exex_manager = ExExManager::new(
1121 provider_factory,
1122 vec![exex_handle1, exex_handle2],
1123 10,
1124 Wal::new(temp_dir.path()).unwrap(),
1125 empty_finalized_header_stream(),
1126 );
1127
1128 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1129
1130 let mut pinned_manager = std::pin::pin!(exex_manager);
1131
1132 let _ = pinned_manager.as_mut().poll(&mut cx);
1133
1134 let mut receiver = pinned_manager.handle.finished_height();
1136
1137 receiver.changed().await.unwrap();
1139
1140 let finished_height = *receiver.borrow();
1142
1143 assert_eq!(finished_height, FinishedExExHeight::Height(42));
1145
1146 }
1150
1151 #[tokio::test]
1152 async fn test_exex_manager_capacity() {
1153 let temp_dir = tempfile::tempdir().unwrap();
1154 let wal = Wal::new(temp_dir.path()).unwrap();
1155
1156 let provider_factory = create_test_provider_factory();
1157
1158 let (exex_handle_1, _, _) = ExExHandle::new(
1159 "test_exex_1".to_string(),
1160 Default::default(),
1161 (),
1162 EthEvmConfig::mainnet(),
1163 wal.handle(),
1164 );
1165
1166 let max_capacity = 2;
1168 let exex_manager = ExExManager::new(
1169 provider_factory,
1170 vec![exex_handle_1],
1171 max_capacity,
1172 Wal::new(temp_dir.path()).unwrap(),
1173 empty_finalized_header_stream(),
1174 );
1175
1176 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1177
1178 let notification = ExExNotification::ChainCommitted {
1180 new: Arc::new(Chain::new(
1181 vec![RecoveredBlock::default()],
1182 Default::default(),
1183 Default::default(),
1184 )),
1185 };
1186
1187 exex_manager
1189 .handle
1190 .exex_tx
1191 .send((ExExNotificationSource::BlockchainTree, notification.clone()))
1192 .unwrap();
1193 exex_manager
1194 .handle
1195 .exex_tx
1196 .send((ExExNotificationSource::BlockchainTree, notification.clone()))
1197 .unwrap();
1198 exex_manager
1199 .handle
1200 .exex_tx
1201 .send((ExExNotificationSource::BlockchainTree, notification))
1202 .unwrap();
1203
1204 let mut pinned_manager = std::pin::pin!(exex_manager);
1206
1207 assert_eq!(pinned_manager.next_id, 0);
1209 assert_eq!(pinned_manager.buffer.len(), 0);
1210
1211 let _ = pinned_manager.as_mut().poll(&mut cx);
1212
1213 assert_eq!(pinned_manager.next_id, 2);
1215 assert_eq!(pinned_manager.buffer.len(), 2);
1216 }
1217
1218 #[tokio::test]
1219 async fn exex_handle_new() {
1220 let provider_factory = create_test_provider_factory();
1221 init_genesis(&provider_factory).unwrap();
1222 let provider = BlockchainProvider::new(provider_factory).unwrap();
1223
1224 let temp_dir = tempfile::tempdir().unwrap();
1225 let wal = Wal::new(temp_dir.path()).unwrap();
1226
1227 let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1228 "test_exex".to_string(),
1229 Default::default(),
1230 provider,
1231 EthEvmConfig::mainnet(),
1232 wal.handle(),
1233 );
1234
1235 assert_eq!(exex_handle.id, "test_exex");
1237 assert_eq!(exex_handle.next_notification_id, 0);
1238
1239 let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1241 block1.set_hash(B256::repeat_byte(0x01));
1242 block1.set_block_number(10);
1243
1244 let mut block2: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1245 block2.set_hash(B256::repeat_byte(0x02));
1246 block2.set_block_number(11);
1247
1248 let notification = ExExNotification::ChainCommitted {
1250 new: Arc::new(Chain::new(
1251 vec![RecoveredBlock::default()],
1252 Default::default(),
1253 Default::default(),
1254 )),
1255 };
1256
1257 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1258
1259 match exex_handle.send(&mut cx, &(22, notification.clone())) {
1261 Poll::Ready(Ok(())) => {
1262 let received_notification = notifications.next().await.unwrap().unwrap();
1263 assert_eq!(received_notification, notification);
1264 }
1265 Poll::Pending => panic!("Notification send is pending"),
1266 Poll::Ready(Err(e)) => panic!("Failed to send notification: {e:?}"),
1267 }
1268
1269 assert_eq!(exex_handle.next_notification_id, 23);
1271 }
1272
1273 #[tokio::test]
1274 async fn test_notification_if_finished_height_gt_chain_tip() {
1275 let provider_factory = create_test_provider_factory();
1276 init_genesis(&provider_factory).unwrap();
1277 let provider = BlockchainProvider::new(provider_factory).unwrap();
1278
1279 let temp_dir = tempfile::tempdir().unwrap();
1280 let wal = Wal::new(temp_dir.path()).unwrap();
1281
1282 let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1283 "test_exex".to_string(),
1284 Default::default(),
1285 provider,
1286 EthEvmConfig::mainnet(),
1287 wal.handle(),
1288 );
1289
1290 exex_handle.finished_height = Some(BlockNumHash::new(15, B256::random()));
1292
1293 let mut block1: RecoveredBlock<reth_ethereum_primitives::Block> = Default::default();
1294 block1.set_hash(B256::repeat_byte(0x01));
1295 block1.set_block_number(10);
1296
1297 let notification = ExExNotification::ChainCommitted {
1298 new: Arc::new(Chain::new(vec![block1.clone()], Default::default(), Default::default())),
1299 };
1300
1301 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1302
1303 match exex_handle.send(&mut cx, &(22, notification)) {
1305 Poll::Ready(Ok(())) => {
1306 poll_fn(|cx| {
1307 assert!(notifications.poll_next_unpin(cx).is_pending());
1310 Poll::Ready(())
1311 })
1312 .await;
1313 }
1314 Poll::Pending | Poll::Ready(Err(_)) => {
1315 panic!("Notification should not be pending or fail");
1316 }
1317 }
1318
1319 assert_eq!(exex_handle.next_notification_id, 23);
1321 }
1322
1323 #[tokio::test]
1324 async fn test_sends_commit_on_other_branch_below_finished_height() {
1325 let provider_factory = create_test_provider_factory();
1326 init_genesis(&provider_factory).unwrap();
1327 let provider = BlockchainProvider::new(provider_factory).unwrap();
1328
1329 let temp_dir = tempfile::tempdir().unwrap();
1330 let wal = Wal::new(temp_dir.path()).unwrap();
1331
1332 let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1333 "test_exex".to_string(),
1334 Default::default(),
1335 provider,
1336 EthEvmConfig::mainnet(),
1337 wal.handle(),
1338 );
1339
1340 let block = |number, hash, parent_hash| {
1341 let mut block = RecoveredBlock::<reth_ethereum_primitives::Block>::default();
1342 block.set_block_number(number);
1343 block.set_hash(hash);
1344 block.set_parent_hash(parent_hash);
1345 block
1346 };
1347 let a2 = BlockNumHash::new(2, B256::repeat_byte(0xa2));
1348 let a5 = BlockNumHash::new(5, B256::repeat_byte(0xa5));
1349 let a3_to_a5 = vec![
1350 block(3, B256::repeat_byte(0xa3), a2.hash),
1351 block(4, B256::repeat_byte(0xa4), B256::repeat_byte(0xa3)),
1352 block(5, a5.hash, B256::repeat_byte(0xa4)),
1353 ];
1354 let b3 = block(3, B256::repeat_byte(0xb3), a2.hash);
1355 let b4 = block(4, B256::repeat_byte(0xb4), b3.hash());
1356
1357 exex_handle.finished_height = Some(a5);
1359 let reorg = ExExNotification::ChainReorged {
1360 old: Arc::new(Chain::new(a3_to_a5, Default::default(), Default::default())),
1361 new: Arc::new(Chain::new(vec![b3], Default::default(), Default::default())),
1362 };
1363 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1364 assert!(exex_handle.send(&mut cx, &(0, reorg.clone())).is_ready());
1365 assert_eq!(notifications.next().await.unwrap().unwrap(), reorg);
1366 assert_eq!(exex_handle.finished_height, Some(a2));
1367
1368 let commit = ExExNotification::ChainCommitted {
1370 new: Arc::new(Chain::new(vec![b4], Default::default(), Default::default())),
1371 };
1372 assert!(exex_handle.send(&mut cx, &(1, commit.clone())).is_ready());
1373 let received = notifications.next().now_or_never().expect("B4 must be delivered");
1374 assert_eq!(received.unwrap().unwrap(), commit);
1375 }
1376
1377 #[tokio::test]
1380 async fn test_ignores_finished_height_sent_before_revert_received() -> eyre::Result<()> {
1381 for report_while_reorg_waits in [true, false] {
1383 let provider_factory = create_test_provider_factory();
1384 init_genesis(&provider_factory)?;
1385 let provider = BlockchainProvider::new(provider_factory)?;
1386
1387 let temp_dir = tempfile::tempdir()?;
1388 let wal = Wal::new(temp_dir.path())?;
1389
1390 let (exex_handle, events_tx, mut notifications) = ExExHandle::new(
1391 "test_exex".to_string(),
1392 Default::default(),
1393 provider.clone(),
1394 EthEvmConfig::mainnet(),
1395 wal.handle(),
1396 );
1397 let mut exex_manager = std::pin::pin!(ExExManager::new(
1398 provider,
1399 vec![exex_handle],
1400 10,
1401 wal,
1402 empty_finalized_header_stream()
1403 ));
1404 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1405
1406 let block = |number, hash, parent_hash| {
1407 let mut block = RecoveredBlock::<reth_ethereum_primitives::Block>::default();
1408 block.set_block_number(number);
1409 block.set_hash(hash);
1410 block.set_parent_hash(parent_hash);
1411 block
1412 };
1413 let chain =
1414 |blocks| Arc::new(Chain::new(blocks, Default::default(), Default::default()));
1415 let a2 = B256::repeat_byte(0xa2);
1416 let a3 = block(3, B256::repeat_byte(0xa3), a2);
1417 let a4 = block(4, B256::repeat_byte(0xa4), a3.hash());
1418 let b3 = block(3, B256::repeat_byte(0xb3), a2);
1419 let b4 = block(4, B256::repeat_byte(0xb4), b3.hash());
1420 let b3_num_hash = b3.num_hash();
1421 let fork_block = BlockNumHash::new(2, a2);
1422
1423 let commit_a3 = ExExNotification::ChainCommitted { new: chain(vec![a3.clone()]) };
1425 exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_a3.clone())?;
1426 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1427 assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_a3)));
1428 events_tx.send(ExExEvent::FinishedHeight(a3.num_hash()))?;
1429
1430 let commit_a4 = ExExNotification::ChainCommitted { new: chain(vec![a4.clone()]) };
1433 let reorg = ExExNotification::ChainReorged {
1434 old: chain(vec![a3, a4.clone()]),
1435 new: chain(vec![b3]),
1436 };
1437 exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_a4.clone())?;
1438 exex_manager.handle().send(ExExNotificationSource::Pipeline, reorg.clone())?;
1439 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1440 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1441 assert_eq!(exex_manager.exex_handles[0].finished_height, Some(fork_block));
1442
1443 assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_a4)));
1446 if report_while_reorg_waits {
1447 events_tx.send(ExExEvent::FinishedHeight(a4.num_hash()))?;
1448 }
1449 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1450 if !report_while_reorg_waits {
1451 events_tx.send(ExExEvent::FinishedHeight(a4.num_hash()))?;
1452 }
1453 let commit_b4 = ExExNotification::ChainCommitted { new: chain(vec![b4]) };
1454 exex_manager.handle().send(ExExNotificationSource::Pipeline, commit_b4.clone())?;
1455 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1456 assert_eq!(exex_manager.exex_handles[0].finished_height, Some(fork_block));
1457
1458 assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(reorg)));
1460 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1461 assert_eq!(notifications.try_poll_next_unpin(&mut cx)?, Poll::Ready(Some(commit_b4)));
1462
1463 events_tx.send(ExExEvent::FinishedHeight(b3_num_hash))?;
1465 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1466 assert_eq!(exex_manager.exex_handles[0].finished_height, Some(b3_num_hash));
1467 }
1468
1469 Ok(())
1470 }
1471
1472 #[tokio::test]
1473 async fn test_sends_chain_reorged_notification() {
1474 let provider_factory = create_test_provider_factory();
1475 init_genesis(&provider_factory).unwrap();
1476 let provider = BlockchainProvider::new(provider_factory).unwrap();
1477
1478 let temp_dir = tempfile::tempdir().unwrap();
1479 let wal = Wal::new(temp_dir.path()).unwrap();
1480
1481 let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1482 "test_exex".to_string(),
1483 Default::default(),
1484 provider,
1485 EthEvmConfig::mainnet(),
1486 wal.handle(),
1487 );
1488
1489 let notification = ExExNotification::ChainReorged {
1490 old: Arc::new(Chain::default()),
1491 new: Arc::new(Chain::default()),
1492 };
1493
1494 exex_handle.finished_height = Some(BlockNumHash::new(u64::MAX, B256::random()));
1497
1498 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1499
1500 match exex_handle.send(&mut cx, &(22, notification.clone())) {
1502 Poll::Ready(Ok(())) => {
1503 let received_notification = notifications.next().await.unwrap().unwrap();
1504 assert_eq!(received_notification, notification);
1505 }
1506 Poll::Pending | Poll::Ready(Err(_)) => {
1507 panic!("Notification should not be pending or fail")
1508 }
1509 }
1510
1511 assert_eq!(exex_handle.next_notification_id, 23);
1513 }
1514
1515 #[tokio::test]
1516 async fn test_sends_chain_reverted_notification() {
1517 let provider_factory = create_test_provider_factory();
1518 init_genesis(&provider_factory).unwrap();
1519 let provider = BlockchainProvider::new(provider_factory).unwrap();
1520
1521 let temp_dir = tempfile::tempdir().unwrap();
1522 let wal = Wal::new(temp_dir.path()).unwrap();
1523
1524 let (mut exex_handle, _, mut notifications) = ExExHandle::new(
1525 "test_exex".to_string(),
1526 Default::default(),
1527 provider,
1528 EthEvmConfig::mainnet(),
1529 wal.handle(),
1530 );
1531
1532 let notification = ExExNotification::ChainReverted { old: Arc::new(Chain::default()) };
1533
1534 exex_handle.finished_height = Some(BlockNumHash::new(u64::MAX, B256::random()));
1537
1538 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1539
1540 match exex_handle.send(&mut cx, &(22, notification.clone())) {
1542 Poll::Ready(Ok(())) => {
1543 let received_notification = notifications.next().await.unwrap().unwrap();
1544 assert_eq!(received_notification, notification);
1545 }
1546 Poll::Pending | Poll::Ready(Err(_)) => {
1547 panic!("Notification should not be pending or fail")
1548 }
1549 }
1550
1551 assert_eq!(exex_handle.next_notification_id, 23);
1553 }
1554
1555 #[tokio::test]
1556 async fn test_exex_wal() -> eyre::Result<()> {
1557 reth_tracing::init_test_tracing();
1558
1559 let mut rng = generators::rng();
1560
1561 let provider_factory = create_test_provider_factory();
1562 let genesis_hash = init_genesis(&provider_factory).unwrap();
1563 let genesis_block = provider_factory
1564 .sealed_block_with_senders(genesis_hash.into(), TransactionVariant::NoHash)
1565 .unwrap()
1566 .ok_or_else(|| eyre::eyre!("genesis block not found"))?;
1567
1568 let block = random_block(
1569 &mut rng,
1570 genesis_block.number + 1,
1571 BlockParams { parent: Some(genesis_hash), ..Default::default() },
1572 )
1573 .try_recover()
1574 .unwrap();
1575 let provider_rw = provider_factory.database_provider_rw().unwrap();
1576 provider_rw.insert_block(&block).unwrap();
1577 provider_rw.commit().unwrap();
1578
1579 let provider = BlockchainProvider::new(provider_factory).unwrap();
1580
1581 let temp_dir = tempfile::tempdir().unwrap();
1582 let wal = Wal::new(temp_dir.path()).unwrap();
1583
1584 let (exex_handle, events_tx, mut notifications) = ExExHandle::new(
1585 "test_exex".to_string(),
1586 Default::default(),
1587 provider.clone(),
1588 EthEvmConfig::mainnet(),
1589 wal.handle(),
1590 );
1591
1592 let genesis_notification = ExExNotification::ChainCommitted {
1593 new: Arc::new(Chain::new(
1594 vec![genesis_block.clone()],
1595 Default::default(),
1596 Default::default(),
1597 )),
1598 };
1599 let notification = ExExNotification::ChainCommitted {
1600 new: Arc::new(Chain::new(vec![block.clone()], Default::default(), Default::default())),
1601 };
1602
1603 let (finalized_headers_tx, rx) = watch::channel(None);
1604 finalized_headers_tx.send(Some(genesis_block.clone_sealed_header()))?;
1605 let finalized_header_stream = ForkChoiceStream::new(rx);
1606
1607 let mut exex_manager = std::pin::pin!(ExExManager::new(
1608 provider,
1609 vec![exex_handle],
1610 2,
1611 wal,
1612 finalized_header_stream
1613 ));
1614
1615 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1616
1617 exex_manager
1618 .handle()
1619 .send(ExExNotificationSource::Pipeline, genesis_notification.clone())?;
1620 exex_manager.handle().send(ExExNotificationSource::BlockchainTree, notification.clone())?;
1621
1622 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1623 assert_eq!(
1624 notifications.try_poll_next_unpin(&mut cx)?,
1625 Poll::Ready(Some(genesis_notification))
1626 );
1627 assert!(exex_manager.as_mut().poll(&mut cx)?.is_pending());
1628 assert_eq!(
1629 notifications.try_poll_next_unpin(&mut cx)?,
1630 Poll::Ready(Some(notification.clone()))
1631 );
1632 assert_eq!(
1634 exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1635 std::slice::from_ref(¬ification)
1636 );
1637
1638 finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1639 assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1640 assert_eq!(
1642 exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1643 std::slice::from_ref(¬ification)
1644 );
1645
1646 events_tx
1648 .send(ExExEvent::FinishedHeight((rng.random::<u64>(), rng.random::<B256>()).into()))
1649 .unwrap();
1650
1651 finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1652 assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1653 assert_eq!(
1656 exex_manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1657 std::slice::from_ref(¬ification)
1658 );
1659
1660 events_tx.send(ExExEvent::FinishedHeight(block.num_hash())).unwrap();
1662
1663 finalized_headers_tx.send(Some(block.clone_sealed_header()))?;
1664 assert!(exex_manager.as_mut().poll(&mut cx).is_pending());
1665 assert_eq!(exex_manager.wal.iter_notifications()?.next().transpose()?, None);
1667
1668 Ok(())
1669 }
1670
1671 #[tokio::test]
1672 async fn test_deadlock_manager_wakes_after_buffer_clears() {
1673 let temp_dir = tempfile::tempdir().unwrap();
1677 let wal = Wal::new(temp_dir.path()).unwrap();
1678 let provider_factory = create_test_provider_factory();
1679 init_genesis(&provider_factory).unwrap();
1680 let provider = BlockchainProvider::new(provider_factory.clone()).unwrap();
1681
1682 let (exex_handle, _, mut notifications) = ExExHandle::new(
1684 "test_exex".to_string(),
1685 Default::default(),
1686 provider,
1687 EthEvmConfig::mainnet(),
1688 wal.handle(),
1689 );
1690
1691 let max_capacity = 2;
1692 let exex_manager = ExExManager::new(
1693 provider_factory,
1694 vec![exex_handle],
1695 max_capacity,
1696 wal,
1697 empty_finalized_header_stream(),
1698 );
1699
1700 let manager_handle = exex_manager.handle();
1701
1702 tokio::spawn(async move {
1704 exex_manager.await.ok();
1705 });
1706
1707 let mut rng = generators::rng();
1709 let mut make_notif = |id: u64| {
1710 let block = random_block(&mut rng, id, BlockParams::default()).try_recover().unwrap();
1711 ExExNotification::ChainCommitted {
1712 new: Arc::new(Chain::new(vec![block], Default::default(), Default::default())),
1713 }
1714 };
1715
1716 manager_handle.send(ExExNotificationSource::Pipeline, make_notif(1)).unwrap();
1717
1718 manager_handle.send(ExExNotificationSource::Pipeline, make_notif(100)).unwrap();
1722
1723 let _ = notifications.next().await.unwrap();
1731
1732 let result =
1737 tokio::time::timeout(std::time::Duration::from_secs(1), notifications.next()).await;
1738
1739 assert!(
1740 result.is_ok(),
1741 "Deadlock detected! Manager failed to wake up and process Pending Item #100."
1742 );
1743 }
1744
1745 fn canonical_notifications(count: u64) -> Vec<CanonStateNotification> {
1746 random_block_range(
1747 &mut generators::rng(),
1748 1..=count,
1749 BlockRangeParams { tx_count: 0..1, ..Default::default() },
1750 )
1751 .into_iter()
1752 .map(|block| CanonStateNotification::Commit {
1753 new: Arc::new(Chain::new(
1754 vec![block.try_recover().unwrap()],
1755 Default::default(),
1756 Default::default(),
1757 )),
1758 })
1759 .collect()
1760 }
1761
1762 fn canonical_manager(wal: Wal) -> ExExManager<MockEthProvider, EthPrimitives> {
1763 ExExManager::new(
1764 MockEthProvider::default(),
1765 vec![],
1766 1,
1767 wal,
1768 empty_finalized_header_stream(),
1769 )
1770 }
1771
1772 #[tokio::test]
1773 async fn test_canonical_notifications_survive_backpressure() -> eyre::Result<()> {
1774 let temp_dir = tempfile::tempdir()?;
1775 let wal = Wal::new(temp_dir.path())?;
1776 let provider = MockEthProvider::<EthPrimitives>::default();
1777 let (first, first_events, mut first_notifications) = ExExHandle::new(
1778 "first".to_string(),
1779 Default::default(),
1780 provider.clone(),
1781 EthEvmConfig::mainnet(),
1782 wal.handle(),
1783 );
1784 let (second, second_events, mut second_notifications) = ExExHandle::new(
1785 "second".to_string(),
1786 Default::default(),
1787 provider.clone(),
1788 EthEvmConfig::mainnet(),
1789 wal.handle(),
1790 );
1791 let mut manager = ExExManager::new(
1792 provider,
1793 vec![first, second],
1794 2,
1795 wal,
1796 empty_finalized_header_stream(),
1797 );
1798 let canonical = manager.handle();
1799 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1800 let mut updates = canonical_notifications(16);
1801
1802 let old = updates.last().unwrap().committed();
1803 let mut rng = generators::rng();
1804 let replacement = random_block(
1805 &mut rng,
1806 old.first().number(),
1807 BlockParams { parent: Some(old.first().parent_hash()), ..Default::default() },
1808 )
1809 .try_recover()?;
1810 let new = Arc::new(Chain::new(vec![replacement], Default::default(), Default::default()));
1811 updates.push(CanonStateNotification::Reorg { old: old.clone(), new: new.clone() });
1812 updates.push(CanonStateNotification::Reorg { old: new, new: old });
1813 let live_parent = updates.last().unwrap().tip().num_hash();
1814
1815 for chunk in updates.chunks(4) {
1818 for update in chunk {
1819 canonical.send(ExExNotificationSource::BlockchainTree, update.clone().into())?;
1820 }
1821 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1822 assert!(manager.buffer.len() <= manager.max_capacity);
1823 tokio::task::yield_now().await;
1824 }
1825 assert!(!manager.queued_notifications.is_empty());
1826 let expected = updates.into_iter().map(ExExNotification::from).collect::<Vec<_>>();
1827 assert_eq!(manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?, expected);
1828
1829 assert_eq!(
1831 first_notifications.try_poll_next_unpin(&mut cx)?,
1832 Poll::Ready(Some(expected[0].clone()))
1833 );
1834 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1835 assert!(!manager.queued_notifications.is_empty());
1836
1837 let mut finished_height = manager.handle().finished_height();
1839 tokio::spawn(manager);
1840 tokio::time::timeout(Duration::from_secs(10), async {
1841 for (index, notification) in expected.iter().enumerate() {
1842 if index > 0 {
1843 assert_eq!(first_notifications.try_next().await?, Some(notification.clone()));
1844 }
1845 assert_eq!(second_notifications.try_next().await?, Some(notification.clone()));
1846 }
1847 eyre::Ok(())
1848 })
1849 .await??;
1850
1851 let block = random_block(
1852 &mut rng,
1853 live_parent.number + 1,
1854 BlockParams { parent: Some(live_parent.hash), ..Default::default() },
1855 )
1856 .try_recover()?;
1857 let live = CanonStateNotification::<EthPrimitives>::Commit {
1858 new: Arc::new(Chain::new(vec![block], Default::default(), Default::default())),
1859 };
1860 let live_head = live.tip().num_hash();
1861 canonical.send(ExExNotificationSource::BlockchainTree, live.clone().into())?;
1862 let live = ExExNotification::from(live);
1863 tokio::time::timeout(Duration::from_secs(10), async {
1864 assert_eq!(first_notifications.try_next().await?, Some(live.clone()));
1865 assert_eq!(second_notifications.try_next().await?, Some(live));
1866 eyre::Ok(())
1867 })
1868 .await??;
1869 assert_eq!(first_notifications.try_poll_next_unpin(&mut cx)?, Poll::Pending);
1870 assert_eq!(second_notifications.try_poll_next_unpin(&mut cx)?, Poll::Pending);
1871
1872 assert_eq!(*finished_height.borrow(), FinishedExExHeight::NotReady);
1874 first_events.send(ExExEvent::FinishedHeight(live_head))?;
1875 second_events.send(ExExEvent::FinishedHeight(live_head))?;
1876 tokio::time::timeout(
1877 Duration::from_secs(10),
1878 finished_height
1879 .wait_for(|height| *height == FinishedExExHeight::Height(live_head.number)),
1880 )
1881 .await??;
1882 Ok(())
1883 }
1884
1885 #[tokio::test]
1886 async fn test_canonical_notifications_follow_queued_handle_notifications() -> eyre::Result<()> {
1887 let temp_dir = tempfile::tempdir()?;
1888 let wal = Wal::new(temp_dir.path())?;
1889 let provider = MockEthProvider::<EthPrimitives>::default();
1890 let (exex, _, mut notifications) = ExExHandle::new(
1891 "exex".to_string(),
1892 Default::default(),
1893 provider.clone(),
1894 EthEvmConfig::mainnet(),
1895 wal.handle(),
1896 );
1897 let mut manager =
1898 ExExManager::new(provider, vec![exex], 1, wal, empty_finalized_header_stream());
1899 let canonical = manager.handle();
1900 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1901 let updates = canonical_notifications(3);
1902 let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
1903
1904 for notification in &expected[..2] {
1907 manager.handle.send(ExExNotificationSource::Pipeline, notification.clone())?;
1908 }
1909 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1910 canonical.send(ExExNotificationSource::BlockchainTree, updates[2].clone().into())?;
1911 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1912
1913 tokio::spawn(manager);
1914 tokio::time::timeout(Duration::from_secs(10), async {
1915 for notification in expected {
1916 assert_eq!(notifications.try_next().await?, Some(notification));
1917 }
1918 eyre::Ok(())
1919 })
1920 .await??;
1921 Ok(())
1922 }
1923
1924 #[tokio::test]
1925 async fn test_canonical_wal_finalization_keeps_queued_notifications() -> eyre::Result<()> {
1926 let temp_dir = tempfile::tempdir()?;
1927 let wal = Wal::<EthPrimitives>::new(temp_dir.path())?;
1928 let (finalized, finalized_receiver) = watch::channel(None);
1929 let mut manager = ExExManager::new(
1930 MockEthProvider::<EthPrimitives>::default(),
1931 vec![],
1932 1,
1933 wal,
1934 ForkChoiceStream::new(finalized_receiver),
1935 );
1936 let canonical = manager.handle();
1937 let updates = canonical_notifications(3);
1938 let header = updates.last().unwrap().tip().clone_sealed_header();
1939 let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
1940 for update in updates {
1941 canonical.send(ExExNotificationSource::BlockchainTree, update.into())?;
1942 }
1943 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1944 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1945 assert!(matches!(
1946 manager.queued_notifications.make_contiguous(),
1947 [QueuedNotification::Wal(1), QueuedNotification::Wal(2)]
1948 ));
1949
1950 finalized.send(Some(header))?;
1952 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1953 assert_eq!(
1954 manager.wal.iter_notifications()?.collect::<WalResult<Vec<_>>>()?,
1955 expected[1..]
1956 );
1957 assert!(matches!(
1958 manager.queued_notifications.make_contiguous(),
1959 [QueuedNotification::Wal(2)]
1960 ));
1961 Ok(())
1962 }
1963
1964 #[tokio::test]
1965 async fn test_canonical_wal_commit_error() -> eyre::Result<()> {
1966 let temp_dir = tempfile::tempdir()?;
1967 let directory = temp_dir.path().join("wal");
1968 let mut manager = canonical_manager(Wal::new(&directory)?);
1969 let canonical = manager.handle();
1970 canonical.send(
1971 ExExNotificationSource::BlockchainTree,
1972 canonical_notifications(1).remove(0).into(),
1973 )?;
1974 reth_fs_util::remove_dir_all(&directory)?;
1975
1976 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1977 let Poll::Ready(Err(error)) = Pin::new(&mut manager).poll(&mut cx) else {
1978 panic!("expected WAL commit failure")
1979 };
1980 assert!(matches!(error.downcast_ref::<WalError>(), Some(WalError::FsPathError(_))));
1981 Ok(())
1982 }
1983
1984 #[tokio::test]
1985 async fn test_canonical_wal_missing_entry() -> eyre::Result<()> {
1986 let temp_dir = tempfile::tempdir()?;
1987 let mut manager = canonical_manager(Wal::new(temp_dir.path())?);
1988 let canonical = manager.handle();
1989 for update in canonical_notifications(2) {
1990 canonical.send(ExExNotificationSource::BlockchainTree, update.into())?;
1991 }
1992 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
1993 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
1994 reth_fs_util::remove_file(temp_dir.path().join("1.wal"))?;
1995
1996 let Poll::Ready(Err(error)) = Pin::new(&mut manager).poll(&mut cx) else {
1997 panic!("expected missing WAL entry")
1998 };
1999 assert!(matches!(error.downcast_ref::<WalError>(), Some(WalError::FileNotFound(1))));
2000 Ok(())
2001 }
2002
2003 #[tokio::test]
2004 async fn test_capacity_accounts_for_queued_notifications() -> eyre::Result<()> {
2005 let temp_dir = tempfile::tempdir()?;
2006 let wal = Wal::new(temp_dir.path())?;
2007 let provider = MockEthProvider::<EthPrimitives>::default();
2008 let (exex, _, mut notifications) = ExExHandle::new(
2009 "exex".to_string(),
2010 Default::default(),
2011 provider.clone(),
2012 EthEvmConfig::mainnet(),
2013 wal.handle(),
2014 );
2015 let mut manager =
2016 ExExManager::new(provider, vec![exex], 2, wal, empty_finalized_header_stream());
2017 let mut handle = manager.handle();
2018 let mut cx = Context::from_waker(futures::task::noop_waker_ref());
2019 let updates = canonical_notifications(4);
2020 let expected = updates.iter().cloned().map(ExExNotification::from).collect::<Vec<_>>();
2021
2022 for update in updates {
2023 handle.send(ExExNotificationSource::BlockchainTree, update.into())?;
2024 }
2025
2026 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2029 assert_eq!(manager.buffer.len(), 1);
2030 assert_eq!(manager.queued_notifications.len(), 2);
2031 assert_eq!(handle.capacity(), 0);
2032 assert!(!handle.has_capacity());
2033 assert!(handle.poll_ready(&mut cx).is_pending());
2034
2035 assert_eq!(
2038 notifications.try_poll_next_unpin(&mut cx)?,
2039 Poll::Ready(Some(expected[0].clone()))
2040 );
2041 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2042 assert_eq!(manager.buffer.len(), 1);
2043 assert_eq!(manager.queued_notifications.len(), 1);
2044 assert_eq!(handle.capacity(), 0);
2045 assert!(!handle.has_capacity());
2046 assert!(handle.poll_ready(&mut cx).is_pending());
2047
2048 assert_eq!(
2050 notifications.try_poll_next_unpin(&mut cx)?,
2051 Poll::Ready(Some(expected[1].clone()))
2052 );
2053 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2054 assert_eq!(manager.buffer.len(), 1);
2055 assert!(manager.queued_notifications.is_empty());
2056 assert_eq!(handle.capacity(), 1);
2057 assert!(handle.has_capacity());
2058 assert!(handle.poll_ready(&mut cx).is_ready());
2059
2060 assert_eq!(
2061 notifications.try_poll_next_unpin(&mut cx)?,
2062 Poll::Ready(Some(expected[2].clone()))
2063 );
2064 assert!(Pin::new(&mut manager).poll(&mut cx)?.is_pending());
2065 assert_eq!(handle.capacity(), 2);
2066 assert_eq!(
2067 notifications.try_poll_next_unpin(&mut cx)?,
2068 Poll::Ready(Some(expected[3].clone()))
2069 );
2070 Ok(())
2071 }
2072}