Skip to main content

reth_e2e_test_utils/
setup_import.rs

1//! Setup utilities for importing RLP chain data before starting nodes.
2
3use crate::{
4    eth_payload_attributes,
5    setup_builder::{launch_test_node, open_test_database, test_node_config, LaunchArgs},
6    wallet::Wallet,
7    NodeHelperType,
8};
9use eyre::WrapErr;
10use reth_chainspec::ChainSpec;
11use reth_cli_commands::import_core::{import_blocks_from_file, ImportConfig, ImportResult};
12use reth_config::Config;
13use reth_db::DatabaseEnv;
14use reth_node_api::{NodeTypesWithDBAdapter, TreeConfig};
15use reth_node_builder::sync::PipelineBackfill;
16use reth_node_core::args::StorageArgs;
17use reth_node_ethereum::EthereumNode;
18use reth_provider::{
19    providers::{RocksDBProvider, StaticFileProvider},
20    DatabaseProviderFactory, ProviderFactory, StageCheckpointReader, StorageSettings,
21};
22use reth_stages_types::StageId;
23use reth_storage_overlay::OverlayManager;
24use reth_tasks::Runtime;
25use std::{path::Path, sync::Arc};
26use tempfile::TempDir;
27use tracing::{debug, info, span, Instrument, Level};
28
29/// Setup result containing nodes and temporary directories that must be kept alive
30pub struct ChainImportResult {
31    /// The nodes that were created
32    pub nodes: Vec<NodeHelperType<EthereumNode>>,
33    /// The wallet for testing
34    pub wallet: Wallet,
35    /// Temporary directories that must be kept alive for the duration of the test
36    pub _temp_dirs: Vec<TempDir>,
37}
38
39impl std::fmt::Debug for ChainImportResult {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.debug_struct("ChainImportResult")
42            .field("nodes", &self.nodes.len())
43            .field("wallet", &self.wallet)
44            .field("temp_dirs", &self._temp_dirs.len())
45            .finish()
46    }
47}
48
49/// Creates a test setup with Ethereum nodes that have pre-imported chain data from RLP files.
50///
51/// This function:
52/// 1. Creates a temporary datadir for each node
53/// 2. Imports the specified RLP chain data into the datadir
54/// 3. Starts the nodes with the pre-populated database
55/// 4. Returns the running nodes ready for testing
56///
57/// The import and all nodes share a single [`Runtime::test`] runtime, and the nodes build payloads
58/// with [`eth_payload_attributes`] for the given chain spec. `storage_v2` selects the storage
59/// layout (`--storage.v2`) for both the imported database and the launched nodes.
60///
61/// Note: This function is currently specific to `EthereumNode` because the import process
62/// uses Ethereum-specific consensus and block format. It can be made generic in the future
63/// by abstracting the import process.
64/// It uses `NoopConsensus` during import to bypass validation checks like gas limit constraints,
65/// which allows importing test chains that may not strictly conform to mainnet consensus rules. The
66/// nodes themselves still run with proper consensus when started.
67pub async fn setup_engine_with_chain_import(
68    num_nodes: usize,
69    chain_spec: Arc<ChainSpec>,
70    is_dev: bool,
71    storage_v2: bool,
72    tree_config: TreeConfig,
73    rlp_path: &Path,
74) -> eyre::Result<ChainImportResult> {
75    let runtime = Runtime::test();
76    let attributes_generator = {
77        let chain_spec = chain_spec.clone();
78        Arc::new(move |timestamp| eth_payload_attributes(&chain_spec, timestamp))
79    };
80
81    // Create nodes with imported data.
82    let mut nodes = Vec::with_capacity(num_nodes);
83    // Keep the temp dirs alive for the lifetime of the nodes.
84    let mut temp_dirs = Vec::with_capacity(num_nodes);
85
86    for idx in 0..num_nodes {
87        // Create a temporary datadir for this node.
88        let temp_dir = TempDir::new()?;
89        let datadir = temp_dir.path().to_path_buf();
90        debug!(target: "e2e::import", "Node {idx} datadir: {datadir:?}");
91
92        let span = span!(Level::INFO, "node", idx);
93        let node_config = test_node_config(chain_spec.clone())
94            .set_dev(is_dev)
95            .with_storage(StorageArgs { v2: storage_v2 });
96
97        // First, import the chain data into this datadir.
98        import_chain(
99            &datadir,
100            chain_spec.clone(),
101            node_config.storage_settings(),
102            rlp_path,
103            runtime.clone(),
104        )
105        .instrument(span.clone())
106        .await
107        .wrap_err_with(|| format!("chain import failed for node {idx}"))?;
108
109        // Now launch the node with the pre-populated datadir.
110        debug!(target: "e2e::import", "Launching node with datadir: {:?}", datadir);
111
112        let database = open_test_database(&datadir)?;
113        let node = launch_test_node(
114            LaunchArgs {
115                idx,
116                node_factory: Arc::new(|_| EthereumNode::default()),
117                node_builder_modifiers: Vec::new(),
118                node_config,
119                runtime: Some(runtime.clone()),
120                tree_config: tree_config.clone(),
121                datadir,
122                attributes_generator: attributes_generator.clone(),
123                dev_payload_attributes: None,
124            },
125            database,
126            PipelineBackfill,
127        )
128        .instrument(span)
129        .await?;
130
131        nodes.push(node);
132        temp_dirs.push(temp_dir);
133    }
134
135    Ok(ChainImportResult {
136        nodes,
137        wallet: Wallet::default().with_chain_id(chain_spec.chain.id()),
138        _temp_dirs: temp_dirs,
139    })
140}
141
142/// Helper to load forkchoice state from a JSON file
143pub fn load_forkchoice_state(path: &Path) -> eyre::Result<alloy_rpc_types_engine::ForkchoiceState> {
144    let json_str = std::fs::read_to_string(path)?;
145    let fcu_data: serde_json::Value = serde_json::from_str(&json_str)?;
146
147    // The headfcu.json file contains a JSON-RPC request with the forkchoice state in params[0]
148    let state = &fcu_data["params"][0];
149    Ok(alloy_rpc_types_engine::ForkchoiceState {
150        head_block_hash: state["headBlockHash"]
151            .as_str()
152            .ok_or_else(|| eyre::eyre!("missing headBlockHash"))?
153            .parse()?,
154        safe_block_hash: state["safeBlockHash"]
155            .as_str()
156            .ok_or_else(|| eyre::eyre!("missing safeBlockHash"))?
157            .parse()?,
158        finalized_block_hash: state["finalizedBlockHash"]
159            .as_str()
160            .ok_or_else(|| eyre::eyre!("missing finalizedBlockHash"))?
161            .parse()?,
162    })
163}
164
165/// Initializes the database in `datadir` with the given storage settings and imports the RLP
166/// encoded chain at `rlp_path`.
167///
168/// All database handles are released on return so the datadir can be reopened, e.g. by a node,
169/// which reads the storage settings back from the database.
170async fn import_chain(
171    datadir: &Path,
172    chain_spec: Arc<ChainSpec>,
173    storage_settings: StorageSettings,
174    rlp_path: &Path,
175    runtime: Runtime,
176) -> eyre::Result<ImportResult> {
177    info!(target: "test", "Importing chain data from {:?} into {:?}", rlp_path, datadir);
178
179    // Initialize the database using init_db, same as the CLI import command.
180    let db_args = reth_node_core::args::DatabaseArgs::default().database_args();
181    let db = reth_db::init_db(datadir.join("db"), db_args)?;
182
183    // Create a provider factory with the initialized database, not a `TempDatabase`.
184    let provider_factory =
185        ProviderFactory::<NodeTypesWithDBAdapter<EthereumNode, DatabaseEnv>>::new(
186            db.clone(),
187            chain_spec.clone(),
188            StaticFileProvider::read_write(datadir.join("static_files"))?,
189            RocksDBProvider::builder(datadir.join("rocksdb")).with_default_tables().build()?,
190            OverlayManager::default(),
191            runtime.clone(),
192        )?;
193
194    // Initialize genesis with the storage settings of the node that later opens the database.
195    reth_db_common::init::init_genesis_with_settings(&provider_factory, storage_settings)?;
196
197    // Use NoopConsensus to skip gas limit validation for test imports.
198    let result = import_blocks_from_file(
199        rlp_path,
200        ImportConfig::default(),
201        provider_factory.clone(),
202        &Config::default(),
203        reth_node_ethereum::EthEvmConfig::new(chain_spec),
204        reth_consensus::noop::NoopConsensus::arc(),
205        runtime,
206    )
207    .await?;
208
209    info!(
210        target: "test",
211        "Imported {} blocks and {} transactions",
212        result.total_imported_blocks,
213        result.total_imported_txns,
214    );
215
216    debug!(target: "e2e::import",
217        "Import result: decoded {} blocks, imported {} blocks, complete: {}",
218        result.total_decoded_blocks,
219        result.total_imported_blocks,
220        result.is_complete()
221    );
222
223    eyre::ensure!(
224        result.total_decoded_blocks == result.total_imported_blocks,
225        "block count mismatch: decoded {} != imported {}",
226        result.total_decoded_blocks,
227        result.total_imported_blocks
228    );
229    eyre::ensure!(
230        result.total_decoded_txns == result.total_imported_txns,
231        "transaction count mismatch: decoded {} != imported {}",
232        result.total_decoded_txns,
233        result.total_imported_txns
234    );
235
236    // Verify the database was properly initialized by checking stage checkpoints.
237    let headers_checkpoint =
238        provider_factory.database_provider_ro()?.get_stage_checkpoint(StageId::Headers)?;
239    eyre::ensure!(headers_checkpoint.is_some(), "Headers stage checkpoint is missing after import");
240    debug!(target: "e2e::import", "Headers stage checkpoint after import: {headers_checkpoint:?}");
241
242    // Close all database handles to release locks before launching the node.
243    drop(provider_factory);
244    drop(db);
245
246    // The header and body downloader tasks spawned on the runtime hold provider factory clones
247    // and only exit once they are polled after the pipeline was dropped, so yield long enough for
248    // them to release the database.
249    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
250
251    Ok(result)
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use crate::{
258        test_chain_spec,
259        test_rlp_utils::{create_fcu_json, generate_test_blocks, write_blocks_to_rlp},
260    };
261    use reth_chainspec::EthereumHardfork;
262    use reth_db::mdbx::DatabaseArguments;
263    use reth_ethereum_primitives::Block;
264    use reth_primitives_traits::SealedBlock;
265    use reth_provider::{BlockHashReader, BlockNumReader, BlockReaderIdExt, MetadataProvider};
266    use std::path::PathBuf;
267
268    /// Helper to setup test blocks and write to RLP.
269    fn setup_test_blocks_and_rlp(
270        chain_spec: &ChainSpec,
271        block_count: u64,
272        temp_dir: &Path,
273    ) -> (Vec<SealedBlock<Block>>, PathBuf) {
274        let test_blocks = generate_test_blocks(chain_spec, block_count);
275        assert_eq!(
276            test_blocks.len(),
277            block_count as usize,
278            "Should have generated expected blocks"
279        );
280
281        let rlp_path = temp_dir.join("test_chain.rlp");
282        write_blocks_to_rlp(&test_blocks, &rlp_path).expect("Failed to write RLP data");
283
284        let rlp_size = std::fs::metadata(&rlp_path).expect("RLP file should exist").len();
285        debug!(target: "e2e::import", "Wrote RLP file with size: {rlp_size} bytes");
286
287        (test_blocks, rlp_path)
288    }
289
290    /// Reopens the database in `datadir` that was written by [`import_chain`].
291    fn reopen_provider_factory(
292        datadir: &Path,
293        chain_spec: Arc<ChainSpec>,
294        runtime: Runtime,
295    ) -> ProviderFactory<NodeTypesWithDBAdapter<EthereumNode, DatabaseEnv>> {
296        let db = reth_db::init_db(datadir.join("db"), DatabaseArguments::default()).unwrap();
297        ProviderFactory::new(
298            db,
299            chain_spec,
300            StaticFileProvider::read_only(datadir.join("static_files")).unwrap(),
301            RocksDBProvider::builder(datadir.join("rocksdb"))
302                .with_default_tables()
303                .build()
304                .unwrap(),
305            OverlayManager::default(),
306            runtime,
307        )
308        .expect("failed to create provider factory")
309    }
310
311    #[tokio::test]
312    async fn test_import_blocks_and_reopen() {
313        // Tests the block import without a node, and that the imported chain and stage
314        // checkpoints persist when reopening the database.
315        reth_tracing::init_test_tracing();
316
317        let runtime = Runtime::test();
318        let chain_spec = test_chain_spec(EthereumHardfork::Shanghai);
319        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
320        let (test_blocks, rlp_path) = setup_test_blocks_and_rlp(&chain_spec, 10, temp_dir.path());
321
322        let datadir = temp_dir.path().join("datadir");
323        std::fs::create_dir_all(&datadir).unwrap();
324        let storage_settings = StorageSettings { storage_v2: StorageArgs::default().v2 };
325        let result = import_chain(
326            &datadir,
327            chain_spec.clone(),
328            storage_settings,
329            &rlp_path,
330            runtime.clone(),
331        )
332        .await
333        .unwrap();
334        assert_eq!(result.total_decoded_blocks, 10);
335        assert_eq!(result.total_imported_blocks, 10);
336        assert_eq!(result.total_decoded_txns, 0);
337        assert_eq!(result.total_imported_txns, 0);
338
339        let provider_factory = reopen_provider_factory(&datadir, chain_spec, runtime);
340        let provider = provider_factory.database_provider_ro().unwrap();
341        assert_eq!(provider.last_block_number().unwrap(), 10);
342        assert_eq!(provider.block_hash(10).unwrap(), Some(test_blocks[9].hash()));
343        let headers_checkpoint = provider.get_stage_checkpoint(StageId::Headers).unwrap();
344        assert_eq!(headers_checkpoint.map(|checkpoint| checkpoint.block_number), Some(10));
345    }
346
347    #[tokio::test]
348    async fn test_import_with_node_integration() {
349        // Tests the full integration with node setup, forkchoice updates, and syncing.
350        reth_tracing::init_test_tracing();
351
352        let chain_spec = test_chain_spec(EthereumHardfork::Shanghai);
353        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
354        let (test_blocks, rlp_path) = setup_test_blocks_and_rlp(&chain_spec, 10, temp_dir.path());
355
356        // Create FCU data for the tip.
357        let tip = test_blocks.last().expect("Should have generated blocks");
358        let fcu_path = temp_dir.path().join("test_fcu.json");
359        std::fs::write(&fcu_path, create_fcu_json(tip).to_string())
360            .expect("Failed to write FCU data");
361
362        for storage_v2 in [false, true] {
363            // Setup nodes with imported chain.
364            let result = setup_engine_with_chain_import(
365                1,
366                chain_spec.clone(),
367                false,
368                storage_v2,
369                TreeConfig::default(),
370                &rlp_path,
371            )
372            .await
373            .expect("Failed to setup nodes with chain import");
374
375            // Load and apply forkchoice state.
376            let fcu_state =
377                load_forkchoice_state(&fcu_path).expect("Failed to load forkchoice state");
378
379            let node = &result.nodes[0];
380
381            // The imported database and the node use the requested storage layout.
382            let settings = node
383                .inner
384                .provider
385                .database_provider_ro()
386                .expect("Failed to open database provider")
387                .storage_settings()
388                .expect("Failed to read storage settings");
389            assert_eq!(settings, Some(StorageSettings { storage_v2 }));
390
391            // Send forkchoice update to make the imported chain canonical.
392            node.update_forkchoice(fcu_state.finalized_block_hash, fcu_state.head_block_hash)
393                .await
394                .expect("Failed to update forkchoice");
395
396            // Wait for the node to sync to the head.
397            node.sync_to(fcu_state.head_block_hash).await.expect("Failed to sync to head");
398
399            // Verify the chain tip.
400            let latest = node
401                .inner
402                .provider
403                .sealed_header_by_id(alloy_eips::BlockId::latest())
404                .expect("Failed to get latest header")
405                .expect("No latest header found");
406
407            assert_eq!(
408                latest.hash(),
409                fcu_state.head_block_hash,
410                "Chain tip does not match expected head"
411            );
412        }
413    }
414}