1#![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#[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#[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#[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#[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
160pub type TmpDB = Arc<TempDatabase<DatabaseEnv>>;
162pub type Adapter = NodeAdapter<RethFullAdapter<TmpDB, TestNode>>;
165pub type TestExExContext = ExExContext<Adapter>;
167
168#[derive(Debug)]
170pub struct TestExExHandle {
171 pub genesis: RecoveredBlock<reth_ethereum_primitives::Block>,
173 pub provider_factory: ProviderFactory<NodeTypesWithDBAdapter<TestNode, TmpDB>>,
175 pub events_rx: UnboundedReceiver<ExExEvent>,
177 pub notifications_tx: Sender<ExExNotification>,
179 pub runtime: Runtime,
181 _wal_directory: TempDir,
183}
184
185impl TestExExHandle {
186 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 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 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 #[track_caller]
216 pub fn assert_events_empty(&self) {
217 assert!(self.events_rx.is_empty());
218 }
219
220 #[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
230pub 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
332pub async fn test_exex_context() -> eyre::Result<(ExExContext<Adapter>, TestExExHandle)> {
336 test_exex_context_with_chain_spec(MAINNET.clone()).await
337}
338
339pub trait PollOnce {
341 fn poll_once(&mut self) -> impl Future<Output = Result<(), PollOnceError>> + Send;
351}
352
353#[derive(Error, Debug)]
355pub enum PollOnceError {
356 #[error("Execution Extension future returned Ready, but it should never resolve")]
358 FutureIsReady,
359 #[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}