1use crate::{
4 common::{AccessRights, CliNodeTypes, Environment, EnvironmentArgs},
5 stage::CliNodeComponents,
6};
7use alloy_eips::BlockHashOrNumber;
8use alloy_primitives::B256;
9use clap::{Parser, Subcommand};
10use reth_chainspec::{ChainSpecProvider, EthChainSpec, EthereumHardforks};
11use reth_cli::chainspec::ChainSpecParser;
12use reth_config::Config;
13use reth_consensus::noop::NoopConsensus;
14use reth_db::DatabaseEnv;
15use reth_downloaders::{bodies::noop::NoopBodiesDownloader, headers::noop::NoopHeaderDownloader};
16use reth_evm::ConfigureEvm;
17use reth_provider::{providers::ProviderNodeTypes, BlockNumReader, ProviderFactory};
18use reth_stages::{
19 sets::{DefaultStages, OfflineStages},
20 stages::{EraImportSource, EraStage},
21 Pipeline, StageId, StageSet,
22};
23use reth_static_file::StaticFileProducer;
24use std::sync::Arc;
25use tokio::sync::watch;
26use tracing::info;
27
28#[derive(Debug, Parser)]
30pub struct Command<C: ChainSpecParser> {
31 #[command(flatten)]
32 env: EnvironmentArgs<C>,
33
34 #[command(subcommand)]
35 command: Subcommands,
36
37 #[arg(long)]
40 offline: bool,
41}
42
43impl<C: ChainSpecParser<ChainSpec: EthChainSpec + EthereumHardforks>> Command<C> {
44 pub async fn execute<N: CliNodeTypes<ChainSpec = C::ChainSpec>, F, Comp>(
46 self,
47 components: F,
48 runtime: reth_tasks::Runtime,
49 ) -> eyre::Result<()>
50 where
51 Comp: CliNodeComponents<N>,
52 F: FnOnce(Arc<C::ChainSpec>) -> Comp,
53 {
54 let Environment { provider_factory, config, data_dir: _ } =
55 self.env.init::<N>(AccessRights::RW, runtime)?;
56
57 let target = self.command.unwind_target(provider_factory.clone())?;
58
59 let components = components(provider_factory.chain_spec());
60
61 if self.offline {
62 info!(target: "reth::cli", "Performing an unwind for offline-only data!");
63 }
64
65 let highest_static_file_block = provider_factory.provider()?.last_block_number()?;
66 info!(target: "reth::cli", ?target, ?highest_static_file_block, prune_config=?config.prune, "Executing a pipeline unwind.");
67
68 let mut pipeline =
70 self.build_pipeline(config, provider_factory, components.evm_config().clone())?;
71
72 pipeline.move_to_static_files()?;
74
75 pipeline.unwind(target, None)?;
76
77 info!(target: "reth::cli", ?target, "Unwound blocks");
78
79 Ok(())
80 }
81
82 fn build_pipeline<N: ProviderNodeTypes<ChainSpec = C::ChainSpec>>(
83 self,
84 config: Config,
85 provider_factory: ProviderFactory<N>,
86 evm_config: impl ConfigureEvm<Primitives = N::Primitives> + 'static,
87 ) -> Result<Pipeline<N>, eyre::Error> {
88 let stage_conf = &config.stages;
89 let prune_modes = config.prune.segments.clone();
90
91 let (tip_tx, tip_rx) = watch::channel(B256::ZERO);
92
93 let builder = if self.offline {
94 Pipeline::<N>::builder().add_stages(
95 OfflineStages::new(
96 evm_config,
97 NoopConsensus::arc(),
98 config.stages,
99 prune_modes.clone(),
100 )
101 .builder()
102 .disable(reth_stages::StageId::SenderRecovery),
103 )
104 } else {
105 Pipeline::<N>::builder().with_tip_sender(tip_tx).add_stages(
106 DefaultStages::new(
107 provider_factory.clone(),
108 tip_rx,
109 Arc::new(NoopConsensus::default()),
110 NoopHeaderDownloader::default(),
111 NoopBodiesDownloader::default(),
112 evm_config,
113 stage_conf.clone(),
114 prune_modes.clone(),
115 None,
116 )
117 .builder()
118 .add_before(
119 EraStage::new(None::<EraImportSource>, stage_conf.etl.clone()),
120 StageId::Headers,
121 ),
122 )
123 };
124
125 let pipeline = builder.build(
126 provider_factory.clone(),
127 StaticFileProducer::new(provider_factory, prune_modes),
128 );
129 Ok(pipeline)
130 }
131}
132
133impl<C: ChainSpecParser> Command<C> {
134 pub fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
136 Some(&self.env.chain)
137 }
138}
139
140#[derive(Subcommand, Debug, Eq, PartialEq)]
142enum Subcommands {
143 #[command(name = "to-block")]
146 ToBlock { target: BlockHashOrNumber },
147 #[command(name = "num-blocks")]
150 NumBlocks { amount: u64 },
151}
152
153impl Subcommands {
154 fn unwind_target<N: ProviderNodeTypes<DB = DatabaseEnv>>(
156 &self,
157 factory: ProviderFactory<N>,
158 ) -> eyre::Result<u64> {
159 let provider = factory.provider()?;
160 let last = provider.last_block_number()?;
161 let target = match self {
162 Self::ToBlock { target } => match target {
163 BlockHashOrNumber::Hash(hash) => provider
164 .block_number(*hash)?
165 .ok_or_else(|| eyre::eyre!("Block hash not found in database: {hash:?}"))?,
166 BlockHashOrNumber::Number(num) => *num,
167 },
168 Self::NumBlocks { amount } => last.saturating_sub(*amount),
169 };
170 if target > last {
171 eyre::bail!(
172 "Target block number {target} is higher than the latest block number {last}"
173 );
174 }
175 Ok(target)
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use reth_chainspec::SEPOLIA;
183 use reth_ethereum_cli::chainspec::EthereumChainSpecParser;
184
185 #[test]
186 fn parse_unwind() {
187 let cmd = Command::<EthereumChainSpecParser>::parse_from([
188 "reth",
189 "--datadir",
190 "dir",
191 "to-block",
192 "100",
193 ]);
194 assert_eq!(cmd.command, Subcommands::ToBlock { target: BlockHashOrNumber::Number(100) });
195
196 let cmd = Command::<EthereumChainSpecParser>::parse_from([
197 "reth",
198 "--datadir",
199 "dir",
200 "num-blocks",
201 "100",
202 ]);
203 assert_eq!(cmd.command, Subcommands::NumBlocks { amount: 100 });
204 }
205
206 #[test]
207 fn parse_unwind_chain() {
208 let cmd = Command::<EthereumChainSpecParser>::parse_from([
209 "reth", "--chain", "sepolia", "to-block", "100",
210 ]);
211 assert_eq!(cmd.command, Subcommands::ToBlock { target: BlockHashOrNumber::Number(100) });
212 assert_eq!(cmd.env.chain.chain_id(), SEPOLIA.chain_id());
213 }
214}