Skip to main content

reth_exex_test_utils/
lib.rs

1//! Test helpers for `reth-exex`
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(docsrs, feature(doc_cfg))]
9#![cfg_attr(not(test), warn(unused_crate_dependencies))]
10
11use std::{
12    fmt::Debug,
13    future::{poll_fn, Future},
14    sync::Arc,
15    task::Poll,
16};
17
18use alloy_eips::BlockNumHash;
19use futures_util::FutureExt;
20use reth_chainspec::{ChainSpec, MAINNET};
21use reth_consensus::test_utils::TestConsensus;
22use reth_db::{
23    test_utils::{
24        create_test_rocksdb_dir, create_test_rw_db, create_test_static_files_dir, TempDatabase,
25    },
26    DatabaseEnv,
27};
28use reth_db_common::init::init_genesis;
29use reth_ethereum_primitives::{EthPrimitives, TransactionSigned};
30use reth_evm_ethereum::MockEvmConfig;
31use reth_execution_types::Chain;
32use reth_exex::{ExExContext, ExExEvent, ExExNotification, ExExNotifications, Wal};
33use reth_network::{config::rng_secret_key, NetworkConfigBuilder, NetworkManager};
34use reth_node_api::{
35    FullNodeTypes, FullNodeTypesAdapter, NodePrimitives, NodeTypes, NodeTypesWithDBAdapter,
36};
37use reth_node_builder::{
38    components::{
39        BasicPayloadServiceBuilder, Components, ComponentsBuilder, ConsensusBuilder,
40        ExecutorBuilder, PoolBuilder,
41    },
42    BuilderContext, Node, NodeAdapter, RethFullAdapter,
43};
44use reth_node_core::node_config::NodeConfig;
45use reth_node_ethereum::{
46    node::{
47        EthereumAddOns, EthereumEngineValidatorBuilder, EthereumEthApiBuilder,
48        EthereumNetworkBuilder, EthereumPayloadBuilder,
49    },
50    EthEngineTypes,
51};
52use reth_payload_builder::noop::NoopPayloadBuilderService;
53use reth_primitives_traits::{Block as _, RecoveredBlock};
54use reth_provider::{
55    providers::{BlockchainProvider, RocksDBProvider, StaticFileProvider},
56    BlockReader, EthStorage, ProviderFactory,
57};
58use reth_storage_overlay::OverlayManager;
59use reth_tasks::Runtime;
60use reth_transaction_pool::test_utils::{testing_pool, TestPool};
61use tempfile::TempDir;
62use thiserror::Error;
63use tokio::sync::mpsc::{Sender, UnboundedReceiver};
64
65/// A test [`PoolBuilder`] that builds a [`TestPool`].
66#[derive(Debug, Default, Clone, Copy)]
67#[non_exhaustive]
68pub struct TestPoolBuilder;
69
70impl<Node, Evm: Send> PoolBuilder<Node, Evm> for TestPoolBuilder
71where
72    Node: FullNodeTypes<Types: NodeTypes<Primitives: NodePrimitives<SignedTx = TransactionSigned>>>,
73{
74    type Pool = TestPool;
75
76    async fn build_pool(
77        self,
78        _ctx: &BuilderContext<Node>,
79        _evm_config: Evm,
80    ) -> eyre::Result<Self::Pool> {
81        Ok(testing_pool())
82    }
83}
84
85/// A test [`ExecutorBuilder`] that builds a [`MockEvmConfig`] for testing.
86#[derive(Debug, Default, Clone, Copy)]
87#[non_exhaustive]
88pub struct TestExecutorBuilder;
89
90impl<Node> ExecutorBuilder<Node> for TestExecutorBuilder
91where
92    Node: FullNodeTypes<Types: NodeTypes<ChainSpec = ChainSpec, Primitives = EthPrimitives>>,
93{
94    type EVM = MockEvmConfig;
95
96    async fn build_evm(self, _ctx: &BuilderContext<Node>) -> eyre::Result<Self::EVM> {
97        let evm_config = MockEvmConfig::default();
98        Ok(evm_config)
99    }
100}
101
102/// A test [`ConsensusBuilder`] that builds a [`TestConsensus`].
103#[derive(Debug, Default, Clone, Copy)]
104#[non_exhaustive]
105pub struct TestConsensusBuilder;
106
107impl<Node> ConsensusBuilder<Node> for TestConsensusBuilder
108where
109    Node: FullNodeTypes,
110{
111    type Consensus = Arc<TestConsensus>;
112
113    async fn build_consensus(self, _ctx: &BuilderContext<Node>) -> eyre::Result<Self::Consensus> {
114        Ok(Arc::new(TestConsensus::default()))
115    }
116}
117
118/// A test [`Node`].
119#[derive(Debug, Default, Clone, Copy)]
120#[non_exhaustive]
121pub struct TestNode;
122
123impl NodeTypes for TestNode {
124    type Primitives = EthPrimitives;
125    type ChainSpec = ChainSpec;
126    type Storage = EthStorage;
127    type Payload = EthEngineTypes;
128}
129
130impl<N> Node<N> for TestNode
131where
132    N: FullNodeTypes<Types = Self>,
133{
134    type ComponentsBuilder = ComponentsBuilder<
135        N,
136        TestPoolBuilder,
137        BasicPayloadServiceBuilder<EthereumPayloadBuilder>,
138        EthereumNetworkBuilder,
139        TestExecutorBuilder,
140        TestConsensusBuilder,
141    >;
142    type AddOns =
143        EthereumAddOns<NodeAdapter<N>, EthereumEthApiBuilder, EthereumEngineValidatorBuilder>;
144
145    fn components_builder(&self) -> Self::ComponentsBuilder {
146        ComponentsBuilder::default()
147            .node_types::<N>()
148            .pool(TestPoolBuilder::default())
149            .executor(TestExecutorBuilder::default())
150            .payload(BasicPayloadServiceBuilder::default())
151            .network(EthereumNetworkBuilder::default())
152            .consensus(TestConsensusBuilder::default())
153    }
154
155    fn add_ons(&self) -> Self::AddOns {
156        EthereumAddOns::default()
157    }
158}
159
160/// A shared [`TempDatabase`] used for testing
161pub type TmpDB = Arc<TempDatabase<DatabaseEnv>>;
162/// The [`NodeAdapter`] for the [`TestExExContext`]. Contains type necessary to
163/// boot the testing environment
164pub type Adapter = NodeAdapter<RethFullAdapter<TmpDB, TestNode>>;
165/// An [`ExExContext`] using the [`Adapter`] type.
166pub type TestExExContext = ExExContext<Adapter>;
167
168/// A helper type for testing Execution Extensions.
169#[derive(Debug)]
170pub struct TestExExHandle {
171    /// Genesis block that was inserted into the storage
172    pub genesis: RecoveredBlock<reth_ethereum_primitives::Block>,
173    /// Provider Factory for accessing the emphemeral storage of the host node
174    pub provider_factory: ProviderFactory<NodeTypesWithDBAdapter<TestNode, TmpDB>>,
175    /// Channel for receiving events from the Execution Extension
176    pub events_rx: UnboundedReceiver<ExExEvent>,
177    /// Channel for sending notifications to the Execution Extension
178    pub notifications_tx: Sender<ExExNotification>,
179    /// Node task runtime
180    pub runtime: Runtime,
181    /// WAL temp directory handle
182    _wal_directory: TempDir,
183}
184
185impl TestExExHandle {
186    /// Send a notification to the Execution Extension that the chain has been committed
187    pub async fn send_notification_chain_committed(&self, chain: Chain) -> eyre::Result<()> {
188        self.notifications_tx
189            .send(ExExNotification::ChainCommitted { new: Arc::new(chain) })
190            .await?;
191        Ok(())
192    }
193
194    /// Send a notification to the Execution Extension that the chain has been reorged
195    pub async fn send_notification_chain_reorged(
196        &self,
197        old: Chain,
198        new: Chain,
199    ) -> eyre::Result<()> {
200        self.notifications_tx
201            .send(ExExNotification::ChainReorged { old: Arc::new(old), new: Arc::new(new) })
202            .await?;
203        Ok(())
204    }
205
206    /// Send a notification to the Execution Extension that the chain has been reverted
207    pub async fn send_notification_chain_reverted(&self, chain: Chain) -> eyre::Result<()> {
208        self.notifications_tx
209            .send(ExExNotification::ChainReverted { old: Arc::new(chain) })
210            .await?;
211        Ok(())
212    }
213
214    /// Asserts that the Execution Extension did not emit any events.
215    #[track_caller]
216    pub fn assert_events_empty(&self) {
217        assert!(self.events_rx.is_empty());
218    }
219
220    /// Asserts that the Execution Extension emitted a `FinishedHeight` event with the correct
221    /// height.
222    #[track_caller]
223    pub fn assert_event_finished_height(&mut self, height: BlockNumHash) -> eyre::Result<()> {
224        let event = self.events_rx.try_recv()?;
225        assert_eq!(event, ExExEvent::FinishedHeight(height));
226        Ok(())
227    }
228}
229
230/// Creates a new [`ExExContext`].
231///
232/// This is a convenience function that does the following:
233/// 1. Sets up an [`ExExContext`] with all dependencies.
234/// 2. Inserts the genesis block of the provided (chain spec)[`ChainSpec`] into the storage.
235/// 3. Creates a channel for receiving events from the Execution Extension.
236/// 4. Creates a channel for sending notifications to the Execution Extension.
237///
238/// # Warning
239/// The genesis block is not sent to the notifications channel. The caller is responsible for
240/// doing this.
241pub async fn test_exex_context_with_chain_spec(
242    chain_spec: Arc<ChainSpec>,
243) -> eyre::Result<(ExExContext<Adapter>, TestExExHandle)> {
244    let transaction_pool = testing_pool();
245    let evm_config = MockEvmConfig::default();
246    let consensus = Arc::new(TestConsensus::default());
247
248    let (static_dir, _) = create_test_static_files_dir();
249    let (rocksdb_dir, _) = create_test_rocksdb_dir();
250    let db = create_test_rw_db();
251    let provider_factory = ProviderFactory::<NodeTypesWithDBAdapter<TestNode, _>>::new(
252        db,
253        chain_spec.clone(),
254        StaticFileProvider::read_write(static_dir.keep()).expect("static file provider"),
255        RocksDBProvider::builder(rocksdb_dir.keep()).with_default_tables().build().unwrap(),
256        OverlayManager::default(),
257        reth_tasks::Runtime::test(),
258    )?;
259
260    let genesis_hash = init_genesis(&provider_factory)?;
261    let provider = BlockchainProvider::new(provider_factory.clone())?;
262
263    let runtime = Runtime::test();
264    let network_manager = NetworkManager::new(
265        NetworkConfigBuilder::new(rng_secret_key(), runtime.clone())
266            .with_unused_discovery_port()
267            .with_unused_listener_port()
268            .build(provider_factory.clone()),
269    )
270    .await?;
271    let network = network_manager.handle().clone();
272    let task_executor = runtime.clone();
273    runtime.spawn_task(network_manager);
274
275    let (_, payload_builder_handle) = NoopPayloadBuilderService::<EthEngineTypes>::new();
276
277    let components = NodeAdapter::<FullNodeTypesAdapter<_, _, _>, _> {
278        components: Components {
279            transaction_pool,
280            evm_config,
281            consensus,
282            network,
283            payload_builder_handle,
284        },
285        task_executor,
286        provider,
287    };
288
289    let genesis = provider_factory
290        .block_by_hash(genesis_hash)?
291        .ok_or_else(|| eyre::eyre!("genesis block not found"))?
292        .seal_slow()
293        .try_recover()?;
294
295    let head = genesis.num_hash();
296
297    let wal_directory = tempfile::tempdir()?;
298    let wal = Wal::new(wal_directory.path())?;
299
300    let (events_tx, events_rx) = tokio::sync::mpsc::unbounded_channel();
301    let (notifications_tx, notifications_rx) = tokio::sync::mpsc::channel(1);
302    let notifications = ExExNotifications::new(
303        head,
304        components.provider.clone(),
305        components.components.evm_config.clone(),
306        notifications_rx,
307        wal.handle(),
308    );
309
310    let ctx = ExExContext {
311        head,
312        config: NodeConfig::test(),
313        reth_config: reth_config::Config::default(),
314        events: events_tx,
315        notifications,
316        components,
317    };
318
319    Ok((
320        ctx,
321        TestExExHandle {
322            genesis,
323            provider_factory,
324            events_rx,
325            notifications_tx,
326            runtime,
327            _wal_directory: wal_directory,
328        },
329    ))
330}
331
332/// Creates a new [`ExExContext`] with (mainnet)[`MAINNET`] chain spec.
333///
334/// For more information see [`test_exex_context_with_chain_spec`].
335pub async fn test_exex_context() -> eyre::Result<(ExExContext<Adapter>, TestExExHandle)> {
336    test_exex_context_with_chain_spec(MAINNET.clone()).await
337}
338
339/// An extension trait for polling an Execution Extension future.
340pub trait PollOnce {
341    /// Polls the given Execution Extension future __once__. The future should be
342    /// (pinned)[`std::pin::pin`].
343    ///
344    /// # Returns
345    /// - `Ok(())` if the future returned [`Poll::Pending`]. The future can be polled again.
346    /// - `Err(PollOnceError::FutureIsReady)` if the future returned [`Poll::Ready`] without an
347    ///   error. The future should never resolve.
348    /// - `Err(PollOnceError::FutureError(err))` if the future returned [`Poll::Ready`] with an
349    ///   error. Something went wrong.
350    fn poll_once(&mut self) -> impl Future<Output = Result<(), PollOnceError>> + Send;
351}
352
353/// An Execution Extension future polling error.
354#[derive(Error, Debug)]
355pub enum PollOnceError {
356    /// The future returned [`Poll::Ready`] without an error, but it should never resolve.
357    #[error("Execution Extension future returned Ready, but it should never resolve")]
358    FutureIsReady,
359    /// The future returned [`Poll::Ready`] with an error.
360    #[error(transparent)]
361    FutureError(#[from] eyre::Error),
362}
363
364impl<F: Future<Output = eyre::Result<()>> + Unpin + Send> PollOnce for F {
365    async fn poll_once(&mut self) -> Result<(), PollOnceError> {
366        poll_fn(|cx| match self.poll_unpin(cx) {
367            Poll::Ready(Ok(())) => Poll::Ready(Err(PollOnceError::FutureIsReady)),
368            Poll::Ready(Err(err)) => Poll::Ready(Err(PollOnceError::FutureError(err))),
369            Poll::Pending => Poll::Ready(Ok(())),
370        })
371        .await
372    }
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    #[tokio::test]
380    async fn check_test_context_creation() {
381        let _ = test_exex_context().await.unwrap();
382    }
383}