reth_optimism_cli/commands/
import_receipts.rs1use crate::receipt_file_codec::OpGethReceiptFileCodec;
5use clap::Parser;
6use reth_cli::chainspec::ChainSpecParser;
7use reth_cli_commands::common::{AccessRights, CliNodeTypes, Environment, EnvironmentArgs};
8use reth_db_api::tables;
9use reth_downloaders::{
10 file_client::{ChunkedFileReader, DEFAULT_BYTE_LEN_CHUNK_CHAIN_FILE},
11 receipt_file_client::ReceiptFileClient,
12};
13use reth_execution_types::ExecutionOutcome;
14use reth_node_builder::ReceiptTy;
15use reth_node_core::version::version_metadata;
16use reth_optimism_chainspec::OpChainSpec;
17use reth_optimism_primitives::{bedrock::is_dup_tx, OpPrimitives, OpReceipt};
18use reth_primitives_traits::NodePrimitives;
19use reth_provider::{
20 providers::ProviderNodeTypes, DBProvider, DatabaseProviderFactory, OriginalValuesKnown,
21 ProviderFactory, StageCheckpointReader, StageCheckpointWriter, StateWriter,
22 StaticFileProviderFactory, StatsReader,
23};
24use reth_stages::{StageCheckpoint, StageId};
25use reth_static_file_types::StaticFileSegment;
26use std::{
27 path::{Path, PathBuf},
28 sync::Arc,
29};
30use tracing::{debug, info, trace, warn};
31
32#[derive(Debug, Parser)]
34pub struct ImportReceiptsOpCommand<C: ChainSpecParser> {
35 #[command(flatten)]
36 env: EnvironmentArgs<C>,
37
38 #[arg(long, value_name = "CHUNK_LEN", verbatim_doc_comment)]
40 chunk_len: Option<u64>,
41
42 #[arg(value_name = "IMPORT_PATH", verbatim_doc_comment)]
47 path: PathBuf,
48}
49
50impl<C: ChainSpecParser<ChainSpec = OpChainSpec>> ImportReceiptsOpCommand<C> {
51 pub async fn execute<N: CliNodeTypes<ChainSpec = C::ChainSpec, Primitives = OpPrimitives>>(
53 self,
54 ) -> eyre::Result<()> {
55 info!(target: "reth::cli", "reth {} starting", version_metadata().short_version);
56
57 debug!(target: "reth::cli",
58 chunk_byte_len=self.chunk_len.unwrap_or(DEFAULT_BYTE_LEN_CHUNK_CHAIN_FILE),
59 "Chunking receipts import"
60 );
61
62 let Environment { provider_factory, .. } = self.env.init::<N>(AccessRights::RW)?;
63
64 import_receipts_from_file(
65 provider_factory,
66 self.path,
67 self.chunk_len,
68 |first_block, receipts| {
69 let mut total_filtered_out_dup_txns = 0;
70 for (index, receipts_for_block) in receipts.iter_mut().enumerate() {
71 if is_dup_tx(first_block + index as u64) {
72 receipts_for_block.clear();
73 total_filtered_out_dup_txns += 1;
74 }
75 }
76
77 total_filtered_out_dup_txns
78 },
79 )
80 .await
81 }
82}
83
84impl<C: ChainSpecParser> ImportReceiptsOpCommand<C> {
85 pub const fn chain_spec(&self) -> Option<&Arc<C::ChainSpec>> {
87 Some(&self.env.chain)
88 }
89}
90
91pub async fn import_receipts_from_file<N, P, F>(
93 provider_factory: ProviderFactory<N>,
94 path: P,
95 chunk_len: Option<u64>,
96 filter: F,
97) -> eyre::Result<()>
98where
99 N: ProviderNodeTypes<ChainSpec = OpChainSpec, Primitives: NodePrimitives<Receipt = OpReceipt>>,
100 P: AsRef<Path>,
101 F: FnMut(u64, &mut Vec<Vec<OpReceipt>>) -> usize,
102{
103 for stage in StageId::ALL {
104 let checkpoint = provider_factory.database_provider_ro()?.get_stage_checkpoint(stage)?;
105 trace!(target: "reth::cli",
106 ?stage,
107 ?checkpoint,
108 "Read stage checkpoints from db"
109 );
110 }
111
112 let reader = ChunkedFileReader::new(&path, chunk_len).await?;
114
115 let _ = import_receipts_from_reader(&provider_factory, reader, filter).await?;
117
118 info!(target: "reth::cli",
119 "Receipt file imported"
120 );
121
122 Ok(())
123}
124
125pub async fn import_receipts_from_reader<N, F>(
132 provider_factory: &ProviderFactory<N>,
133 mut reader: ChunkedFileReader,
134 mut filter: F,
135) -> eyre::Result<ImportReceiptsResult>
136where
137 N: ProviderNodeTypes<Primitives: NodePrimitives<Receipt = OpReceipt>>,
138 F: FnMut(u64, &mut Vec<Vec<ReceiptTy<N>>>) -> usize,
139{
140 let static_file_provider = provider_factory.static_file_provider();
141
142 if let Some(num_receipts) =
144 static_file_provider.get_highest_static_file_tx(StaticFileSegment::Receipts) &&
145 num_receipts > 0
146 {
147 eyre::bail!("Expected no receipts in storage, but found {num_receipts}.");
148 }
149 match static_file_provider.get_highest_static_file_block(StaticFileSegment::Receipts) {
150 Some(receipts_block) => {
151 if receipts_block > 0 {
152 eyre::bail!("Expected highest receipt block to be 0, but found {receipts_block}.");
153 }
154 }
155 None => {
156 eyre::bail!(
157 "Receipts was not initialized. Please import blocks and transactions before calling this command."
158 );
159 }
160 }
161
162 let provider = provider_factory.database_provider_rw()?;
163 let mut total_decoded_receipts = 0;
164 let mut total_receipts = 0;
165 let mut total_filtered_out_dup_txns = 0;
166 let mut highest_block_receipts = 0;
167
168 let highest_block_transactions = static_file_provider
169 .get_highest_static_file_block(StaticFileSegment::Transactions)
170 .expect("transaction static files must exist before importing receipts");
171
172 while let Some(file_client) =
173 reader.next_receipts_chunk::<ReceiptFileClient<OpGethReceiptFileCodec<OpReceipt>>>().await?
174 {
175 if highest_block_receipts == highest_block_transactions {
176 warn!(target: "reth::cli", highest_block_receipts, highest_block_transactions, "Ignoring all other blocks in the file since we have reached the desired height");
177 break
178 }
179
180 let ReceiptFileClient {
182 mut receipts,
183 mut first_block,
184 total_receipts: total_receipts_chunk,
185 ..
186 } = file_client;
187
188 total_decoded_receipts += total_receipts_chunk;
190
191 total_filtered_out_dup_txns += filter(first_block, &mut receipts);
192
193 info!(target: "reth::cli",
194 first_receipts_block=?first_block,
195 total_receipts_chunk,
196 "Importing receipt file chunk"
197 );
198
199 if first_block == 0 {
205 let genesis_receipts = receipts.remove(0);
207 debug_assert!(genesis_receipts.is_empty());
208 first_block = 1;
210 }
211 highest_block_receipts = first_block + receipts.len() as u64 - 1;
212
213 if highest_block_receipts > highest_block_transactions {
215 let excess = highest_block_receipts - highest_block_transactions;
216 highest_block_receipts -= excess;
217
218 receipts.truncate(receipts.len() - excess as usize);
220
221 warn!(target: "reth::cli", highest_block_receipts, "Too many decoded blocks, ignoring the last {excess}.");
222 }
223
224 total_receipts += receipts.iter().map(|v| v.len()).sum::<usize>();
226
227 let execution_outcome =
228 ExecutionOutcome::new(Default::default(), receipts, first_block, Default::default());
229
230 provider.write_state(&execution_outcome, OriginalValuesKnown::Yes)?;
232 }
233
234 let total_imported_txns = static_file_provider
236 .count_entries::<tables::Transactions>()
237 .expect("transaction static files must exist before importing receipts");
238
239 if total_receipts != total_imported_txns {
240 eyre::bail!(
241 "Number of receipts ({total_receipts}) inconsistent with transactions {total_imported_txns}"
242 )
243 }
244
245 if highest_block_receipts != highest_block_transactions {
247 eyre::bail!(
248 "Receipt block height ({highest_block_receipts}) inconsistent with transactions' {highest_block_transactions}"
249 )
250 }
251
252 provider
254 .save_stage_checkpoint(StageId::Execution, StageCheckpoint::new(highest_block_receipts))?;
255
256 provider.commit()?;
257
258 Ok(ImportReceiptsResult { total_decoded_receipts, total_filtered_out_dup_txns })
259}
260
261#[derive(Debug)]
263pub struct ImportReceiptsResult {
264 pub total_decoded_receipts: usize,
266 pub total_filtered_out_dup_txns: usize,
268}
269
270#[cfg(test)]
271mod test {
272 use alloy_primitives::hex;
273 use reth_db_common::init::init_genesis;
274 use reth_optimism_chainspec::OP_MAINNET;
275 use reth_optimism_node::OpNode;
276 use reth_provider::test_utils::create_test_provider_factory_with_node_types;
277 use reth_stages::test_utils::TestStageDB;
278 use tempfile::tempfile;
279 use tokio::{
280 fs::File,
281 io::{AsyncSeekExt, AsyncWriteExt, SeekFrom},
282 };
283
284 use crate::receipt_file_codec::test::{
285 HACK_RECEIPT_ENCODED_BLOCK_1, HACK_RECEIPT_ENCODED_BLOCK_2, HACK_RECEIPT_ENCODED_BLOCK_3,
286 };
287
288 use super::*;
289
290 const EMPTY_RECEIPTS_GENESIS_BLOCK: &[u8] = &hex!("c0");
292
293 #[ignore]
294 #[tokio::test]
295 async fn filter_out_genesis_block_receipts() {
296 let mut f: File = tempfile().unwrap().into();
297 f.write_all(EMPTY_RECEIPTS_GENESIS_BLOCK).await.unwrap();
298 f.write_all(HACK_RECEIPT_ENCODED_BLOCK_1).await.unwrap();
299 f.write_all(HACK_RECEIPT_ENCODED_BLOCK_2).await.unwrap();
300 f.write_all(HACK_RECEIPT_ENCODED_BLOCK_3).await.unwrap();
301 f.flush().await.unwrap();
302 f.seek(SeekFrom::Start(0)).await.unwrap();
303
304 let reader = ChunkedFileReader::from_file(f, DEFAULT_BYTE_LEN_CHUNK_CHAIN_FILE, false)
305 .await
306 .unwrap();
307
308 let db = TestStageDB::default();
309 init_genesis(&db.factory).unwrap();
310
311 let provider_factory =
312 create_test_provider_factory_with_node_types::<OpNode>(OP_MAINNET.clone());
313 let ImportReceiptsResult { total_decoded_receipts, total_filtered_out_dup_txns } =
314 import_receipts_from_reader(&provider_factory, reader, |_, _| 0).await.unwrap();
315
316 assert_eq!(total_decoded_receipts, 3);
317 assert_eq!(total_filtered_out_dup_txns, 0);
318 }
319}