reth_e2e_test_utils/
node.rs

1use crate::{network::NetworkTestContext, payload::PayloadTestContext, rpc::RpcTestContext};
2use alloy_consensus::BlockHeader;
3use alloy_eips::BlockId;
4use alloy_primitives::{BlockHash, BlockNumber, Bytes, Sealable, B256};
5use alloy_rpc_types_engine::ForkchoiceState;
6use alloy_rpc_types_eth::BlockNumberOrTag;
7use eyre::Ok;
8use futures_util::Future;
9use jsonrpsee::http_client::{transport::HttpBackend, HttpClient};
10use reth_chainspec::EthereumHardforks;
11use reth_network_api::test_utils::PeersHandleProvider;
12use reth_node_api::{
13    Block, BlockBody, BlockTy, EngineApiMessageVersion, EngineTypes, FullNodeComponents,
14    PrimitivesTy,
15};
16use reth_node_builder::{rpc::RethRpcAddOns, FullNode, NodeTypesWithEngine};
17use reth_node_core::primitives::SignedTransaction;
18use reth_payload_primitives::{BuiltPayload, PayloadBuilderAttributes};
19use reth_provider::{
20    BlockReader, BlockReaderIdExt, CanonStateNotificationStream, CanonStateSubscriptions,
21    StageCheckpointReader,
22};
23use reth_rpc_eth_api::helpers::{EthApiSpec, EthTransactions, TraceExt};
24use reth_rpc_layer::AuthClientService;
25use reth_stages_types::StageId;
26use std::pin::Pin;
27use tokio_stream::StreamExt;
28use url::Url;
29
30/// An helper struct to handle node actions
31#[expect(missing_debug_implementations)]
32pub struct NodeTestContext<Node, AddOns>
33where
34    Node: FullNodeComponents,
35    AddOns: RethRpcAddOns<Node>,
36{
37    /// The core structure representing the full node.
38    pub inner: FullNode<Node, AddOns>,
39    /// Context for testing payload-related features.
40    pub payload: PayloadTestContext<<Node::Types as NodeTypesWithEngine>::Engine>,
41    /// Context for testing network functionalities.
42    pub network: NetworkTestContext<Node::Network>,
43    /// Context for testing RPC features.
44    pub rpc: RpcTestContext<Node, AddOns::EthApi>,
45    /// Canonical state events.
46    pub canonical_stream: CanonStateNotificationStream<PrimitivesTy<Node::Types>>,
47}
48
49impl<Node, Engine, AddOns> NodeTestContext<Node, AddOns>
50where
51    Engine: EngineTypes,
52    Node: FullNodeComponents,
53    Node::Types: NodeTypesWithEngine<ChainSpec: EthereumHardforks, Engine = Engine>,
54    Node::Network: PeersHandleProvider,
55    AddOns: RethRpcAddOns<Node>,
56{
57    /// Creates a new test node
58    pub async fn new(
59        node: FullNode<Node, AddOns>,
60        attributes_generator: impl Fn(u64) -> Engine::PayloadBuilderAttributes + Send + Sync + 'static,
61    ) -> eyre::Result<Self> {
62        Ok(Self {
63            inner: node.clone(),
64            payload: PayloadTestContext::new(
65                node.payload_builder_handle.clone(),
66                attributes_generator,
67            )
68            .await?,
69            network: NetworkTestContext::new(node.network.clone()),
70            rpc: RpcTestContext { inner: node.add_ons_handle.rpc_registry },
71            canonical_stream: node.provider.canonical_state_stream(),
72        })
73    }
74
75    /// Establish a connection to the node
76    pub async fn connect(&mut self, node: &mut Self) {
77        self.network.add_peer(node.network.record()).await;
78        node.network.next_session_established().await;
79        self.network.next_session_established().await;
80    }
81
82    /// Advances the chain `length` blocks.
83    ///
84    /// Returns the added chain as a Vec of block hashes.
85    pub async fn advance(
86        &mut self,
87        length: u64,
88        tx_generator: impl Fn(u64) -> Pin<Box<dyn Future<Output = Bytes>>>,
89    ) -> eyre::Result<Vec<Engine::BuiltPayload>>
90    where
91        AddOns::EthApi: EthApiSpec<Provider: BlockReader<Block = BlockTy<Node::Types>>>
92            + EthTransactions
93            + TraceExt,
94    {
95        let mut chain = Vec::with_capacity(length as usize);
96        for i in 0..length {
97            let raw_tx = tx_generator(i).await;
98            let tx_hash = self.rpc.inject_tx(raw_tx).await?;
99            let payload = self.advance_block().await?;
100            let block_hash = payload.block().hash();
101            let block_number = payload.block().number();
102            self.assert_new_block(tx_hash, block_hash, block_number).await?;
103            chain.push(payload);
104        }
105        Ok(chain)
106    }
107
108    /// Creates a new payload from given attributes generator
109    /// expects a payload attribute event and waits until the payload is built.
110    ///
111    /// It triggers the resolve payload via engine api and expects the built payload event.
112    pub async fn new_payload(&mut self) -> eyre::Result<Engine::BuiltPayload> {
113        // trigger new payload building draining the pool
114        let eth_attr = self.payload.new_payload().await.unwrap();
115        // first event is the payload attributes
116        self.payload.expect_attr_event(eth_attr.clone()).await?;
117        // wait for the payload builder to have finished building
118        self.payload.wait_for_built_payload(eth_attr.payload_id()).await;
119        // ensure we're also receiving the built payload as event
120        Ok(self.payload.expect_built_payload().await?)
121    }
122
123    /// Triggers payload building job and submits it to the engine.
124    pub async fn build_and_submit_payload(&mut self) -> eyre::Result<Engine::BuiltPayload> {
125        let payload = self.new_payload().await?;
126
127        self.submit_payload(payload.clone()).await?;
128
129        Ok(payload)
130    }
131
132    /// Advances the node forward one block
133    pub async fn advance_block(&mut self) -> eyre::Result<Engine::BuiltPayload> {
134        let payload = self.build_and_submit_payload().await?;
135
136        // trigger forkchoice update via engine api to commit the block to the blockchain
137        self.update_forkchoice(payload.block().hash(), payload.block().hash()).await?;
138
139        Ok(payload)
140    }
141
142    /// Waits for block to be available on node.
143    pub async fn wait_block(
144        &self,
145        number: BlockNumber,
146        expected_block_hash: BlockHash,
147        wait_finish_checkpoint: bool,
148    ) -> eyre::Result<()> {
149        let mut check = !wait_finish_checkpoint;
150        loop {
151            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
152
153            if !check && wait_finish_checkpoint {
154                if let Some(checkpoint) =
155                    self.inner.provider.get_stage_checkpoint(StageId::Finish)?
156                {
157                    if checkpoint.block_number >= number {
158                        check = true
159                    }
160                }
161            }
162
163            if check {
164                if let Some(latest_block) = self.inner.provider.block_by_number(number)? {
165                    assert_eq!(latest_block.header().hash_slow(), expected_block_hash);
166                    break
167                }
168                assert!(
169                    !wait_finish_checkpoint,
170                    "Finish checkpoint matches, but could not fetch block."
171                );
172            }
173        }
174        Ok(())
175    }
176
177    /// Waits for the node to unwind to the given block number
178    pub async fn wait_unwind(&self, number: BlockNumber) -> eyre::Result<()> {
179        loop {
180            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
181            if let Some(checkpoint) = self.inner.provider.get_stage_checkpoint(StageId::Headers)? {
182                if checkpoint.block_number == number {
183                    break
184                }
185            }
186        }
187        Ok(())
188    }
189
190    /// Asserts that a new block has been added to the blockchain
191    /// and the tx has been included in the block.
192    ///
193    /// Does NOT work for pipeline since there's no stream notification!
194    pub async fn assert_new_block(
195        &mut self,
196        tip_tx_hash: B256,
197        block_hash: B256,
198        block_number: BlockNumber,
199    ) -> eyre::Result<()> {
200        // get head block from notifications stream and verify the tx has been pushed to the
201        // pool is actually present in the canonical block
202        let head = self.canonical_stream.next().await.unwrap();
203        let tx = head.tip().body().transactions().first();
204        assert_eq!(tx.unwrap().tx_hash().as_slice(), tip_tx_hash.as_slice());
205
206        loop {
207            // wait for the block to commit
208            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
209            if let Some(latest_block) =
210                self.inner.provider.block_by_number_or_tag(BlockNumberOrTag::Latest)?
211            {
212                if latest_block.header().number() == block_number {
213                    // make sure the block hash we submitted via FCU engine api is the new latest
214                    // block using an RPC call
215                    assert_eq!(latest_block.header().hash_slow(), block_hash);
216                    break
217                }
218            }
219        }
220        Ok(())
221    }
222
223    /// Gets block hash by number.
224    pub fn block_hash(&self, number: u64) -> BlockHash {
225        self.inner
226            .provider
227            .sealed_header_by_number_or_tag(BlockNumberOrTag::Number(number))
228            .unwrap()
229            .unwrap()
230            .hash()
231    }
232
233    /// Sends FCU and waits for the node to sync to the given block.
234    pub async fn sync_to(&self, block: BlockHash) -> eyre::Result<()> {
235        let start = std::time::Instant::now();
236
237        while self
238            .inner
239            .provider
240            .sealed_header_by_id(BlockId::Number(BlockNumberOrTag::Latest))?
241            .is_none_or(|h| h.hash() != block)
242        {
243            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
244            self.update_forkchoice(block, block).await?;
245
246            assert!(start.elapsed() <= std::time::Duration::from_secs(40), "timed out");
247        }
248
249        // Hack to make sure that all components have time to process canonical state update.
250        // Otherwise, this might result in e.g "nonce too low" errors when advancing chain further,
251        // making tests flaky.
252        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
253
254        Ok(())
255    }
256
257    /// Sends a forkchoice update message to the engine.
258    pub async fn update_forkchoice(&self, current_head: B256, new_head: B256) -> eyre::Result<()> {
259        self.inner
260            .add_ons_handle
261            .beacon_engine_handle
262            .fork_choice_updated(
263                ForkchoiceState {
264                    head_block_hash: new_head,
265                    safe_block_hash: current_head,
266                    finalized_block_hash: current_head,
267                },
268                None,
269                EngineApiMessageVersion::default(),
270            )
271            .await?;
272
273        Ok(())
274    }
275
276    /// Sends forkchoice update to the engine api with a zero finalized hash
277    pub async fn update_optimistic_forkchoice(&self, hash: B256) -> eyre::Result<()> {
278        self.update_forkchoice(B256::ZERO, hash).await
279    }
280
281    /// Submits a payload to the engine.
282    pub async fn submit_payload(&self, payload: Engine::BuiltPayload) -> eyre::Result<B256> {
283        let block_hash = payload.block().hash();
284        self.inner
285            .add_ons_handle
286            .beacon_engine_handle
287            .new_payload(Engine::block_to_payload(payload.block().clone()))
288            .await?;
289
290        Ok(block_hash)
291    }
292
293    /// Returns the RPC URL.
294    pub fn rpc_url(&self) -> Url {
295        let addr = self.inner.rpc_server_handle().http_local_addr().unwrap();
296        format!("http://{}", addr).parse().unwrap()
297    }
298
299    /// Returns an RPC client.
300    pub fn rpc_client(&self) -> Option<HttpClient> {
301        self.inner.rpc_server_handle().http_client()
302    }
303
304    /// Returns an Engine API client.
305    pub fn engine_api_client(&self) -> HttpClient<AuthClientService<HttpBackend>> {
306        self.inner.auth_server_handle().http_client()
307    }
308}