Skip to main content

reth_cli_commands/
import_core.rs

1//! Core import functionality without CLI dependencies.
2
3use alloy_primitives::B256;
4use futures::StreamExt;
5use reth_config::Config;
6use reth_consensus::FullConsensus;
7use reth_db_api::{tables, transaction::DbTx};
8use reth_downloaders::{
9    bodies::bodies::BodiesDownloaderBuilder,
10    file_client::{ChunkedFileReader, FileClient, DEFAULT_BYTE_LEN_CHUNK_CHAIN_FILE},
11    headers::reverse_headers::ReverseHeadersDownloaderBuilder,
12};
13use reth_evm::ConfigureEvm;
14use reth_network_p2p::{
15    bodies::downloader::BodyDownloader,
16    headers::downloader::{HeaderDownloader, SyncTarget},
17};
18use reth_node_api::BlockTy;
19use reth_node_events::node::NodeEvent;
20use reth_provider::{
21    providers::ProviderNodeTypes, BlockNumReader, HeaderProvider, ProviderError, ProviderFactory,
22    RocksDBProviderFactory, StageCheckpointReader,
23};
24use reth_prune::PruneModes;
25use reth_stages::{prelude::*, ControlFlow, Pipeline, StageId, StageSet};
26use reth_static_file::StaticFileProducer;
27use reth_storage_api::StorageSettingsCache;
28use std::{path::Path, sync::Arc};
29use tokio::sync::watch;
30use tracing::{debug, error, info, warn};
31
32/// Configuration for importing blocks from RLP files.
33#[derive(Debug, Clone, Default)]
34pub struct ImportConfig {
35    /// Disables stages that require state.
36    pub no_state: bool,
37    /// Chunk byte length to read from file.
38    pub chunk_len: Option<u64>,
39    /// If true, fail immediately when an invalid block is encountered.
40    /// By default (false), the import stops at the last valid block and exits successfully.
41    pub fail_on_invalid_block: bool,
42}
43
44/// Result of an import operation.
45#[derive(Debug)]
46pub struct ImportResult {
47    /// Total number of blocks decoded from the file.
48    pub total_decoded_blocks: usize,
49    /// Total number of transactions decoded from the file.
50    pub total_decoded_txns: usize,
51    /// Total number of blocks imported into the database.
52    pub total_imported_blocks: usize,
53    /// Total number of transactions imported into the database.
54    pub total_imported_txns: usize,
55    /// Whether the import was stopped due to an invalid block.
56    pub stopped_on_invalid_block: bool,
57    /// The block number that was invalid, if any.
58    pub bad_block: Option<u64>,
59    /// The last valid block number when stopped due to invalid block.
60    pub last_valid_block: Option<u64>,
61}
62
63impl ImportResult {
64    /// Returns true if all blocks and transactions were imported successfully.
65    pub fn is_complete(&self) -> bool {
66        self.total_decoded_blocks == self.total_imported_blocks &&
67            self.total_decoded_txns == self.total_imported_txns
68    }
69
70    /// Returns true if the import was successful, considering stop-on-invalid-block mode.
71    ///
72    /// In stop-on-invalid-block mode, a partial import is considered successful if we
73    /// stopped due to an invalid block (leaving the DB at the last valid block).
74    pub fn is_successful(&self) -> bool {
75        self.is_complete() || self.stopped_on_invalid_block
76    }
77}
78
79/// Imports blocks from an RLP-encoded file into the database.
80///
81/// This function reads RLP-encoded blocks from a file in chunks and imports them
82/// using the pipeline infrastructure. It's designed to be used both from the CLI
83/// and from test code.
84pub async fn import_blocks_from_file<N>(
85    path: &Path,
86    import_config: ImportConfig,
87    provider_factory: ProviderFactory<N>,
88    config: &Config,
89    executor: impl ConfigureEvm<Primitives = N::Primitives> + 'static,
90    consensus: Arc<impl FullConsensus<N::Primitives> + 'static>,
91    runtime: reth_tasks::Runtime,
92) -> eyre::Result<ImportResult>
93where
94    N: ProviderNodeTypes,
95{
96    if import_config.no_state {
97        info!(target: "reth::import", "Disabled stages requiring state");
98    }
99
100    debug!(target: "reth::import",
101        chunk_byte_len=import_config.chunk_len.unwrap_or(DEFAULT_BYTE_LEN_CHUNK_CHAIN_FILE),
102        "Chunking chain import"
103    );
104
105    info!(target: "reth::import", "Consensus engine initialized");
106
107    // open file
108    let mut reader = ChunkedFileReader::new(path, import_config.chunk_len).await?;
109
110    let provider = provider_factory.provider()?;
111    let init_blocks = provider.tx_ref().entries::<tables::HeaderNumbers>()?;
112    let init_txns = if provider_factory.cached_storage_settings().storage_v2 {
113        provider_factory.rocksdb_provider().iter::<tables::TransactionHashNumbers>()?.count()
114    } else {
115        provider.tx_ref().entries::<tables::TransactionHashNumbers>()?
116    };
117    drop(provider);
118
119    let mut total_decoded_blocks = 0;
120    let mut total_decoded_txns = 0;
121
122    let mut sealed_header = provider_factory
123        .sealed_header(provider_factory.last_block_number()?)?
124        .expect("should have genesis");
125
126    let static_file_producer =
127        StaticFileProducer::new(provider_factory.clone(), PruneModes::default());
128
129    // Track if we stopped due to an invalid block
130    let mut stopped_on_invalid_block = false;
131    let mut bad_block_number: Option<u64> = None;
132    let mut last_valid_block_number: Option<u64> = None;
133
134    let skip_invalid_blocks = !import_config.fail_on_invalid_block;
135    while let Some(file_client) = reader
136        .next_chunk_with_invalid_block_handling::<BlockTy<N>>(
137            consensus.clone(),
138            Some(sealed_header.clone()),
139            skip_invalid_blocks,
140        )
141        .await?
142    {
143        // create a new FileClient from chunk read from file
144        info!(target: "reth::import",
145            "Importing chain file chunk"
146        );
147
148        if file_client.headers_len() == 0 {
149            debug!(target: "reth::import", "Skipping chain file chunk without valid blocks");
150            continue;
151        }
152
153        let tip = file_client.tip().ok_or(eyre::eyre!("file client has no tip"))?;
154        info!(target: "reth::import", "Chain file chunk read");
155
156        total_decoded_blocks += file_client.headers_len();
157        total_decoded_txns += file_client.total_transactions();
158
159        let (mut pipeline, events) = build_import_pipeline_impl(
160            config,
161            provider_factory.clone(),
162            &consensus,
163            Arc::new(file_client),
164            static_file_producer.clone(),
165            import_config.no_state,
166            executor.clone(),
167            runtime.clone(),
168        )?;
169
170        // override the tip
171        pipeline.set_tip(tip);
172        debug!(target: "reth::import", ?tip, "Tip manually set");
173
174        let latest_block_number =
175            provider_factory.get_stage_checkpoint(StageId::Finish)?.map(|ch| ch.block_number);
176        tokio::spawn(reth_node_events::node::handle_events(None, latest_block_number, events));
177
178        // Run pipeline
179        info!(target: "reth::import", "Starting sync pipeline");
180        if import_config.fail_on_invalid_block {
181            // Original behavior: fail on unwind
182            tokio::select! {
183                res = pipeline.run() => res?,
184                _ = tokio::signal::ctrl_c() => {
185                    info!(target: "reth::import", "Import interrupted by user");
186                    break;
187                },
188            }
189        } else {
190            // Default behavior: Use run_loop() to handle unwinds gracefully
191            let result = tokio::select! {
192                res = pipeline.run_loop() => res,
193                _ = tokio::signal::ctrl_c() => {
194                    info!(target: "reth::import", "Import interrupted by user");
195                    break;
196                },
197            };
198
199            match result {
200                Ok(ControlFlow::Unwind { target, bad_block }) => {
201                    // An invalid block was encountered; stop at last valid block
202                    let bad = bad_block.block.number;
203                    warn!(
204                        target: "reth::import",
205                        bad_block = bad,
206                        last_valid_block = target,
207                        "Invalid block encountered during import; stopping at last valid block"
208                    );
209                    stopped_on_invalid_block = true;
210                    bad_block_number = Some(bad);
211                    last_valid_block_number = Some(target);
212                    break;
213                }
214                Ok(ControlFlow::Continue { block_number }) => {
215                    debug!(target: "reth::import", block_number, "Pipeline chunk completed");
216                }
217                Ok(ControlFlow::NoProgress { block_number }) => {
218                    debug!(target: "reth::import", ?block_number, "Pipeline made no progress");
219                }
220                Err(e) => {
221                    // Propagate other pipeline errors
222                    return Err(e.into());
223                }
224            }
225        }
226
227        sealed_header = provider_factory
228            .sealed_header(provider_factory.last_block_number()?)?
229            .expect("should have genesis");
230    }
231
232    let provider = provider_factory.provider()?;
233    let total_imported_blocks = provider.tx_ref().entries::<tables::HeaderNumbers>()? - init_blocks;
234    let current_txns = if provider_factory.cached_storage_settings().storage_v2 {
235        provider_factory.rocksdb_provider().iter::<tables::TransactionHashNumbers>()?.count()
236    } else {
237        provider.tx_ref().entries::<tables::TransactionHashNumbers>()?
238    };
239    let total_imported_txns = current_txns - init_txns;
240
241    let result = ImportResult {
242        total_decoded_blocks,
243        total_decoded_txns,
244        total_imported_blocks,
245        total_imported_txns,
246        stopped_on_invalid_block,
247        bad_block: bad_block_number,
248        last_valid_block: last_valid_block_number,
249    };
250
251    if result.stopped_on_invalid_block {
252        info!(target: "reth::import",
253            total_imported_blocks,
254            total_imported_txns,
255            bad_block = ?result.bad_block,
256            last_valid_block = ?result.last_valid_block,
257            "Import stopped at last valid block due to invalid block"
258        );
259    } else if !result.is_complete() {
260        error!(target: "reth::import",
261            total_decoded_blocks,
262            total_imported_blocks,
263            total_decoded_txns,
264            total_imported_txns,
265            "Chain was partially imported"
266        );
267    } else {
268        info!(target: "reth::import",
269            total_imported_blocks,
270            total_imported_txns,
271            "Chain was fully imported"
272        );
273    }
274
275    Ok(result)
276}
277
278/// Builds import pipeline.
279///
280/// If configured to execute, all stages will run. Otherwise, only stages that don't require state
281/// will run.
282#[expect(clippy::too_many_arguments)]
283pub fn build_import_pipeline_impl<N, C, E>(
284    config: &Config,
285    provider_factory: ProviderFactory<N>,
286    consensus: &Arc<C>,
287    file_client: Arc<FileClient<BlockTy<N>>>,
288    static_file_producer: StaticFileProducer<ProviderFactory<N>>,
289    disable_exec: bool,
290    evm_config: E,
291    runtime: reth_tasks::Runtime,
292) -> eyre::Result<(Pipeline<N>, impl futures::Stream<Item = NodeEvent<N::Primitives>> + use<N, C, E>)>
293where
294    N: ProviderNodeTypes,
295    C: FullConsensus<N::Primitives> + 'static,
296    E: ConfigureEvm<Primitives = N::Primitives> + 'static,
297{
298    if !file_client.has_canonical_blocks() {
299        eyre::bail!("unable to import non canonical blocks");
300    }
301
302    // Retrieve latest header found in the database.
303    let last_block_number = provider_factory.last_block_number()?;
304    let local_head = provider_factory
305        .sealed_header(last_block_number)?
306        .ok_or_else(|| ProviderError::HeaderNotFound(last_block_number.into()))?;
307
308    let mut header_downloader = ReverseHeadersDownloaderBuilder::new(config.stages.headers)
309        .build(file_client.clone(), consensus.clone())
310        .into_task_with(&runtime);
311    // TODO: The pipeline should correctly configure the downloader on its own.
312    // Find the possibility to remove unnecessary pre-configuration.
313    header_downloader.update_local_head(local_head);
314    header_downloader.update_sync_target(SyncTarget::Tip(file_client.tip().unwrap()));
315
316    let mut body_downloader = BodiesDownloaderBuilder::new(config.stages.bodies)
317        .build(file_client.clone(), consensus.clone(), provider_factory.clone())
318        .into_task_with(&runtime);
319    // TODO: The pipeline should correctly configure the downloader on its own.
320    // Find the possibility to remove unnecessary pre-configuration.
321    body_downloader
322        .set_download_range(file_client.min_block().unwrap()..=file_client.max_block().unwrap())
323        .expect("failed to set download range");
324
325    let (tip_tx, tip_rx) = watch::channel(B256::ZERO);
326
327    let max_block = file_client.max_block().unwrap_or(0);
328
329    let pipeline = Pipeline::builder()
330        .with_tip_sender(tip_tx)
331        // we want to sync all blocks the file client provides or 0 if empty
332        .with_max_block(max_block)
333        .with_fail_on_unwind(true)
334        .add_stages(
335            DefaultStages::new(
336                provider_factory.clone(),
337                tip_rx,
338                consensus.clone(),
339                header_downloader,
340                body_downloader,
341                evm_config,
342                config.stages.clone(),
343                PruneModes::default(),
344                None,
345            )
346            .builder()
347            .disable_all_if(&StageId::STATE_REQUIRED, || disable_exec),
348        )
349        .build(provider_factory, static_file_producer);
350
351    let events = pipeline.events().map(Into::into);
352
353    Ok((pipeline, events))
354}